@didcid/gatekeeper 0.4.0 → 0.4.2
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/cjs/drawbridge-client.cjs +103 -0
- package/dist/cjs/gatekeeper-client.cjs +10 -1
- package/dist/cjs/gatekeeper.cjs +3100 -260
- package/dist/esm/drawbridge-client.js +96 -0
- package/dist/esm/drawbridge-client.js.map +1 -0
- package/dist/esm/gatekeeper-client.js +10 -1
- package/dist/esm/gatekeeper-client.js.map +1 -1
- package/dist/types/drawbridge-client.d.ts +17 -0
- package/dist/types/gatekeeper-client.d.ts +5 -2
- package/dist/types/types.d.ts +41 -0
- package/package.json +13 -5
package/dist/cjs/gatekeeper.cjs
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
Object.defineProperty(exports, '__esModule', { value: true });
|
|
4
4
|
|
|
5
|
-
var crypto$
|
|
5
|
+
var crypto$3 = require('crypto');
|
|
6
6
|
var require$$0$4 = require('assert');
|
|
7
7
|
var require$$0$2 = require('buffer');
|
|
8
8
|
var require$$0$3 = require('stream');
|
|
@@ -30,18 +30,18 @@ var _md = {};
|
|
|
30
30
|
|
|
31
31
|
var utils$4 = {};
|
|
32
32
|
|
|
33
|
-
var crypto$
|
|
33
|
+
var crypto$2 = {};
|
|
34
34
|
|
|
35
35
|
var hasRequiredCrypto;
|
|
36
36
|
|
|
37
37
|
function requireCrypto () {
|
|
38
|
-
if (hasRequiredCrypto) return crypto$
|
|
38
|
+
if (hasRequiredCrypto) return crypto$2;
|
|
39
39
|
hasRequiredCrypto = 1;
|
|
40
|
-
Object.defineProperty(crypto$
|
|
41
|
-
crypto$
|
|
42
|
-
crypto$
|
|
40
|
+
Object.defineProperty(crypto$2, "__esModule", { value: true });
|
|
41
|
+
crypto$2.crypto = void 0;
|
|
42
|
+
crypto$2.crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;
|
|
43
43
|
|
|
44
|
-
return crypto$
|
|
44
|
+
return crypto$2;
|
|
45
45
|
}
|
|
46
46
|
|
|
47
47
|
var hasRequiredUtils$3;
|
|
@@ -22575,7 +22575,7 @@ var hasRequiredCreateHash;
|
|
|
22575
22575
|
function requireCreateHash () {
|
|
22576
22576
|
if (hasRequiredCreateHash) return createHash;
|
|
22577
22577
|
hasRequiredCreateHash = 1;
|
|
22578
|
-
createHash = crypto$
|
|
22578
|
+
createHash = crypto$3.createHash;
|
|
22579
22579
|
return createHash;
|
|
22580
22580
|
}
|
|
22581
22581
|
|
|
@@ -27794,7 +27794,7 @@ function requireRipemd160 () {
|
|
|
27794
27794
|
return ripemd160;
|
|
27795
27795
|
}
|
|
27796
27796
|
|
|
27797
|
-
var secp256k1$
|
|
27797
|
+
var secp256k1$2 = {exports: {}};
|
|
27798
27798
|
|
|
27799
27799
|
function commonjsRequire(path) {
|
|
27800
27800
|
throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');
|
|
@@ -30534,6 +30534,11 @@ function requireBn () {
|
|
|
30534
30534
|
this.words[this.length - 1] &= mask;
|
|
30535
30535
|
}
|
|
30536
30536
|
|
|
30537
|
+
if (this.length === 0) {
|
|
30538
|
+
this.words[0] = 0;
|
|
30539
|
+
this.length = 1;
|
|
30540
|
+
}
|
|
30541
|
+
|
|
30537
30542
|
return this.strip();
|
|
30538
30543
|
};
|
|
30539
30544
|
|
|
@@ -35444,13 +35449,13 @@ function requireHash () {
|
|
|
35444
35449
|
return hash;
|
|
35445
35450
|
}
|
|
35446
35451
|
|
|
35447
|
-
var secp256k1;
|
|
35452
|
+
var secp256k1$1;
|
|
35448
35453
|
var hasRequiredSecp256k1$1;
|
|
35449
35454
|
|
|
35450
35455
|
function requireSecp256k1$1 () {
|
|
35451
|
-
if (hasRequiredSecp256k1$1) return secp256k1;
|
|
35456
|
+
if (hasRequiredSecp256k1$1) return secp256k1$1;
|
|
35452
35457
|
hasRequiredSecp256k1$1 = 1;
|
|
35453
|
-
secp256k1 = {
|
|
35458
|
+
secp256k1$1 = {
|
|
35454
35459
|
doubles: {
|
|
35455
35460
|
step: 4,
|
|
35456
35461
|
points: [
|
|
@@ -36230,7 +36235,7 @@ function requireSecp256k1$1 () {
|
|
|
36230
36235
|
],
|
|
36231
36236
|
},
|
|
36232
36237
|
};
|
|
36233
|
-
return secp256k1;
|
|
36238
|
+
return secp256k1$1;
|
|
36234
36239
|
}
|
|
36235
36240
|
|
|
36236
36241
|
var hasRequiredCurves;
|
|
@@ -37924,14 +37929,14 @@ function requireElliptic () {
|
|
|
37924
37929
|
var hasRequiredSecp256k1;
|
|
37925
37930
|
|
|
37926
37931
|
function requireSecp256k1 () {
|
|
37927
|
-
if (hasRequiredSecp256k1) return secp256k1$
|
|
37932
|
+
if (hasRequiredSecp256k1) return secp256k1$2.exports;
|
|
37928
37933
|
hasRequiredSecp256k1 = 1;
|
|
37929
37934
|
try {
|
|
37930
|
-
secp256k1$
|
|
37935
|
+
secp256k1$2.exports = requireBindings();
|
|
37931
37936
|
} catch (err) {
|
|
37932
|
-
secp256k1$
|
|
37937
|
+
secp256k1$2.exports = requireElliptic();
|
|
37933
37938
|
}
|
|
37934
|
-
return secp256k1$
|
|
37939
|
+
return secp256k1$2.exports;
|
|
37935
37940
|
}
|
|
37936
37941
|
|
|
37937
37942
|
var hdkey;
|
|
@@ -37942,7 +37947,7 @@ function requireHdkey () {
|
|
|
37942
37947
|
hasRequiredHdkey = 1;
|
|
37943
37948
|
var assert = require$$0$4;
|
|
37944
37949
|
var Buffer = requireSafeBuffer$2().Buffer;
|
|
37945
|
-
var crypto = crypto$
|
|
37950
|
+
var crypto = crypto$3;
|
|
37946
37951
|
var bs58check = requireBs58check();
|
|
37947
37952
|
var RIPEMD160 = requireRipemd160();
|
|
37948
37953
|
var secp256k1 = requireSecp256k1();
|
|
@@ -38218,14 +38223,14 @@ var HDKeyNode = /*@__PURE__*/getDefaultExportFromCjs(hdkeyExports);
|
|
|
38218
38223
|
* * b = `7n` // equation param
|
|
38219
38224
|
* * Gx, Gy are coordinates of Generator / base point
|
|
38220
38225
|
*/
|
|
38221
|
-
const secp256k1_CURVE = {
|
|
38226
|
+
const secp256k1_CURVE$1 = {
|
|
38222
38227
|
p: 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,
|
|
38223
38228
|
n: 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n,
|
|
38224
38229
|
b: 7n,
|
|
38225
38230
|
Gx: 0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n,
|
|
38226
38231
|
Gy: 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8n,
|
|
38227
38232
|
};
|
|
38228
|
-
const { p: P, n: N, Gx, Gy, b: _b } = secp256k1_CURVE;
|
|
38233
|
+
const { p: P, n: N, Gx, Gy, b: _b } = secp256k1_CURVE$1;
|
|
38229
38234
|
const L = 32; // field / group byte length
|
|
38230
38235
|
const L2 = 64;
|
|
38231
38236
|
// Helpers and Precomputes sections are reused between libraries
|
|
@@ -38246,7 +38251,7 @@ const abytes$1 = (a, l) => !isBytes$3(a) || (typeof l === 'number' && l > 0 && a
|
|
|
38246
38251
|
const u8n = (len) => new Uint8Array(len);
|
|
38247
38252
|
const u8fr = (buf) => Uint8Array.from(buf);
|
|
38248
38253
|
const padh = (n, pad) => n.toString(16).padStart(pad, '0');
|
|
38249
|
-
const bytesToHex = (b) => Array.from(abytes$1(b))
|
|
38254
|
+
const bytesToHex$1 = (b) => Array.from(abytes$1(b))
|
|
38250
38255
|
.map((e) => padh(e, 2))
|
|
38251
38256
|
.join('');
|
|
38252
38257
|
const C = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 }; // ASCII characters
|
|
@@ -38259,7 +38264,7 @@ const _ch = (ch) => {
|
|
|
38259
38264
|
return ch - (C.a - 10); // 'b' => 98-(97-10)
|
|
38260
38265
|
return;
|
|
38261
38266
|
};
|
|
38262
|
-
const hexToBytes = (hex) => {
|
|
38267
|
+
const hexToBytes$1 = (hex) => {
|
|
38263
38268
|
const e = 'hex invalid';
|
|
38264
38269
|
if (!isStr(hex))
|
|
38265
38270
|
return err(e);
|
|
@@ -38279,18 +38284,18 @@ const hexToBytes = (hex) => {
|
|
|
38279
38284
|
return array;
|
|
38280
38285
|
};
|
|
38281
38286
|
/** normalize hex or ui8a to ui8a */
|
|
38282
|
-
const toU8 = (a, len) => abytes$1(isStr(a) ? hexToBytes(a) : u8fr(abytes$1(a)), len);
|
|
38287
|
+
const toU8 = (a, len) => abytes$1(isStr(a) ? hexToBytes$1(a) : u8fr(abytes$1(a)), len);
|
|
38283
38288
|
const cr = () => globalThis?.crypto; // WebCrypto is available in all modern environments
|
|
38284
38289
|
const subtle = () => cr()?.subtle ?? err('crypto.subtle must be defined');
|
|
38285
38290
|
// prettier-ignore
|
|
38286
|
-
const concatBytes$
|
|
38291
|
+
const concatBytes$3 = (...arrs) => {
|
|
38287
38292
|
const r = u8n(arrs.reduce((sum, a) => sum + abytes$1(a).length, 0)); // create u8a of summed length
|
|
38288
38293
|
let pad = 0; // walk through each array,
|
|
38289
38294
|
arrs.forEach(a => { r.set(a, pad); pad += a.length; }); // ensure they have proper type
|
|
38290
38295
|
return r;
|
|
38291
38296
|
};
|
|
38292
38297
|
/** WebCrypto OS-level CSPRNG (random number generator). Will throw when not available. */
|
|
38293
|
-
const randomBytes$
|
|
38298
|
+
const randomBytes$2 = (len = L) => {
|
|
38294
38299
|
const c = cr();
|
|
38295
38300
|
return c.getRandomValues(u8n(len));
|
|
38296
38301
|
};
|
|
@@ -38304,7 +38309,7 @@ const M = (a, b = P) => {
|
|
|
38304
38309
|
const modN = (a) => M(a, N);
|
|
38305
38310
|
/** Modular inversion using eucledian GCD (non-CT). No negative exponent for now. */
|
|
38306
38311
|
// prettier-ignore
|
|
38307
|
-
const invert = (num, md) => {
|
|
38312
|
+
const invert$1 = (num, md) => {
|
|
38308
38313
|
if (num === 0n || md <= 0n)
|
|
38309
38314
|
err('no inverse n=' + num + ' mod=' + md);
|
|
38310
38315
|
let a = M(num, md), b = md, x = 0n, u = 1n;
|
|
@@ -38338,7 +38343,7 @@ const isEven = (y) => (y & 1n) === 0n;
|
|
|
38338
38343
|
const u8of = (n) => Uint8Array.of(n);
|
|
38339
38344
|
const getPrefix = (y) => u8of(isEven(y) ? 0x02 : 0x03);
|
|
38340
38345
|
/** lift_x from BIP340 calculates square root. Validates x, then validates root*root. */
|
|
38341
|
-
const lift_x = (x) => {
|
|
38346
|
+
const lift_x$1 = (x) => {
|
|
38342
38347
|
// Let c = x³ + 7 mod p. Fail if x ≥ p. (also fail if x < 1)
|
|
38343
38348
|
const c = koblitz(afield(x));
|
|
38344
38349
|
// c = √y
|
|
@@ -38382,7 +38387,7 @@ class Point {
|
|
|
38382
38387
|
if (len === L + 1 && [0x02, 0x03].includes(head)) {
|
|
38383
38388
|
// Equation is y² == x³ + ax + b. We calculate y from x.
|
|
38384
38389
|
// y = √y²; there are two solutions: y, -y. Determine proper solution based on prefix
|
|
38385
|
-
let y = lift_x(x);
|
|
38390
|
+
let y = lift_x$1(x);
|
|
38386
38391
|
const evenY = isEven(y);
|
|
38387
38392
|
const evenH = isEven(big(head));
|
|
38388
38393
|
if (evenH !== evenY)
|
|
@@ -38482,7 +38487,7 @@ class Point {
|
|
|
38482
38487
|
if (n === 1n)
|
|
38483
38488
|
return this;
|
|
38484
38489
|
if (this.equals(G))
|
|
38485
|
-
return wNAF(n).p;
|
|
38490
|
+
return wNAF$1(n).p;
|
|
38486
38491
|
// init result point & fake point
|
|
38487
38492
|
let p = I;
|
|
38488
38493
|
let f = G;
|
|
@@ -38504,7 +38509,7 @@ class Point {
|
|
|
38504
38509
|
return { x: 0n, y: 0n };
|
|
38505
38510
|
if (z === 1n)
|
|
38506
38511
|
return { x, y };
|
|
38507
|
-
const iz = invert(z, P);
|
|
38512
|
+
const iz = invert$1(z, P);
|
|
38508
38513
|
// (Z * Z^-1) must be 1, otherwise bad math
|
|
38509
38514
|
if (M(z * iz) !== 1n)
|
|
38510
38515
|
err('inverse invalid');
|
|
@@ -38524,8 +38529,8 @@ class Point {
|
|
|
38524
38529
|
const { x, y } = this.assertValidity().toAffine();
|
|
38525
38530
|
const x32b = numTo32b(x);
|
|
38526
38531
|
if (isCompressed)
|
|
38527
|
-
return concatBytes$
|
|
38528
|
-
return concatBytes$
|
|
38532
|
+
return concatBytes$3(getPrefix(y), x32b);
|
|
38533
|
+
return concatBytes$3(u8of(0x04), x32b, numTo32b(y));
|
|
38529
38534
|
}
|
|
38530
38535
|
/** Create 3d xyz point from 2d xy. (0, 0) => (0, 1, 0), not (0, 0, 1) */
|
|
38531
38536
|
static fromAffine(ap) {
|
|
@@ -38533,7 +38538,7 @@ class Point {
|
|
|
38533
38538
|
return x === 0n && y === 0n ? I : new Point(x, y, 1n);
|
|
38534
38539
|
}
|
|
38535
38540
|
toHex(isCompressed) {
|
|
38536
|
-
return bytesToHex(this.toBytes(isCompressed));
|
|
38541
|
+
return bytesToHex$1(this.toBytes(isCompressed));
|
|
38537
38542
|
}
|
|
38538
38543
|
static fromPrivateKey(k) {
|
|
38539
38544
|
return G.multiply(toPrivScalar(k));
|
|
@@ -38562,11 +38567,11 @@ Point.ZERO = I;
|
|
|
38562
38567
|
const doubleScalarMulUns = (R, u1, u2) => {
|
|
38563
38568
|
return G.multiply(u1, false).add(R.multiply(u2, false)).assertValidity();
|
|
38564
38569
|
};
|
|
38565
|
-
const bytesToNumBE = (b) => big('0x' + (bytesToHex(b) || '0'));
|
|
38570
|
+
const bytesToNumBE = (b) => big('0x' + (bytesToHex$1(b) || '0'));
|
|
38566
38571
|
const sliceBytesNumBE = (b, from, to) => bytesToNumBE(b.subarray(from, to));
|
|
38567
38572
|
const B256 = 2n ** 256n; // secp256k1 is weierstrass curve. Equation is x³ + ax + b.
|
|
38568
38573
|
/** Number to 32b. Must be 0 <= num < B256. validate, pad, to bytes. */
|
|
38569
|
-
const numTo32b = (num) => hexToBytes(padh(arange(num, 0n, B256), L2));
|
|
38574
|
+
const numTo32b = (num) => hexToBytes$1(padh(arange(num, 0n, B256), L2));
|
|
38570
38575
|
/** Normalize private key to scalar (bigint). Verifies scalar is in range 1<s<N */
|
|
38571
38576
|
const toPrivScalar = (pr) => {
|
|
38572
38577
|
const num = isBig(pr) ? pr : bytesToNumBE(toU8(pr, L));
|
|
@@ -38599,7 +38604,7 @@ class Signature {
|
|
|
38599
38604
|
}
|
|
38600
38605
|
toBytes() {
|
|
38601
38606
|
const { r, s } = this;
|
|
38602
|
-
return concatBytes$
|
|
38607
|
+
return concatBytes$3(numTo32b(r), numTo32b(s));
|
|
38603
38608
|
}
|
|
38604
38609
|
/** Copy signature, with newly added recovery bit. */
|
|
38605
38610
|
addRecoveryBit(bit) {
|
|
@@ -38612,7 +38617,7 @@ class Signature {
|
|
|
38612
38617
|
return this.toBytes();
|
|
38613
38618
|
}
|
|
38614
38619
|
toCompactHex() {
|
|
38615
|
-
return bytesToHex(this.toBytes());
|
|
38620
|
+
return bytesToHex$1(this.toBytes());
|
|
38616
38621
|
}
|
|
38617
38622
|
recoverPublicKey(msg) {
|
|
38618
38623
|
return recoverPublicKey(this, msg);
|
|
@@ -38661,7 +38666,7 @@ const prepSig = (msgh, priv, opts = signOpts) => {
|
|
|
38661
38666
|
/** RFC6979 3.6: additional k' (optional). See {@link ExtraEntropy}. */
|
|
38662
38667
|
// K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')
|
|
38663
38668
|
if (extraEntropy)
|
|
38664
|
-
seed.push(extraEntropy === true ? randomBytes$
|
|
38669
|
+
seed.push(extraEntropy === true ? randomBytes$2(L) : toU8(extraEntropy));
|
|
38665
38670
|
const m = h1i; // convert msg to bigint
|
|
38666
38671
|
// Converts signature params into point w r/s, checks result for validity.
|
|
38667
38672
|
// To transform k => Signature:
|
|
@@ -38678,7 +38683,7 @@ const prepSig = (msgh, priv, opts = signOpts) => {
|
|
|
38678
38683
|
const r = modN(q.x); // r = q.x mod n
|
|
38679
38684
|
if (r === 0n)
|
|
38680
38685
|
return;
|
|
38681
|
-
const ik = invert(k, N); // k^-1 mod n, NOT mod P
|
|
38686
|
+
const ik = invert$1(k, N); // k^-1 mod n, NOT mod P
|
|
38682
38687
|
const s = modN(ik * modN(m + modN(d * r))); // s = k^-1(m + rd) mod n
|
|
38683
38688
|
if (s === 0n)
|
|
38684
38689
|
return;
|
|
@@ -38691,7 +38696,7 @@ const prepSig = (msgh, priv, opts = signOpts) => {
|
|
|
38691
38696
|
}
|
|
38692
38697
|
return new Signature(r, normS, recovery); // use normS, not s
|
|
38693
38698
|
};
|
|
38694
|
-
return { seed: concatBytes$
|
|
38699
|
+
return { seed: concatBytes$3(...seed), k2sig };
|
|
38695
38700
|
};
|
|
38696
38701
|
// HMAC-DRBG from NIST 800-90. Minimal, non-full-spec - used for RFC6979 signatures.
|
|
38697
38702
|
const hmacDrbg = (asynchronous) => {
|
|
@@ -38783,7 +38788,7 @@ const verify = (sig, msgh, pub, opts = veriOpts) => {
|
|
|
38783
38788
|
const { r, s } = sigg;
|
|
38784
38789
|
if (lowS && highS(s))
|
|
38785
38790
|
return false; // lowS bans sig.s >= CURVE.n/2
|
|
38786
|
-
const is = invert(s, N); // s^-1
|
|
38791
|
+
const is = invert$1(s, N); // s^-1
|
|
38787
38792
|
const u1 = modN(h * is); // u1 = hs^-1 mod n
|
|
38788
38793
|
const u2 = modN(r * is); // u2 = rs^-1 mod n
|
|
38789
38794
|
const R = doubleScalarMulUns(P, u1, u2).toAffine(); // R = u1⋅G + u2⋅P
|
|
@@ -38809,9 +38814,9 @@ const recoverPublicKey = (sig, msgh) => {
|
|
|
38809
38814
|
const radj = recovery === 2 || recovery === 3 ? r + N : r;
|
|
38810
38815
|
afield(radj); // ensure q.x is still a field element
|
|
38811
38816
|
const head = getPrefix(big(recovery)); // head is 0x02 or 0x03
|
|
38812
|
-
const Rb = concatBytes$
|
|
38817
|
+
const Rb = concatBytes$3(head, numTo32b(radj)); // concat head + r
|
|
38813
38818
|
const R = Point.fromBytes(Rb);
|
|
38814
|
-
const ir = invert(radj, N); // r^-1
|
|
38819
|
+
const ir = invert$1(radj, N); // r^-1
|
|
38815
38820
|
const u1 = modN(-h * ir); // -hr^-1
|
|
38816
38821
|
const u2 = modN(s * ir); // sr^-1
|
|
38817
38822
|
return doubleScalarMulUns(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1)
|
|
@@ -38836,26 +38841,26 @@ const hashToPrivateKey = (hash) => {
|
|
|
38836
38841
|
const num = M(bytesToNumBE(hash), N - 1n);
|
|
38837
38842
|
return numTo32b(num + 1n);
|
|
38838
38843
|
};
|
|
38839
|
-
const randomPrivateKey = () => hashToPrivateKey(randomBytes$
|
|
38844
|
+
const randomPrivateKey = () => hashToPrivateKey(randomBytes$2(L + 16)); // FIPS 186 B.4.1.
|
|
38840
38845
|
const _sha = 'SHA-256';
|
|
38841
38846
|
/** Math, hex, byte helpers. Not in `utils` because utils share API with noble-curves. */
|
|
38842
38847
|
const etc = {
|
|
38843
|
-
hexToBytes: hexToBytes,
|
|
38844
|
-
bytesToHex: bytesToHex,
|
|
38845
|
-
concatBytes: concatBytes$
|
|
38848
|
+
hexToBytes: hexToBytes$1,
|
|
38849
|
+
bytesToHex: bytesToHex$1,
|
|
38850
|
+
concatBytes: concatBytes$3,
|
|
38846
38851
|
bytesToNumberBE: bytesToNumBE,
|
|
38847
38852
|
numberToBytesBE: numTo32b,
|
|
38848
38853
|
mod: M,
|
|
38849
|
-
invert: invert, // math utilities
|
|
38854
|
+
invert: invert$1, // math utilities
|
|
38850
38855
|
hmacSha256Async: async (key, ...msgs) => {
|
|
38851
38856
|
const s = subtle();
|
|
38852
38857
|
const name = 'HMAC';
|
|
38853
38858
|
const k = await s.importKey('raw', key, { name, hash: { name: _sha } }, false, ['sign']);
|
|
38854
|
-
return u8n(await s.sign(name, k, concatBytes$
|
|
38859
|
+
return u8n(await s.sign(name, k, concatBytes$3(...msgs)));
|
|
38855
38860
|
},
|
|
38856
38861
|
hmacSha256Sync: undefined, // For TypeScript. Actual logic is below
|
|
38857
38862
|
hashToPrivateKey: hashToPrivateKey,
|
|
38858
|
-
randomBytes: randomBytes$
|
|
38863
|
+
randomBytes: randomBytes$2,
|
|
38859
38864
|
};
|
|
38860
38865
|
/** Curve-specific utilities for private keys. */
|
|
38861
38866
|
const utils = {
|
|
@@ -38912,7 +38917,7 @@ const ctneg = (cnd, p) => {
|
|
|
38912
38917
|
*
|
|
38913
38918
|
* !! Precomputes can be disabled by commenting-out call of the wNAF() inside Point#multiply().
|
|
38914
38919
|
*/
|
|
38915
|
-
const wNAF = (n) => {
|
|
38920
|
+
const wNAF$1 = (n) => {
|
|
38916
38921
|
const comp = Gpows || (Gpows = precompute());
|
|
38917
38922
|
let p = I;
|
|
38918
38923
|
let f = G; // f must be G, or could become I in the end
|
|
@@ -38943,6 +38948,8 @@ const wNAF = (n) => {
|
|
|
38943
38948
|
return { p, f }; // return both real and fake points for JIT
|
|
38944
38949
|
};
|
|
38945
38950
|
|
|
38951
|
+
const crypto$1 = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;
|
|
38952
|
+
|
|
38946
38953
|
/**
|
|
38947
38954
|
* Utilities for hex, bytes, CSPRNG.
|
|
38948
38955
|
* @module
|
|
@@ -39006,6 +39013,65 @@ function createView$1(arr) {
|
|
|
39006
39013
|
function rotr(word, shift) {
|
|
39007
39014
|
return (word << (32 - shift)) | (word >>> shift);
|
|
39008
39015
|
}
|
|
39016
|
+
// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex
|
|
39017
|
+
const hasHexBuiltin = /* @__PURE__ */ (() =>
|
|
39018
|
+
// @ts-ignore
|
|
39019
|
+
typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();
|
|
39020
|
+
// Array where index 0xf0 (240) is mapped to string 'f0'
|
|
39021
|
+
const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
|
|
39022
|
+
/**
|
|
39023
|
+
* Convert byte array to hex string. Uses built-in function, when available.
|
|
39024
|
+
* @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
|
|
39025
|
+
*/
|
|
39026
|
+
function bytesToHex(bytes) {
|
|
39027
|
+
abytes(bytes);
|
|
39028
|
+
// @ts-ignore
|
|
39029
|
+
if (hasHexBuiltin)
|
|
39030
|
+
return bytes.toHex();
|
|
39031
|
+
// pre-caching improves the speed 6x
|
|
39032
|
+
let hex = '';
|
|
39033
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
39034
|
+
hex += hexes[bytes[i]];
|
|
39035
|
+
}
|
|
39036
|
+
return hex;
|
|
39037
|
+
}
|
|
39038
|
+
// We use optimized technique to convert hex string to byte array
|
|
39039
|
+
const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
|
|
39040
|
+
function asciiToBase16(ch) {
|
|
39041
|
+
if (ch >= asciis._0 && ch <= asciis._9)
|
|
39042
|
+
return ch - asciis._0; // '2' => 50-48
|
|
39043
|
+
if (ch >= asciis.A && ch <= asciis.F)
|
|
39044
|
+
return ch - (asciis.A - 10); // 'B' => 66-(65-10)
|
|
39045
|
+
if (ch >= asciis.a && ch <= asciis.f)
|
|
39046
|
+
return ch - (asciis.a - 10); // 'b' => 98-(97-10)
|
|
39047
|
+
return;
|
|
39048
|
+
}
|
|
39049
|
+
/**
|
|
39050
|
+
* Convert hex string to byte array. Uses built-in function, when available.
|
|
39051
|
+
* @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
|
|
39052
|
+
*/
|
|
39053
|
+
function hexToBytes(hex) {
|
|
39054
|
+
if (typeof hex !== 'string')
|
|
39055
|
+
throw new Error('hex string expected, got ' + typeof hex);
|
|
39056
|
+
// @ts-ignore
|
|
39057
|
+
if (hasHexBuiltin)
|
|
39058
|
+
return Uint8Array.fromHex(hex);
|
|
39059
|
+
const hl = hex.length;
|
|
39060
|
+
const al = hl / 2;
|
|
39061
|
+
if (hl % 2)
|
|
39062
|
+
throw new Error('hex string expected, got unpadded hex of length ' + hl);
|
|
39063
|
+
const array = new Uint8Array(al);
|
|
39064
|
+
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
|
|
39065
|
+
const n1 = asciiToBase16(hex.charCodeAt(hi));
|
|
39066
|
+
const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
|
|
39067
|
+
if (n1 === undefined || n2 === undefined) {
|
|
39068
|
+
const char = hex[hi] + hex[hi + 1];
|
|
39069
|
+
throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
|
|
39070
|
+
}
|
|
39071
|
+
array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163
|
|
39072
|
+
}
|
|
39073
|
+
return array;
|
|
39074
|
+
}
|
|
39009
39075
|
/**
|
|
39010
39076
|
* Converts string to bytes using UTF8 encoding.
|
|
39011
39077
|
* @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])
|
|
@@ -39026,6 +39092,22 @@ function toBytes$1(data) {
|
|
|
39026
39092
|
abytes(data);
|
|
39027
39093
|
return data;
|
|
39028
39094
|
}
|
|
39095
|
+
/** Copies several Uint8Arrays into one. */
|
|
39096
|
+
function concatBytes$2(...arrays) {
|
|
39097
|
+
let sum = 0;
|
|
39098
|
+
for (let i = 0; i < arrays.length; i++) {
|
|
39099
|
+
const a = arrays[i];
|
|
39100
|
+
abytes(a);
|
|
39101
|
+
sum += a.length;
|
|
39102
|
+
}
|
|
39103
|
+
const res = new Uint8Array(sum);
|
|
39104
|
+
for (let i = 0, pad = 0; i < arrays.length; i++) {
|
|
39105
|
+
const a = arrays[i];
|
|
39106
|
+
res.set(a, pad);
|
|
39107
|
+
pad += a.length;
|
|
39108
|
+
}
|
|
39109
|
+
return res;
|
|
39110
|
+
}
|
|
39029
39111
|
/** For runtime check if class implements interface */
|
|
39030
39112
|
class Hash {
|
|
39031
39113
|
}
|
|
@@ -39038,6 +39120,265 @@ function createHasher(hashCons) {
|
|
|
39038
39120
|
hashC.create = () => hashCons();
|
|
39039
39121
|
return hashC;
|
|
39040
39122
|
}
|
|
39123
|
+
/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */
|
|
39124
|
+
function randomBytes$1(bytesLength = 32) {
|
|
39125
|
+
if (crypto$1 && typeof crypto$1.getRandomValues === 'function') {
|
|
39126
|
+
return crypto$1.getRandomValues(new Uint8Array(bytesLength));
|
|
39127
|
+
}
|
|
39128
|
+
// Legacy Node.js compatibility
|
|
39129
|
+
if (crypto$1 && typeof crypto$1.randomBytes === 'function') {
|
|
39130
|
+
return Uint8Array.from(crypto$1.randomBytes(bytesLength));
|
|
39131
|
+
}
|
|
39132
|
+
throw new Error('crypto.getRandomValues must be defined');
|
|
39133
|
+
}
|
|
39134
|
+
|
|
39135
|
+
/**
|
|
39136
|
+
* Internal Merkle-Damgard hash utils.
|
|
39137
|
+
* @module
|
|
39138
|
+
*/
|
|
39139
|
+
/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */
|
|
39140
|
+
function setBigUint64$1(view, byteOffset, value, isLE) {
|
|
39141
|
+
if (typeof view.setBigUint64 === 'function')
|
|
39142
|
+
return view.setBigUint64(byteOffset, value, isLE);
|
|
39143
|
+
const _32n = BigInt(32);
|
|
39144
|
+
const _u32_max = BigInt(0xffffffff);
|
|
39145
|
+
const wh = Number((value >> _32n) & _u32_max);
|
|
39146
|
+
const wl = Number(value & _u32_max);
|
|
39147
|
+
const h = isLE ? 4 : 0;
|
|
39148
|
+
const l = isLE ? 0 : 4;
|
|
39149
|
+
view.setUint32(byteOffset + h, wh, isLE);
|
|
39150
|
+
view.setUint32(byteOffset + l, wl, isLE);
|
|
39151
|
+
}
|
|
39152
|
+
/** Choice: a ? b : c */
|
|
39153
|
+
function Chi(a, b, c) {
|
|
39154
|
+
return (a & b) ^ (~a & c);
|
|
39155
|
+
}
|
|
39156
|
+
/** Majority function, true if any two inputs is true. */
|
|
39157
|
+
function Maj(a, b, c) {
|
|
39158
|
+
return (a & b) ^ (a & c) ^ (b & c);
|
|
39159
|
+
}
|
|
39160
|
+
/**
|
|
39161
|
+
* Merkle-Damgard hash construction base class.
|
|
39162
|
+
* Could be used to create MD5, RIPEMD, SHA1, SHA2.
|
|
39163
|
+
*/
|
|
39164
|
+
class HashMD extends Hash {
|
|
39165
|
+
constructor(blockLen, outputLen, padOffset, isLE) {
|
|
39166
|
+
super();
|
|
39167
|
+
this.finished = false;
|
|
39168
|
+
this.length = 0;
|
|
39169
|
+
this.pos = 0;
|
|
39170
|
+
this.destroyed = false;
|
|
39171
|
+
this.blockLen = blockLen;
|
|
39172
|
+
this.outputLen = outputLen;
|
|
39173
|
+
this.padOffset = padOffset;
|
|
39174
|
+
this.isLE = isLE;
|
|
39175
|
+
this.buffer = new Uint8Array(blockLen);
|
|
39176
|
+
this.view = createView$1(this.buffer);
|
|
39177
|
+
}
|
|
39178
|
+
update(data) {
|
|
39179
|
+
aexists(this);
|
|
39180
|
+
data = toBytes$1(data);
|
|
39181
|
+
abytes(data);
|
|
39182
|
+
const { view, buffer, blockLen } = this;
|
|
39183
|
+
const len = data.length;
|
|
39184
|
+
for (let pos = 0; pos < len;) {
|
|
39185
|
+
const take = Math.min(blockLen - this.pos, len - pos);
|
|
39186
|
+
// Fast path: we have at least one block in input, cast it to view and process
|
|
39187
|
+
if (take === blockLen) {
|
|
39188
|
+
const dataView = createView$1(data);
|
|
39189
|
+
for (; blockLen <= len - pos; pos += blockLen)
|
|
39190
|
+
this.process(dataView, pos);
|
|
39191
|
+
continue;
|
|
39192
|
+
}
|
|
39193
|
+
buffer.set(data.subarray(pos, pos + take), this.pos);
|
|
39194
|
+
this.pos += take;
|
|
39195
|
+
pos += take;
|
|
39196
|
+
if (this.pos === blockLen) {
|
|
39197
|
+
this.process(view, 0);
|
|
39198
|
+
this.pos = 0;
|
|
39199
|
+
}
|
|
39200
|
+
}
|
|
39201
|
+
this.length += data.length;
|
|
39202
|
+
this.roundClean();
|
|
39203
|
+
return this;
|
|
39204
|
+
}
|
|
39205
|
+
digestInto(out) {
|
|
39206
|
+
aexists(this);
|
|
39207
|
+
aoutput(out, this);
|
|
39208
|
+
this.finished = true;
|
|
39209
|
+
// Padding
|
|
39210
|
+
// We can avoid allocation of buffer for padding completely if it
|
|
39211
|
+
// was previously not allocated here. But it won't change performance.
|
|
39212
|
+
const { buffer, view, blockLen, isLE } = this;
|
|
39213
|
+
let { pos } = this;
|
|
39214
|
+
// append the bit '1' to the message
|
|
39215
|
+
buffer[pos++] = 0b10000000;
|
|
39216
|
+
clean(this.buffer.subarray(pos));
|
|
39217
|
+
// we have less than padOffset left in buffer, so we cannot put length in
|
|
39218
|
+
// current block, need process it and pad again
|
|
39219
|
+
if (this.padOffset > blockLen - pos) {
|
|
39220
|
+
this.process(view, 0);
|
|
39221
|
+
pos = 0;
|
|
39222
|
+
}
|
|
39223
|
+
// Pad until full block byte with zeros
|
|
39224
|
+
for (let i = pos; i < blockLen; i++)
|
|
39225
|
+
buffer[i] = 0;
|
|
39226
|
+
// Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that
|
|
39227
|
+
// You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.
|
|
39228
|
+
// So we just write lowest 64 bits of that value.
|
|
39229
|
+
setBigUint64$1(view, blockLen - 8, BigInt(this.length * 8), isLE);
|
|
39230
|
+
this.process(view, 0);
|
|
39231
|
+
const oview = createView$1(out);
|
|
39232
|
+
const len = this.outputLen;
|
|
39233
|
+
// NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT
|
|
39234
|
+
if (len % 4)
|
|
39235
|
+
throw new Error('_sha2: outputLen should be aligned to 32bit');
|
|
39236
|
+
const outLen = len / 4;
|
|
39237
|
+
const state = this.get();
|
|
39238
|
+
if (outLen > state.length)
|
|
39239
|
+
throw new Error('_sha2: outputLen bigger than state');
|
|
39240
|
+
for (let i = 0; i < outLen; i++)
|
|
39241
|
+
oview.setUint32(4 * i, state[i], isLE);
|
|
39242
|
+
}
|
|
39243
|
+
digest() {
|
|
39244
|
+
const { buffer, outputLen } = this;
|
|
39245
|
+
this.digestInto(buffer);
|
|
39246
|
+
const res = buffer.slice(0, outputLen);
|
|
39247
|
+
this.destroy();
|
|
39248
|
+
return res;
|
|
39249
|
+
}
|
|
39250
|
+
_cloneInto(to) {
|
|
39251
|
+
to || (to = new this.constructor());
|
|
39252
|
+
to.set(...this.get());
|
|
39253
|
+
const { blockLen, buffer, length, finished, destroyed, pos } = this;
|
|
39254
|
+
to.destroyed = destroyed;
|
|
39255
|
+
to.finished = finished;
|
|
39256
|
+
to.length = length;
|
|
39257
|
+
to.pos = pos;
|
|
39258
|
+
if (length % blockLen)
|
|
39259
|
+
to.buffer.set(buffer);
|
|
39260
|
+
return to;
|
|
39261
|
+
}
|
|
39262
|
+
clone() {
|
|
39263
|
+
return this._cloneInto();
|
|
39264
|
+
}
|
|
39265
|
+
}
|
|
39266
|
+
/**
|
|
39267
|
+
* Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
|
|
39268
|
+
* Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
|
|
39269
|
+
*/
|
|
39270
|
+
/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */
|
|
39271
|
+
const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
|
|
39272
|
+
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
|
|
39273
|
+
]);
|
|
39274
|
+
|
|
39275
|
+
/**
|
|
39276
|
+
* SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
|
|
39277
|
+
* SHA256 is the fastest hash implementable in JS, even faster than Blake3.
|
|
39278
|
+
* Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and
|
|
39279
|
+
* [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).
|
|
39280
|
+
* @module
|
|
39281
|
+
*/
|
|
39282
|
+
/**
|
|
39283
|
+
* Round constants:
|
|
39284
|
+
* First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)
|
|
39285
|
+
*/
|
|
39286
|
+
// prettier-ignore
|
|
39287
|
+
const SHA256_K = /* @__PURE__ */ Uint32Array.from([
|
|
39288
|
+
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
|
|
39289
|
+
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
|
|
39290
|
+
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
|
39291
|
+
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
|
|
39292
|
+
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
|
|
39293
|
+
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
|
|
39294
|
+
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
|
|
39295
|
+
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
|
|
39296
|
+
]);
|
|
39297
|
+
/** Reusable temporary buffer. "W" comes straight from spec. */
|
|
39298
|
+
const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
|
|
39299
|
+
class SHA256 extends HashMD {
|
|
39300
|
+
constructor(outputLen = 32) {
|
|
39301
|
+
super(64, outputLen, 8, false);
|
|
39302
|
+
// We cannot use array here since array allows indexing by variable
|
|
39303
|
+
// which means optimizer/compiler cannot use registers.
|
|
39304
|
+
this.A = SHA256_IV[0] | 0;
|
|
39305
|
+
this.B = SHA256_IV[1] | 0;
|
|
39306
|
+
this.C = SHA256_IV[2] | 0;
|
|
39307
|
+
this.D = SHA256_IV[3] | 0;
|
|
39308
|
+
this.E = SHA256_IV[4] | 0;
|
|
39309
|
+
this.F = SHA256_IV[5] | 0;
|
|
39310
|
+
this.G = SHA256_IV[6] | 0;
|
|
39311
|
+
this.H = SHA256_IV[7] | 0;
|
|
39312
|
+
}
|
|
39313
|
+
get() {
|
|
39314
|
+
const { A, B, C, D, E, F, G, H } = this;
|
|
39315
|
+
return [A, B, C, D, E, F, G, H];
|
|
39316
|
+
}
|
|
39317
|
+
// prettier-ignore
|
|
39318
|
+
set(A, B, C, D, E, F, G, H) {
|
|
39319
|
+
this.A = A | 0;
|
|
39320
|
+
this.B = B | 0;
|
|
39321
|
+
this.C = C | 0;
|
|
39322
|
+
this.D = D | 0;
|
|
39323
|
+
this.E = E | 0;
|
|
39324
|
+
this.F = F | 0;
|
|
39325
|
+
this.G = G | 0;
|
|
39326
|
+
this.H = H | 0;
|
|
39327
|
+
}
|
|
39328
|
+
process(view, offset) {
|
|
39329
|
+
// Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array
|
|
39330
|
+
for (let i = 0; i < 16; i++, offset += 4)
|
|
39331
|
+
SHA256_W[i] = view.getUint32(offset, false);
|
|
39332
|
+
for (let i = 16; i < 64; i++) {
|
|
39333
|
+
const W15 = SHA256_W[i - 15];
|
|
39334
|
+
const W2 = SHA256_W[i - 2];
|
|
39335
|
+
const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);
|
|
39336
|
+
const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);
|
|
39337
|
+
SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;
|
|
39338
|
+
}
|
|
39339
|
+
// Compression function main loop, 64 rounds
|
|
39340
|
+
let { A, B, C, D, E, F, G, H } = this;
|
|
39341
|
+
for (let i = 0; i < 64; i++) {
|
|
39342
|
+
const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
|
|
39343
|
+
const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
|
|
39344
|
+
const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
|
|
39345
|
+
const T2 = (sigma0 + Maj(A, B, C)) | 0;
|
|
39346
|
+
H = G;
|
|
39347
|
+
G = F;
|
|
39348
|
+
F = E;
|
|
39349
|
+
E = (D + T1) | 0;
|
|
39350
|
+
D = C;
|
|
39351
|
+
C = B;
|
|
39352
|
+
B = A;
|
|
39353
|
+
A = (T1 + T2) | 0;
|
|
39354
|
+
}
|
|
39355
|
+
// Add the compressed chunk to the current hash value
|
|
39356
|
+
A = (A + this.A) | 0;
|
|
39357
|
+
B = (B + this.B) | 0;
|
|
39358
|
+
C = (C + this.C) | 0;
|
|
39359
|
+
D = (D + this.D) | 0;
|
|
39360
|
+
E = (E + this.E) | 0;
|
|
39361
|
+
F = (F + this.F) | 0;
|
|
39362
|
+
G = (G + this.G) | 0;
|
|
39363
|
+
H = (H + this.H) | 0;
|
|
39364
|
+
this.set(A, B, C, D, E, F, G, H);
|
|
39365
|
+
}
|
|
39366
|
+
roundClean() {
|
|
39367
|
+
clean(SHA256_W);
|
|
39368
|
+
}
|
|
39369
|
+
destroy() {
|
|
39370
|
+
this.set(0, 0, 0, 0, 0, 0, 0, 0);
|
|
39371
|
+
clean(this.buffer);
|
|
39372
|
+
}
|
|
39373
|
+
}
|
|
39374
|
+
/**
|
|
39375
|
+
* SHA2-256 hash function from RFC 4634.
|
|
39376
|
+
*
|
|
39377
|
+
* It is the fastest JS hash, even faster than Blake3.
|
|
39378
|
+
* To break sha256 using birthday attack, attackers need to try 2^128 hashes.
|
|
39379
|
+
* BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
|
|
39380
|
+
*/
|
|
39381
|
+
const sha256$2 = /* @__PURE__ */ createHasher(() => new SHA256());
|
|
39041
39382
|
|
|
39042
39383
|
/**
|
|
39043
39384
|
* HMAC: RFC2104 message authentication code.
|
|
@@ -39125,252 +39466,2554 @@ const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest(
|
|
|
39125
39466
|
hmac.create = (hash, key) => new HMAC(hash, key);
|
|
39126
39467
|
|
|
39127
39468
|
/**
|
|
39128
|
-
*
|
|
39469
|
+
* Hex, bytes and number utilities.
|
|
39129
39470
|
* @module
|
|
39130
39471
|
*/
|
|
39131
|
-
|
|
39132
|
-
|
|
39133
|
-
|
|
39134
|
-
|
|
39135
|
-
|
|
39136
|
-
|
|
39137
|
-
|
|
39138
|
-
|
|
39139
|
-
|
|
39140
|
-
|
|
39141
|
-
view.setUint32(byteOffset + h, wh, isLE);
|
|
39142
|
-
view.setUint32(byteOffset + l, wl, isLE);
|
|
39472
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
39473
|
+
const _0n$4 = /* @__PURE__ */ BigInt(0);
|
|
39474
|
+
const _1n$4 = /* @__PURE__ */ BigInt(1);
|
|
39475
|
+
// tmp name until v2
|
|
39476
|
+
function _abool2(value, title = '') {
|
|
39477
|
+
if (typeof value !== 'boolean') {
|
|
39478
|
+
const prefix = title && `"${title}"`;
|
|
39479
|
+
throw new Error(prefix + 'expected boolean, got type=' + typeof value);
|
|
39480
|
+
}
|
|
39481
|
+
return value;
|
|
39143
39482
|
}
|
|
39144
|
-
|
|
39145
|
-
|
|
39146
|
-
|
|
39483
|
+
// tmp name until v2
|
|
39484
|
+
/** Asserts something is Uint8Array. */
|
|
39485
|
+
function _abytes2(value, length, title = '') {
|
|
39486
|
+
const bytes = isBytes$2(value);
|
|
39487
|
+
const len = value?.length;
|
|
39488
|
+
const needsLen = length !== undefined;
|
|
39489
|
+
if (!bytes || (needsLen && len !== length)) {
|
|
39490
|
+
const prefix = title && `"${title}" `;
|
|
39491
|
+
const ofLen = needsLen ? ` of length ${length}` : '';
|
|
39492
|
+
const got = bytes ? `length=${len}` : `type=${typeof value}`;
|
|
39493
|
+
throw new Error(prefix + 'expected Uint8Array' + ofLen + ', got ' + got);
|
|
39494
|
+
}
|
|
39495
|
+
return value;
|
|
39147
39496
|
}
|
|
39148
|
-
|
|
39149
|
-
function
|
|
39150
|
-
|
|
39497
|
+
// Used in weierstrass, der
|
|
39498
|
+
function numberToHexUnpadded(num) {
|
|
39499
|
+
const hex = num.toString(16);
|
|
39500
|
+
return hex.length & 1 ? '0' + hex : hex;
|
|
39501
|
+
}
|
|
39502
|
+
function hexToNumber(hex) {
|
|
39503
|
+
if (typeof hex !== 'string')
|
|
39504
|
+
throw new Error('hex string expected, got ' + typeof hex);
|
|
39505
|
+
return hex === '' ? _0n$4 : BigInt('0x' + hex); // Big Endian
|
|
39506
|
+
}
|
|
39507
|
+
// BE: Big Endian, LE: Little Endian
|
|
39508
|
+
function bytesToNumberBE(bytes) {
|
|
39509
|
+
return hexToNumber(bytesToHex(bytes));
|
|
39510
|
+
}
|
|
39511
|
+
function bytesToNumberLE(bytes) {
|
|
39512
|
+
abytes(bytes);
|
|
39513
|
+
return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
|
|
39514
|
+
}
|
|
39515
|
+
function numberToBytesBE(n, len) {
|
|
39516
|
+
return hexToBytes(n.toString(16).padStart(len * 2, '0'));
|
|
39517
|
+
}
|
|
39518
|
+
function numberToBytesLE(n, len) {
|
|
39519
|
+
return numberToBytesBE(n, len).reverse();
|
|
39151
39520
|
}
|
|
39152
39521
|
/**
|
|
39153
|
-
*
|
|
39154
|
-
*
|
|
39522
|
+
* Takes hex string or Uint8Array, converts to Uint8Array.
|
|
39523
|
+
* Validates output length.
|
|
39524
|
+
* Will throw error for other types.
|
|
39525
|
+
* @param title descriptive title for an error e.g. 'secret key'
|
|
39526
|
+
* @param hex hex string or Uint8Array
|
|
39527
|
+
* @param expectedLength optional, will compare to result array's length
|
|
39528
|
+
* @returns
|
|
39155
39529
|
*/
|
|
39156
|
-
|
|
39157
|
-
|
|
39158
|
-
|
|
39159
|
-
|
|
39160
|
-
|
|
39161
|
-
|
|
39162
|
-
|
|
39163
|
-
|
|
39164
|
-
|
|
39165
|
-
this.padOffset = padOffset;
|
|
39166
|
-
this.isLE = isLE;
|
|
39167
|
-
this.buffer = new Uint8Array(blockLen);
|
|
39168
|
-
this.view = createView$1(this.buffer);
|
|
39530
|
+
function ensureBytes$1(title, hex, expectedLength) {
|
|
39531
|
+
let res;
|
|
39532
|
+
if (typeof hex === 'string') {
|
|
39533
|
+
try {
|
|
39534
|
+
res = hexToBytes(hex);
|
|
39535
|
+
}
|
|
39536
|
+
catch (e) {
|
|
39537
|
+
throw new Error(title + ' must be hex string or Uint8Array, cause: ' + e);
|
|
39538
|
+
}
|
|
39169
39539
|
}
|
|
39170
|
-
|
|
39171
|
-
|
|
39172
|
-
|
|
39173
|
-
|
|
39174
|
-
|
|
39175
|
-
|
|
39176
|
-
|
|
39177
|
-
|
|
39178
|
-
|
|
39179
|
-
|
|
39180
|
-
|
|
39181
|
-
|
|
39182
|
-
|
|
39183
|
-
|
|
39540
|
+
else if (isBytes$2(hex)) {
|
|
39541
|
+
// Uint8Array.from() instead of hash.slice() because node.js Buffer
|
|
39542
|
+
// is instance of Uint8Array, and its slice() creates **mutable** copy
|
|
39543
|
+
res = Uint8Array.from(hex);
|
|
39544
|
+
}
|
|
39545
|
+
else {
|
|
39546
|
+
throw new Error(title + ' must be hex string or Uint8Array');
|
|
39547
|
+
}
|
|
39548
|
+
const len = res.length;
|
|
39549
|
+
if (typeof expectedLength === 'number' && len !== expectedLength)
|
|
39550
|
+
throw new Error(title + ' of length ' + expectedLength + ' expected, got ' + len);
|
|
39551
|
+
return res;
|
|
39552
|
+
}
|
|
39553
|
+
/**
|
|
39554
|
+
* @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
|
|
39555
|
+
*/
|
|
39556
|
+
// export const utf8ToBytes: typeof utf8ToBytes_ = utf8ToBytes_;
|
|
39557
|
+
/**
|
|
39558
|
+
* Converts bytes to string using UTF8 encoding.
|
|
39559
|
+
* @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'
|
|
39560
|
+
*/
|
|
39561
|
+
// export const bytesToUtf8: typeof bytesToUtf8_ = bytesToUtf8_;
|
|
39562
|
+
// Is positive bigint
|
|
39563
|
+
const isPosBig = (n) => typeof n === 'bigint' && _0n$4 <= n;
|
|
39564
|
+
function inRange(n, min, max) {
|
|
39565
|
+
return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
|
|
39566
|
+
}
|
|
39567
|
+
/**
|
|
39568
|
+
* Asserts min <= n < max. NOTE: It's < max and not <= max.
|
|
39569
|
+
* @example
|
|
39570
|
+
* aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)
|
|
39571
|
+
*/
|
|
39572
|
+
function aInRange(title, n, min, max) {
|
|
39573
|
+
// Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?
|
|
39574
|
+
// consider P=256n, min=0n, max=P
|
|
39575
|
+
// - a for min=0 would require -1: `inRange('x', x, -1n, P)`
|
|
39576
|
+
// - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`
|
|
39577
|
+
// - our way is the cleanest: `inRange('x', x, 0n, P)
|
|
39578
|
+
if (!inRange(n, min, max))
|
|
39579
|
+
throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);
|
|
39580
|
+
}
|
|
39581
|
+
// Bit operations
|
|
39582
|
+
/**
|
|
39583
|
+
* Calculates amount of bits in a bigint.
|
|
39584
|
+
* Same as `n.toString(2).length`
|
|
39585
|
+
* TODO: merge with nLength in modular
|
|
39586
|
+
*/
|
|
39587
|
+
function bitLen(n) {
|
|
39588
|
+
let len;
|
|
39589
|
+
for (len = 0; n > _0n$4; n >>= _1n$4, len += 1)
|
|
39590
|
+
;
|
|
39591
|
+
return len;
|
|
39592
|
+
}
|
|
39593
|
+
/**
|
|
39594
|
+
* Calculate mask for N bits. Not using ** operator with bigints because of old engines.
|
|
39595
|
+
* Same as BigInt(`0b${Array(i).fill('1').join('')}`)
|
|
39596
|
+
*/
|
|
39597
|
+
const bitMask = (n) => (_1n$4 << BigInt(n)) - _1n$4;
|
|
39598
|
+
/**
|
|
39599
|
+
* Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
|
|
39600
|
+
* @returns function that will call DRBG until 2nd arg returns something meaningful
|
|
39601
|
+
* @example
|
|
39602
|
+
* const drbg = createHmacDRBG<Key>(32, 32, hmac);
|
|
39603
|
+
* drbg(seed, bytesToKey); // bytesToKey must return Key or undefined
|
|
39604
|
+
*/
|
|
39605
|
+
function createHmacDrbg(hashLen, qByteLen, hmacFn) {
|
|
39606
|
+
if (typeof hashLen !== 'number' || hashLen < 2)
|
|
39607
|
+
throw new Error('hashLen must be a number');
|
|
39608
|
+
if (typeof qByteLen !== 'number' || qByteLen < 2)
|
|
39609
|
+
throw new Error('qByteLen must be a number');
|
|
39610
|
+
if (typeof hmacFn !== 'function')
|
|
39611
|
+
throw new Error('hmacFn must be a function');
|
|
39612
|
+
// Step B, Step C: set hashLen to 8*ceil(hlen/8)
|
|
39613
|
+
const u8n = (len) => new Uint8Array(len); // creates Uint8Array
|
|
39614
|
+
const u8of = (byte) => Uint8Array.of(byte); // another shortcut
|
|
39615
|
+
let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
|
|
39616
|
+
let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same
|
|
39617
|
+
let i = 0; // Iterations counter, will throw when over 1000
|
|
39618
|
+
const reset = () => {
|
|
39619
|
+
v.fill(1);
|
|
39620
|
+
k.fill(0);
|
|
39621
|
+
i = 0;
|
|
39622
|
+
};
|
|
39623
|
+
const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)
|
|
39624
|
+
const reseed = (seed = u8n(0)) => {
|
|
39625
|
+
// HMAC-DRBG reseed() function. Steps D-G
|
|
39626
|
+
k = h(u8of(0x00), seed); // k = hmac(k || v || 0x00 || seed)
|
|
39627
|
+
v = h(); // v = hmac(k || v)
|
|
39628
|
+
if (seed.length === 0)
|
|
39629
|
+
return;
|
|
39630
|
+
k = h(u8of(0x01), seed); // k = hmac(k || v || 0x01 || seed)
|
|
39631
|
+
v = h(); // v = hmac(k || v)
|
|
39632
|
+
};
|
|
39633
|
+
const gen = () => {
|
|
39634
|
+
// HMAC-DRBG generate() function
|
|
39635
|
+
if (i++ >= 1000)
|
|
39636
|
+
throw new Error('drbg: tried 1000 values');
|
|
39637
|
+
let len = 0;
|
|
39638
|
+
const out = [];
|
|
39639
|
+
while (len < qByteLen) {
|
|
39640
|
+
v = h();
|
|
39641
|
+
const sl = v.slice();
|
|
39642
|
+
out.push(sl);
|
|
39643
|
+
len += v.length;
|
|
39644
|
+
}
|
|
39645
|
+
return concatBytes$2(...out);
|
|
39646
|
+
};
|
|
39647
|
+
const genUntil = (seed, pred) => {
|
|
39648
|
+
reset();
|
|
39649
|
+
reseed(seed); // Steps D-G
|
|
39650
|
+
let res = undefined; // Step H: grind until k is in [1..n-1]
|
|
39651
|
+
while (!(res = pred(gen())))
|
|
39652
|
+
reseed();
|
|
39653
|
+
reset();
|
|
39654
|
+
return res;
|
|
39655
|
+
};
|
|
39656
|
+
return genUntil;
|
|
39657
|
+
}
|
|
39658
|
+
function _validateObject(object, fields, optFields = {}) {
|
|
39659
|
+
if (!object || typeof object !== 'object')
|
|
39660
|
+
throw new Error('expected valid options object');
|
|
39661
|
+
function checkField(fieldName, expectedType, isOpt) {
|
|
39662
|
+
const val = object[fieldName];
|
|
39663
|
+
if (isOpt && val === undefined)
|
|
39664
|
+
return;
|
|
39665
|
+
const current = typeof val;
|
|
39666
|
+
if (current !== expectedType || val === null)
|
|
39667
|
+
throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
|
|
39668
|
+
}
|
|
39669
|
+
Object.entries(fields).forEach(([k, v]) => checkField(k, v, false));
|
|
39670
|
+
Object.entries(optFields).forEach(([k, v]) => checkField(k, v, true));
|
|
39671
|
+
}
|
|
39672
|
+
/**
|
|
39673
|
+
* Memoizes (caches) computation result.
|
|
39674
|
+
* Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.
|
|
39675
|
+
*/
|
|
39676
|
+
function memoized(fn) {
|
|
39677
|
+
const map = new WeakMap();
|
|
39678
|
+
return (arg, ...args) => {
|
|
39679
|
+
const val = map.get(arg);
|
|
39680
|
+
if (val !== undefined)
|
|
39681
|
+
return val;
|
|
39682
|
+
const computed = fn(arg, ...args);
|
|
39683
|
+
map.set(arg, computed);
|
|
39684
|
+
return computed;
|
|
39685
|
+
};
|
|
39686
|
+
}
|
|
39687
|
+
|
|
39688
|
+
/**
|
|
39689
|
+
* Utils for modular division and fields.
|
|
39690
|
+
* Field over 11 is a finite (Galois) field is integer number operations `mod 11`.
|
|
39691
|
+
* There is no division: it is replaced by modular multiplicative inverse.
|
|
39692
|
+
* @module
|
|
39693
|
+
*/
|
|
39694
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
39695
|
+
// prettier-ignore
|
|
39696
|
+
const _0n$3 = BigInt(0), _1n$3 = BigInt(1), _2n$2 = /* @__PURE__ */ BigInt(2), _3n$1 = /* @__PURE__ */ BigInt(3);
|
|
39697
|
+
// prettier-ignore
|
|
39698
|
+
const _4n$1 = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5), _7n = /* @__PURE__ */ BigInt(7);
|
|
39699
|
+
// prettier-ignore
|
|
39700
|
+
const _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9), _16n = /* @__PURE__ */ BigInt(16);
|
|
39701
|
+
// Calculates a modulo b
|
|
39702
|
+
function mod(a, b) {
|
|
39703
|
+
const result = a % b;
|
|
39704
|
+
return result >= _0n$3 ? result : b + result;
|
|
39705
|
+
}
|
|
39706
|
+
/** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */
|
|
39707
|
+
function pow2(x, power, modulo) {
|
|
39708
|
+
let res = x;
|
|
39709
|
+
while (power-- > _0n$3) {
|
|
39710
|
+
res *= res;
|
|
39711
|
+
res %= modulo;
|
|
39712
|
+
}
|
|
39713
|
+
return res;
|
|
39714
|
+
}
|
|
39715
|
+
/**
|
|
39716
|
+
* Inverses number over modulo.
|
|
39717
|
+
* Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).
|
|
39718
|
+
*/
|
|
39719
|
+
function invert(number, modulo) {
|
|
39720
|
+
if (number === _0n$3)
|
|
39721
|
+
throw new Error('invert: expected non-zero number');
|
|
39722
|
+
if (modulo <= _0n$3)
|
|
39723
|
+
throw new Error('invert: expected positive modulus, got ' + modulo);
|
|
39724
|
+
// Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower.
|
|
39725
|
+
let a = mod(number, modulo);
|
|
39726
|
+
let b = modulo;
|
|
39727
|
+
// prettier-ignore
|
|
39728
|
+
let x = _0n$3, u = _1n$3;
|
|
39729
|
+
while (a !== _0n$3) {
|
|
39730
|
+
// JIT applies optimization if those two lines follow each other
|
|
39731
|
+
const q = b / a;
|
|
39732
|
+
const r = b % a;
|
|
39733
|
+
const m = x - u * q;
|
|
39734
|
+
// prettier-ignore
|
|
39735
|
+
b = a, a = r, x = u, u = m;
|
|
39736
|
+
}
|
|
39737
|
+
const gcd = b;
|
|
39738
|
+
if (gcd !== _1n$3)
|
|
39739
|
+
throw new Error('invert: does not exist');
|
|
39740
|
+
return mod(x, modulo);
|
|
39741
|
+
}
|
|
39742
|
+
function assertIsSquare(Fp, root, n) {
|
|
39743
|
+
if (!Fp.eql(Fp.sqr(root), n))
|
|
39744
|
+
throw new Error('Cannot find square root');
|
|
39745
|
+
}
|
|
39746
|
+
// Not all roots are possible! Example which will throw:
|
|
39747
|
+
// const NUM =
|
|
39748
|
+
// n = 72057594037927816n;
|
|
39749
|
+
// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));
|
|
39750
|
+
function sqrt3mod4(Fp, n) {
|
|
39751
|
+
const p1div4 = (Fp.ORDER + _1n$3) / _4n$1;
|
|
39752
|
+
const root = Fp.pow(n, p1div4);
|
|
39753
|
+
assertIsSquare(Fp, root, n);
|
|
39754
|
+
return root;
|
|
39755
|
+
}
|
|
39756
|
+
function sqrt5mod8(Fp, n) {
|
|
39757
|
+
const p5div8 = (Fp.ORDER - _5n) / _8n;
|
|
39758
|
+
const n2 = Fp.mul(n, _2n$2);
|
|
39759
|
+
const v = Fp.pow(n2, p5div8);
|
|
39760
|
+
const nv = Fp.mul(n, v);
|
|
39761
|
+
const i = Fp.mul(Fp.mul(nv, _2n$2), v);
|
|
39762
|
+
const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
|
|
39763
|
+
assertIsSquare(Fp, root, n);
|
|
39764
|
+
return root;
|
|
39765
|
+
}
|
|
39766
|
+
// Based on RFC9380, Kong algorithm
|
|
39767
|
+
// prettier-ignore
|
|
39768
|
+
function sqrt9mod16(P) {
|
|
39769
|
+
const Fp_ = Field(P);
|
|
39770
|
+
const tn = tonelliShanks(P);
|
|
39771
|
+
const c1 = tn(Fp_, Fp_.neg(Fp_.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F
|
|
39772
|
+
const c2 = tn(Fp_, c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F
|
|
39773
|
+
const c3 = tn(Fp_, Fp_.neg(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F
|
|
39774
|
+
const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic
|
|
39775
|
+
return (Fp, n) => {
|
|
39776
|
+
let tv1 = Fp.pow(n, c4); // 1. tv1 = x^c4
|
|
39777
|
+
let tv2 = Fp.mul(tv1, c1); // 2. tv2 = c1 * tv1
|
|
39778
|
+
const tv3 = Fp.mul(tv1, c2); // 3. tv3 = c2 * tv1
|
|
39779
|
+
const tv4 = Fp.mul(tv1, c3); // 4. tv4 = c3 * tv1
|
|
39780
|
+
const e1 = Fp.eql(Fp.sqr(tv2), n); // 5. e1 = (tv2^2) == x
|
|
39781
|
+
const e2 = Fp.eql(Fp.sqr(tv3), n); // 6. e2 = (tv3^2) == x
|
|
39782
|
+
tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x
|
|
39783
|
+
tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x
|
|
39784
|
+
const e3 = Fp.eql(Fp.sqr(tv2), n); // 9. e3 = (tv2^2) == x
|
|
39785
|
+
const root = Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select sqrt from tv1 & tv2
|
|
39786
|
+
assertIsSquare(Fp, root, n);
|
|
39787
|
+
return root;
|
|
39788
|
+
};
|
|
39789
|
+
}
|
|
39790
|
+
/**
|
|
39791
|
+
* Tonelli-Shanks square root search algorithm.
|
|
39792
|
+
* 1. https://eprint.iacr.org/2012/685.pdf (page 12)
|
|
39793
|
+
* 2. Square Roots from 1; 24, 51, 10 to Dan Shanks
|
|
39794
|
+
* @param P field order
|
|
39795
|
+
* @returns function that takes field Fp (created from P) and number n
|
|
39796
|
+
*/
|
|
39797
|
+
function tonelliShanks(P) {
|
|
39798
|
+
// Initialization (precomputation).
|
|
39799
|
+
// Caching initialization could boost perf by 7%.
|
|
39800
|
+
if (P < _3n$1)
|
|
39801
|
+
throw new Error('sqrt is not defined for small field');
|
|
39802
|
+
// Factor P - 1 = Q * 2^S, where Q is odd
|
|
39803
|
+
let Q = P - _1n$3;
|
|
39804
|
+
let S = 0;
|
|
39805
|
+
while (Q % _2n$2 === _0n$3) {
|
|
39806
|
+
Q /= _2n$2;
|
|
39807
|
+
S++;
|
|
39808
|
+
}
|
|
39809
|
+
// Find the first quadratic non-residue Z >= 2
|
|
39810
|
+
let Z = _2n$2;
|
|
39811
|
+
const _Fp = Field(P);
|
|
39812
|
+
while (FpLegendre(_Fp, Z) === 1) {
|
|
39813
|
+
// Basic primality test for P. After x iterations, chance of
|
|
39814
|
+
// not finding quadratic non-residue is 2^x, so 2^1000.
|
|
39815
|
+
if (Z++ > 1000)
|
|
39816
|
+
throw new Error('Cannot find square root: probably non-prime P');
|
|
39817
|
+
}
|
|
39818
|
+
// Fast-path; usually done before Z, but we do "primality test".
|
|
39819
|
+
if (S === 1)
|
|
39820
|
+
return sqrt3mod4;
|
|
39821
|
+
// Slow-path
|
|
39822
|
+
// TODO: test on Fp2 and others
|
|
39823
|
+
let cc = _Fp.pow(Z, Q); // c = z^Q
|
|
39824
|
+
const Q1div2 = (Q + _1n$3) / _2n$2;
|
|
39825
|
+
return function tonelliSlow(Fp, n) {
|
|
39826
|
+
if (Fp.is0(n))
|
|
39827
|
+
return n;
|
|
39828
|
+
// Check if n is a quadratic residue using Legendre symbol
|
|
39829
|
+
if (FpLegendre(Fp, n) !== 1)
|
|
39830
|
+
throw new Error('Cannot find square root');
|
|
39831
|
+
// Initialize variables for the main loop
|
|
39832
|
+
let M = S;
|
|
39833
|
+
let c = Fp.mul(Fp.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp
|
|
39834
|
+
let t = Fp.pow(n, Q); // t = n^Q, first guess at the fudge factor
|
|
39835
|
+
let R = Fp.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root
|
|
39836
|
+
// Main loop
|
|
39837
|
+
// while t != 1
|
|
39838
|
+
while (!Fp.eql(t, Fp.ONE)) {
|
|
39839
|
+
if (Fp.is0(t))
|
|
39840
|
+
return Fp.ZERO; // if t=0 return R=0
|
|
39841
|
+
let i = 1;
|
|
39842
|
+
// Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)
|
|
39843
|
+
let t_tmp = Fp.sqr(t); // t^(2^1)
|
|
39844
|
+
while (!Fp.eql(t_tmp, Fp.ONE)) {
|
|
39845
|
+
i++;
|
|
39846
|
+
t_tmp = Fp.sqr(t_tmp); // t^(2^2)...
|
|
39847
|
+
if (i === M)
|
|
39848
|
+
throw new Error('Cannot find square root');
|
|
39184
39849
|
}
|
|
39185
|
-
|
|
39186
|
-
|
|
39187
|
-
|
|
39188
|
-
|
|
39189
|
-
|
|
39190
|
-
|
|
39850
|
+
// Calculate the exponent for b: 2^(M - i - 1)
|
|
39851
|
+
const exponent = _1n$3 << BigInt(M - i - 1); // bigint is important
|
|
39852
|
+
const b = Fp.pow(c, exponent); // b = 2^(M - i - 1)
|
|
39853
|
+
// Update variables
|
|
39854
|
+
M = i;
|
|
39855
|
+
c = Fp.sqr(b); // c = b^2
|
|
39856
|
+
t = Fp.mul(t, c); // t = (t * b^2)
|
|
39857
|
+
R = Fp.mul(R, b); // R = R*b
|
|
39858
|
+
}
|
|
39859
|
+
return R;
|
|
39860
|
+
};
|
|
39861
|
+
}
|
|
39862
|
+
/**
|
|
39863
|
+
* Square root for a finite field. Will try optimized versions first:
|
|
39864
|
+
*
|
|
39865
|
+
* 1. P ≡ 3 (mod 4)
|
|
39866
|
+
* 2. P ≡ 5 (mod 8)
|
|
39867
|
+
* 3. P ≡ 9 (mod 16)
|
|
39868
|
+
* 4. Tonelli-Shanks algorithm
|
|
39869
|
+
*
|
|
39870
|
+
* Different algorithms can give different roots, it is up to user to decide which one they want.
|
|
39871
|
+
* For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).
|
|
39872
|
+
*/
|
|
39873
|
+
function FpSqrt(P) {
|
|
39874
|
+
// P ≡ 3 (mod 4) => √n = n^((P+1)/4)
|
|
39875
|
+
if (P % _4n$1 === _3n$1)
|
|
39876
|
+
return sqrt3mod4;
|
|
39877
|
+
// P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf
|
|
39878
|
+
if (P % _8n === _5n)
|
|
39879
|
+
return sqrt5mod8;
|
|
39880
|
+
// P ≡ 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)
|
|
39881
|
+
if (P % _16n === _9n)
|
|
39882
|
+
return sqrt9mod16(P);
|
|
39883
|
+
// Tonelli-Shanks algorithm
|
|
39884
|
+
return tonelliShanks(P);
|
|
39885
|
+
}
|
|
39886
|
+
// prettier-ignore
|
|
39887
|
+
const FIELD_FIELDS = [
|
|
39888
|
+
'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',
|
|
39889
|
+
'eql', 'add', 'sub', 'mul', 'pow', 'div',
|
|
39890
|
+
'addN', 'subN', 'mulN', 'sqrN'
|
|
39891
|
+
];
|
|
39892
|
+
function validateField(field) {
|
|
39893
|
+
const initial = {
|
|
39894
|
+
ORDER: 'bigint',
|
|
39895
|
+
MASK: 'bigint',
|
|
39896
|
+
BYTES: 'number',
|
|
39897
|
+
BITS: 'number',
|
|
39898
|
+
};
|
|
39899
|
+
const opts = FIELD_FIELDS.reduce((map, val) => {
|
|
39900
|
+
map[val] = 'function';
|
|
39901
|
+
return map;
|
|
39902
|
+
}, initial);
|
|
39903
|
+
_validateObject(field, opts);
|
|
39904
|
+
// const max = 16384;
|
|
39905
|
+
// if (field.BYTES < 1 || field.BYTES > max) throw new Error('invalid field');
|
|
39906
|
+
// if (field.BITS < 1 || field.BITS > 8 * max) throw new Error('invalid field');
|
|
39907
|
+
return field;
|
|
39908
|
+
}
|
|
39909
|
+
// Generic field functions
|
|
39910
|
+
/**
|
|
39911
|
+
* Same as `pow` but for Fp: non-constant-time.
|
|
39912
|
+
* Unsafe in some contexts: uses ladder, so can expose bigint bits.
|
|
39913
|
+
*/
|
|
39914
|
+
function FpPow(Fp, num, power) {
|
|
39915
|
+
if (power < _0n$3)
|
|
39916
|
+
throw new Error('invalid exponent, negatives unsupported');
|
|
39917
|
+
if (power === _0n$3)
|
|
39918
|
+
return Fp.ONE;
|
|
39919
|
+
if (power === _1n$3)
|
|
39920
|
+
return num;
|
|
39921
|
+
let p = Fp.ONE;
|
|
39922
|
+
let d = num;
|
|
39923
|
+
while (power > _0n$3) {
|
|
39924
|
+
if (power & _1n$3)
|
|
39925
|
+
p = Fp.mul(p, d);
|
|
39926
|
+
d = Fp.sqr(d);
|
|
39927
|
+
power >>= _1n$3;
|
|
39928
|
+
}
|
|
39929
|
+
return p;
|
|
39930
|
+
}
|
|
39931
|
+
/**
|
|
39932
|
+
* Efficiently invert an array of Field elements.
|
|
39933
|
+
* Exception-free. Will return `undefined` for 0 elements.
|
|
39934
|
+
* @param passZero map 0 to 0 (instead of undefined)
|
|
39935
|
+
*/
|
|
39936
|
+
function FpInvertBatch(Fp, nums, passZero = false) {
|
|
39937
|
+
const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);
|
|
39938
|
+
// Walk from first to last, multiply them by each other MOD p
|
|
39939
|
+
const multipliedAcc = nums.reduce((acc, num, i) => {
|
|
39940
|
+
if (Fp.is0(num))
|
|
39941
|
+
return acc;
|
|
39942
|
+
inverted[i] = acc;
|
|
39943
|
+
return Fp.mul(acc, num);
|
|
39944
|
+
}, Fp.ONE);
|
|
39945
|
+
// Invert last element
|
|
39946
|
+
const invertedAcc = Fp.inv(multipliedAcc);
|
|
39947
|
+
// Walk from last to first, multiply them by inverted each other MOD p
|
|
39948
|
+
nums.reduceRight((acc, num, i) => {
|
|
39949
|
+
if (Fp.is0(num))
|
|
39950
|
+
return acc;
|
|
39951
|
+
inverted[i] = Fp.mul(acc, inverted[i]);
|
|
39952
|
+
return Fp.mul(acc, num);
|
|
39953
|
+
}, invertedAcc);
|
|
39954
|
+
return inverted;
|
|
39955
|
+
}
|
|
39956
|
+
/**
|
|
39957
|
+
* Legendre symbol.
|
|
39958
|
+
* Legendre constant is used to calculate Legendre symbol (a | p)
|
|
39959
|
+
* which denotes the value of a^((p-1)/2) (mod p).
|
|
39960
|
+
*
|
|
39961
|
+
* * (a | p) ≡ 1 if a is a square (mod p), quadratic residue
|
|
39962
|
+
* * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue
|
|
39963
|
+
* * (a | p) ≡ 0 if a ≡ 0 (mod p)
|
|
39964
|
+
*/
|
|
39965
|
+
function FpLegendre(Fp, n) {
|
|
39966
|
+
// We can use 3rd argument as optional cache of this value
|
|
39967
|
+
// but seems unneeded for now. The operation is very fast.
|
|
39968
|
+
const p1mod2 = (Fp.ORDER - _1n$3) / _2n$2;
|
|
39969
|
+
const powered = Fp.pow(n, p1mod2);
|
|
39970
|
+
const yes = Fp.eql(powered, Fp.ONE);
|
|
39971
|
+
const zero = Fp.eql(powered, Fp.ZERO);
|
|
39972
|
+
const no = Fp.eql(powered, Fp.neg(Fp.ONE));
|
|
39973
|
+
if (!yes && !zero && !no)
|
|
39974
|
+
throw new Error('invalid Legendre symbol result');
|
|
39975
|
+
return yes ? 1 : zero ? 0 : -1;
|
|
39976
|
+
}
|
|
39977
|
+
// CURVE.n lengths
|
|
39978
|
+
function nLength(n, nBitLength) {
|
|
39979
|
+
// Bit size, byte size of CURVE.n
|
|
39980
|
+
if (nBitLength !== undefined)
|
|
39981
|
+
anumber(nBitLength);
|
|
39982
|
+
const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;
|
|
39983
|
+
const nByteLength = Math.ceil(_nBitLength / 8);
|
|
39984
|
+
return { nBitLength: _nBitLength, nByteLength };
|
|
39985
|
+
}
|
|
39986
|
+
/**
|
|
39987
|
+
* Creates a finite field. Major performance optimizations:
|
|
39988
|
+
* * 1. Denormalized operations like mulN instead of mul.
|
|
39989
|
+
* * 2. Identical object shape: never add or remove keys.
|
|
39990
|
+
* * 3. `Object.freeze`.
|
|
39991
|
+
* Fragile: always run a benchmark on a change.
|
|
39992
|
+
* Security note: operations don't check 'isValid' for all elements for performance reasons,
|
|
39993
|
+
* it is caller responsibility to check this.
|
|
39994
|
+
* This is low-level code, please make sure you know what you're doing.
|
|
39995
|
+
*
|
|
39996
|
+
* Note about field properties:
|
|
39997
|
+
* * CHARACTERISTIC p = prime number, number of elements in main subgroup.
|
|
39998
|
+
* * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.
|
|
39999
|
+
*
|
|
40000
|
+
* @param ORDER field order, probably prime, or could be composite
|
|
40001
|
+
* @param bitLen how many bits the field consumes
|
|
40002
|
+
* @param isLE (default: false) if encoding / decoding should be in little-endian
|
|
40003
|
+
* @param redef optional faster redefinitions of sqrt and other methods
|
|
40004
|
+
*/
|
|
40005
|
+
function Field(ORDER, bitLenOrOpts, // TODO: use opts only in v2?
|
|
40006
|
+
isLE = false, opts = {}) {
|
|
40007
|
+
if (ORDER <= _0n$3)
|
|
40008
|
+
throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);
|
|
40009
|
+
let _nbitLength = undefined;
|
|
40010
|
+
let _sqrt = undefined;
|
|
40011
|
+
let modFromBytes = false;
|
|
40012
|
+
let allowedLengths = undefined;
|
|
40013
|
+
if (typeof bitLenOrOpts === 'object' && bitLenOrOpts != null) {
|
|
40014
|
+
if (opts.sqrt || isLE)
|
|
40015
|
+
throw new Error('cannot specify opts in two arguments');
|
|
40016
|
+
const _opts = bitLenOrOpts;
|
|
40017
|
+
if (_opts.BITS)
|
|
40018
|
+
_nbitLength = _opts.BITS;
|
|
40019
|
+
if (_opts.sqrt)
|
|
40020
|
+
_sqrt = _opts.sqrt;
|
|
40021
|
+
if (typeof _opts.isLE === 'boolean')
|
|
40022
|
+
isLE = _opts.isLE;
|
|
40023
|
+
if (typeof _opts.modFromBytes === 'boolean')
|
|
40024
|
+
modFromBytes = _opts.modFromBytes;
|
|
40025
|
+
allowedLengths = _opts.allowedLengths;
|
|
40026
|
+
}
|
|
40027
|
+
else {
|
|
40028
|
+
if (typeof bitLenOrOpts === 'number')
|
|
40029
|
+
_nbitLength = bitLenOrOpts;
|
|
40030
|
+
if (opts.sqrt)
|
|
40031
|
+
_sqrt = opts.sqrt;
|
|
40032
|
+
}
|
|
40033
|
+
const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, _nbitLength);
|
|
40034
|
+
if (BYTES > 2048)
|
|
40035
|
+
throw new Error('invalid field: expected ORDER of <= 2048 bytes');
|
|
40036
|
+
let sqrtP; // cached sqrtP
|
|
40037
|
+
const f = Object.freeze({
|
|
40038
|
+
ORDER,
|
|
40039
|
+
isLE,
|
|
40040
|
+
BITS,
|
|
40041
|
+
BYTES,
|
|
40042
|
+
MASK: bitMask(BITS),
|
|
40043
|
+
ZERO: _0n$3,
|
|
40044
|
+
ONE: _1n$3,
|
|
40045
|
+
allowedLengths: allowedLengths,
|
|
40046
|
+
create: (num) => mod(num, ORDER),
|
|
40047
|
+
isValid: (num) => {
|
|
40048
|
+
if (typeof num !== 'bigint')
|
|
40049
|
+
throw new Error('invalid field element: expected bigint, got ' + typeof num);
|
|
40050
|
+
return _0n$3 <= num && num < ORDER; // 0 is valid element, but it's not invertible
|
|
40051
|
+
},
|
|
40052
|
+
is0: (num) => num === _0n$3,
|
|
40053
|
+
// is valid and invertible
|
|
40054
|
+
isValidNot0: (num) => !f.is0(num) && f.isValid(num),
|
|
40055
|
+
isOdd: (num) => (num & _1n$3) === _1n$3,
|
|
40056
|
+
neg: (num) => mod(-num, ORDER),
|
|
40057
|
+
eql: (lhs, rhs) => lhs === rhs,
|
|
40058
|
+
sqr: (num) => mod(num * num, ORDER),
|
|
40059
|
+
add: (lhs, rhs) => mod(lhs + rhs, ORDER),
|
|
40060
|
+
sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
|
|
40061
|
+
mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
|
|
40062
|
+
pow: (num, power) => FpPow(f, num, power),
|
|
40063
|
+
div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
|
|
40064
|
+
// Same as above, but doesn't normalize
|
|
40065
|
+
sqrN: (num) => num * num,
|
|
40066
|
+
addN: (lhs, rhs) => lhs + rhs,
|
|
40067
|
+
subN: (lhs, rhs) => lhs - rhs,
|
|
40068
|
+
mulN: (lhs, rhs) => lhs * rhs,
|
|
40069
|
+
inv: (num) => invert(num, ORDER),
|
|
40070
|
+
sqrt: _sqrt ||
|
|
40071
|
+
((n) => {
|
|
40072
|
+
if (!sqrtP)
|
|
40073
|
+
sqrtP = FpSqrt(ORDER);
|
|
40074
|
+
return sqrtP(f, n);
|
|
40075
|
+
}),
|
|
40076
|
+
toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),
|
|
40077
|
+
fromBytes: (bytes, skipValidation = true) => {
|
|
40078
|
+
if (allowedLengths) {
|
|
40079
|
+
if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
|
|
40080
|
+
throw new Error('Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length);
|
|
40081
|
+
}
|
|
40082
|
+
const padded = new Uint8Array(BYTES);
|
|
40083
|
+
// isLE add 0 to right, !isLE to the left.
|
|
40084
|
+
padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
|
|
40085
|
+
bytes = padded;
|
|
40086
|
+
}
|
|
40087
|
+
if (bytes.length !== BYTES)
|
|
40088
|
+
throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);
|
|
40089
|
+
let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
|
|
40090
|
+
if (modFromBytes)
|
|
40091
|
+
scalar = mod(scalar, ORDER);
|
|
40092
|
+
if (!skipValidation)
|
|
40093
|
+
if (!f.isValid(scalar))
|
|
40094
|
+
throw new Error('invalid field element: outside of range 0..ORDER');
|
|
40095
|
+
// NOTE: we don't validate scalar here, please use isValid. This done such way because some
|
|
40096
|
+
// protocol may allow non-reduced scalar that reduced later or changed some other way.
|
|
40097
|
+
return scalar;
|
|
40098
|
+
},
|
|
40099
|
+
// TODO: we don't need it here, move out to separate fn
|
|
40100
|
+
invertBatch: (lst) => FpInvertBatch(f, lst),
|
|
40101
|
+
// We can't move this out because Fp6, Fp12 implement it
|
|
40102
|
+
// and it's unclear what to return in there.
|
|
40103
|
+
cmov: (a, b, c) => (c ? b : a),
|
|
40104
|
+
});
|
|
40105
|
+
return Object.freeze(f);
|
|
40106
|
+
}
|
|
40107
|
+
/**
|
|
40108
|
+
* Returns total number of bytes consumed by the field element.
|
|
40109
|
+
* For example, 32 bytes for usual 256-bit weierstrass curve.
|
|
40110
|
+
* @param fieldOrder number of field elements, usually CURVE.n
|
|
40111
|
+
* @returns byte length of field
|
|
40112
|
+
*/
|
|
40113
|
+
function getFieldBytesLength(fieldOrder) {
|
|
40114
|
+
if (typeof fieldOrder !== 'bigint')
|
|
40115
|
+
throw new Error('field order must be bigint');
|
|
40116
|
+
const bitLength = fieldOrder.toString(2).length;
|
|
40117
|
+
return Math.ceil(bitLength / 8);
|
|
40118
|
+
}
|
|
40119
|
+
/**
|
|
40120
|
+
* Returns minimal amount of bytes that can be safely reduced
|
|
40121
|
+
* by field order.
|
|
40122
|
+
* Should be 2^-128 for 128-bit curve such as P256.
|
|
40123
|
+
* @param fieldOrder number of field elements, usually CURVE.n
|
|
40124
|
+
* @returns byte length of target hash
|
|
40125
|
+
*/
|
|
40126
|
+
function getMinHashLength(fieldOrder) {
|
|
40127
|
+
const length = getFieldBytesLength(fieldOrder);
|
|
40128
|
+
return length + Math.ceil(length / 2);
|
|
40129
|
+
}
|
|
40130
|
+
/**
|
|
40131
|
+
* "Constant-time" private key generation utility.
|
|
40132
|
+
* Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF
|
|
40133
|
+
* and convert them into private scalar, with the modulo bias being negligible.
|
|
40134
|
+
* Needs at least 48 bytes of input for 32-byte private key.
|
|
40135
|
+
* https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/
|
|
40136
|
+
* FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final
|
|
40137
|
+
* RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5
|
|
40138
|
+
* @param hash hash output from SHA3 or a similar function
|
|
40139
|
+
* @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)
|
|
40140
|
+
* @param isLE interpret hash bytes as LE num
|
|
40141
|
+
* @returns valid private scalar
|
|
40142
|
+
*/
|
|
40143
|
+
function mapHashToField(key, fieldOrder, isLE = false) {
|
|
40144
|
+
const len = key.length;
|
|
40145
|
+
const fieldLen = getFieldBytesLength(fieldOrder);
|
|
40146
|
+
const minLen = getMinHashLength(fieldOrder);
|
|
40147
|
+
// No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.
|
|
40148
|
+
if (len < 16 || len < minLen || len > 1024)
|
|
40149
|
+
throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);
|
|
40150
|
+
const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);
|
|
40151
|
+
// `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0
|
|
40152
|
+
const reduced = mod(num, fieldOrder - _1n$3) + _1n$3;
|
|
40153
|
+
return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
|
|
40154
|
+
}
|
|
40155
|
+
|
|
40156
|
+
/**
|
|
40157
|
+
* Methods for elliptic curve multiplication by scalars.
|
|
40158
|
+
* Contains wNAF, pippenger.
|
|
40159
|
+
* @module
|
|
40160
|
+
*/
|
|
40161
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
40162
|
+
const _0n$2 = BigInt(0);
|
|
40163
|
+
const _1n$2 = BigInt(1);
|
|
40164
|
+
function negateCt(condition, item) {
|
|
40165
|
+
const neg = item.negate();
|
|
40166
|
+
return condition ? neg : item;
|
|
40167
|
+
}
|
|
40168
|
+
/**
|
|
40169
|
+
* Takes a bunch of Projective Points but executes only one
|
|
40170
|
+
* inversion on all of them. Inversion is very slow operation,
|
|
40171
|
+
* so this improves performance massively.
|
|
40172
|
+
* Optimization: converts a list of projective points to a list of identical points with Z=1.
|
|
40173
|
+
*/
|
|
40174
|
+
function normalizeZ(c, points) {
|
|
40175
|
+
const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
|
|
40176
|
+
return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
|
|
40177
|
+
}
|
|
40178
|
+
function validateW(W, bits) {
|
|
40179
|
+
if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
|
|
40180
|
+
throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);
|
|
40181
|
+
}
|
|
40182
|
+
function calcWOpts(W, scalarBits) {
|
|
40183
|
+
validateW(W, scalarBits);
|
|
40184
|
+
const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero
|
|
40185
|
+
const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero
|
|
40186
|
+
const maxNumber = 2 ** W; // W=8 256
|
|
40187
|
+
const mask = bitMask(W); // W=8 255 == mask 0b11111111
|
|
40188
|
+
const shiftBy = BigInt(W); // W=8 8
|
|
40189
|
+
return { windows, windowSize, mask, maxNumber, shiftBy };
|
|
40190
|
+
}
|
|
40191
|
+
function calcOffsets(n, window, wOpts) {
|
|
40192
|
+
const { windowSize, mask, maxNumber, shiftBy } = wOpts;
|
|
40193
|
+
let wbits = Number(n & mask); // extract W bits.
|
|
40194
|
+
let nextN = n >> shiftBy; // shift number by W bits.
|
|
40195
|
+
// What actually happens here:
|
|
40196
|
+
// const highestBit = Number(mask ^ (mask >> 1n));
|
|
40197
|
+
// let wbits2 = wbits - 1; // skip zero
|
|
40198
|
+
// if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);
|
|
40199
|
+
// split if bits > max: +224 => 256-32
|
|
40200
|
+
if (wbits > windowSize) {
|
|
40201
|
+
// we skip zero, which means instead of `>= size-1`, we do `> size`
|
|
40202
|
+
wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.
|
|
40203
|
+
nextN += _1n$2; // +256 (carry)
|
|
40204
|
+
}
|
|
40205
|
+
const offsetStart = window * windowSize;
|
|
40206
|
+
const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero
|
|
40207
|
+
const isZero = wbits === 0; // is current window slice a 0?
|
|
40208
|
+
const isNeg = wbits < 0; // is current window slice negative?
|
|
40209
|
+
const isNegF = window % 2 !== 0; // fake random statement for noise
|
|
40210
|
+
const offsetF = offsetStart; // fake offset for noise
|
|
40211
|
+
return { nextN, offset, isZero, isNeg, isNegF, offsetF };
|
|
40212
|
+
}
|
|
40213
|
+
function validateMSMPoints(points, c) {
|
|
40214
|
+
if (!Array.isArray(points))
|
|
40215
|
+
throw new Error('array expected');
|
|
40216
|
+
points.forEach((p, i) => {
|
|
40217
|
+
if (!(p instanceof c))
|
|
40218
|
+
throw new Error('invalid point at index ' + i);
|
|
40219
|
+
});
|
|
40220
|
+
}
|
|
40221
|
+
function validateMSMScalars(scalars, field) {
|
|
40222
|
+
if (!Array.isArray(scalars))
|
|
40223
|
+
throw new Error('array of scalars expected');
|
|
40224
|
+
scalars.forEach((s, i) => {
|
|
40225
|
+
if (!field.isValid(s))
|
|
40226
|
+
throw new Error('invalid scalar at index ' + i);
|
|
40227
|
+
});
|
|
40228
|
+
}
|
|
40229
|
+
// Since points in different groups cannot be equal (different object constructor),
|
|
40230
|
+
// we can have single place to store precomputes.
|
|
40231
|
+
// Allows to make points frozen / immutable.
|
|
40232
|
+
const pointPrecomputes = new WeakMap();
|
|
40233
|
+
const pointWindowSizes = new WeakMap();
|
|
40234
|
+
function getW(P) {
|
|
40235
|
+
// To disable precomputes:
|
|
40236
|
+
// return 1;
|
|
40237
|
+
return pointWindowSizes.get(P) || 1;
|
|
40238
|
+
}
|
|
40239
|
+
function assert0(n) {
|
|
40240
|
+
if (n !== _0n$2)
|
|
40241
|
+
throw new Error('invalid wNAF');
|
|
40242
|
+
}
|
|
40243
|
+
/**
|
|
40244
|
+
* Elliptic curve multiplication of Point by scalar. Fragile.
|
|
40245
|
+
* Table generation takes **30MB of ram and 10ms on high-end CPU**,
|
|
40246
|
+
* but may take much longer on slow devices. Actual generation will happen on
|
|
40247
|
+
* first call of `multiply()`. By default, `BASE` point is precomputed.
|
|
40248
|
+
*
|
|
40249
|
+
* Scalars should always be less than curve order: this should be checked inside of a curve itself.
|
|
40250
|
+
* Creates precomputation tables for fast multiplication:
|
|
40251
|
+
* - private scalar is split by fixed size windows of W bits
|
|
40252
|
+
* - every window point is collected from window's table & added to accumulator
|
|
40253
|
+
* - since windows are different, same point inside tables won't be accessed more than once per calc
|
|
40254
|
+
* - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)
|
|
40255
|
+
* - +1 window is neccessary for wNAF
|
|
40256
|
+
* - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
|
|
40257
|
+
*
|
|
40258
|
+
* @todo Research returning 2d JS array of windows, instead of a single window.
|
|
40259
|
+
* This would allow windows to be in different memory locations
|
|
40260
|
+
*/
|
|
40261
|
+
class wNAF {
|
|
40262
|
+
// Parametrized with a given Point class (not individual point)
|
|
40263
|
+
constructor(Point, bits) {
|
|
40264
|
+
this.BASE = Point.BASE;
|
|
40265
|
+
this.ZERO = Point.ZERO;
|
|
40266
|
+
this.Fn = Point.Fn;
|
|
40267
|
+
this.bits = bits;
|
|
40268
|
+
}
|
|
40269
|
+
// non-const time multiplication ladder
|
|
40270
|
+
_unsafeLadder(elm, n, p = this.ZERO) {
|
|
40271
|
+
let d = elm;
|
|
40272
|
+
while (n > _0n$2) {
|
|
40273
|
+
if (n & _1n$2)
|
|
40274
|
+
p = p.add(d);
|
|
40275
|
+
d = d.double();
|
|
40276
|
+
n >>= _1n$2;
|
|
40277
|
+
}
|
|
40278
|
+
return p;
|
|
40279
|
+
}
|
|
40280
|
+
/**
|
|
40281
|
+
* Creates a wNAF precomputation window. Used for caching.
|
|
40282
|
+
* Default window size is set by `utils.precompute()` and is equal to 8.
|
|
40283
|
+
* Number of precomputed points depends on the curve size:
|
|
40284
|
+
* 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
|
|
40285
|
+
* - 𝑊 is the window size
|
|
40286
|
+
* - 𝑛 is the bitlength of the curve order.
|
|
40287
|
+
* For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
|
|
40288
|
+
* @param point Point instance
|
|
40289
|
+
* @param W window size
|
|
40290
|
+
* @returns precomputed point tables flattened to a single array
|
|
40291
|
+
*/
|
|
40292
|
+
precomputeWindow(point, W) {
|
|
40293
|
+
const { windows, windowSize } = calcWOpts(W, this.bits);
|
|
40294
|
+
const points = [];
|
|
40295
|
+
let p = point;
|
|
40296
|
+
let base = p;
|
|
40297
|
+
for (let window = 0; window < windows; window++) {
|
|
40298
|
+
base = p;
|
|
40299
|
+
points.push(base);
|
|
40300
|
+
// i=1, bc we skip 0
|
|
40301
|
+
for (let i = 1; i < windowSize; i++) {
|
|
40302
|
+
base = base.add(p);
|
|
40303
|
+
points.push(base);
|
|
39191
40304
|
}
|
|
40305
|
+
p = base.double();
|
|
39192
40306
|
}
|
|
39193
|
-
|
|
39194
|
-
this.roundClean();
|
|
39195
|
-
return this;
|
|
40307
|
+
return points;
|
|
39196
40308
|
}
|
|
39197
|
-
|
|
39198
|
-
|
|
39199
|
-
|
|
39200
|
-
|
|
39201
|
-
|
|
39202
|
-
|
|
39203
|
-
|
|
39204
|
-
|
|
39205
|
-
|
|
39206
|
-
|
|
39207
|
-
|
|
39208
|
-
|
|
39209
|
-
|
|
39210
|
-
//
|
|
39211
|
-
|
|
39212
|
-
|
|
39213
|
-
|
|
40309
|
+
/**
|
|
40310
|
+
* Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
|
|
40311
|
+
* More compact implementation:
|
|
40312
|
+
* https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
|
|
40313
|
+
* @returns real and fake (for const-time) points
|
|
40314
|
+
*/
|
|
40315
|
+
wNAF(W, precomputes, n) {
|
|
40316
|
+
// Scalar should be smaller than field order
|
|
40317
|
+
if (!this.Fn.isValid(n))
|
|
40318
|
+
throw new Error('invalid scalar');
|
|
40319
|
+
// Accumulators
|
|
40320
|
+
let p = this.ZERO;
|
|
40321
|
+
let f = this.BASE;
|
|
40322
|
+
// This code was first written with assumption that 'f' and 'p' will never be infinity point:
|
|
40323
|
+
// since each addition is multiplied by 2 ** W, it cannot cancel each other. However,
|
|
40324
|
+
// there is negate now: it is possible that negated element from low value
|
|
40325
|
+
// would be the same as high element, which will create carry into next window.
|
|
40326
|
+
// It's not obvious how this can fail, but still worth investigating later.
|
|
40327
|
+
const wo = calcWOpts(W, this.bits);
|
|
40328
|
+
for (let window = 0; window < wo.windows; window++) {
|
|
40329
|
+
// (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise
|
|
40330
|
+
const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
|
|
40331
|
+
n = nextN;
|
|
40332
|
+
if (isZero) {
|
|
40333
|
+
// bits are 0: add garbage to fake point
|
|
40334
|
+
// Important part for const-time getPublicKey: add random "noise" point to f.
|
|
40335
|
+
f = f.add(negateCt(isNegF, precomputes[offsetF]));
|
|
40336
|
+
}
|
|
40337
|
+
else {
|
|
40338
|
+
// bits are 1: add to result point
|
|
40339
|
+
p = p.add(negateCt(isNeg, precomputes[offset]));
|
|
40340
|
+
}
|
|
39214
40341
|
}
|
|
39215
|
-
|
|
39216
|
-
|
|
39217
|
-
|
|
39218
|
-
//
|
|
39219
|
-
|
|
39220
|
-
// So we just write lowest 64 bits of that value.
|
|
39221
|
-
setBigUint64$1(view, blockLen - 8, BigInt(this.length * 8), isLE);
|
|
39222
|
-
this.process(view, 0);
|
|
39223
|
-
const oview = createView$1(out);
|
|
39224
|
-
const len = this.outputLen;
|
|
39225
|
-
// NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT
|
|
39226
|
-
if (len % 4)
|
|
39227
|
-
throw new Error('_sha2: outputLen should be aligned to 32bit');
|
|
39228
|
-
const outLen = len / 4;
|
|
39229
|
-
const state = this.get();
|
|
39230
|
-
if (outLen > state.length)
|
|
39231
|
-
throw new Error('_sha2: outputLen bigger than state');
|
|
39232
|
-
for (let i = 0; i < outLen; i++)
|
|
39233
|
-
oview.setUint32(4 * i, state[i], isLE);
|
|
40342
|
+
assert0(n);
|
|
40343
|
+
// Return both real and fake points: JIT won't eliminate f.
|
|
40344
|
+
// At this point there is a way to F be infinity-point even if p is not,
|
|
40345
|
+
// which makes it less const-time: around 1 bigint multiply.
|
|
40346
|
+
return { p, f };
|
|
39234
40347
|
}
|
|
39235
|
-
|
|
39236
|
-
|
|
39237
|
-
|
|
39238
|
-
|
|
39239
|
-
|
|
39240
|
-
|
|
40348
|
+
/**
|
|
40349
|
+
* Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
|
|
40350
|
+
* @param acc accumulator point to add result of multiplication
|
|
40351
|
+
* @returns point
|
|
40352
|
+
*/
|
|
40353
|
+
wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
|
|
40354
|
+
const wo = calcWOpts(W, this.bits);
|
|
40355
|
+
for (let window = 0; window < wo.windows; window++) {
|
|
40356
|
+
if (n === _0n$2)
|
|
40357
|
+
break; // Early-exit, skip 0 value
|
|
40358
|
+
const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
|
|
40359
|
+
n = nextN;
|
|
40360
|
+
if (isZero) {
|
|
40361
|
+
// Window bits are 0: skip processing.
|
|
40362
|
+
// Move to next window.
|
|
40363
|
+
continue;
|
|
40364
|
+
}
|
|
40365
|
+
else {
|
|
40366
|
+
const item = precomputes[offset];
|
|
40367
|
+
acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM
|
|
40368
|
+
}
|
|
40369
|
+
}
|
|
40370
|
+
assert0(n);
|
|
40371
|
+
return acc;
|
|
40372
|
+
}
|
|
40373
|
+
getPrecomputes(W, point, transform) {
|
|
40374
|
+
// Calculate precomputes on a first run, reuse them after
|
|
40375
|
+
let comp = pointPrecomputes.get(point);
|
|
40376
|
+
if (!comp) {
|
|
40377
|
+
comp = this.precomputeWindow(point, W);
|
|
40378
|
+
if (W !== 1) {
|
|
40379
|
+
// Doing transform outside of if brings 15% perf hit
|
|
40380
|
+
if (typeof transform === 'function')
|
|
40381
|
+
comp = transform(comp);
|
|
40382
|
+
pointPrecomputes.set(point, comp);
|
|
40383
|
+
}
|
|
40384
|
+
}
|
|
40385
|
+
return comp;
|
|
39241
40386
|
}
|
|
39242
|
-
|
|
39243
|
-
|
|
39244
|
-
|
|
39245
|
-
const { blockLen, buffer, length, finished, destroyed, pos } = this;
|
|
39246
|
-
to.destroyed = destroyed;
|
|
39247
|
-
to.finished = finished;
|
|
39248
|
-
to.length = length;
|
|
39249
|
-
to.pos = pos;
|
|
39250
|
-
if (length % blockLen)
|
|
39251
|
-
to.buffer.set(buffer);
|
|
39252
|
-
return to;
|
|
40387
|
+
cached(point, scalar, transform) {
|
|
40388
|
+
const W = getW(point);
|
|
40389
|
+
return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
|
|
39253
40390
|
}
|
|
39254
|
-
|
|
39255
|
-
|
|
40391
|
+
unsafe(point, scalar, transform, prev) {
|
|
40392
|
+
const W = getW(point);
|
|
40393
|
+
if (W === 1)
|
|
40394
|
+
return this._unsafeLadder(point, scalar, prev); // For W=1 ladder is ~x2 faster
|
|
40395
|
+
return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
|
|
40396
|
+
}
|
|
40397
|
+
// We calculate precomputes for elliptic curve point multiplication
|
|
40398
|
+
// using windowed method. This specifies window size and
|
|
40399
|
+
// stores precomputed values. Usually only base point would be precomputed.
|
|
40400
|
+
createCache(P, W) {
|
|
40401
|
+
validateW(W, this.bits);
|
|
40402
|
+
pointWindowSizes.set(P, W);
|
|
40403
|
+
pointPrecomputes.delete(P);
|
|
40404
|
+
}
|
|
40405
|
+
hasCache(elm) {
|
|
40406
|
+
return getW(elm) !== 1;
|
|
39256
40407
|
}
|
|
39257
40408
|
}
|
|
39258
40409
|
/**
|
|
39259
|
-
*
|
|
39260
|
-
*
|
|
40410
|
+
* Endomorphism-specific multiplication for Koblitz curves.
|
|
40411
|
+
* Cost: 128 dbl, 0-256 adds.
|
|
39261
40412
|
*/
|
|
39262
|
-
|
|
39263
|
-
|
|
39264
|
-
|
|
39265
|
-
|
|
40413
|
+
function mulEndoUnsafe(Point, point, k1, k2) {
|
|
40414
|
+
let acc = point;
|
|
40415
|
+
let p1 = Point.ZERO;
|
|
40416
|
+
let p2 = Point.ZERO;
|
|
40417
|
+
while (k1 > _0n$2 || k2 > _0n$2) {
|
|
40418
|
+
if (k1 & _1n$2)
|
|
40419
|
+
p1 = p1.add(acc);
|
|
40420
|
+
if (k2 & _1n$2)
|
|
40421
|
+
p2 = p2.add(acc);
|
|
40422
|
+
acc = acc.double();
|
|
40423
|
+
k1 >>= _1n$2;
|
|
40424
|
+
k2 >>= _1n$2;
|
|
40425
|
+
}
|
|
40426
|
+
return { p1, p2 };
|
|
40427
|
+
}
|
|
40428
|
+
/**
|
|
40429
|
+
* Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
|
|
40430
|
+
* 30x faster vs naive addition on L=4096, 10x faster than precomputes.
|
|
40431
|
+
* For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.
|
|
40432
|
+
* Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.
|
|
40433
|
+
* @param c Curve Point constructor
|
|
40434
|
+
* @param fieldN field over CURVE.N - important that it's not over CURVE.P
|
|
40435
|
+
* @param points array of L curve points
|
|
40436
|
+
* @param scalars array of L scalars (aka secret keys / bigints)
|
|
40437
|
+
*/
|
|
40438
|
+
function pippenger(c, fieldN, points, scalars) {
|
|
40439
|
+
// If we split scalars by some window (let's say 8 bits), every chunk will only
|
|
40440
|
+
// take 256 buckets even if there are 4096 scalars, also re-uses double.
|
|
40441
|
+
// TODO:
|
|
40442
|
+
// - https://eprint.iacr.org/2024/750.pdf
|
|
40443
|
+
// - https://tches.iacr.org/index.php/TCHES/article/view/10287
|
|
40444
|
+
// 0 is accepted in scalars
|
|
40445
|
+
validateMSMPoints(points, c);
|
|
40446
|
+
validateMSMScalars(scalars, fieldN);
|
|
40447
|
+
const plength = points.length;
|
|
40448
|
+
const slength = scalars.length;
|
|
40449
|
+
if (plength !== slength)
|
|
40450
|
+
throw new Error('arrays of points and scalars must have equal length');
|
|
40451
|
+
// if (plength === 0) throw new Error('array must be of length >= 2');
|
|
40452
|
+
const zero = c.ZERO;
|
|
40453
|
+
const wbits = bitLen(BigInt(plength));
|
|
40454
|
+
let windowSize = 1; // bits
|
|
40455
|
+
if (wbits > 12)
|
|
40456
|
+
windowSize = wbits - 3;
|
|
40457
|
+
else if (wbits > 4)
|
|
40458
|
+
windowSize = wbits - 2;
|
|
40459
|
+
else if (wbits > 0)
|
|
40460
|
+
windowSize = 2;
|
|
40461
|
+
const MASK = bitMask(windowSize);
|
|
40462
|
+
const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array
|
|
40463
|
+
const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
|
|
40464
|
+
let sum = zero;
|
|
40465
|
+
for (let i = lastBits; i >= 0; i -= windowSize) {
|
|
40466
|
+
buckets.fill(zero);
|
|
40467
|
+
for (let j = 0; j < slength; j++) {
|
|
40468
|
+
const scalar = scalars[j];
|
|
40469
|
+
const wbits = Number((scalar >> BigInt(i)) & MASK);
|
|
40470
|
+
buckets[wbits] = buckets[wbits].add(points[j]);
|
|
40471
|
+
}
|
|
40472
|
+
let resI = zero; // not using this will do small speed-up, but will lose ct
|
|
40473
|
+
// Skip first bucket, because it is zero
|
|
40474
|
+
for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {
|
|
40475
|
+
sumI = sumI.add(buckets[j]);
|
|
40476
|
+
resI = resI.add(sumI);
|
|
40477
|
+
}
|
|
40478
|
+
sum = sum.add(resI);
|
|
40479
|
+
if (i !== 0)
|
|
40480
|
+
for (let j = 0; j < windowSize; j++)
|
|
40481
|
+
sum = sum.double();
|
|
40482
|
+
}
|
|
40483
|
+
return sum;
|
|
40484
|
+
}
|
|
40485
|
+
function createField(order, field, isLE) {
|
|
40486
|
+
if (field) {
|
|
40487
|
+
if (field.ORDER !== order)
|
|
40488
|
+
throw new Error('Field.ORDER must match order: Fp == p, Fn == n');
|
|
40489
|
+
validateField(field);
|
|
40490
|
+
return field;
|
|
40491
|
+
}
|
|
40492
|
+
else {
|
|
40493
|
+
return Field(order, { isLE });
|
|
40494
|
+
}
|
|
40495
|
+
}
|
|
40496
|
+
/** Validates CURVE opts and creates fields */
|
|
40497
|
+
function _createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
|
|
40498
|
+
if (FpFnLE === undefined)
|
|
40499
|
+
FpFnLE = type === 'edwards';
|
|
40500
|
+
if (!CURVE || typeof CURVE !== 'object')
|
|
40501
|
+
throw new Error(`expected valid ${type} CURVE object`);
|
|
40502
|
+
for (const p of ['p', 'n', 'h']) {
|
|
40503
|
+
const val = CURVE[p];
|
|
40504
|
+
if (!(typeof val === 'bigint' && val > _0n$2))
|
|
40505
|
+
throw new Error(`CURVE.${p} must be positive bigint`);
|
|
40506
|
+
}
|
|
40507
|
+
const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
|
|
40508
|
+
const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
|
|
40509
|
+
const _b = 'b' ;
|
|
40510
|
+
const params = ['Gx', 'Gy', 'a', _b];
|
|
40511
|
+
for (const p of params) {
|
|
40512
|
+
// @ts-ignore
|
|
40513
|
+
if (!Fp.isValid(CURVE[p]))
|
|
40514
|
+
throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
|
|
40515
|
+
}
|
|
40516
|
+
CURVE = Object.freeze(Object.assign({}, CURVE));
|
|
40517
|
+
return { CURVE, Fp, Fn };
|
|
40518
|
+
}
|
|
39266
40519
|
|
|
39267
40520
|
/**
|
|
39268
|
-
*
|
|
39269
|
-
*
|
|
39270
|
-
*
|
|
39271
|
-
*
|
|
40521
|
+
* Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.
|
|
40522
|
+
*
|
|
40523
|
+
* ### Design rationale for types
|
|
40524
|
+
*
|
|
40525
|
+
* * Interaction between classes from different curves should fail:
|
|
40526
|
+
* `k256.Point.BASE.add(p256.Point.BASE)`
|
|
40527
|
+
* * For this purpose we want to use `instanceof` operator, which is fast and works during runtime
|
|
40528
|
+
* * Different calls of `curve()` would return different classes -
|
|
40529
|
+
* `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,
|
|
40530
|
+
* it won't affect others
|
|
40531
|
+
*
|
|
40532
|
+
* TypeScript can't infer types for classes created inside a function. Classes is one instance
|
|
40533
|
+
* of nominative types in TypeScript and interfaces only check for shape, so it's hard to create
|
|
40534
|
+
* unique type for every function call.
|
|
40535
|
+
*
|
|
40536
|
+
* We can use generic types via some param, like curve opts, but that would:
|
|
40537
|
+
* 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)
|
|
40538
|
+
* which is hard to debug.
|
|
40539
|
+
* 2. Params can be generic and we can't enforce them to be constant value:
|
|
40540
|
+
* if somebody creates curve from non-constant params,
|
|
40541
|
+
* it would be allowed to interact with other curves with non-constant params
|
|
40542
|
+
*
|
|
40543
|
+
* @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol
|
|
39272
40544
|
* @module
|
|
39273
40545
|
*/
|
|
40546
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
40547
|
+
// We construct basis in such way that den is always positive and equals n, but num sign depends on basis (not on secret value)
|
|
40548
|
+
const divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n$1) / den;
|
|
39274
40549
|
/**
|
|
39275
|
-
*
|
|
39276
|
-
|
|
40550
|
+
* Splits scalar for GLV endomorphism.
|
|
40551
|
+
*/
|
|
40552
|
+
function _splitEndoScalar(k, basis, n) {
|
|
40553
|
+
// Split scalar into two such that part is ~half bits: `abs(part) < sqrt(N)`
|
|
40554
|
+
// Since part can be negative, we need to do this on point.
|
|
40555
|
+
// TODO: verifyScalar function which consumes lambda
|
|
40556
|
+
const [[a1, b1], [a2, b2]] = basis;
|
|
40557
|
+
const c1 = divNearest(b2 * k, n);
|
|
40558
|
+
const c2 = divNearest(-b1 * k, n);
|
|
40559
|
+
// |k1|/|k2| is < sqrt(N), but can be negative.
|
|
40560
|
+
// If we do `k1 mod N`, we'll get big scalar (`> sqrt(N)`): so, we do cheaper negation instead.
|
|
40561
|
+
let k1 = k - c1 * a1 - c2 * a2;
|
|
40562
|
+
let k2 = -c1 * b1 - c2 * b2;
|
|
40563
|
+
const k1neg = k1 < _0n$1;
|
|
40564
|
+
const k2neg = k2 < _0n$1;
|
|
40565
|
+
if (k1neg)
|
|
40566
|
+
k1 = -k1;
|
|
40567
|
+
if (k2neg)
|
|
40568
|
+
k2 = -k2;
|
|
40569
|
+
// Double check that resulting scalar less than half bits of N: otherwise wNAF will fail.
|
|
40570
|
+
// This should only happen on wrong basises. Also, math inside is too complex and I don't trust it.
|
|
40571
|
+
const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n$1; // Half bits of N
|
|
40572
|
+
if (k1 < _0n$1 || k1 >= MAX_NUM || k2 < _0n$1 || k2 >= MAX_NUM) {
|
|
40573
|
+
throw new Error('splitScalar (endomorphism): failed, k=' + k);
|
|
40574
|
+
}
|
|
40575
|
+
return { k1neg, k1, k2neg, k2 };
|
|
40576
|
+
}
|
|
40577
|
+
function validateSigFormat(format) {
|
|
40578
|
+
if (!['compact', 'recovered', 'der'].includes(format))
|
|
40579
|
+
throw new Error('Signature format must be "compact", "recovered", or "der"');
|
|
40580
|
+
return format;
|
|
40581
|
+
}
|
|
40582
|
+
function validateSigOpts(opts, def) {
|
|
40583
|
+
const optsn = {};
|
|
40584
|
+
for (let optName of Object.keys(def)) {
|
|
40585
|
+
// @ts-ignore
|
|
40586
|
+
optsn[optName] = opts[optName] === undefined ? def[optName] : opts[optName];
|
|
40587
|
+
}
|
|
40588
|
+
_abool2(optsn.lowS, 'lowS');
|
|
40589
|
+
_abool2(optsn.prehash, 'prehash');
|
|
40590
|
+
if (optsn.format !== undefined)
|
|
40591
|
+
validateSigFormat(optsn.format);
|
|
40592
|
+
return optsn;
|
|
40593
|
+
}
|
|
40594
|
+
class DERErr extends Error {
|
|
40595
|
+
constructor(m = '') {
|
|
40596
|
+
super(m);
|
|
40597
|
+
}
|
|
40598
|
+
}
|
|
40599
|
+
/**
|
|
40600
|
+
* ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:
|
|
40601
|
+
*
|
|
40602
|
+
* [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]
|
|
40603
|
+
*
|
|
40604
|
+
* Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html
|
|
39277
40605
|
*/
|
|
40606
|
+
const DER = {
|
|
40607
|
+
// asn.1 DER encoding utils
|
|
40608
|
+
Err: DERErr,
|
|
40609
|
+
// Basic building block is TLV (Tag-Length-Value)
|
|
40610
|
+
_tlv: {
|
|
40611
|
+
encode: (tag, data) => {
|
|
40612
|
+
const { Err: E } = DER;
|
|
40613
|
+
if (tag < 0 || tag > 256)
|
|
40614
|
+
throw new E('tlv.encode: wrong tag');
|
|
40615
|
+
if (data.length & 1)
|
|
40616
|
+
throw new E('tlv.encode: unpadded data');
|
|
40617
|
+
const dataLen = data.length / 2;
|
|
40618
|
+
const len = numberToHexUnpadded(dataLen);
|
|
40619
|
+
if ((len.length / 2) & 128)
|
|
40620
|
+
throw new E('tlv.encode: long form length too big');
|
|
40621
|
+
// length of length with long form flag
|
|
40622
|
+
const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 128) : '';
|
|
40623
|
+
const t = numberToHexUnpadded(tag);
|
|
40624
|
+
return t + lenLen + len + data;
|
|
40625
|
+
},
|
|
40626
|
+
// v - value, l - left bytes (unparsed)
|
|
40627
|
+
decode(tag, data) {
|
|
40628
|
+
const { Err: E } = DER;
|
|
40629
|
+
let pos = 0;
|
|
40630
|
+
if (tag < 0 || tag > 256)
|
|
40631
|
+
throw new E('tlv.encode: wrong tag');
|
|
40632
|
+
if (data.length < 2 || data[pos++] !== tag)
|
|
40633
|
+
throw new E('tlv.decode: wrong tlv');
|
|
40634
|
+
const first = data[pos++];
|
|
40635
|
+
const isLong = !!(first & 128); // First bit of first length byte is flag for short/long form
|
|
40636
|
+
let length = 0;
|
|
40637
|
+
if (!isLong)
|
|
40638
|
+
length = first;
|
|
40639
|
+
else {
|
|
40640
|
+
// Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]
|
|
40641
|
+
const lenLen = first & 127;
|
|
40642
|
+
if (!lenLen)
|
|
40643
|
+
throw new E('tlv.decode(long): indefinite length not supported');
|
|
40644
|
+
if (lenLen > 4)
|
|
40645
|
+
throw new E('tlv.decode(long): byte length is too big'); // this will overflow u32 in js
|
|
40646
|
+
const lengthBytes = data.subarray(pos, pos + lenLen);
|
|
40647
|
+
if (lengthBytes.length !== lenLen)
|
|
40648
|
+
throw new E('tlv.decode: length bytes not complete');
|
|
40649
|
+
if (lengthBytes[0] === 0)
|
|
40650
|
+
throw new E('tlv.decode(long): zero leftmost byte');
|
|
40651
|
+
for (const b of lengthBytes)
|
|
40652
|
+
length = (length << 8) | b;
|
|
40653
|
+
pos += lenLen;
|
|
40654
|
+
if (length < 128)
|
|
40655
|
+
throw new E('tlv.decode(long): not minimal encoding');
|
|
40656
|
+
}
|
|
40657
|
+
const v = data.subarray(pos, pos + length);
|
|
40658
|
+
if (v.length !== length)
|
|
40659
|
+
throw new E('tlv.decode: wrong value length');
|
|
40660
|
+
return { v, l: data.subarray(pos + length) };
|
|
40661
|
+
},
|
|
40662
|
+
},
|
|
40663
|
+
// https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
|
|
40664
|
+
// since we always use positive integers here. It must always be empty:
|
|
40665
|
+
// - add zero byte if exists
|
|
40666
|
+
// - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
|
|
40667
|
+
_int: {
|
|
40668
|
+
encode(num) {
|
|
40669
|
+
const { Err: E } = DER;
|
|
40670
|
+
if (num < _0n$1)
|
|
40671
|
+
throw new E('integer: negative integers are not allowed');
|
|
40672
|
+
let hex = numberToHexUnpadded(num);
|
|
40673
|
+
// Pad with zero byte if negative flag is present
|
|
40674
|
+
if (Number.parseInt(hex[0], 16) & 0b1000)
|
|
40675
|
+
hex = '00' + hex;
|
|
40676
|
+
if (hex.length & 1)
|
|
40677
|
+
throw new E('unexpected DER parsing assertion: unpadded hex');
|
|
40678
|
+
return hex;
|
|
40679
|
+
},
|
|
40680
|
+
decode(data) {
|
|
40681
|
+
const { Err: E } = DER;
|
|
40682
|
+
if (data[0] & 128)
|
|
40683
|
+
throw new E('invalid signature integer: negative');
|
|
40684
|
+
if (data[0] === 0x00 && !(data[1] & 128))
|
|
40685
|
+
throw new E('invalid signature integer: unnecessary leading zero');
|
|
40686
|
+
return bytesToNumberBE(data);
|
|
40687
|
+
},
|
|
40688
|
+
},
|
|
40689
|
+
toSig(hex) {
|
|
40690
|
+
// parse DER signature
|
|
40691
|
+
const { Err: E, _int: int, _tlv: tlv } = DER;
|
|
40692
|
+
const data = ensureBytes$1('signature', hex);
|
|
40693
|
+
const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);
|
|
40694
|
+
if (seqLeftBytes.length)
|
|
40695
|
+
throw new E('invalid signature: left bytes after parsing');
|
|
40696
|
+
const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);
|
|
40697
|
+
const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);
|
|
40698
|
+
if (sLeftBytes.length)
|
|
40699
|
+
throw new E('invalid signature: left bytes after parsing');
|
|
40700
|
+
return { r: int.decode(rBytes), s: int.decode(sBytes) };
|
|
40701
|
+
},
|
|
40702
|
+
hexFromSig(sig) {
|
|
40703
|
+
const { _tlv: tlv, _int: int } = DER;
|
|
40704
|
+
const rs = tlv.encode(0x02, int.encode(sig.r));
|
|
40705
|
+
const ss = tlv.encode(0x02, int.encode(sig.s));
|
|
40706
|
+
const seq = rs + ss;
|
|
40707
|
+
return tlv.encode(0x30, seq);
|
|
40708
|
+
},
|
|
40709
|
+
};
|
|
40710
|
+
// Be friendly to bad ECMAScript parsers by not using bigint literals
|
|
39278
40711
|
// prettier-ignore
|
|
39279
|
-
const
|
|
39280
|
-
|
|
39281
|
-
|
|
39282
|
-
|
|
39283
|
-
|
|
39284
|
-
|
|
39285
|
-
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
|
|
39286
|
-
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
|
|
39287
|
-
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
|
|
39288
|
-
]);
|
|
39289
|
-
/** Reusable temporary buffer. "W" comes straight from spec. */
|
|
39290
|
-
const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
|
|
39291
|
-
class SHA256 extends HashMD {
|
|
39292
|
-
constructor(outputLen = 32) {
|
|
39293
|
-
super(64, outputLen, 8, false);
|
|
39294
|
-
// We cannot use array here since array allows indexing by variable
|
|
39295
|
-
// which means optimizer/compiler cannot use registers.
|
|
39296
|
-
this.A = SHA256_IV[0] | 0;
|
|
39297
|
-
this.B = SHA256_IV[1] | 0;
|
|
39298
|
-
this.C = SHA256_IV[2] | 0;
|
|
39299
|
-
this.D = SHA256_IV[3] | 0;
|
|
39300
|
-
this.E = SHA256_IV[4] | 0;
|
|
39301
|
-
this.F = SHA256_IV[5] | 0;
|
|
39302
|
-
this.G = SHA256_IV[6] | 0;
|
|
39303
|
-
this.H = SHA256_IV[7] | 0;
|
|
40712
|
+
const _0n$1 = BigInt(0), _1n$1 = BigInt(1), _2n$1 = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);
|
|
40713
|
+
function _normFnElement(Fn, key) {
|
|
40714
|
+
const { BYTES: expected } = Fn;
|
|
40715
|
+
let num;
|
|
40716
|
+
if (typeof key === 'bigint') {
|
|
40717
|
+
num = key;
|
|
39304
40718
|
}
|
|
39305
|
-
|
|
39306
|
-
|
|
39307
|
-
|
|
40719
|
+
else {
|
|
40720
|
+
let bytes = ensureBytes$1('private key', key);
|
|
40721
|
+
try {
|
|
40722
|
+
num = Fn.fromBytes(bytes);
|
|
40723
|
+
}
|
|
40724
|
+
catch (error) {
|
|
40725
|
+
throw new Error(`invalid private key: expected ui8a of size ${expected}, got ${typeof key}`);
|
|
40726
|
+
}
|
|
39308
40727
|
}
|
|
39309
|
-
|
|
39310
|
-
|
|
39311
|
-
|
|
39312
|
-
|
|
39313
|
-
|
|
39314
|
-
|
|
39315
|
-
|
|
39316
|
-
|
|
39317
|
-
|
|
39318
|
-
|
|
40728
|
+
if (!Fn.isValidNot0(num))
|
|
40729
|
+
throw new Error('invalid private key: out of range [1..N-1]');
|
|
40730
|
+
return num;
|
|
40731
|
+
}
|
|
40732
|
+
/**
|
|
40733
|
+
* Creates weierstrass Point constructor, based on specified curve options.
|
|
40734
|
+
*
|
|
40735
|
+
* @example
|
|
40736
|
+
```js
|
|
40737
|
+
const opts = {
|
|
40738
|
+
p: BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff'),
|
|
40739
|
+
n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'),
|
|
40740
|
+
h: BigInt(1),
|
|
40741
|
+
a: BigInt('0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc'),
|
|
40742
|
+
b: BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'),
|
|
40743
|
+
Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'),
|
|
40744
|
+
Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'),
|
|
40745
|
+
};
|
|
40746
|
+
const p256_Point = weierstrass(opts);
|
|
40747
|
+
```
|
|
40748
|
+
*/
|
|
40749
|
+
function weierstrassN(params, extraOpts = {}) {
|
|
40750
|
+
const validated = _createCurveFields('weierstrass', params, extraOpts);
|
|
40751
|
+
const { Fp, Fn } = validated;
|
|
40752
|
+
let CURVE = validated.CURVE;
|
|
40753
|
+
const { h: cofactor, n: CURVE_ORDER } = CURVE;
|
|
40754
|
+
_validateObject(extraOpts, {}, {
|
|
40755
|
+
allowInfinityPoint: 'boolean',
|
|
40756
|
+
clearCofactor: 'function',
|
|
40757
|
+
isTorsionFree: 'function',
|
|
40758
|
+
fromBytes: 'function',
|
|
40759
|
+
toBytes: 'function',
|
|
40760
|
+
endo: 'object',
|
|
40761
|
+
wrapPrivateKey: 'boolean',
|
|
40762
|
+
});
|
|
40763
|
+
const { endo } = extraOpts;
|
|
40764
|
+
if (endo) {
|
|
40765
|
+
// validateObject(endo, { beta: 'bigint', splitScalar: 'function' });
|
|
40766
|
+
if (!Fp.is0(CURVE.a) || typeof endo.beta !== 'bigint' || !Array.isArray(endo.basises)) {
|
|
40767
|
+
throw new Error('invalid endo: expected "beta": bigint and "basises": array');
|
|
40768
|
+
}
|
|
39319
40769
|
}
|
|
39320
|
-
|
|
39321
|
-
|
|
39322
|
-
|
|
39323
|
-
|
|
39324
|
-
|
|
39325
|
-
|
|
39326
|
-
|
|
39327
|
-
|
|
39328
|
-
|
|
39329
|
-
|
|
40770
|
+
const lengths = getWLengths(Fp, Fn);
|
|
40771
|
+
function assertCompressionIsSupported() {
|
|
40772
|
+
if (!Fp.isOdd)
|
|
40773
|
+
throw new Error('compression is not supported: Field does not have .isOdd()');
|
|
40774
|
+
}
|
|
40775
|
+
// Implements IEEE P1363 point encoding
|
|
40776
|
+
function pointToBytes(_c, point, isCompressed) {
|
|
40777
|
+
const { x, y } = point.toAffine();
|
|
40778
|
+
const bx = Fp.toBytes(x);
|
|
40779
|
+
_abool2(isCompressed, 'isCompressed');
|
|
40780
|
+
if (isCompressed) {
|
|
40781
|
+
assertCompressionIsSupported();
|
|
40782
|
+
const hasEvenY = !Fp.isOdd(y);
|
|
40783
|
+
return concatBytes$2(pprefix(hasEvenY), bx);
|
|
39330
40784
|
}
|
|
39331
|
-
|
|
39332
|
-
|
|
39333
|
-
for (let i = 0; i < 64; i++) {
|
|
39334
|
-
const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
|
|
39335
|
-
const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
|
|
39336
|
-
const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
|
|
39337
|
-
const T2 = (sigma0 + Maj(A, B, C)) | 0;
|
|
39338
|
-
H = G;
|
|
39339
|
-
G = F;
|
|
39340
|
-
F = E;
|
|
39341
|
-
E = (D + T1) | 0;
|
|
39342
|
-
D = C;
|
|
39343
|
-
C = B;
|
|
39344
|
-
B = A;
|
|
39345
|
-
A = (T1 + T2) | 0;
|
|
40785
|
+
else {
|
|
40786
|
+
return concatBytes$2(Uint8Array.of(0x04), bx, Fp.toBytes(y));
|
|
39346
40787
|
}
|
|
39347
|
-
// Add the compressed chunk to the current hash value
|
|
39348
|
-
A = (A + this.A) | 0;
|
|
39349
|
-
B = (B + this.B) | 0;
|
|
39350
|
-
C = (C + this.C) | 0;
|
|
39351
|
-
D = (D + this.D) | 0;
|
|
39352
|
-
E = (E + this.E) | 0;
|
|
39353
|
-
F = (F + this.F) | 0;
|
|
39354
|
-
G = (G + this.G) | 0;
|
|
39355
|
-
H = (H + this.H) | 0;
|
|
39356
|
-
this.set(A, B, C, D, E, F, G, H);
|
|
39357
40788
|
}
|
|
39358
|
-
|
|
39359
|
-
|
|
40789
|
+
function pointFromBytes(bytes) {
|
|
40790
|
+
_abytes2(bytes, undefined, 'Point');
|
|
40791
|
+
const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths; // e.g. for 32-byte: 33, 65
|
|
40792
|
+
const length = bytes.length;
|
|
40793
|
+
const head = bytes[0];
|
|
40794
|
+
const tail = bytes.subarray(1);
|
|
40795
|
+
// No actual validation is done here: use .assertValidity()
|
|
40796
|
+
if (length === comp && (head === 0x02 || head === 0x03)) {
|
|
40797
|
+
const x = Fp.fromBytes(tail);
|
|
40798
|
+
if (!Fp.isValid(x))
|
|
40799
|
+
throw new Error('bad point: is not on curve, wrong x');
|
|
40800
|
+
const y2 = weierstrassEquation(x); // y² = x³ + ax + b
|
|
40801
|
+
let y;
|
|
40802
|
+
try {
|
|
40803
|
+
y = Fp.sqrt(y2); // y = y² ^ (p+1)/4
|
|
40804
|
+
}
|
|
40805
|
+
catch (sqrtError) {
|
|
40806
|
+
const err = sqrtError instanceof Error ? ': ' + sqrtError.message : '';
|
|
40807
|
+
throw new Error('bad point: is not on curve, sqrt error' + err);
|
|
40808
|
+
}
|
|
40809
|
+
assertCompressionIsSupported();
|
|
40810
|
+
const isYOdd = Fp.isOdd(y); // (y & _1n) === _1n;
|
|
40811
|
+
const isHeadOdd = (head & 1) === 1; // ECDSA-specific
|
|
40812
|
+
if (isHeadOdd !== isYOdd)
|
|
40813
|
+
y = Fp.neg(y);
|
|
40814
|
+
return { x, y };
|
|
40815
|
+
}
|
|
40816
|
+
else if (length === uncomp && head === 0x04) {
|
|
40817
|
+
// TODO: more checks
|
|
40818
|
+
const L = Fp.BYTES;
|
|
40819
|
+
const x = Fp.fromBytes(tail.subarray(0, L));
|
|
40820
|
+
const y = Fp.fromBytes(tail.subarray(L, L * 2));
|
|
40821
|
+
if (!isValidXY(x, y))
|
|
40822
|
+
throw new Error('bad point: is not on curve');
|
|
40823
|
+
return { x, y };
|
|
40824
|
+
}
|
|
40825
|
+
else {
|
|
40826
|
+
throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
|
|
40827
|
+
}
|
|
39360
40828
|
}
|
|
39361
|
-
|
|
39362
|
-
|
|
39363
|
-
|
|
40829
|
+
const encodePoint = extraOpts.toBytes || pointToBytes;
|
|
40830
|
+
const decodePoint = extraOpts.fromBytes || pointFromBytes;
|
|
40831
|
+
function weierstrassEquation(x) {
|
|
40832
|
+
const x2 = Fp.sqr(x); // x * x
|
|
40833
|
+
const x3 = Fp.mul(x2, x); // x² * x
|
|
40834
|
+
return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b); // x³ + a * x + b
|
|
40835
|
+
}
|
|
40836
|
+
// TODO: move top-level
|
|
40837
|
+
/** Checks whether equation holds for given x, y: y² == x³ + ax + b */
|
|
40838
|
+
function isValidXY(x, y) {
|
|
40839
|
+
const left = Fp.sqr(y); // y²
|
|
40840
|
+
const right = weierstrassEquation(x); // x³ + ax + b
|
|
40841
|
+
return Fp.eql(left, right);
|
|
40842
|
+
}
|
|
40843
|
+
// Validate whether the passed curve params are valid.
|
|
40844
|
+
// Test 1: equation y² = x³ + ax + b should work for generator point.
|
|
40845
|
+
if (!isValidXY(CURVE.Gx, CURVE.Gy))
|
|
40846
|
+
throw new Error('bad curve params: generator point');
|
|
40847
|
+
// Test 2: discriminant Δ part should be non-zero: 4a³ + 27b² != 0.
|
|
40848
|
+
// Guarantees curve is genus-1, smooth (non-singular).
|
|
40849
|
+
const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);
|
|
40850
|
+
const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
|
|
40851
|
+
if (Fp.is0(Fp.add(_4a3, _27b2)))
|
|
40852
|
+
throw new Error('bad curve params: a or b');
|
|
40853
|
+
/** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */
|
|
40854
|
+
function acoord(title, n, banZero = false) {
|
|
40855
|
+
if (!Fp.isValid(n) || (banZero && Fp.is0(n)))
|
|
40856
|
+
throw new Error(`bad point coordinate ${title}`);
|
|
40857
|
+
return n;
|
|
40858
|
+
}
|
|
40859
|
+
function aprjpoint(other) {
|
|
40860
|
+
if (!(other instanceof Point))
|
|
40861
|
+
throw new Error('ProjectivePoint expected');
|
|
40862
|
+
}
|
|
40863
|
+
function splitEndoScalarN(k) {
|
|
40864
|
+
if (!endo || !endo.basises)
|
|
40865
|
+
throw new Error('no endo');
|
|
40866
|
+
return _splitEndoScalar(k, endo.basises, Fn.ORDER);
|
|
40867
|
+
}
|
|
40868
|
+
// Memoized toAffine / validity check. They are heavy. Points are immutable.
|
|
40869
|
+
// Converts Projective point to affine (x, y) coordinates.
|
|
40870
|
+
// Can accept precomputed Z^-1 - for example, from invertBatch.
|
|
40871
|
+
// (X, Y, Z) ∋ (x=X/Z, y=Y/Z)
|
|
40872
|
+
const toAffineMemo = memoized((p, iz) => {
|
|
40873
|
+
const { X, Y, Z } = p;
|
|
40874
|
+
// Fast-path for normalized points
|
|
40875
|
+
if (Fp.eql(Z, Fp.ONE))
|
|
40876
|
+
return { x: X, y: Y };
|
|
40877
|
+
const is0 = p.is0();
|
|
40878
|
+
// If invZ was 0, we return zero point. However we still want to execute
|
|
40879
|
+
// all operations, so we replace invZ with a random number, 1.
|
|
40880
|
+
if (iz == null)
|
|
40881
|
+
iz = is0 ? Fp.ONE : Fp.inv(Z);
|
|
40882
|
+
const x = Fp.mul(X, iz);
|
|
40883
|
+
const y = Fp.mul(Y, iz);
|
|
40884
|
+
const zz = Fp.mul(Z, iz);
|
|
40885
|
+
if (is0)
|
|
40886
|
+
return { x: Fp.ZERO, y: Fp.ZERO };
|
|
40887
|
+
if (!Fp.eql(zz, Fp.ONE))
|
|
40888
|
+
throw new Error('invZ was invalid');
|
|
40889
|
+
return { x, y };
|
|
40890
|
+
});
|
|
40891
|
+
// NOTE: on exception this will crash 'cached' and no value will be set.
|
|
40892
|
+
// Otherwise true will be return
|
|
40893
|
+
const assertValidMemo = memoized((p) => {
|
|
40894
|
+
if (p.is0()) {
|
|
40895
|
+
// (0, 1, 0) aka ZERO is invalid in most contexts.
|
|
40896
|
+
// In BLS, ZERO can be serialized, so we allow it.
|
|
40897
|
+
// (0, 0, 0) is invalid representation of ZERO.
|
|
40898
|
+
if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y))
|
|
40899
|
+
return;
|
|
40900
|
+
throw new Error('bad point: ZERO');
|
|
40901
|
+
}
|
|
40902
|
+
// Some 3rd-party test vectors require different wording between here & `fromCompressedHex`
|
|
40903
|
+
const { x, y } = p.toAffine();
|
|
40904
|
+
if (!Fp.isValid(x) || !Fp.isValid(y))
|
|
40905
|
+
throw new Error('bad point: x or y not field elements');
|
|
40906
|
+
if (!isValidXY(x, y))
|
|
40907
|
+
throw new Error('bad point: equation left != right');
|
|
40908
|
+
if (!p.isTorsionFree())
|
|
40909
|
+
throw new Error('bad point: not in prime-order subgroup');
|
|
40910
|
+
return true;
|
|
40911
|
+
});
|
|
40912
|
+
function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
|
|
40913
|
+
k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
|
|
40914
|
+
k1p = negateCt(k1neg, k1p);
|
|
40915
|
+
k2p = negateCt(k2neg, k2p);
|
|
40916
|
+
return k1p.add(k2p);
|
|
40917
|
+
}
|
|
40918
|
+
/**
|
|
40919
|
+
* Projective Point works in 3d / projective (homogeneous) coordinates:(X, Y, Z) ∋ (x=X/Z, y=Y/Z).
|
|
40920
|
+
* Default Point works in 2d / affine coordinates: (x, y).
|
|
40921
|
+
* We're doing calculations in projective, because its operations don't require costly inversion.
|
|
40922
|
+
*/
|
|
40923
|
+
class Point {
|
|
40924
|
+
/** Does NOT validate if the point is valid. Use `.assertValidity()`. */
|
|
40925
|
+
constructor(X, Y, Z) {
|
|
40926
|
+
this.X = acoord('x', X);
|
|
40927
|
+
this.Y = acoord('y', Y, true);
|
|
40928
|
+
this.Z = acoord('z', Z);
|
|
40929
|
+
Object.freeze(this);
|
|
40930
|
+
}
|
|
40931
|
+
static CURVE() {
|
|
40932
|
+
return CURVE;
|
|
40933
|
+
}
|
|
40934
|
+
/** Does NOT validate if the point is valid. Use `.assertValidity()`. */
|
|
40935
|
+
static fromAffine(p) {
|
|
40936
|
+
const { x, y } = p || {};
|
|
40937
|
+
if (!p || !Fp.isValid(x) || !Fp.isValid(y))
|
|
40938
|
+
throw new Error('invalid affine point');
|
|
40939
|
+
if (p instanceof Point)
|
|
40940
|
+
throw new Error('projective point not allowed');
|
|
40941
|
+
// (0, 0) would've produced (0, 0, 1) - instead, we need (0, 1, 0)
|
|
40942
|
+
if (Fp.is0(x) && Fp.is0(y))
|
|
40943
|
+
return Point.ZERO;
|
|
40944
|
+
return new Point(x, y, Fp.ONE);
|
|
40945
|
+
}
|
|
40946
|
+
static fromBytes(bytes) {
|
|
40947
|
+
const P = Point.fromAffine(decodePoint(_abytes2(bytes, undefined, 'point')));
|
|
40948
|
+
P.assertValidity();
|
|
40949
|
+
return P;
|
|
40950
|
+
}
|
|
40951
|
+
static fromHex(hex) {
|
|
40952
|
+
return Point.fromBytes(ensureBytes$1('pointHex', hex));
|
|
40953
|
+
}
|
|
40954
|
+
get x() {
|
|
40955
|
+
return this.toAffine().x;
|
|
40956
|
+
}
|
|
40957
|
+
get y() {
|
|
40958
|
+
return this.toAffine().y;
|
|
40959
|
+
}
|
|
40960
|
+
/**
|
|
40961
|
+
*
|
|
40962
|
+
* @param windowSize
|
|
40963
|
+
* @param isLazy true will defer table computation until the first multiplication
|
|
40964
|
+
* @returns
|
|
40965
|
+
*/
|
|
40966
|
+
precompute(windowSize = 8, isLazy = true) {
|
|
40967
|
+
wnaf.createCache(this, windowSize);
|
|
40968
|
+
if (!isLazy)
|
|
40969
|
+
this.multiply(_3n); // random number
|
|
40970
|
+
return this;
|
|
40971
|
+
}
|
|
40972
|
+
// TODO: return `this`
|
|
40973
|
+
/** A point on curve is valid if it conforms to equation. */
|
|
40974
|
+
assertValidity() {
|
|
40975
|
+
assertValidMemo(this);
|
|
40976
|
+
}
|
|
40977
|
+
hasEvenY() {
|
|
40978
|
+
const { y } = this.toAffine();
|
|
40979
|
+
if (!Fp.isOdd)
|
|
40980
|
+
throw new Error("Field doesn't support isOdd");
|
|
40981
|
+
return !Fp.isOdd(y);
|
|
40982
|
+
}
|
|
40983
|
+
/** Compare one point to another. */
|
|
40984
|
+
equals(other) {
|
|
40985
|
+
aprjpoint(other);
|
|
40986
|
+
const { X: X1, Y: Y1, Z: Z1 } = this;
|
|
40987
|
+
const { X: X2, Y: Y2, Z: Z2 } = other;
|
|
40988
|
+
const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
|
|
40989
|
+
const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
|
|
40990
|
+
return U1 && U2;
|
|
40991
|
+
}
|
|
40992
|
+
/** Flips point to one corresponding to (x, -y) in Affine coordinates. */
|
|
40993
|
+
negate() {
|
|
40994
|
+
return new Point(this.X, Fp.neg(this.Y), this.Z);
|
|
40995
|
+
}
|
|
40996
|
+
// Renes-Costello-Batina exception-free doubling formula.
|
|
40997
|
+
// There is 30% faster Jacobian formula, but it is not complete.
|
|
40998
|
+
// https://eprint.iacr.org/2015/1060, algorithm 3
|
|
40999
|
+
// Cost: 8M + 3S + 3*a + 2*b3 + 15add.
|
|
41000
|
+
double() {
|
|
41001
|
+
const { a, b } = CURVE;
|
|
41002
|
+
const b3 = Fp.mul(b, _3n);
|
|
41003
|
+
const { X: X1, Y: Y1, Z: Z1 } = this;
|
|
41004
|
+
let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
|
|
41005
|
+
let t0 = Fp.mul(X1, X1); // step 1
|
|
41006
|
+
let t1 = Fp.mul(Y1, Y1);
|
|
41007
|
+
let t2 = Fp.mul(Z1, Z1);
|
|
41008
|
+
let t3 = Fp.mul(X1, Y1);
|
|
41009
|
+
t3 = Fp.add(t3, t3); // step 5
|
|
41010
|
+
Z3 = Fp.mul(X1, Z1);
|
|
41011
|
+
Z3 = Fp.add(Z3, Z3);
|
|
41012
|
+
X3 = Fp.mul(a, Z3);
|
|
41013
|
+
Y3 = Fp.mul(b3, t2);
|
|
41014
|
+
Y3 = Fp.add(X3, Y3); // step 10
|
|
41015
|
+
X3 = Fp.sub(t1, Y3);
|
|
41016
|
+
Y3 = Fp.add(t1, Y3);
|
|
41017
|
+
Y3 = Fp.mul(X3, Y3);
|
|
41018
|
+
X3 = Fp.mul(t3, X3);
|
|
41019
|
+
Z3 = Fp.mul(b3, Z3); // step 15
|
|
41020
|
+
t2 = Fp.mul(a, t2);
|
|
41021
|
+
t3 = Fp.sub(t0, t2);
|
|
41022
|
+
t3 = Fp.mul(a, t3);
|
|
41023
|
+
t3 = Fp.add(t3, Z3);
|
|
41024
|
+
Z3 = Fp.add(t0, t0); // step 20
|
|
41025
|
+
t0 = Fp.add(Z3, t0);
|
|
41026
|
+
t0 = Fp.add(t0, t2);
|
|
41027
|
+
t0 = Fp.mul(t0, t3);
|
|
41028
|
+
Y3 = Fp.add(Y3, t0);
|
|
41029
|
+
t2 = Fp.mul(Y1, Z1); // step 25
|
|
41030
|
+
t2 = Fp.add(t2, t2);
|
|
41031
|
+
t0 = Fp.mul(t2, t3);
|
|
41032
|
+
X3 = Fp.sub(X3, t0);
|
|
41033
|
+
Z3 = Fp.mul(t2, t1);
|
|
41034
|
+
Z3 = Fp.add(Z3, Z3); // step 30
|
|
41035
|
+
Z3 = Fp.add(Z3, Z3);
|
|
41036
|
+
return new Point(X3, Y3, Z3);
|
|
41037
|
+
}
|
|
41038
|
+
// Renes-Costello-Batina exception-free addition formula.
|
|
41039
|
+
// There is 30% faster Jacobian formula, but it is not complete.
|
|
41040
|
+
// https://eprint.iacr.org/2015/1060, algorithm 1
|
|
41041
|
+
// Cost: 12M + 0S + 3*a + 3*b3 + 23add.
|
|
41042
|
+
add(other) {
|
|
41043
|
+
aprjpoint(other);
|
|
41044
|
+
const { X: X1, Y: Y1, Z: Z1 } = this;
|
|
41045
|
+
const { X: X2, Y: Y2, Z: Z2 } = other;
|
|
41046
|
+
let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
|
|
41047
|
+
const a = CURVE.a;
|
|
41048
|
+
const b3 = Fp.mul(CURVE.b, _3n);
|
|
41049
|
+
let t0 = Fp.mul(X1, X2); // step 1
|
|
41050
|
+
let t1 = Fp.mul(Y1, Y2);
|
|
41051
|
+
let t2 = Fp.mul(Z1, Z2);
|
|
41052
|
+
let t3 = Fp.add(X1, Y1);
|
|
41053
|
+
let t4 = Fp.add(X2, Y2); // step 5
|
|
41054
|
+
t3 = Fp.mul(t3, t4);
|
|
41055
|
+
t4 = Fp.add(t0, t1);
|
|
41056
|
+
t3 = Fp.sub(t3, t4);
|
|
41057
|
+
t4 = Fp.add(X1, Z1);
|
|
41058
|
+
let t5 = Fp.add(X2, Z2); // step 10
|
|
41059
|
+
t4 = Fp.mul(t4, t5);
|
|
41060
|
+
t5 = Fp.add(t0, t2);
|
|
41061
|
+
t4 = Fp.sub(t4, t5);
|
|
41062
|
+
t5 = Fp.add(Y1, Z1);
|
|
41063
|
+
X3 = Fp.add(Y2, Z2); // step 15
|
|
41064
|
+
t5 = Fp.mul(t5, X3);
|
|
41065
|
+
X3 = Fp.add(t1, t2);
|
|
41066
|
+
t5 = Fp.sub(t5, X3);
|
|
41067
|
+
Z3 = Fp.mul(a, t4);
|
|
41068
|
+
X3 = Fp.mul(b3, t2); // step 20
|
|
41069
|
+
Z3 = Fp.add(X3, Z3);
|
|
41070
|
+
X3 = Fp.sub(t1, Z3);
|
|
41071
|
+
Z3 = Fp.add(t1, Z3);
|
|
41072
|
+
Y3 = Fp.mul(X3, Z3);
|
|
41073
|
+
t1 = Fp.add(t0, t0); // step 25
|
|
41074
|
+
t1 = Fp.add(t1, t0);
|
|
41075
|
+
t2 = Fp.mul(a, t2);
|
|
41076
|
+
t4 = Fp.mul(b3, t4);
|
|
41077
|
+
t1 = Fp.add(t1, t2);
|
|
41078
|
+
t2 = Fp.sub(t0, t2); // step 30
|
|
41079
|
+
t2 = Fp.mul(a, t2);
|
|
41080
|
+
t4 = Fp.add(t4, t2);
|
|
41081
|
+
t0 = Fp.mul(t1, t4);
|
|
41082
|
+
Y3 = Fp.add(Y3, t0);
|
|
41083
|
+
t0 = Fp.mul(t5, t4); // step 35
|
|
41084
|
+
X3 = Fp.mul(t3, X3);
|
|
41085
|
+
X3 = Fp.sub(X3, t0);
|
|
41086
|
+
t0 = Fp.mul(t3, t1);
|
|
41087
|
+
Z3 = Fp.mul(t5, Z3);
|
|
41088
|
+
Z3 = Fp.add(Z3, t0); // step 40
|
|
41089
|
+
return new Point(X3, Y3, Z3);
|
|
41090
|
+
}
|
|
41091
|
+
subtract(other) {
|
|
41092
|
+
return this.add(other.negate());
|
|
41093
|
+
}
|
|
41094
|
+
is0() {
|
|
41095
|
+
return this.equals(Point.ZERO);
|
|
41096
|
+
}
|
|
41097
|
+
/**
|
|
41098
|
+
* Constant time multiplication.
|
|
41099
|
+
* Uses wNAF method. Windowed method may be 10% faster,
|
|
41100
|
+
* but takes 2x longer to generate and consumes 2x memory.
|
|
41101
|
+
* Uses precomputes when available.
|
|
41102
|
+
* Uses endomorphism for Koblitz curves.
|
|
41103
|
+
* @param scalar by which the point would be multiplied
|
|
41104
|
+
* @returns New point
|
|
41105
|
+
*/
|
|
41106
|
+
multiply(scalar) {
|
|
41107
|
+
const { endo } = extraOpts;
|
|
41108
|
+
if (!Fn.isValidNot0(scalar))
|
|
41109
|
+
throw new Error('invalid scalar: out of range'); // 0 is invalid
|
|
41110
|
+
let point, fake; // Fake point is used to const-time mult
|
|
41111
|
+
const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));
|
|
41112
|
+
/** See docs for {@link EndomorphismOpts} */
|
|
41113
|
+
if (endo) {
|
|
41114
|
+
const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
|
|
41115
|
+
const { p: k1p, f: k1f } = mul(k1);
|
|
41116
|
+
const { p: k2p, f: k2f } = mul(k2);
|
|
41117
|
+
fake = k1f.add(k2f);
|
|
41118
|
+
point = finishEndo(endo.beta, k1p, k2p, k1neg, k2neg);
|
|
41119
|
+
}
|
|
41120
|
+
else {
|
|
41121
|
+
const { p, f } = mul(scalar);
|
|
41122
|
+
point = p;
|
|
41123
|
+
fake = f;
|
|
41124
|
+
}
|
|
41125
|
+
// Normalize `z` for both points, but return only real one
|
|
41126
|
+
return normalizeZ(Point, [point, fake])[0];
|
|
41127
|
+
}
|
|
41128
|
+
/**
|
|
41129
|
+
* Non-constant-time multiplication. Uses double-and-add algorithm.
|
|
41130
|
+
* It's faster, but should only be used when you don't care about
|
|
41131
|
+
* an exposed secret key e.g. sig verification, which works over *public* keys.
|
|
41132
|
+
*/
|
|
41133
|
+
multiplyUnsafe(sc) {
|
|
41134
|
+
const { endo } = extraOpts;
|
|
41135
|
+
const p = this;
|
|
41136
|
+
if (!Fn.isValid(sc))
|
|
41137
|
+
throw new Error('invalid scalar: out of range'); // 0 is valid
|
|
41138
|
+
if (sc === _0n$1 || p.is0())
|
|
41139
|
+
return Point.ZERO;
|
|
41140
|
+
if (sc === _1n$1)
|
|
41141
|
+
return p; // fast-path
|
|
41142
|
+
if (wnaf.hasCache(this))
|
|
41143
|
+
return this.multiply(sc);
|
|
41144
|
+
if (endo) {
|
|
41145
|
+
const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
|
|
41146
|
+
const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2); // 30% faster vs wnaf.unsafe
|
|
41147
|
+
return finishEndo(endo.beta, p1, p2, k1neg, k2neg);
|
|
41148
|
+
}
|
|
41149
|
+
else {
|
|
41150
|
+
return wnaf.unsafe(p, sc);
|
|
41151
|
+
}
|
|
41152
|
+
}
|
|
41153
|
+
multiplyAndAddUnsafe(Q, a, b) {
|
|
41154
|
+
const sum = this.multiplyUnsafe(a).add(Q.multiplyUnsafe(b));
|
|
41155
|
+
return sum.is0() ? undefined : sum;
|
|
41156
|
+
}
|
|
41157
|
+
/**
|
|
41158
|
+
* Converts Projective point to affine (x, y) coordinates.
|
|
41159
|
+
* @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
|
|
41160
|
+
*/
|
|
41161
|
+
toAffine(invertedZ) {
|
|
41162
|
+
return toAffineMemo(this, invertedZ);
|
|
41163
|
+
}
|
|
41164
|
+
/**
|
|
41165
|
+
* Checks whether Point is free of torsion elements (is in prime subgroup).
|
|
41166
|
+
* Always torsion-free for cofactor=1 curves.
|
|
41167
|
+
*/
|
|
41168
|
+
isTorsionFree() {
|
|
41169
|
+
const { isTorsionFree } = extraOpts;
|
|
41170
|
+
if (cofactor === _1n$1)
|
|
41171
|
+
return true;
|
|
41172
|
+
if (isTorsionFree)
|
|
41173
|
+
return isTorsionFree(Point, this);
|
|
41174
|
+
return wnaf.unsafe(this, CURVE_ORDER).is0();
|
|
41175
|
+
}
|
|
41176
|
+
clearCofactor() {
|
|
41177
|
+
const { clearCofactor } = extraOpts;
|
|
41178
|
+
if (cofactor === _1n$1)
|
|
41179
|
+
return this; // Fast-path
|
|
41180
|
+
if (clearCofactor)
|
|
41181
|
+
return clearCofactor(Point, this);
|
|
41182
|
+
return this.multiplyUnsafe(cofactor);
|
|
41183
|
+
}
|
|
41184
|
+
isSmallOrder() {
|
|
41185
|
+
// can we use this.clearCofactor()?
|
|
41186
|
+
return this.multiplyUnsafe(cofactor).is0();
|
|
41187
|
+
}
|
|
41188
|
+
toBytes(isCompressed = true) {
|
|
41189
|
+
_abool2(isCompressed, 'isCompressed');
|
|
41190
|
+
this.assertValidity();
|
|
41191
|
+
return encodePoint(Point, this, isCompressed);
|
|
41192
|
+
}
|
|
41193
|
+
toHex(isCompressed = true) {
|
|
41194
|
+
return bytesToHex(this.toBytes(isCompressed));
|
|
41195
|
+
}
|
|
41196
|
+
toString() {
|
|
41197
|
+
return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;
|
|
41198
|
+
}
|
|
41199
|
+
// TODO: remove
|
|
41200
|
+
get px() {
|
|
41201
|
+
return this.X;
|
|
41202
|
+
}
|
|
41203
|
+
get py() {
|
|
41204
|
+
return this.X;
|
|
41205
|
+
}
|
|
41206
|
+
get pz() {
|
|
41207
|
+
return this.Z;
|
|
41208
|
+
}
|
|
41209
|
+
toRawBytes(isCompressed = true) {
|
|
41210
|
+
return this.toBytes(isCompressed);
|
|
41211
|
+
}
|
|
41212
|
+
_setWindowSize(windowSize) {
|
|
41213
|
+
this.precompute(windowSize);
|
|
41214
|
+
}
|
|
41215
|
+
static normalizeZ(points) {
|
|
41216
|
+
return normalizeZ(Point, points);
|
|
41217
|
+
}
|
|
41218
|
+
static msm(points, scalars) {
|
|
41219
|
+
return pippenger(Point, Fn, points, scalars);
|
|
41220
|
+
}
|
|
41221
|
+
static fromPrivateKey(privateKey) {
|
|
41222
|
+
return Point.BASE.multiply(_normFnElement(Fn, privateKey));
|
|
41223
|
+
}
|
|
39364
41224
|
}
|
|
41225
|
+
// base / generator point
|
|
41226
|
+
Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
|
|
41227
|
+
// zero / infinity / identity point
|
|
41228
|
+
Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0
|
|
41229
|
+
// math field
|
|
41230
|
+
Point.Fp = Fp;
|
|
41231
|
+
// scalar field
|
|
41232
|
+
Point.Fn = Fn;
|
|
41233
|
+
const bits = Fn.BITS;
|
|
41234
|
+
const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
|
|
41235
|
+
Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.
|
|
41236
|
+
return Point;
|
|
41237
|
+
}
|
|
41238
|
+
// Points start with byte 0x02 when y is even; otherwise 0x03
|
|
41239
|
+
function pprefix(hasEvenY) {
|
|
41240
|
+
return Uint8Array.of(hasEvenY ? 0x02 : 0x03);
|
|
41241
|
+
}
|
|
41242
|
+
function getWLengths(Fp, Fn) {
|
|
41243
|
+
return {
|
|
41244
|
+
secretKey: Fn.BYTES,
|
|
41245
|
+
publicKey: 1 + Fp.BYTES,
|
|
41246
|
+
publicKeyUncompressed: 1 + 2 * Fp.BYTES,
|
|
41247
|
+
publicKeyHasPrefix: true,
|
|
41248
|
+
signature: 2 * Fn.BYTES,
|
|
41249
|
+
};
|
|
39365
41250
|
}
|
|
39366
41251
|
/**
|
|
39367
|
-
*
|
|
41252
|
+
* Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.
|
|
41253
|
+
* This helper ensures no signature functionality is present. Less code, smaller bundle size.
|
|
41254
|
+
*/
|
|
41255
|
+
function ecdh(Point, ecdhOpts = {}) {
|
|
41256
|
+
const { Fn } = Point;
|
|
41257
|
+
const randomBytes_ = ecdhOpts.randomBytes || randomBytes$1;
|
|
41258
|
+
const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });
|
|
41259
|
+
function isValidSecretKey(secretKey) {
|
|
41260
|
+
try {
|
|
41261
|
+
return !!_normFnElement(Fn, secretKey);
|
|
41262
|
+
}
|
|
41263
|
+
catch (error) {
|
|
41264
|
+
return false;
|
|
41265
|
+
}
|
|
41266
|
+
}
|
|
41267
|
+
function isValidPublicKey(publicKey, isCompressed) {
|
|
41268
|
+
const { publicKey: comp, publicKeyUncompressed } = lengths;
|
|
41269
|
+
try {
|
|
41270
|
+
const l = publicKey.length;
|
|
41271
|
+
if (isCompressed === true && l !== comp)
|
|
41272
|
+
return false;
|
|
41273
|
+
if (isCompressed === false && l !== publicKeyUncompressed)
|
|
41274
|
+
return false;
|
|
41275
|
+
return !!Point.fromBytes(publicKey);
|
|
41276
|
+
}
|
|
41277
|
+
catch (error) {
|
|
41278
|
+
return false;
|
|
41279
|
+
}
|
|
41280
|
+
}
|
|
41281
|
+
/**
|
|
41282
|
+
* Produces cryptographically secure secret key from random of size
|
|
41283
|
+
* (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.
|
|
41284
|
+
*/
|
|
41285
|
+
function randomSecretKey(seed = randomBytes_(lengths.seed)) {
|
|
41286
|
+
return mapHashToField(_abytes2(seed, lengths.seed, 'seed'), Fn.ORDER);
|
|
41287
|
+
}
|
|
41288
|
+
/**
|
|
41289
|
+
* Computes public key for a secret key. Checks for validity of the secret key.
|
|
41290
|
+
* @param isCompressed whether to return compact (default), or full key
|
|
41291
|
+
* @returns Public key, full when isCompressed=false; short when isCompressed=true
|
|
41292
|
+
*/
|
|
41293
|
+
function getPublicKey(secretKey, isCompressed = true) {
|
|
41294
|
+
return Point.BASE.multiply(_normFnElement(Fn, secretKey)).toBytes(isCompressed);
|
|
41295
|
+
}
|
|
41296
|
+
function keygen(seed) {
|
|
41297
|
+
const secretKey = randomSecretKey(seed);
|
|
41298
|
+
return { secretKey, publicKey: getPublicKey(secretKey) };
|
|
41299
|
+
}
|
|
41300
|
+
/**
|
|
41301
|
+
* Quick and dirty check for item being public key. Does not validate hex, or being on-curve.
|
|
41302
|
+
*/
|
|
41303
|
+
function isProbPub(item) {
|
|
41304
|
+
if (typeof item === 'bigint')
|
|
41305
|
+
return false;
|
|
41306
|
+
if (item instanceof Point)
|
|
41307
|
+
return true;
|
|
41308
|
+
const { secretKey, publicKey, publicKeyUncompressed } = lengths;
|
|
41309
|
+
if (Fn.allowedLengths || secretKey === publicKey)
|
|
41310
|
+
return undefined;
|
|
41311
|
+
const l = ensureBytes$1('key', item).length;
|
|
41312
|
+
return l === publicKey || l === publicKeyUncompressed;
|
|
41313
|
+
}
|
|
41314
|
+
/**
|
|
41315
|
+
* ECDH (Elliptic Curve Diffie Hellman).
|
|
41316
|
+
* Computes shared public key from secret key A and public key B.
|
|
41317
|
+
* Checks: 1) secret key validity 2) shared key is on-curve.
|
|
41318
|
+
* Does NOT hash the result.
|
|
41319
|
+
* @param isCompressed whether to return compact (default), or full key
|
|
41320
|
+
* @returns shared public key
|
|
41321
|
+
*/
|
|
41322
|
+
function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
|
|
41323
|
+
if (isProbPub(secretKeyA) === true)
|
|
41324
|
+
throw new Error('first arg must be private key');
|
|
41325
|
+
if (isProbPub(publicKeyB) === false)
|
|
41326
|
+
throw new Error('second arg must be public key');
|
|
41327
|
+
const s = _normFnElement(Fn, secretKeyA);
|
|
41328
|
+
const b = Point.fromHex(publicKeyB); // checks for being on-curve
|
|
41329
|
+
return b.multiply(s).toBytes(isCompressed);
|
|
41330
|
+
}
|
|
41331
|
+
const utils = {
|
|
41332
|
+
isValidSecretKey,
|
|
41333
|
+
isValidPublicKey,
|
|
41334
|
+
randomSecretKey,
|
|
41335
|
+
// TODO: remove
|
|
41336
|
+
isValidPrivateKey: isValidSecretKey,
|
|
41337
|
+
randomPrivateKey: randomSecretKey,
|
|
41338
|
+
normPrivateKeyToScalar: (key) => _normFnElement(Fn, key),
|
|
41339
|
+
precompute(windowSize = 8, point = Point.BASE) {
|
|
41340
|
+
return point.precompute(windowSize, false);
|
|
41341
|
+
},
|
|
41342
|
+
};
|
|
41343
|
+
return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });
|
|
41344
|
+
}
|
|
41345
|
+
/**
|
|
41346
|
+
* Creates ECDSA signing interface for given elliptic curve `Point` and `hash` function.
|
|
41347
|
+
* We need `hash` for 2 features:
|
|
41348
|
+
* 1. Message prehash-ing. NOT used if `sign` / `verify` are called with `prehash: false`
|
|
41349
|
+
* 2. k generation in `sign`, using HMAC-drbg(hash)
|
|
39368
41350
|
*
|
|
39369
|
-
*
|
|
39370
|
-
*
|
|
39371
|
-
*
|
|
41351
|
+
* ECDSAOpts are only rarely needed.
|
|
41352
|
+
*
|
|
41353
|
+
* @example
|
|
41354
|
+
* ```js
|
|
41355
|
+
* const p256_Point = weierstrass(...);
|
|
41356
|
+
* const p256_sha256 = ecdsa(p256_Point, sha256);
|
|
41357
|
+
* const p256_sha224 = ecdsa(p256_Point, sha224);
|
|
41358
|
+
* const p256_sha224_r = ecdsa(p256_Point, sha224, { randomBytes: (length) => { ... } });
|
|
41359
|
+
* ```
|
|
39372
41360
|
*/
|
|
39373
|
-
|
|
41361
|
+
function ecdsa(Point, hash, ecdsaOpts = {}) {
|
|
41362
|
+
ahash(hash);
|
|
41363
|
+
_validateObject(ecdsaOpts, {}, {
|
|
41364
|
+
hmac: 'function',
|
|
41365
|
+
lowS: 'boolean',
|
|
41366
|
+
randomBytes: 'function',
|
|
41367
|
+
bits2int: 'function',
|
|
41368
|
+
bits2int_modN: 'function',
|
|
41369
|
+
});
|
|
41370
|
+
const randomBytes = ecdsaOpts.randomBytes || randomBytes$1;
|
|
41371
|
+
const hmac$1 = ecdsaOpts.hmac ||
|
|
41372
|
+
((key, ...msgs) => hmac(hash, key, concatBytes$2(...msgs)));
|
|
41373
|
+
const { Fp, Fn } = Point;
|
|
41374
|
+
const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;
|
|
41375
|
+
const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);
|
|
41376
|
+
const defaultSigOpts = {
|
|
41377
|
+
prehash: false,
|
|
41378
|
+
lowS: typeof ecdsaOpts.lowS === 'boolean' ? ecdsaOpts.lowS : false,
|
|
41379
|
+
format: undefined, //'compact' as ECDSASigFormat,
|
|
41380
|
+
extraEntropy: false,
|
|
41381
|
+
};
|
|
41382
|
+
const defaultSigOpts_format = 'compact';
|
|
41383
|
+
function isBiggerThanHalfOrder(number) {
|
|
41384
|
+
const HALF = CURVE_ORDER >> _1n$1;
|
|
41385
|
+
return number > HALF;
|
|
41386
|
+
}
|
|
41387
|
+
function validateRS(title, num) {
|
|
41388
|
+
if (!Fn.isValidNot0(num))
|
|
41389
|
+
throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
|
|
41390
|
+
return num;
|
|
41391
|
+
}
|
|
41392
|
+
function validateSigLength(bytes, format) {
|
|
41393
|
+
validateSigFormat(format);
|
|
41394
|
+
const size = lengths.signature;
|
|
41395
|
+
const sizer = format === 'compact' ? size : format === 'recovered' ? size + 1 : undefined;
|
|
41396
|
+
return _abytes2(bytes, sizer, `${format} signature`);
|
|
41397
|
+
}
|
|
41398
|
+
/**
|
|
41399
|
+
* ECDSA signature with its (r, s) properties. Supports compact, recovered & DER representations.
|
|
41400
|
+
*/
|
|
41401
|
+
class Signature {
|
|
41402
|
+
constructor(r, s, recovery) {
|
|
41403
|
+
this.r = validateRS('r', r); // r in [1..N-1];
|
|
41404
|
+
this.s = validateRS('s', s); // s in [1..N-1];
|
|
41405
|
+
if (recovery != null)
|
|
41406
|
+
this.recovery = recovery;
|
|
41407
|
+
Object.freeze(this);
|
|
41408
|
+
}
|
|
41409
|
+
static fromBytes(bytes, format = defaultSigOpts_format) {
|
|
41410
|
+
validateSigLength(bytes, format);
|
|
41411
|
+
let recid;
|
|
41412
|
+
if (format === 'der') {
|
|
41413
|
+
const { r, s } = DER.toSig(_abytes2(bytes));
|
|
41414
|
+
return new Signature(r, s);
|
|
41415
|
+
}
|
|
41416
|
+
if (format === 'recovered') {
|
|
41417
|
+
recid = bytes[0];
|
|
41418
|
+
format = 'compact';
|
|
41419
|
+
bytes = bytes.subarray(1);
|
|
41420
|
+
}
|
|
41421
|
+
const L = Fn.BYTES;
|
|
41422
|
+
const r = bytes.subarray(0, L);
|
|
41423
|
+
const s = bytes.subarray(L, L * 2);
|
|
41424
|
+
return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
|
|
41425
|
+
}
|
|
41426
|
+
static fromHex(hex, format) {
|
|
41427
|
+
return this.fromBytes(hexToBytes(hex), format);
|
|
41428
|
+
}
|
|
41429
|
+
addRecoveryBit(recovery) {
|
|
41430
|
+
return new Signature(this.r, this.s, recovery);
|
|
41431
|
+
}
|
|
41432
|
+
recoverPublicKey(messageHash) {
|
|
41433
|
+
const FIELD_ORDER = Fp.ORDER;
|
|
41434
|
+
const { r, s, recovery: rec } = this;
|
|
41435
|
+
if (rec == null || ![0, 1, 2, 3].includes(rec))
|
|
41436
|
+
throw new Error('recovery id invalid');
|
|
41437
|
+
// ECDSA recovery is hard for cofactor > 1 curves.
|
|
41438
|
+
// In sign, `r = q.x mod n`, and here we recover q.x from r.
|
|
41439
|
+
// While recovering q.x >= n, we need to add r+n for cofactor=1 curves.
|
|
41440
|
+
// However, for cofactor>1, r+n may not get q.x:
|
|
41441
|
+
// r+n*i would need to be done instead where i is unknown.
|
|
41442
|
+
// To easily get i, we either need to:
|
|
41443
|
+
// a. increase amount of valid recid values (4, 5...); OR
|
|
41444
|
+
// b. prohibit non-prime-order signatures (recid > 1).
|
|
41445
|
+
const hasCofactor = CURVE_ORDER * _2n$1 < FIELD_ORDER;
|
|
41446
|
+
if (hasCofactor && rec > 1)
|
|
41447
|
+
throw new Error('recovery id is ambiguous for h>1 curve');
|
|
41448
|
+
const radj = rec === 2 || rec === 3 ? r + CURVE_ORDER : r;
|
|
41449
|
+
if (!Fp.isValid(radj))
|
|
41450
|
+
throw new Error('recovery id 2 or 3 invalid');
|
|
41451
|
+
const x = Fp.toBytes(radj);
|
|
41452
|
+
const R = Point.fromBytes(concatBytes$2(pprefix((rec & 1) === 0), x));
|
|
41453
|
+
const ir = Fn.inv(radj); // r^-1
|
|
41454
|
+
const h = bits2int_modN(ensureBytes$1('msgHash', messageHash)); // Truncate hash
|
|
41455
|
+
const u1 = Fn.create(-h * ir); // -hr^-1
|
|
41456
|
+
const u2 = Fn.create(s * ir); // sr^-1
|
|
41457
|
+
// (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1). unsafe is fine: there is no private data.
|
|
41458
|
+
const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
|
|
41459
|
+
if (Q.is0())
|
|
41460
|
+
throw new Error('point at infinify');
|
|
41461
|
+
Q.assertValidity();
|
|
41462
|
+
return Q;
|
|
41463
|
+
}
|
|
41464
|
+
// Signatures should be low-s, to prevent malleability.
|
|
41465
|
+
hasHighS() {
|
|
41466
|
+
return isBiggerThanHalfOrder(this.s);
|
|
41467
|
+
}
|
|
41468
|
+
toBytes(format = defaultSigOpts_format) {
|
|
41469
|
+
validateSigFormat(format);
|
|
41470
|
+
if (format === 'der')
|
|
41471
|
+
return hexToBytes(DER.hexFromSig(this));
|
|
41472
|
+
const r = Fn.toBytes(this.r);
|
|
41473
|
+
const s = Fn.toBytes(this.s);
|
|
41474
|
+
if (format === 'recovered') {
|
|
41475
|
+
if (this.recovery == null)
|
|
41476
|
+
throw new Error('recovery bit must be present');
|
|
41477
|
+
return concatBytes$2(Uint8Array.of(this.recovery), r, s);
|
|
41478
|
+
}
|
|
41479
|
+
return concatBytes$2(r, s);
|
|
41480
|
+
}
|
|
41481
|
+
toHex(format) {
|
|
41482
|
+
return bytesToHex(this.toBytes(format));
|
|
41483
|
+
}
|
|
41484
|
+
// TODO: remove
|
|
41485
|
+
assertValidity() { }
|
|
41486
|
+
static fromCompact(hex) {
|
|
41487
|
+
return Signature.fromBytes(ensureBytes$1('sig', hex), 'compact');
|
|
41488
|
+
}
|
|
41489
|
+
static fromDER(hex) {
|
|
41490
|
+
return Signature.fromBytes(ensureBytes$1('sig', hex), 'der');
|
|
41491
|
+
}
|
|
41492
|
+
normalizeS() {
|
|
41493
|
+
return this.hasHighS() ? new Signature(this.r, Fn.neg(this.s), this.recovery) : this;
|
|
41494
|
+
}
|
|
41495
|
+
toDERRawBytes() {
|
|
41496
|
+
return this.toBytes('der');
|
|
41497
|
+
}
|
|
41498
|
+
toDERHex() {
|
|
41499
|
+
return bytesToHex(this.toBytes('der'));
|
|
41500
|
+
}
|
|
41501
|
+
toCompactRawBytes() {
|
|
41502
|
+
return this.toBytes('compact');
|
|
41503
|
+
}
|
|
41504
|
+
toCompactHex() {
|
|
41505
|
+
return bytesToHex(this.toBytes('compact'));
|
|
41506
|
+
}
|
|
41507
|
+
}
|
|
41508
|
+
// RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.
|
|
41509
|
+
// FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.
|
|
41510
|
+
// bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.
|
|
41511
|
+
// int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors
|
|
41512
|
+
const bits2int = ecdsaOpts.bits2int ||
|
|
41513
|
+
function bits2int_def(bytes) {
|
|
41514
|
+
// Our custom check "just in case", for protection against DoS
|
|
41515
|
+
if (bytes.length > 8192)
|
|
41516
|
+
throw new Error('input is too large');
|
|
41517
|
+
// For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)
|
|
41518
|
+
// for some cases, since bytes.length * 8 is not actual bitLength.
|
|
41519
|
+
const num = bytesToNumberBE(bytes); // check for == u8 done here
|
|
41520
|
+
const delta = bytes.length * 8 - fnBits; // truncate to nBitLength leftmost bits
|
|
41521
|
+
return delta > 0 ? num >> BigInt(delta) : num;
|
|
41522
|
+
};
|
|
41523
|
+
const bits2int_modN = ecdsaOpts.bits2int_modN ||
|
|
41524
|
+
function bits2int_modN_def(bytes) {
|
|
41525
|
+
return Fn.create(bits2int(bytes)); // can't use bytesToNumberBE here
|
|
41526
|
+
};
|
|
41527
|
+
// Pads output with zero as per spec
|
|
41528
|
+
const ORDER_MASK = bitMask(fnBits);
|
|
41529
|
+
/** Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. */
|
|
41530
|
+
function int2octets(num) {
|
|
41531
|
+
// IMPORTANT: the check ensures working for case `Fn.BYTES != Fn.BITS * 8`
|
|
41532
|
+
aInRange('num < 2^' + fnBits, num, _0n$1, ORDER_MASK);
|
|
41533
|
+
return Fn.toBytes(num);
|
|
41534
|
+
}
|
|
41535
|
+
function validateMsgAndHash(message, prehash) {
|
|
41536
|
+
_abytes2(message, undefined, 'message');
|
|
41537
|
+
return prehash ? _abytes2(hash(message), undefined, 'prehashed message') : message;
|
|
41538
|
+
}
|
|
41539
|
+
/**
|
|
41540
|
+
* Steps A, D of RFC6979 3.2.
|
|
41541
|
+
* Creates RFC6979 seed; converts msg/privKey to numbers.
|
|
41542
|
+
* Used only in sign, not in verify.
|
|
41543
|
+
*
|
|
41544
|
+
* Warning: we cannot assume here that message has same amount of bytes as curve order,
|
|
41545
|
+
* this will be invalid at least for P521. Also it can be bigger for P224 + SHA256.
|
|
41546
|
+
*/
|
|
41547
|
+
function prepSig(message, privateKey, opts) {
|
|
41548
|
+
if (['recovered', 'canonical'].some((k) => k in opts))
|
|
41549
|
+
throw new Error('sign() legacy options not supported');
|
|
41550
|
+
const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
|
|
41551
|
+
message = validateMsgAndHash(message, prehash); // RFC6979 3.2 A: h1 = H(m)
|
|
41552
|
+
// We can't later call bits2octets, since nested bits2int is broken for curves
|
|
41553
|
+
// with fnBits % 8 !== 0. Because of that, we unwrap it here as int2octets call.
|
|
41554
|
+
// const bits2octets = (bits) => int2octets(bits2int_modN(bits))
|
|
41555
|
+
const h1int = bits2int_modN(message);
|
|
41556
|
+
const d = _normFnElement(Fn, privateKey); // validate secret key, convert to bigint
|
|
41557
|
+
const seedArgs = [int2octets(d), int2octets(h1int)];
|
|
41558
|
+
// extraEntropy. RFC6979 3.6: additional k' (optional).
|
|
41559
|
+
if (extraEntropy != null && extraEntropy !== false) {
|
|
41560
|
+
// K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')
|
|
41561
|
+
// gen random bytes OR pass as-is
|
|
41562
|
+
const e = extraEntropy === true ? randomBytes(lengths.secretKey) : extraEntropy;
|
|
41563
|
+
seedArgs.push(ensureBytes$1('extraEntropy', e)); // check for being bytes
|
|
41564
|
+
}
|
|
41565
|
+
const seed = concatBytes$2(...seedArgs); // Step D of RFC6979 3.2
|
|
41566
|
+
const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!
|
|
41567
|
+
// Converts signature params into point w r/s, checks result for validity.
|
|
41568
|
+
// To transform k => Signature:
|
|
41569
|
+
// q = k⋅G
|
|
41570
|
+
// r = q.x mod n
|
|
41571
|
+
// s = k^-1(m + rd) mod n
|
|
41572
|
+
// Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to
|
|
41573
|
+
// https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:
|
|
41574
|
+
// a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT
|
|
41575
|
+
function k2sig(kBytes) {
|
|
41576
|
+
// RFC 6979 Section 3.2, step 3: k = bits2int(T)
|
|
41577
|
+
// Important: all mod() calls here must be done over N
|
|
41578
|
+
const k = bits2int(kBytes); // mod n, not mod p
|
|
41579
|
+
if (!Fn.isValidNot0(k))
|
|
41580
|
+
return; // Valid scalars (including k) must be in 1..N-1
|
|
41581
|
+
const ik = Fn.inv(k); // k^-1 mod n
|
|
41582
|
+
const q = Point.BASE.multiply(k).toAffine(); // q = k⋅G
|
|
41583
|
+
const r = Fn.create(q.x); // r = q.x mod n
|
|
41584
|
+
if (r === _0n$1)
|
|
41585
|
+
return;
|
|
41586
|
+
const s = Fn.create(ik * Fn.create(m + r * d)); // Not using blinding here, see comment above
|
|
41587
|
+
if (s === _0n$1)
|
|
41588
|
+
return;
|
|
41589
|
+
let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n$1); // recovery bit (2 or 3, when q.x > n)
|
|
41590
|
+
let normS = s;
|
|
41591
|
+
if (lowS && isBiggerThanHalfOrder(s)) {
|
|
41592
|
+
normS = Fn.neg(s); // if lowS was passed, ensure s is always
|
|
41593
|
+
recovery ^= 1; // // in the bottom half of N
|
|
41594
|
+
}
|
|
41595
|
+
return new Signature(r, normS, recovery); // use normS, not s
|
|
41596
|
+
}
|
|
41597
|
+
return { seed, k2sig };
|
|
41598
|
+
}
|
|
41599
|
+
/**
|
|
41600
|
+
* Signs message hash with a secret key.
|
|
41601
|
+
*
|
|
41602
|
+
* ```
|
|
41603
|
+
* sign(m, d) where
|
|
41604
|
+
* k = rfc6979_hmac_drbg(m, d)
|
|
41605
|
+
* (x, y) = G × k
|
|
41606
|
+
* r = x mod n
|
|
41607
|
+
* s = (m + dr) / k mod n
|
|
41608
|
+
* ```
|
|
41609
|
+
*/
|
|
41610
|
+
function sign(message, secretKey, opts = {}) {
|
|
41611
|
+
message = ensureBytes$1('message', message);
|
|
41612
|
+
const { seed, k2sig } = prepSig(message, secretKey, opts); // Steps A, D of RFC6979 3.2.
|
|
41613
|
+
const drbg = createHmacDrbg(hash.outputLen, Fn.BYTES, hmac$1);
|
|
41614
|
+
const sig = drbg(seed, k2sig); // Steps B, C, D, E, F, G
|
|
41615
|
+
return sig;
|
|
41616
|
+
}
|
|
41617
|
+
function tryParsingSig(sg) {
|
|
41618
|
+
// Try to deduce format
|
|
41619
|
+
let sig = undefined;
|
|
41620
|
+
const isHex = typeof sg === 'string' || isBytes$2(sg);
|
|
41621
|
+
const isObj = !isHex &&
|
|
41622
|
+
sg !== null &&
|
|
41623
|
+
typeof sg === 'object' &&
|
|
41624
|
+
typeof sg.r === 'bigint' &&
|
|
41625
|
+
typeof sg.s === 'bigint';
|
|
41626
|
+
if (!isHex && !isObj)
|
|
41627
|
+
throw new Error('invalid signature, expected Uint8Array, hex string or Signature instance');
|
|
41628
|
+
if (isObj) {
|
|
41629
|
+
sig = new Signature(sg.r, sg.s);
|
|
41630
|
+
}
|
|
41631
|
+
else if (isHex) {
|
|
41632
|
+
try {
|
|
41633
|
+
sig = Signature.fromBytes(ensureBytes$1('sig', sg), 'der');
|
|
41634
|
+
}
|
|
41635
|
+
catch (derError) {
|
|
41636
|
+
if (!(derError instanceof DER.Err))
|
|
41637
|
+
throw derError;
|
|
41638
|
+
}
|
|
41639
|
+
if (!sig) {
|
|
41640
|
+
try {
|
|
41641
|
+
sig = Signature.fromBytes(ensureBytes$1('sig', sg), 'compact');
|
|
41642
|
+
}
|
|
41643
|
+
catch (error) {
|
|
41644
|
+
return false;
|
|
41645
|
+
}
|
|
41646
|
+
}
|
|
41647
|
+
}
|
|
41648
|
+
if (!sig)
|
|
41649
|
+
return false;
|
|
41650
|
+
return sig;
|
|
41651
|
+
}
|
|
41652
|
+
/**
|
|
41653
|
+
* Verifies a signature against message and public key.
|
|
41654
|
+
* Rejects lowS signatures by default: see {@link ECDSAVerifyOpts}.
|
|
41655
|
+
* Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:
|
|
41656
|
+
*
|
|
41657
|
+
* ```
|
|
41658
|
+
* verify(r, s, h, P) where
|
|
41659
|
+
* u1 = hs^-1 mod n
|
|
41660
|
+
* u2 = rs^-1 mod n
|
|
41661
|
+
* R = u1⋅G + u2⋅P
|
|
41662
|
+
* mod(R.x, n) == r
|
|
41663
|
+
* ```
|
|
41664
|
+
*/
|
|
41665
|
+
function verify(signature, message, publicKey, opts = {}) {
|
|
41666
|
+
const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
|
|
41667
|
+
publicKey = ensureBytes$1('publicKey', publicKey);
|
|
41668
|
+
message = validateMsgAndHash(ensureBytes$1('message', message), prehash);
|
|
41669
|
+
if ('strict' in opts)
|
|
41670
|
+
throw new Error('options.strict was renamed to lowS');
|
|
41671
|
+
const sig = format === undefined
|
|
41672
|
+
? tryParsingSig(signature)
|
|
41673
|
+
: Signature.fromBytes(ensureBytes$1('sig', signature), format);
|
|
41674
|
+
if (sig === false)
|
|
41675
|
+
return false;
|
|
41676
|
+
try {
|
|
41677
|
+
const P = Point.fromBytes(publicKey);
|
|
41678
|
+
if (lowS && sig.hasHighS())
|
|
41679
|
+
return false;
|
|
41680
|
+
const { r, s } = sig;
|
|
41681
|
+
const h = bits2int_modN(message); // mod n, not mod p
|
|
41682
|
+
const is = Fn.inv(s); // s^-1 mod n
|
|
41683
|
+
const u1 = Fn.create(h * is); // u1 = hs^-1 mod n
|
|
41684
|
+
const u2 = Fn.create(r * is); // u2 = rs^-1 mod n
|
|
41685
|
+
const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2)); // u1⋅G + u2⋅P
|
|
41686
|
+
if (R.is0())
|
|
41687
|
+
return false;
|
|
41688
|
+
const v = Fn.create(R.x); // v = r.x mod n
|
|
41689
|
+
return v === r;
|
|
41690
|
+
}
|
|
41691
|
+
catch (e) {
|
|
41692
|
+
return false;
|
|
41693
|
+
}
|
|
41694
|
+
}
|
|
41695
|
+
function recoverPublicKey(signature, message, opts = {}) {
|
|
41696
|
+
const { prehash } = validateSigOpts(opts, defaultSigOpts);
|
|
41697
|
+
message = validateMsgAndHash(message, prehash);
|
|
41698
|
+
return Signature.fromBytes(signature, 'recovered').recoverPublicKey(message).toBytes();
|
|
41699
|
+
}
|
|
41700
|
+
return Object.freeze({
|
|
41701
|
+
keygen,
|
|
41702
|
+
getPublicKey,
|
|
41703
|
+
getSharedSecret,
|
|
41704
|
+
utils,
|
|
41705
|
+
lengths,
|
|
41706
|
+
Point,
|
|
41707
|
+
sign,
|
|
41708
|
+
verify,
|
|
41709
|
+
recoverPublicKey,
|
|
41710
|
+
Signature,
|
|
41711
|
+
hash,
|
|
41712
|
+
});
|
|
41713
|
+
}
|
|
41714
|
+
function _weierstrass_legacy_opts_to_new(c) {
|
|
41715
|
+
const CURVE = {
|
|
41716
|
+
a: c.a,
|
|
41717
|
+
b: c.b,
|
|
41718
|
+
p: c.Fp.ORDER,
|
|
41719
|
+
n: c.n,
|
|
41720
|
+
h: c.h,
|
|
41721
|
+
Gx: c.Gx,
|
|
41722
|
+
Gy: c.Gy,
|
|
41723
|
+
};
|
|
41724
|
+
const Fp = c.Fp;
|
|
41725
|
+
let allowedLengths = c.allowedPrivateKeyLengths
|
|
41726
|
+
? Array.from(new Set(c.allowedPrivateKeyLengths.map((l) => Math.ceil(l / 2))))
|
|
41727
|
+
: undefined;
|
|
41728
|
+
const Fn = Field(CURVE.n, {
|
|
41729
|
+
BITS: c.nBitLength,
|
|
41730
|
+
allowedLengths: allowedLengths,
|
|
41731
|
+
modFromBytes: c.wrapPrivateKey,
|
|
41732
|
+
});
|
|
41733
|
+
const curveOpts = {
|
|
41734
|
+
Fp,
|
|
41735
|
+
Fn,
|
|
41736
|
+
allowInfinityPoint: c.allowInfinityPoint,
|
|
41737
|
+
endo: c.endo,
|
|
41738
|
+
isTorsionFree: c.isTorsionFree,
|
|
41739
|
+
clearCofactor: c.clearCofactor,
|
|
41740
|
+
fromBytes: c.fromBytes,
|
|
41741
|
+
toBytes: c.toBytes,
|
|
41742
|
+
};
|
|
41743
|
+
return { CURVE, curveOpts };
|
|
41744
|
+
}
|
|
41745
|
+
function _ecdsa_legacy_opts_to_new(c) {
|
|
41746
|
+
const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);
|
|
41747
|
+
const ecdsaOpts = {
|
|
41748
|
+
hmac: c.hmac,
|
|
41749
|
+
randomBytes: c.randomBytes,
|
|
41750
|
+
lowS: c.lowS,
|
|
41751
|
+
bits2int: c.bits2int,
|
|
41752
|
+
bits2int_modN: c.bits2int_modN,
|
|
41753
|
+
};
|
|
41754
|
+
return { CURVE, curveOpts, hash: c.hash, ecdsaOpts };
|
|
41755
|
+
}
|
|
41756
|
+
function _ecdsa_new_output_to_legacy(c, _ecdsa) {
|
|
41757
|
+
const Point = _ecdsa.Point;
|
|
41758
|
+
return Object.assign({}, _ecdsa, {
|
|
41759
|
+
ProjectivePoint: Point,
|
|
41760
|
+
CURVE: Object.assign({}, c, nLength(Point.Fn.ORDER, Point.Fn.BITS)),
|
|
41761
|
+
});
|
|
41762
|
+
}
|
|
41763
|
+
// _ecdsa_legacy
|
|
41764
|
+
function weierstrass(c) {
|
|
41765
|
+
const { CURVE, curveOpts, hash, ecdsaOpts } = _ecdsa_legacy_opts_to_new(c);
|
|
41766
|
+
const Point = weierstrassN(CURVE, curveOpts);
|
|
41767
|
+
const signs = ecdsa(Point, hash, ecdsaOpts);
|
|
41768
|
+
return _ecdsa_new_output_to_legacy(c, signs);
|
|
41769
|
+
}
|
|
41770
|
+
|
|
41771
|
+
/**
|
|
41772
|
+
* Utilities for short weierstrass curves, combined with noble-hashes.
|
|
41773
|
+
* @module
|
|
41774
|
+
*/
|
|
41775
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
41776
|
+
/** @deprecated use new `weierstrass()` and `ecdsa()` methods */
|
|
41777
|
+
function createCurve(curveDef, defHash) {
|
|
41778
|
+
const create = (hash) => weierstrass({ ...curveDef, hash: hash });
|
|
41779
|
+
return { ...create(defHash), create };
|
|
41780
|
+
}
|
|
41781
|
+
|
|
41782
|
+
/**
|
|
41783
|
+
* SECG secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).
|
|
41784
|
+
*
|
|
41785
|
+
* Belongs to Koblitz curves: it has efficiently-computable GLV endomorphism ψ,
|
|
41786
|
+
* check out {@link EndomorphismOpts}. Seems to be rigid (not backdoored).
|
|
41787
|
+
* @module
|
|
41788
|
+
*/
|
|
41789
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
41790
|
+
// Seems like generator was produced from some seed:
|
|
41791
|
+
// `Point.BASE.multiply(Point.Fn.inv(2n, N)).toAffine().x`
|
|
41792
|
+
// // gives short x 0x3b78ce563f89a0ed9414f5aa28ad0d96d6795f9c63n
|
|
41793
|
+
const secp256k1_CURVE = {
|
|
41794
|
+
p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'),
|
|
41795
|
+
n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'),
|
|
41796
|
+
h: BigInt(1),
|
|
41797
|
+
a: BigInt(0),
|
|
41798
|
+
b: BigInt(7),
|
|
41799
|
+
Gx: BigInt('0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'),
|
|
41800
|
+
Gy: BigInt('0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8'),
|
|
41801
|
+
};
|
|
41802
|
+
const secp256k1_ENDO = {
|
|
41803
|
+
beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),
|
|
41804
|
+
basises: [
|
|
41805
|
+
[BigInt('0x3086d221a7d46bcde86c90e49284eb15'), -BigInt('0xe4437ed6010e88286f547fa90abfe4c3')],
|
|
41806
|
+
[BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'), BigInt('0x3086d221a7d46bcde86c90e49284eb15')],
|
|
41807
|
+
],
|
|
41808
|
+
};
|
|
41809
|
+
const _0n = /* @__PURE__ */ BigInt(0);
|
|
41810
|
+
const _1n = /* @__PURE__ */ BigInt(1);
|
|
41811
|
+
const _2n = /* @__PURE__ */ BigInt(2);
|
|
41812
|
+
/**
|
|
41813
|
+
* √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.
|
|
41814
|
+
* (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]
|
|
41815
|
+
*/
|
|
41816
|
+
function sqrtMod(y) {
|
|
41817
|
+
const P = secp256k1_CURVE.p;
|
|
41818
|
+
// prettier-ignore
|
|
41819
|
+
const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
|
|
41820
|
+
// prettier-ignore
|
|
41821
|
+
const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
|
|
41822
|
+
const b2 = (y * y * y) % P; // x^3, 11
|
|
41823
|
+
const b3 = (b2 * b2 * y) % P; // x^7
|
|
41824
|
+
const b6 = (pow2(b3, _3n, P) * b3) % P;
|
|
41825
|
+
const b9 = (pow2(b6, _3n, P) * b3) % P;
|
|
41826
|
+
const b11 = (pow2(b9, _2n, P) * b2) % P;
|
|
41827
|
+
const b22 = (pow2(b11, _11n, P) * b11) % P;
|
|
41828
|
+
const b44 = (pow2(b22, _22n, P) * b22) % P;
|
|
41829
|
+
const b88 = (pow2(b44, _44n, P) * b44) % P;
|
|
41830
|
+
const b176 = (pow2(b88, _88n, P) * b88) % P;
|
|
41831
|
+
const b220 = (pow2(b176, _44n, P) * b44) % P;
|
|
41832
|
+
const b223 = (pow2(b220, _3n, P) * b3) % P;
|
|
41833
|
+
const t1 = (pow2(b223, _23n, P) * b22) % P;
|
|
41834
|
+
const t2 = (pow2(t1, _6n, P) * b2) % P;
|
|
41835
|
+
const root = pow2(t2, _2n, P);
|
|
41836
|
+
if (!Fpk1.eql(Fpk1.sqr(root), y))
|
|
41837
|
+
throw new Error('Cannot find square root');
|
|
41838
|
+
return root;
|
|
41839
|
+
}
|
|
41840
|
+
const Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });
|
|
41841
|
+
/**
|
|
41842
|
+
* secp256k1 curve, ECDSA and ECDH methods.
|
|
41843
|
+
*
|
|
41844
|
+
* Field: `2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n`
|
|
41845
|
+
*
|
|
41846
|
+
* @example
|
|
41847
|
+
* ```js
|
|
41848
|
+
* import { secp256k1 } from '@noble/curves/secp256k1';
|
|
41849
|
+
* const { secretKey, publicKey } = secp256k1.keygen();
|
|
41850
|
+
* const msg = new TextEncoder().encode('hello');
|
|
41851
|
+
* const sig = secp256k1.sign(msg, secretKey);
|
|
41852
|
+
* const isValid = secp256k1.verify(sig, msg, publicKey) === true;
|
|
41853
|
+
* ```
|
|
41854
|
+
*/
|
|
41855
|
+
const secp256k1 = createCurve({ ...secp256k1_CURVE, Fp: Fpk1, lowS: true, endo: secp256k1_ENDO }, sha256$2);
|
|
41856
|
+
// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.
|
|
41857
|
+
// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki
|
|
41858
|
+
/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */
|
|
41859
|
+
const TAGGED_HASH_PREFIXES = {};
|
|
41860
|
+
function taggedHash(tag, ...messages) {
|
|
41861
|
+
let tagP = TAGGED_HASH_PREFIXES[tag];
|
|
41862
|
+
if (tagP === undefined) {
|
|
41863
|
+
const tagH = sha256$2(utf8ToBytes$1(tag));
|
|
41864
|
+
tagP = concatBytes$2(tagH, tagH);
|
|
41865
|
+
TAGGED_HASH_PREFIXES[tag] = tagP;
|
|
41866
|
+
}
|
|
41867
|
+
return sha256$2(concatBytes$2(tagP, ...messages));
|
|
41868
|
+
}
|
|
41869
|
+
// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03
|
|
41870
|
+
const pointToBytes = (point) => point.toBytes(true).slice(1);
|
|
41871
|
+
const Pointk1 = /* @__PURE__ */ (() => secp256k1.Point)();
|
|
41872
|
+
const hasEven = (y) => y % _2n === _0n;
|
|
41873
|
+
// Calculate point, scalar and bytes
|
|
41874
|
+
function schnorrGetExtPubKey(priv) {
|
|
41875
|
+
const { Fn, BASE } = Pointk1;
|
|
41876
|
+
const d_ = _normFnElement(Fn, priv);
|
|
41877
|
+
const p = BASE.multiply(d_); // P = d'⋅G; 0 < d' < n check is done inside
|
|
41878
|
+
const scalar = hasEven(p.y) ? d_ : Fn.neg(d_);
|
|
41879
|
+
return { scalar, bytes: pointToBytes(p) };
|
|
41880
|
+
}
|
|
41881
|
+
/**
|
|
41882
|
+
* lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.
|
|
41883
|
+
* @returns valid point checked for being on-curve
|
|
41884
|
+
*/
|
|
41885
|
+
function lift_x(x) {
|
|
41886
|
+
const Fp = Fpk1;
|
|
41887
|
+
if (!Fp.isValidNot0(x))
|
|
41888
|
+
throw new Error('invalid x: Fail if x ≥ p');
|
|
41889
|
+
const xx = Fp.create(x * x);
|
|
41890
|
+
const c = Fp.create(xx * x + BigInt(7)); // Let c = x³ + 7 mod p.
|
|
41891
|
+
let y = Fp.sqrt(c); // Let y = c^(p+1)/4 mod p. Same as sqrt().
|
|
41892
|
+
// Return the unique point P such that x(P) = x and
|
|
41893
|
+
// y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.
|
|
41894
|
+
if (!hasEven(y))
|
|
41895
|
+
y = Fp.neg(y);
|
|
41896
|
+
const p = Pointk1.fromAffine({ x, y });
|
|
41897
|
+
p.assertValidity();
|
|
41898
|
+
return p;
|
|
41899
|
+
}
|
|
41900
|
+
const num = bytesToNumberBE;
|
|
41901
|
+
/**
|
|
41902
|
+
* Create tagged hash, convert it to bigint, reduce modulo-n.
|
|
41903
|
+
*/
|
|
41904
|
+
function challenge(...args) {
|
|
41905
|
+
return Pointk1.Fn.create(num(taggedHash('BIP0340/challenge', ...args)));
|
|
41906
|
+
}
|
|
41907
|
+
/**
|
|
41908
|
+
* Schnorr public key is just `x` coordinate of Point as per BIP340.
|
|
41909
|
+
*/
|
|
41910
|
+
function schnorrGetPublicKey(secretKey) {
|
|
41911
|
+
return schnorrGetExtPubKey(secretKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G)
|
|
41912
|
+
}
|
|
41913
|
+
/**
|
|
41914
|
+
* Creates Schnorr signature as per BIP340. Verifies itself before returning anything.
|
|
41915
|
+
* auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.
|
|
41916
|
+
*/
|
|
41917
|
+
function schnorrSign(message, secretKey, auxRand = randomBytes$1(32)) {
|
|
41918
|
+
const { Fn } = Pointk1;
|
|
41919
|
+
const m = ensureBytes$1('message', message);
|
|
41920
|
+
const { bytes: px, scalar: d } = schnorrGetExtPubKey(secretKey); // checks for isWithinCurveOrder
|
|
41921
|
+
const a = ensureBytes$1('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array
|
|
41922
|
+
const t = Fn.toBytes(d ^ num(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)
|
|
41923
|
+
const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)
|
|
41924
|
+
// Let k' = int(rand) mod n. Fail if k' = 0. Let R = k'⋅G
|
|
41925
|
+
const { bytes: rx, scalar: k } = schnorrGetExtPubKey(rand);
|
|
41926
|
+
const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.
|
|
41927
|
+
const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).
|
|
41928
|
+
sig.set(rx, 0);
|
|
41929
|
+
sig.set(Fn.toBytes(Fn.create(k + e * d)), 32);
|
|
41930
|
+
// If Verify(bytes(P), m, sig) (see below) returns failure, abort
|
|
41931
|
+
if (!schnorrVerify(sig, m, px))
|
|
41932
|
+
throw new Error('sign: Invalid signature produced');
|
|
41933
|
+
return sig;
|
|
41934
|
+
}
|
|
41935
|
+
/**
|
|
41936
|
+
* Verifies Schnorr signature.
|
|
41937
|
+
* Will swallow errors & return false except for initial type validation of arguments.
|
|
41938
|
+
*/
|
|
41939
|
+
function schnorrVerify(signature, message, publicKey) {
|
|
41940
|
+
const { Fn, BASE } = Pointk1;
|
|
41941
|
+
const sig = ensureBytes$1('signature', signature, 64);
|
|
41942
|
+
const m = ensureBytes$1('message', message);
|
|
41943
|
+
const pub = ensureBytes$1('publicKey', publicKey, 32);
|
|
41944
|
+
try {
|
|
41945
|
+
const P = lift_x(num(pub)); // P = lift_x(int(pk)); fail if that fails
|
|
41946
|
+
const r = num(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p.
|
|
41947
|
+
if (!inRange(r, _1n, secp256k1_CURVE.p))
|
|
41948
|
+
return false;
|
|
41949
|
+
const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.
|
|
41950
|
+
if (!inRange(s, _1n, secp256k1_CURVE.n))
|
|
41951
|
+
return false;
|
|
41952
|
+
// int(challenge(bytes(r)||bytes(P)||m))%n
|
|
41953
|
+
const e = challenge(Fn.toBytes(r), pointToBytes(P), m);
|
|
41954
|
+
// R = s⋅G - e⋅P, where -eP == (n-e)P
|
|
41955
|
+
const R = BASE.multiplyUnsafe(s).add(P.multiplyUnsafe(Fn.neg(e)));
|
|
41956
|
+
const { x, y } = R.toAffine();
|
|
41957
|
+
// Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.
|
|
41958
|
+
if (R.is0() || !hasEven(y) || x !== r)
|
|
41959
|
+
return false;
|
|
41960
|
+
return true;
|
|
41961
|
+
}
|
|
41962
|
+
catch (error) {
|
|
41963
|
+
return false;
|
|
41964
|
+
}
|
|
41965
|
+
}
|
|
41966
|
+
/**
|
|
41967
|
+
* Schnorr signatures over secp256k1.
|
|
41968
|
+
* https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki
|
|
41969
|
+
* @example
|
|
41970
|
+
* ```js
|
|
41971
|
+
* import { schnorr } from '@noble/curves/secp256k1';
|
|
41972
|
+
* const { secretKey, publicKey } = schnorr.keygen();
|
|
41973
|
+
* // const publicKey = schnorr.getPublicKey(secretKey);
|
|
41974
|
+
* const msg = new TextEncoder().encode('hello');
|
|
41975
|
+
* const sig = schnorr.sign(msg, secretKey);
|
|
41976
|
+
* const isValid = schnorr.verify(sig, msg, publicKey);
|
|
41977
|
+
* ```
|
|
41978
|
+
*/
|
|
41979
|
+
const schnorr = /* @__PURE__ */ (() => {
|
|
41980
|
+
const size = 32;
|
|
41981
|
+
const seedLength = 48;
|
|
41982
|
+
const randomSecretKey = (seed = randomBytes$1(seedLength)) => {
|
|
41983
|
+
return mapHashToField(seed, secp256k1_CURVE.n);
|
|
41984
|
+
};
|
|
41985
|
+
// TODO: remove
|
|
41986
|
+
secp256k1.utils.randomSecretKey;
|
|
41987
|
+
function keygen(seed) {
|
|
41988
|
+
const secretKey = randomSecretKey(seed);
|
|
41989
|
+
return { secretKey, publicKey: schnorrGetPublicKey(secretKey) };
|
|
41990
|
+
}
|
|
41991
|
+
return {
|
|
41992
|
+
keygen,
|
|
41993
|
+
getPublicKey: schnorrGetPublicKey,
|
|
41994
|
+
sign: schnorrSign,
|
|
41995
|
+
verify: schnorrVerify,
|
|
41996
|
+
Point: Pointk1,
|
|
41997
|
+
utils: {
|
|
41998
|
+
randomSecretKey: randomSecretKey,
|
|
41999
|
+
randomPrivateKey: randomSecretKey,
|
|
42000
|
+
taggedHash,
|
|
42001
|
+
// TODO: remove
|
|
42002
|
+
lift_x,
|
|
42003
|
+
pointToBytes,
|
|
42004
|
+
numberToBytesBE,
|
|
42005
|
+
bytesToNumberBE,
|
|
42006
|
+
mod,
|
|
42007
|
+
},
|
|
42008
|
+
lengths: {
|
|
42009
|
+
secretKey: size,
|
|
42010
|
+
publicKey: size,
|
|
42011
|
+
publicKeyHasPrefix: false,
|
|
42012
|
+
signature: size * 2,
|
|
42013
|
+
seed: seedLength,
|
|
42014
|
+
},
|
|
42015
|
+
};
|
|
42016
|
+
})();
|
|
39374
42017
|
|
|
39375
42018
|
/**
|
|
39376
42019
|
* SHA2-256 a.k.a. sha256. In JS, it is the fastest hash, even faster than Blake3.
|
|
@@ -41246,6 +43889,187 @@ function jwkToCompressedBytes(jwk) {
|
|
|
41246
43889
|
return new Uint8Array([prefix, ...xBytes]);
|
|
41247
43890
|
}
|
|
41248
43891
|
|
|
43892
|
+
var dist = {};
|
|
43893
|
+
|
|
43894
|
+
var hasRequiredDist;
|
|
43895
|
+
|
|
43896
|
+
function requireDist () {
|
|
43897
|
+
if (hasRequiredDist) return dist;
|
|
43898
|
+
hasRequiredDist = 1;
|
|
43899
|
+
Object.defineProperty(dist, "__esModule", { value: true });
|
|
43900
|
+
dist.bech32m = dist.bech32 = void 0;
|
|
43901
|
+
const ALPHABET = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l';
|
|
43902
|
+
const ALPHABET_MAP = {};
|
|
43903
|
+
for (let z = 0; z < ALPHABET.length; z++) {
|
|
43904
|
+
const x = ALPHABET.charAt(z);
|
|
43905
|
+
ALPHABET_MAP[x] = z;
|
|
43906
|
+
}
|
|
43907
|
+
function polymodStep(pre) {
|
|
43908
|
+
const b = pre >> 25;
|
|
43909
|
+
return (((pre & 0x1ffffff) << 5) ^
|
|
43910
|
+
(-((b >> 0) & 1) & 0x3b6a57b2) ^
|
|
43911
|
+
(-((b >> 1) & 1) & 0x26508e6d) ^
|
|
43912
|
+
(-((b >> 2) & 1) & 0x1ea119fa) ^
|
|
43913
|
+
(-((b >> 3) & 1) & 0x3d4233dd) ^
|
|
43914
|
+
(-((b >> 4) & 1) & 0x2a1462b3));
|
|
43915
|
+
}
|
|
43916
|
+
function prefixChk(prefix) {
|
|
43917
|
+
let chk = 1;
|
|
43918
|
+
for (let i = 0; i < prefix.length; ++i) {
|
|
43919
|
+
const c = prefix.charCodeAt(i);
|
|
43920
|
+
if (c < 33 || c > 126)
|
|
43921
|
+
return 'Invalid prefix (' + prefix + ')';
|
|
43922
|
+
chk = polymodStep(chk) ^ (c >> 5);
|
|
43923
|
+
}
|
|
43924
|
+
chk = polymodStep(chk);
|
|
43925
|
+
for (let i = 0; i < prefix.length; ++i) {
|
|
43926
|
+
const v = prefix.charCodeAt(i);
|
|
43927
|
+
chk = polymodStep(chk) ^ (v & 0x1f);
|
|
43928
|
+
}
|
|
43929
|
+
return chk;
|
|
43930
|
+
}
|
|
43931
|
+
function convert(data, inBits, outBits, pad) {
|
|
43932
|
+
let value = 0;
|
|
43933
|
+
let bits = 0;
|
|
43934
|
+
const maxV = (1 << outBits) - 1;
|
|
43935
|
+
const result = [];
|
|
43936
|
+
for (let i = 0; i < data.length; ++i) {
|
|
43937
|
+
value = (value << inBits) | data[i];
|
|
43938
|
+
bits += inBits;
|
|
43939
|
+
while (bits >= outBits) {
|
|
43940
|
+
bits -= outBits;
|
|
43941
|
+
result.push((value >> bits) & maxV);
|
|
43942
|
+
}
|
|
43943
|
+
}
|
|
43944
|
+
if (pad) {
|
|
43945
|
+
if (bits > 0) {
|
|
43946
|
+
result.push((value << (outBits - bits)) & maxV);
|
|
43947
|
+
}
|
|
43948
|
+
}
|
|
43949
|
+
else {
|
|
43950
|
+
if (bits >= inBits)
|
|
43951
|
+
return 'Excess padding';
|
|
43952
|
+
if ((value << (outBits - bits)) & maxV)
|
|
43953
|
+
return 'Non-zero padding';
|
|
43954
|
+
}
|
|
43955
|
+
return result;
|
|
43956
|
+
}
|
|
43957
|
+
function toWords(bytes) {
|
|
43958
|
+
return convert(bytes, 8, 5, true);
|
|
43959
|
+
}
|
|
43960
|
+
function fromWordsUnsafe(words) {
|
|
43961
|
+
const res = convert(words, 5, 8, false);
|
|
43962
|
+
if (Array.isArray(res))
|
|
43963
|
+
return res;
|
|
43964
|
+
}
|
|
43965
|
+
function fromWords(words) {
|
|
43966
|
+
const res = convert(words, 5, 8, false);
|
|
43967
|
+
if (Array.isArray(res))
|
|
43968
|
+
return res;
|
|
43969
|
+
throw new Error(res);
|
|
43970
|
+
}
|
|
43971
|
+
function getLibraryFromEncoding(encoding) {
|
|
43972
|
+
let ENCODING_CONST;
|
|
43973
|
+
if (encoding === 'bech32') {
|
|
43974
|
+
ENCODING_CONST = 1;
|
|
43975
|
+
}
|
|
43976
|
+
else {
|
|
43977
|
+
ENCODING_CONST = 0x2bc830a3;
|
|
43978
|
+
}
|
|
43979
|
+
function encode(prefix, words, LIMIT) {
|
|
43980
|
+
LIMIT = LIMIT || 90;
|
|
43981
|
+
if (prefix.length + 7 + words.length > LIMIT)
|
|
43982
|
+
throw new TypeError('Exceeds length limit');
|
|
43983
|
+
prefix = prefix.toLowerCase();
|
|
43984
|
+
// determine chk mod
|
|
43985
|
+
let chk = prefixChk(prefix);
|
|
43986
|
+
if (typeof chk === 'string')
|
|
43987
|
+
throw new Error(chk);
|
|
43988
|
+
let result = prefix + '1';
|
|
43989
|
+
for (let i = 0; i < words.length; ++i) {
|
|
43990
|
+
const x = words[i];
|
|
43991
|
+
if (x >> 5 !== 0)
|
|
43992
|
+
throw new Error('Non 5-bit word');
|
|
43993
|
+
chk = polymodStep(chk) ^ x;
|
|
43994
|
+
result += ALPHABET.charAt(x);
|
|
43995
|
+
}
|
|
43996
|
+
for (let i = 0; i < 6; ++i) {
|
|
43997
|
+
chk = polymodStep(chk);
|
|
43998
|
+
}
|
|
43999
|
+
chk ^= ENCODING_CONST;
|
|
44000
|
+
for (let i = 0; i < 6; ++i) {
|
|
44001
|
+
const v = (chk >> ((5 - i) * 5)) & 0x1f;
|
|
44002
|
+
result += ALPHABET.charAt(v);
|
|
44003
|
+
}
|
|
44004
|
+
return result;
|
|
44005
|
+
}
|
|
44006
|
+
function __decode(str, LIMIT) {
|
|
44007
|
+
LIMIT = LIMIT || 90;
|
|
44008
|
+
if (str.length < 8)
|
|
44009
|
+
return str + ' too short';
|
|
44010
|
+
if (str.length > LIMIT)
|
|
44011
|
+
return 'Exceeds length limit';
|
|
44012
|
+
// don't allow mixed case
|
|
44013
|
+
const lowered = str.toLowerCase();
|
|
44014
|
+
const uppered = str.toUpperCase();
|
|
44015
|
+
if (str !== lowered && str !== uppered)
|
|
44016
|
+
return 'Mixed-case string ' + str;
|
|
44017
|
+
str = lowered;
|
|
44018
|
+
const split = str.lastIndexOf('1');
|
|
44019
|
+
if (split === -1)
|
|
44020
|
+
return 'No separator character for ' + str;
|
|
44021
|
+
if (split === 0)
|
|
44022
|
+
return 'Missing prefix for ' + str;
|
|
44023
|
+
const prefix = str.slice(0, split);
|
|
44024
|
+
const wordChars = str.slice(split + 1);
|
|
44025
|
+
if (wordChars.length < 6)
|
|
44026
|
+
return 'Data too short';
|
|
44027
|
+
let chk = prefixChk(prefix);
|
|
44028
|
+
if (typeof chk === 'string')
|
|
44029
|
+
return chk;
|
|
44030
|
+
const words = [];
|
|
44031
|
+
for (let i = 0; i < wordChars.length; ++i) {
|
|
44032
|
+
const c = wordChars.charAt(i);
|
|
44033
|
+
const v = ALPHABET_MAP[c];
|
|
44034
|
+
if (v === undefined)
|
|
44035
|
+
return 'Unknown character ' + c;
|
|
44036
|
+
chk = polymodStep(chk) ^ v;
|
|
44037
|
+
// not in the checksum?
|
|
44038
|
+
if (i + 6 >= wordChars.length)
|
|
44039
|
+
continue;
|
|
44040
|
+
words.push(v);
|
|
44041
|
+
}
|
|
44042
|
+
if (chk !== ENCODING_CONST)
|
|
44043
|
+
return 'Invalid checksum for ' + str;
|
|
44044
|
+
return { prefix, words };
|
|
44045
|
+
}
|
|
44046
|
+
function decodeUnsafe(str, LIMIT) {
|
|
44047
|
+
const res = __decode(str, LIMIT);
|
|
44048
|
+
if (typeof res === 'object')
|
|
44049
|
+
return res;
|
|
44050
|
+
}
|
|
44051
|
+
function decode(str, LIMIT) {
|
|
44052
|
+
const res = __decode(str, LIMIT);
|
|
44053
|
+
if (typeof res === 'object')
|
|
44054
|
+
return res;
|
|
44055
|
+
throw new Error(res);
|
|
44056
|
+
}
|
|
44057
|
+
return {
|
|
44058
|
+
decodeUnsafe,
|
|
44059
|
+
decode,
|
|
44060
|
+
encode,
|
|
44061
|
+
toWords,
|
|
44062
|
+
fromWordsUnsafe,
|
|
44063
|
+
fromWords,
|
|
44064
|
+
};
|
|
44065
|
+
}
|
|
44066
|
+
dist.bech32 = getLibraryFromEncoding('bech32');
|
|
44067
|
+
dist.bech32m = getLibraryFromEncoding('bech32m');
|
|
44068
|
+
return dist;
|
|
44069
|
+
}
|
|
44070
|
+
|
|
44071
|
+
var distExports = requireDist();
|
|
44072
|
+
|
|
41249
44073
|
const canonicalize = canonicalizeModule;
|
|
41250
44074
|
// Polyfill for synchronous signatures
|
|
41251
44075
|
etc.hmacSha256Sync = (k, ...m) => hmac(sha256$1, k, etc.concatBytes(...m));
|
|
@@ -41280,6 +44104,12 @@ class CipherBase {
|
|
|
41280
44104
|
const prefix = yBytes[yBytes.length - 1] % 2 === 0 ? 0x02 : 0x03;
|
|
41281
44105
|
return new Uint8Array([prefix, ...xBytes]);
|
|
41282
44106
|
}
|
|
44107
|
+
jwkToNostr(publicJwk) {
|
|
44108
|
+
const pubkeyBytes = Buffer.from(base64url.baseDecode(publicJwk.x));
|
|
44109
|
+
const pubkey = pubkeyBytes.toString('hex');
|
|
44110
|
+
const npub = distExports.bech32.encode('npub', distExports.bech32.toWords(pubkeyBytes), 1000);
|
|
44111
|
+
return { npub, pubkey };
|
|
44112
|
+
}
|
|
41283
44113
|
hashMessage(msg) {
|
|
41284
44114
|
const hash = sha256$1(msg);
|
|
41285
44115
|
return Buffer.from(hash).toString('hex');
|
|
@@ -41295,6 +44125,16 @@ class CipherBase {
|
|
|
41295
44125
|
const signature = sign(msgHash, privKey);
|
|
41296
44126
|
return signature.toCompactHex();
|
|
41297
44127
|
}
|
|
44128
|
+
signSchnorr(msgHash, privateJwk) {
|
|
44129
|
+
const privKey = base64url.baseDecode(privateJwk.d);
|
|
44130
|
+
const msgHashBytes = Uint8Array.from(Buffer.from(msgHash, 'hex'));
|
|
44131
|
+
const sig = schnorr.sign(msgHashBytes, privKey);
|
|
44132
|
+
return Buffer.from(sig).toString('hex');
|
|
44133
|
+
}
|
|
44134
|
+
jwkToNsec(privateJwk) {
|
|
44135
|
+
const privKeyBytes = base64url.baseDecode(privateJwk.d);
|
|
44136
|
+
return distExports.bech32.encode('nsec', distExports.bech32.toWords(Buffer.from(privKeyBytes)), 1000);
|
|
44137
|
+
}
|
|
41298
44138
|
verifySig(msgHash, sigHex, publicJwk) {
|
|
41299
44139
|
const compressedPublicKeyBytes = this.convertJwkToCompressedBytes(publicJwk);
|
|
41300
44140
|
const signature = Signature.fromCompact(sigHex);
|
|
@@ -41380,7 +44220,7 @@ class CipherNode extends CipherBase {
|
|
|
41380
44220
|
return HDKeyNode.fromJSON(json);
|
|
41381
44221
|
}
|
|
41382
44222
|
generateRandomSalt() {
|
|
41383
|
-
return base64url.encode(crypto$
|
|
44223
|
+
return base64url.encode(crypto$3.randomBytes(32));
|
|
41384
44224
|
}
|
|
41385
44225
|
}
|
|
41386
44226
|
|
|
@@ -42065,7 +44905,7 @@ const code = 0x55;
|
|
|
42065
44905
|
const sha256 = from({
|
|
42066
44906
|
name: 'sha2-256',
|
|
42067
44907
|
code: 0x12,
|
|
42068
|
-
encode: (input) => coerce(crypto$
|
|
44908
|
+
encode: (input) => coerce(crypto$3.createHash('sha256').update(input).digest())
|
|
42069
44909
|
});
|
|
42070
44910
|
|
|
42071
44911
|
function isValidCID(cid) {
|