Files
aevolution/tests/network_control.cpp
T
dingoandClaude Opus 5.5 b73ccbae9a
Foundation / checks (ecs) (push) Successful in 2m19s
Foundation / checks (deploy) (push) Successful in 4m47s
Foundation / postgres-tools (push) Canceled after 0s
Foundation / server-image (push) Canceled after 0s
Foundation / image (push) Canceled after 0s
Foundation / checks (checks) (push) Canceled after 16m48s
Foundation / checks (network) (push) Canceled after 16m46s
Foundation / checks (postgres) (push) Canceled after 16m47s
Foundation / checks (client) (push) Canceled after 16m53s
Foundation / checks (tsan) (push) Canceled after 14m33s
feat(ecology): make photosynthesis regions playable on DEV
ADR-0176 and schema 57 admit raw cellular bundle 13 (rules 11 on owner
format 9) through parser-local normalization to bundle 12, and a fenced
no-tick 12 -> 13 upgrade that declares the region's light; recovery reads
the light from the target and re-derives the whole target from the source.
The resumable cellular-v8 opening provisions a cellular-v7 genesis, one
empty tick and the durable upgrades to bundle 13.

Session v12 adds the owner's captured light and the producers it can see
to its perception, and lets offers name photosynthesis; older sessions keep
their layouts and never receive photosynthesis candidates. The client
draws chloroplasts by efficiency, shows sunlight in the HUD and offers
photosynthesis cards. DEV now provisions and serves region 9 with the
trial light; region 8 stays stored but unserved.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 23:04:34 -04:00

895 lines
45 KiB
C++

#include "evo/identity/identity.hpp"
#include "evo/network/dev_grant.hpp"
#include "evo/network/handoff_ticket.hpp"
#include "evo/network/intent_admission.hpp"
#include "evo/network/session_control.hpp"
#include "evo/network/session_grant.hpp"
#include "evo/network/session_protocol.hpp"
#include "network_test.hpp"
#include <algorithm>
#include <array>
#include <cstdint>
#include <string_view>
#include <vector>
namespace evo::network_test {
namespace {
using namespace evo::network;
using evo::identity::IdentityError;
constexpr world::WorldIdentity world_id{7, 3};
constexpr std::uint64_t region = 11;
constexpr std::uint64_t now = 1'800'000'000;
AccountId account(std::uint8_t tag) {
AccountId a;
a.bytes.fill(tag);
return a;
}
GrantClaims claims(const AccountId& who, std::uint64_t serial, std::uint64_t issued = now,
std::uint64_t lifetime = 60) {
GrantClaims c;
c.grant_id = 1000 + serial;
c.account = who;
c.serial = serial;
c.world = world_id;
c.region = region;
c.issued_at = issued;
c.expires_at = issued + lifetime;
return c;
}
std::span<const std::uint8_t> bytes(std::string_view text) {
return {reinterpret_cast<const std::uint8_t*>(text.data()), text.size()};
}
// One environment's issuer key and region verifier.
struct Keys {
explicit Keys(DeploymentEnvironment e, std::uint32_t key_id = 1)
: signer{*GrantSigningKey::generate(e, key_id)}, verifier{*GrantVerifier::create(e)} {
CHECK(verifier.add_key(key_id, *signer.public_key()));
}
VerifiedSessionGrant verified(const GrantClaims& c) const {
auto grant = signer.sign(c);
CHECK(grant);
auto v = verifier.verify(*grant);
CHECK(v);
return *v;
}
GrantSigningKey signer;
GrantVerifier verifier;
};
ControlConfig config() {
ControlConfig c;
c.environment = DeploymentEnvironment::dev;
c.world = world_id;
c.region = region;
c.epoch = 5;
c.max_sessions = 4;
c.max_accounts = 8;
return c;
}
void grants() {
Keys dev{DeploymentEnvironment::dev};
const auto who = account(0x42);
const auto grant = *dev.signer.sign(claims(who, 1));
const auto v = dev.verifier.verify(grant);
CHECK(v && v->claims().account == who && v->claims().serial == 1 &&
v->claims().world == world_id && v->claims().region == region &&
v->environment() == DeploymentEnvironment::dev);
// Every signed byte matters, including the key id and environment.
for (std::size_t i = 0; i < session_grant_bytes; ++i) {
auto tampered = grant;
tampered.at(i) ^= 0x01;
const auto r = dev.verifier.verify(tampered);
CHECK(!r);
CHECK(r.error() == (i >= 20 && i < 24 ? SessionGrantError::unknown_key
: SessionGrantError::bad_signature));
}
CHECK(refused(dev.verifier.verify(std::span{grant}.first(159)), SessionGrantError::malformed));
// A dev-signed grant never verifies in stage or World0, even if a dev public key were
// misconfigured there: the environment byte is signed.
for (const auto e : {DeploymentEnvironment::stage, DeploymentEnvironment::world0}) {
auto other = *GrantVerifier::create(e);
CHECK(refused(other.verify(grant), SessionGrantError::unknown_key));
CHECK(other.add_key(1, *dev.signer.public_key()));
CHECK(refused(other.verify(grant), SessionGrantError::wrong_environment));
}
// M9 dev grants are not session grants.
std::array<std::uint8_t, dev_key_bytes> secret{};
secret.fill(9);
const auto dev_key = *DevGrantKey::import(DeploymentEnvironment::dev, secret);
DevGrantClaims dc;
dc.grant_id = 1;
dc.subject = 2;
dc.world = world_id;
dc.region = region;
dc.issued_at = now;
dc.expires_at = now + 60;
CHECK(refused(dev.verifier.verify(*dev_key.issue(dc)), SessionGrantError::malformed));
// Rotation: a second key verifies alongside; ids are unique; at most 8 keys.
Keys rotated{DeploymentEnvironment::dev, 2};
CHECK(dev.verifier.add_key(2, *rotated.signer.public_key()));
CHECK(dev.verifier.verify(*rotated.signer.sign(claims(who, 2))));
CHECK(refused(dev.verifier.add_key(2, *rotated.signer.public_key()),
SessionGrantError::duplicate_key));
for (std::uint32_t id = 3; id <= GrantVerifier::max_keys; ++id)
CHECK(dev.verifier.add_key(id, *rotated.signer.public_key()));
CHECK(refused(dev.verifier.add_key(99, *rotated.signer.public_key()),
SessionGrantError::too_many_keys));
// A grant signed by key 2 but labelled key 1 fails (the label is signed too).
auto relabelled = *rotated.signer.sign(claims(who, 3));
relabelled.at(20) = 1;
CHECK(refused(dev.verifier.verify(relabelled), SessionGrantError::bad_signature));
GrantPublicKey not_a_point{};
not_a_point.fill(0x04);
auto fresh = *GrantVerifier::create(DeploymentEnvironment::dev);
CHECK(refused(fresh.add_key(1, not_a_point), SessionGrantError::invalid_key));
CHECK(refused(fresh.add_key(0, *dev.signer.public_key()), SessionGrantError::invalid_key));
// Structural claims and key import.
auto bad = claims(who, 1);
bad.serial = 0;
CHECK(refused(dev.signer.sign(bad), SessionGrantError::invalid_claims));
bad = claims(who, 1);
bad.account = {};
CHECK(refused(dev.signer.sign(bad), SessionGrantError::invalid_claims));
std::array<std::uint8_t, grant_private_key_bytes> scalar{};
scalar.back() = 7;
auto imported = GrantSigningKey::import(DeploymentEnvironment::stage, 4, scalar);
CHECK(imported);
auto stage = *GrantVerifier::create(DeploymentEnvironment::stage);
CHECK(stage.add_key(4, *imported->public_key()));
CHECK(stage.verify(*imported->sign(claims(who, 1))));
CHECK(refused(
GrantSigningKey::import(DeploymentEnvironment::stage, 4, std::span{scalar}.first(31)),
SessionGrantError::invalid_key));
scalar.fill(0);
CHECK(refused(GrantSigningKey::import(DeploymentEnvironment::stage, 4, scalar),
SessionGrantError::invalid_key));
// Moved-from keys are inert.
auto moved = std::move(imported).value();
CHECK(refused(imported->sign(claims(who, 1)), // NOLINT(bugprone-use-after-move)
SessionGrantError::invalid_key));
CHECK(moved.sign(claims(who, 1)));
}
void identity_adapter() {
using namespace evo::identity;
for (const auto e : {DeploymentEnvironment::stage, DeploymentEnvironment::world0})
CHECK(refused(DevTestProvider::create(e), IdentityError::not_dev_environment));
auto provider = *DevTestProvider::create(DeploymentEnvironment::dev);
CHECK(provider.authenticate(bytes("dev-test:alice"))->subject == "alice");
for (const auto bad : {"alice", "dev-test:", "dev-test:Alice", "dev-test:a b",
"dev-test:0123456789abcdef0123456789abcdefX", "steam:alice"})
CHECK(refused(provider.authenticate(bytes(bad)), IdentityError::unauthenticated));
MemoryAccountDirectory directory{2};
const ProviderSubject alice{ProviderKind::dev_test, "alice"};
const auto a1 = *directory.resolve(alice);
CHECK(a1.valid() && *directory.resolve(alice) == a1);
const auto b = *directory.resolve({ProviderKind::dev_test, "bob"});
CHECK(b != a1);
CHECK(refused(directory.resolve({ProviderKind::dev_test, "carol"}),
IdentityError::directory_full));
const auto s1 = *directory.next_grant(a1, now);
const auto s2 = *directory.next_grant(a1, now - 100); // Clock went back.
CHECK(s1.serial == 1 && s2.serial == 2 && s2.issued_at == now);
// End to end: credential -> account -> signed grant -> region control.
Keys dev{DeploymentEnvironment::dev};
MemoryAccountDirectory accounts{16};
auto issuer = GrantIssuer::create(std::move(dev.signer), provider, accounts, 60);
CHECK(issuer);
auto control = *SessionControl::create(config());
const auto g1 = issuer->issue(bytes("dev-test:alice"), world_id, region, now);
const auto opened = control.open(*dev.verifier.verify(*g1), now);
CHECK(opened && opened->superseded == 0);
const auto g2 = issuer->issue(bytes("dev-test:alice"), world_id, region, now + 1);
const auto again = control.open(*dev.verifier.verify(*g2), now + 1);
CHECK(again && again->superseded == opened->session);
CHECK(refused(issuer->issue(bytes("nobody"), world_id, region, now),
IdentityError::unauthenticated));
CHECK(refused(issuer->issue(bytes("dev-test:alice"), {0, 0}, region, now),
IdentityError::invalid_request));
// A dev provider cannot drive a stage or World0 key.
for (const auto e : {DeploymentEnvironment::stage, DeploymentEnvironment::world0})
CHECK(refused(GrantIssuer::create(*GrantSigningKey::generate(e, 1), provider, accounts, 60),
IdentityError::wrong_environment));
CHECK(refused(GrantIssuer::create(*GrantSigningKey::generate(DeploymentEnvironment::dev, 1),
provider, accounts, 0),
IdentityError::invalid_request));
}
void control_rules() {
Keys dev{DeploymentEnvironment::dev};
const auto alice = account(1), bob = account(2);
{
auto bad = config();
bad.max_accounts = 2; // Fewer than sessions.
CHECK(refused(SessionControl::create(bad), ControlError::invalid_config));
bad = config();
bad.max_grant_lifetime = 14400;
CHECK(SessionControl::create(bad));
bad.max_grant_lifetime = 14401;
CHECK(refused(SessionControl::create(bad), ControlError::invalid_config));
bad = config(); // ADR-0097: evo-server's 2000-session cap fits; the bound is 4096.
bad.max_sessions = 2000;
bad.max_accounts = 8192;
CHECK(SessionControl::create(bad));
bad.max_sessions = 4097; // Refused by the session bound alone.
CHECK(refused(SessionControl::create(bad), ControlError::invalid_config));
}
// Scope and time.
{
auto control = *SessionControl::create(config());
auto c = claims(alice, 1);
c.world = {7, 4};
CHECK(refused(control.open(dev.verified(c), now), ControlError::wrong_world));
c = claims(alice, 1);
c.region = 12;
CHECK(refused(control.open(dev.verified(c), now), ControlError::wrong_region));
CHECK(refused(control.open(dev.verified(claims(alice, 1, now, 301)), now),
ControlError::invalid_lifetime));
CHECK(refused(control.open(dev.verified(claims(alice, 1, now + 31)), now),
ControlError::not_yet_valid));
CHECK(control.open(dev.verified(claims(alice, 1, now + 30)), now));
CHECK(refused(control.open(dev.verified(claims(bob, 1)), now + 60), ControlError::expired));
// Grants verified for another environment are refused by this region.
Keys stage{DeploymentEnvironment::stage};
CHECK(refused(control.open(stage.verified(claims(bob, 1)), now),
ControlError::wrong_environment));
}
// Replay, duplicate login (newest wins) and stolen stale grants.
{
auto c = config();
c.max_account_attempts = 16; // Rate limits are tested separately.
auto control = *SessionControl::create(c);
const auto first = dev.verified(claims(alice, 5));
const auto s1 = control.open(first, now);
CHECK(s1 && s1->superseded == 0 && s1->epoch == 5 && s1->expires_at == now + 60);
CHECK(refused(control.open(first, now + 1), ControlError::stale_grant)); // Replay.
// An older, unexpired grant (e.g. stolen earlier) cannot take control.
CHECK(refused(control.open(dev.verified(claims(alice, 4)), now + 1),
ControlError::stale_grant));
CHECK(control.holder(alice) == s1->session);
const auto s2 = control.open(dev.verified(claims(alice, 6)), now + 2);
CHECK(s2 && s2->superseded == s1->session && s2->session != s1->session);
CHECK(control.holder(alice) == s2->session && control.sessions() == 1);
CHECK(!control.account_of(s1->session));
CHECK(refused(control.close(s1->session), ControlError::unknown_session));
// After close, the stale serial stays refused until every older grant expired.
CHECK(control.close(s2->session));
CHECK(refused(control.open(dev.verified(claims(alice, 6)), now + 3),
ControlError::stale_grant));
}
// Rate limits: account attempts (every verified attempt counts) and region attempts.
{
auto c = config();
c.max_account_attempts = 3;
c.max_region_attempts = 5;
c.attempt_window = 10;
auto control = *SessionControl::create(c);
const auto replayed = dev.verified(claims(alice, 1));
CHECK(control.open(replayed, now));
CHECK(refused(control.open(replayed, now), ControlError::stale_grant));
CHECK(refused(control.open(replayed, now), ControlError::stale_grant));
CHECK(
refused(control.open(dev.verified(claims(alice, 2)), now), ControlError::rate_limited));
CHECK(control.open(dev.verified(claims(alice, 2)), now + 10)); // New window.
for (int i = 0; i < 5; ++i)
CHECK(control.attempt(now));
CHECK(refused(control.attempt(now), ControlError::rate_limited));
CHECK(refused(control.attempt(now + 9), ControlError::rate_limited));
CHECK(control.attempt(now + 10));
}
// Capacity: a refused open does not consume the grant; accounts fail closed.
{
auto c = config();
c.max_sessions = 1;
c.max_accounts = 2;
auto control = *SessionControl::create(c);
const auto a = control.open(dev.verified(claims(alice, 1)), now);
const auto bob_grant = dev.verified(claims(bob, 1));
CHECK(refused(control.open(bob_grant, now), ControlError::sessions_full));
CHECK(control.close(a->session));
CHECK(control.open(bob_grant, now)); // Same grant, now admitted.
CHECK(refused(control.open(dev.verified(claims(account(3), 1)), now),
ControlError::accounts_full));
// Idle accounts are forgotten only after their grants and windows end.
CHECK(refused(control.open(dev.verified(claims(account(3), 1, now + 299)), now + 299),
ControlError::accounts_full));
const auto later = dev.verified(claims(account(3), 1, now + 300));
CHECK(refused(control.open(later, now + 300), ControlError::sessions_full)); // Bob holds.
}
// Refresh, expiry and epochs.
{
auto control = *SessionControl::create(config());
const auto a = control.open(dev.verified(claims(alice, 1)), now);
const auto b = control.open(dev.verified(claims(bob, 1)), now);
CHECK(control.refresh(a->session, dev.verified(claims(alice, 2, now + 50)), now + 50) ==
now + 110);
CHECK(refused(control.refresh(a->session, dev.verified(claims(alice, 2)), now + 51),
ControlError::stale_grant));
CHECK(refused(control.refresh(a->session, dev.verified(claims(bob, 2)), now + 51),
ControlError::wrong_account));
CHECK(refused(control.refresh(999, dev.verified(claims(alice, 3)), now + 51),
ControlError::unknown_session));
const auto expired = control.expire(now + 60);
CHECK(expired == std::vector<std::uint64_t>{b->session});
CHECK(control.holder(alice) == a->session && !control.holder(bob));
const auto c2 = control.open(dev.verified(claims(bob, 2, now + 60)), now + 60);
auto closed = control.advance_epoch(6);
CHECK(closed && closed->size() == 2 && control.sessions() == 0 && control.epoch() == 6);
CHECK(std::ranges::find(*closed, c2->session) != closed->end());
CHECK(refused(control.advance_epoch(6), ControlError::invalid_config));
const auto reopened = control.open(dev.verified(claims(alice, 3, now + 61)), now + 61);
CHECK(reopened && reopened->epoch == 6 && reopened->superseded == 0);
}
// Redaction: the log label carries only the first four id bytes.
AccountId labelled;
for (std::size_t i = 0; i < labelled.bytes.size(); ++i)
labelled.bytes.at(i) = static_cast<std::uint8_t>(0xA0 + i);
CHECK(log_label(labelled) == "acct-a0a1a2a3");
}
void session_codec() {
WireGrant grant{};
for (std::size_t i = 0; i < grant.size(); ++i)
grant.at(i) = static_cast<std::uint8_t>(i * 7);
SessionWelcome welcome{1, 2, 3, 4, 5, 6, 7, 8};
const std::vector<SessionMessage> messages{
SessionHello{0, grant},
welcome,
SessionRefresh{grant},
SessionRefreshResult{0, 99},
SessionRefreshResult{static_cast<std::uint8_t>(SessionCloseReason::stale_grant), 0},
SessionClose{SessionCloseReason::superseded},
SessionClose{SessionCloseReason::shutdown},
SessionIntention{1, 2, 3, 4, -1000, 7},
IntentionReceipt{3, AdmitStatus::not_ready, 9},
SimulatedThrough{2, 3, 4},
SessionAction{1, 2, 77, 1, 5},
ActionReceipt{77, AdmitStatus::duplicate, 4, 5},
ActionOutcome{77, ActionResult::committed_no_effect, 5, 12},
ActionQuery{77}};
for (const auto& m : messages) {
const auto bytes = encode_session(m);
CHECK(bytes.at(0) == 'E' && bytes.at(1) == 'V' && bytes.at(2) == 'S' && bytes.at(3) == 'N');
const auto back = decode_session(bytes);
CHECK(back && back->index() == m.index());
CHECK(encode_session(*back) == bytes);
// Every truncation and any extension is refused.
for (std::size_t n = 0; n < bytes.size(); ++n) {
const auto r = decode_session(std::span{bytes}.first(n));
CHECK(!r && r.error() == (n < session_header_bytes ? SessionCodecError::truncated
: SessionCodecError::wrong_length));
}
auto longer = bytes;
longer.push_back(0);
CHECK(refused(decode_session(longer), SessionCodecError::wrong_length));
auto mutated = bytes;
mutated.at(0) ^= 1;
CHECK(refused(decode_session(mutated), SessionCodecError::bad_magic));
mutated = bytes;
mutated.at(4) = 13; // A future version; protocol versions through 12 are supported.
CHECK(refused(decode_session(mutated), SessionCodecError::unsupported_version));
mutated = bytes;
mutated.at(7) = 1;
CHECK(refused(decode_session(mutated), SessionCodecError::reserved_flags));
for (const auto type : std::array<std::uint8_t, 3>{0, 18, 255}) {
mutated = bytes;
mutated.at(6) = type;
CHECK(refused(decode_session(mutated), SessionCodecError::unknown_type));
}
}
CHECK(std::get<SessionWelcome>(*decode_session(encode_session(welcome))) == welcome);
CHECK(std::get<SessionHello>(*decode_session(encode_session(SessionHello{0, grant}))).grant ==
grant);
for (const auto reason : std::array<std::uint8_t, 4>{0, 16, 200, 255}) {
auto close = encode_session(SessionClose{SessionCloseReason::protocol});
close.back() = reason;
CHECK(refused(decode_session(close), SessionCodecError::invalid_value));
if (reason != 0) {
auto result = encode_session(SessionRefreshResult{0, 0});
result.at(session_header_bytes) = reason;
CHECK(refused(decode_session(result), SessionCodecError::invalid_value));
}
}
// Decoded values survive exactly (signed vectors, every field).
const SessionIntention intent{9, 8, 7, 6, -1000, 999};
CHECK(std::get<SessionIntention>(*decode_session(encode_session(intent))) == intent);
const ActionOutcome outcome{5, ActionResult::not_committed, 0, 0};
CHECK(std::get<ActionOutcome>(*decode_session(encode_session(outcome))) == outcome);
const std::array<SessionMessage, 8> life_messages{
PrimitiveLifeRequest{7, 8, 9},
PrimitiveLifeReceipt{9, AdmitStatus::admitted, 10},
PrimitiveLifeOutcome{9, PrimitiveLifeResult::born, 11, 12},
PrimitiveLifeOutcome{9, PrimitiveLifeResult::existing_life, 0, 0},
PrimitiveLifeOutcome{9, PrimitiveLifeResult::cancelled, 0, 0},
PrimitiveLifeOutcome{9, PrimitiveLifeResult::pending, 0, 0},
PrimitiveLifeOutcome{9, PrimitiveLifeResult::unknown, 0, 0},
PrimitiveLifeQuery{9}};
for (const auto& message : life_messages) {
const auto bytes = encode_session(message);
std::uint16_t version{};
const auto decoded = decode_session(bytes, &version);
CHECK(bytes.at(4) == 5 && version == session_protocol_v5);
CHECK(decoded && decoded->index() == message.index());
CHECK(decoded && encode_session(*decoded) == bytes);
auto v4 = bytes;
v4.at(4) = 4;
CHECK(refused(decode_session(v4), SessionCodecError::unknown_type));
}
CHECK(encode_session(life_messages[0], session_protocol_version).empty());
// A state claim appended to an intention (position, energy) is not a valid message.
auto claimed = encode_session(intent);
for (int i = 0; i < 16; ++i)
claimed.push_back(0x7F);
CHECK(refused(decode_session(claimed), SessionCodecError::wrong_length));
for (const auto bad : std::array<std::uint8_t, 3>{11, 200, 255}) {
auto receipt = encode_session(IntentionReceipt{1, AdmitStatus::admitted, 1});
receipt.at(session_header_bytes + 8) = bad;
CHECK(refused(decode_session(receipt), SessionCodecError::invalid_value));
}
for (const auto bad : std::array<std::uint8_t, 3>{0, 5, 255}) {
auto o = encode_session(outcome);
o.at(session_header_bytes + 8) = bad;
CHECK(refused(decode_session(o), SessionCodecError::invalid_value));
}
for (const auto zero : {0, 1}) {
auto w = welcome;
(zero == 0 ? w.session : w.epoch) = 0;
CHECK(refused(decode_session(encode_session(w)), SessionCodecError::invalid_value));
}
}
// Scripted durable action records (10.4b).
struct FakeActions final : ActionLedger {
std::expected<std::optional<ActionOutcome>, ActionLedgerError>
find(const AccountId& who, std::uint64_t action_id) override {
++lookups;
if (unavailable)
return std::unexpected(ActionLedgerError::unavailable);
for (const auto& [account, outcome] : records)
if (account == who && outcome.action_id == action_id)
return std::optional{outcome};
return std::optional<ActionOutcome>{};
}
std::expected<std::vector<std::optional<ActionOutcome>>, ActionLedgerError>
find_all(std::span<const ActionKey> keys) override {
++batches;
return ActionLedger::find_all(keys); // Counts each pair as a lookup too.
}
std::vector<std::pair<AccountId, ActionOutcome>> records;
bool unavailable{};
int lookups{}, batches{};
};
// M10.9d: admission whose durable uniqueness check waits for one `verify` per poll, and a
// commit decided with one ledger request.
void deferred_actions() {
auto a = *IntentAdmission::create(IntentLimits{});
FakeActions ledger;
a.attach(&ledger);
const auto alice = account(1), bob = account(2);
CHECK(a.open(1, alice) && a.open(2, bob));
AdmissionFacts f{true, 5, 100};
const auto admit = [&](std::uint64_t session, std::uint64_t id, std::uint64_t tick) {
return a.admit(session, SessionAction{session, 5, id, 1, tick}, f);
};
ledger.records.emplace_back(alice, ActionOutcome{9, ActionResult::committed_no_effect, 40, 3});
const auto legacy_record = ledger.find_record(alice, 9);
if (!legacy_record.has_value())
throw std::runtime_error{"legacy action lookup failed"};
const auto& maybe_legacy = legacy_record.value();
if (!maybe_legacy.has_value())
throw std::runtime_error{"legacy action record missing"};
const auto& saved_legacy = maybe_legacy.value();
CHECK(saved_legacy.outcome == ActionOutcome{9, ActionResult::committed_no_effect, 40, 3} &&
!saved_legacy.cellular_input);
CHECK(!admit(1, 9, 101) && !admit(1, 20, 101) && !admit(2, 30, 102));
// In-memory refusals answer at once; a repeat of a waiting action is a duplicate.
CHECK(admit(1, 20, 101) == ActionReceipt{20, AdmitStatus::duplicate, 100, 101});
CHECK(admit(1, 21, 150) == ActionReceipt{21, AdmitStatus::outside_window, 100, 150});
const int lookups_before_verify = ledger.lookups;
CHECK(a.carry(110).empty() && ledger.lookups == lookups_before_verify);
// Nothing rides or queries durable records before `verify`.
f.server_tick = 101;
auto receipts = a.verify(f);
CHECK(ledger.batches == 1 && ledger.lookups == lookups_before_verify + 3 &&
receipts.size() == 3);
CHECK(receipts[0] ==
std::pair{std::uint64_t{1}, ActionReceipt{9, AdmitStatus::duplicate, 100, 40}});
CHECK(receipts[1] ==
std::pair{std::uint64_t{1}, ActionReceipt{20, AdmitStatus::admitted, 100, 101}});
CHECK(receipts[2] ==
std::pair{std::uint64_t{2}, ActionReceipt{30, AdmitStatus::admitted, 100, 102}});
CHECK(a.query(1, {9}, f).result == ActionResult::committed_no_effect);
CHECK(a.verify(f).empty() && ledger.batches == 1); // Nothing waiting: nothing asked.
// One request for a whole commit.
const auto riding = a.carry(102);
CHECK(riding.size() == 2);
const auto outcomes = a.committed(riding, 6);
CHECK(ledger.batches == 2 && outcomes.size() == 2 &&
outcomes[0].outcome == ActionOutcome{20, ActionResult::committed_no_effect, 101, 6});
// Unconfirmed uniqueness, lost readiness and a new epoch refuse what was waiting.
f.server_tick = 110; // A new rate window.
ledger.unavailable = true;
CHECK(!admit(1, 22, 111));
receipts = a.verify(f);
CHECK(receipts.size() == 1 && receipts[0].second.status == AdmitStatus::not_ready);
ledger.unavailable = false;
CHECK(a.unresolved(1) == 0);
CHECK(!admit(1, 23, 111));
f.ready = false;
receipts = a.verify(f);
CHECK(receipts.size() == 1 && receipts[0].second.status == AdmitStatus::not_ready);
f.ready = true;
CHECK(!admit(1, 24, 111));
f.epoch = 6;
receipts = a.verify(f);
CHECK(receipts.size() == 1 && receipts[0].second.status == AdmitStatus::stale_epoch);
// Without a ledger nothing waits.
auto plain = *IntentAdmission::create(IntentLimits{});
CHECK(plain.open(1, alice));
CHECK(plain.admit(1, SessionAction{1, 5, 7, 1, 101}, AdmissionFacts{true, 5, 100}) ==
ActionReceipt{7, AdmitStatus::admitted, 100, 101});
CHECK(plain.verify(AdmissionFacts{true, 5, 100}).empty());
}
void durable_actions() {
auto a = *IntentAdmission::create(IntentLimits{});
FakeActions ledger;
a.attach(&ledger);
const auto alice = account(1);
CHECK(a.open(1, alice));
AdmissionFacts f{true, 5, 100};
const auto action = [&](std::uint64_t id, std::uint64_t tick) {
return a.action(1, SessionAction{1, 5, id, 1, tick}, f);
};
// Committed by an earlier epoch, process or region: a duplicate with its outcome.
const ActionOutcome old{9, ActionResult::committed_no_effect, 40, 3};
ledger.records.emplace_back(alice, old);
auto r = action(9, 101);
CHECK(r.status == AdmitStatus::duplicate && r.tick == 40);
CHECK(a.query(1, {9}, f) == old);
// Uniqueness that cannot be confirmed is not admitted.
ledger.unavailable = true;
CHECK(action(10, 101).status == AdmitStatus::not_ready);
ledger.unavailable = false;
const int before = ledger.lookups;
CHECK(action(10, 101).status == AdmitStatus::admitted && ledger.lookups == before + 1);
// A refused attempt never costs a lookup.
CHECK(action(11, 150).status == AdmitStatus::outside_window && ledger.lookups == before + 1);
// Exact commit: the tick reported is the tick the action rode.
auto riding = a.carry(101);
CHECK(riding.size() == 1);
riding[0].tick = 102;
auto outcomes = a.committed(riding, 6);
CHECK(outcomes.size() == 1 &&
outcomes[0].outcome == ActionOutcome{10, ActionResult::committed_no_effect, 102, 6});
// A final drop is not_committed; an unknown one stays pending until its record decides.
f.server_tick = 108;
CHECK(action(12, 109).status == AdmitStatus::admitted);
CHECK(action(13, 109).status == AdmitStatus::admitted);
riding = a.carry(109);
CHECK(riding.size() == 2);
outcomes = a.dropped(std::span{riding}.first(1), true);
CHECK(outcomes.size() == 1 && outcomes[0].outcome.result == ActionResult::not_committed);
CHECK(a.dropped(std::span{riding}.subspan(1), false).empty());
f.ready = false; // Recovering: nothing is decided yet.
CHECK(a.query(1, {13}, f).result == ActionResult::pending);
f.ready = true;
ledger.records.emplace_back(alice,
ActionOutcome{13, ActionResult::committed_no_effect, 109, 7});
CHECK(a.query(1, {13}, f) == ActionOutcome{13, ActionResult::committed_no_effect, 109, 7});
// The same for an action whose record is absent once the new authority is ready.
f.server_tick = 116;
CHECK(action(14, 117).status == AdmitStatus::admitted);
riding = a.carry(117);
CHECK(a.dropped(riding, false).empty());
CHECK(a.query(1, {14}, f) == ActionOutcome{14, ActionResult::not_committed, 0, 0});
// Outcomes evicted from memory are found again on record.
auto small = IntentLimits{};
small.max_finals = 1;
auto b = *IntentAdmission::create(small);
b.attach(&ledger);
CHECK(b.open(1, alice));
CHECK(b.query(1, {13}, f).result == ActionResult::committed_no_effect);
CHECK(b.query(1, {99}, f).result == ActionResult::unknown);
}
// The watermark sent to one session, if any.
std::optional<SimulatedThrough>
mark_of(const std::vector<std::pair<std::uint64_t, SimulatedThrough>>& marks,
std::uint64_t session) {
for (const auto& [s, m] : marks)
if (s == session)
return m;
return std::nullopt;
}
void intent_admission() {
IntentLimits limits;
limits.watermark_every = 20; // Exercise the repeat interval.
limits.max_unresolved = 6;
limits.max_finals = 4;
CHECK(refused(IntentAdmission::create(IntentLimits{0}), IntentConfigError::invalid));
{
IntentLimits wide;
wide.max_sessions = 2000;
CHECK(IntentAdmission::create(wide));
wide.max_sessions = 4097;
CHECK(refused(IntentAdmission::create(wide), IntentConfigError::invalid));
}
auto a = *IntentAdmission::create(limits);
const auto alice = account(1), bob = account(2);
CHECK(a.open(1, alice) && a.open(2, bob) && !a.open(1, alice) && !a.open(0, alice));
AdmissionFacts f{true, 5, 100};
const auto intention = [&](std::uint64_t session, std::uint64_t seq, std::uint64_t tick,
std::int16_t x = 0, std::uint64_t epoch = 5) {
return a.intention(session, SessionIntention{session, epoch, seq, tick, x, 0}, f).status;
};
// Every refusal, in the order admission applies them.
CHECK(intention(1, 1, 101) == AdmitStatus::admitted);
CHECK(a.intention(1, SessionIntention{2, 5, 2, 102, 0, 0}, f).status ==
AdmitStatus::unknown_session); // Names another session.
CHECK(a.intention(9, SessionIntention{9, 5, 2, 102, 0, 0}, f).status ==
AdmitStatus::unknown_session); // No such session.
CHECK(intention(1, 2, 102, 0, 4) == AdmitStatus::stale_epoch);
CHECK(intention(1, 2, 102, 1001) == AdmitStatus::invalid_vector);
CHECK(intention(1, 1, 102) == AdmitStatus::replayed);
CHECK(intention(1, 2, 100) == AdmitStatus::outside_window); // Not in the future.
CHECK(intention(1, 2, 109) == AdmitStatus::outside_window); // Beyond 8 ticks.
CHECK(intention(1, 2, 101) == AdmitStatus::outside_window); // Same tick as before.
CHECK(intention(1, 2, 102) == AdmitStatus::rate_limited); // 8 attempts this window.
f.server_tick = 108; // New window.
f.ready = false;
CHECK(intention(1, 2, 109) == AdmitStatus::not_ready);
f.ready = true;
CHECK(intention(1, 2, 109) == AdmitStatus::admitted);
CHECK(intention(1, 3, 110) == AdmitStatus::admitted);
// Simulated watermark: only intentions whose tick ran, cumulatively.
f.server_tick = 109;
auto marks = a.simulated(f);
CHECK(mark_of(marks, 1) == SimulatedThrough{5, 2, 109});
CHECK(mark_of(marks, 2) == SimulatedThrough{5, 0, 109}); // Bob: the tick, no intention.
CHECK(a.simulated(f).empty()); // Unchanged: not repeated yet.
f.server_tick = 110;
marks = a.simulated(f);
CHECK(marks.size() == 1 && mark_of(marks, 1) == SimulatedThrough{5, 3, 110}); // Bob: not
// repeated.
f.server_tick = 130;
marks = a.simulated(f); // Repeated after 20 ticks so a lost datagram is covered.
CHECK(mark_of(marks, 1) == SimulatedThrough{5, 3, 130} &&
mark_of(marks, 2) == SimulatedThrough{5, 0, 130});
// M10.9d: coalesced, an advancing watermark goes out at most every 4 ticks, still
// cumulative (the latest sequence), and idle repeats keep their interval.
{
IntentLimits l;
l.watermark_every = 20;
l.watermark_coalesce = 4;
IntentLimits zero;
zero.watermark_coalesce = 0;
CHECK(!IntentAdmission::create(zero));
auto c = *IntentAdmission::create(l);
CHECK(c.open(3, alice));
AdmissionFacts g{true, 5, 200};
std::uint64_t sent = 0;
for (std::uint64_t tick = 201; tick <= 216; ++tick) {
CHECK(c.intention(3, SessionIntention{3, 5, tick - 200, tick, 0, 0}, g).status ==
AdmitStatus::admitted);
g.server_tick = tick;
const auto m = mark_of(c.simulated(g), 3);
if (m) {
++sent;
CHECK(m->sequence == tick - 200); // The newest simulated intention.
}
}
CHECK(sent == 4); // Ticks 201 (first), 205, 209, 213.
}
// By default every session hears every simulated tick.
auto every = *IntentAdmission::create(IntentLimits{});
CHECK(every.open(7, alice));
for (std::uint64_t tick = 1; tick <= 3; ++tick)
CHECK(mark_of(every.simulated({true, 5, tick}), 7) == SimulatedThrough{5, 0, tick});
CHECK(every.simulated({true, 5, 3}).empty());
// Actions: receipt, carried with its tick's batch, final after the commit.
const auto action = [&](std::uint64_t session, std::uint64_t id, std::uint64_t tick,
std::uint16_t kind = 1) {
return a.action(session, SessionAction{session, 5, id, kind, tick}, f);
};
f.server_tick = 200;
auto r = action(1, 10, 203);
CHECK(r.status == AdmitStatus::admitted && r.tick == 203 && r.server_tick == 200);
CHECK(a.query(1, {10}, f).result == ActionResult::pending);
CHECK(action(1, 0, 203).status == AdmitStatus::invalid_action);
CHECK(action(1, 11, 203, 9).status == AdmitStatus::invalid_action);
{ // Wire kind 257 must not truncate to a known kind.
auto other = *IntentAdmission::create(IntentLimits{});
CHECK(other.open(1, alice));
CHECK(other.action(1, SessionAction{1, 5, 1, 257, 101}, AdmissionFacts{true, 5, 100})
.status == AdmitStatus::invalid_action);
}
r = action(1, 10, 204); // Retry with another tick: the original stands.
CHECK(r.status == AdmitStatus::duplicate && r.tick == 203);
CHECK(action(1, 12, 203).status == AdmitStatus::rate_limited); // 4 action attempts.
CHECK(a.carry(202).empty());
const auto carried = a.carry(203);
CHECK(carried.size() == 1 &&
carried[0] == CarriedAction{alice, 10, 203, ActionKind::probe, std::nullopt});
CHECK(a.carry(203).empty()); // Each action is carried once.
CHECK(a.committed({}, 7).empty());
auto outcomes = a.committed(carried, 8);
CHECK(outcomes.size() == 1 && outcomes[0].account == alice &&
outcomes[0].outcome == ActionOutcome{10, ActionResult::committed_no_effect, 203, 8});
CHECK(a.query(1, {10}, f) == outcomes[0].outcome);
CHECK(a.query(2, {10}, f).result == ActionResult::unknown); // Bob's account has no action 10.
// A reconnect of the same account (new session) sees the same outcome.
a.close(1);
CHECK(a.query(1, {10}, f).result == ActionResult::unknown); // Closed session asks nothing.
CHECK(a.open(3, alice) && a.session_of(alice) == 3u);
CHECK(a.query(3, {10}, f) == outcomes[0].outcome);
f.server_tick = 300;
CHECK(action(3, 10, 301).status == AdmitStatus::duplicate); // Never admitted twice.
// Unresolved cap counts intentions and actions; abandon finalizes only uncarried actions.
CHECK(action(3, 20, 301).status == AdmitStatus::admitted);
CHECK(action(3, 21, 308).status == AdmitStatus::admitted);
const auto riding = a.carry(301);
for (std::uint64_t i = 0; i < 4; ++i)
CHECK(a.intention(3, SessionIntention{3, 5, i + 1, 302 + i, 0, 0}, f).status ==
AdmitStatus::admitted);
CHECK(a.unresolved(3) == 6);
CHECK(a.intention(3, SessionIntention{3, 5, 9, 307, 0, 0}, f).status ==
AdmitStatus::too_many_unresolved);
outcomes = a.abandon();
CHECK(outcomes.size() == 1 &&
outcomes[0].outcome == ActionOutcome{21, ActionResult::not_committed, 0, 0});
CHECK(a.query(3, {20}, f).result == ActionResult::pending); // Carried: awaits its record.
CHECK(a.unresolved(3) == 1);
CHECK(a.committed(riding, 9).size() == 1); // Its batch turned out durable.
// Final outcomes are kept within a bound; older ones become unknown here.
for (std::uint64_t id = 30; id < 34; ++id) {
f.server_tick += 8;
CHECK(action(3, id, f.server_tick + 1).status == AdmitStatus::admitted);
CHECK(a.committed(a.carry(f.server_tick + 1), id).size() == 1);
}
CHECK(a.query(3, {10}, f).result == ActionResult::unknown);
CHECK(a.query(3, {33}, f).result == ActionResult::committed_no_effect);
}
} // namespace
// M10.8b handoff tickets (ADR-0096): signed by the source region's handoff key, verified
// by the destination against keys bound to source regions; then admitted by SessionControl.
TicketClaims ticket(const AccountId& who, std::uint8_t transfer, std::uint64_t source = 4,
std::uint32_t expires = now + 30, std::uint32_t session = now + 200) {
TicketClaims c;
c.transfer.fill(transfer);
c.account = who;
c.world = world_id;
c.source = source;
c.destination = region;
c.expires_at = expires;
c.session_expires_at = session;
return c;
}
void handoff_tickets() {
const auto alice = account(1), bob = account(2);
auto source = *HandoffSigningKey::generate(DeploymentEnvironment::dev, 41);
auto other = *HandoffSigningKey::generate(DeploymentEnvironment::dev, 42);
auto verifier = *HandoffVerifier::create(DeploymentEnvironment::dev, world_id, region);
CHECK(verifier.add_key(4, 41, *source.public_key()));
CHECK(verifier.add_key(5, 42, *other.public_key()));
CHECK(refused(verifier.add_key(6, 41, *other.public_key()), HandoffTicketError::duplicate_key));
CHECK(refused(verifier.add_key(region, 43, *other.public_key()),
HandoffTicketError::invalid_key)); // Never its own region.
const auto good = source.sign(ticket(alice, 0x71));
CHECK(good && looks_like_handoff_ticket(*good));
const auto v = verifier.verify(*good, now);
CHECK(v && v->claims().account == alice && v->claims().source == 4 &&
v->claims().destination == region && v->claims().transfer[0] == 0x71 &&
v->claims().session_expires_at == now + 200);
// Every signed byte matters; the signature too.
for (std::size_t at = 0; at < handoff_ticket_bytes; at += 7) {
auto bad = *good;
bad.at(at) ^= 0x10;
CHECK(!verifier.verify(bad, now));
}
// A key may only sign for its own region; scope, environment and times are checked.
CHECK(refused(verifier.verify(*other.sign(ticket(alice, 0x72, 4)), now),
HandoffTicketError::wrong_source));
auto elsewhere = ticket(alice, 0x73);
elsewhere.destination = 12;
CHECK(refused(verifier.verify(*source.sign(elsewhere), now), HandoffTicketError::wrong_scope));
elsewhere = ticket(alice, 0x73);
elsewhere.world = {7, 4};
CHECK(refused(verifier.verify(*source.sign(elsewhere), now), HandoffTicketError::wrong_scope));
CHECK(refused(verifier.verify(*good, now + 30), HandoffTicketError::expired));
CHECK(refused(verifier.verify(*source.sign(ticket(alice, 0x74, 4, now + 121)), now),
HandoffTicketError::expired)); // Longer than the maximum lifetime.
CHECK(refused(verifier.verify(*source.sign(ticket(alice, 0x75, 4, now + 30, now)), now),
HandoffTicketError::expired)); // The session would already have ended.
auto stage_key = *HandoffSigningKey::generate(DeploymentEnvironment::stage, 44);
CHECK(verifier.add_key(6, 44, *stage_key.public_key()));
CHECK(refused(verifier.verify(*stage_key.sign(ticket(alice, 0x76, 6)), now),
HandoffTicketError::wrong_environment));
auto unknown = *HandoffSigningKey::generate(DeploymentEnvironment::dev, 99);
CHECK(refused(verifier.verify(*unknown.sign(ticket(alice, 0x77)), now),
HandoffTicketError::unknown_key));
CHECK(refused(source.sign(ticket(alice, 0x78, region)), HandoffTicketError::invalid_claims));
CHECK(refused(source.sign(ticket(AccountId{}, 0x78)), HandoffTicketError::invalid_claims));
// Tickets and grants never verify as each other.
Keys dev{DeploymentEnvironment::dev};
CHECK(!dev.verifier.verify(*good));
const auto grant = dev.signer.sign(claims(alice, 1));
CHECK(grant && !looks_like_handoff_ticket(*grant) && !verifier.verify(*grant, now));
// SessionControl: a ticket opens a session for its account, once; it supersedes a grant
// session; the session ends at the ticket's session expiry, capped at the maximum
// grant lifetime from now.
auto c = config();
c.max_account_attempts = 16;
auto control = *SessionControl::create(c);
const auto by_grant = control.open(dev.verified(claims(alice, 3)), now);
CHECK(by_grant);
CHECK(control.check_handoff(*v, now));
const auto opened = control.open_handoff(*v, now);
CHECK(opened && opened->superseded == by_grant->session && opened->expires_at == now + 200 &&
control.holder(alice) == opened->session);
CHECK(refused(control.check_handoff(*v, now + 1), ControlError::stale_grant)); // Replay.
CHECK(refused(control.open_handoff(*v, now + 1), ControlError::stale_grant));
const auto long_session =
verifier.verify(*source.sign(ticket(bob, 0x79, 4, now + 30, now + 4000)), now);
CHECK(long_session);
const auto capped = control.open_handoff(*long_session, now);
CHECK(capped && capped->expires_at == now + c.max_grant_lifetime);
// A later grant for the account still opens normally (serials are untouched).
CHECK(control.open(dev.verified(claims(alice, 4)), now + 2));
}
// Session protocol v4 (ADR-0096): HandoffOffer and SessionRedirect.
void handoff_codec() {
HandoffOffer offer;
offer.transfer.fill(0x5C);
offer.destination = {12, "void.aeternalisgames.com:7402", "dev-region.evolution.test"};
offer.ticket.fill(0xA1);
const auto bytes = encode_session(offer);
const auto decoded = decode_session(bytes);
CHECK(decoded && std::get<HandoffOffer>(*decoded) == offer);
const SessionRedirect redirect{{12, "10.0.0.2:7400", "region-12.test"}};
const auto r = decode_session(encode_session(redirect));
CHECK(r && std::get<SessionRedirect>(*r) == redirect);
CHECK(decode_session(encode_session(SessionClose{SessionCloseReason::handed_off})));
CHECK(decode_session(encode_session(SessionClose{SessionCloseReason::moved})));
auto beyond = encode_session(SessionClose{SessionCloseReason::moved});
beyond.back() = static_cast<std::uint8_t>(SessionCloseReason::moved) + 1;
CHECK(refused(decode_session(beyond), SessionCodecError::invalid_value));
// Text fields: printable, no spaces, padded with zeros; region and transfer nonzero.
for (const auto& bad : {RegionAddress{12, "has space:1", "n"}, RegionAddress{12, "", "n"},
RegionAddress{0, "h:1", "n"}, RegionAddress{12, "h:1", ""}})
CHECK(refused(decode_session(encode_session(SessionRedirect{bad})),
SessionCodecError::invalid_value));
auto padded = encode_session(redirect);
padded.at(session_header_bytes + 8 + 20) = 'x'; // A byte after the endpoint's end.
CHECK(refused(decode_session(padded), SessionCodecError::invalid_value));
auto zero = offer;
zero.transfer.fill(0);
CHECK(refused(decode_session(encode_session(zero)), SessionCodecError::invalid_value));
auto longer = bytes;
longer.push_back(0);
CHECK(refused(decode_session(longer), SessionCodecError::wrong_length));
}
void control_tests() {
grants();
identity_adapter();
control_rules();
handoff_tickets();
handoff_codec();
session_codec();
intent_admission();
durable_actions();
deferred_actions();
}
} // namespace evo::network_test