@scure/btc-signer 2.0.1 → 2.3.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/src/p2p.ts CHANGED
@@ -22,19 +22,34 @@ import { FpIsSquare } from '@noble/curves/abstract/modular.js';
22
22
  import { concatBytes, abytes } from '@noble/curves/utils.js';
23
23
  import { schnorr, secp256k1 } from '@noble/curves/secp256k1.js';
24
24
  import { randomBytes } from '@noble/hashes/utils.js';
25
- import { tagSchnorr, type Bytes } from './utils.ts';
25
+ import { tagSchnorr, type Bytes, type TArg, type TRet } from './utils.ts';
26
26
 
27
+ // BIP324's EllSwift formulas use full secp256k1 points for priv*G and x-only ECDH
28
+ // before exporting x coordinates or x-only bytes.
27
29
  const Point = secp256k1.Point;
30
+ // BIP324 defines XSwiftEC over integers modulo secp256k1's field prime p, so the
31
+ // EllSwift u/t/x arithmetic and 32-byte field encodings in this file all go through Point.Fp.
28
32
  const Fp = Point.Fp;
33
+ // EllSwift private scalars use secp256k1's subgroup order n, not the field prime p used
34
+ // by Point.Fp; Point.Fn is the generic scalar field object, not a secret-key validator.
29
35
  const Fn = Point.Fn;
30
36
  const _1n = BigInt(1);
31
37
  const _2n = BigInt(2);
32
38
 
39
+ // BIP324's XSwiftEC uses c = sqrt(-3) mod p and chooses the square root that is
40
+ // itself a square, which is what Fp.sqrt(Fp.create(-3)) returns here.
33
41
  const MINUS_3_SQRT = Fp.sqrt(Fp.create(BigInt(-3)));
34
42
  const _3n = BigInt(3);
35
43
  const _4n = BigInt(4);
36
44
  const _7n = BigInt(7);
45
+ // Precomputed 1/2 mod p: turns the frequent "divide by 2" steps of XSwiftEC/XSwiftECInv
46
+ // into single multiplications instead of one modular inversion per call.
47
+ const INV_2 = Fp.inv(Fp.create(_2n));
48
+ // This is the "lift_x(x) succeeds" predicate for field-normalized x values.
49
+ // Raw x >= p would need the full BIP340 range check before reducing modulo p.
37
50
  const isValidX = (x: bigint) => FpIsSquare(Fp, Fp.add(Fp.mul(Fp.mul(x, x), x), _7n));
51
+ // BIP324's "return None if the square root does not exist" branches are modeled with
52
+ // undefined here; current callers only pass field-normalized values from Fp arithmetic.
38
53
  const trySqrt = (x: bigint): bigint | void => {
39
54
  try {
40
55
  return Fp.sqrt(x);
@@ -45,9 +60,20 @@ const trySqrt = (x: bigint): bigint | void => {
45
60
  * Experimental ElligatorSwift implementation:
46
61
  * Schnorr-like x-only ECDH with public keys indistinguishable from uniformly random bytes.
47
62
  * Documented in BIP324.
63
+ * @example
64
+ * Encode an x-only secp256k1 public key into the 64-byte BIP324 pseudorandom form.
65
+ * ```ts
66
+ * import { bytesToNumberBE } from '@noble/curves/utils.js';
67
+ * import { schnorr } from '@noble/curves/secp256k1.js';
68
+ * import { elligatorSwift } from '@scure/btc-signer/p2p.js';
69
+ * const secret = schnorr.utils.randomSecretKey();
70
+ * const encoded = elligatorSwift.encode(bytesToNumberBE(schnorr.getPublicKey(secret)));
71
+ * elligatorSwift.decode(encoded);
72
+ * ```
48
73
  */
49
- export const elligatorSwift = {
74
+ export const elligatorSwift = /* @__PURE__ */ Object.freeze({
50
75
  // (internal stuff, exported for tests only): decode(u, _inv(x, u)) = x
76
+ // Returns the case-selected BIP324 XSwiftECInv representative, or undefined for None.
51
77
  _inv: (x: bigint, u: bigint, ellCase: number): bigint | void => {
52
78
  if (!Number.isSafeInteger(ellCase) || ellCase < 0 || ellCase > 7)
53
79
  throw new Error(`elligatorSwift._inv: wrong case=${ellCase}`);
@@ -68,7 +94,7 @@ export const elligatorSwift = {
68
94
  const r = trySqrt(Fp.mul(Fp.neg(s), Fp.add(Fp.mul(_4n, t0), t1)));
69
95
  if (r === undefined) return; // [2 condition]
70
96
  if (ellCase & 1 && Fp.is0(r)) return;
71
- v = Fp.div(Fp.add(Fp.neg(u), Fp.div(r, s)), _2n); // v = (-u + r / s) / 2
97
+ v = Fp.mul(Fp.add(Fp.neg(u), Fp.div(r, s)), INV_2); // v = (-u + r / s) / 2
72
98
  }
73
99
  const w = trySqrt(s);
74
100
  if (w === undefined) return; // [3 condition]
@@ -76,24 +102,39 @@ export const elligatorSwift = {
76
102
  const t0 = last & 1 ? Fp.add(_1n, MINUS_3_SQRT) : Fp.sub(_1n, MINUS_3_SQRT);
77
103
  const w0 = last === 0 || last === 5 ? Fp.neg(w) : w; // -w | w
78
104
  // w0 * (u * t0 / 2 + v)
79
- return Fp.mul(w0, Fp.add(Fp.div(Fp.mul(u, t0), _2n), v));
105
+ return Fp.mul(w0, Fp.add(Fp.mul(Fp.mul(u, t0), INV_2), v));
80
106
  },
81
107
  // Encode public key (point or x coordinate bigint) into 64-byte pseudorandom encoding
82
- encode: (x: bigint): Uint8Array => {
108
+ // BIP324 samples encodings for x(P), so callers must pass a curve X coordinate in 0..p-1;
109
+ // without an explicit guard, the field helpers below interpret out-of-range x modulo p.
110
+ encode: (x: bigint): TRet<Uint8Array> => {
111
+ // BIP324 XSwiftEC uses field elements in `0..p-1`, and ellswift_create passes `XElligatorSwift(x(P))`,
112
+ // so encode() must reject out-of-range x instead of silently reducing a different bigint modulo p.
113
+ if (!Fp.isValid(x))
114
+ throw new RangeError('elligatorSwift.encode: expected x coordinate in range 0..p-1');
115
+ // Off-curve x cannot round-trip: decode() only returns lift_x-able candidates, so
116
+ // the loop below would silently emit an encoding of a *different* public key.
117
+ if (!isValidX(x))
118
+ throw new RangeError('elligatorSwift.encode: expected x coordinate of a curve point');
83
119
  // 200k test cycles per keygen: avg=4 max=48
84
120
  // seems too much, but same as for reference implementation
85
121
  while (true) {
86
- // random scalar 1..Fp.ORDER
87
- const u = Fp.create(Fp.fromBytes(secp256k1.utils.randomSecretKey()));
122
+ // Random field element 1..p-1: BIP324 samples u over the whole field (the previous
123
+ // secret-key sampler silently restricted u to 1..n-1); decode() remaps u = 0, so
124
+ // zero cannot round-trip and is skipped.
125
+ const u = Fp.create(Fp.fromBytes(randomBytes(32), true));
126
+ if (Fp.is0(u)) continue;
88
127
  const ellCase = randomBytes(1)[0] & 7; // [0..8)
89
128
  const t = elligatorSwift._inv(x, u, ellCase);
90
129
  if (!t) continue;
91
- return concatBytes(Fp.toBytes(u), Fp.toBytes(t));
130
+ return concatBytes(Fp.toBytes(u), Fp.toBytes(t)) as TRet<Uint8Array>;
92
131
  }
93
132
  },
94
133
  // Decode elligatorSwift point to xonly
95
- decode: (data: Uint8Array): Uint8Array => {
134
+ decode: (data: TArg<Uint8Array>): TRet<Uint8Array> => {
96
135
  const _data = abytes(data, 64, 'data');
136
+ // BIP324 interprets both 32-byte halves as integers modulo p before the
137
+ // XSwiftEC remaps below, so arbitrary 64-byte inputs are valid here.
97
138
  let u = Fp.create(Fp.fromBytes(_data.subarray(0, 32), true));
98
139
  let t = Fp.create(Fp.fromBytes(_data.subarray(32, 64), true));
99
140
  if (Fp.is0(u)) u = Fp.create(_1n);
@@ -108,39 +149,50 @@ export const elligatorSwift = {
108
149
  const y = Fp.div(Fp.add(x, t), Fp.mul(MINUS_3_SQRT, u));
109
150
  // try different cases
110
151
  let res = Fp.add(u, Fp.mul(Fp.mul(y, y), _4n)); // u + 4 * Y ** 2,
111
- if (isValidX(res)) return Fp.toBytes(res);
112
- res = Fp.div(Fp.sub(Fp.div(Fp.neg(x), y), u), _2n); // (-X / Y - u) / 2
113
- if (isValidX(res)) return Fp.toBytes(res);
114
- res = Fp.div(Fp.sub(Fp.div(x, y), u), _2n); // (X / Y - u) / 2
115
- if (isValidX(res)) return Fp.toBytes(res);
152
+ if (isValidX(res)) return Fp.toBytes(res) as TRet<Uint8Array>;
153
+ // X / Y is shared by the remaining candidates; computing it once saves an inversion.
154
+ const xDivY = Fp.div(x, y);
155
+ res = Fp.mul(Fp.sub(Fp.neg(xDivY), u), INV_2); // (-X / Y - u) / 2
156
+ if (isValidX(res)) return Fp.toBytes(res) as TRet<Uint8Array>;
157
+ res = Fp.mul(Fp.sub(xDivY, u), INV_2); // (X / Y - u) / 2
158
+ if (isValidX(res)) return Fp.toBytes(res) as TRet<Uint8Array>;
116
159
  throw new Error('elligatorSwift: cannot decode public key');
117
160
  },
118
161
  // Generate pair (public key, secret key)
119
162
  keygen: () => {
163
+ // Use a subgroup-valid secp256k1 secret key, then ElligatorSwift-encode x(priv*G).
120
164
  const privateKey: Bytes = secp256k1.utils.randomSecretKey();
121
165
  const p = Point.BASE.multiply(Point.Fn.fromBytes(privateKey));
122
166
  const publicKey: Bytes = elligatorSwift.encode(p.x);
123
167
  return { privateKey, publicKey };
124
168
  },
125
169
  // Generates shared secret between a pub key and a priv key
126
- getSharedSecret: (privateKeyA: Uint8Array, publicKeyB: Uint8Array): Bytes => {
170
+ getSharedSecret: (privateKeyA: TArg<Uint8Array>, publicKeyB: TArg<Uint8Array>): TRet<Bytes> => {
171
+ // decode() accepts arbitrary 64-byte ElligatorSwift encodings, but the private scalar
172
+ // here still follows the usual secp256k1 subgroup-secret domain (1..n-1).
127
173
  const pub = elligatorSwift.decode(publicKeyB);
128
174
  const priv = abytes(privateKeyA, 32, 'privKey');
129
175
  const point = schnorr.utils.lift_x(Fp.fromBytes(pub));
130
176
  const d = Fn.fromBytes(priv);
131
- return Fp.toBytes(point.multiply(d).x);
177
+ return Fp.toBytes(point.multiply(d).x) as TRet<Bytes>;
132
178
  },
133
179
  // BIP324 shared secret
134
180
  getSharedSecretBip324: (
135
- privateKeyOurs: Uint8Array,
136
- publicKeyTheirs: Uint8Array,
137
- publicKeyOurs: Uint8Array,
181
+ privateKeyOurs: TArg<Uint8Array>,
182
+ publicKeyTheirs: TArg<Uint8Array>,
183
+ publicKeyOurs: TArg<Uint8Array>,
138
184
  initiating: boolean
139
- ): Uint8Array => {
140
- const ours = abytes(publicKeyOurs, undefined, 'publicKeyOurs');
141
- const theirs = abytes(publicKeyTheirs, undefined, 'publicKeyTheirs');
185
+ ): TRet<Uint8Array> => {
186
+ // BIP324 Shared secret computation hashes "the exactly 64-byte public keys'
187
+ // encodings sent over the wire", so both ElligatorSwift inputs must be 64 bytes here.
188
+ // Initiator/responder ordering decides the hash-input order, so require a real boolean
189
+ // instead of letting arbitrary truthy values pick a side.
190
+ if (typeof initiating !== 'boolean')
191
+ throw new TypeError('"initiating" expected boolean, got type=' + typeof initiating);
192
+ const ours = abytes(publicKeyOurs, 64, 'publicKeyOurs');
193
+ const theirs = abytes(publicKeyTheirs, 64, 'publicKeyTheirs');
142
194
  const ecdhPoint = elligatorSwift.getSharedSecret(privateKeyOurs, theirs);
143
195
  const pubs = initiating ? [ours, theirs] : [theirs, ours];
144
- return tagSchnorr('bip324_ellswift_xonly_ecdh', ...pubs, ecdhPoint);
196
+ return tagSchnorr('bip324_ellswift_xonly_ecdh', ...pubs, ecdhPoint) as TRet<Uint8Array>;
145
197
  },
146
- };
198
+ });