@secondlayer/verify 0.5.3 → 0.5.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,8 +1,10 @@
1
+ /** A byte string, held as a Uint8Array. */
1
2
  type Bytes = Uint8Array;
2
3
  /** Encodes bytes as a lowercase hex string. */
3
4
  declare const hex: (b: Bytes) => string;
4
5
  /** Hex to bytes; tolerates a 0x prefix. */
5
6
  declare const unhex: (s: string) => Bytes;
7
+ /** A Nakamoto-era Stacks block header. */
6
8
  interface NakamotoHeader {
7
9
  /** Low 7 bits = header version; high bit = shadow block. */
8
10
  version: number;
@@ -56,6 +58,7 @@ interface Epoch2Header {
56
58
  blockHash: Bytes;
57
59
  consensusHash: Bytes;
58
60
  }
61
+ /** A Stacks block header from either era. */
59
62
  type StacksHeader = NakamotoHeader | Epoch2Header;
60
63
  /**
61
64
  * Parses the epoch 2.x block header at the start of `raw`.
@@ -86,6 +89,7 @@ declare function marfValue(value: string): Bytes;
86
89
  * header hashes to the id the trie committed. Malformed proofs yield no ids.
87
90
  */
88
91
  declare function marfProofAncestors(proof: Bytes): string[];
92
+ /** A MARF proof with the leaf path and value it covers. */
89
93
  interface MarfProofInput {
90
94
  /** Consensus-serialized TrieMerkleProof (`/v2/clarity/marf/<path>?proof=1`). */
91
95
  proof: Bytes;
@@ -117,6 +121,7 @@ interface WitnessLeaf {
117
121
  /** 32-byte value hash (first 32 bytes of the MARFValue; the tail is zero). */
118
122
  valueHash: Bytes;
119
123
  }
124
+ /** A recomputed trie root, its ancestor roots, and leaves. */
120
125
  interface StateWitness {
121
126
  /** Recomputed trie root; compare to the authenticated header's state_index_root. */
122
127
  root: Bytes;
@@ -130,6 +135,7 @@ interface StateWitness {
130
135
  * The result proves nothing until `root` equals a header's state_index_root.
131
136
  */
132
137
  declare function parseWitness(bytes: Bytes): StateWitness;
138
+ /** The witness leaves, claimed writes, and bookkeeping keys to classify. */
133
139
  interface BlockDiffInput {
134
140
  /** `parseWitness(bytes).leaves`, from a witness whose root was checked. */
135
141
  leaves: WitnessLeaf[];
@@ -143,6 +149,7 @@ interface BlockDiffInput {
143
149
  interface ClassifiedLeaf extends WitnessLeaf {
144
150
  key: string;
145
151
  }
152
+ /** A block's witnessed leaves, split into writes, carried, and internal. */
146
153
  interface BlockDiff {
147
154
  /** Leaves matching a claimed write (path and value). */
148
155
  writes: ClassifiedLeaf[];
@@ -174,6 +181,7 @@ type SignerSet = Map<string, bigint>;
174
181
  * `(some (list (tuple (signer principal) (weight uint) ...)))`.
175
182
  */
176
183
  declare function decodeSignerSet(value: string | Bytes): SignerSet;
184
+ /** Whether the signed weight meets the threshold with known signers. */
177
185
  interface SignerCheck {
178
186
  /** Signed weight meets the threshold, and every signature is a distinct known signer. */
179
187
  valid: boolean;
@@ -238,6 +246,7 @@ interface BlockHeader {
238
246
  bits: number;
239
247
  nonce: number;
240
248
  }
249
+ /** A Bitcoin header rule a chain check can fail on. */
241
250
  type HeaderRule = "checkpoint" | "format" | "prev-link" | "bits" | "retarget" | "median-time-past" | "version" | "proof-of-work";
242
251
  /**
243
252
  * Thrown when a Bitcoin header fails a validation rule.
@@ -250,6 +259,7 @@ declare class HeaderValidationError extends Error {
250
259
  readonly name = "HeaderValidationError";
251
260
  constructor(height: number, rule: HeaderRule, detail: string);
252
261
  }
262
+ /** A trusted Bitcoin header that anchors header validation. */
253
263
  interface Checkpoint {
254
264
  height: number;
255
265
  /** Raw 80-byte header, bytes or hex. Trusted without validation. */
@@ -261,6 +271,7 @@ interface Checkpoint {
261
271
  */
262
272
  periodStartTime?: number;
263
273
  }
274
+ /** A Bitcoin header with its height, hash, and raw bytes. */
264
275
  interface ChainEntry {
265
276
  height: number;
266
277
  /** Display-order hex. */
@@ -307,6 +318,7 @@ declare class HeaderChain {
307
318
  * (burn height 967,680 or later); earlier ones by hash chain from 9,055,251.
308
319
  */
309
320
  declare const MAINNET_CHECKPOINT: VerifyCheckpoint;
321
+ /** A trusted Stacks header and signer set to start verification from. */
310
322
  interface VerifyCheckpoint {
311
323
  stacks: {
312
324
  /** Raw Nakamoto header (hex) of a trusted block whose state holds `signerSet`. */
@@ -355,7 +367,7 @@ interface VmEventRow {
355
367
  raw_key?: string | null;
356
368
  raw_value?: string | null;
357
369
  }
358
- /** An epoch 2.x header and the consensus hash its index block hash commits to. */
370
+ /** An epoch 2.x header and the consensus hash it commits to. */
359
371
  interface Epoch2HeaderResponse {
360
372
  /** Consensus-serialized StacksBlockHeader. */
361
373
  header: Bytes;
@@ -404,6 +416,7 @@ declare class SourceError extends Error {
404
416
  type Fetch = (url: string, init?: RequestInit) => Promise<Response>;
405
417
  /** The hosted API. */
406
418
  declare const DEFAULT_API_URL = "https://api.secondlayer.tools";
419
+ /** Options for reading proofs from the Secondlayer API. */
407
420
  interface SecondlayerSourceOptions {
408
421
  /** API origin. Defaults to {@link DEFAULT_API_URL}. */
409
422
  baseUrl?: string;
@@ -451,6 +464,7 @@ declare class SecondlayerProofSource implements ProofSource {
451
464
  getVmEvents: (height: number) => Promise<VmEventRow[]>;
452
465
  constructor(opts?: SecondlayerSourceOptions);
453
466
  }
467
+ /** Options for reading proofs from a Stacks node. */
454
468
  interface NodeRpcSourceOptions {
455
469
  /** Stacks node RPC origin, e.g. `http://localhost:20443`. */
456
470
  nodeUrl: string;
@@ -512,6 +526,7 @@ interface StateFailure {
512
526
  path?: string;
513
527
  ordinal?: number;
514
528
  }
529
+ /** A block's height, parent, and state root to check rows against. */
515
530
  interface BlockStateInput {
516
531
  /** MARF height of the block (its Stacks chain length). */
517
532
  height: number;
@@ -537,6 +552,7 @@ interface BlockStateInput {
537
552
  */
538
553
  parentHolds?: (leaf: WitnessLeaf) => Promise<boolean>;
539
554
  }
555
+ /** The proven diff, rows checked, notes, and failures. */
540
556
  interface BlockStateResult {
541
557
  diff?: ProvenDiff;
542
558
  rowsChecked: number;
@@ -553,6 +569,7 @@ interface BlockStateResult {
553
569
  * `parentLeaves`, and the remaining writes come back unnamed.
554
570
  */
555
571
  declare function verifyBlockState(input: BlockStateInput): Promise<BlockStateResult>;
572
+ /** A transaction's id and its consensus-serialized bytes. */
556
573
  interface BlockTransaction {
557
574
  /** sha512/256 of the transaction bytes, hex. */
558
575
  txid: string;
@@ -609,6 +626,7 @@ interface Ancestry {
609
626
  */
610
627
  via: "parents" | "marf";
611
628
  }
629
+ /** The result of verifying a block, step by step. */
612
630
  interface BlockVerification {
613
631
  /**
614
632
  * Every step passed. At or above the checkpoint: header, burn binding,
@@ -649,6 +667,7 @@ interface BlockVerification {
649
667
  /** Empty when ok. The first entry is the first broken link. */
650
668
  failures: VerifyFailure[];
651
669
  }
670
+ /** The proof source, checkpoint, and row checking for a block verify. */
652
671
  interface VerifyOptions {
653
672
  source: ProofSource;
654
673
  /** Defaults to MAINNET_CHECKPOINT. */
@@ -799,6 +818,7 @@ declare class BlockVerifier {
799
818
  /** One-shot: verify a block from a checkpoint (MAINNET_CHECKPOINT by default). */
800
819
  declare const verifyBlock: (ref: string | number, opts: VerifyOptions) => Promise<BlockVerification>;
801
820
  type LinkStatus = "ok" | "failed" | "skipped";
821
+ /** One verification step with its status and what it proved. */
802
822
  interface LinkLine {
803
823
  step: VerifyStep;
804
824
  label: string;
package/dist/index.js.map CHANGED
@@ -2,24 +2,24 @@
2
2
  "version": 3,
3
3
  "sources": ["../src/bytes.ts", "../src/header.ts", "../src/marf.ts", "../src/witness.ts", "../src/signers.ts", "../src/burn.ts", "../src/keys.ts", "../src/bitcoin/chain.ts", "../src/bitcoin/header.ts", "../src/bitcoin/pow.ts", "../src/checkpoint-mainnet.ts", "../src/source.ts", "../src/state.ts", "../src/txs.ts", "../src/links.ts", "../src/verify-block.ts"],
4
4
  "sourcesContent": [
5
- "// Byte helpers shared by every codec here. Browser-safe: no Buffer.\nimport { sha512_256 } from \"@noble/hashes/sha2.js\";\nimport { bytesToHex, concatBytes, hexToBytes } from \"@noble/hashes/utils.js\";\n\nexport type Bytes = Uint8Array;\n\n/** Encodes bytes as a lowercase hex string. */\nexport const hex = (b: Bytes): string => bytesToHex(b);\n\n/** Hex to bytes; tolerates a 0x prefix. */\nexport const unhex = (s: string): Bytes =>\n\thexToBytes(s.startsWith(\"0x\") ? s.slice(2) : s);\n\nexport const concat = (parts: Bytes[]): Bytes => concatBytes(...parts);\n\nexport const bytesEqual = (a: Bytes, b: Bytes): boolean => {\n\tif (a.length !== b.length) return false;\n\tfor (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;\n\treturn true;\n};\n\n/** sha512/256 over the concatenation of `parts` (stacks-core TrieHasher). */\nexport const hashAll = (parts: Bytes[]): Bytes => {\n\tconst h = sha512_256.create();\n\tfor (const p of parts) h.update(p);\n\treturn h.digest();\n};\n\n/** Big-endian cursor over consensus-serialized bytes. Throws on overrun. */\nexport class Reader {\n\tpos = 0;\n\tconstructor(readonly buf: Bytes) {}\n\n\tbytes(n: number): Bytes {\n\t\tif (n < 0 || this.pos + n > this.buf.length)\n\t\t\tthrow new Error(`unexpected end of input at ${this.pos} reading ${n}`);\n\t\tconst out = this.buf.subarray(this.pos, this.pos + n);\n\t\tthis.pos += n;\n\t\treturn out;\n\t}\n\n\tprivate view(n: number): DataView {\n\t\tconst b = this.bytes(n);\n\t\treturn new DataView(b.buffer, b.byteOffset, n);\n\t}\n\n\tu8 = (): number => this.bytes(1)[0] as number;\n\tu16 = (): number => this.view(2).getUint16(0);\n\tu32 = (): number => this.view(4).getUint32(0);\n\tu64 = (): bigint => this.view(8).getBigUint64(0);\n\ti64 = (): bigint => this.view(8).getBigInt64(0);\n\n\t/** StacksMessageCodec Vec<T>: u32 count prefix, then items. */\n\tvec<T>(item: () => T, max: number): T[] {\n\t\tconst n = this.u32();\n\t\tif (n > max) throw new Error(`vec length ${n} exceeds ${max}`);\n\t\treturn Array.from({ length: n }, item);\n\t}\n\n\tget done(): boolean {\n\t\treturn this.pos === this.buf.length;\n\t}\n}\n",
6
- "// Stacks block header codecs + identity hashes: Nakamoto (stackslib\n// chainstate/nakamoto/mod.rs NakamotoBlockHeader) and epoch 2.x\n// (chainstate/stacks/block.rs StacksBlockHeader).\nimport { sha512_256 } from \"@noble/hashes/sha2.js\";\nimport { type Bytes, Reader, concat, hashAll } from \"./bytes.ts\";\n\nexport interface NakamotoHeader {\n\t/** Low 7 bits = header version; high bit = shadow block. */\n\tversion: number;\n\tchainLength: bigint;\n\tburnSpent: bigint;\n\tconsensusHash: Bytes;\n\tparentBlockId: Bytes;\n\ttxMerkleRoot: Bytes;\n\tstateIndexRoot: Bytes;\n\ttimestamp: bigint;\n\tminerSignature: Bytes;\n\t/** 65-byte recoverable signatures: recovery id, r, s. */\n\tsignerSignatures: Bytes[];\n\t/** Header bytes minus the signer_signature vec: the signer sighash preimage. */\n\tsignerSighashPreimage: Bytes;\n\t/** Serialized header length; block bytes after this are the transactions. */\n\tbyteLength: number;\n}\n\n/** First header version whose sighash commits to `problematic_txs` (epoch 4.0). */\nconst NAKAMOTO_BLOCK_VERSION_EPOCH_4 = 1;\nconst MAX_SIGNERS = 4000;\nconst MAX_PROBLEMATIC_TXS = 1 << 16;\n\n/**\n * Parse the NakamotoBlockHeader at the start of raw block bytes\n * (`/v3/blocks/<id>`). Handles v0 and v1 (v1 appends `problematic_txs`).\n */\nexport function parseNakamotoHeader(raw: Bytes): NakamotoHeader {\n\tconst r = new Reader(raw);\n\tconst version = r.u8();\n\tconst chainLength = r.u64();\n\tconst burnSpent = r.u64();\n\tconst consensusHash = r.bytes(20);\n\tconst parentBlockId = r.bytes(32);\n\tconst txMerkleRoot = r.bytes(32);\n\tconst stateIndexRoot = r.bytes(32);\n\tconst timestamp = r.u64();\n\tconst minerSignature = r.bytes(65);\n\tconst sigStart = r.pos;\n\tconst signerSignatures = r.vec(() => r.bytes(65), MAX_SIGNERS);\n\tconst sigEnd = r.pos;\n\t// pox_treatment: BitVec<4000> = u16 bit length, then Vec<u8> of exactly ceil(len/8).\n\tconst bits = r.u16();\n\tif (bits === 0 || bits > MAX_SIGNERS)\n\t\tthrow new Error(`bad pox_treatment length ${bits}`);\n\tconst bitBytes = Math.ceil(bits / 8);\n\tif (r.u32() !== bitBytes) throw new Error(\"bad pox_treatment data length\");\n\tr.bytes(bitBytes);\n\tif ((version & 0x7f) >= NAKAMOTO_BLOCK_VERSION_EPOCH_4) {\n\t\t// problematic_txs: Vec<(u32 index, u8 marker)>\n\t\tr.vec(() => r.bytes(5), MAX_PROBLEMATIC_TXS);\n\t}\n\tconst end = r.pos;\n\treturn {\n\t\tversion,\n\t\tchainLength,\n\t\tburnSpent,\n\t\tconsensusHash,\n\t\tparentBlockId,\n\t\ttxMerkleRoot,\n\t\tstateIndexRoot,\n\t\ttimestamp,\n\t\tminerSignature,\n\t\tsignerSignatures,\n\t\tsignerSighashPreimage: concat([\n\t\t\traw.subarray(0, sigStart),\n\t\t\traw.subarray(sigEnd, end),\n\t\t]),\n\t\tbyteLength: end,\n\t};\n}\n\n/**\n * Hashes a Nakamoto header the way its signers sign it.\n *\n * It is sha512/256 over every header field except the signer signatures, which\n * is also the header's `block_hash`.\n */\nexport const signerSignatureHash = (h: NakamotoHeader): Bytes =>\n\tsha512_256(h.signerSighashPreimage);\n\n/**\n * Epoch 2.x anchored block header. It commits to the parent's block hash, not\n * its index block hash, and carries no consensus hash: the source supplies\n * that, and `blockId` binds it to an id proven elsewhere.\n */\nexport interface Epoch2Header {\n\tversion: number;\n\t/** total_work.burn: burn spent on the fork so far. */\n\tburnSpent: bigint;\n\t/** total_work.work: the Stacks chain length (one per anchored block). */\n\tchainLength: bigint;\n\tvrfProof: Bytes;\n\tparentBlockHash: Bytes;\n\tparentMicroblock: Bytes;\n\tparentMicroblockSequence: number;\n\ttxMerkleRoot: Bytes;\n\t/** Covers the block and the parent microblock stream it confirms. */\n\tstateIndexRoot: Bytes;\n\tmicroblockPubkeyHash: Bytes;\n\t/** sha512/256 of the serialized header. */\n\tblockHash: Bytes;\n\tconsensusHash: Bytes;\n}\n\nexport type StacksHeader = NakamotoHeader | Epoch2Header;\n\n/** StacksBlockHeader is fixed width: no signatures, no variable fields. */\nexport const EPOCH2_HEADER_LENGTH = 247;\n\n/**\n * Parses the epoch 2.x block header at the start of `raw`.\n *\n * `raw` is a header from `/v2/headers`, or block bytes from `/v2/blocks/<id>`.\n * `consensusHash` is the 20-byte hash of the sortition that elected the block.\n */\nexport function parseEpoch2Header(\n\traw: Bytes,\n\tconsensusHash: Bytes,\n): Epoch2Header {\n\tif (consensusHash.length !== 20)\n\t\tthrow new Error(`consensus hash is ${consensusHash.length} bytes, not 20`);\n\tconst r = new Reader(raw);\n\tconst header: Omit<Epoch2Header, \"blockHash\" | \"consensusHash\"> = {\n\t\tversion: r.u8(),\n\t\tburnSpent: r.u64(),\n\t\tchainLength: r.u64(),\n\t\tvrfProof: r.bytes(80),\n\t\tparentBlockHash: r.bytes(32),\n\t\tparentMicroblock: r.bytes(32),\n\t\tparentMicroblockSequence: r.u16(),\n\t\ttxMerkleRoot: r.bytes(32),\n\t\tstateIndexRoot: r.bytes(32),\n\t\tmicroblockPubkeyHash: r.bytes(20),\n\t};\n\treturn {\n\t\t...header,\n\t\tblockHash: sha512_256(raw.subarray(0, EPOCH2_HEADER_LENGTH)),\n\t\tconsensusHash,\n\t};\n}\n\n/** Narrows a Stacks header to an epoch 2.x header. */\nexport const isEpoch2Header = (h: StacksHeader): h is Epoch2Header =>\n\t\"parentBlockHash\" in h;\n\n/**\n * Computes a header's block id, also called the index block hash.\n *\n * The id is sha512/256(block_hash || consensus_hash). A Nakamoto block hash is\n * its signer signature hash; a 2.x one hashes the whole header.\n */\nexport const blockId = (h: StacksHeader): Bytes =>\n\thashAll([\n\t\tisEpoch2Header(h) ? h.blockHash : signerSignatureHash(h),\n\t\th.consensusHash,\n\t]);\n",
7
- "// MARF hashing primitives + TrieMerkleProof decode/verify.\n// Independent port of stacks-core stackslib/src/chainstate/stacks/index/{proofs,bits,node}.rs.\n// TrieHasher is sha512/256 everywhere.\nimport { sha512_256 } from \"@noble/hashes/sha2.js\";\nimport {\n\ttype Bytes,\n\tReader,\n\tbytesEqual,\n\tconcat,\n\thashAll,\n\thex,\n} from \"./bytes.ts\";\nimport { type StacksHeader, blockId } from \"./header.ts\";\n\n/** MARFValue width: 32-byte value hash + 8 zero bytes. */\nexport const MARF_VALUE_SIZE = 40;\n\nexport const NodeId = {\n\tEmpty: 0,\n\tLeaf: 1,\n\tNode4: 2,\n\tNode16: 3,\n\tNode48: 4,\n\tNode256: 5,\n} as const;\n\n/** Pointer count per node type id (Node4..Node256). */\nexport const NODE_PTR_COUNT: Readonly<Record<number, number>> = {\n\t[NodeId.Node4]: 4,\n\t[NodeId.Node16]: 16,\n\t[NodeId.Node48]: 48,\n\t[NodeId.Node256]: 256,\n};\n\n/** Backptr flag on a TriePtr id: child lives in an ancestor block's trie. */\nexport const isBackptr = (id: number): boolean => (id & 0x80) !== 0;\n\nexport interface TriePtr {\n\tid: number;\n\tchr: number;\n\t/** Ancestor block id for backptrs; 32 zero bytes otherwise. */\n\tbackBlock: Bytes;\n}\n\nexport interface TrieNode {\n\tid: number;\n\tpath: Bytes;\n\tptrs: TriePtr[];\n}\n\n/** Hashes a key to its MARF path: sha512/256 of the UTF-8 key. */\nexport const marfPath = (key: string): Bytes =>\n\tsha512_256(new TextEncoder().encode(key));\n\n/**\n * `__MARF_BLOCK_HEIGHT_TO_HASH::<height>` (index/marf.rs set_block_heights):\n * block `height + 1` stores its parent's id here as a raw MARFValue, so a\n * proof of it at any descendant names that descendant's ancestor at `height`.\n */\nexport const heightToHashKey = (height: number): string =>\n\t`__MARF_BLOCK_HEIGHT_TO_HASH::${height}`;\n\n/** Hashes a value to its MARF value: sha512/256, padded to 40 bytes. */\nexport function marfValue(value: string): Bytes {\n\tconst v = new Uint8Array(MARF_VALUE_SIZE);\n\tv.set(sha512_256(new TextEncoder().encode(value)));\n\treturn v;\n}\n\n// ---------- hashing (bits.rs) ----------\n\nfunction pathPreimage(path: Bytes): Bytes {\n\tif (path.length > 32) throw new Error(\"trie path longer than 32 bytes\");\n\treturn concat([Uint8Array.of(path.length), path]);\n}\n\n/** get_leaf_hash: H(Leaf id || path len || path || 40-byte value). */\nexport const leafHash = (path: Bytes, value: Bytes): Bytes =>\n\thashAll([Uint8Array.of(NodeId.Leaf), pathPreimage(path), value]);\n\n/** get_node_hash: H(id || ptrs(id, chr, back_block) || path len || path || child hashes). */\nexport function nodeHash(node: TrieNode, children: Bytes[]): Bytes {\n\tconst parts: Bytes[] = [Uint8Array.of(node.id)];\n\tfor (const p of node.ptrs)\n\t\tparts.push(Uint8Array.of(p.id, p.chr), p.backBlock);\n\tparts.push(pathPreimage(node.path), ...children);\n\treturn hashAll(parts);\n}\n\n// ---------- proof codec ----------\n\ntype NodeKind = \"Node4\" | \"Node16\" | \"Node48\" | \"Node256\";\nconst PROOF_KIND = [\n\t\"Node4\",\n\t\"Node16\",\n\t\"Node48\",\n\t\"Node256\",\n\t\"Leaf\",\n\t\"Shunt\",\n] as const;\nconst KIND_PTRS: Record<NodeKind, number> = {\n\tNode4: 4,\n\tNode16: 16,\n\tNode48: 48,\n\tNode256: 256,\n};\n\ntype NodeStep = {\n\tkind: NodeKind;\n\tchr: number;\n\tnode: TrieNode;\n\thashes: Bytes[];\n};\ntype LeafStep = { kind: \"Leaf\"; chr: number; path: Bytes; value: Bytes };\ntype ShuntStep = { kind: \"Shunt\"; idx: bigint; hashes: Bytes[] };\ntype ProofStep = NodeStep | LeafStep | ShuntStep;\n\n/** Decode consensus-serialized TrieMerkleProof<StacksBlockId>. Throws on trailing bytes. */\nfunction decodeProof(bytes: Bytes): ProofStep[] {\n\tconst r = new Reader(bytes);\n\tconst hash = () => r.bytes(32);\n\tconst steps = r.vec((): ProofStep => {\n\t\tconst kind = PROOF_KIND[r.u8()];\n\t\tif (!kind) throw new Error(\"bad proof step type\");\n\t\tif (kind === \"Shunt\")\n\t\t\treturn { kind, idx: r.i64(), hashes: r.vec(hash, 1 << 20) };\n\t\tconst chr = r.u8();\n\t\tif (kind === \"Leaf\")\n\t\t\treturn {\n\t\t\t\tkind,\n\t\t\t\tchr,\n\t\t\t\tpath: r.bytes(r.u32()),\n\t\t\t\tvalue: r.bytes(MARF_VALUE_SIZE),\n\t\t\t};\n\t\tconst node: TrieNode = {\n\t\t\tid: r.u8(),\n\t\t\tpath: r.bytes(r.u32()),\n\t\t\tptrs: r.vec(\n\t\t\t\t() => ({ id: r.u8(), chr: r.u8(), backBlock: r.bytes(32) }),\n\t\t\t\t256,\n\t\t\t),\n\t\t};\n\t\tconst hashes = Array.from({ length: KIND_PTRS[kind] - 1 }, hash);\n\t\treturn { kind, chr, node, hashes };\n\t}, 1 << 20);\n\tif (!r.done) throw new Error(\"trailing bytes after proof\");\n\treturn steps;\n}\n\n// ---------- verification (proofs.rs) ----------\n\nconst isShunt = (s: ProofStep | undefined): s is ShuntStep =>\n\ts?.kind === \"Shunt\";\n\nconst segmentEnd = (p: ProofStep[], i: number) => {\n\tlet j = i + 1;\n\twhile (j < p.length && !isShunt(p[j])) j++;\n\treturn j;\n};\n\nfunction segmentProofHash(step: NodeStep, childHash: Bytes): Bytes | null {\n\tconst count = KIND_PTRS[step.kind];\n\tif (step.node.ptrs.length !== count) return null;\n\tconst all: Bytes[] = [];\n\tlet ih = 0;\n\tfor (const p of step.node.ptrs) {\n\t\tif (p.id !== NodeId.Empty && p.chr === step.chr) all.push(childHash);\n\t\telse {\n\t\t\tconst h = step.hashes[ih++];\n\t\t\tif (!h) return null;\n\t\t\tall.push(h);\n\t\t}\n\t}\n\treturn all.length === count ? nodeHash(step.node, all) : null;\n}\n\nfunction verifySegment(seg: ProofStep[], start: Bytes): Bytes | null {\n\tlet h: Bytes | null = start;\n\tfor (const s of seg) {\n\t\tif (s.kind === \"Shunt\" || !h) return null;\n\t\th = s.kind === \"Leaf\" ? leafHash(s.path, s.value) : segmentProofHash(s, h);\n\t}\n\treturn h;\n}\n\nfunction segmentPathPrefix(seg: ProofStep[]): Bytes | null {\n\tconst parts: Bytes[] = [];\n\tfor (const s of seg) {\n\t\tif (s.kind === \"Shunt\") return null;\n\t\t// The leaf step's chr is not part of the path (and not hashed): proofs are malleable there.\n\t\tif (s.kind === \"Leaf\") parts.push(s.path);\n\t\telse parts.push(Uint8Array.of(s.chr), s.node.path);\n\t}\n\treturn concat(parts.reverse());\n}\n\nfunction isWellFormed(p: ProofStep[], expectedPath: Bytes): boolean {\n\tif (p[0]?.kind !== \"Leaf\") return false;\n\tlet i = 0;\n\tlet path: Bytes = new Uint8Array();\n\twhile (i < p.length) {\n\t\tconst j = segmentEnd(p, i);\n\t\tconst prefix = segmentPathPrefix(p.slice(i, j));\n\t\tif (!prefix) return false;\n\t\tif (i === 0) {\n\t\t\tif (!bytesEqual(prefix, expectedPath)) return false;\n\t\t\tpath = prefix;\n\t\t} else if (\n\t\t\tprefix.length > path.length ||\n\t\t\t!bytesEqual(path.subarray(0, prefix.length), prefix)\n\t\t)\n\t\t\treturn false;\n\t\ti = j;\n\t\tif (i >= p.length) return false; // every segment ends in a shunt proof\n\t\tlet k = i + 1;\n\t\twhile (k < p.length && isShunt(p[k])) k++;\n\t\ti = k;\n\t}\n\treturn true;\n}\n\n/** next_shunt_hash / junction: `inserted` goes at position idx-1 among `hashes`, after an optional lead. */\nfunction shuntHash(\n\tlead: Bytes | null,\n\tidx: bigint,\n\tinserted: Bytes,\n\thashes: Bytes[],\n): Bytes | null {\n\tif (idx === 0n) return null;\n\tconst all: Bytes[] = lead ? [lead] : [];\n\tlet hi = 0;\n\tfor (let i = 0; i < hashes.length + 1; i++) {\n\t\tif (idx - 1n === BigInt(i)) all.push(inserted);\n\t\telse {\n\t\t\tconst h = hashes[hi++];\n\t\t\tif (!h) return null;\n\t\t\tall.push(h);\n\t\t}\n\t}\n\treturn hashAll(all);\n}\n\nfunction verifySteps(\n\tproof: ProofStep[],\n\tpath: Bytes,\n\tvalue: Bytes,\n\troot: Bytes,\n\trootToBlock: Map<string, Bytes>,\n): boolean {\n\tif (!isWellFormed(proof, path)) return false;\n\tconst first = proof[0];\n\tif (first?.kind !== \"Leaf\" || !bytesEqual(first.value, value)) return false;\n\n\tlet i = 0;\n\tlet j = segmentEnd(proof, i);\n\tconst nodeRoot = verifySegment(\n\t\tproof.slice(i, j),\n\t\tleafHash(first.path, first.value),\n\t);\n\tif (!nodeRoot) return false;\n\n\t// Shunt proof head: idx must be 0; hashes are the trie's ancestor roots.\n\ti = j;\n\tconst head = proof[i];\n\tif (!isShunt(head) || head.idx !== 0n) return false;\n\tlet trieHash =\n\t\thead.hashes.length === 0 ? nodeRoot : hashAll([nodeRoot, ...head.hashes]);\n\n\ti += 1;\n\tif (i >= proof.length) return bytesEqual(root, trieHash);\n\tlet backBlock = rootToBlock.get(hex(trieHash));\n\tif (!backBlock || isShunt(proof[i])) return false;\n\n\twhile (i < proof.length) {\n\t\tj = segmentEnd(proof, i);\n\t\t// In the ancestor trie, the backptr child hash is the descendant's block id.\n\t\tconst nextNodeRoot = verifySegment(proof.slice(i, j), backBlock);\n\t\tif (!nextNodeRoot) return false;\n\t\ti = j;\n\t\tif (i >= proof.length) return false;\n\t\t// Tail: consecutive shunts with idx != 0; the last one is the junction.\n\t\tj = i;\n\t\twhile (j < proof.length) {\n\t\t\tconst s = proof[j];\n\t\t\tif (!isShunt(s) || s.idx === 0n) break;\n\t\t\tj++;\n\t\t}\n\t\tj -= 1;\n\t\tif (j < i) return false;\n\t\tlet penultimate = trieHash;\n\t\tfor (const s of proof.slice(i, j)) {\n\t\t\tif (!isShunt(s)) return false;\n\t\t\tconst h = shuntHash(null, s.idx, penultimate, s.hashes);\n\t\t\tif (!h) return false;\n\t\t\tpenultimate = h;\n\t\t}\n\t\tconst junction = proof[j];\n\t\tif (!isShunt(junction)) return false;\n\t\tconst next = shuntHash(\n\t\t\tnextNodeRoot,\n\t\t\tjunction.idx,\n\t\t\tpenultimate,\n\t\t\tjunction.hashes,\n\t\t);\n\t\tif (!next) return false;\n\t\ttrieHash = next;\n\t\tbackBlock = rootToBlock.get(hex(trieHash));\n\t\tif (!backBlock) return false;\n\t\ti = j + 1;\n\t\tif (bytesEqual(trieHash, root)) break;\n\t}\n\treturn bytesEqual(root, trieHash);\n}\n\n/**\n * Lists the ancestor tries a MARF proof crosses.\n *\n * Each id is the backptr a descendant trie follows toward the leaf, and\n * `verifyMarfProof` needs every one's header. They are read from untrusted\n * proof bytes, so they are only fetch hints: the proof still fails unless each\n * header hashes to the id the trie committed. Malformed proofs yield no ids.\n */\nexport function marfProofAncestors(proof: Bytes): string[] {\n\tlet steps: ProofStep[];\n\ttry {\n\t\tsteps = decodeProof(proof);\n\t} catch {\n\t\treturn [];\n\t}\n\tconst ids = new Set<string>();\n\tfor (const s of steps) {\n\t\tif (s.kind === \"Leaf\" || s.kind === \"Shunt\") continue;\n\t\tconst ptr = s.node.ptrs.find(\n\t\t\t(p) => p.id !== NodeId.Empty && p.chr === s.chr,\n\t\t);\n\t\tif (ptr && isBackptr(ptr.id)) ids.add(hex(ptr.backBlock));\n\t}\n\treturn [...ids];\n}\n\n/**\n * The 40-byte MARFValue a proof's leaf holds, or null for malformed bytes.\n * Unverified: pass it to `verifyMarfProof` as `value`. For keys whose value\n * is not a stored string (`__MARF_*` bookkeeping) this is the only copy.\n */\nexport function marfProofValue(proof: Bytes): Bytes | null {\n\ttry {\n\t\tconst leaf = decodeProof(proof)[0];\n\t\treturn leaf?.kind === \"Leaf\" ? leaf.value : null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport interface MarfProofInput {\n\t/** Consensus-serialized TrieMerkleProof (`/v2/clarity/marf/<path>?proof=1`). */\n\tproof: Bytes;\n\t/** Leaf path: `marfPath(key)`. */\n\tpath: Bytes;\n\t/** 40-byte MARFValue: `marfValue(valueString)`. */\n\tvalue: Bytes;\n\t/** Tip state_index_root, from a header the caller authenticated. */\n\troot: Bytes;\n\t/**\n\t * Tip header plus every ancestor header the proof crosses. Each contributes\n\t * state_index_root -> recomputed block id, so ancestor roots are only ever\n\t * vouched for by header bytes (a bare root->id map would let a forged\n\t * ancestor trie through).\n\t */\n\theaders: StacksHeader[];\n}\n\n/**\n * Verifies a MARF inclusion proof.\n *\n * It is true only when `value` is stored at `path` in the MARF whose tip root\n * is `root`. Inclusion only: MARF proofs cannot prove absence. Malformed proof\n * bytes verify false.\n */\nexport function verifyMarfProof(input: MarfProofInput): boolean {\n\tconst rootToBlock = new Map<string, Bytes>();\n\tfor (const h of input.headers)\n\t\trootToBlock.set(hex(h.stateIndexRoot), blockId(h));\n\ttry {\n\t\tconst steps = decodeProof(input.proof);\n\t\treturn verifySteps(steps, input.path, input.value, input.root, rootToBlock);\n\t} catch {\n\t\treturn false;\n\t}\n}\n",
8
- "// State witness v2: every node local to block N's trie, enough to recompute\n// N's state_index_root and enumerate every leaf trie N holds.\n//\n// v3 := 0x03 | u32 n_anc | [32]*n_anc ancestor roots | u32 n_tbl | [32]*n_tbl ancestor block ids | node\n// node := u8 id | u8 plen | path | u16 n_ptrs | ptr* | child* (one child per local ptr, in order)\n// ptr := u8 id | (id != 0: u8 chr) | (backptr: u32 tbl_idx) (empty ptr = 0x00, chr 0)\n// leaf := 0x01 | u8 plen | path | [32] value hash\n//\n// Hashing mirrors stacks-core storage.rs: a backptr child contributes the\n// ancestor BLOCK ID, an empty child TrieHash::EMPTY, and the root is\n// sha512/256(node_root || ancestor roots) unless there are no ancestors.\nimport {\n\ttype Bytes,\n\tReader,\n\tbytesEqual,\n\thashAll,\n\thex,\n\tunhex,\n} from \"./bytes.ts\";\nimport {\n\tMARF_VALUE_SIZE,\n\tNODE_PTR_COUNT,\n\tNodeId,\n\ttype TriePtr,\n\tisBackptr,\n\tleafHash,\n\tmarfPath,\n\tmarfValue,\n\tnodeHash,\n} from \"./marf.ts\";\n\nconst WITNESS_VERSION = 3;\nconst PATH_LEN = 32;\n/** stacks-common TrieHash::EMPTY = sha512/256 of the empty string. */\nexport const TRIE_HASH_EMPTY: Uint8Array = unhex(\n\t\"c672b8d1ef56ed28ab87c3622c5114069bdd3ad7b8f9737498d0c01ecef0967a\",\n);\nconst ZERO_BLOCK = new Uint8Array(32);\n\nexport interface WitnessLeaf {\n\t/** Full 32-byte trie path: `marfPath(key)`. */\n\tpath: Bytes;\n\t/** 32-byte value hash (first 32 bytes of the MARFValue; the tail is zero). */\n\tvalueHash: Bytes;\n}\n\nexport interface StateWitness {\n\t/** Recomputed trie root; compare to the authenticated header's state_index_root. */\n\troot: Bytes;\n\t/** Skip-list ancestor trie roots folded into `root`. */\n\tancestorRoots: Bytes[];\n\tleaves: WitnessLeaf[];\n\tnodes: number;\n}\n\n/**\n * Parse a v2 state witness and recompute its root. Throws on malformed input.\n * The result proves nothing until `root` equals a header's state_index_root.\n */\nexport function parseWitness(bytes: Bytes): StateWitness {\n\tconst r = new Reader(bytes);\n\tconst version = r.u8();\n\tif (version !== WITNESS_VERSION)\n\t\tthrow new Error(`unsupported witness version ${version}`);\n\tconst ancestorRoots = Array.from({ length: r.u32() }, () => r.bytes(32));\n\tconst blockTable = Array.from({ length: r.u32() }, () => r.bytes(32));\n\tconst leaves: WitnessLeaf[] = [];\n\tconst seen = new Set<string>();\n\tlet nodes = 0;\n\n\tconst readNode = (prefix: number[], expectedId: number | null): Bytes => {\n\t\tnodes++;\n\t\tconst id = r.u8();\n\t\tif (expectedId !== null && id !== expectedId)\n\t\t\tthrow new Error(\n\t\t\t\t`child id ${id} does not match its pointer id ${expectedId}`,\n\t\t\t);\n\t\tconst path = r.bytes(r.u8());\n\t\tconst depth = prefix.length + path.length;\n\t\tif (id === NodeId.Leaf) {\n\t\t\tif (depth !== PATH_LEN)\n\t\t\t\tthrow new Error(\"leaf path does not complete 32 bytes\");\n\t\t\tconst valueHash = r.bytes(32);\n\t\t\tconst full = Uint8Array.from([...prefix, ...path]);\n\t\t\tconst key = hex(full);\n\t\t\tif (seen.has(key)) throw new Error(`duplicate leaf ${key}`);\n\t\t\tseen.add(key);\n\t\t\tleaves.push({ path: full, valueHash });\n\t\t\treturn leafHash(path, padValue(valueHash));\n\t\t}\n\t\tconst count = NODE_PTR_COUNT[id];\n\t\tif (count === undefined) throw new Error(`bad node id ${id}`);\n\t\tif (depth >= PATH_LEN) throw new Error(\"interior node at full path depth\");\n\t\tconst n = r.u16();\n\t\tif (n !== count)\n\t\t\tthrow new Error(`node id ${id} has ${n} ptrs, expected ${count}`);\n\t\tconst ptrs: TriePtr[] = [];\n\t\tfor (let i = 0; i < n; i++) {\n\t\t\tconst pid = r.u8();\n\t\t\tif (pid === NodeId.Empty) {\n\t\t\t\tptrs.push({ id: pid, chr: 0, backBlock: ZERO_BLOCK });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst chr = r.u8();\n\t\t\tif (!isBackptr(pid)) {\n\t\t\t\tptrs.push({ id: pid, chr, backBlock: ZERO_BLOCK });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst block = blockTable[r.u32()];\n\t\t\tif (!block) throw new Error(\"backptr table index out of range\");\n\t\t\tptrs.push({ id: pid, chr, backBlock: block });\n\t\t}\n\t\tconst childPrefix = [...prefix, ...path];\n\t\tconst children = ptrs.map((p) => {\n\t\t\tif (p.id === NodeId.Empty) return TRIE_HASH_EMPTY;\n\t\t\tif (isBackptr(p.id)) return p.backBlock;\n\t\t\treturn readNode([...childPrefix, p.chr], p.id);\n\t\t});\n\t\treturn nodeHash({ id, path, ptrs }, children);\n\t};\n\n\tconst nodeRoot = readNode([], null);\n\tif (!r.done) throw new Error(\"trailing bytes after witness\");\n\tconst root =\n\t\tancestorRoots.length === 0\n\t\t\t? nodeRoot\n\t\t\t: hashAll([nodeRoot, ...ancestorRoots]);\n\treturn { root, ancestorRoots, leaves, nodes };\n}\n\nconst padValue = (valueHash: Bytes): Bytes => {\n\tconst v = new Uint8Array(MARF_VALUE_SIZE);\n\tv.set(valueHash);\n\treturn v;\n};\n\n/** Leaf value equals a full 40-byte MARFValue (hash head, zero tail). */\nconst leafHolds = (leaf: WitnessLeaf, value: Bytes): boolean =>\n\tvalue.length === MARF_VALUE_SIZE &&\n\tbytesEqual(padValue(leaf.valueHash), value);\n\nexport interface BlockDiffInput {\n\t/** `parseWitness(bytes).leaves`, from a witness whose root was checked. */\n\tleaves: WitnessLeaf[];\n\t/** Claimed writes of the block: [key, value string] as stored by Clarity. */\n\twrites: [key: string, value: string][];\n\t/** MARF bookkeeping keys (`__MARF_*`) with their raw 40-byte MARFValue hex, derived from the header chain. */\n\tinternal: [key: string, valueHex: string][];\n\t/** Value at `pathHex` in the PARENT block's state (40-byte MARFValue hex), already proven by the caller. */\n\tparentValue: (pathHex: string) => string | undefined;\n}\n\nexport interface ClassifiedLeaf extends WitnessLeaf {\n\tkey: string;\n}\n\nexport interface BlockDiff {\n\t/** Leaves matching a claimed write (path and value). */\n\twrites: ClassifiedLeaf[];\n\t/** Unclaimed leaves holding the parent's value: copied forward, not written. */\n\tcarried: WitnessLeaf[];\n\t/** Leaves matching a `__MARF_*` bookkeeping entry. */\n\tinternal: ClassifiedLeaf[];\n\t/** Leaves nothing explains: an unreported write. Non-empty = reject. */\n\thidden: WitnessLeaf[];\n\t/** Claimed write keys with no leaf holding the claimed value. Non-empty = reject. */\n\tmissing: string[];\n\t/** No hidden leaves and no missing writes: the claimed writes are the block's complete diff. */\n\tcomplete: boolean;\n}\n\nconst INTERNAL_PREFIX = \"__MARF_\";\n\n/**\n * Classify every leaf of block N's trie against the claimed write set.\n * Each leaf must be a claimed write, a carried (unchanged) parent value, or a\n * MARF-internal key; anything else is a hidden write.\n */\nexport function classifyBlockDiff(input: BlockDiffInput): BlockDiff {\n\tconst writes = indexClaims(input.writes, (v) => marfValue(v));\n\tconst internal = indexClaims(input.internal, (v) => {\n\t\tconst value = unhex(v);\n\t\tif (value.length !== MARF_VALUE_SIZE)\n\t\t\tthrow new Error(`internal value must be ${MARF_VALUE_SIZE} bytes`);\n\t\treturn value;\n\t});\n\tfor (const { key } of internal.values())\n\t\tif (!key.startsWith(INTERNAL_PREFIX))\n\t\t\tthrow new Error(\n\t\t\t\t`internal key must start with ${INTERNAL_PREFIX}: ${key}`,\n\t\t\t);\n\n\tconst out: BlockDiff = {\n\t\twrites: [],\n\t\tcarried: [],\n\t\tinternal: [],\n\t\thidden: [],\n\t\tmissing: [],\n\t\tcomplete: false,\n\t};\n\tconst matched = new Set<string>();\n\tfor (const leaf of input.leaves) {\n\t\tconst pathHex = hex(leaf.path);\n\t\tconst write = writes.get(pathHex);\n\t\tif (write && leafHolds(leaf, write.value)) {\n\t\t\tout.writes.push({ ...leaf, key: write.key });\n\t\t\tmatched.add(pathHex);\n\t\t\tcontinue;\n\t\t}\n\t\tconst bookkeeping = internal.get(pathHex);\n\t\tif (bookkeeping && leafHolds(leaf, bookkeeping.value)) {\n\t\t\tout.internal.push({ ...leaf, key: bookkeeping.key });\n\t\t\tcontinue;\n\t\t}\n\t\tconst parent = write ? undefined : input.parentValue(pathHex);\n\t\tif (parent !== undefined && leafHolds(leaf, unhex(parent)))\n\t\t\tout.carried.push(leaf);\n\t\telse out.hidden.push(leaf);\n\t}\n\tfor (const [pathHex, { key }] of writes)\n\t\tif (!matched.has(pathHex)) out.missing.push(key);\n\tout.complete = out.hidden.length === 0 && out.missing.length === 0;\n\treturn out;\n}\n\nfunction indexClaims(\n\tclaims: [string, string][],\n\ttoValue: (v: string) => Bytes,\n): Map<string, { key: string; value: Bytes }> {\n\tconst byPath = new Map<string, { key: string; value: Bytes }>();\n\tfor (const [key, value] of claims) {\n\t\tconst pathHex = hex(marfPath(key));\n\t\tif (byPath.has(pathHex)) throw new Error(`duplicate claimed key ${key}`);\n\t\tbyPath.set(pathHex, { key, value: toValue(value) });\n\t}\n\treturn byPath;\n}\n",
9
- "// Signer threshold check: a Nakamoto header is canonical when signers holding\n// >= 70% of the MARF-proven reward-cycle weight signed its signer_signature_hash.\nimport { secp256k1 } from \"@noble/curves/secp256k1.js\";\nimport { deserializeCV } from \"@secondlayer/stacks/clarity\";\nimport { c32address, hash160 } from \"@secondlayer/stacks/utils\";\nimport { type Bytes, hex } from \"./bytes.ts\";\nimport { type NakamotoHeader, signerSignatureHash } from \"./header.ts\";\n\n/** Mainnet single-sig (p2pkh) address version. */\nconst MAINNET_P2PKH = 22;\n\n/** Boot contract holding `cycle-signer-set`, one entry per reward cycle. */\nexport const SIGNERS_CONTRACT = \"SP000000000000000000002Q6VF78.signers\";\n\n/** Signer principal -> weight. */\nexport type SignerSet = Map<string, bigint>;\n\n/**\n * Decodes a `cycle-signer-set` value from the `.signers` contract.\n *\n * The value is hex or bytes, as stored in the MARF:\n * `(some (list (tuple (signer principal) (weight uint) ...)))`.\n */\nexport function decodeSignerSet(value: string | Bytes): SignerSet {\n\tconst cv = deserializeCV(typeof value === \"string\" ? value : hex(value));\n\tif (cv.type !== \"some\" || cv.value.type !== \"list\")\n\t\tthrow new Error(\"signer set must be (some (list ...))\");\n\tconst set: SignerSet = new Map();\n\tfor (const entry of cv.value.value) {\n\t\tif (entry.type !== \"tuple\") throw new Error(\"signer entry must be a tuple\");\n\t\tconst { signer, weight } = entry.value;\n\t\tif (signer?.type !== \"address\" || weight?.type !== \"uint\")\n\t\t\tthrow new Error(\"signer entry needs (signer principal) (weight uint)\");\n\t\tif (set.has(signer.value))\n\t\t\tthrow new Error(`duplicate signer ${signer.value}`);\n\t\tset.set(signer.value, BigInt(weight.value));\n\t}\n\treturn set;\n}\n\nexport interface SignerCheck {\n\t/** Signed weight meets the threshold, and every signature is a distinct known signer. */\n\tvalid: boolean;\n\tsignedWeight: bigint;\n\ttotalWeight: bigint;\n\t/** ceil(total * 7 / 10). */\n\tthreshold: bigint;\n\t/** Recovered signer principals that counted, in signature order. */\n\tsigners: string[];\n\t/** Recovered principals not in the set. */\n\tunknown: string[];\n\t/** Principals that signed more than once. */\n\tduplicates: string[];\n\t/** Signatures that do not recover (malformed or high-S). */\n\tinvalid: number;\n}\n\n/**\n * Sums the weight of the signers who signed a block header.\n *\n * It recovers each header signature's key over `signer_signature_hash`, maps it\n * to its mainnet p2pkh principal, and sums weights from `set`. The set must be\n * the one for the reward cycle of the tenure-electing burn block.\n */\nexport function verifySignerSignatures(\n\theader: NakamotoHeader,\n\tset: SignerSet,\n): SignerCheck {\n\tconst msg = signerSignatureHash(header);\n\tlet totalWeight = 0n;\n\tfor (const w of set.values()) totalWeight += w;\n\tconst threshold = (totalWeight * 7n + 9n) / 10n;\n\tconst out: SignerCheck = {\n\t\tvalid: false,\n\t\tsignedWeight: 0n,\n\t\ttotalWeight,\n\t\tthreshold,\n\t\tsigners: [],\n\t\tunknown: [],\n\t\tduplicates: [],\n\t\tinvalid: 0,\n\t};\n\tconst seen = new Set<string>();\n\tfor (const sig of header.signerSignatures) {\n\t\tconst who = recoverSigner(msg, sig);\n\t\tif (!who) out.invalid++;\n\t\telse if (seen.has(who)) out.duplicates.push(who);\n\t\telse {\n\t\t\tseen.add(who);\n\t\t\tconst weight = set.get(who);\n\t\t\tif (weight === undefined) out.unknown.push(who);\n\t\t\telse {\n\t\t\t\tout.signers.push(who);\n\t\t\t\tout.signedWeight += weight;\n\t\t\t}\n\t\t}\n\t}\n\tout.valid =\n\t\ttotalWeight > 0n &&\n\t\tout.signedWeight >= threshold &&\n\t\tout.unknown.length === 0 &&\n\t\tout.duplicates.length === 0 &&\n\t\tout.invalid === 0;\n\treturn out;\n}\n\n/** Stacks recover_to_pubkey: VRS bytes, low-S enforced, compressed key -> p2pkh principal. */\nfunction recoverSigner(msg: Bytes, sig: Bytes): string | null {\n\ttry {\n\t\tconst s = secp256k1.Signature.fromBytes(sig, \"recovered\");\n\t\tif (s.hasHighS()) return null;\n\t\tconst pubkey = s.recoverPublicKey(msg).toBytes(true);\n\t\treturn c32address(MAINNET_P2PKH, hex(hash160(pubkey)));\n\t} catch {\n\t\treturn null;\n\t}\n}\n",
5
+ "// Byte helpers shared by every codec here. Browser-safe: no Buffer.\nimport { sha512_256 } from \"@noble/hashes/sha2.js\";\nimport { bytesToHex, concatBytes, hexToBytes } from \"@noble/hashes/utils.js\";\n\n/** A byte string, held as a Uint8Array. */\nexport type Bytes = Uint8Array;\n\n/** Encodes bytes as a lowercase hex string. */\nexport const hex = (b: Bytes): string => bytesToHex(b);\n\n/** Hex to bytes; tolerates a 0x prefix. */\nexport const unhex = (s: string): Bytes =>\n\thexToBytes(s.startsWith(\"0x\") ? s.slice(2) : s);\n\nexport const concat = (parts: Bytes[]): Bytes => concatBytes(...parts);\n\nexport const bytesEqual = (a: Bytes, b: Bytes): boolean => {\n\tif (a.length !== b.length) return false;\n\tfor (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;\n\treturn true;\n};\n\n/** sha512/256 over the concatenation of `parts` (stacks-core TrieHasher). */\nexport const hashAll = (parts: Bytes[]): Bytes => {\n\tconst h = sha512_256.create();\n\tfor (const p of parts) h.update(p);\n\treturn h.digest();\n};\n\n/** Big-endian cursor over consensus-serialized bytes. Throws on overrun. */\nexport class Reader {\n\tpos = 0;\n\tconstructor(readonly buf: Bytes) {}\n\n\tbytes(n: number): Bytes {\n\t\tif (n < 0 || this.pos + n > this.buf.length)\n\t\t\tthrow new Error(`unexpected end of input at ${this.pos} reading ${n}`);\n\t\tconst out = this.buf.subarray(this.pos, this.pos + n);\n\t\tthis.pos += n;\n\t\treturn out;\n\t}\n\n\tprivate view(n: number): DataView {\n\t\tconst b = this.bytes(n);\n\t\treturn new DataView(b.buffer, b.byteOffset, n);\n\t}\n\n\tu8 = (): number => this.bytes(1)[0] as number;\n\tu16 = (): number => this.view(2).getUint16(0);\n\tu32 = (): number => this.view(4).getUint32(0);\n\tu64 = (): bigint => this.view(8).getBigUint64(0);\n\ti64 = (): bigint => this.view(8).getBigInt64(0);\n\n\t/** StacksMessageCodec Vec<T>: u32 count prefix, then items. */\n\tvec<T>(item: () => T, max: number): T[] {\n\t\tconst n = this.u32();\n\t\tif (n > max) throw new Error(`vec length ${n} exceeds ${max}`);\n\t\treturn Array.from({ length: n }, item);\n\t}\n\n\tget done(): boolean {\n\t\treturn this.pos === this.buf.length;\n\t}\n}\n",
6
+ "// Stacks block header codecs + identity hashes: Nakamoto (stackslib\n// chainstate/nakamoto/mod.rs NakamotoBlockHeader) and epoch 2.x\n// (chainstate/stacks/block.rs StacksBlockHeader).\nimport { sha512_256 } from \"@noble/hashes/sha2.js\";\nimport { type Bytes, Reader, concat, hashAll } from \"./bytes.ts\";\n\n/** A Nakamoto-era Stacks block header. */\nexport interface NakamotoHeader {\n\t/** Low 7 bits = header version; high bit = shadow block. */\n\tversion: number;\n\tchainLength: bigint;\n\tburnSpent: bigint;\n\tconsensusHash: Bytes;\n\tparentBlockId: Bytes;\n\ttxMerkleRoot: Bytes;\n\tstateIndexRoot: Bytes;\n\ttimestamp: bigint;\n\tminerSignature: Bytes;\n\t/** 65-byte recoverable signatures: recovery id, r, s. */\n\tsignerSignatures: Bytes[];\n\t/** Header bytes minus the signer_signature vec: the signer sighash preimage. */\n\tsignerSighashPreimage: Bytes;\n\t/** Serialized header length; block bytes after this are the transactions. */\n\tbyteLength: number;\n}\n\n/** First header version whose sighash commits to `problematic_txs` (epoch 4.0). */\nconst NAKAMOTO_BLOCK_VERSION_EPOCH_4 = 1;\nconst MAX_SIGNERS = 4000;\nconst MAX_PROBLEMATIC_TXS = 1 << 16;\n\n/**\n * Parse the NakamotoBlockHeader at the start of raw block bytes\n * (`/v3/blocks/<id>`). Handles v0 and v1 (v1 appends `problematic_txs`).\n */\nexport function parseNakamotoHeader(raw: Bytes): NakamotoHeader {\n\tconst r = new Reader(raw);\n\tconst version = r.u8();\n\tconst chainLength = r.u64();\n\tconst burnSpent = r.u64();\n\tconst consensusHash = r.bytes(20);\n\tconst parentBlockId = r.bytes(32);\n\tconst txMerkleRoot = r.bytes(32);\n\tconst stateIndexRoot = r.bytes(32);\n\tconst timestamp = r.u64();\n\tconst minerSignature = r.bytes(65);\n\tconst sigStart = r.pos;\n\tconst signerSignatures = r.vec(() => r.bytes(65), MAX_SIGNERS);\n\tconst sigEnd = r.pos;\n\t// pox_treatment: BitVec<4000> = u16 bit length, then Vec<u8> of exactly ceil(len/8).\n\tconst bits = r.u16();\n\tif (bits === 0 || bits > MAX_SIGNERS)\n\t\tthrow new Error(`bad pox_treatment length ${bits}`);\n\tconst bitBytes = Math.ceil(bits / 8);\n\tif (r.u32() !== bitBytes) throw new Error(\"bad pox_treatment data length\");\n\tr.bytes(bitBytes);\n\tif ((version & 0x7f) >= NAKAMOTO_BLOCK_VERSION_EPOCH_4) {\n\t\t// problematic_txs: Vec<(u32 index, u8 marker)>\n\t\tr.vec(() => r.bytes(5), MAX_PROBLEMATIC_TXS);\n\t}\n\tconst end = r.pos;\n\treturn {\n\t\tversion,\n\t\tchainLength,\n\t\tburnSpent,\n\t\tconsensusHash,\n\t\tparentBlockId,\n\t\ttxMerkleRoot,\n\t\tstateIndexRoot,\n\t\ttimestamp,\n\t\tminerSignature,\n\t\tsignerSignatures,\n\t\tsignerSighashPreimage: concat([\n\t\t\traw.subarray(0, sigStart),\n\t\t\traw.subarray(sigEnd, end),\n\t\t]),\n\t\tbyteLength: end,\n\t};\n}\n\n/**\n * Hashes a Nakamoto header the way its signers sign it.\n *\n * It is sha512/256 over every header field except the signer signatures, which\n * is also the header's `block_hash`.\n */\nexport const signerSignatureHash = (h: NakamotoHeader): Bytes =>\n\tsha512_256(h.signerSighashPreimage);\n\n/**\n * Epoch 2.x anchored block header. It commits to the parent's block hash, not\n * its index block hash, and carries no consensus hash: the source supplies\n * that, and `blockId` binds it to an id proven elsewhere.\n */\nexport interface Epoch2Header {\n\tversion: number;\n\t/** total_work.burn: burn spent on the fork so far. */\n\tburnSpent: bigint;\n\t/** total_work.work: the Stacks chain length (one per anchored block). */\n\tchainLength: bigint;\n\tvrfProof: Bytes;\n\tparentBlockHash: Bytes;\n\tparentMicroblock: Bytes;\n\tparentMicroblockSequence: number;\n\ttxMerkleRoot: Bytes;\n\t/** Covers the block and the parent microblock stream it confirms. */\n\tstateIndexRoot: Bytes;\n\tmicroblockPubkeyHash: Bytes;\n\t/** sha512/256 of the serialized header. */\n\tblockHash: Bytes;\n\tconsensusHash: Bytes;\n}\n\n/** A Stacks block header from either era. */\nexport type StacksHeader = NakamotoHeader | Epoch2Header;\n\n/** StacksBlockHeader is fixed width: no signatures, no variable fields. */\nexport const EPOCH2_HEADER_LENGTH = 247;\n\n/**\n * Parses the epoch 2.x block header at the start of `raw`.\n *\n * `raw` is a header from `/v2/headers`, or block bytes from `/v2/blocks/<id>`.\n * `consensusHash` is the 20-byte hash of the sortition that elected the block.\n */\nexport function parseEpoch2Header(\n\traw: Bytes,\n\tconsensusHash: Bytes,\n): Epoch2Header {\n\tif (consensusHash.length !== 20)\n\t\tthrow new Error(`consensus hash is ${consensusHash.length} bytes, not 20`);\n\tconst r = new Reader(raw);\n\tconst header: Omit<Epoch2Header, \"blockHash\" | \"consensusHash\"> = {\n\t\tversion: r.u8(),\n\t\tburnSpent: r.u64(),\n\t\tchainLength: r.u64(),\n\t\tvrfProof: r.bytes(80),\n\t\tparentBlockHash: r.bytes(32),\n\t\tparentMicroblock: r.bytes(32),\n\t\tparentMicroblockSequence: r.u16(),\n\t\ttxMerkleRoot: r.bytes(32),\n\t\tstateIndexRoot: r.bytes(32),\n\t\tmicroblockPubkeyHash: r.bytes(20),\n\t};\n\treturn {\n\t\t...header,\n\t\tblockHash: sha512_256(raw.subarray(0, EPOCH2_HEADER_LENGTH)),\n\t\tconsensusHash,\n\t};\n}\n\n/** Narrows a Stacks header to an epoch 2.x header. */\nexport const isEpoch2Header = (h: StacksHeader): h is Epoch2Header =>\n\t\"parentBlockHash\" in h;\n\n/**\n * Computes a header's block id, also called the index block hash.\n *\n * The id is sha512/256(block_hash || consensus_hash). A Nakamoto block hash is\n * its signer signature hash; a 2.x one hashes the whole header.\n */\nexport const blockId = (h: StacksHeader): Bytes =>\n\thashAll([\n\t\tisEpoch2Header(h) ? h.blockHash : signerSignatureHash(h),\n\t\th.consensusHash,\n\t]);\n",
7
+ "// MARF hashing primitives + TrieMerkleProof decode/verify.\n// Independent port of stacks-core stackslib/src/chainstate/stacks/index/{proofs,bits,node}.rs.\n// TrieHasher is sha512/256 everywhere.\nimport { sha512_256 } from \"@noble/hashes/sha2.js\";\nimport {\n\ttype Bytes,\n\tReader,\n\tbytesEqual,\n\tconcat,\n\thashAll,\n\thex,\n} from \"./bytes.ts\";\nimport { type StacksHeader, blockId } from \"./header.ts\";\n\n/** MARFValue width: 32-byte value hash + 8 zero bytes. */\nexport const MARF_VALUE_SIZE = 40;\n\nexport const NodeId = {\n\tEmpty: 0,\n\tLeaf: 1,\n\tNode4: 2,\n\tNode16: 3,\n\tNode48: 4,\n\tNode256: 5,\n} as const;\n\n/** Pointer count per node type id (Node4..Node256). */\nexport const NODE_PTR_COUNT: Readonly<Record<number, number>> = {\n\t[NodeId.Node4]: 4,\n\t[NodeId.Node16]: 16,\n\t[NodeId.Node48]: 48,\n\t[NodeId.Node256]: 256,\n};\n\n/** Backptr flag on a TriePtr id: child lives in an ancestor block's trie. */\nexport const isBackptr = (id: number): boolean => (id & 0x80) !== 0;\n\nexport interface TriePtr {\n\tid: number;\n\tchr: number;\n\t/** Ancestor block id for backptrs; 32 zero bytes otherwise. */\n\tbackBlock: Bytes;\n}\n\nexport interface TrieNode {\n\tid: number;\n\tpath: Bytes;\n\tptrs: TriePtr[];\n}\n\n/** Hashes a key to its MARF path: sha512/256 of the UTF-8 key. */\nexport const marfPath = (key: string): Bytes =>\n\tsha512_256(new TextEncoder().encode(key));\n\n/**\n * `__MARF_BLOCK_HEIGHT_TO_HASH::<height>` (index/marf.rs set_block_heights):\n * block `height + 1` stores its parent's id here as a raw MARFValue, so a\n * proof of it at any descendant names that descendant's ancestor at `height`.\n */\nexport const heightToHashKey = (height: number): string =>\n\t`__MARF_BLOCK_HEIGHT_TO_HASH::${height}`;\n\n/** Hashes a value to its MARF value: sha512/256, padded to 40 bytes. */\nexport function marfValue(value: string): Bytes {\n\tconst v = new Uint8Array(MARF_VALUE_SIZE);\n\tv.set(sha512_256(new TextEncoder().encode(value)));\n\treturn v;\n}\n\n// ---------- hashing (bits.rs) ----------\n\nfunction pathPreimage(path: Bytes): Bytes {\n\tif (path.length > 32) throw new Error(\"trie path longer than 32 bytes\");\n\treturn concat([Uint8Array.of(path.length), path]);\n}\n\n/** get_leaf_hash: H(Leaf id || path len || path || 40-byte value). */\nexport const leafHash = (path: Bytes, value: Bytes): Bytes =>\n\thashAll([Uint8Array.of(NodeId.Leaf), pathPreimage(path), value]);\n\n/** get_node_hash: H(id || ptrs(id, chr, back_block) || path len || path || child hashes). */\nexport function nodeHash(node: TrieNode, children: Bytes[]): Bytes {\n\tconst parts: Bytes[] = [Uint8Array.of(node.id)];\n\tfor (const p of node.ptrs)\n\t\tparts.push(Uint8Array.of(p.id, p.chr), p.backBlock);\n\tparts.push(pathPreimage(node.path), ...children);\n\treturn hashAll(parts);\n}\n\n// ---------- proof codec ----------\n\ntype NodeKind = \"Node4\" | \"Node16\" | \"Node48\" | \"Node256\";\nconst PROOF_KIND = [\n\t\"Node4\",\n\t\"Node16\",\n\t\"Node48\",\n\t\"Node256\",\n\t\"Leaf\",\n\t\"Shunt\",\n] as const;\nconst KIND_PTRS: Record<NodeKind, number> = {\n\tNode4: 4,\n\tNode16: 16,\n\tNode48: 48,\n\tNode256: 256,\n};\n\ntype NodeStep = {\n\tkind: NodeKind;\n\tchr: number;\n\tnode: TrieNode;\n\thashes: Bytes[];\n};\ntype LeafStep = { kind: \"Leaf\"; chr: number; path: Bytes; value: Bytes };\ntype ShuntStep = { kind: \"Shunt\"; idx: bigint; hashes: Bytes[] };\ntype ProofStep = NodeStep | LeafStep | ShuntStep;\n\n/** Decode consensus-serialized TrieMerkleProof<StacksBlockId>. Throws on trailing bytes. */\nfunction decodeProof(bytes: Bytes): ProofStep[] {\n\tconst r = new Reader(bytes);\n\tconst hash = () => r.bytes(32);\n\tconst steps = r.vec((): ProofStep => {\n\t\tconst kind = PROOF_KIND[r.u8()];\n\t\tif (!kind) throw new Error(\"bad proof step type\");\n\t\tif (kind === \"Shunt\")\n\t\t\treturn { kind, idx: r.i64(), hashes: r.vec(hash, 1 << 20) };\n\t\tconst chr = r.u8();\n\t\tif (kind === \"Leaf\")\n\t\t\treturn {\n\t\t\t\tkind,\n\t\t\t\tchr,\n\t\t\t\tpath: r.bytes(r.u32()),\n\t\t\t\tvalue: r.bytes(MARF_VALUE_SIZE),\n\t\t\t};\n\t\tconst node: TrieNode = {\n\t\t\tid: r.u8(),\n\t\t\tpath: r.bytes(r.u32()),\n\t\t\tptrs: r.vec(\n\t\t\t\t() => ({ id: r.u8(), chr: r.u8(), backBlock: r.bytes(32) }),\n\t\t\t\t256,\n\t\t\t),\n\t\t};\n\t\tconst hashes = Array.from({ length: KIND_PTRS[kind] - 1 }, hash);\n\t\treturn { kind, chr, node, hashes };\n\t}, 1 << 20);\n\tif (!r.done) throw new Error(\"trailing bytes after proof\");\n\treturn steps;\n}\n\n// ---------- verification (proofs.rs) ----------\n\nconst isShunt = (s: ProofStep | undefined): s is ShuntStep =>\n\ts?.kind === \"Shunt\";\n\nconst segmentEnd = (p: ProofStep[], i: number) => {\n\tlet j = i + 1;\n\twhile (j < p.length && !isShunt(p[j])) j++;\n\treturn j;\n};\n\nfunction segmentProofHash(step: NodeStep, childHash: Bytes): Bytes | null {\n\tconst count = KIND_PTRS[step.kind];\n\tif (step.node.ptrs.length !== count) return null;\n\tconst all: Bytes[] = [];\n\tlet ih = 0;\n\tfor (const p of step.node.ptrs) {\n\t\tif (p.id !== NodeId.Empty && p.chr === step.chr) all.push(childHash);\n\t\telse {\n\t\t\tconst h = step.hashes[ih++];\n\t\t\tif (!h) return null;\n\t\t\tall.push(h);\n\t\t}\n\t}\n\treturn all.length === count ? nodeHash(step.node, all) : null;\n}\n\nfunction verifySegment(seg: ProofStep[], start: Bytes): Bytes | null {\n\tlet h: Bytes | null = start;\n\tfor (const s of seg) {\n\t\tif (s.kind === \"Shunt\" || !h) return null;\n\t\th = s.kind === \"Leaf\" ? leafHash(s.path, s.value) : segmentProofHash(s, h);\n\t}\n\treturn h;\n}\n\nfunction segmentPathPrefix(seg: ProofStep[]): Bytes | null {\n\tconst parts: Bytes[] = [];\n\tfor (const s of seg) {\n\t\tif (s.kind === \"Shunt\") return null;\n\t\t// The leaf step's chr is not part of the path (and not hashed): proofs are malleable there.\n\t\tif (s.kind === \"Leaf\") parts.push(s.path);\n\t\telse parts.push(Uint8Array.of(s.chr), s.node.path);\n\t}\n\treturn concat(parts.reverse());\n}\n\nfunction isWellFormed(p: ProofStep[], expectedPath: Bytes): boolean {\n\tif (p[0]?.kind !== \"Leaf\") return false;\n\tlet i = 0;\n\tlet path: Bytes = new Uint8Array();\n\twhile (i < p.length) {\n\t\tconst j = segmentEnd(p, i);\n\t\tconst prefix = segmentPathPrefix(p.slice(i, j));\n\t\tif (!prefix) return false;\n\t\tif (i === 0) {\n\t\t\tif (!bytesEqual(prefix, expectedPath)) return false;\n\t\t\tpath = prefix;\n\t\t} else if (\n\t\t\tprefix.length > path.length ||\n\t\t\t!bytesEqual(path.subarray(0, prefix.length), prefix)\n\t\t)\n\t\t\treturn false;\n\t\ti = j;\n\t\tif (i >= p.length) return false; // every segment ends in a shunt proof\n\t\tlet k = i + 1;\n\t\twhile (k < p.length && isShunt(p[k])) k++;\n\t\ti = k;\n\t}\n\treturn true;\n}\n\n/** next_shunt_hash / junction: `inserted` goes at position idx-1 among `hashes`, after an optional lead. */\nfunction shuntHash(\n\tlead: Bytes | null,\n\tidx: bigint,\n\tinserted: Bytes,\n\thashes: Bytes[],\n): Bytes | null {\n\tif (idx === 0n) return null;\n\tconst all: Bytes[] = lead ? [lead] : [];\n\tlet hi = 0;\n\tfor (let i = 0; i < hashes.length + 1; i++) {\n\t\tif (idx - 1n === BigInt(i)) all.push(inserted);\n\t\telse {\n\t\t\tconst h = hashes[hi++];\n\t\t\tif (!h) return null;\n\t\t\tall.push(h);\n\t\t}\n\t}\n\treturn hashAll(all);\n}\n\nfunction verifySteps(\n\tproof: ProofStep[],\n\tpath: Bytes,\n\tvalue: Bytes,\n\troot: Bytes,\n\trootToBlock: Map<string, Bytes>,\n): boolean {\n\tif (!isWellFormed(proof, path)) return false;\n\tconst first = proof[0];\n\tif (first?.kind !== \"Leaf\" || !bytesEqual(first.value, value)) return false;\n\n\tlet i = 0;\n\tlet j = segmentEnd(proof, i);\n\tconst nodeRoot = verifySegment(\n\t\tproof.slice(i, j),\n\t\tleafHash(first.path, first.value),\n\t);\n\tif (!nodeRoot) return false;\n\n\t// Shunt proof head: idx must be 0; hashes are the trie's ancestor roots.\n\ti = j;\n\tconst head = proof[i];\n\tif (!isShunt(head) || head.idx !== 0n) return false;\n\tlet trieHash =\n\t\thead.hashes.length === 0 ? nodeRoot : hashAll([nodeRoot, ...head.hashes]);\n\n\ti += 1;\n\tif (i >= proof.length) return bytesEqual(root, trieHash);\n\tlet backBlock = rootToBlock.get(hex(trieHash));\n\tif (!backBlock || isShunt(proof[i])) return false;\n\n\twhile (i < proof.length) {\n\t\tj = segmentEnd(proof, i);\n\t\t// In the ancestor trie, the backptr child hash is the descendant's block id.\n\t\tconst nextNodeRoot = verifySegment(proof.slice(i, j), backBlock);\n\t\tif (!nextNodeRoot) return false;\n\t\ti = j;\n\t\tif (i >= proof.length) return false;\n\t\t// Tail: consecutive shunts with idx != 0; the last one is the junction.\n\t\tj = i;\n\t\twhile (j < proof.length) {\n\t\t\tconst s = proof[j];\n\t\t\tif (!isShunt(s) || s.idx === 0n) break;\n\t\t\tj++;\n\t\t}\n\t\tj -= 1;\n\t\tif (j < i) return false;\n\t\tlet penultimate = trieHash;\n\t\tfor (const s of proof.slice(i, j)) {\n\t\t\tif (!isShunt(s)) return false;\n\t\t\tconst h = shuntHash(null, s.idx, penultimate, s.hashes);\n\t\t\tif (!h) return false;\n\t\t\tpenultimate = h;\n\t\t}\n\t\tconst junction = proof[j];\n\t\tif (!isShunt(junction)) return false;\n\t\tconst next = shuntHash(\n\t\t\tnextNodeRoot,\n\t\t\tjunction.idx,\n\t\t\tpenultimate,\n\t\t\tjunction.hashes,\n\t\t);\n\t\tif (!next) return false;\n\t\ttrieHash = next;\n\t\tbackBlock = rootToBlock.get(hex(trieHash));\n\t\tif (!backBlock) return false;\n\t\ti = j + 1;\n\t\tif (bytesEqual(trieHash, root)) break;\n\t}\n\treturn bytesEqual(root, trieHash);\n}\n\n/**\n * Lists the ancestor tries a MARF proof crosses.\n *\n * Each id is the backptr a descendant trie follows toward the leaf, and\n * `verifyMarfProof` needs every one's header. They are read from untrusted\n * proof bytes, so they are only fetch hints: the proof still fails unless each\n * header hashes to the id the trie committed. Malformed proofs yield no ids.\n */\nexport function marfProofAncestors(proof: Bytes): string[] {\n\tlet steps: ProofStep[];\n\ttry {\n\t\tsteps = decodeProof(proof);\n\t} catch {\n\t\treturn [];\n\t}\n\tconst ids = new Set<string>();\n\tfor (const s of steps) {\n\t\tif (s.kind === \"Leaf\" || s.kind === \"Shunt\") continue;\n\t\tconst ptr = s.node.ptrs.find(\n\t\t\t(p) => p.id !== NodeId.Empty && p.chr === s.chr,\n\t\t);\n\t\tif (ptr && isBackptr(ptr.id)) ids.add(hex(ptr.backBlock));\n\t}\n\treturn [...ids];\n}\n\n/**\n * The 40-byte MARFValue a proof's leaf holds, or null for malformed bytes.\n * Unverified: pass it to `verifyMarfProof` as `value`. For keys whose value\n * is not a stored string (`__MARF_*` bookkeeping) this is the only copy.\n */\nexport function marfProofValue(proof: Bytes): Bytes | null {\n\ttry {\n\t\tconst leaf = decodeProof(proof)[0];\n\t\treturn leaf?.kind === \"Leaf\" ? leaf.value : null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/** A MARF proof with the leaf path and value it covers. */\nexport interface MarfProofInput {\n\t/** Consensus-serialized TrieMerkleProof (`/v2/clarity/marf/<path>?proof=1`). */\n\tproof: Bytes;\n\t/** Leaf path: `marfPath(key)`. */\n\tpath: Bytes;\n\t/** 40-byte MARFValue: `marfValue(valueString)`. */\n\tvalue: Bytes;\n\t/** Tip state_index_root, from a header the caller authenticated. */\n\troot: Bytes;\n\t/**\n\t * Tip header plus every ancestor header the proof crosses. Each contributes\n\t * state_index_root -> recomputed block id, so ancestor roots are only ever\n\t * vouched for by header bytes (a bare root->id map would let a forged\n\t * ancestor trie through).\n\t */\n\theaders: StacksHeader[];\n}\n\n/**\n * Verifies a MARF inclusion proof.\n *\n * It is true only when `value` is stored at `path` in the MARF whose tip root\n * is `root`. Inclusion only: MARF proofs cannot prove absence. Malformed proof\n * bytes verify false.\n */\nexport function verifyMarfProof(input: MarfProofInput): boolean {\n\tconst rootToBlock = new Map<string, Bytes>();\n\tfor (const h of input.headers)\n\t\trootToBlock.set(hex(h.stateIndexRoot), blockId(h));\n\ttry {\n\t\tconst steps = decodeProof(input.proof);\n\t\treturn verifySteps(steps, input.path, input.value, input.root, rootToBlock);\n\t} catch {\n\t\treturn false;\n\t}\n}\n",
8
+ "// State witness v2: every node local to block N's trie, enough to recompute\n// N's state_index_root and enumerate every leaf trie N holds.\n//\n// v3 := 0x03 | u32 n_anc | [32]*n_anc ancestor roots | u32 n_tbl | [32]*n_tbl ancestor block ids | node\n// node := u8 id | u8 plen | path | u16 n_ptrs | ptr* | child* (one child per local ptr, in order)\n// ptr := u8 id | (id != 0: u8 chr) | (backptr: u32 tbl_idx) (empty ptr = 0x00, chr 0)\n// leaf := 0x01 | u8 plen | path | [32] value hash\n//\n// Hashing mirrors stacks-core storage.rs: a backptr child contributes the\n// ancestor BLOCK ID, an empty child TrieHash::EMPTY, and the root is\n// sha512/256(node_root || ancestor roots) unless there are no ancestors.\nimport {\n\ttype Bytes,\n\tReader,\n\tbytesEqual,\n\thashAll,\n\thex,\n\tunhex,\n} from \"./bytes.ts\";\nimport {\n\tMARF_VALUE_SIZE,\n\tNODE_PTR_COUNT,\n\tNodeId,\n\ttype TriePtr,\n\tisBackptr,\n\tleafHash,\n\tmarfPath,\n\tmarfValue,\n\tnodeHash,\n} from \"./marf.ts\";\n\nconst WITNESS_VERSION = 3;\nconst PATH_LEN = 32;\n/** stacks-common TrieHash::EMPTY = sha512/256 of the empty string. */\nexport const TRIE_HASH_EMPTY: Uint8Array = unhex(\n\t\"c672b8d1ef56ed28ab87c3622c5114069bdd3ad7b8f9737498d0c01ecef0967a\",\n);\nconst ZERO_BLOCK = new Uint8Array(32);\n\nexport interface WitnessLeaf {\n\t/** Full 32-byte trie path: `marfPath(key)`. */\n\tpath: Bytes;\n\t/** 32-byte value hash (first 32 bytes of the MARFValue; the tail is zero). */\n\tvalueHash: Bytes;\n}\n\n/** A recomputed trie root, its ancestor roots, and leaves. */\nexport interface StateWitness {\n\t/** Recomputed trie root; compare to the authenticated header's state_index_root. */\n\troot: Bytes;\n\t/** Skip-list ancestor trie roots folded into `root`. */\n\tancestorRoots: Bytes[];\n\tleaves: WitnessLeaf[];\n\tnodes: number;\n}\n\n/**\n * Parse a v2 state witness and recompute its root. Throws on malformed input.\n * The result proves nothing until `root` equals a header's state_index_root.\n */\nexport function parseWitness(bytes: Bytes): StateWitness {\n\tconst r = new Reader(bytes);\n\tconst version = r.u8();\n\tif (version !== WITNESS_VERSION)\n\t\tthrow new Error(`unsupported witness version ${version}`);\n\tconst ancestorRoots = Array.from({ length: r.u32() }, () => r.bytes(32));\n\tconst blockTable = Array.from({ length: r.u32() }, () => r.bytes(32));\n\tconst leaves: WitnessLeaf[] = [];\n\tconst seen = new Set<string>();\n\tlet nodes = 0;\n\n\tconst readNode = (prefix: number[], expectedId: number | null): Bytes => {\n\t\tnodes++;\n\t\tconst id = r.u8();\n\t\tif (expectedId !== null && id !== expectedId)\n\t\t\tthrow new Error(\n\t\t\t\t`child id ${id} does not match its pointer id ${expectedId}`,\n\t\t\t);\n\t\tconst path = r.bytes(r.u8());\n\t\tconst depth = prefix.length + path.length;\n\t\tif (id === NodeId.Leaf) {\n\t\t\tif (depth !== PATH_LEN)\n\t\t\t\tthrow new Error(\"leaf path does not complete 32 bytes\");\n\t\t\tconst valueHash = r.bytes(32);\n\t\t\tconst full = Uint8Array.from([...prefix, ...path]);\n\t\t\tconst key = hex(full);\n\t\t\tif (seen.has(key)) throw new Error(`duplicate leaf ${key}`);\n\t\t\tseen.add(key);\n\t\t\tleaves.push({ path: full, valueHash });\n\t\t\treturn leafHash(path, padValue(valueHash));\n\t\t}\n\t\tconst count = NODE_PTR_COUNT[id];\n\t\tif (count === undefined) throw new Error(`bad node id ${id}`);\n\t\tif (depth >= PATH_LEN) throw new Error(\"interior node at full path depth\");\n\t\tconst n = r.u16();\n\t\tif (n !== count)\n\t\t\tthrow new Error(`node id ${id} has ${n} ptrs, expected ${count}`);\n\t\tconst ptrs: TriePtr[] = [];\n\t\tfor (let i = 0; i < n; i++) {\n\t\t\tconst pid = r.u8();\n\t\t\tif (pid === NodeId.Empty) {\n\t\t\t\tptrs.push({ id: pid, chr: 0, backBlock: ZERO_BLOCK });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst chr = r.u8();\n\t\t\tif (!isBackptr(pid)) {\n\t\t\t\tptrs.push({ id: pid, chr, backBlock: ZERO_BLOCK });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst block = blockTable[r.u32()];\n\t\t\tif (!block) throw new Error(\"backptr table index out of range\");\n\t\t\tptrs.push({ id: pid, chr, backBlock: block });\n\t\t}\n\t\tconst childPrefix = [...prefix, ...path];\n\t\tconst children = ptrs.map((p) => {\n\t\t\tif (p.id === NodeId.Empty) return TRIE_HASH_EMPTY;\n\t\t\tif (isBackptr(p.id)) return p.backBlock;\n\t\t\treturn readNode([...childPrefix, p.chr], p.id);\n\t\t});\n\t\treturn nodeHash({ id, path, ptrs }, children);\n\t};\n\n\tconst nodeRoot = readNode([], null);\n\tif (!r.done) throw new Error(\"trailing bytes after witness\");\n\tconst root =\n\t\tancestorRoots.length === 0\n\t\t\t? nodeRoot\n\t\t\t: hashAll([nodeRoot, ...ancestorRoots]);\n\treturn { root, ancestorRoots, leaves, nodes };\n}\n\nconst padValue = (valueHash: Bytes): Bytes => {\n\tconst v = new Uint8Array(MARF_VALUE_SIZE);\n\tv.set(valueHash);\n\treturn v;\n};\n\n/** Leaf value equals a full 40-byte MARFValue (hash head, zero tail). */\nconst leafHolds = (leaf: WitnessLeaf, value: Bytes): boolean =>\n\tvalue.length === MARF_VALUE_SIZE &&\n\tbytesEqual(padValue(leaf.valueHash), value);\n\n/** The witness leaves, claimed writes, and bookkeeping keys to classify. */\nexport interface BlockDiffInput {\n\t/** `parseWitness(bytes).leaves`, from a witness whose root was checked. */\n\tleaves: WitnessLeaf[];\n\t/** Claimed writes of the block: [key, value string] as stored by Clarity. */\n\twrites: [key: string, value: string][];\n\t/** MARF bookkeeping keys (`__MARF_*`) with their raw 40-byte MARFValue hex, derived from the header chain. */\n\tinternal: [key: string, valueHex: string][];\n\t/** Value at `pathHex` in the PARENT block's state (40-byte MARFValue hex), already proven by the caller. */\n\tparentValue: (pathHex: string) => string | undefined;\n}\n\nexport interface ClassifiedLeaf extends WitnessLeaf {\n\tkey: string;\n}\n\n/** A block's witnessed leaves, split into writes, carried, and internal. */\nexport interface BlockDiff {\n\t/** Leaves matching a claimed write (path and value). */\n\twrites: ClassifiedLeaf[];\n\t/** Unclaimed leaves holding the parent's value: copied forward, not written. */\n\tcarried: WitnessLeaf[];\n\t/** Leaves matching a `__MARF_*` bookkeeping entry. */\n\tinternal: ClassifiedLeaf[];\n\t/** Leaves nothing explains: an unreported write. Non-empty = reject. */\n\thidden: WitnessLeaf[];\n\t/** Claimed write keys with no leaf holding the claimed value. Non-empty = reject. */\n\tmissing: string[];\n\t/** No hidden leaves and no missing writes: the claimed writes are the block's complete diff. */\n\tcomplete: boolean;\n}\n\nconst INTERNAL_PREFIX = \"__MARF_\";\n\n/**\n * Classify every leaf of block N's trie against the claimed write set.\n * Each leaf must be a claimed write, a carried (unchanged) parent value, or a\n * MARF-internal key; anything else is a hidden write.\n */\nexport function classifyBlockDiff(input: BlockDiffInput): BlockDiff {\n\tconst writes = indexClaims(input.writes, (v) => marfValue(v));\n\tconst internal = indexClaims(input.internal, (v) => {\n\t\tconst value = unhex(v);\n\t\tif (value.length !== MARF_VALUE_SIZE)\n\t\t\tthrow new Error(`internal value must be ${MARF_VALUE_SIZE} bytes`);\n\t\treturn value;\n\t});\n\tfor (const { key } of internal.values())\n\t\tif (!key.startsWith(INTERNAL_PREFIX))\n\t\t\tthrow new Error(\n\t\t\t\t`internal key must start with ${INTERNAL_PREFIX}: ${key}`,\n\t\t\t);\n\n\tconst out: BlockDiff = {\n\t\twrites: [],\n\t\tcarried: [],\n\t\tinternal: [],\n\t\thidden: [],\n\t\tmissing: [],\n\t\tcomplete: false,\n\t};\n\tconst matched = new Set<string>();\n\tfor (const leaf of input.leaves) {\n\t\tconst pathHex = hex(leaf.path);\n\t\tconst write = writes.get(pathHex);\n\t\tif (write && leafHolds(leaf, write.value)) {\n\t\t\tout.writes.push({ ...leaf, key: write.key });\n\t\t\tmatched.add(pathHex);\n\t\t\tcontinue;\n\t\t}\n\t\tconst bookkeeping = internal.get(pathHex);\n\t\tif (bookkeeping && leafHolds(leaf, bookkeeping.value)) {\n\t\t\tout.internal.push({ ...leaf, key: bookkeeping.key });\n\t\t\tcontinue;\n\t\t}\n\t\tconst parent = write ? undefined : input.parentValue(pathHex);\n\t\tif (parent !== undefined && leafHolds(leaf, unhex(parent)))\n\t\t\tout.carried.push(leaf);\n\t\telse out.hidden.push(leaf);\n\t}\n\tfor (const [pathHex, { key }] of writes)\n\t\tif (!matched.has(pathHex)) out.missing.push(key);\n\tout.complete = out.hidden.length === 0 && out.missing.length === 0;\n\treturn out;\n}\n\nfunction indexClaims(\n\tclaims: [string, string][],\n\ttoValue: (v: string) => Bytes,\n): Map<string, { key: string; value: Bytes }> {\n\tconst byPath = new Map<string, { key: string; value: Bytes }>();\n\tfor (const [key, value] of claims) {\n\t\tconst pathHex = hex(marfPath(key));\n\t\tif (byPath.has(pathHex)) throw new Error(`duplicate claimed key ${key}`);\n\t\tbyPath.set(pathHex, { key, value: toValue(value) });\n\t}\n\treturn byPath;\n}\n",
9
+ "// Signer threshold check: a Nakamoto header is canonical when signers holding\n// >= 70% of the MARF-proven reward-cycle weight signed its signer_signature_hash.\nimport { secp256k1 } from \"@noble/curves/secp256k1.js\";\nimport { deserializeCV } from \"@secondlayer/stacks/clarity\";\nimport { c32address, hash160 } from \"@secondlayer/stacks/utils\";\nimport { type Bytes, hex } from \"./bytes.ts\";\nimport { type NakamotoHeader, signerSignatureHash } from \"./header.ts\";\n\n/** Mainnet single-sig (p2pkh) address version. */\nconst MAINNET_P2PKH = 22;\n\n/** Boot contract holding `cycle-signer-set`, one entry per reward cycle. */\nexport const SIGNERS_CONTRACT = \"SP000000000000000000002Q6VF78.signers\";\n\n/** Signer principal -> weight. */\nexport type SignerSet = Map<string, bigint>;\n\n/**\n * Decodes a `cycle-signer-set` value from the `.signers` contract.\n *\n * The value is hex or bytes, as stored in the MARF:\n * `(some (list (tuple (signer principal) (weight uint) ...)))`.\n */\nexport function decodeSignerSet(value: string | Bytes): SignerSet {\n\tconst cv = deserializeCV(typeof value === \"string\" ? value : hex(value));\n\tif (cv.type !== \"some\" || cv.value.type !== \"list\")\n\t\tthrow new Error(\"signer set must be (some (list ...))\");\n\tconst set: SignerSet = new Map();\n\tfor (const entry of cv.value.value) {\n\t\tif (entry.type !== \"tuple\") throw new Error(\"signer entry must be a tuple\");\n\t\tconst { signer, weight } = entry.value;\n\t\tif (signer?.type !== \"address\" || weight?.type !== \"uint\")\n\t\t\tthrow new Error(\"signer entry needs (signer principal) (weight uint)\");\n\t\tif (set.has(signer.value))\n\t\t\tthrow new Error(`duplicate signer ${signer.value}`);\n\t\tset.set(signer.value, BigInt(weight.value));\n\t}\n\treturn set;\n}\n\n/** Whether the signed weight meets the threshold with known signers. */\nexport interface SignerCheck {\n\t/** Signed weight meets the threshold, and every signature is a distinct known signer. */\n\tvalid: boolean;\n\tsignedWeight: bigint;\n\ttotalWeight: bigint;\n\t/** ceil(total * 7 / 10). */\n\tthreshold: bigint;\n\t/** Recovered signer principals that counted, in signature order. */\n\tsigners: string[];\n\t/** Recovered principals not in the set. */\n\tunknown: string[];\n\t/** Principals that signed more than once. */\n\tduplicates: string[];\n\t/** Signatures that do not recover (malformed or high-S). */\n\tinvalid: number;\n}\n\n/**\n * Sums the weight of the signers who signed a block header.\n *\n * It recovers each header signature's key over `signer_signature_hash`, maps it\n * to its mainnet p2pkh principal, and sums weights from `set`. The set must be\n * the one for the reward cycle of the tenure-electing burn block.\n */\nexport function verifySignerSignatures(\n\theader: NakamotoHeader,\n\tset: SignerSet,\n): SignerCheck {\n\tconst msg = signerSignatureHash(header);\n\tlet totalWeight = 0n;\n\tfor (const w of set.values()) totalWeight += w;\n\tconst threshold = (totalWeight * 7n + 9n) / 10n;\n\tconst out: SignerCheck = {\n\t\tvalid: false,\n\t\tsignedWeight: 0n,\n\t\ttotalWeight,\n\t\tthreshold,\n\t\tsigners: [],\n\t\tunknown: [],\n\t\tduplicates: [],\n\t\tinvalid: 0,\n\t};\n\tconst seen = new Set<string>();\n\tfor (const sig of header.signerSignatures) {\n\t\tconst who = recoverSigner(msg, sig);\n\t\tif (!who) out.invalid++;\n\t\telse if (seen.has(who)) out.duplicates.push(who);\n\t\telse {\n\t\t\tseen.add(who);\n\t\t\tconst weight = set.get(who);\n\t\t\tif (weight === undefined) out.unknown.push(who);\n\t\t\telse {\n\t\t\t\tout.signers.push(who);\n\t\t\t\tout.signedWeight += weight;\n\t\t\t}\n\t\t}\n\t}\n\tout.valid =\n\t\ttotalWeight > 0n &&\n\t\tout.signedWeight >= threshold &&\n\t\tout.unknown.length === 0 &&\n\t\tout.duplicates.length === 0 &&\n\t\tout.invalid === 0;\n\treturn out;\n}\n\n/** Stacks recover_to_pubkey: VRS bytes, low-S enforced, compressed key -> p2pkh principal. */\nfunction recoverSigner(msg: Bytes, sig: Bytes): string | null {\n\ttry {\n\t\tconst s = secp256k1.Signature.fromBytes(sig, \"recovered\");\n\t\tif (s.hasHighS()) return null;\n\t\tconst pubkey = s.recoverPublicKey(msg).toBytes(true);\n\t\treturn c32address(MAINNET_P2PKH, hex(hash160(pubkey)));\n\t} catch {\n\t\treturn null;\n\t}\n}\n",
10
10
  "// Burn height binding. A Nakamoto header carries no burn height, but its\n// consensus_hash = RIPEMD160(SHA256(preimage)) and the preimage holds the\n// burn block hash at a fixed offset (stacks-core burn/mod.rs):\n//\n// [23,0,0,0] || burn_header_hash(32) || ops_hash(32) || total_burn(u64 BE) || pox_id || prev_CHs\n//\n// Any preimage hashing to the header's CH pins the burn block (forging one is a\n// RIPEMD160∘SHA256 second preimage). Locate that hash in a PoW-verified\n// Bitcoin header chain to get the height, then the reward cycle.\nimport { ripemd160 } from \"@noble/hashes/legacy.js\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { type Bytes, bytesEqual, hex } from \"./bytes.ts\";\n\nconst PREIMAGE_PREFIX = Uint8Array.of(23, 0, 0, 0);\nconst BHH_START = 4;\nconst BHH_END = 36;\n\n/**\n * Check `preimage` against a 20-byte consensus hash. Returns the burn block\n * hash as hex, already in Bitcoin display order (as `bitcoin-cli\n * getblockhash` prints it), or null when the preimage does not match.\n */\nexport function verifyConsensusPreimage(\n\tconsensusHash: Bytes,\n\tpreimage: Bytes,\n): string | null {\n\tif (consensusHash.length !== 20 || preimage.length < BHH_END) return null;\n\tif (!bytesEqual(preimage.subarray(0, BHH_START), PREIMAGE_PREFIX))\n\t\treturn null;\n\tif (!bytesEqual(ripemd160(sha256(preimage)), consensusHash)) return null;\n\treturn hex(preimage.subarray(BHH_START, BHH_END));\n}\n\n/** Mainnet PoX parameters (first_burnchain_block_height, reward_cycle_length). */\nexport const MAINNET_FIRST_BURN_HEIGHT = 666050;\n/** Burn blocks in a mainnet reward cycle. */\nexport const MAINNET_REWARD_CYCLE_LENGTH = 2100;\n/** Mainnet prepare phase: the last 100 burn blocks of a cycle pick the next cycle's signers. */\nexport const MAINNET_PREPARE_LENGTH = 100;\n\n/** First burn height of reward cycle `cycle`. */\nexport const cycleStart = (\n\tcycle: number,\n\tfirstBurnHeight: number = MAINNET_FIRST_BURN_HEIGHT,\n\tcycleLength: number = MAINNET_REWARD_CYCLE_LENGTH,\n): number => firstBurnHeight + cycle * cycleLength;\n\n/** Reward cycle containing `burnHeight`. */\nexport function rewardCycle(\n\tburnHeight: number,\n\tfirstBurnHeight: number = MAINNET_FIRST_BURN_HEIGHT,\n\tcycleLength: number = MAINNET_REWARD_CYCLE_LENGTH,\n): number {\n\tif (burnHeight < firstBurnHeight)\n\t\tthrow new Error(`burn height ${burnHeight} precedes the first burn block`);\n\treturn Math.floor((burnHeight - firstBurnHeight) / cycleLength);\n}\n",
11
11
  "// Clarity MARF keys, mirroring stacks-core clarity_db.rs make_key_for_trip /\n// make_key_for_quad. The leaf path is `marfPath(key)`.\nimport { type ClarityValue, serializeCV } from \"@secondlayer/stacks/clarity\";\nimport { c32addressDecode } from \"@secondlayer/stacks/utils\";\nimport { unhex } from \"./bytes.ts\";\n\n/** clarity_db.rs StoreType discriminants (formatted in decimal inside keys). */\nconst StoreType = { DataMap: 0, Variable: 1, FungibleToken: 2 } as const;\n\n/** The MARF key of a map entry: `vm::<contract>::0::<map>::<serialized key hex>`. */\nexport function mapEntryKey(\n\tcontractId: string,\n\tmapName: string,\n\tkey: ClarityValue,\n): string {\n\treturn `vm::${contractId}::${StoreType.DataMap}::${mapName}::${serializeCV(key)}`;\n}\n\n/** The MARF key of a data variable: `vm::<contract>::1::<var>`. */\nexport function dataVarKey(contractId: string, varName: string): string {\n\treturn `vm::${contractId}::${StoreType.Variable}::${varName}`;\n}\n\n/**\n * The MARF key of a fungible token balance: `vm::<contract>::2::<token>::<principal json>`.\n *\n * The holder is serde-JSON PrincipalData, e.g. `{\"Standard\":[22,[...20 bytes]]}`.\n */\nexport function ftBalanceKey(\n\tcontractId: string,\n\ttokenName: string,\n\tholder: string,\n): string {\n\treturn `vm::${contractId}::${StoreType.FungibleToken}::${tokenName}::${principalJson(holder)}`;\n}\n\nfunction principalJson(principal: string): string {\n\tconst dot = principal.indexOf(\".\");\n\tconst address = dot === -1 ? principal : principal.slice(0, dot);\n\tconst [version, hash160] = c32addressDecode(address);\n\tconst issuer = [version, Array.from(unhex(hash160))];\n\tif (dot === -1) return JSON.stringify({ Standard: issuer });\n\treturn JSON.stringify({\n\t\tContract: { issuer, name: principal.slice(dot + 1) },\n\t});\n}\n",
12
- "/**\n * Minimal Bitcoin header-chain light client (SPV), mainnet rules only.\n *\n * Trust model: the checkpoint header is trusted as-is. Every header appended\n * after it must link to the current tip and satisfy proof-of-work, the\n * difficulty rule (unchanged bits mid-period, exact retarget every 2016\n * blocks), median-time-past, and the BIP34/66/65 minimum version.\n *\n * Append-only: there is no reorg handling. A header that does not extend the\n * tip (a fork, or a replay of a known header) is rejected. Callers that need\n * to follow reorgs should rebuild from a checkpoint safely below the fork.\n *\n * Not checked (needs wall-clock or block bodies): the \"time too far in the\n * future\" rule, and anything about transactions/merkle roots.\n */\n\nimport { bytesToHex, hexToBytes } from \"@noble/hashes/utils.js\";\nimport {\n\ttype BlockHeader,\n\tHEADER_SIZE,\n\theaderHash,\n\tparseHeader,\n\treverseBytes,\n} from \"./header.ts\";\nimport {\n\tRETARGET_INTERVAL,\n\tbitsToTarget,\n\tcheckProofOfWork,\n\theaderWork,\n\tnextRetargetBits,\n} from \"./pow.ts\";\n\n/** Number of previous blocks whose median timestamp a new block must exceed. */\nexport const MEDIAN_TIME_SPAN = 11;\n/** Mainnet height from which version ≥ 4 is required (BIP65; implies BIP34/66). */\nexport const BIP65_HEIGHT = 388_381;\n\nexport type HeaderRule =\n\t| \"checkpoint\"\n\t| \"format\"\n\t| \"prev-link\"\n\t| \"bits\"\n\t| \"retarget\"\n\t| \"median-time-past\"\n\t| \"version\"\n\t| \"proof-of-work\";\n\n/**\n * Thrown when a Bitcoin header fails a validation rule.\n *\n * `rule` names the rule and `height` the header that failed it.\n */\nexport class HeaderValidationError extends Error {\n\toverride readonly name = \"HeaderValidationError\";\n\tconstructor(\n\t\treadonly height: number,\n\t\treadonly rule: HeaderRule,\n\t\tdetail: string,\n\t) {\n\t\tsuper(`header at height ${height} failed ${rule}: ${detail}`);\n\t}\n}\n\nexport interface Checkpoint {\n\theight: number;\n\t/** Raw 80-byte header, bytes or hex. Trusted without validation. */\n\theader: Uint8Array | string;\n\t/**\n\t * Timestamp of the first block of the checkpoint's difficulty period\n\t * (height − height % 2016). Required when the checkpoint is not itself a\n\t * period start; needed to verify the next retarget.\n\t */\n\tperiodStartTime?: number;\n}\n\nexport interface ChainEntry {\n\theight: number;\n\t/** Display-order hex. */\n\thash: string;\n\theader: BlockHeader;\n\traw: Uint8Array;\n}\n\nconst hex8 = (n: number) => `0x${n.toString(16).padStart(8, \"0\")}`;\n\n/** A validated chain of Bitcoin headers, grown forward from a checkpoint. */\nexport class HeaderChain {\n\tprivate readonly entries: ChainEntry[] = [];\n\tprivate readonly heights = new Map<string, number>();\n\tprivate work = 0n;\n\n\tprivate constructor(\n\t\tprivate readonly base: number,\n\t\tprivate readonly periodStartTime: number,\n\t) {}\n\n\t/** Starts a header chain at a checkpoint. */\n\tstatic fromCheckpoint(checkpoint: Checkpoint): HeaderChain {\n\t\tconst { height } = checkpoint;\n\t\tif (!Number.isSafeInteger(height) || height < 0) {\n\t\t\tthrow new HeaderValidationError(\n\t\t\t\theight,\n\t\t\t\t\"checkpoint\",\n\t\t\t\t\"height must be a non-negative integer\",\n\t\t\t);\n\t\t}\n\t\tconst raw = toRaw(checkpoint.header, height);\n\t\tconst header = parseHeader(raw);\n\t\ttry {\n\t\t\tbitsToTarget(header.bits);\n\t\t} catch (err) {\n\t\t\tthrow new HeaderValidationError(\n\t\t\t\theight,\n\t\t\t\t\"checkpoint\",\n\t\t\t\t(err as Error).message,\n\t\t\t);\n\t\t}\n\t\tconst atPeriodStart = height % RETARGET_INTERVAL === 0;\n\t\tlet periodStartTime = checkpoint.periodStartTime;\n\t\tif (atPeriodStart) {\n\t\t\tif (periodStartTime !== undefined && periodStartTime !== header.time) {\n\t\t\t\tthrow new HeaderValidationError(\n\t\t\t\t\theight,\n\t\t\t\t\t\"checkpoint\",\n\t\t\t\t\t`periodStartTime ${periodStartTime} disagrees with the period-start checkpoint's own time ${header.time}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tperiodStartTime = header.time;\n\t\t} else if (periodStartTime === undefined) {\n\t\t\tthrow new HeaderValidationError(\n\t\t\t\theight,\n\t\t\t\t\"checkpoint\",\n\t\t\t\t`periodStartTime is required for a checkpoint inside a difficulty period (period starts at ${height - (height % RETARGET_INTERVAL)})`,\n\t\t\t);\n\t\t}\n\t\tconst chain = new HeaderChain(height, periodStartTime);\n\t\tchain.push(raw, header);\n\t\treturn chain;\n\t}\n\n\tget tip(): ChainEntry {\n\t\treturn this.entries[this.entries.length - 1] as ChainEntry;\n\t}\n\n\t/** Work summed from the checkpoint (inclusive) to the tip; not chainwork since genesis. */\n\tget totalWork(): bigint {\n\t\treturn this.work;\n\t}\n\n\tget checkpointHeight(): number {\n\t\treturn this.base;\n\t}\n\n\t/** Height of a header in this chain by display-order hash, or undefined. */\n\theightOf(hashHex: string): number | undefined {\n\t\treturn this.heights.get(hashHex.toLowerCase());\n\t}\n\n\t/** The header entry at a height, if the chain has one. */\n\theaderAt(height: number): ChainEntry | undefined {\n\t\treturn this.entries[height - this.base];\n\t}\n\n\t/**\n\t * Validates and appends headers in order. All-or-nothing: if any header\n\t * fails, the chain is left exactly as it was and the error is thrown.\n\t */\n\tappend(headers: Iterable<Uint8Array | string>): void {\n\t\tconst before = this.entries.length;\n\t\tconst workBefore = this.work;\n\t\ttry {\n\t\t\tfor (const item of headers) {\n\t\t\t\tconst height = this.tip.height + 1;\n\t\t\t\tconst raw = toRaw(item, height);\n\t\t\t\tthis.validate(height, raw, parseHeader(raw));\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tfor (const removed of this.entries.splice(before)) {\n\t\t\t\tthis.heights.delete(removed.hash);\n\t\t\t}\n\t\t\tthis.work = workBefore;\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tprivate validate(height: number, raw: Uint8Array, header: BlockHeader): void {\n\t\tconst prev = this.tip;\n\n\t\tif (header.prevHash !== prev.hash) {\n\t\t\tconst known = this.heights.get(header.prevHash);\n\t\t\tthrow new HeaderValidationError(\n\t\t\t\theight,\n\t\t\t\t\"prev-link\",\n\t\t\t\tknown === undefined\n\t\t\t\t\t? `prevHash ${header.prevHash} does not match tip ${prev.hash} at ${prev.height}`\n\t\t\t\t\t: `prevHash points at height ${known}, not the tip at ${prev.height} (forks/reorgs are not supported)`,\n\t\t\t);\n\t\t}\n\n\t\tconst expectedBits = this.expectedBits(height, prev);\n\t\tif (header.bits !== expectedBits) {\n\t\t\tconst atRetarget = height % RETARGET_INTERVAL === 0;\n\t\t\tthrow new HeaderValidationError(\n\t\t\t\theight,\n\t\t\t\tatRetarget ? \"retarget\" : \"bits\",\n\t\t\t\tatRetarget\n\t\t\t\t\t? `bits ${hex8(header.bits)} != retargeted ${hex8(expectedBits)}`\n\t\t\t\t\t: `bits ${hex8(header.bits)} != previous ${hex8(expectedBits)} (only height % ${RETARGET_INTERVAL} == 0 may change difficulty)`,\n\t\t\t);\n\t\t}\n\n\t\tconst mtp = this.medianTimePast();\n\t\tif (header.time <= mtp) {\n\t\t\tthrow new HeaderValidationError(\n\t\t\t\theight,\n\t\t\t\t\"median-time-past\",\n\t\t\t\t`time ${header.time} <= median of previous ${Math.min(MEDIAN_TIME_SPAN, this.entries.length)} blocks (${mtp})`,\n\t\t\t);\n\t\t}\n\n\t\tif (height >= BIP65_HEIGHT && header.version < 4) {\n\t\t\tthrow new HeaderValidationError(\n\t\t\t\theight,\n\t\t\t\t\"version\",\n\t\t\t\t`version ${header.version} < 4 (required from height ${BIP65_HEIGHT})`,\n\t\t\t);\n\t\t}\n\n\t\tconst hash = headerHash(raw);\n\t\tif (!checkProofOfWork(hash, header.bits)) {\n\t\t\tthrow new HeaderValidationError(\n\t\t\t\theight,\n\t\t\t\t\"proof-of-work\",\n\t\t\t\t`hash ${bytesToHex(reverseBytes(hash))} exceeds target for bits ${hex8(header.bits)}`,\n\t\t\t);\n\t\t}\n\n\t\tthis.push(raw, header, hash);\n\t}\n\n\tprivate expectedBits(height: number, prev: ChainEntry): number {\n\t\tif (height % RETARGET_INTERVAL !== 0) return prev.header.bits;\n\t\tconst firstHeight = height - RETARGET_INTERVAL;\n\t\tconst firstTime =\n\t\t\tfirstHeight < this.base\n\t\t\t\t? this.periodStartTime\n\t\t\t\t: (this.headerAt(firstHeight) as ChainEntry).header.time;\n\t\treturn nextRetargetBits(prev.header.bits, firstTime, prev.header.time);\n\t}\n\n\t/**\n\t * Median of the last 11 timestamps. Right after the checkpoint fewer are\n\t * known; like Core near genesis, the median of what is available is used.\n\t */\n\tprivate medianTimePast(): number {\n\t\tconst times = this.entries\n\t\t\t.slice(-MEDIAN_TIME_SPAN)\n\t\t\t.map((e) => e.header.time)\n\t\t\t.sort((a, b) => a - b);\n\t\treturn times[Math.floor(times.length / 2)] as number;\n\t}\n\n\tprivate push(raw: Uint8Array, header: BlockHeader, hash = headerHash(raw)) {\n\t\tconst height = this.base + this.entries.length;\n\t\tconst hashHex = bytesToHex(reverseBytes(hash));\n\t\tthis.entries.push({ height, hash: hashHex, header, raw });\n\t\tthis.heights.set(hashHex, height);\n\t\tthis.work += headerWork(header.bits);\n\t}\n}\n\nfunction toRaw(item: Uint8Array | string, height: number): Uint8Array {\n\tlet raw: Uint8Array;\n\ttry {\n\t\t// Copy so later mutation of the caller's buffer cannot alter the chain.\n\t\traw = typeof item === \"string\" ? hexToBytes(item) : Uint8Array.from(item);\n\t} catch {\n\t\tthrow new HeaderValidationError(\n\t\t\theight,\n\t\t\t\"format\",\n\t\t\t\"header is not valid hex\",\n\t\t);\n\t}\n\tif (raw.length !== HEADER_SIZE) {\n\t\tthrow new HeaderValidationError(\n\t\t\theight,\n\t\t\t\"format\",\n\t\t\t`header must be ${HEADER_SIZE} bytes, got ${raw.length}`,\n\t\t);\n\t}\n\treturn raw;\n}\n",
12
+ "/**\n * Minimal Bitcoin header-chain light client (SPV), mainnet rules only.\n *\n * Trust model: the checkpoint header is trusted as-is. Every header appended\n * after it must link to the current tip and satisfy proof-of-work, the\n * difficulty rule (unchanged bits mid-period, exact retarget every 2016\n * blocks), median-time-past, and the BIP34/66/65 minimum version.\n *\n * Append-only: there is no reorg handling. A header that does not extend the\n * tip (a fork, or a replay of a known header) is rejected. Callers that need\n * to follow reorgs should rebuild from a checkpoint safely below the fork.\n *\n * Not checked (needs wall-clock or block bodies): the \"time too far in the\n * future\" rule, and anything about transactions/merkle roots.\n */\n\nimport { bytesToHex, hexToBytes } from \"@noble/hashes/utils.js\";\nimport {\n\ttype BlockHeader,\n\tHEADER_SIZE,\n\theaderHash,\n\tparseHeader,\n\treverseBytes,\n} from \"./header.ts\";\nimport {\n\tRETARGET_INTERVAL,\n\tbitsToTarget,\n\tcheckProofOfWork,\n\theaderWork,\n\tnextRetargetBits,\n} from \"./pow.ts\";\n\n/** Number of previous blocks whose median timestamp a new block must exceed. */\nexport const MEDIAN_TIME_SPAN = 11;\n/** Mainnet height from which version ≥ 4 is required (BIP65; implies BIP34/66). */\nexport const BIP65_HEIGHT = 388_381;\n\n/** A Bitcoin header rule a chain check can fail on. */\nexport type HeaderRule =\n\t| \"checkpoint\"\n\t| \"format\"\n\t| \"prev-link\"\n\t| \"bits\"\n\t| \"retarget\"\n\t| \"median-time-past\"\n\t| \"version\"\n\t| \"proof-of-work\";\n\n/**\n * Thrown when a Bitcoin header fails a validation rule.\n *\n * `rule` names the rule and `height` the header that failed it.\n */\nexport class HeaderValidationError extends Error {\n\toverride readonly name = \"HeaderValidationError\";\n\tconstructor(\n\t\treadonly height: number,\n\t\treadonly rule: HeaderRule,\n\t\tdetail: string,\n\t) {\n\t\tsuper(`header at height ${height} failed ${rule}: ${detail}`);\n\t}\n}\n\n/** A trusted Bitcoin header that anchors header validation. */\nexport interface Checkpoint {\n\theight: number;\n\t/** Raw 80-byte header, bytes or hex. Trusted without validation. */\n\theader: Uint8Array | string;\n\t/**\n\t * Timestamp of the first block of the checkpoint's difficulty period\n\t * (height − height % 2016). Required when the checkpoint is not itself a\n\t * period start; needed to verify the next retarget.\n\t */\n\tperiodStartTime?: number;\n}\n\n/** A Bitcoin header with its height, hash, and raw bytes. */\nexport interface ChainEntry {\n\theight: number;\n\t/** Display-order hex. */\n\thash: string;\n\theader: BlockHeader;\n\traw: Uint8Array;\n}\n\nconst hex8 = (n: number) => `0x${n.toString(16).padStart(8, \"0\")}`;\n\n/** A validated chain of Bitcoin headers, grown forward from a checkpoint. */\nexport class HeaderChain {\n\tprivate readonly entries: ChainEntry[] = [];\n\tprivate readonly heights = new Map<string, number>();\n\tprivate work = 0n;\n\n\tprivate constructor(\n\t\tprivate readonly base: number,\n\t\tprivate readonly periodStartTime: number,\n\t) {}\n\n\t/** Starts a header chain at a checkpoint. */\n\tstatic fromCheckpoint(checkpoint: Checkpoint): HeaderChain {\n\t\tconst { height } = checkpoint;\n\t\tif (!Number.isSafeInteger(height) || height < 0) {\n\t\t\tthrow new HeaderValidationError(\n\t\t\t\theight,\n\t\t\t\t\"checkpoint\",\n\t\t\t\t\"height must be a non-negative integer\",\n\t\t\t);\n\t\t}\n\t\tconst raw = toRaw(checkpoint.header, height);\n\t\tconst header = parseHeader(raw);\n\t\ttry {\n\t\t\tbitsToTarget(header.bits);\n\t\t} catch (err) {\n\t\t\tthrow new HeaderValidationError(\n\t\t\t\theight,\n\t\t\t\t\"checkpoint\",\n\t\t\t\t(err as Error).message,\n\t\t\t);\n\t\t}\n\t\tconst atPeriodStart = height % RETARGET_INTERVAL === 0;\n\t\tlet periodStartTime = checkpoint.periodStartTime;\n\t\tif (atPeriodStart) {\n\t\t\tif (periodStartTime !== undefined && periodStartTime !== header.time) {\n\t\t\t\tthrow new HeaderValidationError(\n\t\t\t\t\theight,\n\t\t\t\t\t\"checkpoint\",\n\t\t\t\t\t`periodStartTime ${periodStartTime} disagrees with the period-start checkpoint's own time ${header.time}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tperiodStartTime = header.time;\n\t\t} else if (periodStartTime === undefined) {\n\t\t\tthrow new HeaderValidationError(\n\t\t\t\theight,\n\t\t\t\t\"checkpoint\",\n\t\t\t\t`periodStartTime is required for a checkpoint inside a difficulty period (period starts at ${height - (height % RETARGET_INTERVAL)})`,\n\t\t\t);\n\t\t}\n\t\tconst chain = new HeaderChain(height, periodStartTime);\n\t\tchain.push(raw, header);\n\t\treturn chain;\n\t}\n\n\tget tip(): ChainEntry {\n\t\treturn this.entries[this.entries.length - 1] as ChainEntry;\n\t}\n\n\t/** Work summed from the checkpoint (inclusive) to the tip; not chainwork since genesis. */\n\tget totalWork(): bigint {\n\t\treturn this.work;\n\t}\n\n\tget checkpointHeight(): number {\n\t\treturn this.base;\n\t}\n\n\t/** Height of a header in this chain by display-order hash, or undefined. */\n\theightOf(hashHex: string): number | undefined {\n\t\treturn this.heights.get(hashHex.toLowerCase());\n\t}\n\n\t/** The header entry at a height, if the chain has one. */\n\theaderAt(height: number): ChainEntry | undefined {\n\t\treturn this.entries[height - this.base];\n\t}\n\n\t/**\n\t * Validates and appends headers in order. All-or-nothing: if any header\n\t * fails, the chain is left exactly as it was and the error is thrown.\n\t */\n\tappend(headers: Iterable<Uint8Array | string>): void {\n\t\tconst before = this.entries.length;\n\t\tconst workBefore = this.work;\n\t\ttry {\n\t\t\tfor (const item of headers) {\n\t\t\t\tconst height = this.tip.height + 1;\n\t\t\t\tconst raw = toRaw(item, height);\n\t\t\t\tthis.validate(height, raw, parseHeader(raw));\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tfor (const removed of this.entries.splice(before)) {\n\t\t\t\tthis.heights.delete(removed.hash);\n\t\t\t}\n\t\t\tthis.work = workBefore;\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tprivate validate(height: number, raw: Uint8Array, header: BlockHeader): void {\n\t\tconst prev = this.tip;\n\n\t\tif (header.prevHash !== prev.hash) {\n\t\t\tconst known = this.heights.get(header.prevHash);\n\t\t\tthrow new HeaderValidationError(\n\t\t\t\theight,\n\t\t\t\t\"prev-link\",\n\t\t\t\tknown === undefined\n\t\t\t\t\t? `prevHash ${header.prevHash} does not match tip ${prev.hash} at ${prev.height}`\n\t\t\t\t\t: `prevHash points at height ${known}, not the tip at ${prev.height} (forks/reorgs are not supported)`,\n\t\t\t);\n\t\t}\n\n\t\tconst expectedBits = this.expectedBits(height, prev);\n\t\tif (header.bits !== expectedBits) {\n\t\t\tconst atRetarget = height % RETARGET_INTERVAL === 0;\n\t\t\tthrow new HeaderValidationError(\n\t\t\t\theight,\n\t\t\t\tatRetarget ? \"retarget\" : \"bits\",\n\t\t\t\tatRetarget\n\t\t\t\t\t? `bits ${hex8(header.bits)} != retargeted ${hex8(expectedBits)}`\n\t\t\t\t\t: `bits ${hex8(header.bits)} != previous ${hex8(expectedBits)} (only height % ${RETARGET_INTERVAL} == 0 may change difficulty)`,\n\t\t\t);\n\t\t}\n\n\t\tconst mtp = this.medianTimePast();\n\t\tif (header.time <= mtp) {\n\t\t\tthrow new HeaderValidationError(\n\t\t\t\theight,\n\t\t\t\t\"median-time-past\",\n\t\t\t\t`time ${header.time} <= median of previous ${Math.min(MEDIAN_TIME_SPAN, this.entries.length)} blocks (${mtp})`,\n\t\t\t);\n\t\t}\n\n\t\tif (height >= BIP65_HEIGHT && header.version < 4) {\n\t\t\tthrow new HeaderValidationError(\n\t\t\t\theight,\n\t\t\t\t\"version\",\n\t\t\t\t`version ${header.version} < 4 (required from height ${BIP65_HEIGHT})`,\n\t\t\t);\n\t\t}\n\n\t\tconst hash = headerHash(raw);\n\t\tif (!checkProofOfWork(hash, header.bits)) {\n\t\t\tthrow new HeaderValidationError(\n\t\t\t\theight,\n\t\t\t\t\"proof-of-work\",\n\t\t\t\t`hash ${bytesToHex(reverseBytes(hash))} exceeds target for bits ${hex8(header.bits)}`,\n\t\t\t);\n\t\t}\n\n\t\tthis.push(raw, header, hash);\n\t}\n\n\tprivate expectedBits(height: number, prev: ChainEntry): number {\n\t\tif (height % RETARGET_INTERVAL !== 0) return prev.header.bits;\n\t\tconst firstHeight = height - RETARGET_INTERVAL;\n\t\tconst firstTime =\n\t\t\tfirstHeight < this.base\n\t\t\t\t? this.periodStartTime\n\t\t\t\t: (this.headerAt(firstHeight) as ChainEntry).header.time;\n\t\treturn nextRetargetBits(prev.header.bits, firstTime, prev.header.time);\n\t}\n\n\t/**\n\t * Median of the last 11 timestamps. Right after the checkpoint fewer are\n\t * known; like Core near genesis, the median of what is available is used.\n\t */\n\tprivate medianTimePast(): number {\n\t\tconst times = this.entries\n\t\t\t.slice(-MEDIAN_TIME_SPAN)\n\t\t\t.map((e) => e.header.time)\n\t\t\t.sort((a, b) => a - b);\n\t\treturn times[Math.floor(times.length / 2)] as number;\n\t}\n\n\tprivate push(raw: Uint8Array, header: BlockHeader, hash = headerHash(raw)) {\n\t\tconst height = this.base + this.entries.length;\n\t\tconst hashHex = bytesToHex(reverseBytes(hash));\n\t\tthis.entries.push({ height, hash: hashHex, header, raw });\n\t\tthis.heights.set(hashHex, height);\n\t\tthis.work += headerWork(header.bits);\n\t}\n}\n\nfunction toRaw(item: Uint8Array | string, height: number): Uint8Array {\n\tlet raw: Uint8Array;\n\ttry {\n\t\t// Copy so later mutation of the caller's buffer cannot alter the chain.\n\t\traw = typeof item === \"string\" ? hexToBytes(item) : Uint8Array.from(item);\n\t} catch {\n\t\tthrow new HeaderValidationError(\n\t\t\theight,\n\t\t\t\"format\",\n\t\t\t\"header is not valid hex\",\n\t\t);\n\t}\n\tif (raw.length !== HEADER_SIZE) {\n\t\tthrow new HeaderValidationError(\n\t\t\theight,\n\t\t\t\"format\",\n\t\t\t`header must be ${HEADER_SIZE} bytes, got ${raw.length}`,\n\t\t);\n\t}\n\treturn raw;\n}\n",
13
13
  "/**\n * Bitcoin block header wire format: 80 bytes, all integers little-endian.\n *\n * version (i32) | prevHash (32) | merkleRoot (32) | time (u32) | bits (u32) | nonce (u32)\n *\n * Hashes are carried in display order (byte-reversed hex, as bitcoind and\n * explorers print them). `headerHash` returns the natural (internal) byte\n * order, which is what proof-of-work compares as a little-endian integer.\n */\n\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { bytesToHex, hexToBytes } from \"@noble/hashes/utils.js\";\n\nexport const HEADER_SIZE = 80;\n\nexport interface BlockHeader {\n\t/** Signed 32-bit version field. */\n\tversion: number;\n\t/** Display-order hex of the previous block hash. */\n\tprevHash: string;\n\t/** Display-order hex of the merkle root. */\n\tmerkleRoot: string;\n\t/** Unix timestamp, seconds. */\n\ttime: number;\n\t/** Compact-encoded target. */\n\tbits: number;\n\tnonce: number;\n}\n\nfunction toBytes(raw: Uint8Array | string): Uint8Array {\n\treturn typeof raw === \"string\" ? hexToBytes(raw) : raw;\n}\n\n/** Reverses byte order: natural <-> display. Returns a copy. */\nexport function reverseBytes(bytes: Uint8Array): Uint8Array {\n\treturn Uint8Array.from(bytes).reverse();\n}\n\nexport function parseHeader(raw: Uint8Array | string): BlockHeader {\n\tconst bytes = toBytes(raw);\n\tif (bytes.length !== HEADER_SIZE) {\n\t\tthrow new RangeError(\n\t\t\t`block header must be ${HEADER_SIZE} bytes, got ${bytes.length}`,\n\t\t);\n\t}\n\tconst view = new DataView(bytes.buffer, bytes.byteOffset, HEADER_SIZE);\n\treturn {\n\t\tversion: view.getInt32(0, true),\n\t\tprevHash: bytesToHex(reverseBytes(bytes.subarray(4, 36))),\n\t\tmerkleRoot: bytesToHex(reverseBytes(bytes.subarray(36, 68))),\n\t\ttime: view.getUint32(68, true),\n\t\tbits: view.getUint32(72, true),\n\t\tnonce: view.getUint32(76, true),\n\t};\n}\n\nexport function serializeHeader(header: BlockHeader): Uint8Array {\n\tconst bytes = new Uint8Array(HEADER_SIZE);\n\tconst view = new DataView(bytes.buffer);\n\tview.setInt32(0, header.version, true);\n\tbytes.set(reverseBytes(hexToBytes(header.prevHash)), 4);\n\tbytes.set(reverseBytes(hexToBytes(header.merkleRoot)), 36);\n\tview.setUint32(68, header.time, true);\n\tview.setUint32(72, header.bits, true);\n\tview.setUint32(76, header.nonce, true);\n\treturn bytes;\n}\n\n/** Double-SHA256 of the raw header, natural (internal) byte order. */\nexport function headerHash(raw: Uint8Array | string): Uint8Array {\n\tconst bytes = toBytes(raw);\n\tif (bytes.length !== HEADER_SIZE) {\n\t\tthrow new RangeError(\n\t\t\t`block header must be ${HEADER_SIZE} bytes, got ${bytes.length}`,\n\t\t);\n\t}\n\treturn sha256(sha256(bytes));\n}\n\n/** Block hash as display-order hex (what bitcoind prints). */\nexport function headerHashHex(raw: Uint8Array | string): string {\n\treturn bytesToHex(reverseBytes(headerHash(raw)));\n}\n",
14
14
  "/**\n * Proof-of-work arithmetic, mirroring Bitcoin Core's arith_uint256\n * SetCompact/GetCompact, CheckProofOfWork, GetBlockProof and\n * CalculateNextWorkRequired (mainnet parameters only).\n */\n\n/** Mainnet powLimit, compact form. */\nexport const POW_LIMIT_BITS = 0x1d00ffff;\n/** Mainnet powLimit: 0x00000000ffff0000...0000. */\nexport const POW_LIMIT = 0xffffn << 208n;\n/** Blocks per difficulty period. */\nexport const RETARGET_INTERVAL = 2016;\n/** Two weeks, seconds. */\nexport const TARGET_TIMESPAN = 14 * 24 * 60 * 60;\n\nconst TWO_256 = 1n << 256n;\n\nexport interface DecodedCompact {\n\ttarget: bigint;\n\tnegative: boolean;\n\toverflow: boolean;\n}\n\n/** Core's arith_uint256::SetCompact, including its negative/overflow flags. */\nexport function decodeCompact(bits: number): DecodedCompact {\n\tconst size = bits >>> 24;\n\tlet word = bits & 0x007fffff;\n\tlet target: bigint;\n\tif (size <= 3) {\n\t\tword >>>= 8 * (3 - size);\n\t\ttarget = BigInt(word);\n\t} else {\n\t\ttarget = BigInt(word) << BigInt(8 * (size - 3));\n\t}\n\tconst negative = word !== 0 && (bits & 0x00800000) !== 0;\n\tconst overflow =\n\t\tword !== 0 &&\n\t\t(size > 34 || (word > 0xff && size > 33) || (word > 0xffff && size > 32));\n\treturn { target: target & (TWO_256 - 1n), negative, overflow };\n}\n\n/** Decodes compact bits to a target, throwing on negative/overflow/zero. */\nexport function bitsToTarget(bits: number): bigint {\n\tconst { target, negative, overflow } = decodeCompact(bits);\n\tif (negative || overflow || target === 0n) {\n\t\tthrow new RangeError(\n\t\t\t`bits 0x${bits.toString(16).padStart(8, \"0\")} do not encode a valid target`,\n\t\t);\n\t}\n\treturn target;\n}\n\n/** Core's arith_uint256::GetCompact for a non-negative target. */\nexport function targetToBits(target: bigint): number {\n\tif (target < 0n) throw new RangeError(\"target must be non-negative\");\n\tlet size = target === 0n ? 0 : Math.ceil(target.toString(2).length / 8);\n\tlet compact =\n\t\tsize <= 3\n\t\t\t? Number(target << BigInt(8 * (3 - size)))\n\t\t\t: Number(target >> BigInt(8 * (size - 3)));\n\tif (compact & 0x00800000) {\n\t\tcompact >>>= 8;\n\t\tsize += 1;\n\t}\n\treturn ((size << 24) | compact) >>> 0;\n}\n\n/** Interprets a natural-order hash as the little-endian 256-bit integer PoW compares. */\nexport function hashToBigInt(hash: Uint8Array): bigint {\n\tlet n = 0n;\n\tfor (let i = hash.length - 1; i >= 0; i--) {\n\t\tn = (n << 8n) | BigInt(hash[i] as number);\n\t}\n\treturn n;\n}\n\n/** Core's CheckProofOfWork: valid target ≤ powLimit and hash ≤ target. */\nexport function checkProofOfWork(hash: Uint8Array, bits: number): boolean {\n\tconst { target, negative, overflow } = decodeCompact(bits);\n\tif (negative || overflow || target === 0n || target > POW_LIMIT) {\n\t\treturn false;\n\t}\n\treturn hashToBigInt(hash) <= target;\n}\n\n/** Expected number of hashes for a block at `bits`: 2^256 / (target + 1). */\nexport function headerWork(bits: number): bigint {\n\tconst target = bitsToTarget(bits);\n\t// Core's GetBlockProof: (~target / (target + 1)) + 1, same value without overflow.\n\treturn (TWO_256 - 1n - target) / (target + 1n) + 1n;\n}\n\n/**\n * Core's CalculateNextWorkRequired. `firstTime` is the timestamp of the first\n * block of the closing period and `lastTime` of its last block, so the\n * measured span covers 2015 intervals, not 2016 (the well-known off-by-one\n * that consensus preserves).\n */\nexport function nextRetargetBits(\n\tlastBits: number,\n\tfirstTime: number,\n\tlastTime: number,\n): number {\n\tlet actual = lastTime - firstTime;\n\tif (actual < TARGET_TIMESPAN / 4) actual = TARGET_TIMESPAN / 4;\n\tif (actual > TARGET_TIMESPAN * 4) actual = TARGET_TIMESPAN * 4;\n\tlet target =\n\t\t(bitsToTarget(lastBits) * BigInt(actual)) / BigInt(TARGET_TIMESPAN);\n\tif (target > POW_LIMIT) target = POW_LIMIT;\n\treturn targetToBits(target);\n}\n",
15
15
  "// Generated by scripts/rotate-checkpoint.ts. Do not edit by hand.\n// Stacks block 9,055,251, cycle 144, Bitcoin height 967,680.\nimport type { VerifyCheckpoint } from \"./checkpoint.ts\";\n\n/**\n * Mainnet: Stacks block 9,055,251 (`10cb4e95…c5be`) holding the cycle 144\n * signer set (31 signers, weight 4000), and Bitcoin block 967,680 (a\n * retarget-period start at or below cycle 144's first burn block 968,450). Later blocks verify forward\n * (burn height 967,680 or later); earlier ones by hash chain from 9,055,251.\n */\nexport const MAINNET_CHECKPOINT: VerifyCheckpoint = {\n\tstacks: {\n\t\theader: [\n\t\t\t\"0100000000008a2c1300000066469e6fe824e36e45dbfb6f63201cc4847d12cae9c128c66d8e9a793304ef768e4728c6\",\n\t\t\t\"7634484bd3dc868a787699dd8952c6b37cdeaefed8451304f9bf56fc8e9b5e8d80c716d8bece86dbe7e855348e71dc23\",\n\t\t\t\"a3e7327ecf9ff95aa970430671f50a2ff6fd8c4ef444c4650ce456c8a10b5c8e084670e692000000006ab58f03003c14\",\n\t\t\t\"9857675a089d271510492aa1e1decfd5c4a32e6f27f4aaaf299822bd0f83599991bc1ee5027e08f2181bcb1285d6f04b\",\n\t\t\t\"a66cd3e4122f1565d266bcae019c0000001701e427ee3446da226d964aba82349d59691a8a9d087cd7519fd53b3ca555\",\n\t\t\t\"e45f0746cd3e0c7cd196e2f8acf668c88aadb0e2bb3c185565d34f6475e13ac003929100b0bc28034cee5679858614f4\",\n\t\t\t\"9e554f55cec31a7cd4cb3f56d6be284df984b3ea2b5e15744325c6d6de0648e3c14f8c4a0f15eb8c1d87693013b13390\",\n\t\t\t\"36f8973900e0853aac5dd6dff18c20d8cf2196a22ed65bced9d5e75b932a0b05778763725a4490f514b85d5274099b3b\",\n\t\t\t\"8a4cb02dd105bd85ea87276bad8a419d1e7ca4fe3601264cc97fc706ad2ae443baf9ea807e2c3ab2c0c561b847689ad9\",\n\t\t\t\"57a2f7ea41c7749d9847dec5b6458693955a8367ee44bf16233db5bab24704470bfa820ebff200a51fd156df644335ba\",\n\t\t\t\"e6d4e63c229ff0556aa75f98360fa0fa72439426e09d2964ffe74ebb628a04ad2493d1bf2c5548416afc0afafcbe57d1\",\n\t\t\t\"d0c2e5d0f54b3a01222775d8bf237bde985b1a5199e3d2bc248fab425d338fb9102bbd860687b0e516c9a7891628ad3b\",\n\t\t\t\"31e11dd447594fc9a3381dd62efe0fdf183a4d6e6d630ae6018c2a16339c484a26b239fbc04572bccc22435e90607a4e\",\n\t\t\t\"01980614ebe4c6b5337ed06fb359e8f2db7add5e6da7f45e806a30a9d2abb8fc4841611c2bf13c9eb901463e39a7b64c\",\n\t\t\t\"26d78deffd691be358fcfa03f28179da0f300aa4b045a59072c523e824372b172aec0a9ea71c568ab769b5672fa01ab1\",\n\t\t\t\"3c36799ba4e85749722b012ab3b504a3ece80bf2186db6fe2407847fb6eef44206de958788b552c1226c034ccf34681f\",\n\t\t\t\"d02f9f2f890b09a94b4002326ac836620a4daffc6a4149bc58a52600977d6a2b9aaf7adf6f5108dd2c9e05f169991907\",\n\t\t\t\"0514fae6c4e0aeab2656b9a47581de7232198cef38d07d7fe1cd0238d88cac758280b2c633d0bab556ffe311010f0162\",\n\t\t\t\"14ac30572c349981bc006617b43315b0d52efb06ea00c012f1269311340c8bd32615d24201279b3cd77d97adbb80b3e5\",\n\t\t\t\"1a0ec357fc1b0865c826f292f4013df0c85f71124088fed20acc3160df54b6d9e0a454a5c7689239125acd4d613e6a2c\",\n\t\t\t\"ed667e92d34d0548983d3c5d53468e00ec15bafc27b8946edae6aed04157008980f7c33cad51d44ff60d61a941cc62b3\",\n\t\t\t\"e73a47e0cda51e564b01433866545640736823d42ae8b74ca35764812ebcf943a47b150f4e7f794c0216611051dd7000\",\n\t\t\t\"c77ba1ce6a3a5d205b701c9d55fe5ac8730ec827deecfa8ad7800c331a839c4c705bc7708728128849ed5945b6020a38\",\n\t\t\t\"7d1dbc08f8d4fb8449a722ee2e9f02b50023724701dc7a7c69b3025abfea79e67d7d7a5156c77072c9d58f4bf1cae2f5\",\n\t\t\t\"f62f29527eb27f725f03d05986be28102ea27ee22052ef046ff1c6a4e09dc9a2c501f5231b9ff20a199c872f137b6ee5\",\n\t\t\t\"cfd9ceb1df5973cd3ffab5a66fb6c89e58de550360f9933f6c5087d833e5b59b928405a676013e7377552bc6353fc852\",\n\t\t\t\"94fd0083c761efba23bd276e82648135a4efcf73298bb13ef6e1cfbff37d3d99c757d46be3bffb5ec0fd46ffa849a1e5\",\n\t\t\t\"813fcdb5d38ee95c5db3283bde0179c7a3b46e016b2418238b35dfeb9b84142f391702f71be43970e725576030102a7d\",\n\t\t\t\"45acd6d834547636d6bc2a0bc559b9408edb460d5f4384ecefcdfad64e89923c30d83ed400a9009444429ec9a22789f2\",\n\t\t\t\"31629ec51067c76a3d3802d0a4a625be9679c36ef12e2a888458bcdac4fe9ada9cfdea650a77a2b46fb760c144485f34\",\n\t\t\t\"ac3ae7d5d70041eb4b36d08f7997747fb991d00c086644cc6ec1bf3f9bb53336e78358961d844d107bdb6e59977f9a9c\",\n\t\t\t\"0d8f996efb36eed0d7fb8ce26fadc63cb9b79cc7795201a9ebee00b3818295c807c90ea8e6f9d0b4beee23003365ada5\",\n\t\t\t\"4ca964390bc1c62bfe1a7e78084c384bef7ca2ed45241e818fefe1911d711fad5e13eff8ddf31000f08d21fc2a3b8c67\",\n\t\t\t\"193fec9a326b8a49c0a9696fc66523014b9db5ed312a824a5bd87e29fbe3328d5f3ed05c3f38c7f4a6e4e53410830849\",\n\t\t\t\"6a7458a149ff975101a957fd6ff8ce3d70bf0a9f5652aa6a87e27f3a8130d3f70558417cc3744d9b9b5879872467e520\",\n\t\t\t\"f641c7253dc159cd1a0e2547d1c9a6ff3c45ce2d233e626fea0001000000010100000000\",\n\t\t].join(\"\"),\n\t\tcycle: 144,\n\t\tsignerSet: [\n\t\t\t\"0a0b0000001f0c00000002067369676e65720516f5061b1c62f399ecc0db8cbb21f8d481af079a380677656967687401\",\n\t\t\t\"0000000000000000000000000000027c0c00000002067369676e65720516a3bbf2a4133fbd5bd1880982957b7a760347\",\n\t\t\t\"b2dc0677656967687401000000000000000000000000000000090c00000002067369676e657205164f72f6b5a9f5d863\",\n\t\t\t\"34b2f0fe701db51a7a246f3d0677656967687401000000000000000000000000000000a90c00000002067369676e6572\",\n\t\t\t\"0516f70ad5f98bb53d1ff1946e62096df4bf71cdb1b20677656967687401000000000000000000000000000000090c00\",\n\t\t\t\"000002067369676e6572051653ec8b4f51c8286dad6f4ff81ca2a3409d2f382d06776569676874010000000000000000\",\n\t\t\t\"00000000000000050c00000002067369676e65720516dba631825ff0f15c7c5946b560070f8f5f5747cb067765696768\",\n\t\t\t\"7401000000000000000000000000000000240c00000002067369676e6572051600d058b39f4495b412ff7eada763eaa6\",\n\t\t\t\"386eb90a06776569676874010000000000000000000000000000027c0c00000002067369676e65720516321ac33715d6\",\n\t\t\t\"84d5e8d0cf427cd985576f64c6df06776569676874010000000000000000000000000000000b0c00000002067369676e\",\n\t\t\t\"6572051671cfb41047d1833d24abc8f08a785182b769fd14067765696768740100000000000000000000000000000004\",\n\t\t\t\"0c00000002067369676e6572051677a52718ba90fca67984166b2a084edb9b3bd8f10677656967687401000000000000\",\n\t\t\t\"000000000000000000090c00000002067369676e65720516a54a20479b3b65a461a427b9161b78e64db58ba706776569\",\n\t\t\t\"67687401000000000000000000000000000001f50c00000002067369676e65720516bc1a58c2a058a9e4150db25562e8\",\n\t\t\t\"331ef8a4267c0677656967687401000000000000000000000000000000060c00000002067369676e657205161091d2da\",\n\t\t\t\"4c9ee17a340171c0d23c4304b54ef43f0677656967687401000000000000000000000000000000670c00000002067369\",\n\t\t\t\"676e6572051654d01a0973ed139736a1a43032a6a18d9295ec7206776569676874010000000000000000000000000000\",\n\t\t\t\"00b50c00000002067369676e657205160c49f5b6c62f1163ddbb21f92aba86f17f7be488067765696768740100000000\",\n\t\t\t\"0000000000000000000000670c00000002067369676e65720516ad16c79ac56b58f0797f78c534385367460626800677\",\n\t\t\t\"656967687401000000000000000000000000000000670c00000002067369676e657205169689e56df00385b6bd81fb6b\",\n\t\t\t\"7769d5b04088acb80677656967687401000000000000000000000000000000aa0c00000002067369676e65720516a4f7\",\n\t\t\t\"f81412f4413771a48825cfbe2062a774d4e90677656967687401000000000000000000000000000002fe0c0000000206\",\n\t\t\t\"7369676e65720516ed73a7398f1c3eb566f3bd7f4bd43f52adf33d8f0677656967687401000000000000000000000000\",\n\t\t\t\"000000670c00000002067369676e65720516937b3b43e0d94c9ef8f171892bce949709e1d41f06776569676874010000\",\n\t\t\t\"00000000000000000000000000240c00000002067369676e6572051631542aacfd6e04858181c3067b5eb07399ba89df\",\n\t\t\t\"0677656967687401000000000000000000000000000000590c00000002067369676e6572051649f034cd1662a222dbc3\",\n\t\t\t\"8a6acd64008ba7e557660677656967687401000000000000000000000000000000050c00000002067369676e65720516\",\n\t\t\t\"a20f660dea498c169897a39cb89ce0d98856e5720677656967687401000000000000000000000000000000090c000000\",\n\t\t\t\"02067369676e6572051652d58897b3678f3a758fa4b9270744fec0605b21067765696768740100000000000000000000\",\n\t\t\t\"0000000000670c00000002067369676e6572051631733264626dc5fef36eb683a5069d89f63b64cc0677656967687401\",\n\t\t\t\"000000000000000000000000000000090c00000002067369676e65720516d80db618c2def577604cd8e40a3940b5b639\",\n\t\t\t\"b1ac06776569676874010000000000000000000000000000000a0c00000002067369676e657205162042a380d946a828\",\n\t\t\t\"66465af8521a273efe6d2a600677656967687401000000000000000000000000000000470c00000002067369676e6572\",\n\t\t\t\"051635e1b36efc22bc607db92f9100cb08e3473d60250677656967687401000000000000000000000000000000030c00\",\n\t\t\t\"000002067369676e657205164843b97054e43dd1a8571fc1e72949c5bedfb7e906776569676874010000000000000000\",\n\t\t\t\"000000000000004b0c00000002067369676e657205164883355670025c19ecae644ffa20e75ce1d730ad067765696768\",\n\t\t\t\"7401000000000000000000000000000000090c00000002067369676e65720516089ffd0e0ecd61d9e3c8ee42ef94148a\",\n\t\t\t\"cf88aa88067765696768740100000000000000000000000000000015\",\n\t\t].join(\"\"),\n\t},\n\tbitcoin: {\n\t\theight: 967680,\n\t\theader:\n\t\t\t\"00000030410ccb1cba623e26f2e02f3fcb0e7f06f66998b68cb5010000000000000000003d16ae2558e8ec7b8dd369ee29bb2733fbd39bcc1058c681970a36a7f1a2bdea1135ae6ac51e0217480c3581\",\n\t},\n};\n",
16
- "// Proof data sources. Everything a source returns is untrusted: verifyBlock\n// checks every byte against the checkpoint, so a lying source can make a\n// check fail but never pass.\nimport { type Bytes, unhex } from \"./bytes.ts\";\n\n/** Sortition preimage behind a consensus hash. */\nexport interface BurnPreimage {\n\tpreimage: Bytes;\n\t/** The source's claimed burn height: a hint for how far to sync Bitcoin headers, never trusted. */\n\tburnHeight: number;\n}\n\n/** Node RPC `/v2/clarity/marf/<path>?proof=1` answer. */\nexport interface MarfProofResponse {\n\t/** Value string as Clarity stored it (hex for Clarity values), 0x prefix tolerated. */\n\tdata: string;\n\t/** Consensus-serialized TrieMerkleProof. */\n\tproof: Bytes;\n}\n\n/** One storage-layer MARF write (`state_writes` row), in block write order. */\nexport interface StateWrite {\n\t/** Null for block-level writes outside any transaction. */\n\ttx_index: number | null;\n\tordinal: number;\n\t/** Full MARF key, e.g. `vm::<contract>::0::<map>::<key hex>`. */\n\tkey: string;\n\t/** Hex of the stored value string's UTF-8 bytes. */\n\tvalue_hex: string;\n}\n\n/** A `vm_events` write row, as the Index API serves it. */\nexport interface VmEventRow {\n\tevent_type: \"var_set\" | \"map_set\" | \"map_insert\" | \"map_delete\";\n\t/** The row's ordinal within the block. */\n\tevent_index: number;\n\ttx_id?: string;\n\ttx_index?: number;\n\tcontract_id: string;\n\tvar_name?: string | null;\n\tmap?: string | null;\n\traw_key?: string | null;\n\traw_value?: string | null;\n}\n\n/** An epoch 2.x header and the consensus hash its index block hash commits to. */\nexport interface Epoch2HeaderResponse {\n\t/** Consensus-serialized StacksBlockHeader. */\n\theader: Bytes;\n\tconsensusHash: Bytes;\n}\n\nexport interface ProofSource {\n\t/** Raw Nakamoto block bytes (header first), by block id or height. */\n\tgetBlock(ref: string | number): Promise<Bytes>;\n\t/**\n\t * Epoch 2.x block header by index block hash: blocks below the checkpoint\n\t * from before Nakamoto. Without it only Nakamoto blocks verify.\n\t */\n\tgetEpoch2Header?(blockId: string): Promise<Epoch2HeaderResponse>;\n\t/**\n\t * MARF inclusion proof for a 32-byte path at `tipId`; null when the key is\n\t * absent. Blocks below the checkpoint also ask for\n\t * `__MARF_BLOCK_HEIGHT_TO_HASH::<height>`, whose value is no stored string:\n\t * only `proof` is read for it.\n\t */\n\tgetMarfProof(\n\t\tpathHex: string,\n\t\ttipId: string,\n\t): Promise<MarfProofResponse | null>;\n\t/** State witness (wire v3) for a block. */\n\tgetWitness(blockId: string): Promise<Bytes>;\n\tgetBurnPreimage(consensusHash: string): Promise<BurnPreimage>;\n\t/** Raw 80-byte Bitcoin headers (hex or bytes) from height `from`. */\n\tgetBitcoinHeaders(from: number, count: number): Promise<(string | Bytes)[]>;\n\t/**\n\t * Every MARF write of the block, in ordinal order; null (or empty) when\n\t * the source has none for it. Names the block's diff.\n\t */\n\tgetStateWrites?(height: number): Promise<StateWrite[] | null>;\n\t/** Indexed vm_events write rows of the block, checked against its proven diff. */\n\tgetVmEvents?(height: number): Promise<VmEventRow[]>;\n}\n\n/**\n * Thrown when a proof source request fails.\n *\n * It carries the request `url`, the HTTP `status` (null when there was none)\n * and the detail.\n */\nexport class SourceError extends Error {\n\toverride readonly name = \"SourceError\";\n\tconstructor(\n\t\treadonly url: string,\n\t\treadonly status: number | null,\n\t\tdetail: string,\n\t) {\n\t\tsuper(`${url}: ${detail}`);\n\t}\n}\n\ntype Fetch = (url: string, init?: RequestInit) => Promise<Response>;\n\ninterface HttpOptions {\n\theaders?: Record<string, string>;\n\tfetch?: Fetch;\n}\n\nconst MAX_ATTEMPTS = 3;\nconst MAX_RETRY_SECONDS = 10;\n\n/** GET with retries on 429 and 503 (honoring retry-after); null on 404. */\nasync function get(\n\turl: string,\n\topts: HttpOptions,\n\tattempt = 1,\n): Promise<Response | null> {\n\tconst doFetch = opts.fetch ?? fetch;\n\tlet res: Response;\n\ttry {\n\t\tres = await doFetch(url, { headers: opts.headers });\n\t} catch (err) {\n\t\tthrow new SourceError(url, null, (err as Error).message);\n\t}\n\tif (res.status === 404) return null;\n\tif ((res.status === 503 || res.status === 429) && attempt < MAX_ATTEMPTS) {\n\t\tconst header = res.headers.get(\"retry-after\");\n\t\tconst seconds = header === null ? 1 : Number(header);\n\t\tconst wait = Number.isFinite(seconds)\n\t\t\t? Math.min(Math.max(seconds, 0), MAX_RETRY_SECONDS)\n\t\t\t: 1;\n\t\tawait new Promise((r) => setTimeout(r, wait * 1000));\n\t\treturn get(url, opts, attempt + 1);\n\t}\n\tif (!res.ok) throw new SourceError(url, res.status, `HTTP ${res.status}`);\n\treturn res;\n}\n\nasync function getJson<T>(url: string, opts: HttpOptions): Promise<T | null> {\n\tconst res = await get(url, opts);\n\treturn res ? ((await res.json()) as T) : null;\n}\n\nasync function getBytes(url: string, opts: HttpOptions): Promise<Bytes | null> {\n\tconst res = await get(url, opts);\n\treturn res ? new Uint8Array(await res.arrayBuffer()) : null;\n}\n\nconst required = <T>(url: string, v: T | null): T => {\n\tif (v === null) throw new SourceError(url, 404, \"not found\");\n\treturn v;\n};\n\nconst trimSlash = (s: string) => s.replace(/\\/+$/, \"\");\n\ntype MarfJson = { data: string; proof?: string; marf_proof?: string };\n\ntype HeadersJson = { header?: unknown; consensus_hash?: unknown }[];\n\n/** The first entry of a node `/v2/headers/1?tip=<id>` answer: the tip itself. */\nconst toEpoch2 = (url: string, j: HeadersJson | null): Epoch2HeaderResponse => {\n\tconst tip = required(url, j)[0];\n\tif (typeof tip?.header !== \"string\" || typeof tip.consensus_hash !== \"string\")\n\t\tthrow new SourceError(url, 200, \"answer needs header and consensus_hash\");\n\treturn {\n\t\theader: unhex(tip.header),\n\t\tconsensusHash: unhex(tip.consensus_hash),\n\t};\n};\n\nconst toMarf = (url: string, j: MarfJson | null): MarfProofResponse | null => {\n\tif (j === null) return null;\n\tconst proof = j.proof ?? j.marf_proof;\n\tif (typeof proof !== \"string\" || typeof j.data !== \"string\")\n\t\tthrow new SourceError(url, 200, \"MARF answer needs data and proof\");\n\treturn { data: j.data, proof: unhex(proof) };\n};\n\n/** The hosted API. */\nexport const DEFAULT_API_URL = \"https://api.secondlayer.tools\";\n\nexport interface SecondlayerSourceOptions {\n\t/** API origin. Defaults to {@link DEFAULT_API_URL}. */\n\tbaseUrl?: string;\n\t/**\n\t * Optional. Proofs are keyless; a key raises the rate limit. Required for\n\t * `rows: true` (metered Index reads). Sent as `Authorization: Bearer`.\n\t */\n\tapiKey?: string;\n\tfetch?: Fetch;\n}\n\nconst VM_WRITE_TYPES = [\n\t\"var_set\",\n\t\"map_set\",\n\t\"map_insert\",\n\t\"map_delete\",\n] as const;\nconst PAGE = 1000;\n\n/** Follow `next_cursor` until a page comes back empty. Null when the first page 404s. */\nasync function pages<T>(\n\tfield: string,\n\turl: string,\n\thttp: HttpOptions,\n): Promise<T[] | null> {\n\tconst out: T[] = [];\n\tlet cursor: string | null = null;\n\tfor (;;) {\n\t\tconst page: string = cursor\n\t\t\t? `${url}&cursor=${encodeURIComponent(cursor)}`\n\t\t\t: url;\n\t\tconst j = await getJson<Record<string, unknown>>(page, http);\n\t\tif (j === null) return cursor === null ? null : out;\n\t\tconst rows = j[field];\n\t\tif (!Array.isArray(rows))\n\t\t\tthrow new SourceError(page, 200, `answer has no ${field} array`);\n\t\tout.push(...(rows as T[]));\n\t\tconst next = j.next_cursor;\n\t\tif (rows.length < PAGE || typeof next !== \"string\" || next === cursor)\n\t\t\treturn out;\n\t\tcursor = next;\n\t}\n}\n\n// Both sources keep their origin and account key in constructor closures, not\n// fields: nothing leaks through a spread, a log or JSON.stringify.\n\n/**\n * Reads every proof input from the Secondlayer API.\n *\n * Blocks, epoch 2.x headers, MARF proofs, witnesses, burn preimages, Bitcoin\n * headers and each block's state writes come from `/v1/proofs/*`, which is free\n * and rate limited. Indexed `vm_events` rows come from the Index API as metered\n * rows, and are read only when `verifyBlock` gets `rows: true`. Methods are own\n * properties, so a partial source spreads over it:\n * `{ ...new SecondlayerProofSource(o), ...new NodeRpcProofSource(n) }`.\n */\nexport class SecondlayerProofSource implements ProofSource {\n\t/** Raw block bytes, header first, by block id or height. */\n\tgetBlock: (ref: string | number) => Promise<Bytes>;\n\t/** An epoch 2.x header and its consensus hash, by index block hash. */\n\tgetEpoch2Header: (blockId: string) => Promise<Epoch2HeaderResponse>;\n\t/**\n\t * A MARF inclusion proof for a path at a tip.\n\t *\n\t * It is null when the key is absent.\n\t */\n\tgetMarfProof: (\n\t\tpathHex: string,\n\t\ttipId: string,\n\t) => Promise<MarfProofResponse | null>;\n\t/** The state witness for a block. */\n\tgetWitness: (blockId: string) => Promise<Bytes>;\n\t/** The burn preimage behind a consensus hash. */\n\tgetBurnPreimage: (consensusHash: string) => Promise<BurnPreimage>;\n\t/** Raw 80-byte Bitcoin headers, `count` of them from height `from`. */\n\tgetBitcoinHeaders: (from: number, count: number) => Promise<string[]>;\n\t/**\n\t * Every MARF write of a block, in ordinal order.\n\t *\n\t * It is null when there are none.\n\t */\n\tgetStateWrites: (height: number) => Promise<StateWrite[] | null>;\n\t/** The indexed `vm_events` write rows of a block, from the Index API. */\n\tgetVmEvents: (height: number) => Promise<VmEventRow[]>;\n\n\tconstructor(opts: SecondlayerSourceOptions = {}) {\n\t\tconst base = trimSlash(opts.baseUrl ?? DEFAULT_API_URL);\n\t\tconst http: HttpOptions = {\n\t\t\theaders: opts.apiKey ? { authorization: `Bearer ${opts.apiKey}` } : {},\n\t\t\tfetch: opts.fetch,\n\t\t};\n\n\t\tthis.getBlock = async (ref) => {\n\t\t\tconst url =\n\t\t\t\ttypeof ref === \"number\"\n\t\t\t\t\t? `${base}/v1/proofs/block/height/${ref}`\n\t\t\t\t\t: `${base}/v1/proofs/block/${ref}`;\n\t\t\treturn required(url, await getBytes(url, http));\n\t\t};\n\n\t\tthis.getEpoch2Header = async (blockId) => {\n\t\t\tconst url = `${base}/v1/proofs/epoch2-header/${blockId}`;\n\t\t\treturn toEpoch2(url, await getJson<HeadersJson>(url, http));\n\t\t};\n\n\t\tthis.getMarfProof = async (pathHex, tipId) => {\n\t\t\tconst url = `${base}/v1/proofs/marf/${pathHex}?tip=${tipId}`;\n\t\t\treturn toMarf(url, await getJson<MarfJson>(url, http));\n\t\t};\n\n\t\tthis.getWitness = async (blockId) => {\n\t\t\tconst url = `${base}/v1/proofs/witness/${blockId}`;\n\t\t\treturn required(url, await getBytes(url, http));\n\t\t};\n\n\t\tthis.getBurnPreimage = async (consensusHash) => {\n\t\t\tconst url = `${base}/v1/proofs/burn/${consensusHash}`;\n\t\t\tconst j = required(\n\t\t\t\turl,\n\t\t\t\tawait getJson<{ burn_height: number; preimage: string }>(url, http),\n\t\t\t);\n\t\t\treturn { preimage: unhex(j.preimage), burnHeight: j.burn_height };\n\t\t};\n\n\t\tthis.getBitcoinHeaders = async (from, count) => {\n\t\t\tconst url = `${base}/v1/proofs/bitcoin-headers?from=${from}&count=${count}`;\n\t\t\tconst j = required(\n\t\t\t\turl,\n\t\t\t\tawait getJson<{ from: number; headers: string[] }>(url, http),\n\t\t\t);\n\t\t\tif (j.from !== from)\n\t\t\t\tthrow new SourceError(url, 200, `headers start at ${j.from}`);\n\t\t\treturn j.headers;\n\t\t};\n\n\t\tthis.getStateWrites = async (height) => {\n\t\t\tconst url = `${base}/v1/proofs/writes/${height}`;\n\t\t\tconst j = await getJson<{ state_writes?: unknown }>(url, http);\n\t\t\tif (j === null) return null;\n\t\t\tif (!Array.isArray(j.state_writes))\n\t\t\t\tthrow new SourceError(url, 200, \"answer has no state_writes array\");\n\t\t\treturn j.state_writes as StateWrite[];\n\t\t};\n\n\t\tthis.getVmEvents = async (height) => {\n\t\t\tconst eventsUrl = (type: string) =>\n\t\t\t\t`${base}/v1/index/events?event_type=${type}&from_height=${height}&to_height=${height}&limit=${PAGE}`;\n\t\t\tif (!opts.apiKey)\n\t\t\t\tthrow new SourceError(\n\t\t\t\t\teventsUrl(VM_WRITE_TYPES[0]),\n\t\t\t\t\t401,\n\t\t\t\t\t\"rows: true reads metered Index events and needs an apiKey\",\n\t\t\t\t);\n\t\t\tconst out: VmEventRow[] = [];\n\t\t\tfor (const type of VM_WRITE_TYPES) {\n\t\t\t\tconst url = eventsUrl(type);\n\t\t\t\tout.push(...((await pages<VmEventRow>(\"events\", url, http)) ?? []));\n\t\t\t}\n\t\t\treturn out.sort((a, b) => a.event_index - b.event_index);\n\t\t};\n\t}\n}\n\nexport interface NodeRpcSourceOptions {\n\t/** Stacks node RPC origin, e.g. `http://localhost:20443`. */\n\tnodeUrl: string;\n\tfetch?: Fetch;\n}\n\n/**\n * Reads blocks, epoch 2.x headers and MARF proofs from a Stacks node.\n *\n * It uses the node's RPC. Witnesses, burn preimages and Bitcoin headers need\n * another source: spread this over one.\n */\nexport class NodeRpcProofSource\n\timplements Pick<ProofSource, \"getBlock\" | \"getEpoch2Header\" | \"getMarfProof\">\n{\n\t/** Raw block bytes, header first, by block id or height. */\n\tgetBlock: (ref: string | number) => Promise<Bytes>;\n\t/** An epoch 2.x header and its consensus hash, by index block hash. */\n\tgetEpoch2Header: (blockId: string) => Promise<Epoch2HeaderResponse>;\n\t/**\n\t * A MARF inclusion proof for a path at a tip.\n\t *\n\t * It is null when the key is absent.\n\t */\n\tgetMarfProof: (\n\t\tpathHex: string,\n\t\ttipId: string,\n\t) => Promise<MarfProofResponse | null>;\n\n\tconstructor(opts: NodeRpcSourceOptions) {\n\t\tconst base = trimSlash(opts.nodeUrl);\n\t\tconst http: HttpOptions = { fetch: opts.fetch };\n\n\t\tthis.getBlock = async (ref) => {\n\t\t\tconst url =\n\t\t\t\ttypeof ref === \"number\"\n\t\t\t\t\t? `${base}/v3/blocks/height/${ref}`\n\t\t\t\t\t: `${base}/v3/blocks/${ref}`;\n\t\t\treturn required(url, await getBytes(url, http));\n\t\t};\n\n\t\tthis.getEpoch2Header = async (blockId) => {\n\t\t\tconst url = `${base}/v2/headers/1?tip=${blockId}`;\n\t\t\treturn toEpoch2(url, await getJson<HeadersJson>(url, http));\n\t\t};\n\n\t\tthis.getMarfProof = async (pathHex, tipId) => {\n\t\t\tconst url = `${base}/v2/clarity/marf/${pathHex}?tip=${tipId}&proof=1`;\n\t\t\treturn toMarf(url, await getJson<MarfJson>(url, http));\n\t\t};\n\t}\n}\n",
17
- "// Steps 6-8 of verifyBlock: a block's state witness against its authenticated\n// header root, every leaf of its trie named, and indexed rows against the diff.\nimport { type Bytes, bytesEqual, hex, unhex } from \"./bytes.ts\";\nimport { dataVarKey } from \"./keys.ts\";\nimport {\n\tMARF_VALUE_SIZE,\n\theightToHashKey,\n\tmarfPath,\n\tmarfValue,\n} from \"./marf.ts\";\nimport type { StateWrite, VmEventRow } from \"./source.ts\";\nimport {\n\ttype WitnessLeaf,\n\tclassifyBlockDiff,\n\tparseWitness,\n} from \"./witness.ts\";\n\nexport interface DiffWrite {\n\t/** MARF key, when a state_writes row names the leaf. */\n\tkey?: string;\n\t/** Leaf path, hex. */\n\tpath: string;\n\t/** sha512/256 of the stored value string, hex. */\n\tvalueHash: string;\n\t/** Transaction of the last write; null for block-level writes. */\n\ttxIndex?: number | null;\n\t/** The stored value string (hex of a Clarity value) the leaf holds; named writes only. */\n\tvalue?: string;\n\t/** False when the source had no state_writes: the leaf may also be a carried copy. */\n\tnamed: boolean;\n}\n\nexport interface DiffLeaf {\n\tkey?: string;\n\tpath: string;\n\tvalueHash: string;\n}\n\nexport interface ProvenDiff {\n\t/** Every leaf is named (state_writes served) and classified. */\n\tnamed: boolean;\n\twrites: DiffWrite[];\n\t/** Unchanged values copied forward from the parent (proven at the parent). */\n\tcarried: DiffLeaf[];\n\t/** `__MARF_BLOCK_*` bookkeeping. */\n\tinternal: DiffLeaf[];\n}\n\nexport type StateFailureCode =\n\t| \"malformed\"\n\t| \"root-mismatch\"\n\t| \"bad-write\"\n\t| \"hidden-write\"\n\t| \"missing-write\"\n\t| \"key-not-written\"\n\t| \"value-mismatch\"\n\t| \"bad-row\";\n\nexport interface StateFailure {\n\tstep: \"witness\" | \"names\" | \"rows\";\n\tcode: StateFailureCode;\n\tmessage: string;\n\tkey?: string;\n\tpath?: string;\n\tordinal?: number;\n}\n\nexport interface BlockStateInput {\n\t/** MARF height of the block (its Stacks chain length). */\n\theight: number;\n\t/** Parent block id from the authenticated header. */\n\tparentBlockId: Bytes;\n\t/** state_index_root from the authenticated header. */\n\tstateRoot: Bytes;\n\twitness: Bytes;\n\t/** The block's state_writes; null when the source has none (names unavailable). */\n\twrites: StateWrite[] | null;\n\t/** Indexed rows to prove against the diff. */\n\trows?: VmEventRow[];\n\t/**\n\t * Leaves of the parent's own trie, from a parent witness whose root the\n\t * caller checked against the parent header: each is the parent state's\n\t * value at its path. Resolves carried leaves without a proof per leaf.\n\t */\n\tparentLeaves?: WitnessLeaf[];\n\t/**\n\t * True iff the leaf's value is stored at its path in the parent's state\n\t * (proven by the caller). Asked only with state_writes, for leaves the\n\t * parent's own trie does not explain.\n\t */\n\tparentHolds?: (leaf: WitnessLeaf) => Promise<boolean>;\n}\n\nexport interface BlockStateResult {\n\tdiff?: ProvenDiff;\n\trowsChecked: number;\n\tnotes: string[];\n\tfailures: StateFailure[];\n}\n\nconst INTERNAL = {\n\tself: \"__MARF_BLOCK_HEIGHT_SELF\",\n\thashToHeight: \"__MARF_BLOCK_HASH_TO_HEIGHT\",\n} as const;\n\n/** MARFValue of a u32 height: little-endian in the first 4 bytes. */\nconst heightValue = (h: number): string => {\n\tconst v = new Uint8Array(MARF_VALUE_SIZE);\n\tnew DataView(v.buffer).setUint32(0, h, true);\n\treturn hex(v);\n};\n/** 40-byte MARFValue hex of a 32-byte hash or block id (zero tail). */\nconst padded = (b32: Bytes): string => `${hex(b32)}${\"00\".repeat(8)}`;\n\n/**\n * The `__MARF_BLOCK_*` entries block `height` writes (stacks-core index/marf.rs).\n * The parent's are fixed by the header. The block's own id is not known while\n * its trie is built, so `HEIGHT_TO_HASH::{height}` holds a temporary hash; its\n * value is taken from the witness and must map back to `height`.\n */\nfunction internalEntries(\n\theight: number,\n\tparentBlockId: Bytes,\n\tleaves: WitnessLeaf[],\n): [key: string, valueHex: string][] {\n\tconst out: [string, string][] = [[INTERNAL.self, heightValue(height)]];\n\tconst ownKey = heightToHashKey(height);\n\tconst ownPath = marfPath(ownKey);\n\tconst own = leaves.find((l) => bytesEqual(l.path, ownPath));\n\tif (own) {\n\t\tout.push([ownKey, padded(own.valueHash)]);\n\t\tout.push([\n\t\t\t`${INTERNAL.hashToHeight}::${hex(own.valueHash)}`,\n\t\t\theightValue(height),\n\t\t]);\n\t}\n\tif (height > 0) {\n\t\tout.push([heightToHashKey(height - 1), padded(parentBlockId)]);\n\t\tout.push([\n\t\t\t`${INTERNAL.hashToHeight}::${hex(parentBlockId)}`,\n\t\t\theightValue(height - 1),\n\t\t]);\n\t}\n\treturn out;\n}\n\nconst utf8 = new TextDecoder(\"utf-8\", { fatal: true });\nconst strip0x = (s: string) => (s.startsWith(\"0x\") ? s.slice(2) : s);\nconst leafHex = (l: WitnessLeaf): DiffLeaf => ({\n\tpath: hex(l.path),\n\tvalueHash: hex(l.valueHash),\n});\n\n/** Last write per key, in ordinal order, with its value as the stored string. */\nfunction lastWrites(\n\twrites: StateWrite[],\n\tfailures: StateFailure[],\n): Map<string, { value: string; txIndex: number | null }> {\n\tconst out = new Map<string, { value: string; txIndex: number | null }>();\n\tfor (const w of [...writes].sort((a, b) => a.ordinal - b.ordinal)) {\n\t\ttry {\n\t\t\tout.set(w.key, {\n\t\t\t\tvalue: utf8.decode(unhex(strip0x(w.value_hex))),\n\t\t\t\ttxIndex: w.tx_index,\n\t\t\t});\n\t\t} catch {\n\t\t\tfailures.push({\n\t\t\t\tstep: \"names\",\n\t\t\t\tcode: \"bad-write\",\n\t\t\t\tmessage: `state write ${w.ordinal} value is not UTF-8 hex`,\n\t\t\t\tkey: w.key,\n\t\t\t\tordinal: w.ordinal,\n\t\t\t});\n\t\t}\n\t}\n\treturn out;\n}\n\n/** The MARF key and stored value string a vm_events row writes (mirrors clarity_db.rs). */\nfunction rowWrite(row: VmEventRow): [key: string, value: string] {\n\tconst need = (v: string | null | undefined, name: string): string => {\n\t\tif (!v) throw new Error(`${row.event_type} row has no ${name}`);\n\t\treturn v;\n\t};\n\tif (row.event_type === \"var_set\")\n\t\treturn [\n\t\t\tdataVarKey(row.contract_id, need(row.var_name, \"var_name\")),\n\t\t\tstrip0x(need(row.raw_value, \"raw_value\")).toLowerCase(),\n\t\t];\n\tconst key = `vm::${row.contract_id}::0::${need(row.map, \"map\")}::${strip0x(need(row.raw_key, \"raw_key\")).toLowerCase()}`;\n\tif (row.event_type === \"map_delete\") return [key, \"09\"];\n\t// put_value stores map entries as (some value).\n\treturn [key, `0a${strip0x(need(row.raw_value, \"raw_value\")).toLowerCase()}`];\n}\n\n/**\n * Rows against the block's leaves: every row's key must be a leaf, and the\n * last row per key must carry the leaf's value.\n */\nfunction checkRows(\n\trows: VmEventRow[],\n\tleaves: WitnessLeaf[],\n\tfailures: StateFailure[],\n): number {\n\tconst byPath = new Map(leaves.map((l) => [hex(l.path), l]));\n\tconst named: { row: VmEventRow; key: string; path: string; value: string }[] =\n\t\t[];\n\tfor (const row of [...rows].sort((a, b) => a.event_index - b.event_index)) {\n\t\ttry {\n\t\t\tconst [key, value] = rowWrite(row);\n\t\t\tnamed.push({ row, key, path: hex(marfPath(key)), value });\n\t\t} catch (err) {\n\t\t\tfailures.push({\n\t\t\t\tstep: \"rows\",\n\t\t\t\tcode: \"bad-row\",\n\t\t\t\tmessage: (err as Error).message,\n\t\t\t\tordinal: row.event_index,\n\t\t\t});\n\t\t}\n\t}\n\tconst last = new Map(named.map((n, i) => [n.path, i]));\n\tnamed.forEach((n, i) => {\n\t\tconst leaf = byPath.get(n.path);\n\t\tconst at = { key: n.key, path: n.path, ordinal: n.row.event_index };\n\t\tif (!leaf)\n\t\t\tfailures.push({\n\t\t\t\tstep: \"rows\",\n\t\t\t\tcode: \"key-not-written\",\n\t\t\t\tmessage: `${n.row.event_type} row ${n.row.event_index} names a key the block did not write`,\n\t\t\t\t...at,\n\t\t\t});\n\t\telse if (\n\t\t\tlast.get(n.path) === i &&\n\t\t\tpadded(leaf.valueHash) !== hex(marfValue(n.value))\n\t\t)\n\t\t\tfailures.push({\n\t\t\t\tstep: \"rows\",\n\t\t\t\tcode: \"value-mismatch\",\n\t\t\t\tmessage: `${n.row.event_type} row ${n.row.event_index} value differs from the block's leaf`,\n\t\t\t\t...at,\n\t\t\t});\n\t});\n\treturn named.length;\n}\n\n/**\n * Verifies a block's state against an authenticated header.\n *\n * The witness must recompute `stateRoot`, then every leaf is classified. With\n * state writes, any leaf that is not a named write, a carried parent value or\n * MARF bookkeeping is a hidden write. Without them the diff is still proven,\n * since every leaf is in the block: carried leaves are told apart only through\n * `parentLeaves`, and the remaining writes come back unnamed.\n */\nexport async function verifyBlockState(\n\tinput: BlockStateInput,\n): Promise<BlockStateResult> {\n\tconst out: BlockStateResult = { rowsChecked: 0, notes: [], failures: [] };\n\tlet witness: ReturnType<typeof parseWitness>;\n\ttry {\n\t\twitness = parseWitness(input.witness);\n\t} catch (err) {\n\t\tout.failures.push({\n\t\t\tstep: \"witness\",\n\t\t\tcode: \"malformed\",\n\t\t\tmessage: (err as Error).message,\n\t\t});\n\t\treturn out;\n\t}\n\tif (!bytesEqual(witness.root, input.stateRoot)) {\n\t\tout.failures.push({\n\t\t\tstep: \"witness\",\n\t\t\tcode: \"root-mismatch\",\n\t\t\tmessage: `witness root ${hex(witness.root)} != header state_index_root ${hex(input.stateRoot)}`,\n\t\t});\n\t\treturn out;\n\t}\n\tconst { leaves } = witness;\n\tconst internal = internalEntries(input.height, input.parentBlockId, leaves);\n\tconst named = input.writes !== null;\n\tconst last = lastWrites(input.writes ?? [], out.failures);\n\tconst writes = [...last].map(([k, w]): [string, string] => [k, w.value]);\n\t// First pass with no parent values finds the leaves that need one.\n\tconst first = classifyBlockDiff({\n\t\tleaves,\n\t\twrites,\n\t\tinternal,\n\t\tparentValue: () => undefined,\n\t});\n\tconst inParent = new Map(\n\t\t(input.parentLeaves ?? []).map((l) => [hex(l.path), hex(l.valueHash)]),\n\t);\n\tconst carried = new Map<string, string>();\n\tfor (const leaf of first.hidden) {\n\t\tconst pathHex = hex(leaf.path);\n\t\tif (\n\t\t\tinParent.get(pathHex) === hex(leaf.valueHash) ||\n\t\t\t(named && (await input.parentHolds?.(leaf)))\n\t\t)\n\t\t\tcarried.set(pathHex, padded(leaf.valueHash));\n\t}\n\tconst d = classifyBlockDiff({\n\t\tleaves,\n\t\twrites,\n\t\tinternal,\n\t\tparentValue: (p) => carried.get(p),\n\t});\n\tout.diff = {\n\t\tnamed,\n\t\twrites: named\n\t\t\t? d.writes.map((l) => ({\n\t\t\t\t\t...leafHex(l),\n\t\t\t\t\tkey: l.key,\n\t\t\t\t\ttxIndex: last.get(l.key)?.txIndex ?? null,\n\t\t\t\t\tvalue: last.get(l.key)?.value,\n\t\t\t\t\tnamed: true,\n\t\t\t\t}))\n\t\t\t: // Without names every unexplained leaf is a write we cannot label.\n\t\t\t\td.hidden.map((l) => ({ ...leafHex(l), named: false })),\n\t\tcarried: d.carried.map(leafHex),\n\t\tinternal: d.internal.map((l) => ({ ...leafHex(l), key: l.key })),\n\t};\n\tif (!named)\n\t\tout.notes.push(\n\t\t\t`source has no state_writes for block ${input.height}: ${d.hidden.length} written leaves are proven in the block but unnamed`,\n\t\t);\n\telse {\n\t\tfor (const l of d.hidden)\n\t\t\tout.failures.push({\n\t\t\t\tstep: \"names\",\n\t\t\t\tcode: \"hidden-write\",\n\t\t\t\tmessage: `leaf ${hex(l.path)} is not a named write, a carried parent value or MARF bookkeeping`,\n\t\t\t\tpath: hex(l.path),\n\t\t\t});\n\t\tfor (const key of d.missing)\n\t\t\tout.failures.push({\n\t\t\t\tstep: \"names\",\n\t\t\t\tcode: \"missing-write\",\n\t\t\t\tmessage: `state write ${key} has no leaf holding its value`,\n\t\t\t\tkey,\n\t\t\t\tpath: hex(marfPath(key)),\n\t\t\t});\n\t}\n\tif (input.rows) out.rowsChecked = checkRows(input.rows, leaves, out.failures);\n\treturn out;\n}\n",
18
- "// A Nakamoto block's transactions against its header's tx_merkle_root\n// (stacks-common util/hash.rs MerkleTree, MerkleHashFunc = Sha512Trunc256Sum).\nimport { sha512_256 } from \"@noble/hashes/sha2.js\";\nimport { splitTransactions } from \"@secondlayer/stacks/transactions\";\nimport { type Bytes, bytesEqual, concat, hex } from \"./bytes.ts\";\nimport type { NakamotoHeader } from \"./header.ts\";\n\nexport interface BlockTransaction {\n\t/** sha512/256 of the transaction bytes, hex. */\n\ttxid: string;\n\t/** The consensus-serialized transaction. */\n\traw: Bytes;\n}\n\nconst LEAF_TAG = new Uint8Array([0x00]);\nconst NODE_TAG = new Uint8Array([0x01]);\n\n/**\n * Computes the `tx_merkle_root` over transaction ids.\n *\n * A leaf is H(0x00 ‖ txid) and a node is H(0x01 ‖ l ‖ r). An odd level\n * duplicates its last node, and a lone leaf is still paired with itself, so a\n * one-transaction block hashes H(0x01 ‖ leaf ‖ leaf).\n */\nexport function txMerkleRoot(txids: Bytes[]): Bytes {\n\tif (txids.length === 0) throw new Error(\"no transactions\");\n\tlet level = txids.map((t) => sha512_256(concat([LEAF_TAG, t])));\n\tdo {\n\t\tif (level.length % 2 === 1) level.push(level[level.length - 1] as Bytes);\n\t\tconst next: Bytes[] = [];\n\t\tfor (let i = 0; i < level.length; i += 2) {\n\t\t\tnext.push(\n\t\t\t\tsha512_256(\n\t\t\t\t\tconcat([NODE_TAG, level[i] as Bytes, level[i + 1] as Bytes]),\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t\tlevel = next;\n\t} while (level.length > 1);\n\treturn level[0] as Bytes;\n}\n\n/** Thrown for a malformed block body or a transaction root mismatch. */\nexport class TransactionsError extends Error {\n\tconstructor(\n\t\treadonly code: \"malformed\" | \"tx-root-mismatch\",\n\t\tmessage: string,\n\t) {\n\t\tsuper(message);\n\t}\n}\n\n/**\n * Hashes a block's transactions and checks them against the header.\n *\n * Each transaction is hashed to its txid and checked against the header's\n * `tx_merkle_root`. The body after `header.byteLength` is a u32 count, then the\n * transactions back to back. It returns null when the bytes are the header\n * alone, as a source that serves headers only does. It throws\n * {@link TransactionsError} on a malformed body, trailing bytes or a root\n * mismatch.\n */\nexport function blockTransactions(\n\traw: Bytes,\n\theader: NakamotoHeader,\n): BlockTransaction[] | null {\n\tconst body = raw.subarray(header.byteLength);\n\tif (body.length === 0) return null;\n\tif (body.length < 4)\n\t\tthrow new TransactionsError(\"malformed\", \"block body has no tx count\");\n\tconst count = new DataView(\n\t\tbody.buffer,\n\t\tbody.byteOffset,\n\t\tbody.byteLength,\n\t).getUint32(0);\n\tif (count === 0)\n\t\tthrow new TransactionsError(\"malformed\", \"block has no transactions\");\n\tlet txs: Bytes[];\n\ttry {\n\t\ttxs = splitTransactions(body.subarray(4), count);\n\t} catch (err) {\n\t\tthrow new TransactionsError(\n\t\t\t\"malformed\",\n\t\t\t`transactions do not parse: ${(err as Error).message}`,\n\t\t);\n\t}\n\tconst used = txs.reduce((n, t) => n + t.length, 4);\n\tif (used !== body.length)\n\t\tthrow new TransactionsError(\n\t\t\t\"malformed\",\n\t\t\t`${body.length - used} bytes after the block's ${count} transactions`,\n\t\t);\n\tconst ids = txs.map((t) => sha512_256(t));\n\tconst root = txMerkleRoot(ids);\n\tif (!bytesEqual(root, header.txMerkleRoot))\n\t\tthrow new TransactionsError(\n\t\t\t\"tx-root-mismatch\",\n\t\t\t`transactions hash to ${hex(root)}, header tx_merkle_root is ${hex(header.txMerkleRoot)}`,\n\t\t);\n\treturn txs.map((t, i) => ({ txid: hex(ids[i] as Bytes), raw: t }));\n}\n",
19
- "import { unhex } from \"./bytes.ts\";\nimport type { VerifyCheckpoint } from \"./checkpoint.ts\";\nimport { parseNakamotoHeader } from \"./header.ts\";\nimport type { BlockVerification, VerifyStep } from \"./verify-block.ts\";\n\nexport type LinkStatus = \"ok\" | \"failed\" | \"skipped\";\n\nexport interface LinkLine {\n\tstep: VerifyStep;\n\tlabel: string;\n\tstatus: LinkStatus;\n\t/** What the link proved, why it failed, or why it was not checked. */\n\tdetail: string;\n}\n\n/** The chain of links, in the order verifyBlock walks them. */\nexport const LINKS: readonly { step: VerifyStep; label: string }[] = [\n\t{ step: \"ancestry\", label: \"ancestry\" },\n\t{ step: \"block\", label: \"block\" },\n\t{ step: \"bitcoin\", label: \"bitcoin\" },\n\t{ step: \"burn\", label: \"burn\" },\n\t{ step: \"signer-set\", label: \"cycle\" },\n\t{ step: \"signatures\", label: \"signatures\" },\n\t{ step: \"txs\", label: \"txs\" },\n\t{ step: \"witness\", label: \"state root\" },\n\t{ step: \"names\", label: \"diff\" },\n\t{ step: \"rows\", label: \"rows\" },\n];\n\nconst n = (v: number | bigint) => v.toLocaleString(\"en-US\");\n\n/** What each link proved, for the human view. */\nfunction linkDetail(\n\tstep: VerifyStep,\n\tr: BlockVerification,\n\tcp: VerifyCheckpoint,\n): string {\n\tswitch (step) {\n\t\tcase \"ancestry\": {\n\t\t\tconst a = r.ancestry;\n\t\t\tif (!a) return \"\";\n\t\t\tconst checkpoint = parseNakamotoHeader(unhex(cp.stacks.header));\n\t\t\tconst start =\n\t\t\t\ta.fromHeight === Number(checkpoint.chainLength)\n\t\t\t\t\t? `the checkpoint ${n(a.fromHeight)}`\n\t\t\t\t\t: `block ${n(a.fromHeight)}`;\n\t\t\treturn a.via === \"marf\"\n\t\t\t\t? `${n(r.height ?? 0)} proven in the state of ${start} (one MARF proof)`\n\t\t\t\t: `${n(r.height ?? 0)} reached from ${start} by parent links`;\n\t\t}\n\t\tcase \"block\":\n\t\t\treturn `${n(r.height ?? 0)} ${r.blockId}`;\n\t\tcase \"bitcoin\":\n\t\t\treturn `headers ${n(cp.bitcoin.height)}..${n(r.burnHeight ?? 0)}, proof-of-work and retargets checked`;\n\t\tcase \"burn\":\n\t\t\treturn `height ${n(r.burnHeight ?? 0)} ${r.bitcoinBlockHash}`;\n\t\tcase \"signer-set\":\n\t\t\treturn r.cycle === cp.stacks.cycle\n\t\t\t\t? `${r.cycle}, the checkpoint's own signer set`\n\t\t\t\t: `${r.cycle}, signer set proven forward from checkpoint cycle ${cp.stacks.cycle}`;\n\t\tcase \"signatures\":\n\t\t\treturn `${n(r.signerWeight ?? 0n)} / ${n(r.totalWeight ?? 0n)} weight signed, threshold ${n(r.threshold ?? 0n)}`;\n\t\tcase \"txs\":\n\t\t\treturn `${n(r.transactions?.length ?? 0)} transactions match the tx merkle root`;\n\t\tcase \"witness\":\n\t\t\treturn `${r.stateRoot} matches the witness`;\n\t\tcase \"names\": {\n\t\t\tconst d = r.diff;\n\t\t\tif (!d) return \"\";\n\t\t\tconst named = d.writes.filter((w) => w.named).length;\n\t\t\tconst written = named\n\t\t\t\t? `${d.writes.length} written (${named} named, ${d.writes.length - named} unnamed)`\n\t\t\t\t: `${d.writes.length} written (unnamed)`;\n\t\t\treturn `${written}, ${d.carried.length} carried, ${d.internal.length} internal`;\n\t\t}\n\t\tcase \"rows\":\n\t\t\treturn `${n(r.rowsChecked ?? 0)} vm_events rows match the diff`;\n\t}\n}\n\n/**\n * Links a block below the checkpoint skips: its id is pinned by hash from a\n * trusted descendant, so no signer set or signatures; the burn block is bound\n * only when the synced Bitcoin chain reaches it.\n */\nfunction notNeeded(step: VerifyStep, r: BlockVerification): boolean {\n\tif (!r.ancestry) return false;\n\tif (step === \"bitcoin\" || step === \"burn\") return r.burnHeight === undefined;\n\treturn step === \"signer-set\" || step === \"signatures\";\n}\n\n/**\n * Describes a verification as one line per link and a verdict.\n *\n * It is the human view, shared by the CLI and the browser checker. Ancestry\n * appears only below the checkpoint. `rows` says whether the caller asked for\n * the rows link.\n */\nexport function describeLinks(\n\tr: BlockVerification,\n\tcp: VerifyCheckpoint,\n\topts: { rows?: boolean } = {},\n): { lines: LinkLine[]; verdict: { ok: boolean; text: string } } {\n\tconst first = r.failures[0];\n\tconst broken = first\n\t\t? LINKS.findIndex((l) => l.step === first.step)\n\t\t: LINKS.length;\n\tconst lines: LinkLine[] = [];\n\tfor (const [i, link] of LINKS.entries()) {\n\t\tconst { step, label } = link;\n\t\tconst failure = r.failures.find((f) => f.step === step);\n\t\t// Ancestry is a link only below the checkpoint.\n\t\tif (step === \"ancestry\" && !failure && !r.ancestry) continue;\n\t\tconst skipped = (detail: string): LinkLine => ({\n\t\t\tstep,\n\t\t\tlabel,\n\t\t\tstatus: \"skipped\",\n\t\t\tdetail,\n\t\t});\n\t\tif (failure)\n\t\t\tlines.push({ step, label, status: \"failed\", detail: failure.message });\n\t\telse if (step === \"rows\" && !opts.rows)\n\t\t\tlines.push(skipped(\"not checked (pass --rows)\"));\n\t\telse if (i > broken)\n\t\t\tlines.push(skipped(\"not checked: an earlier link is broken\"));\n\t\telse if (notNeeded(step, r))\n\t\t\tlines.push(\n\t\t\t\tskipped(\"not needed: the block is hash-chained to the checkpoint\"),\n\t\t\t);\n\t\telse if (step === \"rows\" && r.rowsChecked === undefined)\n\t\t\tlines.push(skipped(\"not checked: the source serves no indexed rows\"));\n\t\telse if (step === \"txs\" && r.transactions === undefined)\n\t\t\tlines.push(\n\t\t\t\tskipped(\n\t\t\t\t\t\"not checked: no transaction bytes (epoch 2.x, or the source served the header only)\",\n\t\t\t\t),\n\t\t\t);\n\t\telse\n\t\t\tlines.push({\n\t\t\t\tstep,\n\t\t\t\tlabel,\n\t\t\t\tstatus: \"ok\",\n\t\t\t\tdetail: linkDetail(step, r, cp),\n\t\t\t});\n\t}\n\n\tif (!first) {\n\t\tconst from = n(parseNakamotoHeader(unhex(cp.stacks.header)).chainLength);\n\t\treturn {\n\t\t\tlines,\n\t\t\tverdict: {\n\t\t\t\tok: true,\n\t\t\t\ttext: `Block ${n(r.height ?? 0)} is proven. Trusted: only the checkpoint (Stacks ${from}, Bitcoin ${n(cp.bitcoin.height)}).`,\n\t\t\t},\n\t\t};\n\t}\n\tconst label = LINKS[broken]?.label ?? first.step;\n\treturn {\n\t\tlines,\n\t\tverdict: {\n\t\t\tok: false,\n\t\t\ttext:\n\t\t\t\tfirst.code === \"unavailable\"\n\t\t\t\t\t? `Could not check the ${label} link: the source could not serve it.`\n\t\t\t\t\t: `Not proven: the ${label} link is broken.`,\n\t\t},\n\t};\n}\n",
20
- "// verifyBlock: the end-to-end trustless check for one Stacks block.\n//\n// At or above the checkpoint, forward:\n// checkpoint ─▶ bitcoin headers (PoW) ─▶ burn height ─▶ cycle ─▶ signer set[cycle] (MARF-proven)\n// ─▶ header N (signatures ≥ 70%) ─▶ txs N (tx merkle root) ─▶ witness N (root)\n// ─▶ named diff ─▶ indexed rows\n//\n// Below it, backward: a trusted descendant's id commits to every ancestor by\n// hash, so no signatures are needed:\n// checkpoint ─▶ id N (parent links, or one MARF proof of __MARF_BLOCK_HEIGHT_TO_HASH::N)\n// ─▶ header N (hashes to id N) ─▶ txs N ─▶ witness N (root) ─▶ named diff ─▶ indexed rows\n//\n// Every input comes from an untrusted ProofSource; only the checkpoint is trusted.\nimport { uintCV } from \"@secondlayer/stacks/clarity\";\nimport { HeaderChain, HeaderValidationError } from \"./bitcoin/chain.ts\";\nimport {\n\tMAINNET_PREPARE_LENGTH,\n\tcycleStart,\n\trewardCycle,\n\tverifyConsensusPreimage,\n} from \"./burn.ts\";\nimport { type Bytes, bytesEqual, hex, unhex } from \"./bytes.ts\";\nimport { MAINNET_CHECKPOINT, type VerifyCheckpoint } from \"./checkpoint.ts\";\nimport {\n\ttype Epoch2Header,\n\ttype NakamotoHeader,\n\ttype StacksHeader,\n\tblockId,\n\tisEpoch2Header,\n\tparseEpoch2Header,\n\tparseNakamotoHeader,\n\tsignerSignatureHash,\n} from \"./header.ts\";\nimport { mapEntryKey } from \"./keys.ts\";\nimport {\n\tMARF_VALUE_SIZE,\n\theightToHashKey,\n\tmarfPath,\n\tmarfProofAncestors,\n\tmarfProofValue,\n\tmarfValue,\n\tverifyMarfProof,\n} from \"./marf.ts\";\nimport {\n\tSIGNERS_CONTRACT,\n\ttype SignerSet,\n\tdecodeSignerSet,\n\tverifySignerSignatures,\n} from \"./signers.ts\";\nimport type { BurnPreimage, ProofSource, StateWrite } from \"./source.ts\";\nimport {\n\ttype ProvenDiff,\n\ttype StateFailureCode,\n\tverifyBlockState,\n} from \"./state.ts\";\nimport {\n\ttype BlockTransaction,\n\tTransactionsError,\n\tblockTransactions,\n} from \"./txs.ts\";\nimport { type WitnessLeaf, parseWitness } from \"./witness.ts\";\n\nexport type VerifyStep =\n\t| \"ancestry\"\n\t| \"block\"\n\t| \"bitcoin\"\n\t| \"burn\"\n\t| \"signer-set\"\n\t| \"signatures\"\n\t| \"txs\"\n\t| \"witness\"\n\t| \"names\"\n\t| \"rows\";\n\nexport type VerifyFailureCode =\n\t| StateFailureCode\n\t/** The source could not serve something the step needs. */\n\t| \"unavailable\"\n\t| \"id-mismatch\"\n\t/** The block's transactions do not hash to its header's tx_merkle_root. */\n\t| \"tx-root-mismatch\"\n\t| \"height-mismatch\"\n\t| \"invalid-header\"\n\t| \"preimage-mismatch\"\n\t| \"burn-not-in-chain\"\n\t| \"before-checkpoint\"\n\t/** The block is not the checkpoint chain's block at its height. */\n\t| \"not-ancestor\"\n\t| \"ancestry-proof-invalid\"\n\t| \"anchor-not-found\"\n\t| \"anchor-outside-window\"\n\t| \"anchor-unsigned\"\n\t| \"set-proof-invalid\"\n\t| \"below-threshold\"\n\t| \"unknown-signer\"\n\t| \"duplicate-signer\"\n\t| \"bad-signature\";\n\nexport interface VerifyFailure {\n\tstep: VerifyStep;\n\tcode: VerifyFailureCode;\n\tmessage: string;\n\t/** Reward cycle being proven (signer-set step). */\n\tcycle?: number;\n\t/** Block the failure is about, when not the target. */\n\tblockId?: string;\n\tkey?: string;\n\tpath?: string;\n\tordinal?: number;\n}\n\n/** How a block below the checkpoint was tied to it. */\nexport interface Ancestry {\n\t/** Trusted descendant it was proven from: the checkpoint, or a block proven below it earlier. */\n\tfromHeight: number;\n\tfromBlockId: string;\n\t/**\n\t * `parents`: each header hashes to the parent id its child commits to.\n\t * `marf`: one MARF proof of `__MARF_BLOCK_HEIGHT_TO_HASH::<height>` against\n\t * the descendant's state root.\n\t */\n\tvia: \"parents\" | \"marf\";\n}\n\nexport interface BlockVerification {\n\t/**\n\t * Every step passed. At or above the checkpoint: header, burn binding,\n\t * signatures, state root, names and rows. Below it: ancestry, header,\n\t * state root, names and rows (and the burn binding when Bitcoin reaches it).\n\t */\n\tok: boolean;\n\theight?: number;\n\tblockId?: string;\n\t/** Nakamoto block hash (the header's signer sighash), hex. Absent for epoch 2.x. */\n\tblockHash?: string;\n\t/** The header's consensus hash, hex. */\n\tconsensusHash?: string;\n\t/** Nakamoto header timestamp, Unix seconds. Absent for epoch 2.x. */\n\ttimestamp?: number;\n\t/** The header's state_index_root, hex: what the witness must hash to. */\n\tstateRoot?: string;\n\t/** Set for blocks below the checkpoint, which need no signatures. */\n\tancestry?: Ancestry;\n\tcycle?: number;\n\tburnHeight?: number;\n\t/** Display-order hex. */\n\tbitcoinBlockHash?: string;\n\tsignerWeight?: bigint;\n\ttotalWeight?: bigint;\n\tthreshold?: bigint;\n\t/**\n\t * The block's transactions, checked against the header's tx_merkle_root.\n\t * Absent for epoch 2.x blocks and when the source served the header only.\n\t */\n\ttransactions?: BlockTransaction[];\n\tdiff?: ProvenDiff;\n\t/** Every state_writes row the names step checked, in ordinal order. */\n\twrites?: StateWrite[];\n\t/** vm_events rows proven against the diff. */\n\trowsChecked?: number;\n\tnotes: string[];\n\t/** Empty when ok. The first entry is the first broken link. */\n\tfailures: VerifyFailure[];\n}\n\nexport interface VerifyOptions {\n\tsource: ProofSource;\n\t/** Defaults to MAINNET_CHECKPOINT. */\n\tcheckpoint?: VerifyCheckpoint;\n\t/**\n\t * Also prove the block's indexed vm_events rows against its diff: reads\n\t * the source's `getVmEvents`, which bill as Index rows on the Secondlayer\n\t * API. Off by default. Naming the diff's writes (`getStateWrites`, free on\n\t * `/v1/proofs`) is always on when the source has them.\n\t */\n\trows?: boolean;\n\t/**\n\t * Called once per link as it passes, in the order the verifier proves them.\n\t * Failures arrive in the result, not here.\n\t */\n\tonStep?: (step: VerifyStep) => void;\n}\n\nclass Broken extends Error {\n\tconstructor(readonly failure: VerifyFailure) {\n\t\tsuper(failure.message);\n\t}\n}\n\nconst fail = (f: VerifyFailure): never => {\n\tthrow new Broken(f);\n};\n\n/** Run a source call; a throw becomes an `unavailable` failure of `step`. */\nasync function fetchFor<T>(\n\tstep: VerifyStep,\n\twhat: string,\n\tcall: () => Promise<T>,\n\textra: Partial<VerifyFailure> = {},\n): Promise<T> {\n\ttry {\n\t\treturn await call();\n\t} catch (err) {\n\t\tif (err instanceof Broken) throw err;\n\t\treturn fail({\n\t\t\tstep,\n\t\t\tcode: \"unavailable\",\n\t\t\tmessage: `${what}: ${(err as Error).message}`,\n\t\t\t...extra,\n\t\t});\n\t}\n}\n\nconst BITCOIN_BATCH = 2016;\n/**\n * Below the checkpoint, ancestors this close to a trusted block are reached by\n * parent links (one block fetch each); farther ones by one MARF proof, which\n * costs the proof plus a header per ancestor trie it crosses.\n */\nconst MAX_WALK = 16;\n\n/** A block position for the anchor search; `burn` is a source hint. */\nexport interface SearchPoint {\n\theight: number;\n\tburn?: number;\n}\n\n/**\n * Find a block whose burn height lies in `[window[0], window[1])`, between\n * `lo` and `hi` (exclusive). Interpolates on burn height, falling back to\n * bisection whenever a probe fails to halve the bracket. Burn heights here\n * are unproven hints: the caller authenticates whatever this returns.\n */\nexport async function findAnchor<T extends SearchPoint & { burn: number }>(\n\tlow: SearchPoint,\n\thigh: SearchPoint,\n\twindow: readonly [number, number],\n\tprobe: (height: number) => Promise<T>,\n\tmaxProbes = 32,\n): Promise<T | null> {\n\tlet [lo, hi] = [low, high];\n\tconst target = (window[0] + window[1]) / 2;\n\tlet bisect = false;\n\tfor (let i = 0; i < maxProbes; i++) {\n\t\tconst span = hi.height - lo.height;\n\t\tif (span <= 1) return null;\n\t\tlet h = Math.floor((lo.height + hi.height) / 2);\n\t\tif (\n\t\t\t!bisect &&\n\t\t\tlo.burn !== undefined &&\n\t\t\thi.burn !== undefined &&\n\t\t\thi.burn > lo.burn\n\t\t)\n\t\t\th =\n\t\t\t\tlo.height +\n\t\t\t\tMath.round(((target - lo.burn) * span) / (hi.burn - lo.burn));\n\t\th = Math.min(Math.max(h, lo.height + 1), hi.height - 1);\n\t\tconst p = await probe(h);\n\t\tif (p.height <= lo.height || p.height >= hi.height) return null;\n\t\tif (p.burn >= window[0] && p.burn < window[1]) return p;\n\t\tif (p.burn < window[0]) lo = p;\n\t\telse hi = p;\n\t\tbisect = hi.height - lo.height > span / 2;\n\t}\n\treturn null;\n}\n\ninterface Probe extends SearchPoint {\n\tburn: number;\n\theader: NakamotoHeader;\n\tid: string;\n}\n\n/**\n * Verifies blocks from one checkpoint against one source.\n *\n * It caches the Bitcoin header chain, proven signer sets and fetched headers\n * across calls.\n */\nexport class BlockVerifier {\n\tprivate readonly source: ProofSource;\n\tprivate readonly checkpoint: VerifyCheckpoint;\n\tprivate readonly rows: boolean;\n\tprivate readonly onStep?: (step: VerifyStep) => void;\n\tprivate readonly chain: HeaderChain;\n\t/** Proven signer sets by cycle. */\n\tprivate readonly sets = new Map<number, SignerSet>();\n\t/** Where each proven set was anchored: the lower bound for the next search. */\n\tprivate readonly anchors = new Map<number, SearchPoint>();\n\t/** Headers fetched by id, each checked to hash to it. */\n\tprivate readonly headers = new Map<string, StacksHeader>();\n\t/** Blocks proven on the checkpoint's chain below it, by height. */\n\tprivate readonly below = new Map<\n\t\tnumber,\n\t\t{ id: string; ancestry: Ancestry }\n\t>();\n\tprivate readonly burns = new Map<\n\t\tstring,\n\t\t{ burnHeight: number; hash: string }\n\t>();\n\t/** Unverified source answers by consensus hash. */\n\tprivate readonly preimages = new Map<string, BurnPreimage>();\n\t/** Raw bytes of the last few blocks fetched, so the txs step reuses the\n\t * block an ancestry walk just read. Bounded: blocks can be megabytes. */\n\tprivate readonly raws = new Map<string, Bytes>();\n\tprivate readonly start: { header: NakamotoHeader; id: string };\n\n\tconstructor(opts: VerifyOptions) {\n\t\tthis.source = opts.source;\n\t\tthis.checkpoint = opts.checkpoint ?? MAINNET_CHECKPOINT;\n\t\tthis.rows = opts.rows ?? false;\n\t\tthis.onStep = opts.onStep;\n\t\tconst { stacks } = this.checkpoint;\n\t\tconst header = parseNakamotoHeader(unhex(stacks.header));\n\t\tthis.start = { header, id: hex(blockId(header)) };\n\t\tthis.headers.set(this.start.id, header);\n\t\tthis.sets.set(stacks.cycle, decodeSignerSet(stacks.signerSet));\n\t\tthis.chain = HeaderChain.fromCheckpoint(this.checkpoint.bitcoin);\n\t}\n\n\t/** Verify one block by id (hex) or height. Never throws for bad source data. */\n\tasync verify(ref: string | number): Promise<BlockVerification> {\n\t\tconst out: BlockVerification = { ok: false, notes: [], failures: [] };\n\t\ttry {\n\t\t\tawait this.run(ref, out);\n\t\t} catch (err) {\n\t\t\tif (!(err instanceof Broken)) throw err;\n\t\t\tout.failures.unshift(err.failure);\n\t\t}\n\t\tout.ok = out.failures.length === 0;\n\t\treturn out;\n\t}\n\n\t/** Report a passed link. A throwing callback must not break verification. */\n\tprivate passed(step: VerifyStep): void {\n\t\ttry {\n\t\t\tthis.onStep?.(step);\n\t\t} catch {}\n\t}\n\n\tprivate async run(\n\t\tref: string | number,\n\t\tout: BlockVerification,\n\t): Promise<void> {\n\t\tconst start = Number(this.start.header.chainLength);\n\t\tif (typeof ref === \"number\" && ref < start)\n\t\t\treturn this.runBelow(ref, undefined, out);\n\t\tlet header: StacksHeader;\n\t\tif (typeof ref === \"string\") {\n\t\t\tconst id = ref.replace(/^0x/, \"\").toLowerCase();\n\t\t\theader = await this.header(id, \"block\");\n\t\t\tconst height = Number(header.chainLength);\n\t\t\tif (height < start) return this.runBelow(height, id, out);\n\t\t\tif (isEpoch2Header(header))\n\t\t\t\tfail({\n\t\t\t\t\tstep: \"block\",\n\t\t\t\t\tcode: \"invalid-header\",\n\t\t\t\t\tmessage: `epoch 2.x block ${id} claims height ${height}, at or above the checkpoint`,\n\t\t\t\t});\n\t\t} else {\n\t\t\tconst raw = await fetchFor(\"block\", `block ${ref}`, () =>\n\t\t\t\tthis.source.getBlock(ref),\n\t\t\t);\n\t\t\theader = parseHeader(raw, \"block\");\n\t\t\tthis.rememberRaw(hex(blockId(header)), raw);\n\t\t}\n\t\tconst id = hex(blockId(header));\n\t\tconst height = Number(header.chainLength);\n\t\tif (typeof ref === \"number\" && height !== ref)\n\t\t\tfail({\n\t\t\t\tstep: \"block\",\n\t\t\t\tcode: \"height-mismatch\",\n\t\t\t\tmessage: `source returned height ${height} for ${ref}`,\n\t\t\t});\n\t\tawait this.runForward(header as NakamotoHeader, id, out);\n\t}\n\n\t/** At or above the checkpoint: Bitcoin, burn binding, signer set, signatures, state. */\n\tprivate async runForward(\n\t\theader: NakamotoHeader,\n\t\tid: string,\n\t\tout: BlockVerification,\n\t): Promise<void> {\n\t\tconst height = Number(header.chainLength);\n\t\tout.height = height;\n\t\tout.blockId = id;\n\t\tdescribeHeader(header, out);\n\t\tthis.passed(\"block\");\n\n\t\tconst burn = await this.bindBurn(header, \"burn\");\n\t\tconst cycle = rewardCycle(burn.burnHeight);\n\t\tout.burnHeight = burn.burnHeight;\n\t\tout.bitcoinBlockHash = burn.hash;\n\t\tout.cycle = cycle;\n\t\tthis.passed(\"bitcoin\");\n\t\tthis.passed(\"burn\");\n\n\t\tconst set = await this.signerSet(cycle, {\n\t\t\theight,\n\t\t\tburn: burn.burnHeight,\n\t\t});\n\t\tthis.passed(\"signer-set\");\n\t\tconst sig = verifySignerSignatures(header, set);\n\t\tout.signerWeight = sig.signedWeight;\n\t\tout.totalWeight = sig.totalWeight;\n\t\tout.threshold = sig.threshold;\n\t\tif (!sig.valid) fail(signatureFailure(sig, \"signatures\", cycle));\n\t\tthis.passed(\"signatures\");\n\t\tawait this.checkTransactions(header, id, out);\n\t\tawait this.verifyState(header, id, out);\n\t}\n\n\t/**\n\t * Below the checkpoint: prove the checkpoint chain's id at `height` (and\n\t * that it is `claimed`, when the caller asked by id), then the header that\n\t * hashes to it, then its state. Signatures add nothing to a header pinned\n\t * by hash from a trusted descendant.\n\t */\n\tprivate async runBelow(\n\t\theight: number,\n\t\tclaimed: string | undefined,\n\t\tout: BlockVerification,\n\t): Promise<void> {\n\t\tout.height = height;\n\t\tconst { id, ancestry } = await this.ancestor(height);\n\t\tout.ancestry = ancestry;\n\t\tif (claimed !== undefined && claimed !== id)\n\t\t\tfail({\n\t\t\t\tstep: \"ancestry\",\n\t\t\t\tcode: \"not-ancestor\",\n\t\t\t\tmessage: `block ${claimed} is not on the checkpoint's chain: its block at height ${height} is ${id}`,\n\t\t\t\tblockId: claimed,\n\t\t\t});\n\t\tthis.passed(\"ancestry\");\n\t\tconst header = await this.header(id, \"block\");\n\t\tif (Number(header.chainLength) !== height)\n\t\t\tfail({\n\t\t\t\tstep: \"block\",\n\t\t\t\tcode: \"height-mismatch\",\n\t\t\t\tmessage: `block ${id} claims height ${header.chainLength}, proven at ${height}`,\n\t\t\t});\n\t\tout.blockId = id;\n\t\tdescribeHeader(header, out);\n\t\tthis.passed(\"block\");\n\t\tawait this.bindBurnBelow(header, out);\n\t\tawait this.checkTransactions(header, id, out);\n\t\tawait this.verifyState(header, id, out);\n\t}\n\n\tprivate rememberRaw(id: string, raw: Bytes): void {\n\t\tthis.raws.delete(id);\n\t\tthis.raws.set(id, raw);\n\t\twhile (this.raws.size > 4) {\n\t\t\tconst oldest = this.raws.keys().next().value as string;\n\t\t\tthis.raws.delete(oldest);\n\t\t}\n\t}\n\n\t/**\n\t * The block's transactions against the authenticated header's\n\t * tx_merkle_root: binds every txid, sender, type and call target to the\n\t * signed (or hash-linked) header.\n\t */\n\tprivate async checkTransactions(\n\t\theader: StacksHeader,\n\t\tid: string,\n\t\tout: BlockVerification,\n\t): Promise<void> {\n\t\tif (isEpoch2Header(header)) {\n\t\t\tout.notes.push(\"epoch 2.x: transactions not checked\");\n\t\t\treturn;\n\t\t}\n\t\tconst raw =\n\t\t\tthis.raws.get(id) ??\n\t\t\t(await fetchFor(\"txs\", `block ${id}`, () => this.source.getBlock(id)));\n\t\tlet txs: BlockTransaction[] | null;\n\t\ttry {\n\t\t\ttxs = blockTransactions(raw, header);\n\t\t} catch (err) {\n\t\t\tif (!(err instanceof TransactionsError)) throw err;\n\t\t\treturn fail({ step: \"txs\", code: err.code, message: err.message });\n\t\t}\n\t\tif (txs === null) {\n\t\t\tout.notes.push(\n\t\t\t\t`transactions not checked: the source served block ${id}'s header only`,\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tout.transactions = txs;\n\t\tthis.passed(\"txs\");\n\t}\n\n\t/**\n\t * The checkpoint chain's block id at `height`, from the nearest trusted\n\t * block above it: parent links when within MAX_WALK, else one MARF proof.\n\t */\n\tprivate async ancestor(\n\t\theight: number,\n\t): Promise<{ id: string; ancestry: Ancestry }> {\n\t\tconst known = this.below.get(height);\n\t\tif (known) return known;\n\t\tconst from = this.nearestAbove(height);\n\t\tif (from.height - height <= MAX_WALK) {\n\t\t\tconst walked = await this.walk(from, height);\n\t\t\tif (walked) return walked;\n\t\t}\n\t\treturn this.jump(this.nearestAbove(height), height);\n\t}\n\n\t/** The lowest trusted block above `height`: the checkpoint or one proven below it. */\n\tprivate nearestAbove(height: number): { height: number; id: string } {\n\t\tlet best = {\n\t\t\theight: Number(this.start.header.chainLength),\n\t\t\tid: this.start.id,\n\t\t};\n\t\tfor (const [h, { id }] of this.below)\n\t\t\tif (h > height && h < best.height) best = { height: h, id };\n\t\treturn best;\n\t}\n\n\t/**\n\t * Follow parent ids down from `from`: each parent header must hash to the\n\t * id its child committed to. Null when a 2.x header stops the walk: it\n\t * commits to its parent's block hash, not the parent's id.\n\t */\n\tprivate async walk(\n\t\tfrom: { height: number; id: string },\n\t\theight: number,\n\t): Promise<{ id: string; ancestry: Ancestry } | null> {\n\t\tconst ancestry: Ancestry = {\n\t\t\tfromHeight: from.height,\n\t\t\tfromBlockId: from.id,\n\t\t\tvia: \"parents\",\n\t\t};\n\t\tlet child = await this.header(from.id, \"ancestry\");\n\t\tfor (let h = from.height - 1; h >= height; h--) {\n\t\t\tif (isEpoch2Header(child)) return null;\n\t\t\tconst id = hex(child.parentBlockId);\n\t\t\tconst parent = await this.header(id, \"ancestry\", { blockId: id });\n\t\t\tif (Number(parent.chainLength) !== h)\n\t\t\t\tfail({\n\t\t\t\t\tstep: \"ancestry\",\n\t\t\t\t\tcode: \"height-mismatch\",\n\t\t\t\t\tmessage: `parent ${id} claims height ${parent.chainLength}, expected ${h}`,\n\t\t\t\t\tblockId: id,\n\t\t\t\t});\n\t\t\tthis.below.set(h, { id, ancestry });\n\t\t\tchild = parent;\n\t\t}\n\t\treturn this.below.get(height) ?? null;\n\t}\n\n\t/**\n\t * Read the id at `height` from `from`'s state: block `height + 1` wrote it\n\t * to `__MARF_BLOCK_HEIGHT_TO_HASH::<height>`, and the proof must recompute\n\t * `from`'s state root through the header of every trie it crosses.\n\t */\n\tprivate async jump(\n\t\tfrom: { height: number; id: string },\n\t\theight: number,\n\t): Promise<{ id: string; ancestry: Ancestry }> {\n\t\tconst at = { blockId: from.id };\n\t\tconst tip = await this.header(from.id, \"ancestry\", at);\n\t\tconst key = heightToHashKey(height);\n\t\tconst path = marfPath(key);\n\t\tconst answer = await fetchFor(\n\t\t\t\"ancestry\",\n\t\t\t`${key} at ${from.id}`,\n\t\t\t() => this.source.getMarfProof(hex(path), from.id),\n\t\t\tat,\n\t\t);\n\t\tif (!answer)\n\t\t\treturn fail({\n\t\t\t\tstep: \"ancestry\",\n\t\t\t\tcode: \"unavailable\",\n\t\t\t\tmessage: `source has no MARF proof of ${key} at block ${from.height}, ${from.height - height} blocks up; parent links reach ${MAX_WALK}`,\n\t\t\t\t...at,\n\t\t\t});\n\t\t// A block id fills the first 32 bytes of the MARFValue; the tail is zero.\n\t\tconst value = marfProofValue(answer.proof) ?? new Uint8Array();\n\t\tconst proven =\n\t\t\tvalue.length === MARF_VALUE_SIZE &&\n\t\t\tvalue.subarray(32).every((b) => b === 0) &&\n\t\t\t(await this.proveAt(tip, path, value, answer.proof, \"ancestry\", at));\n\t\tif (!proven)\n\t\t\treturn fail({\n\t\t\t\tstep: \"ancestry\",\n\t\t\t\tcode: \"ancestry-proof-invalid\",\n\t\t\t\tmessage: `${key} is not proven in block ${from.height}'s state`,\n\t\t\t\t...at,\n\t\t\t});\n\t\tconst ancestry: Ancestry = {\n\t\t\tfromHeight: from.height,\n\t\t\tfromBlockId: from.id,\n\t\t\tvia: \"marf\",\n\t\t};\n\t\tconst found = { id: hex(value.subarray(0, 32)), ancestry };\n\t\tthis.below.set(height, found);\n\t\treturn found;\n\t}\n\n\t/**\n\t * Below the checkpoint the hash chain already pins the block; still bind\n\t * its burn block when the Bitcoin checkpoint reaches it. The burn height\n\t * here is the source's hint, so a low one only skips this extra check.\n\t */\n\tprivate async bindBurnBelow(\n\t\theader: StacksHeader,\n\t\tout: BlockVerification,\n\t): Promise<void> {\n\t\tlet hint: number;\n\t\ttry {\n\t\t\thint = await this.burnHint(header);\n\t\t} catch (err) {\n\t\t\tout.notes.push(`burn block not checked: ${(err as Error).message}`);\n\t\t\treturn;\n\t\t}\n\t\tif (hint < this.chain.checkpointHeight) {\n\t\t\tout.notes.push(\n\t\t\t\t`burn block not checked: its height ${hint} is below the Bitcoin checkpoint ${this.chain.checkpointHeight}`,\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tconst burn = await this.bindBurn(header, \"burn\");\n\t\tout.burnHeight = burn.burnHeight;\n\t\tout.bitcoinBlockHash = burn.hash;\n\t\tthis.passed(\"bitcoin\");\n\t\tthis.passed(\"burn\");\n\t}\n\n\t/** Witness against the authenticated header's root, then the named diff and rows. */\n\tprivate async verifyState(\n\t\theader: StacksHeader,\n\t\tid: string,\n\t\tout: BlockVerification,\n\t): Promise<void> {\n\t\tconst src = this.source;\n\t\tconst height = Number(header.chainLength);\n\t\tconst witness = await fetchFor(\"witness\", `witness ${id}`, () =>\n\t\t\tsrc.getWitness(id),\n\t\t);\n\t\tconst writes = await this.stateWrites(height, out.notes);\n\t\tif (writes) out.writes = writes;\n\t\tconst { getVmEvents }: Partial<ProofSource> = this.rows ? src : {};\n\t\tconst rows = getVmEvents\n\t\t\t? await fetchFor(\"rows\", `vm_events ${height}`, () =>\n\t\t\t\t\tgetVmEvents.call(src, height),\n\t\t\t\t)\n\t\t\t: undefined;\n\t\tconst parent = isEpoch2Header(header)\n\t\t\t? epoch2ParentId(witness, header)\n\t\t\t: header.parentBlockId;\n\t\tconst parentId = parent && hex(parent);\n\t\tconst state = await verifyBlockState({\n\t\t\theight,\n\t\t\t// Null only when the witness fails its root check, which fails the block.\n\t\t\tparentBlockId: parent ?? new Uint8Array(32),\n\t\t\tstateRoot: header.stateIndexRoot,\n\t\t\twitness,\n\t\t\twrites,\n\t\t\trows,\n\t\t\tparentLeaves: parentId\n\t\t\t\t? await this.parentLeaves(parentId, out.notes)\n\t\t\t\t: undefined,\n\t\t\tparentHolds: async (leaf) =>\n\t\t\t\tparentId ? this.parentHolds(parentId, leaf) : false,\n\t\t});\n\t\tout.diff = state.diff;\n\t\tif (rows) out.rowsChecked = state.rowsChecked;\n\t\tout.notes.push(...state.notes);\n\t\tout.failures.push(...state.failures);\n\t\t// Links pass in order up to the first one with a failure.\n\t\tconst broken = new Set(state.failures.map((f) => f.step));\n\t\tfor (const step of [\"witness\", \"names\", \"rows\"] as const) {\n\t\t\tif (broken.has(step) || (step === \"rows\" && !rows)) break;\n\t\t\tthis.passed(step);\n\t\t}\n\t}\n\n\t/**\n\t * The block's state writes, to name its diff. Optional evidence: a source\n\t * with none for the block (404, empty) or that fails leaves the diff\n\t * proven but unnamed, with a note, never a failure.\n\t */\n\tprivate async stateWrites(\n\t\theight: number,\n\t\tnotes: string[],\n\t): Promise<StateWrite[] | null> {\n\t\tconst { getStateWrites } = this.source;\n\t\tif (!getStateWrites) return null;\n\t\ttry {\n\t\t\tconst writes = await getStateWrites.call(this.source, height);\n\t\t\treturn writes?.length ? writes : null;\n\t\t} catch (err) {\n\t\t\tnotes.push(\n\t\t\t\t`state writes for block ${height} unavailable: ${(err as Error).message}`,\n\t\t\t);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/** Header by id, from the cache or the source; it must hash to `id`. */\n\tprivate async header(\n\t\tid: string,\n\t\tstep: VerifyStep,\n\t\textra: Partial<VerifyFailure> = {},\n\t): Promise<StacksHeader> {\n\t\tconst known = this.headers.get(id);\n\t\tif (known) return known;\n\t\tconst header = await this.fetchHeader(id, step, extra);\n\t\tif (hex(blockId(header)) !== id)\n\t\t\tfail({\n\t\t\t\tstep,\n\t\t\t\tcode: \"id-mismatch\",\n\t\t\t\tmessage: `source returned another block for ${id}`,\n\t\t\t\tblockId: id,\n\t\t\t\t...extra,\n\t\t\t});\n\t\tthis.headers.set(id, header);\n\t\treturn header;\n\t}\n\n\t/**\n\t * A Nakamoto block by id, or when the source has none (epoch 2.x blocks are\n\t * not served as Nakamoto blocks) its epoch 2.x header.\n\t */\n\tprivate async fetchHeader(\n\t\tid: string,\n\t\tstep: VerifyStep,\n\t\textra: Partial<VerifyFailure>,\n\t): Promise<StacksHeader> {\n\t\tconst src = this.source;\n\t\tlet raw: Bytes;\n\t\ttry {\n\t\t\traw = await src.getBlock(id);\n\t\t\tthis.rememberRaw(id, raw);\n\t\t} catch (err) {\n\t\t\tconst reason = `block ${id}: ${(err as Error).message}`;\n\t\t\tconst { getEpoch2Header } = src;\n\t\t\tif (!getEpoch2Header)\n\t\t\t\treturn fail({ step, code: \"unavailable\", message: reason, ...extra });\n\t\t\tconst e2 = await fetchFor(\n\t\t\t\tstep,\n\t\t\t\t`${reason}; epoch 2.x header`,\n\t\t\t\t() => getEpoch2Header.call(src, id),\n\t\t\t\textra,\n\t\t\t);\n\t\t\ttry {\n\t\t\t\treturn parseEpoch2Header(e2.header, e2.consensusHash);\n\t\t\t} catch (parseErr) {\n\t\t\t\treturn fail({\n\t\t\t\t\tstep,\n\t\t\t\t\tcode: \"invalid-header\",\n\t\t\t\t\tmessage: `epoch 2.x header ${id} does not parse: ${(parseErr as Error).message}`,\n\t\t\t\t\t...extra,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\treturn parseHeader(raw, step);\n\t}\n\n\t/**\n\t * Prove `value` at `path` in `tip`'s state, fetching the header of every\n\t * ancestor trie the proof crosses.\n\t */\n\tprivate async proveAt(\n\t\ttip: StacksHeader,\n\t\tpath: Bytes,\n\t\tvalue: Bytes,\n\t\tproof: Bytes,\n\t\tstep: VerifyStep,\n\t\textra: Partial<VerifyFailure> = {},\n\t): Promise<boolean> {\n\t\tconst headers = [tip];\n\t\tfor (const id of marfProofAncestors(proof))\n\t\t\theaders.push(await this.header(id, step, extra));\n\t\treturn verifyMarfProof({\n\t\t\tproof,\n\t\t\tpath,\n\t\t\tvalue,\n\t\t\troot: tip.stateIndexRoot,\n\t\t\theaders,\n\t\t});\n\t}\n\n\t/**\n\t * The parent's own trie leaves, from its witness checked against the\n\t * parent header. Optional evidence: when the source cannot serve it,\n\t * carried leaves fall back to per-leaf proofs (named) or stay unlabeled.\n\t */\n\tprivate async parentLeaves(\n\t\tparentId: string,\n\t\tnotes: string[],\n\t): Promise<WitnessLeaf[] | undefined> {\n\t\ttry {\n\t\t\tconst parent = await this.header(parentId, \"names\");\n\t\t\tconst w = parseWitness(await this.source.getWitness(parentId));\n\t\t\tif (bytesEqual(w.root, parent.stateIndexRoot)) return w.leaves;\n\t\t\tnotes.push(`parent witness ${parentId} root does not match its header`);\n\t\t} catch (err) {\n\t\t\tnotes.push(\n\t\t\t\t`parent witness ${parentId} unavailable: ${(err as Error).message}`,\n\t\t\t);\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * A carried leaf holds the parent's value. The parent header is\n\t * authenticated by hash: its id is committed in the authenticated child\n\t * (its header, or for 2.x its own trie).\n\t */\n\tprivate async parentHolds(\n\t\tparentId: string,\n\t\tleaf: WitnessLeaf,\n\t): Promise<boolean> {\n\t\tconst parent = await this.header(parentId, \"names\");\n\t\tconst pathHex = hex(leaf.path);\n\t\tconst answer = await fetchFor(\"names\", `MARF ${pathHex} at parent`, () =>\n\t\t\tthis.source.getMarfProof(pathHex, parentId),\n\t\t);\n\t\tif (!answer) return false;\n\t\tconst value = new Uint8Array(MARF_VALUE_SIZE);\n\t\tvalue.set(leaf.valueHash);\n\t\treturn this.proveAt(parent, leaf.path, value, answer.proof, \"names\");\n\t}\n\n\t/** Consensus hash -> PoW-verified burn block, via the sortition preimage. */\n\tprivate async bindBurn(\n\t\theader: StacksHeader,\n\t\tstep: VerifyStep,\n\t\textra: Partial<VerifyFailure> = {},\n\t): Promise<{ burnHeight: number; hash: string }> {\n\t\tconst ch = hex(header.consensusHash);\n\t\tconst known = this.burns.get(ch);\n\t\tif (known) return known;\n\t\tconst bp = await fetchFor(\n\t\t\tstep,\n\t\t\t`burn preimage ${ch}`,\n\t\t\t() => this.preimage(ch),\n\t\t\textra,\n\t\t);\n\t\tconst hash = verifyConsensusPreimage(header.consensusHash, bp.preimage);\n\t\tif (!hash)\n\t\t\treturn fail({\n\t\t\t\tstep,\n\t\t\t\tcode: \"preimage-mismatch\",\n\t\t\t\tmessage: `preimage does not hash to consensus hash ${ch}`,\n\t\t\t\t...extra,\n\t\t\t});\n\t\tif (bp.burnHeight < this.chain.checkpointHeight)\n\t\t\tfail({\n\t\t\t\tstep,\n\t\t\t\tcode: \"before-checkpoint\",\n\t\t\t\tmessage: `burn height ${bp.burnHeight} is below the Bitcoin checkpoint ${this.chain.checkpointHeight}`,\n\t\t\t\t...extra,\n\t\t\t});\n\t\tawait this.syncBitcoin(bp.burnHeight);\n\t\tconst burnHeight = this.chain.heightOf(hash);\n\t\tif (burnHeight === undefined)\n\t\t\treturn fail({\n\t\t\t\tstep,\n\t\t\t\tcode: \"burn-not-in-chain\",\n\t\t\t\tmessage: `burn block ${hash} is not in the verified Bitcoin chain (synced ${this.chain.checkpointHeight}..${this.chain.tip.height})`,\n\t\t\t\t...extra,\n\t\t\t});\n\t\tconst bound = { burnHeight, hash };\n\t\tthis.burns.set(ch, bound);\n\t\treturn bound;\n\t}\n\n\t/** Extend the Bitcoin chain to `height`, validating PoW, retarget and MTP. */\n\tprivate async syncBitcoin(height: number): Promise<void> {\n\t\twhile (this.chain.tip.height < height) {\n\t\t\tconst from = this.chain.tip.height + 1;\n\t\t\tconst count = Math.min(BITCOIN_BATCH, height - from + 1);\n\t\t\tconst headers = await fetchFor(\"bitcoin\", `bitcoin headers ${from}`, () =>\n\t\t\t\tthis.source.getBitcoinHeaders(from, count),\n\t\t\t);\n\t\t\tif (headers.length === 0)\n\t\t\t\tfail({\n\t\t\t\t\tstep: \"bitcoin\",\n\t\t\t\t\tcode: \"unavailable\",\n\t\t\t\t\tmessage: `source has no Bitcoin headers from ${from}`,\n\t\t\t\t});\n\t\t\ttry {\n\t\t\t\tthis.chain.append(headers);\n\t\t\t} catch (err) {\n\t\t\t\tif (!(err instanceof HeaderValidationError)) throw err;\n\t\t\t\tfail({ step: \"bitcoin\", code: \"invalid-header\", message: err.message });\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * The proven signer set for `cycle`. Walks forward from the checkpoint:\n\t * set c+1 is read from an anchor block in c+1's prepare phase, whose\n\t * header set c signed.\n\t */\n\tprivate async signerSet(\n\t\tcycle: number,\n\t\ttarget: SearchPoint,\n\t): Promise<SignerSet> {\n\t\tconst known = this.sets.get(cycle);\n\t\tif (known) return known;\n\t\tconst first = this.checkpoint.stacks.cycle;\n\t\tif (cycle < first)\n\t\t\tfail({\n\t\t\t\tstep: \"signer-set\",\n\t\t\t\tcode: \"before-checkpoint\",\n\t\t\t\tmessage: `cycle ${cycle} precedes the checkpoint's cycle ${first}`,\n\t\t\t\tcycle,\n\t\t\t});\n\t\tlet lo = await this.startPoint();\n\t\tfor (let c = first; c < cycle; c++) {\n\t\t\tconst next = this.sets.get(c + 1);\n\t\t\tif (next) {\n\t\t\t\tlo = this.anchors.get(c + 1) ?? lo;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst anchor = await this.locateAnchor(c + 1, lo, target);\n\t\t\tthis.sets.set(c + 1, await this.proveNextSet(c + 1, anchor));\n\t\t\tthis.anchors.set(c + 1, anchor);\n\t\t\tlo = anchor;\n\t\t}\n\t\treturn this.sets.get(cycle) as SignerSet;\n\t}\n\n\t/** The checkpoint block as a search bound; its burn height is a source hint. */\n\tprivate async startPoint(): Promise<SearchPoint> {\n\t\tconst { header } = this.start;\n\t\tconst height = Number(header.chainLength);\n\t\ttry {\n\t\t\treturn { height, burn: await this.burnHint(header) };\n\t\t} catch {\n\t\t\treturn { height };\n\t\t}\n\t}\n\n\tprivate async burnHint(header: StacksHeader): Promise<number> {\n\t\tconst ch = hex(header.consensusHash);\n\t\treturn (\n\t\t\tthis.burns.get(ch)?.burnHeight ?? (await this.preimage(ch)).burnHeight\n\t\t);\n\t}\n\n\tprivate async preimage(ch: string): Promise<BurnPreimage> {\n\t\tlet bp = this.preimages.get(ch);\n\t\tif (!bp) {\n\t\t\tbp = await this.source.getBurnPreimage(ch);\n\t\t\tthis.preimages.set(ch, bp);\n\t\t}\n\t\treturn bp;\n\t}\n\n\tprivate async locateAnchor(\n\t\tcycle: number,\n\t\tlo: SearchPoint,\n\t\thi: SearchPoint,\n\t): Promise<Probe> {\n\t\tconst start = cycleStart(cycle);\n\t\tconst window = [start - MAINNET_PREPARE_LENGTH, start] as const;\n\t\tconst probe = async (h: number): Promise<Probe> => {\n\t\t\tconst raw = await fetchFor(\n\t\t\t\t\"signer-set\",\n\t\t\t\t`block at height ${h}`,\n\t\t\t\t() => this.source.getBlock(h),\n\t\t\t\t{ cycle },\n\t\t\t);\n\t\t\tconst header = parseHeader(raw, \"signer-set\");\n\t\t\tconst id = hex(blockId(header));\n\t\t\tthis.headers.set(id, header);\n\t\t\tconst burn = await fetchFor(\n\t\t\t\t\"signer-set\",\n\t\t\t\t`burn hint for block ${id}`,\n\t\t\t\t() => this.burnHint(header),\n\t\t\t\t{ cycle, blockId: id },\n\t\t\t);\n\t\t\treturn { height: Number(header.chainLength), burn, header, id };\n\t\t};\n\t\tconst anchor = await findAnchor(lo, hi, window, probe);\n\t\tif (!anchor)\n\t\t\treturn fail({\n\t\t\t\tstep: \"signer-set\",\n\t\t\t\tcode: \"anchor-not-found\",\n\t\t\t\tmessage: `no block with a burn height in ${window[0]}..${window[1] - 1} (cycle ${cycle} prepare phase) between heights ${lo.height} and ${hi.height}`,\n\t\t\t\tcycle,\n\t\t\t});\n\t\treturn anchor;\n\t}\n\n\t/**\n\t * Set `cycle` from `anchor`: the anchor must be bound to a burn block in\n\t * `cycle`'s prepare phase, be signed by the set of the cycle that burn\n\t * height dictates (`cycle - 1`), and hold set `cycle` in its state (MARF\n\t * proof). Adjacent sets overlap enough that one block can clear both, so\n\t * the set is always chosen by proven burn height, never by which passes.\n\t */\n\tprivate async proveNextSet(cycle: number, anchor: Probe): Promise<SignerSet> {\n\t\tconst at = { cycle, blockId: anchor.id };\n\t\tconst { burnHeight } = await this.bindBurn(anchor.header, \"signer-set\", at);\n\t\tconst start = cycleStart(cycle);\n\t\tif (burnHeight < start - MAINNET_PREPARE_LENGTH || burnHeight >= start)\n\t\t\tfail({\n\t\t\t\tstep: \"signer-set\",\n\t\t\t\tcode: \"anchor-outside-window\",\n\t\t\t\tmessage: `anchor burn height ${burnHeight} is outside cycle ${cycle}'s prepare phase ${start - MAINNET_PREPARE_LENGTH}..${start - 1}`,\n\t\t\t\t...at,\n\t\t\t});\n\t\tconst signing = rewardCycle(burnHeight);\n\t\tconst sig = verifySignerSignatures(\n\t\t\tanchor.header,\n\t\t\tthis.sets.get(signing) as SignerSet,\n\t\t);\n\t\tif (!sig.valid)\n\t\t\tfail({\n\t\t\t\t...signatureFailure(sig, \"signer-set\", signing),\n\t\t\t\t...at,\n\t\t\t\tcode: \"anchor-unsigned\",\n\t\t\t});\n\n\t\tconst path = marfPath(\n\t\t\tmapEntryKey(SIGNERS_CONTRACT, \"cycle-signer-set\", uintCV(cycle)),\n\t\t);\n\t\tconst answer = await fetchFor(\n\t\t\t\"signer-set\",\n\t\t\t`signer set ${cycle} at ${anchor.id}`,\n\t\t\t() => this.source.getMarfProof(hex(path), anchor.id),\n\t\t\tat,\n\t\t);\n\t\tconst value = answer?.data.replace(/^0x/, \"\") ?? \"\";\n\t\tconst proven =\n\t\t\tanswer !== null &&\n\t\t\t(await this.proveAt(\n\t\t\t\tanchor.header,\n\t\t\t\tpath,\n\t\t\t\tmarfValue(value),\n\t\t\t\tanswer.proof,\n\t\t\t\t\"signer-set\",\n\t\t\t\tat,\n\t\t\t));\n\t\tif (!proven)\n\t\t\tfail({\n\t\t\t\tstep: \"signer-set\",\n\t\t\t\tcode: \"set-proof-invalid\",\n\t\t\t\tmessage: `signer set ${cycle} is not proven in anchor ${anchor.id}'s state`,\n\t\t\t\t...at,\n\t\t\t});\n\t\tlet set: SignerSet;\n\t\ttry {\n\t\t\tset = decodeSignerSet(value);\n\t\t} catch (err) {\n\t\t\treturn fail({\n\t\t\t\tstep: \"signer-set\",\n\t\t\t\tcode: \"set-proof-invalid\",\n\t\t\t\tmessage: `signer set ${cycle}: ${(err as Error).message}`,\n\t\t\t\t...at,\n\t\t\t});\n\t\t}\n\t\treturn set;\n\t}\n}\n\n/** The authenticated header's identity fields, for callers that rebuild the block. */\nfunction describeHeader(header: StacksHeader, out: BlockVerification): void {\n\tout.stateRoot = hex(header.stateIndexRoot);\n\tout.consensusHash = hex(header.consensusHash);\n\tif (!isEpoch2Header(header)) {\n\t\tout.blockHash = hex(signerSignatureHash(header));\n\t\tout.timestamp = Number(header.timestamp);\n\t}\n}\n\nfunction parseHeader(raw: Bytes, step: VerifyStep): NakamotoHeader {\n\ttry {\n\t\treturn parseNakamotoHeader(raw);\n\t} catch (err) {\n\t\treturn fail({\n\t\t\tstep,\n\t\t\tcode: \"invalid-header\",\n\t\t\tmessage: `block bytes do not parse: ${(err as Error).message}`,\n\t\t});\n\t}\n}\n\n/**\n * A 2.x header commits only to its parent's block hash; the parent's id is in\n * the block's own trie at `__MARF_BLOCK_HEIGHT_TO_HASH::<height - 1>`. Read\n * from a witness whose root matches the header, else null.\n */\nfunction epoch2ParentId(witness: Bytes, header: Epoch2Header): Bytes | null {\n\tconst height = Number(header.chainLength);\n\tif (height === 0) return null;\n\ttry {\n\t\tconst w = parseWitness(witness);\n\t\tif (!bytesEqual(w.root, header.stateIndexRoot)) return null;\n\t\tconst path = marfPath(heightToHashKey(height - 1));\n\t\treturn w.leaves.find((l) => bytesEqual(l.path, path))?.valueHash ?? null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction signatureFailure(\n\tsig: ReturnType<typeof verifySignerSignatures>,\n\tstep: VerifyStep,\n\tcycle: number,\n): VerifyFailure {\n\tconst weight = `${sig.signedWeight}/${sig.totalWeight} signed, threshold ${sig.threshold}`;\n\tif (sig.unknown.length)\n\t\treturn {\n\t\t\tstep,\n\t\t\tcode: \"unknown-signer\",\n\t\t\tmessage: `${sig.unknown.length} signer(s) not in cycle ${cycle}'s set (${weight})`,\n\t\t\tcycle,\n\t\t};\n\tif (sig.duplicates.length)\n\t\treturn {\n\t\t\tstep,\n\t\t\tcode: \"duplicate-signer\",\n\t\t\tmessage: `${sig.duplicates.length} duplicate signature(s) (${weight})`,\n\t\t\tcycle,\n\t\t};\n\tif (sig.invalid)\n\t\treturn {\n\t\t\tstep,\n\t\t\tcode: \"bad-signature\",\n\t\t\tmessage: `${sig.invalid} signature(s) do not recover (${weight})`,\n\t\t\tcycle,\n\t\t};\n\treturn {\n\t\tstep,\n\t\tcode: \"below-threshold\",\n\t\tmessage: `cycle ${cycle} signers: ${weight}`,\n\t\tcycle,\n\t};\n}\n\n/** One-shot: verify a block from a checkpoint (MAINNET_CHECKPOINT by default). */\nexport const verifyBlock = (\n\tref: string | number,\n\topts: VerifyOptions,\n): Promise<BlockVerification> => new BlockVerifier(opts).verify(ref);\n"
16
+ "// Proof data sources. Everything a source returns is untrusted: verifyBlock\n// checks every byte against the checkpoint, so a lying source can make a\n// check fail but never pass.\nimport { type Bytes, unhex } from \"./bytes.ts\";\n\n/** Sortition preimage behind a consensus hash. */\nexport interface BurnPreimage {\n\tpreimage: Bytes;\n\t/** The source's claimed burn height: a hint for how far to sync Bitcoin headers, never trusted. */\n\tburnHeight: number;\n}\n\n/** Node RPC `/v2/clarity/marf/<path>?proof=1` answer. */\nexport interface MarfProofResponse {\n\t/** Value string as Clarity stored it (hex for Clarity values), 0x prefix tolerated. */\n\tdata: string;\n\t/** Consensus-serialized TrieMerkleProof. */\n\tproof: Bytes;\n}\n\n/** One storage-layer MARF write (`state_writes` row), in block write order. */\nexport interface StateWrite {\n\t/** Null for block-level writes outside any transaction. */\n\ttx_index: number | null;\n\tordinal: number;\n\t/** Full MARF key, e.g. `vm::<contract>::0::<map>::<key hex>`. */\n\tkey: string;\n\t/** Hex of the stored value string's UTF-8 bytes. */\n\tvalue_hex: string;\n}\n\n/** A `vm_events` write row, as the Index API serves it. */\nexport interface VmEventRow {\n\tevent_type: \"var_set\" | \"map_set\" | \"map_insert\" | \"map_delete\";\n\t/** The row's ordinal within the block. */\n\tevent_index: number;\n\ttx_id?: string;\n\ttx_index?: number;\n\tcontract_id: string;\n\tvar_name?: string | null;\n\tmap?: string | null;\n\traw_key?: string | null;\n\traw_value?: string | null;\n}\n\n/** An epoch 2.x header and the consensus hash it commits to. */\nexport interface Epoch2HeaderResponse {\n\t/** Consensus-serialized StacksBlockHeader. */\n\theader: Bytes;\n\tconsensusHash: Bytes;\n}\n\nexport interface ProofSource {\n\t/** Raw Nakamoto block bytes (header first), by block id or height. */\n\tgetBlock(ref: string | number): Promise<Bytes>;\n\t/**\n\t * Epoch 2.x block header by index block hash: blocks below the checkpoint\n\t * from before Nakamoto. Without it only Nakamoto blocks verify.\n\t */\n\tgetEpoch2Header?(blockId: string): Promise<Epoch2HeaderResponse>;\n\t/**\n\t * MARF inclusion proof for a 32-byte path at `tipId`; null when the key is\n\t * absent. Blocks below the checkpoint also ask for\n\t * `__MARF_BLOCK_HEIGHT_TO_HASH::<height>`, whose value is no stored string:\n\t * only `proof` is read for it.\n\t */\n\tgetMarfProof(\n\t\tpathHex: string,\n\t\ttipId: string,\n\t): Promise<MarfProofResponse | null>;\n\t/** State witness (wire v3) for a block. */\n\tgetWitness(blockId: string): Promise<Bytes>;\n\tgetBurnPreimage(consensusHash: string): Promise<BurnPreimage>;\n\t/** Raw 80-byte Bitcoin headers (hex or bytes) from height `from`. */\n\tgetBitcoinHeaders(from: number, count: number): Promise<(string | Bytes)[]>;\n\t/**\n\t * Every MARF write of the block, in ordinal order; null (or empty) when\n\t * the source has none for it. Names the block's diff.\n\t */\n\tgetStateWrites?(height: number): Promise<StateWrite[] | null>;\n\t/** Indexed vm_events write rows of the block, checked against its proven diff. */\n\tgetVmEvents?(height: number): Promise<VmEventRow[]>;\n}\n\n/**\n * Thrown when a proof source request fails.\n *\n * It carries the request `url`, the HTTP `status` (null when there was none)\n * and the detail.\n */\nexport class SourceError extends Error {\n\toverride readonly name = \"SourceError\";\n\tconstructor(\n\t\treadonly url: string,\n\t\treadonly status: number | null,\n\t\tdetail: string,\n\t) {\n\t\tsuper(`${url}: ${detail}`);\n\t}\n}\n\ntype Fetch = (url: string, init?: RequestInit) => Promise<Response>;\n\ninterface HttpOptions {\n\theaders?: Record<string, string>;\n\tfetch?: Fetch;\n}\n\nconst MAX_ATTEMPTS = 3;\nconst MAX_RETRY_SECONDS = 10;\n\n/** GET with retries on 429 and 503 (honoring retry-after); null on 404. */\nasync function get(\n\turl: string,\n\topts: HttpOptions,\n\tattempt = 1,\n): Promise<Response | null> {\n\tconst doFetch = opts.fetch ?? fetch;\n\tlet res: Response;\n\ttry {\n\t\tres = await doFetch(url, { headers: opts.headers });\n\t} catch (err) {\n\t\tthrow new SourceError(url, null, (err as Error).message);\n\t}\n\tif (res.status === 404) return null;\n\tif ((res.status === 503 || res.status === 429) && attempt < MAX_ATTEMPTS) {\n\t\tconst header = res.headers.get(\"retry-after\");\n\t\tconst seconds = header === null ? 1 : Number(header);\n\t\tconst wait = Number.isFinite(seconds)\n\t\t\t? Math.min(Math.max(seconds, 0), MAX_RETRY_SECONDS)\n\t\t\t: 1;\n\t\tawait new Promise((r) => setTimeout(r, wait * 1000));\n\t\treturn get(url, opts, attempt + 1);\n\t}\n\tif (!res.ok) throw new SourceError(url, res.status, `HTTP ${res.status}`);\n\treturn res;\n}\n\nasync function getJson<T>(url: string, opts: HttpOptions): Promise<T | null> {\n\tconst res = await get(url, opts);\n\treturn res ? ((await res.json()) as T) : null;\n}\n\nasync function getBytes(url: string, opts: HttpOptions): Promise<Bytes | null> {\n\tconst res = await get(url, opts);\n\treturn res ? new Uint8Array(await res.arrayBuffer()) : null;\n}\n\nconst required = <T>(url: string, v: T | null): T => {\n\tif (v === null) throw new SourceError(url, 404, \"not found\");\n\treturn v;\n};\n\nconst trimSlash = (s: string) => s.replace(/\\/+$/, \"\");\n\ntype MarfJson = { data: string; proof?: string; marf_proof?: string };\n\ntype HeadersJson = { header?: unknown; consensus_hash?: unknown }[];\n\n/** The first entry of a node `/v2/headers/1?tip=<id>` answer: the tip itself. */\nconst toEpoch2 = (url: string, j: HeadersJson | null): Epoch2HeaderResponse => {\n\tconst tip = required(url, j)[0];\n\tif (typeof tip?.header !== \"string\" || typeof tip.consensus_hash !== \"string\")\n\t\tthrow new SourceError(url, 200, \"answer needs header and consensus_hash\");\n\treturn {\n\t\theader: unhex(tip.header),\n\t\tconsensusHash: unhex(tip.consensus_hash),\n\t};\n};\n\nconst toMarf = (url: string, j: MarfJson | null): MarfProofResponse | null => {\n\tif (j === null) return null;\n\tconst proof = j.proof ?? j.marf_proof;\n\tif (typeof proof !== \"string\" || typeof j.data !== \"string\")\n\t\tthrow new SourceError(url, 200, \"MARF answer needs data and proof\");\n\treturn { data: j.data, proof: unhex(proof) };\n};\n\n/** The hosted API. */\nexport const DEFAULT_API_URL = \"https://api.secondlayer.tools\";\n\n/** Options for reading proofs from the Secondlayer API. */\nexport interface SecondlayerSourceOptions {\n\t/** API origin. Defaults to {@link DEFAULT_API_URL}. */\n\tbaseUrl?: string;\n\t/**\n\t * Optional. Proofs are keyless; a key raises the rate limit. Required for\n\t * `rows: true` (metered Index reads). Sent as `Authorization: Bearer`.\n\t */\n\tapiKey?: string;\n\tfetch?: Fetch;\n}\n\nconst VM_WRITE_TYPES = [\n\t\"var_set\",\n\t\"map_set\",\n\t\"map_insert\",\n\t\"map_delete\",\n] as const;\nconst PAGE = 1000;\n\n/** Follow `next_cursor` until a page comes back empty. Null when the first page 404s. */\nasync function pages<T>(\n\tfield: string,\n\turl: string,\n\thttp: HttpOptions,\n): Promise<T[] | null> {\n\tconst out: T[] = [];\n\tlet cursor: string | null = null;\n\tfor (;;) {\n\t\tconst page: string = cursor\n\t\t\t? `${url}&cursor=${encodeURIComponent(cursor)}`\n\t\t\t: url;\n\t\tconst j = await getJson<Record<string, unknown>>(page, http);\n\t\tif (j === null) return cursor === null ? null : out;\n\t\tconst rows = j[field];\n\t\tif (!Array.isArray(rows))\n\t\t\tthrow new SourceError(page, 200, `answer has no ${field} array`);\n\t\tout.push(...(rows as T[]));\n\t\tconst next = j.next_cursor;\n\t\tif (rows.length < PAGE || typeof next !== \"string\" || next === cursor)\n\t\t\treturn out;\n\t\tcursor = next;\n\t}\n}\n\n// Both sources keep their origin and account key in constructor closures, not\n// fields: nothing leaks through a spread, a log or JSON.stringify.\n\n/**\n * Reads every proof input from the Secondlayer API.\n *\n * Blocks, epoch 2.x headers, MARF proofs, witnesses, burn preimages, Bitcoin\n * headers and each block's state writes come from `/v1/proofs/*`, which is free\n * and rate limited. Indexed `vm_events` rows come from the Index API as metered\n * rows, and are read only when `verifyBlock` gets `rows: true`. Methods are own\n * properties, so a partial source spreads over it:\n * `{ ...new SecondlayerProofSource(o), ...new NodeRpcProofSource(n) }`.\n */\nexport class SecondlayerProofSource implements ProofSource {\n\t/** Raw block bytes, header first, by block id or height. */\n\tgetBlock: (ref: string | number) => Promise<Bytes>;\n\t/** An epoch 2.x header and its consensus hash, by index block hash. */\n\tgetEpoch2Header: (blockId: string) => Promise<Epoch2HeaderResponse>;\n\t/**\n\t * A MARF inclusion proof for a path at a tip.\n\t *\n\t * It is null when the key is absent.\n\t */\n\tgetMarfProof: (\n\t\tpathHex: string,\n\t\ttipId: string,\n\t) => Promise<MarfProofResponse | null>;\n\t/** The state witness for a block. */\n\tgetWitness: (blockId: string) => Promise<Bytes>;\n\t/** The burn preimage behind a consensus hash. */\n\tgetBurnPreimage: (consensusHash: string) => Promise<BurnPreimage>;\n\t/** Raw 80-byte Bitcoin headers, `count` of them from height `from`. */\n\tgetBitcoinHeaders: (from: number, count: number) => Promise<string[]>;\n\t/**\n\t * Every MARF write of a block, in ordinal order.\n\t *\n\t * It is null when there are none.\n\t */\n\tgetStateWrites: (height: number) => Promise<StateWrite[] | null>;\n\t/** The indexed `vm_events` write rows of a block, from the Index API. */\n\tgetVmEvents: (height: number) => Promise<VmEventRow[]>;\n\n\tconstructor(opts: SecondlayerSourceOptions = {}) {\n\t\tconst base = trimSlash(opts.baseUrl ?? DEFAULT_API_URL);\n\t\tconst http: HttpOptions = {\n\t\t\theaders: opts.apiKey ? { authorization: `Bearer ${opts.apiKey}` } : {},\n\t\t\tfetch: opts.fetch,\n\t\t};\n\n\t\tthis.getBlock = async (ref) => {\n\t\t\tconst url =\n\t\t\t\ttypeof ref === \"number\"\n\t\t\t\t\t? `${base}/v1/proofs/block/height/${ref}`\n\t\t\t\t\t: `${base}/v1/proofs/block/${ref}`;\n\t\t\treturn required(url, await getBytes(url, http));\n\t\t};\n\n\t\tthis.getEpoch2Header = async (blockId) => {\n\t\t\tconst url = `${base}/v1/proofs/epoch2-header/${blockId}`;\n\t\t\treturn toEpoch2(url, await getJson<HeadersJson>(url, http));\n\t\t};\n\n\t\tthis.getMarfProof = async (pathHex, tipId) => {\n\t\t\tconst url = `${base}/v1/proofs/marf/${pathHex}?tip=${tipId}`;\n\t\t\treturn toMarf(url, await getJson<MarfJson>(url, http));\n\t\t};\n\n\t\tthis.getWitness = async (blockId) => {\n\t\t\tconst url = `${base}/v1/proofs/witness/${blockId}`;\n\t\t\treturn required(url, await getBytes(url, http));\n\t\t};\n\n\t\tthis.getBurnPreimage = async (consensusHash) => {\n\t\t\tconst url = `${base}/v1/proofs/burn/${consensusHash}`;\n\t\t\tconst j = required(\n\t\t\t\turl,\n\t\t\t\tawait getJson<{ burn_height: number; preimage: string }>(url, http),\n\t\t\t);\n\t\t\treturn { preimage: unhex(j.preimage), burnHeight: j.burn_height };\n\t\t};\n\n\t\tthis.getBitcoinHeaders = async (from, count) => {\n\t\t\tconst url = `${base}/v1/proofs/bitcoin-headers?from=${from}&count=${count}`;\n\t\t\tconst j = required(\n\t\t\t\turl,\n\t\t\t\tawait getJson<{ from: number; headers: string[] }>(url, http),\n\t\t\t);\n\t\t\tif (j.from !== from)\n\t\t\t\tthrow new SourceError(url, 200, `headers start at ${j.from}`);\n\t\t\treturn j.headers;\n\t\t};\n\n\t\tthis.getStateWrites = async (height) => {\n\t\t\tconst url = `${base}/v1/proofs/writes/${height}`;\n\t\t\tconst j = await getJson<{ state_writes?: unknown }>(url, http);\n\t\t\tif (j === null) return null;\n\t\t\tif (!Array.isArray(j.state_writes))\n\t\t\t\tthrow new SourceError(url, 200, \"answer has no state_writes array\");\n\t\t\treturn j.state_writes as StateWrite[];\n\t\t};\n\n\t\tthis.getVmEvents = async (height) => {\n\t\t\tconst eventsUrl = (type: string) =>\n\t\t\t\t`${base}/v1/index/events?event_type=${type}&from_height=${height}&to_height=${height}&limit=${PAGE}`;\n\t\t\tif (!opts.apiKey)\n\t\t\t\tthrow new SourceError(\n\t\t\t\t\teventsUrl(VM_WRITE_TYPES[0]),\n\t\t\t\t\t401,\n\t\t\t\t\t\"rows: true reads metered Index events and needs an apiKey\",\n\t\t\t\t);\n\t\t\tconst out: VmEventRow[] = [];\n\t\t\tfor (const type of VM_WRITE_TYPES) {\n\t\t\t\tconst url = eventsUrl(type);\n\t\t\t\tout.push(...((await pages<VmEventRow>(\"events\", url, http)) ?? []));\n\t\t\t}\n\t\t\treturn out.sort((a, b) => a.event_index - b.event_index);\n\t\t};\n\t}\n}\n\n/** Options for reading proofs from a Stacks node. */\nexport interface NodeRpcSourceOptions {\n\t/** Stacks node RPC origin, e.g. `http://localhost:20443`. */\n\tnodeUrl: string;\n\tfetch?: Fetch;\n}\n\n/**\n * Reads blocks, epoch 2.x headers and MARF proofs from a Stacks node.\n *\n * It uses the node's RPC. Witnesses, burn preimages and Bitcoin headers need\n * another source: spread this over one.\n */\nexport class NodeRpcProofSource\n\timplements Pick<ProofSource, \"getBlock\" | \"getEpoch2Header\" | \"getMarfProof\">\n{\n\t/** Raw block bytes, header first, by block id or height. */\n\tgetBlock: (ref: string | number) => Promise<Bytes>;\n\t/** An epoch 2.x header and its consensus hash, by index block hash. */\n\tgetEpoch2Header: (blockId: string) => Promise<Epoch2HeaderResponse>;\n\t/**\n\t * A MARF inclusion proof for a path at a tip.\n\t *\n\t * It is null when the key is absent.\n\t */\n\tgetMarfProof: (\n\t\tpathHex: string,\n\t\ttipId: string,\n\t) => Promise<MarfProofResponse | null>;\n\n\tconstructor(opts: NodeRpcSourceOptions) {\n\t\tconst base = trimSlash(opts.nodeUrl);\n\t\tconst http: HttpOptions = { fetch: opts.fetch };\n\n\t\tthis.getBlock = async (ref) => {\n\t\t\tconst url =\n\t\t\t\ttypeof ref === \"number\"\n\t\t\t\t\t? `${base}/v3/blocks/height/${ref}`\n\t\t\t\t\t: `${base}/v3/blocks/${ref}`;\n\t\t\treturn required(url, await getBytes(url, http));\n\t\t};\n\n\t\tthis.getEpoch2Header = async (blockId) => {\n\t\t\tconst url = `${base}/v2/headers/1?tip=${blockId}`;\n\t\t\treturn toEpoch2(url, await getJson<HeadersJson>(url, http));\n\t\t};\n\n\t\tthis.getMarfProof = async (pathHex, tipId) => {\n\t\t\tconst url = `${base}/v2/clarity/marf/${pathHex}?tip=${tipId}&proof=1`;\n\t\t\treturn toMarf(url, await getJson<MarfJson>(url, http));\n\t\t};\n\t}\n}\n",
17
+ "// Steps 6-8 of verifyBlock: a block's state witness against its authenticated\n// header root, every leaf of its trie named, and indexed rows against the diff.\nimport { type Bytes, bytesEqual, hex, unhex } from \"./bytes.ts\";\nimport { dataVarKey } from \"./keys.ts\";\nimport {\n\tMARF_VALUE_SIZE,\n\theightToHashKey,\n\tmarfPath,\n\tmarfValue,\n} from \"./marf.ts\";\nimport type { StateWrite, VmEventRow } from \"./source.ts\";\nimport {\n\ttype WitnessLeaf,\n\tclassifyBlockDiff,\n\tparseWitness,\n} from \"./witness.ts\";\n\nexport interface DiffWrite {\n\t/** MARF key, when a state_writes row names the leaf. */\n\tkey?: string;\n\t/** Leaf path, hex. */\n\tpath: string;\n\t/** sha512/256 of the stored value string, hex. */\n\tvalueHash: string;\n\t/** Transaction of the last write; null for block-level writes. */\n\ttxIndex?: number | null;\n\t/** The stored value string (hex of a Clarity value) the leaf holds; named writes only. */\n\tvalue?: string;\n\t/** False when the source had no state_writes: the leaf may also be a carried copy. */\n\tnamed: boolean;\n}\n\nexport interface DiffLeaf {\n\tkey?: string;\n\tpath: string;\n\tvalueHash: string;\n}\n\nexport interface ProvenDiff {\n\t/** Every leaf is named (state_writes served) and classified. */\n\tnamed: boolean;\n\twrites: DiffWrite[];\n\t/** Unchanged values copied forward from the parent (proven at the parent). */\n\tcarried: DiffLeaf[];\n\t/** `__MARF_BLOCK_*` bookkeeping. */\n\tinternal: DiffLeaf[];\n}\n\nexport type StateFailureCode =\n\t| \"malformed\"\n\t| \"root-mismatch\"\n\t| \"bad-write\"\n\t| \"hidden-write\"\n\t| \"missing-write\"\n\t| \"key-not-written\"\n\t| \"value-mismatch\"\n\t| \"bad-row\";\n\nexport interface StateFailure {\n\tstep: \"witness\" | \"names\" | \"rows\";\n\tcode: StateFailureCode;\n\tmessage: string;\n\tkey?: string;\n\tpath?: string;\n\tordinal?: number;\n}\n\n/** A block's height, parent, and state root to check rows against. */\nexport interface BlockStateInput {\n\t/** MARF height of the block (its Stacks chain length). */\n\theight: number;\n\t/** Parent block id from the authenticated header. */\n\tparentBlockId: Bytes;\n\t/** state_index_root from the authenticated header. */\n\tstateRoot: Bytes;\n\twitness: Bytes;\n\t/** The block's state_writes; null when the source has none (names unavailable). */\n\twrites: StateWrite[] | null;\n\t/** Indexed rows to prove against the diff. */\n\trows?: VmEventRow[];\n\t/**\n\t * Leaves of the parent's own trie, from a parent witness whose root the\n\t * caller checked against the parent header: each is the parent state's\n\t * value at its path. Resolves carried leaves without a proof per leaf.\n\t */\n\tparentLeaves?: WitnessLeaf[];\n\t/**\n\t * True iff the leaf's value is stored at its path in the parent's state\n\t * (proven by the caller). Asked only with state_writes, for leaves the\n\t * parent's own trie does not explain.\n\t */\n\tparentHolds?: (leaf: WitnessLeaf) => Promise<boolean>;\n}\n\n/** The proven diff, rows checked, notes, and failures. */\nexport interface BlockStateResult {\n\tdiff?: ProvenDiff;\n\trowsChecked: number;\n\tnotes: string[];\n\tfailures: StateFailure[];\n}\n\nconst INTERNAL = {\n\tself: \"__MARF_BLOCK_HEIGHT_SELF\",\n\thashToHeight: \"__MARF_BLOCK_HASH_TO_HEIGHT\",\n} as const;\n\n/** MARFValue of a u32 height: little-endian in the first 4 bytes. */\nconst heightValue = (h: number): string => {\n\tconst v = new Uint8Array(MARF_VALUE_SIZE);\n\tnew DataView(v.buffer).setUint32(0, h, true);\n\treturn hex(v);\n};\n/** 40-byte MARFValue hex of a 32-byte hash or block id (zero tail). */\nconst padded = (b32: Bytes): string => `${hex(b32)}${\"00\".repeat(8)}`;\n\n/**\n * The `__MARF_BLOCK_*` entries block `height` writes (stacks-core index/marf.rs).\n * The parent's are fixed by the header. The block's own id is not known while\n * its trie is built, so `HEIGHT_TO_HASH::{height}` holds a temporary hash; its\n * value is taken from the witness and must map back to `height`.\n */\nfunction internalEntries(\n\theight: number,\n\tparentBlockId: Bytes,\n\tleaves: WitnessLeaf[],\n): [key: string, valueHex: string][] {\n\tconst out: [string, string][] = [[INTERNAL.self, heightValue(height)]];\n\tconst ownKey = heightToHashKey(height);\n\tconst ownPath = marfPath(ownKey);\n\tconst own = leaves.find((l) => bytesEqual(l.path, ownPath));\n\tif (own) {\n\t\tout.push([ownKey, padded(own.valueHash)]);\n\t\tout.push([\n\t\t\t`${INTERNAL.hashToHeight}::${hex(own.valueHash)}`,\n\t\t\theightValue(height),\n\t\t]);\n\t}\n\tif (height > 0) {\n\t\tout.push([heightToHashKey(height - 1), padded(parentBlockId)]);\n\t\tout.push([\n\t\t\t`${INTERNAL.hashToHeight}::${hex(parentBlockId)}`,\n\t\t\theightValue(height - 1),\n\t\t]);\n\t}\n\treturn out;\n}\n\nconst utf8 = new TextDecoder(\"utf-8\", { fatal: true });\nconst strip0x = (s: string) => (s.startsWith(\"0x\") ? s.slice(2) : s);\nconst leafHex = (l: WitnessLeaf): DiffLeaf => ({\n\tpath: hex(l.path),\n\tvalueHash: hex(l.valueHash),\n});\n\n/** Last write per key, in ordinal order, with its value as the stored string. */\nfunction lastWrites(\n\twrites: StateWrite[],\n\tfailures: StateFailure[],\n): Map<string, { value: string; txIndex: number | null }> {\n\tconst out = new Map<string, { value: string; txIndex: number | null }>();\n\tfor (const w of [...writes].sort((a, b) => a.ordinal - b.ordinal)) {\n\t\ttry {\n\t\t\tout.set(w.key, {\n\t\t\t\tvalue: utf8.decode(unhex(strip0x(w.value_hex))),\n\t\t\t\ttxIndex: w.tx_index,\n\t\t\t});\n\t\t} catch {\n\t\t\tfailures.push({\n\t\t\t\tstep: \"names\",\n\t\t\t\tcode: \"bad-write\",\n\t\t\t\tmessage: `state write ${w.ordinal} value is not UTF-8 hex`,\n\t\t\t\tkey: w.key,\n\t\t\t\tordinal: w.ordinal,\n\t\t\t});\n\t\t}\n\t}\n\treturn out;\n}\n\n/** The MARF key and stored value string a vm_events row writes (mirrors clarity_db.rs). */\nfunction rowWrite(row: VmEventRow): [key: string, value: string] {\n\tconst need = (v: string | null | undefined, name: string): string => {\n\t\tif (!v) throw new Error(`${row.event_type} row has no ${name}`);\n\t\treturn v;\n\t};\n\tif (row.event_type === \"var_set\")\n\t\treturn [\n\t\t\tdataVarKey(row.contract_id, need(row.var_name, \"var_name\")),\n\t\t\tstrip0x(need(row.raw_value, \"raw_value\")).toLowerCase(),\n\t\t];\n\tconst key = `vm::${row.contract_id}::0::${need(row.map, \"map\")}::${strip0x(need(row.raw_key, \"raw_key\")).toLowerCase()}`;\n\tif (row.event_type === \"map_delete\") return [key, \"09\"];\n\t// put_value stores map entries as (some value).\n\treturn [key, `0a${strip0x(need(row.raw_value, \"raw_value\")).toLowerCase()}`];\n}\n\n/**\n * Rows against the block's leaves: every row's key must be a leaf, and the\n * last row per key must carry the leaf's value.\n */\nfunction checkRows(\n\trows: VmEventRow[],\n\tleaves: WitnessLeaf[],\n\tfailures: StateFailure[],\n): number {\n\tconst byPath = new Map(leaves.map((l) => [hex(l.path), l]));\n\tconst named: { row: VmEventRow; key: string; path: string; value: string }[] =\n\t\t[];\n\tfor (const row of [...rows].sort((a, b) => a.event_index - b.event_index)) {\n\t\ttry {\n\t\t\tconst [key, value] = rowWrite(row);\n\t\t\tnamed.push({ row, key, path: hex(marfPath(key)), value });\n\t\t} catch (err) {\n\t\t\tfailures.push({\n\t\t\t\tstep: \"rows\",\n\t\t\t\tcode: \"bad-row\",\n\t\t\t\tmessage: (err as Error).message,\n\t\t\t\tordinal: row.event_index,\n\t\t\t});\n\t\t}\n\t}\n\tconst last = new Map(named.map((n, i) => [n.path, i]));\n\tnamed.forEach((n, i) => {\n\t\tconst leaf = byPath.get(n.path);\n\t\tconst at = { key: n.key, path: n.path, ordinal: n.row.event_index };\n\t\tif (!leaf)\n\t\t\tfailures.push({\n\t\t\t\tstep: \"rows\",\n\t\t\t\tcode: \"key-not-written\",\n\t\t\t\tmessage: `${n.row.event_type} row ${n.row.event_index} names a key the block did not write`,\n\t\t\t\t...at,\n\t\t\t});\n\t\telse if (\n\t\t\tlast.get(n.path) === i &&\n\t\t\tpadded(leaf.valueHash) !== hex(marfValue(n.value))\n\t\t)\n\t\t\tfailures.push({\n\t\t\t\tstep: \"rows\",\n\t\t\t\tcode: \"value-mismatch\",\n\t\t\t\tmessage: `${n.row.event_type} row ${n.row.event_index} value differs from the block's leaf`,\n\t\t\t\t...at,\n\t\t\t});\n\t});\n\treturn named.length;\n}\n\n/**\n * Verifies a block's state against an authenticated header.\n *\n * The witness must recompute `stateRoot`, then every leaf is classified. With\n * state writes, any leaf that is not a named write, a carried parent value or\n * MARF bookkeeping is a hidden write. Without them the diff is still proven,\n * since every leaf is in the block: carried leaves are told apart only through\n * `parentLeaves`, and the remaining writes come back unnamed.\n */\nexport async function verifyBlockState(\n\tinput: BlockStateInput,\n): Promise<BlockStateResult> {\n\tconst out: BlockStateResult = { rowsChecked: 0, notes: [], failures: [] };\n\tlet witness: ReturnType<typeof parseWitness>;\n\ttry {\n\t\twitness = parseWitness(input.witness);\n\t} catch (err) {\n\t\tout.failures.push({\n\t\t\tstep: \"witness\",\n\t\t\tcode: \"malformed\",\n\t\t\tmessage: (err as Error).message,\n\t\t});\n\t\treturn out;\n\t}\n\tif (!bytesEqual(witness.root, input.stateRoot)) {\n\t\tout.failures.push({\n\t\t\tstep: \"witness\",\n\t\t\tcode: \"root-mismatch\",\n\t\t\tmessage: `witness root ${hex(witness.root)} != header state_index_root ${hex(input.stateRoot)}`,\n\t\t});\n\t\treturn out;\n\t}\n\tconst { leaves } = witness;\n\tconst internal = internalEntries(input.height, input.parentBlockId, leaves);\n\tconst named = input.writes !== null;\n\tconst last = lastWrites(input.writes ?? [], out.failures);\n\tconst writes = [...last].map(([k, w]): [string, string] => [k, w.value]);\n\t// First pass with no parent values finds the leaves that need one.\n\tconst first = classifyBlockDiff({\n\t\tleaves,\n\t\twrites,\n\t\tinternal,\n\t\tparentValue: () => undefined,\n\t});\n\tconst inParent = new Map(\n\t\t(input.parentLeaves ?? []).map((l) => [hex(l.path), hex(l.valueHash)]),\n\t);\n\tconst carried = new Map<string, string>();\n\tfor (const leaf of first.hidden) {\n\t\tconst pathHex = hex(leaf.path);\n\t\tif (\n\t\t\tinParent.get(pathHex) === hex(leaf.valueHash) ||\n\t\t\t(named && (await input.parentHolds?.(leaf)))\n\t\t)\n\t\t\tcarried.set(pathHex, padded(leaf.valueHash));\n\t}\n\tconst d = classifyBlockDiff({\n\t\tleaves,\n\t\twrites,\n\t\tinternal,\n\t\tparentValue: (p) => carried.get(p),\n\t});\n\tout.diff = {\n\t\tnamed,\n\t\twrites: named\n\t\t\t? d.writes.map((l) => ({\n\t\t\t\t\t...leafHex(l),\n\t\t\t\t\tkey: l.key,\n\t\t\t\t\ttxIndex: last.get(l.key)?.txIndex ?? null,\n\t\t\t\t\tvalue: last.get(l.key)?.value,\n\t\t\t\t\tnamed: true,\n\t\t\t\t}))\n\t\t\t: // Without names every unexplained leaf is a write we cannot label.\n\t\t\t\td.hidden.map((l) => ({ ...leafHex(l), named: false })),\n\t\tcarried: d.carried.map(leafHex),\n\t\tinternal: d.internal.map((l) => ({ ...leafHex(l), key: l.key })),\n\t};\n\tif (!named)\n\t\tout.notes.push(\n\t\t\t`source has no state_writes for block ${input.height}: ${d.hidden.length} written leaves are proven in the block but unnamed`,\n\t\t);\n\telse {\n\t\tfor (const l of d.hidden)\n\t\t\tout.failures.push({\n\t\t\t\tstep: \"names\",\n\t\t\t\tcode: \"hidden-write\",\n\t\t\t\tmessage: `leaf ${hex(l.path)} is not a named write, a carried parent value or MARF bookkeeping`,\n\t\t\t\tpath: hex(l.path),\n\t\t\t});\n\t\tfor (const key of d.missing)\n\t\t\tout.failures.push({\n\t\t\t\tstep: \"names\",\n\t\t\t\tcode: \"missing-write\",\n\t\t\t\tmessage: `state write ${key} has no leaf holding its value`,\n\t\t\t\tkey,\n\t\t\t\tpath: hex(marfPath(key)),\n\t\t\t});\n\t}\n\tif (input.rows) out.rowsChecked = checkRows(input.rows, leaves, out.failures);\n\treturn out;\n}\n",
18
+ "// A Nakamoto block's transactions against its header's tx_merkle_root\n// (stacks-common util/hash.rs MerkleTree, MerkleHashFunc = Sha512Trunc256Sum).\nimport { sha512_256 } from \"@noble/hashes/sha2.js\";\nimport { splitTransactions } from \"@secondlayer/stacks/transactions\";\nimport { type Bytes, bytesEqual, concat, hex } from \"./bytes.ts\";\nimport type { NakamotoHeader } from \"./header.ts\";\n\n/** A transaction's id and its consensus-serialized bytes. */\nexport interface BlockTransaction {\n\t/** sha512/256 of the transaction bytes, hex. */\n\ttxid: string;\n\t/** The consensus-serialized transaction. */\n\traw: Bytes;\n}\n\nconst LEAF_TAG = new Uint8Array([0x00]);\nconst NODE_TAG = new Uint8Array([0x01]);\n\n/**\n * Computes the `tx_merkle_root` over transaction ids.\n *\n * A leaf is H(0x00 ‖ txid) and a node is H(0x01 ‖ l ‖ r). An odd level\n * duplicates its last node, and a lone leaf is still paired with itself, so a\n * one-transaction block hashes H(0x01 ‖ leaf ‖ leaf).\n */\nexport function txMerkleRoot(txids: Bytes[]): Bytes {\n\tif (txids.length === 0) throw new Error(\"no transactions\");\n\tlet level = txids.map((t) => sha512_256(concat([LEAF_TAG, t])));\n\tdo {\n\t\tif (level.length % 2 === 1) level.push(level[level.length - 1] as Bytes);\n\t\tconst next: Bytes[] = [];\n\t\tfor (let i = 0; i < level.length; i += 2) {\n\t\t\tnext.push(\n\t\t\t\tsha512_256(\n\t\t\t\t\tconcat([NODE_TAG, level[i] as Bytes, level[i + 1] as Bytes]),\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t\tlevel = next;\n\t} while (level.length > 1);\n\treturn level[0] as Bytes;\n}\n\n/** Thrown for a malformed block body or a transaction root mismatch. */\nexport class TransactionsError extends Error {\n\tconstructor(\n\t\treadonly code: \"malformed\" | \"tx-root-mismatch\",\n\t\tmessage: string,\n\t) {\n\t\tsuper(message);\n\t}\n}\n\n/**\n * Hashes a block's transactions and checks them against the header.\n *\n * Each transaction is hashed to its txid and checked against the header's\n * `tx_merkle_root`. The body after `header.byteLength` is a u32 count, then the\n * transactions back to back. It returns null when the bytes are the header\n * alone, as a source that serves headers only does. It throws\n * {@link TransactionsError} on a malformed body, trailing bytes or a root\n * mismatch.\n */\nexport function blockTransactions(\n\traw: Bytes,\n\theader: NakamotoHeader,\n): BlockTransaction[] | null {\n\tconst body = raw.subarray(header.byteLength);\n\tif (body.length === 0) return null;\n\tif (body.length < 4)\n\t\tthrow new TransactionsError(\"malformed\", \"block body has no tx count\");\n\tconst count = new DataView(\n\t\tbody.buffer,\n\t\tbody.byteOffset,\n\t\tbody.byteLength,\n\t).getUint32(0);\n\tif (count === 0)\n\t\tthrow new TransactionsError(\"malformed\", \"block has no transactions\");\n\tlet txs: Bytes[];\n\ttry {\n\t\ttxs = splitTransactions(body.subarray(4), count);\n\t} catch (err) {\n\t\tthrow new TransactionsError(\n\t\t\t\"malformed\",\n\t\t\t`transactions do not parse: ${(err as Error).message}`,\n\t\t);\n\t}\n\tconst used = txs.reduce((n, t) => n + t.length, 4);\n\tif (used !== body.length)\n\t\tthrow new TransactionsError(\n\t\t\t\"malformed\",\n\t\t\t`${body.length - used} bytes after the block's ${count} transactions`,\n\t\t);\n\tconst ids = txs.map((t) => sha512_256(t));\n\tconst root = txMerkleRoot(ids);\n\tif (!bytesEqual(root, header.txMerkleRoot))\n\t\tthrow new TransactionsError(\n\t\t\t\"tx-root-mismatch\",\n\t\t\t`transactions hash to ${hex(root)}, header tx_merkle_root is ${hex(header.txMerkleRoot)}`,\n\t\t);\n\treturn txs.map((t, i) => ({ txid: hex(ids[i] as Bytes), raw: t }));\n}\n",
19
+ "import { unhex } from \"./bytes.ts\";\nimport type { VerifyCheckpoint } from \"./checkpoint.ts\";\nimport { parseNakamotoHeader } from \"./header.ts\";\nimport type { BlockVerification, VerifyStep } from \"./verify-block.ts\";\n\nexport type LinkStatus = \"ok\" | \"failed\" | \"skipped\";\n\n/** One verification step with its status and what it proved. */\nexport interface LinkLine {\n\tstep: VerifyStep;\n\tlabel: string;\n\tstatus: LinkStatus;\n\t/** What the link proved, why it failed, or why it was not checked. */\n\tdetail: string;\n}\n\n/** The chain of links, in the order verifyBlock walks them. */\nexport const LINKS: readonly { step: VerifyStep; label: string }[] = [\n\t{ step: \"ancestry\", label: \"ancestry\" },\n\t{ step: \"block\", label: \"block\" },\n\t{ step: \"bitcoin\", label: \"bitcoin\" },\n\t{ step: \"burn\", label: \"burn\" },\n\t{ step: \"signer-set\", label: \"cycle\" },\n\t{ step: \"signatures\", label: \"signatures\" },\n\t{ step: \"txs\", label: \"txs\" },\n\t{ step: \"witness\", label: \"state root\" },\n\t{ step: \"names\", label: \"diff\" },\n\t{ step: \"rows\", label: \"rows\" },\n];\n\nconst n = (v: number | bigint) => v.toLocaleString(\"en-US\");\n\n/** What each link proved, for the human view. */\nfunction linkDetail(\n\tstep: VerifyStep,\n\tr: BlockVerification,\n\tcp: VerifyCheckpoint,\n): string {\n\tswitch (step) {\n\t\tcase \"ancestry\": {\n\t\t\tconst a = r.ancestry;\n\t\t\tif (!a) return \"\";\n\t\t\tconst checkpoint = parseNakamotoHeader(unhex(cp.stacks.header));\n\t\t\tconst start =\n\t\t\t\ta.fromHeight === Number(checkpoint.chainLength)\n\t\t\t\t\t? `the checkpoint ${n(a.fromHeight)}`\n\t\t\t\t\t: `block ${n(a.fromHeight)}`;\n\t\t\treturn a.via === \"marf\"\n\t\t\t\t? `${n(r.height ?? 0)} proven in the state of ${start} (one MARF proof)`\n\t\t\t\t: `${n(r.height ?? 0)} reached from ${start} by parent links`;\n\t\t}\n\t\tcase \"block\":\n\t\t\treturn `${n(r.height ?? 0)} ${r.blockId}`;\n\t\tcase \"bitcoin\":\n\t\t\treturn `headers ${n(cp.bitcoin.height)}..${n(r.burnHeight ?? 0)}, proof-of-work and retargets checked`;\n\t\tcase \"burn\":\n\t\t\treturn `height ${n(r.burnHeight ?? 0)} ${r.bitcoinBlockHash}`;\n\t\tcase \"signer-set\":\n\t\t\treturn r.cycle === cp.stacks.cycle\n\t\t\t\t? `${r.cycle}, the checkpoint's own signer set`\n\t\t\t\t: `${r.cycle}, signer set proven forward from checkpoint cycle ${cp.stacks.cycle}`;\n\t\tcase \"signatures\":\n\t\t\treturn `${n(r.signerWeight ?? 0n)} / ${n(r.totalWeight ?? 0n)} weight signed, threshold ${n(r.threshold ?? 0n)}`;\n\t\tcase \"txs\":\n\t\t\treturn `${n(r.transactions?.length ?? 0)} transactions match the tx merkle root`;\n\t\tcase \"witness\":\n\t\t\treturn `${r.stateRoot} matches the witness`;\n\t\tcase \"names\": {\n\t\t\tconst d = r.diff;\n\t\t\tif (!d) return \"\";\n\t\t\tconst named = d.writes.filter((w) => w.named).length;\n\t\t\tconst written = named\n\t\t\t\t? `${d.writes.length} written (${named} named, ${d.writes.length - named} unnamed)`\n\t\t\t\t: `${d.writes.length} written (unnamed)`;\n\t\t\treturn `${written}, ${d.carried.length} carried, ${d.internal.length} internal`;\n\t\t}\n\t\tcase \"rows\":\n\t\t\treturn `${n(r.rowsChecked ?? 0)} vm_events rows match the diff`;\n\t}\n}\n\n/**\n * Links a block below the checkpoint skips: its id is pinned by hash from a\n * trusted descendant, so no signer set or signatures; the burn block is bound\n * only when the synced Bitcoin chain reaches it.\n */\nfunction notNeeded(step: VerifyStep, r: BlockVerification): boolean {\n\tif (!r.ancestry) return false;\n\tif (step === \"bitcoin\" || step === \"burn\") return r.burnHeight === undefined;\n\treturn step === \"signer-set\" || step === \"signatures\";\n}\n\n/**\n * Describes a verification as one line per link and a verdict.\n *\n * It is the human view, shared by the CLI and the browser checker. Ancestry\n * appears only below the checkpoint. `rows` says whether the caller asked for\n * the rows link.\n */\nexport function describeLinks(\n\tr: BlockVerification,\n\tcp: VerifyCheckpoint,\n\topts: { rows?: boolean } = {},\n): { lines: LinkLine[]; verdict: { ok: boolean; text: string } } {\n\tconst first = r.failures[0];\n\tconst broken = first\n\t\t? LINKS.findIndex((l) => l.step === first.step)\n\t\t: LINKS.length;\n\tconst lines: LinkLine[] = [];\n\tfor (const [i, link] of LINKS.entries()) {\n\t\tconst { step, label } = link;\n\t\tconst failure = r.failures.find((f) => f.step === step);\n\t\t// Ancestry is a link only below the checkpoint.\n\t\tif (step === \"ancestry\" && !failure && !r.ancestry) continue;\n\t\tconst skipped = (detail: string): LinkLine => ({\n\t\t\tstep,\n\t\t\tlabel,\n\t\t\tstatus: \"skipped\",\n\t\t\tdetail,\n\t\t});\n\t\tif (failure)\n\t\t\tlines.push({ step, label, status: \"failed\", detail: failure.message });\n\t\telse if (step === \"rows\" && !opts.rows)\n\t\t\tlines.push(skipped(\"not checked (pass --rows)\"));\n\t\telse if (i > broken)\n\t\t\tlines.push(skipped(\"not checked: an earlier link is broken\"));\n\t\telse if (notNeeded(step, r))\n\t\t\tlines.push(\n\t\t\t\tskipped(\"not needed: the block is hash-chained to the checkpoint\"),\n\t\t\t);\n\t\telse if (step === \"rows\" && r.rowsChecked === undefined)\n\t\t\tlines.push(skipped(\"not checked: the source serves no indexed rows\"));\n\t\telse if (step === \"txs\" && r.transactions === undefined)\n\t\t\tlines.push(\n\t\t\t\tskipped(\n\t\t\t\t\t\"not checked: no transaction bytes (epoch 2.x, or the source served the header only)\",\n\t\t\t\t),\n\t\t\t);\n\t\telse\n\t\t\tlines.push({\n\t\t\t\tstep,\n\t\t\t\tlabel,\n\t\t\t\tstatus: \"ok\",\n\t\t\t\tdetail: linkDetail(step, r, cp),\n\t\t\t});\n\t}\n\n\tif (!first) {\n\t\tconst from = n(parseNakamotoHeader(unhex(cp.stacks.header)).chainLength);\n\t\treturn {\n\t\t\tlines,\n\t\t\tverdict: {\n\t\t\t\tok: true,\n\t\t\t\ttext: `Block ${n(r.height ?? 0)} is proven. Trusted: only the checkpoint (Stacks ${from}, Bitcoin ${n(cp.bitcoin.height)}).`,\n\t\t\t},\n\t\t};\n\t}\n\tconst label = LINKS[broken]?.label ?? first.step;\n\treturn {\n\t\tlines,\n\t\tverdict: {\n\t\t\tok: false,\n\t\t\ttext:\n\t\t\t\tfirst.code === \"unavailable\"\n\t\t\t\t\t? `Could not check the ${label} link: the source could not serve it.`\n\t\t\t\t\t: `Not proven: the ${label} link is broken.`,\n\t\t},\n\t};\n}\n",
20
+ "// verifyBlock: the end-to-end trustless check for one Stacks block.\n//\n// At or above the checkpoint, forward:\n// checkpoint ─▶ bitcoin headers (PoW) ─▶ burn height ─▶ cycle ─▶ signer set[cycle] (MARF-proven)\n// ─▶ header N (signatures ≥ 70%) ─▶ txs N (tx merkle root) ─▶ witness N (root)\n// ─▶ named diff ─▶ indexed rows\n//\n// Below it, backward: a trusted descendant's id commits to every ancestor by\n// hash, so no signatures are needed:\n// checkpoint ─▶ id N (parent links, or one MARF proof of __MARF_BLOCK_HEIGHT_TO_HASH::N)\n// ─▶ header N (hashes to id N) ─▶ txs N ─▶ witness N (root) ─▶ named diff ─▶ indexed rows\n//\n// Every input comes from an untrusted ProofSource; only the checkpoint is trusted.\nimport { uintCV } from \"@secondlayer/stacks/clarity\";\nimport { HeaderChain, HeaderValidationError } from \"./bitcoin/chain.ts\";\nimport {\n\tMAINNET_PREPARE_LENGTH,\n\tcycleStart,\n\trewardCycle,\n\tverifyConsensusPreimage,\n} from \"./burn.ts\";\nimport { type Bytes, bytesEqual, hex, unhex } from \"./bytes.ts\";\nimport { MAINNET_CHECKPOINT, type VerifyCheckpoint } from \"./checkpoint.ts\";\nimport {\n\ttype Epoch2Header,\n\ttype NakamotoHeader,\n\ttype StacksHeader,\n\tblockId,\n\tisEpoch2Header,\n\tparseEpoch2Header,\n\tparseNakamotoHeader,\n\tsignerSignatureHash,\n} from \"./header.ts\";\nimport { mapEntryKey } from \"./keys.ts\";\nimport {\n\tMARF_VALUE_SIZE,\n\theightToHashKey,\n\tmarfPath,\n\tmarfProofAncestors,\n\tmarfProofValue,\n\tmarfValue,\n\tverifyMarfProof,\n} from \"./marf.ts\";\nimport {\n\tSIGNERS_CONTRACT,\n\ttype SignerSet,\n\tdecodeSignerSet,\n\tverifySignerSignatures,\n} from \"./signers.ts\";\nimport type { BurnPreimage, ProofSource, StateWrite } from \"./source.ts\";\nimport {\n\ttype ProvenDiff,\n\ttype StateFailureCode,\n\tverifyBlockState,\n} from \"./state.ts\";\nimport {\n\ttype BlockTransaction,\n\tTransactionsError,\n\tblockTransactions,\n} from \"./txs.ts\";\nimport { type WitnessLeaf, parseWitness } from \"./witness.ts\";\n\nexport type VerifyStep =\n\t| \"ancestry\"\n\t| \"block\"\n\t| \"bitcoin\"\n\t| \"burn\"\n\t| \"signer-set\"\n\t| \"signatures\"\n\t| \"txs\"\n\t| \"witness\"\n\t| \"names\"\n\t| \"rows\";\n\nexport type VerifyFailureCode =\n\t| StateFailureCode\n\t/** The source could not serve something the step needs. */\n\t| \"unavailable\"\n\t| \"id-mismatch\"\n\t/** The block's transactions do not hash to its header's tx_merkle_root. */\n\t| \"tx-root-mismatch\"\n\t| \"height-mismatch\"\n\t| \"invalid-header\"\n\t| \"preimage-mismatch\"\n\t| \"burn-not-in-chain\"\n\t| \"before-checkpoint\"\n\t/** The block is not the checkpoint chain's block at its height. */\n\t| \"not-ancestor\"\n\t| \"ancestry-proof-invalid\"\n\t| \"anchor-not-found\"\n\t| \"anchor-outside-window\"\n\t| \"anchor-unsigned\"\n\t| \"set-proof-invalid\"\n\t| \"below-threshold\"\n\t| \"unknown-signer\"\n\t| \"duplicate-signer\"\n\t| \"bad-signature\";\n\nexport interface VerifyFailure {\n\tstep: VerifyStep;\n\tcode: VerifyFailureCode;\n\tmessage: string;\n\t/** Reward cycle being proven (signer-set step). */\n\tcycle?: number;\n\t/** Block the failure is about, when not the target. */\n\tblockId?: string;\n\tkey?: string;\n\tpath?: string;\n\tordinal?: number;\n}\n\n/** How a block below the checkpoint was tied to it. */\nexport interface Ancestry {\n\t/** Trusted descendant it was proven from: the checkpoint, or a block proven below it earlier. */\n\tfromHeight: number;\n\tfromBlockId: string;\n\t/**\n\t * `parents`: each header hashes to the parent id its child commits to.\n\t * `marf`: one MARF proof of `__MARF_BLOCK_HEIGHT_TO_HASH::<height>` against\n\t * the descendant's state root.\n\t */\n\tvia: \"parents\" | \"marf\";\n}\n\n/** The result of verifying a block, step by step. */\nexport interface BlockVerification {\n\t/**\n\t * Every step passed. At or above the checkpoint: header, burn binding,\n\t * signatures, state root, names and rows. Below it: ancestry, header,\n\t * state root, names and rows (and the burn binding when Bitcoin reaches it).\n\t */\n\tok: boolean;\n\theight?: number;\n\tblockId?: string;\n\t/** Nakamoto block hash (the header's signer sighash), hex. Absent for epoch 2.x. */\n\tblockHash?: string;\n\t/** The header's consensus hash, hex. */\n\tconsensusHash?: string;\n\t/** Nakamoto header timestamp, Unix seconds. Absent for epoch 2.x. */\n\ttimestamp?: number;\n\t/** The header's state_index_root, hex: what the witness must hash to. */\n\tstateRoot?: string;\n\t/** Set for blocks below the checkpoint, which need no signatures. */\n\tancestry?: Ancestry;\n\tcycle?: number;\n\tburnHeight?: number;\n\t/** Display-order hex. */\n\tbitcoinBlockHash?: string;\n\tsignerWeight?: bigint;\n\ttotalWeight?: bigint;\n\tthreshold?: bigint;\n\t/**\n\t * The block's transactions, checked against the header's tx_merkle_root.\n\t * Absent for epoch 2.x blocks and when the source served the header only.\n\t */\n\ttransactions?: BlockTransaction[];\n\tdiff?: ProvenDiff;\n\t/** Every state_writes row the names step checked, in ordinal order. */\n\twrites?: StateWrite[];\n\t/** vm_events rows proven against the diff. */\n\trowsChecked?: number;\n\tnotes: string[];\n\t/** Empty when ok. The first entry is the first broken link. */\n\tfailures: VerifyFailure[];\n}\n\n/** The proof source, checkpoint, and row checking for a block verify. */\nexport interface VerifyOptions {\n\tsource: ProofSource;\n\t/** Defaults to MAINNET_CHECKPOINT. */\n\tcheckpoint?: VerifyCheckpoint;\n\t/**\n\t * Also prove the block's indexed vm_events rows against its diff: reads\n\t * the source's `getVmEvents`, which bill as Index rows on the Secondlayer\n\t * API. Off by default. Naming the diff's writes (`getStateWrites`, free on\n\t * `/v1/proofs`) is always on when the source has them.\n\t */\n\trows?: boolean;\n\t/**\n\t * Called once per link as it passes, in the order the verifier proves them.\n\t * Failures arrive in the result, not here.\n\t */\n\tonStep?: (step: VerifyStep) => void;\n}\n\nclass Broken extends Error {\n\tconstructor(readonly failure: VerifyFailure) {\n\t\tsuper(failure.message);\n\t}\n}\n\nconst fail = (f: VerifyFailure): never => {\n\tthrow new Broken(f);\n};\n\n/** Run a source call; a throw becomes an `unavailable` failure of `step`. */\nasync function fetchFor<T>(\n\tstep: VerifyStep,\n\twhat: string,\n\tcall: () => Promise<T>,\n\textra: Partial<VerifyFailure> = {},\n): Promise<T> {\n\ttry {\n\t\treturn await call();\n\t} catch (err) {\n\t\tif (err instanceof Broken) throw err;\n\t\treturn fail({\n\t\t\tstep,\n\t\t\tcode: \"unavailable\",\n\t\t\tmessage: `${what}: ${(err as Error).message}`,\n\t\t\t...extra,\n\t\t});\n\t}\n}\n\nconst BITCOIN_BATCH = 2016;\n/**\n * Below the checkpoint, ancestors this close to a trusted block are reached by\n * parent links (one block fetch each); farther ones by one MARF proof, which\n * costs the proof plus a header per ancestor trie it crosses.\n */\nconst MAX_WALK = 16;\n\n/** A block position for the anchor search; `burn` is a source hint. */\nexport interface SearchPoint {\n\theight: number;\n\tburn?: number;\n}\n\n/**\n * Find a block whose burn height lies in `[window[0], window[1])`, between\n * `lo` and `hi` (exclusive). Interpolates on burn height, falling back to\n * bisection whenever a probe fails to halve the bracket. Burn heights here\n * are unproven hints: the caller authenticates whatever this returns.\n */\nexport async function findAnchor<T extends SearchPoint & { burn: number }>(\n\tlow: SearchPoint,\n\thigh: SearchPoint,\n\twindow: readonly [number, number],\n\tprobe: (height: number) => Promise<T>,\n\tmaxProbes = 32,\n): Promise<T | null> {\n\tlet [lo, hi] = [low, high];\n\tconst target = (window[0] + window[1]) / 2;\n\tlet bisect = false;\n\tfor (let i = 0; i < maxProbes; i++) {\n\t\tconst span = hi.height - lo.height;\n\t\tif (span <= 1) return null;\n\t\tlet h = Math.floor((lo.height + hi.height) / 2);\n\t\tif (\n\t\t\t!bisect &&\n\t\t\tlo.burn !== undefined &&\n\t\t\thi.burn !== undefined &&\n\t\t\thi.burn > lo.burn\n\t\t)\n\t\t\th =\n\t\t\t\tlo.height +\n\t\t\t\tMath.round(((target - lo.burn) * span) / (hi.burn - lo.burn));\n\t\th = Math.min(Math.max(h, lo.height + 1), hi.height - 1);\n\t\tconst p = await probe(h);\n\t\tif (p.height <= lo.height || p.height >= hi.height) return null;\n\t\tif (p.burn >= window[0] && p.burn < window[1]) return p;\n\t\tif (p.burn < window[0]) lo = p;\n\t\telse hi = p;\n\t\tbisect = hi.height - lo.height > span / 2;\n\t}\n\treturn null;\n}\n\ninterface Probe extends SearchPoint {\n\tburn: number;\n\theader: NakamotoHeader;\n\tid: string;\n}\n\n/**\n * Verifies blocks from one checkpoint against one source.\n *\n * It caches the Bitcoin header chain, proven signer sets and fetched headers\n * across calls.\n */\nexport class BlockVerifier {\n\tprivate readonly source: ProofSource;\n\tprivate readonly checkpoint: VerifyCheckpoint;\n\tprivate readonly rows: boolean;\n\tprivate readonly onStep?: (step: VerifyStep) => void;\n\tprivate readonly chain: HeaderChain;\n\t/** Proven signer sets by cycle. */\n\tprivate readonly sets = new Map<number, SignerSet>();\n\t/** Where each proven set was anchored: the lower bound for the next search. */\n\tprivate readonly anchors = new Map<number, SearchPoint>();\n\t/** Headers fetched by id, each checked to hash to it. */\n\tprivate readonly headers = new Map<string, StacksHeader>();\n\t/** Blocks proven on the checkpoint's chain below it, by height. */\n\tprivate readonly below = new Map<\n\t\tnumber,\n\t\t{ id: string; ancestry: Ancestry }\n\t>();\n\tprivate readonly burns = new Map<\n\t\tstring,\n\t\t{ burnHeight: number; hash: string }\n\t>();\n\t/** Unverified source answers by consensus hash. */\n\tprivate readonly preimages = new Map<string, BurnPreimage>();\n\t/** Raw bytes of the last few blocks fetched, so the txs step reuses the\n\t * block an ancestry walk just read. Bounded: blocks can be megabytes. */\n\tprivate readonly raws = new Map<string, Bytes>();\n\tprivate readonly start: { header: NakamotoHeader; id: string };\n\n\tconstructor(opts: VerifyOptions) {\n\t\tthis.source = opts.source;\n\t\tthis.checkpoint = opts.checkpoint ?? MAINNET_CHECKPOINT;\n\t\tthis.rows = opts.rows ?? false;\n\t\tthis.onStep = opts.onStep;\n\t\tconst { stacks } = this.checkpoint;\n\t\tconst header = parseNakamotoHeader(unhex(stacks.header));\n\t\tthis.start = { header, id: hex(blockId(header)) };\n\t\tthis.headers.set(this.start.id, header);\n\t\tthis.sets.set(stacks.cycle, decodeSignerSet(stacks.signerSet));\n\t\tthis.chain = HeaderChain.fromCheckpoint(this.checkpoint.bitcoin);\n\t}\n\n\t/** Verify one block by id (hex) or height. Never throws for bad source data. */\n\tasync verify(ref: string | number): Promise<BlockVerification> {\n\t\tconst out: BlockVerification = { ok: false, notes: [], failures: [] };\n\t\ttry {\n\t\t\tawait this.run(ref, out);\n\t\t} catch (err) {\n\t\t\tif (!(err instanceof Broken)) throw err;\n\t\t\tout.failures.unshift(err.failure);\n\t\t}\n\t\tout.ok = out.failures.length === 0;\n\t\treturn out;\n\t}\n\n\t/** Report a passed link. A throwing callback must not break verification. */\n\tprivate passed(step: VerifyStep): void {\n\t\ttry {\n\t\t\tthis.onStep?.(step);\n\t\t} catch {}\n\t}\n\n\tprivate async run(\n\t\tref: string | number,\n\t\tout: BlockVerification,\n\t): Promise<void> {\n\t\tconst start = Number(this.start.header.chainLength);\n\t\tif (typeof ref === \"number\" && ref < start)\n\t\t\treturn this.runBelow(ref, undefined, out);\n\t\tlet header: StacksHeader;\n\t\tif (typeof ref === \"string\") {\n\t\t\tconst id = ref.replace(/^0x/, \"\").toLowerCase();\n\t\t\theader = await this.header(id, \"block\");\n\t\t\tconst height = Number(header.chainLength);\n\t\t\tif (height < start) return this.runBelow(height, id, out);\n\t\t\tif (isEpoch2Header(header))\n\t\t\t\tfail({\n\t\t\t\t\tstep: \"block\",\n\t\t\t\t\tcode: \"invalid-header\",\n\t\t\t\t\tmessage: `epoch 2.x block ${id} claims height ${height}, at or above the checkpoint`,\n\t\t\t\t});\n\t\t} else {\n\t\t\tconst raw = await fetchFor(\"block\", `block ${ref}`, () =>\n\t\t\t\tthis.source.getBlock(ref),\n\t\t\t);\n\t\t\theader = parseHeader(raw, \"block\");\n\t\t\tthis.rememberRaw(hex(blockId(header)), raw);\n\t\t}\n\t\tconst id = hex(blockId(header));\n\t\tconst height = Number(header.chainLength);\n\t\tif (typeof ref === \"number\" && height !== ref)\n\t\t\tfail({\n\t\t\t\tstep: \"block\",\n\t\t\t\tcode: \"height-mismatch\",\n\t\t\t\tmessage: `source returned height ${height} for ${ref}`,\n\t\t\t});\n\t\tawait this.runForward(header as NakamotoHeader, id, out);\n\t}\n\n\t/** At or above the checkpoint: Bitcoin, burn binding, signer set, signatures, state. */\n\tprivate async runForward(\n\t\theader: NakamotoHeader,\n\t\tid: string,\n\t\tout: BlockVerification,\n\t): Promise<void> {\n\t\tconst height = Number(header.chainLength);\n\t\tout.height = height;\n\t\tout.blockId = id;\n\t\tdescribeHeader(header, out);\n\t\tthis.passed(\"block\");\n\n\t\tconst burn = await this.bindBurn(header, \"burn\");\n\t\tconst cycle = rewardCycle(burn.burnHeight);\n\t\tout.burnHeight = burn.burnHeight;\n\t\tout.bitcoinBlockHash = burn.hash;\n\t\tout.cycle = cycle;\n\t\tthis.passed(\"bitcoin\");\n\t\tthis.passed(\"burn\");\n\n\t\tconst set = await this.signerSet(cycle, {\n\t\t\theight,\n\t\t\tburn: burn.burnHeight,\n\t\t});\n\t\tthis.passed(\"signer-set\");\n\t\tconst sig = verifySignerSignatures(header, set);\n\t\tout.signerWeight = sig.signedWeight;\n\t\tout.totalWeight = sig.totalWeight;\n\t\tout.threshold = sig.threshold;\n\t\tif (!sig.valid) fail(signatureFailure(sig, \"signatures\", cycle));\n\t\tthis.passed(\"signatures\");\n\t\tawait this.checkTransactions(header, id, out);\n\t\tawait this.verifyState(header, id, out);\n\t}\n\n\t/**\n\t * Below the checkpoint: prove the checkpoint chain's id at `height` (and\n\t * that it is `claimed`, when the caller asked by id), then the header that\n\t * hashes to it, then its state. Signatures add nothing to a header pinned\n\t * by hash from a trusted descendant.\n\t */\n\tprivate async runBelow(\n\t\theight: number,\n\t\tclaimed: string | undefined,\n\t\tout: BlockVerification,\n\t): Promise<void> {\n\t\tout.height = height;\n\t\tconst { id, ancestry } = await this.ancestor(height);\n\t\tout.ancestry = ancestry;\n\t\tif (claimed !== undefined && claimed !== id)\n\t\t\tfail({\n\t\t\t\tstep: \"ancestry\",\n\t\t\t\tcode: \"not-ancestor\",\n\t\t\t\tmessage: `block ${claimed} is not on the checkpoint's chain: its block at height ${height} is ${id}`,\n\t\t\t\tblockId: claimed,\n\t\t\t});\n\t\tthis.passed(\"ancestry\");\n\t\tconst header = await this.header(id, \"block\");\n\t\tif (Number(header.chainLength) !== height)\n\t\t\tfail({\n\t\t\t\tstep: \"block\",\n\t\t\t\tcode: \"height-mismatch\",\n\t\t\t\tmessage: `block ${id} claims height ${header.chainLength}, proven at ${height}`,\n\t\t\t});\n\t\tout.blockId = id;\n\t\tdescribeHeader(header, out);\n\t\tthis.passed(\"block\");\n\t\tawait this.bindBurnBelow(header, out);\n\t\tawait this.checkTransactions(header, id, out);\n\t\tawait this.verifyState(header, id, out);\n\t}\n\n\tprivate rememberRaw(id: string, raw: Bytes): void {\n\t\tthis.raws.delete(id);\n\t\tthis.raws.set(id, raw);\n\t\twhile (this.raws.size > 4) {\n\t\t\tconst oldest = this.raws.keys().next().value as string;\n\t\t\tthis.raws.delete(oldest);\n\t\t}\n\t}\n\n\t/**\n\t * The block's transactions against the authenticated header's\n\t * tx_merkle_root: binds every txid, sender, type and call target to the\n\t * signed (or hash-linked) header.\n\t */\n\tprivate async checkTransactions(\n\t\theader: StacksHeader,\n\t\tid: string,\n\t\tout: BlockVerification,\n\t): Promise<void> {\n\t\tif (isEpoch2Header(header)) {\n\t\t\tout.notes.push(\"epoch 2.x: transactions not checked\");\n\t\t\treturn;\n\t\t}\n\t\tconst raw =\n\t\t\tthis.raws.get(id) ??\n\t\t\t(await fetchFor(\"txs\", `block ${id}`, () => this.source.getBlock(id)));\n\t\tlet txs: BlockTransaction[] | null;\n\t\ttry {\n\t\t\ttxs = blockTransactions(raw, header);\n\t\t} catch (err) {\n\t\t\tif (!(err instanceof TransactionsError)) throw err;\n\t\t\treturn fail({ step: \"txs\", code: err.code, message: err.message });\n\t\t}\n\t\tif (txs === null) {\n\t\t\tout.notes.push(\n\t\t\t\t`transactions not checked: the source served block ${id}'s header only`,\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tout.transactions = txs;\n\t\tthis.passed(\"txs\");\n\t}\n\n\t/**\n\t * The checkpoint chain's block id at `height`, from the nearest trusted\n\t * block above it: parent links when within MAX_WALK, else one MARF proof.\n\t */\n\tprivate async ancestor(\n\t\theight: number,\n\t): Promise<{ id: string; ancestry: Ancestry }> {\n\t\tconst known = this.below.get(height);\n\t\tif (known) return known;\n\t\tconst from = this.nearestAbove(height);\n\t\tif (from.height - height <= MAX_WALK) {\n\t\t\tconst walked = await this.walk(from, height);\n\t\t\tif (walked) return walked;\n\t\t}\n\t\treturn this.jump(this.nearestAbove(height), height);\n\t}\n\n\t/** The lowest trusted block above `height`: the checkpoint or one proven below it. */\n\tprivate nearestAbove(height: number): { height: number; id: string } {\n\t\tlet best = {\n\t\t\theight: Number(this.start.header.chainLength),\n\t\t\tid: this.start.id,\n\t\t};\n\t\tfor (const [h, { id }] of this.below)\n\t\t\tif (h > height && h < best.height) best = { height: h, id };\n\t\treturn best;\n\t}\n\n\t/**\n\t * Follow parent ids down from `from`: each parent header must hash to the\n\t * id its child committed to. Null when a 2.x header stops the walk: it\n\t * commits to its parent's block hash, not the parent's id.\n\t */\n\tprivate async walk(\n\t\tfrom: { height: number; id: string },\n\t\theight: number,\n\t): Promise<{ id: string; ancestry: Ancestry } | null> {\n\t\tconst ancestry: Ancestry = {\n\t\t\tfromHeight: from.height,\n\t\t\tfromBlockId: from.id,\n\t\t\tvia: \"parents\",\n\t\t};\n\t\tlet child = await this.header(from.id, \"ancestry\");\n\t\tfor (let h = from.height - 1; h >= height; h--) {\n\t\t\tif (isEpoch2Header(child)) return null;\n\t\t\tconst id = hex(child.parentBlockId);\n\t\t\tconst parent = await this.header(id, \"ancestry\", { blockId: id });\n\t\t\tif (Number(parent.chainLength) !== h)\n\t\t\t\tfail({\n\t\t\t\t\tstep: \"ancestry\",\n\t\t\t\t\tcode: \"height-mismatch\",\n\t\t\t\t\tmessage: `parent ${id} claims height ${parent.chainLength}, expected ${h}`,\n\t\t\t\t\tblockId: id,\n\t\t\t\t});\n\t\t\tthis.below.set(h, { id, ancestry });\n\t\t\tchild = parent;\n\t\t}\n\t\treturn this.below.get(height) ?? null;\n\t}\n\n\t/**\n\t * Read the id at `height` from `from`'s state: block `height + 1` wrote it\n\t * to `__MARF_BLOCK_HEIGHT_TO_HASH::<height>`, and the proof must recompute\n\t * `from`'s state root through the header of every trie it crosses.\n\t */\n\tprivate async jump(\n\t\tfrom: { height: number; id: string },\n\t\theight: number,\n\t): Promise<{ id: string; ancestry: Ancestry }> {\n\t\tconst at = { blockId: from.id };\n\t\tconst tip = await this.header(from.id, \"ancestry\", at);\n\t\tconst key = heightToHashKey(height);\n\t\tconst path = marfPath(key);\n\t\tconst answer = await fetchFor(\n\t\t\t\"ancestry\",\n\t\t\t`${key} at ${from.id}`,\n\t\t\t() => this.source.getMarfProof(hex(path), from.id),\n\t\t\tat,\n\t\t);\n\t\tif (!answer)\n\t\t\treturn fail({\n\t\t\t\tstep: \"ancestry\",\n\t\t\t\tcode: \"unavailable\",\n\t\t\t\tmessage: `source has no MARF proof of ${key} at block ${from.height}, ${from.height - height} blocks up; parent links reach ${MAX_WALK}`,\n\t\t\t\t...at,\n\t\t\t});\n\t\t// A block id fills the first 32 bytes of the MARFValue; the tail is zero.\n\t\tconst value = marfProofValue(answer.proof) ?? new Uint8Array();\n\t\tconst proven =\n\t\t\tvalue.length === MARF_VALUE_SIZE &&\n\t\t\tvalue.subarray(32).every((b) => b === 0) &&\n\t\t\t(await this.proveAt(tip, path, value, answer.proof, \"ancestry\", at));\n\t\tif (!proven)\n\t\t\treturn fail({\n\t\t\t\tstep: \"ancestry\",\n\t\t\t\tcode: \"ancestry-proof-invalid\",\n\t\t\t\tmessage: `${key} is not proven in block ${from.height}'s state`,\n\t\t\t\t...at,\n\t\t\t});\n\t\tconst ancestry: Ancestry = {\n\t\t\tfromHeight: from.height,\n\t\t\tfromBlockId: from.id,\n\t\t\tvia: \"marf\",\n\t\t};\n\t\tconst found = { id: hex(value.subarray(0, 32)), ancestry };\n\t\tthis.below.set(height, found);\n\t\treturn found;\n\t}\n\n\t/**\n\t * Below the checkpoint the hash chain already pins the block; still bind\n\t * its burn block when the Bitcoin checkpoint reaches it. The burn height\n\t * here is the source's hint, so a low one only skips this extra check.\n\t */\n\tprivate async bindBurnBelow(\n\t\theader: StacksHeader,\n\t\tout: BlockVerification,\n\t): Promise<void> {\n\t\tlet hint: number;\n\t\ttry {\n\t\t\thint = await this.burnHint(header);\n\t\t} catch (err) {\n\t\t\tout.notes.push(`burn block not checked: ${(err as Error).message}`);\n\t\t\treturn;\n\t\t}\n\t\tif (hint < this.chain.checkpointHeight) {\n\t\t\tout.notes.push(\n\t\t\t\t`burn block not checked: its height ${hint} is below the Bitcoin checkpoint ${this.chain.checkpointHeight}`,\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tconst burn = await this.bindBurn(header, \"burn\");\n\t\tout.burnHeight = burn.burnHeight;\n\t\tout.bitcoinBlockHash = burn.hash;\n\t\tthis.passed(\"bitcoin\");\n\t\tthis.passed(\"burn\");\n\t}\n\n\t/** Witness against the authenticated header's root, then the named diff and rows. */\n\tprivate async verifyState(\n\t\theader: StacksHeader,\n\t\tid: string,\n\t\tout: BlockVerification,\n\t): Promise<void> {\n\t\tconst src = this.source;\n\t\tconst height = Number(header.chainLength);\n\t\tconst witness = await fetchFor(\"witness\", `witness ${id}`, () =>\n\t\t\tsrc.getWitness(id),\n\t\t);\n\t\tconst writes = await this.stateWrites(height, out.notes);\n\t\tif (writes) out.writes = writes;\n\t\tconst { getVmEvents }: Partial<ProofSource> = this.rows ? src : {};\n\t\tconst rows = getVmEvents\n\t\t\t? await fetchFor(\"rows\", `vm_events ${height}`, () =>\n\t\t\t\t\tgetVmEvents.call(src, height),\n\t\t\t\t)\n\t\t\t: undefined;\n\t\tconst parent = isEpoch2Header(header)\n\t\t\t? epoch2ParentId(witness, header)\n\t\t\t: header.parentBlockId;\n\t\tconst parentId = parent && hex(parent);\n\t\tconst state = await verifyBlockState({\n\t\t\theight,\n\t\t\t// Null only when the witness fails its root check, which fails the block.\n\t\t\tparentBlockId: parent ?? new Uint8Array(32),\n\t\t\tstateRoot: header.stateIndexRoot,\n\t\t\twitness,\n\t\t\twrites,\n\t\t\trows,\n\t\t\tparentLeaves: parentId\n\t\t\t\t? await this.parentLeaves(parentId, out.notes)\n\t\t\t\t: undefined,\n\t\t\tparentHolds: async (leaf) =>\n\t\t\t\tparentId ? this.parentHolds(parentId, leaf) : false,\n\t\t});\n\t\tout.diff = state.diff;\n\t\tif (rows) out.rowsChecked = state.rowsChecked;\n\t\tout.notes.push(...state.notes);\n\t\tout.failures.push(...state.failures);\n\t\t// Links pass in order up to the first one with a failure.\n\t\tconst broken = new Set(state.failures.map((f) => f.step));\n\t\tfor (const step of [\"witness\", \"names\", \"rows\"] as const) {\n\t\t\tif (broken.has(step) || (step === \"rows\" && !rows)) break;\n\t\t\tthis.passed(step);\n\t\t}\n\t}\n\n\t/**\n\t * The block's state writes, to name its diff. Optional evidence: a source\n\t * with none for the block (404, empty) or that fails leaves the diff\n\t * proven but unnamed, with a note, never a failure.\n\t */\n\tprivate async stateWrites(\n\t\theight: number,\n\t\tnotes: string[],\n\t): Promise<StateWrite[] | null> {\n\t\tconst { getStateWrites } = this.source;\n\t\tif (!getStateWrites) return null;\n\t\ttry {\n\t\t\tconst writes = await getStateWrites.call(this.source, height);\n\t\t\treturn writes?.length ? writes : null;\n\t\t} catch (err) {\n\t\t\tnotes.push(\n\t\t\t\t`state writes for block ${height} unavailable: ${(err as Error).message}`,\n\t\t\t);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/** Header by id, from the cache or the source; it must hash to `id`. */\n\tprivate async header(\n\t\tid: string,\n\t\tstep: VerifyStep,\n\t\textra: Partial<VerifyFailure> = {},\n\t): Promise<StacksHeader> {\n\t\tconst known = this.headers.get(id);\n\t\tif (known) return known;\n\t\tconst header = await this.fetchHeader(id, step, extra);\n\t\tif (hex(blockId(header)) !== id)\n\t\t\tfail({\n\t\t\t\tstep,\n\t\t\t\tcode: \"id-mismatch\",\n\t\t\t\tmessage: `source returned another block for ${id}`,\n\t\t\t\tblockId: id,\n\t\t\t\t...extra,\n\t\t\t});\n\t\tthis.headers.set(id, header);\n\t\treturn header;\n\t}\n\n\t/**\n\t * A Nakamoto block by id, or when the source has none (epoch 2.x blocks are\n\t * not served as Nakamoto blocks) its epoch 2.x header.\n\t */\n\tprivate async fetchHeader(\n\t\tid: string,\n\t\tstep: VerifyStep,\n\t\textra: Partial<VerifyFailure>,\n\t): Promise<StacksHeader> {\n\t\tconst src = this.source;\n\t\tlet raw: Bytes;\n\t\ttry {\n\t\t\traw = await src.getBlock(id);\n\t\t\tthis.rememberRaw(id, raw);\n\t\t} catch (err) {\n\t\t\tconst reason = `block ${id}: ${(err as Error).message}`;\n\t\t\tconst { getEpoch2Header } = src;\n\t\t\tif (!getEpoch2Header)\n\t\t\t\treturn fail({ step, code: \"unavailable\", message: reason, ...extra });\n\t\t\tconst e2 = await fetchFor(\n\t\t\t\tstep,\n\t\t\t\t`${reason}; epoch 2.x header`,\n\t\t\t\t() => getEpoch2Header.call(src, id),\n\t\t\t\textra,\n\t\t\t);\n\t\t\ttry {\n\t\t\t\treturn parseEpoch2Header(e2.header, e2.consensusHash);\n\t\t\t} catch (parseErr) {\n\t\t\t\treturn fail({\n\t\t\t\t\tstep,\n\t\t\t\t\tcode: \"invalid-header\",\n\t\t\t\t\tmessage: `epoch 2.x header ${id} does not parse: ${(parseErr as Error).message}`,\n\t\t\t\t\t...extra,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\treturn parseHeader(raw, step);\n\t}\n\n\t/**\n\t * Prove `value` at `path` in `tip`'s state, fetching the header of every\n\t * ancestor trie the proof crosses.\n\t */\n\tprivate async proveAt(\n\t\ttip: StacksHeader,\n\t\tpath: Bytes,\n\t\tvalue: Bytes,\n\t\tproof: Bytes,\n\t\tstep: VerifyStep,\n\t\textra: Partial<VerifyFailure> = {},\n\t): Promise<boolean> {\n\t\tconst headers = [tip];\n\t\tfor (const id of marfProofAncestors(proof))\n\t\t\theaders.push(await this.header(id, step, extra));\n\t\treturn verifyMarfProof({\n\t\t\tproof,\n\t\t\tpath,\n\t\t\tvalue,\n\t\t\troot: tip.stateIndexRoot,\n\t\t\theaders,\n\t\t});\n\t}\n\n\t/**\n\t * The parent's own trie leaves, from its witness checked against the\n\t * parent header. Optional evidence: when the source cannot serve it,\n\t * carried leaves fall back to per-leaf proofs (named) or stay unlabeled.\n\t */\n\tprivate async parentLeaves(\n\t\tparentId: string,\n\t\tnotes: string[],\n\t): Promise<WitnessLeaf[] | undefined> {\n\t\ttry {\n\t\t\tconst parent = await this.header(parentId, \"names\");\n\t\t\tconst w = parseWitness(await this.source.getWitness(parentId));\n\t\t\tif (bytesEqual(w.root, parent.stateIndexRoot)) return w.leaves;\n\t\t\tnotes.push(`parent witness ${parentId} root does not match its header`);\n\t\t} catch (err) {\n\t\t\tnotes.push(\n\t\t\t\t`parent witness ${parentId} unavailable: ${(err as Error).message}`,\n\t\t\t);\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * A carried leaf holds the parent's value. The parent header is\n\t * authenticated by hash: its id is committed in the authenticated child\n\t * (its header, or for 2.x its own trie).\n\t */\n\tprivate async parentHolds(\n\t\tparentId: string,\n\t\tleaf: WitnessLeaf,\n\t): Promise<boolean> {\n\t\tconst parent = await this.header(parentId, \"names\");\n\t\tconst pathHex = hex(leaf.path);\n\t\tconst answer = await fetchFor(\"names\", `MARF ${pathHex} at parent`, () =>\n\t\t\tthis.source.getMarfProof(pathHex, parentId),\n\t\t);\n\t\tif (!answer) return false;\n\t\tconst value = new Uint8Array(MARF_VALUE_SIZE);\n\t\tvalue.set(leaf.valueHash);\n\t\treturn this.proveAt(parent, leaf.path, value, answer.proof, \"names\");\n\t}\n\n\t/** Consensus hash -> PoW-verified burn block, via the sortition preimage. */\n\tprivate async bindBurn(\n\t\theader: StacksHeader,\n\t\tstep: VerifyStep,\n\t\textra: Partial<VerifyFailure> = {},\n\t): Promise<{ burnHeight: number; hash: string }> {\n\t\tconst ch = hex(header.consensusHash);\n\t\tconst known = this.burns.get(ch);\n\t\tif (known) return known;\n\t\tconst bp = await fetchFor(\n\t\t\tstep,\n\t\t\t`burn preimage ${ch}`,\n\t\t\t() => this.preimage(ch),\n\t\t\textra,\n\t\t);\n\t\tconst hash = verifyConsensusPreimage(header.consensusHash, bp.preimage);\n\t\tif (!hash)\n\t\t\treturn fail({\n\t\t\t\tstep,\n\t\t\t\tcode: \"preimage-mismatch\",\n\t\t\t\tmessage: `preimage does not hash to consensus hash ${ch}`,\n\t\t\t\t...extra,\n\t\t\t});\n\t\tif (bp.burnHeight < this.chain.checkpointHeight)\n\t\t\tfail({\n\t\t\t\tstep,\n\t\t\t\tcode: \"before-checkpoint\",\n\t\t\t\tmessage: `burn height ${bp.burnHeight} is below the Bitcoin checkpoint ${this.chain.checkpointHeight}`,\n\t\t\t\t...extra,\n\t\t\t});\n\t\tawait this.syncBitcoin(bp.burnHeight);\n\t\tconst burnHeight = this.chain.heightOf(hash);\n\t\tif (burnHeight === undefined)\n\t\t\treturn fail({\n\t\t\t\tstep,\n\t\t\t\tcode: \"burn-not-in-chain\",\n\t\t\t\tmessage: `burn block ${hash} is not in the verified Bitcoin chain (synced ${this.chain.checkpointHeight}..${this.chain.tip.height})`,\n\t\t\t\t...extra,\n\t\t\t});\n\t\tconst bound = { burnHeight, hash };\n\t\tthis.burns.set(ch, bound);\n\t\treturn bound;\n\t}\n\n\t/** Extend the Bitcoin chain to `height`, validating PoW, retarget and MTP. */\n\tprivate async syncBitcoin(height: number): Promise<void> {\n\t\twhile (this.chain.tip.height < height) {\n\t\t\tconst from = this.chain.tip.height + 1;\n\t\t\tconst count = Math.min(BITCOIN_BATCH, height - from + 1);\n\t\t\tconst headers = await fetchFor(\"bitcoin\", `bitcoin headers ${from}`, () =>\n\t\t\t\tthis.source.getBitcoinHeaders(from, count),\n\t\t\t);\n\t\t\tif (headers.length === 0)\n\t\t\t\tfail({\n\t\t\t\t\tstep: \"bitcoin\",\n\t\t\t\t\tcode: \"unavailable\",\n\t\t\t\t\tmessage: `source has no Bitcoin headers from ${from}`,\n\t\t\t\t});\n\t\t\ttry {\n\t\t\t\tthis.chain.append(headers);\n\t\t\t} catch (err) {\n\t\t\t\tif (!(err instanceof HeaderValidationError)) throw err;\n\t\t\t\tfail({ step: \"bitcoin\", code: \"invalid-header\", message: err.message });\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * The proven signer set for `cycle`. Walks forward from the checkpoint:\n\t * set c+1 is read from an anchor block in c+1's prepare phase, whose\n\t * header set c signed.\n\t */\n\tprivate async signerSet(\n\t\tcycle: number,\n\t\ttarget: SearchPoint,\n\t): Promise<SignerSet> {\n\t\tconst known = this.sets.get(cycle);\n\t\tif (known) return known;\n\t\tconst first = this.checkpoint.stacks.cycle;\n\t\tif (cycle < first)\n\t\t\tfail({\n\t\t\t\tstep: \"signer-set\",\n\t\t\t\tcode: \"before-checkpoint\",\n\t\t\t\tmessage: `cycle ${cycle} precedes the checkpoint's cycle ${first}`,\n\t\t\t\tcycle,\n\t\t\t});\n\t\tlet lo = await this.startPoint();\n\t\tfor (let c = first; c < cycle; c++) {\n\t\t\tconst next = this.sets.get(c + 1);\n\t\t\tif (next) {\n\t\t\t\tlo = this.anchors.get(c + 1) ?? lo;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst anchor = await this.locateAnchor(c + 1, lo, target);\n\t\t\tthis.sets.set(c + 1, await this.proveNextSet(c + 1, anchor));\n\t\t\tthis.anchors.set(c + 1, anchor);\n\t\t\tlo = anchor;\n\t\t}\n\t\treturn this.sets.get(cycle) as SignerSet;\n\t}\n\n\t/** The checkpoint block as a search bound; its burn height is a source hint. */\n\tprivate async startPoint(): Promise<SearchPoint> {\n\t\tconst { header } = this.start;\n\t\tconst height = Number(header.chainLength);\n\t\ttry {\n\t\t\treturn { height, burn: await this.burnHint(header) };\n\t\t} catch {\n\t\t\treturn { height };\n\t\t}\n\t}\n\n\tprivate async burnHint(header: StacksHeader): Promise<number> {\n\t\tconst ch = hex(header.consensusHash);\n\t\treturn (\n\t\t\tthis.burns.get(ch)?.burnHeight ?? (await this.preimage(ch)).burnHeight\n\t\t);\n\t}\n\n\tprivate async preimage(ch: string): Promise<BurnPreimage> {\n\t\tlet bp = this.preimages.get(ch);\n\t\tif (!bp) {\n\t\t\tbp = await this.source.getBurnPreimage(ch);\n\t\t\tthis.preimages.set(ch, bp);\n\t\t}\n\t\treturn bp;\n\t}\n\n\tprivate async locateAnchor(\n\t\tcycle: number,\n\t\tlo: SearchPoint,\n\t\thi: SearchPoint,\n\t): Promise<Probe> {\n\t\tconst start = cycleStart(cycle);\n\t\tconst window = [start - MAINNET_PREPARE_LENGTH, start] as const;\n\t\tconst probe = async (h: number): Promise<Probe> => {\n\t\t\tconst raw = await fetchFor(\n\t\t\t\t\"signer-set\",\n\t\t\t\t`block at height ${h}`,\n\t\t\t\t() => this.source.getBlock(h),\n\t\t\t\t{ cycle },\n\t\t\t);\n\t\t\tconst header = parseHeader(raw, \"signer-set\");\n\t\t\tconst id = hex(blockId(header));\n\t\t\tthis.headers.set(id, header);\n\t\t\tconst burn = await fetchFor(\n\t\t\t\t\"signer-set\",\n\t\t\t\t`burn hint for block ${id}`,\n\t\t\t\t() => this.burnHint(header),\n\t\t\t\t{ cycle, blockId: id },\n\t\t\t);\n\t\t\treturn { height: Number(header.chainLength), burn, header, id };\n\t\t};\n\t\tconst anchor = await findAnchor(lo, hi, window, probe);\n\t\tif (!anchor)\n\t\t\treturn fail({\n\t\t\t\tstep: \"signer-set\",\n\t\t\t\tcode: \"anchor-not-found\",\n\t\t\t\tmessage: `no block with a burn height in ${window[0]}..${window[1] - 1} (cycle ${cycle} prepare phase) between heights ${lo.height} and ${hi.height}`,\n\t\t\t\tcycle,\n\t\t\t});\n\t\treturn anchor;\n\t}\n\n\t/**\n\t * Set `cycle` from `anchor`: the anchor must be bound to a burn block in\n\t * `cycle`'s prepare phase, be signed by the set of the cycle that burn\n\t * height dictates (`cycle - 1`), and hold set `cycle` in its state (MARF\n\t * proof). Adjacent sets overlap enough that one block can clear both, so\n\t * the set is always chosen by proven burn height, never by which passes.\n\t */\n\tprivate async proveNextSet(cycle: number, anchor: Probe): Promise<SignerSet> {\n\t\tconst at = { cycle, blockId: anchor.id };\n\t\tconst { burnHeight } = await this.bindBurn(anchor.header, \"signer-set\", at);\n\t\tconst start = cycleStart(cycle);\n\t\tif (burnHeight < start - MAINNET_PREPARE_LENGTH || burnHeight >= start)\n\t\t\tfail({\n\t\t\t\tstep: \"signer-set\",\n\t\t\t\tcode: \"anchor-outside-window\",\n\t\t\t\tmessage: `anchor burn height ${burnHeight} is outside cycle ${cycle}'s prepare phase ${start - MAINNET_PREPARE_LENGTH}..${start - 1}`,\n\t\t\t\t...at,\n\t\t\t});\n\t\tconst signing = rewardCycle(burnHeight);\n\t\tconst sig = verifySignerSignatures(\n\t\t\tanchor.header,\n\t\t\tthis.sets.get(signing) as SignerSet,\n\t\t);\n\t\tif (!sig.valid)\n\t\t\tfail({\n\t\t\t\t...signatureFailure(sig, \"signer-set\", signing),\n\t\t\t\t...at,\n\t\t\t\tcode: \"anchor-unsigned\",\n\t\t\t});\n\n\t\tconst path = marfPath(\n\t\t\tmapEntryKey(SIGNERS_CONTRACT, \"cycle-signer-set\", uintCV(cycle)),\n\t\t);\n\t\tconst answer = await fetchFor(\n\t\t\t\"signer-set\",\n\t\t\t`signer set ${cycle} at ${anchor.id}`,\n\t\t\t() => this.source.getMarfProof(hex(path), anchor.id),\n\t\t\tat,\n\t\t);\n\t\tconst value = answer?.data.replace(/^0x/, \"\") ?? \"\";\n\t\tconst proven =\n\t\t\tanswer !== null &&\n\t\t\t(await this.proveAt(\n\t\t\t\tanchor.header,\n\t\t\t\tpath,\n\t\t\t\tmarfValue(value),\n\t\t\t\tanswer.proof,\n\t\t\t\t\"signer-set\",\n\t\t\t\tat,\n\t\t\t));\n\t\tif (!proven)\n\t\t\tfail({\n\t\t\t\tstep: \"signer-set\",\n\t\t\t\tcode: \"set-proof-invalid\",\n\t\t\t\tmessage: `signer set ${cycle} is not proven in anchor ${anchor.id}'s state`,\n\t\t\t\t...at,\n\t\t\t});\n\t\tlet set: SignerSet;\n\t\ttry {\n\t\t\tset = decodeSignerSet(value);\n\t\t} catch (err) {\n\t\t\treturn fail({\n\t\t\t\tstep: \"signer-set\",\n\t\t\t\tcode: \"set-proof-invalid\",\n\t\t\t\tmessage: `signer set ${cycle}: ${(err as Error).message}`,\n\t\t\t\t...at,\n\t\t\t});\n\t\t}\n\t\treturn set;\n\t}\n}\n\n/** The authenticated header's identity fields, for callers that rebuild the block. */\nfunction describeHeader(header: StacksHeader, out: BlockVerification): void {\n\tout.stateRoot = hex(header.stateIndexRoot);\n\tout.consensusHash = hex(header.consensusHash);\n\tif (!isEpoch2Header(header)) {\n\t\tout.blockHash = hex(signerSignatureHash(header));\n\t\tout.timestamp = Number(header.timestamp);\n\t}\n}\n\nfunction parseHeader(raw: Bytes, step: VerifyStep): NakamotoHeader {\n\ttry {\n\t\treturn parseNakamotoHeader(raw);\n\t} catch (err) {\n\t\treturn fail({\n\t\t\tstep,\n\t\t\tcode: \"invalid-header\",\n\t\t\tmessage: `block bytes do not parse: ${(err as Error).message}`,\n\t\t});\n\t}\n}\n\n/**\n * A 2.x header commits only to its parent's block hash; the parent's id is in\n * the block's own trie at `__MARF_BLOCK_HEIGHT_TO_HASH::<height - 1>`. Read\n * from a witness whose root matches the header, else null.\n */\nfunction epoch2ParentId(witness: Bytes, header: Epoch2Header): Bytes | null {\n\tconst height = Number(header.chainLength);\n\tif (height === 0) return null;\n\ttry {\n\t\tconst w = parseWitness(witness);\n\t\tif (!bytesEqual(w.root, header.stateIndexRoot)) return null;\n\t\tconst path = marfPath(heightToHashKey(height - 1));\n\t\treturn w.leaves.find((l) => bytesEqual(l.path, path))?.valueHash ?? null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction signatureFailure(\n\tsig: ReturnType<typeof verifySignerSignatures>,\n\tstep: VerifyStep,\n\tcycle: number,\n): VerifyFailure {\n\tconst weight = `${sig.signedWeight}/${sig.totalWeight} signed, threshold ${sig.threshold}`;\n\tif (sig.unknown.length)\n\t\treturn {\n\t\t\tstep,\n\t\t\tcode: \"unknown-signer\",\n\t\t\tmessage: `${sig.unknown.length} signer(s) not in cycle ${cycle}'s set (${weight})`,\n\t\t\tcycle,\n\t\t};\n\tif (sig.duplicates.length)\n\t\treturn {\n\t\t\tstep,\n\t\t\tcode: \"duplicate-signer\",\n\t\t\tmessage: `${sig.duplicates.length} duplicate signature(s) (${weight})`,\n\t\t\tcycle,\n\t\t};\n\tif (sig.invalid)\n\t\treturn {\n\t\t\tstep,\n\t\t\tcode: \"bad-signature\",\n\t\t\tmessage: `${sig.invalid} signature(s) do not recover (${weight})`,\n\t\t\tcycle,\n\t\t};\n\treturn {\n\t\tstep,\n\t\tcode: \"below-threshold\",\n\t\tmessage: `cycle ${cycle} signers: ${weight}`,\n\t\tcycle,\n\t};\n}\n\n/** One-shot: verify a block from a checkpoint (MAINNET_CHECKPOINT by default). */\nexport const verifyBlock = (\n\tref: string | number,\n\topts: VerifyOptions,\n): Promise<BlockVerification> => new BlockVerifier(opts).verify(ref);\n"
21
21
  ],
22
- "mappings": ";AACA;AACA;AAKO,IAAM,MAAM,CAAC,MAAqB,WAAW,CAAC;AAG9C,IAAM,QAAQ,CAAC,MACrB,WAAW,EAAE,WAAW,IAAI,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC;AAExC,IAAM,SAAS,CAAC,UAA0B,YAAY,GAAG,KAAK;AAE9D,IAAM,aAAa,CAAC,GAAU,MAAsB;AAAA,EAC1D,IAAI,EAAE,WAAW,EAAE;AAAA,IAAQ,OAAO;AAAA,EAClC,SAAS,IAAI,EAAG,IAAI,EAAE,QAAQ;AAAA,IAAK,IAAI,EAAE,OAAO,EAAE;AAAA,MAAI,OAAO;AAAA,EAC7D,OAAO;AAAA;AAID,IAAM,UAAU,CAAC,UAA0B;AAAA,EACjD,MAAM,IAAI,WAAW,OAAO;AAAA,EAC5B,WAAW,KAAK;AAAA,IAAO,EAAE,OAAO,CAAC;AAAA,EACjC,OAAO,EAAE,OAAO;AAAA;AAAA;AAIV,MAAM,OAAO;AAAA,EAEE;AAAA,EADrB,MAAM;AAAA,EACN,WAAW,CAAU,KAAY;AAAA,IAAZ;AAAA;AAAA,EAErB,KAAK,CAAC,GAAkB;AAAA,IACvB,IAAI,IAAI,KAAK,KAAK,MAAM,IAAI,KAAK,IAAI;AAAA,MACpC,MAAM,IAAI,MAAM,8BAA8B,KAAK,eAAe,GAAG;AAAA,IACtE,MAAM,MAAM,KAAK,IAAI,SAAS,KAAK,KAAK,KAAK,MAAM,CAAC;AAAA,IACpD,KAAK,OAAO;AAAA,IACZ,OAAO;AAAA;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ACN;AAAA,MACA,MAAM;AAAA,MACN,SAAS,GAAG,IAAI,WAAW,kCAAkC;AAAA,MAC7D;AAAA,IACD;AAAA,EACD,IAAI,IAAI;AAAA,IACP,OAAO;AAAA,MACN;AAAA,MACA,MAAM;AAAA,MACN,SAAS,GAAG,IAAI,wCAAwC;AAAA,MACxD;AAAA,IACD;AAAA,EACD,OAAO;AAAA,IACN;AAAA,IACA,MAAM;AAAA,IACN,SAAS,SAAS,kBAAkB;AAAA,IACpC;AAAA,EACD;AAAA;AAIM,IAAM,cAAc,CAC1B,KACA,SACgC,IAAI,cAAc,IAAI,EAAE,OAAO,GAAG;",
23
23
  "debugId": "C611E693588430B164756E2164756E21",
24
24
  "names": []
25
25
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@secondlayer/verify",
3
- "version": "0.5.3",
3
+ "version": "0.5.4",
4
4
  "description": "Check a Stacks block yourself: Bitcoin headers, signer signatures and MARF state proofs, from one trusted checkpoint.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -31,7 +31,7 @@
31
31
  "dependencies": {
32
32
  "@noble/curves": "2.0.1",
33
33
  "@noble/hashes": "2.0.1",
34
- "@secondlayer/stacks": "^6.2.1"
34
+ "@secondlayer/stacks": "^6.2.2"
35
35
  },
36
36
  "devDependencies": {
37
37
  "@types/bun": "latest",