Nakamoto consensus -- the Bitcoin HEADER layer -- as a pure state machine on
urd.consensus.node.
Ported from btcsuite/btcd (read at Jul 2026). It is in the portfolio as a
GENERALITY TEST, not a product: it is the only algorithm here with open
membership and deep reorgs, and therefore the only remaining justification for
the core protocol's revocable :commit/:revert. See the friction notes at
the bottom of this docstring, which are the actual deliverable.
btcd draws the line for us. maybeAcceptBlockHeader (accept.go:123-236) is
a complete consensus engine over headers alone, and HeaderCtx
(interfaces.go:36-55) is a five-method interface -- Height, Bits, Timestamp,
Parent, RelativeAncestorCtx -- that IS the generic Nakamoto surface. So:
IN: heaviest-chain fork choice, cumulative work, the compact target codec, difficulty retarget, double-SHA256 proof verification, median-time-past, the future bound, reorgs. OUT: the UTXO set, scripts, coinbase maturity, merkle root CONTENTS (an opaque payload commitment here), block size/weight, BIP30/34/65/66, versionbits, the testnet min-difficulty rule, and CHECKPOINTS -- which are deliberately dropped, because a checkpoint is exactly a violation of the open membership this algorithm is here to test.
A nonce loop on the JVM is two to four orders of magnitude off an ASIC, and
worse in a browser, so nothing here ever mines competitively. btcd agrees
structurally: its CPU miner lives in mining/, not in blockchain/. mine
below is a bounded, test-only toy, step never calls it, and a real deployment
supplies solved headers from outside via vertex-received -- the same seam a
getblocktemplate client uses. template is the pure query a miner needs.
All 256-bit quantities go through urd.consensus.bignat, a portable limb
implementation, rather than through BigInteger/BigInt reader conditionals.
Fork choice compares cumulative work with a STRICT > (chain.go:1257), so
ties go to the incumbent and first-seen wins; there is no height tie-break
anywhere in Bitcoin. An approximate comparison would turn a tie into a reorg.
now is an explicit parameter of every function that needs it, never an
ambient clock. The node keeps :now in its state and advances it from a
logical :clock timer, so a run is replayable. Note that the core protocol
defines a tick EVENT for this and the simulator never delivers one -- see
the friction notes.
:revert is under-specified. [:revert {:to-vertex v}] tells an
interpreter where the committed prefix should now END, but not what was
dropped, and it presumes the interpreter can LOCATE v in a sequence it was
handed one :commit at a time. The simulator recorded reverts and never
applied them, so its agreement? check could not have detected a
reorg-induced divergence. Fixed here; the fix is what makes the deep-reorg
test mean anything.
:commit's :index cannot be both "globally increasing" and "the
position of these vertices in the committed sequence". For Raft and
Snowman those coincide. Under a reorg they do not, and only the second is
usable by a consumer that also honours :revert. We emit the position (the
block height), which contradicts the docstring.
:persist-then's barrier does nothing here, and correctly so. The rule --
gate exactly the messages that constitute this node's binding commitment --
has an empty left-hand side under proof of work: a header is
self-authenticating, a node signs nothing, and there is no equivocation to
prevent. Nakamoto is the algorithm that shows the barrier is optional.
Membership does not apply, for the second time (Snowman was the first).
There is no validator set, so no predicate over statements is meaningful;
eligibility is hash <= target, which is a property of the vertex, not of
its author. :validators survives only as a gossip peer list.
Nakamoto consensus -- the Bitcoin HEADER layer -- as a pure state machine on
`urd.consensus.node`.
Ported from `btcsuite/btcd` (read at Jul 2026). It is in the portfolio as a
GENERALITY TEST, not a product: it is the only algorithm here with open
membership and deep reorgs, and therefore the only remaining justification for
the core protocol's revocable `:commit`/`:revert`. See the friction notes at
the bottom of this docstring, which are the actual deliverable.
## Scope
btcd draws the line for us. `maybeAcceptBlockHeader` (`accept.go:123-236`) is
a complete consensus engine over headers alone, and `HeaderCtx`
(`interfaces.go:36-55`) is a five-method interface -- Height, Bits, Timestamp,
Parent, RelativeAncestorCtx -- that IS the generic Nakamoto surface. So:
IN: heaviest-chain fork choice, cumulative work, the compact target codec,
difficulty retarget, double-SHA256 proof verification, median-time-past,
the future bound, reorgs.
OUT: the UTXO set, scripts, coinbase maturity, merkle root CONTENTS (an
opaque payload commitment here), block size/weight, BIP30/34/65/66,
versionbits, the testnet min-difficulty rule, and CHECKPOINTS -- which
are deliberately dropped, because a checkpoint is exactly a violation
of the open membership this algorithm is here to test.
## Mining is not in the state machine
A nonce loop on the JVM is two to four orders of magnitude off an ASIC, and
worse in a browser, so nothing here ever mines competitively. btcd agrees
structurally: its CPU miner lives in `mining/`, not in `blockchain/`. `mine`
below is a bounded, test-only toy, `step` never calls it, and a real deployment
supplies solved headers from outside via `vertex-received` -- the same seam a
`getblocktemplate` client uses. `template` is the pure query a miner needs.
## Arithmetic
All 256-bit quantities go through `urd.consensus.bignat`, a portable limb
implementation, rather than through BigInteger/BigInt reader conditionals.
Fork choice compares cumulative work with a STRICT `>` (`chain.go:1257`), so
ties go to the incumbent and first-seen wins; there is no height tie-break
anywhere in Bitcoin. An approximate comparison would turn a tie into a reorg.
## Time
`now` is an explicit parameter of every function that needs it, never an
ambient clock. The node keeps `:now` in its state and advances it from a
logical `:clock` timer, so a run is replayable. Note that the core protocol
defines a `tick` EVENT for this and the simulator never delivers one -- see
the friction notes.
## What this cost the core protocol
1. `:revert` is under-specified. `[:revert {:to-vertex v}]` tells an
interpreter where the committed prefix should now END, but not what was
dropped, and it presumes the interpreter can LOCATE v in a sequence it was
handed one `:commit` at a time. The simulator recorded reverts and never
applied them, so its `agreement?` check could not have detected a
reorg-induced divergence. Fixed here; the fix is what makes the deep-reorg
test mean anything.
2. `:commit`'s `:index` cannot be both "globally increasing" and "the
position of these vertices in the committed sequence". For Raft and
Snowman those coincide. Under a reorg they do not, and only the second is
usable by a consumer that also honours `:revert`. We emit the position (the
block height), which contradicts the docstring.
3. `:persist-then`'s barrier does nothing here, and correctly so. The rule --
gate exactly the messages that constitute this node's binding commitment --
has an empty left-hand side under proof of work: a header is
self-authenticating, a node signs nothing, and there is no equivocation to
prevent. Nakamoto is the algorithm that shows the barrier is optional.
4. `Membership` does not apply, for the second time (Snowman was the first).
There is no validator set, so no predicate over statements is meaningful;
eligibility is `hash <= target`, which is a property of the vertex, not of
its author. `:validators` survives only as a gossip peer list.(ancestor-at-height state id h)The ancestor of id at absolute height h, or nil.
The ancestor of `id` at absolute height `h`, or nil.
(calc-work bits)floor(2^256 / (target + 1)) -- workmath/difficulty.go:135-149.
The inverse of the target, because a LOWER target is harder. The +1 in the denominator avoids a division by zero at target 0 and makes the value fit; the 2^256 numerator keeps it an integer.
floor(2^256 / (target + 1)) -- `workmath/difficulty.go:135-149`. The inverse of the target, because a LOWER target is harder. The +1 in the denominator avoids a division by zero at target 0 and makes the value fit; the 2^256 numerator keeps it an integer.
(check-header-context p state header parent-id)Checks that depend on the header's position -- CheckBlockHeaderContext
(validate.go:744-800), minus the version-bit and checkpoint rules.
The timestamp must be STRICTLY after the median time past of the parent;
!header.Timestamp.After(medianTime) rejects equality.
Checks that depend on the header's position -- `CheckBlockHeaderContext` (`validate.go:744-800`), minus the version-bit and checkpoint rules. The timestamp must be STRICTLY after the median time past of the parent; `!header.Timestamp.After(medianTime)` rejects equality.
(check-header-sanity p header now)Context-free checks -- CheckBlockHeaderSanity (validate.go:495-530).
now is a parameter, not a clock read. btcd consults a MedianTimeSource
here, an adjusted network time; we take the caller's word, which is the same
thing with the adjustment moved outside the state machine.
Context-free checks -- `CheckBlockHeaderSanity` (`validate.go:495-530`). `now` is a parameter, not a clock read. btcd consults a `MedianTimeSource` here, an adjusted network time; we take the caller's word, which is the same thing with the adjustment moved outside the state machine.
(compact->target c)The magnitude of a compact target, as a bignat. Callers must check
compact-negative? separately -- see target-valid?.
The magnitude of a compact target, as a bignat. Callers must check `compact-negative?` separately -- see `target-valid?`.
(compact-negative? c)Bit 23. Bitcoin never needs a negative target, but bitcoind encodes the sign bit anyway, so a header can claim one and must be rejected for it.
Bit 23. Bitcoin never needs a negative target, but bitcoind encodes the sign bit anyway, so a header can claim one and must be rejected for it.
(create)Create a Nakamoto node. Config: {:genesis header :params {...} :seconds-per-tick n :clock-ticks n}.
Create a Nakamoto node. Config: {:genesis header :params {...}
:seconds-per-tick n :clock-ticks n}.Headers accepted between rewrites of the durable log.
Nakamoto writes one record per header and restore replays every one of
them, so a node that has been following the chain for a year pays a year of
reads to start. This collapses them: one record standing in for all the
headers before it.
What this does NOT do is bound MEMORY. The header index still holds every block ever seen, and that is deliberate rather than unfinished -- dropping old headers caps how deep a reorg can be validated, which is a consensus policy and not a storage optimisation. Bitcoin keeps all headers forever for exactly this reason; they are 80 bytes and the alternative is a chain that silently refuses a reorganisation it cannot check. The decision belongs to whoever is choosing the finality depth, so it is not made here.
Headers accepted between rewrites of the durable log. Nakamoto writes one record per header and `restore` replays every one of them, so a node that has been following the chain for a year pays a year of reads to start. This collapses them: one record standing in for all the headers before it. What this does NOT do is bound MEMORY. The header index still holds every block ever seen, and that is deliberate rather than unfinished -- dropping old headers caps how deep a reorg can be validated, which is a consensus policy and not a storage optimisation. Bitcoin keeps all headers forever for exactly this reason; they are 80 bytes and the alternative is a chain that silently refuses a reorganisation it cannot check. The decision belongs to whoever is choosing the finality depth, so it is not made here.
(find-fork state a b)The last common ancestor of two blocks -- chainview.go:292-322.
Walk the deeper one up to the shallower one's height first, then step both up in lockstep. Returns nil if they are not in the same tree.
The last common ancestor of two blocks -- `chainview.go:292-322`. Walk the deeper one up to the shallower one's height first, then step both up in lockstep. Returns nil if they are not in the same tree.
(header-id header)The block id: SHA256d of the 80 bytes, reversed into display order.
The block id: SHA256d of the 80 bytes, reversed into display order.
Bitcoin mainnet, minus everything out of scope.
:pow-limit-bits 0x1d00ffff is mainnet's; tests use a far easier limit,
because at this one a single block costs about 2^32 hashes.
Bitcoin mainnet, minus everything out of scope. `:pow-limit-bits` 0x1d00ffff is mainnet's; tests use a far easier limit, because at this one a single block costs about 2^32 hashes.
(median-time-past p state id)The median of the last median-time-blocks timestamps INCLUDING this block.
btcd takes timestamps[n/2] after sorting -- integer division, deliberately
not the average of the middle two when n is even. The constant is 11, so n is
even only in the first ten blocks of a chain, but the rule is consensus and is
reproduced exactly. The result is therefore always an ELEMENT of its input.
The median of the last `median-time-blocks` timestamps INCLUDING this block. btcd takes `timestamps[n/2]` after sorting -- integer division, deliberately not the average of the middle two when n is even. The constant is 11, so n is even only in the first ten blocks of a chain, but the rule is consensus and is reproduced exactly. The result is therefore always an ELEMENT of its input.
(mine header max-tries)(mine header start max-tries)TEST-ONLY toy miner: try max-tries nonces from start.
Deliberately bounded and deliberately not called from step. Never mine for
real with this -- a JVM nonce loop is orders of magnitude off an ASIC, and
worse in a browser. Tests configure an easy :pow-limit-bits so a solution
costs a handful of hashes.
TEST-ONLY toy miner: try `max-tries` nonces from `start`. Deliberately bounded and deliberately not called from `step`. Never mine for real with this -- a JVM nonce loop is orders of magnitude off an ASIC, and worse in a browser. Tests configure an easy `:pow-limit-bits` so a solution costs a handful of hashes.
(next-work-required p state last-id)The bits the child of last-id must carry -- calcNextRequiredDifficulty.
The famous off-by-one is in first: btcd asks for the ancestor
blocksPerRetarget - 1 back, so the span runs over 2015 inter-block
intervals but is divided by a target timespan computed for 2016. Mainnet
therefore aims at 600.2977 seconds per block rather than 600. It is
reproduced, not fixed: it is consensus.
The testnet min-difficulty reduction is deliberately absent -- out of scope.
The `bits` the child of `last-id` must carry -- `calcNextRequiredDifficulty`. The famous off-by-one is in `first`: btcd asks for the ancestor `blocksPerRetarget - 1` back, so the span runs over 2015 inter-block intervals but is divided by a target timespan computed for 2016. Mainnet therefore aims at 600.2977 seconds per block rather than 600. It is reproduced, not fixed: it is consensus. The testnet min-difficulty reduction is deliberately absent -- out of scope.
(params overrides)Merge overrides onto the mainnet rules and derive the clamp bounds.
btcd derives these once in New (chain.go:2250-2263) rather than at each
retarget, and so do we -- the min/max timespan are the same three constants
every time.
Merge overrides onto the mainnet rules and derive the clamp bounds. btcd derives these once in `New` (`chain.go:2250-2263`) rather than at each retarget, and so do we -- the min/max timespan are the same three constants every time.
(path-from state from to)The blocks strictly after from up to and including to, in order.
This is getReorganizeNodes's attach list (chain.go:512-558), and it serves
as the DETACH list too -- reorg-effects calls it a second time from the fork
point to the old tip. What ours needs no counterpart for is btcd's undo DATA:
every consensus quantity here is a fold over the ancestor path, so a detached
block leaves nothing to roll back. The detached blocks still have to be NAMED,
because :revert carries :dropped and the interpreter checks it -- see the
note on reorg-effects.
ASCENDING, which is the inverse of btcd's descending detachNodes. btcd walks
down because it undoes one block at a time; here the list is compared against
the interpreter's committed vector, which is ascending.
The blocks strictly after `from` up to and including `to`, in order. This is `getReorganizeNodes`'s attach list (`chain.go:512-558`), and it serves as the DETACH list too -- `reorg-effects` calls it a second time from the fork point to the old tip. What ours needs no counterpart for is btcd's undo DATA: every consensus quantity here is a fold over the ancestor path, so a detached block leaves nothing to roll back. The detached blocks still have to be NAMED, because `:revert` carries `:dropped` and the interpreter checks it -- see the note on `reorg-effects`. ASCENDING, which is the inverse of btcd's descending `detachNodes`. btcd walks down because it undoes one block at a time; here the list is compared against the interpreter's committed vector, which is ascending.
(pow-valid? header)Does the header's own hash meet the target it claims?
Note > and not >= in btcd's rejection (validate.go:394): a hash exactly
EQUAL to the target passes.
Does the header's own hash meet the target it claims? Note `>` and not `>=` in btcd's rejection (`validate.go:394`): a hash exactly EQUAL to the target passes.
(process-header state header from)The whole acceptance path -- ProcessBlockHeader / maybeAcceptBlockHeader.
Returns {:state s :effects fx}. An orphan (parent unknown) is parked and its
parent requested; btcd's equivalent lives one layer up, in ProcessBlock.
The whole acceptance path -- `ProcessBlockHeader` / `maybeAcceptBlockHeader`.
Returns {:state s :effects fx}. An orphan (parent unknown) is parked and its
parent requested; btcd's equivalent lives one layer up, in `ProcessBlock`.(relative-ancestor state id distance)HeaderCtx.RelativeAncestorCtx: the ancestor distance blocks back.
`HeaderCtx.RelativeAncestorCtx`: the ancestor `distance` blocks back.
(retarget p old-bits first-time last-time)The pure retarget arithmetic, given the two boundary timestamps.
Separated from chain walking so it can be property-tested directly: the result is always within [old/4, old*4] and never easier than the pow limit.
The pure retarget arithmetic, given the two boundary timestamps. Separated from chain walking so it can be property-tested directly: the result is always within [old/4, old*4] and never easier than the pow limit.
(serialize-header {:keys [version prev merkle-root time bits nonce]})The canonical 80 bytes -- wire/blockheader.go:183-215.
version LE32 | prev 32 | merkle-root 32 | time LE32 | bits LE32 | nonce LE32.
Hash-valued fields are carried here as DISPLAY hex, i.e. the reversed form
everyone quotes block ids in, so they are reversed back to internal order on
the way out. That is the same convention btcd's chainhash.Hash.String uses.
The canonical 80 bytes -- `wire/blockheader.go:183-215`. version LE32 | prev 32 | merkle-root 32 | time LE32 | bits LE32 | nonce LE32. Hash-valued fields are carried here as DISPLAY hex, i.e. the reversed form everyone quotes block ids in, so they are reversed back to internal order on the way out. That is the same convention btcd's `chainhash.Hash.String` uses.
(target->compact n)A bignat back to compact form.
The renormalisation at the end is the subtle part: if the mantissa's high bit would land on the sign bit, the number is divided by 256 and the exponent incremented, so 0x01ff0000 (255) encodes as 0x0200ff00 rather than 0x01ff0000.
A bignat back to compact form. The renormalisation at the end is the subtle part: if the mantissa's high bit would land on the sign bit, the number is divided by 256 and the exponent incremented, so 0x01ff0000 (255) encodes as 0x0200ff00 rather than 0x01ff0000.
(target-valid? p bits)The target must be positive and no easier than the chain's limit
(validate.go:372-388).
The target must be positive and no easier than the chain's limit (`validate.go:372-388`).
(template state {:keys [merkle-root time version on]})The header a miner should try to solve on top of the current tip.
A pure query, not an effect: the consensus engine does not mine, it only says
what a valid next header would look like. :time is raised to one second past
the median time past when the clock is behind it, which is what keeps a chain
with a bad timestamp from stalling.
:on names the block to build on, defaulting to the tip. A miner would never
pass it, but building a competing branch from well back in a test is exactly
the deep-reorg case, and it needs no privileged access to do it.
The header a miner should try to solve on top of the current tip. A pure query, not an effect: the consensus engine does not mine, it only says what a valid next header would look like. `:time` is raised to one second past the median time past when the clock is behind it, which is what keeps a chain with a bad timestamp from stalling. `:on` names the block to build on, defaulting to the tip. A miner would never pass it, but building a competing branch from well back in a test is exactly the deep-reorg case, and it needs no privileged access to do it.
(well-formed? header)Are the six header fields of the right shape?
Open membership means anyone may send anything, so this is checked BEFORE the
header is hashed -- serializing a field that is not a uint32, or a parent hash
that is not 64 hex characters, would throw inside the pure state machine and
take the node down. btcd gets this for free from Go's static types and the
wire decoder; we have to do it explicitly, and it belongs at the very front
because everything downstream, header-id included, presumes it.
Are the six header fields of the right shape? Open membership means anyone may send anything, so this is checked BEFORE the header is hashed -- serializing a field that is not a uint32, or a parent hash that is not 64 hex characters, would throw inside the pure state machine and take the node down. btcd gets this for free from Go's static types and the wire decoder; we have to do it explicitly, and it belongs at the very front because everything downstream, `header-id` included, presumes it.
cljdoc builds & hosts documentation for Clojure/Script libraries
| Ctrl+k | Jump to recent docs |
| ← | Move to previous article |
| → | Move to next article |
| Ctrl+/ | Jump to the search field |