swarmlite 0.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.
@@ -0,0 +1,790 @@
1
+ /*! noble-secp256k1 - MIT License (c) 2019 Paul Miller (paulmillr.com) */
2
+ /**
3
+ * 4KB JS implementation of secp256k1 ECDSA / Schnorr signatures & ECDH.
4
+ * Compliant with RFC6979 & BIP340.
5
+ * @module
6
+ */
7
+ /**
8
+ * Curve params. secp256k1 is short weierstrass / koblitz curve. Equation is y² == x³ + ax + b.
9
+ * * P = `2n**256n-2n**32n-2n**977n` // field over which calculations are done
10
+ * * N = `2n**256n - 0x14551231950b75fc4402da1732fc9bebfn` // group order, amount of curve points
11
+ * * h = `1n` // cofactor
12
+ * * a = `0n` // equation param
13
+ * * b = `7n` // equation param
14
+ * * Gx, Gy are coordinates of Generator / base point
15
+ */
16
+ const secp256k1_CURVE = {
17
+ p: 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,
18
+ n: 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n,
19
+ h: 1n,
20
+ a: 0n,
21
+ b: 7n,
22
+ Gx: 0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n,
23
+ Gy: 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8n,
24
+ };
25
+ const { p: P, n: N, Gx, Gy, b: _b } = secp256k1_CURVE;
26
+ const L = 32; // field / group byte length
27
+ const L2 = 64;
28
+ // Helpers and Precomputes sections are reused between libraries
29
+ // ## Helpers
30
+ // ----------
31
+ // error helper, messes-up stack trace
32
+ const err = (m = '') => {
33
+ throw new Error(m);
34
+ };
35
+ const isBig = (n) => typeof n === 'bigint'; // is big integer
36
+ const isStr = (s) => typeof s === 'string'; // is string
37
+ const isBytes = (a) => a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
38
+ /** assert is Uint8Array (of specific length) */
39
+ const abytes = (a, l) => !isBytes(a) || (typeof l === 'number' && l > 0 && a.length !== l)
40
+ ? err('Uint8Array expected')
41
+ : a;
42
+ /** create Uint8Array */
43
+ const u8n = (len) => new Uint8Array(len);
44
+ const u8fr = (buf) => Uint8Array.from(buf);
45
+ const padh = (n, pad) => n.toString(16).padStart(pad, '0');
46
+ const bytesToHex = (b) => Array.from(abytes(b))
47
+ .map((e) => padh(e, 2))
48
+ .join('');
49
+ const C = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 }; // ASCII characters
50
+ const _ch = (ch) => {
51
+ if (ch >= C._0 && ch <= C._9)
52
+ return ch - C._0; // '2' => 50-48
53
+ if (ch >= C.A && ch <= C.F)
54
+ return ch - (C.A - 10); // 'B' => 66-(65-10)
55
+ if (ch >= C.a && ch <= C.f)
56
+ return ch - (C.a - 10); // 'b' => 98-(97-10)
57
+ return;
58
+ };
59
+ const hexToBytes = (hex) => {
60
+ const e = 'hex invalid';
61
+ if (!isStr(hex))
62
+ return err(e);
63
+ const hl = hex.length;
64
+ const al = hl / 2;
65
+ if (hl % 2)
66
+ return err(e);
67
+ const array = u8n(al);
68
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
69
+ // treat each char as ASCII
70
+ const n1 = _ch(hex.charCodeAt(hi)); // parse first char, multiply it by 16
71
+ const n2 = _ch(hex.charCodeAt(hi + 1)); // parse second char
72
+ if (n1 === undefined || n2 === undefined)
73
+ return err(e);
74
+ array[ai] = n1 * 16 + n2; // example: 'A9' => 10*16 + 9
75
+ }
76
+ return array;
77
+ };
78
+ /** normalize hex or ui8a to ui8a */
79
+ const toU8 = (a, len) => abytes(isStr(a) ? hexToBytes(a) : u8fr(abytes(a)), len);
80
+ const cr = () => globalThis?.crypto; // WebCrypto is available in all modern environments
81
+ const subtle = () => cr()?.subtle ?? err('crypto.subtle must be defined');
82
+ // prettier-ignore
83
+ const concatBytes = (...arrs) => {
84
+ const r = u8n(arrs.reduce((sum, a) => sum + abytes(a).length, 0)); // create u8a of summed length
85
+ let pad = 0; // walk through each array,
86
+ arrs.forEach(a => { r.set(a, pad); pad += a.length; }); // ensure they have proper type
87
+ return r;
88
+ };
89
+ /** WebCrypto OS-level CSPRNG (random number generator). Will throw when not available. */
90
+ const randomBytes = (len = L) => {
91
+ const c = cr();
92
+ return c.getRandomValues(u8n(len));
93
+ };
94
+ const big = BigInt;
95
+ const arange = (n, min, max, msg = 'bad number: out of range') => isBig(n) && min <= n && n < max ? n : err(msg);
96
+ /** modular division */
97
+ const M = (a, b = P) => {
98
+ const r = a % b;
99
+ return r >= 0n ? r : b + r;
100
+ };
101
+ const modN = (a) => M(a, N);
102
+ /** Modular inversion using eucledian GCD (non-CT). No negative exponent for now. */
103
+ // prettier-ignore
104
+ const invert = (num, md) => {
105
+ if (num === 0n || md <= 0n)
106
+ err('no inverse n=' + num + ' mod=' + md);
107
+ let a = M(num, md), b = md, x = 0n, y = 1n, u = 1n, v = 0n;
108
+ while (a !== 0n) {
109
+ const q = b / a, r = b % a;
110
+ const m = x - u * q, n = y - v * q;
111
+ b = a, a = r, x = u, y = v, u = m, v = n;
112
+ }
113
+ return b === 1n ? M(x, md) : err('no inverse'); // b is gcd at this point
114
+ };
115
+ const callHash = (name) => {
116
+ // @ts-ignore
117
+ const fn = etc[name];
118
+ if (typeof fn !== 'function')
119
+ err('hashes.' + name + ' not set');
120
+ return fn;
121
+ };
122
+ const apoint = (p) => (p instanceof Point ? p : err('Point expected'));
123
+ // ## End of Helpers
124
+ // -----------------
125
+ /** secp256k1 formula. Koblitz curves are subclass of weierstrass curves with a=0, making it x³+b */
126
+ const koblitz = (x) => M(M(x * x) * x + _b);
127
+ /** assert is field element or 0 */
128
+ const afield0 = (n) => arange(n, 0n, P);
129
+ /** assert is field element */
130
+ const afield = (n) => arange(n, 1n, P);
131
+ /** assert is group elem */
132
+ const agroup = (n) => arange(n, 1n, N);
133
+ const isEven = (y) => (y & 1n) === 0n;
134
+ /** create Uint8Array of byte n */
135
+ const u8of = (n) => Uint8Array.of(n);
136
+ const getPrefix = (y) => u8of(isEven(y) ? 0x02 : 0x03);
137
+ /** lift_x from BIP340 calculates square root. Validates x, then validates root*root. */
138
+ const lift_x = (x) => {
139
+ // Let c = x³ + 7 mod p. Fail if x ≥ p. (also fail if x < 1)
140
+ const c = koblitz(afield(x));
141
+ // c = √y
142
+ // y = c^((p+1)/4) mod p
143
+ // This formula works for fields p = 3 mod 4 -- a special, fast case.
144
+ // Paper: "Square Roots from 1;24,51,10 to Dan Shanks".
145
+ let r = 1n;
146
+ for (let num = c, e = (P + 1n) / 4n; e > 0n; e >>= 1n) {
147
+ // powMod: modular exponentiation.
148
+ if (e & 1n)
149
+ r = (r * num) % P; // Uses exponentiation by squaring.
150
+ num = (num * num) % P; // Not constant-time.
151
+ }
152
+ return M(r * r) === c ? r : err('sqrt invalid'); // check if result is valid
153
+ };
154
+ /** Point in 3d xyz projective coordinates. 3d takes less inversions than 2d. */
155
+ class Point {
156
+ static BASE;
157
+ static ZERO;
158
+ px;
159
+ py;
160
+ pz;
161
+ constructor(px, py, pz) {
162
+ this.px = afield0(px);
163
+ this.py = afield(py); // y can't be 0 in Projective
164
+ this.pz = afield0(pz);
165
+ Object.freeze(this);
166
+ }
167
+ /** Convert Uint8Array or hex string to Point. */
168
+ static fromBytes(bytes) {
169
+ abytes(bytes);
170
+ let p = undefined;
171
+ // First byte is prefix, rest is data. There are 2 kinds: compressed & uncompressed:
172
+ // * [0x02 or 0x03][32-byte x coordinate]
173
+ // * [0x04] [32-byte x coordinate][32-byte y coordinate]
174
+ const head = bytes[0];
175
+ const tail = bytes.subarray(1);
176
+ const x = sliceBytesNumBE(tail, 0, L);
177
+ const len = bytes.length;
178
+ // Compressed 33-byte point, 0x02 or 0x03 prefix
179
+ if (len === L + 1 && [0x02, 0x03].includes(head)) {
180
+ // Equation is y² == x³ + ax + b. We calculate y from x.
181
+ // y = √y²; there are two solutions: y, -y. Determine proper solution based on prefix
182
+ let y = lift_x(x);
183
+ const evenY = isEven(y);
184
+ const evenH = isEven(big(head));
185
+ if (evenH !== evenY)
186
+ y = M(-y);
187
+ p = new Point(x, y, 1n);
188
+ }
189
+ // Uncompressed 65-byte point, 0x04 prefix
190
+ if (len === L2 + 1 && head === 0x04)
191
+ p = new Point(x, sliceBytesNumBE(tail, L, L2), 1n);
192
+ // Validate point
193
+ return p ? p.assertValidity() : err('bad point: not on curve');
194
+ }
195
+ /** Equality check: compare points P&Q. */
196
+ equals(other) {
197
+ const { px: X1, py: Y1, pz: Z1 } = this;
198
+ const { px: X2, py: Y2, pz: Z2 } = apoint(other); // checks class equality
199
+ const X1Z2 = M(X1 * Z2);
200
+ const X2Z1 = M(X2 * Z1);
201
+ const Y1Z2 = M(Y1 * Z2);
202
+ const Y2Z1 = M(Y2 * Z1);
203
+ return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
204
+ }
205
+ is0() {
206
+ return this.equals(I);
207
+ }
208
+ /** Flip point over y coordinate. */
209
+ negate() {
210
+ return new Point(this.px, M(-this.py), this.pz);
211
+ }
212
+ /** Point doubling: P+P, complete formula. */
213
+ double() {
214
+ return this.add(this);
215
+ }
216
+ /**
217
+ * Point addition: P+Q, complete, exception-free formula
218
+ * (Renes-Costello-Batina, algo 1 of [2015/1060](https://eprint.iacr.org/2015/1060)).
219
+ * Cost: `12M + 0S + 3*a + 3*b3 + 23add`.
220
+ */
221
+ // prettier-ignore
222
+ add(other) {
223
+ const { px: X1, py: Y1, pz: Z1 } = this;
224
+ const { px: X2, py: Y2, pz: Z2 } = apoint(other);
225
+ const a = 0n;
226
+ const b = _b;
227
+ let X3 = 0n, Y3 = 0n, Z3 = 0n;
228
+ const b3 = M(b * 3n);
229
+ let t0 = M(X1 * X2), t1 = M(Y1 * Y2), t2 = M(Z1 * Z2), t3 = M(X1 + Y1); // step 1
230
+ let t4 = M(X2 + Y2); // step 5
231
+ t3 = M(t3 * t4);
232
+ t4 = M(t0 + t1);
233
+ t3 = M(t3 - t4);
234
+ t4 = M(X1 + Z1);
235
+ let t5 = M(X2 + Z2); // step 10
236
+ t4 = M(t4 * t5);
237
+ t5 = M(t0 + t2);
238
+ t4 = M(t4 - t5);
239
+ t5 = M(Y1 + Z1);
240
+ X3 = M(Y2 + Z2); // step 15
241
+ t5 = M(t5 * X3);
242
+ X3 = M(t1 + t2);
243
+ t5 = M(t5 - X3);
244
+ Z3 = M(a * t4);
245
+ X3 = M(b3 * t2); // step 20
246
+ Z3 = M(X3 + Z3);
247
+ X3 = M(t1 - Z3);
248
+ Z3 = M(t1 + Z3);
249
+ Y3 = M(X3 * Z3);
250
+ t1 = M(t0 + t0); // step 25
251
+ t1 = M(t1 + t0);
252
+ t2 = M(a * t2);
253
+ t4 = M(b3 * t4);
254
+ t1 = M(t1 + t2);
255
+ t2 = M(t0 - t2); // step 30
256
+ t2 = M(a * t2);
257
+ t4 = M(t4 + t2);
258
+ t0 = M(t1 * t4);
259
+ Y3 = M(Y3 + t0);
260
+ t0 = M(t5 * t4); // step 35
261
+ X3 = M(t3 * X3);
262
+ X3 = M(X3 - t0);
263
+ t0 = M(t3 * t1);
264
+ Z3 = M(t5 * Z3);
265
+ Z3 = M(Z3 + t0); // step 40
266
+ return new Point(X3, Y3, Z3);
267
+ }
268
+ /**
269
+ * Point-by-scalar multiplication. Scalar must be in range 1 <= n < CURVE.n.
270
+ * Uses {@link wNAF} for base point.
271
+ * Uses fake point to mitigate side-channel leakage.
272
+ * @param n scalar by which point is multiplied
273
+ * @param safe safe mode guards against timing attacks; unsafe mode is faster
274
+ */
275
+ multiply(n, safe = true) {
276
+ if (!safe && n === 0n)
277
+ return I;
278
+ agroup(n);
279
+ if (n === 1n)
280
+ return this;
281
+ if (this.equals(G))
282
+ return wNAF(n).p;
283
+ // init result point & fake point
284
+ let p = I;
285
+ let f = G;
286
+ for (let d = this; n > 0n; d = d.double(), n >>= 1n) {
287
+ // if bit is present, add to point
288
+ // if not present, add to fake, for timing safety
289
+ if (n & 1n)
290
+ p = p.add(d);
291
+ else if (safe)
292
+ f = f.add(d);
293
+ }
294
+ return p;
295
+ }
296
+ /** Convert point to 2d xy affine point. (X, Y, Z) ∋ (x=X/Z, y=Y/Z) */
297
+ toAffine() {
298
+ const { px: x, py: y, pz: z } = this;
299
+ // fast-paths for ZERO point OR Z=1
300
+ if (this.equals(I))
301
+ return { x: 0n, y: 0n };
302
+ if (z === 1n)
303
+ return { x, y };
304
+ const iz = invert(z, P);
305
+ // (Z * Z^-1) must be 1, otherwise bad math
306
+ if (M(z * iz) !== 1n)
307
+ err('inverse invalid');
308
+ // x = X*Z^-1; y = Y*Z^-1
309
+ return { x: M(x * iz), y: M(y * iz) };
310
+ }
311
+ /** Checks if the point is valid and on-curve. */
312
+ assertValidity() {
313
+ const { x, y } = this.toAffine(); // convert to 2d xy affine point.
314
+ afield(x); // must be in range 1 <= x,y < P
315
+ afield(y);
316
+ // y² == x³ + ax + b, equation sides must be equal
317
+ return M(y * y) === koblitz(x) ? this : err('bad point: not on curve');
318
+ }
319
+ /** Converts point to 33/65-byte Uint8Array. */
320
+ toBytes(isCompressed = true) {
321
+ const { x, y } = this.assertValidity().toAffine();
322
+ const x32b = numTo32b(x);
323
+ if (isCompressed)
324
+ return concatBytes(getPrefix(y), x32b);
325
+ return concatBytes(u8of(0x04), x32b, numTo32b(y));
326
+ }
327
+ /** Create 3d xyz point from 2d xy. (0, 0) => (0, 1, 0), not (0, 0, 1) */
328
+ static fromAffine(ap) {
329
+ const { x, y } = ap;
330
+ return x === 0n && y === 0n ? I : new Point(x, y, 1n);
331
+ }
332
+ toHex(isCompressed) {
333
+ return bytesToHex(this.toBytes(isCompressed));
334
+ }
335
+ static fromPrivateKey(k) {
336
+ return G.multiply(toPrivScalar(k));
337
+ }
338
+ static fromHex(hex) {
339
+ return Point.fromBytes(toU8(hex));
340
+ }
341
+ get x() {
342
+ return this.toAffine().x;
343
+ }
344
+ get y() {
345
+ return this.toAffine().y;
346
+ }
347
+ toRawBytes(isCompressed) {
348
+ return this.toBytes(isCompressed);
349
+ }
350
+ }
351
+ /** Generator / base point */
352
+ const G = new Point(Gx, Gy, 1n);
353
+ /** Identity / zero point */
354
+ const I = new Point(0n, 1n, 0n);
355
+ // Static aliases
356
+ Point.BASE = G;
357
+ Point.ZERO = I;
358
+ /** `Q = u1⋅G + u2⋅R`. Verifies Q is not ZERO. Unsafe: non-CT. */
359
+ const doubleScalarMulUns = (R, u1, u2) => {
360
+ return G.multiply(u1, false).add(R.multiply(u2, false)).assertValidity();
361
+ };
362
+ const bytesToNumBE = (b) => big('0x' + (bytesToHex(b) || '0'));
363
+ const sliceBytesNumBE = (b, from, to) => bytesToNumBE(b.subarray(from, to));
364
+ const B256 = 2n ** 256n; // secp256k1 is weierstrass curve. Equation is x³ + ax + b.
365
+ /** Number to 32b. Must be 0 <= num < B256. validate, pad, to bytes. */
366
+ const numTo32b = (num) => hexToBytes(padh(arange(num, 0n, B256), L2));
367
+ /** Normalize private key to scalar (bigint). Verifies scalar is in range 1<s<N */
368
+ const toPrivScalar = (pr) => {
369
+ const num = isBig(pr) ? pr : bytesToNumBE(toU8(pr, L));
370
+ return arange(num, 1n, N, 'private key invalid 3');
371
+ };
372
+ /** For Signature malleability, validates sig.s is bigger than N/2. */
373
+ const highS = (n) => n > N >> 1n;
374
+ /** Creates 33/65-byte public key from 32-byte private key. */
375
+ const getPublicKey = (privKey, isCompressed = true) => {
376
+ return G.multiply(toPrivScalar(privKey)).toBytes(isCompressed);
377
+ };
378
+ /** ECDSA Signature class. Supports only compact 64-byte representation, not DER. */
379
+ class Signature {
380
+ r;
381
+ s;
382
+ recovery;
383
+ constructor(r, s, recovery) {
384
+ this.r = agroup(r); // 1 <= r < N
385
+ this.s = agroup(s); // 1 <= s < N
386
+ if (recovery != null)
387
+ this.recovery = recovery;
388
+ Object.freeze(this);
389
+ }
390
+ /** Create signature from 64b compact (r || s) representation. */
391
+ static fromBytes(b) {
392
+ abytes(b, L2);
393
+ const r = sliceBytesNumBE(b, 0, L);
394
+ const s = sliceBytesNumBE(b, L, L2);
395
+ return new Signature(r, s);
396
+ }
397
+ toBytes() {
398
+ const { r, s } = this;
399
+ return concatBytes(numTo32b(r), numTo32b(s));
400
+ }
401
+ /** Copy signature, with newly added recovery bit. */
402
+ addRecoveryBit(bit) {
403
+ return new Signature(this.r, this.s, bit);
404
+ }
405
+ hasHighS() {
406
+ return highS(this.s);
407
+ }
408
+ toCompactRawBytes() {
409
+ return this.toBytes();
410
+ }
411
+ toCompactHex() {
412
+ return bytesToHex(this.toBytes());
413
+ }
414
+ recoverPublicKey(msg) {
415
+ return recoverPublicKey(this, msg);
416
+ }
417
+ static fromCompact(hex) {
418
+ return Signature.fromBytes(toU8(hex, L2));
419
+ }
420
+ assertValidity() {
421
+ return this;
422
+ }
423
+ normalizeS() {
424
+ const { r, s, recovery } = this;
425
+ return highS(s) ? new Signature(r, modN(-s), recovery) : this;
426
+ }
427
+ }
428
+ /**
429
+ * RFC6979: ensure ECDSA msg is X bytes, convert to BigInt.
430
+ * RFC suggests optional truncating via bits2octets.
431
+ * FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits,
432
+ * which matches bits2int. bits2int can produce res>N.
433
+ */
434
+ const bits2int = (bytes) => {
435
+ const delta = bytes.length * 8 - 256;
436
+ if (delta > 1024)
437
+ err('msg invalid'); // our CUSTOM check, "just-in-case": prohibit long inputs
438
+ const num = bytesToNumBE(bytes);
439
+ return delta > 0 ? num >> big(delta) : num;
440
+ };
441
+ /** int2octets can't be used; pads small msgs with 0: BAD for truncation as per RFC vectors */
442
+ const bits2int_modN = (bytes) => modN(bits2int(abytes(bytes)));
443
+ const signOpts = { lowS: true };
444
+ const veriOpts = { lowS: true };
445
+ // RFC6979 signature generation, preparation step.
446
+ const prepSig = (msgh, priv, opts = signOpts) => {
447
+ if (['der', 'recovered', 'canonical'].some((k) => k in opts))
448
+ // legacy opts
449
+ err('option not supported');
450
+ let { lowS, extraEntropy } = opts; // generates low-s sigs by default
451
+ if (lowS == null)
452
+ lowS = true; // RFC6979 3.2: we skip step A
453
+ const i2o = numTo32b; // int to octets
454
+ const h1i = bits2int_modN(toU8(msgh)); // msg bigint
455
+ const h1o = i2o(h1i); // msg octets
456
+ const d = toPrivScalar(priv); // validate private key, convert to bigint
457
+ const seed = [i2o(d), h1o]; // Step D of RFC6979 3.2
458
+ /** RFC6979 3.6: additional k' (optional). See {@link ExtraEntropy}. */
459
+ // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')
460
+ if (extraEntropy)
461
+ seed.push(extraEntropy === true ? randomBytes(L) : toU8(extraEntropy));
462
+ const m = h1i; // convert msg to bigint
463
+ // Converts signature params into point w r/s, checks result for validity.
464
+ // To transform k => Signature:
465
+ // q = k⋅G
466
+ // r = q.x mod n
467
+ // s = k^-1(m + rd) mod n
468
+ const k2sig = (kBytes) => {
469
+ // RFC 6979 Section 3.2, step 3: k = bits2int(T)
470
+ // Important: all mod() calls here must be done over N
471
+ const k = bits2int(kBytes);
472
+ if (!(1n <= k && k < N))
473
+ return; // Check 0 < k < CURVE.n
474
+ const q = G.multiply(k).toAffine(); // q = k⋅G
475
+ const r = modN(q.x); // r = q.x mod n
476
+ if (r === 0n)
477
+ return;
478
+ const ik = invert(k, N); // k^-1 mod n, NOT mod P
479
+ const s = modN(ik * modN(m + modN(d * r))); // s = k^-1(m + rd) mod n
480
+ if (s === 0n)
481
+ return;
482
+ let normS = s; // normalized S
483
+ let recovery = (q.x === r ? 0 : 2) | Number(q.y & 1n); // recovery bit (2 or 3, when q.x > n)
484
+ if (lowS && highS(s)) {
485
+ // if lowS was passed, ensure s is always
486
+ normS = modN(-s); // in the bottom half of CURVE.n
487
+ recovery ^= 1;
488
+ }
489
+ return new Signature(r, normS, recovery); // use normS, not s
490
+ };
491
+ return { seed: concatBytes(...seed), k2sig };
492
+ };
493
+ // HMAC-DRBG from NIST 800-90. Minimal, non-full-spec - used for RFC6979 signatures.
494
+ const hmacDrbg = (asynchronous) => {
495
+ let v = u8n(L); // Steps B, C of RFC6979 3.2: set hashLen
496
+ let k = u8n(L); // In our case, it's always equal to L
497
+ let i = 0; // Iterations counter, will throw when over max
498
+ const NULL = u8n(0);
499
+ const reset = () => {
500
+ v.fill(1);
501
+ k.fill(0);
502
+ i = 0;
503
+ };
504
+ const max = 1000;
505
+ const _e = 'drbg: tried 1000 values';
506
+ if (asynchronous) {
507
+ // asynchronous=true
508
+ // h = hmac(K || V || ...)
509
+ const h = (...b) => etc.hmacSha256Async(k, v, ...b);
510
+ const reseed = async (seed = NULL) => {
511
+ // HMAC-DRBG reseed() function. Steps D-G
512
+ k = await h(u8of(0x00), seed); // k = hmac(K || V || 0x00 || seed)
513
+ v = await h(); // v = hmac(K || V)
514
+ if (seed.length === 0)
515
+ return;
516
+ k = await h(u8of(0x01), seed); // k = hmac(K || V || 0x01 || seed)
517
+ v = await h(); // v = hmac(K || V)
518
+ };
519
+ // HMAC-DRBG generate() function
520
+ const gen = async () => {
521
+ if (i++ >= max)
522
+ err(_e);
523
+ v = await h(); // v = hmac(K || V)
524
+ return v; // this diverges from noble-curves: we don't allow arbitrary output len!
525
+ };
526
+ // Do not reuse returned fn for more than 1 sig:
527
+ // 1) it's slower (JIT screws up). 2. unsafe (async race conditions)
528
+ return async (seed, pred) => {
529
+ reset();
530
+ await reseed(seed); // Steps D-G
531
+ let res = undefined; // Step H: grind until k is in [1..n-1]
532
+ while (!(res = pred(await gen())))
533
+ await reseed(); // test predicate until it returns ok
534
+ reset();
535
+ return res;
536
+ };
537
+ }
538
+ else {
539
+ // asynchronous=false; same as above, but synchronous
540
+ // h = hmac(K || V || ...)
541
+ const h = (...b) => callHash('hmacSha256Sync')(k, v, ...b);
542
+ const reseed = (seed = NULL) => {
543
+ // HMAC-DRBG reseed() function. Steps D-G
544
+ k = h(u8of(0x00), seed); // k = hmac(k || v || 0x00 || seed)
545
+ v = h(); // v = hmac(k || v)
546
+ if (seed.length === 0)
547
+ return;
548
+ k = h(u8of(0x01), seed); // k = hmac(k || v || 0x01 || seed)
549
+ v = h(); // v = hmac(k || v)
550
+ };
551
+ // HMAC-DRBG generate() function
552
+ const gen = () => {
553
+ if (i++ >= max)
554
+ err(_e);
555
+ v = h(); // v = hmac(k || v)
556
+ return v; // this diverges from noble-curves: we don't allow arbitrary output len!
557
+ };
558
+ // Do not reuse returned fn for more than 1 sig:
559
+ // 1) it's slower (JIT screws up). 2. unsafe (async race conditions)
560
+ return (seed, pred) => {
561
+ reset();
562
+ reseed(seed); // Steps D-G
563
+ let res = undefined; // Step H: grind until k is in [1..n-1]
564
+ while (!(res = pred(gen())))
565
+ reseed(); // test predicate until it returns ok
566
+ reset();
567
+ return res;
568
+ };
569
+ }
570
+ };
571
+ /**
572
+ * Sign a msg hash using secp256k1. Async.
573
+ * Follows [SEC1](https://secg.org/sec1-v2.pdf) 4.1.2 & RFC6979.
574
+ * It's suggested to enable hedging ({@link ExtraEntropy}) to prevent fault attacks.
575
+ * @param msgh - message HASH, not message itself e.g. sha256(message)
576
+ * @param priv - private key
577
+ * @param opts - `lowS: true` prevents malleability, `extraEntropy: true` enables hedging
578
+ */
579
+ const signAsync = async (msgh, priv, opts = signOpts) => {
580
+ // Re-run drbg until k2sig returns ok
581
+ const { seed, k2sig } = prepSig(msgh, priv, opts);
582
+ const sig = await hmacDrbg(true)(seed, k2sig);
583
+ return sig;
584
+ };
585
+ /**
586
+ * Sign a msg hash using secp256k1.
587
+ * Follows [SEC1](https://secg.org/sec1-v2.pdf) 4.1.2 & RFC6979.
588
+ * It's suggested to enable hedging ({@link ExtraEntropy}) to prevent fault attacks.
589
+ * @param msgh - message HASH, not message itself e.g. sha256(message)
590
+ * @param priv - private key
591
+ * @param opts - `lowS: true` prevents malleability, `extraEntropy: true` enables hedging
592
+ * @example
593
+ * const sig = sign(sha256('hello'), privKey, { extraEntropy: true }).toBytes();
594
+ */
595
+ const sign = (msgh, priv, opts = signOpts) => {
596
+ // Re-run drbg until k2sig returns ok
597
+ const { seed, k2sig } = prepSig(msgh, priv, opts);
598
+ const sig = hmacDrbg(false)(seed, k2sig);
599
+ return sig;
600
+ };
601
+ /**
602
+ * Verify a signature using secp256k1.
603
+ * Follows [SEC1](https://secg.org/sec1-v2.pdf) 4.1.4.
604
+ * Default lowS=true, prevents malleability.
605
+ * @param sig - signature, 64-byte or Signature instance
606
+ * @param msgh - message HASH, not message itself e.g. sha256(message)
607
+ * @param pub - public key
608
+ * @param opts - { lowS: true } is default, prohibits s >= CURVE.n/2 to prevent malleability
609
+ */
610
+ const verify = (sig, msgh, pub, opts = veriOpts) => {
611
+ let { lowS } = opts;
612
+ if (lowS == null)
613
+ lowS = true;
614
+ if ('strict' in opts)
615
+ err('option not supported');
616
+ let sigg;
617
+ // Previous ver supported DER sigs.
618
+ // We throw error when DER is suspected now.
619
+ const rs = sig && typeof sig === 'object' && 'r' in sig;
620
+ if (!rs && toU8(sig).length !== L2)
621
+ err('signature must be 64 bytes');
622
+ try {
623
+ sigg = rs ? new Signature(sig.r, sig.s) : Signature.fromCompact(sig);
624
+ const h = bits2int_modN(toU8(msgh)); // Truncate hash
625
+ const P = Point.fromBytes(toU8(pub)); // Validate public key
626
+ const { r, s } = sigg;
627
+ if (lowS && highS(s))
628
+ return false; // lowS bans sig.s >= CURVE.n/2
629
+ const is = invert(s, N); // s^-1
630
+ const u1 = modN(h * is); // u1 = hs^-1 mod n
631
+ const u2 = modN(r * is); // u2 = rs^-1 mod n
632
+ const R = doubleScalarMulUns(P, u1, u2).toAffine(); // R = u1⋅G + u2⋅P
633
+ // Stop if R is identity / zero point. Check is done inside `doubleScalarMulUns`
634
+ const v = modN(R.x); // R.x must be in N's field, not P's
635
+ return v === r; // mod(R.x, n) == r
636
+ }
637
+ catch (error) {
638
+ return false;
639
+ }
640
+ };
641
+ /**
642
+ * ECDSA public key recovery. Requires msg hash and recovery id.
643
+ * Follows [SEC1](https://secg.org/sec1-v2.pdf) 4.1.6.
644
+ */
645
+ const recoverPublicKey = (sig, msgh) => {
646
+ const { r, s, recovery } = sig;
647
+ // 0 or 1 recovery id determines sign of "y" coordinate.
648
+ // 2 or 3 means q.x was >N.
649
+ if (![0, 1, 2, 3].includes(recovery))
650
+ err('recovery id invalid');
651
+ const h = bits2int_modN(toU8(msgh, L)); // Truncate hash
652
+ const radj = recovery === 2 || recovery === 3 ? r + N : r;
653
+ afield(radj); // ensure q.x is still a field element
654
+ const head = getPrefix(big(recovery)); // head is 0x02 or 0x03
655
+ const Rb = concatBytes(head, numTo32b(radj)); // concat head + r
656
+ const R = Point.fromBytes(Rb);
657
+ const ir = invert(radj, N); // r^-1
658
+ const u1 = modN(-h * ir); // -hr^-1
659
+ const u2 = modN(s * ir); // sr^-1
660
+ return doubleScalarMulUns(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1)
661
+ };
662
+ /**
663
+ * Elliptic Curve Diffie-Hellman (ECDH) on secp256k1.
664
+ * Result is **NOT hashed**. Use hash or KDF on it if you need.
665
+ * @param privA private key A
666
+ * @param pubB public key B
667
+ * @param isCompressed 33-byte (true) or 65-byte (false) output
668
+ * @returns public key C
669
+ */
670
+ const getSharedSecret = (privA, pubB, isCompressed = true) => {
671
+ return Point.fromBytes(toU8(pubB)).multiply(toPrivScalar(privA)).toBytes(isCompressed);
672
+ };
673
+ // FIPS 186 B.4.1 compliant key generation produces private keys with modulo bias being neglible.
674
+ // takes >N+8 bytes, returns (hash mod n-1)+1
675
+ const hashToPrivateKey = (hash) => {
676
+ hash = toU8(hash);
677
+ if (hash.length < L + 8 || hash.length > 1024)
678
+ err('expected 40-1024b');
679
+ const num = M(bytesToNumBE(hash), N - 1n);
680
+ return numTo32b(num + 1n);
681
+ };
682
+ const randomPrivateKey = () => hashToPrivateKey(randomBytes(L + 16)); // FIPS 186 B.4.1.
683
+ const _sha = 'SHA-256';
684
+ /** Math, hex, byte helpers. Not in `utils` because utils share API with noble-curves. */
685
+ const etc = {
686
+ hexToBytes: hexToBytes,
687
+ bytesToHex: bytesToHex,
688
+ concatBytes: concatBytes,
689
+ bytesToNumberBE: bytesToNumBE,
690
+ numberToBytesBE: numTo32b,
691
+ mod: M,
692
+ invert: invert, // math utilities
693
+ hmacSha256Async: async (key, ...msgs) => {
694
+ const s = subtle();
695
+ const name = 'HMAC';
696
+ const k = await s.importKey('raw', key, { name, hash: { name: _sha } }, false, ['sign']);
697
+ return u8n(await s.sign(name, k, concatBytes(...msgs)));
698
+ },
699
+ hmacSha256Sync: undefined, // For TypeScript. Actual logic is below
700
+ hashToPrivateKey: hashToPrivateKey,
701
+ randomBytes: randomBytes,
702
+ };
703
+ /** Curve-specific utilities for private keys. */
704
+ const utils = {
705
+ normPrivateKeyToScalar: toPrivScalar,
706
+ isValidPrivateKey: (key) => {
707
+ try {
708
+ return !!toPrivScalar(key);
709
+ }
710
+ catch (e) {
711
+ return false;
712
+ }
713
+ },
714
+ randomPrivateKey: randomPrivateKey,
715
+ precompute: (w = 8, p = G) => {
716
+ p.multiply(3n);
717
+ w;
718
+ return p;
719
+ },
720
+ };
721
+ // ## Precomputes
722
+ // --------------
723
+ const W = 8; // W is window size
724
+ const scalarBits = 256;
725
+ const pwindows = Math.ceil(scalarBits / W) + 1; // 33 for W=8
726
+ const pwindowSize = 2 ** (W - 1); // 128 for W=8
727
+ const precompute = () => {
728
+ const points = [];
729
+ let p = G;
730
+ let b = p;
731
+ for (let w = 0; w < pwindows; w++) {
732
+ b = p;
733
+ points.push(b);
734
+ for (let i = 1; i < pwindowSize; i++) {
735
+ b = b.add(p);
736
+ points.push(b);
737
+ } // i=1, bc we skip 0
738
+ p = b.double();
739
+ }
740
+ return points;
741
+ };
742
+ let Gpows = undefined; // precomputes for base point G
743
+ // const-time negate
744
+ const ctneg = (cnd, p) => {
745
+ const n = p.negate();
746
+ return cnd ? n : p;
747
+ };
748
+ /**
749
+ * Precomputes give 12x faster getPublicKey(), 10x sign(), 2x verify() by
750
+ * caching multiples of G (base point). Cache is stored in 32MB of RAM.
751
+ * Any time `G.multiply` is done, precomputes are used.
752
+ * Not used for getSharedSecret, which instead multiplies random pubkey `P.multiply`.
753
+ *
754
+ * w-ary non-adjacent form (wNAF) precomputation method is 10% slower than windowed method,
755
+ * but takes 2x less RAM. RAM reduction is possible by utilizing `.subtract`.
756
+ *
757
+ * !! Precomputes can be disabled by commenting-out call of the wNAF() inside Point#multiply().
758
+ */
759
+ const wNAF = (n) => {
760
+ const comp = Gpows || (Gpows = precompute());
761
+ let p = I;
762
+ let f = G; // f must be G, or could become I in the end
763
+ const pow_2_w = 2 ** W; // 256 for W=8
764
+ const maxNum = pow_2_w; // 256 for W=8
765
+ const mask = big(pow_2_w - 1); // 255 for W=8 == mask 0b11111111
766
+ const shiftBy = big(W); // 8 for W=8
767
+ for (let w = 0; w < pwindows; w++) {
768
+ let wbits = Number(n & mask); // extract W bits.
769
+ n >>= shiftBy; // shift number by W bits.
770
+ if (wbits > pwindowSize) {
771
+ wbits -= maxNum;
772
+ n += 1n;
773
+ } // split if bits > max: +224 => 256-32
774
+ const off = w * pwindowSize;
775
+ const offF = off; // offsets, evaluate both
776
+ const offP = off + Math.abs(wbits) - 1;
777
+ const isEven = w % 2 !== 0; // conditions, evaluate both
778
+ const isNeg = wbits < 0;
779
+ if (wbits === 0) {
780
+ // off == I: can't add it. Adding random offF instead.
781
+ f = f.add(ctneg(isEven, comp[offF])); // bits are 0: add garbage to fake point
782
+ }
783
+ else {
784
+ p = p.add(ctneg(isNeg, comp[offP])); // bits are 1: add to result point
785
+ }
786
+ }
787
+ return { p, f }; // return both real and fake points for JIT
788
+ };
789
+ // !! Remove the export below to easily use in REPL / browser console
790
+ export { secp256k1_CURVE as CURVE, etc, getPublicKey, getSharedSecret, Point, Point as ProjectivePoint, sign, signAsync, Signature, utils, verify, };