@ocap/client 1.30.24 → 1.30.25

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/lib/verify.js ADDED
@@ -0,0 +1,280 @@
1
+ 'use strict';
2
+
3
+ const { Hasher, Signer, toTxHash } = require('@ocap/mcrypto');
4
+
5
+ function normalizeHex(hex) {
6
+ return String(hex || '').replace(/^0x/i, '').toLowerCase();
7
+ }
8
+
9
+ function sha256Buf(data) {
10
+ const hex = Hasher.SHA2.hash256(data, 1, 'hex');
11
+ return Buffer.from(String(hex).replace(/^0x/i, ''), 'hex');
12
+ }
13
+
14
+ function hashPair(left, right) {
15
+ return sha256Buf(Buffer.concat([left, right]));
16
+ }
17
+
18
+ // Proof length for every leaf of a tree with `treeSize` leaves (odd last node pairs with itself)
19
+ function merkleProofLength(treeSize) {
20
+ let depth = 0;
21
+ for (let width = treeSize; width > 1; width = Math.ceil(width / 2)) {
22
+ depth++;
23
+ }
24
+ return depth;
25
+ }
26
+
27
+ function verifyMerkleProof(leaf, index, proof, root, treeSize) {
28
+ if (!Number.isInteger(index) || index < 0) {
29
+ return false;
30
+ }
31
+ // #972: bind the proof to the checkpoint's tree size
32
+ if (treeSize !== undefined) {
33
+ if (!Number.isInteger(treeSize) || treeSize < 1 || index >= treeSize || proof.length !== merkleProofLength(treeSize)) {
34
+ return false;
35
+ }
36
+ }
37
+ if (proof.length === 0) {
38
+ return index === 0 && leaf.equals(root);
39
+ }
40
+ let currentHash = leaf;
41
+ let currentIndex = index;
42
+ for (let i = 0; i < proof.length; i++) {
43
+ const sibling = proof[i];
44
+ if (currentIndex % 2 === 0) {
45
+ currentHash = hashPair(currentHash, sibling);
46
+ } else {
47
+ currentHash = hashPair(sibling, currentHash);
48
+ }
49
+ currentIndex = Math.floor(currentIndex / 2);
50
+ }
51
+ if (currentIndex !== 0) {
52
+ return false;
53
+ }
54
+ return currentHash.equals(root);
55
+ }
56
+
57
+ function computeEntryHash(sequence, txRaw, stateCommitHash = '') {
58
+ const data = Buffer.concat([Buffer.from(String(sequence)), Buffer.from(txRaw), Buffer.from(stateCommitHash)]);
59
+ return Hasher.SHA2.hash256(data, 1, 'hex');
60
+ }
61
+
62
+ function computeCheckpointHash(checkpoint) {
63
+ const data = Buffer.from(JSON.stringify({
64
+ height: Number(checkpoint.height),
65
+ sequence: Number(checkpoint.sequence),
66
+ prevSequence: Number(checkpoint.prevSequence),
67
+ txRoot: checkpoint.txRoot,
68
+ txCount: Number(checkpoint.txCount),
69
+ stateRoot: checkpoint.stateRoot || undefined,
70
+ timestamp: Number(checkpoint.timestamp),
71
+ prevCheckpoint: checkpoint.prevCheckpoint || null,
72
+ proposer: checkpoint.proposer
73
+ }));
74
+ return Hasher.SHA2.hash256(data, 1, 'hex');
75
+ }
76
+
77
+ async function verifyCheckpointSignature(checkpoint, publicKeyOrVerifier, expectedProposer) {
78
+ if (!checkpoint || !checkpoint.hash || !checkpoint.signature || checkpoint.signature === 'unsigned') {
79
+ return false;
80
+ }
81
+ if (expectedProposer && checkpoint.proposer !== expectedProposer) {
82
+ return false;
83
+ }
84
+ const recomputedHash = computeCheckpointHash(checkpoint);
85
+ if (normalizeHex(recomputedHash) !== normalizeHex(checkpoint.hash)) {
86
+ return false;
87
+ }
88
+ if (!publicKeyOrVerifier) {
89
+ return false;
90
+ }
91
+ const hashBytes = Buffer.from(normalizeHex(checkpoint.hash), 'hex');
92
+ if (typeof publicKeyOrVerifier === 'function') {
93
+ try {
94
+ // Only a literal `true` authenticates: `{ verified: false }`, 1 or 'false' must not pass as truthy.
95
+ return (await publicKeyOrVerifier(hashBytes, checkpoint.signature, checkpoint.proposer)) === true;
96
+ } catch (_err) {
97
+ return false;
98
+ }
99
+ }
100
+ try {
101
+ if (Signer.Ed25519.verify(hashBytes, checkpoint.signature, publicKeyOrVerifier)) {
102
+ return true;
103
+ }
104
+ const sha3Digest = Hasher.SHA3.hash256(hashBytes, 1);
105
+ if (Signer.Ed25519.verify(sha3Digest, checkpoint.signature, publicKeyOrVerifier)) {
106
+ return true;
107
+ }
108
+ const sha2Digest = Hasher.SHA2.hash256(hashBytes, 1);
109
+ if (Signer.Ed25519.verify(sha2Digest, checkpoint.signature, publicKeyOrVerifier)) {
110
+ return true;
111
+ }
112
+ return false;
113
+ } catch (_err) {
114
+ return false;
115
+ }
116
+ }
117
+
118
+ const NO_TRUST_ANCHOR_REASON = 'no trust anchor (proposerPublicKey/verifier) supplied';
119
+
120
+ // Pick the trust anchor that authenticates the checkpoint signature, or undefined when none is usable.
121
+ // Empty / whitespace / bare "0x" strings and zero-length byte arrays do not count as an anchor (#1133).
122
+ // Hex strings are normalised to bytes whether or not they carry a 0x prefix.
123
+ function resolveTrustAnchor(params) {
124
+ if (typeof params.verifier === 'function') return params.verifier;
125
+ const pk = params.proposerPublicKey;
126
+ if (typeof pk === 'string') {
127
+ const bare = pk.trim().replace(/^0x/i, '');
128
+ if (bare.length === 0) return undefined;
129
+ // Hex keys are accepted with or without 0x and in any case; decode them to bytes so both
130
+ // implementations hand the same value to the signature check.
131
+ return (/^[0-9a-fA-F]+$/.test(bare) && bare.length % 2 === 0 ? Buffer.from(bare, 'hex') : pk.trim()
132
+ );
133
+ }
134
+ if (pk instanceof Uint8Array) {
135
+ return pk.length > 0 ? pk : undefined;
136
+ }
137
+ return undefined;
138
+ }
139
+
140
+ /**
141
+ * Pure client-side verification of transaction inclusion in a signed Checkpoint (< 1ms, zero network I/O).
142
+ *
143
+ * Only `txRaw` is authenticated: `entryHash` covers `sequence`, `txRaw` and `stateCommitHash`, not
144
+ * `entry.tx`, `from`, `pk`, `nonce` or `signature`. A `verified: true` result says nothing about those
145
+ * fields. Decode the verified `txRaw` yourself; never read `entry.tx` directly (#1139).
146
+ *
147
+ * @param {object} params
148
+ * @param {object} params.checkpoint
149
+ * @param {object} params.proof
150
+ * @param {object} params.entry
151
+ * @param {string} [params.txHash]
152
+ * @param {boolean} [params.verifyTxRawHash=true] - require entry.hash === toTxHash(txRaw) (#976)
153
+ * @param {string} [params.expectedProposer]
154
+ * @param {string|Buffer} [params.proposerPublicKey] - trust anchor; one of proposerPublicKey / verifier is
155
+ * required, otherwise the result is `{ verified: false }` (#1133)
156
+ * @param {Function} [params.verifier]
157
+ * @param {boolean} [params.allowUnauthenticated=false] - UNSAFE: skip the signature check when no trust anchor
158
+ * is supplied (pre-#1133 behavior). A malicious RPC can then forge inclusion.
159
+ * @returns {Promise<{ verified: boolean, reason?: string }>}
160
+ */
161
+ async function verifyTxInclusion(params) {
162
+ try {
163
+ if (!params || !params.checkpoint || !params.proof || !params.entry) {
164
+ return { verified: false, reason: 'Missing checkpoint, proof, or entry' };
165
+ }
166
+
167
+ const { checkpoint, proof, entry, txHash, expectedProposer } = params;
168
+
169
+ // Fail closed (#1133): every check below is structural and a forging RPC can satisfy them all;
170
+ // only the checkpoint signature against a trust anchor authenticates the bundle.
171
+ const trustAnchor = resolveTrustAnchor(params);
172
+ if (!trustAnchor && params.allowUnauthenticated !== true) {
173
+ return { verified: false, reason: NO_TRUST_ANCHOR_REASON };
174
+ }
175
+
176
+ // entry.hash is not covered by entryHash or the Merkle leaf, so bind it to txRaw (#976).
177
+ // On by default: this client only talks to OCAP chains, where hash = toTxHash(txRaw).
178
+ if (params.verifyTxRawHash !== false && normalizeHex(toTxHash(Buffer.from(String(entry.txRaw || ''), 'base64'))) !== normalizeHex(entry.hash)) {
179
+ return { verified: false, reason: `Transaction hash ${entry.hash} does not match entry txRaw` };
180
+ }
181
+
182
+ if (txHash && entry.hash !== txHash) {
183
+ return {
184
+ verified: false,
185
+ reason: `Transaction hash mismatch: expected ${txHash}, got ${entry.hash}`
186
+ };
187
+ }
188
+
189
+ if (expectedProposer && checkpoint.proposer !== expectedProposer) {
190
+ return {
191
+ verified: false,
192
+ reason: `Checkpoint proposer mismatch: expected ${expectedProposer}, got ${checkpoint.proposer}`
193
+ };
194
+ }
195
+
196
+ const seq = Number(entry.sequence);
197
+ const prevSeq = Number(checkpoint.prevSequence);
198
+ const cpSeq = Number(checkpoint.sequence);
199
+
200
+ if (seq <= prevSeq || seq > cpSeq) {
201
+ return {
202
+ verified: false,
203
+ reason: `Entry sequence ${seq} is outside checkpoint range (${prevSeq}, ${cpSeq}]`
204
+ };
205
+ }
206
+
207
+ const expectedIndex = seq - (prevSeq + 1);
208
+ if (Number(proof.index) !== expectedIndex) {
209
+ return {
210
+ verified: false,
211
+ reason: `Merkle proof index mismatch: expected ${expectedIndex}, got ${proof.index}`
212
+ };
213
+ }
214
+
215
+ const recomputedEntryHash = computeEntryHash(seq, entry.txRaw, entry.stateCommitHash || '');
216
+ if (normalizeHex(entry.entryHash) !== normalizeHex(recomputedEntryHash)) {
217
+ return {
218
+ verified: false,
219
+ reason: `Entry hash mismatch: expected ${recomputedEntryHash}, got ${entry.entryHash}`
220
+ };
221
+ }
222
+
223
+ const expectedLeafHash = Hasher.SHA2.hash256(Buffer.from(recomputedEntryHash), 1, 'hex');
224
+ if (normalizeHex(proof.leaf) !== normalizeHex(expectedLeafHash)) {
225
+ return {
226
+ verified: false,
227
+ reason: `Merkle proof leaf mismatch: expected ${expectedLeafHash}, got ${proof.leaf}`
228
+ };
229
+ }
230
+
231
+ if (normalizeHex(proof.root) !== normalizeHex(checkpoint.txRoot)) {
232
+ return {
233
+ verified: false,
234
+ reason: `Merkle proof root mismatch: expected ${checkpoint.txRoot}, got ${proof.root}`
235
+ };
236
+ }
237
+
238
+ const leafBuf = Buffer.from(normalizeHex(proof.leaf), 'hex');
239
+ const proofBufs = (proof.proof || []).map(p => Buffer.from(normalizeHex(p), 'hex'));
240
+ const rootBuf = Buffer.from(normalizeHex(proof.root), 'hex');
241
+
242
+ if (!verifyMerkleProof(leafBuf, Number(proof.index), proofBufs, rootBuf, Number(checkpoint.txCount))) {
243
+ return { verified: false, reason: 'Invalid Merkle inclusion proof' };
244
+ }
245
+
246
+ const recomputedCpHash = computeCheckpointHash(checkpoint);
247
+ if (normalizeHex(recomputedCpHash) !== normalizeHex(checkpoint.hash)) {
248
+ return {
249
+ verified: false,
250
+ reason: `Checkpoint hash mismatch: expected ${recomputedCpHash}, got ${checkpoint.hash}`
251
+ };
252
+ }
253
+
254
+ if (!checkpoint.signature || checkpoint.signature === 'unsigned') {
255
+ return { verified: false, reason: 'Checkpoint is unsigned' };
256
+ }
257
+
258
+ if (trustAnchor) {
259
+ const sigValid = await verifyCheckpointSignature(checkpoint, trustAnchor, expectedProposer);
260
+ if (!sigValid) {
261
+ return { verified: false, reason: 'Invalid checkpoint signature' };
262
+ }
263
+ }
264
+
265
+ return { verified: true };
266
+ } catch (err) {
267
+ return {
268
+ verified: false,
269
+ reason: err instanceof Error ? err.message : String(err)
270
+ };
271
+ }
272
+ }
273
+
274
+ module.exports = {
275
+ verifyTxInclusion,
276
+ verifyCheckpointSignature,
277
+ computeEntryHash,
278
+ computeCheckpointHash
279
+ };
280
+ //# sourceMappingURL=verify.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/verify.js"],"names":["Hasher","Signer","toTxHash","require","normalizeHex","hex","String","replace","toLowerCase","sha256Buf","data","SHA2","hash256","Buffer","from","hashPair","left","right","concat","merkleProofLength","treeSize","depth","width","Math","ceil","verifyMerkleProof","leaf","index","proof","root","Number","isInteger","undefined","length","equals","currentHash","currentIndex","i","sibling","floor","computeEntryHash","sequence","txRaw","stateCommitHash","computeCheckpointHash","checkpoint","JSON","stringify","height","prevSequence","txRoot","txCount","stateRoot","timestamp","prevCheckpoint","proposer","verifyCheckpointSignature","publicKeyOrVerifier","expectedProposer","hash","signature","recomputedHash","hashBytes","_err","Ed25519","verify","sha3Digest","SHA3","sha2Digest","NO_TRUST_ANCHOR_REASON","resolveTrustAnchor","params","verifier","pk","proposerPublicKey","bare","trim","test","Uint8Array","verifyTxInclusion","entry","verified","reason","txHash","trustAnchor","allowUnauthenticated","verifyTxRawHash","seq","prevSeq","cpSeq","expectedIndex","recomputedEntryHash","entryHash","expectedLeafHash","leafBuf","proofBufs","map","p","rootBuf","recomputedCp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AsCuC,WAAtC,EAAmD1B,gBAAnD,CAAvB;AACA,UAAI,CAAC0C,QAAL,EAAe;AACb,eAAO,EAAEnB,UAAU,KAAZ,EAAmBC,QAAQ,8BAA3B,EAAP;AACD;AACF;;AAED,WAAO,EAAED,UAAU,IAAZ,EAAP;AACD,GA3GD,CA2GE,OAAOoB,GAAP,EAAY;AACZ,WAAO;AACLpB,gBAAU,KADL;AAELC,cAAQmB,eAAeC,KAAf,GAAuBD,IAAIE,OAA3B,GAAqCjG,OAAO+F,GAAP;AAFxC,KAAP;AAID;AACF;;AAEDG,OAAOC,OAAP,GAAiB;AACf1B,mBADe;AAEfvB,2BAFe;AAGfhB,kBAHe;AAIfI;AAJe,CAAjB","file":"verify.js","sourcesContent":["const { Hasher, Signer, toTxHash } = require('@ocap/mcrypto');\n\nfunction normalizeHex(hex) {\n return String(hex || '')\n .replace(/^0x/i, '')\n .toLowerCase();\n}\n\nfunction sha256Buf(data) {\n const hex = Hasher.SHA2.hash256(data, 1, 'hex');\n return Buffer.from(String(hex).replace(/^0x/i, ''), 'hex');\n}\n\nfunction hashPair(left, right) {\n return sha256Buf(Buffer.concat([left, right]));\n}\n\n// Proof length for every leaf of a tree with `treeSize` leaves (odd last node pairs with itself)\nfunction merkleProofLength(treeSize) {\n let depth = 0;\n for (let width = treeSize; width > 1; width = Math.ceil(width / 2)) {\n depth++;\n }\n return depth;\n}\n\nfunction verifyMerkleProof(leaf, index, proof, root, treeSize) {\n if (!Number.isInteger(index) || index < 0) {\n return false;\n }\n // #972: bind the proof to the checkpoint's tree size\n if (treeSize !== undefined) {\n if (\n !Number.isInteger(treeSize) ||\n treeSize < 1 ||\n index >= treeSize ||\n proof.length !== merkleProofLength(treeSize)\n ) {\n return false;\n }\n }\n if (proof.length === 0) {\n return index === 0 && leaf.equals(root);\n }\n let currentHash = leaf;\n let currentIndex = index;\n for (let i = 0; i < proof.length; i++) {\n const sibling = proof[i];\n if (currentIndex % 2 === 0) {\n currentHash = hashPair(currentHash, sibling);\n } else {\n currentHash = hashPair(sibling, currentHash);\n }\n currentIndex = Math.floor(currentIndex / 2);\n }\n if (currentIndex !== 0) {\n return false;\n }\n return currentHash.equals(root);\n}\n\nfunction computeEntryHash(sequence, txRaw, stateCommitHash = '') {\n const data = Buffer.concat([Buffer.from(String(sequence)), Buffer.from(txRaw), Buffer.from(stateCommitHash)]);\n return Hasher.SHA2.hash256(data, 1, 'hex');\n}\n\nfunction computeCheckpointHash(checkpoint) {\n const data = Buffer.from(\n JSON.stringify({\n height: Number(checkpoint.height),\n sequence: Number(checkpoint.sequence),\n prevSequence: Number(checkpoint.prevSequence),\n txRoot: checkpoint.txRoot,\n txCount: Number(checkpoint.txCount),\n stateRoot: checkpoint.stateRoot || undefined,\n timestamp: Number(checkpoint.timestamp),\n prevCheckpoint: checkpoint.prevCheckpoint || null,\n proposer: checkpoint.proposer,\n })\n );\n return Hasher.SHA2.hash256(data, 1, 'hex');\n}\n\nasync function verifyCheckpointSignature(checkpoint, publicKeyOrVerifier, expectedProposer) {\n if (!checkpoint || !checkpoint.hash || !checkpoint.signature || checkpoint.signature === 'unsigned') {\n return false;\n }\n if (expectedProposer && checkpoint.proposer !== expectedProposer) {\n return false;\n }\n const recomputedHash = computeCheckpointHash(checkpoint);\n if (normalizeHex(recomputedHash) !== normalizeHex(checkpoint.hash)) {\n return false;\n }\n if (!publicKeyOrVerifier) {\n return false;\n }\n const hashBytes = Buffer.from(normalizeHex(checkpoint.hash), 'hex');\n if (typeof publicKeyOrVerifier === 'function') {\n try {\n // Only a literal `true` authenticates: `{ verified: false }`, 1 or 'false' must not pass as truthy.\n return (await publicKeyOrVerifier(hashBytes, checkpoint.signature, checkpoint.proposer)) === true;\n } catch (_err) {\n return false;\n }\n }\n try {\n if (Signer.Ed25519.verify(hashBytes, checkpoint.signature, publicKeyOrVerifier)) {\n return true;\n }\n const sha3Digest = Hasher.SHA3.hash256(hashBytes, 1);\n if (Signer.Ed25519.verify(sha3Digest, checkpoint.signature, publicKeyOrVerifier)) {\n return true;\n }\n const sha2Digest = Hasher.SHA2.hash256(hashBytes, 1);\n if (Signer.Ed25519.verify(sha2Digest, checkpoint.signature, publicKeyOrVerifier)) {\n return true;\n }\n return false;\n } catch (_err) {\n return false;\n }\n}\n\nconst NO_TRUST_ANCHOR_REASON = 'no trust anchor (proposerPublicKey/verifier) supplied';\n\n// Pick the trust anchor that authenticates the checkpoint signature, or undefined when none is usable.\n// Empty / whitespace / bare \"0x\" strings and zero-length byte arrays do not count as an anchor (#1133).\n// Hex strings are normalised to bytes whether or not they carry a 0x prefix.\nfunction resolveTrustAnchor(params) {\n if (typeof params.verifier === 'function') return params.verifier;\n const pk = params.proposerPublicKey;\n if (typeof pk === 'string') {\n const bare = pk.trim().replace(/^0x/i, '');\n if (bare.length === 0) return undefined;\n // Hex keys are accepted with or without 0x and in any case; decode them to bytes so both\n // implementations hand the same value to the signature check.\n return /^[0-9a-fA-F]+$/.test(bare) && bare.length % 2 === 0 ? Buffer.from(bare, 'hex') : pk.trim();\n }\n if (pk instanceof Uint8Array) {\n return pk.length > 0 ? pk : undefined;\n }\n return undefined;\n}\n\n/**\n * Pure client-side verification of transaction inclusion in a signed Checkpoint (< 1ms, zero network I/O).\n *\n * Only `txRaw` is authenticated: `entryHash` covers `sequence`, `txRaw` and `stateCommitHash`, not\n * `entry.tx`, `from`, `pk`, `nonce` or `signature`. A `verified: true` result says nothing about those\n * fields. Decode the verified `txRaw` yourself; never read `entry.tx` directly (#1139).\n *\n * @param {object} params\n * @param {object} params.checkpoint\n * @param {object} params.proof\n * @param {object} params.entry\n * @param {string} [params.txHash]\n * @param {boolean} [params.verifyTxRawHash=true] - require entry.hash === toTxHash(txRaw) (#976)\n * @param {string} [params.expectedProposer]\n * @param {string|Buffer} [params.proposerPublicKey] - trust anchor; one of proposerPublicKey / verifier is\n * required, otherwise the result is `{ verified: false }` (#1133)\n * @param {Function} [params.verifier]\n * @param {boolean} [params.allowUnauthenticated=false] - UNSAFE: skip the signature check when no trust anchor\n * is supplied (pre-#1133 behavior). A malicious RPC can then forge inclusion.\n * @returns {Promise<{ verified: boolean, reason?: string }>}\n */\nasync function verifyTxInclusion(params) {\n try {\n if (!params || !params.checkpoint || !params.proof || !params.entry) {\n return { verified: false, reason: 'Missing checkpoint, proof, or entry' };\n }\n\n const { checkpoint, proof, entry, txHash, expectedProposer } = params;\n\n // Fail closed (#1133): every check below is structural and a forging RPC can satisfy them all;\n // only the checkpoint signature against a trust anchor authenticates the bundle.\n const trustAnchor = resolveTrustAnchor(params);\n if (!trustAnchor && params.allowUnauthenticated !== true) {\n return { verified: false, reason: NO_TRUST_ANCHOR_REASON };\n }\n\n // entry.hash is not covered by entryHash or the Merkle leaf, so bind it to txRaw (#976).\n // On by default: this client only talks to OCAP chains, where hash = toTxHash(txRaw).\n if (\n params.verifyTxRawHash !== false &&\n normalizeHex(toTxHash(Buffer.from(String(entry.txRaw || ''), 'base64'))) !== normalizeHex(entry.hash)\n ) {\n return { verified: false, reason: `Transaction hash ${entry.hash} does not match entry txRaw` };\n }\n\n if (txHash && entry.hash !== txHash) {\n return {\n verified: false,\n reason: `Transaction hash mismatch: expected ${txHash}, got ${entry.hash}`,\n };\n }\n\n if (expectedProposer && checkpoint.proposer !== expectedProposer) {\n return {\n verified: false,\n reason: `Checkpoint proposer mismatch: expected ${expectedProposer}, got ${checkpoint.proposer}`,\n };\n }\n\n const seq = Number(entry.sequence);\n const prevSeq = Number(checkpoint.prevSequence);\n const cpSeq = Number(checkpoint.sequence);\n\n if (seq <= prevSeq || seq > cpSeq) {\n return {\n verified: false,\n reason: `Entry sequence ${seq} is outside checkpoint range (${prevSeq}, ${cpSeq}]`,\n };\n }\n\n const expectedIndex = seq - (prevSeq + 1);\n if (Number(proof.index) !== expectedIndex) {\n return {\n verified: false,\n reason: `Merkle proof index mismatch: expected ${expectedIndex}, got ${proof.index}`,\n };\n }\n\n const recomputedEntryHash = computeEntryHash(seq, entry.txRaw, entry.stateCommitHash || '');\n if (normalizeHex(entry.entryHash) !== normalizeHex(recomputedEntryHash)) {\n return {\n verified: false,\n reason: `Entry hash mismatch: expected ${recomputedEntryHash}, got ${entry.entryHash}`,\n };\n }\n\n const expectedLeafHash = Hasher.SHA2.hash256(Buffer.from(recomputedEntryHash), 1, 'hex');\n if (normalizeHex(proof.leaf) !== normalizeHex(expectedLeafHash)) {\n return {\n verified: false,\n reason: `Merkle proof leaf mismatch: expected ${expectedLeafHash}, got ${proof.leaf}`,\n };\n }\n\n if (normalizeHex(proof.root) !== normalizeHex(checkpoint.txRoot)) {\n return {\n verified: false,\n reason: `Merkle proof root mismatch: expected ${checkpoint.txRoot}, got ${proof.root}`,\n };\n }\n\n const leafBuf = Buffer.from(normalizeHex(proof.leaf), 'hex');\n const proofBufs = (proof.proof || []).map((p) => Buffer.from(normalizeHex(p), 'hex'));\n const rootBuf = Buffer.from(normalizeHex(proof.root), 'hex');\n\n if (!verifyMerkleProof(leafBuf, Number(proof.index), proofBufs, rootBuf, Number(checkpoint.txCount))) {\n return { verified: false, reason: 'Invalid Merkle inclusion proof' };\n }\n\n const recomputedCpHash = computeCheckpointHash(checkpoint);\n if (normalizeHex(recomputedCpHash) !== normalizeHex(checkpoint.hash)) {\n return {\n verified: false,\n reason: `Checkpoint hash mismatch: expected ${recomputedCpHash}, got ${checkpoint.hash}`,\n };\n }\n\n if (!checkpoint.signature || checkpoint.signature === 'unsigned') {\n return { verified: false, reason: 'Checkpoint is unsigned' };\n }\n\n if (trustAnchor) {\n const sigValid = await verifyCheckpointSignature(checkpoint, trustAnchor, expectedProposer);\n if (!sigValid) {\n return { verified: false, reason: 'Invalid checkpoint signature' };\n }\n }\n\n return { verified: true };\n } catch (err) {\n return {\n verified: false,\n reason: err instanceof Error ? err.message : String(err),\n };\n }\n}\n\nmodule.exports = {\n verifyTxInclusion,\n verifyCheckpointSignature,\n computeEntryHash,\n computeCheckpointHash,\n};\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ocap/client",
3
- "version": "1.30.24",
3
+ "version": "1.30.25",
4
4
  "description": "graphql client to read/write data on arcblock blockchain",
5
5
  "keywords": [
6
6
  "graphql",
@@ -52,17 +52,17 @@
52
52
  "encode.d.ts"
53
53
  ],
54
54
  "dependencies": {
55
- "@arcblock/did": "1.30.24",
56
- "@arcblock/did-util": "1.30.24",
57
- "@arcblock/jwt": "1.30.24",
55
+ "@arcblock/did": "1.30.25",
56
+ "@arcblock/did-util": "1.30.25",
57
+ "@arcblock/jwt": "1.30.25",
58
58
  "@arcblock/sdk-util": "^0.36.4",
59
- "@arcblock/ws": "1.30.24",
60
- "@ocap/asset": "1.30.24",
61
- "@ocap/mcrypto": "1.30.24",
62
- "@ocap/message": "1.30.24",
63
- "@ocap/proto": "1.30.24",
64
- "@ocap/util": "1.30.24",
65
- "@ocap/wallet": "1.30.24",
59
+ "@arcblock/ws": "1.30.25",
60
+ "@ocap/asset": "1.30.25",
61
+ "@ocap/mcrypto": "1.30.25",
62
+ "@ocap/message": "1.30.25",
63
+ "@ocap/proto": "1.30.25",
64
+ "@ocap/util": "1.30.25",
65
+ "@ocap/wallet": "1.30.25",
66
66
  "blueimp-md5": "^2.19.0",
67
67
  "buffer": "6.0.3",
68
68
  "debug": "^4.4.3",