-
Notifications
You must be signed in to change notification settings - Fork 0
/
secp256k1.js
2199 lines (2147 loc) · 74 KB
/
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
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(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.secp256k1 = 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){
module.exports = require('@bitcoinerlab/secp256k1');
},{"@bitcoinerlab/secp256k1":2}],2:[function(require,module,exports){
'use strict';
var necc = require('@noble/secp256k1');
var hmac = require('@noble/hashes/hmac');
var sha256 = require('@noble/hashes/sha256');
function _interopNamespaceDefault(e) {
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () { return e[k]; }
});
}
});
}
n.default = e;
return Object.freeze(n);
}
var necc__namespace = /*#__PURE__*/_interopNamespaceDefault(necc);
/*
* Copyright (c) 2023 Jose-Luis Landabaso
* Distributed under the MIT software license.
*
* This file includes code from the following sources:
* * Paul Miller's @noble/secp256k1 (specifically, the privateAdd,
* privateNegate, pointAddScalar, and pointMultiply functions).
* * Some pieces from tiny-secp256k1
* (https://github.com/bitcoinjs/tiny-secp256k1)
* * It also uses code from BitGo's BitGoJS library
* (https://github.com/BitGo/BitGoJS)
*
* This package's tests are based on modified versions of tests from
* tiny-secp256k1 (https://github.com/bitcoinjs/tiny-secp256k1/tests).
*/
necc__namespace.utils.hmacSha256Sync = (key, ...msgs) =>
hmac.hmac(sha256.sha256, key, necc__namespace.utils.concatBytes(...msgs));
necc__namespace.utils.sha256Sync = (...msgs) => sha256.sha256(necc__namespace.utils.concatBytes(...msgs));
const normalizePrivateKey = necc__namespace.utils._normalizePrivateKey;
const HASH_SIZE = 32;
const TWEAK_SIZE = 32;
const BN32_N = new Uint8Array([
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
254, 186, 174, 220, 230, 175, 72, 160, 59, 191, 210, 94, 140, 208, 54, 65, 65
]);
const EXTRA_DATA_SIZE = 32;
function cmpBN32(data1, data2) {
for (let i = 0; i < 32; ++i) {
if (data1[i] !== data2[i]) {
return data1[i] < data2[i] ? -1 : 1;
}
}
return 0;
}
function isTweak(tweak) {
// Check that the tweak is a Uint8Array of the correct length
if (
!(tweak instanceof Uint8Array) ||
tweak.length !== TWEAK_SIZE ||
cmpBN32(tweak, BN32_N) >= 0
) {
return false;
}
return true;
}
function isSignature(signature) {
return (
signature instanceof Uint8Array &&
signature.length === 64 &&
cmpBN32(signature.subarray(0, 32), BN32_N) < 0 &&
cmpBN32(signature.subarray(32, 64), BN32_N) < 0
);
}
function isHash(h) {
return h instanceof Uint8Array && h.length === HASH_SIZE;
}
function isExtraData(e) {
return (
e === undefined || (e instanceof Uint8Array && e.length === EXTRA_DATA_SIZE)
);
}
function hexToNumber(hex) {
if (typeof hex !== 'string') {
throw new TypeError('hexToNumber: expected string, got ' + typeof hex);
}
return BigInt(`0x${hex}`);
}
function bytesToNumber(bytes) {
return hexToNumber(necc__namespace.utils.bytesToHex(bytes));
}
function normalizeScalar(scalar) {
let num;
if (typeof scalar === 'bigint') {
num = scalar;
} else if (
typeof scalar === 'number' &&
Number.isSafeInteger(scalar) &&
scalar >= 0
) {
num = BigInt(scalar);
} else if (typeof scalar === 'string') {
if (scalar.length !== 64)
throw new Error('Expected 32 bytes of private scalar');
num = hexToNumber(scalar);
} else if (scalar instanceof Uint8Array) {
if (scalar.length !== 32)
throw new Error('Expected 32 bytes of private scalar');
num = bytesToNumber(scalar);
} else {
throw new TypeError('Expected valid private scalar');
}
if (num < 0) throw new Error('Expected private scalar >= 0');
return num;
}
const _privateAdd = (privateKey, tweak) => {
const p = normalizePrivateKey(privateKey);
const t = normalizeScalar(tweak);
const add = necc__namespace.utils._bigintTo32Bytes(necc__namespace.utils.mod(p + t, necc__namespace.CURVE.n));
if (necc__namespace.utils.isValidPrivateKey(add)) return add;
else return null;
};
const _privateSub = (privateKey, tweak) => {
const p = normalizePrivateKey(privateKey);
const t = normalizeScalar(tweak);
const sub = necc__namespace.utils._bigintTo32Bytes(necc__namespace.utils.mod(p - t, necc__namespace.CURVE.n));
if (necc__namespace.utils.isValidPrivateKey(sub)) return sub;
else return null;
};
const _privateNegate = privateKey => {
const p = normalizePrivateKey(privateKey);
const not = necc__namespace.utils._bigintTo32Bytes(necc__namespace.CURVE.n - p);
if (necc__namespace.utils.isValidPrivateKey(not)) return not;
else return null;
};
const _pointAddScalar = (p, tweak, isCompressed) => {
const P = necc__namespace.Point.fromHex(p);
const t = normalizeScalar(tweak);
const Q = necc__namespace.Point.BASE.multiplyAndAddUnsafe(P, t, 1n);
if (!Q) throw new Error('Tweaked point at infinity');
return Q.toRawBytes(isCompressed);
};
const _pointMultiply = (p, tweak, isCompressed) => {
const P = necc__namespace.Point.fromHex(p);
const h = typeof tweak === 'string' ? tweak : necc__namespace.utils.bytesToHex(tweak);
const t = BigInt(`0x${h}`);
return P.multiply(t).toRawBytes(isCompressed);
};
function assumeCompression(compressed, p) {
if (compressed === undefined) {
return p !== undefined ? isPointCompressed(p) : true;
}
return compressed ? true : false;
}
function throwToNull(fn) {
try {
return fn();
} catch (e) {
return null;
}
}
function _isPoint(p, xOnly) {
if ((p.length === 32) !== xOnly) return false;
try {
return !!necc__namespace.Point.fromHex(p);
} catch (e) {
return false;
}
}
function isPoint(p) {
return _isPoint(p, false);
}
function isPointCompressed(p) {
const PUBLIC_KEY_COMPRESSED_SIZE = 33;
return _isPoint(p, false) && p.length === PUBLIC_KEY_COMPRESSED_SIZE;
}
function isPrivate(d) {
return necc__namespace.utils.isValidPrivateKey(d);
}
function isXOnlyPoint(p) {
return _isPoint(p, true);
}
function xOnlyPointAddTweak(p, tweak) {
if (!isXOnlyPoint(p)) {
throw new Error('Expected Point');
}
if (!isTweak(tweak)) {
throw new Error('Expected Tweak');
}
return throwToNull(() => {
const P = _pointAddScalar(p, tweak, true);
const parity = P[0] % 2 === 1 ? 1 : 0;
return { parity, xOnlyPubkey: P.slice(1) };
});
}
function xOnlyPointFromPoint(p) {
if (!isPoint(p)) {
throw new Error('Expected Point');
}
return p.slice(1, 33);
}
function pointFromScalar(sk, compressed) {
if (!isPrivate(sk)) {
throw new Error('Expected Private');
}
return throwToNull(() =>
necc__namespace.getPublicKey(sk, assumeCompression(compressed))
);
}
function xOnlyPointFromScalar(d) {
if (!isPrivate(d)) {
throw new Error('Expected Private');
}
return xOnlyPointFromPoint(pointFromScalar(d));
}
function pointCompress(p, compressed) {
if (!isPoint(p)) {
throw new Error('Expected Point');
}
return necc__namespace.Point.fromHex(p).toRawBytes(assumeCompression(compressed, p));
}
function pointMultiply(a, tweak, compressed) {
if (!isPoint(a)) {
throw new Error('Expected Point');
}
if (!isTweak(tweak)) {
throw new Error('Expected Tweak');
}
return throwToNull(() =>
_pointMultiply(a, tweak, assumeCompression(compressed, a))
);
}
function pointAdd(a, b, compressed) {
if (!isPoint(a) || !isPoint(b)) {
throw new Error('Expected Point');
}
return throwToNull(() => {
const A = necc__namespace.Point.fromHex(a);
const B = necc__namespace.Point.fromHex(b);
if (A.equals(B.negate())) {
//https://github.com/paulmillr/noble-secp256k1/issues/91
return null;
} else {
return A.add(B).toRawBytes(assumeCompression(compressed, a));
}
});
}
function pointAddScalar(p, tweak, compressed) {
if (!isPoint(p)) {
throw new Error('Expected Point');
}
if (!isTweak(tweak)) {
throw new Error('Expected Tweak');
}
return throwToNull(() =>
_pointAddScalar(p, tweak, assumeCompression(compressed, p))
);
}
function privateAdd(d, tweak) {
if (isPrivate(d) === false) {
throw new Error('Expected Private');
}
if (isTweak(tweak) === false) {
throw new Error('Expected Tweak');
}
return throwToNull(() => _privateAdd(d, tweak));
}
function privateSub(d, tweak) {
if (isPrivate(d) === false) {
throw new Error('Expected Private');
}
if (isTweak(tweak) === false) {
throw new Error('Expected Tweak');
}
return throwToNull(() => _privateSub(d, tweak));
}
function privateNegate(d) {
if (isPrivate(d) === false) {
throw new Error('Expected Private');
}
return _privateNegate(d);
}
function sign(h, d, e) {
if (!isPrivate(d)) {
throw new Error('Expected Private');
}
if (!isHash(h)) {
throw new Error('Expected Scalar');
}
if (!isExtraData(e)) {
throw new Error('Expected Extra Data (32 bytes)');
}
return necc__namespace.signSync(h, d, { der: false, extraEntropy: e });
}
function signSchnorr(h, d, e) {
if (e === undefined) {
console.warn(
`Warning: The extra data 'e' is not defined. This library defaults to a random value when 'e' is undefined, which is different from the deterministic approach in tiny-secp256k1. This might lead to discrepancies in the Schnorr signatures between the two libraries.`
);
}
if (!isPrivate(d)) {
throw new Error('Expected Private');
}
if (!isHash(h)) {
throw new Error('Expected Scalar');
}
return necc__namespace.schnorr.signSync(h, d, e);
}
function verify(h, Q, signature, strict) {
if (!isPoint(Q)) {
throw new Error('Expected Point');
}
if (!isSignature(signature)) {
throw new Error('Expected Signature');
}
if (!isHash(h)) {
throw new Error('Expected Scalar');
}
return necc__namespace.verify(signature, h, Q, { strict });
}
function verifySchnorr(h, Q, signature) {
if (!isXOnlyPoint(Q)) {
throw new Error('Expected Point');
}
if (!isSignature(signature)) {
throw new Error('Expected Signature');
}
if (!isHash(h)) {
throw new Error('Expected Scalar');
}
return necc__namespace.schnorr.verifySync(signature, h, Q);
}
exports.isPoint = isPoint;
exports.isPointCompressed = isPointCompressed;
exports.isPrivate = isPrivate;
exports.isXOnlyPoint = isXOnlyPoint;
exports.pointAdd = pointAdd;
exports.pointAddScalar = pointAddScalar;
exports.pointCompress = pointCompress;
exports.pointFromScalar = pointFromScalar;
exports.pointMultiply = pointMultiply;
exports.privateAdd = privateAdd;
exports.privateNegate = privateNegate;
exports.privateSub = privateSub;
exports.sign = sign;
exports.signSchnorr = signSchnorr;
exports.verify = verify;
exports.verifySchnorr = verifySchnorr;
exports.xOnlyPointAddTweak = xOnlyPointAddTweak;
exports.xOnlyPointFromPoint = xOnlyPointFromPoint;
exports.xOnlyPointFromScalar = xOnlyPointFromScalar;
},{"@noble/hashes/hmac":6,"@noble/hashes/sha256":7,"@noble/secp256k1":9}],3:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.output = exports.exists = exports.hash = exports.bytes = exports.bool = exports.number = void 0;
function number(n) {
if (!Number.isSafeInteger(n) || n < 0)
throw new Error(`Wrong positive integer: ${n}`);
}
exports.number = number;
function bool(b) {
if (typeof b !== 'boolean')
throw new Error(`Expected boolean, not ${b}`);
}
exports.bool = bool;
function bytes(b, ...lengths) {
if (!(b instanceof Uint8Array))
throw new Error('Expected Uint8Array');
if (lengths.length > 0 && !lengths.includes(b.length))
throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`);
}
exports.bytes = bytes;
function hash(hash) {
if (typeof hash !== 'function' || typeof hash.create !== 'function')
throw new Error('Hash should be wrapped by utils.wrapConstructor');
number(hash.outputLen);
number(hash.blockLen);
}
exports.hash = hash;
function exists(instance, checkFinished = true) {
if (instance.destroyed)
throw new Error('Hash instance has been destroyed');
if (checkFinished && instance.finished)
throw new Error('Hash#digest() has already been called');
}
exports.exists = exists;
function output(out, instance) {
bytes(out);
const min = instance.outputLen;
if (out.length < min) {
throw new Error(`digestInto() expects output buffer of length at least ${min}`);
}
}
exports.output = output;
const assert = {
number,
bool,
bytes,
hash,
exists,
output,
};
exports.default = assert;
},{}],4:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SHA2 = void 0;
const _assert_js_1 = require("./_assert.js");
const utils_js_1 = require("./utils.js");
// Polyfill for Safari 14
function setBigUint64(view, byteOffset, value, isLE) {
if (typeof view.setBigUint64 === 'function')
return view.setBigUint64(byteOffset, value, isLE);
const _32n = BigInt(32);
const _u32_max = BigInt(0xffffffff);
const wh = Number((value >> _32n) & _u32_max);
const wl = Number(value & _u32_max);
const h = isLE ? 4 : 0;
const l = isLE ? 0 : 4;
view.setUint32(byteOffset + h, wh, isLE);
view.setUint32(byteOffset + l, wl, isLE);
}
// Base SHA2 class (RFC 6234)
class SHA2 extends utils_js_1.Hash {
constructor(blockLen, outputLen, padOffset, isLE) {
super();
this.blockLen = blockLen;
this.outputLen = outputLen;
this.padOffset = padOffset;
this.isLE = isLE;
this.finished = false;
this.length = 0;
this.pos = 0;
this.destroyed = false;
this.buffer = new Uint8Array(blockLen);
this.view = (0, utils_js_1.createView)(this.buffer);
}
update(data) {
_assert_js_1.default.exists(this);
const { view, buffer, blockLen } = this;
data = (0, utils_js_1.toBytes)(data);
const len = data.length;
for (let pos = 0; pos < len;) {
const take = Math.min(blockLen - this.pos, len - pos);
// Fast path: we have at least one block in input, cast it to view and process
if (take === blockLen) {
const dataView = (0, utils_js_1.createView)(data);
for (; blockLen <= len - pos; pos += blockLen)
this.process(dataView, pos);
continue;
}
buffer.set(data.subarray(pos, pos + take), this.pos);
this.pos += take;
pos += take;
if (this.pos === blockLen) {
this.process(view, 0);
this.pos = 0;
}
}
this.length += data.length;
this.roundClean();
return this;
}
digestInto(out) {
_assert_js_1.default.exists(this);
_assert_js_1.default.output(out, this);
this.finished = true;
// Padding
// We can avoid allocation of buffer for padding completely if it
// was previously not allocated here. But it won't change performance.
const { buffer, view, blockLen, isLE } = this;
let { pos } = this;
// append the bit '1' to the message
buffer[pos++] = 0b10000000;
this.buffer.subarray(pos).fill(0);
// we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again
if (this.padOffset > blockLen - pos) {
this.process(view, 0);
pos = 0;
}
// Pad until full block byte with zeros
for (let i = pos; i < blockLen; i++)
buffer[i] = 0;
// Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that
// You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.
// So we just write lowest 64 bits of that value.
setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
this.process(view, 0);
const oview = (0, utils_js_1.createView)(out);
const len = this.outputLen;
// NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT
if (len % 4)
throw new Error('_sha2: outputLen should be aligned to 32bit');
const outLen = len / 4;
const state = this.get();
if (outLen > state.length)
throw new Error('_sha2: outputLen bigger than state');
for (let i = 0; i < outLen; i++)
oview.setUint32(4 * i, state[i], isLE);
}
digest() {
const { buffer, outputLen } = this;
this.digestInto(buffer);
const res = buffer.slice(0, outputLen);
this.destroy();
return res;
}
_cloneInto(to) {
to || (to = new this.constructor());
to.set(...this.get());
const { blockLen, buffer, length, finished, destroyed, pos } = this;
to.length = length;
to.pos = pos;
to.finished = finished;
to.destroyed = destroyed;
if (length % blockLen)
to.buffer.set(buffer);
return to;
}
}
exports.SHA2 = SHA2;
},{"./_assert.js":3,"./utils.js":8}],5:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.crypto = void 0;
exports.crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;
},{}],6:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.hmac = exports.HMAC = void 0;
const _assert_js_1 = require("./_assert.js");
const utils_js_1 = require("./utils.js");
// HMAC (RFC 2104)
class HMAC extends utils_js_1.Hash {
constructor(hash, _key) {
super();
this.finished = false;
this.destroyed = false;
_assert_js_1.default.hash(hash);
const key = (0, utils_js_1.toBytes)(_key);
this.iHash = hash.create();
if (typeof this.iHash.update !== 'function')
throw new Error('Expected instance of class which extends utils.Hash');
this.blockLen = this.iHash.blockLen;
this.outputLen = this.iHash.outputLen;
const blockLen = this.blockLen;
const pad = new Uint8Array(blockLen);
// blockLen can be bigger than outputLen
pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
for (let i = 0; i < pad.length; i++)
pad[i] ^= 0x36;
this.iHash.update(pad);
// By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone
this.oHash = hash.create();
// Undo internal XOR && apply outer XOR
for (let i = 0; i < pad.length; i++)
pad[i] ^= 0x36 ^ 0x5c;
this.oHash.update(pad);
pad.fill(0);
}
update(buf) {
_assert_js_1.default.exists(this);
this.iHash.update(buf);
return this;
}
digestInto(out) {
_assert_js_1.default.exists(this);
_assert_js_1.default.bytes(out, this.outputLen);
this.finished = true;
this.iHash.digestInto(out);
this.oHash.update(out);
this.oHash.digestInto(out);
this.destroy();
}
digest() {
const out = new Uint8Array(this.oHash.outputLen);
this.digestInto(out);
return out;
}
_cloneInto(to) {
// Create new instance without calling constructor since key already in state and we don't know it.
to || (to = Object.create(Object.getPrototypeOf(this), {}));
const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
to = to;
to.finished = finished;
to.destroyed = destroyed;
to.blockLen = blockLen;
to.outputLen = outputLen;
to.oHash = oHash._cloneInto(to.oHash);
to.iHash = iHash._cloneInto(to.iHash);
return to;
}
destroy() {
this.destroyed = true;
this.oHash.destroy();
this.iHash.destroy();
}
}
exports.HMAC = HMAC;
/**
* HMAC: RFC2104 message authentication code.
* @param hash - function that would be used e.g. sha256
* @param key - message key
* @param message - message data
*/
const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
exports.hmac = hmac;
exports.hmac.create = (hash, key) => new HMAC(hash, key);
},{"./_assert.js":3,"./utils.js":8}],7:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.sha224 = exports.sha256 = void 0;
const _sha2_js_1 = require("./_sha2.js");
const utils_js_1 = require("./utils.js");
// Choice: a ? b : c
const Chi = (a, b, c) => (a & b) ^ (~a & c);
// Majority function, true if any two inpust is true
const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c);
// Round constants:
// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)
// prettier-ignore
const SHA256_K = new Uint32Array([
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
]);
// Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):
// prettier-ignore
const IV = new Uint32Array([
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
]);
// Temporary buffer, not used to store anything between runs
// Named this way because it matches specification.
const SHA256_W = new Uint32Array(64);
class SHA256 extends _sha2_js_1.SHA2 {
constructor() {
super(64, 32, 8, false);
// We cannot use array here since array allows indexing by variable
// which means optimizer/compiler cannot use registers.
this.A = IV[0] | 0;
this.B = IV[1] | 0;
this.C = IV[2] | 0;
this.D = IV[3] | 0;
this.E = IV[4] | 0;
this.F = IV[5] | 0;
this.G = IV[6] | 0;
this.H = IV[7] | 0;
}
get() {
const { A, B, C, D, E, F, G, H } = this;
return [A, B, C, D, E, F, G, H];
}
// prettier-ignore
set(A, B, C, D, E, F, G, H) {
this.A = A | 0;
this.B = B | 0;
this.C = C | 0;
this.D = D | 0;
this.E = E | 0;
this.F = F | 0;
this.G = G | 0;
this.H = H | 0;
}
process(view, offset) {
// Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array
for (let i = 0; i < 16; i++, offset += 4)
SHA256_W[i] = view.getUint32(offset, false);
for (let i = 16; i < 64; i++) {
const W15 = SHA256_W[i - 15];
const W2 = SHA256_W[i - 2];
const s0 = (0, utils_js_1.rotr)(W15, 7) ^ (0, utils_js_1.rotr)(W15, 18) ^ (W15 >>> 3);
const s1 = (0, utils_js_1.rotr)(W2, 17) ^ (0, utils_js_1.rotr)(W2, 19) ^ (W2 >>> 10);
SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;
}
// Compression function main loop, 64 rounds
let { A, B, C, D, E, F, G, H } = this;
for (let i = 0; i < 64; i++) {
const sigma1 = (0, utils_js_1.rotr)(E, 6) ^ (0, utils_js_1.rotr)(E, 11) ^ (0, utils_js_1.rotr)(E, 25);
const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
const sigma0 = (0, utils_js_1.rotr)(A, 2) ^ (0, utils_js_1.rotr)(A, 13) ^ (0, utils_js_1.rotr)(A, 22);
const T2 = (sigma0 + Maj(A, B, C)) | 0;
H = G;
G = F;
F = E;
E = (D + T1) | 0;
D = C;
C = B;
B = A;
A = (T1 + T2) | 0;
}
// Add the compressed chunk to the current hash value
A = (A + this.A) | 0;
B = (B + this.B) | 0;
C = (C + this.C) | 0;
D = (D + this.D) | 0;
E = (E + this.E) | 0;
F = (F + this.F) | 0;
G = (G + this.G) | 0;
H = (H + this.H) | 0;
this.set(A, B, C, D, E, F, G, H);
}
roundClean() {
SHA256_W.fill(0);
}
destroy() {
this.set(0, 0, 0, 0, 0, 0, 0, 0);
this.buffer.fill(0);
}
}
// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf
class SHA224 extends SHA256 {
constructor() {
super();
this.A = 0xc1059ed8 | 0;
this.B = 0x367cd507 | 0;
this.C = 0x3070dd17 | 0;
this.D = 0xf70e5939 | 0;
this.E = 0xffc00b31 | 0;
this.F = 0x68581511 | 0;
this.G = 0x64f98fa7 | 0;
this.H = 0xbefa4fa4 | 0;
this.outputLen = 28;
}
}
/**
* SHA2-256 hash function
* @param message - data that would be hashed
*/
exports.sha256 = (0, utils_js_1.wrapConstructor)(() => new SHA256());
exports.sha224 = (0, utils_js_1.wrapConstructor)(() => new SHA224());
},{"./_sha2.js":4,"./utils.js":8}],8:[function(require,module,exports){
"use strict";
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
Object.defineProperty(exports, "__esModule", { value: true });
exports.randomBytes = exports.wrapXOFConstructorWithOpts = exports.wrapConstructorWithOpts = exports.wrapConstructor = exports.checkOpts = exports.Hash = exports.concatBytes = exports.toBytes = exports.utf8ToBytes = exports.asyncLoop = exports.nextTick = exports.hexToBytes = exports.bytesToHex = exports.isLE = exports.rotr = exports.createView = exports.u32 = exports.u8 = void 0;
// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
// node.js versions earlier than v19 don't declare it in global scope.
// For node.js, package.json#exports field mapping rewrites import
// from `crypto` to `cryptoNode`, which imports native module.
// Makes the utils un-importable in browsers without a bundler.
// Once node.js 18 is deprecated, we can just drop the import.
const crypto_1 = require("@noble/hashes/crypto");
const u8a = (a) => a instanceof Uint8Array;
// Cast array to different type
const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
exports.u8 = u8;
const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
exports.u32 = u32;
// Cast array to view
const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
exports.createView = createView;
// The rotate right (circular right shift) operation for uint32
const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);
exports.rotr = rotr;
// big-endian hardware is rare. Just in case someone still decides to run hashes:
// early-throw an error because we don't support BE yet.
exports.isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;
if (!exports.isLE)
throw new Error('Non little-endian hardware is not supported');
const hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0'));
/**
* @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
*/
function bytesToHex(bytes) {
if (!u8a(bytes))
throw new Error('Uint8Array expected');
// pre-caching improves the speed 6x
let hex = '';
for (let i = 0; i < bytes.length; i++) {
hex += hexes[bytes[i]];
}
return hex;
}
exports.bytesToHex = bytesToHex;
/**
* @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
*/
function hexToBytes(hex) {
if (typeof hex !== 'string')
throw new Error('hex string expected, got ' + typeof hex);
const len = hex.length;
if (len % 2)
throw new Error('padded hex string expected, got unpadded hex of length ' + len);
const array = new Uint8Array(len / 2);
for (let i = 0; i < array.length; i++) {
const j = i * 2;
const hexByte = hex.slice(j, j + 2);
const byte = Number.parseInt(hexByte, 16);
if (Number.isNaN(byte) || byte < 0)
throw new Error('Invalid byte sequence');
array[i] = byte;
}
return array;
}
exports.hexToBytes = hexToBytes;
// There is no setImmediate in browser and setTimeout is slow.
// call of async fn will return Promise, which will be fullfiled only on
// next scheduler queue processing step and this is exactly what we need.
const nextTick = async () => { };
exports.nextTick = nextTick;
// Returns control to thread each 'tick' ms to avoid blocking
async function asyncLoop(iters, tick, cb) {
let ts = Date.now();
for (let i = 0; i < iters; i++) {
cb(i);
// Date.now() is not monotonic, so in case if clock goes backwards we return return control too
const diff = Date.now() - ts;
if (diff >= 0 && diff < tick)
continue;
await (0, exports.nextTick)();
ts += diff;
}
}
exports.asyncLoop = asyncLoop;
/**
* @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
*/
function utf8ToBytes(str) {
if (typeof str !== 'string')
throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
}
exports.utf8ToBytes = utf8ToBytes;
/**
* Normalizes (non-hex) string or Uint8Array to Uint8Array.
* Warning: when Uint8Array is passed, it would NOT get copied.
* Keep in mind for future mutable operations.
*/
function toBytes(data) {
if (typeof data === 'string')
data = utf8ToBytes(data);
if (!u8a(data))
throw new Error(`expected Uint8Array, got ${typeof data}`);
return data;
}
exports.toBytes = toBytes;
/**
* Copies several Uint8Arrays into one.
*/
function concatBytes(...arrays) {
const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0));
let pad = 0; // walk through each item, ensure they have proper type
arrays.forEach((a) => {
if (!u8a(a))
throw new Error('Uint8Array expected');
r.set(a, pad);
pad += a.length;
});
return r;
}
exports.concatBytes = concatBytes;
// For runtime check if class implements interface
class Hash {
// Safe version that clones internal state
clone() {
return this._cloneInto();
}
}
exports.Hash = Hash;
// Check if object doens't have custom constructor (like Uint8Array/Array)
const isPlainObject = (obj) => Object.prototype.toString.call(obj) === '[object Object]' && obj.constructor === Object;
function checkOpts(defaults, opts) {
if (opts !== undefined && (typeof opts !== 'object' || !isPlainObject(opts)))
throw new Error('Options should be object or undefined');
const merged = Object.assign(defaults, opts);
return merged;
}
exports.checkOpts = checkOpts;
function wrapConstructor(hashCons) {
const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
const tmp = hashCons();
hashC.outputLen = tmp.outputLen;
hashC.blockLen = tmp.blockLen;
hashC.create = () => hashCons();
return hashC;
}
exports.wrapConstructor = wrapConstructor;
function wrapConstructorWithOpts(hashCons) {
const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
const tmp = hashCons({});
hashC.outputLen = tmp.outputLen;
hashC.blockLen = tmp.blockLen;
hashC.create = (opts) => hashCons(opts);
return hashC;
}
exports.wrapConstructorWithOpts = wrapConstructorWithOpts;
function wrapXOFConstructorWithOpts(hashCons) {
const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
const tmp = hashCons({});
hashC.outputLen = tmp.outputLen;
hashC.blockLen = tmp.blockLen;
hashC.create = (opts) => hashCons(opts);
return hashC;
}
exports.wrapXOFConstructorWithOpts = wrapXOFConstructorWithOpts;
/**
* Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.
*/
function randomBytes(bytesLength = 32) {
if (crypto_1.crypto && typeof crypto_1.crypto.getRandomValues === 'function') {
return crypto_1.crypto.getRandomValues(new Uint8Array(bytesLength));
}
throw new Error('crypto.getRandomValues must be defined');
}
exports.randomBytes = randomBytes;
},{"@noble/hashes/crypto":5}],9:[function(require,module,exports){
"use strict";
/*! noble-secp256k1 - MIT License (c) 2019 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.Signature = exports.Point = exports.CURVE = void 0;
const nodeCrypto = require("crypto");
const _0n = BigInt(0);
const _1n = BigInt(1);
const _2n = BigInt(2);
const _3n = BigInt(3);
const _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'),
});
exports.CURVE = CURVE;
const divNearest = (a, b) => (a + b / _2n) / b;
const endo = {
beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),
splitScalar(k) {
const { n } = CURVE;
const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15');
const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3');
const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8');
const b2 = a1;
const POW_2_128 = BigInt('0x100000000000000000000000000000000');
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;