ox 0.14.36 → 0.14.38

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.
@@ -0,0 +1,809 @@
1
+ import * as Address from '../core/Address.js';
2
+ import * as Errors from '../core/Errors.js';
3
+ import * as Hash from '../core/Hash.js';
4
+ import * as Hex from '../core/Hex.js';
5
+ import * as KeyAuthorization_ from './KeyAuthorization.js';
6
+ import * as MultisigConfig from './MultisigConfig.js';
7
+ import * as SignatureEnvelope from './SignatureEnvelope.js';
8
+ import * as TxEnvelopeTempo from './TxEnvelopeTempo.js';
9
+ /** Maximum supported multisig configuration version. */
10
+ const maxConfigVersion = 2n ** 64n - 1n;
11
+ /**
12
+ * Derives the deterministic hash for a multisig operation.
13
+ *
14
+ * @example
15
+ * ```ts twoslash
16
+ * // @noErrors
17
+ * import { MultisigOperation } from 'ox/tempo'
18
+ *
19
+ * const hash = MultisigOperation.getHash({
20
+ * account,
21
+ * configVersion: 1n,
22
+ * transaction,
23
+ * type: 'transaction',
24
+ * })
25
+ * ```
26
+ *
27
+ * @param options - Operation payload and multisig identity.
28
+ * @returns The operation hash signed by each owner.
29
+ */
30
+ export function getHash(options) {
31
+ const { account, configVersion } = options;
32
+ const payload = options.type === 'transaction'
33
+ ? TxEnvelopeTempo.getSignPayload(TxEnvelopeTempo.deserialize(options.transaction))
34
+ : KeyAuthorization_.getSignPayload(KeyAuthorization_.deserialize(options.keyAuthorization));
35
+ return MultisigConfig.getSignPayload({
36
+ account,
37
+ payload,
38
+ version: configVersion,
39
+ });
40
+ }
41
+ /**
42
+ * Validates, deduplicates, and selects owner approvals for an operation.
43
+ *
44
+ * The function retains one canonical approval per owner. It selects the
45
+ * smallest deterministic quorum by owner weight, then orders the selected
46
+ * approvals by owner address for serialization.
47
+ *
48
+ * @example
49
+ * ```ts twoslash
50
+ * // @noErrors
51
+ * import { MultisigOperation } from 'ox/tempo'
52
+ *
53
+ * const selection = await MultisigOperation.selectApprovals({
54
+ * account,
55
+ * approvals,
56
+ * config,
57
+ * hash,
58
+ * resolveConfig,
59
+ * })
60
+ * ```
61
+ *
62
+ * @param options - Approval selection parameters.
63
+ * @returns The retained approvals and deterministic quorum selection.
64
+ */
65
+ export async function selectApprovals(options) {
66
+ const { account, approvals, hash, resolveConfig } = options;
67
+ if (!Address.validate(account) || Hex.toBigInt(account) === 0n)
68
+ throw new InvalidApprovalError({ reason: 'account is invalid' });
69
+ if (!Hash.validate(hash))
70
+ throw new InvalidApprovalError({ reason: 'hash is invalid' });
71
+ return selectApprovals_internal({
72
+ account,
73
+ approvals,
74
+ config: MultisigConfig.from(options.config),
75
+ hash,
76
+ resolveConfig,
77
+ }, [account.toLowerCase()]);
78
+ }
79
+ /**
80
+ * Serializes a multisig transaction operation with selected owner approvals.
81
+ *
82
+ * @example
83
+ * ```ts twoslash
84
+ * // @noErrors
85
+ * import { MultisigOperation } from 'ox/tempo'
86
+ *
87
+ * const transaction = MultisigOperation.serializeTransaction(operation, {
88
+ * approvals: selection.selectedApprovals,
89
+ * })
90
+ * ```
91
+ *
92
+ * @param operation - Multisig transaction operation.
93
+ * @param options - Transaction serialization options.
94
+ * @returns The signed serialized Tempo transaction.
95
+ */
96
+ export function serializeTransaction(operation, options) {
97
+ const value = from(operation);
98
+ const envelope = TxEnvelopeTempo.deserialize(value.transaction);
99
+ const approvals = options.approvals.map((approval) => SignatureEnvelope.from(approval));
100
+ assertRetainedApprovals(value, approvals);
101
+ const signatures = SignatureEnvelope.sortMultisigApprovals({
102
+ account: value.account,
103
+ payload: TxEnvelopeTempo.getSignPayload(envelope),
104
+ signatures: approvals,
105
+ version: value.configVersion,
106
+ });
107
+ const signature = value.init
108
+ ? SignatureEnvelope.from({
109
+ init: true,
110
+ initialConfig: value.config,
111
+ signatures,
112
+ })
113
+ : SignatureEnvelope.from({
114
+ account: value.account,
115
+ signatures,
116
+ });
117
+ return TxEnvelopeTempo.serialize(envelope, value.transaction.startsWith(TxEnvelopeTempo.feePayerMagic)
118
+ ? {
119
+ format: 'feePayer',
120
+ sender: envelope.from,
121
+ signature,
122
+ }
123
+ : { signature });
124
+ }
125
+ /**
126
+ * Validates and normalizes a multisig operation.
127
+ *
128
+ * @example
129
+ * ```ts twoslash
130
+ * // @noErrors
131
+ * import { MultisigOperation } from 'ox/tempo'
132
+ *
133
+ * const operation = MultisigOperation.from(value)
134
+ * ```
135
+ *
136
+ * @param operation - Multisig operation.
137
+ * @returns The validated operation.
138
+ */
139
+ export function from(operation) {
140
+ try {
141
+ const config = MultisigConfig.from(operation.config);
142
+ if (typeof config.threshold !== 'number' ||
143
+ config.owners.some((owner) => typeof owner.weight !== 'number'))
144
+ throw new InvalidOperationError({
145
+ reason: 'config threshold and owner weights must be numbers',
146
+ });
147
+ assertBase(operation, config);
148
+ if (operation.type === 'transaction')
149
+ assertTransaction(operation);
150
+ else if (operation.type === 'keyAuthorization')
151
+ assertKeyAuthorization(operation, config);
152
+ else
153
+ throw new InvalidOperationError({ reason: 'unknown operation type' });
154
+ return { ...operation, config };
155
+ }
156
+ catch (cause) {
157
+ if (cause instanceof InvalidOperationError)
158
+ throw cause;
159
+ throw new InvalidOperationError({ cause });
160
+ }
161
+ }
162
+ /**
163
+ * Converts a JSON-RPC multisig operation to its domain representation.
164
+ *
165
+ * @example
166
+ * ```ts twoslash
167
+ * // @noErrors
168
+ * import { MultisigOperation } from 'ox/tempo'
169
+ *
170
+ * const operation = MultisigOperation.fromRpc(value)
171
+ * ```
172
+ *
173
+ * @param operation - JSON-RPC multisig operation.
174
+ * @returns The validated operation.
175
+ */
176
+ export function fromRpc(operation) {
177
+ try {
178
+ if (typeof operation.configVersion !== 'string' ||
179
+ !Hex.validate(operation.configVersion))
180
+ throw new InvalidOperationError({
181
+ reason: 'configVersion must be a hexadecimal quantity',
182
+ });
183
+ const configVersion = Hex.toBigInt(operation.configVersion);
184
+ if (Hex.fromNumber(configVersion) !== operation.configVersion)
185
+ throw new InvalidOperationError({
186
+ reason: 'configVersion must use canonical quantity encoding',
187
+ });
188
+ return from({ ...operation, configVersion });
189
+ }
190
+ catch (cause) {
191
+ if (cause instanceof InvalidOperationError)
192
+ throw cause;
193
+ throw new InvalidOperationError({ cause });
194
+ }
195
+ }
196
+ /**
197
+ * Converts a multisig operation to its JSON-RPC representation.
198
+ *
199
+ * @example
200
+ * ```ts twoslash
201
+ * // @noErrors
202
+ * import { MultisigOperation } from 'ox/tempo'
203
+ *
204
+ * const operationRpc = MultisigOperation.toRpc(operation)
205
+ * ```
206
+ *
207
+ * @param operation - Multisig operation.
208
+ * @returns The JSON-RPC operation.
209
+ */
210
+ export function toRpc(operation) {
211
+ const value = from(operation);
212
+ return {
213
+ ...value,
214
+ configVersion: Hex.fromNumber(value.configVersion),
215
+ };
216
+ }
217
+ /**
218
+ * Validates and selects approvals recursively.
219
+ *
220
+ * @internal
221
+ */
222
+ async function selectApprovals_internal(options, path) {
223
+ const owners = new Map(options.config.owners.map((owner) => [
224
+ owner.owner.toLowerCase(),
225
+ { address: owner.owner, weight: Number(owner.weight) },
226
+ ]));
227
+ const groups = new Map();
228
+ for (const serialized of options.approvals) {
229
+ const signature = SignatureEnvelope.from(serialized);
230
+ if (signature.type === 'keychain')
231
+ throw new InvalidApprovalError({
232
+ reason: 'keychain signatures cannot approve a multisig operation',
233
+ });
234
+ const address = signature.type === 'multisig'
235
+ ? signature.account
236
+ : SignatureEnvelope.extractAddress({
237
+ payload: options.hash,
238
+ signature,
239
+ });
240
+ const owner = owners.get(address.toLowerCase());
241
+ if (!owner)
242
+ throw new InvalidApprovalError({
243
+ reason: `signature is from non-owner ${address}`,
244
+ });
245
+ const key = address.toLowerCase();
246
+ const group = groups.get(key);
247
+ if (group)
248
+ group.signatures.push(signature);
249
+ else
250
+ groups.set(key, {
251
+ address: owner.address,
252
+ signatures: [signature],
253
+ weight: owner.weight,
254
+ });
255
+ }
256
+ const valid = [];
257
+ const retained = [];
258
+ for (const group of groups.values()) {
259
+ const nested = group.signatures.filter((signature) => signature.type === 'multisig');
260
+ if (nested.length > 0) {
261
+ if (nested.length !== group.signatures.length)
262
+ throw new InvalidApprovalError({
263
+ reason: `owner ${group.address} has conflicting signature types`,
264
+ });
265
+ if (nested.some((signature) => signature.init))
266
+ throw new InvalidApprovalError({
267
+ reason: `nested multisig owner ${group.address} cannot carry init`,
268
+ });
269
+ if (path.length >= MultisigConfig.maxNestingDepth ||
270
+ path.includes(group.address.toLowerCase()))
271
+ throw new InvalidApprovalError({
272
+ reason: `nested multisig owner ${group.address} is invalid`,
273
+ });
274
+ if (!options.resolveConfig)
275
+ throw new InvalidApprovalError({
276
+ reason: `nested multisig owner ${group.address} requires a config resolver`,
277
+ });
278
+ const resolved = await options.resolveConfig({ account: group.address });
279
+ const selected = await selectApprovals_internal({
280
+ account: group.address,
281
+ approvals: nested.flatMap((signature) => signature.signatures.map((approval) => SignatureEnvelope.serialize(approval))),
282
+ config: MultisigConfig.from(resolved.config),
283
+ hash: MultisigConfig.getSignPayload({
284
+ account: group.address,
285
+ payload: options.hash,
286
+ version: resolved.version,
287
+ }),
288
+ resolveConfig: options.resolveConfig,
289
+ }, [...path, group.address.toLowerCase()]);
290
+ retained.push({
291
+ address: group.address,
292
+ signature: SignatureEnvelope.serialize(SignatureEnvelope.from({
293
+ account: group.address,
294
+ signatures: selected.approvals.map((approval) => SignatureEnvelope.from(approval)),
295
+ })),
296
+ });
297
+ if (selected.weight >= selected.threshold)
298
+ valid.push({
299
+ address: group.address,
300
+ signature: SignatureEnvelope.serialize(SignatureEnvelope.from({
301
+ account: group.address,
302
+ signatures: selected.selectedApprovals.map((approval) => SignatureEnvelope.from(approval)),
303
+ })),
304
+ weight: group.weight,
305
+ });
306
+ continue;
307
+ }
308
+ const signatures = group.signatures.map((signature) => {
309
+ if (!SignatureEnvelope.verify(signature, {
310
+ address: group.address,
311
+ payload: options.hash,
312
+ }))
313
+ throw new InvalidApprovalError({
314
+ reason: `signature from owner ${group.address} is invalid`,
315
+ });
316
+ return SignatureEnvelope.serialize(signature);
317
+ });
318
+ const signature = signatures.sort(compareHex)[0];
319
+ valid.push({
320
+ address: group.address,
321
+ signature,
322
+ weight: group.weight,
323
+ });
324
+ retained.push({ address: group.address, signature });
325
+ }
326
+ const ranked = valid.sort((a, b) => b.weight - a.weight || compareApprovalAddress(a, b));
327
+ const selected = [];
328
+ let weight = 0;
329
+ for (const approval of ranked.slice(0, MultisigConfig.maxSignatures)) {
330
+ if (weight >= Number(options.config.threshold))
331
+ break;
332
+ selected.push(approval);
333
+ weight += approval.weight;
334
+ }
335
+ selected.sort(compareApprovalAddress);
336
+ return {
337
+ approvals: retained
338
+ .sort(compareApprovalAddress)
339
+ .map((approval) => approval.signature),
340
+ selectedApprovals: selected.map((approval) => approval.signature),
341
+ signatureCount: selected.length,
342
+ threshold: Number(options.config.threshold),
343
+ weight,
344
+ };
345
+ }
346
+ /**
347
+ * Orders approval records by owner address.
348
+ *
349
+ * @internal
350
+ */
351
+ function compareApprovalAddress(a, b) {
352
+ const addressA = Hex.toBigInt(a.address);
353
+ const addressB = Hex.toBigInt(b.address);
354
+ return addressA < addressB ? -1 : addressA > addressB ? 1 : 0;
355
+ }
356
+ /**
357
+ * Orders hexadecimal data bytewise.
358
+ *
359
+ * @internal
360
+ */
361
+ function compareHex(a, b) {
362
+ const hexA = a.toLowerCase();
363
+ const hexB = b.toLowerCase();
364
+ return hexA < hexB ? -1 : hexA > hexB ? 1 : 0;
365
+ }
366
+ /**
367
+ * Validates fields shared by every operation.
368
+ *
369
+ * @internal
370
+ */
371
+ function assertBase(operation, config) {
372
+ if (!Address.validate(operation.account))
373
+ throw new InvalidOperationError({ reason: 'account is invalid' });
374
+ if (Hex.toBigInt(operation.account) === 0n)
375
+ throw new InvalidOperationError({ reason: 'account cannot be zero' });
376
+ if (!Hash.validate(operation.hash))
377
+ throw new InvalidOperationError({ reason: 'hash is invalid' });
378
+ if (typeof operation.init !== 'boolean')
379
+ throw new InvalidOperationError({ reason: 'init must be a boolean' });
380
+ if (typeof operation.configVersion !== 'bigint' ||
381
+ operation.configVersion < 0n ||
382
+ operation.configVersion > maxConfigVersion)
383
+ throw new InvalidOperationError({
384
+ reason: 'configVersion must be an unsigned 64-bit integer',
385
+ });
386
+ assertInteger(operation.createdAt, 'createdAt');
387
+ assertInteger(operation.updatedAt, 'updatedAt');
388
+ if (operation.updatedAt < operation.createdAt)
389
+ throw new InvalidOperationError({
390
+ reason: 'updatedAt cannot precede createdAt',
391
+ });
392
+ assertInteger(operation.signatureCount, 'signatureCount');
393
+ assertInteger(operation.threshold, 'threshold');
394
+ assertInteger(operation.weight, 'weight');
395
+ if (operation.threshold !== Number(config.threshold))
396
+ throw new InvalidOperationError({
397
+ reason: 'threshold must equal config.threshold',
398
+ });
399
+ if (operation.weight > 0xff)
400
+ throw new InvalidOperationError({ reason: 'weight exceeds u8 max' });
401
+ if (operation.signatureCount > MultisigConfig.maxSignatures)
402
+ throw new InvalidOperationError({ reason: 'too many selected signatures' });
403
+ if (!Array.isArray(operation.approvals))
404
+ throw new InvalidOperationError({ reason: 'approvals must be an array' });
405
+ if (operation.approvals.length > config.owners.length)
406
+ throw new InvalidOperationError({ reason: 'too many retained approvals' });
407
+ if (operation.signatureCount > operation.approvals.length)
408
+ throw new InvalidOperationError({
409
+ reason: 'signatureCount exceeds retained approvals',
410
+ });
411
+ if ((operation.signatureCount === 0) !== (operation.weight === 0))
412
+ throw new InvalidOperationError({
413
+ reason: 'signatureCount and weight must both be zero or nonzero',
414
+ });
415
+ const owners = new Map(config.owners.map((owner) => [
416
+ owner.owner.toLowerCase(),
417
+ Number(owner.weight),
418
+ ]));
419
+ const approvalWeights = [];
420
+ const seen = new Set();
421
+ for (const approval of operation.approvals) {
422
+ if (typeof approval !== 'string' ||
423
+ !Hex.validate(approval, { strict: true }))
424
+ throw new InvalidOperationError({ reason: 'approval is invalid' });
425
+ const signature = assertApproval(operation.account, approval);
426
+ const address = SignatureEnvelope.extractAddress({
427
+ payload: operation.hash,
428
+ signature,
429
+ });
430
+ const key = address.toLowerCase();
431
+ const weight = owners.get(key);
432
+ if (weight === undefined)
433
+ throw new InvalidOperationError({
434
+ reason: 'approval is from a non-owner',
435
+ });
436
+ if (seen.has(key))
437
+ throw new InvalidOperationError({
438
+ reason: operation.type === 'keyAuthorization'
439
+ ? 'key authorization contains duplicate owner approvals'
440
+ : 'duplicate owner approval',
441
+ });
442
+ seen.add(key);
443
+ approvalWeights.push(weight);
444
+ }
445
+ if (!isWeightReachable(approvalWeights, operation.signatureCount, operation.weight))
446
+ throw new InvalidOperationError({
447
+ reason: 'weight is not reachable by signatureCount retained owner approvals',
448
+ });
449
+ if (operation.init) {
450
+ if (operation.configVersion !== 0n)
451
+ throw new InvalidOperationError({
452
+ reason: 'bootstrap operations must use config version zero',
453
+ });
454
+ if (MultisigConfig.getAddress(config).toLowerCase() !==
455
+ operation.account.toLowerCase())
456
+ throw new InvalidOperationError({
457
+ reason: 'bootstrap config does not derive the operation account',
458
+ });
459
+ }
460
+ }
461
+ /**
462
+ * Validates a transaction operation and its state-specific fields.
463
+ *
464
+ * @internal
465
+ */
466
+ function assertTransaction(operation) {
467
+ if ('keyAuthorization' in operation &&
468
+ operation.keyAuthorization !== undefined)
469
+ throw new InvalidOperationError({
470
+ reason: 'transaction operations cannot contain keyAuthorization',
471
+ });
472
+ const expiresAt = operation.expiresAt;
473
+ const submissionId = operation.submissionId;
474
+ const transactionHash = operation.transactionHash;
475
+ if (operation.status === 'pending') {
476
+ if (expiresAt !== undefined ||
477
+ submissionId !== undefined ||
478
+ transactionHash !== undefined)
479
+ throw new InvalidOperationError({
480
+ reason: 'pending transactions cannot contain submission fields',
481
+ });
482
+ }
483
+ else if (operation.status === 'submitting') {
484
+ assertInteger(expiresAt, 'expiresAt');
485
+ if (!Hash.validate(submissionId ?? ''))
486
+ throw new InvalidOperationError({ reason: 'submissionId is invalid' });
487
+ if (submissionId.toLowerCase() === operation.hash.toLowerCase())
488
+ throw new InvalidOperationError({
489
+ reason: 'submissionId must differ from the operation hash',
490
+ });
491
+ if (transactionHash !== undefined)
492
+ throw new InvalidOperationError({
493
+ reason: 'submitting transactions cannot contain transactionHash',
494
+ });
495
+ }
496
+ else if (operation.status === 'success') {
497
+ if (!Hash.validate(transactionHash ?? ''))
498
+ throw new InvalidOperationError({ reason: 'transactionHash is invalid' });
499
+ if (expiresAt !== undefined || submissionId !== undefined)
500
+ throw new InvalidOperationError({
501
+ reason: 'successful transactions cannot contain submission fields',
502
+ });
503
+ }
504
+ else
505
+ throw new InvalidOperationError({ reason: 'invalid transaction status' });
506
+ if (operation.status !== 'pending' &&
507
+ (operation.weight < operation.threshold || operation.signatureCount === 0))
508
+ throw new InvalidOperationError({
509
+ reason: 'submitted transactions must have quorum',
510
+ });
511
+ if (typeof operation.transaction !== 'string')
512
+ throw new InvalidOperationError({ reason: 'transaction is invalid' });
513
+ const transaction = TxEnvelopeTempo.deserialize(operation.transaction);
514
+ if (transaction.signature)
515
+ throw new InvalidOperationError({
516
+ reason: 'transaction must not contain an outer sender signature',
517
+ });
518
+ if (transaction.from &&
519
+ transaction.from.toLowerCase() !== operation.account.toLowerCase())
520
+ throw new InvalidOperationError({
521
+ reason: 'transaction sender does not match the operation account',
522
+ });
523
+ assertOperationHash(operation, TxEnvelopeTempo.getSignPayload(transaction));
524
+ const feePayer = operation.transaction.startsWith(TxEnvelopeTempo.feePayerMagic);
525
+ const serialized = TxEnvelopeTempo.serialize(transaction, feePayer
526
+ ? transaction.from
527
+ ? { format: 'feePayer', sender: transaction.from }
528
+ : { format: 'feePayer' }
529
+ : {});
530
+ if (serialized.toLowerCase() !== operation.transaction.toLowerCase())
531
+ throw new InvalidOperationError({
532
+ reason: 'transaction is not canonically serialized',
533
+ });
534
+ }
535
+ /**
536
+ * Validates a key authorization operation and its serialized payload.
537
+ *
538
+ * @internal
539
+ */
540
+ function assertKeyAuthorization(operation, config) {
541
+ const transactionFields = operation;
542
+ if (transactionFields.expiresAt !== undefined ||
543
+ transactionFields.submissionId !== undefined ||
544
+ transactionFields.transaction !== undefined ||
545
+ transactionFields.transactionHash !== undefined)
546
+ throw new InvalidOperationError({
547
+ reason: 'key authorization operations cannot contain transaction fields',
548
+ });
549
+ if (operation.status !== 'pending' && operation.status !== 'success')
550
+ throw new InvalidOperationError({
551
+ reason: 'invalid key authorization status',
552
+ });
553
+ if (operation.status === 'success' &&
554
+ (operation.weight < operation.threshold || operation.signatureCount === 0))
555
+ throw new InvalidOperationError({
556
+ reason: 'successful key authorizations must have quorum',
557
+ });
558
+ if (operation.status === 'pending' && operation.weight >= operation.threshold)
559
+ throw new InvalidOperationError({
560
+ reason: 'pending key authorizations cannot have quorum',
561
+ });
562
+ if (typeof operation.keyAuthorization !== 'string')
563
+ throw new InvalidOperationError({ reason: 'keyAuthorization is invalid' });
564
+ const authorization = KeyAuthorization_.deserialize(operation.keyAuthorization);
565
+ if (!authorization.account ||
566
+ authorization.account.toLowerCase() !== operation.account.toLowerCase())
567
+ throw new InvalidOperationError({
568
+ reason: 'key authorization account does not match the operation account',
569
+ });
570
+ const signature = authorization.signature;
571
+ if (operation.status === 'pending' && signature)
572
+ throw new InvalidOperationError({
573
+ reason: 'pending key authorizations must be unsigned',
574
+ });
575
+ if (operation.status === 'success') {
576
+ if (signature?.type !== 'multisig')
577
+ throw new InvalidOperationError({
578
+ reason: 'successful key authorizations require a multisig signature',
579
+ });
580
+ if (signature.account.toLowerCase() !== operation.account.toLowerCase())
581
+ throw new InvalidOperationError({
582
+ reason: 'key authorization signature account does not match',
583
+ });
584
+ if (signature.signatures.length !== operation.signatureCount)
585
+ throw new InvalidOperationError({
586
+ reason: 'key authorization signatureCount does not match its signature',
587
+ });
588
+ assertSelectedApprovals(operation, signature.signatures, authorization);
589
+ if (!!signature.init !== operation.init)
590
+ throw new InvalidOperationError({
591
+ reason: 'key authorization bootstrap state does not match',
592
+ });
593
+ if (signature.init && !sameConfig(signature.init, config))
594
+ throw new InvalidOperationError({
595
+ reason: 'key authorization bootstrap config does not match',
596
+ });
597
+ }
598
+ assertOperationHash(operation, KeyAuthorization_.getSignPayload(authorization));
599
+ if (KeyAuthorization_.serialize(authorization).toLowerCase() !==
600
+ operation.keyAuthorization.toLowerCase())
601
+ throw new InvalidOperationError({
602
+ reason: 'keyAuthorization is not canonically serialized',
603
+ });
604
+ }
605
+ /**
606
+ * Validates a retained signature in the root owner's approval context.
607
+ *
608
+ * @internal
609
+ */
610
+ function assertApproval(account, serialized) {
611
+ const approval = SignatureEnvelope.deserialize(serialized);
612
+ SignatureEnvelope.assert({
613
+ account,
614
+ signatures: [approval],
615
+ type: 'multisig',
616
+ });
617
+ if (SignatureEnvelope.serialize(approval).toLowerCase() !==
618
+ serialized.toLowerCase())
619
+ throw new InvalidOperationError({ reason: 'approval is not canonical' });
620
+ return approval;
621
+ }
622
+ /**
623
+ * Checks that selected transaction approvals are retained by the operation.
624
+ *
625
+ * @internal
626
+ */
627
+ function assertRetainedApprovals(operation, selected) {
628
+ const retained = operation.approvals.map((approval) => SignatureEnvelope.deserialize(approval));
629
+ for (const approval of selected) {
630
+ const index = retained.findIndex((candidate) => includesApproval(candidate, approval));
631
+ if (index === -1)
632
+ throw new InvalidOperationError({
633
+ reason: 'transaction signature is not a retained approval',
634
+ });
635
+ retained.splice(index, 1);
636
+ }
637
+ }
638
+ /**
639
+ * Checks that a successful key authorization uses retained approvals in canonical order.
640
+ *
641
+ * @internal
642
+ */
643
+ function assertSelectedApprovals(operation, selected, authorization) {
644
+ const retained = operation.approvals.map((approval) => SignatureEnvelope.deserialize(approval));
645
+ for (const approval of selected) {
646
+ const index = retained.findIndex((candidate) => includesApproval(candidate, approval));
647
+ if (index === -1)
648
+ throw new InvalidOperationError({
649
+ reason: 'key authorization signature is not a retained approval',
650
+ });
651
+ retained.splice(index, 1);
652
+ }
653
+ const digest = MultisigConfig.getSignPayload({
654
+ account: operation.account,
655
+ payload: KeyAuthorization_.getSignPayload(authorization),
656
+ version: operation.configVersion,
657
+ });
658
+ const addresses = selected.map((signature) => SignatureEnvelope.extractAddress({ payload: digest, signature }));
659
+ for (let index = 1; index < addresses.length; index++) {
660
+ const previous = Hex.toBigInt(addresses[index - 1]);
661
+ const current = Hex.toBigInt(addresses[index]);
662
+ if (previous === current)
663
+ throw new InvalidOperationError({
664
+ reason: 'key authorization contains duplicate owner approvals',
665
+ });
666
+ if (previous > current)
667
+ throw new InvalidOperationError({
668
+ reason: 'key authorization approvals are not canonically ordered',
669
+ });
670
+ }
671
+ }
672
+ /**
673
+ * Checks whether a selected approval is contained in a retained approval tree.
674
+ *
675
+ * @internal
676
+ */
677
+ function includesApproval(retained, selected) {
678
+ if (retained.type !== 'multisig' || selected.type !== 'multisig')
679
+ return (SignatureEnvelope.serialize(retained).toLowerCase() ===
680
+ SignatureEnvelope.serialize(selected).toLowerCase());
681
+ if (retained.account.toLowerCase() !== selected.account.toLowerCase())
682
+ return false;
683
+ // Nested versions are not serialized, so selected child approvals must preserve the validated retained order.
684
+ let index = 0;
685
+ for (const approval of selected.signatures) {
686
+ while (index < retained.signatures.length &&
687
+ !includesApproval(retained.signatures[index], approval))
688
+ index++;
689
+ if (index === retained.signatures.length)
690
+ return false;
691
+ index++;
692
+ }
693
+ return true;
694
+ }
695
+ /**
696
+ * Checks whether exactly `signatureCount` retained owners can produce `weight`.
697
+ *
698
+ * @internal
699
+ */
700
+ function isWeightReachable(weights, signatureCount, weight) {
701
+ const reachable = Array.from({ length: signatureCount + 1 }, () => new Set());
702
+ reachable[0].add(0);
703
+ for (const ownerWeight of weights)
704
+ for (let count = signatureCount; count > 0; count--)
705
+ for (const current of reachable[count - 1])
706
+ reachable[count].add(current + ownerWeight);
707
+ return reachable[signatureCount].has(weight);
708
+ }
709
+ /**
710
+ * Validates the deterministic operation hash.
711
+ *
712
+ * @internal
713
+ */
714
+ function assertOperationHash(operation, payload) {
715
+ const hash = MultisigConfig.getSignPayload({
716
+ account: operation.account,
717
+ payload,
718
+ version: operation.configVersion,
719
+ });
720
+ if (hash.toLowerCase() !== operation.hash.toLowerCase())
721
+ throw new InvalidOperationError({
722
+ reason: 'hash does not match the operation payload',
723
+ });
724
+ }
725
+ /**
726
+ * Validates a nonnegative safe integer field.
727
+ *
728
+ * @internal
729
+ */
730
+ function assertInteger(value, field) {
731
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0)
732
+ throw new InvalidOperationError({
733
+ reason: `${field} must be a nonnegative safe integer`,
734
+ });
735
+ }
736
+ /**
737
+ * Compares normalized multisig configurations.
738
+ *
739
+ * @internal
740
+ */
741
+ function sameConfig(a, b) {
742
+ const configA = MultisigConfig.from(a);
743
+ const configB = MultisigConfig.from(b);
744
+ return (Hex.isEqual(configA.salt ?? MultisigConfig.zeroSalt, configB.salt ?? MultisigConfig.zeroSalt) &&
745
+ configA.threshold === configB.threshold &&
746
+ configA.owners.length === configB.owners.length &&
747
+ configA.owners.every((owner, index) => {
748
+ const other = configB.owners[index];
749
+ return (Address.isEqual(owner.owner, other.owner) &&
750
+ owner.weight === other.weight);
751
+ }));
752
+ }
753
+ /** Thrown when a multisig owner approval is invalid. */
754
+ export class InvalidApprovalError extends Errors.BaseError {
755
+ /**
756
+ * Creates an invalid multisig approval error.
757
+ *
758
+ * @example
759
+ * ```ts twoslash
760
+ * import { MultisigOperation } from 'ox/tempo'
761
+ *
762
+ * throw new MultisigOperation.InvalidApprovalError({
763
+ * reason: 'signature is from a non-owner',
764
+ * })
765
+ * ```
766
+ *
767
+ * @param options - Error options.
768
+ */
769
+ constructor(options = {}) {
770
+ super(options.reason
771
+ ? `Invalid multisig approval: ${options.reason}.`
772
+ : 'Invalid multisig approval.', { cause: options.cause });
773
+ Object.defineProperty(this, "name", {
774
+ enumerable: true,
775
+ configurable: true,
776
+ writable: true,
777
+ value: 'MultisigOperation.InvalidApprovalError'
778
+ });
779
+ }
780
+ }
781
+ /** Thrown when a multisig operation is malformed or internally inconsistent. */
782
+ export class InvalidOperationError extends Errors.BaseError {
783
+ /**
784
+ * Creates an invalid multisig operation error.
785
+ *
786
+ * @example
787
+ * ```ts twoslash
788
+ * import { MultisigOperation } from 'ox/tempo'
789
+ *
790
+ * throw new MultisigOperation.InvalidOperationError({
791
+ * reason: 'hash does not match the operation payload',
792
+ * })
793
+ * ```
794
+ *
795
+ * @param options - Error options.
796
+ */
797
+ constructor(options = {}) {
798
+ super(options.reason
799
+ ? `Invalid multisig operation: ${options.reason}.`
800
+ : 'Invalid multisig operation.', { cause: options.cause });
801
+ Object.defineProperty(this, "name", {
802
+ enumerable: true,
803
+ configurable: true,
804
+ writable: true,
805
+ value: 'MultisigOperation.InvalidOperationError'
806
+ });
807
+ }
808
+ }
809
+ //# sourceMappingURL=MultisigOperation.js.map