Firebreak

Reference implementation

Epoch ledger

Sorted Merkle trees with inclusion and non-membership proofs, chained epochs and Bitcoin anchors.

Source
7 files, 403 lines
Tests
2 files, 19 cases
Paper
sec:app-protocol

Epoch ledger

Purpose

Each epoch, operators commit their chips' reports to a Merkle tree whose leaves are sorted by key, and the global root is anchored on Bitcoin. Sorting is what makes absence provable: anyone can show that a registered chip is missing from an epoch. That proof is the paper's "omission" slashing predicate. This module builds those trees, proves inclusion and non-membership against a committed root, and produces the epoch records that are anchored.

Data formats

All hashes are SHA-256 from @noble/hashes. Domain separation uses a one-byte prefix on every hash input (the RFC 6962 style), not BIP340 tagged hashes.

Object Definition
entry (key: 32 bytes, value: bytes). Keys are unique; the tree sorts them lexicographically.
leaf H(0x00 || key || H(value))
interior node H(0x01 || left || right)
odd node promoted to the next level unchanged, never paired with a copy of itself
empty Merkle root H("Firebreak/ledger/empty"), a fixed tag
committed root H(0x02 || u64le(size) || merkleRoot). This is the value proofs are checked against and epochs commit to.
epoch record { epoch, prevRoot, root, size }
epoch commitment H(0x03 || u64le(epoch) || prevRoot || root || u64le(size))
anchor payload "FBK1" || epochCommitment, 36 bytes, carried in an OP_RETURN output

prevRoot is the previous record's commitment (32 zero bytes for epoch 0), so the anchored commitments form a hash chain. linksTo(prev, next) checks one link. parseAnchorPayload reads the commitment back out of OP_RETURN data.

Proofs

  • Inclusion: { index, siblings[] }. The verifier walks from the leaf to the root. At each level, the size decides whether the node has a sibling (left if the index is odd, right if a right neighbor exists) or was promoted. The proof must contain exactly the expected number of siblings.

  • Non-membership of key k, one of:

    • empty: the size is 0 and the root is the empty committed root;
    • before-first: an inclusion proof of leaf 0, with k < its key;
    • after-last: an inclusion proof of leaf size-1, with k > its key;
    • between: inclusion proofs of leaves i and i+1, with left.key < k < right.key.

    A neighbor carries its key, the hash of its value and its path, so the value itself need not be revealed. The verifier checks adjacency (indices i and i+1) and the boundary indices against the committed size.

Flow

  1. Collect entries, then buildTree(entries) (throws on a key that is not 32 bytes or appears twice).
  2. nextEpoch(prev, tree) makes the record; anchorPayload(record) gives the OP_RETURN data.
  3. proveInclusion / proveAbsence return null when the request is impossible (an absent key has no inclusion proof; a present key has no absence proof).
  4. verifyInclusion(root, size, key, value, proof) / verifyAbsence(root, size, key, proof).

Security properties and the tests that check them

The tests are in test/ledger/. Trees are generated by fast-check with sizes 0 to 300, weighted toward 0, 1, 2, 3 and powers of two plus or minus one.

Property Test
The hash layout is exactly as documented (known answers built from raw SHA-256) "matches the documented hash layout", "gives the empty tree a fixed committed root", "hashes the record in the documented layout"
Odd nodes are promoted, so [a, b, c] and [a, b, c, c] have different roots "promotes an odd node instead of duplicating it"
Every leaf of every tree has a verifying inclusion proof "every leaf of every tree has a proof that verifies"
Flipping any byte of any sibling, the root, the key or the value, or changing the index or the sibling count, makes verification fail "flipping any byte of the proof, the root, the key or the value makes it fail"
An inclusion proof does not verify against any other size "a proof does not verify against any other size"
Non-membership verifies for random absent keys and for keys at every boundary (just below the first, just above the last, between neighbors) "verifies for absent keys at random and at every boundary"
Flipping any byte of an absence proof or the root makes it fail "flipping any byte of an absence proof or the root makes it fail"
No absence proof can be built for a present key, and every crafted one (each boundary form, non-adjacent neighbors, neighbors equal to the key, empty on a non-empty tree) is rejected "cannot be built for a present key, and every crafted one is rejected"
Every epoch record chains to the previous record's commitment, and changing any field breaks the commitment and the chain "chains each record...", "commits to every field..."

Interpretations

  • Prefix bytes rather than tagged hashes for the tree, the RFC 6962 convention. Signed messages elsewhere in the protocol use BIP340 tagged hashes.
  • prevRoot is the previous record's commitment, not the previous tree root. This makes the anchored values themselves a hash chain, matching the paper's "a later root also commits to the hash of the previous one".

Open questions for the paper's authors

  • Sortedness is trusted. A non-membership proof is only as good as the guarantee that the committed tree really is sorted. An operator who commits an unsorted tree can prove a present chip absent. Archive nodes holding the full epoch data can check sortedness, and a sparse Merkle tree keyed by chip_id would remove the assumption. The paper should say which it relies on.
  • Two-level trees. The paper has operator roots combined into a global root. This module implements one level. The global combination (sorted by operator id, so an operator's absence is also provable) uses the same construction, but the paper does not fix its format.

Source

The code

src/ledger/bytes.ts22 lines
/**
 * Byte helpers the ledger needs beyond what @noble provides.
 */

/** Orders two byte strings lexicographically: negative if a < b, zero if equal, positive if a > b. */
export function compareBytes(a: Uint8Array, b: Uint8Array): number {
  const n = Math.min(a.length, b.length);
  for (let i = 0; i < n; i++) {
    const d = (a[i] as number) - (b[i] as number);
    if (d !== 0) return d;
  }
  return a.length - b.length;
}

/** Encodes a safe non-negative integer as 8 bytes, little-endian. */
export function u64le(n: number): Uint8Array {
  if (!Number.isSafeInteger(n) || n < 0) throw new RangeError(`u64le: ${n} is not a safe non-negative integer`);
  const out = new Uint8Array(8);
  new DataView(out.buffer).setBigUint64(0, BigInt(n), true);
  return out;
}

View on GitHub

src/ledger/epoch.ts62 lines
/**
 * Epoch records and their Bitcoin anchor.
 *
 * Each epoch's record commits to the previous record's commitment, so the
 * anchored commitments form a hash chain whose order cannot be disputed.
 */
import { sha256 } from "@noble/hashes/sha2.js";
import { concatBytes, utf8ToBytes } from "@noble/hashes/utils.js";
import { equalBytes } from "@noble/curves/utils.js";
import { u64le } from "./bytes";
import { HASH_LEN, Tag } from "./hash";
import type { EpochTree } from "./tree";

/** One epoch: its number, the previous epoch's commitment, this epoch's committed root and its leaf count. */
export interface EpochRecord {
  readonly epoch: number;
  /** The previous record's commitment (32 zero bytes for epoch 0). */
  readonly prevRoot: Uint8Array;
  /** The committed root of this epoch's tree. */
  readonly root: Uint8Array;
  readonly size: number;
}

/** The prevRoot of epoch 0. */
export const GENESIS_PREV_ROOT: Uint8Array = new Uint8Array(HASH_LEN);

/** The four magic bytes that open every anchor payload. */
export const ANCHOR_MAGIC: Uint8Array = utf8ToBytes("FBK1");

/** Hashes a record: SHA-256(0x03 || u64le(epoch) || prevRoot || root || u64le(size)). */
export function epochCommitment(r: EpochRecord): Uint8Array {
  return sha256(concatBytes(Uint8Array.of(Tag.epoch), u64le(r.epoch), r.prevRoot, r.root, u64le(r.size)));
}

/** Makes the record for a new tree, chained to the previous record (or to genesis when prev is null). */
export function nextEpoch(prev: EpochRecord | null, tree: EpochTree): EpochRecord {
  return {
    epoch: prev ? prev.epoch + 1 : 0,
    prevRoot: prev ? epochCommitment(prev) : GENESIS_PREV_ROOT,
    root: tree.root,
    size: tree.size,
  };
}

/** Checks that next directly follows prev: the next epoch number and prev's commitment as its prevRoot. */
export function linksTo(prev: EpochRecord | null, next: EpochRecord): boolean {
  if (prev === null) return next.epoch === 0 && equalBytes(next.prevRoot, GENESIS_PREV_ROOT);
  return next.epoch === prev.epoch + 1 && equalBytes(next.prevRoot, epochCommitment(prev));
}

/** Returns the OP_RETURN data for a record: "FBK1" followed by its 32-byte commitment (36 bytes). */
export function anchorPayload(r: EpochRecord): Uint8Array {
  return concatBytes(ANCHOR_MAGIC, epochCommitment(r));
}

/** Reads the commitment back out of an anchor payload, or returns null if it is not one. */
export function parseAnchorPayload(data: Uint8Array): Uint8Array | null {
  if (data.length !== ANCHOR_MAGIC.length + HASH_LEN) return null;
  if (!equalBytes(data.subarray(0, ANCHOR_MAGIC.length), ANCHOR_MAGIC)) return null;
  return data.slice(ANCHOR_MAGIC.length);
}

View on GitHub

src/ledger/hash.ts45 lines
/**
 * Domain-separated SHA-256 for the epoch ledger.
 *
 * Every hash input starts with a one-byte domain tag (the RFC 6962 style), so a
 * leaf can never be reinterpreted as an interior node, a committed root or an
 * epoch record.
 */
import { sha256 } from "@noble/hashes/sha2.js";
import { concatBytes, utf8ToBytes } from "@noble/hashes/utils.js";
import { u64le } from "./bytes";

/** Length in bytes of every hash and every leaf key. */
export const HASH_LEN = 32;

/** Domain tags: the first byte of each hash input. */
export const Tag = {
  leaf: 0x00,
  node: 0x01,
  root: 0x02,
  epoch: 0x03,
} as const;

/** The Merkle root of a tree with no leaves: a fixed tag, SHA-256("Firebreak/ledger/empty"). */
export const EMPTY_MERKLE_ROOT: Uint8Array = sha256(utf8ToBytes("Firebreak/ledger/empty"));

/** Hashes a value so a leaf commits to it at fixed length: SHA-256(value). */
export function valueHash(value: Uint8Array): Uint8Array {
  return sha256(value);
}

/** Hashes a leaf: SHA-256(0x00 || key || valueHash). */
export function leafHash(key: Uint8Array, vHash: Uint8Array): Uint8Array {
  return sha256(concatBytes(Uint8Array.of(Tag.leaf), key, vHash));
}

/** Hashes an interior node: SHA-256(0x01 || left || right). */
export function nodeHash(left: Uint8Array, right: Uint8Array): Uint8Array {
  return sha256(concatBytes(Uint8Array.of(Tag.node), left, right));
}

/** Hashes the committed root, which binds the leaf count: SHA-256(0x02 || u64le(size) || merkleRoot). */
export function committedRoot(size: number, merkleRoot: Uint8Array): Uint8Array {
  return sha256(concatBytes(Uint8Array.of(Tag.root), u64le(size), merkleRoot));
}

View on GitHub

src/ledger/proof.ts140 lines
/**
 * Inclusion and non-membership proofs for the sorted epoch tree.
 *
 * Proofs are checked against a committed root and the size it commits to. The
 * size fixes the shape of every path (which nodes have siblings and which were
 * promoted), so a proof for one size cannot be replayed against another, and
 * the committed root rejects a wrong size in any case.
 */
import { equalBytes } from "@noble/curves/utils.js";
import { compareBytes } from "./bytes";
import { committedRoot, EMPTY_MERKLE_ROOT, HASH_LEN, leafHash, nodeHash, valueHash } from "./hash";
import { type Entry, type EpochTree, locate } from "./tree";

/** A Merkle path: the leaf's index and its siblings from the bottom level up. */
export interface InclusionProof {
  readonly index: number;
  readonly siblings: readonly Uint8Array[];
}

/** A leaf shown inside an absence proof: its key, the hash of its value and its path. */
export interface Neighbor {
  readonly key: Uint8Array;
  readonly valueHash: Uint8Array;
  readonly proof: InclusionProof;
}

/** Evidence that a key is not in the tree. */
export type AbsenceProof =
  /** The tree is empty. */
  | { readonly kind: "empty" }
  /** The key sorts before leaf 0. */
  | { readonly kind: "before-first"; readonly first: Neighbor }
  /** The key sorts after leaf size-1. */
  | { readonly kind: "after-last"; readonly last: Neighbor }
  /** The key sorts strictly between leaves i and i+1. */
  | { readonly kind: "between"; readonly left: Neighbor; readonly right: Neighbor };

/** Builds the inclusion proof for a present key, or null if the key is absent. */
export function proveInclusion(tree: EpochTree, key: Uint8Array): InclusionProof | null {
  const { found, index } = locate(tree, key);
  return found ? pathAt(tree, index) : null;
}

/** Checks that (key, value) is a leaf of the tree with this committed root and size. */
export function verifyInclusion(
  root: Uint8Array,
  size: number,
  key: Uint8Array,
  value: Uint8Array,
  proof: InclusionProof,
): boolean {
  return verifyLeaf(root, size, key, valueHash(value), proof);
}

/** Builds the non-membership proof for an absent key, or null if the key is present. */
export function proveAbsence(tree: EpochTree, key: Uint8Array): AbsenceProof | null {
  const { found, index } = locate(tree, key);
  if (found) return null;
  if (tree.size === 0) return { kind: "empty" };
  if (index === 0) return { kind: "before-first", first: neighborAt(tree, 0) };
  if (index === tree.size) return { kind: "after-last", last: neighborAt(tree, tree.size - 1) };
  return { kind: "between", left: neighborAt(tree, index - 1), right: neighborAt(tree, index) };
}

/** Checks that a key is absent from the tree with this committed root and size. */
export function verifyAbsence(root: Uint8Array, size: number, key: Uint8Array, proof: AbsenceProof): boolean {
  if (key.length !== HASH_LEN) return false;
  switch (proof.kind) {
    case "empty":
      return size === 0 && equalBytes(root, committedRoot(0, EMPTY_MERKLE_ROOT));
    case "before-first":
      return (
        proof.first.proof.index === 0 &&
        compareBytes(key, proof.first.key) < 0 &&
        verifyNeighbor(root, size, proof.first)
      );
    case "after-last":
      return (
        proof.last.proof.index === size - 1 &&
        compareBytes(proof.last.key, key) < 0 &&
        verifyNeighbor(root, size, proof.last)
      );
    case "between":
      return (
        proof.left.proof.index + 1 === proof.right.proof.index &&
        compareBytes(proof.left.key, key) < 0 &&
        compareBytes(key, proof.right.key) < 0 &&
        verifyNeighbor(root, size, proof.left) &&
        verifyNeighbor(root, size, proof.right)
      );
  }
}

/** Recomputes the Merkle root from a leaf and its path, or returns null if the path has the wrong shape for this size. */
export function rootFromPath(leaf: Uint8Array, size: number, proof: InclusionProof): Uint8Array | null {
  const { index, siblings } = proof;
  if (!Number.isSafeInteger(size) || !Number.isSafeInteger(index) || index < 0 || index >= size) return null;
  let node = leaf;
  let i = index;
  let width = size;
  let used = 0;
  while (width > 1) {
    const hasSibling = i % 2 === 1 || i + 1 < width;
    if (hasSibling) {
      const sibling = siblings[used++];
      if (!sibling || sibling.length !== HASH_LEN) return null;
      node = i % 2 === 1 ? nodeHash(sibling, node) : nodeHash(node, sibling);
    }
    i = Math.floor(i / 2);
    width = Math.ceil(width / 2);
  }
  return used === siblings.length ? node : null;
}

function verifyLeaf(root: Uint8Array, size: number, key: Uint8Array, vHash: Uint8Array, proof: InclusionProof): boolean {
  if (key.length !== HASH_LEN || vHash.length !== HASH_LEN) return false;
  const top = rootFromPath(leafHash(key, vHash), size, proof);
  return top !== null && equalBytes(root, committedRoot(size, top));
}

function verifyNeighbor(root: Uint8Array, size: number, n: Neighbor): boolean {
  return verifyLeaf(root, size, n.key, n.valueHash, n.proof);
}

function pathAt(tree: EpochTree, index: number): InclusionProof {
  const siblings: Uint8Array[] = [];
  let i = index;
  for (const level of tree.levels.slice(0, -1)) {
    const sibling = level[i % 2 === 1 ? i - 1 : i + 1];
    if (sibling) siblings.push(sibling);
    i = Math.floor(i / 2);
  }
  return { index, siblings };
}

function neighborAt(tree: EpochTree, index: number): Neighbor {
  const e = tree.entries[index] as Entry;
  return { key: e.key, valueHash: valueHash(e.value), proof: pathAt(tree, index) };
}

View on GitHub

src/ledger/schedule.ts26 lines
/**
 * The two levels of the epoch schedule (Appendix A, "Epoch schedule").
 *
 * Each operator builds a sorted tree over its chips' reports, keyed by
 * chip_id, so that a chip's absence can be proven. The Agency combines the
 * operator roots into a global tree, one leaf per operator keyed by
 * SHA-256(op_id). The global tree's epoch record (nextEpoch) commits to the
 * previous global record, and that record is what is anchored on Bitcoin.
 */
import { sha256 } from "@noble/hashes/sha2.js";
import { concatBytes, utf8ToBytes } from "@noble/hashes/utils.js";
import { u64le } from "./bytes";
import { HASH_LEN } from "./hash";
import type { Entry } from "./tree";

/** The global tree's key for an operator: SHA-256 of its op_id. */
export function operatorKey(opId: string): Uint8Array {
  return sha256(utf8ToBytes(opId));
}

/** The global tree's leaf for one operator's tree: value = committed root || u64le(size). */
export function globalEntry(opId: string, operatorRoot: Uint8Array, operatorSize: number): Entry {
  if (operatorRoot.length !== HASH_LEN) throw new RangeError("operator root must be 32 bytes");
  return { key: operatorKey(opId), value: concatBytes(operatorRoot, u64le(operatorSize)) };
}

View on GitHub

src/ledger/tree.ts79 lines
/**
 * The sorted Merkle epoch tree.
 *
 * Leaves are sorted by key and keys are unique, which is what lets an absent key
 * be proven absent: it would have to sit between two adjacent leaves. When a
 * level has an odd number of nodes, the last one is promoted to the next level
 * unchanged. It is never paired with a copy of itself, which closes the
 * CVE-2012-2459 class of attacks where two different leaf lists share a root.
 */
import { compareBytes } from "./bytes";
import { committedRoot, EMPTY_MERKLE_ROOT, HASH_LEN, leafHash, nodeHash, valueHash } from "./hash";

/** One ledger entry: a 32-byte key and an arbitrary value. */
export interface Entry {
  readonly key: Uint8Array;
  readonly value: Uint8Array;
}

/** A built epoch tree. Entries are sorted by key; levels[0] holds the leaf hashes. */
export interface EpochTree {
  readonly entries: readonly Entry[];
  readonly levels: readonly (readonly Uint8Array[])[];
  readonly size: number;
  /** The Merkle root before the size is bound in. */
  readonly merkleRoot: Uint8Array;
  /** The committed root, H(0x02 || u64le(size) || merkleRoot). This is what gets anchored. */
  readonly root: Uint8Array;
}

/** Builds a tree from entries in any order; throws on a key that is not 32 bytes or appears twice. */
export function buildTree(entries: Iterable<Entry>): EpochTree {
  const sorted = [...entries].sort((a, b) => compareBytes(a.key, b.key));
  sorted.forEach((e, i) => {
    if (e.key.length !== HASH_LEN) throw new RangeError(`entry key must be ${HASH_LEN} bytes, got ${e.key.length}`);
    const prev = sorted[i - 1];
    if (prev && compareBytes(prev.key, e.key) === 0) throw new RangeError("duplicate entry key");
  });
  const levels = buildLevels(sorted.map((e) => leafHash(e.key, valueHash(e.value))));
  const top = levels[levels.length - 1]?.[0] ?? EMPTY_MERKLE_ROOT;
  return { entries: sorted, levels, size: sorted.length, merkleRoot: top, root: committedRoot(sorted.length, top) };
}

/** Computes the Merkle root of a list of leaf hashes, promoting odd nodes; the empty list gives EMPTY_MERKLE_ROOT. */
export function merkleRoot(leaves: readonly Uint8Array[]): Uint8Array {
  const levels = buildLevels(leaves);
  return levels[levels.length - 1]?.[0] ?? EMPTY_MERKLE_ROOT;
}

/** Finds a key by binary search: its index if present, otherwise the index where it would be inserted. */
export function locate(tree: EpochTree, key: Uint8Array): { readonly found: boolean; readonly index: number } {
  let lo = 0;
  let hi = tree.size;
  while (lo < hi) {
    const mid = (lo + hi) >>> 1;
    const c = compareBytes((tree.entries[mid] as Entry).key, key);
    if (c === 0) return { found: true, index: mid };
    if (c < 0) lo = mid + 1;
    else hi = mid;
  }
  return { found: false, index: lo };
}

function buildLevels(leaves: readonly Uint8Array[]): Uint8Array[][] {
  if (leaves.length === 0) return [];
  const levels: Uint8Array[][] = [[...leaves]];
  let level = levels[0] as Uint8Array[];
  while (level.length > 1) {
    const next: Uint8Array[] = [];
    for (let i = 0; i < level.length; i += 2) {
      const left = level[i] as Uint8Array;
      const right = level[i + 1];
      next.push(right ? nodeHash(left, right) : left);
    }
    levels.push(next);
    level = next;
  }
  return levels;
}

View on GitHub

src/ledger/index.ts29 lines
/**
 * The epoch ledger: a sorted Merkle tree with inclusion and non-membership
 * proofs, and epoch records anchored on Bitcoin. See SPEC.md.
 */
export { compareBytes, u64le } from "./bytes";
export { committedRoot, EMPTY_MERKLE_ROOT, HASH_LEN, leafHash, nodeHash, Tag, valueHash } from "./hash";
export { buildTree, locate, merkleRoot, type Entry, type EpochTree } from "./tree";
export {
  proveAbsence,
  proveInclusion,
  rootFromPath,
  verifyAbsence,
  verifyInclusion,
  type AbsenceProof,
  type InclusionProof,
  type Neighbor,
} from "./proof";
export {
  ANCHOR_MAGIC,
  anchorPayload,
  epochCommitment,
  GENESIS_PREV_ROOT,
  linksTo,
  nextEpoch,
  parseAnchorPayload,
  type EpochRecord,
} from "./epoch";
export { globalEntry, operatorKey } from "./schedule";

View on GitHub