Firebreak

Reference implementation

Bitcoin time beacon

Header-chain verification against real mainnet headers, difficulty floors, most-work tips and outage evidence.

Source
10 files, 1,039 lines
Tests
6 files, 53 cases
Paper
sec:architecture

Bitcoin time beacon

Purpose

The paper's Layer 2 gives each Firebreak Guarantee Module (FGM) two clocks: a local monotonic counter driven by an oscillator inside the enclosure (checked against a second, physically different oscillator), and the Bitcoin header chain. This module is the FGM-side logic for both and for the outage rule of Layer 1:

  • a header-chain verifier that extends a trusted checkpoint with real Bitcoin headers, enforcing proof of work, Bitcoin's retarget rule, the median-time-past rule and the license's difficulty floor d_min = difficulty(h) / k (licenseFloor, licenseFloorFactor), and accumulating chainwork;
  • most-work tip selection among competing branches (beaconState, submitBranch): the FGM stores the tip with the most cumulative work, not the greatest height, and refuses any header chain that would move it backward;
  • the license clock (checkOscillators, licenseClock): at most lambda of local time on the faster of the two oscillators, a clock anomaly when they diverge beyond tolerance, and a second expiry when the chain passes H_to, which can end a license early but never extend it;
  • two-sided time bounds [tLo, tHi] from the chain and the oscillators, and a pace check that turns header withholding into a visible "stale" state;
  • outage evidence (verifyOutageEvidence): every full block of the outage window, each checked against its header's Merkle root, with no epoch anchor among them.

Formats

  • Header: the 80-byte Bitcoin wire format (version i32, prevHash 32, merkleRoot 32, time u32, nBits u32, nonce u32, all little-endian). Hashes are double SHA-256 (@noble/hashes) kept in internal byte order; displayHash gives explorer order.
  • Checkpoint (what a license carries): { height, hash, bits }. When the checkpoint is not the first block of a difficulty period, the license must also carry that period's first timestamp (periodStartTime), or the verifier cannot check the next retarget and refuses to cross it.
  • ChainAnchor (FGM state): tip height, hash, nBits, cumulative chainwork, the last 11 timestamps, the largest timestamp seen, and the period's first timestamp.
  • Fixture fixtures/mainnet-headers.json: real mainnet headers 973717..975844 (k = 483: 11 headers of MTP context, the full period starting at the checkpoint 973728 = 2016 x 483, the retarget at 975744 and 100 headers after it), the genesis header, the checkpoint, and six hashes cross-checked against mempool.space. Fetched by scripts/fetch-headers.ts with the Electrum method blockchain.block.headers over TLS from electrum.blockstream.info:50002.
  • Full blocks (outage evidence only): Bitcoin's block serialization, transactions in legacy or BIP144 extended form. A txid is the double SHA-256 of the non-witness serialization. The Merkle root follows Bitcoin Core's ComputeMerkleRoot: odd levels duplicate their last hash, and two equal neighbours mark the tree as mutated.
  • Anchor: an OP_RETURN output whose pushed data contains the ledger's 36-byte payload "FBK1" || epochCommitment (src/ledger). Pushes are concatenated, so a payload split across pushes still counts.
  • Fixture fixtures/mainnet-small-blocks.json: raw mainnet blocks 170 (490 bytes) and 100000 (957 bytes, four transactions) from mempool.space, each block hash checked against blockstream.info by scripts/fetch-small-blocks.ts.

Flow

license: checkpoint h (height, hash, bits) [+ periodStartTime], H_from, H_to, lambda
         floor target = target(h) x k,  k = 4^(1 + max(0, ceil(lambda / T) - 1))   (d_min = difficulty(h) / k)
                |
history headers ending at the checkpoint  --anchorFromHistory-->  ChainAnchor
                |
new headers  --verifyHeaders-->  for each header, in order:
     80 bytes? -> prevHash == tip? -> nBits valid (not negative, no overflow, <= powLimit)?
     -> nBits == tip's (inside a period) or == retarget(tip, periodStart) (at height % 2016 == 0)?
     -> hash <= target? -> target <= floor? -> time > median(last 11)?
     -> chainwork += 2^256 / (target + 1)
                |
submitBranch(state, headers): the first header must build on a block in state.recent
     (the last `depth` blocks of the FGM's chain, default 144); every header must verify;
     the branch becomes the tip only with strictly more chainwork than the stored tip
     (a taller branch with less work is refused); the abandoned branch is forgotten
                |
licenseClock:  anomaly         if |a - b| / max(a, b) > tolerance  (a, b: the two oscillators)
               expired-local   if max(a, b) >= lambda              (headers cannot change this)
               expired-height  if tip height > H_to                (headers can only shorten)
               before-window   if tip height < H_from
               licensed        otherwise
                |
timeBounds:  tLo = maxTimestamp - 7200         (or MTP - 7200)
             tHi = tSyncHi + (1 + eps) x oscillatorElapsed
             consistent = tLo <= tHi
checkPace:   stale  if P[Poisson(rate x elapsed / (1+eps) / 600) <= headers] < 1e-6
             ahead  if P[Poisson(elapsed x (1+eps) / 600) >= headers]      < 1e-6

Outage evidence (verifyOutageEvidence), checked against the FGM's own verified tip:

headers of the window (>= windowBlocks, consecutive, last one hashes to the stored tip)
for each header i:  block i present and its first 80 bytes == header i     else "gap"
                    block parses exactly (no truncation, no trailing bytes) else "parse"
                    no 64-byte transaction                                  else "tx-64-bytes"
                    Merkle tree not mutated (CVE-2012-2459)                 else "merkle-mutated"
                    Merkle root of txids == header's merkleRoot             else "merkle"
                    no OP_RETURN carrying a (valid) FBK1 anchor             else "anchor-present"
accept -> the FGM may enter outage grace (inference only, at most g r)

Because the window ends at a tip whose headers the FGM verified one by one, and each header commits to its parent, the shown headers are the FGM's own chain; because each block's transactions hash to that header's Merkle root, no transaction can be left out.

Retarget rule (Bitcoin Core CalculateNextWorkRequired): at height h with h % 2016 == 0, span = time(h-1) - time(h-2016), clamped to [T/4, 4T] with T = 1,209,600 s; new target = target(h-1) x span / T, capped at powLimit, then rounded through the compact encoding. The span covers 2015 intervals, not 2016: this off-by-one is Bitcoin's, it is reproduced exactly, and it is what makes the timewarp attack possible on Bitcoin.

Security properties and the tests that check them

Property Test (test/beacon/)
Genesis header hashes to 000000000019d6...e26f and meets its own target; its work is 0x100010001 verify.test.ts "genesis"
The whole real fixture verifies under mainnet rules with the checkpoint floor, ending at the cross-checked hash "verifies end to end ..."
The real retarget at 975744 is reproduced bit for bit; using the wrong first block gives a different result "crosses a real retarget ..."
A single-bit flip in any of the 80 bytes of any of the 2116 verified headers is rejected (169,280 cases) "rejects a single-bit flip ..."
Any bit flip in the checkpoint history is rejected "rejects a bit flip in any byte of the checkpoint history"
A missing header breaks the chain (link) "rejects a broken link"
A wrong nBits at the boundary is rejected (retarget) "rejects a wrong retarget at the boundary"
A floor above the real difficulty rejects the real chain (floor) "rejects the fixture when the floor is raised"
Crossing a boundary without the period's first timestamp is refused "needs the period's first timestamp"
A regtest-difficulty chain (0x207fffff, mined in JS) passes structural checks but is rejected by the mainnet floor and by mainnet powLimit "regtest-difficulty chain" block
Median-time-past rule enforced "enforces the median-time-past rule"
Tip only moves to strictly more work "keeps the most-work tip ..."
A branch longer by height but with less work loses; the heavier branch reorgs a taller one that arrived first; equal work does not move the tip; a bad header rejects the whole branch; forks deeper than remembered are refused branch.test.ts "most-work tip selection"
k is 4 up to two weeks and 4x per extra retarget period; d_min = difficulty(h) / 4 for a two-week license, and every real header across the 975744 retarget meets it branch.test.ts "difficulty floor"
Expiry at lambda on the faster oscillator; height expiry once the chain passes H_to (not at it); divergence is a clock anomaly branch.test.ts "license clock"
Property: licensed only while both oscillators are under lambda and agree; more headers never revive an expired license branch.test.ts "property: ..."
Real blocks 170 and 100000: txids equal bitcoinjs-lib's, Merkle root equals the header's, each is valid evidence for a one-block window outage.test.ts "full-block parsing ..."
Outage evidence: a full anchor-free window passes; a withheld block fails (gap); an altered transaction fails (merkle); an FBK1 anchor fails (anchor-present), also when split over two pushes; not ending at the tip, too short or non-consecutive fails; 64-byte transactions, mutated Merkle trees and truncated blocks fail outage.test.ts "outage evidence"
The same checks on blocks bitcoind mined (segwit coinbase and wallet transactions): window with the anchor refused, anchor-free window accepted, withheld block and tampered transaction refused test/regtest/bond.test.ts "anchors a ledger epoch root ..."
nBits decoding and encoding match Bitcoin Core's vectors; negative and overflowing nBits rejected "compact nBits" block
tLo never decreases as headers are accepted; tHi is monotone in elapsed time and eps (property tests) time.test.ts "property: ..."
Contradiction between chain and oscillator is flagged "flags inconsistency ..."
Conservative expiry at (1+eps) lambda and height expiry at H_to "expires by oscillator ..."
Poisson tails accurate deep in the tail; stale detector flags withholding, not ordinary gaps time.test.ts "Poisson tails", "withholding detector"

Interpretations

  • Interpretation: the floor factor k. The paper sets d_min "a small factor below the difficulty at the license's block h, within the range Bitcoin's own retargeting allows over a license period". One adjustment can land just after h and lower difficulty by up to 4x; each later one lowers it only if its period took longer than T (two weeks), so at most ceil(lambda / T) - 1 more. We take k = 4^(1 + max(0, ceil(lambda / T) - 1)): 4 for any license up to two weeks, 16 up to four weeks. Every counterfeit header then costs at least 1/k of an honest block's work. The bound is conservative (a real chain cannot reach it), which is the safe side for liveness and the costly side for counterfeit resistance.
  • Interpretation: the reorg window. The FGM keeps the chain states of its last depth blocks (default 144, about a day) so it can judge a heavier fork that does not build on its exact tip. A branch is all or nothing.
  • Interpretation: the two oscillators. Elapsed local time is the larger of the two counts, so a slowed oscillator cannot stretch a license; relative divergence above the tolerance, after the first second, is a clock anomaly. timeBounds should be fed checkOscillators(...).elapsed.
  • Interpretation: "passes H_to" means tip height > H_to; a tip below H_from is reported as before-window (the license is not yet usable).
  • Interpretation: the outage window is counted in blocks ending at the FGM's tip. The paper counts it in epochs; the caller converts. By default any well-formed FBK1 payload in an OP_RETURN counts as an anchor; isValidAnchor can narrow this.
  • Interpretation: 64-byte transactions are refused in outage evidence. A 64-byte transaction has the same shape as an inner Merkle node, so a forged "block" could replace a subtree (holding an anchor) with one fake transaction. BIP54 would make such transactions invalid; mainnet does not yet. Mutated (duplicated-leaf) trees are refused as Bitcoin Core does.
  • Interpretation: tLo = newest timestamp - 7200 s, because nodes reject blocks more than two hours ahead of their clock (MAX_FUTURE_BLOCK_TIME). A median-time-past rule is offered as an option (see open questions).
  • Interpretation: tSyncHi is an input: the upper bound on real time at the last sync point, carried in FGM state from the previous sync or from provisioning.
  • Interpretation: expiry is judged by tHi (the latest time it could be), so a license never runs past its expiry; the height expiry H_to can only end it early.
  • Interpretation: the pace check is the paper's "cumulative work consistent with the local time elapsed", done on header counts (equivalent while difficulty is constant). "stale" uses the slowest plausible elapsed time, "ahead" the fastest, both at p < 1e-6. minRateFactor and maxRateFactor (default 1) allow for hashrate swings between retargets.
  • Not checked: block version and soft-fork activation rules. They cost an attacker nothing, so they add no security to a header-only verifier.

Open questions for the paper authors

  1. Which timestamp sets the lower bound? With "newest timestamp - 2 h", one header mined at floor difficulty with a far-future timestamp pushes tLo forward, which can make the FGM think a license has expired or flag a contradiction (a bricking attack costing about a quarter of a block's work). Using median-time-past costs the attacker six such headers. The paper should pick one.
  2. The floor factor and lambda. The paper should state k as a function of lambda (ours: 4^(1 + max(0, ceil(lambda / T) - 1))). For licenses longer than two weeks it grows fast (16, 64, ...), so a counterfeit header becomes cheap; this argues for lambda of at most two weeks.
  3. Reorg window size. "Store the most-work tip" needs a window of recent chain states so the FGM can accept a heavier fork that does not extend its exact tip. The paper should give the depth (ours: 144 blocks).
  4. What makes an anchor "valid" for the outage rule? If any FBK1-shaped OP_RETURN counts, anyone can block outage grace for the whole world by publishing one cheap OP_RETURN per window; if only anchors that extend the known epoch chain count, the FGM must hold that chain's state. The paper should define validity (for example, a payload whose epoch record links to the last root the FGM saw, or a spend from a key the Council publishes).
  5. The outage window's unit and the evidence's size. The paper counts the window in epochs; the FGM needs it in blocks. Full blocks are up to about 4 MB each, so a day-long window is about 600 MB the FGM must hash; the paper should size the window with that cost in mind.
  6. Who keeps blocks below a reorg? Outage evidence is only as good as the FGM's tip: an operator who controls the FGM's header feed can stop it at an old tip, but then the pace check reports "stale", so the outage rule should require a non-stale pace before accepting evidence. The paper does not say how the two interact.
  7. Hashrate drops. The plain Poisson(T/600) stale test fires falsely if hashrate falls sharply before a retarget. The paper should say how much slack the Grace state allows (our minRateFactor).
  8. Where tSyncHi comes from at first boot (provisioning) is not specified.
  9. Timewarp. Mainnet still permits timewarp (the BIP54 consensus cleanup is not active). The floor bounds what a private timewarp chain can gain, which is why the floor matters; the paper should state this dependency.

Source

The code

src/beacon/block.ts154 lines
/**
 * Full Bitcoin blocks, for the outage rule only: a strict parser, txids from the
 * non-witness serialization, and the transaction Merkle root computed exactly as
 * Bitcoin Core does (odd levels duplicate their last hash; equal neighbours flag
 * a mutated tree). Hashes are internal byte order.
 */
import { equalBytes } from "@noble/curves/utils.js";
import { concatBytes } from "@noble/hashes/utils.js";
import { hash256, HEADER_LEN, parseHeader, type BlockHeader } from "./header";

/** One transaction output. */
export interface TxOutput {
  readonly value: bigint;
  readonly script: Uint8Array;
}

/** A parsed transaction: its txid, outputs and non-witness size. */
export interface ParsedTx {
  /** Double SHA-256 of the non-witness serialization, internal byte order. */
  readonly txid: Uint8Array;
  readonly outputs: readonly TxOutput[];
  /** Length of the non-witness serialization in bytes. */
  readonly baseSize: number;
}

/** A parsed block. */
export interface ParsedBlock {
  readonly header: BlockHeader;
  readonly txs: readonly ParsedTx[];
}

/** Sequential reader that throws on any read past the end. */
class Reader {
  pos = 0;
  constructor(private readonly b: Uint8Array) {}
  get left(): number {
    return this.b.length - this.pos;
  }
  bytes(n: number): Uint8Array {
    if (n < 0 || n > this.left) throw new Error("block truncated");
    const out = this.b.subarray(this.pos, this.pos + n);
    this.pos += n;
    return out;
  }
  u8(): number {
    return this.bytes(1)[0]!;
  }
  peek(offset = 0): number | undefined {
    return this.b[this.pos + offset];
  }
  u64(): bigint {
    const s = this.bytes(8);
    let v = 0n;
    for (let i = 7; i >= 0; i--) v = (v << 8n) | BigInt(s[i]!);
    return v;
  }
  varint(): number {
    const first = this.u8();
    if (first < 0xfd) return first;
    const len = first === 0xfd ? 2 : first === 0xfe ? 4 : 8;
    const s = this.bytes(len);
    let v = 0n;
    for (let i = len - 1; i >= 0; i--) v = (v << 8n) | BigInt(s[i]!);
    if (v > BigInt(this.left)) throw new Error("length prefix exceeds block size");
    return Number(v);
  }
  varbytes(): Uint8Array {
    return this.bytes(this.varint());
  }
  slice(from: number, to: number): Uint8Array {
    return this.b.subarray(from, to);
  }
}

/** Reads one transaction (legacy or BIP144 extended format) and returns it with its txid. */
function readTx(r: Reader): ParsedTx {
  const start = r.pos;
  r.bytes(4); // version
  const segwit = r.peek() === 0x00 && r.peek(1) === 0x01;
  if (segwit) r.bytes(2);
  const bodyStart = r.pos;
  const nIn = r.varint();
  if (nIn === 0) throw new Error("transaction has no inputs");
  for (let i = 0; i < nIn; i++) {
    r.bytes(36);
    r.varbytes();
    r.bytes(4);
  }
  const nOut = r.varint();
  const outputs: TxOutput[] = [];
  for (let i = 0; i < nOut; i++) outputs.push({ value: r.u64(), script: r.varbytes() });
  const bodyEnd = r.pos;
  if (segwit) {
    for (let i = 0; i < nIn; i++) {
      const items = r.varint();
      for (let j = 0; j < items; j++) r.varbytes();
    }
  }
  const lockStart = r.pos;
  r.bytes(4);
  const base = concatBytes(r.slice(start, start + 4), r.slice(bodyStart, bodyEnd), r.slice(lockStart, lockStart + 4));
  return { txid: hash256(base), outputs, baseSize: base.length };
}

/** Parses a raw block; throws on truncation, trailing bytes or an empty transaction list. */
export function parseBlock(raw: Uint8Array): ParsedBlock {
  const r = new Reader(raw);
  const header = parseHeader(r.bytes(HEADER_LEN).slice());
  const n = r.varint();
  if (n === 0) throw new Error("block has no transactions");
  const txs: ParsedTx[] = [];
  for (let i = 0; i < n; i++) txs.push(readTx(r));
  if (r.left !== 0) throw new Error(`${r.left} trailing bytes after the last transaction`);
  return { header, txs };
}

/** Bitcoin Core's ComputeMerkleRoot: the root, and whether two equal neighbours (CVE-2012-2459) were seen. */
export function merkleRoot(txids: readonly Uint8Array[]): { root: Uint8Array; mutated: boolean } {
  if (txids.length === 0) throw new Error("no transactions");
  let level = [...txids];
  let mutated = false;
  while (level.length > 1) {
    for (let i = 0; i + 1 < level.length; i += 2) if (equalBytes(level[i]!, level[i + 1]!)) mutated = true;
    if (level.length % 2 === 1) level.push(level[level.length - 1]!);
    const next: Uint8Array[] = [];
    for (let i = 0; i < level.length; i += 2) next.push(hash256(concatBytes(level[i]!, level[i + 1]!)));
    level = next;
  }
  return { root: level[0]!, mutated };
}

/** Pushed data in an output script after OP_RETURN, concatenated; null if the script is not OP_RETURN. */
export function opReturnData(script: Uint8Array): Uint8Array | null {
  if (script[0] !== 0x6a) return null;
  const parts: Uint8Array[] = [];
  let i = 1;
  while (i < script.length) {
    const op = script[i++]!;
    let len: number;
    if (op >= 0x01 && op <= 0x4b) len = op;
    else if (op === 0x4c) len = script[i++] ?? 0;
    else if (op === 0x4d) {
      len = (script[i] ?? 0) | ((script[i + 1] ?? 0) << 8);
      i += 2;
    } else if (op === 0x4e) {
      len = ((script[i] ?? 0) | ((script[i + 1] ?? 0) << 8) | ((script[i + 2] ?? 0) << 16) | ((script[i + 3] ?? 0) << 24)) >>> 0;
      i += 4;
    } else continue; // a non-push opcode carries no data
    parts.push(script.subarray(i, Math.min(i + len, script.length)));
    i += len;
  }
  return concatBytes(...parts);
}

View on GitHub

src/beacon/branch.ts64 lines
/**
 * Most-work tip selection among competing branches. The FGM stores the tip with
 * the most cumulative work it has seen, not the greatest height, and refuses any
 * header chain that would move it backward. To judge a branch that forks below
 * its tip it keeps the chain state of recent blocks.
 */
import { bytesToHex } from "@noble/hashes/utils.js";
import { verifyHeaders, type ChainAnchor, type HeaderErrorCode, type VerifyOptions } from "./verify";

/** The FGM's chain state: its tip and the states of recent blocks on its chain, by hash. */
export interface BeaconState {
  readonly tip: ChainAnchor;
  /** Chain states at recent heights (tip included), keyed by hex hash in internal byte order. */
  readonly recent: ReadonlyMap<string, ChainAnchor>;
  /** How many recent heights to keep: the deepest fork the FGM can judge. */
  readonly depth: number;
}

/** Outcome of offering a branch. */
export type BranchResult =
  | { readonly ok: true; readonly moved: true; readonly state: BeaconState; readonly reorgDepth: number }
  | { readonly ok: true; readonly moved: false; readonly state: BeaconState; readonly reason: "not-more-work" }
  | {
      readonly ok: false;
      readonly state: BeaconState;
      readonly code: HeaderErrorCode | "unknown-fork" | "empty";
      readonly message: string;
    };

/** Starts a beacon state at a trusted anchor. Interpretation: default depth 144 blocks (about a day). */
export function beaconState(anchor: ChainAnchor, depth = 144): BeaconState {
  if (!Number.isInteger(depth) || depth < 1) throw new Error("depth must be a positive integer");
  return { tip: anchor, recent: new Map([[bytesToHex(anchor.hash), anchor]]), depth };
}

/**
 * Offers headers whose first one builds on any block the state remembers. The whole
 * branch must verify; it then becomes the tip only if it has strictly more cumulative work.
 */
export function submitBranch(state: BeaconState, headers: readonly Uint8Array[], opts: VerifyOptions): BranchResult {
  const first = headers[0];
  if (first === undefined || first.length < 36) return { ok: false, state, code: "empty", message: "no headers" };
  const fork = state.recent.get(bytesToHex(first.subarray(4, 36)));
  if (!fork) return { ok: false, state, code: "unknown-fork", message: "branch does not build on a remembered block" };

  const states: ChainAnchor[] = [];
  let cur = fork;
  for (const h of headers) {
    const r = verifyHeaders(cur, [h], opts);
    if (!r.ok) return { ok: false, state, code: r.code, message: `height ${r.height}: ${r.message}` };
    cur = r.anchor;
    states.push(cur);
  }
  if (cur.chainwork <= state.tip.chainwork) return { ok: true, moved: false, state, reason: "not-more-work" };

  // The remembered states form one chain, so those at or below the fork are its ancestors; keep them and add the branch.
  const recent = new Map<string, ChainAnchor>();
  for (const [k, a] of state.recent) if (a.height <= fork.height) recent.set(k, a);
  for (const a of states) recent.set(bytesToHex(a.hash), a);
  for (const [k, a] of recent) if (a.height <= cur.height - state.depth) recent.delete(k);
  return { ok: true, moved: true, state: { tip: cur, recent, depth: state.depth }, reorgDepth: state.tip.height - fork.height };
}

View on GitHub

src/beacon/compact.ts56 lines
/**
 * Compact difficulty targets (nBits) and proof-of-work arithmetic, matching
 * Bitcoin Core's arith_uint256 SetCompact/GetCompact and GetBlockProof.
 */

/** Result of decoding nBits. `negative` and `overflow` make a header invalid. */
export interface DecodedTarget {
  readonly target: bigint;
  readonly negative: boolean;
  readonly overflow: boolean;
}

/** Decodes compact nBits to a target, reporting the sign bit and overflow like SetCompact. */
export function decodeCompact(bits: number): DecodedTarget {
  const size = bits >>> 24;
  const word = bits & 0x007fffff;
  const target = size <= 3 ? BigInt(word >>> (8 * (3 - size))) : BigInt(word) << BigInt(8 * (size - 3));
  const negative = word !== 0 && (bits & 0x00800000) !== 0;
  const overflow = word !== 0 && (size > 34 || (word > 0xff && size > 33) || (word > 0xffff && size > 32));
  return { target, negative, overflow };
}

/** Encodes a non-negative target as compact nBits, rounding down like GetCompact. */
export function encodeCompact(target: bigint): number {
  if (target < 0n) throw new Error("target must be non-negative");
  let size = byteLength(target);
  let compact = size <= 3 ? Number(target << BigInt(8 * (3 - size))) : Number(target >> BigInt(8 * (size - 3)));
  if (compact & 0x00800000) {
    compact >>>= 8;
    size += 1;
  }
  return ((size << 24) | compact) >>> 0;
}

/** Number of bytes needed to hold n (0 for n = 0). */
function byteLength(n: bigint): number {
  let size = 0;
  while (n > 0n) {
    n >>= 8n;
    size += 1;
  }
  return size;
}

const TWO_256 = 1n << 256n;

/** Expected number of hashes to find a block at this target: 2^256 / (target + 1). */
export function workForTarget(target: bigint): bigint {
  return TWO_256 / (target + 1n);
}

/** Converts a target to the familiar "difficulty" number relative to a reference target (as a float). */
export function difficulty(target: bigint, referenceTarget: bigint): number {
  return Number((referenceTarget * 1_000_000n) / target) / 1_000_000;
}

View on GitHub

src/beacon/header.ts82 lines
/**
 * Bitcoin block headers: the 80-byte wire format and the block hash.
 */
import { sha256 } from "@noble/hashes/sha2.js";
import { bytesToHex, hexToBytes } from "@noble/hashes/utils.js";

/** Size of a serialized block header in bytes. */
export const HEADER_LEN = 80;

/** A parsed block header. Hashes are kept in internal (little-endian) byte order. */
export interface BlockHeader {
  readonly version: number;
  /** Hash of the previous header, internal byte order. */
  readonly prevHash: Uint8Array;
  readonly merkleRoot: Uint8Array;
  /** Unix time in seconds, as the miner wrote it. */
  readonly timestamp: number;
  /** Compact difficulty target (nBits). */
  readonly bits: number;
  readonly nonce: number;
  /** Double SHA-256 of the 80 raw bytes, internal byte order. */
  readonly hash: Uint8Array;
  /** The raw 80 bytes. */
  readonly raw: Uint8Array;
}

/** Double SHA-256, the hash Bitcoin uses for headers and transactions. */
export function hash256(data: Uint8Array): Uint8Array {
  return sha256(sha256(data));
}

/** Parses an 80-byte header; throws on any other length. */
export function parseHeader(raw: Uint8Array): BlockHeader {
  if (raw.length !== HEADER_LEN) throw new Error(`header must be ${HEADER_LEN} bytes, got ${raw.length}`);
  const view = new DataView(raw.buffer, raw.byteOffset, raw.byteLength);
  return {
    version: view.getInt32(0, true),
    prevHash: raw.slice(4, 36),
    merkleRoot: raw.slice(36, 68),
    timestamp: view.getUint32(68, true),
    bits: view.getUint32(72, true),
    nonce: view.getUint32(76, true),
    hash: hash256(raw),
    raw: raw.slice(),
  };
}

/** Parses a header from 160 hex characters. */
export function parseHeaderHex(hex: string): BlockHeader {
  return parseHeader(hexToBytes(hex));
}

/** Serializes header fields to the 80-byte wire format. */
export function serializeHeader(h: Omit<BlockHeader, "hash" | "raw">): Uint8Array {
  const raw = new Uint8Array(HEADER_LEN);
  const view = new DataView(raw.buffer);
  view.setInt32(0, h.version, true);
  raw.set(h.prevHash, 4);
  raw.set(h.merkleRoot, 36);
  view.setUint32(68, h.timestamp, true);
  view.setUint32(72, h.bits, true);
  view.setUint32(76, h.nonce, true);
  return raw;
}

/** Shows an internal-order hash the way explorers print it (byte-reversed hex). */
export function displayHash(hash: Uint8Array): string {
  return bytesToHex(hash.slice().reverse());
}

/** Reads an explorer-style hash string into internal byte order. */
export function hashFromDisplay(hex: string): Uint8Array {
  return hexToBytes(hex).reverse();
}

/** Interprets an internal-order hash as the 256-bit integer the PoW check compares. */
export function hashToBigInt(hash: Uint8Array): bigint {
  let n = 0n;
  for (let i = hash.length - 1; i >= 0; i--) n = (n << 8n) | BigInt(hash[i]!);
  return n;
}

View on GitHub

src/beacon/license.ts57 lines
/**
 * The license clock. A license runs at most lambda units of local time, counted
 * by two physically different oscillators inside the enclosure; divergence beyond
 * tolerance is a clock anomaly. Headers add a second expiry at height H_to, which
 * can end a license early but never extend it: the upper bound on a license's real
 * duration comes from the oscillators alone, because headers can be withheld.
 */

/** The two oscillators' counts since the license was accepted, in nominal seconds. */
export interface OscillatorCounts {
  readonly a: number;
  readonly b: number;
}

/** Result of comparing the oscillators. */
export interface OscillatorCheck {
  /** The larger count: the elapsed local time used for expiry (and for timeBounds' oscillatorElapsed). */
  readonly elapsed: number;
  /** |a - b| / max(a, b), or 0 before either has counted. */
  readonly divergence: number;
  readonly anomaly: boolean;
}

/**
 * Compares the two oscillators. Interpretation: an anomaly is relative divergence above
 * `tolerance` once `minElapsed` seconds have passed (to ignore start-up quantization),
 * and immediately if either count is negative or not finite.
 */
export function checkOscillators(c: OscillatorCounts, tolerance: number, minElapsed = 1): OscillatorCheck {
  if (!(tolerance >= 0)) throw new Error("tolerance must be non-negative");
  const elapsed = Math.max(c.a, c.b);
  if (!Number.isFinite(c.a) || !Number.isFinite(c.b) || c.a < 0 || c.b < 0) return { elapsed: Infinity, divergence: Infinity, anomaly: true };
  const divergence = elapsed === 0 ? 0 : Math.abs(c.a - c.b) / elapsed;
  return { elapsed, divergence, anomaly: elapsed >= minElapsed && divergence > tolerance };
}

/** The parts of a license the clock needs. */
export interface LicenseTerms {
  readonly hFrom: number;
  readonly hTo: number;
  /** Maximum local duration, in seconds of local time. */
  readonly lambda: number;
}

/** The license's state on the clock (budget and tamper are tracked elsewhere). */
export type LicenseClockState = "licensed" | "before-window" | "expired-local" | "expired-height" | "clock-anomaly";

/** Applies the paper's expiry rules: clock anomaly, lambda of local time, or the chain passing H_to. */
export function licenseClock(terms: LicenseTerms, counts: OscillatorCounts, tolerance: number, tipHeight: number): LicenseClockState {
  const osc = checkOscillators(counts, tolerance);
  if (osc.anomaly) return "clock-anomaly";
  if (osc.elapsed >= terms.lambda) return "expired-local";
  if (tipHeight > terms.hTo) return "expired-height";
  if (tipHeight < terms.hFrom) return "before-window";
  return "licensed";
}

View on GitHub

src/beacon/outage.ts115 lines
/**
 * Positive evidence of a regime outage (paper, Layer 1): the FGM enters outage
 * grace only when shown every full block of the outage window, each checked
 * against its header's Merkle root, with no valid epoch anchor among them.
 * Headers alone cannot show absence, because an operator could withhold the
 * blocks that carry anchors; full blocks bound to the verified header chain can.
 */
import { equalBytes } from "@noble/curves/utils.js";
import { parseAnchorPayload, ANCHOR_MAGIC } from "../ledger";
import { hash256, HEADER_LEN, parseHeader } from "./header";
import { merkleRoot, opReturnData, parseBlock } from "./block";

/** Why outage evidence was refused. */
export type OutageErrorCode =
  | "window-short"
  | "not-at-tip"
  | "link"
  | "gap"
  | "parse"
  | "tx-64-bytes"
  | "merkle-mutated"
  | "merkle"
  | "anchor-present";

/** The evidence and what it is checked against. */
export interface OutageEvidenceInput {
  /** Hash of the FGM's recorded most-work tip (internal byte order); its chain was verified header by header. */
  readonly tipHash: Uint8Array;
  /** Height of that tip. */
  readonly tipHeight: number;
  /** Number of blocks in the outage window, ending at the tip. */
  readonly windowBlocks: number;
  /** Consecutive 80-byte headers of the window, oldest first, the last being the tip. */
  readonly headers: readonly Uint8Array[];
  /** One raw full block per header, same order. */
  readonly blocks: readonly Uint8Array[];
  /**
   * Narrows which FBK1 payloads count as a valid anchor (for example, those that link into
   * the epoch chain the FGM knows). Interpretation: default counts every well-formed payload,
   * so no one can manufacture an outage by publishing anchors in an unexpected form.
   */
  readonly isValidAnchor?: (commitment: Uint8Array) => boolean;
}

/** Result: evidence accepted, or the first problem found. */
export type OutageResult =
  | { readonly ok: true; readonly fromHeight: number; readonly toHeight: number; readonly transactions: number }
  | { readonly ok: false; readonly code: OutageErrorCode; readonly height: number; readonly message: string };

/** Every 36-byte FBK1 payload inside OP_RETURN data (the magic may sit anywhere in the pushed bytes). */
function anchorsIn(data: Uint8Array): Uint8Array[] {
  const out: Uint8Array[] = [];
  for (let i = 0; i + 36 <= data.length; i++) {
    if (equalBytes(data.subarray(i, i + ANCHOR_MAGIC.length), ANCHOR_MAGIC)) {
      const c = parseAnchorPayload(data.slice(i, i + 36));
      if (c) out.push(c);
    }
  }
  return out;
}

/** Checks outage evidence: the window's full blocks match the verified headers and carry no valid anchor. */
export function verifyOutageEvidence(input: OutageEvidenceInput): OutageResult {
  const { headers, blocks, windowBlocks, tipHeight } = input;
  const fromHeight = tipHeight - headers.length + 1;
  const fail = (code: OutageErrorCode, i: number, message: string): OutageResult => ({ ok: false, code, height: fromHeight + i, message });

  if (!(windowBlocks >= 1) || headers.length < windowBlocks) {
    return fail("window-short", 0, `need ${windowBlocks} headers, got ${headers.length}`);
  }
  const last = headers[headers.length - 1]!;
  if (last.length !== HEADER_LEN || !equalBytes(hash256(last), input.tipHash)) {
    return fail("not-at-tip", headers.length - 1, "the window does not end at the recorded tip");
  }
  // Each header must be the parent of the next, so the run is the FGM's own chain below its tip.
  for (let i = 1; i < headers.length; i++) {
    if (headers[i - 1]!.length !== HEADER_LEN || !equalBytes(parseHeader(headers[i]!).prevHash, hash256(headers[i - 1]!))) {
      return fail("link", i, "headers are not consecutive");
    }
  }

  let transactions = 0;
  for (let i = 0; i < headers.length; i++) {
    const raw = blocks[i];
    if (raw === undefined || raw.length < HEADER_LEN || !equalBytes(raw.subarray(0, HEADER_LEN), headers[i]!)) {
      return fail("gap", i, "the block for this header is missing");
    }
    let block;
    try {
      block = parseBlock(raw);
    } catch (e) {
      return fail("parse", i, (e as Error).message);
    }
    // A 64-byte transaction can pose as an inner Merkle node and hide a subtree (BIP54 makes them invalid).
    const tiny = block.txs.findIndex((t) => t.baseSize === 64);
    if (tiny >= 0) return fail("tx-64-bytes", i, `transaction ${tiny} is 64 bytes`);
    const { root, mutated } = merkleRoot(block.txs.map((t) => t.txid));
    if (mutated) return fail("merkle-mutated", i, "duplicate transactions in the Merkle tree");
    if (!equalBytes(root, block.header.merkleRoot)) return fail("merkle", i, "transactions do not match the header's Merkle root");
    for (const tx of block.txs) {
      for (const out of tx.outputs) {
        const data = opReturnData(out.script);
        if (!data) continue;
        for (const c of anchorsIn(data)) {
          if (input.isValidAnchor === undefined || input.isValidAnchor(c)) {
            return fail("anchor-present", i, "an epoch anchor was found in this block");
          }
        }
      }
    }
    transactions += block.txs.length;
  }
  return { ok: true, fromHeight, toHeight: tipHeight, transactions };
}

View on GitHub

src/beacon/params.ts53 lines
/**
 * Consensus parameters the header verifier needs.
 */
import { decodeCompact } from "./compact";

/** Proof-of-work parameters of one Bitcoin network. */
export interface ChainParams {
  readonly name: string;
  /** Easiest allowed target. */
  readonly powLimit: bigint;
  /** Target block spacing in seconds (600). */
  readonly targetSpacing: number;
  /** Target timespan of one difficulty period in seconds (two weeks). */
  readonly targetTimespan: number;
  /** Regtest never retargets. */
  readonly noRetargeting: boolean;
}

/** Blocks per difficulty period: targetTimespan / targetSpacing = 2016 on every network. */
export function periodLength(p: ChainParams): number {
  return p.targetTimespan / p.targetSpacing;
}

/** Bitcoin mainnet (powLimit is the target of nBits 0x1d00ffff). */
export const MAINNET: ChainParams = {
  name: "mainnet",
  powLimit: (1n << 224n) - 1n,
  targetSpacing: 600,
  targetTimespan: 14 * 24 * 60 * 60,
  noRetargeting: false,
};

/** Bitcoin regtest (powLimit 0x7fff...; blocks carry nBits 0x207fffff). */
export const REGTEST: ChainParams = {
  name: "regtest",
  powLimit: (1n << 255n) - 1n,
  targetSpacing: 600,
  targetTimespan: 14 * 24 * 60 * 60,
  noRetargeting: true,
};

/** nBits used by every regtest block. */
export const REGTEST_BITS = 0x207fffff;

/** nBits of the mainnet genesis block (and of powLimit). */
export const MAINNET_GENESIS_BITS = 0x1d00ffff;

/** Mainnet genesis block hash, explorer byte order. */
export const MAINNET_GENESIS_HASH = "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f";

/** The target that nBits 0x1d00ffff encodes, the reference for "difficulty 1". */
export const DIFFICULTY_1_TARGET: bigint = decodeCompact(MAINNET_GENESIS_BITS).target;

View on GitHub

src/beacon/time.ts159 lines
/**
 * Two-sided time bounds for the FGM and a header-withholding detector.
 *
 * Lower bound: Bitcoin nodes reject a block whose timestamp is more than two
 * hours ahead of their clock, so once a header exists real time was at least
 * its timestamp minus 7200 s. Upper bound: the local oscillators, which no one
 * outside the enclosure controls, bound elapsed real time by (1 + eps) times
 * what they counted (feed `oscillatorElapsed` from checkOscillators in license.ts). Headers cannot give an upper bound because an operator can
 * withhold them; the pace check below turns withholding into a visible state.
 */
import { medianTimePast, type ChainAnchor } from "./verify";

/** Nodes reject blocks more than this many seconds in the future (Bitcoin's MAX_FUTURE_BLOCK_TIME). */
export const MAX_FUTURE_BLOCK_TIME = 7200;

/** Which header timestamp the lower bound uses. */
export type LowerBoundRule = "max-timestamp" | "median-time-past";

/** Inputs to the time bounds, all in seconds. */
export interface TimeBoundsInput {
  /** Newest accepted chain state. */
  readonly anchor: ChainAnchor;
  /** Upper bound on real time at the last sync point (carried from the previous state). */
  readonly tSyncHi: number;
  /** Seconds the local oscillator has counted since that sync point. */
  readonly oscillatorElapsed: number;
  /** Oscillator tolerance: real elapsed time is at most (1 + eps) times the counted time. */
  readonly eps: number;
  /** Default "max-timestamp". "median-time-past" costs an attacker six blocks instead of one. */
  readonly rule?: LowerBoundRule;
}

/** A closed interval [tLo, tHi] that real time lies in, if the inputs are honest. */
export interface TimeBounds {
  readonly tLo: number;
  readonly tHi: number;
  /** False when tLo > tHi: the headers and the oscillator contradict each other. */
  readonly consistent: boolean;
}

/** Computes tLo from the chain and tHi from the oscillator, and flags a contradiction. */
export function timeBounds(input: TimeBoundsInput): TimeBounds {
  const { anchor, tSyncHi, oscillatorElapsed, eps } = input;
  if (!(oscillatorElapsed >= 0) || !(eps >= 0)) throw new Error("elapsed and eps must be non-negative");
  const base = (input.rule ?? "max-timestamp") === "max-timestamp" ? anchor.maxTimestamp : medianTimePast(anchor.timestamps);
  const tLo = base - MAX_FUTURE_BLOCK_TIME;
  const tHi = tSyncHi + (1 + eps) * oscillatorElapsed;
  return { tLo, tHi, consistent: tLo <= tHi };
}

/** Conservative expiry: expired as soon as the latest time it could be (tHi) reaches `expiresAt`. */
export function isExpiredConservative(bounds: TimeBounds, expiresAt: number): boolean {
  return bounds.tHi >= expiresAt;
}

/** The paper's second expiry: a license valid for heights up to hTo ends once the accepted chain passes hTo. */
export function isExpiredByHeight(anchor: ChainAnchor, hTo: number): boolean {
  return anchor.height > hTo;
}

/** Natural log of the Poisson(mu) probability mass at k. */
function logPmf(k: number, mu: number): number {
  let lnFact = 0;
  for (let i = 2; i <= k; i++) lnFact += Math.log(i);
  return -mu + k * Math.log(mu) - lnFact;
}

/** log(exp(a) + exp(b)) without overflow. */
function logAdd(a: number, b: number): number {
  if (a === -Infinity) return b;
  if (b === -Infinity) return a;
  const m = Math.max(a, b);
  return m + Math.log(Math.exp(a - m) + Math.exp(b - m));
}

/** P(X <= k) for X ~ Poisson(mu), computed in log space so tiny tails stay accurate. */
export function poissonCdf(k: number, mu: number): number {
  if (k < 0) return 0;
  if (mu === 0) return 1;
  let term = -mu;
  let acc = term;
  for (let i = 1; i <= k; i++) {
    term += Math.log(mu) - Math.log(i);
    acc = logAdd(acc, term);
  }
  return Math.min(1, Math.exp(acc));
}

/** P(X >= k) for X ~ Poisson(mu), summed upward from k so tiny tails stay accurate. */
export function poissonSf(k: number, mu: number): number {
  if (k <= 0) return 1;
  if (mu === 0) return 0;
  let term = logPmf(k, mu);
  let acc = term;
  for (let i = k + 1; ; i++) {
    term += Math.log(mu) - Math.log(i);
    acc = logAdd(acc, term);
    if (i > mu && term < acc - 40) break;
  }
  return Math.min(1, Math.exp(acc));
}

/** Smallest header count that is not "stale" for Poisson mean mu at tail probability p. */
export function minPlausibleCount(mu: number, p: number): number {
  let k = 0;
  while (poissonCdf(k, mu) < p) k++;
  return k;
}

/** Pace of headers against the oscillator: ok, stale (withheld) or ahead (more than time allows). */
export type PaceStatus = "ok" | "stale" | "ahead";

/** Inputs to the pace check. */
export interface PaceInput {
  /** Headers accepted since the sync point. */
  readonly headers: number;
  /** Oscillator seconds since the sync point. */
  readonly oscillatorElapsed: number;
  readonly eps: number;
  /** Tail probability for both alarms. Default 1e-6. */
  readonly p?: number;
  /** Mean block interval in seconds. Default 600. */
  readonly spacing?: number;
  /**
   * Interpretation: multiplies the expected block rate for the stale test, to allow for
   * a sudden hashrate drop before the next retarget. Default 1 (the plain Poisson(T/600) test).
   */
  readonly minRateFactor?: number;
  /** Interpretation: the same allowance for a hashrate rise in the "ahead" test. Default 1. */
  readonly maxRateFactor?: number;
}

/** Result of the pace check, with the tail probabilities behind it. */
export interface PaceResult {
  readonly status: PaceStatus;
  /** P(X <= headers) under the slowest plausible elapsed time. */
  readonly pLow: number;
  /** P(X >= headers) under the fastest plausible elapsed time. */
  readonly pHigh: number;
  /** Fewest headers that would not be stale. */
  readonly minHeaders: number;
}

/** Flags withholding ("stale") or impossible speed ("ahead") at tail probability p. */
export function checkPace(input: PaceInput): PaceResult {
  const p = input.p ?? 1e-6;
  const spacing = input.spacing ?? 600;
  const rateLow = input.minRateFactor ?? 1;
  const rateHigh = input.maxRateFactor ?? 1;
  if (!(input.oscillatorElapsed >= 0) || !(input.eps >= 0) || !(input.headers >= 0)) throw new Error("bad pace input");
  // Real elapsed time lies in [counted / (1 + eps), counted * (1 + eps)].
  const muLow = (rateLow * input.oscillatorElapsed) / (1 + input.eps) / spacing;
  const muHigh = (rateHigh * input.oscillatorElapsed * (1 + input.eps)) / spacing;
  const pLow = poissonCdf(input.headers, muLow);
  const pHigh = poissonSf(input.headers, muHigh);
  const status: PaceStatus = pLow < p ? "stale" : pHigh < p ? "ahead" : "ok";
  return { status, pLow, pHigh, minHeaders: minPlausibleCount(muLow, p) };
}

View on GitHub

src/beacon/verify.ts228 lines
/**
 * Header-chain verification for the Bitcoin time beacon.
 *
 * The verifier extends a trusted anchor (the checkpoint a license carries) with
 * a run of headers and checks, for each one: the 80-byte format, the link to the
 * previous hash, the nBits encoding, Bitcoin's exact retarget rule (or "no change"
 * inside a period), proof of work, the median-time-past rule and the difficulty
 * floor. It accumulates chainwork so the caller can keep the most-work tip.
 */
import { equalBytes } from "@noble/curves/utils.js";
import { decodeCompact, encodeCompact, workForTarget } from "./compact";
import { hashToBigInt, parseHeader, type BlockHeader } from "./header";
import { periodLength, type ChainParams } from "./params";

/** Number of previous timestamps whose median a new header must exceed. */
export const MTP_WINDOW = 11;

/** What the verifier knows about the chain up to its current tip. */
export interface ChainAnchor {
  readonly height: number;
  /** Tip hash, internal byte order. */
  readonly hash: Uint8Array;
  /** Tip nBits. */
  readonly bits: number;
  /** Cumulative work up to the tip, relative to whatever base the first anchor used. */
  readonly chainwork: bigint;
  /** Up to the last 11 timestamps, oldest first, ending with the tip's. */
  readonly timestamps: readonly number[];
  /** Largest timestamp among all headers accepted so far. */
  readonly maxTimestamp: number;
  /** Timestamp of the first block of the tip's difficulty period, or null if unknown. */
  readonly periodStartTime: number | null;
}

/** A trusted checkpoint, as a license would carry it. */
export interface Checkpoint {
  readonly height: number;
  /** Block hash, internal byte order. */
  readonly hash: Uint8Array;
  readonly bits: number;
}

/** Why a header was rejected. */
export type HeaderErrorCode =
  | "length"
  | "link"
  | "bits-encoding"
  | "pow-limit"
  | "bits-changed"
  | "retarget"
  | "period-unknown"
  | "pow"
  | "floor"
  | "timestamp-mtp"
  | "checkpoint";

/** Outcome of verifying a header run. */
export type VerifyResult =
  | { readonly ok: true; readonly anchor: ChainAnchor; readonly accepted: number; readonly work: bigint }
  | {
      readonly ok: false;
      readonly index: number;
      readonly height: number;
      readonly code: HeaderErrorCode;
      readonly message: string;
      /** The anchor after the last header that passed. */
      readonly anchor: ChainAnchor;
    };

/** Options for verification. */
export interface VerifyOptions {
  readonly params: ChainParams;
  /** Largest target (smallest difficulty) any header may have. Omit for no floor. */
  readonly floorTarget?: bigint;
}

/** Median of the given timestamps as Bitcoin computes it (sorted, element n/2). */
export function medianTimePast(timestamps: readonly number[]): number {
  if (timestamps.length === 0) throw new Error("no timestamps");
  const sorted = [...timestamps].sort((a, b) => a - b);
  return sorted[Math.floor(sorted.length / 2)]!;
}

/** Bitcoin's retarget: last period's target scaled by its clamped timespan, capped at powLimit. */
export function nextRetargetBits(
  lastBits: number,
  periodFirstTime: number,
  lastTime: number,
  params: ChainParams,
): number {
  const T = params.targetTimespan;
  let span = lastTime - periodFirstTime;
  if (span < T / 4) span = T / 4;
  if (span > T * 4) span = T * 4;
  let target = (decodeCompact(lastBits).target * BigInt(span)) / BigInt(T);
  if (target > params.powLimit) target = params.powLimit;
  return encodeCompact(target);
}

/**
 * The factor k in d_min = difficulty(h) / k: the most Bitcoin's retargeting can lower
 * difficulty during a license of `licenseSeconds`. One adjustment may land right after
 * h and lower it by up to 4x; every later one lowers it only if its period took longer
 * than the target timespan T, so at most ceil(lambda / T) - 1 more, each at most 4x.
 * Interpretation: k = 4^(1 + max(0, ceil(lambda / T) - 1)), which is 4 for licenses up to two weeks.
 */
export function licenseFloorFactor(licenseSeconds: number, params: ChainParams): number {
  if (!(licenseSeconds > 0)) throw new Error("license period must be positive");
  if (params.noRetargeting) return 1;
  return 4 ** (1 + Math.max(0, Math.ceil(licenseSeconds / params.targetTimespan) - 1));
}

/** The license's floor target: the target at block h times licenseFloorFactor, capped at powLimit (d_min = difficulty(h) / k). */
export function licenseFloor(bitsAtH: number, licenseSeconds: number, params: ChainParams): bigint {
  return floorFromCheckpoint(bitsAtH, params, licenseFloorFactor(licenseSeconds, params));
}

/** The checkpoint's target times `factor` (one maximal retarget drop by default), capped at powLimit. */
export function floorFromCheckpoint(checkpointBits: number, params: ChainParams, factor = 4): bigint {
  if (!(factor >= 1) || !Number.isInteger(factor)) throw new Error("floor factor must be an integer >= 1");
  const t = decodeCompact(checkpointBits).target * BigInt(factor);
  return t > params.powLimit ? params.powLimit : t;
}

/**
 * Builds an anchor from consecutive headers that end at a trusted checkpoint.
 * The earlier headers only supply median-time-past context; their links are checked.
 * `periodStartTime` is needed unless the checkpoint is itself the first block of a period.
 */
export function anchorFromHistory(
  history: readonly Uint8Array[],
  checkpoint: Checkpoint,
  params: ChainParams,
  periodStartTime?: number,
): { ok: true; anchor: ChainAnchor } | { ok: false; message: string } {
  if (history.length === 0) return { ok: false, message: "empty history" };
  let parsed: BlockHeader[];
  try {
    parsed = history.map((raw) => parseHeader(raw));
  } catch (e) {
    return { ok: false, message: (e as Error).message };
  }
  for (let i = 1; i < parsed.length; i++) {
    if (!equalBytes(parsed[i]!.prevHash, parsed[i - 1]!.hash)) return { ok: false, message: `history link broken at ${i}` };
  }
  const tip = parsed[parsed.length - 1]!;
  if (!equalBytes(tip.hash, checkpoint.hash) || tip.bits !== checkpoint.bits) {
    return { ok: false, message: "history does not end at the checkpoint" };
  }
  const timestamps = parsed.slice(-MTP_WINDOW).map((h) => h.timestamp);
  const startsPeriod = checkpoint.height % periodLength(params) === 0;
  return {
    ok: true,
    anchor: {
      height: checkpoint.height,
      hash: tip.hash,
      bits: tip.bits,
      chainwork: 0n,
      timestamps,
      maxTimestamp: Math.max(...parsed.map((h) => h.timestamp)),
      periodStartTime: startsPeriod ? tip.timestamp : (periodStartTime ?? null),
    },
  };
}

/** Verifies headers that extend `anchor`, stopping at the first failure. */
export function verifyHeaders(anchor: ChainAnchor, headers: readonly Uint8Array[], opts: VerifyOptions): VerifyResult {
  const { params, floorTarget } = opts;
  const period = periodLength(params);
  let cur = anchor;
  let work = 0n;
  const fail = (index: number, code: HeaderErrorCode, message: string): VerifyResult => ({
    ok: false,
    index,
    height: cur.height + 1,
    code,
    message,
    anchor: cur,
  });

  for (let i = 0; i < headers.length; i++) {
    const raw = headers[i]!;
    if (raw.length !== 80) return fail(i, "length", `header is ${raw.length} bytes`);
    const h = parseHeader(raw);
    const height = cur.height + 1;

    if (!equalBytes(h.prevHash, cur.hash)) return fail(i, "link", "prevHash does not match the tip");

    const { target, negative, overflow } = decodeCompact(h.bits);
    if (negative || overflow || target === 0n) return fail(i, "bits-encoding", `invalid nBits 0x${h.bits.toString(16)}`);
    if (target > params.powLimit) return fail(i, "pow-limit", "target above powLimit");

    if (params.noRetargeting || height % period !== 0) {
      if (h.bits !== cur.bits) return fail(i, "bits-changed", "nBits changed inside a difficulty period");
    } else {
      if (cur.periodStartTime === null) return fail(i, "period-unknown", "retarget needs the period's first timestamp");
      const want = nextRetargetBits(cur.bits, cur.periodStartTime, cur.timestamps[cur.timestamps.length - 1]!, params);
      if (h.bits !== want) {
        return fail(i, "retarget", `retarget nBits 0x${h.bits.toString(16)}, expected 0x${want.toString(16)}`);
      }
    }

    if (hashToBigInt(h.hash) > target) return fail(i, "pow", "hash above target");
    if (floorTarget !== undefined && target > floorTarget) return fail(i, "floor", "target above the difficulty floor");

    const mtp = medianTimePast(cur.timestamps);
    if (h.timestamp <= mtp) return fail(i, "timestamp-mtp", `timestamp ${h.timestamp} not after median ${mtp}`);

    const w = workForTarget(target);
    work += w;
    cur = {
      height,
      hash: h.hash,
      bits: h.bits,
      chainwork: cur.chainwork + w,
      timestamps: [...cur.timestamps, h.timestamp].slice(-MTP_WINDOW),
      maxTimestamp: Math.max(cur.maxTimestamp, h.timestamp),
      periodStartTime: height % period === 0 ? h.timestamp : cur.periodStartTime,
    };
  }
  return { ok: true, anchor: cur, accepted: headers.length, work };
}

/** Keeps the tip with the most cumulative work (not the greatest height); refuses any candidate that would not move it forward. */
export function chooseTip(current: ChainAnchor, candidate: ChainAnchor): { anchor: ChainAnchor; moved: boolean } {
  return candidate.chainwork > current.chainwork ? { anchor: candidate, moved: true } : { anchor: current, moved: false };
}

View on GitHub

src/beacon/index.ts71 lines
/**
 * The Bitcoin time beacon: a header-chain verifier with a difficulty floor,
 * most-work branch selection, two-sided time bounds from the chain and the FGM's
 * two oscillators, the license clock, and outage evidence from full blocks. See SPEC.md.
 */
export { decodeCompact, difficulty, encodeCompact, workForTarget, type DecodedTarget } from "./compact";
export {
  displayHash,
  hash256,
  hashFromDisplay,
  hashToBigInt,
  HEADER_LEN,
  parseHeader,
  parseHeaderHex,
  serializeHeader,
  type BlockHeader,
} from "./header";
export {
  DIFFICULTY_1_TARGET,
  MAINNET,
  MAINNET_GENESIS_BITS,
  MAINNET_GENESIS_HASH,
  periodLength,
  REGTEST,
  REGTEST_BITS,
  type ChainParams,
} from "./params";
export {
  anchorFromHistory,
  chooseTip,
  floorFromCheckpoint,
  licenseFloor,
  licenseFloorFactor,
  medianTimePast,
  MTP_WINDOW,
  nextRetargetBits,
  verifyHeaders,
  type ChainAnchor,
  type Checkpoint,
  type HeaderErrorCode,
  type VerifyOptions,
  type VerifyResult,
} from "./verify";
export {
  checkPace,
  isExpiredByHeight,
  isExpiredConservative,
  MAX_FUTURE_BLOCK_TIME,
  minPlausibleCount,
  poissonCdf,
  poissonSf,
  timeBounds,
  type LowerBoundRule,
  type PaceInput,
  type PaceResult,
  type PaceStatus,
  type TimeBounds,
  type TimeBoundsInput,
} from "./time";
export { beaconState, submitBranch, type BeaconState, type BranchResult } from "./branch";
export {
  checkOscillators,
  licenseClock,
  type LicenseClockState,
  type LicenseTerms,
  type OscillatorCheck,
  type OscillatorCounts,
} from "./license";
export { merkleRoot, opReturnData, parseBlock, type ParsedBlock, type ParsedTx, type TxOutput } from "./block";
export { verifyOutageEvidence, type OutageErrorCode, type OutageEvidenceInput, type OutageResult } from "./outage";

View on GitHub