Exnode: a Bitcoin Full Node in Elixir/OTP

Note: exnode is an experimental Bitcoin full node written in Elixir/OTP. It is not production-ready.

Why write a full-node in Elixir on the BEAM?

Because a full node is also a concurrent, fault-tolerant, multi-protocol distributed system: hundreds of untrusted TCP connections, parallel block downloads, header trees, mempool verification, background indexers, RPC/REST servers, and crash recovery. OTP’s supervision trees, isolated processes, and explicit message passing fit that problem shape remarkably well.

Today, exnode sits at roughly 40,000 lines of Elixir across 113 modules plus ~1,500 lines of C across 5 small native components, pinned against Bitcoin Core v32.1 (libbitcoinkernel). Of course, mostly AI-generated, wouldn’t have done it without it. The idea of this project is simply to experiment with and validate certain architectural decisions and tests.

Here is how it is put together, the design decisions behind it, and how we try to keep ourselves honest about correctness.


1. Process Architecture: Supervision Follows Ownership

In exnode, the node is an OTP supervision tree (Exnode.Node) where restart boundaries follow state ownership and data dependencies:

Node (rest_for_one)
├─ Shadow.Monitor         optional: Core's engine in a separate OS process
├─ Headers                header tree, PoW, headers presync (anti-DoS)
├─ ScriptExec             shared native script worker pool (blocks + mempool)
├─ ChainState             single writer of the archive; chain selection & reorgs
├─ Relay (rest_for_one)   MempoolVerify, Mempool (cluster mempool), TxRelay
├─ P2P (rest_for_one)     AddrMan, SyncState, BlockDownload, HighBandwidth,
│                         BlockServing, DecodeBudget,
│                         Conns (one_for_all: PeerSup + Connman), Listener
└─ Services (one_for_one) BIP158 BlockFilter, Scripthash index, JSON-RPC, Esplora REST

Why this layout?

  • Upstream authority: Headers and ChainState sit upstream of everything else. If ChainState restarts, downstream consumers holding views of chain state restart cleanly with it (rest_for_one).
  • Scoped failure for Relay: If Mempool or TxRelay crashes, only the Relay subtree restarts. Existing P2P connections stay alive, and the new TxRelay asks peers to re-register (:tx_relay_resync).
  • Paired connection state: Inside P2P, PeerSup (one BEAM process per peer) and Connman sit under a one_for_all supervisor so Connman’s peer table never drifts from the set of live peer processes. A protocol violation from a misbehaving peer kills only that single Peer process and discourages its address.
  • Independent leaves: Indexes, JSON-RPC, and Esplora REST sit under one_for_one. A bug or overload in an index or API server does not take down P2P or chain validation.
  • Named lookup, no stale PIDs: Subsystems address each other via registered names scoped per node prefix, so multiple independent nodes can run simultaneously inside the same BEAM VM during tests.

Of course, BEAM process isolation is not magic: native NIFs share the VM’s address space. A memory bug or abort inside a NIF takes down the entire node, which directly shaped how we designed our native boundary.


2. The Life of a Block: From Wire to Disk

Getting a block from an untrusted peer into durable storage crosses eight distinct stages:

  1. Framing & Decoding (Peer): Each peer process decodes plain v1 or BIP324 encrypted v2 frames under a node-wide DecodeBudget cap (preventing memory amplification from many simultaneous huge messages). Mutated block bodies are caught before changing download ownership.
  2. Header Tree & Presync (Headers): Validates PoW, difficulty transitions, timestamps, and version rules. Low-work header chains pass through Bitcoin Core’s HeadersSyncState presync/redownload state machine first so an attacker cannot flood RAM with cheap fake headers.
  3. Download Scheduling (BlockDownload): Requests blocks along the best header chain across peers (16 blocks in flight per peer, 1024-block sliding window, global byte budget, and anti-stalling timeouts). Crucially, once a block arrives, its reservation transitions from :requested to :checking rather than disappearing—preventing other peers from re-downloading the same block while it is being validated, and protecting it from compact-block theft.
  4. Parallel Context-Free Checks (Peer → ChainState): Peers run context-free CheckBlock checks in parallel. ChainState stores accepted bodies in an ephemeral staging/ pending store and, during IBD, replies immediately so downloads never stall waiting on disk commits.
  5. Pipelined Activation & Speculative Prefetch (ChainState, Chain.Prefetch, ScriptExec): ChainState is the sole owner of canonical chain state. It drives a persistent activation plan in bounded turns: non-script contextual checks run sequentially across up to 8 provisional blocks using earlier blocks’ coin deltas, while Chain.Prefetch prepares committed prevouts ahead of time and ScriptExec dispatches script verification jobs to libbitcoinkernel on dirty CPU schedulers. Scripts from multiple blocks execute in parallel, with oldest-block priority so the retirement head never starves (and a reserved slice for mempool verification).
  6. Ordered Retirement: Only the contiguous valid prefix retires into the archive. If block N fails validation, any speculative work for blocks N+1 \dots is discarded via plan/body identity tags so stale worker results can never leak into a new branch or retry.
  7. Atomic Commit: Connected blocks accumulate in an in-memory batch (so the active tip can lead the durable tip). On commit, exnode fsyncs the append-only segment files first, then writes a single synced atomic RocksDB WriteBatch containing index updates, archive metadata/tip, and pending-body deletions.
  8. Async Followers & Shadow Cross-Check: Optional indexes (BIP158 filters, scripthash history) follow the committed chain asynchronously in their own processes. If --shadow is enabled, committed blocks and consensus rejections are cross-checked against Bitcoin Core’s full engine.

3. Core Architecture Decisions and Trade-offs

Decision 1: Elixir Owns the Node; libbitcoinkernel Executes Scripts

I did not want to reimplement Bitcoin Script’s subtle consensus quirks in Elixir initially. Instead, exnode implements networking, BIP324, header validation, chain selection, reorgs, non-script consensus rules (BIP30/34/68/113/141, merkle trees, coinbase maturity, inflation, sigops), storage, and mempool policy in Elixir, and delegates only script verification to Bitcoin Core v32.1’s libbitcoinkernel via a tiny C NIF.

Every Elixir port of a Core rule cites the exact Bitcoin Core v32.1 function it mirrors.


Decision 2: An Archive Instead of a UTXO Database

Bitcoin Core stores raw blocks (blk*.dat), undo files (rev*.dat), and a mutable UTXO set (chainstate/).

exnode takes an archive-first design (inspired by rbitcoin): it stores the chain once, decomposed into:

  • Append-only segments: monotonic IDs for blocks, outputs, inputs, and witnesses.
  • RocksDB index: transaction index (txindex), block metadata, and spend records (output_id + spending_block → input_id).

There is no separate UTXO database and no rev*.dat undo files. Whether a coin is unspent on the selected chain is a query over creation/spending block membership (plus BIP30 duplicate-txid overwrite metadata). A reorg simply removes the disconnected blocks’ spend records; the historical outputs stay intact.

To make storage practical:

  • Hot/cold split (--datadir-cold): Outputs (needed for prevout lookups) stay on fast storage; input and witness segments can live on a cheaper secondary volume.
  • Witness pruning (--prune-witness): Old witness segments can be pruned while keeping base transaction history and keeping the last 288 blocks fully servable.
  • In-memory coin overlay (--dbcache, 450 MiB default): Mirrors CCoinsViewCache, caching hot coins and masking uncommitted spends ahead of disk commits.

Why do this? Validation, P2P block serving, RPC, and optional indexes all read from one unified historical store. Indexes can be built or rebuilt strictly from the committed archive without watching live validation events.

The trade-offs: Permanent history and index growth, an always-on txindex (it’s structural, not optional), and raw block reconstruction + merkle/witness commitment verification whenever read_block serves a full block.


Decision 3: Four Explicit Milestones & Fail-Stop Storage Durability

A recurring source of subtle bugs in full nodes is conflating “I received this block” with “it’s active” or “it’s crash-safe.” exnode separates four explicit milestones:

Milestone Meaning
Stored Body written (unsynced) to staging/; eligible for activation, may still fail validation or vanish on power loss (just re-downloaded).
Active (tip) Ordered validation passed and the block joined the selected chain (may lead the durable tip inside an uncommitted batch).
Committed Append-only segments fsynced, followed by one synced atomic RocksDB batch publishing metadata, tip, and pending deletions.
Index-ready An optional derived index (e.g., scripthash) caught up to the committed target (sync: false; always rebuildable from the archive).

On disk, we physically isolate three classes of RocksDB stores:

  1. Canonical consensus state (index/): single-writer, sync: true with use_fsync, atomic_flush, paranoid_checks, and absolute_consistency WAL recovery.
  2. Ephemeral staging (staging/): pending downloads and cached headers (which re-verify their own hash on reload).
  3. Derived query stores (derived/filters/, derived/scripthash/): independent single-writer stores.

Every store is guarded by a strict flush.lock clean-close gate (Exnode.Store.Guard):

  • The lock file is created and fsynced before opening RocksDB, and deleted only after a clean, fault-free shutdown.
  • After commits (every commit near tip and on shutdown, or every --snapshot-every commits during IBD), exnode takes a quiescent RocksDB checkpoint (hard-linking immutable SSTs) and rotates snapshots/primary and snapshots/secondary via atomic renames.
  • If the node crashes (SIGKILL or power loss), it refuses to open a dirty store directly. Instead, an offline tool (mix exnode.restore / bin/exnode-restore) replaces a dirty index/ wholesale from the latest complete snapshot, truncates hot/cold segments to the snapshot’s exact committed byte offsets (ends), wipes staging/, reconciles any derived store that ended up ahead of the restored canonical tip, and clears flush.lock.
  • Any storage I/O error, checksum mismatch, or archive integrity failure permanently latches a :faulted state (an absorbing state in the guard state machine), halts the node immediately, and writes the fault record into flush.lock so the operator must intervene rather than silently corrupting state.

Decision 4: Local Failure Is Not Consensus Invalidity (Quarantine + Shadow Validator)

If a peer sends a consensus-invalid block, you mark the header invalid, invalidate descendants, and penalize the peer.

But what if CheckBlock fails due to a wire-malleated block (CVE-2012-2459)? Or what if a worker crashes, an Elixir bug raises, or the kernel API returns a local error? Marking a valid block’s header as permanently invalid over a local bug or malleated body can fork you off the network.

exnode explicitly classifies every validation outcome (Exnode.Chain.Outcome):

  • :check_block failures never invalidate headers (CVE-2012-2459 protection).
  • Local errors and crashes quarantine the block hash (persisting a crash report) without invalidating its header or punishing the peer. Once fixed, mix exnode.reconsider clears the quarantine offline.

To catch real consensus bugs in our Elixir code, exnode also ships with --shadow: a separate OS process running Bitcoin Core’s full libbitcoinkernel chainstate engine. Every connected block and consensus rejection is cross-checked against Core, with backpressure and an automatic halt on any divergence.


Decision 5: Cluster Mempool & Documented Deviations

exnode implements a cluster mempool (Exnode.Mempool.*) with package relay, RBF, sibling eviction, ancestor/descendant/cluster limits, and Bitcoin Core v32.1 ATMPArgs mode parity.

Rather than pretending to be 100% bug-for-bug identical to Core’s mempool, every intentional deviation is documented up front:

  • Mempool scripts use consensus flags only (due to the libbitcoinkernel C API).
  • Cluster linearization in exnode is always optimal, which can differ from Core’s budget-limited linearizer on pathological graphs.
  • Memory usage is estimated per entry rather than matching Core’s C++ DynamicMemoryUsage.
  • Exact bounded sets replace rolling bloom filters in several places, and AddrMan uses exnode’s own peers.dat format (preserving Core’s new/tried tables, buckets, and netgroup protections).
  • Only IPv4/IPv6 peers are dialled (Tor/I2P/CJDNS addresses are parsed and stored, not dialled).

4. Defense in Depth: Tests, Ratchets, and Formal Verification

Because a full node has a huge state space and an adversarial network boundary, we layered five different verification mechanisms.

Layer 1: Deterministic Unit, Property, and Mutation-Checked Tests

The test suite spans 166 test files with ~850 test cases, including 44 StreamData property tests covering codecs, PoW, orphanage invariants, data structures, reorg coin models, and differential consensus checks.

Two design choices make the test suite fast and deterministic:

  • Per-node mockable Exnode.Clock: Wall time and monotonic timers are explicitly injected per node. Tests run multiple nodes inside a single BEAM VM, advance one node’s clock without affecting another, and tick periodic timers synchronously—no flaky Process.sleep races.
  • Core test vectors & mutation checking: Ported test vectors from Core v32.1 (tx_valid.json/tx_invalid.json, BIP324 packet vectors, net_peer_eviction_tests.cpp, token buckets, blockfilters.json, and an invalid-block corpus). Many consensus and DoS tests were mutation-checked by deliberately breaking the rule to verify the test actually catches it.

Layer 2: Live bitcoind v32.1 Interop Suite

Sixteen dedicated :interop test modules spin up real bitcoind v32.1 instances on regtest alongside exnode to test:

  • Headers and block sync, block serving (full and NODE_NETWORK_LIMITED), compact blocks, and BIP324 v2 encrypted transport.
  • Transaction relay, mempool replay, sequence-lock equality, consensus boundary cases, and the invalid-block corpus.
  • BIP158 block filters, JSON-RPC response shapes, Esplora REST oracle comparison, and SIGKILL crash recovery.

Layer 3: Dedicated DoS Regression Suite

Under test/exnode/dos/, 21 targeted test files attempt concrete remote attacks against the node:

  • Orphan fanout and orphan reconsideration stalls
  • Message decode amplification, receive-buffer memory exhaustion, frame retention, and BEAM sub-binary retention
  • Unsolicited and low-work compact blocks, compact-block request stealing, and block stalling
  • notfound churn, TxRelay cast floods, TxRelay known-set memory growth, and invalid-witness RBF linearization freezes
  • Inbound eviction stalls, listener accept floods, and mutated block delivery

Layer 4: Static Architectural Ratchets (scripts/check_architecture.exs)

Good architecture erodes over time unless enforced mechanically. In CI, check_architecture.exs parses the AST of every file under lib/exnode/ and fails the build on any violation of:

  • Single-owner :rocksdb: Only lib/exnode/store/kv.ex may touch :rocksdb.
  • Single-owner "flush.lock": Only lib/exnode/store/guard.ex may reference "flush.lock".
  • Single-owner ETS writes: Only 6 designated owner modules may call mutating :ets functions.
  • Strict layer boundaries: Pure core (codec/, consensus/, crypto/, validation/) cannot reference P2P, Mempool, RPC, REST, Index, CLI, or Node; rpc/ and rest/ cannot bypass committed reader APIs to touch Store.KV directly.
  • Clock hygiene: Pure deterministic modules cannot call System.os_time, System.monotonic_time, or :erlang.timestamp.
  • Monotonic ratchets: Dynamic atom creation (String.to_atom, :erlang.binary_to_atom) and Process.sleep counts are pinned to a tiny allowlist that can only stay flat or decrease.

Layer 5: Formal Verification (Lean 4 + TLA+)

We split formal verification along the exact boundary between pure decision logic and concurrent state machines, and locked both to production code so they cannot silently rot:

  • Lean 4 (zero-drift table proofs): Instead of hand-copying Elixir logic into Lean, mix exnode.export_formal_tables evaluates compiled production Elixir functions (Store.Guard, Store.Snapshot, Chain.Outcome, Mempool.Accept, P2P.BlockDownload, and ChainParams) over their entire finite domains and generates formal/lean/ExnodeFormal/Generated.lean. Proofs.lean then machine-checks 20 theorems over those exact tables (absorbing fault latches, snapshot restore safety, CVE-2012-2459 header protection, quarantine non-punishment, ATMPArgs invariants, stall-decision safety, and buried softfork height monotonicity). Both ExUnit and CI fail immediately if Generated.lean drifts by a single byte from the compiled Elixir code.
  • TLA+ / TLC (concurrent state machines + bug-injection regressions): Four TLA+ specifications (StoreDurability, ChainPipeline, MempoolReorg, BlockDownloadLiveness) model crash recovery, multi-turn reorgs with Shadow.Monitor, async mempool verification races, and P2P block-download/compact-block liveness. Every spec ships with a *_Fixed.cfg (which must pass TLC) and two *_Buggy*.cfg configs that flip intentional bug-injection constants on and must fail with an invariant violation—proving our invariants are not vacuous.
  • Model sync ratchet (scripts/check_model_sync.exs): Verifies that every .tla spec’s Models: header cites real production .ex files and real def/defp function names, that both Fixed and Buggy configs exist, and that the Lean tables are in sync.

Closing Thoughts

Building exnode has been a lesson in combining the ergonomics of a high-level functional runtime with the paranoia of systems programming. OTP makes concurrency, supervision, and testing multi-node topologies a joy; C NIFs and careful BEAM memory profiling keep the hot paths sane; and layering interop tests, DoS tests, AST ratchets, a shadow validator, Lean 4, and TLA+ turns “it seems to work” into something you can actually reason about.

If you’re curious to poke around the code, start with:

  • Supervision & wiring: lib/exnode/node.ex
  • Archive & native overlay: lib/exnode/archive.ex, lib/exnode/archive/overlay.ex
  • Crash-safe guards & snapshots: lib/exnode/store/guard.ex, lib/exnode/store/snapshot.ex
  • Architectural & formal ratchets: scripts/check_architecture.exs, scripts/check_model_sync.exs, formal/lean/, formal/tla/

Also, thanks @jurraca for contributing to the project.


Note: LLM helped me to write this.

Maybe add a link to the GitHub repo at the top for convenience, I didn’t see any :slight_smile:

Woops, sorry, forgot it. Just added the link.