-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathnoble-secp256k1.js
986 lines (984 loc) · 33.7 KB
/
noble-secp256k1.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.nobleSecp256k1 = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
},{}],2:[function(require,module,exports){
"use strict";
/*! noble-secp256k1 - MIT License (c) Paul Miller (paulmillr.com) */
Object.defineProperty(exports, "__esModule", { value: true });
exports.utils = exports.schnorr = exports.verify = exports.signSync = exports.sign = exports.getSharedSecret = exports.recoverPublicKey = exports.getPublicKey = exports.SignResult = exports.Signature = exports.Point = exports.CURVE = void 0;
const CURVE = {
a: 0n,
b: 7n,
P: 2n ** 256n - 2n ** 32n - 977n,
n: 2n ** 256n - 432420386565659656852420866394968145599n,
h: 1n,
Gx: 55066263022277343669578718895168534326250603453777594175500187360389116729240n,
Gy: 32670510020758816978083085130507043184471273380659243275938904335757337482424n,
beta: 0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501een,
};
exports.CURVE = CURVE;
function weistrass(x) {
const { a, b } = CURVE;
return mod(x ** 3n + a * x + b);
}
const USE_ENDOMORPHISM = CURVE.a === 0n;
class JacobianPoint {
constructor(x, y, z) {
this.x = x;
this.y = y;
this.z = z;
}
static fromAffine(p) {
if (!(p instanceof Point)) {
throw new TypeError('JacobianPoint#fromAffine: expected Point');
}
return new JacobianPoint(p.x, p.y, 1n);
}
static toAffineBatch(points) {
const toInv = invertBatch(points.map((p) => p.z));
return points.map((p, i) => p.toAffine(toInv[i]));
}
static normalizeZ(points) {
return JacobianPoint.toAffineBatch(points).map(JacobianPoint.fromAffine);
}
equals(other) {
const a = this;
const b = other;
const az2 = mod(a.z * a.z);
const az3 = mod(a.z * az2);
const bz2 = mod(b.z * b.z);
const bz3 = mod(b.z * bz2);
return mod(a.x * bz2) === mod(az2 * b.x) && mod(a.y * bz3) === mod(az3 * b.y);
}
negate() {
return new JacobianPoint(this.x, mod(-this.y), this.z);
}
double() {
const X1 = this.x;
const Y1 = this.y;
const Z1 = this.z;
const A = mod(X1 ** 2n);
const B = mod(Y1 ** 2n);
const C = mod(B ** 2n);
const D = mod(2n * (mod(mod((X1 + B) ** 2n)) - A - C));
const E = mod(3n * A);
const F = mod(E ** 2n);
const X3 = mod(F - 2n * D);
const Y3 = mod(E * (D - X3) - 8n * C);
const Z3 = mod(2n * Y1 * Z1);
return new JacobianPoint(X3, Y3, Z3);
}
add(other) {
if (!(other instanceof JacobianPoint)) {
throw new TypeError('JacobianPoint#add: expected JacobianPoint');
}
const X1 = this.x;
const Y1 = this.y;
const Z1 = this.z;
const X2 = other.x;
const Y2 = other.y;
const Z2 = other.z;
if (X2 === 0n || Y2 === 0n)
return this;
if (X1 === 0n || Y1 === 0n)
return other;
const Z1Z1 = mod(Z1 ** 2n);
const Z2Z2 = mod(Z2 ** 2n);
const U1 = mod(X1 * Z2Z2);
const U2 = mod(X2 * Z1Z1);
const S1 = mod(Y1 * Z2 * Z2Z2);
const S2 = mod(mod(Y2 * Z1) * Z1Z1);
const H = mod(U2 - U1);
const r = mod(S2 - S1);
if (H === 0n) {
if (r === 0n) {
return this.double();
}
else {
return JacobianPoint.ZERO;
}
}
const HH = mod(H ** 2n);
const HHH = mod(H * HH);
const V = mod(U1 * HH);
const X3 = mod(r ** 2n - HHH - 2n * V);
const Y3 = mod(r * (V - X3) - S1 * HHH);
const Z3 = mod(Z1 * Z2 * H);
return new JacobianPoint(X3, Y3, Z3);
}
subtract(other) {
return this.add(other.negate());
}
multiplyUnsafe(scalar) {
if (!isValidScalar(scalar))
throw new TypeError('Point#multiply: expected valid scalar');
let n = mod(BigInt(scalar), CURVE.n);
if (!USE_ENDOMORPHISM) {
let p = JacobianPoint.ZERO;
let d = this;
while (n > 0n) {
if (n & 1n)
p = p.add(d);
d = d.double();
n >>= 1n;
}
return p;
}
let [k1neg, k1, k2neg, k2] = splitScalarEndo(n);
let k1p = JacobianPoint.ZERO;
let k2p = JacobianPoint.ZERO;
let d = this;
while (k1 > 0n || k2 > 0n) {
if (k1 & 1n)
k1p = k1p.add(d);
if (k2 & 1n)
k2p = k2p.add(d);
d = d.double();
k1 >>= 1n;
k2 >>= 1n;
}
if (k1neg)
k1p = k1p.negate();
if (k2neg)
k2p = k2p.negate();
k2p = new JacobianPoint(mod(k2p.x * CURVE.beta), k2p.y, k2p.z);
return k1p.add(k2p);
}
precomputeWindow(W) {
const windows = USE_ENDOMORPHISM ? 128 / W + 1 : 256 / W + 1;
let points = [];
let p = this;
let base = p;
for (let window = 0; window < windows; window++) {
base = p;
points.push(base);
for (let i = 1; i < 2 ** (W - 1); i++) {
base = base.add(p);
points.push(base);
}
p = base.double();
}
return points;
}
wNAF(n, affinePoint) {
if (!affinePoint && this.equals(JacobianPoint.BASE))
affinePoint = Point.BASE;
const W = (affinePoint && affinePoint._WINDOW_SIZE) || 1;
if (256 % W) {
throw new Error('Point#wNAF: Invalid precomputation window, must be power of 2');
}
let precomputes = affinePoint && pointPrecomputes.get(affinePoint);
if (!precomputes) {
precomputes = this.precomputeWindow(W);
if (affinePoint && W !== 1) {
precomputes = JacobianPoint.normalizeZ(precomputes);
pointPrecomputes.set(affinePoint, precomputes);
}
}
let p = JacobianPoint.ZERO;
let f = JacobianPoint.ZERO;
const windows = USE_ENDOMORPHISM ? 128 / W + 1 : 256 / W + 1;
const windowSize = 2 ** (W - 1);
const mask = BigInt(2 ** W - 1);
const maxNumber = 2 ** W;
const shiftBy = BigInt(W);
for (let window = 0; window < windows; window++) {
const offset = window * windowSize;
let wbits = Number(n & mask);
n >>= shiftBy;
if (wbits > windowSize) {
wbits -= maxNumber;
n += 1n;
}
if (wbits === 0) {
f = f.add(window % 2 ? precomputes[offset].negate() : precomputes[offset]);
}
else {
const cached = precomputes[offset + Math.abs(wbits) - 1];
p = p.add(wbits < 0 ? cached.negate() : cached);
}
}
return [p, f];
}
multiply(scalar, affinePoint) {
if (!isValidScalar(scalar))
throw new TypeError('Point#multiply: expected valid scalar');
let n = mod(BigInt(scalar), CURVE.n);
let point;
let fake;
if (USE_ENDOMORPHISM) {
const [k1neg, k1, k2neg, k2] = splitScalarEndo(n);
let k1p, k2p, f1p, f2p;
[k1p, f1p] = this.wNAF(k1, affinePoint);
[k2p, f2p] = this.wNAF(k2, affinePoint);
if (k1neg)
k1p = k1p.negate();
if (k2neg)
k2p = k2p.negate();
k2p = new JacobianPoint(mod(k2p.x * CURVE.beta), k2p.y, k2p.z);
[point, fake] = [k1p.add(k2p), f1p.add(f2p)];
}
else {
[point, fake] = this.wNAF(n, affinePoint);
}
return JacobianPoint.normalizeZ([point, fake])[0];
}
toAffine(invZ = invert(this.z)) {
const invZ2 = invZ ** 2n;
const x = mod(this.x * invZ2);
const y = mod(this.y * invZ2 * invZ);
return new Point(x, y);
}
}
JacobianPoint.BASE = new JacobianPoint(CURVE.Gx, CURVE.Gy, 1n);
JacobianPoint.ZERO = new JacobianPoint(0n, 1n, 0n);
const pointPrecomputes = new WeakMap();
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
_setWindowSize(windowSize) {
this._WINDOW_SIZE = windowSize;
pointPrecomputes.delete(this);
}
static fromCompressedHex(bytes) {
const isShort = bytes.length === 32;
const x = bytesToNumber(isShort ? bytes : bytes.slice(1));
const y2 = weistrass(x);
let y = sqrtMod(y2);
const isYOdd = (y & 1n) === 1n;
if (isShort) {
if (isYOdd)
y = mod(-y);
}
else {
const isFirstByteOdd = (bytes[0] & 1) === 1;
if (isFirstByteOdd !== isYOdd)
y = mod(-y);
}
const point = new Point(x, y);
point.assertValidity();
return point;
}
static fromUncompressedHex(bytes) {
const x = bytesToNumber(bytes.slice(1, 33));
const y = bytesToNumber(bytes.slice(33));
const point = new Point(x, y);
point.assertValidity();
return point;
}
static fromHex(hex) {
const bytes = ensureBytes(hex);
const header = bytes[0];
if (bytes.length === 32 || (bytes.length === 33 && (header === 0x02 || header === 0x03))) {
return this.fromCompressedHex(bytes);
}
if (bytes.length === 65 && header === 0x04)
return this.fromUncompressedHex(bytes);
throw new Error(`Point.fromHex: received invalid point. Expected 32-33 compressed bytes or 65 uncompressed bytes, not ${bytes.length}`);
}
static fromPrivateKey(privateKey) {
return Point.BASE.multiply(normalizePrivateKey(privateKey));
}
static fromSignature(msgHash, signature, recovery) {
let h = msgHash instanceof Uint8Array ? bytesToNumber(msgHash) : hexToNumber(msgHash);
const sig = normalizeSignature(signature);
const { r, s } = sig;
if (recovery !== 0 && recovery !== 1) {
throw new Error('Cannot recover signature: invalid yParity bit');
}
const prefix = 2 + (recovery & 1);
const P_ = Point.fromHex(`0${prefix}${pad64(r)}`);
const sP = JacobianPoint.fromAffine(P_).multiplyUnsafe(s);
const hG = JacobianPoint.BASE.multiply(h);
const rinv = invert(r, CURVE.n);
const Q = sP.subtract(hG).multiplyUnsafe(rinv);
const point = Q.toAffine();
point.assertValidity();
return point;
}
toRawBytes(isCompressed = false) {
return hexToBytes(this.toHex(isCompressed));
}
toHex(isCompressed = false) {
const x = pad64(this.x);
if (isCompressed) {
return `${this.y & 1n ? '03' : '02'}${x}`;
}
else {
return `04${x}${pad64(this.y)}`;
}
}
toHexX() {
return this.toHex(true).slice(2);
}
toRawX() {
return this.toRawBytes(true).slice(1);
}
assertValidity() {
const msg = 'Point is not on elliptic curve';
const { P } = CURVE;
const { x, y } = this;
if (x === 0n || y === 0n || x >= P || y >= P)
throw new Error(msg);
const left = mod(y * y);
const right = weistrass(x);
if ((left - right) % P !== 0n)
throw new Error(msg);
}
equals(other) {
return this.x === other.x && this.y === other.y;
}
negate() {
return new Point(this.x, mod(-this.y));
}
double() {
return JacobianPoint.fromAffine(this).double().toAffine();
}
add(other) {
return JacobianPoint.fromAffine(this).add(JacobianPoint.fromAffine(other)).toAffine();
}
subtract(other) {
return this.add(other.negate());
}
multiply(scalar) {
return JacobianPoint.fromAffine(this).multiply(scalar, this).toAffine();
}
}
exports.Point = Point;
Point.BASE = new Point(CURVE.Gx, CURVE.Gy);
Point.ZERO = new Point(0n, 0n);
function sliceDer(s) {
return Number.parseInt(s[0], 16) >= 8 ? '00' + s : s;
}
class Signature {
constructor(r, s) {
this.r = r;
this.s = s;
}
static fromCompact(hex) {
if (typeof hex !== 'string' && !(hex instanceof Uint8Array)) {
throw new TypeError(`Signature.fromCompact: Expected string or Uint8Array`);
}
const str = hex instanceof Uint8Array ? bytesToHex(hex) : hex;
if (str.length !== 128)
throw new Error('Signature.fromCompact: Expected 64-byte hex');
const sig = new Signature(hexToNumber(str.slice(0, 64)), hexToNumber(str.slice(64, 128)));
sig.assertValidity();
return sig;
}
static fromDER(hex) {
const fn = 'Signature.fromDER';
if (typeof hex !== 'string' && !(hex instanceof Uint8Array)) {
throw new TypeError(`${fn}: Expected string or Uint8Array`);
}
const str = hex instanceof Uint8Array ? bytesToHex(hex) : hex;
const length = parseByte(str.slice(2, 4));
if (str.slice(0, 2) !== '30' || length !== str.length - 4 || str.slice(4, 6) !== '02') {
throw new Error(`${fn}: Invalid signature ${str}`);
}
const rLen = parseByte(str.slice(6, 8));
const rEnd = 8 + rLen;
const rr = str.slice(8, rEnd);
if (rr.startsWith('00') && parseByte(rr.slice(2, 4)) <= 0x7f) {
throw new Error(`${fn}: Invalid r with trailing length`);
}
const r = hexToNumber(rr);
const separator = str.slice(rEnd, rEnd + 2);
if (separator !== '02') {
throw new Error(`${fn}: Invalid r-s separator`);
}
const sLen = parseByte(str.slice(rEnd + 2, rEnd + 4));
const diff = length - sLen - rLen - 10;
if (diff > 0 || diff === -4) {
throw new Error(`${fn}: Invalid total length`);
}
if (sLen > length - rLen - 4) {
throw new Error(`${fn}: Invalid s`);
}
const sStart = rEnd + 4;
const ss = str.slice(sStart, sStart + sLen);
if (ss.startsWith('00') && parseByte(ss.slice(2, 4)) <= 0x7f) {
throw new Error(`${fn}: Invalid s with trailing length`);
}
const s = hexToNumber(ss);
const sig = new Signature(r, s);
sig.assertValidity();
return sig;
}
static fromHex(hex) {
return this.fromDER(hex);
}
assertValidity() {
const { r, s } = this;
if (!isWithinCurveOrder(r))
throw new Error('Invalid Signature: r must be 0 < r < n');
if (!isWithinCurveOrder(s))
throw new Error('Invalid Signature: s must be 0 < s < n');
}
toDERRawBytes(isCompressed = false) {
return hexToBytes(this.toDERHex(isCompressed));
}
toDERHex(isCompressed = false) {
const sHex = sliceDer(numberToHex(this.s));
if (isCompressed)
return sHex;
const rHex = sliceDer(numberToHex(this.r));
const rLen = numberToHex(rHex.length / 2);
const sLen = numberToHex(sHex.length / 2);
const length = numberToHex(rHex.length / 2 + sHex.length / 2 + 4);
return `30${length}02${rLen}${rHex}02${sLen}${sHex}`;
}
toRawBytes() {
return this.toDERRawBytes();
}
toHex() {
return this.toDERHex();
}
toCompactRawBytes() {
return hexToBytes(this.toCompactHex());
}
toCompactHex() {
return pad64(this.r) + pad64(this.s);
}
}
exports.Signature = Signature;
exports.SignResult = Signature;
function concatBytes(...arrays) {
if (arrays.length === 1)
return arrays[0];
const length = arrays.reduce((a, arr) => a + arr.length, 0);
const result = new Uint8Array(length);
for (let i = 0, pad = 0; i < arrays.length; i++) {
const arr = arrays[i];
result.set(arr, pad);
pad += arr.length;
}
return result;
}
function bytesToHex(uint8a) {
let hex = '';
for (let i = 0; i < uint8a.length; i++) {
hex += uint8a[i].toString(16).padStart(2, '0');
}
return hex;
}
function pad64(num) {
return num.toString(16).padStart(64, '0');
}
function pad32b(num) {
return hexToBytes(pad64(num));
}
function numberToHex(num) {
const hex = num.toString(16);
return hex.length & 1 ? `0${hex}` : hex;
}
function hexToNumber(hex) {
if (typeof hex !== 'string') {
throw new TypeError('hexToNumber: expected string, got ' + typeof hex);
}
return BigInt(`0x${hex}`);
}
function hexToBytes(hex) {
if (typeof hex !== 'string') {
throw new TypeError('hexToBytes: expected string, got ' + typeof hex);
}
if (hex.length % 2)
throw new Error('hexToBytes: received invalid unpadded hex');
const array = new Uint8Array(hex.length / 2);
for (let i = 0; i < array.length; i++) {
const j = i * 2;
array[i] = Number.parseInt(hex.slice(j, j + 2), 16);
}
return array;
}
function ensureBytes(hex) {
return hex instanceof Uint8Array ? hex : hexToBytes(hex);
}
function bytesToNumber(bytes) {
return hexToNumber(bytesToHex(bytes));
}
function parseByte(str) {
return Number.parseInt(str, 16) * 2;
}
function isValidScalar(num) {
if (typeof num === 'bigint' && num > 0n)
return true;
if (typeof num === 'number' && num > 0 && Number.isSafeInteger(num))
return true;
return false;
}
function mod(a, b = CURVE.P) {
const result = a % b;
return result >= 0 ? result : b + result;
}
function pow2(x, power) {
const { P } = CURVE;
let res = x;
while (power-- > 0n) {
res *= res;
res %= P;
}
return res;
}
function sqrtMod(x) {
const { P } = CURVE;
const b2 = (x * x * x) % P;
const b3 = (b2 * b2 * x) % P;
const b6 = (pow2(b3, 3n) * b3) % P;
const b9 = (pow2(b6, 3n) * b3) % P;
const b11 = (pow2(b9, 2n) * b2) % P;
const b22 = (pow2(b11, 11n) * b11) % P;
const b44 = (pow2(b22, 22n) * b22) % P;
const b88 = (pow2(b44, 44n) * b44) % P;
const b176 = (pow2(b88, 88n) * b88) % P;
const b220 = (pow2(b176, 44n) * b44) % P;
const b223 = (pow2(b220, 3n) * b3) % P;
const t1 = (pow2(b223, 23n) * b22) % P;
const t2 = (pow2(t1, 6n) * b2) % P;
return pow2(t2, 2n);
}
function invert(number, modulo = CURVE.P) {
if (number === 0n || modulo <= 0n) {
throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);
}
let a = mod(number, modulo);
let b = modulo;
let [x, y, u, v] = [0n, 1n, 1n, 0n];
while (a !== 0n) {
const q = b / a;
const r = b % a;
const m = x - u * q;
const n = y - v * q;
[b, a] = [a, r];
[x, y] = [u, v];
[u, v] = [m, n];
}
const gcd = b;
if (gcd !== 1n)
throw new Error('invert: does not exist');
return mod(x, modulo);
}
function invertBatch(nums, n = CURVE.P) {
const len = nums.length;
const scratch = new Array(len);
let acc = 1n;
for (let i = 0; i < len; i++) {
if (nums[i] === 0n)
continue;
scratch[i] = acc;
acc = mod(acc * nums[i], n);
}
acc = invert(acc, n);
for (let i = len - 1; i >= 0; i--) {
if (nums[i] === 0n)
continue;
const tmp = mod(acc * nums[i], n);
nums[i] = mod(acc * scratch[i], n);
acc = tmp;
}
return nums;
}
const divNearest = (a, b) => (a + b / 2n) / b;
const POW_2_128 = 2n ** 128n;
function splitScalarEndo(k) {
const { n } = CURVE;
const a1 = 0x3086d221a7d46bcde86c90e49284eb15n;
const b1 = -0xe4437ed6010e88286f547fa90abfe4c3n;
const a2 = 0x114ca50f7a8e2f3f657c1108d9d44cfd8n;
const b2 = a1;
const c1 = divNearest(b2 * k, n);
const c2 = divNearest(-b1 * k, n);
let k1 = mod(k - c1 * a1 - c2 * a2, n);
let k2 = mod(-c1 * b1 - c2 * b2, n);
const k1neg = k1 > POW_2_128;
const k2neg = k2 > POW_2_128;
if (k1neg)
k1 = n - k1;
if (k2neg)
k2 = n - k2;
if (k1 > POW_2_128 || k2 > POW_2_128)
throw new Error('splitScalarEndo: Endomorphism failed');
return [k1neg, k1, k2neg, k2];
}
function truncateHash(hash) {
if (typeof hash !== 'string')
hash = bytesToHex(hash);
let msg = hexToNumber(hash || '0');
const byteLength = hash.length / 2;
const delta = byteLength * 8 - 256;
if (delta > 0) {
msg = msg >> BigInt(delta);
}
if (msg >= CURVE.n) {
msg -= CURVE.n;
}
return msg;
}
function _abc6979(msgHash, privateKey) {
if (msgHash == null)
throw new Error(`sign: expected valid msgHash, not "${msgHash}"`);
const num = typeof msgHash === 'string' ? hexToNumber(msgHash) : bytesToNumber(msgHash);
const h1 = pad32b(num);
const h1n = bytesToNumber(h1);
const x = pad32b(privateKey);
let v = new Uint8Array(32).fill(1);
let k = new Uint8Array(32).fill(0);
const b0 = Uint8Array.from([0x00]);
const b1 = Uint8Array.from([0x01]);
return [h1, h1n, x, v, k, b0, b1];
}
async function getQRSrfc6979(msgHash, privateKey) {
const privKey = normalizePrivateKey(privateKey);
let [h1, h1n, x, v, k, b0, b1] = _abc6979(msgHash, privKey);
const hmac = exports.utils.hmacSha256;
k = await hmac(k, v, b0, x, h1);
v = await hmac(k, v);
k = await hmac(k, v, b1, x, h1);
v = await hmac(k, v);
for (let i = 0; i < 1000; i++) {
v = await hmac(k, v);
let qrs = calcQRSFromK(v, h1n, privKey);
if (qrs)
return qrs;
k = await hmac(k, v, b0);
v = await hmac(k, v);
}
throw new TypeError('secp256k1: Tried 1,000 k values for sign(), all were invalid');
}
function getQRSrfc6979Sync(msgHash, privateKey) {
const privKey = normalizePrivateKey(privateKey);
let [h1, h1n, x, v, k, b0, b1] = _abc6979(msgHash, privKey);
const hmac = exports.utils.hmacSha256Sync;
if (!hmac)
throw new Error('utils.hmacSha256Sync is undefined, you need to set it');
k = hmac(k, v, b0, x, h1);
if (k instanceof Promise)
throw new Error('To use sync sign(), ensure utils.hmacSha256 is sync');
v = hmac(k, v);
k = hmac(k, v, b1, x, h1);
v = hmac(k, v);
for (let i = 0; i < 1000; i++) {
v = hmac(k, v);
let qrs = calcQRSFromK(v, h1n, privKey);
if (qrs)
return qrs;
k = hmac(k, v, b0);
v = hmac(k, v);
}
throw new TypeError('secp256k1: Tried 1,000 k values for sign(), all were invalid');
}
function isWithinCurveOrder(num) {
return 0 < num && num < CURVE.n;
}
function calcQRSFromK(v, msg, priv) {
const k = bytesToNumber(v);
if (!isWithinCurveOrder(k))
return;
const max = CURVE.n;
const q = Point.BASE.multiply(k);
const r = mod(q.x, max);
const s = mod(invert(k, max) * (msg + r * priv), max);
if (r === 0n || s === 0n)
return;
return [q, r, s];
}
function normalizePrivateKey(key) {
let num;
if (typeof key === 'bigint') {
num = key;
}
else if (typeof key === 'number' && Number.isSafeInteger(key) && key > 0) {
num = BigInt(key);
}
else if (typeof key === 'string') {
if (key.length !== 64)
throw new Error('Expected 32 bytes of private key');
num = hexToNumber(key);
}
else if (key instanceof Uint8Array) {
if (key.length !== 32)
throw new Error('Expected 32 bytes of private key');
num = bytesToNumber(key);
}
else {
throw new TypeError('Expected valid private key');
}
if (!isWithinCurveOrder(num))
throw new Error('Expected private key: 0 < key < n');
return num;
}
function normalizePublicKey(publicKey) {
if (publicKey instanceof Point) {
publicKey.assertValidity();
return publicKey;
}
else {
return Point.fromHex(publicKey);
}
}
function normalizeSignature(signature) {
if (signature instanceof Signature) {
signature.assertValidity();
return signature;
}
else {
return Signature.fromDER(signature);
}
}
function getPublicKey(privateKey, isCompressed = false) {
const point = Point.fromPrivateKey(privateKey);
if (typeof privateKey === 'string') {
return point.toHex(isCompressed);
}
return point.toRawBytes(isCompressed);
}
exports.getPublicKey = getPublicKey;
function recoverPublicKey(msgHash, signature, recovery) {
const point = Point.fromSignature(msgHash, signature, recovery);
return typeof msgHash === 'string' ? point.toHex() : point.toRawBytes();
}
exports.recoverPublicKey = recoverPublicKey;
function isPub(item) {
const arr = item instanceof Uint8Array;
const str = typeof item === 'string';
const len = (arr || str) && item.length;
if (arr)
return len === 33 || len === 65;
if (str)
return len === 66 || len === 130;
if (item instanceof Point)
return true;
return false;
}
function getSharedSecret(privateA, publicB, isCompressed = false) {
if (isPub(privateA))
throw new TypeError('getSharedSecret: first arg must be private key');
if (!isPub(publicB))
throw new TypeError('getSharedSecret: second arg must be public key');
const b = normalizePublicKey(publicB);
b.assertValidity();
const shared = b.multiply(normalizePrivateKey(privateA));
return typeof privateA === 'string'
? shared.toHex(isCompressed)
: shared.toRawBytes(isCompressed);
}
exports.getSharedSecret = getSharedSecret;
function QRSToSig(qrs, opts, str = false) {
const [q, r, s] = qrs;
let { canonical, der, recovered } = opts;
let recovery = (q.x === r ? 0 : 2) | Number(q.y & 1n);
let adjustedS = s;
const HIGH_NUMBER = CURVE.n >> 1n;
if (s > HIGH_NUMBER && canonical) {
adjustedS = CURVE.n - s;
recovery ^= 1;
}
const sig = new Signature(r, adjustedS);
sig.assertValidity();
const hex = der === false ? sig.toCompactHex() : sig.toDERHex();
const hashed = str ? hex : hexToBytes(hex);
return recovered ? [hashed, recovery] : hashed;
}
async function sign(msgHash, privKey, opts = {}) {
return QRSToSig(await getQRSrfc6979(msgHash, privKey), opts, typeof msgHash === 'string');
}
exports.sign = sign;
function signSync(msgHash, privKey, opts = {}) {
return QRSToSig(getQRSrfc6979Sync(msgHash, privKey), opts, typeof msgHash === 'string');
}
exports.signSync = signSync;
function verify(signature, msgHash, publicKey) {
const { n } = CURVE;
let sig;
try {
sig = normalizeSignature(signature);
}
catch (error) {
return false;
}
const { r, s } = sig;
const h = truncateHash(msgHash);
if (h === 0n)
return false;
const pubKey = JacobianPoint.fromAffine(normalizePublicKey(publicKey));
const s1 = invert(s, n);
const u1 = mod(h * s1, n);
const u2 = mod(r * s1, n);
const Ghs1 = JacobianPoint.BASE.multiply(u1);
const Prs1 = pubKey.multiplyUnsafe(u2);
const R = Ghs1.add(Prs1).toAffine();
const v = mod(R.x, n);
return v === r;
}
exports.verify = verify;
async function taggedHash(tag, ...messages) {
const tagB = new Uint8Array(tag.split('').map((c) => c.charCodeAt(0)));
const tagH = await exports.utils.sha256(tagB);
const h = await exports.utils.sha256(concatBytes(tagH, tagH, ...messages));
return bytesToNumber(h);
}
async function createChallenge(x, P, message) {
const rx = pad32b(x);
const t = await taggedHash('BIP0340/challenge', rx, P.toRawX(), message);
return mod(t, CURVE.n);
}
function hasEvenY(point) {
return mod(point.y, 2n) === 0n;
}
class SchnorrSignature {
constructor(r, s) {
this.r = r;
this.s = s;
if (r <= 0n || s <= 0n || r >= CURVE.P || s >= CURVE.n)
throw new Error('Invalid signature');
}
static fromHex(hex) {
const bytes = ensureBytes(hex);
if (bytes.length !== 64) {
throw new TypeError(`SchnorrSignature.fromHex: expected 64 bytes, not ${bytes.length}`);
}
const r = bytesToNumber(bytes.slice(0, 32));
const s = bytesToNumber(bytes.slice(32));
return new SchnorrSignature(r, s);
}
toHex() {
return pad64(this.r) + pad64(this.s);
}
toRawBytes() {
return hexToBytes(this.toHex());
}
}
function schnorrGetPublicKey(privateKey) {
const P = Point.fromPrivateKey(privateKey);
return typeof privateKey === 'string' ? P.toHexX() : P.toRawX();
}
async function schnorrSign(msgHash, privateKey, auxRand = exports.utils.randomBytes()) {
if (msgHash == null)
throw new TypeError(`sign: Expected valid message, not "${msgHash}"`);
if (!privateKey)
privateKey = 0n;
const { n } = CURVE;
const m = ensureBytes(msgHash);
const d0 = normalizePrivateKey(privateKey);
const rand = ensureBytes(auxRand);
if (rand.length !== 32)
throw new TypeError('sign: Expected 32 bytes of aux randomness');
const P = Point.fromPrivateKey(d0);
const d = hasEvenY(P) ? d0 : n - d0;
const t0h = await taggedHash('BIP0340/aux', rand);
const t = d ^ t0h;
const k0h = await taggedHash('BIP0340/nonce', pad32b(t), P.toRawX(), m);
const k0 = mod(k0h, n);
if (k0 === 0n)
throw new Error('sign: Creation of signature failed. k is zero');
const R = Point.fromPrivateKey(k0);
const k = hasEvenY(R) ? k0 : n - k0;
const e = await createChallenge(R.x, P, m);
const sig = new SchnorrSignature(R.x, mod(k + e * d, n));
const isValid = await schnorrVerify(sig.toRawBytes(), m, P.toRawX());
if (!isValid)
throw new Error('sign: Invalid signature produced');
return typeof msgHash === 'string' ? sig.toHex() : sig.toRawBytes();
}
async function schnorrVerify(signature, msgHash, publicKey) {
const sig = signature instanceof SchnorrSignature ? signature : SchnorrSignature.fromHex(signature);
const m = typeof msgHash === 'string' ? hexToBytes(msgHash) : msgHash;
const P = normalizePublicKey(publicKey);
const e = await createChallenge(sig.r, P, m);
const sG = Point.fromPrivateKey(sig.s);
const eP = P.multiply(e);
const R = sG.subtract(eP);
if (R.equals(Point.BASE) || !hasEvenY(R) || R.x !== sig.r)
return false;
return true;
}
exports.schnorr = {
Signature: SchnorrSignature,
getPublicKey: schnorrGetPublicKey,
sign: schnorrSign,
verify: schnorrVerify,
};
Point.BASE._setWindowSize(8);
const crypto = (() => {
const webCrypto = typeof self === 'object' && 'crypto' in self ? self.crypto : undefined;
const nodeRequire = typeof module !== 'undefined' && typeof require === 'function';
return {
node: nodeRequire && !webCrypto ? require('crypto') : undefined,
web: webCrypto,
};
})();
exports.utils = {
isValidPrivateKey(privateKey) {
try {
normalizePrivateKey(privateKey);
return true;
}
catch (error) {
return false;
}
},
randomBytes: (bytesLength = 32) => {
if (crypto.web) {
return crypto.web.getRandomValues(new Uint8Array(bytesLength));
}
else if (crypto.node) {
const { randomBytes } = crypto.node;
return new Uint8Array(randomBytes(bytesLength).buffer);
}
else {
throw new Error("The environment doesn't have randomBytes function");
}
},
randomPrivateKey: () => {
let i = 8;
while (i--) {
const b32 = exports.utils.randomBytes(32);
const num = bytesToNumber(b32);
if (isWithinCurveOrder(num) && num !== 1n)
return b32;
}
throw new Error('Valid private key was not found in 8 iterations. PRNG is broken');
},
sha256: async (message) => {
if (crypto.web) {
const buffer = await crypto.web.subtle.digest('SHA-256', message.buffer);
return new Uint8Array(buffer);
}
else if (crypto.node) {
const { createHash } = crypto.node;
return Uint8Array.from(createHash('sha256').update(message).digest());
}
else {
throw new Error("The environment doesn't have sha256 function");
}
},
hmacSha256: async (key, ...messages) => {
if (crypto.web) {
const ckey = await crypto.web.subtle.importKey('raw', key, { name: 'HMAC', hash: { name: 'SHA-256' } }, false, ['sign']);
const message = concatBytes(...messages);
const buffer = await crypto.web.subtle.sign('HMAC', ckey, message);
return new Uint8Array(buffer);
}
else if (crypto.node) {
const { createHmac } = crypto.node;
const hash = createHmac('sha256', key);
for (let message of messages) {
hash.update(message);
}
return Uint8Array.from(hash.digest());
}
else {
throw new Error("The environment doesn't have hmac-sha256 function");
}
},
sha256Sync: undefined,
hmacSha256Sync: undefined,
precompute(windowSize = 8, point = Point.BASE) {
const cached = point === Point.BASE ? point : new Point(point.x, point.y);
cached._setWindowSize(windowSize);
cached.multiply(3n);
return cached;
},
};
},{"crypto":1}]},{},[2])(2)
});