Liking cljdoc? Tell your friends :D

urd.consensus.algorithms.bullshark

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.

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.
raw docstring

urd.consensus.algorithms.nakamoto

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.

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.
raw docstring

urd.consensus.algorithms.raft

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.

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*.
raw docstring

urd.consensus.algorithms.round-robin

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.

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.
raw docstring

urd.consensus.algorithms.scp

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.

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.
raw docstring

urd.consensus.algorithms.snowflake

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.

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.
raw docstring

urd.consensus.algorithms.snowman

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.

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.
raw docstring

urd.consensus.algorithms.snowtree

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.

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.
raw docstring

urd.consensus.algorithms.tendermint

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.

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.
raw docstring

cljdoc builds & hosts documentation for Clojure/Script libraries

Keyboard shortcuts
Ctrl+kJump to recent docs
←Move to previous article
→Move to next article
Ctrl+/Jump to the search field
× close