koilib 5.6.0 → 5.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/koinos.js CHANGED
@@ -153,9 +153,9 @@ function bool(b) {
153
153
  exports.bool = bool;
154
154
  function bytes(b, ...lengths) {
155
155
  if (!(b instanceof Uint8Array))
156
- throw new TypeError('Expected Uint8Array');
156
+ throw new Error('Expected Uint8Array');
157
157
  if (lengths.length > 0 && !lengths.includes(b.length))
158
- throw new TypeError(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`);
158
+ throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`);
159
159
  }
160
160
  exports.bytes = bytes;
161
161
  function hash(hash) {
@@ -189,7 +189,7 @@ const assert = {
189
189
  output,
190
190
  };
191
191
  exports["default"] = assert;
192
-
192
+ //# sourceMappingURL=_assert.js.map
193
193
 
194
194
  /***/ }),
195
195
 
@@ -282,7 +282,16 @@ class SHA2 extends utils_js_1.Hash {
282
282
  setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
283
283
  this.process(view, 0);
284
284
  const oview = (0, utils_js_1.createView)(out);
285
- this.get().forEach((v, i) => oview.setUint32(4 * i, v, isLE));
285
+ const len = this.outputLen;
286
+ // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT
287
+ if (len % 4)
288
+ throw new Error('_sha2: outputLen should be aligned to 32bit');
289
+ const outLen = len / 4;
290
+ const state = this.get();
291
+ if (outLen > state.length)
292
+ throw new Error('_sha2: outputLen bigger than state');
293
+ for (let i = 0; i < outLen; i++)
294
+ oview.setUint32(4 * i, state[i], isLE);
286
295
  }
287
296
  digest() {
288
297
  const { buffer, outputLen } = this;
@@ -305,22 +314,19 @@ class SHA2 extends utils_js_1.Hash {
305
314
  }
306
315
  }
307
316
  exports.SHA2 = SHA2;
308
-
317
+ //# sourceMappingURL=_sha2.js.map
309
318
 
310
319
  /***/ }),
311
320
 
312
- /***/ 4421:
321
+ /***/ 1945:
313
322
  /***/ ((__unused_webpack_module, exports) => {
314
323
 
315
324
  "use strict";
316
325
 
317
326
  Object.defineProperty(exports, "__esModule", ({ value: true }));
318
327
  exports.crypto = void 0;
319
- exports.crypto = {
320
- node: undefined,
321
- web: typeof self === 'object' && 'crypto' in self ? self.crypto : undefined,
322
- };
323
-
328
+ exports.crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;
329
+ //# sourceMappingURL=crypto.js.map
324
330
 
325
331
  /***/ }),
326
332
 
@@ -431,7 +437,7 @@ exports.RIPEMD160 = RIPEMD160;
431
437
  * @param message - msg that would be hashed
432
438
  */
433
439
  exports.ripemd160 = (0, utils_js_1.wrapConstructor)(() => new RIPEMD160());
434
-
440
+ //# sourceMappingURL=ripemd160.js.map
435
441
 
436
442
  /***/ }),
437
443
 
@@ -441,7 +447,7 @@ exports.ripemd160 = (0, utils_js_1.wrapConstructor)(() => new RIPEMD160());
441
447
  "use strict";
442
448
 
443
449
  Object.defineProperty(exports, "__esModule", ({ value: true }));
444
- exports.sha256 = void 0;
450
+ exports.sha224 = exports.sha256 = void 0;
445
451
  const _sha2_js_1 = __webpack_require__(7505);
446
452
  const utils_js_1 = __webpack_require__(8089);
447
453
  // Choice: a ? b : c
@@ -544,12 +550,28 @@ class SHA256 extends _sha2_js_1.SHA2 {
544
550
  this.buffer.fill(0);
545
551
  }
546
552
  }
553
+ // Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf
554
+ class SHA224 extends SHA256 {
555
+ constructor() {
556
+ super();
557
+ this.A = 0xc1059ed8 | 0;
558
+ this.B = 0x367cd507 | 0;
559
+ this.C = 0x3070dd17 | 0;
560
+ this.D = 0xf70e5939 | 0;
561
+ this.E = 0xffc00b31 | 0;
562
+ this.F = 0x68581511 | 0;
563
+ this.G = 0x64f98fa7 | 0;
564
+ this.H = 0xbefa4fa4 | 0;
565
+ this.outputLen = 28;
566
+ }
567
+ }
547
568
  /**
548
569
  * SHA2-256 hash function
549
570
  * @param message - data that would be hashed
550
571
  */
551
572
  exports.sha256 = (0, utils_js_1.wrapConstructor)(() => new SHA256());
552
-
573
+ exports.sha224 = (0, utils_js_1.wrapConstructor)(() => new SHA224());
574
+ //# sourceMappingURL=sha256.js.map
553
575
 
554
576
  /***/ }),
555
577
 
@@ -560,10 +582,15 @@ exports.sha256 = (0, utils_js_1.wrapConstructor)(() => new SHA256());
560
582
 
561
583
  /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
562
584
  Object.defineProperty(exports, "__esModule", ({ value: true }));
563
- exports.randomBytes = 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;
564
- // The import here is via the package name. This is to ensure
565
- // that exports mapping/resolution does fall into place.
566
- const crypto_1 = __webpack_require__(4421);
585
+ 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;
586
+ // We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
587
+ // node.js versions earlier than v19 don't declare it in global scope.
588
+ // For node.js, package.json#exports field mapping rewrites import
589
+ // from `crypto` to `cryptoNode`, which imports native module.
590
+ // Makes the utils un-importable in browsers without a bundler.
591
+ // Once node.js 18 is deprecated, we can just drop the import.
592
+ const crypto_1 = __webpack_require__(1945);
593
+ const u8a = (a) => a instanceof Uint8Array;
567
594
  // Cast array to different type
568
595
  const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
569
596
  exports.u8 = u8;
@@ -575,36 +602,36 @@ exports.createView = createView;
575
602
  // The rotate right (circular right shift) operation for uint32
576
603
  const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);
577
604
  exports.rotr = rotr;
605
+ // big-endian hardware is rare. Just in case someone still decides to run hashes:
606
+ // early-throw an error because we don't support BE yet.
578
607
  exports.isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;
579
- // There is almost no big endian hardware, but js typed arrays uses platform specific endianness.
580
- // So, just to be sure not to corrupt anything.
581
608
  if (!exports.isLE)
582
609
  throw new Error('Non little-endian hardware is not supported');
583
610
  const hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0'));
584
611
  /**
585
- * @example bytesToHex(Uint8Array.from([0xde, 0xad, 0xbe, 0xef]))
612
+ * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
586
613
  */
587
- function bytesToHex(uint8a) {
588
- // pre-caching improves the speed 6x
589
- if (!(uint8a instanceof Uint8Array))
614
+ function bytesToHex(bytes) {
615
+ if (!u8a(bytes))
590
616
  throw new Error('Uint8Array expected');
617
+ // pre-caching improves the speed 6x
591
618
  let hex = '';
592
- for (let i = 0; i < uint8a.length; i++) {
593
- hex += hexes[uint8a[i]];
619
+ for (let i = 0; i < bytes.length; i++) {
620
+ hex += hexes[bytes[i]];
594
621
  }
595
622
  return hex;
596
623
  }
597
624
  exports.bytesToHex = bytesToHex;
598
625
  /**
599
- * @example hexToBytes('deadbeef')
626
+ * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
600
627
  */
601
628
  function hexToBytes(hex) {
602
- if (typeof hex !== 'string') {
603
- throw new TypeError('hexToBytes: expected string, got ' + typeof hex);
604
- }
605
- if (hex.length % 2)
606
- throw new Error('hexToBytes: received invalid unpadded hex');
607
- const array = new Uint8Array(hex.length / 2);
629
+ if (typeof hex !== 'string')
630
+ throw new Error('hex string expected, got ' + typeof hex);
631
+ const len = hex.length;
632
+ if (len % 2)
633
+ throw new Error('padded hex string expected, got unpadded hex of length ' + len);
634
+ const array = new Uint8Array(len / 2);
608
635
  for (let i = 0; i < array.length; i++) {
609
636
  const j = i * 2;
610
637
  const hexByte = hex.slice(j, j + 2);
@@ -616,8 +643,9 @@ function hexToBytes(hex) {
616
643
  return array;
617
644
  }
618
645
  exports.hexToBytes = hexToBytes;
619
- // There is no setImmediate in browser and setTimeout is slow. However, call to async function will return Promise
620
- // which will be fullfiled only on next scheduler queue processing step and this is exactly what we need.
646
+ // There is no setImmediate in browser and setTimeout is slow.
647
+ // call of async fn will return Promise, which will be fullfiled only on
648
+ // next scheduler queue processing step and this is exactly what we need.
621
649
  const nextTick = async () => { };
622
650
  exports.nextTick = nextTick;
623
651
  // Returns control to thread each 'tick' ms to avoid blocking
@@ -634,38 +662,41 @@ async function asyncLoop(iters, tick, cb) {
634
662
  }
635
663
  }
636
664
  exports.asyncLoop = asyncLoop;
665
+ /**
666
+ * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
667
+ */
637
668
  function utf8ToBytes(str) {
638
- if (typeof str !== 'string') {
639
- throw new TypeError(`utf8ToBytes expected string, got ${typeof str}`);
640
- }
641
- return new TextEncoder().encode(str);
669
+ if (typeof str !== 'string')
670
+ throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
671
+ return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
642
672
  }
643
673
  exports.utf8ToBytes = utf8ToBytes;
674
+ /**
675
+ * Normalizes (non-hex) string or Uint8Array to Uint8Array.
676
+ * Warning: when Uint8Array is passed, it would NOT get copied.
677
+ * Keep in mind for future mutable operations.
678
+ */
644
679
  function toBytes(data) {
645
680
  if (typeof data === 'string')
646
681
  data = utf8ToBytes(data);
647
- if (!(data instanceof Uint8Array))
648
- throw new TypeError(`Expected input type is Uint8Array (got ${typeof data})`);
682
+ if (!u8a(data))
683
+ throw new Error(`expected Uint8Array, got ${typeof data}`);
649
684
  return data;
650
685
  }
651
686
  exports.toBytes = toBytes;
652
687
  /**
653
- * Concats Uint8Array-s into one; like `Buffer.concat([buf1, buf2])`
654
- * @example concatBytes(buf1, buf2)
688
+ * Copies several Uint8Arrays into one.
655
689
  */
656
690
  function concatBytes(...arrays) {
657
- if (!arrays.every((a) => a instanceof Uint8Array))
658
- throw new Error('Uint8Array list expected');
659
- if (arrays.length === 1)
660
- return arrays[0];
661
- const length = arrays.reduce((a, arr) => a + arr.length, 0);
662
- const result = new Uint8Array(length);
663
- for (let i = 0, pad = 0; i < arrays.length; i++) {
664
- const arr = arrays[i];
665
- result.set(arr, pad);
666
- pad += arr.length;
667
- }
668
- return result;
691
+ const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0));
692
+ let pad = 0; // walk through each item, ensure they have proper type
693
+ arrays.forEach((a) => {
694
+ if (!u8a(a))
695
+ throw new Error('Uint8Array expected');
696
+ r.set(a, pad);
697
+ pad += a.length;
698
+ });
699
+ return r;
669
700
  }
670
701
  exports.concatBytes = concatBytes;
671
702
  // For runtime check if class implements interface
@@ -680,17 +711,17 @@ exports.Hash = Hash;
680
711
  const isPlainObject = (obj) => Object.prototype.toString.call(obj) === '[object Object]' && obj.constructor === Object;
681
712
  function checkOpts(defaults, opts) {
682
713
  if (opts !== undefined && (typeof opts !== 'object' || !isPlainObject(opts)))
683
- throw new TypeError('Options should be object or undefined');
714
+ throw new Error('Options should be object or undefined');
684
715
  const merged = Object.assign(defaults, opts);
685
716
  return merged;
686
717
  }
687
718
  exports.checkOpts = checkOpts;
688
- function wrapConstructor(hashConstructor) {
689
- const hashC = (message) => hashConstructor().update(toBytes(message)).digest();
690
- const tmp = hashConstructor();
719
+ function wrapConstructor(hashCons) {
720
+ const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
721
+ const tmp = hashCons();
691
722
  hashC.outputLen = tmp.outputLen;
692
723
  hashC.blockLen = tmp.blockLen;
693
- hashC.create = () => hashConstructor();
724
+ hashC.create = () => hashCons();
694
725
  return hashC;
695
726
  }
696
727
  exports.wrapConstructor = wrapConstructor;
@@ -703,22 +734,26 @@ function wrapConstructorWithOpts(hashCons) {
703
734
  return hashC;
704
735
  }
705
736
  exports.wrapConstructorWithOpts = wrapConstructorWithOpts;
737
+ function wrapXOFConstructorWithOpts(hashCons) {
738
+ const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
739
+ const tmp = hashCons({});
740
+ hashC.outputLen = tmp.outputLen;
741
+ hashC.blockLen = tmp.blockLen;
742
+ hashC.create = (opts) => hashCons(opts);
743
+ return hashC;
744
+ }
745
+ exports.wrapXOFConstructorWithOpts = wrapXOFConstructorWithOpts;
706
746
  /**
707
- * Secure PRNG
747
+ * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.
708
748
  */
709
749
  function randomBytes(bytesLength = 32) {
710
- if (crypto_1.crypto.web) {
711
- return crypto_1.crypto.web.getRandomValues(new Uint8Array(bytesLength));
712
- }
713
- else if (crypto_1.crypto.node) {
714
- return new Uint8Array(crypto_1.crypto.node.randomBytes(bytesLength).buffer);
715
- }
716
- else {
717
- throw new Error("The environment doesn't have randomBytes function");
750
+ if (crypto_1.crypto && typeof crypto_1.crypto.getRandomValues === 'function') {
751
+ return crypto_1.crypto.getRandomValues(new Uint8Array(bytesLength));
718
752
  }
753
+ throw new Error('crypto.getRandomValues must be defined');
719
754
  }
720
755
  exports.randomBytes = randomBytes;
721
-
756
+ //# sourceMappingURL=utils.js.map
722
757
 
723
758
  /***/ }),
724
759
 
@@ -736,25 +771,64 @@ const _1n = BigInt(1);
736
771
  const _2n = BigInt(2);
737
772
  const _3n = BigInt(3);
738
773
  const _8n = BigInt(8);
739
- const POW_2_256 = _2n ** BigInt(256);
740
- const CURVE = {
774
+ const CURVE = Object.freeze({
741
775
  a: _0n,
742
776
  b: BigInt(7),
743
- P: POW_2_256 - _2n ** BigInt(32) - BigInt(977),
744
- n: POW_2_256 - BigInt('432420386565659656852420866394968145599'),
777
+ P: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'),
778
+ n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'),
745
779
  h: _1n,
746
780
  Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),
747
781
  Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),
748
782
  beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),
749
- };
783
+ });
750
784
  exports.CURVE = CURVE;
751
- function weistrass(x) {
785
+ const divNearest = (a, b) => (a + b / _2n) / b;
786
+ const endo = {
787
+ beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),
788
+ splitScalar(k) {
789
+ const { n } = CURVE;
790
+ const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15');
791
+ const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3');
792
+ const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8');
793
+ const b2 = a1;
794
+ const POW_2_128 = BigInt('0x100000000000000000000000000000000');
795
+ const c1 = divNearest(b2 * k, n);
796
+ const c2 = divNearest(-b1 * k, n);
797
+ let k1 = mod(k - c1 * a1 - c2 * a2, n);
798
+ let k2 = mod(-c1 * b1 - c2 * b2, n);
799
+ const k1neg = k1 > POW_2_128;
800
+ const k2neg = k2 > POW_2_128;
801
+ if (k1neg)
802
+ k1 = n - k1;
803
+ if (k2neg)
804
+ k2 = n - k2;
805
+ if (k1 > POW_2_128 || k2 > POW_2_128) {
806
+ throw new Error('splitScalarEndo: Endomorphism failed, k=' + k);
807
+ }
808
+ return { k1neg, k1, k2neg, k2 };
809
+ },
810
+ };
811
+ const fieldLen = 32;
812
+ const groupLen = 32;
813
+ const hashLen = 32;
814
+ const compressedLen = fieldLen + 1;
815
+ const uncompressedLen = 2 * fieldLen + 1;
816
+ function weierstrass(x) {
752
817
  const { a, b } = CURVE;
753
818
  const x2 = mod(x * x);
754
819
  const x3 = mod(x2 * x);
755
820
  return mod(x3 + a * x + b);
756
821
  }
757
822
  const USE_ENDOMORPHISM = CURVE.a === _0n;
823
+ class ShaError extends Error {
824
+ constructor(message) {
825
+ super(message);
826
+ }
827
+ }
828
+ function assertJacPoint(other) {
829
+ if (!(other instanceof JacobianPoint))
830
+ throw new TypeError('JacobianPoint expected');
831
+ }
758
832
  class JacobianPoint {
759
833
  constructor(x, y, z) {
760
834
  this.x = x;
@@ -765,6 +839,8 @@ class JacobianPoint {
765
839
  if (!(p instanceof Point)) {
766
840
  throw new TypeError('JacobianPoint#fromAffine: expected Point');
767
841
  }
842
+ if (p.equals(Point.ZERO))
843
+ return JacobianPoint.ZERO;
768
844
  return new JacobianPoint(p.x, p.y, _1n);
769
845
  }
770
846
  static toAffineBatch(points) {
@@ -775,12 +851,11 @@ class JacobianPoint {
775
851
  return JacobianPoint.toAffineBatch(points).map(JacobianPoint.fromAffine);
776
852
  }
777
853
  equals(other) {
778
- if (!(other instanceof JacobianPoint))
779
- throw new TypeError('JacobianPoint expected');
854
+ assertJacPoint(other);
780
855
  const { x: X1, y: Y1, z: Z1 } = this;
781
856
  const { x: X2, y: Y2, z: Z2 } = other;
782
- const Z1Z1 = mod(Z1 ** _2n);
783
- const Z2Z2 = mod(Z2 ** _2n);
857
+ const Z1Z1 = mod(Z1 * Z1);
858
+ const Z2Z2 = mod(Z2 * Z2);
784
859
  const U1 = mod(X1 * Z2Z2);
785
860
  const U2 = mod(X2 * Z1Z1);
786
861
  const S1 = mod(mod(Y1 * Z2) * Z2Z2);
@@ -792,28 +867,28 @@ class JacobianPoint {
792
867
  }
793
868
  double() {
794
869
  const { x: X1, y: Y1, z: Z1 } = this;
795
- const A = mod(X1 ** _2n);
796
- const B = mod(Y1 ** _2n);
797
- const C = mod(B ** _2n);
798
- const D = mod(_2n * (mod((X1 + B) ** _2n) - A - C));
870
+ const A = mod(X1 * X1);
871
+ const B = mod(Y1 * Y1);
872
+ const C = mod(B * B);
873
+ const x1b = X1 + B;
874
+ const D = mod(_2n * (mod(x1b * x1b) - A - C));
799
875
  const E = mod(_3n * A);
800
- const F = mod(E ** _2n);
876
+ const F = mod(E * E);
801
877
  const X3 = mod(F - _2n * D);
802
878
  const Y3 = mod(E * (D - X3) - _8n * C);
803
879
  const Z3 = mod(_2n * Y1 * Z1);
804
880
  return new JacobianPoint(X3, Y3, Z3);
805
881
  }
806
882
  add(other) {
807
- if (!(other instanceof JacobianPoint))
808
- throw new TypeError('JacobianPoint expected');
883
+ assertJacPoint(other);
809
884
  const { x: X1, y: Y1, z: Z1 } = this;
810
885
  const { x: X2, y: Y2, z: Z2 } = other;
811
886
  if (X2 === _0n || Y2 === _0n)
812
887
  return this;
813
888
  if (X1 === _0n || Y1 === _0n)
814
889
  return other;
815
- const Z1Z1 = mod(Z1 ** _2n);
816
- const Z2Z2 = mod(Z2 ** _2n);
890
+ const Z1Z1 = mod(Z1 * Z1);
891
+ const Z2Z2 = mod(Z2 * Z2);
817
892
  const U1 = mod(X1 * Z2Z2);
818
893
  const U2 = mod(X2 * Z1Z1);
819
894
  const S1 = mod(mod(Y1 * Z2) * Z2Z2);
@@ -828,10 +903,10 @@ class JacobianPoint {
828
903
  return JacobianPoint.ZERO;
829
904
  }
830
905
  }
831
- const HH = mod(H ** _2n);
906
+ const HH = mod(H * H);
832
907
  const HHH = mod(H * HH);
833
908
  const V = mod(U1 * HH);
834
- const X3 = mod(r ** _2n - HHH - _2n * V);
909
+ const X3 = mod(r * r - HHH - _2n * V);
835
910
  const Y3 = mod(r * (V - X3) - S1 * HHH);
836
911
  const Z3 = mod(Z1 * Z2 * H);
837
912
  return new JacobianPoint(X3, Y3, Z3);
@@ -857,7 +932,7 @@ class JacobianPoint {
857
932
  }
858
933
  return p;
859
934
  }
860
- let { k1neg, k1, k2neg, k2 } = splitScalarEndo(n);
935
+ let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);
861
936
  let k1p = P0;
862
937
  let k2p = P0;
863
938
  let d = this;
@@ -874,7 +949,7 @@ class JacobianPoint {
874
949
  k1p = k1p.negate();
875
950
  if (k2neg)
876
951
  k2p = k2p.negate();
877
- k2p = new JacobianPoint(mod(k2p.x * CURVE.beta), k2p.y, k2p.z);
952
+ k2p = new JacobianPoint(mod(k2p.x * endo.beta), k2p.y, k2p.z);
878
953
  return k1p.add(k2p);
879
954
  }
880
955
  precomputeWindow(W) {
@@ -909,7 +984,7 @@ class JacobianPoint {
909
984
  }
910
985
  }
911
986
  let p = JacobianPoint.ZERO;
912
- let f = JacobianPoint.ZERO;
987
+ let f = JacobianPoint.BASE;
913
988
  const windows = 1 + (USE_ENDOMORPHISM ? 128 / W : 256 / W);
914
989
  const windowSize = 2 ** (W - 1);
915
990
  const mask = BigInt(2 ** W - 1);
@@ -923,17 +998,15 @@ class JacobianPoint {
923
998
  wbits -= maxNumber;
924
999
  n += _1n;
925
1000
  }
1001
+ const offset1 = offset;
1002
+ const offset2 = offset + Math.abs(wbits) - 1;
1003
+ const cond1 = window % 2 !== 0;
1004
+ const cond2 = wbits < 0;
926
1005
  if (wbits === 0) {
927
- let pr = precomputes[offset];
928
- if (window % 2)
929
- pr = pr.negate();
930
- f = f.add(pr);
1006
+ f = f.add(constTimeNegate(cond1, precomputes[offset1]));
931
1007
  }
932
1008
  else {
933
- let cached = precomputes[offset + Math.abs(wbits) - 1];
934
- if (wbits < 0)
935
- cached = cached.negate();
936
- p = p.add(cached);
1009
+ p = p.add(constTimeNegate(cond2, precomputes[offset2]));
937
1010
  }
938
1011
  }
939
1012
  return { p, f };
@@ -943,14 +1016,12 @@ class JacobianPoint {
943
1016
  let point;
944
1017
  let fake;
945
1018
  if (USE_ENDOMORPHISM) {
946
- const { k1neg, k1, k2neg, k2 } = splitScalarEndo(n);
1019
+ const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);
947
1020
  let { p: k1p, f: f1p } = this.wNAF(k1, affinePoint);
948
1021
  let { p: k2p, f: f2p } = this.wNAF(k2, affinePoint);
949
- if (k1neg)
950
- k1p = k1p.negate();
951
- if (k2neg)
952
- k2p = k2p.negate();
953
- k2p = new JacobianPoint(mod(k2p.x * CURVE.beta), k2p.y, k2p.z);
1022
+ k1p = constTimeNegate(k1neg, k1p);
1023
+ k2p = constTimeNegate(k2neg, k2p);
1024
+ k2p = new JacobianPoint(mod(k2p.x * endo.beta), k2p.y, k2p.z);
954
1025
  point = k1p.add(k2p);
955
1026
  fake = f1p.add(f2p);
956
1027
  }
@@ -961,14 +1032,19 @@ class JacobianPoint {
961
1032
  }
962
1033
  return JacobianPoint.normalizeZ([point, fake])[0];
963
1034
  }
964
- toAffine(invZ = invert(this.z)) {
1035
+ toAffine(invZ) {
965
1036
  const { x, y, z } = this;
1037
+ const is0 = this.equals(JacobianPoint.ZERO);
1038
+ if (invZ == null)
1039
+ invZ = is0 ? _8n : invert(z);
966
1040
  const iz1 = invZ;
967
1041
  const iz2 = mod(iz1 * iz1);
968
1042
  const iz3 = mod(iz2 * iz1);
969
1043
  const ax = mod(x * iz2);
970
1044
  const ay = mod(y * iz3);
971
1045
  const zz = mod(z * iz1);
1046
+ if (is0)
1047
+ return Point.ZERO;
972
1048
  if (zz !== _1n)
973
1049
  throw new Error('invZ was invalid');
974
1050
  return new Point(ax, ay);
@@ -976,6 +1052,10 @@ class JacobianPoint {
976
1052
  }
977
1053
  JacobianPoint.BASE = new JacobianPoint(CURVE.Gx, CURVE.Gy, _1n);
978
1054
  JacobianPoint.ZERO = new JacobianPoint(_0n, _1n, _0n);
1055
+ function constTimeNegate(condition, item) {
1056
+ const neg = item.negate();
1057
+ return condition ? neg : item;
1058
+ }
979
1059
  const pointPrecomputes = new WeakMap();
980
1060
  class Point {
981
1061
  constructor(x, y) {
@@ -986,12 +1066,15 @@ class Point {
986
1066
  this._WINDOW_SIZE = windowSize;
987
1067
  pointPrecomputes.delete(this);
988
1068
  }
1069
+ hasEvenY() {
1070
+ return this.y % _2n === _0n;
1071
+ }
989
1072
  static fromCompressedHex(bytes) {
990
1073
  const isShort = bytes.length === 32;
991
1074
  const x = bytesToNumber(isShort ? bytes : bytes.subarray(1));
992
1075
  if (!isValidFieldElement(x))
993
1076
  throw new Error('Point is not on curve');
994
- const y2 = weistrass(x);
1077
+ const y2 = weierstrass(x);
995
1078
  let y = sqrtMod(y2);
996
1079
  const isYOdd = (y & _1n) === _1n;
997
1080
  if (isShort) {
@@ -1008,8 +1091,8 @@ class Point {
1008
1091
  return point;
1009
1092
  }
1010
1093
  static fromUncompressedHex(bytes) {
1011
- const x = bytesToNumber(bytes.subarray(1, 33));
1012
- const y = bytesToNumber(bytes.subarray(33, 65));
1094
+ const x = bytesToNumber(bytes.subarray(1, fieldLen + 1));
1095
+ const y = bytesToNumber(bytes.subarray(fieldLen + 1, fieldLen * 2 + 1));
1013
1096
  const point = new Point(x, y);
1014
1097
  point.assertValidity();
1015
1098
  return point;
@@ -1018,29 +1101,30 @@ class Point {
1018
1101
  const bytes = ensureBytes(hex);
1019
1102
  const len = bytes.length;
1020
1103
  const header = bytes[0];
1021
- if (len === 32 || (len === 33 && (header === 0x02 || header === 0x03))) {
1104
+ if (len === fieldLen)
1105
+ return this.fromCompressedHex(bytes);
1106
+ if (len === compressedLen && (header === 0x02 || header === 0x03)) {
1022
1107
  return this.fromCompressedHex(bytes);
1023
1108
  }
1024
- if (len === 65 && header === 0x04)
1109
+ if (len === uncompressedLen && header === 0x04)
1025
1110
  return this.fromUncompressedHex(bytes);
1026
- throw new Error(`Point.fromHex: received invalid point. Expected 32-33 compressed bytes or 65 uncompressed bytes, not ${len}`);
1111
+ throw new Error(`Point.fromHex: received invalid point. Expected 32-${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes, not ${len}`);
1027
1112
  }
1028
1113
  static fromPrivateKey(privateKey) {
1029
1114
  return Point.BASE.multiply(normalizePrivateKey(privateKey));
1030
1115
  }
1031
1116
  static fromSignature(msgHash, signature, recovery) {
1032
- msgHash = ensureBytes(msgHash);
1033
- const h = truncateHash(msgHash);
1034
1117
  const { r, s } = normalizeSignature(signature);
1035
- if (recovery !== 0 && recovery !== 1) {
1036
- throw new Error('Cannot recover signature: invalid recovery bit');
1037
- }
1038
- const prefix = recovery & 1 ? '03' : '02';
1039
- const R = Point.fromHex(prefix + numTo32bStr(r));
1118
+ if (![0, 1, 2, 3].includes(recovery))
1119
+ throw new Error('Cannot recover: invalid recovery bit');
1120
+ const h = truncateHash(ensureBytes(msgHash));
1040
1121
  const { n } = CURVE;
1041
- const rinv = invert(r, n);
1122
+ const radj = recovery === 2 || recovery === 3 ? r + n : r;
1123
+ const rinv = invert(radj, n);
1042
1124
  const u1 = mod(-h * rinv, n);
1043
1125
  const u2 = mod(s * rinv, n);
1126
+ const prefix = recovery & 1 ? '03' : '02';
1127
+ const R = Point.fromHex(prefix + numTo32bStr(radj));
1044
1128
  const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2);
1045
1129
  if (!Q)
1046
1130
  throw new Error('Cannot recover signature: point at infinify');
@@ -1053,7 +1137,7 @@ class Point {
1053
1137
  toHex(isCompressed = false) {
1054
1138
  const x = numTo32bStr(this.x);
1055
1139
  if (isCompressed) {
1056
- const prefix = this.y & _1n ? '03' : '02';
1140
+ const prefix = this.hasEvenY() ? '02' : '03';
1057
1141
  return `${prefix}${x}`;
1058
1142
  }
1059
1143
  else {
@@ -1072,7 +1156,7 @@ class Point {
1072
1156
  if (!isValidFieldElement(x) || !isValidFieldElement(y))
1073
1157
  throw new Error(msg);
1074
1158
  const left = mod(y * y);
1075
- const right = weistrass(x);
1159
+ const right = weierstrass(x);
1076
1160
  if (mod(left - right) !== _0n)
1077
1161
  throw new Error(msg);
1078
1162
  }
@@ -1143,7 +1227,7 @@ class Signature {
1143
1227
  this.assertValidity();
1144
1228
  }
1145
1229
  static fromCompact(hex) {
1146
- const arr = isUint8a(hex);
1230
+ const arr = hex instanceof Uint8Array;
1147
1231
  const name = 'Signature.fromCompact';
1148
1232
  if (typeof hex !== 'string' && !arr)
1149
1233
  throw new TypeError(`${name}: Expected string or Uint8Array`);
@@ -1153,7 +1237,7 @@ class Signature {
1153
1237
  return new Signature(hexToNumber(str.slice(0, 64)), hexToNumber(str.slice(64, 128)));
1154
1238
  }
1155
1239
  static fromDER(hex) {
1156
- const arr = isUint8a(hex);
1240
+ const arr = hex instanceof Uint8Array;
1157
1241
  if (typeof hex !== 'string' && !arr)
1158
1242
  throw new TypeError(`Signature.fromDER: Expected string or Uint8Array`);
1159
1243
  const { r, s } = parseDERSignature(arr ? hex : hexToBytes(hex));
@@ -1174,19 +1258,19 @@ class Signature {
1174
1258
  return this.s > HALF;
1175
1259
  }
1176
1260
  normalizeS() {
1177
- return this.hasHighS() ? new Signature(this.r, CURVE.n - this.s) : this;
1261
+ return this.hasHighS() ? new Signature(this.r, mod(-this.s, CURVE.n)) : this;
1178
1262
  }
1179
- toDERRawBytes(isCompressed = false) {
1180
- return hexToBytes(this.toDERHex(isCompressed));
1263
+ toDERRawBytes() {
1264
+ return hexToBytes(this.toDERHex());
1181
1265
  }
1182
- toDERHex(isCompressed = false) {
1266
+ toDERHex() {
1183
1267
  const sHex = sliceDER(numberToHexUnpadded(this.s));
1184
- if (isCompressed)
1185
- return sHex;
1186
1268
  const rHex = sliceDER(numberToHexUnpadded(this.r));
1187
- const rLen = numberToHexUnpadded(rHex.length / 2);
1188
- const sLen = numberToHexUnpadded(sHex.length / 2);
1189
- const length = numberToHexUnpadded(rHex.length / 2 + sHex.length / 2 + 4);
1269
+ const sHexL = sHex.length / 2;
1270
+ const rHexL = rHex.length / 2;
1271
+ const sLen = numberToHexUnpadded(sHexL);
1272
+ const rLen = numberToHexUnpadded(rHexL);
1273
+ const length = numberToHexUnpadded(rHexL + sHexL + 4);
1190
1274
  return `30${length}02${rLen}${rHex}02${sLen}${sHex}`;
1191
1275
  }
1192
1276
  toRawBytes() {
@@ -1204,7 +1288,7 @@ class Signature {
1204
1288
  }
1205
1289
  exports.Signature = Signature;
1206
1290
  function concatBytes(...arrays) {
1207
- if (!arrays.every(isUint8a))
1291
+ if (!arrays.every((b) => b instanceof Uint8Array))
1208
1292
  throw new Error('Uint8Array list expected');
1209
1293
  if (arrays.length === 1)
1210
1294
  return arrays[0];
@@ -1217,9 +1301,6 @@ function concatBytes(...arrays) {
1217
1301
  }
1218
1302
  return result;
1219
1303
  }
1220
- function isUint8a(bytes) {
1221
- return bytes instanceof Uint8Array;
1222
- }
1223
1304
  const hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0'));
1224
1305
  function bytesToHex(uint8a) {
1225
1306
  if (!(uint8a instanceof Uint8Array))
@@ -1230,13 +1311,19 @@ function bytesToHex(uint8a) {
1230
1311
  }
1231
1312
  return hex;
1232
1313
  }
1314
+ const POW_2_256 = BigInt('0x10000000000000000000000000000000000000000000000000000000000000000');
1233
1315
  function numTo32bStr(num) {
1234
- if (num > POW_2_256)
1235
- throw new Error('Expected number < 2^256');
1316
+ if (typeof num !== 'bigint')
1317
+ throw new Error('Expected bigint');
1318
+ if (!(_0n <= num && num < POW_2_256))
1319
+ throw new Error('Expected number 0 <= n < 2^256');
1236
1320
  return num.toString(16).padStart(64, '0');
1237
1321
  }
1238
1322
  function numTo32b(num) {
1239
- return hexToBytes(numTo32bStr(num));
1323
+ const b = hexToBytes(numTo32bStr(num));
1324
+ if (b.length !== 32)
1325
+ throw new Error('Error: expected 32 bytes');
1326
+ return b;
1240
1327
  }
1241
1328
  function numberToHexUnpadded(num) {
1242
1329
  const hex = num.toString(16);
@@ -1312,7 +1399,11 @@ function sqrtMod(x) {
1312
1399
  const b223 = (pow2(b220, _3n) * b3) % P;
1313
1400
  const t1 = (pow2(b223, _23n) * b22) % P;
1314
1401
  const t2 = (pow2(t1, _6n) * b2) % P;
1315
- return pow2(t2, _2n);
1402
+ const rt = pow2(t2, _2n);
1403
+ const xc = (rt * rt) % P;
1404
+ if (xc !== x)
1405
+ throw new Error('Cannot find square root');
1406
+ return rt;
1316
1407
  }
1317
1408
  function invert(number, modulo = CURVE.P) {
1318
1409
  if (number === _0n || modulo <= _0n) {
@@ -1350,61 +1441,45 @@ function invertBatch(nums, p = CURVE.P) {
1350
1441
  }, inverted);
1351
1442
  return scratch;
1352
1443
  }
1353
- const divNearest = (a, b) => (a + b / _2n) / b;
1354
- const POW_2_128 = _2n ** BigInt(128);
1355
- function splitScalarEndo(k) {
1356
- const { n } = CURVE;
1357
- const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15');
1358
- const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3');
1359
- const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8');
1360
- const b2 = a1;
1361
- const c1 = divNearest(b2 * k, n);
1362
- const c2 = divNearest(-b1 * k, n);
1363
- let k1 = mod(k - c1 * a1 - c2 * a2, n);
1364
- let k2 = mod(-c1 * b1 - c2 * b2, n);
1365
- const k1neg = k1 > POW_2_128;
1366
- const k2neg = k2 > POW_2_128;
1367
- if (k1neg)
1368
- k1 = n - k1;
1369
- if (k2neg)
1370
- k2 = n - k2;
1371
- if (k1 > POW_2_128 || k2 > POW_2_128) {
1372
- throw new Error('splitScalarEndo: Endomorphism failed, k=' + k);
1373
- }
1374
- return { k1neg, k1, k2neg, k2 };
1444
+ function bits2int_2(bytes) {
1445
+ const delta = bytes.length * 8 - groupLen * 8;
1446
+ const num = bytesToNumber(bytes);
1447
+ return delta > 0 ? num >> BigInt(delta) : num;
1375
1448
  }
1376
- function truncateHash(hash) {
1449
+ function truncateHash(hash, truncateOnly = false) {
1450
+ const h = bits2int_2(hash);
1451
+ if (truncateOnly)
1452
+ return h;
1377
1453
  const { n } = CURVE;
1378
- const byteLength = hash.length;
1379
- const delta = byteLength * 8 - 256;
1380
- let h = bytesToNumber(hash);
1381
- if (delta > 0)
1382
- h = h >> BigInt(delta);
1383
- if (h >= n)
1384
- h -= n;
1385
- return h;
1454
+ return h >= n ? h - n : h;
1386
1455
  }
1456
+ let _sha256Sync;
1457
+ let _hmacSha256Sync;
1387
1458
  class HmacDrbg {
1388
- constructor() {
1389
- this.v = new Uint8Array(32).fill(1);
1390
- this.k = new Uint8Array(32).fill(0);
1459
+ constructor(hashLen, qByteLen) {
1460
+ this.hashLen = hashLen;
1461
+ this.qByteLen = qByteLen;
1462
+ if (typeof hashLen !== 'number' || hashLen < 2)
1463
+ throw new Error('hashLen must be a number');
1464
+ if (typeof qByteLen !== 'number' || qByteLen < 2)
1465
+ throw new Error('qByteLen must be a number');
1466
+ this.v = new Uint8Array(hashLen).fill(1);
1467
+ this.k = new Uint8Array(hashLen).fill(0);
1391
1468
  this.counter = 0;
1392
1469
  }
1393
1470
  hmac(...values) {
1394
1471
  return exports.utils.hmacSha256(this.k, ...values);
1395
1472
  }
1396
1473
  hmacSync(...values) {
1397
- if (typeof exports.utils.hmacSha256Sync !== 'function')
1398
- throw new Error('utils.hmacSha256Sync is undefined, you need to set it');
1399
- const res = exports.utils.hmacSha256Sync(this.k, ...values);
1400
- if (res instanceof Promise)
1401
- throw new Error('To use sync sign(), ensure utils.hmacSha256 is sync');
1402
- return res;
1474
+ return _hmacSha256Sync(this.k, ...values);
1475
+ }
1476
+ checkSync() {
1477
+ if (typeof _hmacSha256Sync !== 'function')
1478
+ throw new ShaError('hmacSha256Sync needs to be set');
1403
1479
  }
1404
1480
  incr() {
1405
- if (this.counter >= 1000) {
1481
+ if (this.counter >= 1000)
1406
1482
  throw new Error('Tried 1,000 k values for sign(), all were invalid');
1407
- }
1408
1483
  this.counter += 1;
1409
1484
  }
1410
1485
  async reseed(seed = new Uint8Array()) {
@@ -1416,6 +1491,7 @@ class HmacDrbg {
1416
1491
  this.v = await this.hmac(this.v);
1417
1492
  }
1418
1493
  reseedSync(seed = new Uint8Array()) {
1494
+ this.checkSync();
1419
1495
  this.k = this.hmacSync(this.v, Uint8Array.from([0x00]), seed);
1420
1496
  this.v = this.hmacSync(this.v);
1421
1497
  if (seed.length === 0)
@@ -1425,13 +1501,28 @@ class HmacDrbg {
1425
1501
  }
1426
1502
  async generate() {
1427
1503
  this.incr();
1428
- this.v = await this.hmac(this.v);
1429
- return this.v;
1504
+ let len = 0;
1505
+ const out = [];
1506
+ while (len < this.qByteLen) {
1507
+ this.v = await this.hmac(this.v);
1508
+ const sl = this.v.slice();
1509
+ out.push(sl);
1510
+ len += this.v.length;
1511
+ }
1512
+ return concatBytes(...out);
1430
1513
  }
1431
1514
  generateSync() {
1515
+ this.checkSync();
1432
1516
  this.incr();
1433
- this.v = this.hmacSync(this.v);
1434
- return this.v;
1517
+ let len = 0;
1518
+ const out = [];
1519
+ while (len < this.qByteLen) {
1520
+ this.v = this.hmacSync(this.v);
1521
+ const sl = this.v.slice();
1522
+ out.push(sl);
1523
+ len += this.v.length;
1524
+ }
1525
+ return concatBytes(...out);
1435
1526
  }
1436
1527
  }
1437
1528
  function isWithinCurveOrder(num) {
@@ -1440,20 +1531,25 @@ function isWithinCurveOrder(num) {
1440
1531
  function isValidFieldElement(num) {
1441
1532
  return _0n < num && num < CURVE.P;
1442
1533
  }
1443
- function kmdToSig(kBytes, m, d) {
1444
- const k = bytesToNumber(kBytes);
1534
+ function kmdToSig(kBytes, m, d, lowS = true) {
1535
+ const { n } = CURVE;
1536
+ const k = truncateHash(kBytes, true);
1445
1537
  if (!isWithinCurveOrder(k))
1446
1538
  return;
1447
- const { n } = CURVE;
1539
+ const kinv = invert(k, n);
1448
1540
  const q = Point.BASE.multiply(k);
1449
1541
  const r = mod(q.x, n);
1450
1542
  if (r === _0n)
1451
1543
  return;
1452
- const s = mod(invert(k, n) * mod(m + d * r, n), n);
1544
+ const s = mod(kinv * mod(m + d * r, n), n);
1453
1545
  if (s === _0n)
1454
1546
  return;
1455
- const sig = new Signature(r, s);
1456
- const recovery = (q.x === sig.r ? 0 : 2) | Number(q.y & _1n);
1547
+ let sig = new Signature(r, s);
1548
+ let recovery = (q.x === sig.r ? 0 : 2) | Number(q.y & _1n);
1549
+ if (lowS && sig.hasHighS()) {
1550
+ sig = sig.normalizeS();
1551
+ recovery ^= 1;
1552
+ }
1457
1553
  return { sig, recovery };
1458
1554
  }
1459
1555
  function normalizePrivateKey(key) {
@@ -1465,12 +1561,12 @@ function normalizePrivateKey(key) {
1465
1561
  num = BigInt(key);
1466
1562
  }
1467
1563
  else if (typeof key === 'string') {
1468
- if (key.length !== 64)
1564
+ if (key.length !== 2 * groupLen)
1469
1565
  throw new Error('Expected 32 bytes of private key');
1470
1566
  num = hexToNumber(key);
1471
1567
  }
1472
- else if (isUint8a(key)) {
1473
- if (key.length !== 32)
1568
+ else if (key instanceof Uint8Array) {
1569
+ if (key.length !== groupLen)
1474
1570
  throw new Error('Expected 32 bytes of private key');
1475
1571
  num = bytesToNumber(key);
1476
1572
  }
@@ -1510,22 +1606,22 @@ function recoverPublicKey(msgHash, signature, recovery, isCompressed = false) {
1510
1606
  return Point.fromSignature(msgHash, signature, recovery).toRawBytes(isCompressed);
1511
1607
  }
1512
1608
  exports.recoverPublicKey = recoverPublicKey;
1513
- function isPub(item) {
1514
- const arr = isUint8a(item);
1609
+ function isProbPub(item) {
1610
+ const arr = item instanceof Uint8Array;
1515
1611
  const str = typeof item === 'string';
1516
1612
  const len = (arr || str) && item.length;
1517
1613
  if (arr)
1518
- return len === 33 || len === 65;
1614
+ return len === compressedLen || len === uncompressedLen;
1519
1615
  if (str)
1520
- return len === 66 || len === 130;
1616
+ return len === compressedLen * 2 || len === uncompressedLen * 2;
1521
1617
  if (item instanceof Point)
1522
1618
  return true;
1523
1619
  return false;
1524
1620
  }
1525
1621
  function getSharedSecret(privateA, publicB, isCompressed = false) {
1526
- if (isPub(privateA))
1622
+ if (isProbPub(privateA))
1527
1623
  throw new TypeError('getSharedSecret: first arg must be private key');
1528
- if (!isPub(publicB))
1624
+ if (!isProbPub(publicB))
1529
1625
  throw new TypeError('getSharedSecret: second arg must be public key');
1530
1626
  const b = normalizePublicKey(publicB);
1531
1627
  b.assertValidity();
@@ -1533,7 +1629,7 @@ function getSharedSecret(privateA, publicB, isCompressed = false) {
1533
1629
  }
1534
1630
  exports.getSharedSecret = getSharedSecret;
1535
1631
  function bits2int(bytes) {
1536
- const slice = bytes.length > 32 ? bytes.slice(0, 32) : bytes;
1632
+ const slice = bytes.length > fieldLen ? bytes.slice(0, fieldLen) : bytes;
1537
1633
  return bytesToNumber(slice);
1538
1634
  }
1539
1635
  function bits2octets(bytes) {
@@ -1542,10 +1638,7 @@ function bits2octets(bytes) {
1542
1638
  return int2octets(z2 < _0n ? z1 : z2);
1543
1639
  }
1544
1640
  function int2octets(num) {
1545
- if (typeof num !== 'bigint')
1546
- throw new Error('Expected bigint');
1547
- const hex = numTo32bStr(num);
1548
- return hexToBytes(hex);
1641
+ return numTo32b(num);
1549
1642
  }
1550
1643
  function initSigArgs(msgHash, privateKey, extraEntropy) {
1551
1644
  if (msgHash == null)
@@ -1555,10 +1648,10 @@ function initSigArgs(msgHash, privateKey, extraEntropy) {
1555
1648
  const seedArgs = [int2octets(d), bits2octets(h1)];
1556
1649
  if (extraEntropy != null) {
1557
1650
  if (extraEntropy === true)
1558
- extraEntropy = exports.utils.randomBytes(32);
1651
+ extraEntropy = exports.utils.randomBytes(fieldLen);
1559
1652
  const e = ensureBytes(extraEntropy);
1560
- if (e.length !== 32)
1561
- throw new Error('sign: Expected 32 bytes of extra data');
1653
+ if (e.length !== fieldLen)
1654
+ throw new Error(`sign: Expected ${fieldLen} bytes of extra data`);
1562
1655
  seedArgs.push(e);
1563
1656
  }
1564
1657
  const seed = concatBytes(...seedArgs);
@@ -1566,31 +1659,27 @@ function initSigArgs(msgHash, privateKey, extraEntropy) {
1566
1659
  return { seed, m, d };
1567
1660
  }
1568
1661
  function finalizeSig(recSig, opts) {
1569
- let { sig, recovery } = recSig;
1570
- const { canonical, der, recovered } = Object.assign({ canonical: true, der: true }, opts);
1571
- if (canonical && sig.hasHighS()) {
1572
- sig = sig.normalizeS();
1573
- recovery ^= 1;
1574
- }
1662
+ const { sig, recovery } = recSig;
1663
+ const { der, recovered } = Object.assign({ canonical: true, der: true }, opts);
1575
1664
  const hashed = der ? sig.toDERRawBytes() : sig.toCompactRawBytes();
1576
1665
  return recovered ? [hashed, recovery] : hashed;
1577
1666
  }
1578
1667
  async function sign(msgHash, privKey, opts = {}) {
1579
1668
  const { seed, m, d } = initSigArgs(msgHash, privKey, opts.extraEntropy);
1580
- let sig;
1581
- const drbg = new HmacDrbg();
1669
+ const drbg = new HmacDrbg(hashLen, groupLen);
1582
1670
  await drbg.reseed(seed);
1583
- while (!(sig = kmdToSig(await drbg.generate(), m, d)))
1671
+ let sig;
1672
+ while (!(sig = kmdToSig(await drbg.generate(), m, d, opts.canonical)))
1584
1673
  await drbg.reseed();
1585
1674
  return finalizeSig(sig, opts);
1586
1675
  }
1587
1676
  exports.sign = sign;
1588
1677
  function signSync(msgHash, privKey, opts = {}) {
1589
1678
  const { seed, m, d } = initSigArgs(msgHash, privKey, opts.extraEntropy);
1590
- let sig;
1591
- const drbg = new HmacDrbg();
1679
+ const drbg = new HmacDrbg(hashLen, groupLen);
1592
1680
  drbg.reseedSync(seed);
1593
- while (!(sig = kmdToSig(drbg.generateSync(), m, d)))
1681
+ let sig;
1682
+ while (!(sig = kmdToSig(drbg.generateSync(), m, d, opts.canonical)))
1594
1683
  drbg.reseedSync();
1595
1684
  return finalizeSig(sig, opts);
1596
1685
  }
@@ -1627,12 +1716,9 @@ function verify(signature, msgHash, publicKey, opts = vopts) {
1627
1716
  return v === r;
1628
1717
  }
1629
1718
  exports.verify = verify;
1630
- function finalizeSchnorrChallenge(ch) {
1719
+ function schnorrChallengeFinalize(ch) {
1631
1720
  return mod(bytesToNumber(ch), CURVE.n);
1632
1721
  }
1633
- function hasEvenY(point) {
1634
- return (point.y & _1n) === _0n;
1635
- }
1636
1722
  class SchnorrSignature {
1637
1723
  constructor(r, s) {
1638
1724
  this.r = r;
@@ -1662,55 +1748,67 @@ class SchnorrSignature {
1662
1748
  function schnorrGetPublicKey(privateKey) {
1663
1749
  return Point.fromPrivateKey(privateKey).toRawX();
1664
1750
  }
1665
- function initSchnorrSigArgs(message, privateKey, auxRand) {
1666
- if (message == null)
1667
- throw new TypeError(`sign: Expected valid message, not "${message}"`);
1668
- const m = ensureBytes(message);
1669
- const d0 = normalizePrivateKey(privateKey);
1670
- const rand = ensureBytes(auxRand);
1671
- if (rand.length !== 32)
1672
- throw new TypeError('sign: Expected 32 bytes of aux randomness');
1673
- const P = Point.fromPrivateKey(d0);
1674
- const px = P.toRawX();
1675
- const d = hasEvenY(P) ? d0 : CURVE.n - d0;
1676
- return { m, P, px, d, rand };
1677
- }
1678
- function initSchnorrNonce(d, t0h) {
1679
- return numTo32b(d ^ bytesToNumber(t0h));
1680
- }
1681
- function finalizeSchnorrNonce(k0h) {
1682
- const k0 = mod(bytesToNumber(k0h), CURVE.n);
1683
- if (k0 === _0n)
1684
- throw new Error('sign: Creation of signature failed. k is zero');
1685
- const R = Point.fromPrivateKey(k0);
1686
- const rx = R.toRawX();
1687
- const k = hasEvenY(R) ? k0 : CURVE.n - k0;
1688
- return { R, rx, k };
1689
- }
1690
- function finalizeSchnorrSig(R, k, e, d) {
1691
- return new SchnorrSignature(R.x, mod(k + e * d, CURVE.n)).toRawBytes();
1692
- }
1693
- async function schnorrSign(message, privateKey, auxRand = exports.utils.randomBytes()) {
1694
- const { m, px, d, rand } = initSchnorrSigArgs(message, privateKey, auxRand);
1695
- const t = initSchnorrNonce(d, await exports.utils.taggedHash(TAGS.aux, rand));
1696
- const { R, rx, k } = finalizeSchnorrNonce(await exports.utils.taggedHash(TAGS.nonce, t, px, m));
1697
- const e = finalizeSchnorrChallenge(await exports.utils.taggedHash(TAGS.challenge, rx, px, m));
1698
- const sig = finalizeSchnorrSig(R, k, e, d);
1699
- const isValid = await schnorrVerify(sig, m, px);
1700
- if (!isValid)
1751
+ class InternalSchnorrSignature {
1752
+ constructor(message, privateKey, auxRand = exports.utils.randomBytes()) {
1753
+ if (message == null)
1754
+ throw new TypeError(`sign: Expected valid message, not "${message}"`);
1755
+ this.m = ensureBytes(message);
1756
+ const { x, scalar } = this.getScalar(normalizePrivateKey(privateKey));
1757
+ this.px = x;
1758
+ this.d = scalar;
1759
+ this.rand = ensureBytes(auxRand);
1760
+ if (this.rand.length !== 32)
1761
+ throw new TypeError('sign: Expected 32 bytes of aux randomness');
1762
+ }
1763
+ getScalar(priv) {
1764
+ const point = Point.fromPrivateKey(priv);
1765
+ const scalar = point.hasEvenY() ? priv : CURVE.n - priv;
1766
+ return { point, scalar, x: point.toRawX() };
1767
+ }
1768
+ initNonce(d, t0h) {
1769
+ return numTo32b(d ^ bytesToNumber(t0h));
1770
+ }
1771
+ finalizeNonce(k0h) {
1772
+ const k0 = mod(bytesToNumber(k0h), CURVE.n);
1773
+ if (k0 === _0n)
1774
+ throw new Error('sign: Creation of signature failed. k is zero');
1775
+ const { point: R, x: rx, scalar: k } = this.getScalar(k0);
1776
+ return { R, rx, k };
1777
+ }
1778
+ finalizeSig(R, k, e, d) {
1779
+ return new SchnorrSignature(R.x, mod(k + e * d, CURVE.n)).toRawBytes();
1780
+ }
1781
+ error() {
1701
1782
  throw new Error('sign: Invalid signature produced');
1702
- return sig;
1783
+ }
1784
+ async calc() {
1785
+ const { m, d, px, rand } = this;
1786
+ const tag = exports.utils.taggedHash;
1787
+ const t = this.initNonce(d, await tag(TAGS.aux, rand));
1788
+ const { R, rx, k } = this.finalizeNonce(await tag(TAGS.nonce, t, px, m));
1789
+ const e = schnorrChallengeFinalize(await tag(TAGS.challenge, rx, px, m));
1790
+ const sig = this.finalizeSig(R, k, e, d);
1791
+ if (!(await schnorrVerify(sig, m, px)))
1792
+ this.error();
1793
+ return sig;
1794
+ }
1795
+ calcSync() {
1796
+ const { m, d, px, rand } = this;
1797
+ const tag = exports.utils.taggedHashSync;
1798
+ const t = this.initNonce(d, tag(TAGS.aux, rand));
1799
+ const { R, rx, k } = this.finalizeNonce(tag(TAGS.nonce, t, px, m));
1800
+ const e = schnorrChallengeFinalize(tag(TAGS.challenge, rx, px, m));
1801
+ const sig = this.finalizeSig(R, k, e, d);
1802
+ if (!schnorrVerifySync(sig, m, px))
1803
+ this.error();
1804
+ return sig;
1805
+ }
1703
1806
  }
1704
- function schnorrSignSync(message, privateKey, auxRand = exports.utils.randomBytes()) {
1705
- const { m, px, d, rand } = initSchnorrSigArgs(message, privateKey, auxRand);
1706
- const t = initSchnorrNonce(d, exports.utils.taggedHashSync(TAGS.aux, rand));
1707
- const { R, rx, k } = finalizeSchnorrNonce(exports.utils.taggedHashSync(TAGS.nonce, t, px, m));
1708
- const e = finalizeSchnorrChallenge(exports.utils.taggedHashSync(TAGS.challenge, rx, px, m));
1709
- const sig = finalizeSchnorrSig(R, k, e, d);
1710
- const isValid = schnorrVerifySync(sig, m, px);
1711
- if (!isValid)
1712
- throw new Error('sign: Invalid signature produced');
1713
- return sig;
1807
+ async function schnorrSign(msg, privKey, auxRand) {
1808
+ return new InternalSchnorrSignature(msg, privKey, auxRand).calc();
1809
+ }
1810
+ function schnorrSignSync(msg, privKey, auxRand) {
1811
+ return new InternalSchnorrSignature(msg, privKey, auxRand).calcSync();
1714
1812
  }
1715
1813
  function initSchnorrVerify(signature, message, publicKey) {
1716
1814
  const raw = signature instanceof SchnorrSignature;
@@ -1725,14 +1823,14 @@ function initSchnorrVerify(signature, message, publicKey) {
1725
1823
  }
1726
1824
  function finalizeSchnorrVerify(r, P, s, e) {
1727
1825
  const R = Point.BASE.multiplyAndAddUnsafe(P, normalizePrivateKey(s), mod(-e, CURVE.n));
1728
- if (!R || !hasEvenY(R) || R.x !== r)
1826
+ if (!R || !R.hasEvenY() || R.x !== r)
1729
1827
  return false;
1730
1828
  return true;
1731
1829
  }
1732
1830
  async function schnorrVerify(signature, message, publicKey) {
1733
1831
  try {
1734
1832
  const { r, s, m, P } = initSchnorrVerify(signature, message, publicKey);
1735
- const e = finalizeSchnorrChallenge(await exports.utils.taggedHash(TAGS.challenge, numTo32b(r), P.toRawX(), m));
1833
+ const e = schnorrChallengeFinalize(await exports.utils.taggedHash(TAGS.challenge, numTo32b(r), P.toRawX(), m));
1736
1834
  return finalizeSchnorrVerify(r, P, s, e);
1737
1835
  }
1738
1836
  catch (error) {
@@ -1742,10 +1840,12 @@ async function schnorrVerify(signature, message, publicKey) {
1742
1840
  function schnorrVerifySync(signature, message, publicKey) {
1743
1841
  try {
1744
1842
  const { r, s, m, P } = initSchnorrVerify(signature, message, publicKey);
1745
- const e = finalizeSchnorrChallenge(exports.utils.taggedHashSync(TAGS.challenge, numTo32b(r), P.toRawX(), m));
1843
+ const e = schnorrChallengeFinalize(exports.utils.taggedHashSync(TAGS.challenge, numTo32b(r), P.toRawX(), m));
1746
1844
  return finalizeSchnorrVerify(r, P, s, e);
1747
1845
  }
1748
1846
  catch (error) {
1847
+ if (error instanceof ShaError)
1848
+ throw error;
1749
1849
  return false;
1750
1850
  }
1751
1851
  }
@@ -1769,6 +1869,11 @@ const TAGS = {
1769
1869
  };
1770
1870
  const TAGGED_HASH_PREFIXES = {};
1771
1871
  exports.utils = {
1872
+ bytesToHex,
1873
+ hexToBytes,
1874
+ concatBytes,
1875
+ mod,
1876
+ invert,
1772
1877
  isValidPrivateKey(privateKey) {
1773
1878
  try {
1774
1879
  normalizePrivateKey(privateKey);
@@ -1778,32 +1883,14 @@ exports.utils = {
1778
1883
  return false;
1779
1884
  }
1780
1885
  },
1781
- privateAdd: (privateKey, tweak) => {
1782
- const p = normalizePrivateKey(privateKey);
1783
- const t = normalizePrivateKey(tweak);
1784
- return numTo32b(mod(p + t, CURVE.n));
1785
- },
1786
- privateNegate: (privateKey) => {
1787
- const p = normalizePrivateKey(privateKey);
1788
- return numTo32b(CURVE.n - p);
1789
- },
1790
- pointAddScalar: (p, tweak, isCompressed) => {
1791
- const P = Point.fromHex(p);
1792
- const t = normalizePrivateKey(tweak);
1793
- const Q = Point.BASE.multiplyAndAddUnsafe(P, t, _1n);
1794
- if (!Q)
1795
- throw new Error('Tweaked point at infinity');
1796
- return Q.toRawBytes(isCompressed);
1797
- },
1798
- pointMultiply: (p, tweak, isCompressed) => {
1799
- const P = Point.fromHex(p);
1800
- const t = bytesToNumber(ensureBytes(tweak));
1801
- return P.multiply(t).toRawBytes(isCompressed);
1802
- },
1886
+ _bigintTo32Bytes: numTo32b,
1887
+ _normalizePrivateKey: normalizePrivateKey,
1803
1888
  hashToPrivateKey: (hash) => {
1804
1889
  hash = ensureBytes(hash);
1805
- if (hash.length < 40 || hash.length > 1024)
1806
- throw new Error('Expected 40-1024 bytes of private key as per FIPS 186');
1890
+ const minLen = groupLen + 8;
1891
+ if (hash.length < minLen || hash.length > 1024) {
1892
+ throw new Error(`Expected valid bytes of private key as per FIPS 186`);
1893
+ }
1807
1894
  const num = mod(bytesToNumber(hash), CURVE.n - _1n) + _1n;
1808
1895
  return numTo32b(num);
1809
1896
  },
@@ -1819,14 +1906,13 @@ exports.utils = {
1819
1906
  throw new Error("The environment doesn't have randomBytes function");
1820
1907
  }
1821
1908
  },
1822
- randomPrivateKey: () => {
1823
- return exports.utils.hashToPrivateKey(exports.utils.randomBytes(40));
1909
+ randomPrivateKey: () => exports.utils.hashToPrivateKey(exports.utils.randomBytes(groupLen + 8)),
1910
+ precompute(windowSize = 8, point = Point.BASE) {
1911
+ const cached = point === Point.BASE ? point : new Point(point.x, point.y);
1912
+ cached._setWindowSize(windowSize);
1913
+ cached.multiply(_3n);
1914
+ return cached;
1824
1915
  },
1825
- bytesToHex,
1826
- hexToBytes,
1827
- concatBytes,
1828
- mod,
1829
- invert,
1830
1916
  sha256: async (...messages) => {
1831
1917
  if (crypto.web) {
1832
1918
  const buffer = await crypto.web.subtle.digest('SHA-256', concatBytes(...messages));
@@ -1871,23 +1957,40 @@ exports.utils = {
1871
1957
  return exports.utils.sha256(tagP, ...messages);
1872
1958
  },
1873
1959
  taggedHashSync: (tag, ...messages) => {
1874
- if (typeof exports.utils.sha256Sync !== 'function')
1875
- throw new Error('utils.sha256Sync is undefined, you need to set it');
1960
+ if (typeof _sha256Sync !== 'function')
1961
+ throw new ShaError('sha256Sync is undefined, you need to set it');
1876
1962
  let tagP = TAGGED_HASH_PREFIXES[tag];
1877
1963
  if (tagP === undefined) {
1878
- const tagH = exports.utils.sha256Sync(Uint8Array.from(tag, (c) => c.charCodeAt(0)));
1964
+ const tagH = _sha256Sync(Uint8Array.from(tag, (c) => c.charCodeAt(0)));
1879
1965
  tagP = concatBytes(tagH, tagH);
1880
1966
  TAGGED_HASH_PREFIXES[tag] = tagP;
1881
1967
  }
1882
- return exports.utils.sha256Sync(tagP, ...messages);
1883
- },
1884
- precompute(windowSize = 8, point = Point.BASE) {
1885
- const cached = point === Point.BASE ? point : new Point(point.x, point.y);
1886
- cached._setWindowSize(windowSize);
1887
- cached.multiply(_3n);
1888
- return cached;
1968
+ return _sha256Sync(tagP, ...messages);
1889
1969
  },
1970
+ _JacobianPoint: JacobianPoint,
1890
1971
  };
1972
+ Object.defineProperties(exports.utils, {
1973
+ sha256Sync: {
1974
+ configurable: false,
1975
+ get() {
1976
+ return _sha256Sync;
1977
+ },
1978
+ set(val) {
1979
+ if (!_sha256Sync)
1980
+ _sha256Sync = val;
1981
+ },
1982
+ },
1983
+ hmacSha256Sync: {
1984
+ configurable: false,
1985
+ get() {
1986
+ return _hmacSha256Sync;
1987
+ },
1988
+ set(val) {
1989
+ if (!_hmacSha256Sync)
1990
+ _hmacSha256Sync = val;
1991
+ },
1992
+ },
1993
+ });
1891
1994
 
1892
1995
 
1893
1996
  /***/ }),
@@ -15013,13 +15116,21 @@ var Enum = __webpack_require__(7025),
15013
15116
  * @ignore
15014
15117
  */
15015
15118
  function genValuePartial_fromObject(gen, field, fieldIndex, prop) {
15119
+ var defaultAlreadyEmitted = false;
15016
15120
  /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */
15017
15121
  if (field.resolvedType) {
15018
15122
  if (field.resolvedType instanceof Enum) { gen
15019
15123
  ("switch(d%s){", prop);
15020
15124
  for (var values = field.resolvedType.values, keys = Object.keys(values), i = 0; i < keys.length; ++i) {
15021
- if (field.repeated && values[keys[i]] === field.typeDefault) gen
15022
- ("default:");
15125
+ // enum unknown values passthrough
15126
+ if (values[keys[i]] === field.typeDefault && !defaultAlreadyEmitted) { gen
15127
+ ("default:")
15128
+ ("if(typeof(d%s)===\"number\"){m%s=d%s;break}", prop, prop, prop);
15129
+ if (!field.repeated) gen // fallback to default value only for
15130
+ // arrays, to avoid leaving holes.
15131
+ ("break"); // for non-repeated fields, just ignore
15132
+ defaultAlreadyEmitted = true;
15133
+ }
15023
15134
  gen
15024
15135
  ("case%j:", keys[i])
15025
15136
  ("case %i:", values[keys[i]])
@@ -15151,7 +15262,7 @@ function genValuePartial_toObject(gen, field, fieldIndex, prop) {
15151
15262
  /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */
15152
15263
  if (field.resolvedType) {
15153
15264
  if (field.resolvedType instanceof Enum) gen
15154
- ("d%s=o.enums===String?types[%i].values[m%s]:m%s", prop, fieldIndex, prop, prop);
15265
+ ("d%s=o.enums===String?(types[%i].values[m%s]===undefined?m%s:types[%i].values[m%s]):m%s", prop, fieldIndex, prop, prop, fieldIndex, prop, prop);
15155
15266
  else gen
15156
15267
  ("d%s=types[%i].toObject(m%s,o)", prop, fieldIndex, prop);
15157
15268
  } else {
@@ -15559,8 +15670,9 @@ var Namespace = __webpack_require__(9313),
15559
15670
  * @param {Object.<string,*>} [options] Declared options
15560
15671
  * @param {string} [comment] The comment for this enum
15561
15672
  * @param {Object.<string,string>} [comments] The value comments for this enum
15673
+ * @param {Object.<string,Object<string,*>>|undefined} [valuesOptions] The value options for this enum
15562
15674
  */
15563
- function Enum(name, values, options, comment, comments) {
15675
+ function Enum(name, values, options, comment, comments, valuesOptions) {
15564
15676
  ReflectionObject.call(this, name, options);
15565
15677
 
15566
15678
  if (values && typeof values !== "object")
@@ -15590,6 +15702,12 @@ function Enum(name, values, options, comment, comments) {
15590
15702
  */
15591
15703
  this.comments = comments || {};
15592
15704
 
15705
+ /**
15706
+ * Values options, if any
15707
+ * @type {Object<string, Object<string, *>>|undefined}
15708
+ */
15709
+ this.valuesOptions = valuesOptions;
15710
+
15593
15711
  /**
15594
15712
  * Reserved ranges, if any.
15595
15713
  * @type {Array.<number[]|string>}
@@ -15634,11 +15752,12 @@ Enum.fromJSON = function fromJSON(name, json) {
15634
15752
  Enum.prototype.toJSON = function toJSON(toJSONOptions) {
15635
15753
  var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;
15636
15754
  return util.toObject([
15637
- "options" , this.options,
15638
- "values" , this.values,
15639
- "reserved" , this.reserved && this.reserved.length ? this.reserved : undefined,
15640
- "comment" , keepComments ? this.comment : undefined,
15641
- "comments" , keepComments ? this.comments : undefined
15755
+ "options" , this.options,
15756
+ "valuesOptions" , this.valuesOptions,
15757
+ "values" , this.values,
15758
+ "reserved" , this.reserved && this.reserved.length ? this.reserved : undefined,
15759
+ "comment" , keepComments ? this.comment : undefined,
15760
+ "comments" , keepComments ? this.comments : undefined
15642
15761
  ]);
15643
15762
  };
15644
15763
 
@@ -15647,11 +15766,12 @@ Enum.prototype.toJSON = function toJSON(toJSONOptions) {
15647
15766
  * @param {string} name Value name
15648
15767
  * @param {number} id Value id
15649
15768
  * @param {string} [comment] Comment, if any
15769
+ * @param {Object.<string, *>|undefined} [options] Options, if any
15650
15770
  * @returns {Enum} `this`
15651
15771
  * @throws {TypeError} If arguments are invalid
15652
15772
  * @throws {Error} If there is already a value with this name or id
15653
15773
  */
15654
- Enum.prototype.add = function add(name, id, comment) {
15774
+ Enum.prototype.add = function add(name, id, comment, options) {
15655
15775
  // utilized by the parser but not by .fromJSON
15656
15776
 
15657
15777
  if (!util.isString(name))
@@ -15676,6 +15796,12 @@ Enum.prototype.add = function add(name, id, comment) {
15676
15796
  } else
15677
15797
  this.valuesById[this.values[name] = id] = name;
15678
15798
 
15799
+ if (options) {
15800
+ if (this.valuesOptions === undefined)
15801
+ this.valuesOptions = {};
15802
+ this.valuesOptions[name] = options || null;
15803
+ }
15804
+
15679
15805
  this.comments[name] = comment || null;
15680
15806
  return this;
15681
15807
  };
@@ -15699,6 +15825,8 @@ Enum.prototype.remove = function remove(name) {
15699
15825
  delete this.valuesById[val];
15700
15826
  delete this.values[name];
15701
15827
  delete this.comments[name];
15828
+ if (this.valuesOptions)
15829
+ delete this.valuesOptions[name];
15702
15830
 
15703
15831
  return this;
15704
15832
  };
@@ -16745,7 +16873,8 @@ var ReflectionObject = __webpack_require__(3243);
16745
16873
  ((Namespace.prototype = Object.create(ReflectionObject.prototype)).constructor = Namespace).className = "Namespace";
16746
16874
 
16747
16875
  var Field = __webpack_require__(3548),
16748
- util = __webpack_require__(9935);
16876
+ util = __webpack_require__(9935),
16877
+ OneOf = __webpack_require__(7598);
16749
16878
 
16750
16879
  var Type, // cyclic
16751
16880
  Service,
@@ -16881,9 +17010,8 @@ Object.defineProperty(Namespace.prototype, "nestedArray", {
16881
17010
  /**
16882
17011
  * Any nested object descriptor.
16883
17012
  * @typedef AnyNestedObject
16884
- * @type {IEnum|IType|IService|AnyExtensionField|INamespace}
17013
+ * @type {IEnum|IType|IService|AnyExtensionField|INamespace|IOneOf}
16885
17014
  */
16886
- // ^ BEWARE: VSCode hangs forever when using more than 5 types (that's why AnyExtensionField exists in the first place)
16887
17015
 
16888
17016
  /**
16889
17017
  * Converts this namespace to a namespace descriptor.
@@ -16956,7 +17084,7 @@ Namespace.prototype.getEnum = function getEnum(name) {
16956
17084
  */
16957
17085
  Namespace.prototype.add = function add(object) {
16958
17086
 
16959
- if (!(object instanceof Field && object.extend !== undefined || object instanceof Type || object instanceof Enum || object instanceof Service || object instanceof Namespace))
17087
+ if (!(object instanceof Field && object.extend !== undefined || object instanceof Type || object instanceof OneOf || object instanceof Enum || object instanceof Service || object instanceof Namespace))
16960
17088
  throw TypeError("object must be a valid nested object");
16961
17089
 
16962
17090
  if (!this.nested)
@@ -18002,6 +18130,16 @@ function parse(source, root, options) {
18002
18130
  parseGroup(parent, rule);
18003
18131
  return;
18004
18132
  }
18133
+ // Type names can consume multiple tokens, in multiple variants:
18134
+ // package.subpackage field tokens: "package.subpackage" [TYPE NAME ENDS HERE] "field"
18135
+ // package . subpackage field tokens: "package" "." "subpackage" [TYPE NAME ENDS HERE] "field"
18136
+ // package. subpackage field tokens: "package." "subpackage" [TYPE NAME ENDS HERE] "field"
18137
+ // package .subpackage field tokens: "package" ".subpackage" [TYPE NAME ENDS HERE] "field"
18138
+ // Keep reading tokens until we get a type name with no period at the end,
18139
+ // and the next token does not start with a period.
18140
+ while (type.endsWith(".") || peek().startsWith(".")) {
18141
+ type += next();
18142
+ }
18005
18143
 
18006
18144
  /* istanbul ignore if */
18007
18145
  if (!typeRefRe.test(type))
@@ -18085,6 +18223,14 @@ function parse(source, root, options) {
18085
18223
  }
18086
18224
  break;
18087
18225
 
18226
+ case "message":
18227
+ parseType(type, token);
18228
+ break;
18229
+
18230
+ case "enum":
18231
+ parseEnum(type, token);
18232
+ break;
18233
+
18088
18234
  /* istanbul ignore next */
18089
18235
  default:
18090
18236
  throw illegal(token); // there are no groups with proto3 semantics
@@ -18185,7 +18331,14 @@ function parse(source, root, options) {
18185
18331
 
18186
18332
  skip("=");
18187
18333
  var value = parseId(next(), true),
18188
- dummy = {};
18334
+ dummy = {
18335
+ options: undefined
18336
+ };
18337
+ dummy.setOption = function(name, value) {
18338
+ if (this.options === undefined)
18339
+ this.options = {};
18340
+ this.options[name] = value;
18341
+ };
18189
18342
  ifBlock(dummy, function parseEnumValue_block(token) {
18190
18343
 
18191
18344
  /* istanbul ignore else */
@@ -18198,7 +18351,7 @@ function parse(source, root, options) {
18198
18351
  }, function parseEnumValue_line() {
18199
18352
  parseInlineOptions(dummy); // skip
18200
18353
  });
18201
- parent.add(token, value, dummy.comment);
18354
+ parent.add(token, value, dummy.comment, dummy.options);
18202
18355
  }
18203
18356
 
18204
18357
  function parseOption(parent, token) {
@@ -19117,6 +19270,7 @@ Root.prototype.load = function load(filename, options, callback) {
19117
19270
 
19118
19271
  // Fetches a single file
19119
19272
  function fetch(filename, weak) {
19273
+ filename = getBundledFileName(filename) || filename;
19120
19274
 
19121
19275
  // Skip if already loaded / attempted
19122
19276
  if (self.files.indexOf(filename) > -1)
@@ -19245,6 +19399,10 @@ function tryHandleExtension(root, field) {
19245
19399
  var extendedType = field.parent.lookup(field.extend);
19246
19400
  if (extendedType) {
19247
19401
  var sisterField = new Field(field.fullName, field.id, field.type, field.rule, undefined, field.options);
19402
+ //do not allow to extend same field twice to prevent the error
19403
+ if (extendedType.get(sisterField.name)) {
19404
+ return true;
19405
+ }
19248
19406
  sisterField.declaringField = field;
19249
19407
  field.extensionField = sisterField;
19250
19408
  extendedType.add(sisterField);
@@ -21141,7 +21299,7 @@ util.decorateEnum = function decorateEnum(object) {
21141
21299
  util.setProperty = function setProperty(dst, path, value) {
21142
21300
  function setProp(dst, path, value) {
21143
21301
  var part = path.shift();
21144
- if (part === "__proto__") {
21302
+ if (part === "__proto__" || part === "prototype") {
21145
21303
  return dst;
21146
21304
  }
21147
21305
  if (path.length > 0) {
@@ -21179,7 +21337,7 @@ Object.defineProperty(util, "decorateRoot", {
21179
21337
 
21180
21338
  /***/ }),
21181
21339
 
21182
- /***/ 1945:
21340
+ /***/ 2630:
21183
21341
  /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
21184
21342
 
21185
21343
  "use strict";
@@ -21416,7 +21574,7 @@ util.utf8 = __webpack_require__(4997);
21416
21574
  util.pool = __webpack_require__(6662);
21417
21575
 
21418
21576
  // utility to work with the low and high bits of a 64 bit value
21419
- util.LongBits = __webpack_require__(1945);
21577
+ util.LongBits = __webpack_require__(2630);
21420
21578
 
21421
21579
  /**
21422
21580
  * Whether running within node or not.
@@ -21681,7 +21839,7 @@ function newError(name) {
21681
21839
  configurable: true,
21682
21840
  },
21683
21841
  name: {
21684
- get() { return name; },
21842
+ get: function get() { return name; },
21685
21843
  set: undefined,
21686
21844
  enumerable: false,
21687
21845
  // configurable: false would accurately preserve the behavior of
@@ -21691,7 +21849,7 @@ function newError(name) {
21691
21849
  configurable: true,
21692
21850
  },
21693
21851
  toString: {
21694
- value() { return this.name + ": " + this.message; },
21852
+ value: function value() { return this.name + ": " + this.message; },
21695
21853
  writable: true,
21696
21854
  enumerable: false,
21697
21855
  configurable: true,