@ocap/client 1.31.9 → 1.32.1

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