@did-btcr2/method 0.36.1 → 0.37.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/.tsbuildinfo +1 -1
- package/dist/browser.js +1060 -96
- package/dist/browser.mjs +1060 -96
- package/dist/cjs/index.js +1153 -179
- package/dist/esm/core/aggregation/beacon-strategy.js +19 -6
- package/dist/esm/core/aggregation/beacon-strategy.js.map +1 -1
- package/dist/esm/core/aggregation/cohort.js +142 -33
- package/dist/esm/core/aggregation/cohort.js.map +1 -1
- package/dist/esm/core/aggregation/conditions.js +27 -0
- package/dist/esm/core/aggregation/conditions.js.map +1 -1
- package/dist/esm/core/aggregation/fallback-spend.js +132 -0
- package/dist/esm/core/aggregation/fallback-spend.js.map +1 -0
- package/dist/esm/core/aggregation/messages/base.js.map +1 -1
- package/dist/esm/core/aggregation/messages/bodies.js +46 -1
- package/dist/esm/core/aggregation/messages/bodies.js.map +1 -1
- package/dist/esm/core/aggregation/messages/constants.js +11 -0
- package/dist/esm/core/aggregation/messages/constants.js.map +1 -1
- package/dist/esm/core/aggregation/messages/factories.js +27 -1
- package/dist/esm/core/aggregation/messages/factories.js.map +1 -1
- package/dist/esm/core/aggregation/messages/guards.js +4 -1
- package/dist/esm/core/aggregation/messages/guards.js.map +1 -1
- package/dist/esm/core/aggregation/participant.js +210 -21
- package/dist/esm/core/aggregation/participant.js.map +1 -1
- package/dist/esm/core/aggregation/phases.js +6 -0
- package/dist/esm/core/aggregation/phases.js.map +1 -1
- package/dist/esm/core/aggregation/recovery-policy.js +156 -0
- package/dist/esm/core/aggregation/recovery-policy.js.map +1 -0
- package/dist/esm/core/aggregation/recovery-spend.js +106 -0
- package/dist/esm/core/aggregation/recovery-spend.js.map +1 -0
- package/dist/esm/core/aggregation/runner/aggregation-runner.js +11 -3
- package/dist/esm/core/aggregation/runner/aggregation-runner.js.map +1 -1
- package/dist/esm/core/aggregation/runner/participant-runner.js +74 -22
- package/dist/esm/core/aggregation/runner/participant-runner.js.map +1 -1
- package/dist/esm/core/aggregation/runner/service-runner.js +97 -9
- package/dist/esm/core/aggregation/runner/service-runner.js.map +1 -1
- package/dist/esm/core/aggregation/service.js +221 -11
- package/dist/esm/core/aggregation/service.js.map +1 -1
- package/dist/esm/core/aggregation/signing-session.js +3 -3
- package/dist/esm/core/aggregation/signing-session.js.map +1 -1
- package/dist/esm/core/aggregation/transport/http/envelope.js +3 -3
- package/dist/esm/core/aggregation/transport/http/inbox-buffer.js +1 -1
- package/dist/esm/core/aggregation/transport/http/nonce-cache.js +1 -1
- package/dist/esm/core/aggregation/transport/http/rate-limiter.js +1 -1
- package/dist/esm/core/aggregation/transport/http/request-auth.js +1 -1
- package/dist/esm/core/aggregation/transport/http/server.js +1 -1
- package/dist/esm/core/aggregation/transport/http/sse-stream.js +1 -1
- package/dist/esm/core/aggregation/transport/http/sse-writer.js +1 -1
- package/dist/esm/core/aggregation/transport/in-memory.js +1 -1
- package/dist/esm/core/aggregation/transport/nostr.js +6 -6
- package/dist/esm/core/beacon/beacon.js +15 -10
- package/dist/esm/core/beacon/beacon.js.map +1 -1
- package/dist/esm/core/beacon/cas-beacon.js +6 -6
- package/dist/esm/core/beacon/cas-beacon.js.map +1 -1
- package/dist/esm/core/beacon/singleton-beacon.js +2 -2
- package/dist/esm/core/beacon/singleton-beacon.js.map +1 -1
- package/dist/esm/core/beacon/smt-beacon.js +3 -3
- package/dist/esm/core/beacon/smt-beacon.js.map +1 -1
- package/dist/esm/core/resolver.js +8 -8
- package/dist/esm/core/resolver.js.map +1 -1
- package/dist/esm/core/updater.js +6 -6
- package/dist/esm/core/updater.js.map +1 -1
- package/dist/esm/did-btcr2.js +2 -2
- package/dist/esm/index.js +3 -0
- package/dist/esm/index.js.map +1 -1
- package/dist/types/core/aggregation/beacon-strategy.d.ts +8 -4
- package/dist/types/core/aggregation/beacon-strategy.d.ts.map +1 -1
- package/dist/types/core/aggregation/cohort.d.ts +88 -17
- package/dist/types/core/aggregation/cohort.d.ts.map +1 -1
- package/dist/types/core/aggregation/conditions.d.ts +28 -0
- package/dist/types/core/aggregation/conditions.d.ts.map +1 -1
- package/dist/types/core/aggregation/fallback-spend.d.ts +94 -0
- package/dist/types/core/aggregation/fallback-spend.d.ts.map +1 -0
- package/dist/types/core/aggregation/logger.d.ts +1 -1
- package/dist/types/core/aggregation/messages/base.d.ts +6 -0
- package/dist/types/core/aggregation/messages/base.d.ts.map +1 -1
- package/dist/types/core/aggregation/messages/bodies.d.ts +50 -2
- package/dist/types/core/aggregation/messages/bodies.d.ts.map +1 -1
- package/dist/types/core/aggregation/messages/constants.d.ts +8 -0
- package/dist/types/core/aggregation/messages/constants.d.ts.map +1 -1
- package/dist/types/core/aggregation/messages/factories.d.ts +40 -0
- package/dist/types/core/aggregation/messages/factories.d.ts.map +1 -1
- package/dist/types/core/aggregation/messages/guards.d.ts.map +1 -1
- package/dist/types/core/aggregation/participant.d.ts +41 -7
- package/dist/types/core/aggregation/participant.d.ts.map +1 -1
- package/dist/types/core/aggregation/phases.d.ts +8 -2
- package/dist/types/core/aggregation/phases.d.ts.map +1 -1
- package/dist/types/core/aggregation/recovery-policy.d.ts +132 -0
- package/dist/types/core/aggregation/recovery-policy.d.ts.map +1 -0
- package/dist/types/core/aggregation/recovery-spend.d.ts +94 -0
- package/dist/types/core/aggregation/recovery-spend.d.ts.map +1 -0
- package/dist/types/core/aggregation/runner/aggregation-runner.d.ts +13 -3
- package/dist/types/core/aggregation/runner/aggregation-runner.d.ts.map +1 -1
- package/dist/types/core/aggregation/runner/events.d.ts +28 -7
- package/dist/types/core/aggregation/runner/events.d.ts.map +1 -1
- package/dist/types/core/aggregation/runner/participant-runner.d.ts +3 -3
- package/dist/types/core/aggregation/runner/participant-runner.d.ts.map +1 -1
- package/dist/types/core/aggregation/runner/service-runner.d.ts +28 -3
- package/dist/types/core/aggregation/runner/service-runner.d.ts.map +1 -1
- package/dist/types/core/aggregation/service.d.ts +26 -2
- package/dist/types/core/aggregation/service.d.ts.map +1 -1
- package/dist/types/core/aggregation/signing-session.d.ts +2 -2
- package/dist/types/core/aggregation/signing-session.d.ts.map +1 -1
- package/dist/types/core/aggregation/transport/http/envelope.d.ts +3 -3
- package/dist/types/core/aggregation/transport/http/inbox-buffer.d.ts +1 -1
- package/dist/types/core/aggregation/transport/http/nonce-cache.d.ts +1 -1
- package/dist/types/core/aggregation/transport/http/rate-limiter.d.ts +1 -1
- package/dist/types/core/aggregation/transport/http/request-auth.d.ts +1 -1
- package/dist/types/core/aggregation/transport/http/server.d.ts +1 -1
- package/dist/types/core/aggregation/transport/http/sse-stream.d.ts +2 -2
- package/dist/types/core/aggregation/transport/http/sse-writer.d.ts +1 -1
- package/dist/types/core/aggregation/transport/in-memory.d.ts +1 -1
- package/dist/types/core/aggregation/transport/nostr.d.ts +4 -4
- package/dist/types/core/aggregation/transport/transport.d.ts +4 -4
- package/dist/types/core/aggregation/transport/transport.d.ts.map +1 -1
- package/dist/types/core/beacon/beacon.d.ts +7 -7
- package/dist/types/core/beacon/beacon.d.ts.map +1 -1
- package/dist/types/core/beacon/cas-beacon.d.ts +2 -2
- package/dist/types/core/beacon/interfaces.d.ts +1 -1
- package/dist/types/core/resolver.d.ts +3 -3
- package/dist/types/core/updater.d.ts +4 -4
- package/dist/types/did-btcr2.d.ts +2 -2
- package/dist/types/index.d.ts +3 -0
- package/dist/types/index.d.ts.map +1 -1
- package/package.json +4 -4
- package/src/core/aggregation/beacon-strategy.ts +27 -9
- package/src/core/aggregation/cohort.ts +171 -35
- package/src/core/aggregation/conditions.ts +56 -0
- package/src/core/aggregation/fallback-spend.ts +223 -0
- package/src/core/aggregation/logger.ts +1 -1
- package/src/core/aggregation/messages/base.ts +6 -0
- package/src/core/aggregation/messages/bodies.ts +94 -1
- package/src/core/aggregation/messages/constants.ts +12 -0
- package/src/core/aggregation/messages/factories.ts +57 -0
- package/src/core/aggregation/messages/guards.ts +6 -0
- package/src/core/aggregation/participant.ts +255 -23
- package/src/core/aggregation/phases.ts +9 -0
- package/src/core/aggregation/recovery-policy.ts +237 -0
- package/src/core/aggregation/recovery-spend.ts +192 -0
- package/src/core/aggregation/runner/aggregation-runner.ts +27 -5
- package/src/core/aggregation/runner/events.ts +26 -7
- package/src/core/aggregation/runner/participant-runner.ts +75 -23
- package/src/core/aggregation/runner/service-runner.ts +120 -10
- package/src/core/aggregation/service.ts +260 -14
- package/src/core/aggregation/signing-session.ts +3 -3
- package/src/core/aggregation/transport/http/envelope.ts +3 -3
- package/src/core/aggregation/transport/http/inbox-buffer.ts +1 -1
- package/src/core/aggregation/transport/http/nonce-cache.ts +1 -1
- package/src/core/aggregation/transport/http/rate-limiter.ts +1 -1
- package/src/core/aggregation/transport/http/request-auth.ts +1 -1
- package/src/core/aggregation/transport/http/server.ts +1 -1
- package/src/core/aggregation/transport/http/sse-stream.ts +2 -2
- package/src/core/aggregation/transport/http/sse-writer.ts +1 -1
- package/src/core/aggregation/transport/in-memory.ts +1 -1
- package/src/core/aggregation/transport/nostr.ts +6 -6
- package/src/core/aggregation/transport/transport.ts +4 -4
- package/src/core/beacon/beacon.ts +16 -11
- package/src/core/beacon/cas-beacon.ts +7 -7
- package/src/core/beacon/interfaces.ts +1 -1
- package/src/core/beacon/singleton-beacon.ts +2 -2
- package/src/core/beacon/smt-beacon.ts +3 -3
- package/src/core/resolver.ts +8 -8
- package/src/core/updater.ts +6 -6
- package/src/did-btcr2.ts +2 -2
- package/src/index.ts +3 -0
|
@@ -4,11 +4,13 @@ import type { SignedBTCR2Update } from '@did-btcr2/cryptosuite';
|
|
|
4
4
|
import type { SerializedSMTProof, TreeEntry } from '@did-btcr2/smt';
|
|
5
5
|
import { BTCR2MerkleTree } from '@did-btcr2/smt';
|
|
6
6
|
import { schnorr } from '@noble/curves/secp256k1.js';
|
|
7
|
-
import { hexToBytes, randomBytes } from '@noble/hashes/utils';
|
|
7
|
+
import { concatBytes, hexToBytes, randomBytes } from '@noble/hashes/utils';
|
|
8
8
|
import { p2tr } from '@scure/btc-signer';
|
|
9
9
|
import { keyAggExport, keyAggregate, sortKeys } from '@scure/btc-signer/musig2';
|
|
10
10
|
import type { CASAnnouncement } from '../types.js';
|
|
11
11
|
import { AggregationCohortError } from './errors.js';
|
|
12
|
+
import type { FundingModel } from './recovery-policy.js';
|
|
13
|
+
import { DEFAULT_FUNDING_MODEL, buildRecoveryLeaves, resolveFallbackThreshold } from './recovery-policy.js';
|
|
12
14
|
|
|
13
15
|
export type AggregationCohortParams = {
|
|
14
16
|
id?: string;
|
|
@@ -16,14 +18,22 @@ export type AggregationCohortParams = {
|
|
|
16
18
|
minParticipants?: number;
|
|
17
19
|
network: string;
|
|
18
20
|
beaconType?: string;
|
|
21
|
+
/** Operator recovery key, x-only (32 bytes). Required to compute the beacon address. */
|
|
22
|
+
recoveryKey?: Uint8Array;
|
|
23
|
+
/** Relative-timelock (BIP-68 nSequence) before recovery is spendable. Required to compute the beacon address. */
|
|
24
|
+
recoverySequence?: number;
|
|
25
|
+
/** Funding model governing the recovery leaves. Defaults to 'operator-funded'. */
|
|
26
|
+
fundingModel?: FundingModel;
|
|
27
|
+
/** Advertised k of the k-of-n fallback leaf. Absent defaults to n-1 at address computation. */
|
|
28
|
+
fallbackThreshold?: number;
|
|
19
29
|
};
|
|
20
30
|
|
|
21
31
|
/**
|
|
22
|
-
* Represents an Aggregation Cohort
|
|
32
|
+
* Represents an Aggregation Cohort: a set of Aggregation Participants who
|
|
23
33
|
* submitted cryptographic material to an Aggregation Service to coordinate
|
|
24
34
|
* signing of a shared n-of-n MuSig2 Bitcoin transaction.
|
|
25
35
|
*
|
|
26
|
-
* This is a pure data class
|
|
36
|
+
* This is a pure data class: it holds cohort state and provides computation
|
|
27
37
|
* helpers (key aggregation, CAS Announcement building, SMT tree building).
|
|
28
38
|
* It performs no I/O and emits no messages. Both AggregationService and
|
|
29
39
|
* AggregationParticipant create their own AggregationCohort instances to
|
|
@@ -51,8 +61,8 @@ export class AggregationCohort {
|
|
|
51
61
|
participants: Array<string> = [];
|
|
52
62
|
|
|
53
63
|
/**
|
|
54
|
-
* Mapping from participant DID
|
|
55
|
-
* Distinct from {@link cohortKeys} (which is sorted per BIP-327)
|
|
64
|
+
* Mapping from participant DID to their compressed secp256k1 public key.
|
|
65
|
+
* Distinct from {@link cohortKeys} (which is sorted per BIP-327): this lets
|
|
56
66
|
* callers look up a participant's key without knowing their position in the
|
|
57
67
|
* sorted array. Populated by the service at `acceptParticipant` time.
|
|
58
68
|
*/
|
|
@@ -62,19 +72,51 @@ export class AggregationCohort {
|
|
|
62
72
|
#cohortKeys: Array<Uint8Array> = [];
|
|
63
73
|
|
|
64
74
|
/**
|
|
65
|
-
* BIP-341 TapTweak
|
|
66
|
-
*
|
|
67
|
-
*
|
|
75
|
+
* BIP-341 TapTweak scalar: `taggedHash("TapTweak", internalPubkey || tapMerkleRoot)`.
|
|
76
|
+
* The beacon output is an internal key (the MuSig2 aggregate) plus a script
|
|
77
|
+
* tree (the recovery leaves), so the tweak commits to the tree's Merkle root.
|
|
78
|
+
* The MuSig2 signing session applies this as an x-only tweak; a value that does
|
|
79
|
+
* not match the root the funded address was derived from silently yields an
|
|
80
|
+
* invalid key-path signature.
|
|
68
81
|
*/
|
|
69
82
|
tapTweak: Uint8Array = new Uint8Array();
|
|
70
83
|
|
|
71
|
-
/** The n-of-n MuSig2
|
|
84
|
+
/** The n-of-n MuSig2 aggregate internal key, x-only (32 bytes), set by computeBeaconAddress(). */
|
|
85
|
+
internalKey: Uint8Array = new Uint8Array();
|
|
86
|
+
|
|
87
|
+
/** BIP-341 Taproot Merkle root of the recovery script tree, set by computeBeaconAddress(). */
|
|
88
|
+
tapMerkleRoot: Uint8Array = new Uint8Array();
|
|
89
|
+
|
|
90
|
+
/** Operator recovery key, x-only (32 bytes). Used to build the CSV recovery leaf. */
|
|
91
|
+
recoveryKey?: Uint8Array;
|
|
92
|
+
|
|
93
|
+
/** Relative-timelock (BIP-68 nSequence) before the recovery leaf is spendable. */
|
|
94
|
+
recoverySequence?: number;
|
|
95
|
+
|
|
96
|
+
/** Funding model governing the recovery leaves (default 'operator-funded'). */
|
|
97
|
+
fundingModel: FundingModel;
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Advertised k of the k-of-n fallback leaf, or undefined to default to n-1 at
|
|
101
|
+
* address computation. Read the resolved value via {@link effectiveFallbackThreshold}.
|
|
102
|
+
*/
|
|
103
|
+
fallbackThreshold?: number;
|
|
104
|
+
|
|
105
|
+
/** The Taproot beacon address: key path is the MuSig2 aggregate, script path is fallback + recovery. */
|
|
72
106
|
beaconAddress: string = '';
|
|
73
107
|
|
|
74
108
|
/** Pending DID updates submitted by participants, keyed by DID. */
|
|
75
109
|
pendingUpdates: Map<string, SignedBTCR2Update> = new Map();
|
|
76
110
|
|
|
77
|
-
/**
|
|
111
|
+
/**
|
|
112
|
+
* Participant DIDs that explicitly declined to submit an update this round
|
|
113
|
+
* (cooperative non-inclusion). A decliner is absent from the CAS Announcement
|
|
114
|
+
* Map and carries a non-inclusion leaf in the SMT, yet still signs. Kept
|
|
115
|
+
* disjoint from {@link pendingUpdates} so CAS correctness holds by construction.
|
|
116
|
+
*/
|
|
117
|
+
nonIncluded: Set<string> = new Set();
|
|
118
|
+
|
|
119
|
+
/** CAS Beacon Announcement Map (DID to updateHash), set by buildCASAnnouncement(). */
|
|
78
120
|
casAnnouncement?: CASAnnouncement;
|
|
79
121
|
|
|
80
122
|
/** Per-participant SMT proofs, set by buildSMTTree(). */
|
|
@@ -89,7 +131,7 @@ export class AggregationCohort {
|
|
|
89
131
|
/** Set of participant DIDs that have rejected the aggregated data. */
|
|
90
132
|
validationRejections: Set<string> = new Set();
|
|
91
133
|
|
|
92
|
-
constructor({ id, minParticipants, serviceDid, network, beaconType }: AggregationCohortParams) {
|
|
134
|
+
constructor({ id, minParticipants, serviceDid, network, beaconType, recoveryKey, recoverySequence, fundingModel, fallbackThreshold }: AggregationCohortParams) {
|
|
93
135
|
this.id = id || crypto.randomUUID();
|
|
94
136
|
// `?? 2` (not `|| 2`) so a deliberately-passed 0 is preserved rather than
|
|
95
137
|
// silently coerced; the service rejects an invalid count at createCohort.
|
|
@@ -97,6 +139,10 @@ export class AggregationCohort {
|
|
|
97
139
|
this.serviceDid = serviceDid || '';
|
|
98
140
|
this.network = network;
|
|
99
141
|
this.beaconType = beaconType || 'CASBeacon';
|
|
142
|
+
this.recoveryKey = recoveryKey;
|
|
143
|
+
this.recoverySequence = recoverySequence;
|
|
144
|
+
this.fundingModel = fundingModel ?? DEFAULT_FUNDING_MODEL;
|
|
145
|
+
this.fallbackThreshold = fallbackThreshold;
|
|
100
146
|
}
|
|
101
147
|
|
|
102
148
|
/** Sorted cohort keys (sorted on assignment per BIP-327). */
|
|
@@ -109,8 +155,27 @@ export class AggregationCohort {
|
|
|
109
155
|
}
|
|
110
156
|
|
|
111
157
|
/**
|
|
112
|
-
*
|
|
113
|
-
*
|
|
158
|
+
* The resolved k of the k-of-n fallback leaf: the advertised
|
|
159
|
+
* {@link fallbackThreshold}, or n-1 (floored at 1) when unadvertised, where n is
|
|
160
|
+
* the current cohort size. This is the value the beacon address commits to and
|
|
161
|
+
* the spend builders must reproduce. Returns 0 before any cohort keys are set.
|
|
162
|
+
*/
|
|
163
|
+
public get effectiveFallbackThreshold(): number {
|
|
164
|
+
if(this.#cohortKeys.length === 0) return 0;
|
|
165
|
+
return resolveFallbackThreshold(this.fallbackThreshold, this.#cohortKeys.length);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Computes the Taproot beacon address from the cohort keys and recovery params.
|
|
170
|
+
*
|
|
171
|
+
* The output's key path is the n-of-n MuSig2 aggregate of the cohort keys; its
|
|
172
|
+
* script path is the recovery tree (a CSV recovery leaf so a missing signer
|
|
173
|
+
* cannot permanently lock the UTXO). Sets `internalKey`, `tapMerkleRoot`, and
|
|
174
|
+
* the `tapTweak` the MuSig2 session must apply for the key-path spend.
|
|
175
|
+
*
|
|
176
|
+
* The tweak is derived from the Merkle root the address was built with (read
|
|
177
|
+
* back from the payment), never recomputed by hand, so the MuSig2 key-path
|
|
178
|
+
* signature is guaranteed to validate against the funded address.
|
|
114
179
|
*/
|
|
115
180
|
public computeBeaconAddress(): string {
|
|
116
181
|
if(this.#cohortKeys.length === 0) {
|
|
@@ -119,16 +184,39 @@ export class AggregationCohort {
|
|
|
119
184
|
'NO_COHORT_KEYS', { cohortId: this.id }
|
|
120
185
|
);
|
|
121
186
|
}
|
|
187
|
+
if(!this.recoveryKey || this.recoveryKey.length === 0 || this.recoverySequence === undefined) {
|
|
188
|
+
throw new AggregationCohortError(
|
|
189
|
+
'Cannot compute beacon address: missing recovery key or sequence.',
|
|
190
|
+
'NO_RECOVERY_PARAMS', { cohortId: this.id }
|
|
191
|
+
);
|
|
192
|
+
}
|
|
122
193
|
const keyAggContext = keyAggregate(this.#cohortKeys);
|
|
123
194
|
const aggPubkey = keyAggExport(keyAggContext);
|
|
124
|
-
// Derive the address for the cohort's network. Without the network arg
|
|
125
|
-
// p2tr defaults to mainnet, so a mutinynet/signet/regtest cohort would
|
|
126
|
-
// otherwise advertise a `bc1p...` address that no participant can fund.
|
|
127
|
-
const payment = p2tr(aggPubkey, undefined, getNetwork(this.network));
|
|
128
195
|
|
|
129
|
-
//
|
|
130
|
-
//
|
|
131
|
-
|
|
196
|
+
// The beacon output commits to the script tree (k-of-n fallback leaf + CSV
|
|
197
|
+
// recovery leaf) alongside the MuSig2 internal key. Derive the address for
|
|
198
|
+
// the cohort's network. Without the network arg p2tr defaults to mainnet, so
|
|
199
|
+
// a mutinynet/signet/regtest cohort would otherwise advertise a `bc1p...`
|
|
200
|
+
// address that no participant can fund.
|
|
201
|
+
const leaves = buildRecoveryLeaves(this.fundingModel, {
|
|
202
|
+
recoveryKey : this.recoveryKey,
|
|
203
|
+
recoverySequence : this.recoverySequence,
|
|
204
|
+
cohortKeys : this.#cohortKeys,
|
|
205
|
+
fallbackThreshold : resolveFallbackThreshold(this.fallbackThreshold, this.#cohortKeys.length),
|
|
206
|
+
});
|
|
207
|
+
// allowUnknownOutputs: the CSV recovery leaf is a custom script, not one of
|
|
208
|
+
// p2tr's recognized templates (tr_ns/tr_ms), so the template check must be
|
|
209
|
+
// waived. The leaf hash (and thus the address) is computed from the raw
|
|
210
|
+
// script bytes regardless.
|
|
211
|
+
const payment = p2tr(aggPubkey, leaves, getNetwork(this.network), true);
|
|
212
|
+
|
|
213
|
+
// BIP-341: the key-path tweak commits to the script tree's Merkle root.
|
|
214
|
+
// taggedHash("TapTweak", internalPubkey || tapMerkleRoot). Use the root the
|
|
215
|
+
// library committed to (payment.tapMerkleRoot) so the tweak matches the
|
|
216
|
+
// funded address byte-for-byte.
|
|
217
|
+
this.internalKey = aggPubkey;
|
|
218
|
+
this.tapMerkleRoot = payment.tapMerkleRoot;
|
|
219
|
+
this.tapTweak = schnorr.utils.taggedHash('TapTweak', concatBytes(aggPubkey, payment.tapMerkleRoot));
|
|
132
220
|
|
|
133
221
|
if(!payment.address) {
|
|
134
222
|
throw new AggregationCohortError(
|
|
@@ -189,20 +277,56 @@ export class AggregationCohort {
|
|
|
189
277
|
this.pendingUpdates.set(participantDid, signedUpdate);
|
|
190
278
|
}
|
|
191
279
|
|
|
280
|
+
/**
|
|
281
|
+
* Record that a participant declined to submit an update this round
|
|
282
|
+
* (cooperative non-inclusion). The member stays in the cohort and still signs.
|
|
283
|
+
*/
|
|
284
|
+
public addNonInclusion(participantDid: string): void {
|
|
285
|
+
if(!this.participants.includes(participantDid)) {
|
|
286
|
+
throw new AggregationCohortError(
|
|
287
|
+
`Participant ${participantDid} is not in cohort ${this.id}.`,
|
|
288
|
+
'UNKNOWN_PARTICIPANT', { cohortId: this.id, participantDid }
|
|
289
|
+
);
|
|
290
|
+
}
|
|
291
|
+
// A DID cannot both submit and decline. The service guards re-submission, but
|
|
292
|
+
// keep the invariant local so the response gate and builders stay consistent.
|
|
293
|
+
if(this.pendingUpdates.has(participantDid)) {
|
|
294
|
+
throw new AggregationCohortError(
|
|
295
|
+
`Participant ${participantDid} already submitted an update; cannot also decline.`,
|
|
296
|
+
'CONFLICTING_RESPONSE', { cohortId: this.id, participantDid }
|
|
297
|
+
);
|
|
298
|
+
}
|
|
299
|
+
this.nonIncluded.add(participantDid);
|
|
300
|
+
}
|
|
301
|
+
|
|
192
302
|
public hasAllUpdates(): boolean {
|
|
193
303
|
return this.pendingUpdates.size === this.participants.length;
|
|
194
304
|
}
|
|
195
305
|
|
|
306
|
+
/**
|
|
307
|
+
* True when every participant has responded for this round, either with an
|
|
308
|
+
* update or with an explicit non-inclusion. This is the aggregation gate when
|
|
309
|
+
* non-inclusion is in play; it generalizes {@link hasAllUpdates} the same way
|
|
310
|
+
* {@link hasAllValidationResponses} generalizes a unanimous ack.
|
|
311
|
+
*/
|
|
312
|
+
public hasAllResponses(): boolean {
|
|
313
|
+
return this.pendingUpdates.size + this.nonIncluded.size === this.participants.length;
|
|
314
|
+
}
|
|
315
|
+
|
|
196
316
|
/**
|
|
197
317
|
* Builds a CAS Announcement Map from collected updates.
|
|
198
|
-
* Maps each participant DID
|
|
318
|
+
* Maps each participant DID to base64url canonical hash of their signed update.
|
|
199
319
|
* Computes signal bytes as SHA-256 of canonicalized announcement.
|
|
320
|
+
*
|
|
321
|
+
* Members who declined (cooperative non-inclusion) are naturally absent from
|
|
322
|
+
* the map: the body iterates {@link pendingUpdates}, which never holds a
|
|
323
|
+
* decliner. Absence from the map is exactly the CAS non-inclusion signal.
|
|
200
324
|
*/
|
|
201
325
|
public buildCASAnnouncement(): CASAnnouncement {
|
|
202
|
-
if(!this.
|
|
326
|
+
if(!this.hasAllResponses()) {
|
|
203
327
|
throw new AggregationCohortError(
|
|
204
|
-
'Cannot build CAS Announcement: not all
|
|
205
|
-
'
|
|
328
|
+
'Cannot build CAS Announcement: not all participants have responded.',
|
|
329
|
+
'INCOMPLETE_RESPONSES', { cohortId: this.id, updates: this.pendingUpdates.size, declined: this.nonIncluded.size, total: this.participants.length }
|
|
206
330
|
);
|
|
207
331
|
}
|
|
208
332
|
const announcement: CASAnnouncement = {};
|
|
@@ -215,25 +339,37 @@ export class AggregationCohort {
|
|
|
215
339
|
}
|
|
216
340
|
|
|
217
341
|
/**
|
|
218
|
-
* Builds an SMT tree
|
|
219
|
-
*
|
|
220
|
-
*
|
|
342
|
+
* Builds an SMT tree with one leaf per participant.
|
|
343
|
+
*
|
|
344
|
+
* A member who submitted an update gets an inclusion leaf
|
|
345
|
+
* (SHA-256(SHA-256(nonce) || SHA-256(update))); a member who declined gets a
|
|
346
|
+
* non-inclusion leaf (SHA-256(SHA-256(nonce)), the `signedUpdate` entry field
|
|
347
|
+
* omitted). The cohort mints each member's nonce and returns it inside that
|
|
348
|
+
* member's serialized proof, so a decliner can self-validate its own
|
|
349
|
+
* non-inclusion slot and the resolver can recompute the leaf. Stores
|
|
350
|
+
* per-participant proofs and the SMT root as signalBytes.
|
|
221
351
|
*/
|
|
222
352
|
public buildSMTTree(): Map<string, SerializedSMTProof> {
|
|
223
|
-
if(!this.
|
|
353
|
+
if(!this.hasAllResponses()) {
|
|
224
354
|
throw new AggregationCohortError(
|
|
225
|
-
'Cannot build SMT tree: not all
|
|
226
|
-
'
|
|
355
|
+
'Cannot build SMT tree: not all participants have responded.',
|
|
356
|
+
'INCOMPLETE_RESPONSES', { cohortId: this.id, updates: this.pendingUpdates.size, declined: this.nonIncluded.size, total: this.participants.length }
|
|
227
357
|
);
|
|
228
358
|
}
|
|
229
359
|
const tree = new BTCR2MerkleTree();
|
|
230
360
|
const entries: TreeEntry[] = [];
|
|
231
361
|
const encoder = new TextEncoder();
|
|
232
362
|
|
|
233
|
-
for
|
|
234
|
-
|
|
363
|
+
// Slot every participant: an inclusion leaf for submitters, a non-inclusion
|
|
364
|
+
// leaf (signedUpdate omitted) for decliners.
|
|
365
|
+
for(const did of this.participants) {
|
|
235
366
|
const nonce = randomBytes(32);
|
|
236
|
-
|
|
367
|
+
const signedUpdate = this.pendingUpdates.get(did);
|
|
368
|
+
if(signedUpdate) {
|
|
369
|
+
entries.push({ did, nonce, signedUpdate: encoder.encode(canonicalize(signedUpdate)) });
|
|
370
|
+
} else {
|
|
371
|
+
entries.push({ did, nonce });
|
|
372
|
+
}
|
|
237
373
|
}
|
|
238
374
|
|
|
239
375
|
tree.addEntries(entries);
|
|
@@ -241,7 +377,7 @@ export class AggregationCohort {
|
|
|
241
377
|
|
|
242
378
|
this.signalBytes = tree.rootHash;
|
|
243
379
|
this.smtProofs = new Map();
|
|
244
|
-
for(const
|
|
380
|
+
for(const did of this.participants) {
|
|
245
381
|
this.smtProofs.set(did, tree.proof(did));
|
|
246
382
|
}
|
|
247
383
|
return this.smtProofs;
|
|
@@ -269,7 +405,7 @@ export class AggregationCohort {
|
|
|
269
405
|
}
|
|
270
406
|
|
|
271
407
|
/**
|
|
272
|
-
* True when all participants approved. Note: differs from {@link hasAllValidationResponses}
|
|
408
|
+
* True when all participants approved. Note: differs from {@link hasAllValidationResponses},
|
|
273
409
|
* this returns false if any participant rejected, even if all responses are in.
|
|
274
410
|
*/
|
|
275
411
|
public isFullyValidated(): boolean {
|
|
@@ -15,9 +15,15 @@
|
|
|
15
15
|
* settlement (consistent with ADR 008).
|
|
16
16
|
*/
|
|
17
17
|
|
|
18
|
+
import type { FundingModel } from './recovery-policy.js';
|
|
19
|
+
import { MAX_RECOVERY_SEQUENCE } from './recovery-policy.js';
|
|
20
|
+
|
|
18
21
|
/** Beacon types that support aggregation (singleton is single-party only, per ADR 037). */
|
|
19
22
|
export const KNOWN_BEACON_TYPES = ['CASBeacon', 'SMTBeacon'] as const;
|
|
20
23
|
|
|
24
|
+
/** Funding models an operator may advertise. Only 'operator-funded' is implemented (ADR 042). */
|
|
25
|
+
export const KNOWN_FUNDING_MODELS = ['operator-funded', 'participant-funded'] as const;
|
|
26
|
+
|
|
21
27
|
/**
|
|
22
28
|
* An advertised price. `unit` is operator-defined (the spec does not specify a
|
|
23
29
|
* currency); `basis` distinguishes a per-DID from a per-participant charge for
|
|
@@ -51,6 +57,31 @@ export interface CohortConditions {
|
|
|
51
57
|
maxSecondsBetweenAnnouncements?: number;
|
|
52
58
|
/** 7. Pending-update count that triggers an announcement. Advertised; enforcement staged (AGG-5) - generalizes hasAllUpdates(). */
|
|
53
59
|
pendingUpdateTrigger?: number;
|
|
60
|
+
/**
|
|
61
|
+
* Who funds the beacon UTXO and holds the recovery path. Defaults to
|
|
62
|
+
* 'operator-funded' when absent. See ADR 042.
|
|
63
|
+
*/
|
|
64
|
+
fundingModel?: FundingModel;
|
|
65
|
+
/**
|
|
66
|
+
* Operator recovery key, x-only (64-character hex / 32 bytes). The beacon
|
|
67
|
+
* output commits to a CSV recovery leaf keyed to this key, so a missing signer
|
|
68
|
+
* can never permanently lock the funded UTXO. Required (ADR 042).
|
|
69
|
+
*/
|
|
70
|
+
recoveryKey: string;
|
|
71
|
+
/**
|
|
72
|
+
* Relative-timelock (BIP-68 nSequence, in blocks) before the recovery leaf is
|
|
73
|
+
* spendable. Required, >= 1 (ADR 042).
|
|
74
|
+
*/
|
|
75
|
+
recoverySequence: number;
|
|
76
|
+
/**
|
|
77
|
+
* Number of signers (k) the k-of-n fallback leaf requires, so any k cohort
|
|
78
|
+
* members can still announce when the optimistic n-of-n key path stalls
|
|
79
|
+
* (graceful liveness, ADR 042). Optional: when absent it defaults to n-1 at
|
|
80
|
+
* keygen, where n is the finalized participant count. When advertised it must
|
|
81
|
+
* be an integer >= 1 (and <= maxParticipants when that is set); the upper bound
|
|
82
|
+
* against the actual cohort size n is enforced at keygen.
|
|
83
|
+
*/
|
|
84
|
+
fallbackThreshold?: number;
|
|
54
85
|
}
|
|
55
86
|
|
|
56
87
|
/** Validate an optional [min, max] integer pair. */
|
|
@@ -109,8 +140,33 @@ export function validateCohortConditions(c: CohortConditions): string[] {
|
|
|
109
140
|
problems.push('pendingUpdateTrigger must be an integer >= 1');
|
|
110
141
|
}
|
|
111
142
|
|
|
143
|
+
// Fallback threshold (k of the k-of-n fallback leaf). Optional; when advertised
|
|
144
|
+
// it must be a positive integer and cannot exceed maxParticipants (the binding
|
|
145
|
+
// upper bound against the actual cohort size n is checked at keygen, where n is
|
|
146
|
+
// known). See ADR 042.
|
|
147
|
+
if(c.fallbackThreshold !== undefined) {
|
|
148
|
+
if(!Number.isInteger(c.fallbackThreshold) || c.fallbackThreshold < 1) {
|
|
149
|
+
problems.push('fallbackThreshold must be an integer >= 1');
|
|
150
|
+
} else if(c.maxParticipants !== undefined && Number.isInteger(c.maxParticipants) && c.fallbackThreshold > c.maxParticipants) {
|
|
151
|
+
problems.push('fallbackThreshold must be <= maxParticipants');
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
112
155
|
checkCost(problems, 'costOfEnrollment', c.costOfEnrollment);
|
|
113
156
|
checkCost(problems, 'costPerAnnouncement', c.costPerAnnouncement);
|
|
114
157
|
|
|
158
|
+
// Recovery params: the beacon output's CSV recovery leaf. Required so a
|
|
159
|
+
// missing signer can never permanently lock the funded UTXO (ADR 042). The
|
|
160
|
+
// key is an x-only (32-byte) Schnorr public key, carried as 64 hex chars.
|
|
161
|
+
if(typeof c.recoveryKey !== 'string' || !/^[0-9a-fA-F]{64}$/.test(c.recoveryKey)) {
|
|
162
|
+
problems.push('recoveryKey must be a 64-character hex string (x-only public key)');
|
|
163
|
+
}
|
|
164
|
+
if(!Number.isInteger(c.recoverySequence) || c.recoverySequence < 1 || c.recoverySequence > MAX_RECOVERY_SEQUENCE) {
|
|
165
|
+
problems.push(`recoverySequence must be a block-based BIP-68 relative timelock in [1, ${MAX_RECOVERY_SEQUENCE}]`);
|
|
166
|
+
}
|
|
167
|
+
if(c.fundingModel !== undefined && !(KNOWN_FUNDING_MODELS as readonly string[]).includes(c.fundingModel)) {
|
|
168
|
+
problems.push(`fundingModel must be one of ${KNOWN_FUNDING_MODELS.join(', ')}`);
|
|
169
|
+
}
|
|
170
|
+
|
|
115
171
|
return problems;
|
|
116
172
|
}
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Fallback spend builder for aggregate beacon outputs.
|
|
3
|
+
*
|
|
4
|
+
* An aggregate beacon UTXO is a Taproot output whose key path is the cohort's
|
|
5
|
+
* n-of-n MuSig2 aggregate key and whose script path carries a k-of-n fallback
|
|
6
|
+
* leaf (`p2tr_ms` CHECKSIGADD) plus a CSV recovery leaf (see
|
|
7
|
+
* {@link ./recovery-policy.ts} and ADR 042). When the optimistic n-of-n key path
|
|
8
|
+
* stalls (a missing or defecting signer), the cohort can still push the SAME
|
|
9
|
+
* announcement transaction through the fallback leaf with any k members'
|
|
10
|
+
* signatures, instead of abandoning the round or waiting out the recovery
|
|
11
|
+
* timelock.
|
|
12
|
+
*
|
|
13
|
+
* Unlike the MuSig2 key path, the fallback is a plain k-of-n script-path spend:
|
|
14
|
+
* each signer produces a standalone BIP-340 signature over the script-path
|
|
15
|
+
* sighash (no nonce round), and the coordinator assembles k of them into the
|
|
16
|
+
* witness. The coordinator never holds a participant secret - it injects the
|
|
17
|
+
* collected signatures and finalizes.
|
|
18
|
+
*
|
|
19
|
+
* This module is pure with respect to the network: it takes the beacon
|
|
20
|
+
* transaction, the cohort and recovery parameters, the spent output, and the
|
|
21
|
+
* collected signatures, and returns a finalized {@link Transaction}.
|
|
22
|
+
* Broadcasting is the caller's concern.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
import { getNetwork } from '@did-btcr2/bitcoin';
|
|
26
|
+
import { schnorr } from '@noble/curves/secp256k1.js';
|
|
27
|
+
import type { Transaction} from '@scure/btc-signer';
|
|
28
|
+
import { SigHash, p2tr } from '@scure/btc-signer';
|
|
29
|
+
import { keyAggExport, keyAggregate, sortKeys } from '@scure/btc-signer/musig2';
|
|
30
|
+
import { AggregationCohortError } from './errors.js';
|
|
31
|
+
import type { FundingModel } from './recovery-policy.js';
|
|
32
|
+
import {
|
|
33
|
+
DEFAULT_FUNDING_MODEL,
|
|
34
|
+
TAPROOT_LEAF_VERSION,
|
|
35
|
+
buildFallbackLeaf,
|
|
36
|
+
buildRecoveryLeaves,
|
|
37
|
+
resolveFallbackThreshold,
|
|
38
|
+
tapLeafHash,
|
|
39
|
+
} from './recovery-policy.js';
|
|
40
|
+
|
|
41
|
+
/** A single member's standalone signature over the fallback script-path sighash. */
|
|
42
|
+
export interface FallbackSignature {
|
|
43
|
+
/** Signer's x-only public key (32 bytes). Must be one of the cohort's keys. */
|
|
44
|
+
pubKey: Uint8Array;
|
|
45
|
+
/** 64-byte BIP-340 Schnorr signature over the script-path sighash. */
|
|
46
|
+
signature: Uint8Array;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Inputs to {@link buildFallbackSpend}. */
|
|
50
|
+
export interface FallbackSpendParams {
|
|
51
|
+
/**
|
|
52
|
+
* The beacon announcement transaction to finalize. Input {@link inputIndex}
|
|
53
|
+
* spends the beacon UTXO; its key-path witness must not be set (the fallback
|
|
54
|
+
* assembles a script-path witness instead).
|
|
55
|
+
*/
|
|
56
|
+
pendingTx: Transaction;
|
|
57
|
+
/** Index of the beacon input within {@link pendingTx}. Defaults to 0. */
|
|
58
|
+
inputIndex?: number;
|
|
59
|
+
/**
|
|
60
|
+
* The cohort's participant public keys (compressed secp256k1, 33 bytes).
|
|
61
|
+
* Sorted internally per BIP-327 so the reconstructed tree matches the funded
|
|
62
|
+
* output.
|
|
63
|
+
*/
|
|
64
|
+
cohortKeys: Uint8Array[];
|
|
65
|
+
/**
|
|
66
|
+
* The advertised k of the k-of-n fallback leaf, or omit for the cohort's n-1
|
|
67
|
+
* default. Resolved against `cohortKeys.length` exactly as the cohort does.
|
|
68
|
+
*/
|
|
69
|
+
fallbackThreshold?: number;
|
|
70
|
+
/** Operator recovery key, x-only (32 bytes). Needed to reconstruct the script tree. */
|
|
71
|
+
recoveryKey: Uint8Array;
|
|
72
|
+
/** Relative-timelock (BIP-68) the recovery leaf enforces. Needed to reconstruct the script tree. */
|
|
73
|
+
recoverySequence: number;
|
|
74
|
+
/** Funding model governing the leaves. Defaults to 'operator-funded'. */
|
|
75
|
+
fundingModel?: FundingModel;
|
|
76
|
+
/** Bitcoin network name (bitcoin/mainnet, mutinynet, signet, testnet, regtest). */
|
|
77
|
+
network: string;
|
|
78
|
+
/** scriptPubKey of the beacon UTXO being spent. Must equal the reconstructed tree output script. */
|
|
79
|
+
prevOutScript: Uint8Array;
|
|
80
|
+
/** Value of the beacon UTXO in satoshis. */
|
|
81
|
+
prevOutValue: bigint;
|
|
82
|
+
/**
|
|
83
|
+
* Standalone signatures collected from cohort members. At least
|
|
84
|
+
* {@link fallbackThreshold} valid, distinct-by-key signatures are required;
|
|
85
|
+
* exactly k are injected (a k-of-n CHECKSIGADD leaf demands exactly k).
|
|
86
|
+
*/
|
|
87
|
+
signatures: FallbackSignature[];
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function bytesEqual(a: Uint8Array, b: Uint8Array): boolean {
|
|
91
|
+
return a.length === b.length && a.every((x, i) => x === b[i]);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Compute the BIP-341 script-path sighash a cohort member must sign to authorize
|
|
96
|
+
* the fallback spend. The leaf is the k-of-n fallback leaf; signers produce a
|
|
97
|
+
* standalone BIP-340 signature over this digest with SIGHASH_DEFAULT.
|
|
98
|
+
*/
|
|
99
|
+
export function fallbackSighash(
|
|
100
|
+
tx: Transaction,
|
|
101
|
+
inputIndex: number,
|
|
102
|
+
prevOutScript: Uint8Array,
|
|
103
|
+
prevOutValue: bigint,
|
|
104
|
+
fallbackLeafScript: Uint8Array,
|
|
105
|
+
): Uint8Array {
|
|
106
|
+
return tx.preimageWitnessV1(
|
|
107
|
+
inputIndex,
|
|
108
|
+
[ prevOutScript ],
|
|
109
|
+
SigHash.DEFAULT,
|
|
110
|
+
[ prevOutValue ],
|
|
111
|
+
undefined,
|
|
112
|
+
fallbackLeafScript,
|
|
113
|
+
TAPROOT_LEAF_VERSION,
|
|
114
|
+
);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Assemble and finalize a k-of-n fallback spend of an aggregate beacon UTXO.
|
|
119
|
+
*
|
|
120
|
+
* Reconstructs the funded Taproot output (MuSig2 internal key + fallback/recovery
|
|
121
|
+
* script tree), verifies each collected signature against the script-path
|
|
122
|
+
* sighash and a cohort key, injects exactly k distinct valid signatures into the
|
|
123
|
+
* fallback leaf, and finalizes the witness. The returned transaction is the same
|
|
124
|
+
* announcement the optimistic path would have produced, signed via the script
|
|
125
|
+
* path instead of the key path.
|
|
126
|
+
*
|
|
127
|
+
* @throws {AggregationCohortError} when there are no cohort keys, the spent
|
|
128
|
+
* script does not match the reconstructed tree output, or fewer than k valid
|
|
129
|
+
* distinct signatures were supplied.
|
|
130
|
+
*/
|
|
131
|
+
export function buildFallbackSpend(params: FallbackSpendParams): Transaction {
|
|
132
|
+
const {
|
|
133
|
+
pendingTx, cohortKeys, recoveryKey, recoverySequence,
|
|
134
|
+
fundingModel, network, prevOutScript, prevOutValue, signatures,
|
|
135
|
+
} = params;
|
|
136
|
+
const inputIndex = params.inputIndex ?? 0;
|
|
137
|
+
|
|
138
|
+
if(cohortKeys.length === 0) {
|
|
139
|
+
throw new AggregationCohortError(
|
|
140
|
+
'Cannot build fallback spend: no cohort keys.',
|
|
141
|
+
'NO_COHORT_KEYS'
|
|
142
|
+
);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// Resolve k the same way the cohort did, so the reconstructed leaf matches.
|
|
146
|
+
const fallbackThreshold = resolveFallbackThreshold(params.fallbackThreshold, cohortKeys.length);
|
|
147
|
+
|
|
148
|
+
// Reconstruct the funded output the same way the cohort derived its address.
|
|
149
|
+
const internalKey = keyAggExport(keyAggregate(sortKeys(cohortKeys)));
|
|
150
|
+
const leaves = buildRecoveryLeaves(fundingModel ?? DEFAULT_FUNDING_MODEL, {
|
|
151
|
+
recoveryKey, recoverySequence, cohortKeys, fallbackThreshold,
|
|
152
|
+
});
|
|
153
|
+
const net = getNetwork(network);
|
|
154
|
+
// allowUnknownOutputs: the CSV recovery leaf is a custom script (see cohort.ts).
|
|
155
|
+
const payment = p2tr(internalKey, leaves, net, true);
|
|
156
|
+
|
|
157
|
+
// The output we are spending must be the cohort's funded beacon output; if the
|
|
158
|
+
// reconstructed tree script differs, the witness would not match the chain.
|
|
159
|
+
if(!bytesEqual(payment.script, prevOutScript)) {
|
|
160
|
+
throw new AggregationCohortError(
|
|
161
|
+
'Reconstructed beacon output script does not match the spent prevout script.',
|
|
162
|
+
'PREVOUT_SCRIPT_MISMATCH'
|
|
163
|
+
);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const fallbackLeaf = buildFallbackLeaf({ cohortKeys, fallbackThreshold });
|
|
167
|
+
// Locate the fallback leaf's tapLeafScript entry: each entry is
|
|
168
|
+
// [controlBlock, script || leafVersion]; strip the trailing version byte to
|
|
169
|
+
// compare the script.
|
|
170
|
+
const leafEntry = payment.tapLeafScript?.find(([ , scriptVer ]) => {
|
|
171
|
+
const script = scriptVer.slice(0, scriptVer.length - 1);
|
|
172
|
+
return bytesEqual(script, fallbackLeaf);
|
|
173
|
+
});
|
|
174
|
+
if(!leafEntry) {
|
|
175
|
+
throw new AggregationCohortError(
|
|
176
|
+
'Could not locate the fallback leaf in the reconstructed beacon output.',
|
|
177
|
+
'FALLBACK_LEAF_NOT_FOUND'
|
|
178
|
+
);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// Validate the collected signatures against the script-path sighash. The leaf
|
|
182
|
+
// is keyed by x-only cohort keys, so a valid signature must verify against one
|
|
183
|
+
// of them. Keep only distinct, valid signatures (first occurrence per key).
|
|
184
|
+
const cohortXOnly = sortKeys(cohortKeys).map(k => k.slice(1));
|
|
185
|
+
const tx = pendingTx;
|
|
186
|
+
const sighash = fallbackSighash(tx, inputIndex, prevOutScript, prevOutValue, fallbackLeaf);
|
|
187
|
+
|
|
188
|
+
const leafHash = tapLeafHash(fallbackLeaf);
|
|
189
|
+
const accepted = new Map<string, Uint8Array>(); // x-only hex to signature
|
|
190
|
+
for(const { pubKey, signature } of signatures) {
|
|
191
|
+
if(pubKey.length !== 32 || signature.length !== 64) continue;
|
|
192
|
+
const isCohortKey = cohortXOnly.some(k => bytesEqual(k, pubKey));
|
|
193
|
+
if(!isCohortKey) continue;
|
|
194
|
+
const hex = Array.from(pubKey, b => b.toString(16).padStart(2, '0')).join('');
|
|
195
|
+
if(accepted.has(hex)) continue;
|
|
196
|
+
let ok = false;
|
|
197
|
+
try { ok = schnorr.verify(signature, sighash, pubKey); } catch { ok = false; }
|
|
198
|
+
if(ok) accepted.set(hex, signature);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
if(accepted.size < fallbackThreshold) {
|
|
202
|
+
throw new AggregationCohortError(
|
|
203
|
+
`Not enough valid fallback signatures: have ${accepted.size}, need ${fallbackThreshold}.`,
|
|
204
|
+
'NOT_ENOUGH_FALLBACK_SIGNATURES', { have: accepted.size, need: fallbackThreshold }
|
|
205
|
+
);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// A k-of-n CHECKSIGADD leaf demands EXACTLY k satisfied signatures (the final
|
|
209
|
+
// <k> NUMEQUAL fails if the running count differs), so inject exactly k.
|
|
210
|
+
const chosen = cohortXOnly
|
|
211
|
+
.filter(k => accepted.has(Array.from(k, b => b.toString(16).padStart(2, '0')).join('')))
|
|
212
|
+
.slice(0, fallbackThreshold);
|
|
213
|
+
|
|
214
|
+
tx.updateInput(inputIndex, {
|
|
215
|
+
tapLeafScript : [ leafEntry ],
|
|
216
|
+
tapScriptSig : chosen.map(pubKey => {
|
|
217
|
+
const hex = Array.from(pubKey, b => b.toString(16).padStart(2, '0')).join('');
|
|
218
|
+
return [ { pubKey, leafHash }, accepted.get(hex)! ];
|
|
219
|
+
}),
|
|
220
|
+
});
|
|
221
|
+
tx.finalize();
|
|
222
|
+
return tx;
|
|
223
|
+
}
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
* {@link SILENT_LOGGER} to suppress output (useful for tests) or a custom
|
|
7
7
|
* implementation to route logs to pino, winston, Sentry, etc.
|
|
8
8
|
*
|
|
9
|
-
* The interface is intentionally small
|
|
9
|
+
* The interface is intentionally small: we don't want production code taking
|
|
10
10
|
* a hard dependency on any specific logger library.
|
|
11
11
|
*/
|
|
12
12
|
export interface Logger {
|
|
@@ -22,6 +22,12 @@ export type BaseBody = Partial<CohortConditions> & {
|
|
|
22
22
|
aggregatedNonce?: Uint8Array;
|
|
23
23
|
nonceContribution?: Uint8Array;
|
|
24
24
|
partialSignature?: Uint8Array;
|
|
25
|
+
/** Fallback (k-of-n script-path) leaf script, hex. Carried on FALLBACK_AUTHORIZATION_REQUEST. */
|
|
26
|
+
fallbackLeafScriptHex?: string;
|
|
27
|
+
/** Signer's x-only key for a fallback signature (which CHECKSIGADD slot it satisfies). */
|
|
28
|
+
signerPk?: Uint8Array;
|
|
29
|
+
/** A member's standalone BIP-340 fallback script-path signature (64 bytes). */
|
|
30
|
+
fallbackSignature?: Uint8Array;
|
|
25
31
|
pendingTx?: string;
|
|
26
32
|
/** Hex-encoded scriptPubKey of the UTXO being spent. Required for BIP-341 sighash. */
|
|
27
33
|
prevOutScriptHex?: string;
|