@scure/btc-signer 2.0.0 → 2.2.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/README.md +189 -39
- package/index.d.ts +15 -5
- package/index.d.ts.map +1 -1
- package/index.js +16 -6
- package/index.js.map +1 -1
- package/musig2.d.ts +202 -64
- package/musig2.d.ts.map +1 -1
- package/musig2.js +324 -87
- package/musig2.js.map +1 -1
- package/p2p.d.ts +17 -7
- package/p2p.d.ts.map +1 -1
- package/p2p.js +40 -4
- package/p2p.js.map +1 -1
- package/package.json +25 -10
- package/payment.d.ts +407 -38
- package/payment.d.ts.map +1 -1
- package/payment.js +504 -57
- package/payment.js.map +1 -1
- package/psbt.d.ts +2958 -559
- package/psbt.d.ts.map +1 -1
- package/psbt.js +462 -118
- package/psbt.js.map +1 -1
- package/script.d.ts +311 -132
- package/script.d.ts.map +1 -1
- package/script.js +246 -35
- package/script.js.map +1 -1
- package/src/index.ts +34 -11
- package/src/musig2.ts +387 -145
- package/src/p2p.ts +54 -18
- package/src/payment.ts +823 -226
- package/src/psbt.ts +633 -228
- package/src/script.ts +353 -117
- package/src/transaction.ts +593 -169
- package/src/utils.ts +322 -43
- package/src/utxo.ts +154 -51
- package/transaction.d.ts +242 -31
- package/transaction.d.ts.map +1 -1
- package/transaction.js +460 -100
- package/transaction.js.map +1 -1
- package/utils.d.ts +266 -24
- package/utils.d.ts.map +1 -1
- package/utils.js +278 -27
- package/utils.js.map +1 -1
- package/utxo.d.ts +438 -75
- package/utxo.d.ts.map +1 -1
- package/utxo.js +123 -36
- package/utxo.js.map +1 -1
package/musig2.js
CHANGED
|
@@ -6,8 +6,17 @@ import { compareBytes, hasEven } from "./utils.js";
|
|
|
6
6
|
/**
|
|
7
7
|
* Represents an error indicating an invalid contribution from a signer.
|
|
8
8
|
* This allows pointing out which participant is malicious and what specifically is wrong.
|
|
9
|
+
* @param idx - signer index with the invalid contribution
|
|
10
|
+
* @param m - error message
|
|
11
|
+
* @example
|
|
12
|
+
* Create an error that points to the participant who sent invalid data.
|
|
13
|
+
* ```ts
|
|
14
|
+
* new InvalidContributionErr(0, 'pubkey');
|
|
15
|
+
* ```
|
|
9
16
|
*/
|
|
10
17
|
export class InvalidContributionErr extends Error {
|
|
18
|
+
// BIP327 identifiable aborts blame exactly one signer by participant index in the
|
|
19
|
+
// caller's session ordering, so callers interpret idx using the same ordering they signed with.
|
|
11
20
|
idx; // Indice of participant
|
|
12
21
|
constructor(idx, m) {
|
|
13
22
|
super(m);
|
|
@@ -15,65 +24,136 @@ export class InvalidContributionErr extends Error {
|
|
|
15
24
|
}
|
|
16
25
|
}
|
|
17
26
|
// Utils
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
const
|
|
21
|
-
|
|
22
|
-
|
|
27
|
+
// MuSig2 reuses BIP340 tagged hashing, i.e. SHA256(SHA256(tag) || SHA256(tag) || msg...),
|
|
28
|
+
// for all of the domain-separated hashes below (KeyAgg list, noncecoef, challenge, aux, ...).
|
|
29
|
+
const taggedHash = /* @__PURE__ */ (() => schnorr.utils.taggedHash)();
|
|
30
|
+
// BIP327 uses xbytes(P) = bytes(32, x(P)) for aggregate keys, nonce/challenge hashes,
|
|
31
|
+
// and final signatures, so this alias is intentionally x-only instead of 33-byte SEC1.
|
|
32
|
+
const pointToBytes = /* @__PURE__ */ (() => schnorr.utils.pointToBytes)();
|
|
33
|
+
// MuSig2 keeps aggregate keys/nonces as full secp256k1 points so it can represent infinity
|
|
34
|
+
// and inspect parity before exporting compressed or x-only encodings at the API boundaries.
|
|
35
|
+
const Point = /* @__PURE__ */ (() => secp256k1.Point)();
|
|
36
|
+
// MuSig2 scalars live in Z_n with fixed 32-byte encodings: strict inputs like secret keys
|
|
37
|
+
// use Fn.fromBytes(...), tweak bytes allow 0 per ApplyTweak, and hash-derived values are
|
|
38
|
+
// intentionally reduced mod n.
|
|
39
|
+
const Fn = /* @__PURE__ */ (() => Point.Fn)();
|
|
40
|
+
// BIP327 signer keys are plain compressed pubkeys (33 bytes); only aggregate exports switch
|
|
41
|
+
// to BIP340's 32-byte x-only format, so the internal input length stays on secp256k1.publicKey.
|
|
42
|
+
const PUBKEY_LEN = /* @__PURE__ */ (() => secp256k1.lengths.publicKey)();
|
|
43
|
+
// BIP327 uses bytes(33, 0) both as cbytes_ext(Point.ZERO) for infinity and as GetSecondKey's
|
|
44
|
+
// "no second distinct key" sentinel, so this all-zero compressed slot is intentionally out-of-band.
|
|
45
|
+
const ZERO = /* @__PURE__ */ new Uint8Array(PUBKEY_LEN); // Compressed zero point
|
|
23
46
|
// Encoding
|
|
24
47
|
// TODO: re-use in PSBT?
|
|
25
|
-
|
|
48
|
+
// This is BIP327's cbytes_ext/cpoint_ext adapter: normal points stay in compressed SEC1,
|
|
49
|
+
// while Point.ZERO maps to bytes(33, 0) as the out-of-band infinity sentinel for aggnonce.
|
|
50
|
+
const compressed = /* @__PURE__ */ (() => P.apply(P.bytes(33), {
|
|
26
51
|
decode: (p) => (isZero(p) ? ZERO : p.toBytes(true)),
|
|
27
52
|
encode: (b) => (equalBytes(b, ZERO) ? Point.ZERO : Point.fromBytes(b)),
|
|
28
|
-
});
|
|
29
|
-
|
|
53
|
+
}))();
|
|
54
|
+
// This coder is only for stored secnonce limbs k1/k2, which BIP327 requires to be
|
|
55
|
+
// nonzero scalars in [1, n); tweak scalars use different validation because 0 is allowed there.
|
|
56
|
+
const scalar = /* @__PURE__ */ (() => P.validate(P.U256BE, (n) => {
|
|
30
57
|
aInRange('n', n, 1n, Fn.ORDER);
|
|
31
58
|
return n;
|
|
32
|
-
});
|
|
33
|
-
|
|
34
|
-
|
|
59
|
+
}))();
|
|
60
|
+
// Shared for both per-signer pubnonce bytes and aggregate aggnonce bytes. Because it accepts
|
|
61
|
+
// the BIP327 infinity sentinel, so individual pubnonce callers still need
|
|
62
|
+
// an explicit zero-point check.
|
|
63
|
+
const PubNonce = /* @__PURE__ */ (() => P.struct({ R1: compressed, R2: compressed }))();
|
|
64
|
+
// BIP327 stores secnonce as k1 || k2 || pk so Sign can reject reused or
|
|
65
|
+
// invalid nonce limbs and detect when the caller pairs the nonce with a
|
|
66
|
+
// different individual public key than NonceGen used.
|
|
67
|
+
const SecretNonce = /* @__PURE__ */ (() => P.struct({
|
|
68
|
+
k1: scalar,
|
|
69
|
+
k2: scalar,
|
|
70
|
+
publicKey: P.bytes(PUBKEY_LEN),
|
|
71
|
+
}))();
|
|
35
72
|
function abytesOptional(b, ...lengths) {
|
|
73
|
+
// Optional-byte helper: exact-length checks only happen when callers pass them explicitly.
|
|
36
74
|
if (b !== undefined)
|
|
37
75
|
abytes(b, ...lengths);
|
|
38
76
|
}
|
|
39
77
|
function abytesArray(lst, ...lengths) {
|
|
78
|
+
// Element-shape helper only: callers still enforce list-size rules like BIP327's 0 < u < 2^32.
|
|
40
79
|
if (!Array.isArray(lst))
|
|
41
|
-
throw new
|
|
80
|
+
throw new TypeError('expected array');
|
|
42
81
|
lst.forEach((i) => abytes(i, ...lengths));
|
|
43
82
|
}
|
|
44
83
|
function aXonly(lst) {
|
|
84
|
+
// BIP327 tweak modes are strict booleans; callers should run this before
|
|
85
|
+
// branching on isXonly values because plain JS truthiness would accept invalid inputs.
|
|
45
86
|
if (!Array.isArray(lst))
|
|
46
|
-
throw new
|
|
87
|
+
throw new TypeError('expected array');
|
|
47
88
|
lst.forEach((i, j) => {
|
|
48
89
|
if (typeof i !== 'boolean')
|
|
49
|
-
throw new
|
|
90
|
+
throw new TypeError('expected boolean in xOnly array, got' + i + '(' + j + ')');
|
|
50
91
|
});
|
|
51
92
|
}
|
|
93
|
+
// BIP327/BIP340 treat tagged-hash outputs as big-endian integers reduced mod n for
|
|
94
|
+
// coefficients, nonce scalars, and challenges; this helper is that int(hash_tag(...)) mod n step.
|
|
52
95
|
const taggedInt = (tag, ...messages) => Fn.create(Fn.fromBytes(taggedHash(tag, ...messages), true));
|
|
96
|
+
// BIP327 repeatedly says "use x if the point has even Y, otherwise use n - x"; this
|
|
97
|
+
// helper is that parity-conditioned scalar negation for nonce limbs and Q-dependent signs.
|
|
53
98
|
const evenScalar = (p, n) => (hasEven(p.y) ? n : Fn.neg(n));
|
|
54
99
|
// Short utility for compat with reference implementation
|
|
100
|
+
/**
|
|
101
|
+
* Derives a compressed secp256k1 public key from a private key.
|
|
102
|
+
* @param seckey - signer private key
|
|
103
|
+
* @returns Compressed public key bytes.
|
|
104
|
+
* @example
|
|
105
|
+
* Turn a signer's secret key into the compressed key format MuSig2 expects.
|
|
106
|
+
* ```ts
|
|
107
|
+
* import { schnorr } from '@noble/curves/secp256k1.js';
|
|
108
|
+
* import { IndividualPubkey } from '@scure/btc-signer/musig2.js';
|
|
109
|
+
* IndividualPubkey(schnorr.utils.randomSecretKey());
|
|
110
|
+
* ```
|
|
111
|
+
*/
|
|
112
|
+
// BIP327 IndividualPubkey is cbytes(d*G): the 33-byte compressed signer key.
|
|
113
|
+
// Aggregate exports use separate x-only encoding and should not call this helper.
|
|
55
114
|
export function IndividualPubkey(seckey) {
|
|
56
115
|
return secp256k1.getPublicKey(seckey, true);
|
|
57
116
|
}
|
|
58
117
|
// Same, but returns Point
|
|
118
|
+
// Base-point multiply helper for the BIP327 x*G steps below. Point.BASE.multiply rejects 0,
|
|
119
|
+
// so call sites that allow zero scalars need to handle that case explicitly instead of using this.
|
|
59
120
|
function mulBase(n) {
|
|
60
121
|
return Point.BASE.multiply(n);
|
|
61
122
|
}
|
|
123
|
+
// Local alias for BIP327's is_infinite(P): used both for rejecting infinity where cpoint(...)
|
|
124
|
+
// must never yield it and for the "if R' is infinite, use G" nonce-aggregation fallback.
|
|
62
125
|
function isZero(point) {
|
|
63
126
|
return point.equals(Point.ZERO);
|
|
64
127
|
}
|
|
65
128
|
/**
|
|
66
129
|
* Lexicographically sorts an array of public keys.
|
|
67
|
-
* @param publicKeys
|
|
130
|
+
* @param publicKeys - array of public keys
|
|
68
131
|
* @returns A new array containing the sorted public keys.
|
|
69
|
-
* @throws
|
|
132
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
133
|
+
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
134
|
+
* @example
|
|
135
|
+
* Sort participant public keys before building the aggregate MuSig2 key.
|
|
136
|
+
* ```ts
|
|
137
|
+
* import { IndividualPubkey, sortKeys } from '@scure/btc-signer/musig2.js';
|
|
138
|
+
* import { randomPrivateKeyBytes } from '@scure/btc-signer/utils.js';
|
|
139
|
+
* sortKeys([
|
|
140
|
+
* IndividualPubkey(randomPrivateKeyBytes()),
|
|
141
|
+
* IndividualPubkey(randomPrivateKeyBytes()),
|
|
142
|
+
* ]);
|
|
143
|
+
* ```
|
|
70
144
|
*/
|
|
71
145
|
export function sortKeys(publicKeys) {
|
|
146
|
+
// BIP327 KeySort is defined for non-empty signer-key lists, and this helper returns a sorted copy
|
|
147
|
+
// so callers do not lose their original participant ordering as a side effect of key aggregation.
|
|
72
148
|
abytesArray(publicKeys, PUBKEY_LEN);
|
|
73
|
-
|
|
149
|
+
if (!publicKeys.length)
|
|
150
|
+
throw new RangeError('sortKeys: expected non-empty signer key list');
|
|
151
|
+
return Array.from(publicKeys).sort(compareBytes);
|
|
74
152
|
}
|
|
75
153
|
// Finds second distinct key (to make coefficient 1)
|
|
76
154
|
function getSecondKey(publicKeys) {
|
|
155
|
+
// BIP327 GetSecondKey returns bytes(33, 0) when all signer keys are equal; that sentinel
|
|
156
|
+
// means no key hits the special pk' = pk2 coefficient-1 shortcut in the all-equal case.
|
|
77
157
|
abytesArray(publicKeys, PUBKEY_LEN);
|
|
78
158
|
for (let j = 1; j < publicKeys.length; j++)
|
|
79
159
|
if (!equalBytes(publicKeys[j], publicKeys[0]))
|
|
@@ -81,10 +161,14 @@ function getSecondKey(publicKeys) {
|
|
|
81
161
|
return ZERO;
|
|
82
162
|
}
|
|
83
163
|
function keyAggL(publicKeys) {
|
|
164
|
+
// BIP327 HashKeys hashes keys in the caller-provided order. Run KeySort first when
|
|
165
|
+
// the surrounding protocol requires the canonical lexicographic participant ordering.
|
|
84
166
|
abytesArray(publicKeys, PUBKEY_LEN);
|
|
85
167
|
return taggedHash('KeyAgg list', ...publicKeys);
|
|
86
168
|
}
|
|
87
169
|
function keyAggCoeffInternal(publicKey1, publicKey2, L) {
|
|
170
|
+
// BIP327 only short-circuits to coefficient 1 for pk' = pk2. When all keys are equal,
|
|
171
|
+
// pk2 is the all-zero sentinel from GetSecondKey, so every real signer key still hashes.
|
|
88
172
|
abytes(publicKey1, PUBKEY_LEN);
|
|
89
173
|
abytes(publicKey2, PUBKEY_LEN);
|
|
90
174
|
if (equalBytes(publicKey1, publicKey2))
|
|
@@ -93,18 +177,38 @@ function keyAggCoeffInternal(publicKey1, publicKey2, L) {
|
|
|
93
177
|
}
|
|
94
178
|
/**
|
|
95
179
|
* Aggregates multiple public keys using the MuSig2 key aggregation algorithm.
|
|
96
|
-
* @param publicKeys
|
|
97
|
-
* @param tweaks
|
|
98
|
-
* @param isXonly
|
|
99
|
-
* @returns An object containing the aggregate public key, accumulated sign,
|
|
100
|
-
*
|
|
101
|
-
* @throws
|
|
180
|
+
* @param publicKeys - individual participant public keys
|
|
181
|
+
* @param tweaks - optional tweaks applied to the aggregate key
|
|
182
|
+
* @param isXonly - whether each tweak uses x-only semantics
|
|
183
|
+
* @returns An object containing the aggregate public key, accumulated sign,
|
|
184
|
+
* and accumulated tweak.
|
|
185
|
+
* @throws If the input is invalid, such as non-array public keys or mismatched
|
|
186
|
+
* tweak metadata. {@link Error}
|
|
187
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
188
|
+
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
189
|
+
* @throws If any of the public keys are invalid and cannot be processed.
|
|
190
|
+
* {@link InvalidContributionErr}
|
|
191
|
+
* @example
|
|
192
|
+
* Combine all participant public keys into the shared MuSig2 context.
|
|
193
|
+
* ```ts
|
|
194
|
+
* import { IndividualPubkey, keyAggregate } from '@scure/btc-signer/musig2.js';
|
|
195
|
+
* import { randomPrivateKeyBytes } from '@scure/btc-signer/utils.js';
|
|
196
|
+
* keyAggregate([
|
|
197
|
+
* IndividualPubkey(randomPrivateKeyBytes()),
|
|
198
|
+
* IndividualPubkey(randomPrivateKeyBytes()),
|
|
199
|
+
* ]);
|
|
200
|
+
* ```
|
|
102
201
|
*/
|
|
103
202
|
export function keyAggregate(publicKeys, tweaks = [], isXonly = []) {
|
|
203
|
+
// BIP327 KeyAgg inputs require `0 < u < 2^32`, and ApplyTweak consumes a one-for-one
|
|
204
|
+
// list of boolean tweak modes; callers should enforce that public contract here.
|
|
104
205
|
abytesArray(publicKeys, PUBKEY_LEN);
|
|
206
|
+
if (publicKeys.length < 1)
|
|
207
|
+
throw new RangeError('keyAggregate: expected at least 1 public key');
|
|
105
208
|
abytesArray(tweaks, 32);
|
|
209
|
+
aXonly(isXonly);
|
|
106
210
|
if (tweaks.length !== isXonly.length)
|
|
107
|
-
throw new
|
|
211
|
+
throw new RangeError('The tweaks and isXonly arrays must have the same length');
|
|
108
212
|
// Aggregate
|
|
109
213
|
const pk2 = getSecondKey(publicKeys);
|
|
110
214
|
const L = keyAggL(publicKeys);
|
|
@@ -124,8 +228,11 @@ export function keyAggregate(publicKeys, tweaks = [], isXonly = []) {
|
|
|
124
228
|
// Apply tweaks
|
|
125
229
|
for (let i = 0; i < tweaks.length; i++) {
|
|
126
230
|
const g = isXonly[i] && !hasEven(aggPublicKey.y) ? Fn.neg(Fn.ONE) : Fn.ONE;
|
|
127
|
-
|
|
128
|
-
|
|
231
|
+
// BIP327 ApplyTweak: `Let t = int(tweak); fail if t >= n`, so 32-byte zero tweaks are valid.
|
|
232
|
+
const t = Fn.fromBytes(tweaks[i], true);
|
|
233
|
+
if (!Fn.isValid(t))
|
|
234
|
+
throw new RangeError('invalid scalar: out of range');
|
|
235
|
+
aggPublicKey = aggPublicKey.multiply(g).add(Fn.is0(t) ? Point.ZERO : mulBase(t));
|
|
129
236
|
if (isZero(aggPublicKey))
|
|
130
237
|
throw new Error('The result of tweaking cannot be infinity');
|
|
131
238
|
gAcc = Fn.mul(g, gAcc);
|
|
@@ -135,13 +242,28 @@ export function keyAggregate(publicKeys, tweaks = [], isXonly = []) {
|
|
|
135
242
|
}
|
|
136
243
|
/**
|
|
137
244
|
* Exports the aggregate public key to a byte array.
|
|
138
|
-
* @param ctx
|
|
245
|
+
* @param ctx - result of {@link keyAggregate}
|
|
139
246
|
* @returns The aggregate public key as a byte array.
|
|
247
|
+
* @example
|
|
248
|
+
* Serialize the aggregate key after building the MuSig2 context.
|
|
249
|
+
* ```ts
|
|
250
|
+
* import { IndividualPubkey, keyAggregate, keyAggExport } from '@scure/btc-signer/musig2.js';
|
|
251
|
+
* import { randomPrivateKeyBytes } from '@scure/btc-signer/utils.js';
|
|
252
|
+
* const ctx = keyAggregate([
|
|
253
|
+
* IndividualPubkey(randomPrivateKeyBytes()),
|
|
254
|
+
* IndividualPubkey(randomPrivateKeyBytes()),
|
|
255
|
+
* ]);
|
|
256
|
+
* keyAggExport(ctx);
|
|
257
|
+
* ```
|
|
140
258
|
*/
|
|
141
259
|
export function keyAggExport(ctx) {
|
|
260
|
+
// BIP327 GetXonlyPubkey returns xbytes(Q), so this is the 32-byte x-only aggregate key
|
|
261
|
+
// instead of the 33-byte compressed SEC1 form.
|
|
142
262
|
return pointToBytes(ctx.aggPublicKey);
|
|
143
263
|
}
|
|
144
264
|
function aux(secret, rand) {
|
|
265
|
+
// BIP327 NonceGen and DeterministicSign blind the caller-provided 32-byte randomness with
|
|
266
|
+
// hash_MuSig/aux(rand) before hashing the session inputs into nonce scalars.
|
|
145
267
|
const rand2 = taggedHash('MuSig/aux', rand);
|
|
146
268
|
if (secret.length !== rand2.length)
|
|
147
269
|
throw new Error('Cannot XOR arrays of different lengths');
|
|
@@ -150,29 +272,44 @@ function aux(secret, rand) {
|
|
|
150
272
|
res[i] = secret[i] ^ rand2[i];
|
|
151
273
|
return res;
|
|
152
274
|
}
|
|
153
|
-
const nonceHash = (rand, publicKey, aggPublicKey, i, msgPrefixed, extraIn) =>
|
|
275
|
+
const nonceHash = (rand, publicKey, aggPublicKey, i, msgPrefixed, extraIn) =>
|
|
276
|
+
// BIP327 NonceGen hashes rand || len(pk) || pk || len(aggpk) || aggpk || m_prefixed ||
|
|
277
|
+
// len(extra_in) || extra_in || bytes(1, i - 1), so callers pass i = 0/1 here.
|
|
278
|
+
taggedInt('MuSig/nonce', rand, new Uint8Array([publicKey.length]), publicKey, new Uint8Array([aggPublicKey.length]), aggPublicKey, msgPrefixed, numberToBytesBE(extraIn.length, 4), extraIn, new Uint8Array([i]));
|
|
154
279
|
/**
|
|
155
280
|
* Generates a nonce pair (public and secret) for MuSig2 signing.
|
|
156
|
-
* @param publicKey
|
|
157
|
-
* @param secretKey
|
|
158
|
-
* @param aggPublicKey
|
|
159
|
-
* @param msg
|
|
160
|
-
* @param extraIn
|
|
161
|
-
* @param rand
|
|
281
|
+
* @param publicKey - individual public key of the signer
|
|
282
|
+
* @param secretKey - optional secret key, mixed in to blind the randomness source
|
|
283
|
+
* @param aggPublicKey - aggregate public key of all signers
|
|
284
|
+
* @param msg - message to be signed
|
|
285
|
+
* @param extraIn - extra input mixed into nonce generation
|
|
286
|
+
* @param rand - random 32-byte seed for the nonce derivation
|
|
162
287
|
* @returns An object containing the public and secret nonces.
|
|
163
|
-
* @throws
|
|
288
|
+
* @throws If the input is invalid, such as non-array public keys or malformed
|
|
289
|
+
* nonce inputs. {@link Error}
|
|
290
|
+
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
291
|
+
* @example
|
|
292
|
+
* Generate the signer-local nonce pair before sharing the public nonce with peers.
|
|
293
|
+
* ```ts
|
|
294
|
+
* import { IndividualPubkey, nonceGen } from '@scure/btc-signer/musig2.js';
|
|
295
|
+
* import { randomPrivateKeyBytes } from '@scure/btc-signer/utils.js';
|
|
296
|
+
* const secretKey = randomPrivateKeyBytes();
|
|
297
|
+
* nonceGen(IndividualPubkey(secretKey), secretKey);
|
|
298
|
+
* ```
|
|
164
299
|
*/
|
|
165
300
|
export function nonceGen(publicKey, secretKey, aggPublicKey = new Uint8Array(0), msg, extraIn = new Uint8Array(0), rand = randomBytes(32)) {
|
|
166
301
|
abytes(publicKey, PUBKEY_LEN);
|
|
167
302
|
abytesOptional(secretKey, 32);
|
|
168
303
|
abytes(aggPublicKey);
|
|
169
304
|
if (![0, 32].includes(aggPublicKey.length))
|
|
170
|
-
throw new
|
|
305
|
+
throw new RangeError('wrong aggPublicKey');
|
|
171
306
|
abytesOptional(msg);
|
|
172
307
|
abytes(extraIn);
|
|
173
308
|
abytes(rand, 32);
|
|
174
309
|
if (secretKey !== undefined)
|
|
175
310
|
rand = aux(secretKey, rand);
|
|
311
|
+
// BIP327 distinguishes an omitted message from an explicitly empty one so the two cases
|
|
312
|
+
// derive different nonces even when every other session parameter matches.
|
|
176
313
|
const msgPrefixed = msg !== undefined
|
|
177
314
|
? concatBytes(Uint8Array.of(1), numberToBytesBE(msg.length, 8), msg)
|
|
178
315
|
: Uint8Array.of(0);
|
|
@@ -185,13 +322,33 @@ export function nonceGen(publicKey, secretKey, aggPublicKey = new Uint8Array(0),
|
|
|
185
322
|
}
|
|
186
323
|
/**
|
|
187
324
|
* Aggregates public nonces from multiple signers into a single aggregate nonce.
|
|
188
|
-
* @param pubNonces
|
|
325
|
+
* @param pubNonces - public nonces from each signer
|
|
189
326
|
* @returns The aggregate nonce (Uint8Array).
|
|
190
|
-
* @throws
|
|
191
|
-
* @throws
|
|
327
|
+
* @throws If the nonce payloads are malformed or contain infinity points. {@link Error}
|
|
328
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
329
|
+
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
330
|
+
* @throws If any of the public nonces are invalid and cannot be processed.
|
|
331
|
+
* {@link InvalidContributionErr}
|
|
332
|
+
* @example
|
|
333
|
+
* Combine all participant public nonces before building the session.
|
|
334
|
+
* ```ts
|
|
335
|
+
* import { IndividualPubkey, nonceAggregate, nonceGen } from '@scure/btc-signer/musig2.js';
|
|
336
|
+
* import { randomPrivateKeyBytes } from '@scure/btc-signer/utils.js';
|
|
337
|
+
* const alice = randomPrivateKeyBytes();
|
|
338
|
+
* const bob = randomPrivateKeyBytes();
|
|
339
|
+
* nonceAggregate([
|
|
340
|
+
* nonceGen(IndividualPubkey(alice), alice).public,
|
|
341
|
+
* nonceGen(IndividualPubkey(bob), bob).public,
|
|
342
|
+
* ]);
|
|
343
|
+
* ```
|
|
192
344
|
*/
|
|
193
345
|
export function nonceAggregate(pubNonces) {
|
|
194
346
|
abytesArray(pubNonces, 66);
|
|
347
|
+
// BIP327 NonceAgg input: "The number u of pubnonces with 0 < u < 2^32".
|
|
348
|
+
// cbytes_ext uses bytes(33, 0) as the infinity sentinel for summed real contributions,
|
|
349
|
+
// not as an "empty aggregate" encoding.
|
|
350
|
+
if (pubNonces.length < 1)
|
|
351
|
+
throw new RangeError('nonceAggregate: expected at least 1 public nonce');
|
|
195
352
|
let R1 = Point.ZERO;
|
|
196
353
|
let R2 = Point.ZERO;
|
|
197
354
|
for (let i = 0; i < pubNonces.length; i++) {
|
|
@@ -210,8 +367,41 @@ export function nonceAggregate(pubNonces) {
|
|
|
210
367
|
return PubNonce.encode({ R1, R2 });
|
|
211
368
|
}
|
|
212
369
|
// Class allows us re-use pre-computed stuff
|
|
213
|
-
// NOTE: it would be nice to aggregate nonce in
|
|
370
|
+
// NOTE: it would be nice to aggregate nonce in constructor, but there is a
|
|
371
|
+
// test that passes an already aggregated nonce here.
|
|
372
|
+
/**
|
|
373
|
+
* MuSig2 session context for partial signing and aggregation.
|
|
374
|
+
* @param aggNonce - aggregate nonce from all participants combined
|
|
375
|
+
* @param publicKeys - all participant public keys
|
|
376
|
+
* @param msg - message to be signed
|
|
377
|
+
* @param tweaks - optional tweaks applied to the aggregate public key
|
|
378
|
+
* @param isXonly - whether each tweak uses x-only semantics
|
|
379
|
+
* @example
|
|
380
|
+
* Build one session object and reuse it for all partial-signature steps.
|
|
381
|
+
* ```ts
|
|
382
|
+
* import {
|
|
383
|
+
* IndividualPubkey,
|
|
384
|
+
* Session,
|
|
385
|
+
* keyAggregate,
|
|
386
|
+
* keyAggExport,
|
|
387
|
+
* nonceAggregate,
|
|
388
|
+
* nonceGen,
|
|
389
|
+
* } from '@scure/btc-signer/musig2.js';
|
|
390
|
+
* import { randomPrivateKeyBytes } from '@scure/btc-signer/utils.js';
|
|
391
|
+
* const alice = randomPrivateKeyBytes();
|
|
392
|
+
* const bob = randomPrivateKeyBytes();
|
|
393
|
+
* const publicKeys = [IndividualPubkey(alice), IndividualPubkey(bob)];
|
|
394
|
+
* const agg = keyAggregate(publicKeys);
|
|
395
|
+
* const aggNonce = nonceAggregate([
|
|
396
|
+
* nonceGen(publicKeys[0], alice, keyAggExport(agg)).public,
|
|
397
|
+
* nonceGen(publicKeys[1], bob, keyAggExport(agg)).public,
|
|
398
|
+
* ]);
|
|
399
|
+
* const msg = new TextEncoder().encode('hello musig2');
|
|
400
|
+
* new Session(aggNonce, publicKeys, msg);
|
|
401
|
+
* ```
|
|
402
|
+
*/
|
|
214
403
|
export class Session {
|
|
404
|
+
aggNonce;
|
|
215
405
|
publicKeys;
|
|
216
406
|
Q;
|
|
217
407
|
gAcc;
|
|
@@ -227,12 +417,12 @@ export class Session {
|
|
|
227
417
|
* Constructor for the Session class.
|
|
228
418
|
* It precomputes and stores values derived from the aggregate nonce, public keys,
|
|
229
419
|
* message, and optional tweaks, optimizing the signing process.
|
|
230
|
-
* @param aggNonce
|
|
231
|
-
* @param publicKeys
|
|
232
|
-
* @param msg
|
|
233
|
-
* @param tweaks
|
|
234
|
-
* @param isXonly
|
|
235
|
-
* @throws
|
|
420
|
+
* @param aggNonce - aggregate nonce from all participants combined
|
|
421
|
+
* @param publicKeys - participant public keys
|
|
422
|
+
* @param msg - message to be signed
|
|
423
|
+
* @param tweaks - tweaks applied to the aggregate public key
|
|
424
|
+
* @param isXonly - whether each tweak uses x-only semantics
|
|
425
|
+
* @throws If the input is invalid, such as wrong array sizes or lengths. {@link Error}
|
|
236
426
|
*/
|
|
237
427
|
constructor(aggNonce, publicKeys, msg, tweaks = [], isXonly = []) {
|
|
238
428
|
abytesArray(publicKeys, 33);
|
|
@@ -240,10 +430,15 @@ export class Session {
|
|
|
240
430
|
aXonly(isXonly);
|
|
241
431
|
abytes(msg);
|
|
242
432
|
if (tweaks.length !== isXonly.length)
|
|
243
|
-
throw new
|
|
433
|
+
throw new RangeError('The tweaks and isXonly arrays must have the same length');
|
|
244
434
|
const { aggPublicKey, gAcc, tweakAcc } = keyAggregate(publicKeys, tweaks, isXonly);
|
|
245
435
|
const { R1, R2 } = PubNonce.decode(aggNonce);
|
|
246
|
-
|
|
436
|
+
// BIP327 requires cached session-context state to be protected from third-party mutation,
|
|
437
|
+
// so Session must own detached copies of the caller-provided arrays and byte entries.
|
|
438
|
+
// Use Uint8Array.from(...) here instead of .slice() because Node Buffer overrides slice()
|
|
439
|
+
// to return a shared-memory view, which would let later caller mutation rewrite session state.
|
|
440
|
+
this.aggNonce = Uint8Array.from(aggNonce);
|
|
441
|
+
this.publicKeys = publicKeys.map((pk) => Uint8Array.from(pk));
|
|
247
442
|
this.Q = aggPublicKey;
|
|
248
443
|
this.gAcc = gAcc;
|
|
249
444
|
this.tweakAcc = tweakAcc;
|
|
@@ -251,21 +446,23 @@ export class Session {
|
|
|
251
446
|
const R = R1.add(R2.multiply(this.b));
|
|
252
447
|
this.R = isZero(R) ? Point.BASE : R;
|
|
253
448
|
this.e = taggedInt('BIP0340/challenge', pointToBytes(this.R), pointToBytes(aggPublicKey), msg);
|
|
254
|
-
this.tweaks = tweaks;
|
|
255
|
-
this.isXonly = isXonly;
|
|
256
|
-
this.L = keyAggL(publicKeys);
|
|
257
|
-
this.secondKey = getSecondKey(publicKeys);
|
|
449
|
+
this.tweaks = tweaks.map((t) => Uint8Array.from(t));
|
|
450
|
+
this.isXonly = isXonly.slice();
|
|
451
|
+
this.L = keyAggL(this.publicKeys);
|
|
452
|
+
this.secondKey = getSecondKey(this.publicKeys);
|
|
258
453
|
}
|
|
259
454
|
/**
|
|
260
455
|
* Calculates the key aggregation coefficient for a given point.
|
|
261
456
|
* @private
|
|
262
|
-
* @param P
|
|
457
|
+
* @param P - point to calculate the coefficient for
|
|
263
458
|
* @returns The key aggregation coefficient as a bigint.
|
|
264
|
-
* @throws
|
|
459
|
+
* @throws If the provided public key is not included in the list of pubkeys. {@link Error}
|
|
265
460
|
*/
|
|
266
461
|
getSessionKeyAggCoeff(P) {
|
|
267
462
|
const { publicKeys } = this;
|
|
268
463
|
const pk = P.toBytes(true);
|
|
464
|
+
// BIP327 GetSessionKeyAggCoeff fails if cbytes(P) is not one of the session pubkeys;
|
|
465
|
+
// once membership is confirmed, the cached L/secondKey state is enough to derive KeyAggCoeff.
|
|
269
466
|
const found = publicKeys.some((p) => equalBytes(p, pk));
|
|
270
467
|
if (!found)
|
|
271
468
|
throw new Error("The signer's pubkey must be included in the list of pubkeys");
|
|
@@ -276,33 +473,39 @@ export class Session {
|
|
|
276
473
|
const s = Fn.fromBytes(partialSig, true);
|
|
277
474
|
if (!Fn.isValid(s))
|
|
278
475
|
return false;
|
|
476
|
+
// BIP327 PartialSigVerifyInternal: `Let s = int(psig); fail if s >= n`, so s=0 must stay
|
|
477
|
+
// in the public verification equation and return false on mismatch instead of throwing.
|
|
279
478
|
const { R1, R2 } = PubNonce.decode(publicNonce);
|
|
280
479
|
const Re_s_ = R1.add(R2.multiply(b));
|
|
281
480
|
const Re_s = hasEven(R.y) ? Re_s_ : Re_s_.negate();
|
|
282
481
|
const P = Point.fromBytes(publicKey);
|
|
283
482
|
const a = this.getSessionKeyAggCoeff(P);
|
|
284
483
|
const g = Fn.mul(evenScalar(Q, 1n), gAcc);
|
|
285
|
-
const left =
|
|
484
|
+
const left = Point.BASE.multiplyUnsafe(s);
|
|
286
485
|
const right = Re_s.add(P.multiply(Fn.mul(e, Fn.mul(a, g))));
|
|
287
486
|
return left.equals(right);
|
|
288
487
|
}
|
|
289
488
|
/**
|
|
290
|
-
* Generates a partial signature for a given message, secret nonce,
|
|
291
|
-
*
|
|
292
|
-
* @param
|
|
293
|
-
* @param
|
|
294
|
-
* @param fastSign if
|
|
489
|
+
* Generates a partial signature for a given message, secret nonce,
|
|
490
|
+
* secret key, and session context.
|
|
491
|
+
* @param secretNonce - secret nonce for this signing session; it is zeroed after use
|
|
492
|
+
* @param secret - secret key of the signer
|
|
493
|
+
* @param fastSign - if `true`, skip the self-verification pass
|
|
295
494
|
* @returns The partial signature (Uint8Array).
|
|
296
|
-
* @throws
|
|
495
|
+
* @throws If the input is invalid, such as wrong array sizes,
|
|
496
|
+
* invalid nonce, or invalid secret key. {@link Error}
|
|
297
497
|
*/
|
|
298
498
|
sign(secretNonce, secret, fastSign = false) {
|
|
299
499
|
abytes(secret, 32);
|
|
300
500
|
if (typeof fastSign !== 'boolean')
|
|
301
|
-
throw new
|
|
501
|
+
throw new TypeError('expected boolean');
|
|
302
502
|
const { Q, gAcc, b, R, e } = this;
|
|
303
503
|
const { k1: k1_, k2: k2_, publicKey: originalPk } = SecretNonce.decode(secretNonce);
|
|
304
504
|
// zero-out the first 64 bytes of secretNonce so it cannot be reused
|
|
305
|
-
//
|
|
505
|
+
// BIP327 permits overwriting the first 64 secnonce bytes after reading k1/k2 so
|
|
506
|
+
// accidental reuse fails fast instead of reusing the same nonce scalars.
|
|
507
|
+
// TODO: this was in the reference implementation, but feels very broken.
|
|
508
|
+
// Modifying input arguments is pretty bad.
|
|
306
509
|
secretNonce.fill(0, 0, 64);
|
|
307
510
|
if (!Fn.isValid(k1_))
|
|
308
511
|
throw new Error('wrong k1');
|
|
@@ -336,15 +539,12 @@ export class Session {
|
|
|
336
539
|
}
|
|
337
540
|
/**
|
|
338
541
|
* Verifies a partial signature against the aggregate public key and other session parameters.
|
|
339
|
-
* @param partialSig
|
|
340
|
-
* @param pubNonces
|
|
341
|
-
* @param
|
|
342
|
-
* @
|
|
343
|
-
* @
|
|
344
|
-
*
|
|
345
|
-
* @param i The index of the signer whose partial signature is being verified.
|
|
346
|
-
* @returns True if the partial signature is valid, false otherwise.
|
|
347
|
-
* @throws {Error} If the input is invalid, such as non array partialSig, pubNonces, pubKeys, tweaks.
|
|
542
|
+
* @param partialSig - partial signature to verify
|
|
543
|
+
* @param pubNonces - public nonces from each signer
|
|
544
|
+
* @param i - index of the signer whose partial signature is being verified
|
|
545
|
+
* @returns `true` if the partial signature is valid.
|
|
546
|
+
* @throws If the input is invalid, such as non-array partial signatures
|
|
547
|
+
* or mismatched nonce counts. {@link Error}
|
|
348
548
|
*/
|
|
349
549
|
partialSigVerify(partialSig, pubNonces, i) {
|
|
350
550
|
const { publicKeys, tweaks, isXonly } = this;
|
|
@@ -355,22 +555,32 @@ export class Session {
|
|
|
355
555
|
aXonly(isXonly);
|
|
356
556
|
anumber(i);
|
|
357
557
|
if (pubNonces.length !== publicKeys.length)
|
|
358
|
-
throw new
|
|
558
|
+
throw new RangeError('The pubNonces and publicKeys arrays must have the same length');
|
|
359
559
|
if (tweaks.length !== isXonly.length)
|
|
360
|
-
throw new
|
|
560
|
+
throw new RangeError('The tweaks and isXonly arrays must have the same length');
|
|
561
|
+
// BIP327 PartialSigVerify rebuilds session_ctx from aggnonce = NonceAgg(pubnonce_1..u),
|
|
562
|
+
// and GetSessionValues derives b and R from that aggnonce. This Session caches b/R/e from
|
|
563
|
+
// the constructor aggNonce, so a stale Session would otherwise accept mismatched pubNonces
|
|
564
|
+
// as long as pubNonces[i] still matched the signer slot.
|
|
361
565
|
if (i >= pubNonces.length)
|
|
362
|
-
throw new
|
|
566
|
+
throw new RangeError('index outside of pubKeys/pubNonces');
|
|
567
|
+
if (!equalBytes(this.aggNonce, nonceAggregate(pubNonces)))
|
|
568
|
+
return false;
|
|
363
569
|
return this.partialSigVerifyInternal(partialSig, pubNonces[i], publicKeys[i]);
|
|
364
570
|
}
|
|
365
571
|
/**
|
|
366
572
|
* Aggregates partial signatures from multiple signers into a single final signature.
|
|
367
|
-
* @param partialSigs
|
|
368
|
-
* @param sessionCtx The session context containing all necessary information for signing.
|
|
573
|
+
* @param partialSigs - partial signatures from each signer
|
|
369
574
|
* @returns The final aggregate signature (Uint8Array).
|
|
370
|
-
* @throws
|
|
575
|
+
* @throws If the input is invalid, such as wrong array sizes or malformed
|
|
576
|
+
* signatures. {@link Error}
|
|
371
577
|
*/
|
|
372
578
|
partialSigAgg(partialSigs) {
|
|
373
579
|
abytesArray(partialSigs, 32);
|
|
580
|
+
// BIP327 PartialSigAgg is defined for a non-empty psig_1..u list tied to this session_ctx;
|
|
581
|
+
// [] is not a valid aggregate-signature input even though the sum starts from zero.
|
|
582
|
+
if (partialSigs.length < 1)
|
|
583
|
+
throw new RangeError('partialSigs.length must be >= 1');
|
|
374
584
|
const { Q, tweakAcc, R, e } = this;
|
|
375
585
|
let s = 0n;
|
|
376
586
|
for (let i = 0; i < partialSigs.length; i++) {
|
|
@@ -384,17 +594,42 @@ export class Session {
|
|
|
384
594
|
return concatBytes(pointToBytes(R), Fn.toBytes(s));
|
|
385
595
|
}
|
|
386
596
|
}
|
|
387
|
-
const deterministicNonceHash = (secret, aggOtherNonce, aggPublicKey, msg, i) => taggedInt('MuSig/deterministic/nonce', secret, aggOtherNonce, aggPublicKey, numberToBytesBE(msg.length, 8), msg,
|
|
597
|
+
const deterministicNonceHash = (secret, aggOtherNonce, aggPublicKey, msg, i) => taggedInt('MuSig/deterministic/nonce', secret, aggOtherNonce, aggPublicKey, numberToBytesBE(msg.length, 8), msg,
|
|
598
|
+
// BIP327 hashes bytes(1, i - 1) for i=1,2; callers pass 0/1 directly here.
|
|
599
|
+
new Uint8Array([i]));
|
|
388
600
|
/**
|
|
389
601
|
* Generates a nonce pair and partial signature deterministically for a single signer.
|
|
390
|
-
* @param secret
|
|
391
|
-
* @param aggOtherNonce
|
|
392
|
-
* @param publicKeys
|
|
393
|
-
* @param
|
|
394
|
-
* @param
|
|
395
|
-
* @param
|
|
396
|
-
* @param rand
|
|
602
|
+
* @param secret - secret key of the signer
|
|
603
|
+
* @param aggOtherNonce - aggregate public nonce of the other signers
|
|
604
|
+
* @param publicKeys - public keys of all signers
|
|
605
|
+
* @param msg - message to be signed
|
|
606
|
+
* @param tweaks - tweaks applied to the aggregate public key
|
|
607
|
+
* @param isXonly - whether each tweak uses x-only semantics
|
|
608
|
+
* @param rand - optional extra randomness
|
|
609
|
+
* @param fastSign - whether to skip partial-signature self-verification
|
|
397
610
|
* @returns An object containing the public nonce and partial signature.
|
|
611
|
+
* @throws If MuSig2 session setup or signing fails. {@link Error}
|
|
612
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
613
|
+
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
614
|
+
* @throws If one of the aggregated public keys or nonces is invalid. {@link InvalidContributionErr}
|
|
615
|
+
* @example
|
|
616
|
+
* Generate one signer's deterministic nonce and partial signature in one step.
|
|
617
|
+
* ```ts
|
|
618
|
+
* import {
|
|
619
|
+
* IndividualPubkey,
|
|
620
|
+
* deterministicSign,
|
|
621
|
+
* keyAggregate,
|
|
622
|
+
* keyAggExport,
|
|
623
|
+
* nonceGen,
|
|
624
|
+
* } from '@scure/btc-signer/musig2.js';
|
|
625
|
+
* import { randomPrivateKeyBytes } from '@scure/btc-signer/utils.js';
|
|
626
|
+
* const alice = randomPrivateKeyBytes();
|
|
627
|
+
* const bob = randomPrivateKeyBytes();
|
|
628
|
+
* const publicKeys = [IndividualPubkey(alice), IndividualPubkey(bob)];
|
|
629
|
+
* const agg = keyAggregate(publicKeys);
|
|
630
|
+
* const otherNonce = nonceGen(publicKeys[1], bob, keyAggExport(agg)).public;
|
|
631
|
+
* deterministicSign(alice, otherNonce, publicKeys, new TextEncoder().encode('hello musig2'));
|
|
632
|
+
* ```
|
|
398
633
|
*/
|
|
399
634
|
export function deterministicSign(secret, aggOtherNonce, publicKeys, msg, tweaks = [], isXonly = [], rand, fastSign = false) {
|
|
400
635
|
abytes(secret, 32);
|
|
@@ -402,7 +637,9 @@ export function deterministicSign(secret, aggOtherNonce, publicKeys, msg, tweaks
|
|
|
402
637
|
abytesArray(publicKeys, PUBKEY_LEN);
|
|
403
638
|
abytesArray(tweaks, 32);
|
|
404
639
|
abytes(msg);
|
|
405
|
-
abytesOptional(rand);
|
|
640
|
+
abytesOptional(rand, 32);
|
|
641
|
+
// BIP327 DeterministicSign input bullet: `The auxiliary randomness rand: a 32-byte array`
|
|
642
|
+
// when present, so this optional argument still needs the exact-length check here.
|
|
406
643
|
const sk = rand !== undefined ? aux(secret, rand) : secret;
|
|
407
644
|
const aggPublicKey = keyAggExport(keyAggregate(publicKeys, tweaks, isXonly));
|
|
408
645
|
const k1 = deterministicNonceHash(sk, aggOtherNonce, aggPublicKey, msg, 0);
|