-
Notifications
You must be signed in to change notification settings - Fork 0
/
tap_combined_final.js
8416 lines (8301 loc) · 340 KB
/
tap_combined_final.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
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/******
*
START OF BASE SECTION
*
*
******/
/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */
var base = {};
var taproot = {};
var secp = {};
var hashmini = {};
(function(){
base.bytes = base.stringToBytes = base.str = base.bytesToString = base.hex = base.utf8 = base.bech32m = base.bech32 = base.base58check = base.base58xmr = base.base58xrp = base.base58flickr = base.base58 = base.base64url = base.base64 = base.base32crockford = base.base32hex = base.base32 = base.base16 = base.utils = base.assertNumber = void 0;
// Utilities
function assertNumber(n) {
if (!Number.isSafeInteger(n))
throw new Error("Wrong integer: ".concat(n));
}
base.assertNumber = assertNumber;
function chain() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
// Wrap call in closure so JIT can inline calls
var wrap = function (a, b) { return function (c) { return a(b(c)); }; };
// Construct chain of args[-1].encode(args[-2].encode([...]))
var encode = Array.from(args)
.reverse()
.reduce(function (acc, i) { return (acc ? wrap(acc, i.encode) : i.encode); }, undefined);
// Construct chain of args[0].decode(args[1].decode(...))
var decode = args.reduce(function (acc, i) { return (acc ? wrap(acc, i.decode) : i.decode); }, undefined);
return { encode: encode, decode: decode };
}
// Encodes integer radix representation to array of strings using alphabet and back
function alphabet(alphabet) {
return {
encode: function (digits) {
if (!Array.isArray(digits) || (digits.length && typeof digits[0] !== 'number'))
throw new Error('alphabet.encode input should be an array of numbers');
return digits.map(function (i) {
assertNumber(i);
if (i < 0 || i >= alphabet.length)
throw new Error("Digit index outside alphabet: ".concat(i, " (alphabet: ").concat(alphabet.length, ")"));
return alphabet[i];
});
},
decode: function (input) {
if (!Array.isArray(input) || (input.length && typeof input[0] !== 'string'))
throw new Error('alphabet.decode input should be array of strings');
return input.map(function (letter) {
if (typeof letter !== 'string')
throw new Error("alphabet.decode: not string element=".concat(letter));
var index = alphabet.indexOf(letter);
if (index === -1)
throw new Error("Unknown letter: \"".concat(letter, "\". Allowed: ").concat(alphabet));
return index;
});
},
};
}
function join(separator) {
if (separator === void 0) { separator = ''; }
if (typeof separator !== 'string')
throw new Error('join separator should be string');
return {
encode: function (from) {
if (!Array.isArray(from) || (from.length && typeof from[0] !== 'string'))
throw new Error('join.encode input should be array of strings');
for (var _i = 0, from_1 = from; _i < from_1.length; _i++) {
var i = from_1[_i];
if (typeof i !== 'string')
throw new Error("join.encode: non-string input=".concat(i));
}
return from.join(separator);
},
decode: function (to) {
if (typeof to !== 'string')
throw new Error('join.decode input should be string');
return to.split(separator);
},
};
}
// Pad strings array so it has integer number of bits
function padding(bits, chr) {
if (chr === void 0) { chr = '='; }
assertNumber(bits);
if (typeof chr !== 'string')
throw new Error('padding chr should be string');
return {
encode: function (data) {
if (!Array.isArray(data) || (data.length && typeof data[0] !== 'string'))
throw new Error('padding.encode input should be array of strings');
for (var _i = 0, data_1 = data; _i < data_1.length; _i++) {
var i = data_1[_i];
if (typeof i !== 'string')
throw new Error("padding.encode: non-string input=".concat(i));
}
while ((data.length * bits) % 8)
data.push(chr);
return data;
},
decode: function (input) {
if (!Array.isArray(input) || (input.length && typeof input[0] !== 'string'))
throw new Error('padding.encode input should be array of strings');
for (var _i = 0, input_1 = input; _i < input_1.length; _i++) {
var i = input_1[_i];
if (typeof i !== 'string')
throw new Error("padding.decode: non-string input=".concat(i));
}
var end = input.length;
if ((end * bits) % 8)
throw new Error('Invalid padding: string should have whole number of bytes');
for (; end > 0 && input[end - 1] === chr; end--) {
if (!(((end - 1) * bits) % 8))
throw new Error('Invalid padding: string has too much padding');
}
return input.slice(0, end);
},
};
}
function normalize(fn) {
if (typeof fn !== 'function')
throw new Error('normalize fn should be function');
return { encode: function (from) { return from; }, decode: function (to) { return fn(to); } };
}
// NOTE: it has quadratic time complexity
function convertRadix(data, from, to) {
// base 1 is impossible
if (from < 2)
throw new Error("convertRadix: wrong from=".concat(from, ", base cannot be less than 2"));
if (to < 2)
throw new Error("convertRadix: wrong to=".concat(to, ", base cannot be less than 2"));
if (!Array.isArray(data))
throw new Error('convertRadix: data should be array');
if (!data.length)
return [];
var pos = 0;
var res = [];
var digits = Array.from(data);
digits.forEach(function (d) {
assertNumber(d);
if (d < 0 || d >= from)
throw new Error("Wrong integer: ".concat(d));
});
while (true) {
var carry = 0;
var done = true;
for (var i = pos; i < digits.length; i++) {
var digit = digits[i];
var digitBase = from * carry + digit;
if (!Number.isSafeInteger(digitBase) ||
(from * carry) / from !== carry ||
digitBase - digit !== from * carry) {
throw new Error('convertRadix: carry overflow');
}
carry = digitBase % to;
digits[i] = Math.floor(digitBase / to);
if (!Number.isSafeInteger(digits[i]) || digits[i] * to + carry !== digitBase)
throw new Error('convertRadix: carry overflow');
if (!done)
continue;
else if (!digits[i])
pos = i;
else
done = false;
}
res.push(carry);
if (done)
break;
}
for (var i = 0; i < data.length - 1 && data[i] === 0; i++)
res.push(0);
return res.reverse();
}
var gcd = function (a, b) { return (!b ? a : gcd(b, a % b)); };
var radix2carry = function (from, to) { return from + (to - gcd(from, to)); };
// BigInt is 5x slower
function convertRadix2(data, from, to, padding) {
if (!Array.isArray(data))
throw new Error('convertRadix2: data should be array');
if (from <= 0 || from > 32)
throw new Error("convertRadix2: wrong from=".concat(from));
if (to <= 0 || to > 32)
throw new Error("convertRadix2: wrong to=".concat(to));
if (radix2carry(from, to) > 32) {
throw new Error("convertRadix2: carry overflow from=".concat(from, " to=").concat(to, " carryBits=").concat(radix2carry(from, to)));
}
var carry = 0;
var pos = 0; // bitwise position in current element
var mask = Math.pow(2, to) - 1;
var res = [];
for (var _i = 0, data_2 = data; _i < data_2.length; _i++) {
var n = data_2[_i];
assertNumber(n);
if (n >= Math.pow(2, from))
throw new Error("convertRadix2: invalid data word=".concat(n, " from=").concat(from));
carry = (carry << from) | n;
if (pos + from > 32)
throw new Error("convertRadix2: carry overflow pos=".concat(pos, " from=").concat(from));
pos += from;
for (; pos >= to; pos -= to)
res.push(((carry >> (pos - to)) & mask) >>> 0);
carry &= Math.pow(2, pos) - 1; // clean carry, otherwise it will cause overflow
}
carry = (carry << (to - pos)) & mask;
if (!padding && pos >= from)
throw new Error('Excess padding');
if (!padding && carry)
throw new Error("Non-zero padding: ".concat(carry));
if (padding && pos > 0)
res.push(carry >>> 0);
return res;
}
function radix(num) {
assertNumber(num);
return {
encode: function (bytes) {
if (!(bytes instanceof Uint8Array))
throw new Error('radix.encode input should be Uint8Array');
return convertRadix(Array.from(bytes), Math.pow(2, 8), num);
},
decode: function (digits) {
if (!Array.isArray(digits) || (digits.length && typeof digits[0] !== 'number'))
throw new Error('radix.decode input should be array of strings');
return Uint8Array.from(convertRadix(digits, num, Math.pow(2, 8)));
},
};
}
// If both bases are power of same number (like `2**8 <-> 2**64`),
// there is a linear algorithm. For now we have implementation for power-of-two bases only
function radix2(bits, revPadding) {
if (revPadding === void 0) { revPadding = false; }
assertNumber(bits);
if (bits <= 0 || bits > 32)
throw new Error('radix2: bits should be in (0..32]');
if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32)
throw new Error('radix2: carry overflow');
return {
encode: function (bytes) {
if (!(bytes instanceof Uint8Array))
throw new Error('radix2.encode input should be Uint8Array');
return convertRadix2(Array.from(bytes), 8, bits, !revPadding);
},
decode: function (digits) {
if (!Array.isArray(digits) || (digits.length && typeof digits[0] !== 'number'))
throw new Error('radix2.decode input should be array of strings');
return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding));
},
};
}
function unsafeWrapper(fn) {
if (typeof fn !== 'function')
throw new Error('unsafeWrapper fn should be function');
return function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
try {
return fn.apply(null, args);
}
catch (e) { }
};
}
function checksum(len, fn) {
assertNumber(len);
if (typeof fn !== 'function')
throw new Error('checksum fn should be function');
return {
encode: function (data) {
if (!(data instanceof Uint8Array))
throw new Error('checksum.encode: input should be Uint8Array');
var checksum = fn(data).slice(0, len);
var res = new Uint8Array(data.length + len);
res.set(data);
res.set(checksum, data.length);
return res;
},
decode: function (data) {
if (!(data instanceof Uint8Array))
throw new Error('checksum.decode: input should be Uint8Array');
var payload = data.slice(0, -len);
var newChecksum = fn(payload).slice(0, len);
var oldChecksum = data.slice(-len);
for (var i = 0; i < len; i++)
if (newChecksum[i] !== oldChecksum[i])
throw new Error('Invalid checksum');
return payload;
},
};
}
base.utils = { alphabet: alphabet, chain: chain, checksum: checksum, radix: radix, radix2: radix2, join: join, padding: padding };
// RFC 4648 aka RFC 3548
// ---------------------
base.base16 = chain(radix2(4), alphabet('0123456789ABCDEF'), join(''));
base.base32 = chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), padding(5), join(''));
base.base32hex = chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'), padding(5), join(''));
base.base32crockford = chain(radix2(5), alphabet('0123456789ABCDEFGHJKMNPQRSTVWXYZ'), join(''), normalize(function (s) { return s.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1'); }));
base.base64 = chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'), padding(6), join(''));
base.base64url = chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'), padding(6), join(''));
// base58 code
// -----------
var genBase58 = function (abc) { return chain(radix(58), alphabet(abc), join('')); };
base.base58 = genBase58('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz');
base.base58flickr = genBase58('123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ');
base.base58xrp = genBase58('rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz');
// xmr ver is done in 8-byte blocks (which equals 11 chars in decoding). Last (non-full) block padded with '1' to size in XMR_BLOCK_LEN.
// Block encoding significantly reduces quadratic complexity of base58.
// Data len (index) -> encoded block len
var XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11];
base.base58xmr = {
encode: function (data) {
var res = '';
for (var i = 0; i < data.length; i += 8) {
var block = data.subarray(i, i + 8);
res += base.base58.encode(block).padStart(XMR_BLOCK_LEN[block.length], '1');
}
return res;
},
decode: function (str) {
var res = [];
for (var i = 0; i < str.length; i += 11) {
var slice = str.slice(i, i + 11);
var blockLen = XMR_BLOCK_LEN.indexOf(slice.length);
var block = base.base58.decode(slice);
for (var j = 0; j < block.length - blockLen; j++) {
if (block[j] !== 0)
throw new Error('base58xmr: wrong padding');
}
res = res.concat(Array.from(block.slice(block.length - blockLen)));
}
return Uint8Array.from(res);
},
};
var base58check = function (sha256) {
return chain(checksum(4, function (data) { return sha256(sha256(data)); }), base.base58);
};
base.base58check = base58check;
var BECH_ALPHABET = chain(alphabet('qpzry9x8gf2tvdw0s3jn54khce6mua7l'), join(''));
var POLYMOD_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];
function bech32Polymod(pre) {
var b = pre >> 25;
var chk = (pre & 0x1ffffff) << 5;
for (var i = 0; i < POLYMOD_GENERATORS.length; i++) {
if (((b >> i) & 1) === 1)
chk ^= POLYMOD_GENERATORS[i];
}
return chk;
}
function bechChecksum(prefix, words, encodingConst) {
if (encodingConst === void 0) { encodingConst = 1; }
var len = prefix.length;
var chk = 1;
for (var i = 0; i < len; i++) {
var c = prefix.charCodeAt(i);
if (c < 33 || c > 126)
throw new Error("Invalid prefix (".concat(prefix, ")"));
chk = bech32Polymod(chk) ^ (c >> 5);
}
chk = bech32Polymod(chk);
for (var i = 0; i < len; i++)
chk = bech32Polymod(chk) ^ (prefix.charCodeAt(i) & 0x1f);
for (var _i = 0, words_1 = words; _i < words_1.length; _i++) {
var v = words_1[_i];
chk = bech32Polymod(chk) ^ v;
}
for (var i = 0; i < 6; i++)
chk = bech32Polymod(chk);
chk ^= encodingConst;
return BECH_ALPHABET.encode(convertRadix2([chk % Math.pow(2, 30)], 30, 5, false));
}
function genBech32(encoding) {
var ENCODING_CONST = encoding === 'bech32' ? 1 : 0x2bc830a3;
var _words = radix2(5);
var fromWords = _words.decode;
var toWords = _words.encode;
var fromWordsUnsafe = unsafeWrapper(fromWords);
function encode(prefix, words, limit) {
if (limit === void 0) { limit = 90; }
if (typeof prefix !== 'string')
throw new Error("bech32.encode prefix should be string, not ".concat(typeof prefix));
if (!Array.isArray(words) || (words.length && typeof words[0] !== 'number'))
throw new Error("bech32.encode words should be array of numbers, not ".concat(typeof words));
var actualLength = prefix.length + 7 + words.length;
if (limit !== false && actualLength > limit)
throw new TypeError("Length ".concat(actualLength, " exceeds limit ").concat(limit));
prefix = prefix.toLowerCase();
return "".concat(prefix, "1").concat(BECH_ALPHABET.encode(words)).concat(bechChecksum(prefix, words, ENCODING_CONST));
}
function decode(str, limit) {
if (limit === void 0) { limit = 90; }
if (typeof str !== 'string')
throw new Error("bech32.decode input should be string, not ".concat(typeof str));
if (str.length < 8 || (limit !== false && str.length > limit))
throw new TypeError("Wrong string length: ".concat(str.length, " (").concat(str, "). Expected (8..").concat(limit, ")"));
// don't allow mixed case
var lowered = str.toLowerCase();
if (str !== lowered && str !== str.toUpperCase())
throw new Error("String must be lowercase or uppercase");
str = lowered;
var sepIndex = str.lastIndexOf('1');
if (sepIndex === 0 || sepIndex === -1)
throw new Error("Letter \"1\" must be present between prefix and data only");
var prefix = str.slice(0, sepIndex);
var _words = str.slice(sepIndex + 1);
if (_words.length < 6)
throw new Error('Data must be at least 6 characters long');
var words = BECH_ALPHABET.decode(_words).slice(0, -6);
var sum = bechChecksum(prefix, words, ENCODING_CONST);
if (!_words.endsWith(sum))
throw new Error("Invalid checksum in ".concat(str, ": expected \"").concat(sum, "\""));
return { prefix: prefix, words: words };
}
var decodeUnsafe = unsafeWrapper(decode);
function decodeToBytes(str) {
var _a = decode(str, false), prefix = _a.prefix, words = _a.words;
return { prefix: prefix, words: words, bytes: fromWords(words) };
}
return { encode: encode, decode: decode, decodeToBytes: decodeToBytes, decodeUnsafe: decodeUnsafe, fromWords: fromWords, fromWordsUnsafe: fromWordsUnsafe, toWords: toWords };
}
base.bech32 = genBech32('bech32');
base.bech32m = genBech32('bech32m');
base.utf8 = {
encode: function (data) { return new TextDecoder().decode(data); },
decode: function (str) { return new TextEncoder().encode(str); },
};
base.hex = chain(radix2(4), alphabet('0123456789abcdef'), join(''), normalize(function (s) {
if (typeof s !== 'string' || s.length % 2)
throw new TypeError("hex.decode: expected string, got ".concat(typeof s, " with length ").concat(s.length));
return s.toLowerCase();
}));
// prettier-ignore
var CODERS = {
utf8: base.utf8,
hex: base.hex,
base16: base.base16,
base32: base.base32,
base64: base.base64,
base64url: base.base64url,
base58: base.base58,
base58xmr: base.base58xmr
};
var coderTypeError = "Invalid encoding type. Available types: ".concat(Object.keys(CODERS).join(', '));
var bytesToString = function (type, bytes) {
if (typeof type !== 'string' || !CODERS.hasOwnProperty(type))
throw new TypeError(coderTypeError);
if (!(bytes instanceof Uint8Array))
throw new TypeError('bytesToString() expects Uint8Array');
return CODERS[type].encode(bytes);
};
base.bytesToString = bytesToString;
base.str = base.bytesToString; // as in python, but for bytes only
var stringToBytes = function (type, str) {
if (!CODERS.hasOwnProperty(type))
throw new TypeError(coderTypeError);
if (typeof str !== 'string')
throw new TypeError('stringToBytes() expects string');
return CODERS[type].decode(str);
};
base.stringToBytes = stringToBytes;
base.bytes = base.stringToBytes;
/****
*
*
START OF SECP AND SCHNORR SECTION
*
*
*****/
const _nodeResolve_empty = {};
const nodeCrypto = /*#__PURE__*/Object.freeze({
__proto__: null,
'default': _nodeResolve_empty
});
/*! noble-secp256k1 - MIT License (c) 2019 Paul Miller (paulmillr.com) */
var _0n = BigInt(0);
var _1n = BigInt(1);
var _2n = BigInt(2);
var _3n = BigInt(3);
var _8n = BigInt(8);
const CURVE = Object.freeze({
a: _0n,
b: BigInt(7),
P: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'),
n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'),
h: _1n,
Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),
Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),
beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),
});
function weistrass(x) {
const { a, b } = CURVE;
const x2 = mod(x * x);
const x3 = mod(x2 * x);
return mod(x3 + a * x + b);
}
const USE_ENDOMORPHISM = CURVE.a === _0n;
class ShaError extends Error {
constructor(message) {
super(message);
}
}
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) {
if (!(other instanceof JacobianPoint))
throw new TypeError('JacobianPoint expected');
const { x: X1, y: Y1, z: Z1 } = this;
const { x: X2, y: Y2, z: Z2 } = other;
const Z1Z1 = mod(Z1 * Z1);
const Z2Z2 = mod(Z2 * Z2);
const U1 = mod(X1 * Z2Z2);
const U2 = mod(X2 * Z1Z1);
const S1 = mod(mod(Y1 * Z2) * Z2Z2);
const S2 = mod(mod(Y2 * Z1) * Z1Z1);
return U1 === U2 && S1 === S2;
}
negate() {
return new JacobianPoint(this.x, mod(-this.y), this.z);
}
double() {
const { x: X1, y: Y1, z: Z1 } = this;
const A = mod(X1 * X1);
const B = mod(Y1 * Y1);
const C = mod(B * B);
const x1b = X1 + B;
const D = mod(_2n * (mod(x1b * x1b) - A - C));
const E = mod(_3n * A);
const F = mod(E * E);
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 expected');
const { x: X1, y: Y1, z: Z1 } = this;
const { x: X2, y: Y2, z: Z2 } = other;
if (X2 === _0n || Y2 === _0n)
return this;
if (X1 === _0n || Y1 === _0n)
return other;
const Z1Z1 = mod(Z1 * Z1);
const Z2Z2 = mod(Z2 * Z2);
const U1 = mod(X1 * Z2Z2);
const U2 = mod(X2 * Z1Z1);
const S1 = mod(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 * H);
const HHH = mod(H * HH);
const V = mod(U1 * HH);
const X3 = mod(r * r - 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) {
const P0 = JacobianPoint.ZERO;
if (typeof scalar === 'bigint' && scalar === _0n)
return P0;
let n = normalizeScalar(scalar);
if (n === _1n)
return this;
if (!USE_ENDOMORPHISM) {
let p = P0;
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 = P0;
let k2p = P0;
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;
const 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 = 1 + (USE_ENDOMORPHISM ? 128 / W : 256 / W);
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) {
let pr = precomputes[offset];
if (window % 2)
pr = pr.negate();
f = f.add(pr);
}
else {
let cached = precomputes[offset + Math.abs(wbits) - 1];
if (wbits < 0)
cached = cached.negate();
p = p.add(cached);
}
}
return { p, f };
}
multiply(scalar, affinePoint) {
let n = normalizeScalar(scalar);
let point;
let fake;
if (USE_ENDOMORPHISM) {
const { k1neg, k1, k2neg, k2 } = splitScalarEndo(n);
let { p: k1p, f: f1p } = this.wNAF(k1, affinePoint);
let { p: k2p, f: 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 = k1p.add(k2p);
fake = f1p.add(f2p);
}
else {
const { p, f } = this.wNAF(n, affinePoint);
point = p;
fake = f;
}
return JacobianPoint.normalizeZ([point, fake])[0];
}
toAffine(invZ = invert(this.z)) {
const { x, y, z } = this;
const iz1 = invZ;
const iz2 = mod(iz1 * iz1);
const iz3 = mod(iz2 * iz1);
const ax = mod(x * iz2);
const ay = mod(y * iz3);
const zz = mod(z * iz1);
if (zz !== _1n)
throw new Error('invZ was invalid');
return new Point(ax, ay);
}
}
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);
}
hasEvenY() {
return this.y % _2n === _0n;
}
static fromCompressedHex(bytes) {
const isShort = bytes.length === 32;
const x = bytesToNumber(isShort ? bytes : bytes.subarray(1));
if (!isValidFieldElement(x))
throw new Error('Point is not on curve');
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.subarray(1, 33));
const y = bytesToNumber(bytes.subarray(33, 65));
const point = new Point(x, y);
point.assertValidity();
return point;
}
static fromHex(hex) {
const bytes = ensureBytes(hex);
const len = bytes.length;
const header = bytes[0];
if (len === 32 || (len === 33 && (header === 0x02 || header === 0x03))) {
return this.fromCompressedHex(bytes);
}
if (len === 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 ${len}`);
}
static fromPrivateKey(privateKey) {
return Point.BASE.multiply(normalizePrivateKey(privateKey));
}
static fromSignature(msgHash, signature, recovery) {
msgHash = ensureBytes(msgHash);
const h = truncateHash(msgHash);
const { r, s } = normalizeSignature(signature);
if (recovery !== 0 && recovery !== 1) {
throw new Error('Cannot recover signature: invalid recovery bit');
}
const prefix = recovery & 1 ? '03' : '02';
const R = Point.fromHex(prefix + numTo32bStr(r));
const { n } = CURVE;
const rinv = invert(r, n);
const u1 = mod(-h * rinv, n);
const u2 = mod(s * rinv, n);
const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2);
if (!Q)
throw new Error('Cannot recover signature: point at infinify');
Q.assertValidity();
return Q;
}
toRawBytes(isCompressed = false) {
return hexToBytes(this.toHex(isCompressed));
}
toHex(isCompressed = false) {
const x = numTo32bStr(this.x);
if (isCompressed) {
const prefix = this.hasEvenY() ? '02' : '03';
return `${prefix}${x}`;
}
else {
return `04${x}${numTo32bStr(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 { x, y } = this;
if (!isValidFieldElement(x) || !isValidFieldElement(y))
throw new Error(msg);
const left = mod(y * y);
const right = weistrass(x);
if (mod(left - right) !== _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();
}
multiplyAndAddUnsafe(Q, a, b) {
const P = JacobianPoint.fromAffine(this);
const aP = a === _0n || a === _1n || this !== Point.BASE ? P.multiplyUnsafe(a) : P.multiply(a);
const bQ = JacobianPoint.fromAffine(Q).multiplyUnsafe(b);
const sum = aP.add(bQ);
return sum.equals(JacobianPoint.ZERO) ? undefined : sum.toAffine();
}
}
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;
}
function parseDERInt(data) {
if (data.length < 2 || data[0] !== 0x02) {
throw new Error(`Invalid signature integer tag: ${bytesToHex(data)}`);
}
const len = data[1];
const res = data.subarray(2, len + 2);
if (!len || res.length !== len) {
throw new Error(`Invalid signature integer: wrong length`);
}
if (res[0] === 0x00 && res[1] <= 0x7f) {
throw new Error('Invalid signature integer: trailing length');
}
return { data: bytesToNumber(res), left: data.subarray(len + 2) };
}
function parseDERSignature(data) {
if (data.length < 2 || data[0] != 0x30) {
throw new Error(`Invalid signature tag: ${bytesToHex(data)}`);
}
if (data[1] !== data.length - 2) {
throw new Error('Invalid signature: incorrect length');
}
const { data: r, left: sBytes } = parseDERInt(data.subarray(2));
const { data: s, left: rBytesLeft } = parseDERInt(sBytes);
if (rBytesLeft.length) {
throw new Error(`Invalid signature: left bytes after parsing: ${bytesToHex(rBytesLeft)}`);
}
return { r, s };
}
class Signature {
constructor(r, s) {
this.r = r;
this.s = s;
this.assertValidity();
}
static fromCompact(hex) {
const arr = hex instanceof Uint8Array;
const name = 'Signature.fromCompact';
if (typeof hex !== 'string' && !arr)
throw new TypeError(`${name}: Expected string or Uint8Array`);
const str = arr ? bytesToHex(hex) : hex;
if (str.length !== 128)
throw new Error(`${name}: Expected 64-byte hex`);
return new Signature(hexToNumber(str.slice(0, 64)), hexToNumber(str.slice(64, 128)));
}
static fromDER(hex) {
const arr = hex instanceof Uint8Array;
if (typeof hex !== 'string' && !arr)
throw new TypeError(`Signature.fromDER: Expected string or Uint8Array`);
const { r, s } = parseDERSignature(arr ? hex : hexToBytes(hex));
return new Signature(r, s);
}
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');
}
hasHighS() {
const HALF = CURVE.n >> _1n;
return this.s > HALF;
}
normalizeS() {
return this.hasHighS() ? new Signature(this.r, CURVE.n - this.s) : this;
}
toDERRawBytes(isCompressed = false) {
return hexToBytes(this.toDERHex(isCompressed));
}
toDERHex(isCompressed = false) {
const sHex = sliceDER(numberToHexUnpadded(this.s));
if (isCompressed)
return sHex;
const rHex = sliceDER(numberToHexUnpadded(this.r));
const rLen = numberToHexUnpadded(rHex.length / 2);
const sLen = numberToHexUnpadded(sHex.length / 2);
const length = numberToHexUnpadded(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 numTo32bStr(this.r) + numTo32bStr(this.s);
}
}
function concatBytes(...arrays) {
if (!arrays.every((b) => b instanceof Uint8Array))
throw new Error('Uint8Array list expected');
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;
}
var hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0'));
function bytesToHex(uint8a) {
if (!(uint8a instanceof Uint8Array))
throw new Error('Expected Uint8Array');
let hex = '';
for (let i = 0; i < uint8a.length; i++) {
hex += hexes[uint8a[i]];
}
return hex;
}
secp.bytesToHex = bytesToHex
const POW_2_256 = BigInt('0x10000000000000000000000000000000000000000000000000000000000000000');
function numTo32bStr(num) {
if (typeof num !== 'bigint')
throw new Error('Expected bigint');
if (!(_0n <= num && num < POW_2_256))
throw new Error('Expected number < 2^256');
return num.toString(16).padStart(64, '0');
}
function numTo32b(num) {
const b = hexToBytes(numTo32bStr(num));
if (b.length !== 32)
throw new Error('Error: expected 32 bytes');
return b;