@secondlayer/shared 11.14.2 → 11.14.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/src/node/client.js
CHANGED
|
@@ -126,7 +126,7 @@ function txMerkleRoot(txidsHex) {
|
|
|
126
126
|
if (txidsHex.length === 0)
|
|
127
127
|
throw new Error("no transactions");
|
|
128
128
|
let level = txidsHex.map((t) => tagged(LEAF_TAG, fromHex(t)));
|
|
129
|
-
|
|
129
|
+
do {
|
|
130
130
|
if (level.length % 2 === 1)
|
|
131
131
|
level.push(level[level.length - 1]);
|
|
132
132
|
const next = [];
|
|
@@ -134,7 +134,7 @@ function txMerkleRoot(txidsHex) {
|
|
|
134
134
|
next.push(tagged(NODE_TAG, level[i], level[i + 1]));
|
|
135
135
|
}
|
|
136
136
|
level = next;
|
|
137
|
-
}
|
|
137
|
+
} while (level.length > 1);
|
|
138
138
|
return toHex(level[0]);
|
|
139
139
|
}
|
|
140
140
|
function txMerkleProof(txidsHex, index) {
|
|
@@ -144,7 +144,7 @@ function txMerkleProof(txidsHex, index) {
|
|
|
144
144
|
let level = txidsHex.map((t) => tagged(LEAF_TAG, fromHex(t)));
|
|
145
145
|
let idx = index;
|
|
146
146
|
const path = [];
|
|
147
|
-
|
|
147
|
+
do {
|
|
148
148
|
if (level.length % 2 === 1)
|
|
149
149
|
level.push(level[level.length - 1]);
|
|
150
150
|
const siblingIdx = idx % 2 === 0 ? idx + 1 : idx - 1;
|
|
@@ -158,7 +158,7 @@ function txMerkleProof(txidsHex, index) {
|
|
|
158
158
|
}
|
|
159
159
|
level = next;
|
|
160
160
|
idx = Math.floor(idx / 2);
|
|
161
|
-
}
|
|
161
|
+
} while (level.length > 1);
|
|
162
162
|
return path;
|
|
163
163
|
}
|
|
164
164
|
function verifyTxMerkleProof(txidHex, path, txMerkleRootHex) {
|
|
@@ -266,5 +266,5 @@ export {
|
|
|
266
266
|
StacksNodeClient
|
|
267
267
|
};
|
|
268
268
|
|
|
269
|
-
//# debugId=
|
|
269
|
+
//# debugId=6DE2545AD8FD5E2064756E2164756E21
|
|
270
270
|
//# sourceMappingURL=client.js.map
|
|
@@ -3,9 +3,9 @@
|
|
|
3
3
|
"sources": ["../src/node/client.ts", "../src/node/nakamoto.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
5
|
"import { http, createPublicClient } from \"@secondlayer/stacks\";\nimport { getContractAbi, getRawBlock } from \"@secondlayer/stacks/actions\";\nimport type { RewardSet } from \"./consensus.ts\";\nimport {\n\ttype NakamotoBlockHeader,\n\tnakamotoBlockHash,\n\tnakamotoBlockId,\n\tparseNakamotoBlockHeader,\n} from \"./nakamoto.ts\";\n\nexport interface NodeInfo {\n\tpeer_version: number;\n\tpox_consensus: string;\n\tburn_block_height: number;\n\tstable_pox_consensus: string;\n\tstable_burn_block_height: number;\n\tserver_version: string;\n\tnetwork_id: number;\n\tparent_network_id: number;\n\tstacks_tip_height: number;\n\tstacks_tip: string;\n\tstacks_tip_consensus_hash: string;\n\tgenesis_chainstate_hash: string;\n}\n\nexport interface BlockResponse {\n\thash: string;\n\theight: number;\n\tparent_block_hash: string;\n\tburn_block_height: number;\n\tburn_block_hash: string;\n\tburn_block_time: number;\n\tindex_block_hash: string;\n\tparent_index_block_hash: string;\n\tminer_txid: string;\n\ttxs: string[];\n\t// Full block data varies by endpoint — kept minimal for fetch use case\n}\n\nexport class StacksNodeClient {\n\tprivate rpcUrl: string;\n\n\tconstructor(rpcUrl?: string) {\n\t\tthis.rpcUrl =\n\t\t\trpcUrl || process.env.STACKS_NODE_RPC_URL || \"http://localhost:20443\";\n\t}\n\n\t/**\n\t * A stacks-backed client for the given call's original timeout, with no\n\t * retries — matches every method's prior single-attempt fetch semantics\n\t * (in particular `getInfo`'s fast-fail timing, which `isHealthy()` and its\n\t * callers depend on).\n\t */\n\tprivate client(timeoutMs: number) {\n\t\treturn createPublicClient({\n\t\t\ttransport: http(this.rpcUrl, { retryCount: 0, timeout: timeoutMs }),\n\t\t});\n\t}\n\n\tasync getInfo(): Promise<NodeInfo> {\n\t\tconst data = await this.client(10_000).request(\"/v2/info\", {\n\t\t\tmethod: \"GET\",\n\t\t});\n\t\treturn data as NodeInfo;\n\t}\n\n\tasync getBlock(height: number): Promise<BlockResponse | null> {\n\t\treturn getRawBlock(this.client(30_000), { height });\n\t}\n\n\t/**\n\t * Fetch + parse a Nakamoto block by its index_block_hash. Returns the raw\n\t * bytes, the parsed header, and the recomputed block_hash / index_block_hash\n\t * (so a caller can cross-check the node's answer). Null on 404.\n\t */\n\tasync getNakamotoBlock(blockId: string): Promise<{\n\t\traw: Uint8Array;\n\t\theader: NakamotoBlockHeader;\n\t\tblockHash: string;\n\t\tindexBlockHash: string;\n\t} | null> {\n\t\tconst id = blockId.startsWith(\"0x\") ? blockId.slice(2) : blockId;\n\t\tconst res = await fetch(`${this.rpcUrl}/v3/blocks/${id}`, {\n\t\t\tsignal: AbortSignal.timeout(30_000),\n\t\t});\n\t\tif (res.status === 404) return null;\n\t\tif (!res.ok) {\n\t\t\tthrow new Error(`Node RPC /v3/blocks/${id} returned ${res.status}`);\n\t\t}\n\t\tconst raw = new Uint8Array(await res.arrayBuffer());\n\t\tconst header = parseNakamotoBlockHeader(raw);\n\t\tconst blockHash = nakamotoBlockHash(header);\n\t\treturn {\n\t\t\traw,\n\t\t\theader,\n\t\t\tblockHash,\n\t\t\tindexBlockHash: nakamotoBlockId(blockHash, header.consensusHash),\n\t\t};\n\t}\n\n\t/**\n\t * Fetch the reward set (signer keys + weights) for a reward cycle from\n\t * `/v3/stacker_set/{cycle}`. Null on 404 (cycle not yet computed).\n\t */\n\tasync getRewardSet(cycle: number): Promise<RewardSet | null> {\n\t\tconst res = await fetch(`${this.rpcUrl}/v3/stacker_set/${cycle}`, {\n\t\t\tsignal: AbortSignal.timeout(15_000),\n\t\t});\n\t\tif (res.status === 404) return null;\n\t\tif (!res.ok) {\n\t\t\tthrow new Error(\n\t\t\t\t`Node RPC /v3/stacker_set/${cycle} returned ${res.status}`,\n\t\t\t);\n\t\t}\n\t\tconst body = (await res.json()) as {\n\t\t\tstacker_set: { signers: { signing_key: string; weight: number }[] };\n\t\t};\n\t\tconst signers = body.stacker_set.signers.map((s) => ({\n\t\t\tsigning_key: s.signing_key.startsWith(\"0x\")\n\t\t\t\t? s.signing_key.slice(2)\n\t\t\t\t: s.signing_key,\n\t\t\tweight: s.weight,\n\t\t}));\n\t\treturn {\n\t\t\tsigners,\n\t\t\ttotal_weight: signers.reduce((sum, s) => sum + s.weight, 0),\n\t\t};\n\t}\n\n\tasync isHealthy(): Promise<boolean> {\n\t\ttry {\n\t\t\tconst info = await this.getInfo();\n\t\t\treturn info.stacks_tip_height > 0;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tasync getContractAbi(contractId: string): Promise<unknown> {\n\t\treturn getContractAbi(this.client(30_000), { contract: contractId });\n\t}\n\n\tgetRpcUrl(): string {\n\t\treturn this.rpcUrl;\n\t}\n}\n",
|
|
6
|
-
"import { createHash } from \"node:crypto\";\n\n/**\n * Nakamoto block-header parsing + consensus hashing for trustless verification.\n *\n * Version 0 is bit-exact against mainnet `stacks-node 3.4.0.0.3`. Version 1\n * (Epoch 4.0 / PoX-5, first mainnet height 8,665,568) appends\n * `problematic_txs` after `pox_treatment` and includes those bytes in the\n * signer-signature-hash preimage. Pre-4.0 hashes are unchanged.\n */\n\n/** SHA-512/256 — the hash Stacks uses everywhere (NOT truncated SHA-512). */\nexport function sha512_256(bytes: Uint8Array): Uint8Array {\n\treturn createHash(\"sha512-256\").update(bytes).digest();\n}\n\nconst toHex = (b: Uint8Array): string => Buffer.from(b).toString(\"hex\");\nconst fromHex = (h: string): Uint8Array =>\n\tUint8Array.from(Buffer.from(h.startsWith(\"0x\") ? h.slice(2) : h, \"hex\"));\n\n// Fixed-size header prefix: version..miner_signature, before signer_signature.\nconst PREFIX_LEN = 206;\nconst CONSENSUS_HASH_OFF = 17;\nconst TX_MERKLE_ROOT_OFF = 69;\nconst STATE_INDEX_ROOT_OFF = 101;\nconst TIMESTAMP_OFF = 133;\nconst MINER_SIG_OFF = 141;\nconst SIGNER_VEC_OFF = 206; // u32 count, then 65 bytes per signer\nconst SIG_LEN = 65;\nconst PROBLEMATIC_TX_MARKER_LEN = 5; // u32 tx_index ‖ u8 category\n\n/** Pre-Epoch-4.0 Nakamoto header. Omits `problematic_txs`. */\nexport const NAKAMOTO_BLOCK_VERSION = 0;\n/** Epoch 4.0+ header. Serializes and hashes `problematic_txs`. */\nexport const NAKAMOTO_BLOCK_VERSION_EPOCH_4 = 1;\n\nexport type ProblematicTxMarker = {\n\ttxIndex: number;\n\tcategory: number;\n};\n\n/** Low 7 bits are the header version; high bit 0x80 is the shadow-block flag. */\nexport function versionIncludesProblematicTxs(version: number): boolean {\n\treturn (version & 0x7f) >= NAKAMOTO_BLOCK_VERSION_EPOCH_4;\n}\n\nexport interface NakamotoBlockHeader {\n\tversion: number;\n\tchainLength: bigint;\n\tburnSpent: bigint;\n\t/** 20-byte consensus hash (hex). */\n\tconsensusHash: string;\n\t/** 32-byte parent StacksBlockId (hex). */\n\tparentBlockId: string;\n\t/** 32-byte SHA512/256 merkle root over the block's txids (hex). */\n\ttxMerkleRoot: string;\n\t/** 32-byte MARF root after applying this block (hex). */\n\tstateIndexRoot: string;\n\ttimestamp: bigint;\n\t/** 65-byte recoverable ECDSA miner signature (hex). */\n\tminerSignature: string;\n\t/** Per-signer recoverable ECDSA signatures, reward-set order (hex, 65B each). */\n\tsignerSignatures: string[];\n\t/** Full serialized pox_treatment BitVec bytes (u16 bits ‖ u32 len ‖ data). */\n\tpoxTreatment: Uint8Array;\n\t/**\n\t * Epoch 4.0+ marker list. Empty (and absent from the wire) on version 0.\n\t * An empty list still serializes as a u32 count of 0 on version 1+.\n\t */\n\tproblematicTxs: ProblematicTxMarker[];\n\t/**\n\t * Exact bytes whose SHA512/256 IS the block_hash / signer_signature_hash:\n\t * header minus the signer_signature vector. Version 0 is\n\t * prefix[0:206] ‖ pox; version 1+ is prefix[0:206] ‖ pox ‖ problematic_txs.\n\t */\n\tsignerSignatureHashPreimage: Uint8Array;\n\t/** Offset at which the tx `Vec` begins (= total header byte length). */\n\theaderByteLength: number;\n}\n\nfunction u32(b: Uint8Array, off: number): number {\n\treturn new DataView(b.buffer, b.byteOffset, b.byteLength).getUint32(off);\n}\nfunction u64(b: Uint8Array, off: number): bigint {\n\treturn new DataView(b.buffer, b.byteOffset, b.byteLength).getBigUint64(off);\n}\n\n/** Parse the Nakamoto block header from the raw `/v3/blocks` body. */\nexport function parseNakamotoBlockHeader(raw: Uint8Array): NakamotoBlockHeader {\n\tif (raw.length < PREFIX_LEN + 4) {\n\t\tthrow new Error(\"raw block too short for a Nakamoto header\");\n\t}\n\tconst version = raw[0];\n\tconst signerCount = u32(raw, SIGNER_VEC_OFF);\n\tconst sigsStart = SIGNER_VEC_OFF + 4;\n\tif (sigsStart + signerCount * SIG_LEN > raw.length) {\n\t\tthrow new Error(\"raw block truncated in signer_signature vector\");\n\t}\n\tconst signerSignatures: string[] = [];\n\tfor (let i = 0; i < signerCount; i++) {\n\t\tconst off = sigsStart + i * SIG_LEN;\n\t\tsignerSignatures.push(toHex(raw.subarray(off, off + SIG_LEN)));\n\t}\n\t// pox_treatment: u16 num_bits ‖ u32 data_len ‖ data[data_len].\n\tconst poxOff = sigsStart + signerCount * SIG_LEN;\n\tif (poxOff + 6 > raw.length) {\n\t\tthrow new Error(\"raw block truncated in pox_treatment\");\n\t}\n\tconst poxDataLen = u32(raw, poxOff + 2);\n\tconst poxEnd = poxOff + 6 + poxDataLen;\n\tif (poxEnd > raw.length) {\n\t\tthrow new Error(\"raw block truncated in pox_treatment data\");\n\t}\n\tconst poxTreatment = raw.subarray(poxOff, poxEnd);\n\n\t// Epoch 4.0+ (version low-7-bits >= 1): Vec<ProblematicTxMarker>\n\t// after pox_treatment. Version 0 omits the field entirely so pre-fork\n\t// hashes stay byte-identical.\n\tlet headerEnd = poxEnd;\n\tconst problematicTxs: ProblematicTxMarker[] = [];\n\tif (versionIncludesProblematicTxs(version)) {\n\t\tif (poxEnd + 4 > raw.length) {\n\t\t\tthrow new Error(\"raw block truncated in problematic_txs count\");\n\t\t}\n\t\tconst markerCount = u32(raw, poxEnd);\n\t\theaderEnd = poxEnd + 4 + markerCount * PROBLEMATIC_TX_MARKER_LEN;\n\t\tif (headerEnd > raw.length) {\n\t\t\tthrow new Error(\"raw block truncated in problematic_txs list\");\n\t\t}\n\t\tfor (let i = 0; i < markerCount; i++) {\n\t\t\tconst off = poxEnd + 4 + i * PROBLEMATIC_TX_MARKER_LEN;\n\t\t\tproblematicTxs.push({\n\t\t\t\ttxIndex: u32(raw, off),\n\t\t\t\tcategory: raw[off + 4] ?? 0,\n\t\t\t});\n\t\t}\n\t}\n\n\t// block_hash preimage = header minus signer_signature.\n\t// v0: prefix[0:206] ‖ pox\n\t// v1: prefix[0:206] ‖ pox ‖ problematic_txs (count + markers)\n\tconst markersBytes = raw.subarray(poxEnd, headerEnd);\n\tconst preimage = new Uint8Array(\n\t\tPREFIX_LEN + poxTreatment.length + markersBytes.length,\n\t);\n\tpreimage.set(raw.subarray(0, PREFIX_LEN), 0);\n\tpreimage.set(poxTreatment, PREFIX_LEN);\n\tpreimage.set(markersBytes, PREFIX_LEN + poxTreatment.length);\n\n\treturn {\n\t\tversion,\n\t\tchainLength: u64(raw, 1),\n\t\tburnSpent: u64(raw, 9),\n\t\tconsensusHash: toHex(\n\t\t\traw.subarray(CONSENSUS_HASH_OFF, CONSENSUS_HASH_OFF + 20),\n\t\t),\n\t\tparentBlockId: toHex(raw.subarray(37, 69)),\n\t\ttxMerkleRoot: toHex(\n\t\t\traw.subarray(TX_MERKLE_ROOT_OFF, TX_MERKLE_ROOT_OFF + 32),\n\t\t),\n\t\tstateIndexRoot: toHex(\n\t\t\traw.subarray(STATE_INDEX_ROOT_OFF, STATE_INDEX_ROOT_OFF + 32),\n\t\t),\n\t\ttimestamp: u64(raw, TIMESTAMP_OFF),\n\t\tminerSignature: toHex(raw.subarray(MINER_SIG_OFF, MINER_SIG_OFF + SIG_LEN)),\n\t\tsignerSignatures,\n\t\tpoxTreatment,\n\t\tproblematicTxs,\n\t\tsignerSignatureHashPreimage: preimage,\n\t\theaderByteLength: headerEnd,\n\t};\n}\n\n/**\n * block_hash (== signer_signature_hash): SHA512/256 over the header with the\n * signer_signature vector omitted. This is what each signer signs.\n */\nexport function nakamotoBlockHash(header: NakamotoBlockHeader): string {\n\treturn toHex(sha512_256(header.signerSignatureHashPreimage));\n}\n\n/** index_block_hash (StacksBlockId) = SHA512/256(block_hash ‖ consensus_hash). */\nexport function nakamotoBlockId(\n\tblockHashHex: string,\n\tconsensusHashHex: string,\n): string {\n\tconst a = fromHex(blockHashHex);\n\tconst b = fromHex(consensusHashHex);\n\tconst buf = new Uint8Array(a.length + b.length);\n\tbuf.set(a, 0);\n\tbuf.set(b, a.length);\n\treturn toHex(sha512_256(buf));\n}\n\n/** A Stacks txid = SHA512/256 of the transaction's consensus serialization. */\nexport function stacksTxid(rawTx: Uint8Array): string {\n\treturn toHex(sha512_256(rawTx));\n}\n\nconst LEAF_TAG = 0x00;\nconst NODE_TAG = 0x01;\n\nfunction tagged(tag: number, ...parts: Uint8Array[]): Uint8Array {\n\tconst len = parts.reduce((n, p) => n + p.length, 1);\n\tconst buf = new Uint8Array(len);\n\tbuf[0] = tag;\n\tlet o = 1;\n\tfor (const p of parts) {\n\t\tbuf.set(p, o);\n\t\to += p.length;\n\t}\n\treturn sha512_256(buf);\n}\n\n/**\n * tx_merkle_root over the block's txids (hex), reproducing the consensus rule:\n * leaf = H(0x00 ‖ txid), node = H(0x01 ‖ left ‖ right), odd level duplicates the\n * last node. Returns the root hex; throws on an empty tx list.\n */\nexport function txMerkleRoot(txidsHex: string[]): string {\n\tif (txidsHex.length === 0) throw new Error(\"no transactions\");\n\tlet level = txidsHex.map((t) => tagged(LEAF_TAG, fromHex(t)));\n\twhile (level.length > 1) {\n\t\tif (level.length % 2 === 1) level.push(level[level.length - 1]);\n\t\tconst next: Uint8Array[] = [];\n\t\tfor (let i = 0; i < level.length; i += 2) {\n\t\t\tnext.push(tagged(NODE_TAG, level[i], level[i + 1]));\n\t\t}\n\t\tlevel = next;\n\t}\n\treturn toHex(level[0]);\n}\n\n/** One authentication-path step: the sibling hash and which side it's on. */\nexport interface MerkleProofStep {\n\t/** Side the SIBLING is on relative to the accumulator. */\n\tposition: \"left\" | \"right\";\n\t/** Sibling node hash (hex). */\n\thash: string;\n}\n\n/**\n * Build the tx-inclusion authentication path for the tx at `index` in a block,\n * reproducing the consensus merkle tree (incl. duplicate-last-on-odd). The path\n * lets a verifier recompute `tx_merkle_root` from just the target txid.\n */\nexport function txMerkleProof(\n\ttxidsHex: string[],\n\tindex: number,\n): MerkleProofStep[] {\n\tif (index < 0 || index >= txidsHex.length) {\n\t\tthrow new Error(\"index out of range\");\n\t}\n\tlet level = txidsHex.map((t) => tagged(LEAF_TAG, fromHex(t)));\n\tlet idx = index;\n\tconst path: MerkleProofStep[] = [];\n\twhile (level.length > 1) {\n\t\tif (level.length % 2 === 1) level.push(level[level.length - 1]);\n\t\tconst siblingIdx = idx % 2 === 0 ? idx + 1 : idx - 1;\n\t\tpath.push({\n\t\t\tposition: idx % 2 === 0 ? \"right\" : \"left\",\n\t\t\thash: toHex(level[siblingIdx]),\n\t\t});\n\t\tconst next: Uint8Array[] = [];\n\t\tfor (let i = 0; i < level.length; i += 2) {\n\t\t\tnext.push(tagged(NODE_TAG, level[i], level[i + 1]));\n\t\t}\n\t\tlevel = next;\n\t\tidx = Math.floor(idx / 2);\n\t}\n\treturn path;\n}\n\n/**\n * Verify a tx-inclusion proof: fold the target `txid` (hex) up through `path`\n * and check it equals `txMerkleRoot` (hex). The verifier recomputes the txid\n * itself from the raw tx bytes, so nothing here is trusted.\n */\nexport function verifyTxMerkleProof(\n\ttxidHex: string,\n\tpath: MerkleProofStep[],\n\ttxMerkleRootHex: string,\n): boolean {\n\tlet acc = tagged(LEAF_TAG, fromHex(txidHex));\n\tfor (const step of path) {\n\t\tconst sib = fromHex(step.hash);\n\t\tacc =\n\t\t\tstep.position === \"right\"\n\t\t\t\t? tagged(NODE_TAG, acc, sib)\n\t\t\t\t: tagged(NODE_TAG, sib, acc);\n\t}\n\tconst root = txMerkleRootHex.startsWith(\"0x\")\n\t\t? txMerkleRootHex.slice(2)\n\t\t: txMerkleRootHex;\n\treturn toHex(acc) === root;\n}\n\n/**\n * Fetch and parse a Nakamoto block from a stacks-node. `blockId` is the\n * index_block_hash (with or without 0x). Returns the raw bytes + parsed header +\n * the recomputed block_hash / index_block_hash so a caller can cross-check.\n */\nexport async function fetchNakamotoBlock(opts: {\n\tnodeUrl: string;\n\tblockId: string;\n\tfetchImpl?: typeof fetch;\n}): Promise<{\n\traw: Uint8Array;\n\theader: NakamotoBlockHeader;\n\tblockHash: string;\n\tindexBlockHash: string;\n}> {\n\tconst id = opts.blockId.startsWith(\"0x\")\n\t\t? opts.blockId.slice(2)\n\t\t: opts.blockId;\n\tconst f = opts.fetchImpl ?? fetch;\n\tconst res = await f(`${opts.nodeUrl.replace(/\\/+$/, \"\")}/v3/blocks/${id}`);\n\tif (!res.ok) {\n\t\tthrow new Error(`/v3/blocks/${id} returned ${res.status}`);\n\t}\n\tconst raw = new Uint8Array(await res.arrayBuffer());\n\tconst header = parseNakamotoBlockHeader(raw);\n\tconst blockHash = nakamotoBlockHash(header);\n\treturn {\n\t\traw,\n\t\theader,\n\t\tblockHash,\n\t\tindexBlockHash: nakamotoBlockId(blockHash, header.consensusHash),\n\t};\n}\n"
|
|
6
|
+
"import { createHash } from \"node:crypto\";\n\n/**\n * Nakamoto block-header parsing + consensus hashing for trustless verification.\n *\n * Version 0 is bit-exact against mainnet `stacks-node 3.4.0.0.3`. Version 1\n * (Epoch 4.0 / PoX-5, first mainnet height 8,665,568) appends\n * `problematic_txs` after `pox_treatment` and includes those bytes in the\n * signer-signature-hash preimage. Pre-4.0 hashes are unchanged.\n */\n\n/** SHA-512/256 — the hash Stacks uses everywhere (NOT truncated SHA-512). */\nexport function sha512_256(bytes: Uint8Array): Uint8Array {\n\treturn createHash(\"sha512-256\").update(bytes).digest();\n}\n\nconst toHex = (b: Uint8Array): string => Buffer.from(b).toString(\"hex\");\nconst fromHex = (h: string): Uint8Array =>\n\tUint8Array.from(Buffer.from(h.startsWith(\"0x\") ? h.slice(2) : h, \"hex\"));\n\n// Fixed-size header prefix: version..miner_signature, before signer_signature.\nconst PREFIX_LEN = 206;\nconst CONSENSUS_HASH_OFF = 17;\nconst TX_MERKLE_ROOT_OFF = 69;\nconst STATE_INDEX_ROOT_OFF = 101;\nconst TIMESTAMP_OFF = 133;\nconst MINER_SIG_OFF = 141;\nconst SIGNER_VEC_OFF = 206; // u32 count, then 65 bytes per signer\nconst SIG_LEN = 65;\nconst PROBLEMATIC_TX_MARKER_LEN = 5; // u32 tx_index ‖ u8 category\n\n/** Pre-Epoch-4.0 Nakamoto header. Omits `problematic_txs`. */\nexport const NAKAMOTO_BLOCK_VERSION = 0;\n/** Epoch 4.0+ header. Serializes and hashes `problematic_txs`. */\nexport const NAKAMOTO_BLOCK_VERSION_EPOCH_4 = 1;\n\nexport type ProblematicTxMarker = {\n\ttxIndex: number;\n\tcategory: number;\n};\n\n/** Low 7 bits are the header version; high bit 0x80 is the shadow-block flag. */\nexport function versionIncludesProblematicTxs(version: number): boolean {\n\treturn (version & 0x7f) >= NAKAMOTO_BLOCK_VERSION_EPOCH_4;\n}\n\nexport interface NakamotoBlockHeader {\n\tversion: number;\n\tchainLength: bigint;\n\tburnSpent: bigint;\n\t/** 20-byte consensus hash (hex). */\n\tconsensusHash: string;\n\t/** 32-byte parent StacksBlockId (hex). */\n\tparentBlockId: string;\n\t/** 32-byte SHA512/256 merkle root over the block's txids (hex). */\n\ttxMerkleRoot: string;\n\t/** 32-byte MARF root after applying this block (hex). */\n\tstateIndexRoot: string;\n\ttimestamp: bigint;\n\t/** 65-byte recoverable ECDSA miner signature (hex). */\n\tminerSignature: string;\n\t/** Per-signer recoverable ECDSA signatures, reward-set order (hex, 65B each). */\n\tsignerSignatures: string[];\n\t/** Full serialized pox_treatment BitVec bytes (u16 bits ‖ u32 len ‖ data). */\n\tpoxTreatment: Uint8Array;\n\t/**\n\t * Epoch 4.0+ marker list. Empty (and absent from the wire) on version 0.\n\t * An empty list still serializes as a u32 count of 0 on version 1+.\n\t */\n\tproblematicTxs: ProblematicTxMarker[];\n\t/**\n\t * Exact bytes whose SHA512/256 IS the block_hash / signer_signature_hash:\n\t * header minus the signer_signature vector. Version 0 is\n\t * prefix[0:206] ‖ pox; version 1+ is prefix[0:206] ‖ pox ‖ problematic_txs.\n\t */\n\tsignerSignatureHashPreimage: Uint8Array;\n\t/** Offset at which the tx `Vec` begins (= total header byte length). */\n\theaderByteLength: number;\n}\n\nfunction u32(b: Uint8Array, off: number): number {\n\treturn new DataView(b.buffer, b.byteOffset, b.byteLength).getUint32(off);\n}\nfunction u64(b: Uint8Array, off: number): bigint {\n\treturn new DataView(b.buffer, b.byteOffset, b.byteLength).getBigUint64(off);\n}\n\n/** Parse the Nakamoto block header from the raw `/v3/blocks` body. */\nexport function parseNakamotoBlockHeader(raw: Uint8Array): NakamotoBlockHeader {\n\tif (raw.length < PREFIX_LEN + 4) {\n\t\tthrow new Error(\"raw block too short for a Nakamoto header\");\n\t}\n\tconst version = raw[0];\n\tconst signerCount = u32(raw, SIGNER_VEC_OFF);\n\tconst sigsStart = SIGNER_VEC_OFF + 4;\n\tif (sigsStart + signerCount * SIG_LEN > raw.length) {\n\t\tthrow new Error(\"raw block truncated in signer_signature vector\");\n\t}\n\tconst signerSignatures: string[] = [];\n\tfor (let i = 0; i < signerCount; i++) {\n\t\tconst off = sigsStart + i * SIG_LEN;\n\t\tsignerSignatures.push(toHex(raw.subarray(off, off + SIG_LEN)));\n\t}\n\t// pox_treatment: u16 num_bits ‖ u32 data_len ‖ data[data_len].\n\tconst poxOff = sigsStart + signerCount * SIG_LEN;\n\tif (poxOff + 6 > raw.length) {\n\t\tthrow new Error(\"raw block truncated in pox_treatment\");\n\t}\n\tconst poxDataLen = u32(raw, poxOff + 2);\n\tconst poxEnd = poxOff + 6 + poxDataLen;\n\tif (poxEnd > raw.length) {\n\t\tthrow new Error(\"raw block truncated in pox_treatment data\");\n\t}\n\tconst poxTreatment = raw.subarray(poxOff, poxEnd);\n\n\t// Epoch 4.0+ (version low-7-bits >= 1): Vec<ProblematicTxMarker>\n\t// after pox_treatment. Version 0 omits the field entirely so pre-fork\n\t// hashes stay byte-identical.\n\tlet headerEnd = poxEnd;\n\tconst problematicTxs: ProblematicTxMarker[] = [];\n\tif (versionIncludesProblematicTxs(version)) {\n\t\tif (poxEnd + 4 > raw.length) {\n\t\t\tthrow new Error(\"raw block truncated in problematic_txs count\");\n\t\t}\n\t\tconst markerCount = u32(raw, poxEnd);\n\t\theaderEnd = poxEnd + 4 + markerCount * PROBLEMATIC_TX_MARKER_LEN;\n\t\tif (headerEnd > raw.length) {\n\t\t\tthrow new Error(\"raw block truncated in problematic_txs list\");\n\t\t}\n\t\tfor (let i = 0; i < markerCount; i++) {\n\t\t\tconst off = poxEnd + 4 + i * PROBLEMATIC_TX_MARKER_LEN;\n\t\t\tproblematicTxs.push({\n\t\t\t\ttxIndex: u32(raw, off),\n\t\t\t\tcategory: raw[off + 4] ?? 0,\n\t\t\t});\n\t\t}\n\t}\n\n\t// block_hash preimage = header minus signer_signature.\n\t// v0: prefix[0:206] ‖ pox\n\t// v1: prefix[0:206] ‖ pox ‖ problematic_txs (count + markers)\n\tconst markersBytes = raw.subarray(poxEnd, headerEnd);\n\tconst preimage = new Uint8Array(\n\t\tPREFIX_LEN + poxTreatment.length + markersBytes.length,\n\t);\n\tpreimage.set(raw.subarray(0, PREFIX_LEN), 0);\n\tpreimage.set(poxTreatment, PREFIX_LEN);\n\tpreimage.set(markersBytes, PREFIX_LEN + poxTreatment.length);\n\n\treturn {\n\t\tversion,\n\t\tchainLength: u64(raw, 1),\n\t\tburnSpent: u64(raw, 9),\n\t\tconsensusHash: toHex(\n\t\t\traw.subarray(CONSENSUS_HASH_OFF, CONSENSUS_HASH_OFF + 20),\n\t\t),\n\t\tparentBlockId: toHex(raw.subarray(37, 69)),\n\t\ttxMerkleRoot: toHex(\n\t\t\traw.subarray(TX_MERKLE_ROOT_OFF, TX_MERKLE_ROOT_OFF + 32),\n\t\t),\n\t\tstateIndexRoot: toHex(\n\t\t\traw.subarray(STATE_INDEX_ROOT_OFF, STATE_INDEX_ROOT_OFF + 32),\n\t\t),\n\t\ttimestamp: u64(raw, TIMESTAMP_OFF),\n\t\tminerSignature: toHex(raw.subarray(MINER_SIG_OFF, MINER_SIG_OFF + SIG_LEN)),\n\t\tsignerSignatures,\n\t\tpoxTreatment,\n\t\tproblematicTxs,\n\t\tsignerSignatureHashPreimage: preimage,\n\t\theaderByteLength: headerEnd,\n\t};\n}\n\n/**\n * block_hash (== signer_signature_hash): SHA512/256 over the header with the\n * signer_signature vector omitted. This is what each signer signs.\n */\nexport function nakamotoBlockHash(header: NakamotoBlockHeader): string {\n\treturn toHex(sha512_256(header.signerSignatureHashPreimage));\n}\n\n/** index_block_hash (StacksBlockId) = SHA512/256(block_hash ‖ consensus_hash). */\nexport function nakamotoBlockId(\n\tblockHashHex: string,\n\tconsensusHashHex: string,\n): string {\n\tconst a = fromHex(blockHashHex);\n\tconst b = fromHex(consensusHashHex);\n\tconst buf = new Uint8Array(a.length + b.length);\n\tbuf.set(a, 0);\n\tbuf.set(b, a.length);\n\treturn toHex(sha512_256(buf));\n}\n\n/** A Stacks txid = SHA512/256 of the transaction's consensus serialization. */\nexport function stacksTxid(rawTx: Uint8Array): string {\n\treturn toHex(sha512_256(rawTx));\n}\n\nconst LEAF_TAG = 0x00;\nconst NODE_TAG = 0x01;\n\nfunction tagged(tag: number, ...parts: Uint8Array[]): Uint8Array {\n\tconst len = parts.reduce((n, p) => n + p.length, 1);\n\tconst buf = new Uint8Array(len);\n\tbuf[0] = tag;\n\tlet o = 1;\n\tfor (const p of parts) {\n\t\tbuf.set(p, o);\n\t\to += p.length;\n\t}\n\treturn sha512_256(buf);\n}\n\n/**\n * tx_merkle_root over the block's txids (hex), reproducing the consensus rule:\n * leaf = H(0x00 ‖ txid), node = H(0x01 ‖ left ‖ right), odd level duplicates the\n * last node. Returns the root hex; throws on an empty tx list.\n *\n * Every level is combined at least once, including a single leaf: consensus\n * duplicates a lone leaf too, so a one-tx block's root is\n * H(0x01 ‖ leaf ‖ leaf), not the bare leaf hash (checked against a mainnet\n * header, block 9,070,019).\n */\nexport function txMerkleRoot(txidsHex: string[]): string {\n\tif (txidsHex.length === 0) throw new Error(\"no transactions\");\n\tlet level = txidsHex.map((t) => tagged(LEAF_TAG, fromHex(t)));\n\tdo {\n\t\tif (level.length % 2 === 1) level.push(level[level.length - 1]);\n\t\tconst next: Uint8Array[] = [];\n\t\tfor (let i = 0; i < level.length; i += 2) {\n\t\t\tnext.push(tagged(NODE_TAG, level[i], level[i + 1]));\n\t\t}\n\t\tlevel = next;\n\t} while (level.length > 1);\n\treturn toHex(level[0]);\n}\n\n/** One authentication-path step: the sibling hash and which side it's on. */\nexport interface MerkleProofStep {\n\t/** Side the SIBLING is on relative to the accumulator. */\n\tposition: \"left\" | \"right\";\n\t/** Sibling node hash (hex). */\n\thash: string;\n}\n\n/**\n * Build the tx-inclusion authentication path for the tx at `index` in a block,\n * reproducing the consensus merkle tree (incl. duplicate-last-on-odd). The path\n * lets a verifier recompute `tx_merkle_root` from just the target txid.\n */\nexport function txMerkleProof(\n\ttxidsHex: string[],\n\tindex: number,\n): MerkleProofStep[] {\n\tif (index < 0 || index >= txidsHex.length) {\n\t\tthrow new Error(\"index out of range\");\n\t}\n\tlet level = txidsHex.map((t) => tagged(LEAF_TAG, fromHex(t)));\n\tlet idx = index;\n\tconst path: MerkleProofStep[] = [];\n\t// do-while for the same reason as txMerkleRoot: a lone leaf is paired with\n\t// itself, so a one-tx block's proof has one step (its own leaf, on the right).\n\tdo {\n\t\tif (level.length % 2 === 1) level.push(level[level.length - 1]);\n\t\tconst siblingIdx = idx % 2 === 0 ? idx + 1 : idx - 1;\n\t\tpath.push({\n\t\t\tposition: idx % 2 === 0 ? \"right\" : \"left\",\n\t\t\thash: toHex(level[siblingIdx]),\n\t\t});\n\t\tconst next: Uint8Array[] = [];\n\t\tfor (let i = 0; i < level.length; i += 2) {\n\t\t\tnext.push(tagged(NODE_TAG, level[i], level[i + 1]));\n\t\t}\n\t\tlevel = next;\n\t\tidx = Math.floor(idx / 2);\n\t} while (level.length > 1);\n\treturn path;\n}\n\n/**\n * Verify a tx-inclusion proof: fold the target `txid` (hex) up through `path`\n * and check it equals `txMerkleRoot` (hex). The verifier recomputes the txid\n * itself from the raw tx bytes, so nothing here is trusted.\n */\nexport function verifyTxMerkleProof(\n\ttxidHex: string,\n\tpath: MerkleProofStep[],\n\ttxMerkleRootHex: string,\n): boolean {\n\tlet acc = tagged(LEAF_TAG, fromHex(txidHex));\n\tfor (const step of path) {\n\t\tconst sib = fromHex(step.hash);\n\t\tacc =\n\t\t\tstep.position === \"right\"\n\t\t\t\t? tagged(NODE_TAG, acc, sib)\n\t\t\t\t: tagged(NODE_TAG, sib, acc);\n\t}\n\tconst root = txMerkleRootHex.startsWith(\"0x\")\n\t\t? txMerkleRootHex.slice(2)\n\t\t: txMerkleRootHex;\n\treturn toHex(acc) === root;\n}\n\n/**\n * Fetch and parse a Nakamoto block from a stacks-node. `blockId` is the\n * index_block_hash (with or without 0x). Returns the raw bytes + parsed header +\n * the recomputed block_hash / index_block_hash so a caller can cross-check.\n */\nexport async function fetchNakamotoBlock(opts: {\n\tnodeUrl: string;\n\tblockId: string;\n\tfetchImpl?: typeof fetch;\n}): Promise<{\n\traw: Uint8Array;\n\theader: NakamotoBlockHeader;\n\tblockHash: string;\n\tindexBlockHash: string;\n}> {\n\tconst id = opts.blockId.startsWith(\"0x\")\n\t\t? opts.blockId.slice(2)\n\t\t: opts.blockId;\n\tconst f = opts.fetchImpl ?? fetch;\n\tconst res = await f(`${opts.nodeUrl.replace(/\\/+$/, \"\")}/v3/blocks/${id}`);\n\tif (!res.ok) {\n\t\tthrow new Error(`/v3/blocks/${id} returned ${res.status}`);\n\t}\n\tconst raw = new Uint8Array(await res.arrayBuffer());\n\tconst header = parseNakamotoBlockHeader(raw);\n\tconst blockHash = nakamotoBlockHash(header);\n\treturn {\n\t\traw,\n\t\theader,\n\t\tblockHash,\n\t\tindexBlockHash: nakamotoBlockId(blockHash, header.consensusHash),\n\t};\n}\n"
|
|
7
7
|
],
|
|
8
|
-
"mappings": ";AAAA;AACA;;;ACDA;AAYO,SAAS,UAAU,CAAC,OAA+B;AAAA,EACzD,OAAO,WAAW,YAAY,EAAE,OAAO,KAAK,EAAE,OAAO;AAAA;AAGtD,IAAM,QAAQ,CAAC,MAA0B,OAAO,KAAK,CAAC,EAAE,SAAS,KAAK;AACtE,IAAM,UAAU,CAAC,MAChB,WAAW,KAAK,OAAO,KAAK,EAAE,WAAW,IAAI,IAAI,EAAE,MAAM,CAAC,IAAI,GAAG,KAAK,CAAC;AAGxE,IAAM,aAAa;AACnB,IAAM,qBAAqB;AAC3B,IAAM,qBAAqB;AAC3B,IAAM,uBAAuB;AAC7B,IAAM,gBAAgB;AACtB,IAAM,gBAAgB;AACtB,IAAM,iBAAiB;AACvB,IAAM,UAAU;AAChB,IAAM,4BAA4B;AAG3B,IAAM,yBAAyB;AAE/B,IAAM,iCAAiC;AAQvC,SAAS,6BAA6B,CAAC,SAA0B;AAAA,EACvE,QAAQ,UAAU,QAAS;AAAA;AAqC5B,SAAS,GAAG,CAAC,GAAe,KAAqB;AAAA,EAChD,OAAO,IAAI,SAAS,EAAE,QAAQ,EAAE,YAAY,EAAE,UAAU,EAAE,UAAU,GAAG;AAAA;AAExE,SAAS,GAAG,CAAC,GAAe,KAAqB;AAAA,EAChD,OAAO,IAAI,SAAS,EAAE,QAAQ,EAAE,YAAY,EAAE,UAAU,EAAE,aAAa,GAAG;A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,OAAQ,MAAM,IAAI,KAAK;AAAA,IAG7B,MAAM,UAAU,KAAK,YAAY,QAAQ,IAAI,CAAC,OAAO;AAAA,MACpD,aAAa,EAAE,YAAY,WAAW,IAAI,IACvC,EAAE,YAAY,MAAM,CAAC,IACrB,EAAE;AAAA,MACL,QAAQ,EAAE;AAAA,IACX,EAAE;AAAA,IACF,OAAO;AAAA,MACN;AAAA,MACA,cAAc,QAAQ,OAAO,CAAC,KAAK,MAAM,MAAM,EAAE,QAAQ,CAAC;AAAA,IAC3D;AAAA;AAAA,OAGK,UAAS,GAAqB;AAAA,IACnC,IAAI;AAAA,MACH,MAAM,OAAO,MAAM,KAAK,QAAQ;AAAA,MAChC,OAAO,KAAK,oBAAoB;AAAA,MAC/B,MAAM;AAAA,MACP,OAAO;AAAA;AAAA;AAAA,OAIH,eAAc,CAAC,YAAsC;AAAA,IAC1D,OAAO,eAAe,KAAK,OAAO,KAAM,GAAG,EAAE,UAAU,WAAW,CAAC;AAAA;AAAA,EAGpE,SAAS,GAAW;AAAA,IACnB,OAAO,KAAK;AAAA;AAEd;",
|
|
9
|
+
"debugId": "6DE2545AD8FD5E2064756E2164756E21",
|
|
10
10
|
"names": []
|
|
11
11
|
}
|
|
@@ -66,6 +66,11 @@ declare function stacksTxid(rawTx: Uint8Array): string;
|
|
|
66
66
|
* tx_merkle_root over the block's txids (hex), reproducing the consensus rule:
|
|
67
67
|
* leaf = H(0x00 ‖ txid), node = H(0x01 ‖ left ‖ right), odd level duplicates the
|
|
68
68
|
* last node. Returns the root hex; throws on an empty tx list.
|
|
69
|
+
*
|
|
70
|
+
* Every level is combined at least once, including a single leaf: consensus
|
|
71
|
+
* duplicates a lone leaf too, so a one-tx block's root is
|
|
72
|
+
* H(0x01 ‖ leaf ‖ leaf), not the bare leaf hash (checked against a mainnet
|
|
73
|
+
* header, block 9,070,019).
|
|
69
74
|
*/
|
|
70
75
|
declare function txMerkleRoot(txidsHex: string[]): string;
|
|
71
76
|
/** One authentication-path step: the sibling hash and which side it's on. */
|
|
@@ -122,7 +122,7 @@ function txMerkleRoot(txidsHex) {
|
|
|
122
122
|
if (txidsHex.length === 0)
|
|
123
123
|
throw new Error("no transactions");
|
|
124
124
|
let level = txidsHex.map((t) => tagged(LEAF_TAG, fromHex(t)));
|
|
125
|
-
|
|
125
|
+
do {
|
|
126
126
|
if (level.length % 2 === 1)
|
|
127
127
|
level.push(level[level.length - 1]);
|
|
128
128
|
const next = [];
|
|
@@ -130,7 +130,7 @@ function txMerkleRoot(txidsHex) {
|
|
|
130
130
|
next.push(tagged(NODE_TAG, level[i], level[i + 1]));
|
|
131
131
|
}
|
|
132
132
|
level = next;
|
|
133
|
-
}
|
|
133
|
+
} while (level.length > 1);
|
|
134
134
|
return toHex(level[0]);
|
|
135
135
|
}
|
|
136
136
|
function txMerkleProof(txidsHex, index) {
|
|
@@ -140,7 +140,7 @@ function txMerkleProof(txidsHex, index) {
|
|
|
140
140
|
let level = txidsHex.map((t) => tagged(LEAF_TAG, fromHex(t)));
|
|
141
141
|
let idx = index;
|
|
142
142
|
const path = [];
|
|
143
|
-
|
|
143
|
+
do {
|
|
144
144
|
if (level.length % 2 === 1)
|
|
145
145
|
level.push(level[level.length - 1]);
|
|
146
146
|
const siblingIdx = idx % 2 === 0 ? idx + 1 : idx - 1;
|
|
@@ -154,7 +154,7 @@ function txMerkleProof(txidsHex, index) {
|
|
|
154
154
|
}
|
|
155
155
|
level = next;
|
|
156
156
|
idx = Math.floor(idx / 2);
|
|
157
|
-
}
|
|
157
|
+
} while (level.length > 1);
|
|
158
158
|
return path;
|
|
159
159
|
}
|
|
160
160
|
function verifyTxMerkleProof(txidHex, path, txMerkleRootHex) {
|
|
@@ -198,5 +198,5 @@ export {
|
|
|
198
198
|
versionIncludesProblematicTxs
|
|
199
199
|
};
|
|
200
200
|
|
|
201
|
-
//# debugId=
|
|
201
|
+
//# debugId=315B5F852B83F8F264756E2164756E21
|
|
202
202
|
//# sourceMappingURL=nakamoto.js.map
|
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/node/nakamoto.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"import { createHash } from \"node:crypto\";\n\n/**\n * Nakamoto block-header parsing + consensus hashing for trustless verification.\n *\n * Version 0 is bit-exact against mainnet `stacks-node 3.4.0.0.3`. Version 1\n * (Epoch 4.0 / PoX-5, first mainnet height 8,665,568) appends\n * `problematic_txs` after `pox_treatment` and includes those bytes in the\n * signer-signature-hash preimage. Pre-4.0 hashes are unchanged.\n */\n\n/** SHA-512/256 — the hash Stacks uses everywhere (NOT truncated SHA-512). */\nexport function sha512_256(bytes: Uint8Array): Uint8Array {\n\treturn createHash(\"sha512-256\").update(bytes).digest();\n}\n\nconst toHex = (b: Uint8Array): string => Buffer.from(b).toString(\"hex\");\nconst fromHex = (h: string): Uint8Array =>\n\tUint8Array.from(Buffer.from(h.startsWith(\"0x\") ? h.slice(2) : h, \"hex\"));\n\n// Fixed-size header prefix: version..miner_signature, before signer_signature.\nconst PREFIX_LEN = 206;\nconst CONSENSUS_HASH_OFF = 17;\nconst TX_MERKLE_ROOT_OFF = 69;\nconst STATE_INDEX_ROOT_OFF = 101;\nconst TIMESTAMP_OFF = 133;\nconst MINER_SIG_OFF = 141;\nconst SIGNER_VEC_OFF = 206; // u32 count, then 65 bytes per signer\nconst SIG_LEN = 65;\nconst PROBLEMATIC_TX_MARKER_LEN = 5; // u32 tx_index ‖ u8 category\n\n/** Pre-Epoch-4.0 Nakamoto header. Omits `problematic_txs`. */\nexport const NAKAMOTO_BLOCK_VERSION = 0;\n/** Epoch 4.0+ header. Serializes and hashes `problematic_txs`. */\nexport const NAKAMOTO_BLOCK_VERSION_EPOCH_4 = 1;\n\nexport type ProblematicTxMarker = {\n\ttxIndex: number;\n\tcategory: number;\n};\n\n/** Low 7 bits are the header version; high bit 0x80 is the shadow-block flag. */\nexport function versionIncludesProblematicTxs(version: number): boolean {\n\treturn (version & 0x7f) >= NAKAMOTO_BLOCK_VERSION_EPOCH_4;\n}\n\nexport interface NakamotoBlockHeader {\n\tversion: number;\n\tchainLength: bigint;\n\tburnSpent: bigint;\n\t/** 20-byte consensus hash (hex). */\n\tconsensusHash: string;\n\t/** 32-byte parent StacksBlockId (hex). */\n\tparentBlockId: string;\n\t/** 32-byte SHA512/256 merkle root over the block's txids (hex). */\n\ttxMerkleRoot: string;\n\t/** 32-byte MARF root after applying this block (hex). */\n\tstateIndexRoot: string;\n\ttimestamp: bigint;\n\t/** 65-byte recoverable ECDSA miner signature (hex). */\n\tminerSignature: string;\n\t/** Per-signer recoverable ECDSA signatures, reward-set order (hex, 65B each). */\n\tsignerSignatures: string[];\n\t/** Full serialized pox_treatment BitVec bytes (u16 bits ‖ u32 len ‖ data). */\n\tpoxTreatment: Uint8Array;\n\t/**\n\t * Epoch 4.0+ marker list. Empty (and absent from the wire) on version 0.\n\t * An empty list still serializes as a u32 count of 0 on version 1+.\n\t */\n\tproblematicTxs: ProblematicTxMarker[];\n\t/**\n\t * Exact bytes whose SHA512/256 IS the block_hash / signer_signature_hash:\n\t * header minus the signer_signature vector. Version 0 is\n\t * prefix[0:206] ‖ pox; version 1+ is prefix[0:206] ‖ pox ‖ problematic_txs.\n\t */\n\tsignerSignatureHashPreimage: Uint8Array;\n\t/** Offset at which the tx `Vec` begins (= total header byte length). */\n\theaderByteLength: number;\n}\n\nfunction u32(b: Uint8Array, off: number): number {\n\treturn new DataView(b.buffer, b.byteOffset, b.byteLength).getUint32(off);\n}\nfunction u64(b: Uint8Array, off: number): bigint {\n\treturn new DataView(b.buffer, b.byteOffset, b.byteLength).getBigUint64(off);\n}\n\n/** Parse the Nakamoto block header from the raw `/v3/blocks` body. */\nexport function parseNakamotoBlockHeader(raw: Uint8Array): NakamotoBlockHeader {\n\tif (raw.length < PREFIX_LEN + 4) {\n\t\tthrow new Error(\"raw block too short for a Nakamoto header\");\n\t}\n\tconst version = raw[0];\n\tconst signerCount = u32(raw, SIGNER_VEC_OFF);\n\tconst sigsStart = SIGNER_VEC_OFF + 4;\n\tif (sigsStart + signerCount * SIG_LEN > raw.length) {\n\t\tthrow new Error(\"raw block truncated in signer_signature vector\");\n\t}\n\tconst signerSignatures: string[] = [];\n\tfor (let i = 0; i < signerCount; i++) {\n\t\tconst off = sigsStart + i * SIG_LEN;\n\t\tsignerSignatures.push(toHex(raw.subarray(off, off + SIG_LEN)));\n\t}\n\t// pox_treatment: u16 num_bits ‖ u32 data_len ‖ data[data_len].\n\tconst poxOff = sigsStart + signerCount * SIG_LEN;\n\tif (poxOff + 6 > raw.length) {\n\t\tthrow new Error(\"raw block truncated in pox_treatment\");\n\t}\n\tconst poxDataLen = u32(raw, poxOff + 2);\n\tconst poxEnd = poxOff + 6 + poxDataLen;\n\tif (poxEnd > raw.length) {\n\t\tthrow new Error(\"raw block truncated in pox_treatment data\");\n\t}\n\tconst poxTreatment = raw.subarray(poxOff, poxEnd);\n\n\t// Epoch 4.0+ (version low-7-bits >= 1): Vec<ProblematicTxMarker>\n\t// after pox_treatment. Version 0 omits the field entirely so pre-fork\n\t// hashes stay byte-identical.\n\tlet headerEnd = poxEnd;\n\tconst problematicTxs: ProblematicTxMarker[] = [];\n\tif (versionIncludesProblematicTxs(version)) {\n\t\tif (poxEnd + 4 > raw.length) {\n\t\t\tthrow new Error(\"raw block truncated in problematic_txs count\");\n\t\t}\n\t\tconst markerCount = u32(raw, poxEnd);\n\t\theaderEnd = poxEnd + 4 + markerCount * PROBLEMATIC_TX_MARKER_LEN;\n\t\tif (headerEnd > raw.length) {\n\t\t\tthrow new Error(\"raw block truncated in problematic_txs list\");\n\t\t}\n\t\tfor (let i = 0; i < markerCount; i++) {\n\t\t\tconst off = poxEnd + 4 + i * PROBLEMATIC_TX_MARKER_LEN;\n\t\t\tproblematicTxs.push({\n\t\t\t\ttxIndex: u32(raw, off),\n\t\t\t\tcategory: raw[off + 4] ?? 0,\n\t\t\t});\n\t\t}\n\t}\n\n\t// block_hash preimage = header minus signer_signature.\n\t// v0: prefix[0:206] ‖ pox\n\t// v1: prefix[0:206] ‖ pox ‖ problematic_txs (count + markers)\n\tconst markersBytes = raw.subarray(poxEnd, headerEnd);\n\tconst preimage = new Uint8Array(\n\t\tPREFIX_LEN + poxTreatment.length + markersBytes.length,\n\t);\n\tpreimage.set(raw.subarray(0, PREFIX_LEN), 0);\n\tpreimage.set(poxTreatment, PREFIX_LEN);\n\tpreimage.set(markersBytes, PREFIX_LEN + poxTreatment.length);\n\n\treturn {\n\t\tversion,\n\t\tchainLength: u64(raw, 1),\n\t\tburnSpent: u64(raw, 9),\n\t\tconsensusHash: toHex(\n\t\t\traw.subarray(CONSENSUS_HASH_OFF, CONSENSUS_HASH_OFF + 20),\n\t\t),\n\t\tparentBlockId: toHex(raw.subarray(37, 69)),\n\t\ttxMerkleRoot: toHex(\n\t\t\traw.subarray(TX_MERKLE_ROOT_OFF, TX_MERKLE_ROOT_OFF + 32),\n\t\t),\n\t\tstateIndexRoot: toHex(\n\t\t\traw.subarray(STATE_INDEX_ROOT_OFF, STATE_INDEX_ROOT_OFF + 32),\n\t\t),\n\t\ttimestamp: u64(raw, TIMESTAMP_OFF),\n\t\tminerSignature: toHex(raw.subarray(MINER_SIG_OFF, MINER_SIG_OFF + SIG_LEN)),\n\t\tsignerSignatures,\n\t\tpoxTreatment,\n\t\tproblematicTxs,\n\t\tsignerSignatureHashPreimage: preimage,\n\t\theaderByteLength: headerEnd,\n\t};\n}\n\n/**\n * block_hash (== signer_signature_hash): SHA512/256 over the header with the\n * signer_signature vector omitted. This is what each signer signs.\n */\nexport function nakamotoBlockHash(header: NakamotoBlockHeader): string {\n\treturn toHex(sha512_256(header.signerSignatureHashPreimage));\n}\n\n/** index_block_hash (StacksBlockId) = SHA512/256(block_hash ‖ consensus_hash). */\nexport function nakamotoBlockId(\n\tblockHashHex: string,\n\tconsensusHashHex: string,\n): string {\n\tconst a = fromHex(blockHashHex);\n\tconst b = fromHex(consensusHashHex);\n\tconst buf = new Uint8Array(a.length + b.length);\n\tbuf.set(a, 0);\n\tbuf.set(b, a.length);\n\treturn toHex(sha512_256(buf));\n}\n\n/** A Stacks txid = SHA512/256 of the transaction's consensus serialization. */\nexport function stacksTxid(rawTx: Uint8Array): string {\n\treturn toHex(sha512_256(rawTx));\n}\n\nconst LEAF_TAG = 0x00;\nconst NODE_TAG = 0x01;\n\nfunction tagged(tag: number, ...parts: Uint8Array[]): Uint8Array {\n\tconst len = parts.reduce((n, p) => n + p.length, 1);\n\tconst buf = new Uint8Array(len);\n\tbuf[0] = tag;\n\tlet o = 1;\n\tfor (const p of parts) {\n\t\tbuf.set(p, o);\n\t\to += p.length;\n\t}\n\treturn sha512_256(buf);\n}\n\n/**\n * tx_merkle_root over the block's txids (hex), reproducing the consensus rule:\n * leaf = H(0x00 ‖ txid), node = H(0x01 ‖ left ‖ right), odd level duplicates the\n * last node. Returns the root hex; throws on an empty tx list.\n */\nexport function txMerkleRoot(txidsHex: string[]): string {\n\tif (txidsHex.length === 0) throw new Error(\"no transactions\");\n\tlet level = txidsHex.map((t) => tagged(LEAF_TAG, fromHex(t)));\n\twhile (level.length > 1) {\n\t\tif (level.length % 2 === 1) level.push(level[level.length - 1]);\n\t\tconst next: Uint8Array[] = [];\n\t\tfor (let i = 0; i < level.length; i += 2) {\n\t\t\tnext.push(tagged(NODE_TAG, level[i], level[i + 1]));\n\t\t}\n\t\tlevel = next;\n\t}\n\treturn toHex(level[0]);\n}\n\n/** One authentication-path step: the sibling hash and which side it's on. */\nexport interface MerkleProofStep {\n\t/** Side the SIBLING is on relative to the accumulator. */\n\tposition: \"left\" | \"right\";\n\t/** Sibling node hash (hex). */\n\thash: string;\n}\n\n/**\n * Build the tx-inclusion authentication path for the tx at `index` in a block,\n * reproducing the consensus merkle tree (incl. duplicate-last-on-odd). The path\n * lets a verifier recompute `tx_merkle_root` from just the target txid.\n */\nexport function txMerkleProof(\n\ttxidsHex: string[],\n\tindex: number,\n): MerkleProofStep[] {\n\tif (index < 0 || index >= txidsHex.length) {\n\t\tthrow new Error(\"index out of range\");\n\t}\n\tlet level = txidsHex.map((t) => tagged(LEAF_TAG, fromHex(t)));\n\tlet idx = index;\n\tconst path: MerkleProofStep[] = [];\n\twhile (level.length > 1) {\n\t\tif (level.length % 2 === 1) level.push(level[level.length - 1]);\n\t\tconst siblingIdx = idx % 2 === 0 ? idx + 1 : idx - 1;\n\t\tpath.push({\n\t\t\tposition: idx % 2 === 0 ? \"right\" : \"left\",\n\t\t\thash: toHex(level[siblingIdx]),\n\t\t});\n\t\tconst next: Uint8Array[] = [];\n\t\tfor (let i = 0; i < level.length; i += 2) {\n\t\t\tnext.push(tagged(NODE_TAG, level[i], level[i + 1]));\n\t\t}\n\t\tlevel = next;\n\t\tidx = Math.floor(idx / 2);\n\t}\n\treturn path;\n}\n\n/**\n * Verify a tx-inclusion proof: fold the target `txid` (hex) up through `path`\n * and check it equals `txMerkleRoot` (hex). The verifier recomputes the txid\n * itself from the raw tx bytes, so nothing here is trusted.\n */\nexport function verifyTxMerkleProof(\n\ttxidHex: string,\n\tpath: MerkleProofStep[],\n\ttxMerkleRootHex: string,\n): boolean {\n\tlet acc = tagged(LEAF_TAG, fromHex(txidHex));\n\tfor (const step of path) {\n\t\tconst sib = fromHex(step.hash);\n\t\tacc =\n\t\t\tstep.position === \"right\"\n\t\t\t\t? tagged(NODE_TAG, acc, sib)\n\t\t\t\t: tagged(NODE_TAG, sib, acc);\n\t}\n\tconst root = txMerkleRootHex.startsWith(\"0x\")\n\t\t? txMerkleRootHex.slice(2)\n\t\t: txMerkleRootHex;\n\treturn toHex(acc) === root;\n}\n\n/**\n * Fetch and parse a Nakamoto block from a stacks-node. `blockId` is the\n * index_block_hash (with or without 0x). Returns the raw bytes + parsed header +\n * the recomputed block_hash / index_block_hash so a caller can cross-check.\n */\nexport async function fetchNakamotoBlock(opts: {\n\tnodeUrl: string;\n\tblockId: string;\n\tfetchImpl?: typeof fetch;\n}): Promise<{\n\traw: Uint8Array;\n\theader: NakamotoBlockHeader;\n\tblockHash: string;\n\tindexBlockHash: string;\n}> {\n\tconst id = opts.blockId.startsWith(\"0x\")\n\t\t? opts.blockId.slice(2)\n\t\t: opts.blockId;\n\tconst f = opts.fetchImpl ?? fetch;\n\tconst res = await f(`${opts.nodeUrl.replace(/\\/+$/, \"\")}/v3/blocks/${id}`);\n\tif (!res.ok) {\n\t\tthrow new Error(`/v3/blocks/${id} returned ${res.status}`);\n\t}\n\tconst raw = new Uint8Array(await res.arrayBuffer());\n\tconst header = parseNakamotoBlockHeader(raw);\n\tconst blockHash = nakamotoBlockHash(header);\n\treturn {\n\t\traw,\n\t\theader,\n\t\tblockHash,\n\t\tindexBlockHash: nakamotoBlockId(blockHash, header.consensusHash),\n\t};\n}\n"
|
|
5
|
+
"import { createHash } from \"node:crypto\";\n\n/**\n * Nakamoto block-header parsing + consensus hashing for trustless verification.\n *\n * Version 0 is bit-exact against mainnet `stacks-node 3.4.0.0.3`. Version 1\n * (Epoch 4.0 / PoX-5, first mainnet height 8,665,568) appends\n * `problematic_txs` after `pox_treatment` and includes those bytes in the\n * signer-signature-hash preimage. Pre-4.0 hashes are unchanged.\n */\n\n/** SHA-512/256 — the hash Stacks uses everywhere (NOT truncated SHA-512). */\nexport function sha512_256(bytes: Uint8Array): Uint8Array {\n\treturn createHash(\"sha512-256\").update(bytes).digest();\n}\n\nconst toHex = (b: Uint8Array): string => Buffer.from(b).toString(\"hex\");\nconst fromHex = (h: string): Uint8Array =>\n\tUint8Array.from(Buffer.from(h.startsWith(\"0x\") ? h.slice(2) : h, \"hex\"));\n\n// Fixed-size header prefix: version..miner_signature, before signer_signature.\nconst PREFIX_LEN = 206;\nconst CONSENSUS_HASH_OFF = 17;\nconst TX_MERKLE_ROOT_OFF = 69;\nconst STATE_INDEX_ROOT_OFF = 101;\nconst TIMESTAMP_OFF = 133;\nconst MINER_SIG_OFF = 141;\nconst SIGNER_VEC_OFF = 206; // u32 count, then 65 bytes per signer\nconst SIG_LEN = 65;\nconst PROBLEMATIC_TX_MARKER_LEN = 5; // u32 tx_index ‖ u8 category\n\n/** Pre-Epoch-4.0 Nakamoto header. Omits `problematic_txs`. */\nexport const NAKAMOTO_BLOCK_VERSION = 0;\n/** Epoch 4.0+ header. Serializes and hashes `problematic_txs`. */\nexport const NAKAMOTO_BLOCK_VERSION_EPOCH_4 = 1;\n\nexport type ProblematicTxMarker = {\n\ttxIndex: number;\n\tcategory: number;\n};\n\n/** Low 7 bits are the header version; high bit 0x80 is the shadow-block flag. */\nexport function versionIncludesProblematicTxs(version: number): boolean {\n\treturn (version & 0x7f) >= NAKAMOTO_BLOCK_VERSION_EPOCH_4;\n}\n\nexport interface NakamotoBlockHeader {\n\tversion: number;\n\tchainLength: bigint;\n\tburnSpent: bigint;\n\t/** 20-byte consensus hash (hex). */\n\tconsensusHash: string;\n\t/** 32-byte parent StacksBlockId (hex). */\n\tparentBlockId: string;\n\t/** 32-byte SHA512/256 merkle root over the block's txids (hex). */\n\ttxMerkleRoot: string;\n\t/** 32-byte MARF root after applying this block (hex). */\n\tstateIndexRoot: string;\n\ttimestamp: bigint;\n\t/** 65-byte recoverable ECDSA miner signature (hex). */\n\tminerSignature: string;\n\t/** Per-signer recoverable ECDSA signatures, reward-set order (hex, 65B each). */\n\tsignerSignatures: string[];\n\t/** Full serialized pox_treatment BitVec bytes (u16 bits ‖ u32 len ‖ data). */\n\tpoxTreatment: Uint8Array;\n\t/**\n\t * Epoch 4.0+ marker list. Empty (and absent from the wire) on version 0.\n\t * An empty list still serializes as a u32 count of 0 on version 1+.\n\t */\n\tproblematicTxs: ProblematicTxMarker[];\n\t/**\n\t * Exact bytes whose SHA512/256 IS the block_hash / signer_signature_hash:\n\t * header minus the signer_signature vector. Version 0 is\n\t * prefix[0:206] ‖ pox; version 1+ is prefix[0:206] ‖ pox ‖ problematic_txs.\n\t */\n\tsignerSignatureHashPreimage: Uint8Array;\n\t/** Offset at which the tx `Vec` begins (= total header byte length). */\n\theaderByteLength: number;\n}\n\nfunction u32(b: Uint8Array, off: number): number {\n\treturn new DataView(b.buffer, b.byteOffset, b.byteLength).getUint32(off);\n}\nfunction u64(b: Uint8Array, off: number): bigint {\n\treturn new DataView(b.buffer, b.byteOffset, b.byteLength).getBigUint64(off);\n}\n\n/** Parse the Nakamoto block header from the raw `/v3/blocks` body. */\nexport function parseNakamotoBlockHeader(raw: Uint8Array): NakamotoBlockHeader {\n\tif (raw.length < PREFIX_LEN + 4) {\n\t\tthrow new Error(\"raw block too short for a Nakamoto header\");\n\t}\n\tconst version = raw[0];\n\tconst signerCount = u32(raw, SIGNER_VEC_OFF);\n\tconst sigsStart = SIGNER_VEC_OFF + 4;\n\tif (sigsStart + signerCount * SIG_LEN > raw.length) {\n\t\tthrow new Error(\"raw block truncated in signer_signature vector\");\n\t}\n\tconst signerSignatures: string[] = [];\n\tfor (let i = 0; i < signerCount; i++) {\n\t\tconst off = sigsStart + i * SIG_LEN;\n\t\tsignerSignatures.push(toHex(raw.subarray(off, off + SIG_LEN)));\n\t}\n\t// pox_treatment: u16 num_bits ‖ u32 data_len ‖ data[data_len].\n\tconst poxOff = sigsStart + signerCount * SIG_LEN;\n\tif (poxOff + 6 > raw.length) {\n\t\tthrow new Error(\"raw block truncated in pox_treatment\");\n\t}\n\tconst poxDataLen = u32(raw, poxOff + 2);\n\tconst poxEnd = poxOff + 6 + poxDataLen;\n\tif (poxEnd > raw.length) {\n\t\tthrow new Error(\"raw block truncated in pox_treatment data\");\n\t}\n\tconst poxTreatment = raw.subarray(poxOff, poxEnd);\n\n\t// Epoch 4.0+ (version low-7-bits >= 1): Vec<ProblematicTxMarker>\n\t// after pox_treatment. Version 0 omits the field entirely so pre-fork\n\t// hashes stay byte-identical.\n\tlet headerEnd = poxEnd;\n\tconst problematicTxs: ProblematicTxMarker[] = [];\n\tif (versionIncludesProblematicTxs(version)) {\n\t\tif (poxEnd + 4 > raw.length) {\n\t\t\tthrow new Error(\"raw block truncated in problematic_txs count\");\n\t\t}\n\t\tconst markerCount = u32(raw, poxEnd);\n\t\theaderEnd = poxEnd + 4 + markerCount * PROBLEMATIC_TX_MARKER_LEN;\n\t\tif (headerEnd > raw.length) {\n\t\t\tthrow new Error(\"raw block truncated in problematic_txs list\");\n\t\t}\n\t\tfor (let i = 0; i < markerCount; i++) {\n\t\t\tconst off = poxEnd + 4 + i * PROBLEMATIC_TX_MARKER_LEN;\n\t\t\tproblematicTxs.push({\n\t\t\t\ttxIndex: u32(raw, off),\n\t\t\t\tcategory: raw[off + 4] ?? 0,\n\t\t\t});\n\t\t}\n\t}\n\n\t// block_hash preimage = header minus signer_signature.\n\t// v0: prefix[0:206] ‖ pox\n\t// v1: prefix[0:206] ‖ pox ‖ problematic_txs (count + markers)\n\tconst markersBytes = raw.subarray(poxEnd, headerEnd);\n\tconst preimage = new Uint8Array(\n\t\tPREFIX_LEN + poxTreatment.length + markersBytes.length,\n\t);\n\tpreimage.set(raw.subarray(0, PREFIX_LEN), 0);\n\tpreimage.set(poxTreatment, PREFIX_LEN);\n\tpreimage.set(markersBytes, PREFIX_LEN + poxTreatment.length);\n\n\treturn {\n\t\tversion,\n\t\tchainLength: u64(raw, 1),\n\t\tburnSpent: u64(raw, 9),\n\t\tconsensusHash: toHex(\n\t\t\traw.subarray(CONSENSUS_HASH_OFF, CONSENSUS_HASH_OFF + 20),\n\t\t),\n\t\tparentBlockId: toHex(raw.subarray(37, 69)),\n\t\ttxMerkleRoot: toHex(\n\t\t\traw.subarray(TX_MERKLE_ROOT_OFF, TX_MERKLE_ROOT_OFF + 32),\n\t\t),\n\t\tstateIndexRoot: toHex(\n\t\t\traw.subarray(STATE_INDEX_ROOT_OFF, STATE_INDEX_ROOT_OFF + 32),\n\t\t),\n\t\ttimestamp: u64(raw, TIMESTAMP_OFF),\n\t\tminerSignature: toHex(raw.subarray(MINER_SIG_OFF, MINER_SIG_OFF + SIG_LEN)),\n\t\tsignerSignatures,\n\t\tpoxTreatment,\n\t\tproblematicTxs,\n\t\tsignerSignatureHashPreimage: preimage,\n\t\theaderByteLength: headerEnd,\n\t};\n}\n\n/**\n * block_hash (== signer_signature_hash): SHA512/256 over the header with the\n * signer_signature vector omitted. This is what each signer signs.\n */\nexport function nakamotoBlockHash(header: NakamotoBlockHeader): string {\n\treturn toHex(sha512_256(header.signerSignatureHashPreimage));\n}\n\n/** index_block_hash (StacksBlockId) = SHA512/256(block_hash ‖ consensus_hash). */\nexport function nakamotoBlockId(\n\tblockHashHex: string,\n\tconsensusHashHex: string,\n): string {\n\tconst a = fromHex(blockHashHex);\n\tconst b = fromHex(consensusHashHex);\n\tconst buf = new Uint8Array(a.length + b.length);\n\tbuf.set(a, 0);\n\tbuf.set(b, a.length);\n\treturn toHex(sha512_256(buf));\n}\n\n/** A Stacks txid = SHA512/256 of the transaction's consensus serialization. */\nexport function stacksTxid(rawTx: Uint8Array): string {\n\treturn toHex(sha512_256(rawTx));\n}\n\nconst LEAF_TAG = 0x00;\nconst NODE_TAG = 0x01;\n\nfunction tagged(tag: number, ...parts: Uint8Array[]): Uint8Array {\n\tconst len = parts.reduce((n, p) => n + p.length, 1);\n\tconst buf = new Uint8Array(len);\n\tbuf[0] = tag;\n\tlet o = 1;\n\tfor (const p of parts) {\n\t\tbuf.set(p, o);\n\t\to += p.length;\n\t}\n\treturn sha512_256(buf);\n}\n\n/**\n * tx_merkle_root over the block's txids (hex), reproducing the consensus rule:\n * leaf = H(0x00 ‖ txid), node = H(0x01 ‖ left ‖ right), odd level duplicates the\n * last node. Returns the root hex; throws on an empty tx list.\n *\n * Every level is combined at least once, including a single leaf: consensus\n * duplicates a lone leaf too, so a one-tx block's root is\n * H(0x01 ‖ leaf ‖ leaf), not the bare leaf hash (checked against a mainnet\n * header, block 9,070,019).\n */\nexport function txMerkleRoot(txidsHex: string[]): string {\n\tif (txidsHex.length === 0) throw new Error(\"no transactions\");\n\tlet level = txidsHex.map((t) => tagged(LEAF_TAG, fromHex(t)));\n\tdo {\n\t\tif (level.length % 2 === 1) level.push(level[level.length - 1]);\n\t\tconst next: Uint8Array[] = [];\n\t\tfor (let i = 0; i < level.length; i += 2) {\n\t\t\tnext.push(tagged(NODE_TAG, level[i], level[i + 1]));\n\t\t}\n\t\tlevel = next;\n\t} while (level.length > 1);\n\treturn toHex(level[0]);\n}\n\n/** One authentication-path step: the sibling hash and which side it's on. */\nexport interface MerkleProofStep {\n\t/** Side the SIBLING is on relative to the accumulator. */\n\tposition: \"left\" | \"right\";\n\t/** Sibling node hash (hex). */\n\thash: string;\n}\n\n/**\n * Build the tx-inclusion authentication path for the tx at `index` in a block,\n * reproducing the consensus merkle tree (incl. duplicate-last-on-odd). The path\n * lets a verifier recompute `tx_merkle_root` from just the target txid.\n */\nexport function txMerkleProof(\n\ttxidsHex: string[],\n\tindex: number,\n): MerkleProofStep[] {\n\tif (index < 0 || index >= txidsHex.length) {\n\t\tthrow new Error(\"index out of range\");\n\t}\n\tlet level = txidsHex.map((t) => tagged(LEAF_TAG, fromHex(t)));\n\tlet idx = index;\n\tconst path: MerkleProofStep[] = [];\n\t// do-while for the same reason as txMerkleRoot: a lone leaf is paired with\n\t// itself, so a one-tx block's proof has one step (its own leaf, on the right).\n\tdo {\n\t\tif (level.length % 2 === 1) level.push(level[level.length - 1]);\n\t\tconst siblingIdx = idx % 2 === 0 ? idx + 1 : idx - 1;\n\t\tpath.push({\n\t\t\tposition: idx % 2 === 0 ? \"right\" : \"left\",\n\t\t\thash: toHex(level[siblingIdx]),\n\t\t});\n\t\tconst next: Uint8Array[] = [];\n\t\tfor (let i = 0; i < level.length; i += 2) {\n\t\t\tnext.push(tagged(NODE_TAG, level[i], level[i + 1]));\n\t\t}\n\t\tlevel = next;\n\t\tidx = Math.floor(idx / 2);\n\t} while (level.length > 1);\n\treturn path;\n}\n\n/**\n * Verify a tx-inclusion proof: fold the target `txid` (hex) up through `path`\n * and check it equals `txMerkleRoot` (hex). The verifier recomputes the txid\n * itself from the raw tx bytes, so nothing here is trusted.\n */\nexport function verifyTxMerkleProof(\n\ttxidHex: string,\n\tpath: MerkleProofStep[],\n\ttxMerkleRootHex: string,\n): boolean {\n\tlet acc = tagged(LEAF_TAG, fromHex(txidHex));\n\tfor (const step of path) {\n\t\tconst sib = fromHex(step.hash);\n\t\tacc =\n\t\t\tstep.position === \"right\"\n\t\t\t\t? tagged(NODE_TAG, acc, sib)\n\t\t\t\t: tagged(NODE_TAG, sib, acc);\n\t}\n\tconst root = txMerkleRootHex.startsWith(\"0x\")\n\t\t? txMerkleRootHex.slice(2)\n\t\t: txMerkleRootHex;\n\treturn toHex(acc) === root;\n}\n\n/**\n * Fetch and parse a Nakamoto block from a stacks-node. `blockId` is the\n * index_block_hash (with or without 0x). Returns the raw bytes + parsed header +\n * the recomputed block_hash / index_block_hash so a caller can cross-check.\n */\nexport async function fetchNakamotoBlock(opts: {\n\tnodeUrl: string;\n\tblockId: string;\n\tfetchImpl?: typeof fetch;\n}): Promise<{\n\traw: Uint8Array;\n\theader: NakamotoBlockHeader;\n\tblockHash: string;\n\tindexBlockHash: string;\n}> {\n\tconst id = opts.blockId.startsWith(\"0x\")\n\t\t? opts.blockId.slice(2)\n\t\t: opts.blockId;\n\tconst f = opts.fetchImpl ?? fetch;\n\tconst res = await f(`${opts.nodeUrl.replace(/\\/+$/, \"\")}/v3/blocks/${id}`);\n\tif (!res.ok) {\n\t\tthrow new Error(`/v3/blocks/${id} returned ${res.status}`);\n\t}\n\tconst raw = new Uint8Array(await res.arrayBuffer());\n\tconst header = parseNakamotoBlockHeader(raw);\n\tconst blockHash = nakamotoBlockHash(header);\n\treturn {\n\t\traw,\n\t\theader,\n\t\tblockHash,\n\t\tindexBlockHash: nakamotoBlockId(blockHash, header.consensusHash),\n\t};\n}\n"
|
|
6
6
|
],
|
|
7
|
-
"mappings": ";AAAA;AAYO,SAAS,UAAU,CAAC,OAA+B;AAAA,EACzD,OAAO,WAAW,YAAY,EAAE,OAAO,KAAK,EAAE,OAAO;AAAA;AAGtD,IAAM,QAAQ,CAAC,MAA0B,OAAO,KA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