@secondlayer/shared 11.14.1 → 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/archive/range-digest.d.ts +3 -0
- package/dist/src/archive/semantic-digest-builder.d.ts +3 -0
- package/dist/src/coverage/index.d.ts +3 -0
- package/dist/src/db/index.d.ts +3 -0
- package/dist/src/db/queries/chain-reorgs.d.ts +3 -0
- package/dist/src/db/queries/contracts.d.ts +3 -0
- package/dist/src/db/queries/instance.d.ts +3 -0
- package/dist/src/db/queries/integrity.d.ts +28 -1
- package/dist/src/db/queries/integrity.js +25 -2
- package/dist/src/db/queries/integrity.js.map +3 -3
- package/dist/src/db/queries/subgraph-gaps.d.ts +3 -0
- package/dist/src/db/queries/subgraph-operations.d.ts +3 -0
- package/dist/src/db/queries/subgraphs.d.ts +3 -0
- package/dist/src/db/queries/sync-scope.d.ts +3 -0
- package/dist/src/db/queries/webhooks.d.ts +3 -0
- package/dist/src/db/schema.d.ts +3 -0
- package/dist/src/index.d.ts +3 -0
- package/dist/src/node/client.js +5 -5
- package/dist/src/node/client.js.map +3 -3
- package/dist/src/node/local-client.d.ts +3 -0
- package/dist/src/node/nakamoto.d.ts +5 -0
- package/dist/src/node/nakamoto.js +5 -5
- package/dist/src/node/nakamoto.js.map +3 -3
- package/dist/src/types.d.ts +3 -0
- package/migrations/0143_blocks_tx_count.ts +24 -0
- package/package.json +1 -1
|
@@ -29,6 +29,9 @@ interface BlocksTable {
|
|
|
29
29
|
index_block_hash: ColumnType<string | null, string | null | undefined, string | null>;
|
|
30
30
|
timestamp: number;
|
|
31
31
|
canonical: Generated<boolean>;
|
|
32
|
+
/** Tx count `persistBlock` was handed for this height. Null on rows
|
|
33
|
+
* ingested before this column existed. */
|
|
34
|
+
tx_count: ColumnType<number | null, number | null | undefined, number | null>;
|
|
32
35
|
created_at: Generated<Date>;
|
|
33
36
|
}
|
|
34
37
|
interface TransactionsTable {
|
|
@@ -29,6 +29,9 @@ interface BlocksTable {
|
|
|
29
29
|
index_block_hash: ColumnType<string | null, string | null | undefined, string | null>;
|
|
30
30
|
timestamp: number;
|
|
31
31
|
canonical: Generated<boolean>;
|
|
32
|
+
/** Tx count `persistBlock` was handed for this height. Null on rows
|
|
33
|
+
* ingested before this column existed. */
|
|
34
|
+
tx_count: ColumnType<number | null, number | null | undefined, number | null>;
|
|
32
35
|
created_at: Generated<Date>;
|
|
33
36
|
}
|
|
34
37
|
interface TransactionsTable {
|
|
@@ -346,6 +346,9 @@ interface BlocksTable {
|
|
|
346
346
|
index_block_hash: ColumnType<string | null, string | null | undefined, string | null>;
|
|
347
347
|
timestamp: number;
|
|
348
348
|
canonical: Generated<boolean>;
|
|
349
|
+
/** Tx count `persistBlock` was handed for this height. Null on rows
|
|
350
|
+
* ingested before this column existed. */
|
|
351
|
+
tx_count: ColumnType<number | null, number | null | undefined, number | null>;
|
|
349
352
|
created_at: Generated<Date>;
|
|
350
353
|
}
|
|
351
354
|
interface TransactionsTable {
|
package/dist/src/db/index.d.ts
CHANGED
|
@@ -30,6 +30,9 @@ interface BlocksTable {
|
|
|
30
30
|
index_block_hash: ColumnType<string | null, string | null | undefined, string | null>;
|
|
31
31
|
timestamp: number;
|
|
32
32
|
canonical: Generated<boolean>;
|
|
33
|
+
/** Tx count `persistBlock` was handed for this height. Null on rows
|
|
34
|
+
* ingested before this column existed. */
|
|
35
|
+
tx_count: ColumnType<number | null, number | null | undefined, number | null>;
|
|
33
36
|
created_at: Generated<Date>;
|
|
34
37
|
}
|
|
35
38
|
interface TransactionsTable {
|
|
@@ -29,6 +29,9 @@ interface BlocksTable {
|
|
|
29
29
|
index_block_hash: ColumnType<string | null, string | null | undefined, string | null>;
|
|
30
30
|
timestamp: number;
|
|
31
31
|
canonical: Generated<boolean>;
|
|
32
|
+
/** Tx count `persistBlock` was handed for this height. Null on rows
|
|
33
|
+
* ingested before this column existed. */
|
|
34
|
+
tx_count: ColumnType<number | null, number | null | undefined, number | null>;
|
|
32
35
|
created_at: Generated<Date>;
|
|
33
36
|
}
|
|
34
37
|
interface TransactionsTable {
|
|
@@ -29,6 +29,9 @@ interface BlocksTable {
|
|
|
29
29
|
index_block_hash: ColumnType<string | null, string | null | undefined, string | null>;
|
|
30
30
|
timestamp: number;
|
|
31
31
|
canonical: Generated<boolean>;
|
|
32
|
+
/** Tx count `persistBlock` was handed for this height. Null on rows
|
|
33
|
+
* ingested before this column existed. */
|
|
34
|
+
tx_count: ColumnType<number | null, number | null | undefined, number | null>;
|
|
32
35
|
created_at: Generated<Date>;
|
|
33
36
|
}
|
|
34
37
|
interface TransactionsTable {
|
|
@@ -29,6 +29,9 @@ interface BlocksTable {
|
|
|
29
29
|
index_block_hash: ColumnType<string | null, string | null | undefined, string | null>;
|
|
30
30
|
timestamp: number;
|
|
31
31
|
canonical: Generated<boolean>;
|
|
32
|
+
/** Tx count `persistBlock` was handed for this height. Null on rows
|
|
33
|
+
* ingested before this column existed. */
|
|
34
|
+
tx_count: ColumnType<number | null, number | null | undefined, number | null>;
|
|
32
35
|
created_at: Generated<Date>;
|
|
33
36
|
}
|
|
34
37
|
interface TransactionsTable {
|
|
@@ -29,6 +29,9 @@ interface BlocksTable {
|
|
|
29
29
|
index_block_hash: ColumnType<string | null, string | null | undefined, string | null>;
|
|
30
30
|
timestamp: number;
|
|
31
31
|
canonical: Generated<boolean>;
|
|
32
|
+
/** Tx count `persistBlock` was handed for this height. Null on rows
|
|
33
|
+
* ingested before this column existed. */
|
|
34
|
+
tx_count: ColumnType<number | null, number | null | undefined, number | null>;
|
|
32
35
|
created_at: Generated<Date>;
|
|
33
36
|
}
|
|
34
37
|
interface TransactionsTable {
|
|
@@ -995,6 +998,30 @@ declare function checkChainDataIntegrity(db: Kysely<Database>, opts?: {
|
|
|
995
998
|
lookback?: number
|
|
996
999
|
}): Promise<ChainDataIntegrity>;
|
|
997
1000
|
declare function computeContiguousTip(db: Kysely<Database>, fromHeight: number): Promise<number>;
|
|
1001
|
+
type ShortBlock = {
|
|
1002
|
+
height: number
|
|
1003
|
+
expectedTxCount: number
|
|
1004
|
+
actualTxCount: number
|
|
1005
|
+
};
|
|
1006
|
+
/**
|
|
1007
|
+
* Canonical heights where `transactions` holds fewer (or more) rows than the
|
|
1008
|
+
* block was supposed to. `blocks.tx_count` is set by `persistBlock` from the
|
|
1009
|
+
* incoming block, so a mismatch means a later write silently moved or dropped
|
|
1010
|
+
* a tx after that block was persisted — a reorg replaying the wrong height, a
|
|
1011
|
+
* same-height tx_id collision, or a bug in the persist path itself. Ingest
|
|
1012
|
+
* used to report the *parsed* count, not the inserted count, so this kind of
|
|
1013
|
+
* short block was invisible; a skipped insert looked identical to success.
|
|
1014
|
+
*
|
|
1015
|
+
* Scoped to heights with `tx_count IS NOT NULL` — rows ingested before this
|
|
1016
|
+
* column existed have no baseline to check against. Also scoped to a recent
|
|
1017
|
+
* window by default (like `findBrokenLinks`): every new block sets
|
|
1018
|
+
* `tx_count`, so the eligible range only grows, and a short block is an
|
|
1019
|
+
* active-repair concern, not something worth a full-table scan every cycle.
|
|
1020
|
+
*/
|
|
1021
|
+
declare function findShortBlocks(db: Kysely<Database>, opts?: {
|
|
1022
|
+
window?: number | null
|
|
1023
|
+
limit?: number
|
|
1024
|
+
}): Promise<ShortBlock[]>;
|
|
998
1025
|
type BrokenLink = {
|
|
999
1026
|
height: number
|
|
1000
1027
|
hash: string
|
|
@@ -1020,4 +1047,4 @@ declare function findBrokenLinks(db: Kysely<Database>, opts?: {
|
|
|
1020
1047
|
window?: number | null
|
|
1021
1048
|
limit?: number
|
|
1022
1049
|
}): Promise<BrokenLink[]>;
|
|
1023
|
-
export { BrokenLink, ChainDataIntegrity, Gap, checkChainDataIntegrity, computeContiguousTip, countMissingBlocks, findBrokenLinks, findGaps };
|
|
1050
|
+
export { BrokenLink, ChainDataIntegrity, Gap, ShortBlock, checkChainDataIntegrity, computeContiguousTip, countMissingBlocks, findBrokenLinks, findGaps, findShortBlocks };
|
|
@@ -76,6 +76,28 @@ async function computeContiguousTip(db, fromHeight) {
|
|
|
76
76
|
`.execute(db);
|
|
77
77
|
return Number(rows[0]?.tip ?? fromHeight);
|
|
78
78
|
}
|
|
79
|
+
async function findShortBlocks(db, opts = {}) {
|
|
80
|
+
const windowSize = opts.window === undefined ? 1e4 : opts.window;
|
|
81
|
+
const limitClause = opts.limit ? sql`LIMIT ${opts.limit}` : sql``;
|
|
82
|
+
const windowClause = windowSize === null ? sql`` : sql`AND b.height > (SELECT MAX(height) - ${windowSize} FROM blocks WHERE canonical = true)`;
|
|
83
|
+
const { rows } = await sql`
|
|
84
|
+
SELECT b.height, b.tx_count, COUNT(t.tx_id) AS actual_count
|
|
85
|
+
FROM blocks b
|
|
86
|
+
LEFT JOIN transactions t ON t.block_height = b.height
|
|
87
|
+
WHERE b.canonical = true
|
|
88
|
+
AND b.tx_count IS NOT NULL
|
|
89
|
+
${windowClause}
|
|
90
|
+
GROUP BY b.height, b.tx_count
|
|
91
|
+
HAVING COUNT(t.tx_id) <> b.tx_count
|
|
92
|
+
ORDER BY b.height
|
|
93
|
+
${limitClause}
|
|
94
|
+
`.execute(db);
|
|
95
|
+
return rows.map((r) => ({
|
|
96
|
+
height: Number(r.height),
|
|
97
|
+
expectedTxCount: Number(r.tx_count),
|
|
98
|
+
actualTxCount: Number(r.actual_count)
|
|
99
|
+
}));
|
|
100
|
+
}
|
|
79
101
|
async function findBrokenLinks(db, opts = {}) {
|
|
80
102
|
const windowSize = opts.window === undefined ? 1e4 : opts.window;
|
|
81
103
|
const limitClause = opts.limit ? sql`LIMIT ${opts.limit}` : sql``;
|
|
@@ -106,8 +128,9 @@ export {
|
|
|
106
128
|
computeContiguousTip,
|
|
107
129
|
countMissingBlocks,
|
|
108
130
|
findBrokenLinks,
|
|
109
|
-
findGaps
|
|
131
|
+
findGaps,
|
|
132
|
+
findShortBlocks
|
|
110
133
|
};
|
|
111
134
|
|
|
112
|
-
//# debugId=
|
|
135
|
+
//# debugId=E92283960DE6C55264756E2164756E21
|
|
113
136
|
//# sourceMappingURL=integrity.js.map
|
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/db/queries/integrity.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"import { type Kysely, sql } from \"kysely\";\nimport type { Database } from \"../types.ts\";\n\nexport interface Gap {\n\tgapStart: number;\n\tgapEnd: number;\n\tsize: number;\n}\n\nexport async function findGaps(\n\tdb: Kysely<Database>,\n\tlimit?: number,\n): Promise<Gap[]> {\n\tconst limitClause = limit ? sql`LIMIT ${limit}` : sql``;\n\tconst { rows } = await sql<{\n\t\tgap_start: string;\n\t\tgap_end: string;\n\t\tsize: string;\n\t}>`\n SELECT gap_start, gap_end, gap_end - gap_start + 1 AS size\n FROM (\n SELECT height + 1 AS gap_start, next_height - 1 AS gap_end\n FROM (\n SELECT height, LEAD(height) OVER (ORDER BY height) AS next_height\n FROM blocks WHERE canonical = true\n ) sub\n WHERE next_height - height > 1\n ) gaps\n ORDER BY gap_start\n ${limitClause}\n `.execute(db);\n\n\treturn rows.map((r) => ({\n\t\tgapStart: Number(r.gap_start),\n\t\tgapEnd: Number(r.gap_end),\n\t\tsize: Number(r.size),\n\t}));\n}\n\nexport async function countMissingBlocks(\n\tdb: Kysely<Database>,\n): Promise<number> {\n\tconst { rows } = await sql<{ total: string }>`\n SELECT COALESCE(SUM(next_height - height - 1), 0) AS total\n FROM (\n SELECT height, LEAD(height) OVER (ORDER BY height) AS next_height\n FROM blocks WHERE canonical = true\n ) sub\n WHERE next_height - height > 1\n `.execute(db);\n\n\treturn Number(rows[0]?.total ?? 0);\n}\n\nexport interface ChainDataIntegrity {\n\tok: boolean;\n\tmaxHeight: number;\n\tsampleHeight: number | null;\n\tsampleBlocks: number;\n\treason: string | null;\n}\n\n/**\n * Cheap sanity check that the `blocks` table actually holds the history its tip\n * implies. Catches a wrong/empty Postgres volume — e.g. a container recreated\n * against a fresh volume — being silently served: if the tip is high but a\n * window of blocks well below it is missing, the data isn't what the tip claims.\n *\n * Below `checkFloor` we can't distinguish a fresh install from an empty volume,\n * so we report ok — a genuinely new DB legitimately has little history. Two\n * indexed lookups, safe to run on every startup / health poll.\n */\nexport async function checkChainDataIntegrity(\n\tdb: Kysely<Database>,\n\topts?: { checkFloor?: number; lookback?: number },\n): Promise<ChainDataIntegrity> {\n\tconst checkFloor = opts?.checkFloor ?? 1_000_000;\n\tconst lookback = opts?.lookback ?? 500_000;\n\n\tconst { rows: tipRows } = await sql<{ max: string | null }>`\n\t\tSELECT MAX(height) AS max FROM blocks WHERE canonical = true\n\t`.execute(db);\n\tconst maxHeight = Number(tipRows[0]?.max ?? 0);\n\n\tif (maxHeight < checkFloor) {\n\t\treturn {\n\t\t\tok: true,\n\t\t\tmaxHeight,\n\t\t\tsampleHeight: null,\n\t\t\tsampleBlocks: 0,\n\t\t\treason: null,\n\t\t};\n\t}\n\n\tconst sampleHeight = maxHeight - lookback;\n\tconst { rows: sampleRows } = await sql<{ n: string }>`\n\t\tSELECT count(*) AS n FROM blocks\n\t\tWHERE canonical = true AND height >= ${sampleHeight} AND height < ${sampleHeight + 1000}\n\t`.execute(db);\n\tconst sampleBlocks = Number(sampleRows[0]?.n ?? 0);\n\n\treturn {\n\t\tok: sampleBlocks > 0,\n\t\tmaxHeight,\n\t\tsampleHeight,\n\t\tsampleBlocks,\n\t\treason:\n\t\t\tsampleBlocks > 0\n\t\t\t\t? null\n\t\t\t\t: `tip is ${maxHeight} but no canonical blocks near ${sampleHeight} — wrong or empty volume?`,\n\t};\n}\n\nexport async function computeContiguousTip(\n\tdb: Kysely<Database>,\n\tfromHeight: number,\n): Promise<number> {\n\tconst { rows } = await sql<{ tip: string }>`\n SELECT COALESCE(MAX(height), ${fromHeight}) AS tip\n FROM (\n SELECT height, height - ROW_NUMBER() OVER (ORDER BY height) AS grp\n FROM blocks WHERE canonical = true AND height >= ${fromHeight}\n ) sub\n WHERE grp = (\n SELECT height - ROW_NUMBER() OVER (ORDER BY height)\n FROM blocks WHERE canonical = true AND height = ${fromHeight}\n )\n `.execute(db);\n\n\treturn Number(rows[0]?.tip ?? fromHeight);\n}\n\nexport type BrokenLink = {\n\theight: number;\n\thash: string;\n\texpectedParent: string;\n\tstoredParent: string;\n};\n\n/**\n * Canonical heights whose block does not descend from the canonical block\n * below it.\n *\n * `findGaps` asks \"is every height present?\", which a chain sitting on a losing\n * fork answers yes to. On 2026-07-30 a reorg at 8,663,166 was resolved the\n * wrong way: we adopted a block that mainnet orphaned, its true successors were\n * swept non-canonical, and later blocks were inserted canonical on top. Every\n * height existed. Nothing was \"missing\". The chain simply did not join up, and\n * no check asked that question — so we served a broken chain for seventeen\n * hours and only noticed because subgraphs stopped moving.\n *\n * Scoped to a recent window by default: an unlinked height is an active-repair\n * concern, and scanning eight million rows every cycle is not.\n */\nexport async function findBrokenLinks(\n\tdb: Kysely<Database>,\n\t/** Heights below the tip to scan; `null` scans the whole chain. */\n\topts: { window?: number | null; limit?: number } = {},\n): Promise<BrokenLink[]> {\n\tconst windowSize = opts.window === undefined ? 10_000 : opts.window;\n\tconst limitClause = opts.limit ? sql`LIMIT ${opts.limit}` : sql``;\n\tconst windowClause =\n\t\twindowSize === null\n\t\t\t? sql``\n\t\t\t: sql`AND height > (SELECT MAX(height) - ${windowSize} FROM blocks WHERE canonical = true)`;\n\tconst { rows } = await sql<{\n\t\theight: string | number;\n\t\thash: string;\n\t\texpected_parent: string;\n\t\tstored_parent: string;\n\t}>`\n\t\tWITH recent AS (\n\t\t\tSELECT height, hash, parent_hash\n\t\t\tFROM blocks\n\t\t\tWHERE canonical = true\n\t\t\t\t${windowClause}\n\t\t)\n\t\tSELECT b.height, b.hash, p.hash AS expected_parent, b.parent_hash AS stored_parent\n\t\tFROM recent b\n\t\tJOIN recent p ON p.height = b.height - 1\n\t\tWHERE b.parent_hash <> p.hash\n\t\tORDER BY b.height\n\t\t${limitClause}\n\t`.execute(db);\n\treturn rows.map((r) => ({\n\t\theight: Number(r.height),\n\t\thash: r.hash,\n\t\texpectedParent: r.expected_parent,\n\t\tstoredParent: r.stored_parent,\n\t}));\n}\n"
|
|
5
|
+
"import { type Kysely, sql } from \"kysely\";\nimport type { Database } from \"../types.ts\";\n\nexport interface Gap {\n\tgapStart: number;\n\tgapEnd: number;\n\tsize: number;\n}\n\nexport async function findGaps(\n\tdb: Kysely<Database>,\n\tlimit?: number,\n): Promise<Gap[]> {\n\tconst limitClause = limit ? sql`LIMIT ${limit}` : sql``;\n\tconst { rows } = await sql<{\n\t\tgap_start: string;\n\t\tgap_end: string;\n\t\tsize: string;\n\t}>`\n SELECT gap_start, gap_end, gap_end - gap_start + 1 AS size\n FROM (\n SELECT height + 1 AS gap_start, next_height - 1 AS gap_end\n FROM (\n SELECT height, LEAD(height) OVER (ORDER BY height) AS next_height\n FROM blocks WHERE canonical = true\n ) sub\n WHERE next_height - height > 1\n ) gaps\n ORDER BY gap_start\n ${limitClause}\n `.execute(db);\n\n\treturn rows.map((r) => ({\n\t\tgapStart: Number(r.gap_start),\n\t\tgapEnd: Number(r.gap_end),\n\t\tsize: Number(r.size),\n\t}));\n}\n\nexport async function countMissingBlocks(\n\tdb: Kysely<Database>,\n): Promise<number> {\n\tconst { rows } = await sql<{ total: string }>`\n SELECT COALESCE(SUM(next_height - height - 1), 0) AS total\n FROM (\n SELECT height, LEAD(height) OVER (ORDER BY height) AS next_height\n FROM blocks WHERE canonical = true\n ) sub\n WHERE next_height - height > 1\n `.execute(db);\n\n\treturn Number(rows[0]?.total ?? 0);\n}\n\nexport interface ChainDataIntegrity {\n\tok: boolean;\n\tmaxHeight: number;\n\tsampleHeight: number | null;\n\tsampleBlocks: number;\n\treason: string | null;\n}\n\n/**\n * Cheap sanity check that the `blocks` table actually holds the history its tip\n * implies. Catches a wrong/empty Postgres volume — e.g. a container recreated\n * against a fresh volume — being silently served: if the tip is high but a\n * window of blocks well below it is missing, the data isn't what the tip claims.\n *\n * Below `checkFloor` we can't distinguish a fresh install from an empty volume,\n * so we report ok — a genuinely new DB legitimately has little history. Two\n * indexed lookups, safe to run on every startup / health poll.\n */\nexport async function checkChainDataIntegrity(\n\tdb: Kysely<Database>,\n\topts?: { checkFloor?: number; lookback?: number },\n): Promise<ChainDataIntegrity> {\n\tconst checkFloor = opts?.checkFloor ?? 1_000_000;\n\tconst lookback = opts?.lookback ?? 500_000;\n\n\tconst { rows: tipRows } = await sql<{ max: string | null }>`\n\t\tSELECT MAX(height) AS max FROM blocks WHERE canonical = true\n\t`.execute(db);\n\tconst maxHeight = Number(tipRows[0]?.max ?? 0);\n\n\tif (maxHeight < checkFloor) {\n\t\treturn {\n\t\t\tok: true,\n\t\t\tmaxHeight,\n\t\t\tsampleHeight: null,\n\t\t\tsampleBlocks: 0,\n\t\t\treason: null,\n\t\t};\n\t}\n\n\tconst sampleHeight = maxHeight - lookback;\n\tconst { rows: sampleRows } = await sql<{ n: string }>`\n\t\tSELECT count(*) AS n FROM blocks\n\t\tWHERE canonical = true AND height >= ${sampleHeight} AND height < ${sampleHeight + 1000}\n\t`.execute(db);\n\tconst sampleBlocks = Number(sampleRows[0]?.n ?? 0);\n\n\treturn {\n\t\tok: sampleBlocks > 0,\n\t\tmaxHeight,\n\t\tsampleHeight,\n\t\tsampleBlocks,\n\t\treason:\n\t\t\tsampleBlocks > 0\n\t\t\t\t? null\n\t\t\t\t: `tip is ${maxHeight} but no canonical blocks near ${sampleHeight} — wrong or empty volume?`,\n\t};\n}\n\nexport async function computeContiguousTip(\n\tdb: Kysely<Database>,\n\tfromHeight: number,\n): Promise<number> {\n\tconst { rows } = await sql<{ tip: string }>`\n SELECT COALESCE(MAX(height), ${fromHeight}) AS tip\n FROM (\n SELECT height, height - ROW_NUMBER() OVER (ORDER BY height) AS grp\n FROM blocks WHERE canonical = true AND height >= ${fromHeight}\n ) sub\n WHERE grp = (\n SELECT height - ROW_NUMBER() OVER (ORDER BY height)\n FROM blocks WHERE canonical = true AND height = ${fromHeight}\n )\n `.execute(db);\n\n\treturn Number(rows[0]?.tip ?? fromHeight);\n}\n\nexport type ShortBlock = {\n\theight: number;\n\texpectedTxCount: number;\n\tactualTxCount: number;\n};\n\n/**\n * Canonical heights where `transactions` holds fewer (or more) rows than the\n * block was supposed to. `blocks.tx_count` is set by `persistBlock` from the\n * incoming block, so a mismatch means a later write silently moved or dropped\n * a tx after that block was persisted — a reorg replaying the wrong height, a\n * same-height tx_id collision, or a bug in the persist path itself. Ingest\n * used to report the *parsed* count, not the inserted count, so this kind of\n * short block was invisible; a skipped insert looked identical to success.\n *\n * Scoped to heights with `tx_count IS NOT NULL` — rows ingested before this\n * column existed have no baseline to check against. Also scoped to a recent\n * window by default (like `findBrokenLinks`): every new block sets\n * `tx_count`, so the eligible range only grows, and a short block is an\n * active-repair concern, not something worth a full-table scan every cycle.\n */\nexport async function findShortBlocks(\n\tdb: Kysely<Database>,\n\t/** Heights below the tip to scan; `null` scans the whole chain. */\n\topts: { window?: number | null; limit?: number } = {},\n): Promise<ShortBlock[]> {\n\tconst windowSize = opts.window === undefined ? 10_000 : opts.window;\n\tconst limitClause = opts.limit ? sql`LIMIT ${opts.limit}` : sql``;\n\tconst windowClause =\n\t\twindowSize === null\n\t\t\t? sql``\n\t\t\t: sql`AND b.height > (SELECT MAX(height) - ${windowSize} FROM blocks WHERE canonical = true)`;\n\tconst { rows } = await sql<{\n\t\theight: string | number;\n\t\ttx_count: number;\n\t\tactual_count: string | number;\n\t}>`\n\t\tSELECT b.height, b.tx_count, COUNT(t.tx_id) AS actual_count\n\t\t FROM blocks b\n\t\t LEFT JOIN transactions t ON t.block_height = b.height\n\t\t WHERE b.canonical = true\n\t\t AND b.tx_count IS NOT NULL\n\t\t ${windowClause}\n\t\t GROUP BY b.height, b.tx_count\n\t\tHAVING COUNT(t.tx_id) <> b.tx_count\n\t\t ORDER BY b.height\n\t\t ${limitClause}\n\t`.execute(db);\n\n\treturn rows.map((r) => ({\n\t\theight: Number(r.height),\n\t\texpectedTxCount: Number(r.tx_count),\n\t\tactualTxCount: Number(r.actual_count),\n\t}));\n}\n\nexport type BrokenLink = {\n\theight: number;\n\thash: string;\n\texpectedParent: string;\n\tstoredParent: string;\n};\n\n/**\n * Canonical heights whose block does not descend from the canonical block\n * below it.\n *\n * `findGaps` asks \"is every height present?\", which a chain sitting on a losing\n * fork answers yes to. On 2026-07-30 a reorg at 8,663,166 was resolved the\n * wrong way: we adopted a block that mainnet orphaned, its true successors were\n * swept non-canonical, and later blocks were inserted canonical on top. Every\n * height existed. Nothing was \"missing\". The chain simply did not join up, and\n * no check asked that question — so we served a broken chain for seventeen\n * hours and only noticed because subgraphs stopped moving.\n *\n * Scoped to a recent window by default: an unlinked height is an active-repair\n * concern, and scanning eight million rows every cycle is not.\n */\nexport async function findBrokenLinks(\n\tdb: Kysely<Database>,\n\t/** Heights below the tip to scan; `null` scans the whole chain. */\n\topts: { window?: number | null; limit?: number } = {},\n): Promise<BrokenLink[]> {\n\tconst windowSize = opts.window === undefined ? 10_000 : opts.window;\n\tconst limitClause = opts.limit ? sql`LIMIT ${opts.limit}` : sql``;\n\tconst windowClause =\n\t\twindowSize === null\n\t\t\t? sql``\n\t\t\t: sql`AND height > (SELECT MAX(height) - ${windowSize} FROM blocks WHERE canonical = true)`;\n\tconst { rows } = await sql<{\n\t\theight: string | number;\n\t\thash: string;\n\t\texpected_parent: string;\n\t\tstored_parent: string;\n\t}>`\n\t\tWITH recent AS (\n\t\t\tSELECT height, hash, parent_hash\n\t\t\tFROM blocks\n\t\t\tWHERE canonical = true\n\t\t\t\t${windowClause}\n\t\t)\n\t\tSELECT b.height, b.hash, p.hash AS expected_parent, b.parent_hash AS stored_parent\n\t\tFROM recent b\n\t\tJOIN recent p ON p.height = b.height - 1\n\t\tWHERE b.parent_hash <> p.hash\n\t\tORDER BY b.height\n\t\t${limitClause}\n\t`.execute(db);\n\treturn rows.map((r) => ({\n\t\theight: Number(r.height),\n\t\thash: r.hash,\n\t\texpectedParent: r.expected_parent,\n\t\tstoredParent: r.stored_parent,\n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;AAAA,EACxB,MAAM,aAAa,KAAK,WAAW,YAAY,MAAS,KAAK;AAAA,EAC7D,MAAM,cAAc,KAAK,QAAQ,YAAY,KAAK,UAAU;AAAA,EAC5D,MAAM,eACL,eAAe,OACZ,QACA,yCAAyC;AAAA,EAC7C,QAAQ,SAAS,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA,MAUlB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAOF;AAAA,GACD,QAAQ,EAAE;AAAA,EACZ,OAAO,KAAK,IAAI,CAAC,OAAO;AAAA,IACvB,QAAQ,OAAO,EAAE,MAAM;AAAA,IACvB,MAAM,EAAE;AAAA,IACR,gBAAgB,EAAE;AAAA,IAClB,cAAc,EAAE;AAAA,EACjB,EAAE;AAAA;",
|
|
8
|
+
"debugId": "E92283960DE6C55264756E2164756E21",
|
|
9
9
|
"names": []
|
|
10
10
|
}
|
|
@@ -29,6 +29,9 @@ interface BlocksTable {
|
|
|
29
29
|
index_block_hash: ColumnType<string | null, string | null | undefined, string | null>;
|
|
30
30
|
timestamp: number;
|
|
31
31
|
canonical: Generated<boolean>;
|
|
32
|
+
/** Tx count `persistBlock` was handed for this height. Null on rows
|
|
33
|
+
* ingested before this column existed. */
|
|
34
|
+
tx_count: ColumnType<number | null, number | null | undefined, number | null>;
|
|
32
35
|
created_at: Generated<Date>;
|
|
33
36
|
}
|
|
34
37
|
interface TransactionsTable {
|
|
@@ -29,6 +29,9 @@ interface BlocksTable {
|
|
|
29
29
|
index_block_hash: ColumnType<string | null, string | null | undefined, string | null>;
|
|
30
30
|
timestamp: number;
|
|
31
31
|
canonical: Generated<boolean>;
|
|
32
|
+
/** Tx count `persistBlock` was handed for this height. Null on rows
|
|
33
|
+
* ingested before this column existed. */
|
|
34
|
+
tx_count: ColumnType<number | null, number | null | undefined, number | null>;
|
|
32
35
|
created_at: Generated<Date>;
|
|
33
36
|
}
|
|
34
37
|
interface TransactionsTable {
|
|
@@ -29,6 +29,9 @@ interface BlocksTable {
|
|
|
29
29
|
index_block_hash: ColumnType<string | null, string | null | undefined, string | null>;
|
|
30
30
|
timestamp: number;
|
|
31
31
|
canonical: Generated<boolean>;
|
|
32
|
+
/** Tx count `persistBlock` was handed for this height. Null on rows
|
|
33
|
+
* ingested before this column existed. */
|
|
34
|
+
tx_count: ColumnType<number | null, number | null | undefined, number | null>;
|
|
32
35
|
created_at: Generated<Date>;
|
|
33
36
|
}
|
|
34
37
|
interface TransactionsTable {
|
|
@@ -39,6 +39,9 @@ interface BlocksTable {
|
|
|
39
39
|
index_block_hash: ColumnType<string | null, string | null | undefined, string | null>;
|
|
40
40
|
timestamp: number;
|
|
41
41
|
canonical: Generated<boolean>;
|
|
42
|
+
/** Tx count `persistBlock` was handed for this height. Null on rows
|
|
43
|
+
* ingested before this column existed. */
|
|
44
|
+
tx_count: ColumnType<number | null, number | null | undefined, number | null>;
|
|
42
45
|
created_at: Generated<Date>;
|
|
43
46
|
}
|
|
44
47
|
interface TransactionsTable {
|
|
@@ -29,6 +29,9 @@ interface BlocksTable {
|
|
|
29
29
|
index_block_hash: ColumnType<string | null, string | null | undefined, string | null>;
|
|
30
30
|
timestamp: number;
|
|
31
31
|
canonical: Generated<boolean>;
|
|
32
|
+
/** Tx count `persistBlock` was handed for this height. Null on rows
|
|
33
|
+
* ingested before this column existed. */
|
|
34
|
+
tx_count: ColumnType<number | null, number | null | undefined, number | null>;
|
|
32
35
|
created_at: Generated<Date>;
|
|
33
36
|
}
|
|
34
37
|
interface TransactionsTable {
|
package/dist/src/db/schema.d.ts
CHANGED
|
@@ -28,6 +28,9 @@ interface BlocksTable {
|
|
|
28
28
|
index_block_hash: ColumnType<string | null, string | null | undefined, string | null>;
|
|
29
29
|
timestamp: number;
|
|
30
30
|
canonical: Generated<boolean>;
|
|
31
|
+
/** Tx count `persistBlock` was handed for this height. Null on rows
|
|
32
|
+
* ingested before this column existed. */
|
|
33
|
+
tx_count: ColumnType<number | null, number | null | undefined, number | null>;
|
|
31
34
|
created_at: Generated<Date>;
|
|
32
35
|
}
|
|
33
36
|
interface TransactionsTable {
|
package/dist/src/index.d.ts
CHANGED
|
@@ -28,6 +28,9 @@ interface BlocksTable {
|
|
|
28
28
|
index_block_hash: ColumnType<string | null, string | null | undefined, string | null>;
|
|
29
29
|
timestamp: number;
|
|
30
30
|
canonical: Generated<boolean>;
|
|
31
|
+
/** Tx count `persistBlock` was handed for this height. Null on rows
|
|
32
|
+
* ingested before this column existed. */
|
|
33
|
+
tx_count: ColumnType<number | null, number | null | undefined, number | null>;
|
|
31
34
|
created_at: Generated<Date>;
|
|
32
35
|
}
|
|
33
36
|
interface TransactionsTable {
|
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;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0C;AAAA,IAC5D,MAAM,MAAM,MAAM,MAAM,GAAG,KAAK,yBAAyB,SAAS;AAAA,MACjE,QAAQ,YAAY,QAAQ,KAAM;AAAA,IACnC,CAAC;AAAA,IACD,IAAI,IAAI,WAAW;AAAA,MAAK,OAAO;AAAA,IAC/B,IAAI,CAAC,IAAI,IAAI;AAAA,MACZ,MAAM,IAAI,MACT,4BAA4B,kBAAkB,IAAI,QACnD;AAAA,IACD;AAAA,IACA,MAAM,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
|
}
|
|
@@ -29,6 +29,9 @@ interface BlocksTable {
|
|
|
29
29
|
index_block_hash: ColumnType<string | null, string | null | undefined, string | null>;
|
|
30
30
|
timestamp: number;
|
|
31
31
|
canonical: Generated<boolean>;
|
|
32
|
+
/** Tx count `persistBlock` was handed for this height. Null on rows
|
|
33
|
+
* ingested before this column existed. */
|
|
34
|
+
tx_count: ColumnType<number | null, number | null | undefined, number | null>;
|
|
32
35
|
created_at: Generated<Date>;
|
|
33
36
|
}
|
|
34
37
|
interface TransactionsTable {
|
|
@@ -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,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;A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B,SAAS,MAAM,SAAS;AAAA,EACxB,OAAO;AAAA;AAQD,SAAS,mBAAmB,CAClC,SACA,MACA,iBACU;AAAA,EACV,IAAI,MAAM,OAAO,UAAU,QAAQ,OAAO,CAAC;AAAA,EAC3C,WAAW,QAAQ,MAAM;AAAA,IACxB,MAAM,MAAM,QAAQ,KAAK,IAAI;AAAA,IAC7B,MACC,KAAK,aAAa,UACf,OAAO,UAAU,KAAK,GAAG,IACzB,OAAO,UAAU,KAAK,GAAG;AAAA,EAC9B;AAAA,EACA,MAAM,OAAO,gBAAgB,WAAW,IAAI,IACzC,gBAAgB,MAAM,CAAC,IACvB;AAAA,EACH,OAAO,MAAM,GAAG,MAAM;AAAA;AAQvB,eAAsB,kBAAkB,CAAC,MAStC;AAAA,EACF,MAAM,KAAK,KAAK,QAAQ,WAAW,IAAI,IACpC,KAAK,QAAQ,MAAM,CAAC,IACpB,KAAK;AAAA,EACR,MAAM,IAAI,KAAK,aAAa;AAAA,EAC5B,MAAM,MAAM,MAAM,EAAE,GAAG,KAAK,QAAQ,QAAQ,QAAQ,EAAE,eAAe,IAAI;AAAA,EACzE,IAAI,CAAC,IAAI,IAAI;AAAA,IACZ,MAAM,IAAI,MAAM,cAAc,eAAe,IAAI,QAAQ;AAAA,EAC1D;AAAA,EACA,MAAM,MAAM,IAAI,WAAW,MAAM,IAAI,YAAY,CAAC;AAAA,EAClD,MAAM,SAAS,yBAAyB,GAAG;AAAA,EAC3C,MAAM,YAAY,kBAAkB,MAAM;AAAA,EAC1C,OAAO;AAAA,IACN;AAAA,IACA;AAAA,IACA;AAAA,IACA,gBAAgB,gBAAgB,WAAW,OAAO,aAAa;AAAA,EAChE;AAAA;",
|
|
8
|
+
"debugId": "315B5F852B83F8F264756E2164756E21",
|
|
9
9
|
"names": []
|
|
10
10
|
}
|
package/dist/src/types.d.ts
CHANGED
|
@@ -9,6 +9,9 @@ interface BlocksTable {
|
|
|
9
9
|
index_block_hash: ColumnType<string | null, string | null | undefined, string | null>;
|
|
10
10
|
timestamp: number;
|
|
11
11
|
canonical: Generated<boolean>;
|
|
12
|
+
/** Tx count `persistBlock` was handed for this height. Null on rows
|
|
13
|
+
* ingested before this column existed. */
|
|
14
|
+
tx_count: ColumnType<number | null, number | null | undefined, number | null>;
|
|
12
15
|
created_at: Generated<Date>;
|
|
13
16
|
}
|
|
14
17
|
interface TransactionsTable {
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { type Kysely, sql } from "kysely";
|
|
2
|
+
import { onChainPlane } from "../src/db/migration-role.ts";
|
|
3
|
+
|
|
4
|
+
// The tx count `persistBlock` was actually handed for a height, set at write
|
|
5
|
+
// time from the incoming block. Nullable: historical rows backfill lazily /
|
|
6
|
+
// on demand. Lets a completeness check compare `count(transactions at h)`
|
|
7
|
+
// against what the block was supposed to hold, catching a persist that
|
|
8
|
+
// silently landed fewer rows than it received — see the ingest transaction
|
|
9
|
+
// completeness plan. `blocks` is a chain-plane table, so the DDL no-ops on
|
|
10
|
+
// the control DB under the source/target split.
|
|
11
|
+
export async function up(db: Kysely<unknown>): Promise<void> {
|
|
12
|
+
await onChainPlane(async () => {
|
|
13
|
+
await sql`SET lock_timeout = '30s'`.execute(db);
|
|
14
|
+
await sql`ALTER TABLE blocks ADD COLUMN IF NOT EXISTS tx_count INT`.execute(
|
|
15
|
+
db,
|
|
16
|
+
);
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export async function down(db: Kysely<unknown>): Promise<void> {
|
|
21
|
+
await onChainPlane(async () => {
|
|
22
|
+
await sql`ALTER TABLE blocks DROP COLUMN IF EXISTS tx_count`.execute(db);
|
|
23
|
+
});
|
|
24
|
+
}
|