Narwhal + Bullshark: a certified DAG mempool with a zero-message ordering layer, on urd's core protocol.
Ported from MystenLabs/narwhal at e67f915 (read Aug 2026). The repo was
archived in 2022 when the work moved into sui, so where the code and the
papers disagree the papers win -- Narwhal/Tusk arXiv:2105.11827, Bullshark
arXiv:2201.05677, and the partially synchronous variant at
sonnino.com/papers/bullshark-simple.pdf. One such disagreement is load-bearing
and is documented at order-anchors below.
This is the PARTIALLY SYNCHRONOUS Bullshark (2 rounds per wave), not Tusk. The distinction is the reason it is in the portfolio: Tusk needs a threshold common coin, and Bullshark-PS does not, so this algorithm adds no new cryptography at all. Where Narwhal aggregates BLS12-381 signatures into one certificate signature plus a roaring bitmap of committee indices, we carry one attestation per signer -- 2f+1 x 64 bytes on the wire rather than 96 plus a bitmap. That is the entire cost of the substitution.
This paragraph used to claim that the state machine's predicate was
unchanged, because what it checks is that the SET of signers is decisive,
never the bytes. That sentence was the bug. A certificate is a THIRD PARTY's
aggregated claim and it is relayed: the peer handing it to us is almost never
a signer, so transport authentication says nothing about the signers and the
names alone are worth nothing. certified? verifies each attestation and
counts stake only over those that verify; init refuses to start without a
verifier, because a permissive default is how the missing check went
unnoticed through an entire audit round.
Narwhal builds a certified DAG. A vertex is a CERTIFICATE: a header
(author, round, payload, parents) plus signatures from >= 2f+1 stake. The
2f+1 is what makes the DAG safe rather than merely shaped like a DAG. At
most one certificate per (author, round) can be certified, so equivocation
cannot survive certification; and >= f+1 signers are honest, so the payload
is retrievable. A round r+1 header must name >= 2f+1 stake of certificates
from EXACTLY round r as parents (primary/src/core.rs:229-245 -- note this
check is in the Core, not in Header::verify, and it is the invariant the
whole ordering layer silently assumes).
Bullshark orders it. commit-sequence is a pure function of the DAG
and emits NOTHING. Every honest node runs it on its own copy and gets the
identical total order. This is the first algorithm in urd's portfolio whose
decision layer sends no messages, and the first that commits a multi-vertex
sequence retroactively.
Anchors exist only at EVEN rounds (bullshark.rs:49-52). The anchor of
round r is anchor-fn(r, validators, stake) -- a deterministic function of
the round alone, evaluated identically by everyone.
Commit rule: sum the stake of round-(r+1) certificates whose parents
include the anchor; commit iff >= f+1 (bullshark.rs:66-82). Only f+1 is
needed, and that is the elegant part: the 2f+1 intersection argument was
already discharged at DAG-construction time, so the ordering layer gets to
be cheap.
Retroactive back-fill (utils.rs:11-40): from the newly committed
anchor, walk backwards by 2 to the last committed round, including each
earlier anchor iff it is REACHABLE from the newer one. One certificate can
therefore commit an anchor plus several earlier anchors and all of their
sub-DAGs at once.
Deterministic flatten (utils.rs:58-100): pre-order DFS from each
anchor over parents, skipping vertices already queued or already committed
for that author, then a stable sort by round.
Arrival-order independence comes from the DFS, not from the sort's
stability. The DFS visits parents through (sort (cert-parents x)), so its
output sequence is already a function of the DAG alone and cannot see the
order certificates were inserted in. Stability then fixes the WITHIN-ROUND
order to that DFS sequence rather than to an arbitrary permutation of it.
Both matter; only the first is what makes two nodes agree. narwhal's own
comment is blunter: ordering the output by round is not really necessary,
it just makes the commit sequence prettier (utils.rs:96).
GC drops rounds more than gc-depth below the last committed round, and
each author's certificates below its own last committed round.
already-queued dedups within one flatten;The bootstrap case falls out of (2): last-committed starts at 0 for EVERY
validator, and genesis certificates are at round 0, so the DFS stops there and
genesis is never emitted. Miss that seeding and the very first commit contains
n phantom vertices -- and, worse, agrees with itself across nodes, so nothing
catches it.
The DFS pushes parents in sorted digest order and the stable sort by round
preserves DFS discovery order WITHIN a round, so the digest comparator decides
the total order. hasch/uuid gives content-addressed identity on both
platforms, but a raw UUID must never be compared: the JVM's UUID/compareTo
compares the two 64-bit halves as SIGNED longs, while ClojureScript's UUID
compares the printed string. Those orders differ for any pair whose high bit
differs -- half of all pairs -- so a JVM node and a browser node would produce
different total orders from the identical DAG, silently. Digests are therefore
STRINGS everywhere. Pinned in portability-test.
Opaque to consensus, and supplied through request-value. The intended
payload is the map of snapshot ids datahike already hands to
coordinated-commit!; Narwhal's own is {batch-digest -> worker-id}, which
is the same shape. See the PR for why the certificate DAG is a urd-owned
structure rather than a yggdrasil one.
Narwhal + Bullshark: a certified DAG mempool with a zero-message ordering
layer, on urd's core protocol.
Ported from MystenLabs/narwhal at `e67f915` (read Aug 2026). The repo was
archived in 2022 when the work moved into sui, so where the code and the
papers disagree the papers win -- Narwhal/Tusk arXiv:2105.11827, Bullshark
arXiv:2201.05677, and the partially synchronous variant at
sonnino.com/papers/bullshark-simple.pdf. One such disagreement is load-bearing
and is documented at `order-anchors` below.
This is the PARTIALLY SYNCHRONOUS Bullshark (2 rounds per wave), not Tusk.
The distinction is the reason it is in the portfolio: Tusk needs a threshold
common coin, and Bullshark-PS does not, so this algorithm adds **no new
cryptography at all**. Where Narwhal aggregates BLS12-381 signatures into one
certificate signature plus a roaring bitmap of committee indices, we carry one
attestation per signer -- 2f+1 x 64 bytes on the wire rather than 96 plus a
bitmap. That is the entire cost of the substitution.
This paragraph used to claim that the state machine's predicate was
unchanged, because what it checks is that the SET of signers is decisive,
never the bytes. That sentence was the bug. A certificate is a THIRD PARTY's
aggregated claim and it is relayed: the peer handing it to us is almost never
a signer, so transport authentication says nothing about the signers and the
names alone are worth nothing. `certified?` verifies each attestation and
counts stake only over those that verify; `init` refuses to start without a
verifier, because a permissive default is how the missing check went
unnoticed through an entire audit round.
## Two layers, and only one of them talks
1. **Narwhal** builds a certified DAG. A vertex is a CERTIFICATE: a header
(author, round, payload, parents) plus signatures from >= 2f+1 stake. The
2f+1 is what makes the DAG safe rather than merely shaped like a DAG. At
most one certificate per (author, round) can be certified, so equivocation
cannot survive certification; and >= f+1 signers are honest, so the payload
is retrievable. A round r+1 header must name >= 2f+1 stake of certificates
from EXACTLY round r as parents (`primary/src/core.rs:229-245` -- note this
check is in the Core, not in `Header::verify`, and it is the invariant the
whole ordering layer silently assumes).
2. **Bullshark** orders it. `commit-sequence` is a pure function of the DAG
and emits NOTHING. Every honest node runs it on its own copy and gets the
identical total order. This is the first algorithm in urd's portfolio whose
decision layer sends no messages, and the first that commits a multi-vertex
sequence retroactively.
## The ordering rule, exactly
- Anchors exist only at EVEN rounds (`bullshark.rs:49-52`). The anchor of
round r is `anchor-fn(r, validators, stake)` -- a deterministic function of
the round alone, evaluated identically by everyone.
- **Commit rule**: sum the stake of round-(r+1) certificates whose parents
include the anchor; commit iff `>= f+1` (`bullshark.rs:66-82`). Only f+1 is
needed, and that is the elegant part: the 2f+1 intersection argument was
already discharged at DAG-construction time, so the ordering layer gets to
be cheap.
- **Retroactive back-fill** (`utils.rs:11-40`): from the newly committed
anchor, walk backwards by 2 to the last committed round, including each
earlier anchor iff it is REACHABLE from the newer one. One certificate can
therefore commit an anchor plus several earlier anchors and all of their
sub-DAGs at once.
- **Deterministic flatten** (`utils.rs:58-100`): pre-order DFS from each
anchor over parents, skipping vertices already queued or already committed
for that author, then a stable sort by round.
Arrival-order independence comes from the DFS, not from the sort's
stability. The DFS visits parents through `(sort (cert-parents x))`, so its
output sequence is already a function of the DAG alone and cannot see the
order certificates were inserted in. Stability then fixes the WITHIN-ROUND
order to that DFS sequence rather than to an arbitrary permutation of it.
Both matter; only the first is what makes two nodes agree. narwhal's own
comment is blunter: ordering the output by round is not really necessary,
it just makes the commit sequence prettier (`utils.rs:96`).
- GC drops rounds more than `gc-depth` below the last committed round, and
each author's certificates below its own last committed round.
## Three mechanisms stop the DFS, and all three are needed
1. `already-queued` dedups within one flatten;
2. each author's committed watermark stops the walk at or below it;
3. GC and live insertion keep certificates below that watermark out of the DAG.
The bootstrap case falls out of (2): `last-committed` starts at 0 for EVERY
validator, and genesis certificates are at round 0, so the DFS stops there and
genesis is never emitted. Miss that seeding and the very first commit contains
n phantom vertices -- and, worse, agrees with itself across nodes, so nothing
catches it.
## Portability: why digests are strings
The DFS pushes parents in sorted digest order and the stable sort by round
preserves DFS discovery order WITHIN a round, so the digest comparator decides
the total order. `hasch/uuid` gives content-addressed identity on both
platforms, but a raw UUID must never be compared: the JVM's `UUID/compareTo`
compares the two 64-bit halves as SIGNED longs, while ClojureScript's `UUID`
compares the printed string. Those orders differ for any pair whose high bit
differs -- half of all pairs -- so a JVM node and a browser node would produce
different total orders from the identical DAG, silently. Digests are therefore
STRINGS everywhere. Pinned in `portability-test`.
## Payload
Opaque to consensus, and supplied through `request-value`. The intended
payload is the map of snapshot ids datahike already hands to
`coordinated-commit!`; Narwhal's own is `{batch-digest -> worker-id}`, which
is the same shape. See the PR for why the certificate DAG is a urd-owned
structure rather than a yggdrasil one.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.Raft as a pure state machine on urd.consensus.node.
Ported from etcd-io/raft (read at Aug 2026). Scope: leader election with
PreVote, log replication with per-peer progress, durable hard state and log
entries, log truncation on a conflicting suffix, and membership changes
including joint consensus. Out of scope: snapshots, leadership transfer,
read-index/lease reads, CheckQuorum, and inflight-based flow control.
raft.go:546 routes exactly {MsgAppResp, MsgVoteResp, MsgPreVoteResp} into
msgsAfterAppend; everything else is sent immediately. Those three are the
node's binding commitments: acknowledging an append or publishing a vote is a
promise that survives a restart. Here they go into :then of a persist-then
and everything else is a bare :send.
durable? follows MustSync (rawnode.go:191-198): fsync iff entries are
non-empty, or the vote changed, or the term changed. A commit-index change
alone is recoverable by replay, so it is a buffered write.
etcd-raft models the leader's own durability as a MsgAppResp from itself to
itself, delayed by the fsync (raft.go:845), and the candidate's self-vote as
a MsgVoteResp from itself to itself (raft.go:1059). That removes the
leader/follower asymmetry from commit advancement: the leader's own entry
counts toward the quorum only once durable, exactly like everyone else's.
We keep the semantics but not the mechanism. urd has no effect for
"deliver this event to myself", and routing a self-addressed message through
[:send ...] would send it over the simulated network, where it can be
delayed, duplicated, or dropped -- a self-ack that the drop-rate can lose is a
liveness bug. Instead the node associates each local append acknowledgement and self-vote
with the write that carries it, then consumes it on persisted. The
ordering guarantee is identical (the ack lands after the write is durable,
before the gated messages go out), and it stays inside the state machine.
rawnode.go:266-363 explains it at length: a persist completion must be
dropped if the term changed while it was in flight, or a stale completion
marks entries durable that a newer append has since overwritten. urd's
persist-then carries :epoch and the persisted event echoes it, so we set
:epoch to the term at issue time and treat a mismatch as a no-op.
Completions are correlated by a CALLER-SUPPLIED token: we mint one per write,
key :pending-writes by it, and match on the way back.
This was originally a FIFO queue, popped from the front, on the assumption
that interpreters complete writes in issue order. urd's own simulator does
not: a non-durable write completes at the current tick while a durable one
completes persist-latency ticks later (sim.cljc:178), so a LATER buffered
write routinely lands before an EARLIER fsync. And because an outstanding
self-ack forces a write on every subsequent step, that reordering was the
default path rather than a rare race -- the leader counted its own entry as
durable while the entry was still in flight, which is the exact loss this
barrier exists to prevent.
log.go:109-131 (maybeAppend) plus log_unstable.go:191-213
(truncateAndAppend). etcd-raft leaves the truncation implicit -- storage has
to infer it from an append at a lower index. We set :truncate-from on the
persist-then instead. Note that a conflict at or below the commit index is a
Raft invariant violation; etcd-raft panics, and so do we.
Everything here is .cljc with no host interop except one character-code
helper. Time is logical (set-timer, in ticks) and the randomized election
timeout is derived from a portable hash of (peer-id, term) rather than from a
host PRNG -- urd has no effect that yields a random number, only one that
yields random peers.
Raft as a pure state machine on `urd.consensus.node`.
Ported from `etcd-io/raft` (read at Aug 2026). Scope: leader election with
PreVote, log replication with per-peer progress, durable hard state and log
entries, log truncation on a conflicting suffix, and membership changes
including joint consensus. Out of scope: snapshots, leadership transfer,
read-index/lease reads, CheckQuorum, and inflight-based flow control.
## The durability barrier
`raft.go:546` routes exactly {MsgAppResp, MsgVoteResp, MsgPreVoteResp} into
`msgsAfterAppend`; everything else is sent immediately. Those three are the
node's binding commitments: acknowledging an append or publishing a vote is a
promise that survives a restart. Here they go into `:then` of a `persist-then`
and everything else is a bare `:send`.
`durable?` follows `MustSync` (`rawnode.go:191-198`): fsync iff entries are
non-empty, or the vote changed, or the term changed. A commit-index change
alone is recoverable by replay, so it is a buffered write.
## The self-addressed message, and why we do not use one
etcd-raft models the leader's own durability as a `MsgAppResp` from itself to
itself, delayed by the fsync (`raft.go:845`), and the candidate's self-vote as
a `MsgVoteResp` from itself to itself (`raft.go:1059`). That removes the
leader/follower asymmetry from commit advancement: the leader's own entry
counts toward the quorum only once durable, exactly like everyone else's.
We keep the *semantics* but not the mechanism. urd has no effect for
"deliver this event to myself", and routing a self-addressed message through
`[:send ...]` would send it over the simulated network, where it can be
delayed, duplicated, or dropped -- a self-ack that the drop-rate can lose is a
liveness bug. Instead the node associates each local append acknowledgement and self-vote
with the write that carries it, then consumes it on `persisted`. The
ordering guarantee is identical (the ack lands after the write is durable,
before the gated messages go out), and it stays inside the state machine.
## The ABA hazard
`rawnode.go:266-363` explains it at length: a persist completion must be
dropped if the term changed while it was in flight, or a stale completion
marks entries durable that a newer append has since overwritten. urd's
`persist-then` carries `:epoch` and the `persisted` event echoes it, so we set
`:epoch` to the term at issue time and treat a mismatch as a no-op.
Completions are correlated by a CALLER-SUPPLIED token: we mint one per write,
key `:pending-writes` by it, and match on the way back.
This was originally a FIFO queue, popped from the front, on the assumption
that interpreters complete writes in issue order. urd's own simulator does
not: a non-durable write completes at the current tick while a durable one
completes `persist-latency` ticks later (`sim.cljc:178`), so a LATER buffered
write routinely lands before an EARLIER fsync. And because an outstanding
self-ack forces a write on every subsequent step, that reordering was the
default path rather than a rare race -- the leader counted its own entry as
durable while the entry was still in flight, which is the exact loss this
barrier exists to prevent.
## Truncation
`log.go:109-131` (`maybeAppend`) plus `log_unstable.go:191-213`
(`truncateAndAppend`). etcd-raft leaves the truncation implicit -- storage has
to infer it from an append at a lower index. We set `:truncate-from` on the
`persist-then` instead. Note that a conflict at or below the commit index is a
Raft invariant violation; etcd-raft panics, and so do we.
## Portability
Everything here is `.cljc` with no host interop except one character-code
helper. Time is logical (`set-timer`, in ticks) and the randomized election
timeout is derived from a portable hash of (peer-id, term) rather than from a
host PRNG -- urd has no effect that yields a random *number*, only one that
yields random *peers*.Round-robin consensus: a rotating single proposer with majority voting, on urd's core protocol.
The simplest thing that is still consensus, and it is in the portfolio for two reasons. It is the reference the datahike writer path was first built against, and it is the CRASH-fault-tolerant corner: fixed proposer per height, no locking, no equivocation handling.
Proposer selection rotates by HEIGHT, not by round:
height 0 -> validator 0 proposes height 1 -> validator 1 ...
Each height: the proposer broadcasts, validators vote if the proposal is valid, a majority finalizes, and a timeout retransmits the outstanding request.
ConsensusAlgorithm protocolThis used to sit on urd.consensus.state-machine, an earlier version of
node -- same idea, its docstring even says so: transitions are pure
functions from (state, event) to state plus effects. Two protocols for one
concept is one too many, so this moved and state-machine went.
Four things changed in the move, and each was a defect rather than a translation:
The transitions were not pure. handle-proposal-received and
handle-proposal-ready called println -- I/O inside step, which rule 1
of the core protocol forbids, and which is why the legacy runtime's test
output was full of interleaved debug lines from concurrent validators.
Those are log effects now, which is what the effect exists for.
Timeouts were in MILLISECONDS. The legacy runtime interpreted
set-timer with :duration-ms against a wall clock. Logical ticks are
what make a failing schedule reproducible, and half the repository did not
have them; the flakiness of the legacy tests under load traces to exactly
this.
:add-own-vote was an effect, so a node's own vote was written to a log
by the runtime rather than held in the node's own state. The algorithm now
records it directly, which is both simpler and the only version that can
be reasoned about locally -- a vote that lives outside the state machine is
a vote the state machine cannot count.
The effect vocabulary was this algorithm's, generalised by accident.
request-missing-proposal, request-state-sync, request-votes,
broadcast-finalization and trigger-next-round were all interpreted by a
runtime that called itself generic. They are ordinary messages and a timer,
and they are spelled that way now.
Round-robin consensus: a rotating single proposer with majority voting, on urd's core protocol. The simplest thing that is still consensus, and it is in the portfolio for two reasons. It is the reference the datahike writer path was first built against, and it is the CRASH-fault-tolerant corner: fixed proposer per height, no locking, no equivocation handling. Proposer selection rotates by HEIGHT, not by round: height 0 -> validator 0 proposes height 1 -> validator 1 ... Each height: the proposer broadcasts, validators vote if the proposal is valid, a majority finalizes, and a timeout retransmits the outstanding request. ## Ported from the legacy `ConsensusAlgorithm` protocol This used to sit on `urd.consensus.state-machine`, an earlier version of `node` -- same idea, its docstring even says so: transitions are pure functions from (state, event) to state plus effects. Two protocols for one concept is one too many, so this moved and `state-machine` went. Four things changed in the move, and each was a defect rather than a translation: 1. **The transitions were not pure.** `handle-proposal-received` and `handle-proposal-ready` called `println` -- I/O inside `step`, which rule 1 of the core protocol forbids, and which is why the legacy runtime's test output was full of interleaved debug lines from concurrent validators. Those are `log` effects now, which is what the effect exists for. 2. **Timeouts were in MILLISECONDS.** The legacy runtime interpreted `set-timer` with `:duration-ms` against a wall clock. Logical ticks are what make a failing schedule reproducible, and half the repository did not have them; the flakiness of the legacy tests under load traces to exactly this. 3. **`:add-own-vote` was an effect**, so a node's own vote was written to a log by the runtime rather than held in the node's own state. The algorithm now records it directly, which is both simpler and the only version that can be reasoned about locally -- a vote that lives outside the state machine is a vote the state machine cannot count. 4. **The effect vocabulary was this algorithm's, generalised by accident.** `request-missing-proposal`, `request-state-sync`, `request-votes`, `broadcast-finalization` and `trigger-next-round` were all interpreted by a runtime that called itself generic. They are ordinary messages and a timer, and they are spelled that way now.
Stellar Consensus Protocol -- Federated Byzantine Agreement -- as a pure
state machine on urd.consensus.node.
The sixth algorithm in the library, and the first with no global validator set. Raft, Tendermint, round-robin and Snowman all start from "here are the n validators"; Nakamoto starts from "anyone with hashpower". SCP starts from neither. Each node names its own quorum slices, and whether a set of peers is decisive is a question only that node can answer -- from data it may not have yet.
stellar-core/src/scp/ (checkout of 2017; SCP's core has been frozen since
2015, so it is authoritative). File/line references below point there. The
IETF draft draft-mazieres-dinrg-scp-05 is the same algorithm in prose.
Two deliberate divergences, both marked at their definitions:
update-round-leaders ACCUMULATES leaders across nomination rounds. The
2017 checkout clears the set each round (NominationProtocol.cpp:203);
current stellar-core keeps them, and the growing-leader-set argument is what
makes nomination converge. We implement the convergent version.attempt* rules scan candidate ballots from ALL known statements rather
than from the hint statement that triggered them. stellar-core's hint is
an optimisation to bound the scan; taking the union over every possible hint
is a superset, and a superset cannot cause an unsafe accept because each
candidate still has to clear federated voting on its own.Membership's tri-state quorum? and node/fixpoint were designed for SCP
and, until this file, never exercised by anything. The verdicts are recorded
at each definition.
A set U is a quorum iff every member of U has one of its own slices
contained in U. That is self-referential, so it is computed as a greatest
fixpoint (LocalNode.cpp:252-290): start from all candidates, repeatedly
discard anyone whose advertised quorum set is not satisfied by the survivors,
stop when stable, then ask whether the survivors contain a slice of MINE.
v-blocking? (LocalNode.cpp:194-220) is the cardinality DUAL and is purely
LOCAL -- it reads only my own quorum set and never anybody else's. The
asymmetry is the point: quorum is transitive, v-blocking is not.
:unknownEvery statement carries the HASH of its sender's quorum set, not the set itself. A node routinely holds a statement whose quorum set it has never seen, and then it genuinely cannot evaluate the fixpoint.
stellar-core sidesteps this by refusing to process such an envelope at all --
Herder's ItemFetcher parks it until the quorum set arrives -- and inside
isQuorum an unresolvable quorum set simply excludes its node
(LocalNode.cpp:266-274), which is a safe UNDER-approximation. We do better,
because the protocol offers a third value and it is worth finding out whether
it carries its weight: quorum-tri computes BOTH bounds. Dropping the
unknown-quorum-set nodes is the lower bound; treating them as unconditionally
satisfied is the upper bound. Then
lower = true -> true (no arriving data can retract it) upper = false -> false (no arriving data can establish it) otherwise -> :unknown
so :unknown means precisely this answer will change once I fetch something,
which is exactly the condition under which fetching is worth doing. false
means decided with respect to arriving QUORUM SETS -- an arriving STATEMENT
enlarges the node set being tested and can still flip it, which is harmless
because the answer is recomputed on every pass, but it is not the stronger
claim -- decided regardless of what arrives -- that this used to make.
Monotonicity is what makes those bounds sound. Learning a quorum set can only ADD survivors to the fixpoint, and more survivors can only satisfy more slices, so the answer moves in one direction only.
§4 of the design doc proposed a [:request-qset] effect and a
:qset-received event. Neither is necessary and we did not add them: a
missing quorum set has to come from a peer, so it is a unicast request and a
unicast reply -- send-to and message-received, which already exist. See
the PR; hiding a network round trip behind a bespoke effect would have made
its failure modes invisible.
Replies are content-addressed and VERIFIED: (= hash (qset-hash qset)) before
the cache is touched, so a Byzantine peer cannot answer a fetch with a quorum
set of its choosing and thereby manufacture a quorum for us.
.cljc, no host interop except one character-code helper (the same reader
conditional raft uses), no clock, no RNG. Nomination leader election is a
portable hash of (slot, previous value, round, node), which is the role
stellar-core gives SHA-256; see content-hash for why the obvious portable
hash was not good enough, and for what a real deployment should use instead.
Stellar Consensus Protocol -- Federated Byzantine Agreement -- as a pure state machine on `urd.consensus.node`. The sixth algorithm in the library, and the first with **no global validator set**. Raft, Tendermint, round-robin and Snowman all start from "here are the n validators"; Nakamoto starts from "anyone with hashpower". SCP starts from neither. Each node names its own *quorum slices*, and whether a set of peers is decisive is a question only that node can answer -- from data it may not have yet. ## Source of truth `stellar-core/src/scp/` (checkout of 2017; SCP's core has been frozen since 2015, so it is authoritative). File/line references below point there. The IETF draft `draft-mazieres-dinrg-scp-05` is the same algorithm in prose. Two deliberate divergences, both marked at their definitions: - `update-round-leaders` ACCUMULATES leaders across nomination rounds. The 2017 checkout clears the set each round (`NominationProtocol.cpp:203`); current stellar-core keeps them, and the growing-leader-set argument is what makes nomination converge. We implement the convergent version. - The `attempt*` rules scan candidate ballots from ALL known statements rather than from the `hint` statement that triggered them. stellar-core's hint is an optimisation to bound the scan; taking the union over every possible hint is a superset, and a superset cannot cause an unsafe accept because each candidate still has to clear federated voting on its own. ## The four things this file exists to test `Membership`'s tri-state `quorum?` and `node/fixpoint` were designed for SCP and, until this file, never exercised by anything. The verdicts are recorded at each definition. ## Quorum-ness is a greatest fixpoint, not a cardinality A set U is a *quorum* iff every member of U has one of its own slices contained in U. That is self-referential, so it is computed as a greatest fixpoint (`LocalNode.cpp:252-290`): start from all candidates, repeatedly discard anyone whose advertised quorum set is not satisfied by the survivors, stop when stable, then ask whether the survivors contain a slice of MINE. `v-blocking?` (`LocalNode.cpp:194-220`) is the cardinality DUAL and is purely LOCAL -- it reads only my own quorum set and never anybody else's. The asymmetry is the point: quorum is transitive, v-blocking is not. ## Why the answer can be `:unknown` Every statement carries the HASH of its sender's quorum set, not the set itself. A node routinely holds a statement whose quorum set it has never seen, and then it genuinely cannot evaluate the fixpoint. stellar-core sidesteps this by refusing to process such an envelope at all -- `Herder`'s `ItemFetcher` parks it until the quorum set arrives -- and inside `isQuorum` an unresolvable quorum set simply excludes its node (`LocalNode.cpp:266-274`), which is a safe UNDER-approximation. We do better, because the protocol offers a third value and it is worth finding out whether it carries its weight: `quorum-tri` computes BOTH bounds. Dropping the unknown-quorum-set nodes is the lower bound; treating them as unconditionally satisfied is the upper bound. Then lower = true -> true (no arriving data can retract it) upper = false -> false (no arriving data can establish it) otherwise -> :unknown so `:unknown` means precisely *this answer will change once I fetch something*, which is exactly the condition under which fetching is worth doing. `false` means decided with respect to arriving QUORUM SETS -- an arriving STATEMENT enlarges the node set being tested and can still flip it, which is harmless because the answer is recomputed on every pass, but it is not the stronger claim -- decided regardless of what arrives -- that this used to make. Monotonicity is what makes those bounds sound. Learning a quorum set can only ADD survivors to the fixpoint, and more survivors can only satisfy more slices, so the answer moves in one direction only. ## Fetching a missing quorum set needs no new effect §4 of the design doc proposed a `[:request-qset]` effect and a `:qset-received` event. Neither is necessary and we did not add them: a missing quorum set has to come from a peer, so it is a unicast request and a unicast reply -- `send-to` and `message-received`, which already exist. See the PR; hiding a network round trip behind a bespoke effect would have made its failure modes invisible. Replies are content-addressed and VERIFIED: `(= hash (qset-hash qset))` before the cache is touched, so a Byzantine peer cannot answer a fetch with a quorum set of its choosing and thereby manufacture a quorum for us. ## Purity `.cljc`, no host interop except one character-code helper (the same reader conditional `raft` uses), no clock, no RNG. Nomination leader election is a portable hash of (slot, previous value, round, node), which is the role stellar-core gives SHA-256; see `content-hash` for why the obvious portable hash was not good enough, and for what a real deployment should use instead.
Snowflake and Snowball: the repeated-sampling core of the Avalanche family.
These are pure functions over a small map. They are separated from the Snowman node deliberately -- they are total, they have real invariants, and they are the natural first target for machine-checked verification.
Slush keeps only a preference. Snowflake adds a CONSECUTIVE-success
confidence counter and an absorbing finalized flag. Snowball adds a
CUMULATIVE preference-strength tally and returns the argmax of that instead of
the last successful poll's choice. Each is a strict superset of the previous.
Ported from avalanchego/snow/consensus/snowball (Aug 2026).
Snowflake. Not Snowball. chains/manager.go:933 and :1358 both build
&smcon.Topological{Factory: snowball.SnowflakeFactory}, and
git log -S SnowflakeFactory -- chains/manager.go returns exactly one commit:
db3b57a96f -- make snowman use snowflake directly instead of snowball
(#3403). SnowballFactory is exported, exercised by the package's own tests,
and wired into no chain.
So Snowball below -- the cumulative :strength tally, the argmax preference,
the finalized-versus-argmax asymmetry that accept-weird-color pins -- is
reference material rather than production behaviour. It is kept because it is
the published algorithm, because the papers are stated in its terms, and
because a library covering the family should be able to express it. It is not
kept under the impression that it is what the network runs.
Two further notes on drift from the papers, both verified against that tree:
betaVirtuous / betaRogue are GONE. They were replaced by a single
beta plus a list of (alpha-confidence, beta) termination conditions.
Production always uses exactly one pair; the multi-condition path ("early
termination": a stronger quorum finalizes in fewer rounds) is exercised
only by tests. We model the list, since it costs nothing and the
single-condition case is just a list of one. termination-conditions is
public and overridable so the multi-condition path can actually be
CONSTRUCTED: while the pairs were derived from params inside a private
function, no caller could build an instance with more than one counter, the
partial-clear semantics that are the vector's whole reason for existing were
unobservable, and the claim above was not true of the code.
The Avalanche DAG protocol has been DELETED from avalanchego entirely (the X-Chain moved to Snowman in Cortina). Only Snowman remains, so the papers are the sole source for the DAG variant.
k sample size per poll
alpha-preference votes needed to move the preference
alpha-confidence votes needed to increment confidence
beta consecutive successes needed to finalize
Validity (parameters.go:93-116):
k/2 < alpha-preference <= alpha-confidence <= k
The first conjunct forces a strict majority of the sample, so two conflicting
choices cannot both clear alpha-preference in one poll of one honest node.
The second guarantees that any poll which increments confidence also moved the
preference -- which is what makes the beta-run characterisation below hold.
Snowflake and Snowball: the repeated-sampling core of the Avalanche family.
These are pure functions over a small map. They are separated from the
Snowman node deliberately -- they are total, they have real invariants, and
they are the natural first target for machine-checked verification.
## The family
Slush keeps only a preference. Snowflake adds a CONSECUTIVE-success
confidence counter and an absorbing `finalized` flag. Snowball adds a
CUMULATIVE preference-strength tally and returns the argmax of that instead of
the last successful poll's choice. Each is a strict superset of the previous.
Ported from `avalanchego/snow/consensus/snowball` (Aug 2026).
## Which of these avalanchego actually deploys
**Snowflake.** Not Snowball. `chains/manager.go:933` and `:1358` both build
`&smcon.Topological{Factory: snowball.SnowflakeFactory}`, and
`git log -S SnowflakeFactory -- chains/manager.go` returns exactly one commit:
`db3b57a96f` -- make snowman use snowflake directly instead of snowball
(#3403). `SnowballFactory` is exported, exercised by the package's own tests,
and wired into no chain.
So Snowball below -- the cumulative `:strength` tally, the argmax preference,
the finalized-versus-argmax asymmetry that `accept-weird-color` pins -- is
reference material rather than production behaviour. It is kept because it is
the published algorithm, because the papers are stated in its terms, and
because a library covering the family should be able to express it. It is not
kept under the impression that it is what the network runs.
Two further notes on drift from the papers, both verified against that tree:
- `betaVirtuous` / `betaRogue` are GONE. They were replaced by a single
`beta` plus a list of (alpha-confidence, beta) termination conditions.
Production always uses exactly one pair; the multi-condition path ("early
termination": a stronger quorum finalizes in fewer rounds) is exercised
only by tests. We model the list, since it costs nothing and the
single-condition case is just a list of one. `termination-conditions` is
public and overridable so the multi-condition path can actually be
CONSTRUCTED: while the pairs were derived from `params` inside a private
function, no caller could build an instance with more than one counter, the
partial-clear semantics that are the vector's whole reason for existing were
unobservable, and the claim above was not true of the code.
- The Avalanche DAG protocol has been DELETED from avalanchego entirely
(the X-Chain moved to Snowman in Cortina). Only Snowman remains, so the
papers are the sole source for the DAG variant.
## Parameters
k sample size per poll
alpha-preference votes needed to move the preference
alpha-confidence votes needed to increment confidence
beta consecutive successes needed to finalize
Validity (`parameters.go:93-116`):
k/2 < alpha-preference <= alpha-confidence <= k
The first conjunct forces a strict majority of the sample, so two conflicting
choices cannot both clear `alpha-preference` in one poll of one honest node.
The second guarantees that any poll which increments confidence also moved the
preference -- which is what makes the beta-run characterisation below hold.Snowman: leaderless consensus by repeated sampling, on urd's core protocol.
This exists to stress the OPPOSITE corner of the protocol from Raft. Where Raft is leader-based, log-structured, quorum-decided and absolutely final, Snowman is leaderless, chain-structured, SAMPLE-decided and only probabilistically final. If one protocol expresses both cleanly, the generality claim has evidence; if not, we learn where it breaks.
There is no quorum. A node repeatedly samples k peers, asks each for its current preference, and feeds the tally into a Snowball instance. Confidence accumulates only on CONSECUTIVE successful polls, so a network that keeps flip-flopping never finalizes -- and one that has tipped past the metastable point converges fast. Safety is probabilistic, parameterised by k, alpha, beta and the Byzantine fraction; it is not enforced by the code, and this implementation does not pretend otherwise.
One instance per PARENT, arbitrating among its children. This is
snowman_block.go:22-44, where the instance is a field of the block and
AddChild adds each new child as one of its choices; topological.go:517
votes into parentBlock.sb.
What that instance IS, is the next section. This one is about the PLACEMENT, which is the part that was a safety bug.
It is worth stating why, because the obvious alternative -- one instance per
candidate block, keyed by and voting for itself -- looks equivalent and is
not. Snowflake's entire safety argument is that confidence counts CONSECUTIVE
successes, enforced by nnary_snowflake.go:66-68: a poll whose winner differs
from the current preference zeroes confidence before incrementing. That flip
is only visible to an instance that can see both siblings. Give each block its
own instance and the flip never happens, no instance ever holds more than one
choice, and confidence in a losing sibling is never cleared -- so two honest
nodes seeing the alternating tallies X, Y, X, Y, X and Y, X, Y, X, Y both
reach beta and accept CONFLICTING blocks. Alternating tallies are the expected
outcome of a split preference, not a contrived one. The consecutive-poll
invariant this namespace advertises has to be enforced at the layer that
accepts blocks, or it is not enforced at all.
Two consequences follow from getting the PLACEMENT right:
topological.go:362-427 does this with a Kahn
sort; the path walk below is the same relation computed per chit).topological.go:296-311), rather than leaving preference
at the child of the last accepted block -- which would cap the chain at one
block per round.:variant selects it and defaults to :tree, which is what a running node
uses: chains/manager.go:933 and :1358 build Topological{Factory: SnowflakeFactory}, and snowman_block.go:39 hands that factory to
snowball.NewTree.
:tree NewTree(SnowflakeFactory) -- production
:flat-snowflake NewFlat(SnowflakeFactory)
:flat-snowball NewFlat(SnowballFactory) -- the published algorithm
The flat variants are kept because the papers are stated in Snowball's terms
and a library covering this family should be able to express them. Neither is
what any chain runs; NewFlat has no non-test caller anywhere in avalanchego.
The Tree is not an optimization of the flat form, which is how the design doc
had it filed. Flat.RecordPoll feeds one n-ary instance the PLURALITY choice
and its count; the Tree feeds each of its nodes every vote that reached it, so
votes for two siblings combine at every node above the bit where their ids
diverge. Three children where two share a leading bit the third lacks: a
split between the two still eliminates the third, on evidence the flat form
discards as a sub-alpha plurality. See snowtree.
Block ids stay whatever the application calls them. The Tree needs
fixed-width bits, so choice-key derives them with hasch/uuid rather than
constraining the vertex contract.
Membership does NOT apply. Snowman never asks "is this set a quorum of
the validators?" -- it asks "did alpha of my k SAMPLED peers agree?". The
Membership protocol is therefore optional, not universal, and a runtime
must not require it. Documented in the design as a correction.
:sample returning a BAG is load-bearing, and would have been easy to get
wrong. Weight is drawn without replacement, so one peer can appear several
times and its multiplicity IS its vote weight. The multiplicity belongs to
the REQUEST, not to the peer: several polls are in flight at once and a
peer's weight differs between them, so storing it in one global map lets
one poll's tally exceed k.
Probabilistic finality still maps onto :commit without :revert.
Preference flips freely BEFORE finalization, but a finalized decision is
never revoked -- so Snowman needs the revocable API less than Raft does,
which is a pleasing inversion of the usual intuition.
Snowman: leaderless consensus by repeated sampling, on urd's core protocol.
This exists to stress the OPPOSITE corner of the protocol from Raft. Where
Raft is leader-based, log-structured, quorum-decided and absolutely final,
Snowman is leaderless, chain-structured, SAMPLE-decided and only
probabilistically final. If one protocol expresses both cleanly, the
generality claim has evidence; if not, we learn where it breaks.
## How it decides
There is no quorum. A node repeatedly samples k peers, asks each for its
current preference, and feeds the tally into a Snowball instance. Confidence
accumulates only on CONSECUTIVE successful polls, so a network that keeps
flip-flopping never finalizes -- and one that has tipped past the metastable
point converges fast. Safety is probabilistic, parameterised by k, alpha, beta
and the Byzantine fraction; it is not enforced by the code, and this
implementation does not pretend otherwise.
## Where the instances live, and why it matters
**One instance per PARENT, arbitrating among its children.** This is
`snowman_block.go:22-44`, where the instance is a field of the block and
`AddChild` adds each new child as one of its choices; `topological.go:517`
votes into `parentBlock.sb`.
What that instance IS, is the next section. This one is about the PLACEMENT,
which is the part that was a safety bug.
It is worth stating why, because the obvious alternative -- one instance per
candidate block, keyed by and voting for itself -- looks equivalent and is
not. Snowflake's entire safety argument is that confidence counts CONSECUTIVE
successes, enforced by `nnary_snowflake.go:66-68`: a poll whose winner differs
from the current preference zeroes confidence before incrementing. That flip
is only visible to an instance that can see both siblings. Give each block its
own instance and the flip never happens, no instance ever holds more than one
choice, and confidence in a losing sibling is never cleared -- so two honest
nodes seeing the alternating tallies X, Y, X, Y, X and Y, X, Y, X, Y both
reach beta and accept CONFLICTING blocks. Alternating tallies are the expected
outcome of a split preference, not a contrived one. The consecutive-poll
invariant this namespace advertises has to be enforced at the layer that
accepts blocks, or it is not enforced at all.
Two consequences follow from getting the PLACEMENT right:
- **Vote bubbling is transitive.** A chit for a deep block is a vote for every
block on the path from the last accepted block down to it, each counted in
its own parent's instance (`topological.go:362-427` does this with a Kahn
sort; the path walk below is the same relation computed per chit).
- **Preference is the TIP.** After recording a poll we walk down the preferred
branch to a leaf (`topological.go:296-311`), rather than leaving preference
at the child of the last accepted block -- which would cap the chain at one
block per round.
## Which instance, of the three avalanchego has
`:variant` selects it and defaults to `:tree`, which is what a running node
uses: `chains/manager.go:933` and `:1358` build `Topological{Factory:
SnowflakeFactory}`, and `snowman_block.go:39` hands that factory to
`snowball.NewTree`.
:tree NewTree(SnowflakeFactory) -- production
:flat-snowflake NewFlat(SnowflakeFactory)
:flat-snowball NewFlat(SnowballFactory) -- the published algorithm
The flat variants are kept because the papers are stated in Snowball's terms
and a library covering this family should be able to express them. Neither is
what any chain runs; `NewFlat` has no non-test caller anywhere in avalanchego.
The Tree is not an optimization of the flat form, which is how the design doc
had it filed. `Flat.RecordPoll` feeds one n-ary instance the PLURALITY choice
and its count; the Tree feeds each of its nodes every vote that reached it, so
votes for two siblings combine at every node above the bit where their ids
diverge. Three children where two share a leading bit the third lacks: a
split between the two still eliminates the third, on evidence the flat form
discards as a sub-alpha plurality. See `snowtree`.
Block ids stay whatever the application calls them. The Tree needs
fixed-width bits, so `choice-key` derives them with `hasch/uuid` rather than
constraining the vertex contract.
## What it revealed about the core protocol
1. `Membership` does NOT apply. Snowman never asks "is this set a quorum of
the validators?" -- it asks "did alpha of my k SAMPLED peers agree?". The
`Membership` protocol is therefore optional, not universal, and a runtime
must not require it. Documented in the design as a correction.
2. `:sample` returning a BAG is load-bearing, and would have been easy to get
wrong. Weight is drawn without replacement, so one peer can appear several
times and its multiplicity IS its vote weight. The multiplicity belongs to
the REQUEST, not to the peer: several polls are in flight at once and a
peer's weight differs between them, so storing it in one global map lets
one poll's tally exceed k.
3. Probabilistic finality still maps onto `:commit` without `:revert`.
Preference flips freely BEFORE finalization, but a finalized decision is
never revoked -- so Snowman needs the revocable API less than Raft does,
which is a pleasing inversion of the usual intuition.The Snowball Tree: what avalanchego actually runs under Snowman.
snow/consensus/snowball/tree.go. A patricia trie over the BITS of the
candidate ids, deciding the winner one bit-range at a time rather than
deciding among the candidates as a set.
Flat.RecordPoll (flat.go:29-33) is three lines:
pollMode, numVotes := votes.Mode()
f.Nnary.RecordPoll(numVotes, pollMode)
The plurality choice and its count, fed to one n-ary instance. That is what
urd's Snowman did, exactly, and NewFlat has no non-test caller anywhere in
avalanchego.
The Tree instead feeds each node votes.Len() -- EVERY vote that reached it,
whatever choice it names. So votes for two siblings COMBINE at every node
above the bit where their ids diverge. Three children X, Y, Z where Y and Z
share a leading bit that X does not: a 2/2 split between Y and Z still
delivers 4 votes to the not-X side of the top binary node. The flat form sees
a plurality of 2 and may not clear alpha at all. This is a real behavioural
difference, not a change of representation, and it is why the reference can
make progress on a contested slot that the flat form stalls on.
avalanchego indexes bit i as bit i mod 8 of byte i div 8, least
significant first (ids/id.go:140-155). We index bit i as bit i mod 4 of
hex digit i div 4, least significant first.
The difference is immaterial and worth saying why, because it looks like the
kind of thing that would matter. The Tree is defined over an arbitrary but
FIXED total order on the bits of an id; any such order gives the same
algorithm. What changes is which pairs of ids happen to share a prefix, and
since ids here are hasch/uuid digests that is uniformly random under either
order. What we give up is the ability to replay avalanchego's own test
vectors, which are literal ids.ID byte arrays -- and those were never
replayable anyway, since urd's choices are not 32-byte avalanche ids. The
tests port the structural claims instead.
{:kind :unary
:preference key
:decided-prefix the first bit this node covers
:common-prefix one past the last bit it covers
:snow a unary instance
:should-reset bool
:child node or nil}
{:kind :binary
:preferences [key-when-bit-0 key-when-bit-1]
:bit the bit index this node decides
:snow a binary instance
:should-reset [bool bool]
:children [node-or-nil node-or-nil]}
Keys are fixed-width lowercase hex strings. The tree carries :choices, from
key back to whatever the caller called a choice, so a caller keeps using its
own ids and never sees a digest.
The Snowball Tree: what avalanchego actually runs under Snowman.
`snow/consensus/snowball/tree.go`. A patricia trie over the BITS of the
candidate ids, deciding the winner one bit-range at a time rather than
deciding among the candidates as a set.
## Why this exists and the flat form does not suffice
`Flat.RecordPoll` (`flat.go:29-33`) is three lines:
pollMode, numVotes := votes.Mode()
f.Nnary.RecordPoll(numVotes, pollMode)
The plurality choice and its count, fed to one n-ary instance. That is what
urd's Snowman did, exactly, and `NewFlat` has no non-test caller anywhere in
avalanchego.
The Tree instead feeds each node `votes.Len()` -- EVERY vote that reached it,
whatever choice it names. So votes for two siblings COMBINE at every node
above the bit where their ids diverge. Three children X, Y, Z where Y and Z
share a leading bit that X does not: a 2/2 split between Y and Z still
delivers 4 votes to the not-X side of the top binary node. The flat form sees
a plurality of 2 and may not clear alpha at all. This is a real behavioural
difference, not a change of representation, and it is why the reference can
make progress on a contested slot that the flat form stalls on.
## Bit order
avalanchego indexes bit `i` as bit `i mod 8` of byte `i div 8`, least
significant first (`ids/id.go:140-155`). We index bit `i` as bit `i mod 4` of
hex digit `i div 4`, least significant first.
The difference is immaterial and worth saying why, because it looks like the
kind of thing that would matter. The Tree is defined over an arbitrary but
FIXED total order on the bits of an id; any such order gives the same
algorithm. What changes is which pairs of ids happen to share a prefix, and
since ids here are `hasch/uuid` digests that is uniformly random under either
order. What we give up is the ability to replay avalanchego's own test
vectors, which are literal `ids.ID` byte arrays -- and those were never
replayable anyway, since urd's choices are not 32-byte avalanche ids. The
tests port the structural claims instead.
## What a node holds
{:kind :unary
:preference key
:decided-prefix the first bit this node covers
:common-prefix one past the last bit it covers
:snow a unary instance
:should-reset bool
:child node or nil}
{:kind :binary
:preferences [key-when-bit-0 key-when-bit-1]
:bit the bit index this node decides
:snow a binary instance
:should-reset [bool bool]
:children [node-or-nil node-or-nil]}
Keys are fixed-width lowercase hex strings. The tree carries `:choices`, from
key back to whatever the caller called a choice, so a caller keeps using its
own ids and never sees a digest.Tendermint BFT consensus as a pure state machine on urd.consensus.node.
The first genuinely BYZANTINE algorithm in the library: Raft tolerates crashes, Snowman is probabilistic, this one keeps agreement while f of 3f+1 validators lie.
The normative algorithm is the pseudocode of arXiv:1807.04938, The latest gossip on BFT consensus, transcribed in the CometBFT tree at
spec/consensus/consensus-paper/consensus.tex:28-174. Line numbers in the
comments below (L22, L28, ...) refer to it.
Two sources that look authoritative and are NOT used:
spec/consensus/consensus.md is STALE -- it documents the pre-2018
PoLC/unlock design, and spec/consensus/readme.md:26 says so.consensus/state.go:2362) where the paper uses f+1, and the L28 unlock is
not a prevote rule there at all but happens asynchronously inside addVote
(consensus/state.go:2312-2328). We implement the paper.The structure follows spec/ivy-proofs/tendermint.ivy, a mechanically
checked transliteration in which the paper's for the first time latches are
explicit relations -- done_l34(R), done_l36(R,V), done_l47(R)
(tendermint.ivy:86-88). Those three latches are the trickiest bookkeeping
in the protocol and having them named is worth the whole file.
Each of these is subtle enough that it has a dedicated test:
lockedRound <= vr -- less-than-or-EQUAL. And the 2f+1
prevotes it needs are at round vr, not at the current round.step >= prevote, so it also fires when we are already
in precommit; in that case ONLY validValue/validRound move.validRound := round_p, the current round, NOT the proposal's
vr.Signature verification happens outside this namespace, by construction:
ClojureScript's Web Crypto is promise-based so geheimnis' Ed25519 verify
returns a channel and cannot be called from a pure function. Events arrive
pre-authenticated with :verified-by, which is exactly the seam CometBFT's
own layering already has -- addVerifiedVote is documented "assumes
signature is valid" (types/vote_set.go:259-329).
A consequence worth stating: (vote -> signature) is NOT a function.
Signatures from a remote signer can be non-deterministic; CometBFT carries
ErrVoteNonDeterministicSignature (types/vote_set.go:215) precisely for
this. So two votes from the same validator for the same value with DIFFERENT
signature bytes are a duplicate, not equivocation. Only a differing value is
equivocation, and it is reported through report-equivocation rather than
dropped.
CometBFT fsyncs exactly the messages this node SIGNS -- its own proposal,
prevote, precommit -- plus the end-height marker, in one function with a
default: panic so that a new self-message type cannot silently skip the
barrier (consensus/state.go:881-905). signed-message-step below is that
function, throw and all.
The ordering is STRICTER than Raft's: sign -> fsync -> apply -> broadcast,
with the fsync happening before this state machine even sees its own message.
So a signed message is put in :pending-signed, the broadcast rides in the
:then of a persist-then, and the vote is added to our own tally only when
the persisted event comes back. A node that crashes before its own fsync
has not voted, which is the entire point.
.cljc, no host interop, no clock, no RNG. Timeouts are logical ticks and
grow per round: timeout(r) = init + r*delta, reset at each height.
Tendermint BFT consensus as a pure state machine on `urd.consensus.node`. The first genuinely BYZANTINE algorithm in the library: Raft tolerates crashes, Snowman is probabilistic, this one keeps agreement while f of 3f+1 validators lie. ## Source of truth The normative algorithm is the pseudocode of arXiv:1807.04938, `The latest gossip on BFT consensus`, transcribed in the CometBFT tree at `spec/consensus/consensus-paper/consensus.tex:28-174`. Line numbers in the comments below (`L22`, `L28`, ...) refer to it. Two sources that look authoritative and are NOT used: - `spec/consensus/consensus.md` is STALE -- it documents the pre-2018 PoLC/unlock design, and `spec/consensus/readme.md:26` says so. - CometBFT's own implementation DIVERGES from the paper in at least two places we deliberately did not copy: round-skip triggers on 2f+1 (`consensus/state.go:2362`) where the paper uses f+1, and the L28 unlock is not a prevote rule there at all but happens asynchronously inside `addVote` (`consensus/state.go:2312-2328`). We implement the paper. The structure follows `spec/ivy-proofs/tendermint.ivy`, a mechanically checked transliteration in which the paper's `for the first time` latches are explicit relations -- `done_l34(R)`, `done_l36(R,V)`, `done_l47(R)` (`tendermint.ivy:86-88`). Those three latches are the trickiest bookkeeping in the protocol and having them named is worth the whole file. ## The rules, and the four traps Each of these is subtle enough that it has a dedicated test: - **L28's unlock is `lockedRound <= vr`** -- less-than-or-EQUAL. And the 2f+1 prevotes it needs are at round `vr`, not at the current round. - **L36 fires when `step >= prevote`**, so it also fires when we are already in precommit; in that case ONLY validValue/validRound move. - **L36 sets `validRound := round_p`**, the current round, NOT the proposal's `vr`. - **L47 has no step guard at all**, and **L49 decides on ANY round r**, not only the current one. ## Where the crypto is not Signature verification happens outside this namespace, by construction: ClojureScript's Web Crypto is promise-based so geheimnis' Ed25519 verify returns a channel and cannot be called from a pure function. Events arrive pre-authenticated with `:verified-by`, which is exactly the seam CometBFT's own layering already has -- `addVerifiedVote` is documented "assumes signature is valid" (`types/vote_set.go:259-329`). A consequence worth stating: `(vote -> signature)` is NOT a function. Signatures from a remote signer can be non-deterministic; CometBFT carries `ErrVoteNonDeterministicSignature` (`types/vote_set.go:215`) precisely for this. So two votes from the same validator for the same value with DIFFERENT signature bytes are a duplicate, not equivocation. Only a differing value is equivocation, and it is reported through `report-equivocation` rather than dropped. ## Durability CometBFT fsyncs exactly the messages this node SIGNS -- its own proposal, prevote, precommit -- plus the end-height marker, in one function with a `default: panic` so that a new self-message type cannot silently skip the barrier (`consensus/state.go:881-905`). `signed-message-step` below is that function, throw and all. The ordering is STRICTER than Raft's: sign -> fsync -> apply -> broadcast, with the fsync happening before this state machine even sees its own message. So a signed message is put in `:pending-signed`, the broadcast rides in the `:then` of a `persist-then`, and the vote is added to our own tally only when the `persisted` event comes back. A node that crashes before its own fsync has not voted, which is the entire point. ## Portability `.cljc`, no host interop, no clock, no RNG. Timeouts are logical ticks and grow per round: `timeout(r) = init + r*delta`, reset at each height.
The convention by which a decided value commits to APPLICATION state.
Nothing in urd's consensus state says anything about the application's state. Consensus agrees on an ORDER of values; whether two nodes that applied the same order ended up in the same state is not something any node can check. A validator whose application diverged -- a non-deterministic transaction, a storage bug, a different library version -- keeps voting, and every vote it casts is on behalf of a state nobody else has. It is a silent, permanent fork of exactly the thing consensus exists to keep identical.
The fix costs no protocol change, because values are OPAQUE to urd: the value carries a digest of the application state, and the quorum that decides the value certifies the digest along with it.
The digest describes the state as of the LAST DECIDED value, not as of the
value carrying it. Value N says here is what my application looked like after N-1.
The alternative -- the digest of the state after applying THIS value -- reads as more direct and costs much more. The proposer would have to execute its own proposal speculatively before proposing, and every validator would have to execute it speculatively before VOTING, because the digest cannot be checked without doing so. That makes execution part of the voting path, which means it must be deterministic, bounded, and fast enough to fit inside a vote timeout, on every validator, for every proposal -- including proposals that never get decided.
Lagging by one removes all of it. A validator checking value N compares the
digest against a state it computed long ago, when N-1 was decided. It is a
map lookup, not an execution. CometBFT made this choice for these reasons and
its AppHash has this meaning.
What it costs is one block of latency in DETECTION: divergence caused by value N is caught when N+1 is proposed. That is still before anything is built on N, because N+1 is where the chain would continue -- so the fork is refused rather than discovered later.
urd never computes a digest, never inspects one, and has no opinion about how
it is derived. datahike supplies one for free with :crypto-hash? true,
where the commit-id IS a merkle hash over the stored roots -- but that is one
implementation of the convention, not the convention. A plain hash of an
application's own state is another, and so is anything Proximum or Scriptum
produce. Everything here is = on values the application chose.
The tempting reading of a missing :app-hash is this value makes no claim, so there is nothing to check. That is a bypass: an attacker proposing a
value simply omits the field and the check never runs. Every proposal it
makes is then exempt from exactly the guard that would catch it.
So checker refuses a value with no digest unless :require? is explicitly
set to false. This follows urd.consensus.auth/authenticator, and for the
same reason -- a permissive default is how a check that is described but not
performed survives review.
The convention by which a decided value commits to APPLICATION state. ## What is missing without it Nothing in urd's consensus state says anything about the application's state. Consensus agrees on an ORDER of values; whether two nodes that applied the same order ended up in the same state is not something any node can check. A validator whose application diverged -- a non-deterministic transaction, a storage bug, a different library version -- keeps voting, and every vote it casts is on behalf of a state nobody else has. It is a silent, permanent fork of exactly the thing consensus exists to keep identical. The fix costs no protocol change, because values are OPAQUE to urd: the value carries a digest of the application state, and the quorum that decides the value certifies the digest along with it. ## LAGGING by one, and why that is the right choice rather than a compromise The digest describes the state as of the LAST DECIDED value, not as of the value carrying it. Value N says `here is what my application looked like after N-1`. The alternative -- the digest of the state after applying THIS value -- reads as more direct and costs much more. The proposer would have to execute its own proposal speculatively before proposing, and every validator would have to execute it speculatively before VOTING, because the digest cannot be checked without doing so. That makes execution part of the voting path, which means it must be deterministic, bounded, and fast enough to fit inside a vote timeout, on every validator, for every proposal -- including proposals that never get decided. Lagging by one removes all of it. A validator checking value N compares the digest against a state it computed long ago, when N-1 was decided. It is a map lookup, not an execution. CometBFT made this choice for these reasons and its `AppHash` has this meaning. What it costs is one block of latency in DETECTION: divergence caused by value N is caught when N+1 is proposed. That is still before anything is built on N, because N+1 is where the chain would continue -- so the fork is refused rather than discovered later. ## Opaque, and it must stay opaque urd never computes a digest, never inspects one, and has no opinion about how it is derived. datahike supplies one for free with `:crypto-hash? true`, where the commit-id IS a merkle hash over the stored roots -- but that is one implementation of the convention, not the convention. A plain hash of an application's own state is another, and so is anything Proximum or Scriptum produce. Everything here is `=` on values the application chose. ## An ABSENT digest is not a valid one The tempting reading of a missing `:app-hash` is `this value makes no claim, so there is nothing to check`. That is a bypass: an attacker proposing a value simply omits the field and the check never runs. Every proposal it makes is then exempt from exactly the guard that would catch it. So `checker` refuses a value with no digest unless `:require?` is explicitly set to false. This follows `urd.consensus.auth/authenticator`, and for the same reason -- a permissive default is how a check that is described but not performed survives review.
Real vote attestations, and the commit certificates built from them.
Every algorithm here takes its attestation scheme as configuration -- a
{:sign-vote :verify-vote} pair -- and each one ships a test-attestations
that is a hash of the voter and the payload. Those are labelled NOT
CRYPTOGRAPHY in capitals and they mean it: anyone who can read the namespace
can mint a vote for any validator. They exist to give tests the SHAPE, and
round-robin's init refuses to start without a scheme precisely so the
stub cannot be reached by accident. This namespace is the thing init is
waiting for.
urd.consensus.auth already signs every message on the wire, and it is not
enough. It proves who SENT a message; an attestation must prove who VOTED,
and those separate the moment a vote is relayed. answer-want-votes exists
to hand one peer another peer's votes, and record-vote's docstring records
what happened when votes were bare names: :vote-bundle and :catchup
amounted to "here are the validators I say voted", and one peer could hand
us a quorum it invented. An attestation is what makes a vote transferable
through a party nobody trusts.
(voter payload), and the payload must bind the heightTendermint already took a payload -- [height round value-id] -- and its
docstring gives the argument: without the height a signature replays at every
later height, without the round it replays across rounds of the same height.
Round-robin signed a bare proposal-id, which is NOT height-bound. That is
safe only as long as a proposal id never repeats, and a proposal id may be a
snapshot-id is a "UUID or content-hash" -- under the content-hash reading,
proposing the same value at two heights yields the same id, and a vote cast
at the first is a valid vote at the second. Round-robin now signs
[height proposal-id]; Bullshark needs no change because header-id already
digests the author and round along with the content.
This namespace never looks inside a payload. It signs whatever the algorithm says a vote covers, which is what lets one implementation serve all three.
An attestation covers (wire/signing-bytes {:kind :urd/vote ...}) -- the same
RFC 8949 encoding a transaction signature covers, for the same reason: a
light client that wants to check that height H was really decided should not
have to be written in Clojure to do it. doc/interop/verify_certificate.py verifies one.
:kind is a discriminator. The vote payload and the transaction payload
already have disjoint key sets, so their encodings could not collide anyway,
but a security property that holds by accident of field naming is one field
rename away from not holding.
geheimnis returns channels on both platforms because ClojureScript's Web
Crypto is promise-based. The sign-vote/verify-vote seam is synchronous and
sits inside pure state-machine transitions, so it cannot await anything.
On the JVM this is a non-problem: geheimnis computes eagerly and puts the
result on a buffered channel before returning it, so the value is already
there. Rather than assume that, now! uses poll! -- which never parks --
and throws if the channel is not ready. If geheimnis ever becomes genuinely
asynchronous on the JVM, this fails loudly at the first vote instead of
deadlocking a consensus round inside a go block.
On ClojureScript there is no synchronous path at all: Web Crypto is
promise-only and the @noble/ed25519 fallback that geheimnis/set-fallback!
takes is used through verifyAsync. So attestations refuses to build under
ClojureScript rather than quietly returning something weaker. That is not a
portability gap being papered over -- validators run on the JVM, and the part
a browser or Node client actually needs is verify-certificate, which is
asynchronous, portable, and tested under both runners.
Making this seam portable means a synchronous Ed25519 verify for ClojureScript, which noble can do when handed a synchronous SHA-512. That is an upstream change to geheimnis and is recorded in the backlog.
Real vote attestations, and the commit certificates built from them.
Every algorithm here takes its attestation scheme as configuration -- a
`{:sign-vote :verify-vote}` pair -- and each one ships a `test-attestations`
that is a hash of the voter and the payload. Those are labelled NOT
CRYPTOGRAPHY in capitals and they mean it: anyone who can read the namespace
can mint a vote for any validator. They exist to give tests the SHAPE, and
`round-robin`'s `init` refuses to start without a scheme precisely so the
stub cannot be reached by accident. This namespace is the thing `init` is
waiting for.
## What an attestation is, and why it is not message authentication
`urd.consensus.auth` already signs every message on the wire, and it is not
enough. It proves who SENT a message; an attestation must prove who VOTED,
and those separate the moment a vote is relayed. `answer-want-votes` exists
to hand one peer another peer's votes, and `record-vote`'s docstring records
what happened when votes were bare names: `:vote-bundle` and `:catchup`
amounted to "here are the validators I say voted", and one peer could hand
us a quorum it invented. An attestation is what makes a vote transferable
through a party nobody trusts.
## The seam is `(voter payload)`, and the payload must bind the height
Tendermint already took a payload -- `[height round value-id]` -- and its
docstring gives the argument: without the height a signature replays at every
later height, without the round it replays across rounds of the same height.
Round-robin signed a bare `proposal-id`, which is NOT height-bound. That is
safe only as long as a proposal id never repeats, and a proposal id may be a
`snapshot-id` is a "UUID or content-hash" -- under the content-hash reading,
proposing the same value at two heights yields the same id, and a vote cast
at the first is a valid vote at the second. Round-robin now signs
`[height proposal-id]`; Bullshark needs no change because `header-id` already
digests the author and round along with the content.
This namespace never looks inside a payload. It signs whatever the algorithm
says a vote covers, which is what lets one implementation serve all three.
## Canonical CBOR, so a certificate is checkable off-platform
An attestation covers `(wire/signing-bytes {:kind :urd/vote ...})` -- the same
RFC 8949 encoding a transaction signature covers, for the same reason: a
light client that wants to check that height H was really decided should not
have to be written in Clojure to do it. `doc/interop/verify_certificate.py` verifies one.
`:kind` is a discriminator. The vote payload and the transaction payload
already have disjoint key sets, so their encodings could not collide anyway,
but a security property that holds by accident of field naming is one field
rename away from not holding.
## Signing is synchronous here, and that is checked rather than assumed
`geheimnis` returns channels on both platforms because ClojureScript's Web
Crypto is promise-based. The `sign-vote`/`verify-vote` seam is synchronous and
sits inside pure state-machine transitions, so it cannot await anything.
On the JVM this is a non-problem: `geheimnis` computes eagerly and puts the
result on a buffered channel before returning it, so the value is already
there. Rather than assume that, `now!` uses `poll!` -- which never parks --
and throws if the channel is not ready. If geheimnis ever becomes genuinely
asynchronous on the JVM, this fails loudly at the first vote instead of
deadlocking a consensus round inside a go block.
On ClojureScript there is no synchronous path at all: Web Crypto is
promise-only and the `@noble/ed25519` fallback that `geheimnis/set-fallback!`
takes is used through `verifyAsync`. So `attestations` refuses to build under
ClojureScript rather than quietly returning something weaker. That is not a
portability gap being papered over -- validators run on the JVM, and the part
a browser or Node client actually needs is `verify-certificate`, which is
asynchronous, portable, and tested under both runners.
Making this seam portable means a synchronous Ed25519 verify for
ClojureScript, which noble can do when handed a synchronous SHA-512. That is
an upstream change to geheimnis and is recorded in the backlog.The verification edge: what makes verified-by mean something.
Nothing. node.cljc states the contract -- "verified-by is the set of
peer-ids whose signature was checked at the edge; the state machine must
never see an unverified signature" -- and the edge did this:
(let [sender (:sender msg)]
(n/message-received sender msg #{sender}))
:sender is a field the sending peer writes into its own message. So
verified-by was the attacker's claim about who the attacker was, and
Tendermint's identity guard (contains? verified-by (:from msg)) was a
tautology over two fields the same party controls. urd.crypto was required
by four namespaces and called from none.
Every Byzantine property this library proves was therefore conditional on an authenticated transport that did not exist. That is the hole this closes.
Not a layering preference -- a constraint. ClojureScript's Web Crypto is
promise-based, so Ed25519 verification returns a channel on that platform;
geheimnis gives both platforms the same channel-returning contract so that
one implementation works on each. A step is a pure function and cannot
await a channel, so verification has to happen where there is already an
async context: the network handler. The same reasoning puts konserve's async
API at the store seam.
This is why the protocol carries verified-by at all rather than passing
signatures inward. The seam was right; only the implementation was missing.
The canonical CBOR encoding of {:chain :from :topic :to :seq :msg} -- see
urd.wire for why a signature covers RFC 8949 bytes rather than a
Clojure-specific hash, and digest below for why each of those fields is in
there.
:chain is domain separation and is not optional. Without it a signature
produced on a testnet verifies on mainnet, two deployments that can reach each
other cross-contaminate, and a vote captured from one network replays into
another. The audit found no domain separation anywhere in the codebase; this
is where it goes, because this is the only place every message passes through.
Ed25519 signatures are 64 raw bytes and geheimnis hands them over as a byte
array. A byte array is not a wire format: kabel serialises messages as EDN,
and a Java byte[] prints as #object[[B 0x...], which no reader can read
back. The first authenticated run over websockets died with "No reader
function for tag object" and every peer silently failed to assemble.
So seal base64-encodes and unseal decodes. The envelope is plain EDN --
keywords, a uuid, a string -- which is the contract every other message in
this library already meets.
The unit tests did not catch this because they passed the envelope straight
from seal to unseal in one process, where a byte array is a perfectly good
value. a-sealed-envelope-survives-the-wire round-trips through the reader,
because that is the thing that was actually broken.
authenticator requires keys. Running without them requires passing
:none explicitly. There is no permissive default, because a permissive
default is precisely how the original hole survived: the machinery was
described, the check was absent, and every test passed.
The verification edge: what makes `verified-by` mean something.
## What was here before
Nothing. `node.cljc` states the contract -- "`verified-by` is the set of
peer-ids whose signature was checked at the edge; the state machine must
never see an unverified signature" -- and the edge did this:
(let [sender (:sender msg)]
(n/message-received sender msg #{sender}))
`:sender` is a field the sending peer writes into its own message. So
`verified-by` was the attacker's claim about who the attacker was, and
Tendermint's identity guard `(contains? verified-by (:from msg))` was a
tautology over two fields the same party controls. `urd.crypto` was required
by four namespaces and called from none.
Every Byzantine property this library proves was therefore conditional on an
authenticated transport that did not exist. That is the hole this closes.
## Why it lives at the edge and not in the state machine
Not a layering preference -- a constraint. ClojureScript's Web Crypto is
promise-based, so Ed25519 verification returns a channel on that platform;
`geheimnis` gives both platforms the same channel-returning contract so that
one implementation works on each. A `step` is a pure function and cannot
await a channel, so verification has to happen where there is already an
async context: the network handler. The same reasoning puts konserve's async
API at the store seam.
This is why the protocol carries `verified-by` at all rather than passing
signatures inward. The seam was right; only the implementation was missing.
## What is signed
The canonical CBOR encoding of `{:chain :from :topic :to :seq :msg}` -- see
`urd.wire` for why a signature covers RFC 8949 bytes rather than a
Clojure-specific hash, and `digest` below for why each of those fields is in
there.
`:chain` is domain separation and is not optional. Without it a signature
produced on a testnet verifies on mainnet, two deployments that can reach each
other cross-contaminate, and a vote captured from one network replays into
another. The audit found no domain separation anywhere in the codebase; this
is where it goes, because this is the only place every message passes through.
## Why the signature is a string on the wire
Ed25519 signatures are 64 raw bytes and `geheimnis` hands them over as a byte
array. A byte array is not a wire format: kabel serialises messages as EDN,
and a Java `byte[]` prints as `#object[[B 0x...]`, which no reader can read
back. The first authenticated run over websockets died with "No reader
function for tag object" and every peer silently failed to assemble.
So `seal` base64-encodes and `unseal` decodes. The envelope is plain EDN --
keywords, a uuid, a string -- which is the contract every other message in
this library already meets.
The unit tests did not catch this because they passed the envelope straight
from `seal` to `unseal` in one process, where a byte array is a perfectly good
value. `a-sealed-envelope-survives-the-wire` round-trips through the reader,
because that is the thing that was actually broken.
## Refusing is a choice you have to make
`authenticator` requires keys. Running without them requires passing
`:none` explicitly. There is no permissive default, because a permissive
default is precisely how the original hole survived: the machinery was
described, the check was absent, and every test passed.Arbitrary-precision NATURAL numbers, in portable ClojureScript-safe arithmetic.
This exists for exactly one reason: Nakamoto fork choice compares cumulative
proof-of-work, which is a sum of terms of the form floor(2^256 / (target+1)).
Those numbers do not fit in a JavaScript double, and the comparison must be
EXACT -- btcd's rule is > and not >= (chain.go:1257), so ties go to the
incumbent and first-seen wins. An approximate comparison would silently
convert a tie into a reorg, which is a consensus fault, not a rounding error.
java.math.BigInteger exists; js/BigInt exists. Using them would mean a
reader conditional in every arithmetic expression, and -- worse -- two
independent implementations of the consensus arithmetic, which is precisely
the shape of bug this repository has already been bitten by once: rng
produced different draws under ClojureScript for as long as it existed,
because bit-and there yields a SIGNED 32-bit integer. Nothing in this
namespace can diverge that way, because it is one implementation.
The JVM's BigInteger is still useful -- as an ORACLE. bignat_test property-
tests every operation here against it.
A vector of limbs, base 2^16, LEAST significant first, with no trailing zero
limbs. Zero is [].
Base 2^16 is chosen so that every intermediate stays exactly representable in
a double. The largest quantity computed anywhere below is a schoolbook
multiply accumulator, limb*limb + limb + carry < 2^32 + 2^17, about 4.3e9 --
eleven orders of magnitude short of 2^53. A base of 2^24 would still fit a
single product but not a long accumulation, and base 2^32 would not fit at
all. Bit operations are never applied to anything wider than a limb, so
ClojureScript's signed 32-bit bit-and is never reached.
Everything here is total and non-negative: sub requires a >= b.
Arbitrary-precision NATURAL numbers, in portable ClojureScript-safe arithmetic. This exists for exactly one reason: Nakamoto fork choice compares cumulative proof-of-work, which is a sum of terms of the form `floor(2^256 / (target+1))`. Those numbers do not fit in a JavaScript double, and the comparison must be EXACT -- btcd's rule is `>` and not `>=` (`chain.go:1257`), so ties go to the incumbent and first-seen wins. An approximate comparison would silently convert a tie into a reorg, which is a consensus fault, not a rounding error. ## Why not the host's big integers `java.math.BigInteger` exists; `js/BigInt` exists. Using them would mean a reader conditional in every arithmetic expression, and -- worse -- two independent implementations of the consensus arithmetic, which is precisely the shape of bug this repository has already been bitten by once: `rng` produced different draws under ClojureScript for as long as it existed, because `bit-and` there yields a SIGNED 32-bit integer. Nothing in this namespace can diverge that way, because it is one implementation. The JVM's BigInteger is still useful -- as an ORACLE. `bignat_test` property- tests every operation here against it. ## Representation A vector of limbs, base 2^16, LEAST significant first, with no trailing zero limbs. Zero is `[]`. Base 2^16 is chosen so that every intermediate stays exactly representable in a double. The largest quantity computed anywhere below is a schoolbook multiply accumulator, `limb*limb + limb + carry < 2^32 + 2^17`, about 4.3e9 -- eleven orders of magnitude short of 2^53. A base of 2^24 would still fit a single product but not a long accumulation, and base 2^32 would not fit at all. Bit operations are never applied to anything wider than a limb, so ClojureScript's signed 32-bit `bit-and` is never reached. Everything here is total and non-negative: `sub` requires `a >= b`.
Network abstraction for consensus protocols.
Provides both mock (in-memory) and real (kabel) implementations.
Network abstraction for consensus protocols. Provides both mock (in-memory) and real (kabel) implementations.
Kabel-based P2P network implementation for consensus.
Provides a real P2P network layer using Kabel WebSockets. This is one implementation of the ConsensusNetwork protocol.
Kabel-based P2P network implementation for consensus. Provides a real P2P network layer using Kabel WebSockets. This is one implementation of the ConsensusNetwork protocol.
Simulation network for in-process testing.
Routes messages between validators in the same process, allowing fast deterministic testing of consensus logic without real networking.
Simulation network for in-process testing. Routes messages between validators in the same process, allowing fast deterministic testing of consensus logic without real networking.
The core consensus abstraction: a node is a pure state machine.
A Node maps (state, input) to a new state plus a vector of effects --
data describing side effects for a runtime or simulator to interpret. No
algorithm here performs I/O, reads a clock, or draws a random number; all
three are effects, which is what makes runs deterministic and replayable.
The obvious shape -- "a log of decided values at increasing heights" -- cannot express three of the algorithms we target, so we do not use it. The core is fork choice over a vertex DAG plus a finality predicate:
:commit is revocable -- but by ONE algorithm, and this paragraph used to
claim otherwise. It said Raft needs revocation too, because a new leader makes
followers truncate a conflicting suffix; that suffix is UNCOMMITTED, and
discarding an uncommitted entry is not revoking a decision. It said Bullshark
needs it, because it retroactively commits earlier anchors; that is a
multi-vertex commit, not a revert. And it called Tendermint the degenerate
case.
Seven implementations later the capability declarations say what is true:
Raft, Tendermint, SCP, Bullshark and Snowman declare no :revert at all.
Nakamoto is the only one, and open membership is exactly why. Absolute
finality is the common case and reorgs are the exception -- the reverse of
what was assumed when the DAG shape was chosen.
The DAG shape survives that correction, because it was never justified by revocation alone: Bullshark's ordering is over a certificate DAG, Nakamoto's fork choice is over a block tree, and Snowman's is over a block tree with a trie inside each node. A height-indexed log expresses none of the three.
Note also that revocability and PROBABILISTIC finality are different axes,
which is not the intuition. Snowman's safety is parameterised and its
acceptance is absorbing: a consumer needs an assumption about k, alpha and
beta, and no code for a decision being taken back. Only the second belongs in
a type, which is what capabilities encodes.
println, no clock, no RNG, no I/O inside init or step.geheimnis Ed25519 verification returns a
channel and cannot be called from a pure function. Events therefore arrive
already authenticated, carrying :verified-by. (Hashing is different:
hasch/sha256 is synchronous on both platforms, so proof-of-work checks
CAN run inline.)The core consensus abstraction: a node is a pure state machine. A `Node` maps (state, input) to a new state plus a vector of *effects* -- data describing side effects for a runtime or simulator to interpret. No algorithm here performs I/O, reads a clock, or draws a random number; all three are effects, which is what makes runs deterministic and replayable. ## Why the core is a DAG and not a log The obvious shape -- "a log of decided values at increasing heights" -- cannot express three of the algorithms we target, so we do not use it. The core is fork choice over a vertex DAG plus a finality predicate: - vertices carry parent links and a payload; - a fork-choice rule maps known vertices and votes to the current head; - a finality rule identifies the irreversible prefix; - an eligibility rule says who may extend, and with what weight. `:commit` is *revocable* -- but by ONE algorithm, and this paragraph used to claim otherwise. It said Raft needs revocation too, because a new leader makes followers truncate a conflicting suffix; that suffix is UNCOMMITTED, and discarding an uncommitted entry is not revoking a decision. It said Bullshark needs it, because it retroactively commits earlier anchors; that is a multi-vertex commit, not a revert. And it called Tendermint the degenerate case. Seven implementations later the capability declarations say what is true: Raft, Tendermint, SCP, Bullshark and Snowman declare no `:revert` at all. Nakamoto is the only one, and open membership is exactly why. Absolute finality is the common case and reorgs are the exception -- the reverse of what was assumed when the DAG shape was chosen. The DAG shape survives that correction, because it was never justified by revocation alone: Bullshark's ordering is over a certificate DAG, Nakamoto's fork choice is over a block tree, and Snowman's is over a block tree with a trie inside each node. A height-indexed log expresses none of the three. Note also that revocability and PROBABILISTIC finality are different axes, which is not the intuition. Snowman's safety is parameterised and its acceptance is absorbing: a consumer needs an assumption about k, alpha and beta, and no code for a decision being taken back. Only the second belongs in a type, which is what `capabilities` encodes. ## Purity rules 1. No `println`, no clock, no RNG, no I/O inside `init` or `step`. 2. Signature verification happens OUTSIDE the state machine. ClojureScript's Web Crypto is promise-based, so `geheimnis` Ed25519 verification returns a channel and cannot be called from a pure function. Events therefore arrive already authenticated, carrying `:verified-by`. (Hashing is different: `hasch/sha256` is synchronous on both platforms, so proof-of-work checks CAN run inline.) 3. Effects are values. Two runs with the same inputs produce equal effects.
Park an input whose dependency we do not hold; re-process it when we do.
Six reference audits found the same defect in four algorithms, and it is the single most common way this codebase strands a node:
:want, and
never revisits it -- so it never votes for that header even once the
parents land;Every one is the same shape: something arrived that REFERENCES what we lack,
we could not use it, and we threw it away. The references all do the opposite
and all in the same way -- avalanchego SendGets the block and
blocked.Schedules the vote against it (engine.go:709-722, :396-415);
Narwhal queues WaiterMessage::SyncParents carrying the header itself and
loops it back through process_header (header_waiter.rs:239-277,
core.rs:644); btcd parks the orphan, requests GetOrphanRoot, and
reconsiders on arrival (netsync/manager.go:788-794).
The protocol already has everything needed. send-to asks the peer that
referenced the thing -- the one peer we know has it -- and deliver-self
hands a parked input back to the node at the next tick, which is exactly
Narwhal's loop-back. What was missing was not a capability but the BOOKKEEPING
between them, written once instead of four subtly different times.
Nakamoto's orphan pool does this correctly and was fuzzed over 60 random branch trees without stranding a node inside itself, so this is its shape rather than a fresh invention: park keyed by the DEPENDENCY, evict oldest by ARRIVAL SEQUENCE rather than by timestamp (whole-second clocks tie, and breaking a tie by id or by map order makes eviction arbitrary -- a header delivered child-first could evict its own parent one message later), and expire on age.
One thing it does that Nakamoto did not: park is idempotent on the item id.
btcd checks if _, exists := b.orphans[hash]; exists BEFORE adding
(process.go:162-166); Nakamoto did not, so a re-delivered orphan re-ran
eviction and re-stamped its arrival sequence -- measurably evicting a
legitimate orphan to make room for something already held, and defeating the
FIFO property the sequence counter exists to establish. Rotating through
already-held headers kept the pool one below capacity indefinitely. Fixed
here by construction, for every user.
It does not decide when to ask, whom to ask, or what a request looks like: those are the algorithm's, and differ. It holds inputs and hands them back.
Park an input whose dependency we do not hold; re-process it when we do. ## The gap this closes Six reference audits found the same defect in four algorithms, and it is the single most common way this codebase strands a node: - round-robin answered a peer behind us with silence; - Bullshark drops a header whose parents are missing, fires one `:want`, and never revisits it -- so it never votes for that header even once the parents land; - Snowman drops a chit naming a block it does not hold, and nothing ever requests the block; - Tendermint keeps the first proposal it saw and cannot replace it, so a node holding a full quorum of precommits for a different value waits forever. Every one is the same shape: something arrived that REFERENCES what we lack, we could not use it, and we threw it away. The references all do the opposite and all in the same way -- avalanchego `SendGet`s the block and `blocked.Schedule`s the vote against it (`engine.go:709-722`, `:396-415`); Narwhal queues `WaiterMessage::SyncParents` carrying the header itself and loops it back through `process_header` (`header_waiter.rs:239-277`, `core.rs:644`); btcd parks the orphan, requests `GetOrphanRoot`, and reconsiders on arrival (`netsync/manager.go:788-794`). ## Why this is a helper and not a new effect The protocol already has everything needed. `send-to` asks the peer that referenced the thing -- the one peer we know has it -- and `deliver-self` hands a parked input back to the node at the next tick, which is exactly Narwhal's loop-back. What was missing was not a capability but the BOOKKEEPING between them, written once instead of four subtly different times. ## Generalised from the one that was already right Nakamoto's orphan pool does this correctly and was fuzzed over 60 random branch trees without stranding a node inside itself, so this is its shape rather than a fresh invention: park keyed by the DEPENDENCY, evict oldest by ARRIVAL SEQUENCE rather than by timestamp (whole-second clocks tie, and breaking a tie by id or by map order makes eviction arbitrary -- a header delivered child-first could evict its own parent one message later), and expire on age. One thing it does that Nakamoto did not: `park` is idempotent on the item id. btcd checks `if _, exists := b.orphans[hash]; exists` BEFORE adding (`process.go:162-166`); Nakamoto did not, so a re-delivered orphan re-ran eviction and re-stamped its arrival sequence -- measurably evicting a legitimate orphan to make room for something already held, and defeating the FIFO property the sequence counter exists to establish. Rotating through already-held headers kept the pool one below capacity indefinitely. Fixed here by construction, for every user. ## What this does NOT do It does not decide when to ask, whom to ask, or what a request looks like: those are the algorithm's, and differ. It holds inputs and hands them back.
Weighted round-robin proposer selection.
Ported from CometBFT (types/validator_set.go:131-250, read Aug 2026) and
spec/consensus/proposer-selection.md. Kept OUT of the consensus state
machine on purpose: it is a total function of (priorities, powers, round), so
it can be tested and reasoned about without a node, and an algorithm that
wants a different eligibility rule can swap it.
Per selection run:
max - min > 2 * totalPower, divide every priority by
ceil(diff / 2*totalPower), bounding the priority window;times times: increment every validator by its voting power,
elect the argmax, then demote the winner by the total power.Note the implementation does scale+center ONCE, before the loop, while the
spec document's pseudocode does it per run. We follow the implementation,
because it is what actually produced every chain's history; the difference
shows up only when times > 1, i.e. when skipping rounds.
center must floor-divide, not truncate. CometBFT computes the average
with big.Int.Div, which is Euclidean (rounds toward -infinity), NOT Quo
(which truncates toward zero). Clojure's quot truncates, so using it here
would diverge from CometBFT exactly when the priority sum is negative --
which is the normal case, since the winner is demoted by the total power
every round. rescale on the other hand uses Go's / on int64, which DOES
truncate toward zero, so quot is correct there. Two divisions, two
different roundings, ten lines apart.
Ties are broken by validator id, ascending. CometBFT compares raw address
bytes (types/validator.go:76). We compare ids with clojure.core/compare,
which requires the ids to be mutually comparable -- keywords, strings or
numbers, not a mixture.
Weighted round-robin proposer selection.
Ported from CometBFT (`types/validator_set.go:131-250`, read Aug 2026) and
`spec/consensus/proposer-selection.md`. Kept OUT of the consensus state
machine on purpose: it is a total function of (priorities, powers, round), so
it can be tested and reasoned about without a node, and an algorithm that
wants a different eligibility rule can swap it.
## The algorithm
Per selection run:
1. **scale** -- if `max - min > 2 * totalPower`, divide every priority by
`ceil(diff / 2*totalPower)`, bounding the priority window;
2. **center** -- subtract the mean, so priorities stay near zero and cannot
drift;
3. repeat `times` times: **increment** every validator by its voting power,
**elect** the argmax, then **demote** the winner by the total power.
Note the implementation does scale+center ONCE, before the loop, while the
spec document's pseudocode does it per run. We follow the implementation,
because it is what actually produced every chain's history; the difference
shows up only when `times > 1`, i.e. when skipping rounds.
## Two portability hazards, both real
**`center` must floor-divide, not truncate.** CometBFT computes the average
with `big.Int.Div`, which is Euclidean (rounds toward -infinity), NOT `Quo`
(which truncates toward zero). Clojure's `quot` truncates, so using it here
would diverge from CometBFT exactly when the priority sum is negative --
which is the normal case, since the winner is demoted by the total power
every round. `rescale` on the other hand uses Go's `/` on int64, which DOES
truncate toward zero, so `quot` is correct there. Two divisions, two
different roundings, ten lines apart.
**Ties are broken by validator id, ascending.** CometBFT compares raw address
bytes (`types/validator.go:76`). We compare ids with `clojure.core/compare`,
which requires the ids to be mutually comparable -- keywords, strings or
numbers, not a mixture.Validator set changes: the part that is the same for every algorithm.
Written after reading four reference implementations (CometBFT/tendermint-go, etcd-raft, Narwhal, stellar-core). They gave four different answers, and this namespace is deliberately only the intersection.
A set change decomposes into a TRIGGER, a TRANSITION, and an ACTIVATION.
The trigger generalises completely: a decided value may carry updates, so the decision about who is a validator is made by the same consensus that orders everything else. Every reference that supports the feature does it this way, including Narwhal -- whose epoch predicate is a pure function of the committed sequence even though nothing else about its mechanism generalises.
The transition is this namespace: (config, updates) -> config', pure and
total. Also common to all of them.
The ACTIVATION does not generalise, and pretending otherwise would be the error. It stays with each algorithm:
Tendermint +2 heights. The offset decomposes -- one is forced, because a
header is built from PRE-execution state, so the result of
deciding H cannot appear in H's own header; the second buys
pre-commitment, letting a light client verify adjacent headers
by hash chain alone. N=1 suffices without light clients.
Raft at APPLY, with at most one update un-applied at a time. etcd
measures that against applied, not committed, because its
active config is its applied config and applied trails commit
by an unbounded amount. Where decide == apply -- which is urd's
case, step being pure and its state BEING the applied state
-- the two-phase joint transition collapses to two consecutive
decisions at a fixed offset.
Bullshark NOT THIS MECHANISM. order-anchors re-derives who led
HISTORICAL rounds using the CURRENT committee, so a change
silently rewrites which anchors led the past. Narwhal resolves
this by destroying the DAG and rebuilding from a new genesis.
Epochs, or certificates carrying a committee digest -- a
different protocol, not a configuration of this one.
SCP NOT APPLICABLE. There is no agreed set: a quorum set is local
configuration, nodes are designed to disagree, and in
stellar-core the only mutator is dead code with zero callers.
Both chain references use a diff -- CometBFT's ValidatorUpdate{pub_key, power} with power 0 meaning remove, etcd's ConfChangeSingle. A whole-set
replacement is easier to validate and loses something worth keeping: with a
diff, two proposals that touch different validators are visibly independent,
and the application says what it MEANT rather than what it computed.
The cost is that a diff can be invalid in ways a replacement cannot -- naming a validator twice, removing one that is not there, emptying the set -- so every one of those is checked below and named.
CometBFT issue #3181: proposer selection depended on the ORDER of updates in
the ABCI response, so two honest nodes given identical input computed
different proposer priorities. The fix (cce4d21cc, consensus-breaking) was
to treat updates as a SET.
That is the single most important thing to get right here, because the
failure is silent and the input is identical on both nodes -- no message is
lost, nothing is malformed, and the two simply disagree about who proposes
next. apply-updates therefore canonicalises before doing anything, and
same-result-whatever-the-order in the tests drives it.
Every function here returns data. An invalid update yields {:error ...}
rather than throwing, because what to do about it is an algorithm-level
decision with two defensible answers -- halt (CometBFT panics, and since the
input is identical everywhere all nodes halt identically, which is a stall
rather than a fork) or skip. What is NOT defensible is for two nodes to
classify the same update differently, so validity here depends on nothing but
the config and the updates.
etcd learned the harder version of this: validating at PROPOSE time, against
whatever config happened to be active, caused real data corruption in
CockroachDB because the basis was not stable. Hence DisableConfChangeValidation
and the caveat that the checks are best-effort. Validation here is a function
of the config the update is applied TO, which is the stable basis.
Validator set changes: the part that is the same for every algorithm.
Written after reading four reference implementations (CometBFT/tendermint-go,
etcd-raft, Narwhal, stellar-core). They gave four different answers, and this
namespace is deliberately only the intersection.
## What generalises, and what does not
A set change decomposes into a TRIGGER, a TRANSITION, and an ACTIVATION.
The trigger generalises completely: a decided value may carry updates, so the
decision about who is a validator is made by the same consensus that orders
everything else. Every reference that supports the feature does it this way,
including Narwhal -- whose epoch predicate is a pure function of the committed
sequence even though nothing else about its mechanism generalises.
The transition is this namespace: `(config, updates) -> config'`, pure and
total. Also common to all of them.
The ACTIVATION does not generalise, and pretending otherwise would be the
error. It stays with each algorithm:
Tendermint +2 heights. The offset decomposes -- one is forced, because a
header is built from PRE-execution state, so the result of
deciding H cannot appear in H's own header; the second buys
pre-commitment, letting a light client verify adjacent headers
by hash chain alone. N=1 suffices without light clients.
Raft at APPLY, with at most one update un-applied at a time. etcd
measures that against `applied`, not `committed`, because its
active config is its applied config and applied trails commit
by an unbounded amount. Where decide == apply -- which is urd's
case, `step` being pure and its state BEING the applied state
-- the two-phase joint transition collapses to two consecutive
decisions at a fixed offset.
Bullshark NOT THIS MECHANISM. `order-anchors` re-derives who led
HISTORICAL rounds using the CURRENT committee, so a change
silently rewrites which anchors led the past. Narwhal resolves
this by destroying the DAG and rebuilding from a new genesis.
Epochs, or certificates carrying a committee digest -- a
different protocol, not a configuration of this one.
SCP NOT APPLICABLE. There is no agreed set: a quorum set is local
configuration, nodes are designed to disagree, and in
stellar-core the only mutator is dead code with zero callers.
## Why a sparse diff rather than a whole set
Both chain references use a diff -- CometBFT's `ValidatorUpdate{pub_key,
power}` with power 0 meaning remove, etcd's `ConfChangeSingle`. A whole-set
replacement is easier to validate and loses something worth keeping: with a
diff, two proposals that touch different validators are visibly independent,
and the application says what it MEANT rather than what it computed.
The cost is that a diff can be invalid in ways a replacement cannot -- naming
a validator twice, removing one that is not there, emptying the set -- so
every one of those is checked below and named.
## Order independence is a SAFETY property, not tidiness
CometBFT issue #3181: proposer selection depended on the ORDER of updates in
the ABCI response, so two honest nodes given identical input computed
different proposer priorities. The fix (`cce4d21cc`, consensus-breaking) was
to treat updates as a SET.
That is the single most important thing to get right here, because the
failure is silent and the input is identical on both nodes -- no message is
lost, nothing is malformed, and the two simply disagree about who proposes
next. `apply-updates` therefore canonicalises before doing anything, and
`same-result-whatever-the-order` in the tests drives it.
## Rejection must be deterministic, and it is the CALLER's to act on
Every function here returns data. An invalid update yields `{:error ...}`
rather than throwing, because what to do about it is an algorithm-level
decision with two defensible answers -- halt (CometBFT panics, and since the
input is identical everywhere all nodes halt identically, which is a stall
rather than a fork) or skip. What is NOT defensible is for two nodes to
classify the same update differently, so validity here depends on nothing but
the config and the updates.
etcd learned the harder version of this: validating at PROPOSE time, against
whatever config happened to be active, caused real data corruption in
CockroachDB because the basis was not stable. Hence `DisableConfChangeValidation`
and the caveat that the checks are best-effort. Validation here is a function
of the config the update is applied TO, which is the stable basis.A deterministic, portable pseudo-random generator.
java.util.Random is not available in ClojureScript, and even where a host
PRNG exists the two platforms would not agree bit-for-bit -- which would mean a
simulation run that fails on the JVM could not be reproduced in the browser.
So we carry our own.
This is xorshift32: three shift/xor rounds on a 32-bit word. It is fast, tiny,
and has a period of 2^32-1, which is far more than a simulation needs. It is
emphatically NOT cryptographic -- use urd.crypto for anything that must
resist an adversary. This exists only so that a failing schedule is
reproducible from its seed.
ClojureScript's bit operations coerce to 32-bit SIGNED integers; Clojure's act
on 64-bit longs. Every operation here therefore normalizes back to an unsigned
32-bit VALUE with mask32, so both platforms produce identical sequences. The
tests pin a known sequence, and rng-agrees-across-platforms in
urd.consensus.portability-test is the one that must be run under BOTH.
bit-and alone is not enough, and this was a real bug: in ClojureScript
(bit-and 0xFFFFFFFF 0xFFFFFFFF) is -1, not 4294967295. The bit PATTERN is
right but the NUMBER is negative, and the two places that treat the word as a
number rather than as bits -- next-int's rejection bound and its mod --
then take different branches. Measured before the fix, next-int with seed 7
and bound 100 gave [83 55 7 45 67 56 62 87] on the JVM and
[83 55 11 49 71 56 62 87] under Node. So the simulator's message delays, drop
decisions and peer sampling all differed between platforms, which is precisely
what this namespace exists to prevent. The extra unsigned-bit-shift-right
by zero is a no-op on the JVM and is the standard >>> 0 coercion to an
unsigned value in JavaScript.
The generator is a value, not a mutable object: every draw returns
[value next-rng]. Threading it explicitly is what lets a simulation be
replayed, forked, or stepped backwards.
A deterministic, portable pseudo-random generator. `java.util.Random` is not available in ClojureScript, and even where a host PRNG exists the two platforms would not agree bit-for-bit -- which would mean a simulation run that fails on the JVM could not be reproduced in the browser. So we carry our own. This is xorshift32: three shift/xor rounds on a 32-bit word. It is fast, tiny, and has a period of 2^32-1, which is far more than a simulation needs. It is emphatically NOT cryptographic -- use `urd.crypto` for anything that must resist an adversary. This exists only so that a failing schedule is reproducible from its seed. ## Portability ClojureScript's bit operations coerce to 32-bit SIGNED integers; Clojure's act on 64-bit longs. Every operation here therefore normalizes back to an unsigned 32-bit VALUE with `mask32`, so both platforms produce identical sequences. The tests pin a known sequence, and `rng-agrees-across-platforms` in `urd.consensus.portability-test` is the one that must be run under BOTH. `bit-and` alone is not enough, and this was a real bug: in ClojureScript `(bit-and 0xFFFFFFFF 0xFFFFFFFF)` is -1, not 4294967295. The bit PATTERN is right but the NUMBER is negative, and the two places that treat the word as a number rather than as bits -- `next-int`'s rejection bound and its `mod` -- then take different branches. Measured before the fix, `next-int` with seed 7 and bound 100 gave [83 55 7 45 67 56 62 87] on the JVM and [83 55 11 49 71 56 62 87] under Node. So the simulator's message delays, drop decisions and peer sampling all differed between platforms, which is precisely what this namespace exists to prevent. The extra `unsigned-bit-shift-right` by zero is a no-op on the JVM and is the standard `>>> 0` coercion to an unsigned value in JavaScript. ## Purity The generator is a value, not a mutable object: every draw returns `[value next-rng]`. Threading it explicitly is what lets a simulation be replayed, forked, or stepped backwards.
A real-network runtime for urd.consensus.node.
The simulator interprets a node's effects against logical time and an
in-memory network; this interprets the SAME effects against core.async, a
wall clock and a ConsensusNetwork. One algorithm, two interpreters, and the
algorithm cannot tell them apart -- which is the point, and is what makes a
schedule that fails in the simulator meaningful about a deployment.
ConsensusAlgorithm protocolThis used to drive urd.consensus.state-machine, an earlier version of
node. Three things changed, and each was a layering fault rather than a
translation:
The effect vocabulary was one algorithm's, generalised by accident.
A supposedly generic runtime knew request-missing-proposal,
request-state-sync, request-votes, broadcast-finalization,
add-own-vote and trigger-next-round by name -- every one of them
round-robin's. They are ordinary messages, a vote, and a timer; the
algorithm spells them that way now and this interprets the thirteen
effects the protocol actually defines.
add-own-vote meant a node's own vote lived in the runtime's log
rather than in the node's state. A vote outside the state machine is a
vote the state machine cannot count.
Timers were wall-clock milliseconds. A node now asks for TICKS and
:tick-ms converts. That keeps the algorithm's contract identical under
both interpreters: logical time is what makes a failing schedule
reproducible, and an algorithm whose timeouts are milliseconds cannot be
replayed at all.
ConsensusNetwork is topic pubsub with no unicast, so send-to is carried on
a :direct topic with a :to field and filtered on receipt. That is honest
rather than clever: the message reaches every peer and all but one drop it, so
send-to here costs what a broadcast costs. Kabel's pubsub is the constraint;
a transport with real unicast should override this.
A real-network runtime for `urd.consensus.node`. The simulator interprets a node's effects against logical time and an in-memory network; this interprets the SAME effects against core.async, a wall clock and a `ConsensusNetwork`. One algorithm, two interpreters, and the algorithm cannot tell them apart -- which is the point, and is what makes a schedule that fails in the simulator meaningful about a deployment. ## Ported from the legacy `ConsensusAlgorithm` protocol This used to drive `urd.consensus.state-machine`, an earlier version of `node`. Three things changed, and each was a layering fault rather than a translation: 1. **The effect vocabulary was one algorithm's, generalised by accident.** A supposedly generic runtime knew `request-missing-proposal`, `request-state-sync`, `request-votes`, `broadcast-finalization`, `add-own-vote` and `trigger-next-round` by name -- every one of them round-robin's. They are ordinary messages, a vote, and a timer; the algorithm spells them that way now and this interprets the thirteen effects the protocol actually defines. 2. **`add-own-vote` meant a node's own vote lived in the runtime's log rather than in the node's state.** A vote outside the state machine is a vote the state machine cannot count. 3. **Timers were wall-clock milliseconds.** A node now asks for TICKS and `:tick-ms` converts. That keeps the algorithm's contract identical under both interpreters: logical time is what makes a failing schedule reproducible, and an algorithm whose timeouts are milliseconds cannot be replayed at all. ## Unicast over a broadcast transport `ConsensusNetwork` is topic pubsub with no unicast, so `send-to` is carried on a `:direct` topic with a `:to` field and filtered on receipt. That is honest rather than clever: the message reaches every peer and all but one drop it, so `send-to` here costs what a broadcast costs. Kabel's pubsub is the constraint; a transport with real unicast should override this.
Schedules as DATA, so a failing run shrinks to a minimal counterexample.
Every property test in this project generated a seed and handed it to the simulator. test.check then dutifully shrank the seed -- and a numerically smaller seed produces a completely unrelated schedule, not a simpler one. So a failure reported "seed 47283 fails" and nothing more: no minimal case, no reduction, no way to see which fault mattered. Shrinking was structurally useless, which is most of the value of property testing.
A schedule is instead an ordered vector of steps:
[[:tick 3]
[:crash :b]
[:tick 5]
[:partition [#{:a :b} #{:c :d}]]
[:tick 10]
[:heal]
[:tick 20]]
test.check shrinks a vector by dropping elements and simplifying each one, so it will remove the partition, then the crash, then shorten the ticks, and hand back the smallest schedule that still fails. That is a counterexample you can read.
Message delays and duplication remain RNG-driven, because enumerating them as data would make schedules enormous without making counterexamples clearer. The faults that a human reasons about -- who crashed, who was partitioned from whom, when -- are data. Both are reproducible; only the second shrinks.
A schedule with no fault steps is just "run for n ticks", so this subsumes the plain case rather than replacing it.
Schedules as DATA, so a failing run shrinks to a minimal counterexample.
## The problem this solves
Every property test in this project generated a *seed* and handed it to the
simulator. test.check then dutifully shrank the seed -- and a numerically
smaller seed produces a completely unrelated schedule, not a simpler one. So a
failure reported "seed 47283 fails" and nothing more: no minimal case, no
reduction, no way to see which fault mattered. Shrinking was structurally
useless, which is most of the value of property testing.
A schedule is instead an ordered vector of steps:
[[:tick 3]
[:crash :b]
[:tick 5]
[:partition [#{:a :b} #{:c :d}]]
[:tick 10]
[:heal]
[:tick 20]]
test.check shrinks a vector by dropping elements and simplifying each one, so
it will remove the partition, then the crash, then shorten the ticks, and hand
back the smallest schedule that still fails. That is a counterexample you can
read.
## What is still drawn from the seed
Message delays and duplication remain RNG-driven, because enumerating them as
data would make schedules enormous without making counterexamples clearer. The
faults that a human reasons about -- who crashed, who was partitioned from
whom, when -- are data. Both are reproducible; only the second shrinks.
A schedule with no fault steps is just "run for n ticks", so this subsumes
the plain case rather than replacing it.The double-sign guard: the second durability barrier from the protocol design, kept deliberately separate from the write-ahead log.
CometBFT keeps FilePVLastSignState{Height,Round,Step} in an atomically
rewritten file distinct from the WAL (privval/file.go:74-83), because it is
the one thing that must survive even a WAL wipe. A validator that loses its
WAL can safely re-derive everything else; a validator that loses this file
can be slashed.
may-sign below is the function EMITTED by the ansatz proof in
proofs/may_sign.clj, which proves:
no-double-sign -- (may-sign h r s h r s) = false same-round-requires-a-later-step lower-height-is-never-signable lower-round-at-same-height-not-signable
Ansatz is JVM-only and urd is portable, so the proof is checked separately and the erased definition ships here. Do not edit one without the other.
CometBFT writes this rule as four clauses (spec/consensus/signing.md:216-223)
only because its wire encoding is not order-compatible: proposal is 0x20 = 32,
numerically ABOVE prevote = 1. Re-encoded in semantic order the four clauses
collapse to "lexicographically greater", and the whole property becomes
"a strict order has no repeats".
The double-sign guard: the second durability barrier from the protocol
design, kept deliberately separate from the write-ahead log.
CometBFT keeps `FilePVLastSignState{Height,Round,Step}` in an atomically
rewritten file distinct from the WAL (`privval/file.go:74-83`), because it is
the one thing that must survive even a WAL wipe. A validator that loses its
WAL can safely re-derive everything else; a validator that loses this file
can be slashed.
## The predicate is machine-checked
`may-sign` below is the function EMITTED by the ansatz proof in
`proofs/may_sign.clj`, which proves:
no-double-sign -- (may-sign h r s h r s) = false
same-round-requires-a-later-step
lower-height-is-never-signable
lower-round-at-same-height-not-signable
Ansatz is JVM-only and urd is portable, so the proof is checked separately
and the erased definition ships here. Do not edit one without the other.
CometBFT writes this rule as four clauses (`spec/consensus/signing.md:216-223`)
only because its wire encoding is not order-compatible: proposal is 0x20 = 32,
numerically ABOVE prevote = 1. Re-encoded in semantic order the four clauses
collapse to "lexicographically greater", and the whole property becomes
"a strict order has no repeats".A deterministic discrete-event simulator for consensus algorithms.
This is the primary way algorithms are tested. Everything that could vary
between runs -- time, randomness, message delay, message loss, crash points --
is drawn from an explicit seed and threaded through pure functions, so a
failing run is fully reproducible from (seed, config) and can be replayed,
forked, or stepped one tick at a time.
The simulator is itself a value. advance takes a sim and returns a sim; no
atoms, no threads, no wall clock. That is what makes shrinking work: a
test.check failure hands you a seed, and the seed hands you the exact history.
A tick is the unit. Timers are armed for a number of ticks, message delays are a number of ticks. Nothing consults a real clock, so a timeout-dependent bug reproduces identically on a fast machine, a slow machine, and in a browser.
Map iteration order is not guaranteed to be stable across platforms, so anywhere order could affect the result -- delivering to peers, breaking ties -- we sort explicitly. Where a collection is drawn from, we sort before sampling. Violating this would make a run irreproducible in exactly the cases that matter most.
A deterministic discrete-event simulator for consensus algorithms. This is the primary way algorithms are tested. Everything that could vary between runs -- time, randomness, message delay, message loss, crash points -- is drawn from an explicit seed and threaded through pure functions, so a failing run is fully reproducible from `(seed, config)` and can be replayed, forked, or stepped one tick at a time. The simulator is itself a value. `advance` takes a sim and returns a sim; no atoms, no threads, no wall clock. That is what makes shrinking work: a test.check failure hands you a seed, and the seed hands you the exact history. ## Time is logical A tick is the unit. Timers are armed for a number of ticks, message delays are a number of ticks. Nothing consults a real clock, so a timeout-dependent bug reproduces identically on a fast machine, a slow machine, and in a browser. ## Determinism rules Map iteration order is not guaranteed to be stable across platforms, so anywhere order could affect the result -- delivering to peers, breaking ties -- we sort explicitly. Where a collection is drawn from, we sort before sampling. Violating this would make a run irreproducible in exactly the cases that matter most.
Durable storage behind the persist-then effect.
Very little, deliberately. A store lands write RECORDS in order and hands them back on restart. It never interprets a key.
That division is forced by the shape of what the algorithms write. Look at
the six of them together and :writes carries three different disciplines
under one map:
:hard-state, SCP's :scp,
Tendermint's :last-signed;:entries, Tendermint's :wal;[:cert id], Nakamoto's
[:header id].A store that tried to honour all three would need to know which keys mean
what, which is to say it would need a copy of each algorithm's storage
schema. So it knows none of them. It keeps the ordered log; the ALGORITHM
replays it in init and decides what a key means. truncate-from rides
along as replay metadata rather than as an instruction to truncate anything
here -- an append log cannot un-append, and a merged map cannot express a
truncation at all.
This is the simulator's contract, stated as a protocol. sim/restart hands a
node {:durable <merge of every landed write> :writes <ordered records>} and
the same two views appear here, so an algorithm's restart path cannot tell
the interpreters apart -- which is the property the whole two-interpreter
design rests on.
:durable is derived, not storedThe merged view is a fold over the log rather than a second key kept in step with it. Two keys would have to be written together and could not be, so every crash between them would leave a snapshot disagreeing with the log it summarises -- and the disagreement would surface only on the restart path, which is the one path that is hard to test and where being wrong is worst. One key has no such window.
A checkpoint replaces the retained log with records supplied by the algorithm. Writes, checkpoints and subsequent reads must observe issue order. A backend can discard older records once the replacement is durable.
Durable storage behind the `persist-then` effect.
## What a store is responsible for, and what it is not
Very little, deliberately. A store lands write RECORDS in order and hands
them back on restart. It never interprets a key.
That division is forced by the shape of what the algorithms write. Look at
the six of them together and `:writes` carries three different disciplines
under one map:
- **snapshot**, overwrite the key -- Raft's `:hard-state`, SCP's `:scp`,
Tendermint's `:last-signed`;
- **append**, extend a log -- Raft's `:entries`, Tendermint's `:wal`;
- **content-keyed put** -- Bullshark's `[:cert id]`, Nakamoto's
`[:header id]`.
A store that tried to honour all three would need to know which keys mean
what, which is to say it would need a copy of each algorithm's storage
schema. So it knows none of them. It keeps the ordered log; the ALGORITHM
replays it in `init` and decides what a key means. `truncate-from` rides
along as replay metadata rather than as an instruction to truncate anything
here -- an append log cannot un-append, and a merged map cannot express a
truncation at all.
This is the simulator's contract, stated as a protocol. `sim/restart` hands a
node `{:durable <merge of every landed write> :writes <ordered records>}` and
the same two views appear here, so an algorithm's restart path cannot tell
the interpreters apart -- which is the property the whole two-interpreter
design rests on.
## `:durable` is derived, not stored
The merged view is a fold over the log rather than a second key kept in step
with it. Two keys would have to be written together and could not be, so
every crash between them would leave a snapshot disagreeing with the log it
summarises -- and the disagreement would surface only on the restart path,
which is the one path that is hard to test and where being wrong is worst.
One key has no such window.
A checkpoint replaces the retained log with records supplied by the
algorithm. Writes, checkpoints and subsequent reads must observe issue
order. A backend can discard older records once the replacement is durable.A DurableStore on konserve.
konserve.core/append writes the element and a pointer and nothing else,
which is what a write-ahead log wants: the cost of landing a record does not
grow with the number of records already landed. reduce-log folds it back on
restart. Both views the protocol owes a restarting node come from that one
log -- the ordered records directly, and the merged map as a fold -- so there
is no second key to keep in step with it.
append is a read-modify-write on the list pointer, so two in flight against
the same key interleave. The runtime issues writes from its event loop
without awaiting the non-durable ones, so two CAN be in flight. Every write
therefore goes through a single go-loop, one at a time.
Measured rather than assumed. Removing the writer and appending directly, forty writes issued without awaiting came back in the order
4 2 9 10 11 7 14 13 15 16 18 19 17 21 22 24 3 25 23 5 0 6 1 30 ...
All forty records were still there -- this is not, at least against the
in-memory store, a loss bug. It is an ORDERING bug, and that is bad enough
twice over. truncate-from replay depends on log order being issue order:
records applied out of order resurrect entries a later truncation dropped.
And the merged view is a fold over the log, so it takes its value from
whichever write happens to land last -- in that run {:n 35} where the node
had written {:n 39}. A restarting Raft would come back with a stale term
it never held.
This wraps a store you have already connected rather than connecting one, so
it works against a filestore on the JVM and IndexedDB in the browser without
this namespace knowing which. connect-fs-store! below is a JVM convenience,
not the seam.
Note that konserve.filestore fsyncs every blob by default
(:sync-blob? true), so a record marked :durable? false is still written
through to disk here. That is stronger than asked for, never weaker, and the
distinction that survives is the one the runtime acts on: a durable write's
gated effects wait for the disk and a buffered one's do not.
A `DurableStore` on konserve.
## Why konserve's append log rather than a key per write
`konserve.core/append` writes the element and a pointer and nothing else,
which is what a write-ahead log wants: the cost of landing a record does not
grow with the number of records already landed. `reduce-log` folds it back on
restart. Both views the protocol owes a restarting node come from that one
log -- the ordered records directly, and the merged map as a fold -- so there
is no second key to keep in step with it.
## Writes are serialized, and this is not paranoia
`append` is a read-modify-write on the list pointer, so two in flight against
the same key interleave. The runtime issues writes from its event loop
without awaiting the non-durable ones, so two CAN be in flight. Every write
therefore goes through a single go-loop, one at a time.
Measured rather than assumed. Removing the writer and appending directly,
forty writes issued without awaiting came back in the order
4 2 9 10 11 7 14 13 15 16 18 19 17 21 22 24 3 25 23 5 0 6 1 30 ...
All forty records were still there -- this is not, at least against the
in-memory store, a loss bug. It is an ORDERING bug, and that is bad enough
twice over. `truncate-from` replay depends on log order being issue order:
records applied out of order resurrect entries a later truncation dropped.
And the merged view is a fold over the log, so it takes its value from
whichever write happens to land last -- in that run `{:n 35}` where the node
had written `{:n 39}`. A restarting Raft would come back with a stale term
it never held.
## Portability
This wraps a store you have already connected rather than connecting one, so
it works against a filestore on the JVM and IndexedDB in the browser without
this namespace knowing which. `connect-fs-store!` below is a JVM convenience,
not the seam.
Note that `konserve.filestore` fsyncs every blob by default
(`:sync-blob? true`), so a record marked `:durable? false` is still written
through to disk here. That is stronger than asked for, never weaker, and the
distinction that survives is the one the runtime acts on: a durable write's
gated effects wait for the disk and a buffered one's do not.A tracing wrapper for any urd.consensus.node/Node.
avalanchego does exactly this: chains/manager.go builds its consensus and
then wraps it -- smcon.Trace(consensus, tracer) -- so tracing is a decorator
around the interface rather than calls scattered through the algorithm. The
same shape works here and buys three things:
Node, so they take a traced Node. That matters more than it
sounds: the simulator already had a :trace and the real runtime had
nothing, so every problem in the network layer had to be debugged by
starting a network, sleeping, and inspecting state -- which is guessing with
extra steps. A debugging affordance that exists in only one interpreter is
one you cannot use where the bugs are.One entry per step, with the input's type, the KINDS of effects that came
out, and a sequence number:
{:seq 41 :peer :b :in :message-received :out [:broadcast :set-timer]}
Kinds rather than whole effects, deliberately: a full effect log is enormous
and unreadable, and the question a trace has to answer first is always
"is this node receiving anything at all, and does it react?". Pass
:detail? true for the whole event and effect vector when the answer to that
is yes and the next question is why.
The entries go to an in-memory ring buffer, and optionally to :sink, a
function of one entry. Two different jobs:
the ring buffer is for TEST ASSERTIONS and post-hoc inspection -- the
simulator's own :trace is already used that way, and Bullshark's
revert-mismatch assertions depend on it;
the sink is for watching a live run. replikativ.logging is the natural
one, since it is a trove facade taking a namespaced keyword id for
structured filtering and is already the house style:
(trace/tracing node {:sink #(rlog/trace :urd.consensus/step %)})
It is not a dependency here. The trace should not require a logging backend to be useful, and which backend to depend on is a project decision rather than this namespace's.
This namespace carried a do-not-use-over-kabel warning for one commit. It was wrong. Traced over kabel, five validators produce 67 to 97 events each, receive messages, fire timers and commit -- the wrapper is transparent under both interpreters, as a decorator has to be.
What actually happened: the diagnostic built its nodes as (rr/create) with
NO validator set, and the runtime config carries neither :validator-set nor
:validators through to init, so every node came up with an empty set. The
first timer tick then reached get-proposer-id, which computes
(mod height (count validator-ids)) and divided by zero, and the exception
killed the event loop inside a go block where nothing surfaced it. Every node
showed exactly one traced event and then silence -- which reads precisely like
a wrapper that hangs.
Two lessons, and the second is the one worth keeping. An exception inside a core.async loop is invisible unless something reports it. And a tool built to diagnose a problem is itself untested code: the first output of a new instrument says as much about the instrument as about the system, and should be treated that way until it has been checked against a known-good control.
A tracing wrapper for any `urd.consensus.node/Node`.
## Why a wrapper and not instrumentation
avalanchego does exactly this: `chains/manager.go` builds its consensus and
then wraps it -- `smcon.Trace(consensus, tracer)` -- so tracing is a decorator
around the interface rather than calls scattered through the algorithm. The
same shape works here and buys three things:
- **No algorithm changes.** All seven implementations are traceable without
touching one of them.
- **It works under BOTH interpreters.** The simulator and the kabel runtime
take a `Node`, so they take a traced `Node`. That matters more than it
sounds: the simulator already had a `:trace` and the real runtime had
nothing, so every problem in the network layer had to be debugged by
starting a network, sleeping, and inspecting state -- which is guessing with
extra steps. A debugging affordance that exists in only one interpreter is
one you cannot use where the bugs are.
- **It composes with capabilities.** A wrapper reports what it wraps, exactly
as the test adversaries do.
## What it records
One entry per `step`, with the input's type, the KINDS of effects that came
out, and a sequence number:
{:seq 41 :peer :b :in :message-received :out [:broadcast :set-timer]}
Kinds rather than whole effects, deliberately: a full effect log is enormous
and unreadable, and the question a trace has to answer first is always
"is this node receiving anything at all, and does it react?". Pass
`:detail? true` for the whole event and effect vector when the answer to that
is yes and the next question is why.
## Backends
The entries go to an in-memory ring buffer, and optionally to `:sink`, a
function of one entry. Two different jobs:
- the ring buffer is for TEST ASSERTIONS and post-hoc inspection -- the
simulator's own `:trace` is already used that way, and Bullshark's
`revert-mismatch` assertions depend on it;
- the sink is for watching a live run. `replikativ.logging` is the natural
one, since it is a trove facade taking a namespaced keyword id for
structured filtering and is already the house style:
(trace/tracing node {:sink #(rlog/trace :urd.consensus/step %)})
It is not a dependency here. The trace should not require a logging backend
to be useful, and which backend to depend on is a project decision rather than
this namespace's.
## A false alarm, recorded because the shape recurs
This namespace carried a do-not-use-over-kabel warning for one commit. It
was wrong. Traced over kabel, five validators produce 67 to 97 events each,
receive messages, fire timers and commit -- the wrapper is transparent under
both interpreters, as a decorator has to be.
What actually happened: the diagnostic built its nodes as `(rr/create)` with
NO validator set, and the runtime config carries neither `:validator-set` nor
`:validators` through to `init`, so every node came up with an empty set. The
first timer tick then reached `get-proposer-id`, which computes
`(mod height (count validator-ids))` and divided by zero, and the exception
killed the event loop inside a go block where nothing surfaced it. Every node
showed exactly one traced event and then silence -- which reads precisely like
a wrapper that hangs.
Two lessons, and the second is the one worth keeping. An exception inside a
core.async loop is invisible unless something reports it. And a tool built to
diagnose a problem is itself untested code: the first output of a new
instrument says as much about the instrument as about the system, and should
be treated that way until it has been checked against a known-good control.Main API for creating and managing consensus validators.
A validator encapsulates:
This is the primary entry point for using the consensus system.
Main API for creating and managing consensus validators. A validator encapsulates: - Consensus state machine (the algorithm) - Network interface (simulation or real P2P) - Runtime (effect interpreter) - Storage (consensus log) This is the primary entry point for using the consensus system.
Byte codecs, delegated to geheimnis.
484 lines: a BouncyCastle Ed25519 with a ClojureScript branch that threw
"ED25519 not yet implemented", a snapshot-signing layer, a multi-signature
certificate layer, and a merkle root. Every one of them had ZERO callers --
each production mention was a comment or a docstring. The live signing path
is urd.consensus.auth and urd.consensus.attest, both on geheimnis, and has
been for some time.
It was not merely dead, it was a third implementation of something two other
libraries in this stack already had, and it is where a real bug lived:
base64->bytes used Closure's decodeStringToByteArray, which returns a
plain JS Array. Web Crypto refuses one, so no signature could verify on
ClojureScript. geheimnis's codec uses decodeStringToUint8Array and never
had the bug. That is the argument for deduplicating in one line.
The signature field moved from standard base64 to base64url, because that is
what geheimnis provides and because it is the better choice for a wire
format: URL- and filename-safe, unpadded, no +// to escape. Nothing is
deployed, so this is free now and would not be later.
Hex is unchanged, byte for byte -- verified against the old implementation
including negative bytes. That matters more than it sounds: bytes->hex of
a public key IS the attribute namespace a user owns, so a difference here
would silently re-address every datom anyone had written.
Byte codecs, delegated to geheimnis. ## What used to be here, and why it is gone 484 lines: a BouncyCastle Ed25519 with a ClojureScript branch that threw `"ED25519 not yet implemented"`, a snapshot-signing layer, a multi-signature certificate layer, and a merkle root. Every one of them had ZERO callers -- each production mention was a comment or a docstring. The live signing path is `urd.consensus.auth` and `urd.consensus.attest`, both on geheimnis, and has been for some time. It was not merely dead, it was a third implementation of something two other libraries in this stack already had, and it is where a real bug lived: `base64->bytes` used Closure's `decodeStringToByteArray`, which returns a plain JS Array. Web Crypto refuses one, so no signature could verify on ClojureScript. geheimnis's codec uses `decodeStringToUint8Array` and never had the bug. That is the argument for deduplicating in one line. ## Base64url, not base64 The signature field moved from standard base64 to base64url, because that is what geheimnis provides and because it is the better choice for a wire format: URL- and filename-safe, unpadded, no `+`/`/` to escape. Nothing is deployed, so this is free now and would not be later. Hex is unchanged, byte for byte -- verified against the old implementation including negative bytes. That matters more than it sounds: `bytes->hex` of a public key IS the attribute namespace a user owns, so a difference here would silently re-address every datom anyone had written.
The bytes a signature covers.
hasch/edn-hash callsurd signed hasch/edn-hash of a Clojure map. That works, and it was
deterministic across clj and cljs, but it makes every signature in the system
reachable only from Clojure: edn-hash is a replikativ-specific walk over
Clojure's own value model, and a Python or Rust client wanting to submit a
transaction would have to reimplement it -- correctly, including its handling
of sets, maps, keywords and ratios -- before it could sign anything at all.
That is a large and thankless amount of work to demand of a client, and every
bug in it is a client that silently cannot transact.
So a signature covers canonical CBOR instead. The message is
(boring/encode payload {:profile :canonical}): RFC 8949 core deterministic
encoding, which is a published specification with implementations in every
language anyone would write a client in. In Python the whole of it is
cbor2.dumps(payload, canonical=True) # note: see the caveat below
signing_key.sign(message) # ed25519, arbitrary length
:canonical SORTS map keys and set elements (boring.core/encode-all
says so explicitly). This matters more than it looks. Clojure's hash maps
and sets iterate in an order determined by hashes, and while that order is
stable for the same contents within one platform, it is not a property the
two platforms promise each other. Sorting removes the question.
Ed25519 signs arbitrary-length messages, so nothing needs pre-hashing. The bytes ARE the message, which is one less thing for a client to get wrong and one less place for a length-extension argument to be had.
Keywords encode as CBOR tag 39 (identifier) around the printed keyword
including its leading colon -- :chain is 39(":chain"). That is a
registered tag, not a boring extension, and kabel's own CBOR wire already
uses it, so a client that can talk to a kabel peer at all already handles
it. cbor2.CBORTag(39, ":chain") is the Python side.
There are two canonical CBOR orderings. RFC 8949 sorts keys bytewise on their
ENCODED form; RFC 7049 sorted length-first. They differ whenever a map mixes
key lengths, which every payload here does. :profile :canonical is 8949.
Python's cbor2.dumps(..., canonical=True) is also 8949 in current releases
but was 7049 in older ones, so a client that produces signatures nothing
verifies should check that first. boring can emit the old order for
comparison via :profile :canonical-rfc7049; urd never signs it.
It does not hash. urd.crypto and hasch remain how urd content-addresses
values -- a snapshot ref, an invariant's identity -- and those are internal
identities rather than things a foreign client must reproduce. Signing and
content-addressing are different jobs and giving them the same encoding by
accident is how one of them ends up constrained by the other's needs.
The bytes a signature covers.
## Why this is a namespace and not two `hasch/edn-hash` calls
urd signed `hasch/edn-hash` of a Clojure map. That works, and it was
deterministic across clj and cljs, but it makes every signature in the system
reachable only from Clojure: `edn-hash` is a replikativ-specific walk over
Clojure's own value model, and a Python or Rust client wanting to submit a
transaction would have to reimplement it -- correctly, including its handling
of sets, maps, keywords and ratios -- before it could sign anything at all.
That is a large and thankless amount of work to demand of a client, and every
bug in it is a client that silently cannot transact.
So a signature covers canonical CBOR instead. The message is
`(boring/encode payload {:profile :canonical})`: RFC 8949 core deterministic
encoding, which is a published specification with implementations in every
language anyone would write a client in. In Python the whole of it is
cbor2.dumps(payload, canonical=True) # note: see the caveat below
signing_key.sign(message) # ed25519, arbitrary length
## The three properties that make this safe to sign
1. `:canonical` SORTS map keys and set elements (`boring.core/encode-all`
says so explicitly). This matters more than it looks. Clojure's hash maps
and sets iterate in an order determined by hashes, and while that order is
stable for the same contents within one platform, it is not a property the
two platforms promise each other. Sorting removes the question.
2. Ed25519 signs arbitrary-length messages, so nothing needs pre-hashing. The
bytes ARE the message, which is one less thing for a client to get wrong
and one less place for a length-extension argument to be had.
3. Keywords encode as CBOR tag 39 (`identifier`) around the printed keyword
including its leading colon -- `:chain` is `39(":chain")`. That is a
registered tag, not a boring extension, and kabel's own CBOR wire already
uses it, so a client that can talk to a kabel peer at all already handles
it. `cbor2.CBORTag(39, ":chain")` is the Python side.
## Caveat for client authors: which canonical
There are two canonical CBOR orderings. RFC 8949 sorts keys bytewise on their
ENCODED form; RFC 7049 sorted length-first. They differ whenever a map mixes
key lengths, which every payload here does. `:profile :canonical` is 8949.
Python's `cbor2.dumps(..., canonical=True)` is also 8949 in current releases
but was 7049 in older ones, so a client that produces signatures nothing
verifies should check that first. boring can emit the old order for
comparison via `:profile :canonical-rfc7049`; urd never signs it.
## What this deliberately does NOT do
It does not hash. `urd.crypto` and `hasch` remain how urd content-addresses
values -- a snapshot ref, an invariant's identity -- and those are internal
identities rather than things a foreign client must reproduce. Signing and
content-addressing are different jobs and giving them the same encoding by
accident is how one of them ends up constrained by the other's needs.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 |