@ocap/client 1.31.8 → 1.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/verify.js CHANGED
@@ -1,11 +1,366 @@
1
1
  'use strict';
2
2
 
3
- const { Hasher, Signer, toTxHash } = require('@ocap/mcrypto');
3
+ const {
4
+ isEthereumDid,
5
+ isFromPublicKey,
6
+ isValid: isValidDid,
7
+ toAddress,
8
+ toChecksumAddress,
9
+ toTypeInfo
10
+ } = require('@arcblock/did');
11
+ const { Hasher, Signer, types: mcryptoTypes, toTxHash } = require('@ocap/mcrypto');
4
12
  const { formatMessage, toTypeUrl } = require('@ocap/message');
5
13
  const { CANONICAL_SELF_DESCRIBE_PREFIX, decodeTx: decodeCbor, encodeTx: encodeCbor } = require('@ocap/message/cbor');
6
14
  const { decodeTx: decodeProto, encodeTx: encodeProto } = require('@ocap/message/protobuf');
7
15
  const { stripDefaultDepositV2BridgeFieldsInTx } = require('@ocap/util/lib/deposit-v2-bridge-fields');
8
16
 
17
+ const MAX_CHECKPOINT_HASH_CHAIN_LENGTH = 100000;
18
+ const HEX_PK_LENGTHS = new Set([64, 66, 128, 130]);
19
+ const BASE64_PK_LENGTHS = new Set([43, 44, 86, 87, 88]);
20
+
21
+ function isStrictSafeInt(val) {
22
+ return typeof val === 'number' && Number.isSafeInteger(val);
23
+ }
24
+
25
+ function normalizeDidForCompare(did) {
26
+ const trimmed = String(did || '').trim();
27
+ if (!trimmed) return '';
28
+ const bare = toAddress(trimmed);
29
+ if (isEthereumDid(bare)) {
30
+ return toChecksumAddress(bare);
31
+ }
32
+ return bare;
33
+ }
34
+
35
+ function curveFromPkType(pkType) {
36
+ if (pkType === undefined) return undefined;
37
+ if (pkType === mcryptoTypes.KeyType.ED25519) return 'ed25519';
38
+ if (pkType === mcryptoTypes.KeyType.SECP256K1 || pkType === mcryptoTypes.KeyType.ETHEREUM) return 'secp256k1';
39
+ return 'unsupported';
40
+ }
41
+
42
+ function curveFromDidIfValid(did) {
43
+ if (!did || typeof did !== 'string') return undefined;
44
+ const clean = normalizeDidForCompare(did);
45
+ if (!clean) return undefined;
46
+ if (isEthereumDid(clean)) return 'secp256k1';
47
+ if (!isValidDid(clean)) return undefined;
48
+ try {
49
+ const info = toTypeInfo(clean);
50
+ return curveFromPkType(info.pk);
51
+ } catch (_err) {
52
+ return undefined;
53
+ }
54
+ }
55
+
56
+ function classifyPublicKeyBytes(bytes) {
57
+ if (!bytes || !(bytes instanceof Uint8Array)) return null;
58
+ if (bytes.length === 32) {
59
+ return { bytes: Buffer.from(bytes), curve: 'ed25519' };
60
+ }
61
+ if (bytes.length === 33 && (bytes[0] === 0x02 || bytes[0] === 0x03)) {
62
+ return { bytes: Buffer.from(bytes), curve: 'secp256k1' };
63
+ }
64
+ if (bytes.length === 65 && bytes[0] === 0x04) {
65
+ return { bytes: Buffer.from(bytes), curve: 'secp256k1' };
66
+ }
67
+ if (bytes.length === 64) {
68
+ const prefixed = Buffer.alloc(65);
69
+ prefixed[0] = 0x04;
70
+ Buffer.from(bytes).copy(prefixed, 1);
71
+ return { bytes: prefixed, curve: 'secp256k1' };
72
+ }
73
+ return null;
74
+ }
75
+
76
+ const CANONICAL_BASE64_OR_URL_RE = /^(?:[A-Za-z0-9+/]+={0,2}|[A-Za-z0-9_-]+={0,2})$/;
77
+
78
+ function tryStrictBase64Decode(str) {
79
+ if (typeof str !== 'string' || !CANONICAL_BASE64_OR_URL_RE.test(str)) {
80
+ return null;
81
+ }
82
+ const unpadded = str.replace(/=+$/, '');
83
+ if (!unpadded || unpadded.length % 4 === 1) {
84
+ return null;
85
+ }
86
+ try {
87
+ const normalized = unpadded.replace(/-/g, '+').replace(/_/g, '/');
88
+ const padded = normalized + '='.repeat((4 - normalized.length % 4) % 4);
89
+ const decoded = Buffer.from(padded, 'base64');
90
+ if (decoded.length === 0) return null;
91
+ const expectedStd = decoded.toString('base64');
92
+ const expectedStdUnpadded = expectedStd.replace(/=+$/, '');
93
+ const expectedUrl = expectedStdUnpadded.replace(/\+/g, '-').replace(/\//g, '_');
94
+ if (str !== expectedUrl && str !== expectedStd && str !== expectedStdUnpadded) {
95
+ return null;
96
+ }
97
+ return decoded;
98
+ } catch (_err) {
99
+ return null;
100
+ }
101
+ }
102
+
103
+ function tryCanonicalTxRawBytes(txRaw) {
104
+ if (typeof txRaw !== 'string' || !txRaw) return null;
105
+ if (txRaw !== txRaw.trim()) return null;
106
+ if (!CANONICAL_BASE64_OR_URL_RE.test(txRaw)) {
107
+ return null;
108
+ }
109
+ const unpaddedRaw = txRaw.replace(/=+$/, '');
110
+ if (!unpaddedRaw || unpaddedRaw.length % 4 === 1) {
111
+ return null;
112
+ }
113
+ const unpadded = unpaddedRaw.replace(/-/g, '+').replace(/_/g, '/');
114
+ const padded = unpadded + '='.repeat((4 - unpadded.length % 4) % 4);
115
+ const decoded = Buffer.from(padded, 'base64');
116
+ const expectedStd = decoded.toString('base64');
117
+ const expectedStdUnpadded = expectedStd.replace(/=+$/, '');
118
+ const expectedUrl = expectedStd.replace(/\+/g, '-').replace(/\//g, '_');
119
+ const expectedUrlUnpadded = expectedStdUnpadded.replace(/\+/g, '-').replace(/\//g, '_');
120
+ if (txRaw !== expectedStd && txRaw !== expectedStdUnpadded && txRaw !== expectedUrl && txRaw !== expectedUrlUnpadded) {
121
+ return null;
122
+ }
123
+ return decoded;
124
+ }
125
+
126
+ function decodeMultiCurvePublicKey(publicKey) {
127
+ if (publicKey instanceof Uint8Array) {
128
+ return classifyPublicKeyBytes(publicKey);
129
+ }
130
+ if (typeof publicKey !== 'string') {
131
+ return null;
132
+ }
133
+ const trimmed = publicKey.trim();
134
+ if (!trimmed || /^0x$/i.test(trimmed)) {
135
+ return null;
136
+ }
137
+ const has0x = /^0x/i.test(trimmed);
138
+ const without0x = has0x ? trimmed.slice(2) : trimmed;
139
+
140
+ if (HEX_PK_LENGTHS.has(without0x.length) && /^[0-9a-fA-F]+$/.test(without0x)) {
141
+ return classifyPublicKeyBytes(Buffer.from(without0x.toLowerCase(), 'hex'));
142
+ }
143
+
144
+ if (BASE64_PK_LENGTHS.has(trimmed.length)) {
145
+ const b64Bytes = tryStrictBase64Decode(trimmed);
146
+ if (b64Bytes) {
147
+ const classified = classifyPublicKeyBytes(b64Bytes);
148
+ if (classified) return classified;
149
+ }
150
+ }
151
+
152
+ return null;
153
+ }
154
+
155
+ function verifyDidMatchesMultiCurvePublicKey(did, publicKey) {
156
+ if (!did || typeof did !== 'string') return false;
157
+ const normalized = normalizeDidForCompare(did);
158
+ if (!normalized || !isEthereumDid(normalized) && !isValidDid(normalized)) {
159
+ return false;
160
+ }
161
+ const decoded = decodeMultiCurvePublicKey(publicKey);
162
+ if (!decoded) {
163
+ return false;
164
+ }
165
+ const didCurve = curveFromDidIfValid(normalized);
166
+ if (didCurve !== decoded.curve) {
167
+ return false;
168
+ }
169
+ try {
170
+ if (decoded.curve === 'ed25519') {
171
+ if (isEthereumDid(normalized) || toTypeInfo(normalized).pk !== mcryptoTypes.KeyType.ED25519) {
172
+ return false;
173
+ }
174
+ return isFromPublicKey(normalized, decoded.bytes);
175
+ }
176
+ const uncompressed65 = typeof Signer.Secp256k1.toUncompressedPublicKey === 'function' ? Signer.Secp256k1.toUncompressedPublicKey(decoded.bytes) : null;
177
+ if (!uncompressed65 || uncompressed65.length !== 65) {
178
+ return false;
179
+ }
180
+ if (isEthereumDid(normalized)) {
181
+ return isFromPublicKey(normalized, uncompressed65.subarray(1));
182
+ }
183
+ const pkType = toTypeInfo(normalized).pk;
184
+ if (pkType === mcryptoTypes.KeyType.ETHEREUM) {
185
+ return isFromPublicKey(normalized, uncompressed65.subarray(1));
186
+ }
187
+ if (pkType !== mcryptoTypes.KeyType.SECP256K1) {
188
+ return false;
189
+ }
190
+ if (isFromPublicKey(normalized, uncompressed65)) {
191
+ return true;
192
+ }
193
+ const compressed33 = Buffer.alloc(33);
194
+ compressed33[0] = (uncompressed65[64] & 1) === 1 ? 0x03 : 0x02;
195
+ Buffer.from(uncompressed65.subarray(1, 33)).copy(compressed33, 1);
196
+ if (isFromPublicKey(normalized, compressed33)) {
197
+ return true;
198
+ }
199
+ return false;
200
+ } catch (_err) {
201
+ return false;
202
+ }
203
+ }
204
+
205
+ function decodeSignatureBytes(signature) {
206
+ if (signature instanceof Uint8Array) {
207
+ return signature.length > 0 ? Buffer.from(signature) : null;
208
+ }
209
+ if (typeof signature === 'string') {
210
+ const trimmed = signature.trim();
211
+ if (!trimmed || trimmed === 'unsigned') return null;
212
+ const bare = trimmed.replace(/^0x/i, '');
213
+ if (!bare || bare.length % 2 !== 0 || !/^[0-9a-fA-F]+$/.test(bare)) {
214
+ return null;
215
+ }
216
+ return Buffer.from(bare.toLowerCase(), 'hex');
217
+ }
218
+ return null;
219
+ }
220
+
221
+ const ED25519_ZERO = BigInt(0);
222
+ const ED25519_ONE = BigInt(1);
223
+ const ED25519_TWO = BigInt(2);
224
+ const ED25519_BYTE_BASE = BigInt(256);
225
+ const ED25519_P = BigInt('57896044618658097711785492504343953926634992332820282019728792003956564819949');
226
+ const ED25519_P_MINUS_5_DIV_8 = BigInt('7237005577332262213973186563042994240829374041602535252466099000494570602493');
227
+ const ED25519_D = BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555');
228
+ const ED25519_SQRT_M1 = BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752');
229
+
230
+ function ed25519ModPow(baseIn, expIn, mod) {
231
+ let result = ED25519_ONE;
232
+ let base = (baseIn % mod + mod) % mod;
233
+ let exp = expIn;
234
+ while (exp > ED25519_ZERO) {
235
+ if (exp % ED25519_TWO === ED25519_ONE) result = result * base % mod;
236
+ base = base * base % mod;
237
+ exp = exp / ED25519_TWO;
238
+ }
239
+ return result;
240
+ }
241
+
242
+ function isValidEd25519PublicKey(bytes) {
243
+ if (!(bytes instanceof Uint8Array) || bytes.length !== 32) return false;
244
+ let y = ED25519_ZERO;
245
+ let mult = ED25519_ONE;
246
+ for (let i = 0; i < 32; i++) {
247
+ const byte = bytes[i];
248
+ y = y + BigInt(i === 31 ? byte & 0x7f : byte) * mult;
249
+ mult = mult * ED25519_BYTE_BASE;
250
+ }
251
+ const x0 = bytes[31] >> 7 & 1;
252
+ if (y >= ED25519_P) return false;
253
+
254
+ const y2 = y * y % ED25519_P;
255
+ const u = (y2 - ED25519_ONE + ED25519_P) % ED25519_P;
256
+ const v = (ED25519_D * y2 + ED25519_ONE) % ED25519_P;
257
+
258
+ const v2 = v * v % ED25519_P;
259
+ const v3 = v2 * v % ED25519_P;
260
+ const v7 = v3 * v3 % ED25519_P * v % ED25519_P;
261
+ const uv7 = u * v7 % ED25519_P;
262
+ let x = u * v3 % ED25519_P * ed25519ModPow(uv7, ED25519_P_MINUS_5_DIV_8, ED25519_P) % ED25519_P;
263
+
264
+ const vx2 = v * (x * x % ED25519_P) % ED25519_P;
265
+ if (vx2 !== u) {
266
+ if (vx2 === (ED25519_P - u) % ED25519_P) {
267
+ x = x * ED25519_SQRT_M1 % ED25519_P;
268
+ } else {
269
+ return false;
270
+ }
271
+ }
272
+ if (x === ED25519_ZERO && x0 === 1) return false;
273
+ if (Number(x % ED25519_TWO) !== x0) {
274
+ x = ED25519_P - x;
275
+ }
276
+
277
+ let X = x;
278
+ let Y = y;
279
+ let Z = ED25519_ONE;
280
+ const twoP = ED25519_TWO * ED25519_P;
281
+ for (let i = 0; i < 3; i++) {
282
+ const A = X * X % ED25519_P;
283
+ const B = Y * Y % ED25519_P;
284
+ const C = ED25519_TWO * (Z * Z % ED25519_P) % ED25519_P;
285
+ const D = (ED25519_P - A) % ED25519_P;
286
+ const xPlusY = (X + Y) % ED25519_P;
287
+ const E = (xPlusY * xPlusY % ED25519_P - A - B + twoP) % ED25519_P;
288
+ const G = (D + B) % ED25519_P;
289
+ const F = (G - C + ED25519_P) % ED25519_P;
290
+ const H = (D - B + ED25519_P) % ED25519_P;
291
+ X = E * F % ED25519_P;
292
+ Y = G * H % ED25519_P;
293
+ Z = F * G % ED25519_P;
294
+ }
295
+ return !(X === ED25519_ZERO && Y === Z);
296
+ }
297
+
298
+ function verifyMultiCurveDigestSignature(digestBytes, signature, publicKey, signerDid) {
299
+ if (!(digestBytes instanceof Uint8Array) || digestBytes.length === 0) {
300
+ return false;
301
+ }
302
+ const decodedPk = decodeMultiCurvePublicKey(publicKey);
303
+ if (!decodedPk) {
304
+ return false;
305
+ }
306
+ if (decodedPk.curve === 'ed25519' && !isValidEd25519PublicKey(decodedPk.bytes)) {
307
+ return false;
308
+ }
309
+ if (signerDid && typeof signerDid === 'string') {
310
+ const normalizedSigner = normalizeDidForCompare(signerDid);
311
+ if (normalizedSigner && (isEthereumDid(normalizedSigner) || isValidDid(normalizedSigner)) && !verifyDidMatchesMultiCurvePublicKey(normalizedSigner, decodedPk.bytes)) {
312
+ return false;
313
+ }
314
+ }
315
+ const didCurve = curveFromDidIfValid(signerDid);
316
+ if (didCurve !== undefined && didCurve !== decodedPk.curve) {
317
+ return false;
318
+ }
319
+ const sigBytes = decodeSignatureBytes(signature);
320
+ if (!sigBytes) {
321
+ return false;
322
+ }
323
+
324
+ try {
325
+ if (decodedPk.curve === 'ed25519') {
326
+ if (sigBytes.length !== 64) {
327
+ return false;
328
+ }
329
+ if (Signer.Ed25519.verify(digestBytes, sigBytes, decodedPk.bytes)) {
330
+ return true;
331
+ }
332
+ const sha3Digest = Hasher.SHA3.hash256(digestBytes, 1);
333
+ if (Signer.Ed25519.verify(sha3Digest, sigBytes, decodedPk.bytes)) {
334
+ return true;
335
+ }
336
+ const sha2Digest = Hasher.SHA2.hash256(digestBytes, 1);
337
+ if (Signer.Ed25519.verify(sha2Digest, sigBytes, decodedPk.bytes)) {
338
+ return true;
339
+ }
340
+ return false;
341
+ }
342
+
343
+ if (Signer.Secp256k1.verify(digestBytes, sigBytes, decodedPk.bytes)) {
344
+ return true;
345
+ }
346
+ const sha3Digest = Hasher.SHA3.hash256(digestBytes, 1);
347
+ if (Signer.Secp256k1.verify(sha3Digest, sigBytes, decodedPk.bytes)) {
348
+ return true;
349
+ }
350
+ const sha2Digest = Hasher.SHA2.hash256(digestBytes, 1);
351
+ if (Signer.Secp256k1.verify(sha2Digest, sigBytes, decodedPk.bytes)) {
352
+ return true;
353
+ }
354
+ const keccakDigest = Hasher.Keccak.hash256(digestBytes, 1);
355
+ if (Signer.Secp256k1.verify(keccakDigest, sigBytes, decodedPk.bytes)) {
356
+ return true;
357
+ }
358
+ return false;
359
+ } catch (_err) {
360
+ return false;
361
+ }
362
+ }
363
+
9
364
  function normalizeHex(hex) {
10
365
  return String(hex || '').replace(/^0x/i, '').toLowerCase();
11
366
  }
@@ -49,33 +404,48 @@ function validatePresentEntryPrimitives(entry) {
49
404
  for (let i = 0; i < stringFields.length; i++) {
50
405
  const field = stringFields[i];
51
406
  const val = entry[field];
52
- if (val !== undefined && val !== null && typeof val !== 'string') {
407
+ if (val === null) {
408
+ return `Entry ${field} must not be null`;
409
+ }
410
+ if (val !== undefined && typeof val !== 'string') {
53
411
  return `Entry ${field} must be a string`;
54
412
  }
55
413
  }
56
- if (entry.nonce !== undefined && entry.nonce !== null) {
414
+ if (entry.nonce === null) {
415
+ return 'Entry nonce must not be null';
416
+ }
417
+ if (entry.nonce !== undefined) {
57
418
  const isNum = typeof entry.nonce === 'number' && Number.isFinite(entry.nonce);
58
419
  const isStr = typeof entry.nonce === 'string';
59
420
  if (!isNum && !isStr) {
60
421
  return 'Entry nonce must be a finite number or string';
61
422
  }
62
423
  }
424
+ if (entry.tx === null) {
425
+ return 'Entry tx must not be null';
426
+ }
63
427
  return null;
64
428
  }
65
429
 
66
430
  function tryDecodeOcapWireTx(txRaw) {
67
- const trimmed = String(txRaw || '').trim();
431
+ if (typeof txRaw !== 'string' || !txRaw) return { kind: 'none' };
432
+ const trimmed = txRaw.trim();
68
433
  if (!trimmed || trimmed.startsWith('{')) return { kind: 'none' };
434
+ const hasSurroundingWhitespace = txRaw !== trimmed;
69
435
  let rawBuf;
70
436
  try {
71
- rawBuf = Buffer.from(trimmed, 'base64');
437
+ rawBuf = Buffer.from(trimmed.replace(/-/g, '+').replace(/_/g, '/'), 'base64');
72
438
  } catch (_err) {
73
439
  return { kind: 'none' };
74
440
  }
75
441
  if (rawBuf.length === 0) {
76
442
  return { kind: 'none' };
77
443
  }
78
- const isCanonicalBase64 = rawBuf.toString('base64') === trimmed;
444
+ const stdB64 = rawBuf.toString('base64');
445
+ const stdB64Unpadded = stdB64.replace(/=+$/, '');
446
+ const urlB64 = stdB64.replace(/\+/g, '-').replace(/\//g, '_');
447
+ const urlB64Unpadded = urlB64.replace(/=+$/, '');
448
+ const isCanonicalBase64 = !hasSurroundingWhitespace && (txRaw === stdB64 || txRaw === stdB64Unpadded || txRaw === urlB64 || txRaw === urlB64Unpadded);
79
449
  const rawBytes = new Uint8Array(rawBuf.buffer, rawBuf.byteOffset, rawBuf.byteLength);
80
450
 
81
451
  if (hasCborSelfDescribeTag(rawBytes)) {
@@ -133,7 +503,13 @@ function authenticateEntryDecodedFields(entry, strict) {
133
503
  return { ok: false, reason: primitiveErr };
134
504
  }
135
505
 
136
- const rawStr = String(entry.txRaw !== undefined && entry.txRaw !== null ? entry.txRaw : '').trim();
506
+ if (typeof entry.txRaw !== 'string' || !entry.txRaw) {
507
+ return { ok: false, reason: 'Entry txRaw must be a non-empty string' };
508
+ }
509
+ if (entry.txRaw !== entry.txRaw.trim()) {
510
+ return { ok: false, reason: 'Non-canonical whitespace in entry txRaw' };
511
+ }
512
+ const rawStr = entry.txRaw;
137
513
 
138
514
  if (rawStr.startsWith('{')) {
139
515
  let parsedRaw;
@@ -339,7 +715,30 @@ function computeEntryHash(sequence, txRaw, stateCommitHash = '') {
339
715
  return Hasher.SHA2.hash256(data, 1, 'hex');
340
716
  }
341
717
 
718
+ const CANONICAL_DECIMAL_UINT_RE = /^(?:0|[1-9]\d*)$/;
719
+
720
+ function normalizeCanonicalCheckpointTimestamp(ts) {
721
+ if (typeof ts === 'number') {
722
+ if (!Number.isSafeInteger(ts) || ts < 0) {
723
+ return null;
724
+ }
725
+ return ts === 0 ? 0 : ts;
726
+ }
727
+ if (typeof ts === 'string') {
728
+ if (!CANONICAL_DECIMAL_UINT_RE.test(ts)) {
729
+ return null;
730
+ }
731
+ const parsed = Number(ts);
732
+ if (!Number.isSafeInteger(parsed)) {
733
+ return null;
734
+ }
735
+ return parsed;
736
+ }
737
+ return null;
738
+ }
739
+
342
740
  function computeCheckpointHash(checkpoint) {
741
+ const normalizedTs = normalizeCanonicalCheckpointTimestamp(checkpoint.timestamp);
343
742
  const data = Buffer.from(JSON.stringify({
344
743
  height: Number(checkpoint.height),
345
744
  sequence: Number(checkpoint.sequence),
@@ -347,7 +746,7 @@ function computeCheckpointHash(checkpoint) {
347
746
  txRoot: checkpoint.txRoot,
348
747
  txCount: Number(checkpoint.txCount),
349
748
  stateRoot: checkpoint.stateRoot || undefined,
350
- timestamp: Number(checkpoint.timestamp),
749
+ timestamp: normalizedTs !== null ? normalizedTs : checkpoint.timestamp,
351
750
  prevCheckpoint: checkpoint.prevCheckpoint || null,
352
751
  proposer: checkpoint.proposer
353
752
  }));
@@ -358,7 +757,7 @@ async function verifyCheckpointSignature(checkpoint, publicKeyOrVerifier, expect
358
757
  if (!checkpoint || !checkpoint.hash || !checkpoint.signature || checkpoint.signature === 'unsigned') {
359
758
  return false;
360
759
  }
361
- if (expectedProposer && checkpoint.proposer !== expectedProposer) {
760
+ if (expectedProposer && normalizeDidForCompare(checkpoint.proposer) !== normalizeDidForCompare(expectedProposer)) {
362
761
  return false;
363
762
  }
364
763
  const recomputedHash = computeCheckpointHash(checkpoint);
@@ -377,46 +776,708 @@ async function verifyCheckpointSignature(checkpoint, publicKeyOrVerifier, expect
377
776
  return false;
378
777
  }
379
778
  }
380
- try {
381
- if (Signer.Ed25519.verify(hashBytes, checkpoint.signature, publicKeyOrVerifier)) {
382
- return true;
779
+ return verifyMultiCurveDigestSignature(hashBytes, checkpoint.signature, publicKeyOrVerifier, checkpoint.proposer);
780
+ }
781
+
782
+ const NO_TRUST_ANCHOR_REASON = 'no trust anchor (proposerPublicKey/verifier) supplied';
783
+
784
+ function ensureHexPrefix(hex) {
785
+ const clean = normalizeHex(hex);
786
+ return clean ? `0x${clean}` : '0x';
787
+ }
788
+
789
+ function validateClientHotStuffConfig(config) {
790
+ if (!config || typeof config !== 'object') {
791
+ throw new TypeError('HotStuff cluster config is required');
792
+ }
793
+ if (!config.chainId || typeof config.chainId !== 'string') {
794
+ throw new TypeError('config.chainId is required');
795
+ }
796
+ if (!Array.isArray(config.validators) || config.validators.length < 1 || config.validators.length > 7) {
797
+ throw new RangeError('HotStuff-Lite cluster size must be between 1 and 7');
798
+ }
799
+ const n = config.validators.length;
800
+ const defaultQuorum = Math.floor(2 * n / 3) + 1;
801
+ let threshold = defaultQuorum;
802
+ if (config.quorumThreshold !== undefined) {
803
+ const explicit = Number(config.quorumThreshold);
804
+ const minSafe = n >= 4 ? defaultQuorum : Math.floor(n / 2) + 1;
805
+ if (!Number.isInteger(explicit) || explicit < minSafe || explicit > n) {
806
+ throw new RangeError(`Invalid quorumThreshold ${String(config.quorumThreshold)} for cluster size ${n}`);
383
807
  }
384
- const sha3Digest = Hasher.SHA3.hash256(hashBytes, 1);
385
- if (Signer.Ed25519.verify(sha3Digest, checkpoint.signature, publicKeyOrVerifier)) {
386
- return true;
808
+ threshold = explicit;
809
+ }
810
+ const validatorMap = new Map();
811
+ const byNormDid = new Map();
812
+ const seenKeys = new Set();
813
+ for (let i = 0; i < config.validators.length; i++) {
814
+ const m = config.validators[i];
815
+ if (!m || typeof m.did !== 'string' || !m.did) {
816
+ throw new TypeError('Each validator member must have a valid DID');
387
817
  }
388
- const sha2Digest = Hasher.SHA2.hash256(hashBytes, 1);
389
- if (Signer.Ed25519.verify(sha2Digest, checkpoint.signature, publicKeyOrVerifier)) {
390
- return true;
818
+ const decoded = decodeMultiCurvePublicKey(m.publicKey);
819
+ if (!decoded) {
820
+ throw new TypeError(`Validator ${m.did} must have a valid publicKey`);
391
821
  }
392
- return false;
393
- } catch (_err) {
394
- return false;
822
+ const cleanPk = Buffer.from(decoded.bytes).toString('hex').toLowerCase();
823
+ const normDid = normalizeDidForCompare(m.did) || m.did;
824
+ if ((isEthereumDid(normDid) || isValidDid(normDid)) && !verifyDidMatchesMultiCurvePublicKey(normDid, m.publicKey)) {
825
+ throw new Error(`Validator ${m.did} publicKey does not cryptographically match DID`);
826
+ }
827
+ if (validatorMap.has(m.did) || byNormDid.has(normDid) || seenKeys.has(cleanPk)) {
828
+ throw new Error(`Duplicate validator DID or publicKey in HotStuff cluster config: ${m.did}`);
829
+ }
830
+ const entry = { did: m.did, publicKey: cleanPk };
831
+ validatorMap.set(m.did, entry);
832
+ byNormDid.set(normDid, entry);
833
+ seenKeys.add(cleanPk);
395
834
  }
835
+ return { threshold: threshold, validatorMap: validatorMap, byNormDid: byNormDid };
396
836
  }
397
837
 
398
- const NO_TRUST_ANCHOR_REASON = 'no trust anchor (proposerPublicKey/verifier) supplied';
838
+ function verifyClientCheckpointQuorumCertificate(checkpoint, config) {
839
+ const parsed = validateClientHotStuffConfig(config);
840
+ const qc = checkpoint ? checkpoint.qc : null;
841
+ if (!qc || typeof qc !== 'object' || qc.version !== 1) {
842
+ return { ok: false, reason: 'Checkpoint is missing required HotStuff QuorumCertificate (qc)' };
843
+ }
844
+ if (qc.chainId !== config.chainId) {
845
+ return { ok: false, reason: `QC chainId (${qc.chainId}) does not match expected chainId (${config.chainId})` };
846
+ }
847
+ if (qc.quorumThreshold !== parsed.threshold || qc.clusterSize !== config.validators.length) {
848
+ return { ok: false, reason: 'QC quorum metadata does not match cluster config' };
849
+ }
850
+ if (!isStrictSafeInt(qc.viewNumber) || qc.viewNumber < 0) {
851
+ return { ok: false, reason: 'Invalid QC viewNumber' };
852
+ }
853
+ const expectedLeader = config.validators[qc.viewNumber % config.validators.length];
854
+ if (!expectedLeader || qc.leaderDid !== expectedLeader.did) {
855
+ return { ok: false, reason: 'QC leaderDid does not match expected view leader' };
856
+ }
857
+ if (qc.height !== checkpoint.height || qc.prevSequence !== checkpoint.prevSequence || qc.sequence !== checkpoint.sequence || normalizeHex(qc.checkpointHash) !== normalizeHex(checkpoint.hash) || normalizeHex(qc.prevCheckpointHash || '') !== normalizeHex(checkpoint.prevCheckpoint || '') || normalizeHex(qc.txRoot) !== normalizeHex(checkpoint.txRoot) || normalizeHex(qc.stateRoot || '') !== normalizeHex(checkpoint.stateRoot || '')) {
858
+ return { ok: false, reason: 'Checkpoint QC header fields do not match checkpoint' };
859
+ }
860
+ if (!Array.isArray(qc.signatures)) {
861
+ return { ok: false, reason: 'Invalid QC signatures array' };
862
+ }
863
+ const canonicalSigs = qc.signatures.slice().sort((a, b) => String(a.voterDid).localeCompare(String(b.voterDid))).map(s => ({
864
+ voterDid: s.voterDid,
865
+ signature: normalizeHex(s.signature),
866
+ timestamp: s.timestamp
867
+ }));
868
+ const recomputedQcHash = ensureHexPrefix(Hasher.SHA2.hash256(Buffer.from(JSON.stringify({
869
+ domain: 'arcblock:hotstuff:qc:v1',
870
+ version: 1,
871
+ chainId: qc.chainId,
872
+ viewNumber: qc.viewNumber,
873
+ height: qc.height,
874
+ checkpointHash: ensureHexPrefix(qc.checkpointHash),
875
+ prevCheckpointHash: qc.prevCheckpointHash ? ensureHexPrefix(qc.prevCheckpointHash) : null,
876
+ prevSequence: qc.prevSequence,
877
+ sequence: qc.sequence,
878
+ txRoot: ensureHexPrefix(qc.txRoot),
879
+ stateRoot: qc.stateRoot ? ensureHexPrefix(qc.stateRoot) : null,
880
+ leaderDid: qc.leaderDid,
881
+ quorumThreshold: qc.quorumThreshold,
882
+ clusterSize: qc.clusterSize,
883
+ signatures: canonicalSigs
884
+ }), 'utf8'), 1, 'hex'));
885
+ if (normalizeHex(recomputedQcHash) !== normalizeHex(qc.qcHash)) {
886
+ return { ok: false, reason: 'QC hash mismatch' };
887
+ }
888
+
889
+ const seenVoters = new Set();
890
+ let validCount = 0;
891
+ for (let i = 0; i < qc.signatures.length; i++) {
892
+ const sigEntry = qc.signatures[i];
893
+ if (!sigEntry || typeof sigEntry.voterDid !== 'string' || !isStrictSafeInt(sigEntry.timestamp)) {
894
+ return { ok: false, reason: 'Invalid QC signature entry' };
895
+ }
896
+ const normVoter = normalizeDidForCompare(sigEntry.voterDid) || sigEntry.voterDid;
897
+ if (seenVoters.has(normVoter)) {
898
+ return { ok: false, reason: `Duplicate voter signature in QC: ${sigEntry.voterDid}` };
899
+ }
900
+ const member = parsed.validatorMap.get(sigEntry.voterDid);
901
+ if (!member) {
902
+ return { ok: false, reason: `QC signer ${sigEntry.voterDid} is not in cluster validator roster` };
903
+ }
904
+ const voteSignPreimage = JSON.stringify({
905
+ domain: 'arcblock:hotstuff:vote:v1',
906
+ version: 1,
907
+ chainId: qc.chainId,
908
+ viewNumber: qc.viewNumber,
909
+ height: qc.height,
910
+ checkpointHash: ensureHexPrefix(qc.checkpointHash),
911
+ prevCheckpointHash: qc.prevCheckpointHash ? ensureHexPrefix(qc.prevCheckpointHash) : null,
912
+ prevSequence: qc.prevSequence,
913
+ sequence: qc.sequence,
914
+ txRoot: ensureHexPrefix(qc.txRoot),
915
+ stateRoot: qc.stateRoot ? ensureHexPrefix(qc.stateRoot) : null,
916
+ voterDid: sigEntry.voterDid,
917
+ timestamp: sigEntry.timestamp
918
+ });
919
+ const voteHashHex = Hasher.SHA2.hash256(Buffer.from(voteSignPreimage, 'utf8'), 1, 'hex');
920
+ const voteHashBytes = Buffer.from(normalizeHex(voteHashHex), 'hex');
921
+ if (!verifyMultiCurveDigestSignature(voteHashBytes, sigEntry.signature, member.publicKey, member.did)) {
922
+ return { ok: false, reason: `Invalid signature in QC for voter ${sigEntry.voterDid}` };
923
+ }
924
+ seenVoters.add(normVoter);
925
+ validCount += 1;
926
+ }
927
+ if (validCount < parsed.threshold) {
928
+ return { ok: false, reason: `QC valid signers (${validCount}) below threshold (${parsed.threshold})` };
929
+ }
930
+ return { ok: true };
931
+ }
399
932
 
400
933
  // Pick the trust anchor that authenticates the checkpoint signature, or undefined when none is usable.
401
934
  // Empty / whitespace / bare "0x" strings and zero-length byte arrays do not count as an anchor (#1133).
402
- // Hex strings are normalised to bytes whether or not they carry a 0x prefix.
403
935
  function resolveTrustAnchor(params) {
404
936
  if (typeof params.verifier === 'function') return params.verifier;
405
937
  const pk = params.proposerPublicKey;
406
938
  if (typeof pk === 'string') {
407
- const bare = pk.trim().replace(/^0x/i, '');
408
- if (bare.length === 0) return undefined;
409
- // Hex keys are accepted with or without 0x and in any case; decode them to bytes so both
410
- // implementations hand the same value to the signature check.
411
- return (/^[0-9a-fA-F]+$/.test(bare) && bare.length % 2 === 0 ? Buffer.from(bare, 'hex') : pk.trim()
412
- );
939
+ const trimmed = pk.trim();
940
+ if (trimmed.length === 0 || /^0x$/i.test(trimmed)) return undefined;
941
+ const decoded = decodeMultiCurvePublicKey(trimmed);
942
+ return decoded ? decoded.bytes : trimmed;
413
943
  }
414
944
  if (pk instanceof Uint8Array) {
415
945
  return pk.length > 0 ? pk : undefined;
416
946
  }
947
+ if (params.hotstuffClusterConfig !== undefined && params.hotstuffClusterConfig !== null) {
948
+ try {
949
+ const parsed = validateClientHotStuffConfig(params.hotstuffClusterConfig);
950
+ return function hotstuffRosterVerifier(data, signature, proposer) {
951
+ if (!proposer || !signature) return false;
952
+ const norm = normalizeDidForCompare(proposer) || proposer;
953
+ const member = parsed.byNormDid.get(norm) || parsed.validatorMap.get(proposer);
954
+ if (!member) return false;
955
+ return verifyMultiCurveDigestSignature(data, signature, member.publicKey, member.did);
956
+ };
957
+ } catch (_err) {
958
+ return function invalidHotStuffVerifier() {
959
+ return false;
960
+ };
961
+ }
962
+ }
417
963
  return undefined;
418
964
  }
419
965
 
966
+ function parseEntryHashV2From(raw) {
967
+ if (raw === undefined) {
968
+ return { ok: true, value: undefined };
969
+ }
970
+ if (raw === Number.POSITIVE_INFINITY) {
971
+ return { ok: true, value: Number.POSITIVE_INFINITY };
972
+ }
973
+ if (typeof raw === 'string') {
974
+ const trimmed = raw.trim();
975
+ if (trimmed.toLowerCase() === 'infinity') {
976
+ return { ok: true, value: Number.POSITIVE_INFINITY };
977
+ }
978
+ if (/^[1-9][0-9]*$/.test(trimmed)) {
979
+ const parsed = Number(trimmed);
980
+ if (Number.isSafeInteger(parsed) && parsed >= 1) {
981
+ return { ok: true, value: parsed };
982
+ }
983
+ }
984
+ return { ok: false, reason: 'Invalid entryHashV2From: must be a safe integer >= 1 or "infinity"' };
985
+ }
986
+ if (typeof raw === 'number' && Number.isSafeInteger(raw) && raw >= 1) {
987
+ return { ok: true, value: raw };
988
+ }
989
+ return { ok: false, reason: 'Invalid entryHashV2From: must be a safe integer >= 1 or "infinity"' };
990
+ }
991
+
992
+ async function verifyPreActivationCheckpointChain(opts) {
993
+ const checkpoint = opts.checkpoint;
994
+ const checkpointSigActivationHeight = opts.checkpointSigActivationHeight;
995
+ const activationCheckpointHash = opts.activationCheckpointHash;
996
+ const checkpointChain = opts.checkpointChain;
997
+ const trustAnchor = opts.trustAnchor;
998
+ const expectedProposer = opts.expectedProposer;
999
+
1000
+ if (typeof activationCheckpointHash !== 'string') {
1001
+ return { ok: false, reason: 'Pre-activation checkpoint requires a valid 64-hex activationCheckpointHash' };
1002
+ }
1003
+ const cleanAnchorHash = normalizeHex(activationCheckpointHash.trim());
1004
+ if (!/^[0-9a-f]{64}$/.test(cleanAnchorHash)) {
1005
+ return { ok: false, reason: 'Pre-activation checkpoint requires a valid 64-hex activationCheckpointHash' };
1006
+ }
1007
+
1008
+ if (checkpointChain !== undefined && !Array.isArray(checkpointChain)) {
1009
+ return { ok: false, reason: 'Invalid checkpointChain: must be an array of checkpoints' };
1010
+ }
1011
+ const chain = checkpointChain || [];
1012
+ if (chain.length > MAX_CHECKPOINT_HASH_CHAIN_LENGTH) {
1013
+ return {
1014
+ ok: false,
1015
+ reason: `Checkpoint hash chain exceeds maximum length (${MAX_CHECKPOINT_HASH_CHAIN_LENGTH})`
1016
+ };
1017
+ }
1018
+
1019
+ let prev = checkpoint;
1020
+ let startIdx = 0;
1021
+
1022
+ if (chain.length > 0) {
1023
+ const first = chain[0];
1024
+ if (!first || typeof first !== 'object') {
1025
+ return { ok: false, reason: 'Invalid checkpoint in checkpointChain at index 0' };
1026
+ }
1027
+ if (isStrictSafeInt(first.height) && first.height === checkpoint.height) {
1028
+ const recomputedFirst = computeCheckpointHash(first);
1029
+ if (normalizeHex(recomputedFirst) !== normalizeHex(first.hash) || normalizeHex(first.hash) !== normalizeHex(checkpoint.hash)) {
1030
+ return { ok: false, reason: 'checkpointChain[0] does not match target checkpoint hash' };
1031
+ }
1032
+ startIdx = 1;
1033
+ }
1034
+ }
1035
+
1036
+ for (let i = startIdx; i < chain.length; i++) {
1037
+ const curr = chain[i];
1038
+ if (!curr || typeof curr !== 'object') {
1039
+ return { ok: false, reason: `Invalid checkpoint in checkpointChain at index ${i}` };
1040
+ }
1041
+ const currHeight = curr.height;
1042
+ const prevHeight = prev.height;
1043
+ if (!isStrictSafeInt(currHeight) || currHeight !== prevHeight + 1) {
1044
+ return {
1045
+ ok: false,
1046
+ reason: `Broken checkpointChain height continuity at index ${i}: expected ${prevHeight + 1}, got ${curr.height}`
1047
+ };
1048
+ }
1049
+ const currPrevSeq = curr.prevSequence;
1050
+ const currSeq = curr.sequence;
1051
+ const prevSeq = prev.sequence;
1052
+ if (!isStrictSafeInt(currPrevSeq) || !isStrictSafeInt(currSeq) || currPrevSeq !== prevSeq || currSeq <= currPrevSeq) {
1053
+ return {
1054
+ ok: false,
1055
+ reason: `Broken checkpointChain sequence continuity at height ${currHeight}`
1056
+ };
1057
+ }
1058
+ const currTxCount = curr.txCount;
1059
+ if (!isStrictSafeInt(currTxCount) || currTxCount !== currSeq - currPrevSeq) {
1060
+ return {
1061
+ ok: false,
1062
+ reason: `Checkpoint txCount mismatch in checkpointChain at height ${currHeight}`
1063
+ };
1064
+ }
1065
+ if (normalizeHex(curr.prevCheckpoint) !== normalizeHex(prev.hash)) {
1066
+ return {
1067
+ ok: false,
1068
+ reason: `Broken prevCheckpoint hash link at height ${currHeight}`
1069
+ };
1070
+ }
1071
+ const recomputed = computeCheckpointHash(curr);
1072
+ if (normalizeHex(recomputed) !== normalizeHex(curr.hash)) {
1073
+ return {
1074
+ ok: false,
1075
+ reason: `Checkpoint hash mismatch in checkpointChain at height ${currHeight}`
1076
+ };
1077
+ }
1078
+ prev = curr;
1079
+ }
1080
+
1081
+ if (normalizeHex(prev.hash) !== cleanAnchorHash) {
1082
+ return {
1083
+ ok: false,
1084
+ reason: `Checkpoint hash chain tail ${prev.hash} does not match activationCheckpointHash ${activationCheckpointHash}`
1085
+ };
1086
+ }
1087
+
1088
+ if (!isStrictSafeInt(prev.height) || prev.height < checkpointSigActivationHeight) {
1089
+ return {
1090
+ ok: false,
1091
+ reason: `Activation anchor checkpoint height (${prev.height}) must be >= checkpointSigActivationHeight (${checkpointSigActivationHeight})`
1092
+ };
1093
+ }
1094
+
1095
+ if (expectedProposer && normalizeDidForCompare(prev.proposer) !== normalizeDidForCompare(expectedProposer)) {
1096
+ return {
1097
+ ok: false,
1098
+ reason: `Activation checkpoint proposer mismatch: expected ${expectedProposer}, got ${prev.proposer}`
1099
+ };
1100
+ }
1101
+ if (!prev.signature || prev.signature === 'unsigned') {
1102
+ return { ok: false, reason: 'Activation anchor checkpoint in checkpointChain is unsigned' };
1103
+ }
1104
+ if (trustAnchor) {
1105
+ const anchorSigValid = await verifyCheckpointSignature(prev, trustAnchor, expectedProposer);
1106
+ if (!anchorSigValid) {
1107
+ return { ok: false, reason: 'Invalid signature on activation anchor checkpoint' };
1108
+ }
1109
+ }
1110
+
1111
+ return { ok: true };
1112
+ }
1113
+
1114
+ const MAX_WITNESS_REASON_LENGTH = 512;
1115
+
1116
+ function validateWitnessAttestationStructure(att) {
1117
+ if (!isPlainObject(att)) {
1118
+ return { ok: false, reason: 'Witness attestation must be a JSON object' };
1119
+ }
1120
+ if (typeof att.chainId !== 'string' || !att.chainId.trim() || att.chainId.length > 256) {
1121
+ return { ok: false, reason: 'Witness attestation chainId must be a non-empty string' };
1122
+ }
1123
+ if (!isStrictSafeInt(att.height) || att.height < 1) {
1124
+ return { ok: false, reason: 'Witness attestation height must be a safe integer >= 1' };
1125
+ }
1126
+ if (typeof att.checkpointHash !== 'string' || !/^[0-9a-f]{64}$/.test(normalizeHex(att.checkpointHash))) {
1127
+ return { ok: false, reason: 'Witness attestation checkpointHash must be a 64-hex digest' };
1128
+ }
1129
+ if (typeof att.txRoot !== 'string' || !/^[0-9a-f]{64}$/.test(normalizeHex(att.txRoot))) {
1130
+ return { ok: false, reason: 'Witness attestation txRoot must be a 64-hex digest' };
1131
+ }
1132
+ if (att.stateRoot !== undefined && att.stateRoot !== null) {
1133
+ if (typeof att.stateRoot !== 'string' || att.stateRoot.length > 256) {
1134
+ return { ok: false, reason: 'Witness attestation stateRoot must be a string' };
1135
+ }
1136
+ }
1137
+ if (typeof att.ok !== 'boolean') {
1138
+ return { ok: false, reason: 'Witness attestation ok must be a boolean' };
1139
+ }
1140
+ if (att.reason !== undefined && att.reason !== null) {
1141
+ if (typeof att.reason !== 'string' || att.reason.length > MAX_WITNESS_REASON_LENGTH) {
1142
+ return {
1143
+ ok: false,
1144
+ reason: `Witness attestation reason must be a string <= ${MAX_WITNESS_REASON_LENGTH} characters`
1145
+ };
1146
+ }
1147
+ }
1148
+ if (typeof att.witness !== 'string' || !normalizeDidForCompare(att.witness) || att.witness.length > 128) {
1149
+ return { ok: false, reason: 'Witness attestation witness DID must be a valid non-empty string' };
1150
+ }
1151
+ if (att.witnessPublicKey !== undefined && att.witnessPublicKey !== null) {
1152
+ if (typeof att.witnessPublicKey !== 'string' || !decodeMultiCurvePublicKey(att.witnessPublicKey)) {
1153
+ return { ok: false, reason: 'Witness attestation witnessPublicKey is malformed' };
1154
+ }
1155
+ }
1156
+ if (!isStrictSafeInt(att.timestamp) || att.timestamp < 0) {
1157
+ return { ok: false, reason: 'Witness attestation timestamp must be a safe integer >= 0' };
1158
+ }
1159
+ if (typeof att.signature !== 'string' || !att.signature.trim() || att.signature === 'unsigned') {
1160
+ return { ok: false, reason: 'Witness attestation signature is missing or unsigned' };
1161
+ }
1162
+ const cleanAttestation = {
1163
+ chainId: att.chainId,
1164
+ height: att.height,
1165
+ checkpointHash: att.checkpointHash,
1166
+ txRoot: att.txRoot,
1167
+ ok: att.ok,
1168
+ witness: att.witness,
1169
+ timestamp: att.timestamp,
1170
+ signature: att.signature
1171
+ };
1172
+ if (typeof att.stateRoot === 'string') {
1173
+ cleanAttestation.stateRoot = att.stateRoot;
1174
+ }
1175
+ if (typeof att.reason === 'string') {
1176
+ cleanAttestation.reason = att.reason;
1177
+ }
1178
+ if (typeof att.witnessPublicKey === 'string') {
1179
+ cleanAttestation.witnessPublicKey = att.witnessPublicKey;
1180
+ }
1181
+ return {
1182
+ ok: true,
1183
+ attestation: cleanAttestation
1184
+ };
1185
+ }
1186
+
1187
+ function computeWitnessAttestationHash(attestation) {
1188
+ const preimage = JSON.stringify({
1189
+ chainId: attestation.chainId,
1190
+ height: attestation.height,
1191
+ checkpointHash: attestation.checkpointHash,
1192
+ txRoot: attestation.txRoot,
1193
+ stateRoot: attestation.stateRoot !== undefined && attestation.stateRoot !== null ? attestation.stateRoot : null,
1194
+ ok: Boolean(attestation.ok),
1195
+ reason: attestation.reason !== undefined && attestation.reason !== null ? attestation.reason : null,
1196
+ witness: attestation.witness,
1197
+ timestamp: attestation.timestamp
1198
+ });
1199
+ const digest = Hasher.SHA2.hash256(Buffer.from(preimage, 'utf8'), 1, 'hex');
1200
+ return digest.startsWith('0x') ? digest : `0x${digest}`;
1201
+ }
1202
+
1203
+ async function verifyWitnessAttestationSignature(attestation, witnessPublicKeyOrVerifier) {
1204
+ const checked = validateWitnessAttestationStructure(attestation);
1205
+ if (!checked.ok) {
1206
+ return false;
1207
+ }
1208
+ const expectedHash = computeWitnessAttestationHash(checked.attestation);
1209
+ const hashBytes = Buffer.from(normalizeHex(expectedHash), 'hex');
1210
+ if (typeof witnessPublicKeyOrVerifier === 'function') {
1211
+ return (await witnessPublicKeyOrVerifier(hashBytes, checked.attestation.signature, checked.attestation.witness)) === true;
1212
+ }
1213
+ return verifyMultiCurveDigestSignature(hashBytes, checked.attestation.signature, witnessPublicKeyOrVerifier, checked.attestation.witness);
1214
+ }
1215
+
1216
+ function buildNormalizedTrustedWitnessMap(trustedWitnesses) {
1217
+ const map = new Map();
1218
+ if (!trustedWitnesses) {
1219
+ return { hasFilter: false, map };
1220
+ }
1221
+ if (Array.isArray(trustedWitnesses)) {
1222
+ for (let i = 0; i < trustedWitnesses.length; i++) {
1223
+ const normalized = normalizeDidForCompare(trustedWitnesses[i]);
1224
+ if (normalized) {
1225
+ map.set(normalized, true);
1226
+ }
1227
+ }
1228
+ return { hasFilter: true, map };
1229
+ }
1230
+ if (typeof trustedWitnesses === 'object') {
1231
+ const entries = Object.entries(trustedWitnesses);
1232
+ for (let i = 0; i < entries.length; i++) {
1233
+ const [did, pk] = entries[i];
1234
+ const normalized = normalizeDidForCompare(did);
1235
+ if (normalized && pk !== undefined && pk !== null) {
1236
+ map.set(normalized, pk);
1237
+ }
1238
+ }
1239
+ return { hasFilter: true, map };
1240
+ }
1241
+ return { hasFilter: false, map };
1242
+ }
1243
+
1244
+ function canonicalizeMultiCurvePublicKey(publicKey) {
1245
+ const decoded = decodeMultiCurvePublicKey(publicKey);
1246
+ if (!decoded) return null;
1247
+ if (decoded.curve === 'ed25519') {
1248
+ return isValidEd25519PublicKey(decoded.bytes) ? decoded : null;
1249
+ }
1250
+ const uncompressed65 = typeof Signer.Secp256k1.toUncompressedPublicKey === 'function' ? Signer.Secp256k1.toUncompressedPublicKey(decoded.bytes) : null;
1251
+ if (!uncompressed65 || uncompressed65.length !== 65) {
1252
+ return null;
1253
+ }
1254
+ return { bytes: Buffer.from(uncompressed65), curve: 'secp256k1' };
1255
+ }
1256
+
1257
+ function resolveVerifiedWitnessKey(att, trustedMap) {
1258
+ const witnessDid = normalizeDidForCompare(att.witness);
1259
+ if (!witnessDid) {
1260
+ return { ok: false, reason: 'Invalid witness DID' };
1261
+ }
1262
+ const entry = trustedMap.get(witnessDid);
1263
+ if (!entry) {
1264
+ return { ok: false, reason: `Untrusted witness: ${att.witness}` };
1265
+ }
1266
+ if (entry !== true) {
1267
+ const pinnedCanonical = canonicalizeMultiCurvePublicKey(entry);
1268
+ if (!pinnedCanonical) {
1269
+ return { ok: false, reason: `Malformed pinned public key for witness ${att.witness}` };
1270
+ }
1271
+ if (att.witnessPublicKey !== undefined) {
1272
+ const attCanonical = canonicalizeMultiCurvePublicKey(att.witnessPublicKey);
1273
+ if (!attCanonical || attCanonical.bytes.toString('hex') !== pinnedCanonical.bytes.toString('hex')) {
1274
+ return { ok: false, reason: `Witness public key mismatch against pinned allowlist for ${att.witness}` };
1275
+ }
1276
+ }
1277
+ return { ok: true, witnessDid, publicKey: pinnedCanonical.bytes };
1278
+ }
1279
+ if (!att.witnessPublicKey || !verifyDidMatchesMultiCurvePublicKey(witnessDid, att.witnessPublicKey)) {
1280
+ return {
1281
+ ok: false,
1282
+ reason: `Witness ${att.witness} requires a matching witnessPublicKey when trustedWitnesses only specifies DIDs`
1283
+ };
1284
+ }
1285
+ const decoded = decodeMultiCurvePublicKey(att.witnessPublicKey);
1286
+ if (!decoded) {
1287
+ return { ok: false, reason: `Invalid witnessPublicKey for ${att.witness}` };
1288
+ }
1289
+ return { ok: true, witnessDid, publicKey: decoded.bytes };
1290
+ }
1291
+
1292
+ async function evaluateWitnessQuorum(checkpoint, attestations, options) {
1293
+ const rawQuorum = options && options.quorum !== undefined ? options.quorum : 0;
1294
+ if (!isStrictSafeInt(rawQuorum) || rawQuorum < 0) {
1295
+ return {
1296
+ finalized: false,
1297
+ validCount: 0,
1298
+ requiredQuorum: 0,
1299
+ circuitBroken: false,
1300
+ fraudAlerts: [],
1301
+ reason: 'Invalid witnessQuorum: must be a non-negative safe integer'
1302
+ };
1303
+ }
1304
+ const quorum = rawQuorum;
1305
+ const { hasFilter, map: trustedMap } = buildNormalizedTrustedWitnessMap(options ? options.trustedWitnesses : undefined);
1306
+
1307
+ if (quorum > 0 && (!hasFilter || trustedMap.size === 0)) {
1308
+ return {
1309
+ finalized: false,
1310
+ validCount: 0,
1311
+ requiredQuorum: quorum,
1312
+ circuitBroken: false,
1313
+ fraudAlerts: [],
1314
+ reason: 'trustedWitnesses allowlist is required when witnessQuorum > 0'
1315
+ };
1316
+ }
1317
+
1318
+ const cpChainId = checkpoint && typeof checkpoint.chainId === 'string' && checkpoint.chainId.trim() ? checkpoint.chainId : undefined;
1319
+ const expectedChainId = (options ? options.expectedChainId : undefined) || cpChainId;
1320
+
1321
+ const validSigners = new Set();
1322
+ const fraudAlertSigners = new Set();
1323
+ const fraudAlerts = [];
1324
+
1325
+ if (hasFilter && trustedMap.size > 0 && Array.isArray(attestations)) {
1326
+ for (let i = 0; i < attestations.length; i++) {
1327
+ const checked = validateWitnessAttestationStructure(attestations[i]);
1328
+ if (!checked.ok) continue;
1329
+ const att = checked.attestation;
1330
+ if (att.height !== checkpoint.height) continue;
1331
+ if (expectedChainId && att.chainId !== expectedChainId) continue;
1332
+
1333
+ const resolvedKey = resolveVerifiedWitnessKey(att, trustedMap);
1334
+ if (!resolvedKey.ok) continue;
1335
+ const sigValid = await verifyWitnessAttestationSignature(att, resolvedKey.publicKey);
1336
+ if (!sigValid) continue;
1337
+
1338
+ if (!att.ok) {
1339
+ if (!fraudAlertSigners.has(resolvedKey.witnessDid)) {
1340
+ fraudAlertSigners.add(resolvedKey.witnessDid);
1341
+ fraudAlerts.push(att);
1342
+ }
1343
+ continue;
1344
+ }
1345
+
1346
+ const attStateRoot = att.stateRoot !== undefined && att.stateRoot !== null ? att.stateRoot : undefined;
1347
+ const cpStateRoot = checkpoint.stateRoot !== undefined && checkpoint.stateRoot !== null ? checkpoint.stateRoot : undefined;
1348
+ if (normalizeHex(att.checkpointHash) === normalizeHex(checkpoint.hash) && normalizeHex(att.txRoot) === normalizeHex(checkpoint.txRoot) && attStateRoot === cpStateRoot) {
1349
+ validSigners.add(resolvedKey.witnessDid);
1350
+ }
1351
+ }
1352
+ }
1353
+
1354
+ if (fraudAlerts.length > 0) {
1355
+ return {
1356
+ finalized: false,
1357
+ validCount: validSigners.size,
1358
+ requiredQuorum: quorum,
1359
+ circuitBroken: true,
1360
+ fraudAlerts,
1361
+ reason: fraudAlerts[0].reason || `Witness circuit breaker triggered by ${fraudAlerts[0].witness}`
1362
+ };
1363
+ }
1364
+
1365
+ if (quorum === 0) {
1366
+ return {
1367
+ finalized: true,
1368
+ validCount: validSigners.size,
1369
+ requiredQuorum: 0,
1370
+ circuitBroken: false,
1371
+ fraudAlerts: []
1372
+ };
1373
+ }
1374
+
1375
+ const finalized = validSigners.size >= quorum;
1376
+ const quorumOut = {
1377
+ finalized,
1378
+ validCount: validSigners.size,
1379
+ requiredQuorum: quorum,
1380
+ circuitBroken: false,
1381
+ fraudAlerts: []
1382
+ };
1383
+ if (!finalized) {
1384
+ quorumOut.reason = `Insufficient witness cosignatures: ${validSigners.size}/${quorum}`;
1385
+ }
1386
+ return quorumOut;
1387
+ }
1388
+
1389
+ function computeAnchorHash(payload) {
1390
+ const data = Buffer.from(JSON.stringify({
1391
+ chainId: payload.chainId,
1392
+ height: payload.height,
1393
+ sequence: payload.sequence,
1394
+ checkpointHash: payload.checkpointHash,
1395
+ stateRoot: payload.stateRoot !== undefined && payload.stateRoot !== null ? payload.stateRoot : null,
1396
+ timestamp: payload.timestamp,
1397
+ proposer: payload.proposer
1398
+ }), 'utf8');
1399
+ return Hasher.SHA2.hash256(data, 1, 'hex');
1400
+ }
1401
+
1402
+ async function verifyAnchorReceipt(receipt, checkpoint, publicKeyOrVerifier) {
1403
+ if (!receipt || typeof receipt !== 'object' || !receipt.payload || typeof receipt.payload !== 'object') {
1404
+ return false;
1405
+ }
1406
+ const p = receipt.payload;
1407
+ if (typeof p.chainId !== 'string' || !p.chainId.trim() || !isStrictSafeInt(p.height) || p.height < 1 || !isStrictSafeInt(p.sequence) || p.sequence < 1 || typeof p.checkpointHash !== 'string' || !/^[0-9a-f]{64}$/.test(normalizeHex(p.checkpointHash)) || !isStrictSafeInt(p.timestamp) || typeof p.proposer !== 'string' || !p.proposer.trim() || typeof receipt.anchorHash !== 'string' || !/^[0-9a-f]{64}$/.test(normalizeHex(receipt.anchorHash))) {
1408
+ return false;
1409
+ }
1410
+
1411
+ const recomputedHash = computeAnchorHash(p);
1412
+ if (normalizeHex(recomputedHash) !== normalizeHex(receipt.anchorHash)) {
1413
+ return false;
1414
+ }
1415
+
1416
+ if (checkpoint) {
1417
+ if (p.height !== checkpoint.height || p.sequence !== checkpoint.sequence || normalizeHex(p.checkpointHash) !== normalizeHex(checkpoint.hash) || normalizeDidForCompare(p.proposer) !== normalizeDidForCompare(checkpoint.proposer)) {
1418
+ return false;
1419
+ }
1420
+ if (p.txRoot !== undefined && normalizeHex(p.txRoot) !== normalizeHex(checkpoint.txRoot)) {
1421
+ return false;
1422
+ }
1423
+ const payloadStateRoot = p.stateRoot !== undefined && p.stateRoot !== null ? p.stateRoot : undefined;
1424
+ const cpStateRoot = checkpoint.stateRoot !== undefined && checkpoint.stateRoot !== null ? checkpoint.stateRoot : undefined;
1425
+ if (payloadStateRoot !== cpStateRoot) {
1426
+ return false;
1427
+ }
1428
+ }
1429
+
1430
+ if (publicKeyOrVerifier) {
1431
+ if (typeof receipt.signature !== 'string' || !receipt.signature.trim() || receipt.signature === 'unsigned') {
1432
+ return false;
1433
+ }
1434
+ const hashBytes = Buffer.from(normalizeHex(receipt.anchorHash), 'hex');
1435
+ const effectiveSignerDid = receipt.anchorSigner || p.proposer;
1436
+ if (typeof publicKeyOrVerifier === 'function') {
1437
+ try {
1438
+ return (await publicKeyOrVerifier(hashBytes, receipt.signature, effectiveSignerDid)) === true;
1439
+ } catch (_err) {
1440
+ return false;
1441
+ }
1442
+ }
1443
+ const signerDidForKeyCheck = receipt.anchorSigner ? receipt.anchorSigner : verifyDidMatchesMultiCurvePublicKey(p.proposer, publicKeyOrVerifier) ? p.proposer : undefined;
1444
+ return verifyMultiCurveDigestSignature(hashBytes, receipt.signature, publicKeyOrVerifier, signerDidForKeyCheck);
1445
+ }
1446
+
1447
+ return true;
1448
+ }
1449
+
1450
+ function detectAnchorConflict(localCheckpoint, externalReceipt) {
1451
+ if (!localCheckpoint || !externalReceipt || !externalReceipt.payload) {
1452
+ return { conflict: false };
1453
+ }
1454
+ if (localCheckpoint.height === externalReceipt.payload.height) {
1455
+ if (normalizeHex(localCheckpoint.hash) !== normalizeHex(externalReceipt.payload.checkpointHash)) {
1456
+ return {
1457
+ conflict: true,
1458
+ reason: `Anchor checkpointHash mismatch at height ${localCheckpoint.height}: local ${localCheckpoint.hash} !== anchored ${externalReceipt.payload.checkpointHash}`
1459
+ };
1460
+ }
1461
+ if (localCheckpoint.sequence !== externalReceipt.payload.sequence) {
1462
+ return {
1463
+ conflict: true,
1464
+ reason: `Anchor sequence mismatch at height ${localCheckpoint.height}: local ${localCheckpoint.sequence} !== anchored ${externalReceipt.payload.sequence}`
1465
+ };
1466
+ }
1467
+ } else if (localCheckpoint.height < externalReceipt.payload.height && localCheckpoint.sequence >= externalReceipt.payload.sequence) {
1468
+ return {
1469
+ conflict: true,
1470
+ reason: `Anchor monotonicity conflict: checkpoint height ${localCheckpoint.height} has sequence ${localCheckpoint.sequence} >= higher anchor height ${externalReceipt.payload.height} (seq ${externalReceipt.payload.sequence})`
1471
+ };
1472
+ } else if (localCheckpoint.height > externalReceipt.payload.height && localCheckpoint.sequence <= externalReceipt.payload.sequence) {
1473
+ return {
1474
+ conflict: true,
1475
+ reason: `Anchor monotonicity conflict: checkpoint height ${localCheckpoint.height} has sequence ${localCheckpoint.sequence} <= lower anchor height ${externalReceipt.payload.height} (seq ${externalReceipt.payload.sequence})`
1476
+ };
1477
+ }
1478
+ return { conflict: false };
1479
+ }
1480
+
420
1481
  /**
421
1482
  * Pure client-side verification of transaction inclusion in a signed Checkpoint (< 1ms, zero network I/O).
422
1483
  *
@@ -445,19 +1506,134 @@ async function verifyTxInclusion(params) {
445
1506
  return { verified: false, reason: 'Missing checkpoint, proof, or entry' };
446
1507
  }
447
1508
 
448
- const { checkpoint, proof, entry, txHash, expectedProposer } = params;
1509
+ const { checkpoint: rawCheckpoint, proof, entry, txHash, expectedProposer, checkpointSigActivationHeight } = params;
1510
+
1511
+ if (!isStrictSafeInt(rawCheckpoint.height) || rawCheckpoint.height < 1) {
1512
+ return {
1513
+ verified: false,
1514
+ reason: 'Invalid checkpoint height: must be a safe integer >= 1'
1515
+ };
1516
+ }
1517
+ if (!isStrictSafeInt(rawCheckpoint.sequence) || !isStrictSafeInt(rawCheckpoint.prevSequence) || !isStrictSafeInt(rawCheckpoint.txCount) || rawCheckpoint.txCount < 1) {
1518
+ return {
1519
+ verified: false,
1520
+ reason: 'Invalid checkpoint sequence/prevSequence/txCount: must be safe integers'
1521
+ };
1522
+ }
1523
+ const normalizedCheckpointTs = normalizeCanonicalCheckpointTimestamp(rawCheckpoint.timestamp);
1524
+ if (normalizedCheckpointTs === null) {
1525
+ return {
1526
+ verified: false,
1527
+ reason: 'Invalid checkpoint timestamp'
1528
+ };
1529
+ }
1530
+ const checkpoint = Object.assign({}, rawCheckpoint, {
1531
+ timestamp: normalizedCheckpointTs
1532
+ });
1533
+
1534
+ let normalizedCheckpointChain;
1535
+ if (params.checkpointChain !== undefined) {
1536
+ if (!Array.isArray(params.checkpointChain)) {
1537
+ return { verified: false, reason: 'Invalid checkpointChain: must be an array of checkpoints' };
1538
+ }
1539
+ if (params.checkpointChain.length > MAX_CHECKPOINT_HASH_CHAIN_LENGTH) {
1540
+ return {
1541
+ verified: false,
1542
+ reason: `Checkpoint hash chain exceeds maximum length (${MAX_CHECKPOINT_HASH_CHAIN_LENGTH})`
1543
+ };
1544
+ }
1545
+ normalizedCheckpointChain = new Array(params.checkpointChain.length);
1546
+ for (let ci = 0; ci < params.checkpointChain.length; ci++) {
1547
+ const chainItem = params.checkpointChain[ci];
1548
+ if (!chainItem || typeof chainItem !== 'object') {
1549
+ return { verified: false, reason: `Invalid checkpoint in checkpointChain at index ${ci}` };
1550
+ }
1551
+ const normalizedChainTs = normalizeCanonicalCheckpointTimestamp(chainItem.timestamp);
1552
+ if (normalizedChainTs === null) {
1553
+ return { verified: false, reason: 'Invalid checkpoint timestamp' };
1554
+ }
1555
+ normalizedCheckpointChain[ci] = Object.assign({}, chainItem, {
1556
+ timestamp: normalizedChainTs
1557
+ });
1558
+ }
1559
+ }
1560
+ if (!isStrictSafeInt(entry.sequence) || entry.sequence < 1) {
1561
+ return {
1562
+ verified: false,
1563
+ reason: 'Invalid entry sequence: must be a safe integer >= 1'
1564
+ };
1565
+ }
1566
+ if (!isStrictSafeInt(proof.index) || proof.index < 0) {
1567
+ return {
1568
+ verified: false,
1569
+ reason: 'Invalid Merkle proof index: must be a safe integer >= 0'
1570
+ };
1571
+ }
1572
+
1573
+ if (checkpointSigActivationHeight !== undefined) {
1574
+ if (!isStrictSafeInt(checkpointSigActivationHeight) || checkpointSigActivationHeight < 1) {
1575
+ return {
1576
+ verified: false,
1577
+ reason: 'Invalid checkpointSigActivationHeight: must be a safe integer >= 1'
1578
+ };
1579
+ }
1580
+ }
1581
+
1582
+ const parsedV2From = parseEntryHashV2From(params.entryHashV2From);
1583
+ if (!parsedV2From.ok) {
1584
+ return { verified: false, reason: parsedV2From.reason };
1585
+ }
1586
+
1587
+ if (params.hotstuffClusterConfig !== undefined) {
1588
+ try {
1589
+ validateClientHotStuffConfig(params.hotstuffClusterConfig);
1590
+ } catch (cfgErr) {
1591
+ return {
1592
+ verified: false,
1593
+ reason: `Invalid hotstuffClusterConfig: ${cfgErr instanceof Error ? cfgErr.message : String(cfgErr)}`
1594
+ };
1595
+ }
1596
+ }
1597
+
1598
+ const isPreActivation = checkpointSigActivationHeight !== undefined && checkpoint.height < checkpointSigActivationHeight;
449
1599
 
450
1600
  // Fail closed (#1133): every check below is structural and a forging RPC can satisfy them all;
451
- // only the checkpoint signature against a trust anchor authenticates the bundle.
1601
+ // only the checkpoint signature (or pinned pre-activation hash chain) authenticates the bundle.
452
1602
  const trustAnchor = resolveTrustAnchor(params);
453
- if (!trustAnchor && params.allowUnauthenticated !== true) {
454
- return { verified: false, reason: NO_TRUST_ANCHOR_REASON };
1603
+ const hasPreActivationHashAnchor = isPreActivation && typeof params.activationCheckpointHash === 'string' && /^[0-9a-f]{64}$/.test(normalizeHex(params.activationCheckpointHash.trim()));
1604
+
1605
+ if (!trustAnchor && !hasPreActivationHashAnchor && params.allowUnauthenticated !== true) {
1606
+ return {
1607
+ verified: false,
1608
+ reason: isPreActivation ? 'Pre-activation checkpoint requires a valid 64-hex activationCheckpointHash' : NO_TRUST_ANCHOR_REASON
1609
+ };
455
1610
  }
456
1611
 
457
1612
  // entry.hash is not covered by entryHash or the Merkle leaf, so bind it to txRaw (#976).
458
1613
  // On by default: this client only talks to OCAP chains, where hash = toTxHash(txRaw).
459
- if (params.verifyTxRawHash !== false && normalizeHex(toTxHash(Buffer.from(String(entry.txRaw || ''), 'base64'))) !== normalizeHex(entry.hash)) {
460
- return { verified: false, reason: `Transaction hash ${entry.hash} does not match entry txRaw` };
1614
+ if (params.verifyTxRawHash !== false) {
1615
+ const txRawBytes = tryCanonicalTxRawBytes(entry.txRaw);
1616
+ if (!txRawBytes || normalizeHex(toTxHash(txRawBytes)) !== normalizeHex(entry.hash)) {
1617
+ return { verified: false, reason: `Transaction hash ${entry.hash} does not match entry txRaw` };
1618
+ }
1619
+ }
1620
+
1621
+ if (params.expectedChainId !== undefined) {
1622
+ if (typeof params.expectedChainId !== 'string' || !params.expectedChainId.trim()) {
1623
+ return { verified: false, reason: 'Invalid expectedChainId: must be a non-empty string' };
1624
+ }
1625
+ if (typeof checkpoint.chainId === 'string' && checkpoint.chainId.trim() && checkpoint.chainId !== params.expectedChainId) {
1626
+ return {
1627
+ verified: false,
1628
+ reason: `Checkpoint chainId mismatch: expected ${params.expectedChainId}, got ${checkpoint.chainId}`
1629
+ };
1630
+ }
1631
+ if (typeof entry.chainId !== 'string' || entry.chainId !== params.expectedChainId) {
1632
+ return {
1633
+ verified: false,
1634
+ reason: `Entry chainId mismatch: expected ${params.expectedChainId}, got ${entry.chainId}`
1635
+ };
1636
+ }
461
1637
  }
462
1638
 
463
1639
  if (txHash && entry.hash !== txHash) {
@@ -467,16 +1643,16 @@ async function verifyTxInclusion(params) {
467
1643
  };
468
1644
  }
469
1645
 
470
- if (expectedProposer && checkpoint.proposer !== expectedProposer) {
1646
+ if (!isPreActivation && expectedProposer && normalizeDidForCompare(checkpoint.proposer) !== normalizeDidForCompare(expectedProposer)) {
471
1647
  return {
472
1648
  verified: false,
473
1649
  reason: `Checkpoint proposer mismatch: expected ${expectedProposer}, got ${checkpoint.proposer}`
474
1650
  };
475
1651
  }
476
1652
 
477
- const seq = Number(entry.sequence);
478
- const prevSeq = Number(checkpoint.prevSequence);
479
- const cpSeq = Number(checkpoint.sequence);
1653
+ const seq = entry.sequence;
1654
+ const prevSeq = checkpoint.prevSequence;
1655
+ const cpSeq = checkpoint.sequence;
480
1656
 
481
1657
  if (seq <= prevSeq || seq > cpSeq) {
482
1658
  return {
@@ -486,7 +1662,7 @@ async function verifyTxInclusion(params) {
486
1662
  }
487
1663
 
488
1664
  const expectedIndex = seq - (prevSeq + 1);
489
- if (Number(proof.index) !== expectedIndex) {
1665
+ if (proof.index !== expectedIndex) {
490
1666
  return {
491
1667
  verified: false,
492
1668
  reason: `Merkle proof index mismatch: expected ${expectedIndex}, got ${proof.index}`
@@ -495,14 +1671,19 @@ async function verifyTxInclusion(params) {
495
1671
 
496
1672
  // v2 (length-prefixed) first, then legacy v1 so proofs from 1.30.26 nodes keep verifying (#1337).
497
1673
  // With params.entryHashV2From the version is exact: seq >= v2From -> v2, below -> v1.
498
- // allowLegacyEntryHash:false (without a pin) refuses v1. v1's boundary ambiguity cannot be
499
- // exploited here because entry.hash == toTxHash(txRaw) (default on) and the Merkle index pin
500
- // txRaw and sequence; pass entryHashV2From if you also disable verifyTxRawHash.
501
1674
  const v2Hash = computeEntryHash(seq, entry.txRaw, entry.stateCommitHash || '');
502
1675
  const v1Hash = computeEntryHashV1(seq, entry.txRaw, entry.stateCommitHash || '');
503
- const pinned = params.entryHashV2From === undefined ? undefined : seq >= Number(params.entryHashV2From) ? 2 : 1;
504
- const legacyAllowed = pinned === 1 || pinned === undefined && params.allowLegacyEntryHash !== false;
1676
+ const pinned = parsedV2From.value === undefined ? undefined : seq >= parsedV2From.value ? 2 : 1;
505
1677
  const givenHash = normalizeHex(entry.entryHash);
1678
+ if (params.allowLegacyEntryHash === false) {
1679
+ if (pinned === 1 || givenHash !== normalizeHex(v2Hash)) {
1680
+ return {
1681
+ verified: false,
1682
+ reason: `Entry hash mismatch: expected ${v2Hash}, got ${entry.entryHash}`
1683
+ };
1684
+ }
1685
+ }
1686
+ const legacyAllowed = pinned === 1 || pinned === undefined && params.allowLegacyEntryHash !== false;
506
1687
  let recomputedEntryHash = v2Hash;
507
1688
  if (pinned !== 2 && legacyAllowed && givenHash !== normalizeHex(v2Hash) && givenHash === normalizeHex(v1Hash)) {
508
1689
  recomputedEntryHash = v1Hash;
@@ -547,14 +1728,156 @@ async function verifyTxInclusion(params) {
547
1728
  };
548
1729
  }
549
1730
 
550
- if (!checkpoint.signature || checkpoint.signature === 'unsigned') {
551
- return { verified: false, reason: 'Checkpoint is unsigned' };
1731
+ let qcChainIdBound = false;
1732
+ if (isPreActivation) {
1733
+ const chainRes = await verifyPreActivationCheckpointChain({
1734
+ checkpoint,
1735
+ checkpointSigActivationHeight,
1736
+ activationCheckpointHash: params.activationCheckpointHash,
1737
+ checkpointChain: normalizedCheckpointChain,
1738
+ trustAnchor,
1739
+ expectedProposer
1740
+ });
1741
+ if (!chainRes.ok) {
1742
+ return { verified: false, reason: chainRes.reason };
1743
+ }
1744
+ if (checkpoint.signature && checkpoint.signature !== 'unsigned' && trustAnchor) {
1745
+ const preSigValid = await verifyCheckpointSignature(checkpoint, trustAnchor);
1746
+ if (!preSigValid) {
1747
+ return { verified: false, reason: 'Invalid checkpoint signature' };
1748
+ }
1749
+ }
1750
+ } else {
1751
+ if (!checkpoint.signature || checkpoint.signature === 'unsigned') {
1752
+ return { verified: false, reason: 'Checkpoint is unsigned' };
1753
+ }
1754
+
1755
+ if (trustAnchor) {
1756
+ const sigValid = await verifyCheckpointSignature(checkpoint, trustAnchor, expectedProposer);
1757
+ if (!sigValid) {
1758
+ return { verified: false, reason: 'Invalid checkpoint signature' };
1759
+ }
1760
+ }
1761
+
1762
+ if (params.hotstuffClusterConfig) {
1763
+ if (params.expectedChainId !== undefined && params.hotstuffClusterConfig.chainId !== params.expectedChainId) {
1764
+ return {
1765
+ verified: false,
1766
+ reason: `HotStuff cluster chainId (${params.hotstuffClusterConfig.chainId}) does not match expectedChainId (${params.expectedChainId})`
1767
+ };
1768
+ }
1769
+ const qcRes = verifyClientCheckpointQuorumCertificate(checkpoint, params.hotstuffClusterConfig);
1770
+ if (!qcRes.ok) {
1771
+ return {
1772
+ verified: false,
1773
+ reason: qcRes.reason || 'Invalid checkpoint HotStuff QuorumCertificate'
1774
+ };
1775
+ }
1776
+ if (params.expectedChainId !== undefined && checkpoint.qc && checkpoint.qc.chainId === params.expectedChainId) {
1777
+ qcChainIdBound = true;
1778
+ }
1779
+ }
1780
+ }
1781
+
1782
+ const effectiveChainId = params.expectedChainId || (typeof entry.chainId === 'string' && entry.chainId.trim() ? entry.chainId : undefined);
1783
+
1784
+ let witnessChainIdBound = false;
1785
+ if (params.witnessQuorum !== undefined) {
1786
+ if (typeof params.witnessQuorum !== 'number' || !Number.isSafeInteger(params.witnessQuorum) || params.witnessQuorum < 0) {
1787
+ return { verified: false, reason: 'Invalid witnessQuorum: must be a non-negative safe integer' };
1788
+ }
1789
+ }
1790
+ if (params.witnessQuorum !== undefined || params.witnessAttestations && params.witnessAttestations.length > 0) {
1791
+ const quorumResult = await evaluateWitnessQuorum(checkpoint, params.witnessAttestations || [], {
1792
+ quorum: params.witnessQuorum !== undefined ? params.witnessQuorum : 0,
1793
+ trustedWitnesses: params.trustedWitnesses,
1794
+ expectedChainId: effectiveChainId
1795
+ });
1796
+ if (!quorumResult.finalized) {
1797
+ return {
1798
+ verified: false,
1799
+ reason: quorumResult.reason || 'Witness cosignature quorum not met'
1800
+ };
1801
+ }
1802
+ if (params.expectedChainId !== undefined && quorumResult.validCount > 0) {
1803
+ witnessChainIdBound = true;
1804
+ }
1805
+ }
1806
+
1807
+ if (params.requireAnchorReceipt === true && !params.anchorReceipt) {
1808
+ return {
1809
+ verified: false,
1810
+ reason: 'Anchor receipt is required when requireAnchorReceipt is true'
1811
+ };
1812
+ }
1813
+
1814
+ let anchorTrustAnchor;
1815
+ if (params.anchorVerifier !== undefined || params.anchorPublicKey !== undefined) {
1816
+ if (params.anchorVerifier === null || params.anchorPublicKey === null) {
1817
+ return { verified: false, reason: 'Invalid anchorPublicKey or anchorVerifier' };
1818
+ }
1819
+ const explicitAnchorTrust = resolveTrustAnchor({
1820
+ verifier: params.anchorVerifier,
1821
+ proposerPublicKey: params.anchorPublicKey
1822
+ });
1823
+ if (!explicitAnchorTrust) {
1824
+ return { verified: false, reason: 'Invalid anchorPublicKey or anchorVerifier' };
1825
+ }
1826
+ anchorTrustAnchor = explicitAnchorTrust;
552
1827
  }
553
1828
 
554
- if (trustAnchor) {
555
- const sigValid = await verifyCheckpointSignature(checkpoint, trustAnchor, expectedProposer);
556
- if (!sigValid) {
557
- return { verified: false, reason: 'Invalid checkpoint signature' };
1829
+ let anchorChainIdBound = false;
1830
+ if (params.anchorReceipt !== undefined && params.anchorReceipt !== null) {
1831
+ if (!anchorTrustAnchor && params.allowUnauthenticated !== true) {
1832
+ return {
1833
+ verified: false,
1834
+ reason: 'Anchor receipt verification requires an explicit anchorPublicKey or anchorVerifier'
1835
+ };
1836
+ }
1837
+ if (effectiveChainId && (!params.anchorReceipt.payload || params.anchorReceipt.payload.chainId !== effectiveChainId)) {
1838
+ return {
1839
+ verified: false,
1840
+ reason: `Anchor receipt chainId mismatch: expected ${effectiveChainId}, got ${params.anchorReceipt.payload ? params.anchorReceipt.payload.chainId : undefined}`
1841
+ };
1842
+ }
1843
+ const anchorOk = await verifyAnchorReceipt(params.anchorReceipt, checkpoint, anchorTrustAnchor);
1844
+ if (!anchorOk) {
1845
+ return {
1846
+ verified: false,
1847
+ reason: 'Invalid or unauthenticated anchor receipt'
1848
+ };
1849
+ }
1850
+ if (params.expectedChainId !== undefined && params.anchorReceipt.payload && params.anchorReceipt.payload.chainId === params.expectedChainId) {
1851
+ anchorChainIdBound = true;
1852
+ }
1853
+ }
1854
+
1855
+ if (params.priorAnchorReceipt !== undefined && params.priorAnchorReceipt !== null) {
1856
+ if (!anchorTrustAnchor && params.allowUnauthenticated !== true) {
1857
+ return {
1858
+ verified: false,
1859
+ reason: 'Prior anchor receipt verification requires an explicit anchorPublicKey or anchorVerifier'
1860
+ };
1861
+ }
1862
+ if (effectiveChainId && (!params.priorAnchorReceipt.payload || params.priorAnchorReceipt.payload.chainId !== effectiveChainId)) {
1863
+ return {
1864
+ verified: false,
1865
+ reason: `Prior anchor receipt chainId mismatch: expected ${effectiveChainId}, got ${params.priorAnchorReceipt.payload ? params.priorAnchorReceipt.payload.chainId : undefined}`
1866
+ };
1867
+ }
1868
+ const priorOk = await verifyAnchorReceipt(params.priorAnchorReceipt, undefined, anchorTrustAnchor);
1869
+ if (!priorOk) {
1870
+ return {
1871
+ verified: false,
1872
+ reason: 'Invalid or unauthenticated priorAnchorReceipt'
1873
+ };
1874
+ }
1875
+ const conflictCheck = detectAnchorConflict(checkpoint, params.priorAnchorReceipt);
1876
+ if (conflictCheck.conflict) {
1877
+ return {
1878
+ verified: false,
1879
+ reason: conflictCheck.reason || 'Checkpoint conflicts with prior anchor receipt'
1880
+ };
558
1881
  }
559
1882
  }
560
1883
 
@@ -567,6 +1890,69 @@ async function verifyTxInclusion(params) {
567
1890
  decodedTx = authFields.decodedTx;
568
1891
  }
569
1892
 
1893
+ if (params.expectedChainId !== undefined) {
1894
+ let txForChainCheck = decodedTx;
1895
+ if (txForChainCheck === undefined && params.verifyDecodedEntry === false) {
1896
+ const probeAuth = authenticateEntryDecodedFields(entry, false);
1897
+ if (!probeAuth.ok) {
1898
+ return { verified: false, reason: probeAuth.reason };
1899
+ }
1900
+ txForChainCheck = probeAuth.decodedTx;
1901
+ }
1902
+
1903
+ let txChainIdBound = false;
1904
+ if (txForChainCheck && txForChainCheck.chainId !== undefined && txForChainCheck.chainId !== null) {
1905
+ if (String(txForChainCheck.chainId) !== params.expectedChainId) {
1906
+ return {
1907
+ verified: false,
1908
+ reason: `Decoded transaction chainId mismatch: expected ${params.expectedChainId}, got ${txForChainCheck.chainId}`
1909
+ };
1910
+ }
1911
+ txChainIdBound = true;
1912
+ } else if (typeof entry.txRaw === 'string' && entry.txRaw.trim().indexOf('{') === 0 && typeof entry.stateCommitHash === 'string' && entry.stateCommitHash.length > 0) {
1913
+ const fromStr = typeof entry.from === 'string' && entry.from ? entry.from : 'did:abt:embedded';
1914
+ const txTypeStr = typeof entry.txType === 'string' && entry.txType ? entry.txType : 'arc.event';
1915
+ const tsNum = entry.timestamp;
1916
+ const candidateNonces = [entry.nonce, txForChainCheck ? txForChainCheck.nonce : undefined, tsNum];
1917
+ for (let ni = 0; ni < candidateNonces.length; ni++) {
1918
+ const nonceCandidate = candidateNonces[ni];
1919
+ if (nonceCandidate === undefined || nonceCandidate === null) continue;
1920
+ const preimage = `${params.expectedChainId}:${fromStr}:${txTypeStr}:${nonceCandidate}:${tsNum}:${entry.txRaw}`;
1921
+ const preimageHash = Hasher.SHA2.hash256(Buffer.from(preimage, 'utf8'), 1, 'hex');
1922
+ if (normalizeHex(preimageHash) === normalizeHex(entry.stateCommitHash)) {
1923
+ txChainIdBound = true;
1924
+ break;
1925
+ }
1926
+ }
1927
+ }
1928
+
1929
+ let segmentChainIdBound = false;
1930
+ if (params.segmentChainIdAuthenticated === true && trustAnchor && typeof checkpoint.segmentContentHash === 'string' && /^[0-9a-f]{64}$/.test(normalizeHex(checkpoint.segmentContentHash)) && typeof checkpoint.segmentCommitmentSignature === 'string' && checkpoint.segmentCommitmentSignature !== 'unsigned') {
1931
+ const commitmentDigestHex = Hasher.SHA2.hash256(Buffer.from(JSON.stringify({
1932
+ checkpointHash: checkpoint.hash,
1933
+ segmentContentHash: checkpoint.segmentContentHash
1934
+ }), 'utf8'), 1, 'hex');
1935
+ const commitmentDigestBytes = Buffer.from(normalizeHex(commitmentDigestHex), 'hex');
1936
+ const effectiveSegProposer = expectedProposer || checkpoint.proposer;
1937
+ if (typeof trustAnchor === 'function') {
1938
+ try {
1939
+ segmentChainIdBound = (await trustAnchor(commitmentDigestBytes, checkpoint.segmentCommitmentSignature, effectiveSegProposer)) === true;
1940
+ } catch (_segErr) {
1941
+ segmentChainIdBound = false;
1942
+ }
1943
+ } else {
1944
+ segmentChainIdBound = verifyMultiCurveDigestSignature(commitmentDigestBytes, checkpoint.segmentCommitmentSignature, trustAnchor, effectiveSegProposer);
1945
+ }
1946
+ }
1947
+
1948
+ if (!txChainIdBound && !witnessChainIdBound && !anchorChainIdBound && !segmentChainIdBound && !qcChainIdBound && params.allowUnauthenticated !== true) {
1949
+ return {
1950
+ verified: false,
1951
+ reason: 'Entry chainId is not cryptographically bound to txRaw, stateCommitHash, witness quorum, or anchor receipt'
1952
+ };
1953
+ }
1954
+ }
1955
+
570
1956
  const res = { verified: true };
571
1957
  if (decodedTx !== undefined) {
572
1958
  Object.defineProperty(res, 'decodedTx', {
@@ -588,8 +1974,23 @@ async function verifyTxInclusion(params) {
588
1974
  module.exports = {
589
1975
  verifyTxInclusion,
590
1976
  verifyCheckpointSignature,
1977
+ verifyDidMatchesMultiCurvePublicKey,
1978
+ verifyMultiCurveDigestSignature,
1979
+ decodeMultiCurvePublicKey,
1980
+ canonicalizeMultiCurvePublicKey,
1981
+ normalizeDidForCompare,
1982
+ parseEntryHashV2From,
591
1983
  computeEntryHash,
592
1984
  computeEntryHashV1,
593
- computeCheckpointHash
1985
+ computeCheckpointHash,
1986
+ normalizeCanonicalCheckpointTimestamp,
1987
+ validateWitnessAttestationStructure,
1988
+ computeWitnessAttestationHash,
1989
+ verifyWitnessAttestationSignature,
1990
+ evaluateWitnessQuorum,
1991
+ computeAnchorHash,
1992
+ verifyAnchorReceipt,
1993
+ detectAnchorConflict,
1994
+ MAX_CHECKPOINT_HASH_CHAIN_LENGTH
594
1995
  };
595
1996
  //# sourceMappingURL=verify.js.map