Porting go-zenon to Rust (zenon-rs) with a Gemini 4 Neon Agent Swarm, Bun-in-Rust Discipline, and Bend Formal Verification
We’ve built a full, pure-Rust port of go-zenon (dev, pinned to commit 175f3056) called zenon-rs—spanning 214,607 lines of Rust across 403 files and 14 crates, backed by 11,374 lines of Bend formal proofs, 1,636 workspace tests, 24/24 passing Go TestLedger E2E tests, and a live mainnet sync currently running ~1.86× faster than go-zenon with zero hash mismatches.
Here’s how we structured the port, why we borrowed the Bun-in-Rust playbook, how Bend formal verification kept protocol invariants honest, how the Neon agent swarm executed it, and what live testing actually caught.
1. The Playbook: Borrowing from “Bun in Rust”
Large language-to-language ports fail in one predictable way: trying to “improve” or redesign the architecture while you’re still translating it. For a blockchain node—where a single off-by-one key encoding, rounding difference, or error-precedence swap causes a consensus fork—that’s fatal.
We adopted the core engineering rules from the Bun-in-Rust methodology upfront in PORTING.md and OWNERSHIP.tsv:
- Mechanical 1:1 behavioral port FIRST, optimize SECOND.
We preserved exact Protobuf & RLP wire encodings, KV key prefixes (including little-endian vs big-endian keys),goleveldb.Batch.Dump()(ChangesHash) bytes, FIPS-202 SHA3-256 vs legacy Keccak-256 separation,div_floorvs truncating division, Gomath/randv1 PRNG for consensus elections, Go’s case-insensitiveencoding/jsonconfig overlay quirks, mainnet height gates (10,109,240&14,567,887), spork gating, and CLI flag semantics before touching performance. - Strict anti-stub policy.
Zerotodo!(), zerounimplemented!(), zero#[ignore]tests, and zero hand-wavy workarounds:“If you need a paragraph-long comment to justify why the workaround is OK, the code is wrong — fix the code.”
- Acyclic crate DAG + explicit ownership table before writing code.
All 56 Go packages ingo-zenon/devwere mapped into 14 strictly acyclic Rust crates (L0–L9):L0:zenon-common(crypto, types, pure-Rustfjall 3LSM storage,ProtocolParams, log15 logging)L1:zenon-abi(split out ofvmto break Go’s package cycle),zenon-nom,zenon-wallet,zenon-p2p(legacy devp2p + libp2p + switcher)L2–L4:zenon-pow(incl. Dynamic Plasma),zenon-chain,zenon-consensusL5–L7:zenon-vm(verifier + all 12 embedded contracts),zenon-genesis,zenon-protocol,zenon-pillarL8–L9:zenon-node(HTTP/WS/InProc JSON-RPC, all 15 namespaces / 71 methods,ZenonImpl,MockZenonImpl),zenon-app(znnd,devnet-keygen,genesishash, andlibznnFFIcdylib)
- Zero mutable process-globals.
Instead of Go’s package-level globals (spork maps, clock, enforcement heights), every instance threads anArc<ProtocolParams>, making parallelcargo testcompletely deterministic and race-free.
2. How the Neon Agent Swarm Built It
Rather than pointing one agent at a 56-package codebase and hoping for the best, we ran a coordinated Gemini 4 Neon agent swarm across 8 sequential phases (Phases 0–7):
- Phase 0 (Spec, Oracle & Formal Models first): Before writing production node code, dedicated workers (
spec-architect,go-oracle,bend-laws) producedPORTING.md,OWNERSHIP.tsv, the deterministic Go-oracle vector generator (tools/go-oracle/), and the Bend formal suites (test/bend/). - Phases 1–6 (Bottom-up parallel crate porting): Each layer fanned out to specialized workers with disjoint file ownership slices (
port-common,port-abi,port-nom,port-wallet,port-p2p,port-pow,port-chain,port-consensus,port-vm-core,port-vm-contracts-a/b,port-genesis,proto-*,port-pillar,port-node-core,port-node-rpc,port-app). - Strict phase-boundary reviews & gates: Every phase had to pass
cargo test --locked --workspace,cargo clippy -- -D warnings,cargo fmt --check, Go-oracle parity checks, and adversarial code review (reviewer-1,reviewer-2, plus external cross-model reviews across Phases 0–6) before the next layer could begin. - Why phased gates mattered: They caught subtle bugs early—like
fjall 2tombstone resurrection (prompting an immediate upgrade tofjall 3.1.13), RPC blocking-handler offload and client reconnect edge cases, exact Goencoding/jsondecoder edge cases, and a fail-closed detector preventingzenon-rsfrom accidentally opening a legacy Go LevelDB directory.
3. Formal Verification with Bend
Unit tests check the cases you remember to write. For core consensus and economic invariants, we built a 6-step formal verification pipeline in Bend 2.0.40 (11,374 lines under test/bend/) covering four suites—ledger, escrow, plasma, and rewards—all executed via test/bend/run.sh:
- 160 Formal Laws (
LAWS.bend) & Machine-Checked Proofs (PROOF.bend):20ledger,33escrow,54plasma,53rewards — 4/4 suitesALL PROOFS CHECK.
- Independent Lean 4.34.0 Kernel Soundness Verdict (
--verdict):- 4/4 suites
ALL PROOFS CHECK.
- 4/4 suites
- 101 Witnessed Mutants (
mutants.py):- Deliberately buggy model mutations (
16ledger,17escrow,37plasma,31rewards) — 101/101caught, proving the laws aren’t vacuous.
- Deliberately buggy model mutations (
- Bend Model vs. Real Rust Node Fuzzing (
BEND_RANDOM=40):- 10/10 differential model-vs-node scenarios pass against the real
zenon-node/zenon-vm/zenon-chainstack (crates/zenon-node/tests/bend_laws.rs).
- 10/10 differential model-vs-node scenarios pass against the real
- 21 Rust VM Fault-Injection Hooks (
node_faults.py):- Strictly compiled out of default/release builds (
#[cfg(feature = "bend-faults")]), armed viaZENON_BEND_FAULT=<name>. - Default-build isolation check PASS + 21/21 injected faults
caught(3ledger,10escrow,4plasma,4rewards)—proving the differential harness actually catches real protocol violations inside the Rust VM.
- Strictly compiled out of default/release builds (
- Exhaustive Bounded Trace Comparison (
DEPTH=2):- 8/8 PASS — 1,104/1,104 action sequences compared between Bend models and the Rust node with 0 differences.
4. How We Tested It (And What Testing Actually Caught)
We tested zenon-rs across five escalating layers:
Layer 1: Deterministic Go Oracle (tools/go-oracle/)
We generated 13 golden JSON vector suites (testdata/vectors/*.json, ~3.4 MB) directly from the real go-zenon/dev binary—covering crypto/types, ABI, RLP, Protobuf, wallet/Argon2id/KeyFile, PoW & Dynamic Plasma, chain/patches, consensus elections, 16 VM scenarios, P2P, and both Alphanet (9e204601...) and mock genesis hashes—plus tools/go-oracle/run.sh --check-repro verifying zero drift. During Phase 4 we also ran differential sweeps across 34.9M genesis JSON documents and 152k+ VM/crypto/regex vectors with 0 mismatches.
Layer 2: Workspace & Formal Suites
cargo test --locked --workspace: 1,636 passed, 0 failed, 0 ignoredcargo test --locked -p zenon-vm --features bend-faults: 167 passedcargo clippy --workspace --all-targets -- -D warnings: 0 warnings- Full 6-step
test/bend/run.sh: all 6 steps green
Layer 3: Real Go test/e2e (TestLedger), Mixed Go↔Rust Devnet & RPC Soak
- Live Go
TestLedgeron a 4-node Rust release devnet: Runninggo-zenon’s own E2E suite against 4 Rust nodes immediately caught a real RPC error-string mismatch (check_token_id_validinterceptedERR_DATA_NON_EXISTENTand returned"ts doesn't exist"instead of Go’s"data non existent"). Fixed → 24/24 PASS (130s), 0 forks, all 3 genesis pillars producing, 34 refused blocks properly rejected. - Mixed Go ↔ Rust devnet:
devnet-keygenandgenesishashmatched bit-for-bit (34eb0f51...); both Go producer → Rust follower and Rust producer → Go follower achieved 100% RPC parity. - RPC & WebSocket stress soak: 8,000 concurrent batch RPC calls + 50 abrupt
SO_LINGER=0TCP resets + 30 WebSocket churn cycles completed in<1s,stats.syncInfop50 = max = 1.90 ms, 0 file descriptor leaks (31 FDs before and after).
Layer 4: Exact-Height Zero-Normalization State Parity (h = 51,201)
We synced go-zenon live on mainnet to height 51,201, froze it locally, and peered a fresh zenon-rs node exclusively to local go-zenon over enode:// P2P (1 → 51,201 in 62.4s). At exact height 51,201, with zero JSON normalization (including live token.totalSupply, numConfirmations, pairedAccountBlock, balances, pillars, and rewards):
Exact-Height Check (h = 51,201) |
Checked | Mismatches |
|---|---|---|
ledger.getMomentumsByHeight (1..51,201, incl. changesHash) |
51,201 | 0 |
ledger.getDetailedMomentumsByHeight (h >= 2) |
309 | 0 |
ledger.getAccountBlockByHash (incl. 100 genesis blocks) |
783 | 0 |
| Embedded contract global queries (51 pillars, 31 tokens, 50 sentinels, swap, bridge, liquidity, spork, accelerator) | 11 | 0 |
Per-account queries across 120 active/pillar/contract addresses (accountInfo, frontierBlock, unreceived, plasma, stakeReward, delegatedPillar) |
720 | 0 |
Layer 5: Head-to-Head Live Mainnet Sync & Real-Time Profiling
Running go-zenon and zenon-rs side-by-side against live mainnet with a real-time field-by-field verifier (hash, previousHash, changesHash, content, producer, signature) proved the value of “port faithfully first, profile second”:
- Baseline run: Verified 703,560 consecutive mainnet momentums (~81.4 epochs) with 0 hash mismatches—and exposed a real scaling bottleneck once the DB passed ~300 MB (
h > 200k), where Rust slowed from ~670/s down to ~60–180/s with ~15–20s pauses at every epoch boundary (~8,640momentums). - A 5-second live macOS
sampleprofile ath = 661,667pinpointed 4 exact bottlenecks:MergedDb::get()4× redundant LSM probes: Faithfully ported from Go’smerged.go, callinglayer.has()beforelayer.get()across 3 nested overlay layers insideLdbManager::get()caused3 × has() + 1 × get()per read—79% ofEnableDeleteDb::getCPU during per-epochcompute_pillar_delegations.fjallcache & index pinning defaults: Default 32 MiB block cache, unpinned L2+ index/filter blocks, andworker_threads(1)caused 76% of active CPU to thrash inpread()+xxh3_128block checksums once SSTables reached L2+.- Unbuffered log writes:
RotatingFileWriterdid a rawwrite(2)syscall on every singleINFOlog line (~15% of active CPU). - Eager iterator chunking:
FjallIterator::fill_chunkalways cloned 256 KV pairs even for single-entry.last()frontier lookups.
- After patching all four in commit
64eb6a7(zero protocol changes):- Re-running side-by-side on live mainnet eliminated the epoch stalls completely:
zenon-rsjumped to ~1,110–1,230 momentums/s (750k+momentums in ~11 minutes vsgo-zenon’s404k— ~1.86× faster than Go and >2× faster than unpatched Rust), with 0 hash mismatches and 0 errors/panics.
- Re-running side-by-side on live mainnet eliminated the epoch stalls completely:
5. Current Status & What’s Next
- Full
14.76Mlive mainnet sync is running right now side-by-side withgo-zenonto live-verify late-era sporks (Bridge, Liquidity, HTLC, Accelerator-Z, Dynamic Plasma v2 momentums) and mainnet height gates (10,109,240&14,567,887) all the way to tip. - Storage note:
zenon-rsuses pure-Rustfjall 3(no Go LevelDB dependency) and intentionally fails closed if pointed at an existing Gonomdirectory—sync into a fresh data directory. - Repo: github.com/0x3639/zenon-rs — feedback, testing, and full-chain sync reports welcome!