// M10.4c headless session client (ADR-0091, ADR-0092). Development and test only. // // evo-session-probe keys --out DIR // Writes a fresh dev issuer key pair: DIR/issuer.key (32-byte P-256 scalar, owner-only) // and DIR/issuer.pub (65-byte public key for evo-server --m10-issuer). // evo-session-probe grants --issuer-key FILE --world N --frame N --region N // --account HEX32 --out FILE [--serial N] [--count 1..64] [--lifetime 60..14400] // M10.5c (ADR-0093): writes COUNT 160-byte grants for one account (the engineering // client's grant bundle), serials SERIAL..SERIAL+COUNT-1, all issued now. Without // --serial the first is 64 x the issue time in seconds, so a later bundle for the same // account supersedes an earlier one without bookkeeping. The file is created new and // owner-only (a credential: never commit or share it); the issuer key stays here. // The region refuses grants longer than its --m10-max-grant-lifetime (default 300). // M10.8c (ADR-0096): --region may repeat; COUNT grants are written per region, // interleaved in serial order, so a client crossing between regions always has a newer // serial for the next one (serials must rise world-wide). A handoff key is a key pair // from `keys` (issuer.key for --m10-handoff-key, issuer.pub for --m10-neighbour). // M10.9d (ADR-0097): --accounts N (1..256) writes the same for N accounts, account by // account: account i is --account with its last two bytes replaced by i + 1 (big // endian). This is the load bundle `evo-load --grants FILE --grants-per-bot COUNT` uses. // evo-session-probe run --connect HOST:PORT --server-name NAME --ca FILE --issuer-key FILE // --world N --frame N --region N --account HEX32 --serial N [--lifetime S] // [--intents N] [--actions N --action-base ID] [--query ID]... [--timeout-ms N] // [--interest X,Y,Z,R] [--snapshots N] // Signs a dev grant for the account and serial, logs in over QUIC, sends N intentions // (one per tick, two ticks ahead) and N probe actions (three ticks ahead), queries the // given action ids, and prints one line per answer: // welcome SESSION EPOCH TICK | intention SEQ STATUS | simulated SEQ TICK // receipt ID STATUS TICK | outcome ID RESULT TICK COMMIT | done // resolved HOST ADDRESS (a host name was looked up; IPv4) // snapshot TICK CELLS ORGANISMS MINX MINY MAXX MAXY Z (each newly applied snapshot; // --snapshots N waits for N; --interest asks for another focus than the default) // marker TICK X Y APPLIED (the session's own probe marker in each new snapshot: um // position after TICK and the newest applied intention sequence; ADR-0094) // handoff REGION ENDPOINT | redirect REGION ENDPOINT (v4, ADR-0096; then closed) // closed REASON TRANSPORT (TRANSPORT names why QUIC ended: untrusted means the server // answered but failed the pinned CA/name check; idle means nothing answered) // Statuses, results and reasons are the session-v1 wire values. Exits 0 once every // action is final and every query answered, 1 on timeout, 3 when the server closes. // evo-session-probe run --connect HOST:PORT --server-name NAME --ca FILE --grants FILE // [--grant N] [options as above] // M10.9 (ADR-0097): logs in with grant N (from 0) of an existing bundle instead of // signing one, e.g. the bundle a dev renewal produced; no issuer key is needed here. // Serials rise through a bundle and a used serial is refused (stale_grant), so each // login takes the next N. Prints "grant N of COUNT" first. // The issuer key is a development credential: the probe refuses any environment but dev. #include "evo/client/region_session.hpp" #include "evo/network/session_grant.hpp" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace { using namespace evo; using namespace evo::network; using Clock = std::chrono::steady_clock; std::optional number(std::string_view v) { std::uint64_t n = 0; const auto [end, ec] = std::from_chars(v.data(), v.data() + v.size(), n); if (ec != std::errc{} || end != v.data() + v.size()) return std::nullopt; return n; } std::string read(const std::filesystem::path& path) { std::ifstream file{path, std::ios::binary}; return {std::istreambuf_iterator{file}, std::istreambuf_iterator{}}; } bool write(const std::filesystem::path& path, std::span bytes) { std::ofstream file{path, std::ios::binary | std::ios::trunc}; file.write(reinterpret_cast(bytes.data()), static_cast(bytes.size())); return file.good(); } std::optional account_of(std::string_view hex) { if (hex.size() != 32) return std::nullopt; AccountId id; for (std::size_t i = 0; i < 16; ++i) { unsigned value = 0; const auto [end, ec] = std::from_chars(hex.data() + (2 * i), hex.data() + (2 * i) + 2, value, 16); if (ec != std::errc{} || end != hex.data() + (2 * i) + 2) return std::nullopt; id.bytes.at(i) = static_cast(value); } return id.valid() ? std::optional{id} : std::nullopt; } const char* cause_name(std::optional c) { if (!c) return "none"; switch (*c) { case quic::CloseCause::local: return "local"; case quic::CloseCause::peer: return "peer"; case quic::CloseCause::idle: return "idle"; case quic::CloseCause::untrusted: return "untrusted"; case quic::CloseCause::overloaded: return "overloaded"; case quic::CloseCause::protocol: return "protocol"; default: return "transport"; } } std::uint64_t now_seconds() { return static_cast(std::chrono::duration_cast( std::chrono::system_clock::now().time_since_epoch()) .count()); } std::optional issuer(const std::string& path) { const auto scalar = read(path); auto key = GrantSigningKey::import( DeploymentEnvironment::dev, 1, std::span{reinterpret_cast(scalar.data()), scalar.size()}); if (!key) return std::nullopt; return std::move(*key); } std::optional sign(const GrantSigningKey& key, GrantClaims claims) { std::array id{}; if (!random_bytes(id)) return std::nullopt; for (std::size_t i = 0; i < id.size(); ++i) claims.grant_id |= static_cast(id.at(i)) << (8U * i); claims.grant_id = std::max(claims.grant_id, 1); const auto grant = key.sign(claims); if (!grant) return std::nullopt; return *grant; } int keys(const std::filesystem::path& out) { std::filesystem::create_directories(out); for (int attempt = 0; attempt < 8; ++attempt) { std::array scalar{}; if (!random_bytes(scalar)) return 1; auto key = GrantSigningKey::import(DeploymentEnvironment::dev, 1, scalar); if (!key) continue; // Out of the curve's range: draw again. const auto pub = key->public_key(); if (!pub || !write(out / "issuer.key", scalar) || !write(out / "issuer.pub", *pub)) return 1; std::filesystem::permissions(out / "issuer.key", std::filesystem::perms::owner_read | std::filesystem::perms::owner_write, std::filesystem::perm_options::replace); std::puts("keys written"); return 0; } return 1; } struct RunOptions { std::string host, server_name, ca, issuer_key, grants_file; std::uint64_t grant_index{}; std::uint16_t port{}; std::uint64_t world{}, frame{}, region{}, serial{}, lifetime{60}, intents{}, actions{}, action_base{1}, timeout_ms{20000}; std::optional account; std::vector queries; std::vector more_regions; // grants: further --region values. std::optional interest; std::uint64_t snapshots{}; }; std::optional interest_of(std::string_view v) { std::array parts{}; for (std::size_t i = 0; i < parts.size(); ++i) { const auto comma = v.find(','); const auto part = v.substr(0, comma); const auto [end, ec] = std::from_chars(part.data(), part.data() + part.size(), parts.at(i)); if (ec != std::errc{} || end != part.data() + part.size() || (comma == std::string_view::npos) != (i + 1 == parts.size())) return std::nullopt; v.remove_prefix(comma == std::string_view::npos ? v.size() : comma + 1); } if (parts[3] < 0 || parts[3] > 65535) return std::nullopt; return SessionInterest{parts[0], parts[1], parts[2], static_cast(parts[3])}; } // Exclusive create, owner-only on POSIX: a bundle is a credential. bool write_new(const std::filesystem::path& path, std::span bytes) { if (std::filesystem::exists(path)) return false; if (!write(path, bytes)) return false; std::filesystem::permissions( path, std::filesystem::perms::owner_read | std::filesystem::perms::owner_write, std::filesystem::perm_options::replace); return true; } int grants(const RunOptions& o, const std::string& out, std::uint64_t count, std::uint64_t accounts) { const auto key = issuer(o.issuer_key); if (!key || !o.account) { std::puts("error issuer-key"); return 2; } GrantClaims claims; claims.world = {o.world, o.frame}; claims.issued_at = now_seconds(); claims.expires_at = claims.issued_at + o.lifetime; const auto first = o.serial != 0 ? o.serial : claims.issued_at * 64; std::vector regions{o.region}; regions.insert(regions.end(), o.more_regions.begin(), o.more_regions.end()); if (count * regions.size() > 64) { std::puts("error count (at most 64 grants per account)"); return 2; } std::vector bundle; for (std::uint64_t a = 0; a < accounts; ++a) { claims.account = *o.account; if (accounts > 1) { // Account a: the last two bytes are a + 1. claims.account.bytes.at(14) = static_cast(((a + 1) >> 8U) & 0xFFU); claims.account.bytes.at(15) = static_cast((a + 1) & 0xFFU); } std::uint64_t serial = first; for (std::uint64_t i = 0; i < count; ++i) for (const auto region : regions) { claims.region = region; claims.serial = serial++; const auto grant = sign(*key, claims); if (!grant) { std::puts("error grant"); return 2; } bundle.insert(bundle.end(), grant->begin(), grant->end()); } } count *= regions.size(); if (!write_new(out, bundle)) { std::puts("error out (exists or unwritable)"); return 1; } std::printf( "wrote %llu grants serial %llu..%llu valid %llu s accounts %llu\n", static_cast(count) * accounts, static_cast(first), static_cast(first + count - 1), static_cast(o.lifetime), static_cast(accounts)); return 0; } // Grant `index` of a bundle file (concatenated 160-byte grants). std::optional bundled(const std::string& path, std::uint64_t index) { const auto bytes = read(path); const auto count = bytes.size() / session_grant_bytes; if (bytes.empty() || bytes.size() % session_grant_bytes != 0 || index >= count) return std::nullopt; SessionGrant g{}; std::copy_n(bytes.begin() + static_cast(index * session_grant_bytes), session_grant_bytes, reinterpret_cast(g.data())); std::printf("grant %llu of %zu\n", static_cast(index), count); return g; } int run(const RunOptions& o) { std::optional grant; if (!o.grants_file.empty()) { grant = bundled(o.grants_file, o.grant_index); if (!grant) { std::puts("error grants"); return 2; } } else { const auto key = issuer(o.issuer_key); if (!key) { std::puts("error issuer-key"); return 2; } if (!o.account) return 2; // Required at parse time. GrantClaims claims; claims.account = *o.account; claims.serial = o.serial; claims.world = {o.world, o.frame}; claims.region = o.region; claims.issued_at = now_seconds(); claims.expires_at = claims.issued_at + o.lifetime; grant = sign(*key, claims); } if (!grant) { std::puts("error grant"); return 2; } client::RegionSessionClientConfig config; const auto address = quic::resolve_ipv4(o.host); if (!address) { std::puts("error resolve"); return 2; } if (*address != o.host) std::printf("resolved %s %s\n", o.host.c_str(), address->c_str()); config.transport.server_address = *address; config.transport.port = o.port; config.transport.server_name = o.server_name; config.transport.authority_pem = read(o.ca); config.transport.authority_pem_file = o.ca; config.grant = *grant; auto made = client::RegionSessionClient::connect(std::move(config), Clock::now()); if (!made) { std::puts("error connect"); return 2; } auto& c = **made; const auto deadline = Clock::now() + std::chrono::milliseconds{o.timeout_ms}; bool welcomed = false, queried = false; std::uint64_t sent_intents = 0, sent_actions = 0, last_tick = 0, simulated = 0; std::uint64_t seen_snapshot = 0, snapshots = 0; std::set pending_actions, pending_queries(o.queries.begin(), o.queries.end()); for (std::uint64_t i = 0; i < o.actions; ++i) pending_actions.insert(o.action_base + i); while (Clock::now() < deadline) { c.poll(Clock::now()); if (c.state() == client::RegionSessionState::closed) { if (const auto offer = c.take_handoff()) std::printf("handoff %llu %s\n", static_cast(offer->destination.region), offer->destination.endpoint.c_str()); if (const auto& to = c.redirect()) std::printf("redirect %llu %s\n", static_cast(to->region), to->endpoint.c_str()); std::printf("closed %u %s\n", static_cast( c.close_reason().value_or(SessionCloseReason::connection_lost)), cause_name(c.transport_cause())); return 3; } if (c.state() != client::RegionSessionState::established) { std::this_thread::sleep_for(std::chrono::milliseconds{2}); continue; } if (!welcomed) { welcomed = true; const auto& w = *c.welcome(); std::printf("welcome %llu %llu %llu\n", static_cast(w.session), static_cast(w.epoch), static_cast(w.server_tick)); } const auto tick = c.server_tick(); if (tick != last_tick) { last_tick = tick; if (sent_intents < o.intents && c.send_intention(tick + 2, 100, 0)) ++sent_intents; if (sent_actions < o.actions && c.send_action(o.action_base + sent_actions, ActionKind::probe, tick + 3)) ++sent_actions; } if (!queried) { queried = true; if (o.interest && !c.set_interest(*o.interest)) std::puts("error interest"); for (const auto query : o.queries) (void)c.query_action(query); } for (const auto& r : c.take_intention_receipts()) std::printf("intention %llu %u\n", static_cast(r.sequence), static_cast(r.status)); if (const auto s = c.simulated(); s && s->sequence != simulated) { simulated = s->sequence; std::printf("simulated %llu %llu\n", static_cast(s->sequence), static_cast(s->tick)); } if (const auto* v = c.view(); v && v->tick != seen_snapshot) { seen_snapshot = v->tick; ++snapshots; std::int64_t min_x = 0, min_y = 0, max_x = 0, max_y = 0; for (std::size_t i = 0; i < v->environment.size(); ++i) { const auto& voxel = v->environment[i].voxel; min_x = i == 0 ? voxel.x : std::min(min_x, voxel.x); min_y = i == 0 ? voxel.y : std::min(min_y, voxel.y); max_x = i == 0 ? voxel.x : std::max(max_x, voxel.x); max_y = i == 0 ? voxel.y : std::max(max_y, voxel.y); } std::printf("snapshot %llu %zu %zu %lld %lld %lld %lld %lld\n", static_cast(v->tick), v->environment.size(), v->organisms.size(), static_cast(min_x), static_cast(min_y), static_cast(max_x), static_cast(max_y), static_cast(v->slice_z)); for (const auto& m : v->markers) if (m.own) std::printf( "marker %llu %lld %lld %llu\n", static_cast(v->tick), static_cast(m.state.x), static_cast(m.state.y), static_cast(m.applied_sequence)); } for (const auto& r : c.take_action_receipts()) std::printf("receipt %llu %u %llu\n", static_cast(r.action_id), static_cast(r.status), static_cast(r.tick)); for (const auto& out : c.take_action_outcomes()) { std::printf( "outcome %llu %u %llu %llu\n", static_cast(out.action_id), static_cast(out.result), static_cast(out.tick), static_cast(out.commit_sequence)); pending_queries.erase(out.action_id); if (out.result == ActionResult::committed_no_effect || out.result == ActionResult::not_committed) pending_actions.erase(out.action_id); } std::fflush(stdout); if (sent_actions == o.actions && pending_actions.empty() && pending_queries.empty() && sent_intents == o.intents && simulated >= std::min(o.intents, 1) && snapshots >= o.snapshots) { std::printf("snapshot-bytes %llu chunks %llu\n", static_cast(c.snapshot_bytes()), static_cast(c.snapshot_chunks())); std::puts("done"); c.close(); return 0; } std::this_thread::sleep_for(std::chrono::milliseconds{2}); } std::puts("timeout"); return 1; } } // namespace int main(int argc, char** argv) { const std::vector args(argv + 1, argv + argc); if (args.size() == 3 && args[0] == "keys" && args[1] == "--out") return keys(std::filesystem::path{std::string{args[2]}}); RunOptions o; const bool bundle = !args.empty() && args[0] == "grants"; std::string out; std::uint64_t count = 1, accounts = 1; if (bundle) o.lifetime = 300; // The region's default maximum. bool ok = !args.empty() && (args[0] == "run" || bundle) && args.size() % 2 == 1; for (std::size_t i = 1; ok && i + 1 < args.size(); i += 2) { const auto flag = args[i]; const auto value = args[i + 1]; const auto n = number(value); if (flag == "--connect") { const auto colon = value.rfind(':'); const auto port = colon == std::string_view::npos ? std::nullopt : number(value.substr(colon + 1)); ok = port && *port > 0 && *port <= 65535; if (ok) { o.host = std::string{value.substr(0, colon)}; o.port = static_cast(*port); } } else if (flag == "--server-name") o.server_name = value; else if (flag == "--ca") o.ca = value; else if (flag == "--issuer-key") o.issuer_key = value; else if (flag == "--grants" && !bundle) o.grants_file = value; else if (n && flag == "--grant" && !bundle) o.grant_index = *n; else if (flag == "--account") ok = (o.account = account_of(value)).has_value(); else if (flag == "--query" && n) o.queries.push_back(*n); else if (n && flag == "--world") o.world = *n; else if (n && flag == "--frame") o.frame = *n; else if (n && *n != 0 && flag == "--region" && bundle && o.region != 0) o.more_regions.push_back(*n); else if (n && flag == "--region") o.region = *n; else if (n && flag == "--serial") o.serial = *n; else if (n && flag == "--lifetime" && *n > 0 && *n <= 14400) o.lifetime = *n; else if (n && flag == "--intents" && *n <= 1000) o.intents = *n; else if (n && flag == "--actions" && *n <= 1000) o.actions = *n; else if (n && flag == "--action-base" && *n > 0) o.action_base = *n; else if (n && flag == "--timeout-ms" && *n > 0) o.timeout_ms = *n; else if (n && flag == "--snapshots" && *n <= 100000) o.snapshots = *n; else if (flag == "--interest") ok = (o.interest = interest_of(value)).has_value(); else if (bundle && flag == "--out") out = value; else if (bundle && n && flag == "--count" && *n >= 1 && *n <= 64) count = *n; else if (bundle && n && flag == "--accounts" && *n >= 1 && *n <= 256) accounts = *n; else ok = false; } if (bundle && ok && !o.issuer_key.empty() && o.account && o.world != 0 && o.frame != 0 && o.region != 0 && !out.empty() && o.lifetime >= 60 && o.host.empty()) return grants(o, out, count, accounts); const bool signs = o.grants_file.empty(); if (bundle || !ok || o.host.empty() || o.server_name.empty() || o.ca.empty() || (signs && (o.issuer_key.empty() || !o.account || o.world == 0 || o.frame == 0 || o.region == 0 || o.serial == 0)) || (!signs && !o.issuer_key.empty())) { std::fputs( "usage: evo-session-probe keys --out DIR | grants --issuer-key FILE " "--world N --frame N --region N --account HEX32 --out FILE [--serial N] " "[--count 1..64] [--accounts 1..256] [--lifetime 60..14400] | run --connect HOST:PORT " "--server-name NAME --ca FILE --issuer-key FILE --world N --frame N " "--region N --account HEX32 --serial N [--lifetime S] [--intents N] " "[--actions N --action-base ID] [--query ID]... [--timeout-ms N] " "[--interest X,Y,Z,R] [--snapshots N] | run --connect HOST:PORT " "--server-name NAME --ca FILE --grants FILE [--grant N] [run options]\n", stderr); return 2; } return run(o); }