Private crypto accounting: scan RAILGUN txs with a viewing key into a Beancount ledger.
NOTE: I could not finish this in time for the deadline.
pool-watcher is a privacy-preserving accounting system for RAILGUN V2, the private-transaction protocol on Ethereum. RAILGUN hides who sent what to whom, which is great for privacy but terrible for bookkeeping: a merchant receiving private payments has no normal way to produce a ledger, because the on-chain data is encrypted. This project closes that gap end to end.
The core idea is viewing-key-based trial decryption. A wallet's viewing key can see its own transactions but can never spend funds. We use that asymmetry to build a read-only accounting pipeline that never touches spending authority.
The system has four parts. First, a local test bed: an Anvil chain with a fresh RAILGUN V2 deployment and a scripted scenario that shields 1000 test tokens to wallet A, sends five private transfers from A to B with product memos, then unshields 50 from B to a public address, exporting the resulting logs, steps, and viewing keys as ground truth. Second, a stateless scanner: a Node/TypeScript service that trial-decrypts RAILGUN Shield, Transact, and Unshield logs for a single viewing key. It holds no database, no Merkle tree, no RPC access, and no state, making it a pure decrypt primitive. It speaks NDJSON over a Unix socket (init, scan, pubkey, ping) and returns one event per decrypted note, including direction, memo, sender and receiver, and the unshield fee split. A Rust handle crate defines the wire contract and is the production client. Third, a Rust integration app: an actix-web UI where the merchant pastes their viewing key. The browser seals that key client-side to the scanner's X25519 public key using X25519, HKDF-SHA256, and XChaCha20-Poly1305, so the plaintext key never crosses the socket or touches disk. An alloy listener backfills and live-subscribes to chain logs, feeds them to the scanner, and a writer turns the decrypted events into a Beancount ledger. Fourth, Fava serves that ledger as a real accounting UI. Incoming private transfers appear as product-narrated sales, the unshield appears as a withdrawal to the bank with the fee booked as an expense, and change notes are excluded. The ledger is idempotent: events are deduped in memory and the file is atomically rewritten, so restarts rebuild cleanly from backfill.
Why it matters: it demonstrates that private on-chain payments can still be reconciled with double-entry accounting. bean-check passes, balances tie out (185 TST remaining, 235 in sales, 50 minus fee to the bank), and spending keys are never exposed and plaintext viewing keys never leak. The scanner is also chain-, asset-, and pool-agnostic, and its KeyService seam is designed to swap the sealed-box demo for a future Nitro enclave, where the viewing key would be decrypted inside attested hardware.
In short: private money, public-grade books. A complete demo that takes encrypted RAILGUN activity and turns it into an auditable merchant ledger, with privacy preserved at every step.
How I built pool-watcher
The stack at a glance. The project is four cooperating pieces: a Nix/devenv-managed local test bed, a Node/TypeScript decryption scanner, a Rust integration app, and a Beancount/Fava accounting UI, wired together with Docker Compose. The through-line is RAILGUN V2, the privacy protocol whose encrypted events we turn into a ledger.
The test bed (ground truth). We needed real RAILGUN history to build against, so we built a reproducible local chain. devenv.nix pins Foundry (Anvil and cast), Node 22, Yarn, Rust, and jq; scripts/install.sh is idempotent and does the heavy lifting. It checks out a pinned RAILGUN contracts submodule (vendor/contract), applies a patch, installs the Hardhat 2.x/ethers v5 toolchain, compiles the contracts, and installs the demo's TypeScript deps. scripts/chain.sh starts Anvil with --state .state/anvil.json so history survives restarts. scripts/deploy.sh runs hardhat deploy:test, parses the deployed proxy/delegator/testERC20 addresses out of Hardhat's log, and records them plus a deployment block in .state/deployment.json. The scenario itself uses the official @railgun-community/wallet SDK (10.4.0) with snarkjs and leveldown for proof generation and the engine DB. scripts/scenario.sh shields 1000 test tokens to wallet A, sends five private A-to-B transfers with product memos, unshields 50 from B to a public EOA, then exports balances, keys, and the raw proxy logs. Those exports (out/steps.jsonl, out/keys.json, out/logs.json) are the ground truth every other component is tested against.
The scanner (stateless trial decryption). The scanner is a Node/TypeScript service that imports only the decryption primitives from @railgun-community/engine — ShieldNote.decryptRandom, TransactNote.decrypt, getNoteHash, serializeTokenData — not the wallet/engine runtime. It holds no database, no Merkle tree, no RPC, and no state: it is a pure decrypt primitive. For each Transact ciphertext it derives a shared key from the viewing key and the blinded receiver key, tries isSentNote=false, then the blinded sender key with isSentNote=true; a passing AES-GCM auth means the note belongs to the wallet. Shields use the shieldKey the same way. The wire protocol is deliberately boring: NDJSON over a Unix domain socket, one JSON object per line, one response per request, with init, scan, pubkey, and ping ops. One process and one socket per viewing key, single-flight (extra connections queue). We used zod to validate requests and ethers' Interface to parse the RAILGUN ABI. The Rust railgun-scanner-handle crate is the source of truth for the wire contract; the Node scanner mirrors it, and the same crate is used as the cross-language protocol test client.
The app (Rust: actix-web + alloy + Beancount). The integration app is a Rust binary. actix-web 4.18 serves a small UI and API; alloy 2.5 does the chain I/O; tokio runs the async runtime; bigdecimal and chrono handle money and dates. The flow: the browser fetches the scanner's X25519 public key, seals the pasted viewing key client-side, and POSTs only ciphertext to /api/init. The app relays it to the scanner over the socket; the scanner opens it, derives the 0zk wallet address, and becomes ready. The plaintext viewing key never crosses the socket and never touches disk. Once initialized, an alloy listener backfills eth_getLogs from the deployment block, then keeps a live eth_subscribe WebSocket stream. Logs are grouped by block, each block's timestamp is fetched for the Beancount date, and batches are sent to the scanner. A ledger writer maps events to double-entry Beancount: incoming notes with product memos become sales, the unshield becomes a withdrawal with the fee split to Expenses:Fees, and change notes are excluded. It dedupes by txHash:logIndex:hash:direction and rewrites the file atomically (temp + rename), so Fava reloads on the rename and restarts rebuild idempotently from backfill. Fava runs in its own container and waits for the ledger file to appear.
How it's pieced together. Docker Compose runs scanner-b, app, and fava; Anvil stays on the host. The scanner and app share a Unix-socket volume; the app mounts .state read-only and a ledger volume that Fava also mounts. The app's Dockerfile uses the repo root as build context because the Rust crate path-depends on scanner/crates/handle. A multi-stage build compiles the browser seal bundle with esbuild, then embeds it into the Rust binary with include_str!. The scanner's KEY_SERVICE is a build arg baked into the image (local for tests, sealedbox for the demo), never a wire input.
Partner technologies and why they helped. RAILGUN is the whole point: its viewing-key model gives us read-only visibility without spending authority, and its engine gave us battle-tested note decryption instead of reimplementing the cryptography. Foundry/Anvil gave us a fast, state-persistent local chain with cast for scripting. alloy gave us typed HTTP + WS providers and log subscriptions in Rust with minimal glue. actix-web gave us a tiny, fast UI/API server. Beancount + Fava gave us a real, auditable double-entry ledger and a polished accounting UI for free. @noble (curves/hashes/ciphers) let the exact same sealed-box code run in the browser and the scanner. Nix/devenv made the whole toolchain reproducible.
The notably hacky bits. The test-artifacts tarball was dead (HTTP 525), so we patched the contracts repo to drop @railgun-community/circuit-artifacts and make loadAllArtifacts a no-op, then wrote register-vkeys.ts to fetch production vkeys from IPFS and register all 54 non-POI variants directly. eth_estimateGas lied: it estimated ~87k for delegator.callContract(proxy, setVerificationKey, 0) when the real cost was ~1.2M, so the inner call silently ran out of gas while the outer tx succeeded; we send an explicit gasLimit of 5,000,000 and assert the VerifyingKeySet event. The engine's exports map blocks deep imports, and getSharedSymmetricKey, poseidon, and encodeAddress aren't exported, so we reimplemented the small primitives: X25519 scalar multiplication + SHA-256 for the shared key, Poseidon via circomlibjs, and bech32m 0zk address encoding. Unshield attribution: the public Unshield event has no sender, so we attribute it to the wallet that can decrypt a note in the same transaction (the change note) — otherwise wallet A would see B's withdrawal. Unshield amounts are net: the contract emits base already net of fee; we report value = base + fee (gross leaving the private balance) and fee separately so the ledger can post net to the bank and fee to expenses. Change notes decrypt both ways, producing an in and an out event that cancel in the balance arithmetic. Anvil's --state reload doesn't preserve historical eth_getCode, so a binary search for the exact proxy block fails after restart; we record the pre-deploy block as a safe lower bound. V3 addresses don't exist in the pinned contracts, so lib.ts disables V3 at runtime by mutating both the top-level and the wallet SDK's nested shared-models copy. Bridging sync and async: the Rust handle is deliberately synchronous (std::UnixStream, no tokio), so the app owns it on a dedicated thread and talks to it over an mpsc channel with oneshot replies, serializing all scans. Custom sealed-box envelope: ephemeralPub(32) || nonce(24) || ciphertext, key = HKDF-SHA256(shared, info="railgun-scanner-vk"), AEAD = XChaCha20-Poly1305 — identical code in seal.ts and the scanner. Meta-hack: we built the project with a ticket-driven "Ralph loop" (scripts/ralph.sh) over a git-native ticket board (tk), where opencode implements each ticket and a separate verifier run must end with VERDICT: PASS before the ticket closes and commits.
The result is a demo where bean-check passes, balances tie out (185 TST left, 235 in sales, 50 minus fee to the bank), and privacy is preserved end to end.

