solid-ui 2.4.27-8924ae81 → 2.4.27-8b9aa479

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/solid-ui.js CHANGED
@@ -2593,6 +2593,8 @@ var _solidLogic = __webpack_require__(/*! solid-logic */ "./node_modules/solid-l
2593
2593
  var ns = _interopRequireWildcard(__webpack_require__(/*! ../ns */ "./lib/ns.js"));
2594
2594
  var $rdf = _interopRequireWildcard(__webpack_require__(/*! rdflib */ "./node_modules/rdflib/esm/index.js"));
2595
2595
  var utils = _interopRequireWildcard(__webpack_require__(/*! ../utils */ "./lib/utils/index.js"));
2596
+ var _signature = __webpack_require__(/*! ./signature */ "./lib/chat/signature.js");
2597
+ var _keys = __webpack_require__(/*! ./keys */ "./lib/chat/keys.js");
2596
2598
  function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
2597
2599
  function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
2598
2600
  /**
@@ -2653,7 +2655,7 @@ var ChatChannel = /*#__PURE__*/function () {
2653
2655
  var oldMsg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
2654
2656
  var deleteIt = arguments.length > 2 ? arguments[2] : undefined;
2655
2657
  return /*#__PURE__*/_regenerator["default"].mark(function _callee2() {
2656
- var sts, now, timestamp, dateStamp, chatDocument, message, me, msg;
2658
+ var sts, now, timestamp, dateStamp, chatDocument, message, me, msg, privateKey, errMsg;
2657
2659
  return _regenerator["default"].wrap(function _callee2$(_context2) {
2658
2660
  while (1) switch (_context2.prev = _context2.next) {
2659
2661
  case 0:
@@ -2664,41 +2666,57 @@ var ChatChannel = /*#__PURE__*/function () {
2664
2666
  chatDocument = oldMsg ? oldMsg.doc() : _this.dateFolder.leafDocumentFromDate(now);
2665
2667
  message = _solidLogic.store.sym(chatDocument.uri + '#' + 'Msg' + timestamp); // const content = store.literal(text)
2666
2668
  me = _solidLogic.authn.currentUser(); // If already logged on
2669
+ msg = _signature.getBlankMsg;
2670
+ msg.id = message;
2667
2671
  if (oldMsg) {
2668
2672
  // edit message replaces old one
2669
2673
  sts.push($rdf.st(mostRecentVersion(oldMsg), ns.dct('isReplacedBy'), message, chatDocument));
2674
+ // do we need to rebuild oldMsg signaturen ?
2670
2675
  if (deleteIt) {
2671
2676
  sts.push($rdf.st(message, ns.schema('dateDeleted'), dateStamp, chatDocument));
2677
+ msg.dateDeleted = dateStamp;
2672
2678
  }
2673
2679
  } else {
2674
2680
  // link new message to channel
2675
2681
  sts.push($rdf.st(_this.channel, ns.wf('message'), message, chatDocument));
2676
2682
  }
2677
2683
  sts.push($rdf.st(message, ns.sioc('content'), _solidLogic.store.literal(text), chatDocument));
2684
+ msg.content = text;
2678
2685
  sts.push($rdf.st(message, ns.dct('created'), dateStamp, chatDocument));
2679
- if (me) {
2680
- sts.push($rdf.st(message, ns.foaf('maker'), me, chatDocument));
2686
+ msg.created = dateStamp;
2687
+ if (!me) {
2688
+ _context2.next = 21;
2689
+ break;
2681
2690
  }
2682
- _context2.prev = 11;
2683
- _context2.next = 14;
2691
+ sts.push($rdf.st(message, ns.foaf('maker'), me, chatDocument));
2692
+ msg.maker = me;
2693
+ // privateKey the cached private key of me, cache should be deleted after a certain time
2694
+ _context2.next = 19;
2695
+ return (0, _keys.getPrivateKey)(me);
2696
+ case 19:
2697
+ privateKey = _context2.sent;
2698
+ sts.push($rdf.st(message, $rdf.sym("".concat(_signature.SEC, "Proof")), $rdf.sym((0, _signature.signMsg)(msg, privateKey), chatDocument)));
2699
+ case 21:
2700
+ _context2.prev = 21;
2701
+ _context2.next = 24;
2684
2702
  return _solidLogic.store.updater.update([], sts);
2685
- case 14:
2686
- _context2.next = 22;
2703
+ case 24:
2704
+ _context2.next = 32;
2687
2705
  break;
2688
- case 16:
2689
- _context2.prev = 16;
2690
- _context2.t0 = _context2["catch"](11);
2691
- msg = 'Error saving chat message: ' + _context2.t0;
2692
- debug.warn(msg);
2693
- alert(msg);
2694
- throw new Error(msg);
2695
- case 22:
2706
+ case 26:
2707
+ _context2.prev = 26;
2708
+ _context2.t0 = _context2["catch"](21);
2709
+ errMsg = 'Error saving chat message: ' + _context2.t0;
2710
+ debug.warn(errMsg);
2711
+ alert(errMsg);
2712
+ throw new Error(errMsg);
2713
+ case 32:
2696
2714
  return _context2.abrupt("return", message);
2697
- case 23:
2715
+ case 33:
2698
2716
  case "end":
2699
2717
  return _context2.stop();
2700
2718
  }
2701
- }, _callee2, null, [[11, 16]]);
2719
+ }, _callee2, null, [[21, 26]]);
2702
2720
  })();
2703
2721
  });
2704
2722
  function updateMessage(_x2) {
@@ -3973,6 +3991,104 @@ function _infiniteMessageArea() {
3973
3991
 
3974
3992
  /***/ }),
3975
3993
 
3994
+ /***/ "./lib/chat/keys.js":
3995
+ /*!**************************!*\
3996
+ !*** ./lib/chat/keys.js ***!
3997
+ \**************************/
3998
+ /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3999
+
4000
+ "use strict";
4001
+
4002
+
4003
+ var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js");
4004
+ var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js");
4005
+ Object.defineProperty(exports, "__esModule", ({
4006
+ value: true
4007
+ }));
4008
+ exports.generatePrivateKey = generatePrivateKey;
4009
+ exports.generatePublicKey = generatePublicKey;
4010
+ exports.getPrivateKey = getPrivateKey;
4011
+ exports.getPublicKey = getPublicKey;
4012
+ var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js"));
4013
+ var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js"));
4014
+ var _secp256k = __webpack_require__(/*! @noble/curves/secp256k1 */ "./node_modules/@noble/curves/secp256k1.js");
4015
+ var _utils = __webpack_require__(/*! @noble/hashes/utils */ "./node_modules/@noble/hashes/utils.js");
4016
+ var _signature = __webpack_require__(/*! ./signature */ "./lib/chat/signature.js");
4017
+ var _solidLogic = __webpack_require__(/*! solid-logic */ "./node_modules/solid-logic/lib/index.js");
4018
+ var $rdf = _interopRequireWildcard(__webpack_require__(/*! rdflib */ "./node_modules/rdflib/esm/index.js"));
4019
+ function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
4020
+ function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
4021
+ function generatePrivateKey() {
4022
+ return (0, _utils.bytesToHex)(_secp256k.schnorr.utils.randomPrivateKey());
4023
+ }
4024
+ function generatePublicKey(privateKey) {
4025
+ return (0, _utils.bytesToHex)(_secp256k.schnorr.getPublicKey(privateKey));
4026
+ }
4027
+ function getPublicKey(webId) {
4028
+ // find publickey
4029
+ /* const url = new URL(webId)
4030
+ url.hash = ''
4031
+ store.fetcher.load(url.href)
4032
+ let publicKey = store.any(store.sym(webId), store.sym(CERT +'publicKey')) */
4033
+ var publicKey = publicKeyExists(webId);
4034
+ return publicKey === null || publicKey === void 0 ? void 0 : publicKey.uri;
4035
+ }
4036
+ function publicKeyExists(webId) {
4037
+ // find publickey
4038
+ var url = new URL(webId);
4039
+ url.hash = '';
4040
+ _solidLogic.store.fetcher.load(url.href);
4041
+ var publicKey = _solidLogic.store.any(_solidLogic.store.sym(webId), _solidLogic.store.sym(_signature.CERT + 'publicKey'));
4042
+ return publicKey;
4043
+ }
4044
+ function privateKeyExists(webId) {
4045
+ var url = new URL(webId);
4046
+ var privateKeyUrl = url.hostname + '/profile/privateKey.ttl';
4047
+ _solidLogic.store.fetcher.load(privateKeyUrl);
4048
+ var privateKey = _solidLogic.store.any(_solidLogic.store.sym(webId), _solidLogic.store.sym(_signature.CERT + 'privateKey'));
4049
+ return privateKey;
4050
+ }
4051
+ function getPrivateKey(_x) {
4052
+ return _getPrivateKey.apply(this, arguments);
4053
+ }
4054
+ function _getPrivateKey() {
4055
+ _getPrivateKey = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(webId) {
4056
+ var url, privateKeyUrl, publicKey, privateKey, del, add;
4057
+ return _regenerator["default"].wrap(function _callee$(_context) {
4058
+ while (1) switch (_context.prev = _context.next) {
4059
+ case 0:
4060
+ url = new URL(webId);
4061
+ privateKeyUrl = url.hostname + '/profile/privateKey.ttl'; // find publickey
4062
+ publicKey = publicKeyExists(webId); // find privateKey
4063
+ privateKey = privateKeyExists(webId); // create key pair
4064
+ if (!(!privateKey || !publicKey)) {
4065
+ _context.next = 15;
4066
+ break;
4067
+ }
4068
+ del = [];
4069
+ add = [];
4070
+ if (privateKey) del.push($rdf.st($rdf.sym(webId), $rdf.sym(_signature.CERT + 'privateKey'), privateKey, $rdf.sym(privateKeyUrl)));
4071
+ if (publicKey) del.push($rdf.st($rdf.sym(webId), $rdf.sym(_signature.CERT + 'publicKey'), publicKey, $rdf.sym(url.href)));
4072
+ privateKey = _solidLogic.store.sym(generatePrivateKey());
4073
+ publicKey = _solidLogic.store.sym(generatePublicKey(privateKey.uri));
4074
+ add.push($rdf.st($rdf.sym(webId), $rdf.sym(_signature.CERT + 'privateKey'), $rdf.literal(privateKey.uri), $rdf.sym(privateKeyUrl)));
4075
+ add.push($rdf.st($rdf.sym(webId), $rdf.sym(_signature.CERT + 'publicKey'), $rdf.literal(publicKey.uri), $rdf.sym(url.href)));
4076
+ _context.next = 15;
4077
+ return _solidLogic.store.updater.updateMany(del, add);
4078
+ case 15:
4079
+ return _context.abrupt("return", privateKey.uri);
4080
+ case 16:
4081
+ case "end":
4082
+ return _context.stop();
4083
+ }
4084
+ }, _callee);
4085
+ }));
4086
+ return _getPrivateKey.apply(this, arguments);
4087
+ }
4088
+ //# sourceMappingURL=keys.js.map
4089
+
4090
+ /***/ }),
4091
+
3976
4092
  /***/ "./lib/chat/message.js":
3977
4093
  /*!*****************************!*\
3978
4094
  !*** ./lib/chat/message.js ***!
@@ -4009,6 +4125,8 @@ var pad = _interopRequireWildcard(__webpack_require__(/*! ../pad */ "./lib/pad.j
4009
4125
  var style = _interopRequireWildcard(__webpack_require__(/*! ../style */ "./lib/style.js"));
4010
4126
  var utils = _interopRequireWildcard(__webpack_require__(/*! ../utils */ "./lib/utils/index.js"));
4011
4127
  var widgets = _interopRequireWildcard(__webpack_require__(/*! ../widgets */ "./lib/widgets/index.js"));
4128
+ var _signature = __webpack_require__(/*! ./signature */ "./lib/chat/signature.js");
4129
+ var _keys = __webpack_require__(/*! ./keys */ "./lib/chat/keys.js");
4012
4130
  function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
4013
4131
  function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
4014
4132
  function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }
@@ -4096,6 +4214,20 @@ function renderMessageRow(channelObject, message, fresh, options, userContext) {
4096
4214
  var date = _solidLogic.store.any(message, ns.dct('created'));
4097
4215
  var latestVersion = (0, _chatLogic.mostRecentVersion)(message);
4098
4216
  var content = _solidLogic.store.any(latestVersion, ns.sioc('content'));
4217
+ var signature = _solidLogic.store.any(message, $rdf.sym("".concat(_signature.SEC, "Proof")));
4218
+
4219
+ // verify signature
4220
+ var msg = (0, _signature.getBlankMsg)();
4221
+ msg.id = message;
4222
+ msg.created = date;
4223
+ // this is not correct.
4224
+ // If the message has been edited/deleted we must verify the latest message and may be the intermediate ones
4225
+ msg.content = content;
4226
+ msg.maker = creator;
4227
+
4228
+ // pubKey could be store in a cache for all makers
4229
+ var pubKey = (0, _keys.getPublicKey)(creator); // alain no
4230
+ if (!(0, _signature.verifySignature)(signature, msg, pubKey)) throw new Error();
4099
4231
  var originalMessage = (0, _chatLogic.originalVersion)(message);
4100
4232
  var edited = !message.sameTerm(originalMessage);
4101
4233
  var sortDate = _solidLogic.store.the(originalMessage, ns.dct('created'), null, originalMessage.doc()); // In message
@@ -4876,6 +5008,126 @@ function messageToolbar(message, messageRow, userContext, channelObject) {
4876
5008
 
4877
5009
  /***/ }),
4878
5010
 
5011
+ /***/ "./lib/chat/signature.js":
5012
+ /*!*******************************!*\
5013
+ !*** ./lib/chat/signature.js ***!
5014
+ \*******************************/
5015
+ /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
5016
+
5017
+ "use strict";
5018
+
5019
+
5020
+ Object.defineProperty(exports, "__esModule", ({
5021
+ value: true
5022
+ }));
5023
+ exports.SEC = exports.CERT = void 0;
5024
+ exports.finishMsg = finishMsg;
5025
+ exports.getBlankMsg = getBlankMsg;
5026
+ exports.getMsgHash = getMsgHash;
5027
+ exports.serializeMsg = serializeMsg;
5028
+ exports.signMsg = signMsg;
5029
+ exports.utf8Encoder = exports.utf8Decoder = void 0;
5030
+ exports.validateMsg = validateMsg;
5031
+ exports.verifySignature = verifySignature;
5032
+ var _secp256k = __webpack_require__(/*! @noble/curves/secp256k1 */ "./node_modules/@noble/curves/secp256k1.js");
5033
+ var _sha = __webpack_require__(/*! @noble/hashes/sha256 */ "./node_modules/@noble/hashes/sha256.js");
5034
+ var _utils = __webpack_require__(/*! @noble/hashes/utils */ "./node_modules/@noble/hashes/utils.js");
5035
+ // import {utf8Encoder} from './utils'
5036
+ // import { getPublicKey } from './keys'
5037
+
5038
+ var utf8Decoder = new TextDecoder('utf-8');
5039
+ exports.utf8Decoder = utf8Decoder;
5040
+ var utf8Encoder = new TextEncoder();
5041
+ exports.utf8Encoder = utf8Encoder;
5042
+ var SEC = 'https://w3id.org/security#'; // Proof, VerificationMethod
5043
+ exports.SEC = SEC;
5044
+ var CERT = 'http://www.w3.org/ns/auth/cert#'; // PrivatKey, PublicKey
5045
+
5046
+ /* eslint-disable no-unused-vars */
5047
+ /* export enum Kind {
5048
+ Metadata = 0,
5049
+ Text = 1,
5050
+ RecommendRelay = 2,
5051
+ Contacts = 3,
5052
+ EncryptedDirectMessage = 4,
5053
+ EventDeletion = 5,
5054
+ Reaction = 7,
5055
+ BadgeAward = 8,
5056
+ ChannelCreation = 40,
5057
+ ChannelMetadata = 41,
5058
+ ChannelMessage = 42,
5059
+ ChannelHideMessage = 43,
5060
+ ChannelMuteUser = 44,
5061
+ Report = 1984,
5062
+ ZapRequest = 9734,
5063
+ Zap = 9735,
5064
+ RelayList = 10002,
5065
+ ClientAuth = 22242,
5066
+ BadgeDefinition = 30008,
5067
+ ProfileBadge = 30009,
5068
+ Article = 30023
5069
+ } */
5070
+ exports.CERT = CERT;
5071
+ function getBlankMsg() {
5072
+ return {
5073
+ id: '',
5074
+ created: '',
5075
+ dateDeleted: '',
5076
+ content: '',
5077
+ maker: '',
5078
+ sig: ''
5079
+ };
5080
+ }
5081
+ function finishMsg(t, privateKey) {
5082
+ // to update to chat message triples
5083
+ var message = t;
5084
+ // message.pubkey = getPublicKey(privateKey)
5085
+ message.id = getMsgHash(message);
5086
+ message.sig = signMsg(message, privateKey);
5087
+ return message;
5088
+ }
5089
+ function serializeMsg(msg) {
5090
+ // to update to chat messages triples
5091
+ /* if (!validateMsg(msg))
5092
+ throw new Error("can't serialize message with wrong or missing properties") */
5093
+
5094
+ return JSON.stringify(msg);
5095
+ }
5096
+ function getMsgHash(message) {
5097
+ var msgHash = (0, _sha.sha256)(utf8Encoder.encode(serializeMsg(message)));
5098
+ return (0, _utils.bytesToHex)(msgHash);
5099
+ }
5100
+ var isRecord = function isRecord(obj) {
5101
+ return obj instanceof Object;
5102
+ };
5103
+ function validateMsg(message) {
5104
+ /* if (!isRecord(message)) return false
5105
+ if (typeof message.kind !== 'number') return false
5106
+ if (typeof message.content !== 'string') return false
5107
+ if (typeof message.created_at !== 'number') return false
5108
+ if (typeof message.pubkey !== 'string') return false
5109
+ if (!message.pubkey.match(/^[a-f0-9]{64}$/)) return false
5110
+ if (!Array.isArray(message.tags)) return false
5111
+ for (let i = 0; i < message.tags.length; i++) {
5112
+ let tag = message.tags[i]
5113
+ if (!Array.isArray(tag)) return false
5114
+ for (let j = 0; j < tag.length; j++) {
5115
+ if (typeof tag[j] === 'object') return false
5116
+ }
5117
+ } */
5118
+
5119
+ return true;
5120
+ }
5121
+ function verifySignature(sig, message, pubKey) {
5122
+ return _secp256k.schnorr.verify(sig, getMsgHash(message), pubKey);
5123
+ }
5124
+ function signMsg(message, key) {
5125
+ return (0, _utils.bytesToHex)(_secp256k.schnorr.sign(getMsgHash(message), key));
5126
+ }
5127
+ //# sourceMappingURL=signature.js.map
5128
+
5129
+ /***/ }),
5130
+
4879
5131
  /***/ "./lib/create/create.js":
4880
5132
  /*!******************************!*\
4881
5133
  !*** ./lib/create/create.js ***!
@@ -12922,8 +13174,8 @@ Object.defineProperty(exports, "__esModule", ({
12922
13174
  }));
12923
13175
  exports.versionInfo = void 0;
12924
13176
  var versionInfo = {
12925
- buildTime: '2023-04-16T11:32:07Z',
12926
- commit: '8924ae81610399e968faf5b83a2f5669db70c87c',
13177
+ buildTime: '2023-04-17T20:18:01Z',
13178
+ commit: '8b9aa4797c648215f66d05ecbd2df13c4c14235b',
12927
13179
  npmInfo: {
12928
13180
  'solid-ui': '2.4.27',
12929
13181
  npm: '8.19.4',
@@ -29332,6 +29584,2962 @@ function validate(uuid) {
29332
29584
 
29333
29585
  /***/ }),
29334
29586
 
29587
+ /***/ "./node_modules/@noble/curves/_shortw_utils.js":
29588
+ /*!*****************************************************!*\
29589
+ !*** ./node_modules/@noble/curves/_shortw_utils.js ***!
29590
+ \*****************************************************/
29591
+ /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
29592
+
29593
+ "use strict";
29594
+
29595
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
29596
+ exports.createCurve = exports.getHash = void 0;
29597
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
29598
+ const hmac_1 = __webpack_require__(/*! @noble/hashes/hmac */ "./node_modules/@noble/hashes/hmac.js");
29599
+ const utils_1 = __webpack_require__(/*! @noble/hashes/utils */ "./node_modules/@noble/hashes/utils.js");
29600
+ const weierstrass_js_1 = __webpack_require__(/*! ./abstract/weierstrass.js */ "./node_modules/@noble/curves/abstract/weierstrass.js");
29601
+ // connects noble-curves to noble-hashes
29602
+ function getHash(hash) {
29603
+ return {
29604
+ hash,
29605
+ hmac: (key, ...msgs) => (0, hmac_1.hmac)(hash, key, (0, utils_1.concatBytes)(...msgs)),
29606
+ randomBytes: utils_1.randomBytes,
29607
+ };
29608
+ }
29609
+ exports.getHash = getHash;
29610
+ function createCurve(curveDef, defHash) {
29611
+ const create = (hash) => (0, weierstrass_js_1.weierstrass)({ ...curveDef, ...getHash(hash) });
29612
+ return Object.freeze({ ...create(defHash), create });
29613
+ }
29614
+ exports.createCurve = createCurve;
29615
+ //# sourceMappingURL=_shortw_utils.js.map
29616
+
29617
+ /***/ }),
29618
+
29619
+ /***/ "./node_modules/@noble/curves/abstract/curve.js":
29620
+ /*!******************************************************!*\
29621
+ !*** ./node_modules/@noble/curves/abstract/curve.js ***!
29622
+ \******************************************************/
29623
+ /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
29624
+
29625
+ "use strict";
29626
+
29627
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
29628
+ exports.validateBasic = exports.wNAF = void 0;
29629
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
29630
+ // Abelian group utilities
29631
+ const modular_js_1 = __webpack_require__(/*! ./modular.js */ "./node_modules/@noble/curves/abstract/modular.js");
29632
+ const utils_js_1 = __webpack_require__(/*! ./utils.js */ "./node_modules/@noble/curves/abstract/utils.js");
29633
+ const _0n = BigInt(0);
29634
+ const _1n = BigInt(1);
29635
+ // Elliptic curve multiplication of Point by scalar. Fragile.
29636
+ // Scalars should always be less than curve order: this should be checked inside of a curve itself.
29637
+ // Creates precomputation tables for fast multiplication:
29638
+ // - private scalar is split by fixed size windows of W bits
29639
+ // - every window point is collected from window's table & added to accumulator
29640
+ // - since windows are different, same point inside tables won't be accessed more than once per calc
29641
+ // - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)
29642
+ // - +1 window is neccessary for wNAF
29643
+ // - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
29644
+ // TODO: Research returning 2d JS array of windows, instead of a single window. This would allow
29645
+ // windows to be in different memory locations
29646
+ function wNAF(c, bits) {
29647
+ const constTimeNegate = (condition, item) => {
29648
+ const neg = item.negate();
29649
+ return condition ? neg : item;
29650
+ };
29651
+ const opts = (W) => {
29652
+ const windows = Math.ceil(bits / W) + 1; // +1, because
29653
+ const windowSize = 2 ** (W - 1); // -1 because we skip zero
29654
+ return { windows, windowSize };
29655
+ };
29656
+ return {
29657
+ constTimeNegate,
29658
+ // non-const time multiplication ladder
29659
+ unsafeLadder(elm, n) {
29660
+ let p = c.ZERO;
29661
+ let d = elm;
29662
+ while (n > _0n) {
29663
+ if (n & _1n)
29664
+ p = p.add(d);
29665
+ d = d.double();
29666
+ n >>= _1n;
29667
+ }
29668
+ return p;
29669
+ },
29670
+ /**
29671
+ * Creates a wNAF precomputation window. Used for caching.
29672
+ * Default window size is set by `utils.precompute()` and is equal to 8.
29673
+ * Number of precomputed points depends on the curve size:
29674
+ * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
29675
+ * - 𝑊 is the window size
29676
+ * - 𝑛 is the bitlength of the curve order.
29677
+ * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
29678
+ * @returns precomputed point tables flattened to a single array
29679
+ */
29680
+ precomputeWindow(elm, W) {
29681
+ const { windows, windowSize } = opts(W);
29682
+ const points = [];
29683
+ let p = elm;
29684
+ let base = p;
29685
+ for (let window = 0; window < windows; window++) {
29686
+ base = p;
29687
+ points.push(base);
29688
+ // =1, because we skip zero
29689
+ for (let i = 1; i < windowSize; i++) {
29690
+ base = base.add(p);
29691
+ points.push(base);
29692
+ }
29693
+ p = base.double();
29694
+ }
29695
+ return points;
29696
+ },
29697
+ /**
29698
+ * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
29699
+ * @param W window size
29700
+ * @param precomputes precomputed tables
29701
+ * @param n scalar (we don't check here, but should be less than curve order)
29702
+ * @returns real and fake (for const-time) points
29703
+ */
29704
+ wNAF(W, precomputes, n) {
29705
+ // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise
29706
+ // But need to carefully remove other checks before wNAF. ORDER == bits here
29707
+ const { windows, windowSize } = opts(W);
29708
+ let p = c.ZERO;
29709
+ let f = c.BASE;
29710
+ const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.
29711
+ const maxNumber = 2 ** W;
29712
+ const shiftBy = BigInt(W);
29713
+ for (let window = 0; window < windows; window++) {
29714
+ const offset = window * windowSize;
29715
+ // Extract W bits.
29716
+ let wbits = Number(n & mask);
29717
+ // Shift number by W bits.
29718
+ n >>= shiftBy;
29719
+ // If the bits are bigger than max size, we'll split those.
29720
+ // +224 => 256 - 32
29721
+ if (wbits > windowSize) {
29722
+ wbits -= maxNumber;
29723
+ n += _1n;
29724
+ }
29725
+ // This code was first written with assumption that 'f' and 'p' will never be infinity point:
29726
+ // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,
29727
+ // there is negate now: it is possible that negated element from low value
29728
+ // would be the same as high element, which will create carry into next window.
29729
+ // It's not obvious how this can fail, but still worth investigating later.
29730
+ // Check if we're onto Zero point.
29731
+ // Add random point inside current window to f.
29732
+ const offset1 = offset;
29733
+ const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero
29734
+ const cond1 = window % 2 !== 0;
29735
+ const cond2 = wbits < 0;
29736
+ if (wbits === 0) {
29737
+ // The most important part for const-time getPublicKey
29738
+ f = f.add(constTimeNegate(cond1, precomputes[offset1]));
29739
+ }
29740
+ else {
29741
+ p = p.add(constTimeNegate(cond2, precomputes[offset2]));
29742
+ }
29743
+ }
29744
+ // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ()
29745
+ // Even if the variable is still unused, there are some checks which will
29746
+ // throw an exception, so compiler needs to prove they won't happen, which is hard.
29747
+ // At this point there is a way to F be infinity-point even if p is not,
29748
+ // which makes it less const-time: around 1 bigint multiply.
29749
+ return { p, f };
29750
+ },
29751
+ wNAFCached(P, precomputesMap, n, transform) {
29752
+ // @ts-ignore
29753
+ const W = P._WINDOW_SIZE || 1;
29754
+ // Calculate precomputes on a first run, reuse them after
29755
+ let comp = precomputesMap.get(P);
29756
+ if (!comp) {
29757
+ comp = this.precomputeWindow(P, W);
29758
+ if (W !== 1) {
29759
+ precomputesMap.set(P, transform(comp));
29760
+ }
29761
+ }
29762
+ return this.wNAF(W, comp, n);
29763
+ },
29764
+ };
29765
+ }
29766
+ exports.wNAF = wNAF;
29767
+ function validateBasic(curve) {
29768
+ (0, modular_js_1.validateField)(curve.Fp);
29769
+ (0, utils_js_1.validateObject)(curve, {
29770
+ n: 'bigint',
29771
+ h: 'bigint',
29772
+ Gx: 'field',
29773
+ Gy: 'field',
29774
+ }, {
29775
+ nBitLength: 'isSafeInteger',
29776
+ nByteLength: 'isSafeInteger',
29777
+ });
29778
+ // Set defaults
29779
+ return Object.freeze({
29780
+ ...(0, modular_js_1.nLength)(curve.n, curve.nBitLength),
29781
+ ...curve,
29782
+ ...{ p: curve.Fp.ORDER },
29783
+ });
29784
+ }
29785
+ exports.validateBasic = validateBasic;
29786
+ //# sourceMappingURL=curve.js.map
29787
+
29788
+ /***/ }),
29789
+
29790
+ /***/ "./node_modules/@noble/curves/abstract/hash-to-curve.js":
29791
+ /*!**************************************************************!*\
29792
+ !*** ./node_modules/@noble/curves/abstract/hash-to-curve.js ***!
29793
+ \**************************************************************/
29794
+ /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
29795
+
29796
+ "use strict";
29797
+
29798
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
29799
+ exports.createHasher = exports.isogenyMap = exports.hash_to_field = exports.expand_message_xof = exports.expand_message_xmd = void 0;
29800
+ const modular_js_1 = __webpack_require__(/*! ./modular.js */ "./node_modules/@noble/curves/abstract/modular.js");
29801
+ const utils_js_1 = __webpack_require__(/*! ./utils.js */ "./node_modules/@noble/curves/abstract/utils.js");
29802
+ function validateDST(dst) {
29803
+ if (dst instanceof Uint8Array)
29804
+ return dst;
29805
+ if (typeof dst === 'string')
29806
+ return (0, utils_js_1.utf8ToBytes)(dst);
29807
+ throw new Error('DST must be Uint8Array or string');
29808
+ }
29809
+ // Octet Stream to Integer. "spec" implementation of os2ip is 2.5x slower vs bytesToNumberBE.
29810
+ const os2ip = utils_js_1.bytesToNumberBE;
29811
+ // Integer to Octet Stream (numberToBytesBE)
29812
+ function i2osp(value, length) {
29813
+ if (value < 0 || value >= 1 << (8 * length)) {
29814
+ throw new Error(`bad I2OSP call: value=${value} length=${length}`);
29815
+ }
29816
+ const res = Array.from({ length }).fill(0);
29817
+ for (let i = length - 1; i >= 0; i--) {
29818
+ res[i] = value & 0xff;
29819
+ value >>>= 8;
29820
+ }
29821
+ return new Uint8Array(res);
29822
+ }
29823
+ function strxor(a, b) {
29824
+ const arr = new Uint8Array(a.length);
29825
+ for (let i = 0; i < a.length; i++) {
29826
+ arr[i] = a[i] ^ b[i];
29827
+ }
29828
+ return arr;
29829
+ }
29830
+ function isBytes(item) {
29831
+ if (!(item instanceof Uint8Array))
29832
+ throw new Error('Uint8Array expected');
29833
+ }
29834
+ function isNum(item) {
29835
+ if (!Number.isSafeInteger(item))
29836
+ throw new Error('number expected');
29837
+ }
29838
+ // Produces a uniformly random byte string using a cryptographic hash function H that outputs b bits
29839
+ // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-5.4.1
29840
+ function expand_message_xmd(msg, DST, lenInBytes, H) {
29841
+ isBytes(msg);
29842
+ isBytes(DST);
29843
+ isNum(lenInBytes);
29844
+ // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-16#section-5.3.3
29845
+ if (DST.length > 255)
29846
+ DST = H((0, utils_js_1.concatBytes)((0, utils_js_1.utf8ToBytes)('H2C-OVERSIZE-DST-'), DST));
29847
+ const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;
29848
+ const ell = Math.ceil(lenInBytes / b_in_bytes);
29849
+ if (ell > 255)
29850
+ throw new Error('Invalid xmd length');
29851
+ const DST_prime = (0, utils_js_1.concatBytes)(DST, i2osp(DST.length, 1));
29852
+ const Z_pad = i2osp(0, r_in_bytes);
29853
+ const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str
29854
+ const b = new Array(ell);
29855
+ const b_0 = H((0, utils_js_1.concatBytes)(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));
29856
+ b[0] = H((0, utils_js_1.concatBytes)(b_0, i2osp(1, 1), DST_prime));
29857
+ for (let i = 1; i <= ell; i++) {
29858
+ const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];
29859
+ b[i] = H((0, utils_js_1.concatBytes)(...args));
29860
+ }
29861
+ const pseudo_random_bytes = (0, utils_js_1.concatBytes)(...b);
29862
+ return pseudo_random_bytes.slice(0, lenInBytes);
29863
+ }
29864
+ exports.expand_message_xmd = expand_message_xmd;
29865
+ function expand_message_xof(msg, DST, lenInBytes, k, H) {
29866
+ isBytes(msg);
29867
+ isBytes(DST);
29868
+ isNum(lenInBytes);
29869
+ // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-16#section-5.3.3
29870
+ // DST = H('H2C-OVERSIZE-DST-' || a_very_long_DST, Math.ceil((lenInBytes * k) / 8));
29871
+ if (DST.length > 255) {
29872
+ const dkLen = Math.ceil((2 * k) / 8);
29873
+ DST = H.create({ dkLen }).update((0, utils_js_1.utf8ToBytes)('H2C-OVERSIZE-DST-')).update(DST).digest();
29874
+ }
29875
+ if (lenInBytes > 65535 || DST.length > 255)
29876
+ throw new Error('expand_message_xof: invalid lenInBytes');
29877
+ return (H.create({ dkLen: lenInBytes })
29878
+ .update(msg)
29879
+ .update(i2osp(lenInBytes, 2))
29880
+ // 2. DST_prime = DST || I2OSP(len(DST), 1)
29881
+ .update(DST)
29882
+ .update(i2osp(DST.length, 1))
29883
+ .digest());
29884
+ }
29885
+ exports.expand_message_xof = expand_message_xof;
29886
+ /**
29887
+ * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F
29888
+ * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-5.3
29889
+ * @param msg a byte string containing the message to hash
29890
+ * @param count the number of elements of F to output
29891
+ * @param options `{DST: string, p: bigint, m: number, k: number, expand: 'xmd' | 'xof', hash: H}`, see above
29892
+ * @returns [u_0, ..., u_(count - 1)], a list of field elements.
29893
+ */
29894
+ function hash_to_field(msg, count, options) {
29895
+ (0, utils_js_1.validateObject)(options, {
29896
+ DST: 'string',
29897
+ p: 'bigint',
29898
+ m: 'isSafeInteger',
29899
+ k: 'isSafeInteger',
29900
+ hash: 'hash',
29901
+ });
29902
+ const { p, k, m, hash, expand, DST: _DST } = options;
29903
+ isBytes(msg);
29904
+ isNum(count);
29905
+ const DST = validateDST(_DST);
29906
+ const log2p = p.toString(2).length;
29907
+ const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above
29908
+ const len_in_bytes = count * m * L;
29909
+ let prb; // pseudo_random_bytes
29910
+ if (expand === 'xmd') {
29911
+ prb = expand_message_xmd(msg, DST, len_in_bytes, hash);
29912
+ }
29913
+ else if (expand === 'xof') {
29914
+ prb = expand_message_xof(msg, DST, len_in_bytes, k, hash);
29915
+ }
29916
+ else if (expand === '_internal_pass') {
29917
+ // for internal tests only
29918
+ prb = msg;
29919
+ }
29920
+ else {
29921
+ throw new Error('expand must be "xmd" or "xof"');
29922
+ }
29923
+ const u = new Array(count);
29924
+ for (let i = 0; i < count; i++) {
29925
+ const e = new Array(m);
29926
+ for (let j = 0; j < m; j++) {
29927
+ const elm_offset = L * (j + i * m);
29928
+ const tv = prb.subarray(elm_offset, elm_offset + L);
29929
+ e[j] = (0, modular_js_1.mod)(os2ip(tv), p);
29930
+ }
29931
+ u[i] = e;
29932
+ }
29933
+ return u;
29934
+ }
29935
+ exports.hash_to_field = hash_to_field;
29936
+ function isogenyMap(field, map) {
29937
+ // Make same order as in spec
29938
+ const COEFF = map.map((i) => Array.from(i).reverse());
29939
+ return (x, y) => {
29940
+ const [xNum, xDen, yNum, yDen] = COEFF.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x), i)));
29941
+ x = field.div(xNum, xDen); // xNum / xDen
29942
+ y = field.mul(y, field.div(yNum, yDen)); // y * (yNum / yDev)
29943
+ return { x, y };
29944
+ };
29945
+ }
29946
+ exports.isogenyMap = isogenyMap;
29947
+ function createHasher(Point, mapToCurve, def) {
29948
+ if (typeof mapToCurve !== 'function')
29949
+ throw new Error('mapToCurve() must be defined');
29950
+ return {
29951
+ // Encodes byte string to elliptic curve
29952
+ // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-16#section-3
29953
+ hashToCurve(msg, options) {
29954
+ const u = hash_to_field(msg, 2, { ...def, DST: def.DST, ...options });
29955
+ const u0 = Point.fromAffine(mapToCurve(u[0]));
29956
+ const u1 = Point.fromAffine(mapToCurve(u[1]));
29957
+ const P = u0.add(u1).clearCofactor();
29958
+ P.assertValidity();
29959
+ return P;
29960
+ },
29961
+ // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-16#section-3
29962
+ encodeToCurve(msg, options) {
29963
+ const u = hash_to_field(msg, 1, { ...def, DST: def.encodeDST, ...options });
29964
+ const P = Point.fromAffine(mapToCurve(u[0])).clearCofactor();
29965
+ P.assertValidity();
29966
+ return P;
29967
+ },
29968
+ };
29969
+ }
29970
+ exports.createHasher = createHasher;
29971
+ //# sourceMappingURL=hash-to-curve.js.map
29972
+
29973
+ /***/ }),
29974
+
29975
+ /***/ "./node_modules/@noble/curves/abstract/modular.js":
29976
+ /*!********************************************************!*\
29977
+ !*** ./node_modules/@noble/curves/abstract/modular.js ***!
29978
+ \********************************************************/
29979
+ /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
29980
+
29981
+ "use strict";
29982
+
29983
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
29984
+ exports.hashToPrivateScalar = exports.FpSqrtEven = exports.FpSqrtOdd = exports.Field = exports.nLength = exports.FpIsSquare = exports.FpDiv = exports.FpInvertBatch = exports.FpPow = exports.validateField = exports.isNegativeLE = exports.FpSqrt = exports.tonelliShanks = exports.invert = exports.pow2 = exports.pow = exports.mod = void 0;
29985
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
29986
+ // Utilities for modular arithmetics and finite fields
29987
+ const utils_js_1 = __webpack_require__(/*! ./utils.js */ "./node_modules/@noble/curves/abstract/utils.js");
29988
+ // prettier-ignore
29989
+ const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);
29990
+ // prettier-ignore
29991
+ const _4n = BigInt(4), _5n = BigInt(5), _8n = BigInt(8);
29992
+ // prettier-ignore
29993
+ const _9n = BigInt(9), _16n = BigInt(16);
29994
+ // Calculates a modulo b
29995
+ function mod(a, b) {
29996
+ const result = a % b;
29997
+ return result >= _0n ? result : b + result;
29998
+ }
29999
+ exports.mod = mod;
30000
+ /**
30001
+ * Efficiently exponentiate num to power and do modular division.
30002
+ * Unsafe in some contexts: uses ladder, so can expose bigint bits.
30003
+ * @example
30004
+ * powMod(2n, 6n, 11n) // 64n % 11n == 9n
30005
+ */
30006
+ // TODO: use field version && remove
30007
+ function pow(num, power, modulo) {
30008
+ if (modulo <= _0n || power < _0n)
30009
+ throw new Error('Expected power/modulo > 0');
30010
+ if (modulo === _1n)
30011
+ return _0n;
30012
+ let res = _1n;
30013
+ while (power > _0n) {
30014
+ if (power & _1n)
30015
+ res = (res * num) % modulo;
30016
+ num = (num * num) % modulo;
30017
+ power >>= _1n;
30018
+ }
30019
+ return res;
30020
+ }
30021
+ exports.pow = pow;
30022
+ // Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4)
30023
+ function pow2(x, power, modulo) {
30024
+ let res = x;
30025
+ while (power-- > _0n) {
30026
+ res *= res;
30027
+ res %= modulo;
30028
+ }
30029
+ return res;
30030
+ }
30031
+ exports.pow2 = pow2;
30032
+ // Inverses number over modulo
30033
+ function invert(number, modulo) {
30034
+ if (number === _0n || modulo <= _0n) {
30035
+ throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);
30036
+ }
30037
+ // Eucledian GCD https://brilliant.org/wiki/extended-euclidean-algorithm/
30038
+ // Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower.
30039
+ let a = mod(number, modulo);
30040
+ let b = modulo;
30041
+ // prettier-ignore
30042
+ let x = _0n, y = _1n, u = _1n, v = _0n;
30043
+ while (a !== _0n) {
30044
+ // JIT applies optimization if those two lines follow each other
30045
+ const q = b / a;
30046
+ const r = b % a;
30047
+ const m = x - u * q;
30048
+ const n = y - v * q;
30049
+ // prettier-ignore
30050
+ b = a, a = r, x = u, y = v, u = m, v = n;
30051
+ }
30052
+ const gcd = b;
30053
+ if (gcd !== _1n)
30054
+ throw new Error('invert: does not exist');
30055
+ return mod(x, modulo);
30056
+ }
30057
+ exports.invert = invert;
30058
+ // Tonelli-Shanks algorithm
30059
+ // Paper 1: https://eprint.iacr.org/2012/685.pdf (page 12)
30060
+ // Paper 2: Square Roots from 1; 24, 51, 10 to Dan Shanks
30061
+ function tonelliShanks(P) {
30062
+ // Legendre constant: used to calculate Legendre symbol (a | p),
30063
+ // which denotes the value of a^((p-1)/2) (mod p).
30064
+ // (a | p) ≡ 1 if a is a square (mod p)
30065
+ // (a | p) ≡ -1 if a is not a square (mod p)
30066
+ // (a | p) ≡ 0 if a ≡ 0 (mod p)
30067
+ const legendreC = (P - _1n) / _2n;
30068
+ let Q, S, Z;
30069
+ // Step 1: By factoring out powers of 2 from p - 1,
30070
+ // find q and s such that p - 1 = q*(2^s) with q odd
30071
+ for (Q = P - _1n, S = 0; Q % _2n === _0n; Q /= _2n, S++)
30072
+ ;
30073
+ // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq
30074
+ for (Z = _2n; Z < P && pow(Z, legendreC, P) !== P - _1n; Z++)
30075
+ ;
30076
+ // Fast-path
30077
+ if (S === 1) {
30078
+ const p1div4 = (P + _1n) / _4n;
30079
+ return function tonelliFast(Fp, n) {
30080
+ const root = Fp.pow(n, p1div4);
30081
+ if (!Fp.eql(Fp.sqr(root), n))
30082
+ throw new Error('Cannot find square root');
30083
+ return root;
30084
+ };
30085
+ }
30086
+ // Slow-path
30087
+ const Q1div2 = (Q + _1n) / _2n;
30088
+ return function tonelliSlow(Fp, n) {
30089
+ // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1
30090
+ if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE))
30091
+ throw new Error('Cannot find square root');
30092
+ let r = S;
30093
+ // TODO: will fail at Fp2/etc
30094
+ let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b
30095
+ let x = Fp.pow(n, Q1div2); // first guess at the square root
30096
+ let b = Fp.pow(n, Q); // first guess at the fudge factor
30097
+ while (!Fp.eql(b, Fp.ONE)) {
30098
+ if (Fp.eql(b, Fp.ZERO))
30099
+ return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0)
30100
+ // Find m such b^(2^m)==1
30101
+ let m = 1;
30102
+ for (let t2 = Fp.sqr(b); m < r; m++) {
30103
+ if (Fp.eql(t2, Fp.ONE))
30104
+ break;
30105
+ t2 = Fp.sqr(t2); // t2 *= t2
30106
+ }
30107
+ // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow
30108
+ const ge = Fp.pow(g, _1n << BigInt(r - m - 1)); // ge = 2^(r-m-1)
30109
+ g = Fp.sqr(ge); // g = ge * ge
30110
+ x = Fp.mul(x, ge); // x *= ge
30111
+ b = Fp.mul(b, g); // b *= g
30112
+ r = m;
30113
+ }
30114
+ return x;
30115
+ };
30116
+ }
30117
+ exports.tonelliShanks = tonelliShanks;
30118
+ function FpSqrt(P) {
30119
+ // NOTE: different algorithms can give different roots, it is up to user to decide which one they want.
30120
+ // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).
30121
+ // P ≡ 3 (mod 4)
30122
+ // √n = n^((P+1)/4)
30123
+ if (P % _4n === _3n) {
30124
+ // Not all roots possible!
30125
+ // const ORDER =
30126
+ // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn;
30127
+ // const NUM = 72057594037927816n;
30128
+ const p1div4 = (P + _1n) / _4n;
30129
+ return function sqrt3mod4(Fp, n) {
30130
+ const root = Fp.pow(n, p1div4);
30131
+ // Throw if root**2 != n
30132
+ if (!Fp.eql(Fp.sqr(root), n))
30133
+ throw new Error('Cannot find square root');
30134
+ return root;
30135
+ };
30136
+ }
30137
+ // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10)
30138
+ if (P % _8n === _5n) {
30139
+ const c1 = (P - _5n) / _8n;
30140
+ return function sqrt5mod8(Fp, n) {
30141
+ const n2 = Fp.mul(n, _2n);
30142
+ const v = Fp.pow(n2, c1);
30143
+ const nv = Fp.mul(n, v);
30144
+ const i = Fp.mul(Fp.mul(nv, _2n), v);
30145
+ const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
30146
+ if (!Fp.eql(Fp.sqr(root), n))
30147
+ throw new Error('Cannot find square root');
30148
+ return root;
30149
+ };
30150
+ }
30151
+ // P ≡ 9 (mod 16)
30152
+ if (P % _16n === _9n) {
30153
+ // NOTE: tonelli is too slow for bls-Fp2 calculations even on start
30154
+ // Means we cannot use sqrt for constants at all!
30155
+ //
30156
+ // const c1 = Fp.sqrt(Fp.negate(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F
30157
+ // const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F
30158
+ // const c3 = Fp.sqrt(Fp.negate(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F
30159
+ // const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic
30160
+ // sqrt = (x) => {
30161
+ // let tv1 = Fp.pow(x, c4); // 1. tv1 = x^c4
30162
+ // let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1
30163
+ // const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1
30164
+ // let tv4 = Fp.mul(c3, tv1); // 4. tv4 = c3 * tv1
30165
+ // const e1 = Fp.equals(Fp.square(tv2), x); // 5. e1 = (tv2^2) == x
30166
+ // const e2 = Fp.equals(Fp.square(tv3), x); // 6. e2 = (tv3^2) == x
30167
+ // tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x
30168
+ // tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x
30169
+ // const e3 = Fp.equals(Fp.square(tv2), x); // 9. e3 = (tv2^2) == x
30170
+ // return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2
30171
+ // }
30172
+ }
30173
+ // Other cases: Tonelli-Shanks algorithm
30174
+ return tonelliShanks(P);
30175
+ }
30176
+ exports.FpSqrt = FpSqrt;
30177
+ // Little-endian check for first LE bit (last BE bit);
30178
+ const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;
30179
+ exports.isNegativeLE = isNegativeLE;
30180
+ // prettier-ignore
30181
+ const FIELD_FIELDS = [
30182
+ 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',
30183
+ 'eql', 'add', 'sub', 'mul', 'pow', 'div',
30184
+ 'addN', 'subN', 'mulN', 'sqrN'
30185
+ ];
30186
+ function validateField(field) {
30187
+ const initial = {
30188
+ ORDER: 'bigint',
30189
+ MASK: 'bigint',
30190
+ BYTES: 'isSafeInteger',
30191
+ BITS: 'isSafeInteger',
30192
+ };
30193
+ const opts = FIELD_FIELDS.reduce((map, val) => {
30194
+ map[val] = 'function';
30195
+ return map;
30196
+ }, initial);
30197
+ return (0, utils_js_1.validateObject)(field, opts);
30198
+ }
30199
+ exports.validateField = validateField;
30200
+ // Generic field functions
30201
+ function FpPow(f, num, power) {
30202
+ // Should have same speed as pow for bigints
30203
+ // TODO: benchmark!
30204
+ if (power < _0n)
30205
+ throw new Error('Expected power > 0');
30206
+ if (power === _0n)
30207
+ return f.ONE;
30208
+ if (power === _1n)
30209
+ return num;
30210
+ let p = f.ONE;
30211
+ let d = num;
30212
+ while (power > _0n) {
30213
+ if (power & _1n)
30214
+ p = f.mul(p, d);
30215
+ d = f.sqr(d);
30216
+ power >>= _1n;
30217
+ }
30218
+ return p;
30219
+ }
30220
+ exports.FpPow = FpPow;
30221
+ // 0 is non-invertible: non-batched version will throw on 0
30222
+ function FpInvertBatch(f, nums) {
30223
+ const tmp = new Array(nums.length);
30224
+ // Walk from first to last, multiply them by each other MOD p
30225
+ const lastMultiplied = nums.reduce((acc, num, i) => {
30226
+ if (f.is0(num))
30227
+ return acc;
30228
+ tmp[i] = acc;
30229
+ return f.mul(acc, num);
30230
+ }, f.ONE);
30231
+ // Invert last element
30232
+ const inverted = f.inv(lastMultiplied);
30233
+ // Walk from last to first, multiply them by inverted each other MOD p
30234
+ nums.reduceRight((acc, num, i) => {
30235
+ if (f.is0(num))
30236
+ return acc;
30237
+ tmp[i] = f.mul(acc, tmp[i]);
30238
+ return f.mul(acc, num);
30239
+ }, inverted);
30240
+ return tmp;
30241
+ }
30242
+ exports.FpInvertBatch = FpInvertBatch;
30243
+ function FpDiv(f, lhs, rhs) {
30244
+ return f.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, f.ORDER) : f.inv(rhs));
30245
+ }
30246
+ exports.FpDiv = FpDiv;
30247
+ // This function returns True whenever the value x is a square in the field F.
30248
+ function FpIsSquare(f) {
30249
+ const legendreConst = (f.ORDER - _1n) / _2n; // Integer arithmetic
30250
+ return (x) => {
30251
+ const p = f.pow(x, legendreConst);
30252
+ return f.eql(p, f.ZERO) || f.eql(p, f.ONE);
30253
+ };
30254
+ }
30255
+ exports.FpIsSquare = FpIsSquare;
30256
+ // CURVE.n lengths
30257
+ function nLength(n, nBitLength) {
30258
+ // Bit size, byte size of CURVE.n
30259
+ const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;
30260
+ const nByteLength = Math.ceil(_nBitLength / 8);
30261
+ return { nBitLength: _nBitLength, nByteLength };
30262
+ }
30263
+ exports.nLength = nLength;
30264
+ /**
30265
+ * Initializes a galois field over prime. Non-primes are not supported for now.
30266
+ * Do not init in loop: slow. Very fragile: always run a benchmark on change.
30267
+ * Major performance gains:
30268
+ * a) non-normalized operations like mulN instead of mul
30269
+ * b) `Object.freeze`
30270
+ * c) Same object shape: never add or remove keys
30271
+ * @param ORDER prime positive bigint
30272
+ * @param bitLen how many bits the field consumes
30273
+ * @param isLE (def: false) if encoding / decoding should be in little-endian
30274
+ * @param redef optional faster redefinitions of sqrt and other methods
30275
+ */
30276
+ function Field(ORDER, bitLen, isLE = false, redef = {}) {
30277
+ if (ORDER <= _0n)
30278
+ throw new Error(`Expected Fp ORDER > 0, got ${ORDER}`);
30279
+ const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);
30280
+ if (BYTES > 2048)
30281
+ throw new Error('Field lengths over 2048 bytes are not supported');
30282
+ const sqrtP = FpSqrt(ORDER);
30283
+ const f = Object.freeze({
30284
+ ORDER,
30285
+ BITS,
30286
+ BYTES,
30287
+ MASK: (0, utils_js_1.bitMask)(BITS),
30288
+ ZERO: _0n,
30289
+ ONE: _1n,
30290
+ create: (num) => mod(num, ORDER),
30291
+ isValid: (num) => {
30292
+ if (typeof num !== 'bigint')
30293
+ throw new Error(`Invalid field element: expected bigint, got ${typeof num}`);
30294
+ return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible
30295
+ },
30296
+ is0: (num) => num === _0n,
30297
+ isOdd: (num) => (num & _1n) === _1n,
30298
+ neg: (num) => mod(-num, ORDER),
30299
+ eql: (lhs, rhs) => lhs === rhs,
30300
+ sqr: (num) => mod(num * num, ORDER),
30301
+ add: (lhs, rhs) => mod(lhs + rhs, ORDER),
30302
+ sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
30303
+ mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
30304
+ pow: (num, power) => FpPow(f, num, power),
30305
+ div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
30306
+ // Same as above, but doesn't normalize
30307
+ sqrN: (num) => num * num,
30308
+ addN: (lhs, rhs) => lhs + rhs,
30309
+ subN: (lhs, rhs) => lhs - rhs,
30310
+ mulN: (lhs, rhs) => lhs * rhs,
30311
+ inv: (num) => invert(num, ORDER),
30312
+ sqrt: redef.sqrt || ((n) => sqrtP(f, n)),
30313
+ invertBatch: (lst) => FpInvertBatch(f, lst),
30314
+ // TODO: do we really need constant cmov?
30315
+ // We don't have const-time bigints anyway, so probably will be not very useful
30316
+ cmov: (a, b, c) => (c ? b : a),
30317
+ toBytes: (num) => (isLE ? (0, utils_js_1.numberToBytesLE)(num, BYTES) : (0, utils_js_1.numberToBytesBE)(num, BYTES)),
30318
+ fromBytes: (bytes) => {
30319
+ if (bytes.length !== BYTES)
30320
+ throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`);
30321
+ return isLE ? (0, utils_js_1.bytesToNumberLE)(bytes) : (0, utils_js_1.bytesToNumberBE)(bytes);
30322
+ },
30323
+ });
30324
+ return Object.freeze(f);
30325
+ }
30326
+ exports.Field = Field;
30327
+ function FpSqrtOdd(Fp, elm) {
30328
+ if (!Fp.isOdd)
30329
+ throw new Error(`Field doesn't have isOdd`);
30330
+ const root = Fp.sqrt(elm);
30331
+ return Fp.isOdd(root) ? root : Fp.neg(root);
30332
+ }
30333
+ exports.FpSqrtOdd = FpSqrtOdd;
30334
+ function FpSqrtEven(Fp, elm) {
30335
+ if (!Fp.isOdd)
30336
+ throw new Error(`Field doesn't have isOdd`);
30337
+ const root = Fp.sqrt(elm);
30338
+ return Fp.isOdd(root) ? Fp.neg(root) : root;
30339
+ }
30340
+ exports.FpSqrtEven = FpSqrtEven;
30341
+ /**
30342
+ * FIPS 186 B.4.1-compliant "constant-time" private key generation utility.
30343
+ * Can take (n+8) or more bytes of uniform input e.g. from CSPRNG or KDF
30344
+ * and convert them into private scalar, with the modulo bias being neglible.
30345
+ * Needs at least 40 bytes of input for 32-byte private key.
30346
+ * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/
30347
+ * @param hash hash output from SHA3 or a similar function
30348
+ * @returns valid private scalar
30349
+ */
30350
+ function hashToPrivateScalar(hash, groupOrder, isLE = false) {
30351
+ hash = (0, utils_js_1.ensureBytes)('privateHash', hash);
30352
+ const hashLen = hash.length;
30353
+ const minLen = nLength(groupOrder).nByteLength + 8;
30354
+ if (minLen < 24 || hashLen < minLen || hashLen > 1024)
30355
+ throw new Error(`hashToPrivateScalar: expected ${minLen}-1024 bytes of input, got ${hashLen}`);
30356
+ const num = isLE ? (0, utils_js_1.bytesToNumberLE)(hash) : (0, utils_js_1.bytesToNumberBE)(hash);
30357
+ return mod(num, groupOrder - _1n) + _1n;
30358
+ }
30359
+ exports.hashToPrivateScalar = hashToPrivateScalar;
30360
+ //# sourceMappingURL=modular.js.map
30361
+
30362
+ /***/ }),
30363
+
30364
+ /***/ "./node_modules/@noble/curves/abstract/utils.js":
30365
+ /*!******************************************************!*\
30366
+ !*** ./node_modules/@noble/curves/abstract/utils.js ***!
30367
+ \******************************************************/
30368
+ /***/ ((__unused_webpack_module, exports) => {
30369
+
30370
+ "use strict";
30371
+
30372
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
30373
+ exports.validateObject = exports.createHmacDrbg = exports.bitMask = exports.bitSet = exports.bitGet = exports.bitLen = exports.utf8ToBytes = exports.equalBytes = exports.concatBytes = exports.ensureBytes = exports.numberToVarBytesBE = exports.numberToBytesLE = exports.numberToBytesBE = exports.bytesToNumberLE = exports.bytesToNumberBE = exports.hexToBytes = exports.hexToNumber = exports.numberToHexUnpadded = exports.bytesToHex = void 0;
30374
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
30375
+ const _0n = BigInt(0);
30376
+ const _1n = BigInt(1);
30377
+ const _2n = BigInt(2);
30378
+ const u8a = (a) => a instanceof Uint8Array;
30379
+ const hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0'));
30380
+ function bytesToHex(bytes) {
30381
+ if (!u8a(bytes))
30382
+ throw new Error('Uint8Array expected');
30383
+ // pre-caching improves the speed 6x
30384
+ let hex = '';
30385
+ for (let i = 0; i < bytes.length; i++) {
30386
+ hex += hexes[bytes[i]];
30387
+ }
30388
+ return hex;
30389
+ }
30390
+ exports.bytesToHex = bytesToHex;
30391
+ function numberToHexUnpadded(num) {
30392
+ const hex = num.toString(16);
30393
+ return hex.length & 1 ? `0${hex}` : hex;
30394
+ }
30395
+ exports.numberToHexUnpadded = numberToHexUnpadded;
30396
+ function hexToNumber(hex) {
30397
+ if (typeof hex !== 'string')
30398
+ throw new Error('hex string expected, got ' + typeof hex);
30399
+ // Big Endian
30400
+ return BigInt(hex === '' ? '0' : `0x${hex}`);
30401
+ }
30402
+ exports.hexToNumber = hexToNumber;
30403
+ // Caching slows it down 2-3x
30404
+ function hexToBytes(hex) {
30405
+ if (typeof hex !== 'string')
30406
+ throw new Error('hex string expected, got ' + typeof hex);
30407
+ if (hex.length % 2)
30408
+ throw new Error('hex string is invalid: unpadded ' + hex.length);
30409
+ const array = new Uint8Array(hex.length / 2);
30410
+ for (let i = 0; i < array.length; i++) {
30411
+ const j = i * 2;
30412
+ const hexByte = hex.slice(j, j + 2);
30413
+ const byte = Number.parseInt(hexByte, 16);
30414
+ if (Number.isNaN(byte) || byte < 0)
30415
+ throw new Error('invalid byte sequence');
30416
+ array[i] = byte;
30417
+ }
30418
+ return array;
30419
+ }
30420
+ exports.hexToBytes = hexToBytes;
30421
+ // Big Endian
30422
+ function bytesToNumberBE(bytes) {
30423
+ return hexToNumber(bytesToHex(bytes));
30424
+ }
30425
+ exports.bytesToNumberBE = bytesToNumberBE;
30426
+ function bytesToNumberLE(bytes) {
30427
+ if (!u8a(bytes))
30428
+ throw new Error('Uint8Array expected');
30429
+ return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
30430
+ }
30431
+ exports.bytesToNumberLE = bytesToNumberLE;
30432
+ const numberToBytesBE = (n, len) => hexToBytes(n.toString(16).padStart(len * 2, '0'));
30433
+ exports.numberToBytesBE = numberToBytesBE;
30434
+ const numberToBytesLE = (n, len) => (0, exports.numberToBytesBE)(n, len).reverse();
30435
+ exports.numberToBytesLE = numberToBytesLE;
30436
+ // Returns variable number bytes (minimal bigint encoding?)
30437
+ const numberToVarBytesBE = (n) => hexToBytes(numberToHexUnpadded(n));
30438
+ exports.numberToVarBytesBE = numberToVarBytesBE;
30439
+ function ensureBytes(title, hex, expectedLength) {
30440
+ let res;
30441
+ if (typeof hex === 'string') {
30442
+ try {
30443
+ res = hexToBytes(hex);
30444
+ }
30445
+ catch (e) {
30446
+ throw new Error(`${title} must be valid hex string, got "${hex}". Cause: ${e}`);
30447
+ }
30448
+ }
30449
+ else if (u8a(hex)) {
30450
+ // Uint8Array.from() instead of hash.slice() because node.js Buffer
30451
+ // is instance of Uint8Array, and its slice() creates **mutable** copy
30452
+ res = Uint8Array.from(hex);
30453
+ }
30454
+ else {
30455
+ throw new Error(`${title} must be hex string or Uint8Array`);
30456
+ }
30457
+ const len = res.length;
30458
+ if (typeof expectedLength === 'number' && len !== expectedLength)
30459
+ throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`);
30460
+ return res;
30461
+ }
30462
+ exports.ensureBytes = ensureBytes;
30463
+ // Copies several Uint8Arrays into one.
30464
+ function concatBytes(...arrs) {
30465
+ const r = new Uint8Array(arrs.reduce((sum, a) => sum + a.length, 0));
30466
+ let pad = 0; // walk through each item, ensure they have proper type
30467
+ arrs.forEach((a) => {
30468
+ if (!u8a(a))
30469
+ throw new Error('Uint8Array expected');
30470
+ r.set(a, pad);
30471
+ pad += a.length;
30472
+ });
30473
+ return r;
30474
+ }
30475
+ exports.concatBytes = concatBytes;
30476
+ function equalBytes(b1, b2) {
30477
+ // We don't care about timing attacks here
30478
+ if (b1.length !== b2.length)
30479
+ return false;
30480
+ for (let i = 0; i < b1.length; i++)
30481
+ if (b1[i] !== b2[i])
30482
+ return false;
30483
+ return true;
30484
+ }
30485
+ exports.equalBytes = equalBytes;
30486
+ function utf8ToBytes(str) {
30487
+ if (typeof str !== 'string') {
30488
+ throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
30489
+ }
30490
+ return new TextEncoder().encode(str);
30491
+ }
30492
+ exports.utf8ToBytes = utf8ToBytes;
30493
+ // Bit operations
30494
+ // Amount of bits inside bigint (Same as n.toString(2).length)
30495
+ function bitLen(n) {
30496
+ let len;
30497
+ for (len = 0; n > _0n; n >>= _1n, len += 1)
30498
+ ;
30499
+ return len;
30500
+ }
30501
+ exports.bitLen = bitLen;
30502
+ // Gets single bit at position. NOTE: first bit position is 0 (same as arrays)
30503
+ // Same as !!+Array.from(n.toString(2)).reverse()[pos]
30504
+ const bitGet = (n, pos) => (n >> BigInt(pos)) & _1n;
30505
+ exports.bitGet = bitGet;
30506
+ // Sets single bit at position
30507
+ const bitSet = (n, pos, value) => n | ((value ? _1n : _0n) << BigInt(pos));
30508
+ exports.bitSet = bitSet;
30509
+ // Return mask for N bits (Same as BigInt(`0b${Array(i).fill('1').join('')}`))
30510
+ // Not using ** operator with bigints for old engines.
30511
+ const bitMask = (n) => (_2n << BigInt(n - 1)) - _1n;
30512
+ exports.bitMask = bitMask;
30513
+ // DRBG
30514
+ const u8n = (data) => new Uint8Array(data); // creates Uint8Array
30515
+ const u8fr = (arr) => Uint8Array.from(arr); // another shortcut
30516
+ /**
30517
+ * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
30518
+ * @returns function that will call DRBG until 2nd arg returns something meaningful
30519
+ * @example
30520
+ * const drbg = createHmacDRBG<Key>(32, 32, hmac);
30521
+ * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined
30522
+ */
30523
+ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
30524
+ if (typeof hashLen !== 'number' || hashLen < 2)
30525
+ throw new Error('hashLen must be a number');
30526
+ if (typeof qByteLen !== 'number' || qByteLen < 2)
30527
+ throw new Error('qByteLen must be a number');
30528
+ if (typeof hmacFn !== 'function')
30529
+ throw new Error('hmacFn must be a function');
30530
+ // Step B, Step C: set hashLen to 8*ceil(hlen/8)
30531
+ let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
30532
+ let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same
30533
+ let i = 0; // Iterations counter, will throw when over 1000
30534
+ const reset = () => {
30535
+ v.fill(1);
30536
+ k.fill(0);
30537
+ i = 0;
30538
+ };
30539
+ const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)
30540
+ const reseed = (seed = u8n()) => {
30541
+ // HMAC-DRBG reseed() function. Steps D-G
30542
+ k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)
30543
+ v = h(); // v = hmac(k || v)
30544
+ if (seed.length === 0)
30545
+ return;
30546
+ k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed)
30547
+ v = h(); // v = hmac(k || v)
30548
+ };
30549
+ const gen = () => {
30550
+ // HMAC-DRBG generate() function
30551
+ if (i++ >= 1000)
30552
+ throw new Error('drbg: tried 1000 values');
30553
+ let len = 0;
30554
+ const out = [];
30555
+ while (len < qByteLen) {
30556
+ v = h();
30557
+ const sl = v.slice();
30558
+ out.push(sl);
30559
+ len += v.length;
30560
+ }
30561
+ return concatBytes(...out);
30562
+ };
30563
+ const genUntil = (seed, pred) => {
30564
+ reset();
30565
+ reseed(seed); // Steps D-G
30566
+ let res = undefined; // Step H: grind until k is in [1..n-1]
30567
+ while (!(res = pred(gen())))
30568
+ reseed();
30569
+ reset();
30570
+ return res;
30571
+ };
30572
+ return genUntil;
30573
+ }
30574
+ exports.createHmacDrbg = createHmacDrbg;
30575
+ // Validating curves and fields
30576
+ const validatorFns = {
30577
+ bigint: (val) => typeof val === 'bigint',
30578
+ function: (val) => typeof val === 'function',
30579
+ boolean: (val) => typeof val === 'boolean',
30580
+ string: (val) => typeof val === 'string',
30581
+ isSafeInteger: (val) => Number.isSafeInteger(val),
30582
+ array: (val) => Array.isArray(val),
30583
+ field: (val, object) => object.Fp.isValid(val),
30584
+ hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),
30585
+ };
30586
+ // type Record<K extends string | number | symbol, T> = { [P in K]: T; }
30587
+ function validateObject(object, validators, optValidators = {}) {
30588
+ const checkField = (fieldName, type, isOptional) => {
30589
+ const checkVal = validatorFns[type];
30590
+ if (typeof checkVal !== 'function')
30591
+ throw new Error(`Invalid validator "${type}", expected function`);
30592
+ const val = object[fieldName];
30593
+ if (isOptional && val === undefined)
30594
+ return;
30595
+ if (!checkVal(val, object)) {
30596
+ throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`);
30597
+ }
30598
+ };
30599
+ for (const [fieldName, type] of Object.entries(validators))
30600
+ checkField(fieldName, type, false);
30601
+ for (const [fieldName, type] of Object.entries(optValidators))
30602
+ checkField(fieldName, type, true);
30603
+ return object;
30604
+ }
30605
+ exports.validateObject = validateObject;
30606
+ // validate type tests
30607
+ // const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };
30608
+ // const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!
30609
+ // // Should fail type-check
30610
+ // const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });
30611
+ // const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });
30612
+ // const z3 = validateObject(o, { test: 'boolean', z: 'bug' });
30613
+ // const z4 = validateObject(o, { a: 'boolean', z: 'bug' });
30614
+ //# sourceMappingURL=utils.js.map
30615
+
30616
+ /***/ }),
30617
+
30618
+ /***/ "./node_modules/@noble/curves/abstract/weierstrass.js":
30619
+ /*!************************************************************!*\
30620
+ !*** ./node_modules/@noble/curves/abstract/weierstrass.js ***!
30621
+ \************************************************************/
30622
+ /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
30623
+
30624
+ "use strict";
30625
+
30626
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
30627
+ exports.mapToCurveSimpleSWU = exports.SWUFpSqrtRatio = exports.weierstrass = exports.weierstrassPoints = exports.DER = void 0;
30628
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
30629
+ // Short Weierstrass curve. The formula is: y² = x³ + ax + b
30630
+ const mod = __webpack_require__(/*! ./modular.js */ "./node_modules/@noble/curves/abstract/modular.js");
30631
+ const ut = __webpack_require__(/*! ./utils.js */ "./node_modules/@noble/curves/abstract/utils.js");
30632
+ const utils_js_1 = __webpack_require__(/*! ./utils.js */ "./node_modules/@noble/curves/abstract/utils.js");
30633
+ const curve_js_1 = __webpack_require__(/*! ./curve.js */ "./node_modules/@noble/curves/abstract/curve.js");
30634
+ function validatePointOpts(curve) {
30635
+ const opts = (0, curve_js_1.validateBasic)(curve);
30636
+ ut.validateObject(opts, {
30637
+ a: 'field',
30638
+ b: 'field',
30639
+ }, {
30640
+ allowedPrivateKeyLengths: 'array',
30641
+ wrapPrivateKey: 'boolean',
30642
+ isTorsionFree: 'function',
30643
+ clearCofactor: 'function',
30644
+ allowInfinityPoint: 'boolean',
30645
+ fromBytes: 'function',
30646
+ toBytes: 'function',
30647
+ });
30648
+ const { endo, Fp, a } = opts;
30649
+ if (endo) {
30650
+ if (!Fp.eql(a, Fp.ZERO)) {
30651
+ throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0');
30652
+ }
30653
+ if (typeof endo !== 'object' ||
30654
+ typeof endo.beta !== 'bigint' ||
30655
+ typeof endo.splitScalar !== 'function') {
30656
+ throw new Error('Expected endomorphism with beta: bigint and splitScalar: function');
30657
+ }
30658
+ }
30659
+ return Object.freeze({ ...opts });
30660
+ }
30661
+ // ASN.1 DER encoding utilities
30662
+ const { bytesToNumberBE: b2n, hexToBytes: h2b } = ut;
30663
+ exports.DER = {
30664
+ // asn.1 DER encoding utils
30665
+ Err: class DERErr extends Error {
30666
+ constructor(m = '') {
30667
+ super(m);
30668
+ }
30669
+ },
30670
+ _parseInt(data) {
30671
+ const { Err: E } = exports.DER;
30672
+ if (data.length < 2 || data[0] !== 0x02)
30673
+ throw new E('Invalid signature integer tag');
30674
+ const len = data[1];
30675
+ const res = data.subarray(2, len + 2);
30676
+ if (!len || res.length !== len)
30677
+ throw new E('Invalid signature integer: wrong length');
30678
+ // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
30679
+ // since we always use positive integers here. It must always be empty:
30680
+ // - add zero byte if exists
30681
+ // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
30682
+ if (res[0] & 0b10000000)
30683
+ throw new E('Invalid signature integer: negative');
30684
+ if (res[0] === 0x00 && !(res[1] & 0b10000000))
30685
+ throw new E('Invalid signature integer: unnecessary leading zero');
30686
+ return { d: b2n(res), l: data.subarray(len + 2) }; // d is data, l is left
30687
+ },
30688
+ toSig(hex) {
30689
+ // parse DER signature
30690
+ const { Err: E } = exports.DER;
30691
+ const data = typeof hex === 'string' ? h2b(hex) : hex;
30692
+ if (!(data instanceof Uint8Array))
30693
+ throw new Error('ui8a expected');
30694
+ let l = data.length;
30695
+ if (l < 2 || data[0] != 0x30)
30696
+ throw new E('Invalid signature tag');
30697
+ if (data[1] !== l - 2)
30698
+ throw new E('Invalid signature: incorrect length');
30699
+ const { d: r, l: sBytes } = exports.DER._parseInt(data.subarray(2));
30700
+ const { d: s, l: rBytesLeft } = exports.DER._parseInt(sBytes);
30701
+ if (rBytesLeft.length)
30702
+ throw new E('Invalid signature: left bytes after parsing');
30703
+ return { r, s };
30704
+ },
30705
+ hexFromSig(sig) {
30706
+ // Add leading zero if first byte has negative bit enabled. More details in '_parseInt'
30707
+ const slice = (s) => (Number.parseInt(s[0], 16) & 0b1000 ? '00' + s : s);
30708
+ const h = (num) => {
30709
+ const hex = num.toString(16);
30710
+ return hex.length & 1 ? `0${hex}` : hex;
30711
+ };
30712
+ const s = slice(h(sig.s));
30713
+ const r = slice(h(sig.r));
30714
+ const shl = s.length / 2;
30715
+ const rhl = r.length / 2;
30716
+ const sl = h(shl);
30717
+ const rl = h(rhl);
30718
+ return `30${h(rhl + shl + 4)}02${rl}${r}02${sl}${s}`;
30719
+ },
30720
+ };
30721
+ // Be friendly to bad ECMAScript parsers by not using bigint literals
30722
+ // prettier-ignore
30723
+ const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);
30724
+ function weierstrassPoints(opts) {
30725
+ const CURVE = validatePointOpts(opts);
30726
+ const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ
30727
+ const toBytes = CURVE.toBytes ||
30728
+ ((c, point, isCompressed) => {
30729
+ const a = point.toAffine();
30730
+ return ut.concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y));
30731
+ });
30732
+ const fromBytes = CURVE.fromBytes ||
30733
+ ((bytes) => {
30734
+ // const head = bytes[0];
30735
+ const tail = bytes.subarray(1);
30736
+ // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported');
30737
+ const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));
30738
+ const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));
30739
+ return { x, y };
30740
+ });
30741
+ /**
30742
+ * y² = x³ + ax + b: Short weierstrass curve formula
30743
+ * @returns y²
30744
+ */
30745
+ function weierstrassEquation(x) {
30746
+ const { a, b } = CURVE;
30747
+ const x2 = Fp.sqr(x); // x * x
30748
+ const x3 = Fp.mul(x2, x); // x2 * x
30749
+ return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b
30750
+ }
30751
+ // Validate whether the passed curve params are valid.
30752
+ // We check if curve equation works for generator point.
30753
+ // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381.
30754
+ // ProjectivePoint class has not been initialized yet.
30755
+ if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx)))
30756
+ throw new Error('bad generator point: equation left != right');
30757
+ // Valid group elements reside in range 1..n-1
30758
+ function isWithinCurveOrder(num) {
30759
+ return typeof num === 'bigint' && _0n < num && num < CURVE.n;
30760
+ }
30761
+ function assertGE(num) {
30762
+ if (!isWithinCurveOrder(num))
30763
+ throw new Error('Expected valid bigint: 0 < bigint < curve.n');
30764
+ }
30765
+ // Validates if priv key is valid and converts it to bigint.
30766
+ // Supports options allowedPrivateKeyLengths and wrapPrivateKey.
30767
+ function normPrivateKeyToScalar(key) {
30768
+ const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n } = CURVE;
30769
+ if (lengths && typeof key !== 'bigint') {
30770
+ if (key instanceof Uint8Array)
30771
+ key = ut.bytesToHex(key);
30772
+ // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes
30773
+ if (typeof key !== 'string' || !lengths.includes(key.length))
30774
+ throw new Error('Invalid key');
30775
+ key = key.padStart(nByteLength * 2, '0');
30776
+ }
30777
+ let num;
30778
+ try {
30779
+ num =
30780
+ typeof key === 'bigint'
30781
+ ? key
30782
+ : ut.bytesToNumberBE((0, utils_js_1.ensureBytes)('private key', key, nByteLength));
30783
+ }
30784
+ catch (error) {
30785
+ throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`);
30786
+ }
30787
+ if (wrapPrivateKey)
30788
+ num = mod.mod(num, n); // disabled by default, enabled for BLS
30789
+ assertGE(num); // num in range [1..N-1]
30790
+ return num;
30791
+ }
30792
+ const pointPrecomputes = new Map();
30793
+ function assertPrjPoint(other) {
30794
+ if (!(other instanceof Point))
30795
+ throw new Error('ProjectivePoint expected');
30796
+ }
30797
+ /**
30798
+ * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z)
30799
+ * Default Point works in 2d / affine coordinates: (x, y)
30800
+ * We're doing calculations in projective, because its operations don't require costly inversion.
30801
+ */
30802
+ class Point {
30803
+ constructor(px, py, pz) {
30804
+ this.px = px;
30805
+ this.py = py;
30806
+ this.pz = pz;
30807
+ if (px == null || !Fp.isValid(px))
30808
+ throw new Error('x required');
30809
+ if (py == null || !Fp.isValid(py))
30810
+ throw new Error('y required');
30811
+ if (pz == null || !Fp.isValid(pz))
30812
+ throw new Error('z required');
30813
+ }
30814
+ // Does not validate if the point is on-curve.
30815
+ // Use fromHex instead, or call assertValidity() later.
30816
+ static fromAffine(p) {
30817
+ const { x, y } = p || {};
30818
+ if (!p || !Fp.isValid(x) || !Fp.isValid(y))
30819
+ throw new Error('invalid affine point');
30820
+ if (p instanceof Point)
30821
+ throw new Error('projective point not allowed');
30822
+ const is0 = (i) => Fp.eql(i, Fp.ZERO);
30823
+ // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0)
30824
+ if (is0(x) && is0(y))
30825
+ return Point.ZERO;
30826
+ return new Point(x, y, Fp.ONE);
30827
+ }
30828
+ get x() {
30829
+ return this.toAffine().x;
30830
+ }
30831
+ get y() {
30832
+ return this.toAffine().y;
30833
+ }
30834
+ /**
30835
+ * Takes a bunch of Projective Points but executes only one
30836
+ * inversion on all of them. Inversion is very slow operation,
30837
+ * so this improves performance massively.
30838
+ * Optimization: converts a list of projective points to a list of identical points with Z=1.
30839
+ */
30840
+ static normalizeZ(points) {
30841
+ const toInv = Fp.invertBatch(points.map((p) => p.pz));
30842
+ return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);
30843
+ }
30844
+ /**
30845
+ * Converts hash string or Uint8Array to Point.
30846
+ * @param hex short/long ECDSA hex
30847
+ */
30848
+ static fromHex(hex) {
30849
+ const P = Point.fromAffine(fromBytes((0, utils_js_1.ensureBytes)('pointHex', hex)));
30850
+ P.assertValidity();
30851
+ return P;
30852
+ }
30853
+ // Multiplies generator point by privateKey.
30854
+ static fromPrivateKey(privateKey) {
30855
+ return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));
30856
+ }
30857
+ // "Private method", don't use it directly
30858
+ _setWindowSize(windowSize) {
30859
+ this._WINDOW_SIZE = windowSize;
30860
+ pointPrecomputes.delete(this);
30861
+ }
30862
+ // A point on curve is valid if it conforms to equation.
30863
+ assertValidity() {
30864
+ // Zero is valid point too!
30865
+ if (this.is0()) {
30866
+ if (CURVE.allowInfinityPoint)
30867
+ return;
30868
+ throw new Error('bad point: ZERO');
30869
+ }
30870
+ // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`
30871
+ const { x, y } = this.toAffine();
30872
+ // Check if x, y are valid field elements
30873
+ if (!Fp.isValid(x) || !Fp.isValid(y))
30874
+ throw new Error('bad point: x or y not FE');
30875
+ const left = Fp.sqr(y); // y²
30876
+ const right = weierstrassEquation(x); // x³ + ax + b
30877
+ if (!Fp.eql(left, right))
30878
+ throw new Error('bad point: equation left != right');
30879
+ if (!this.isTorsionFree())
30880
+ throw new Error('bad point: not in prime-order subgroup');
30881
+ }
30882
+ hasEvenY() {
30883
+ const { y } = this.toAffine();
30884
+ if (Fp.isOdd)
30885
+ return !Fp.isOdd(y);
30886
+ throw new Error("Field doesn't support isOdd");
30887
+ }
30888
+ /**
30889
+ * Compare one point to another.
30890
+ */
30891
+ equals(other) {
30892
+ assertPrjPoint(other);
30893
+ const { px: X1, py: Y1, pz: Z1 } = this;
30894
+ const { px: X2, py: Y2, pz: Z2 } = other;
30895
+ const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
30896
+ const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
30897
+ return U1 && U2;
30898
+ }
30899
+ /**
30900
+ * Flips point to one corresponding to (x, -y) in Affine coordinates.
30901
+ */
30902
+ negate() {
30903
+ return new Point(this.px, Fp.neg(this.py), this.pz);
30904
+ }
30905
+ // Renes-Costello-Batina exception-free doubling formula.
30906
+ // There is 30% faster Jacobian formula, but it is not complete.
30907
+ // https://eprint.iacr.org/2015/1060, algorithm 3
30908
+ // Cost: 8M + 3S + 3*a + 2*b3 + 15add.
30909
+ double() {
30910
+ const { a, b } = CURVE;
30911
+ const b3 = Fp.mul(b, _3n);
30912
+ const { px: X1, py: Y1, pz: Z1 } = this;
30913
+ let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
30914
+ let t0 = Fp.mul(X1, X1); // step 1
30915
+ let t1 = Fp.mul(Y1, Y1);
30916
+ let t2 = Fp.mul(Z1, Z1);
30917
+ let t3 = Fp.mul(X1, Y1);
30918
+ t3 = Fp.add(t3, t3); // step 5
30919
+ Z3 = Fp.mul(X1, Z1);
30920
+ Z3 = Fp.add(Z3, Z3);
30921
+ X3 = Fp.mul(a, Z3);
30922
+ Y3 = Fp.mul(b3, t2);
30923
+ Y3 = Fp.add(X3, Y3); // step 10
30924
+ X3 = Fp.sub(t1, Y3);
30925
+ Y3 = Fp.add(t1, Y3);
30926
+ Y3 = Fp.mul(X3, Y3);
30927
+ X3 = Fp.mul(t3, X3);
30928
+ Z3 = Fp.mul(b3, Z3); // step 15
30929
+ t2 = Fp.mul(a, t2);
30930
+ t3 = Fp.sub(t0, t2);
30931
+ t3 = Fp.mul(a, t3);
30932
+ t3 = Fp.add(t3, Z3);
30933
+ Z3 = Fp.add(t0, t0); // step 20
30934
+ t0 = Fp.add(Z3, t0);
30935
+ t0 = Fp.add(t0, t2);
30936
+ t0 = Fp.mul(t0, t3);
30937
+ Y3 = Fp.add(Y3, t0);
30938
+ t2 = Fp.mul(Y1, Z1); // step 25
30939
+ t2 = Fp.add(t2, t2);
30940
+ t0 = Fp.mul(t2, t3);
30941
+ X3 = Fp.sub(X3, t0);
30942
+ Z3 = Fp.mul(t2, t1);
30943
+ Z3 = Fp.add(Z3, Z3); // step 30
30944
+ Z3 = Fp.add(Z3, Z3);
30945
+ return new Point(X3, Y3, Z3);
30946
+ }
30947
+ // Renes-Costello-Batina exception-free addition formula.
30948
+ // There is 30% faster Jacobian formula, but it is not complete.
30949
+ // https://eprint.iacr.org/2015/1060, algorithm 1
30950
+ // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
30951
+ add(other) {
30952
+ assertPrjPoint(other);
30953
+ const { px: X1, py: Y1, pz: Z1 } = this;
30954
+ const { px: X2, py: Y2, pz: Z2 } = other;
30955
+ let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
30956
+ const a = CURVE.a;
30957
+ const b3 = Fp.mul(CURVE.b, _3n);
30958
+ let t0 = Fp.mul(X1, X2); // step 1
30959
+ let t1 = Fp.mul(Y1, Y2);
30960
+ let t2 = Fp.mul(Z1, Z2);
30961
+ let t3 = Fp.add(X1, Y1);
30962
+ let t4 = Fp.add(X2, Y2); // step 5
30963
+ t3 = Fp.mul(t3, t4);
30964
+ t4 = Fp.add(t0, t1);
30965
+ t3 = Fp.sub(t3, t4);
30966
+ t4 = Fp.add(X1, Z1);
30967
+ let t5 = Fp.add(X2, Z2); // step 10
30968
+ t4 = Fp.mul(t4, t5);
30969
+ t5 = Fp.add(t0, t2);
30970
+ t4 = Fp.sub(t4, t5);
30971
+ t5 = Fp.add(Y1, Z1);
30972
+ X3 = Fp.add(Y2, Z2); // step 15
30973
+ t5 = Fp.mul(t5, X3);
30974
+ X3 = Fp.add(t1, t2);
30975
+ t5 = Fp.sub(t5, X3);
30976
+ Z3 = Fp.mul(a, t4);
30977
+ X3 = Fp.mul(b3, t2); // step 20
30978
+ Z3 = Fp.add(X3, Z3);
30979
+ X3 = Fp.sub(t1, Z3);
30980
+ Z3 = Fp.add(t1, Z3);
30981
+ Y3 = Fp.mul(X3, Z3);
30982
+ t1 = Fp.add(t0, t0); // step 25
30983
+ t1 = Fp.add(t1, t0);
30984
+ t2 = Fp.mul(a, t2);
30985
+ t4 = Fp.mul(b3, t4);
30986
+ t1 = Fp.add(t1, t2);
30987
+ t2 = Fp.sub(t0, t2); // step 30
30988
+ t2 = Fp.mul(a, t2);
30989
+ t4 = Fp.add(t4, t2);
30990
+ t0 = Fp.mul(t1, t4);
30991
+ Y3 = Fp.add(Y3, t0);
30992
+ t0 = Fp.mul(t5, t4); // step 35
30993
+ X3 = Fp.mul(t3, X3);
30994
+ X3 = Fp.sub(X3, t0);
30995
+ t0 = Fp.mul(t3, t1);
30996
+ Z3 = Fp.mul(t5, Z3);
30997
+ Z3 = Fp.add(Z3, t0); // step 40
30998
+ return new Point(X3, Y3, Z3);
30999
+ }
31000
+ subtract(other) {
31001
+ return this.add(other.negate());
31002
+ }
31003
+ is0() {
31004
+ return this.equals(Point.ZERO);
31005
+ }
31006
+ wNAF(n) {
31007
+ return wnaf.wNAFCached(this, pointPrecomputes, n, (comp) => {
31008
+ const toInv = Fp.invertBatch(comp.map((p) => p.pz));
31009
+ return comp.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);
31010
+ });
31011
+ }
31012
+ /**
31013
+ * Non-constant-time multiplication. Uses double-and-add algorithm.
31014
+ * It's faster, but should only be used when you don't care about
31015
+ * an exposed private key e.g. sig verification, which works over *public* keys.
31016
+ */
31017
+ multiplyUnsafe(n) {
31018
+ const I = Point.ZERO;
31019
+ if (n === _0n)
31020
+ return I;
31021
+ assertGE(n); // Will throw on 0
31022
+ if (n === _1n)
31023
+ return this;
31024
+ const { endo } = CURVE;
31025
+ if (!endo)
31026
+ return wnaf.unsafeLadder(this, n);
31027
+ // Apply endomorphism
31028
+ let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);
31029
+ let k1p = I;
31030
+ let k2p = I;
31031
+ let d = this;
31032
+ while (k1 > _0n || k2 > _0n) {
31033
+ if (k1 & _1n)
31034
+ k1p = k1p.add(d);
31035
+ if (k2 & _1n)
31036
+ k2p = k2p.add(d);
31037
+ d = d.double();
31038
+ k1 >>= _1n;
31039
+ k2 >>= _1n;
31040
+ }
31041
+ if (k1neg)
31042
+ k1p = k1p.negate();
31043
+ if (k2neg)
31044
+ k2p = k2p.negate();
31045
+ k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);
31046
+ return k1p.add(k2p);
31047
+ }
31048
+ /**
31049
+ * Constant time multiplication.
31050
+ * Uses wNAF method. Windowed method may be 10% faster,
31051
+ * but takes 2x longer to generate and consumes 2x memory.
31052
+ * Uses precomputes when available.
31053
+ * Uses endomorphism for Koblitz curves.
31054
+ * @param scalar by which the point would be multiplied
31055
+ * @returns New point
31056
+ */
31057
+ multiply(scalar) {
31058
+ assertGE(scalar);
31059
+ let n = scalar;
31060
+ let point, fake; // Fake point is used to const-time mult
31061
+ const { endo } = CURVE;
31062
+ if (endo) {
31063
+ const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);
31064
+ let { p: k1p, f: f1p } = this.wNAF(k1);
31065
+ let { p: k2p, f: f2p } = this.wNAF(k2);
31066
+ k1p = wnaf.constTimeNegate(k1neg, k1p);
31067
+ k2p = wnaf.constTimeNegate(k2neg, k2p);
31068
+ k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);
31069
+ point = k1p.add(k2p);
31070
+ fake = f1p.add(f2p);
31071
+ }
31072
+ else {
31073
+ const { p, f } = this.wNAF(n);
31074
+ point = p;
31075
+ fake = f;
31076
+ }
31077
+ // Normalize `z` for both points, but return only real one
31078
+ return Point.normalizeZ([point, fake])[0];
31079
+ }
31080
+ /**
31081
+ * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.
31082
+ * Not using Strauss-Shamir trick: precomputation tables are faster.
31083
+ * The trick could be useful if both P and Q are not G (not in our case).
31084
+ * @returns non-zero affine point
31085
+ */
31086
+ multiplyAndAddUnsafe(Q, a, b) {
31087
+ const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes
31088
+ const mul = (P, a // Select faster multiply() method
31089
+ ) => (a === _0n || a === _1n || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a));
31090
+ const sum = mul(this, a).add(mul(Q, b));
31091
+ return sum.is0() ? undefined : sum;
31092
+ }
31093
+ // Converts Projective point to affine (x, y) coordinates.
31094
+ // Can accept precomputed Z^-1 - for example, from invertBatch.
31095
+ // (x, y, z) ∋ (x=x/z, y=y/z)
31096
+ toAffine(iz) {
31097
+ const { px: x, py: y, pz: z } = this;
31098
+ const is0 = this.is0();
31099
+ // If invZ was 0, we return zero point. However we still want to execute
31100
+ // all operations, so we replace invZ with a random number, 1.
31101
+ if (iz == null)
31102
+ iz = is0 ? Fp.ONE : Fp.inv(z);
31103
+ const ax = Fp.mul(x, iz);
31104
+ const ay = Fp.mul(y, iz);
31105
+ const zz = Fp.mul(z, iz);
31106
+ if (is0)
31107
+ return { x: Fp.ZERO, y: Fp.ZERO };
31108
+ if (!Fp.eql(zz, Fp.ONE))
31109
+ throw new Error('invZ was invalid');
31110
+ return { x: ax, y: ay };
31111
+ }
31112
+ isTorsionFree() {
31113
+ const { h: cofactor, isTorsionFree } = CURVE;
31114
+ if (cofactor === _1n)
31115
+ return true; // No subgroups, always torsion-free
31116
+ if (isTorsionFree)
31117
+ return isTorsionFree(Point, this);
31118
+ throw new Error('isTorsionFree() has not been declared for the elliptic curve');
31119
+ }
31120
+ clearCofactor() {
31121
+ const { h: cofactor, clearCofactor } = CURVE;
31122
+ if (cofactor === _1n)
31123
+ return this; // Fast-path
31124
+ if (clearCofactor)
31125
+ return clearCofactor(Point, this);
31126
+ return this.multiplyUnsafe(CURVE.h);
31127
+ }
31128
+ toRawBytes(isCompressed = true) {
31129
+ this.assertValidity();
31130
+ return toBytes(Point, this, isCompressed);
31131
+ }
31132
+ toHex(isCompressed = true) {
31133
+ return ut.bytesToHex(this.toRawBytes(isCompressed));
31134
+ }
31135
+ }
31136
+ Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
31137
+ Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
31138
+ const _bits = CURVE.nBitLength;
31139
+ const wnaf = (0, curve_js_1.wNAF)(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits);
31140
+ // Validate if generator point is on curve
31141
+ return {
31142
+ CURVE,
31143
+ ProjectivePoint: Point,
31144
+ normPrivateKeyToScalar,
31145
+ weierstrassEquation,
31146
+ isWithinCurveOrder,
31147
+ };
31148
+ }
31149
+ exports.weierstrassPoints = weierstrassPoints;
31150
+ function validateOpts(curve) {
31151
+ const opts = (0, curve_js_1.validateBasic)(curve);
31152
+ ut.validateObject(opts, {
31153
+ hash: 'hash',
31154
+ hmac: 'function',
31155
+ randomBytes: 'function',
31156
+ }, {
31157
+ bits2int: 'function',
31158
+ bits2int_modN: 'function',
31159
+ lowS: 'boolean',
31160
+ });
31161
+ return Object.freeze({ lowS: true, ...opts });
31162
+ }
31163
+ function weierstrass(curveDef) {
31164
+ const CURVE = validateOpts(curveDef);
31165
+ const { Fp, n: CURVE_ORDER } = CURVE;
31166
+ const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32
31167
+ const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32
31168
+ function isValidFieldElement(num) {
31169
+ return _0n < num && num < Fp.ORDER; // 0 is banned since it's not invertible FE
31170
+ }
31171
+ function modN(a) {
31172
+ return mod.mod(a, CURVE_ORDER);
31173
+ }
31174
+ function invN(a) {
31175
+ return mod.invert(a, CURVE_ORDER);
31176
+ }
31177
+ const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder, } = weierstrassPoints({
31178
+ ...CURVE,
31179
+ toBytes(c, point, isCompressed) {
31180
+ const a = point.toAffine();
31181
+ const x = Fp.toBytes(a.x);
31182
+ const cat = ut.concatBytes;
31183
+ if (isCompressed) {
31184
+ return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x);
31185
+ }
31186
+ else {
31187
+ return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y));
31188
+ }
31189
+ },
31190
+ fromBytes(bytes) {
31191
+ const len = bytes.length;
31192
+ const head = bytes[0];
31193
+ const tail = bytes.subarray(1);
31194
+ // this.assertValidity() is done inside of fromHex
31195
+ if (len === compressedLen && (head === 0x02 || head === 0x03)) {
31196
+ const x = ut.bytesToNumberBE(tail);
31197
+ if (!isValidFieldElement(x))
31198
+ throw new Error('Point is not on curve');
31199
+ const y2 = weierstrassEquation(x); // y² = x³ + ax + b
31200
+ let y = Fp.sqrt(y2); // y = y² ^ (p+1)/4
31201
+ const isYOdd = (y & _1n) === _1n;
31202
+ // ECDSA
31203
+ const isHeadOdd = (head & 1) === 1;
31204
+ if (isHeadOdd !== isYOdd)
31205
+ y = Fp.neg(y);
31206
+ return { x, y };
31207
+ }
31208
+ else if (len === uncompressedLen && head === 0x04) {
31209
+ const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));
31210
+ const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));
31211
+ return { x, y };
31212
+ }
31213
+ else {
31214
+ throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`);
31215
+ }
31216
+ },
31217
+ });
31218
+ const numToNByteStr = (num) => ut.bytesToHex(ut.numberToBytesBE(num, CURVE.nByteLength));
31219
+ function isBiggerThanHalfOrder(number) {
31220
+ const HALF = CURVE_ORDER >> _1n;
31221
+ return number > HALF;
31222
+ }
31223
+ function normalizeS(s) {
31224
+ return isBiggerThanHalfOrder(s) ? modN(-s) : s;
31225
+ }
31226
+ // slice bytes num
31227
+ const slcNum = (b, from, to) => ut.bytesToNumberBE(b.slice(from, to));
31228
+ /**
31229
+ * ECDSA signature with its (r, s) properties. Supports DER & compact representations.
31230
+ */
31231
+ class Signature {
31232
+ constructor(r, s, recovery) {
31233
+ this.r = r;
31234
+ this.s = s;
31235
+ this.recovery = recovery;
31236
+ this.assertValidity();
31237
+ }
31238
+ // pair (bytes of r, bytes of s)
31239
+ static fromCompact(hex) {
31240
+ const l = CURVE.nByteLength;
31241
+ hex = (0, utils_js_1.ensureBytes)('compactSignature', hex, l * 2);
31242
+ return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));
31243
+ }
31244
+ // DER encoded ECDSA signature
31245
+ // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script
31246
+ static fromDER(hex) {
31247
+ const { r, s } = exports.DER.toSig((0, utils_js_1.ensureBytes)('DER', hex));
31248
+ return new Signature(r, s);
31249
+ }
31250
+ assertValidity() {
31251
+ // can use assertGE here
31252
+ if (!isWithinCurveOrder(this.r))
31253
+ throw new Error('r must be 0 < r < CURVE.n');
31254
+ if (!isWithinCurveOrder(this.s))
31255
+ throw new Error('s must be 0 < s < CURVE.n');
31256
+ }
31257
+ addRecoveryBit(recovery) {
31258
+ return new Signature(this.r, this.s, recovery);
31259
+ }
31260
+ recoverPublicKey(msgHash) {
31261
+ const { r, s, recovery: rec } = this;
31262
+ const h = bits2int_modN((0, utils_js_1.ensureBytes)('msgHash', msgHash)); // Truncate hash
31263
+ if (rec == null || ![0, 1, 2, 3].includes(rec))
31264
+ throw new Error('recovery id invalid');
31265
+ const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;
31266
+ if (radj >= Fp.ORDER)
31267
+ throw new Error('recovery id 2 or 3 invalid');
31268
+ const prefix = (rec & 1) === 0 ? '02' : '03';
31269
+ const R = Point.fromHex(prefix + numToNByteStr(radj));
31270
+ const ir = invN(radj); // r^-1
31271
+ const u1 = modN(-h * ir); // -hr^-1
31272
+ const u2 = modN(s * ir); // sr^-1
31273
+ const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1)
31274
+ if (!Q)
31275
+ throw new Error('point at infinify'); // unsafe is fine: no priv data leaked
31276
+ Q.assertValidity();
31277
+ return Q;
31278
+ }
31279
+ // Signatures should be low-s, to prevent malleability.
31280
+ hasHighS() {
31281
+ return isBiggerThanHalfOrder(this.s);
31282
+ }
31283
+ normalizeS() {
31284
+ return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this;
31285
+ }
31286
+ // DER-encoded
31287
+ toDERRawBytes() {
31288
+ return ut.hexToBytes(this.toDERHex());
31289
+ }
31290
+ toDERHex() {
31291
+ return exports.DER.hexFromSig({ r: this.r, s: this.s });
31292
+ }
31293
+ // padded bytes of r, then padded bytes of s
31294
+ toCompactRawBytes() {
31295
+ return ut.hexToBytes(this.toCompactHex());
31296
+ }
31297
+ toCompactHex() {
31298
+ return numToNByteStr(this.r) + numToNByteStr(this.s);
31299
+ }
31300
+ }
31301
+ const utils = {
31302
+ isValidPrivateKey(privateKey) {
31303
+ try {
31304
+ normPrivateKeyToScalar(privateKey);
31305
+ return true;
31306
+ }
31307
+ catch (error) {
31308
+ return false;
31309
+ }
31310
+ },
31311
+ normPrivateKeyToScalar: normPrivateKeyToScalar,
31312
+ /**
31313
+ * Produces cryptographically secure private key from random of size (nBitLength+64)
31314
+ * as per FIPS 186 B.4.1 with modulo bias being neglible.
31315
+ */
31316
+ randomPrivateKey: () => {
31317
+ const rand = CURVE.randomBytes(Fp.BYTES + 8);
31318
+ const num = mod.hashToPrivateScalar(rand, CURVE_ORDER);
31319
+ return ut.numberToBytesBE(num, CURVE.nByteLength);
31320
+ },
31321
+ /**
31322
+ * Creates precompute table for an arbitrary EC point. Makes point "cached".
31323
+ * Allows to massively speed-up `point.multiply(scalar)`.
31324
+ * @returns cached point
31325
+ * @example
31326
+ * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));
31327
+ * fast.multiply(privKey); // much faster ECDH now
31328
+ */
31329
+ precompute(windowSize = 8, point = Point.BASE) {
31330
+ point._setWindowSize(windowSize);
31331
+ point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here
31332
+ return point;
31333
+ },
31334
+ };
31335
+ /**
31336
+ * Computes public key for a private key. Checks for validity of the private key.
31337
+ * @param privateKey private key
31338
+ * @param isCompressed whether to return compact (default), or full key
31339
+ * @returns Public key, full when isCompressed=false; short when isCompressed=true
31340
+ */
31341
+ function getPublicKey(privateKey, isCompressed = true) {
31342
+ return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);
31343
+ }
31344
+ /**
31345
+ * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.
31346
+ */
31347
+ function isProbPub(item) {
31348
+ const arr = item instanceof Uint8Array;
31349
+ const str = typeof item === 'string';
31350
+ const len = (arr || str) && item.length;
31351
+ if (arr)
31352
+ return len === compressedLen || len === uncompressedLen;
31353
+ if (str)
31354
+ return len === 2 * compressedLen || len === 2 * uncompressedLen;
31355
+ if (item instanceof Point)
31356
+ return true;
31357
+ return false;
31358
+ }
31359
+ /**
31360
+ * ECDH (Elliptic Curve Diffie Hellman).
31361
+ * Computes shared public key from private key and public key.
31362
+ * Checks: 1) private key validity 2) shared key is on-curve.
31363
+ * Does NOT hash the result.
31364
+ * @param privateA private key
31365
+ * @param publicB different public key
31366
+ * @param isCompressed whether to return compact (default), or full key
31367
+ * @returns shared public key
31368
+ */
31369
+ function getSharedSecret(privateA, publicB, isCompressed = true) {
31370
+ if (isProbPub(privateA))
31371
+ throw new Error('first arg must be private key');
31372
+ if (!isProbPub(publicB))
31373
+ throw new Error('second arg must be public key');
31374
+ const b = Point.fromHex(publicB); // check for being on-curve
31375
+ return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);
31376
+ }
31377
+ // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.
31378
+ // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.
31379
+ // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.
31380
+ // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors
31381
+ const bits2int = CURVE.bits2int ||
31382
+ function (bytes) {
31383
+ // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)
31384
+ // for some cases, since bytes.length * 8 is not actual bitLength.
31385
+ const num = ut.bytesToNumberBE(bytes); // check for == u8 done here
31386
+ const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits
31387
+ return delta > 0 ? num >> BigInt(delta) : num;
31388
+ };
31389
+ const bits2int_modN = CURVE.bits2int_modN ||
31390
+ function (bytes) {
31391
+ return modN(bits2int(bytes)); // can't use bytesToNumberBE here
31392
+ };
31393
+ // NOTE: pads output with zero as per spec
31394
+ const ORDER_MASK = ut.bitMask(CURVE.nBitLength);
31395
+ /**
31396
+ * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.
31397
+ */
31398
+ function int2octets(num) {
31399
+ if (typeof num !== 'bigint')
31400
+ throw new Error('bigint expected');
31401
+ if (!(_0n <= num && num < ORDER_MASK))
31402
+ throw new Error(`bigint expected < 2^${CURVE.nBitLength}`);
31403
+ // works with order, can have different size than numToField!
31404
+ return ut.numberToBytesBE(num, CURVE.nByteLength);
31405
+ }
31406
+ // Steps A, D of RFC6979 3.2
31407
+ // Creates RFC6979 seed; converts msg/privKey to numbers.
31408
+ // Used only in sign, not in verify.
31409
+ // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521.
31410
+ // Also it can be bigger for P224 + SHA256
31411
+ function prepSig(msgHash, privateKey, opts = defaultSigOpts) {
31412
+ if (['recovered', 'canonical'].some((k) => k in opts))
31413
+ throw new Error('sign() legacy options not supported');
31414
+ const { hash, randomBytes } = CURVE;
31415
+ let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default
31416
+ if (lowS == null)
31417
+ lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash
31418
+ msgHash = (0, utils_js_1.ensureBytes)('msgHash', msgHash);
31419
+ if (prehash)
31420
+ msgHash = (0, utils_js_1.ensureBytes)('prehashed msgHash', hash(msgHash));
31421
+ // We can't later call bits2octets, since nested bits2int is broken for curves
31422
+ // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call.
31423
+ // const bits2octets = (bits) => int2octets(bits2int_modN(bits))
31424
+ const h1int = bits2int_modN(msgHash);
31425
+ const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint
31426
+ const seedArgs = [int2octets(d), int2octets(h1int)];
31427
+ // extraEntropy. RFC6979 3.6: additional k' (optional).
31428
+ if (ent != null) {
31429
+ // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')
31430
+ const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is
31431
+ seedArgs.push((0, utils_js_1.ensureBytes)('extraEntropy', e, Fp.BYTES)); // check for being of size BYTES
31432
+ }
31433
+ const seed = ut.concatBytes(...seedArgs); // Step D of RFC6979 3.2
31434
+ const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!
31435
+ // Converts signature params into point w r/s, checks result for validity.
31436
+ function k2sig(kBytes) {
31437
+ // RFC 6979 Section 3.2, step 3: k = bits2int(T)
31438
+ const k = bits2int(kBytes); // Cannot use fields methods, since it is group element
31439
+ if (!isWithinCurveOrder(k))
31440
+ return; // Important: all mod() calls here must be done over N
31441
+ const ik = invN(k); // k^-1 mod n
31442
+ const q = Point.BASE.multiply(k).toAffine(); // q = Gk
31443
+ const r = modN(q.x); // r = q.x mod n
31444
+ if (r === _0n)
31445
+ return;
31446
+ // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to
31447
+ // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:
31448
+ // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT
31449
+ const s = modN(ik * modN(m + r * d)); // Not using blinding here
31450
+ if (s === _0n)
31451
+ return;
31452
+ let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)
31453
+ let normS = s;
31454
+ if (lowS && isBiggerThanHalfOrder(s)) {
31455
+ normS = normalizeS(s); // if lowS was passed, ensure s is always
31456
+ recovery ^= 1; // // in the bottom half of N
31457
+ }
31458
+ return new Signature(r, normS, recovery); // use normS, not s
31459
+ }
31460
+ return { seed, k2sig };
31461
+ }
31462
+ const defaultSigOpts = { lowS: CURVE.lowS, prehash: false };
31463
+ const defaultVerOpts = { lowS: CURVE.lowS, prehash: false };
31464
+ /**
31465
+ * Signs message hash (not message: you need to hash it by yourself).
31466
+ * ```
31467
+ * sign(m, d, k) where
31468
+ * (x, y) = G × k
31469
+ * r = x mod n
31470
+ * s = (m + dr)/k mod n
31471
+ * ```
31472
+ * @param opts `lowS, extraEntropy, prehash`
31473
+ */
31474
+ function sign(msgHash, privKey, opts = defaultSigOpts) {
31475
+ const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2.
31476
+ const drbg = ut.createHmacDrbg(CURVE.hash.outputLen, CURVE.nByteLength, CURVE.hmac);
31477
+ return drbg(seed, k2sig); // Steps B, C, D, E, F, G
31478
+ }
31479
+ // Enable precomputes. Slows down first publicKey computation by 20ms.
31480
+ Point.BASE._setWindowSize(8);
31481
+ // utils.precompute(8, ProjectivePoint.BASE)
31482
+ /**
31483
+ * Verifies a signature against message hash and public key.
31484
+ * Rejects lowS signatures by default: to override,
31485
+ * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:
31486
+ *
31487
+ * ```
31488
+ * verify(r, s, h, P) where
31489
+ * U1 = hs^-1 mod n
31490
+ * U2 = rs^-1 mod n
31491
+ * R = U1⋅G - U2⋅P
31492
+ * mod(R.x, n) == r
31493
+ * ```
31494
+ */
31495
+ function verify(signature, msgHash, publicKey, opts = defaultVerOpts) {
31496
+ const sg = signature;
31497
+ msgHash = (0, utils_js_1.ensureBytes)('msgHash', msgHash);
31498
+ publicKey = (0, utils_js_1.ensureBytes)('publicKey', publicKey);
31499
+ if ('strict' in opts)
31500
+ throw new Error('options.strict was renamed to lowS');
31501
+ const { lowS, prehash } = opts;
31502
+ let _sig = undefined;
31503
+ let P;
31504
+ try {
31505
+ if (typeof sg === 'string' || sg instanceof Uint8Array) {
31506
+ // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length).
31507
+ // Since DER can also be 2*nByteLength bytes, we check for it first.
31508
+ try {
31509
+ _sig = Signature.fromDER(sg);
31510
+ }
31511
+ catch (derError) {
31512
+ if (!(derError instanceof exports.DER.Err))
31513
+ throw derError;
31514
+ _sig = Signature.fromCompact(sg);
31515
+ }
31516
+ }
31517
+ else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') {
31518
+ const { r, s } = sg;
31519
+ _sig = new Signature(r, s);
31520
+ }
31521
+ else {
31522
+ throw new Error('PARSE');
31523
+ }
31524
+ P = Point.fromHex(publicKey);
31525
+ }
31526
+ catch (error) {
31527
+ if (error.message === 'PARSE')
31528
+ throw new Error(`signature must be Signature instance, Uint8Array or hex string`);
31529
+ return false;
31530
+ }
31531
+ if (lowS && _sig.hasHighS())
31532
+ return false;
31533
+ if (prehash)
31534
+ msgHash = CURVE.hash(msgHash);
31535
+ const { r, s } = _sig;
31536
+ const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element
31537
+ const is = invN(s); // s^-1
31538
+ const u1 = modN(h * is); // u1 = hs^-1 mod n
31539
+ const u2 = modN(r * is); // u2 = rs^-1 mod n
31540
+ const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P
31541
+ if (!R)
31542
+ return false;
31543
+ const v = modN(R.x);
31544
+ return v === r;
31545
+ }
31546
+ return {
31547
+ CURVE,
31548
+ getPublicKey,
31549
+ getSharedSecret,
31550
+ sign,
31551
+ verify,
31552
+ ProjectivePoint: Point,
31553
+ Signature,
31554
+ utils,
31555
+ };
31556
+ }
31557
+ exports.weierstrass = weierstrass;
31558
+ // Implementation of the Shallue and van de Woestijne method for any Weierstrass curve
31559
+ // TODO: check if there is a way to merge this with uvRatio in Edwards && move to modular?
31560
+ // b = True and y = sqrt(u / v) if (u / v) is square in F, and
31561
+ // b = False and y = sqrt(Z * (u / v)) otherwise.
31562
+ function SWUFpSqrtRatio(Fp, Z) {
31563
+ // Generic implementation
31564
+ const q = Fp.ORDER;
31565
+ let l = _0n;
31566
+ for (let o = q - _1n; o % _2n === _0n; o /= _2n)
31567
+ l += _1n;
31568
+ const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.
31569
+ const c2 = (q - _1n) / _2n ** c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic
31570
+ const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic
31571
+ const c4 = _2n ** c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic
31572
+ const c5 = _2n ** (c1 - _1n); // 5. c5 = 2^(c1 - 1) # Integer arithmetic
31573
+ const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2
31574
+ const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)
31575
+ let sqrtRatio = (u, v) => {
31576
+ let tv1 = c6; // 1. tv1 = c6
31577
+ let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4
31578
+ let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2
31579
+ tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v
31580
+ let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3
31581
+ tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3
31582
+ tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2
31583
+ tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v
31584
+ tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u
31585
+ let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2
31586
+ tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5
31587
+ let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1
31588
+ tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7
31589
+ tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1
31590
+ tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)
31591
+ tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)
31592
+ // 17. for i in (c1, c1 - 1, ..., 2):
31593
+ for (let i = c1; i > _1n; i--) {
31594
+ let tv5 = _2n ** (i - _2n); // 18. tv5 = i - 2; 19. tv5 = 2^tv5
31595
+ let tvv5 = Fp.pow(tv4, tv5); // 20. tv5 = tv4^tv5
31596
+ const e1 = Fp.eql(tvv5, Fp.ONE); // 21. e1 = tv5 == 1
31597
+ tv2 = Fp.mul(tv3, tv1); // 22. tv2 = tv3 * tv1
31598
+ tv1 = Fp.mul(tv1, tv1); // 23. tv1 = tv1 * tv1
31599
+ tvv5 = Fp.mul(tv4, tv1); // 24. tv5 = tv4 * tv1
31600
+ tv3 = Fp.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1)
31601
+ tv4 = Fp.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1)
31602
+ }
31603
+ return { isValid: isQR, value: tv3 };
31604
+ };
31605
+ if (Fp.ORDER % _4n === _3n) {
31606
+ // sqrt_ratio_3mod4(u, v)
31607
+ const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic
31608
+ const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)
31609
+ sqrtRatio = (u, v) => {
31610
+ let tv1 = Fp.sqr(v); // 1. tv1 = v^2
31611
+ const tv2 = Fp.mul(u, v); // 2. tv2 = u * v
31612
+ tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2
31613
+ let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1
31614
+ y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2
31615
+ const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2
31616
+ const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v
31617
+ const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u
31618
+ let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)
31619
+ return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2
31620
+ };
31621
+ }
31622
+ // No curves uses that
31623
+ // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8
31624
+ return sqrtRatio;
31625
+ }
31626
+ exports.SWUFpSqrtRatio = SWUFpSqrtRatio;
31627
+ // From draft-irtf-cfrg-hash-to-curve-16
31628
+ function mapToCurveSimpleSWU(Fp, opts) {
31629
+ mod.validateField(Fp);
31630
+ if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z))
31631
+ throw new Error('mapToCurveSimpleSWU: invalid opts');
31632
+ const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z);
31633
+ if (!Fp.isOdd)
31634
+ throw new Error('Fp.isOdd is not implemented!');
31635
+ // Input: u, an element of F.
31636
+ // Output: (x, y), a point on E.
31637
+ return (u) => {
31638
+ // prettier-ignore
31639
+ let tv1, tv2, tv3, tv4, tv5, tv6, x, y;
31640
+ tv1 = Fp.sqr(u); // 1. tv1 = u^2
31641
+ tv1 = Fp.mul(tv1, opts.Z); // 2. tv1 = Z * tv1
31642
+ tv2 = Fp.sqr(tv1); // 3. tv2 = tv1^2
31643
+ tv2 = Fp.add(tv2, tv1); // 4. tv2 = tv2 + tv1
31644
+ tv3 = Fp.add(tv2, Fp.ONE); // 5. tv3 = tv2 + 1
31645
+ tv3 = Fp.mul(tv3, opts.B); // 6. tv3 = B * tv3
31646
+ tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)
31647
+ tv4 = Fp.mul(tv4, opts.A); // 8. tv4 = A * tv4
31648
+ tv2 = Fp.sqr(tv3); // 9. tv2 = tv3^2
31649
+ tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2
31650
+ tv5 = Fp.mul(tv6, opts.A); // 11. tv5 = A * tv6
31651
+ tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5
31652
+ tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3
31653
+ tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4
31654
+ tv5 = Fp.mul(tv6, opts.B); // 15. tv5 = B * tv6
31655
+ tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5
31656
+ x = Fp.mul(tv1, tv3); // 17. x = tv1 * tv3
31657
+ const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)
31658
+ y = Fp.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1
31659
+ y = Fp.mul(y, value); // 20. y = y * y1
31660
+ x = Fp.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square)
31661
+ y = Fp.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square)
31662
+ const e1 = Fp.isOdd(u) === Fp.isOdd(y); // 23. e1 = sgn0(u) == sgn0(y)
31663
+ y = Fp.cmov(Fp.neg(y), y, e1); // 24. y = CMOV(-y, y, e1)
31664
+ x = Fp.div(x, tv4); // 25. x = x / tv4
31665
+ return { x, y };
31666
+ };
31667
+ }
31668
+ exports.mapToCurveSimpleSWU = mapToCurveSimpleSWU;
31669
+ //# sourceMappingURL=weierstrass.js.map
31670
+
31671
+ /***/ }),
31672
+
31673
+ /***/ "./node_modules/@noble/curves/secp256k1.js":
31674
+ /*!*************************************************!*\
31675
+ !*** ./node_modules/@noble/curves/secp256k1.js ***!
31676
+ \*************************************************/
31677
+ /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
31678
+
31679
+ "use strict";
31680
+
31681
+ var _a;
31682
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
31683
+ exports.encodeToCurve = exports.hashToCurve = exports.schnorr = exports.secp256k1 = void 0;
31684
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
31685
+ const sha256_1 = __webpack_require__(/*! @noble/hashes/sha256 */ "./node_modules/@noble/hashes/sha256.js");
31686
+ const utils_1 = __webpack_require__(/*! @noble/hashes/utils */ "./node_modules/@noble/hashes/utils.js");
31687
+ const modular_js_1 = __webpack_require__(/*! ./abstract/modular.js */ "./node_modules/@noble/curves/abstract/modular.js");
31688
+ const weierstrass_js_1 = __webpack_require__(/*! ./abstract/weierstrass.js */ "./node_modules/@noble/curves/abstract/weierstrass.js");
31689
+ const utils_js_1 = __webpack_require__(/*! ./abstract/utils.js */ "./node_modules/@noble/curves/abstract/utils.js");
31690
+ const htf = __webpack_require__(/*! ./abstract/hash-to-curve.js */ "./node_modules/@noble/curves/abstract/hash-to-curve.js");
31691
+ const _shortw_utils_js_1 = __webpack_require__(/*! ./_shortw_utils.js */ "./node_modules/@noble/curves/_shortw_utils.js");
31692
+ const secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');
31693
+ const secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');
31694
+ const _1n = BigInt(1);
31695
+ const _2n = BigInt(2);
31696
+ const divNearest = (a, b) => (a + b / _2n) / b;
31697
+ /**
31698
+ * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.
31699
+ * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]
31700
+ */
31701
+ function sqrtMod(y) {
31702
+ const P = secp256k1P;
31703
+ // prettier-ignore
31704
+ const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
31705
+ // prettier-ignore
31706
+ const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
31707
+ const b2 = (y * y * y) % P; // x^3, 11
31708
+ const b3 = (b2 * b2 * y) % P; // x^7
31709
+ const b6 = ((0, modular_js_1.pow2)(b3, _3n, P) * b3) % P;
31710
+ const b9 = ((0, modular_js_1.pow2)(b6, _3n, P) * b3) % P;
31711
+ const b11 = ((0, modular_js_1.pow2)(b9, _2n, P) * b2) % P;
31712
+ const b22 = ((0, modular_js_1.pow2)(b11, _11n, P) * b11) % P;
31713
+ const b44 = ((0, modular_js_1.pow2)(b22, _22n, P) * b22) % P;
31714
+ const b88 = ((0, modular_js_1.pow2)(b44, _44n, P) * b44) % P;
31715
+ const b176 = ((0, modular_js_1.pow2)(b88, _88n, P) * b88) % P;
31716
+ const b220 = ((0, modular_js_1.pow2)(b176, _44n, P) * b44) % P;
31717
+ const b223 = ((0, modular_js_1.pow2)(b220, _3n, P) * b3) % P;
31718
+ const t1 = ((0, modular_js_1.pow2)(b223, _23n, P) * b22) % P;
31719
+ const t2 = ((0, modular_js_1.pow2)(t1, _6n, P) * b2) % P;
31720
+ const root = (0, modular_js_1.pow2)(t2, _2n, P);
31721
+ if (!Fp.eql(Fp.sqr(root), y))
31722
+ throw new Error('Cannot find square root');
31723
+ return root;
31724
+ }
31725
+ const Fp = (0, modular_js_1.Field)(secp256k1P, undefined, undefined, { sqrt: sqrtMod });
31726
+ exports.secp256k1 = (0, _shortw_utils_js_1.createCurve)({
31727
+ a: BigInt(0),
31728
+ b: BigInt(7),
31729
+ Fp,
31730
+ n: secp256k1N,
31731
+ // Base point (x, y) aka generator point
31732
+ Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),
31733
+ Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),
31734
+ h: BigInt(1),
31735
+ lowS: true,
31736
+ /**
31737
+ * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.
31738
+ * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.
31739
+ * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.
31740
+ * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066
31741
+ */
31742
+ endo: {
31743
+ beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),
31744
+ splitScalar: (k) => {
31745
+ const n = secp256k1N;
31746
+ const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15');
31747
+ const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3');
31748
+ const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8');
31749
+ const b2 = a1;
31750
+ const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16)
31751
+ const c1 = divNearest(b2 * k, n);
31752
+ const c2 = divNearest(-b1 * k, n);
31753
+ let k1 = (0, modular_js_1.mod)(k - c1 * a1 - c2 * a2, n);
31754
+ let k2 = (0, modular_js_1.mod)(-c1 * b1 - c2 * b2, n);
31755
+ const k1neg = k1 > POW_2_128;
31756
+ const k2neg = k2 > POW_2_128;
31757
+ if (k1neg)
31758
+ k1 = n - k1;
31759
+ if (k2neg)
31760
+ k2 = n - k2;
31761
+ if (k1 > POW_2_128 || k2 > POW_2_128) {
31762
+ throw new Error('splitScalar: Endomorphism failed, k=' + k);
31763
+ }
31764
+ return { k1neg, k1, k2neg, k2 };
31765
+ },
31766
+ },
31767
+ }, sha256_1.sha256);
31768
+ // Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.
31769
+ // https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki
31770
+ const _0n = BigInt(0);
31771
+ const fe = (x) => typeof x === 'bigint' && _0n < x && x < secp256k1P;
31772
+ const ge = (x) => typeof x === 'bigint' && _0n < x && x < secp256k1N;
31773
+ /** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */
31774
+ const TAGGED_HASH_PREFIXES = {};
31775
+ function taggedHash(tag, ...messages) {
31776
+ let tagP = TAGGED_HASH_PREFIXES[tag];
31777
+ if (tagP === undefined) {
31778
+ const tagH = (0, sha256_1.sha256)(Uint8Array.from(tag, (c) => c.charCodeAt(0)));
31779
+ tagP = (0, utils_js_1.concatBytes)(tagH, tagH);
31780
+ TAGGED_HASH_PREFIXES[tag] = tagP;
31781
+ }
31782
+ return (0, sha256_1.sha256)((0, utils_js_1.concatBytes)(tagP, ...messages));
31783
+ }
31784
+ // ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03
31785
+ const pointToBytes = (point) => point.toRawBytes(true).slice(1);
31786
+ const numTo32b = (n) => (0, utils_js_1.numberToBytesBE)(n, 32);
31787
+ const modP = (x) => (0, modular_js_1.mod)(x, secp256k1P);
31788
+ const modN = (x) => (0, modular_js_1.mod)(x, secp256k1N);
31789
+ const Point = exports.secp256k1.ProjectivePoint;
31790
+ const GmulAdd = (Q, a, b) => Point.BASE.multiplyAndAddUnsafe(Q, a, b);
31791
+ // Calculate point, scalar and bytes
31792
+ function schnorrGetExtPubKey(priv) {
31793
+ let d_ = exports.secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey
31794
+ let p = Point.fromPrivateKey(d_); // P = d'⋅G; 0 < d' < n check is done inside
31795
+ const scalar = p.hasEvenY() ? d_ : modN(-d_);
31796
+ return { scalar: scalar, bytes: pointToBytes(p) };
31797
+ }
31798
+ /**
31799
+ * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.
31800
+ * @returns valid point checked for being on-curve
31801
+ */
31802
+ function lift_x(x) {
31803
+ if (!fe(x))
31804
+ throw new Error('bad x: need 0 < x < p'); // Fail if x ≥ p.
31805
+ const xx = modP(x * x);
31806
+ const c = modP(xx * x + BigInt(7)); // Let c = x³ + 7 mod p.
31807
+ let y = sqrtMod(c); // Let y = c^(p+1)/4 mod p.
31808
+ if (y % _2n !== _0n)
31809
+ y = modP(-y); // Return the unique point P such that x(P) = x and
31810
+ const p = new Point(x, y, _1n); // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.
31811
+ p.assertValidity();
31812
+ return p;
31813
+ }
31814
+ /**
31815
+ * Create tagged hash, convert it to bigint, reduce modulo-n.
31816
+ */
31817
+ function challenge(...args) {
31818
+ return modN((0, utils_js_1.bytesToNumberBE)(taggedHash('BIP0340/challenge', ...args)));
31819
+ }
31820
+ /**
31821
+ * Schnorr public key is just `x` coordinate of Point as per BIP340.
31822
+ */
31823
+ function schnorrGetPublicKey(privateKey) {
31824
+ return schnorrGetExtPubKey(privateKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G)
31825
+ }
31826
+ /**
31827
+ * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.
31828
+ * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.
31829
+ */
31830
+ function schnorrSign(message, privateKey, auxRand = (0, utils_1.randomBytes)(32)) {
31831
+ const m = (0, utils_js_1.ensureBytes)('message', message);
31832
+ const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); // checks for isWithinCurveOrder
31833
+ const a = (0, utils_js_1.ensureBytes)('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array
31834
+ const t = numTo32b(d ^ (0, utils_js_1.bytesToNumberBE)(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)
31835
+ const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)
31836
+ const k_ = modN((0, utils_js_1.bytesToNumberBE)(rand)); // Let k' = int(rand) mod n
31837
+ if (k_ === _0n)
31838
+ throw new Error('sign failed: k is zero'); // Fail if k' = 0.
31839
+ const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'⋅G.
31840
+ const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.
31841
+ const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).
31842
+ sig.set(rx, 0);
31843
+ sig.set(numTo32b(modN(k + e * d)), 32);
31844
+ // If Verify(bytes(P), m, sig) (see below) returns failure, abort
31845
+ if (!schnorrVerify(sig, m, px))
31846
+ throw new Error('sign: Invalid signature produced');
31847
+ return sig;
31848
+ }
31849
+ /**
31850
+ * Verifies Schnorr signature.
31851
+ * Will swallow errors & return false except for initial type validation of arguments.
31852
+ */
31853
+ function schnorrVerify(signature, message, publicKey) {
31854
+ const sig = (0, utils_js_1.ensureBytes)('signature', signature, 64);
31855
+ const m = (0, utils_js_1.ensureBytes)('message', message);
31856
+ const pub = (0, utils_js_1.ensureBytes)('publicKey', publicKey, 32);
31857
+ try {
31858
+ const P = lift_x((0, utils_js_1.bytesToNumberBE)(pub)); // P = lift_x(int(pk)); fail if that fails
31859
+ const r = (0, utils_js_1.bytesToNumberBE)(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p.
31860
+ if (!fe(r))
31861
+ return false;
31862
+ const s = (0, utils_js_1.bytesToNumberBE)(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.
31863
+ if (!ge(s))
31864
+ return false;
31865
+ const e = challenge(numTo32b(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n
31866
+ const R = GmulAdd(P, s, modN(-e)); // R = s⋅G - e⋅P
31867
+ if (!R || !R.hasEvenY() || R.toAffine().x !== r)
31868
+ return false; // -eP == (n-e)P
31869
+ return true; // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.
31870
+ }
31871
+ catch (error) {
31872
+ return false;
31873
+ }
31874
+ }
31875
+ exports.schnorr = {
31876
+ getPublicKey: schnorrGetPublicKey,
31877
+ sign: schnorrSign,
31878
+ verify: schnorrVerify,
31879
+ utils: {
31880
+ randomPrivateKey: exports.secp256k1.utils.randomPrivateKey,
31881
+ lift_x,
31882
+ pointToBytes,
31883
+ numberToBytesBE: utils_js_1.numberToBytesBE,
31884
+ bytesToNumberBE: utils_js_1.bytesToNumberBE,
31885
+ taggedHash,
31886
+ mod: modular_js_1.mod,
31887
+ },
31888
+ };
31889
+ const isoMap = htf.isogenyMap(Fp, [
31890
+ // xNum
31891
+ [
31892
+ '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',
31893
+ '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',
31894
+ '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',
31895
+ '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',
31896
+ ],
31897
+ // xDen
31898
+ [
31899
+ '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',
31900
+ '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',
31901
+ '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1
31902
+ ],
31903
+ // yNum
31904
+ [
31905
+ '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',
31906
+ '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',
31907
+ '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',
31908
+ '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',
31909
+ ],
31910
+ // yDen
31911
+ [
31912
+ '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',
31913
+ '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',
31914
+ '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',
31915
+ '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1
31916
+ ],
31917
+ ].map((i) => i.map((j) => BigInt(j))));
31918
+ const mapSWU = (0, weierstrass_js_1.mapToCurveSimpleSWU)(Fp, {
31919
+ A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),
31920
+ B: BigInt('1771'),
31921
+ Z: Fp.create(BigInt('-11')),
31922
+ });
31923
+ _a = htf.createHasher(exports.secp256k1.ProjectivePoint, (scalars) => {
31924
+ const { x, y } = mapSWU(Fp.create(scalars[0]));
31925
+ return isoMap(x, y);
31926
+ }, {
31927
+ DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',
31928
+ encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',
31929
+ p: Fp.ORDER,
31930
+ m: 1,
31931
+ k: 128,
31932
+ expand: 'xmd',
31933
+ hash: sha256_1.sha256,
31934
+ }), exports.hashToCurve = _a.hashToCurve, exports.encodeToCurve = _a.encodeToCurve;
31935
+ //# sourceMappingURL=secp256k1.js.map
31936
+
31937
+ /***/ }),
31938
+
31939
+ /***/ "./node_modules/@noble/hashes/_assert.js":
31940
+ /*!***********************************************!*\
31941
+ !*** ./node_modules/@noble/hashes/_assert.js ***!
31942
+ \***********************************************/
31943
+ /***/ ((__unused_webpack_module, exports) => {
31944
+
31945
+ "use strict";
31946
+
31947
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
31948
+ exports.output = exports.exists = exports.hash = exports.bytes = exports.bool = exports.number = void 0;
31949
+ function number(n) {
31950
+ if (!Number.isSafeInteger(n) || n < 0)
31951
+ throw new Error(`Wrong positive integer: ${n}`);
31952
+ }
31953
+ exports.number = number;
31954
+ function bool(b) {
31955
+ if (typeof b !== 'boolean')
31956
+ throw new Error(`Expected boolean, not ${b}`);
31957
+ }
31958
+ exports.bool = bool;
31959
+ function bytes(b, ...lengths) {
31960
+ if (!(b instanceof Uint8Array))
31961
+ throw new TypeError('Expected Uint8Array');
31962
+ if (lengths.length > 0 && !lengths.includes(b.length))
31963
+ throw new TypeError(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`);
31964
+ }
31965
+ exports.bytes = bytes;
31966
+ function hash(hash) {
31967
+ if (typeof hash !== 'function' || typeof hash.create !== 'function')
31968
+ throw new Error('Hash should be wrapped by utils.wrapConstructor');
31969
+ number(hash.outputLen);
31970
+ number(hash.blockLen);
31971
+ }
31972
+ exports.hash = hash;
31973
+ function exists(instance, checkFinished = true) {
31974
+ if (instance.destroyed)
31975
+ throw new Error('Hash instance has been destroyed');
31976
+ if (checkFinished && instance.finished)
31977
+ throw new Error('Hash#digest() has already been called');
31978
+ }
31979
+ exports.exists = exists;
31980
+ function output(out, instance) {
31981
+ bytes(out);
31982
+ const min = instance.outputLen;
31983
+ if (out.length < min) {
31984
+ throw new Error(`digestInto() expects output buffer of length at least ${min}`);
31985
+ }
31986
+ }
31987
+ exports.output = output;
31988
+ const assert = {
31989
+ number,
31990
+ bool,
31991
+ bytes,
31992
+ hash,
31993
+ exists,
31994
+ output,
31995
+ };
31996
+ exports["default"] = assert;
31997
+ //# sourceMappingURL=_assert.js.map
31998
+
31999
+ /***/ }),
32000
+
32001
+ /***/ "./node_modules/@noble/hashes/_sha2.js":
32002
+ /*!*********************************************!*\
32003
+ !*** ./node_modules/@noble/hashes/_sha2.js ***!
32004
+ \*********************************************/
32005
+ /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
32006
+
32007
+ "use strict";
32008
+
32009
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
32010
+ exports.SHA2 = void 0;
32011
+ const _assert_js_1 = __webpack_require__(/*! ./_assert.js */ "./node_modules/@noble/hashes/_assert.js");
32012
+ const utils_js_1 = __webpack_require__(/*! ./utils.js */ "./node_modules/@noble/hashes/utils.js");
32013
+ // Polyfill for Safari 14
32014
+ function setBigUint64(view, byteOffset, value, isLE) {
32015
+ if (typeof view.setBigUint64 === 'function')
32016
+ return view.setBigUint64(byteOffset, value, isLE);
32017
+ const _32n = BigInt(32);
32018
+ const _u32_max = BigInt(0xffffffff);
32019
+ const wh = Number((value >> _32n) & _u32_max);
32020
+ const wl = Number(value & _u32_max);
32021
+ const h = isLE ? 4 : 0;
32022
+ const l = isLE ? 0 : 4;
32023
+ view.setUint32(byteOffset + h, wh, isLE);
32024
+ view.setUint32(byteOffset + l, wl, isLE);
32025
+ }
32026
+ // Base SHA2 class (RFC 6234)
32027
+ class SHA2 extends utils_js_1.Hash {
32028
+ constructor(blockLen, outputLen, padOffset, isLE) {
32029
+ super();
32030
+ this.blockLen = blockLen;
32031
+ this.outputLen = outputLen;
32032
+ this.padOffset = padOffset;
32033
+ this.isLE = isLE;
32034
+ this.finished = false;
32035
+ this.length = 0;
32036
+ this.pos = 0;
32037
+ this.destroyed = false;
32038
+ this.buffer = new Uint8Array(blockLen);
32039
+ this.view = (0, utils_js_1.createView)(this.buffer);
32040
+ }
32041
+ update(data) {
32042
+ _assert_js_1.default.exists(this);
32043
+ const { view, buffer, blockLen } = this;
32044
+ data = (0, utils_js_1.toBytes)(data);
32045
+ const len = data.length;
32046
+ for (let pos = 0; pos < len;) {
32047
+ const take = Math.min(blockLen - this.pos, len - pos);
32048
+ // Fast path: we have at least one block in input, cast it to view and process
32049
+ if (take === blockLen) {
32050
+ const dataView = (0, utils_js_1.createView)(data);
32051
+ for (; blockLen <= len - pos; pos += blockLen)
32052
+ this.process(dataView, pos);
32053
+ continue;
32054
+ }
32055
+ buffer.set(data.subarray(pos, pos + take), this.pos);
32056
+ this.pos += take;
32057
+ pos += take;
32058
+ if (this.pos === blockLen) {
32059
+ this.process(view, 0);
32060
+ this.pos = 0;
32061
+ }
32062
+ }
32063
+ this.length += data.length;
32064
+ this.roundClean();
32065
+ return this;
32066
+ }
32067
+ digestInto(out) {
32068
+ _assert_js_1.default.exists(this);
32069
+ _assert_js_1.default.output(out, this);
32070
+ this.finished = true;
32071
+ // Padding
32072
+ // We can avoid allocation of buffer for padding completely if it
32073
+ // was previously not allocated here. But it won't change performance.
32074
+ const { buffer, view, blockLen, isLE } = this;
32075
+ let { pos } = this;
32076
+ // append the bit '1' to the message
32077
+ buffer[pos++] = 0b10000000;
32078
+ this.buffer.subarray(pos).fill(0);
32079
+ // we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again
32080
+ if (this.padOffset > blockLen - pos) {
32081
+ this.process(view, 0);
32082
+ pos = 0;
32083
+ }
32084
+ // Pad until full block byte with zeros
32085
+ for (let i = pos; i < blockLen; i++)
32086
+ buffer[i] = 0;
32087
+ // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that
32088
+ // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.
32089
+ // So we just write lowest 64 bits of that value.
32090
+ setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
32091
+ this.process(view, 0);
32092
+ const oview = (0, utils_js_1.createView)(out);
32093
+ const len = this.outputLen;
32094
+ // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT
32095
+ if (len % 4)
32096
+ throw new Error('_sha2: outputLen should be aligned to 32bit');
32097
+ const outLen = len / 4;
32098
+ const state = this.get();
32099
+ if (outLen > state.length)
32100
+ throw new Error('_sha2: outputLen bigger than state');
32101
+ for (let i = 0; i < outLen; i++)
32102
+ oview.setUint32(4 * i, state[i], isLE);
32103
+ }
32104
+ digest() {
32105
+ const { buffer, outputLen } = this;
32106
+ this.digestInto(buffer);
32107
+ const res = buffer.slice(0, outputLen);
32108
+ this.destroy();
32109
+ return res;
32110
+ }
32111
+ _cloneInto(to) {
32112
+ to || (to = new this.constructor());
32113
+ to.set(...this.get());
32114
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
32115
+ to.length = length;
32116
+ to.pos = pos;
32117
+ to.finished = finished;
32118
+ to.destroyed = destroyed;
32119
+ if (length % blockLen)
32120
+ to.buffer.set(buffer);
32121
+ return to;
32122
+ }
32123
+ }
32124
+ exports.SHA2 = SHA2;
32125
+ //# sourceMappingURL=_sha2.js.map
32126
+
32127
+ /***/ }),
32128
+
32129
+ /***/ "./node_modules/@noble/hashes/crypto.js":
32130
+ /*!**********************************************!*\
32131
+ !*** ./node_modules/@noble/hashes/crypto.js ***!
32132
+ \**********************************************/
32133
+ /***/ ((__unused_webpack_module, exports) => {
32134
+
32135
+ "use strict";
32136
+
32137
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
32138
+ exports.crypto = void 0;
32139
+ exports.crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;
32140
+ //# sourceMappingURL=crypto.js.map
32141
+
32142
+ /***/ }),
32143
+
32144
+ /***/ "./node_modules/@noble/hashes/hmac.js":
32145
+ /*!********************************************!*\
32146
+ !*** ./node_modules/@noble/hashes/hmac.js ***!
32147
+ \********************************************/
32148
+ /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
32149
+
32150
+ "use strict";
32151
+
32152
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
32153
+ exports.hmac = void 0;
32154
+ const _assert_js_1 = __webpack_require__(/*! ./_assert.js */ "./node_modules/@noble/hashes/_assert.js");
32155
+ const utils_js_1 = __webpack_require__(/*! ./utils.js */ "./node_modules/@noble/hashes/utils.js");
32156
+ // HMAC (RFC 2104)
32157
+ class HMAC extends utils_js_1.Hash {
32158
+ constructor(hash, _key) {
32159
+ super();
32160
+ this.finished = false;
32161
+ this.destroyed = false;
32162
+ _assert_js_1.default.hash(hash);
32163
+ const key = (0, utils_js_1.toBytes)(_key);
32164
+ this.iHash = hash.create();
32165
+ if (typeof this.iHash.update !== 'function')
32166
+ throw new TypeError('Expected instance of class which extends utils.Hash');
32167
+ this.blockLen = this.iHash.blockLen;
32168
+ this.outputLen = this.iHash.outputLen;
32169
+ const blockLen = this.blockLen;
32170
+ const pad = new Uint8Array(blockLen);
32171
+ // blockLen can be bigger than outputLen
32172
+ pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
32173
+ for (let i = 0; i < pad.length; i++)
32174
+ pad[i] ^= 0x36;
32175
+ this.iHash.update(pad);
32176
+ // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone
32177
+ this.oHash = hash.create();
32178
+ // Undo internal XOR && apply outer XOR
32179
+ for (let i = 0; i < pad.length; i++)
32180
+ pad[i] ^= 0x36 ^ 0x5c;
32181
+ this.oHash.update(pad);
32182
+ pad.fill(0);
32183
+ }
32184
+ update(buf) {
32185
+ _assert_js_1.default.exists(this);
32186
+ this.iHash.update(buf);
32187
+ return this;
32188
+ }
32189
+ digestInto(out) {
32190
+ _assert_js_1.default.exists(this);
32191
+ _assert_js_1.default.bytes(out, this.outputLen);
32192
+ this.finished = true;
32193
+ this.iHash.digestInto(out);
32194
+ this.oHash.update(out);
32195
+ this.oHash.digestInto(out);
32196
+ this.destroy();
32197
+ }
32198
+ digest() {
32199
+ const out = new Uint8Array(this.oHash.outputLen);
32200
+ this.digestInto(out);
32201
+ return out;
32202
+ }
32203
+ _cloneInto(to) {
32204
+ // Create new instance without calling constructor since key already in state and we don't know it.
32205
+ to || (to = Object.create(Object.getPrototypeOf(this), {}));
32206
+ const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
32207
+ to = to;
32208
+ to.finished = finished;
32209
+ to.destroyed = destroyed;
32210
+ to.blockLen = blockLen;
32211
+ to.outputLen = outputLen;
32212
+ to.oHash = oHash._cloneInto(to.oHash);
32213
+ to.iHash = iHash._cloneInto(to.iHash);
32214
+ return to;
32215
+ }
32216
+ destroy() {
32217
+ this.destroyed = true;
32218
+ this.oHash.destroy();
32219
+ this.iHash.destroy();
32220
+ }
32221
+ }
32222
+ /**
32223
+ * HMAC: RFC2104 message authentication code.
32224
+ * @param hash - function that would be used e.g. sha256
32225
+ * @param key - message key
32226
+ * @param message - message data
32227
+ */
32228
+ const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
32229
+ exports.hmac = hmac;
32230
+ exports.hmac.create = (hash, key) => new HMAC(hash, key);
32231
+ //# sourceMappingURL=hmac.js.map
32232
+
32233
+ /***/ }),
32234
+
32235
+ /***/ "./node_modules/@noble/hashes/sha256.js":
32236
+ /*!**********************************************!*\
32237
+ !*** ./node_modules/@noble/hashes/sha256.js ***!
32238
+ \**********************************************/
32239
+ /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
32240
+
32241
+ "use strict";
32242
+
32243
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
32244
+ exports.sha224 = exports.sha256 = void 0;
32245
+ const _sha2_js_1 = __webpack_require__(/*! ./_sha2.js */ "./node_modules/@noble/hashes/_sha2.js");
32246
+ const utils_js_1 = __webpack_require__(/*! ./utils.js */ "./node_modules/@noble/hashes/utils.js");
32247
+ // Choice: a ? b : c
32248
+ const Chi = (a, b, c) => (a & b) ^ (~a & c);
32249
+ // Majority function, true if any two inpust is true
32250
+ const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c);
32251
+ // Round constants:
32252
+ // first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)
32253
+ // prettier-ignore
32254
+ const SHA256_K = new Uint32Array([
32255
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
32256
+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
32257
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
32258
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
32259
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
32260
+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
32261
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
32262
+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
32263
+ ]);
32264
+ // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):
32265
+ // prettier-ignore
32266
+ const IV = new Uint32Array([
32267
+ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
32268
+ ]);
32269
+ // Temporary buffer, not used to store anything between runs
32270
+ // Named this way because it matches specification.
32271
+ const SHA256_W = new Uint32Array(64);
32272
+ class SHA256 extends _sha2_js_1.SHA2 {
32273
+ constructor() {
32274
+ super(64, 32, 8, false);
32275
+ // We cannot use array here since array allows indexing by variable
32276
+ // which means optimizer/compiler cannot use registers.
32277
+ this.A = IV[0] | 0;
32278
+ this.B = IV[1] | 0;
32279
+ this.C = IV[2] | 0;
32280
+ this.D = IV[3] | 0;
32281
+ this.E = IV[4] | 0;
32282
+ this.F = IV[5] | 0;
32283
+ this.G = IV[6] | 0;
32284
+ this.H = IV[7] | 0;
32285
+ }
32286
+ get() {
32287
+ const { A, B, C, D, E, F, G, H } = this;
32288
+ return [A, B, C, D, E, F, G, H];
32289
+ }
32290
+ // prettier-ignore
32291
+ set(A, B, C, D, E, F, G, H) {
32292
+ this.A = A | 0;
32293
+ this.B = B | 0;
32294
+ this.C = C | 0;
32295
+ this.D = D | 0;
32296
+ this.E = E | 0;
32297
+ this.F = F | 0;
32298
+ this.G = G | 0;
32299
+ this.H = H | 0;
32300
+ }
32301
+ process(view, offset) {
32302
+ // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array
32303
+ for (let i = 0; i < 16; i++, offset += 4)
32304
+ SHA256_W[i] = view.getUint32(offset, false);
32305
+ for (let i = 16; i < 64; i++) {
32306
+ const W15 = SHA256_W[i - 15];
32307
+ const W2 = SHA256_W[i - 2];
32308
+ const s0 = (0, utils_js_1.rotr)(W15, 7) ^ (0, utils_js_1.rotr)(W15, 18) ^ (W15 >>> 3);
32309
+ const s1 = (0, utils_js_1.rotr)(W2, 17) ^ (0, utils_js_1.rotr)(W2, 19) ^ (W2 >>> 10);
32310
+ SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;
32311
+ }
32312
+ // Compression function main loop, 64 rounds
32313
+ let { A, B, C, D, E, F, G, H } = this;
32314
+ for (let i = 0; i < 64; i++) {
32315
+ const sigma1 = (0, utils_js_1.rotr)(E, 6) ^ (0, utils_js_1.rotr)(E, 11) ^ (0, utils_js_1.rotr)(E, 25);
32316
+ const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
32317
+ const sigma0 = (0, utils_js_1.rotr)(A, 2) ^ (0, utils_js_1.rotr)(A, 13) ^ (0, utils_js_1.rotr)(A, 22);
32318
+ const T2 = (sigma0 + Maj(A, B, C)) | 0;
32319
+ H = G;
32320
+ G = F;
32321
+ F = E;
32322
+ E = (D + T1) | 0;
32323
+ D = C;
32324
+ C = B;
32325
+ B = A;
32326
+ A = (T1 + T2) | 0;
32327
+ }
32328
+ // Add the compressed chunk to the current hash value
32329
+ A = (A + this.A) | 0;
32330
+ B = (B + this.B) | 0;
32331
+ C = (C + this.C) | 0;
32332
+ D = (D + this.D) | 0;
32333
+ E = (E + this.E) | 0;
32334
+ F = (F + this.F) | 0;
32335
+ G = (G + this.G) | 0;
32336
+ H = (H + this.H) | 0;
32337
+ this.set(A, B, C, D, E, F, G, H);
32338
+ }
32339
+ roundClean() {
32340
+ SHA256_W.fill(0);
32341
+ }
32342
+ destroy() {
32343
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
32344
+ this.buffer.fill(0);
32345
+ }
32346
+ }
32347
+ // Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf
32348
+ class SHA224 extends SHA256 {
32349
+ constructor() {
32350
+ super();
32351
+ this.A = 0xc1059ed8 | 0;
32352
+ this.B = 0x367cd507 | 0;
32353
+ this.C = 0x3070dd17 | 0;
32354
+ this.D = 0xf70e5939 | 0;
32355
+ this.E = 0xffc00b31 | 0;
32356
+ this.F = 0x68581511 | 0;
32357
+ this.G = 0x64f98fa7 | 0;
32358
+ this.H = 0xbefa4fa4 | 0;
32359
+ this.outputLen = 28;
32360
+ }
32361
+ }
32362
+ /**
32363
+ * SHA2-256 hash function
32364
+ * @param message - data that would be hashed
32365
+ */
32366
+ exports.sha256 = (0, utils_js_1.wrapConstructor)(() => new SHA256());
32367
+ exports.sha224 = (0, utils_js_1.wrapConstructor)(() => new SHA224());
32368
+ //# sourceMappingURL=sha256.js.map
32369
+
32370
+ /***/ }),
32371
+
32372
+ /***/ "./node_modules/@noble/hashes/utils.js":
32373
+ /*!*********************************************!*\
32374
+ !*** ./node_modules/@noble/hashes/utils.js ***!
32375
+ \*********************************************/
32376
+ /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
32377
+
32378
+ "use strict";
32379
+
32380
+ /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
32381
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
32382
+ 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;
32383
+ // We use `globalThis.crypto`, but node.js versions earlier than v19 don't
32384
+ // declare it in global scope. For node.js, package.json#exports field mapping
32385
+ // rewrites import from `crypto` to `cryptoNode`, which imports native module.
32386
+ // Makes the utils un-importable in browsers without a bundler.
32387
+ // Once node.js 18 is deprecated, we can just drop the import.
32388
+ const crypto_1 = __webpack_require__(/*! @noble/hashes/crypto */ "./node_modules/@noble/hashes/crypto.js");
32389
+ // Cast array to different type
32390
+ const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
32391
+ exports.u8 = u8;
32392
+ const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
32393
+ exports.u32 = u32;
32394
+ // Cast array to view
32395
+ const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
32396
+ exports.createView = createView;
32397
+ // The rotate right (circular right shift) operation for uint32
32398
+ const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);
32399
+ exports.rotr = rotr;
32400
+ // big-endian hardware is rare. Just in case someone still decides to run hashes:
32401
+ // early-throw an error because we don't support BE yet.
32402
+ exports.isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;
32403
+ if (!exports.isLE)
32404
+ throw new Error('Non little-endian hardware is not supported');
32405
+ const hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0'));
32406
+ /**
32407
+ * @example bytesToHex(Uint8Array.from([0xde, 0xad, 0xbe, 0xef])) // 'deadbeef'
32408
+ */
32409
+ function bytesToHex(uint8a) {
32410
+ // pre-caching improves the speed 6x
32411
+ if (!(uint8a instanceof Uint8Array))
32412
+ throw new Error('Uint8Array expected');
32413
+ let hex = '';
32414
+ for (let i = 0; i < uint8a.length; i++) {
32415
+ hex += hexes[uint8a[i]];
32416
+ }
32417
+ return hex;
32418
+ }
32419
+ exports.bytesToHex = bytesToHex;
32420
+ /**
32421
+ * @example hexToBytes('deadbeef') // Uint8Array.from([0xde, 0xad, 0xbe, 0xef])
32422
+ */
32423
+ function hexToBytes(hex) {
32424
+ if (typeof hex !== 'string') {
32425
+ throw new TypeError('hexToBytes: expected string, got ' + typeof hex);
32426
+ }
32427
+ if (hex.length % 2)
32428
+ throw new Error('hexToBytes: received invalid unpadded hex');
32429
+ const array = new Uint8Array(hex.length / 2);
32430
+ for (let i = 0; i < array.length; i++) {
32431
+ const j = i * 2;
32432
+ const hexByte = hex.slice(j, j + 2);
32433
+ const byte = Number.parseInt(hexByte, 16);
32434
+ if (Number.isNaN(byte) || byte < 0)
32435
+ throw new Error('Invalid byte sequence');
32436
+ array[i] = byte;
32437
+ }
32438
+ return array;
32439
+ }
32440
+ exports.hexToBytes = hexToBytes;
32441
+ // There is no setImmediate in browser and setTimeout is slow.
32442
+ // call of async fn will return Promise, which will be fullfiled only on
32443
+ // next scheduler queue processing step and this is exactly what we need.
32444
+ const nextTick = async () => { };
32445
+ exports.nextTick = nextTick;
32446
+ // Returns control to thread each 'tick' ms to avoid blocking
32447
+ async function asyncLoop(iters, tick, cb) {
32448
+ let ts = Date.now();
32449
+ for (let i = 0; i < iters; i++) {
32450
+ cb(i);
32451
+ // Date.now() is not monotonic, so in case if clock goes backwards we return return control too
32452
+ const diff = Date.now() - ts;
32453
+ if (diff >= 0 && diff < tick)
32454
+ continue;
32455
+ await (0, exports.nextTick)();
32456
+ ts += diff;
32457
+ }
32458
+ }
32459
+ exports.asyncLoop = asyncLoop;
32460
+ function utf8ToBytes(str) {
32461
+ if (typeof str !== 'string') {
32462
+ throw new TypeError(`utf8ToBytes expected string, got ${typeof str}`);
32463
+ }
32464
+ return new TextEncoder().encode(str);
32465
+ }
32466
+ exports.utf8ToBytes = utf8ToBytes;
32467
+ function toBytes(data) {
32468
+ if (typeof data === 'string')
32469
+ data = utf8ToBytes(data);
32470
+ if (!(data instanceof Uint8Array))
32471
+ throw new TypeError(`Expected input type is Uint8Array (got ${typeof data})`);
32472
+ return data;
32473
+ }
32474
+ exports.toBytes = toBytes;
32475
+ /**
32476
+ * Concats Uint8Array-s into one; like `Buffer.concat([buf1, buf2])`
32477
+ * @example concatBytes(buf1, buf2)
32478
+ */
32479
+ function concatBytes(...arrays) {
32480
+ if (!arrays.every((a) => a instanceof Uint8Array))
32481
+ throw new Error('Uint8Array list expected');
32482
+ if (arrays.length === 1)
32483
+ return arrays[0];
32484
+ const length = arrays.reduce((a, arr) => a + arr.length, 0);
32485
+ const result = new Uint8Array(length);
32486
+ for (let i = 0, pad = 0; i < arrays.length; i++) {
32487
+ const arr = arrays[i];
32488
+ result.set(arr, pad);
32489
+ pad += arr.length;
32490
+ }
32491
+ return result;
32492
+ }
32493
+ exports.concatBytes = concatBytes;
32494
+ // For runtime check if class implements interface
32495
+ class Hash {
32496
+ // Safe version that clones internal state
32497
+ clone() {
32498
+ return this._cloneInto();
32499
+ }
32500
+ }
32501
+ exports.Hash = Hash;
32502
+ // Check if object doens't have custom constructor (like Uint8Array/Array)
32503
+ const isPlainObject = (obj) => Object.prototype.toString.call(obj) === '[object Object]' && obj.constructor === Object;
32504
+ function checkOpts(defaults, opts) {
32505
+ if (opts !== undefined && (typeof opts !== 'object' || !isPlainObject(opts)))
32506
+ throw new TypeError('Options should be object or undefined');
32507
+ const merged = Object.assign(defaults, opts);
32508
+ return merged;
32509
+ }
32510
+ exports.checkOpts = checkOpts;
32511
+ function wrapConstructor(hashConstructor) {
32512
+ const hashC = (message) => hashConstructor().update(toBytes(message)).digest();
32513
+ const tmp = hashConstructor();
32514
+ hashC.outputLen = tmp.outputLen;
32515
+ hashC.blockLen = tmp.blockLen;
32516
+ hashC.create = () => hashConstructor();
32517
+ return hashC;
32518
+ }
32519
+ exports.wrapConstructor = wrapConstructor;
32520
+ function wrapConstructorWithOpts(hashCons) {
32521
+ const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
32522
+ const tmp = hashCons({});
32523
+ hashC.outputLen = tmp.outputLen;
32524
+ hashC.blockLen = tmp.blockLen;
32525
+ hashC.create = (opts) => hashCons(opts);
32526
+ return hashC;
32527
+ }
32528
+ exports.wrapConstructorWithOpts = wrapConstructorWithOpts;
32529
+ /**
32530
+ * Secure PRNG. Uses `globalThis.crypto` or node.js crypto module.
32531
+ */
32532
+ function randomBytes(bytesLength = 32) {
32533
+ if (crypto_1.crypto && typeof crypto_1.crypto.getRandomValues === 'function') {
32534
+ return crypto_1.crypto.getRandomValues(new Uint8Array(bytesLength));
32535
+ }
32536
+ throw new Error('crypto.getRandomValues must be defined');
32537
+ }
32538
+ exports.randomBytes = randomBytes;
32539
+ //# sourceMappingURL=utils.js.map
32540
+
32541
+ /***/ }),
32542
+
29335
32543
  /***/ "./node_modules/@xmldom/xmldom/lib/conventions.js":
29336
32544
  /*!********************************************************!*\
29337
32545
  !*** ./node_modules/@xmldom/xmldom/lib/conventions.js ***!