@secondlayer/verify 0.0.0-stage → 0.2.0

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.
@@ -0,0 +1,23 @@
1
+ {
2
+ "version": 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.ts", "../src/source.ts", "../src/state.ts", "../src/verify-block.ts"],
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\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 * NakamotoBlockHeader::signer_signature_hash: sha512/256 over every header field\n * except the signer signatures. 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 * Parse the epoch 2.x StacksBlockHeader at the start of `raw` (a header from\n * `/v2/headers`, or block bytes from `/v2/blocks/<id>`), with the 20-byte\n * consensus hash of the sortition that elected it.\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\nexport const isEpoch2Header = (h: StacksHeader): h is Epoch2Header =>\n\t\"parentBlockHash\" in h;\n\n/**\n * StacksBlockId (index block hash) = sha512/256(block_hash || consensus_hash).\n * A Nakamoto block hash is its signer signature hash; a 2.x one hashes the\n * 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/** TrieHash::from_key: sha512/256(utf8(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/** MARFValue::from_value: sha512/256(utf8(value)) 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 * Block ids of the ancestor tries a proof crosses: each one is the backptr a\n * descendant trie follows toward the leaf. `verifyMarfProof` needs every one's\n * header. Read from untrusted proof bytes, so they are only fetch hints; the\n * proof still fails unless each header hashes to the id the trie committed.\n * 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 * TrieMerkleProof::verify. True iff `value` is stored at `path` in the MARF\n * whose tip root is `root`. Inclusion only: MARF proofs cannot prove absence.\n * Malformed proof 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 * Decode the `.signers` `cycle-signer-set` map value (hex or bytes, as stored\n * in the MARF): `(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 * Recover each header signature's key over signer_signature_hash, map it to\n * its mainnet p2pkh principal, and sum weights from `set`. The set must be the\n * 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
+ "// 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;\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
+ "// 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/** `vm::<contract>::0::<map>::<serialized key hex>` (make_key_for_data_map_entry). */\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/** `vm::<contract>::1::<var>` (make_key_for_trip, StoreType::Variable). */\nexport function dataVarKey(contractId: string, varName: string): string {\n\treturn `vm::${contractId}::${StoreType.Variable}::${varName}`;\n}\n\n/**\n * `vm::<contract>::2::<token>::<principal json>` (get_ft_balance). The holder\n * 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\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\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\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\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
+ "/**\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
+ "/**\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
+ "// Trusted starting point baked into each release. Everything verifyBlock\n// proves is relative to it: a Stacks block whose state holds one cycle's\n// signer set, and a Bitcoin header to sync proof-of-work from.\n//\n// Bump it once per release so the signer-set walk stays short:\n// 1. Pick a recent reward cycle C and a canonical Stacks block X whose burn\n// block is in C-1's prepare phase or later (its state holds set C).\n// 2. Fetch X's raw block (`/v3/blocks/<id>`, keep the header bytes) and\n// `cycle-signer-set[C]` with its proof at X (`/v2/clarity/marf/<path>?tip=X&proof=1`,\n// key `mapEntryKey(SIGNERS_CONTRACT, \"cycle-signer-set\", uintCV(C))`).\n// 3. Bitcoin: the retarget-period start (a multiple of 2016) at or below C's\n// first burn block, 666050 + 2100 * C. Blocks above X whose burn height\n// is below the Bitcoin checkpoint cannot be verified; blocks below X are\n// verified by hash chain from X instead.\n// 4. Add X's header, its proof ancestors and the set proof to test/fixtures:\n// the checkpoint test re-proves the baked set against X.\nimport type { Checkpoint } from \"./bitcoin/chain.ts\";\n\nexport interface VerifyCheckpoint {\n\tstacks: {\n\t\t/** Raw Nakamoto header (hex) of a trusted block whose state holds `signerSet`. */\n\t\theader: string;\n\t\t/** Reward cycle `signerSet` belongs to. */\n\t\tcycle: number;\n\t\t/** `.signers` `cycle-signer-set[cycle]` as stored: hex of `(some (list ...))`. */\n\t\tsignerSet: string;\n\t};\n\t/** Retarget-boundary Bitcoin header at or below the first burn block of `stacks.cycle`. */\n\tbitcoin: Checkpoint;\n}\n\n/**\n * Mainnet: Stacks block 8,956,304 (`3914ea5f…74bb`) holding the cycle 143\n * signer set (29 signers, weight 4000), and Bitcoin block 967,680 (a\n * retarget-period start inside cycle 143). Later blocks verify forward\n * (burn height 967,680 or later); earlier ones by hash chain from 8,956,304.\n */\nexport const MAINNET_CHECKPOINT: VerifyCheckpoint = {\n\tstacks: {\n\t\theader: [\n\t\t\t\"01000000000088a9900000006629951a50e3616a1c1e0b8c05ba66615c7065053804c56e2a68dc605cf905df5a754c57\",\n\t\t\t\"144e9ddde1191353b05f1a5e6d3c99244aeb006ba4f4db761cb1efecfb92693a8c08fefc766a4cd5ccfcb8f13789a809\",\n\t\t\t\"e7ee0c2e6b7dfb64868cf1e4e6acc50513202acfab84553454b433248c0ef06cebda3c734c000000006aa28bfd013be3\",\n\t\t\t\"826a60039f518d7021a4799f2e083dafaaaac7a2d56fda601d674d596d3046b9bbcd52e79fba491e54d92fdab0ca3ab9\",\n\t\t\t\"9ccf346c6e6726fbd4c8579a02b80000000d0004f2d135dd684fcdf24973ad0e9d4f11ef10890a8159614b1df97d8f31\",\n\t\t\t\"76532d1ce4ebdcbbf45afcd01d5bb298ef9556b232f877f3586d65303642dabc210059012d5f341c979fd10a1ce9b48f\",\n\t\t\t\"4a38f68da5ccbb8749c02e164a99668328890ed706accfbec155202f63ff487a26aba793169341c2ff91a43ffed38f0e\",\n\t\t\t\"941c3dc1012a12bb2148d6cf23dd05e228d29286e3bb87ff717712ecc2c9f0c4297c241ac41f879baeee87a570243a31\",\n\t\t\t\"cf43e775862e71a7f51cb150bbc31f3a2f62a1772d00f8bdd615ab5b58841c7918d69cf98a030f52ca410c9b91a188ba\",\n\t\t\t\"038138563ea35f8453075907fc3cdac7e3eff8fa9f61fcb53a1e14a102309fa297e420826bfe015628863a16f1bdc077\",\n\t\t\t\"90c6eead0cfd7a0aa7222df6d8d41415427b0b4057eb972dc31bd413f1e425ef1bc738cc5c3b8507890bad0940bafdf2\",\n\t\t\t\"220a6ecadb33ed002f9a476eb20c5e532bafa7b559b285932e1dab1159c93038d8cb0da8d55d25294cc8e6b0972efc08\",\n\t\t\t\"fdf825407e3215d8d01531f5cddfe993db10be07b38c18fa006999eb6418eac4696bb42ca149f79832442754ea08b0e1\",\n\t\t\t\"c6237feb522df034a3388c0de90b1a4652218b319f839ff16a132baa90dbbca2876f52b1a5750dc07001cffca3ed6e92\",\n\t\t\t\"2483e6567f183a78a1c09d16846743f08c5cce93e7e06294c4a722283d31195722b6ce97087c6dd00eedecd1db77be10\",\n\t\t\t\"9c298c322c53e83ea43201dd0684e8171ad29f6895ed9892d3932daeb0986f32992d6758db194ae9ba8eb256fdff3b61\",\n\t\t\t\"af0cd448aafe5e4e62e7e75409dfcd3cef3913c792e412849a02550109083fa52598f5fa2907e840050c41db32163838\",\n\t\t\t\"32aa7cb5e23de14ced47961e356b23e442f2a657ea89fed2845a6b380624dc12347e4d591c80e15016ae35fc005ae002\",\n\t\t\t\"f1fc5837c21185b88b06cc8611cfb482c021df5329d878e2b4f221341a47e6fe02182c9250d25fe162f42a0bbe9b8ce2\",\n\t\t\t\"f9a70aa2dcca9e955a61a0fe24016398a0fdf5e2541d3d0838d9f7e24b4093d27660a48cd71bf0728fe5d02e6d374a3e\",\n\t\t\t\"aa67c91aee87635d7458bb1fe89755021fbe8d34e271fba1d765b065e266008a862c839aeec0d6a9940cfe44e0bc1586\",\n\t\t\t\"2bd2ac23b3ab6fc59734a8171b44401b395984f0f906b2d15b4a3a24d2136a8ca925485f197197b3aa1bb2c46d02e000\",\n\t\t\t\"01000000010100000000\",\n\t\t].join(\"\"),\n\t\tcycle: 143,\n\t\tsignerSet: [\n\t\t\t\"0a0b0000001d0c00000002067369676e65720516f5061b1c62f399ecc0db8cbb21f8d481af079a380677656967687401\",\n\t\t\t\"000000000000000000000000000002860c00000002067369676e65720516a3bbf2a4133fbd5bd1880982957b7a760347\",\n\t\t\t\"b2dc0677656967687401000000000000000000000000000000090c00000002067369676e657205164f72f6b5a9f5d863\",\n\t\t\t\"34b2f0fe701db51a7a246f3d0677656967687401000000000000000000000000000000990c00000002067369676e6572\",\n\t\t\t\"051653ec8b4f51c8286dad6f4ff81ca2a3409d2f382d0677656967687401000000000000000000000000000000050c00\",\n\t\t\t\"000002067369676e65720516dba631825ff0f15c7c5946b560070f8f5f5747cb06776569676874010000000000000000\",\n\t\t\t\"00000000000000240c00000002067369676e6572051600d058b39f4495b412ff7eada763eaa6386eb90a067765696768\",\n\t\t\t\"7401000000000000000000000000000002860c00000002067369676e65720516321ac33715d684d5e8d0cf427cd98557\",\n\t\t\t\"6f64c6df06776569676874010000000000000000000000000000000b0c00000002067369676e6572051677a52718ba90\",\n\t\t\t\"fca67984166b2a084edb9b3bd8f10677656967687401000000000000000000000000000000030c00000002067369676e\",\n\t\t\t\"65720516a54a20479b3b65a461a427b9161b78e64db58ba70677656967687401000000000000000000000000000001a9\",\n\t\t\t\"0c00000002067369676e65720516bc1a58c2a058a9e4150db25562e8331ef8a4267c0677656967687401000000000000\",\n\t\t\t\"000000000000000000060c00000002067369676e657205161091d2da4c9ee17a340171c0d23c4304b54ef43f06776569\",\n\t\t\t\"67687401000000000000000000000000000000680c00000002067369676e6572051654d01a0973ed139736a1a43032a6\",\n\t\t\t\"a18d9295ec7206776569676874010000000000000000000000000000008d0c00000002067369676e657205160c49f5b6\",\n\t\t\t\"c62f1163ddbb21f92aba86f17f7be4880677656967687401000000000000000000000000000000680c00000002067369\",\n\t\t\t\"676e65720516ad16c79ac56b58f0797f78c5343853674606268006776569676874010000000000000000000000000000\",\n\t\t\t\"00680c00000002067369676e657205169689e56df00385b6bd81fb6b7769d5b04088acb8067765696768740100000000\",\n\t\t\t\"0000000000000000000000ad0c00000002067369676e65720516a4f7f81412f4413771a48825cfbe2062a774d4e90677\",\n\t\t\t\"656967687401000000000000000000000000000003090c00000002067369676e65720516ed73a7398f1c3eb566f3bd7f\",\n\t\t\t\"4bd43f52adf33d8f0677656967687401000000000000000000000000000000680c00000002067369676e65720516937b\",\n\t\t\t\"3b43e0d94c9ef8f171892bce949709e1d41f0677656967687401000000000000000000000000000000250c0000000206\",\n\t\t\t\"7369676e6572051631542aacfd6e04858181c3067b5eb07399ba89df0677656967687401000000000000000000000000\",\n\t\t\t\"0000005b0c00000002067369676e6572051649f034cd1662a222dbc38a6acd64008ba7e5576606776569676874010000\",\n\t\t\t\"00000000000000000000000000060c00000002067369676e65720516a20f660dea498c169897a39cb89ce0d98856e572\",\n\t\t\t\"0677656967687401000000000000000000000000000000090c00000002067369676e6572051652d58897b3678f3a758f\",\n\t\t\t\"a4b9270744fec0605b210677656967687401000000000000000000000000000000680c00000002067369676e65720516\",\n\t\t\t\"31733264626dc5fef36eb683a5069d89f63b64cc0677656967687401000000000000000000000000000000090c000000\",\n\t\t\t\"02067369676e65720516d80db618c2def577604cd8e40a3940b5b639b1ac067765696768740100000000000000000000\",\n\t\t\t\"00000000000a0c00000002067369676e657205162042a380d946a82866465af8521a273efe6d2a600677656967687401\",\n\t\t\t\"000000000000000000000000000000490c00000002067369676e6572051635e1b36efc22bc607db92f9100cb08e3473d\",\n\t\t\t\"602506776569676874010000000000000000000000000000006b0c00000002067369676e657205164843b97054e43dd1\",\n\t\t\t\"a8571fc1e72949c5bedfb7e906776569676874010000000000000000000000000000004d0c00000002067369676e6572\",\n\t\t\t\"05164883355670025c19ecae644ffa20e75ce1d730ad0677656967687401000000000000000000000000000000090c00\",\n\t\t\t\"000002067369676e65720516089ffd0e0ecd61d9e3c8ee42ef94148acf88aa8806776569676874010000000000000000\",\n\t\t\t\"0000000000000015\",\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/** Every MARF write of the block; null when the source has none for it. */\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\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 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 && 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\nexport interface SecondlayerSourceOptions {\n\t/** API origin, e.g. `https://api.secondlayer.tools`. */\n\tbaseUrl: string;\n\t/** Account key, sent as `Authorization: Bearer`. */\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 * Every proof input from the Secondlayer API: `/v1/proofs/*` for blocks, epoch\n * 2.x headers, MARF proofs, witnesses, burn preimages and Bitcoin headers; the Index API for\n * state_writes and vm_events, read only when verifyBlock gets `rows: true`.\n * Methods are own properties, so a partial source spreads over it:\n * `{ ...new SecondlayerProofSource(o), ...new NodeRpcProofSource(n) }`.\n */\nexport class SecondlayerProofSource implements ProofSource {\n\tgetBlock: (ref: string | number) => Promise<Bytes>;\n\tgetEpoch2Header: (blockId: string) => Promise<Epoch2HeaderResponse>;\n\tgetMarfProof: (\n\t\tpathHex: string,\n\t\ttipId: string,\n\t) => Promise<MarfProofResponse | null>;\n\tgetWitness: (blockId: string) => Promise<Bytes>;\n\tgetBurnPreimage: (consensusHash: string) => Promise<BurnPreimage>;\n\tgetBitcoinHeaders: (from: number, count: number) => Promise<string[]>;\n\tgetStateWrites: (height: number) => Promise<StateWrite[] | null>;\n\tgetVmEvents: (height: number) => Promise<VmEventRow[]>;\n\n\tconstructor(opts: SecondlayerSourceOptions) {\n\t\tconst base = trimSlash(opts.baseUrl);\n\t\tconst http: HttpOptions = {\n\t\t\theaders: { 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 = (height) =>\n\t\t\tpages<StateWrite>(\n\t\t\t\t\"state_writes\",\n\t\t\t\t`${base}/v1/index/state-writes?block_height=${height}&limit=${PAGE}`,\n\t\t\t\thttp,\n\t\t\t);\n\n\t\tthis.getVmEvents = async (height) => {\n\t\t\tconst out: VmEventRow[] = [];\n\t\t\tfor (const type of VM_WRITE_TYPES) {\n\t\t\t\tconst url = `${base}/v1/index/events?event_type=${type}&from_height=${height}&to_height=${height}&limit=${PAGE}`;\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 * Blocks, epoch 2.x headers and MARF proofs straight from a Stacks node's RPC.\n * Witnesses, burn preimages and Bitcoin headers need another source: spread\n * this over one.\n */\nexport class NodeRpcProofSource\n\timplements Pick<ProofSource, \"getBlock\" | \"getEpoch2Header\" | \"getMarfProof\">\n{\n\tgetBlock: (ref: string | number) => Promise<Bytes>;\n\tgetEpoch2Header: (blockId: string) => Promise<Epoch2HeaderResponse>;\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/** 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 * Verify block state against an authenticated header: the witness must\n * recompute `stateRoot`, then every leaf is classified. With state_writes,\n * any leaf that is not a named write, a carried parent value or MARF\n * bookkeeping is a hidden write. Without them the diff is still proven\n * (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\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
+ "// 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%) ─▶ witness N (root) ─▶ 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) ─▶ 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} 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 } from \"./source.ts\";\nimport {\n\ttype ProvenDiff,\n\ttype StateFailureCode,\n\tverifyBlockState,\n} from \"./state.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| \"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| \"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/** 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\tdiff?: ProvenDiff;\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 name the block's writes and prove its indexed rows: reads the\n\t * source's `getStateWrites` and `getVmEvents`, which bill as Index rows on\n\t * the Secondlayer API. Off by default, so verification reads proofs only.\n\t */\n\trows?: boolean;\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, caching the Bitcoin\n * header chain, proven signer sets and fetched headers across calls.\n */\nexport class BlockVerifier {\n\tprivate readonly source: ProofSource;\n\tprivate readonly checkpoint: VerifyCheckpoint;\n\tprivate readonly rows: boolean;\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\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\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\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}\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\tout.stateRoot = hex(header.stateIndexRoot);\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\n\t\tconst set = await this.signerSet(cycle, {\n\t\t\theight,\n\t\t\tburn: burn.burnHeight,\n\t\t});\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\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\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\tout.stateRoot = hex(header.stateIndexRoot);\n\t\tawait this.bindBurnBelow(header, out);\n\t\tawait this.verifyState(header, id, out);\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}\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 { getStateWrites, getVmEvents }: Partial<ProofSource> = this.rows\n\t\t\t? src\n\t\t\t: {};\n\t\tconst writes = getStateWrites\n\t\t\t? await fetchFor(\"names\", `state_writes ${height}`, () =>\n\t\t\t\t\tgetStateWrites.call(src, height),\n\t\t\t\t)\n\t\t\t: null;\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}\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} 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\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"
19
+ ],
20
+ "mappings": ";AACA;AACA;AAIO,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,EA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"name": "@secondlayer/verify",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@secondlayer/verify",
3
+ "version": "0.2.0",
4
+ "description": "Check a Stacks block yourself: Bitcoin headers, signer signatures and MARF state proofs, from one trusted checkpoint.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/ryanwaits/secondlayer.git",
9
+ "directory": "packages/verify"
10
+ },
11
+ "homepage": "https://github.com/ryanwaits/secondlayer/tree/main/packages/verify#readme",
12
+ "type": "module",
13
+ "main": "./dist/index.js",
14
+ "types": "./dist/index.d.ts",
15
+ "exports": {
16
+ ".": {
17
+ "types": "./dist/index.d.ts",
18
+ "import": "./dist/index.js"
19
+ }
20
+ },
21
+ "files": ["dist", "README.md"],
22
+ "scripts": {
23
+ "build": "bunup",
24
+ "dev": "bunup --watch",
25
+ "test": "bun test",
26
+ "typecheck": "tsc --noEmit",
27
+ "prepublishOnly": "bun run build"
28
+ },
29
+ "dependencies": {
30
+ "@noble/curves": "2.0.1",
31
+ "@noble/hashes": "2.0.1",
32
+ "@secondlayer/stacks": "^6.1.1"
33
+ },
34
+ "devDependencies": {
35
+ "@types/bun": "latest",
36
+ "typescript": "^5"
37
+ },
38
+ "publishConfig": {
39
+ "access": "public"
40
+ }
41
+ }