@fastnear/utils 0.9.8 → 0.9.10

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.
@@ -1,20 +1,12 @@
1
- /* ⋈ 🏃🏻💨 FastNEAR Utils - IIFE/UMD (@fastnear/utils version 0.9.7) */
2
- /* https://www.npmjs.com/package/@fastnear/utils/v/0.9.7 */
1
+ /* ⋈ 🏃🏻💨 FastNear Utils - IIFE/UMD (@fastnear/utils version 0.9.10) */
2
+ /* https://www.npmjs.com/package/@fastnear/utils/v/0.9.10 */
3
3
  "use strict";
4
4
  var NearUtils = (() => {
5
- var __create = Object.create;
6
5
  var __defProp = Object.defineProperty;
7
6
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
8
7
  var __getOwnPropNames = Object.getOwnPropertyNames;
9
- var __getProtoOf = Object.getPrototypeOf;
10
8
  var __hasOwnProp = Object.prototype.hasOwnProperty;
11
9
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
12
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
13
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
14
- }) : x)(function(x) {
15
- if (typeof require !== "undefined") return require.apply(this, arguments);
16
- throw Error('Dynamic require of "' + x + '" is not supported');
17
- });
18
10
  var __export = (target, all) => {
19
11
  for (var name in all)
20
12
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -27,14 +19,6 @@ var NearUtils = (() => {
27
19
  }
28
20
  return to;
29
21
  };
30
- var __toESM = (mod2, isNodeMode, target) => (target = mod2 != null ? __create(__getProtoOf(mod2)) : {}, __copyProps(
31
- // If the importer is in node compatibility mode or this is not an ESM
32
- // file that has been converted to a CommonJS file using a Babel-
33
- // compatible transform (i.e. "__esModule" has not been set), then set
34
- // "default" to the CommonJS "module.exports" for node compatibility.
35
- isNodeMode || !mod2 || !mod2.__esModule ? __defProp(target, "default", { value: mod2, enumerable: true }) : target,
36
- mod2
37
- ));
38
22
  var __toCommonJS = (mod2) => __copyProps(__defProp({}, "__esModule", { value: true }), mod2);
39
23
 
40
24
  // src/index.ts
@@ -76,16 +60,29 @@ var NearUtils = (() => {
76
60
  txToJsonStringified: () => txToJsonStringified
77
61
  });
78
62
 
79
- // ../../node_modules/@noble/hashes/esm/_assert.js
63
+ // node_modules/@noble/hashes/utils.js
80
64
  function isBytes(a) {
81
65
  return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
82
66
  }
83
67
  __name(isBytes, "isBytes");
84
- function abytes(b, ...lengths) {
85
- if (!isBytes(b))
86
- throw new Error("Uint8Array expected");
87
- if (lengths.length > 0 && !lengths.includes(b.length))
88
- throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
68
+ function anumber(n, title = "") {
69
+ if (!Number.isSafeInteger(n) || n < 0) {
70
+ const prefix = title && `"${title}" `;
71
+ throw new Error(`${prefix}expected integer >= 0, got ${n}`);
72
+ }
73
+ }
74
+ __name(anumber, "anumber");
75
+ function abytes(value, length, title = "") {
76
+ const bytes = isBytes(value);
77
+ const len = value?.length;
78
+ const needsLen = length !== void 0;
79
+ if (!bytes || needsLen && len !== length) {
80
+ const prefix = title && `"${title}" `;
81
+ const ofLen = needsLen ? ` of length ${length}` : "";
82
+ const got = bytes ? `length=${len}` : `type=${typeof value}`;
83
+ throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got);
84
+ }
85
+ return value;
89
86
  }
90
87
  __name(abytes, "abytes");
91
88
  function aexists(instance, checkFinished = true) {
@@ -96,19 +93,19 @@ var NearUtils = (() => {
96
93
  }
97
94
  __name(aexists, "aexists");
98
95
  function aoutput(out, instance) {
99
- abytes(out);
96
+ abytes(out, void 0, "digestInto() output");
100
97
  const min = instance.outputLen;
101
98
  if (out.length < min) {
102
- throw new Error("digestInto() expects output buffer of length at least " + min);
99
+ throw new Error('"digestInto() output" expected to be of length >=' + min);
103
100
  }
104
101
  }
105
102
  __name(aoutput, "aoutput");
106
-
107
- // ../../node_modules/@noble/hashes/esm/cryptoNode.js
108
- var nc = __toESM(__require("node:crypto"), 1);
109
- var crypto2 = nc && typeof nc === "object" && "webcrypto" in nc ? nc.webcrypto : nc && typeof nc === "object" && "randomBytes" in nc ? nc : void 0;
110
-
111
- // ../../node_modules/@noble/hashes/esm/utils.js
103
+ function clean(...arrays) {
104
+ for (let i = 0; i < arrays.length; i++) {
105
+ arrays[i].fill(0);
106
+ }
107
+ }
108
+ __name(clean, "clean");
112
109
  function createView(arr) {
113
110
  return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
114
111
  }
@@ -117,62 +114,93 @@ var NearUtils = (() => {
117
114
  return word << 32 - shift | word >>> shift;
118
115
  }
119
116
  __name(rotr, "rotr");
120
- function utf8ToBytes(str) {
121
- if (typeof str !== "string")
122
- throw new Error("utf8ToBytes expected string, got " + typeof str);
123
- return new Uint8Array(new TextEncoder().encode(str));
124
- }
125
- __name(utf8ToBytes, "utf8ToBytes");
126
- function toBytes(data) {
127
- if (typeof data === "string")
128
- data = utf8ToBytes(data);
129
- abytes(data);
130
- return data;
131
- }
132
- __name(toBytes, "toBytes");
133
- var Hash = class {
134
- static {
135
- __name(this, "Hash");
117
+ var hasHexBuiltin = /* @__PURE__ */ (() => (
118
+ // @ts-ignore
119
+ typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
120
+ ))();
121
+ var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
122
+ function bytesToHex(bytes) {
123
+ abytes(bytes);
124
+ if (hasHexBuiltin)
125
+ return bytes.toHex();
126
+ let hex = "";
127
+ for (let i = 0; i < bytes.length; i++) {
128
+ hex += hexes[bytes[i]];
136
129
  }
137
- // Safe version that clones internal state
138
- clone() {
139
- return this._cloneInto();
130
+ return hex;
131
+ }
132
+ __name(bytesToHex, "bytesToHex");
133
+ var asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
134
+ function asciiToBase16(ch) {
135
+ if (ch >= asciis._0 && ch <= asciis._9)
136
+ return ch - asciis._0;
137
+ if (ch >= asciis.A && ch <= asciis.F)
138
+ return ch - (asciis.A - 10);
139
+ if (ch >= asciis.a && ch <= asciis.f)
140
+ return ch - (asciis.a - 10);
141
+ return;
142
+ }
143
+ __name(asciiToBase16, "asciiToBase16");
144
+ function hexToBytes(hex) {
145
+ if (typeof hex !== "string")
146
+ throw new Error("hex string expected, got " + typeof hex);
147
+ if (hasHexBuiltin)
148
+ return Uint8Array.fromHex(hex);
149
+ const hl = hex.length;
150
+ const al = hl / 2;
151
+ if (hl % 2)
152
+ throw new Error("hex string expected, got unpadded hex of length " + hl);
153
+ const array = new Uint8Array(al);
154
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
155
+ const n1 = asciiToBase16(hex.charCodeAt(hi));
156
+ const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
157
+ if (n1 === void 0 || n2 === void 0) {
158
+ const char = hex[hi] + hex[hi + 1];
159
+ throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
160
+ }
161
+ array[ai] = n1 * 16 + n2;
140
162
  }
141
- };
142
- function wrapConstructor(hashCons) {
143
- const hashC = /* @__PURE__ */ __name((msg) => hashCons().update(toBytes(msg)).digest(), "hashC");
144
- const tmp = hashCons();
163
+ return array;
164
+ }
165
+ __name(hexToBytes, "hexToBytes");
166
+ function concatBytes(...arrays) {
167
+ let sum = 0;
168
+ for (let i = 0; i < arrays.length; i++) {
169
+ const a = arrays[i];
170
+ abytes(a);
171
+ sum += a.length;
172
+ }
173
+ const res = new Uint8Array(sum);
174
+ for (let i = 0, pad = 0; i < arrays.length; i++) {
175
+ const a = arrays[i];
176
+ res.set(a, pad);
177
+ pad += a.length;
178
+ }
179
+ return res;
180
+ }
181
+ __name(concatBytes, "concatBytes");
182
+ function createHasher(hashCons, info = {}) {
183
+ const hashC = /* @__PURE__ */ __name((msg, opts) => hashCons(opts).update(msg).digest(), "hashC");
184
+ const tmp = hashCons(void 0);
145
185
  hashC.outputLen = tmp.outputLen;
146
186
  hashC.blockLen = tmp.blockLen;
147
- hashC.create = () => hashCons();
148
- return hashC;
187
+ hashC.create = (opts) => hashCons(opts);
188
+ Object.assign(hashC, info);
189
+ return Object.freeze(hashC);
149
190
  }
150
- __name(wrapConstructor, "wrapConstructor");
191
+ __name(createHasher, "createHasher");
151
192
  function randomBytes(bytesLength = 32) {
152
- if (crypto2 && typeof crypto2.getRandomValues === "function") {
153
- return crypto2.getRandomValues(new Uint8Array(bytesLength));
154
- }
155
- if (crypto2 && typeof crypto2.randomBytes === "function") {
156
- return crypto2.randomBytes(bytesLength);
157
- }
158
- throw new Error("crypto.getRandomValues must be defined");
193
+ const cr = typeof globalThis === "object" ? globalThis.crypto : null;
194
+ if (typeof cr?.getRandomValues !== "function")
195
+ throw new Error("crypto.getRandomValues must be defined");
196
+ return cr.getRandomValues(new Uint8Array(bytesLength));
159
197
  }
160
198
  __name(randomBytes, "randomBytes");
199
+ var oidNist = /* @__PURE__ */ __name((suffix) => ({
200
+ oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix])
201
+ }), "oidNist");
161
202
 
162
- // ../../node_modules/@noble/hashes/esm/_md.js
163
- function setBigUint64(view, byteOffset, value, isLE) {
164
- if (typeof view.setBigUint64 === "function")
165
- return view.setBigUint64(byteOffset, value, isLE);
166
- const _32n2 = BigInt(32);
167
- const _u32_max = BigInt(4294967295);
168
- const wh = Number(value >> _32n2 & _u32_max);
169
- const wl = Number(value & _u32_max);
170
- const h = isLE ? 4 : 0;
171
- const l = isLE ? 0 : 4;
172
- view.setUint32(byteOffset + h, wh, isLE);
173
- view.setUint32(byteOffset + l, wl, isLE);
174
- }
175
- __name(setBigUint64, "setBigUint64");
203
+ // node_modules/@noble/hashes/_md.js
176
204
  function Chi(a, b, c) {
177
205
  return a & b ^ ~a & c;
178
206
  }
@@ -181,27 +209,33 @@ var NearUtils = (() => {
181
209
  return a & b ^ a & c ^ b & c;
182
210
  }
183
211
  __name(Maj, "Maj");
184
- var HashMD = class extends Hash {
212
+ var HashMD = class {
185
213
  static {
186
214
  __name(this, "HashMD");
187
215
  }
216
+ blockLen;
217
+ outputLen;
218
+ padOffset;
219
+ isLE;
220
+ // For partial updates less than block size
221
+ buffer;
222
+ view;
223
+ finished = false;
224
+ length = 0;
225
+ pos = 0;
226
+ destroyed = false;
188
227
  constructor(blockLen, outputLen, padOffset, isLE) {
189
- super();
190
228
  this.blockLen = blockLen;
191
229
  this.outputLen = outputLen;
192
230
  this.padOffset = padOffset;
193
231
  this.isLE = isLE;
194
- this.finished = false;
195
- this.length = 0;
196
- this.pos = 0;
197
- this.destroyed = false;
198
232
  this.buffer = new Uint8Array(blockLen);
199
233
  this.view = createView(this.buffer);
200
234
  }
201
235
  update(data) {
202
236
  aexists(this);
237
+ abytes(data);
203
238
  const { view, buffer, blockLen } = this;
204
- data = toBytes(data);
205
239
  const len = data.length;
206
240
  for (let pos = 0; pos < len; ) {
207
241
  const take = Math.min(blockLen - this.pos, len - pos);
@@ -230,19 +264,19 @@ var NearUtils = (() => {
230
264
  const { buffer, view, blockLen, isLE } = this;
231
265
  let { pos } = this;
232
266
  buffer[pos++] = 128;
233
- this.buffer.subarray(pos).fill(0);
267
+ clean(this.buffer.subarray(pos));
234
268
  if (this.padOffset > blockLen - pos) {
235
269
  this.process(view, 0);
236
270
  pos = 0;
237
271
  }
238
272
  for (let i = pos; i < blockLen; i++)
239
273
  buffer[i] = 0;
240
- setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
274
+ view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);
241
275
  this.process(view, 0);
242
276
  const oview = createView(out);
243
277
  const len = this.outputLen;
244
278
  if (len % 4)
245
- throw new Error("_sha2: outputLen should be aligned to 32bit");
279
+ throw new Error("_sha2: outputLen must be aligned to 32bit");
246
280
  const outLen = len / 4;
247
281
  const state = this.get();
248
282
  if (outLen > state.length)
@@ -258,20 +292,51 @@ var NearUtils = (() => {
258
292
  return res;
259
293
  }
260
294
  _cloneInto(to) {
261
- to || (to = new this.constructor());
295
+ to ||= new this.constructor();
262
296
  to.set(...this.get());
263
297
  const { blockLen, buffer, length, finished, destroyed, pos } = this;
298
+ to.destroyed = destroyed;
299
+ to.finished = finished;
264
300
  to.length = length;
265
301
  to.pos = pos;
266
- to.finished = finished;
267
- to.destroyed = destroyed;
268
302
  if (length % blockLen)
269
303
  to.buffer.set(buffer);
270
304
  return to;
271
305
  }
306
+ clone() {
307
+ return this._cloneInto();
308
+ }
272
309
  };
310
+ var SHA256_IV = /* @__PURE__ */ Uint32Array.from([
311
+ 1779033703,
312
+ 3144134277,
313
+ 1013904242,
314
+ 2773480762,
315
+ 1359893119,
316
+ 2600822924,
317
+ 528734635,
318
+ 1541459225
319
+ ]);
320
+ var SHA512_IV = /* @__PURE__ */ Uint32Array.from([
321
+ 1779033703,
322
+ 4089235720,
323
+ 3144134277,
324
+ 2227873595,
325
+ 1013904242,
326
+ 4271175723,
327
+ 2773480762,
328
+ 1595750129,
329
+ 1359893119,
330
+ 2917565137,
331
+ 2600822924,
332
+ 725511199,
333
+ 528734635,
334
+ 4215389547,
335
+ 1541459225,
336
+ 327033209
337
+ ]);
273
338
 
274
- // ../../node_modules/@noble/hashes/esm/_u64.js
339
+ // node_modules/@noble/hashes/_u64.js
275
340
  var U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
276
341
  var _32n = /* @__PURE__ */ BigInt(32);
277
342
  function fromBig(n, le = false) {
@@ -281,28 +346,22 @@ var NearUtils = (() => {
281
346
  }
282
347
  __name(fromBig, "fromBig");
283
348
  function split(lst, le = false) {
284
- let Ah = new Uint32Array(lst.length);
285
- let Al = new Uint32Array(lst.length);
286
- for (let i = 0; i < lst.length; i++) {
349
+ const len = lst.length;
350
+ let Ah = new Uint32Array(len);
351
+ let Al = new Uint32Array(len);
352
+ for (let i = 0; i < len; i++) {
287
353
  const { h, l } = fromBig(lst[i], le);
288
354
  [Ah[i], Al[i]] = [h, l];
289
355
  }
290
356
  return [Ah, Al];
291
357
  }
292
358
  __name(split, "split");
293
- var toBig = /* @__PURE__ */ __name((h, l) => BigInt(h >>> 0) << _32n | BigInt(l >>> 0), "toBig");
294
359
  var shrSH = /* @__PURE__ */ __name((h, _l, s) => h >>> s, "shrSH");
295
360
  var shrSL = /* @__PURE__ */ __name((h, l, s) => h << 32 - s | l >>> s, "shrSL");
296
361
  var rotrSH = /* @__PURE__ */ __name((h, l, s) => h >>> s | l << 32 - s, "rotrSH");
297
362
  var rotrSL = /* @__PURE__ */ __name((h, l, s) => h << 32 - s | l >>> s, "rotrSL");
298
363
  var rotrBH = /* @__PURE__ */ __name((h, l, s) => h << 64 - s | l >>> s - 32, "rotrBH");
299
364
  var rotrBL = /* @__PURE__ */ __name((h, l, s) => h >>> s - 32 | l << 64 - s, "rotrBL");
300
- var rotr32H = /* @__PURE__ */ __name((_h, l) => l, "rotr32H");
301
- var rotr32L = /* @__PURE__ */ __name((h, _l) => h, "rotr32L");
302
- var rotlSH = /* @__PURE__ */ __name((h, l, s) => h << s | l >>> 32 - s, "rotlSH");
303
- var rotlSL = /* @__PURE__ */ __name((h, l, s) => l << s | h >>> 32 - s, "rotlSL");
304
- var rotlBH = /* @__PURE__ */ __name((h, l, s) => l << s - 32 | h >>> 64 - s, "rotlBH");
305
- var rotlBL = /* @__PURE__ */ __name((h, l, s) => h << s - 32 | l >>> 64 - s, "rotlBL");
306
365
  function add(Ah, Al, Bh, Bl) {
307
366
  const l = (Al >>> 0) + (Bl >>> 0);
308
367
  return { h: Ah + Bh + (l / 2 ** 32 | 0) | 0, l: l | 0 };
@@ -314,34 +373,159 @@ var NearUtils = (() => {
314
373
  var add4H = /* @__PURE__ */ __name((low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0, "add4H");
315
374
  var add5L = /* @__PURE__ */ __name((Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0), "add5L");
316
375
  var add5H = /* @__PURE__ */ __name((low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0, "add5H");
317
- var u64 = {
318
- fromBig,
319
- split,
320
- toBig,
321
- shrSH,
322
- shrSL,
323
- rotrSH,
324
- rotrSL,
325
- rotrBH,
326
- rotrBL,
327
- rotr32H,
328
- rotr32L,
329
- rotlSH,
330
- rotlSL,
331
- rotlBH,
332
- rotlBL,
333
- add,
334
- add3L,
335
- add3H,
336
- add4L,
337
- add4H,
338
- add5H,
339
- add5L
340
- };
341
- var u64_default = u64;
342
376
 
343
- // ../../node_modules/@noble/hashes/esm/sha512.js
344
- var [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64_default.split([
377
+ // node_modules/@noble/hashes/sha2.js
378
+ var SHA256_K = /* @__PURE__ */ Uint32Array.from([
379
+ 1116352408,
380
+ 1899447441,
381
+ 3049323471,
382
+ 3921009573,
383
+ 961987163,
384
+ 1508970993,
385
+ 2453635748,
386
+ 2870763221,
387
+ 3624381080,
388
+ 310598401,
389
+ 607225278,
390
+ 1426881987,
391
+ 1925078388,
392
+ 2162078206,
393
+ 2614888103,
394
+ 3248222580,
395
+ 3835390401,
396
+ 4022224774,
397
+ 264347078,
398
+ 604807628,
399
+ 770255983,
400
+ 1249150122,
401
+ 1555081692,
402
+ 1996064986,
403
+ 2554220882,
404
+ 2821834349,
405
+ 2952996808,
406
+ 3210313671,
407
+ 3336571891,
408
+ 3584528711,
409
+ 113926993,
410
+ 338241895,
411
+ 666307205,
412
+ 773529912,
413
+ 1294757372,
414
+ 1396182291,
415
+ 1695183700,
416
+ 1986661051,
417
+ 2177026350,
418
+ 2456956037,
419
+ 2730485921,
420
+ 2820302411,
421
+ 3259730800,
422
+ 3345764771,
423
+ 3516065817,
424
+ 3600352804,
425
+ 4094571909,
426
+ 275423344,
427
+ 430227734,
428
+ 506948616,
429
+ 659060556,
430
+ 883997877,
431
+ 958139571,
432
+ 1322822218,
433
+ 1537002063,
434
+ 1747873779,
435
+ 1955562222,
436
+ 2024104815,
437
+ 2227730452,
438
+ 2361852424,
439
+ 2428436474,
440
+ 2756734187,
441
+ 3204031479,
442
+ 3329325298
443
+ ]);
444
+ var SHA256_W = /* @__PURE__ */ new Uint32Array(64);
445
+ var SHA2_32B = class extends HashMD {
446
+ static {
447
+ __name(this, "SHA2_32B");
448
+ }
449
+ constructor(outputLen) {
450
+ super(64, outputLen, 8, false);
451
+ }
452
+ get() {
453
+ const { A, B, C, D, E, F, G, H } = this;
454
+ return [A, B, C, D, E, F, G, H];
455
+ }
456
+ // prettier-ignore
457
+ set(A, B, C, D, E, F, G, H) {
458
+ this.A = A | 0;
459
+ this.B = B | 0;
460
+ this.C = C | 0;
461
+ this.D = D | 0;
462
+ this.E = E | 0;
463
+ this.F = F | 0;
464
+ this.G = G | 0;
465
+ this.H = H | 0;
466
+ }
467
+ process(view, offset) {
468
+ for (let i = 0; i < 16; i++, offset += 4)
469
+ SHA256_W[i] = view.getUint32(offset, false);
470
+ for (let i = 16; i < 64; i++) {
471
+ const W15 = SHA256_W[i - 15];
472
+ const W2 = SHA256_W[i - 2];
473
+ const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
474
+ const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
475
+ SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
476
+ }
477
+ let { A, B, C, D, E, F, G, H } = this;
478
+ for (let i = 0; i < 64; i++) {
479
+ const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
480
+ const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
481
+ const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
482
+ const T2 = sigma0 + Maj(A, B, C) | 0;
483
+ H = G;
484
+ G = F;
485
+ F = E;
486
+ E = D + T1 | 0;
487
+ D = C;
488
+ C = B;
489
+ B = A;
490
+ A = T1 + T2 | 0;
491
+ }
492
+ A = A + this.A | 0;
493
+ B = B + this.B | 0;
494
+ C = C + this.C | 0;
495
+ D = D + this.D | 0;
496
+ E = E + this.E | 0;
497
+ F = F + this.F | 0;
498
+ G = G + this.G | 0;
499
+ H = H + this.H | 0;
500
+ this.set(A, B, C, D, E, F, G, H);
501
+ }
502
+ roundClean() {
503
+ clean(SHA256_W);
504
+ }
505
+ destroy() {
506
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
507
+ clean(this.buffer);
508
+ }
509
+ };
510
+ var _SHA256 = class extends SHA2_32B {
511
+ static {
512
+ __name(this, "_SHA256");
513
+ }
514
+ // We cannot use array here since array allows indexing by variable
515
+ // which means optimizer/compiler cannot use registers.
516
+ A = SHA256_IV[0] | 0;
517
+ B = SHA256_IV[1] | 0;
518
+ C = SHA256_IV[2] | 0;
519
+ D = SHA256_IV[3] | 0;
520
+ E = SHA256_IV[4] | 0;
521
+ F = SHA256_IV[5] | 0;
522
+ G = SHA256_IV[6] | 0;
523
+ H = SHA256_IV[7] | 0;
524
+ constructor() {
525
+ super(32);
526
+ }
527
+ };
528
+ var K512 = /* @__PURE__ */ (() => split([
345
529
  "0x428a2f98d728ae22",
346
530
  "0x7137449123ef65cd",
347
531
  "0xb5c0fbcfec4d3b2f",
@@ -423,30 +607,16 @@ var NearUtils = (() => {
423
607
  "0x5fcb6fab3ad6faec",
424
608
  "0x6c44198c4a475817"
425
609
  ].map((n) => BigInt(n))))();
610
+ var SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
611
+ var SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
426
612
  var SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
427
613
  var SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
428
- var SHA512 = class extends HashMD {
614
+ var SHA2_64B = class extends HashMD {
429
615
  static {
430
- __name(this, "SHA512");
616
+ __name(this, "SHA2_64B");
431
617
  }
432
- constructor() {
433
- super(128, 64, 16, false);
434
- this.Ah = 1779033703 | 0;
435
- this.Al = 4089235720 | 0;
436
- this.Bh = 3144134277 | 0;
437
- this.Bl = 2227873595 | 0;
438
- this.Ch = 1013904242 | 0;
439
- this.Cl = 4271175723 | 0;
440
- this.Dh = 2773480762 | 0;
441
- this.Dl = 1595750129 | 0;
442
- this.Eh = 1359893119 | 0;
443
- this.El = 2917565137 | 0;
444
- this.Fh = 2600822924 | 0;
445
- this.Fl = 725511199 | 0;
446
- this.Gh = 528734635 | 0;
447
- this.Gl = 4215389547 | 0;
448
- this.Hh = 1541459225 | 0;
449
- this.Hl = 327033209 | 0;
618
+ constructor(outputLen) {
619
+ super(128, outputLen, 16, false);
450
620
  }
451
621
  // prettier-ignore
452
622
  get() {
@@ -480,28 +650,28 @@ var NearUtils = (() => {
480
650
  for (let i = 16; i < 80; i++) {
481
651
  const W15h = SHA512_W_H[i - 15] | 0;
482
652
  const W15l = SHA512_W_L[i - 15] | 0;
483
- const s0h = u64_default.rotrSH(W15h, W15l, 1) ^ u64_default.rotrSH(W15h, W15l, 8) ^ u64_default.shrSH(W15h, W15l, 7);
484
- const s0l = u64_default.rotrSL(W15h, W15l, 1) ^ u64_default.rotrSL(W15h, W15l, 8) ^ u64_default.shrSL(W15h, W15l, 7);
653
+ const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7);
654
+ const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7);
485
655
  const W2h = SHA512_W_H[i - 2] | 0;
486
656
  const W2l = SHA512_W_L[i - 2] | 0;
487
- const s1h = u64_default.rotrSH(W2h, W2l, 19) ^ u64_default.rotrBH(W2h, W2l, 61) ^ u64_default.shrSH(W2h, W2l, 6);
488
- const s1l = u64_default.rotrSL(W2h, W2l, 19) ^ u64_default.rotrBL(W2h, W2l, 61) ^ u64_default.shrSL(W2h, W2l, 6);
489
- const SUMl = u64_default.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
490
- const SUMh = u64_default.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
657
+ const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6);
658
+ const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6);
659
+ const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
660
+ const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
491
661
  SHA512_W_H[i] = SUMh | 0;
492
662
  SHA512_W_L[i] = SUMl | 0;
493
663
  }
494
664
  let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
495
665
  for (let i = 0; i < 80; i++) {
496
- const sigma1h = u64_default.rotrSH(Eh, El, 14) ^ u64_default.rotrSH(Eh, El, 18) ^ u64_default.rotrBH(Eh, El, 41);
497
- const sigma1l = u64_default.rotrSL(Eh, El, 14) ^ u64_default.rotrSL(Eh, El, 18) ^ u64_default.rotrBL(Eh, El, 41);
666
+ const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41);
667
+ const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41);
498
668
  const CHIh = Eh & Fh ^ ~Eh & Gh;
499
669
  const CHIl = El & Fl ^ ~El & Gl;
500
- const T1ll = u64_default.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
501
- const T1h = u64_default.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
670
+ const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
671
+ const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
502
672
  const T1l = T1ll | 0;
503
- const sigma0h = u64_default.rotrSH(Ah, Al, 28) ^ u64_default.rotrBH(Ah, Al, 34) ^ u64_default.rotrBH(Ah, Al, 39);
504
- const sigma0l = u64_default.rotrSL(Ah, Al, 28) ^ u64_default.rotrBL(Ah, Al, 34) ^ u64_default.rotrBL(Ah, Al, 39);
673
+ const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39);
674
+ const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39);
505
675
  const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch;
506
676
  const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl;
507
677
  Hh = Gh | 0;
@@ -510,155 +680,119 @@ var NearUtils = (() => {
510
680
  Gl = Fl | 0;
511
681
  Fh = Eh | 0;
512
682
  Fl = El | 0;
513
- ({ h: Eh, l: El } = u64_default.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
683
+ ({ h: Eh, l: El } = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
514
684
  Dh = Ch | 0;
515
685
  Dl = Cl | 0;
516
686
  Ch = Bh | 0;
517
687
  Cl = Bl | 0;
518
688
  Bh = Ah | 0;
519
689
  Bl = Al | 0;
520
- const All = u64_default.add3L(T1l, sigma0l, MAJl);
521
- Ah = u64_default.add3H(All, T1h, sigma0h, MAJh);
690
+ const All = add3L(T1l, sigma0l, MAJl);
691
+ Ah = add3H(All, T1h, sigma0h, MAJh);
522
692
  Al = All | 0;
523
693
  }
524
- ({ h: Ah, l: Al } = u64_default.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
525
- ({ h: Bh, l: Bl } = u64_default.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
526
- ({ h: Ch, l: Cl } = u64_default.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
527
- ({ h: Dh, l: Dl } = u64_default.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
528
- ({ h: Eh, l: El } = u64_default.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
529
- ({ h: Fh, l: Fl } = u64_default.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
530
- ({ h: Gh, l: Gl } = u64_default.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
531
- ({ h: Hh, l: Hl } = u64_default.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
694
+ ({ h: Ah, l: Al } = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
695
+ ({ h: Bh, l: Bl } = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
696
+ ({ h: Ch, l: Cl } = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
697
+ ({ h: Dh, l: Dl } = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
698
+ ({ h: Eh, l: El } = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
699
+ ({ h: Fh, l: Fl } = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
700
+ ({ h: Gh, l: Gl } = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
701
+ ({ h: Hh, l: Hl } = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
532
702
  this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
533
703
  }
534
704
  roundClean() {
535
- SHA512_W_H.fill(0);
536
- SHA512_W_L.fill(0);
705
+ clean(SHA512_W_H, SHA512_W_L);
537
706
  }
538
707
  destroy() {
539
- this.buffer.fill(0);
708
+ clean(this.buffer);
540
709
  this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
541
710
  }
542
711
  };
543
- var sha512 = /* @__PURE__ */ wrapConstructor(() => new SHA512());
712
+ var _SHA512 = class extends SHA2_64B {
713
+ static {
714
+ __name(this, "_SHA512");
715
+ }
716
+ Ah = SHA512_IV[0] | 0;
717
+ Al = SHA512_IV[1] | 0;
718
+ Bh = SHA512_IV[2] | 0;
719
+ Bl = SHA512_IV[3] | 0;
720
+ Ch = SHA512_IV[4] | 0;
721
+ Cl = SHA512_IV[5] | 0;
722
+ Dh = SHA512_IV[6] | 0;
723
+ Dl = SHA512_IV[7] | 0;
724
+ Eh = SHA512_IV[8] | 0;
725
+ El = SHA512_IV[9] | 0;
726
+ Fh = SHA512_IV[10] | 0;
727
+ Fl = SHA512_IV[11] | 0;
728
+ Gh = SHA512_IV[12] | 0;
729
+ Gl = SHA512_IV[13] | 0;
730
+ Hh = SHA512_IV[14] | 0;
731
+ Hl = SHA512_IV[15] | 0;
732
+ constructor() {
733
+ super(64);
734
+ }
735
+ };
736
+ var sha256 = /* @__PURE__ */ createHasher(
737
+ () => new _SHA256(),
738
+ /* @__PURE__ */ oidNist(1)
739
+ );
740
+ var sha512 = /* @__PURE__ */ createHasher(
741
+ () => new _SHA512(),
742
+ /* @__PURE__ */ oidNist(3)
743
+ );
544
744
 
545
- // ../../node_modules/@noble/curves/esm/abstract/utils.js
745
+ // node_modules/@noble/curves/utils.js
546
746
  var _0n = /* @__PURE__ */ BigInt(0);
547
747
  var _1n = /* @__PURE__ */ BigInt(1);
548
- var _2n = /* @__PURE__ */ BigInt(2);
549
- function isBytes2(a) {
550
- return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
551
- }
552
- __name(isBytes2, "isBytes");
553
- function abytes2(item) {
554
- if (!isBytes2(item))
555
- throw new Error("Uint8Array expected");
556
- }
557
- __name(abytes2, "abytes");
558
- function abool(title, value) {
559
- if (typeof value !== "boolean")
560
- throw new Error(title + " boolean expected, got " + value);
748
+ function abool(value, title = "") {
749
+ if (typeof value !== "boolean") {
750
+ const prefix = title && `"${title}" `;
751
+ throw new Error(prefix + "expected boolean, got type=" + typeof value);
752
+ }
753
+ return value;
561
754
  }
562
755
  __name(abool, "abool");
563
- var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
564
- function bytesToHex(bytes) {
565
- abytes2(bytes);
566
- let hex = "";
567
- for (let i = 0; i < bytes.length; i++) {
568
- hex += hexes[bytes[i]];
569
- }
570
- return hex;
756
+ function abignumber(n) {
757
+ if (typeof n === "bigint") {
758
+ if (!isPosBig(n))
759
+ throw new Error("positive bigint expected, got " + n);
760
+ } else
761
+ anumber(n);
762
+ return n;
571
763
  }
572
- __name(bytesToHex, "bytesToHex");
764
+ __name(abignumber, "abignumber");
573
765
  function hexToNumber(hex) {
574
766
  if (typeof hex !== "string")
575
767
  throw new Error("hex string expected, got " + typeof hex);
576
768
  return hex === "" ? _0n : BigInt("0x" + hex);
577
769
  }
578
770
  __name(hexToNumber, "hexToNumber");
579
- var asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
580
- function asciiToBase16(ch) {
581
- if (ch >= asciis._0 && ch <= asciis._9)
582
- return ch - asciis._0;
583
- if (ch >= asciis.A && ch <= asciis.F)
584
- return ch - (asciis.A - 10);
585
- if (ch >= asciis.a && ch <= asciis.f)
586
- return ch - (asciis.a - 10);
587
- return;
588
- }
589
- __name(asciiToBase16, "asciiToBase16");
590
- function hexToBytes(hex) {
591
- if (typeof hex !== "string")
592
- throw new Error("hex string expected, got " + typeof hex);
593
- const hl = hex.length;
594
- const al = hl / 2;
595
- if (hl % 2)
596
- throw new Error("hex string expected, got unpadded hex of length " + hl);
597
- const array = new Uint8Array(al);
598
- for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
599
- const n1 = asciiToBase16(hex.charCodeAt(hi));
600
- const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
601
- if (n1 === void 0 || n2 === void 0) {
602
- const char = hex[hi] + hex[hi + 1];
603
- throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
604
- }
605
- array[ai] = n1 * 16 + n2;
606
- }
607
- return array;
608
- }
609
- __name(hexToBytes, "hexToBytes");
610
- function bytesToNumberBE(bytes) {
611
- return hexToNumber(bytesToHex(bytes));
771
+ function bytesToNumberBE(bytes) {
772
+ return hexToNumber(bytesToHex(bytes));
612
773
  }
613
774
  __name(bytesToNumberBE, "bytesToNumberBE");
614
775
  function bytesToNumberLE(bytes) {
615
- abytes2(bytes);
616
- return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
776
+ return hexToNumber(bytesToHex(copyBytes(abytes(bytes)).reverse()));
617
777
  }
618
778
  __name(bytesToNumberLE, "bytesToNumberLE");
619
779
  function numberToBytesBE(n, len) {
620
- return hexToBytes(n.toString(16).padStart(len * 2, "0"));
780
+ anumber(len);
781
+ n = abignumber(n);
782
+ const res = hexToBytes(n.toString(16).padStart(len * 2, "0"));
783
+ if (res.length !== len)
784
+ throw new Error("number too large");
785
+ return res;
621
786
  }
622
787
  __name(numberToBytesBE, "numberToBytesBE");
623
788
  function numberToBytesLE(n, len) {
624
789
  return numberToBytesBE(n, len).reverse();
625
790
  }
626
791
  __name(numberToBytesLE, "numberToBytesLE");
627
- function ensureBytes(title, hex, expectedLength) {
628
- let res;
629
- if (typeof hex === "string") {
630
- try {
631
- res = hexToBytes(hex);
632
- } catch (e) {
633
- throw new Error(title + " must be hex string or Uint8Array, cause: " + e);
634
- }
635
- } else if (isBytes2(hex)) {
636
- res = Uint8Array.from(hex);
637
- } else {
638
- throw new Error(title + " must be hex string or Uint8Array");
639
- }
640
- const len = res.length;
641
- if (typeof expectedLength === "number" && len !== expectedLength)
642
- throw new Error(title + " of length " + expectedLength + " expected, got " + len);
643
- return res;
644
- }
645
- __name(ensureBytes, "ensureBytes");
646
- function concatBytes(...arrays) {
647
- let sum = 0;
648
- for (let i = 0; i < arrays.length; i++) {
649
- const a = arrays[i];
650
- abytes2(a);
651
- sum += a.length;
652
- }
653
- const res = new Uint8Array(sum);
654
- for (let i = 0, pad = 0; i < arrays.length; i++) {
655
- const a = arrays[i];
656
- res.set(a, pad);
657
- pad += a.length;
658
- }
659
- return res;
792
+ function copyBytes(bytes) {
793
+ return Uint8Array.from(bytes);
660
794
  }
661
- __name(concatBytes, "concatBytes");
795
+ __name(copyBytes, "copyBytes");
662
796
  var isPosBig = /* @__PURE__ */ __name((n) => typeof n === "bigint" && _0n <= n, "isPosBig");
663
797
  function inRange(n, min, max) {
664
798
  return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
@@ -669,42 +803,22 @@ var NearUtils = (() => {
669
803
  throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
670
804
  }
671
805
  __name(aInRange, "aInRange");
672
- function bitLen(n) {
673
- let len;
674
- for (len = 0; n > _0n; n >>= _1n, len += 1)
675
- ;
676
- return len;
677
- }
678
- __name(bitLen, "bitLen");
679
- var bitMask = /* @__PURE__ */ __name((n) => (_2n << BigInt(n - 1)) - _1n, "bitMask");
680
- var validatorFns = {
681
- bigint: /* @__PURE__ */ __name((val) => typeof val === "bigint", "bigint"),
682
- function: /* @__PURE__ */ __name((val) => typeof val === "function", "function"),
683
- boolean: /* @__PURE__ */ __name((val) => typeof val === "boolean", "boolean"),
684
- string: /* @__PURE__ */ __name((val) => typeof val === "string", "string"),
685
- stringOrUint8Array: /* @__PURE__ */ __name((val) => typeof val === "string" || isBytes2(val), "stringOrUint8Array"),
686
- isSafeInteger: /* @__PURE__ */ __name((val) => Number.isSafeInteger(val), "isSafeInteger"),
687
- array: /* @__PURE__ */ __name((val) => Array.isArray(val), "array"),
688
- field: /* @__PURE__ */ __name((val, object) => object.Fp.isValid(val), "field"),
689
- hash: /* @__PURE__ */ __name((val) => typeof val === "function" && Number.isSafeInteger(val.outputLen), "hash")
690
- };
691
- function validateObject(object, validators, optValidators = {}) {
692
- const checkField = /* @__PURE__ */ __name((fieldName, type, isOptional) => {
693
- const checkVal = validatorFns[type];
694
- if (typeof checkVal !== "function")
695
- throw new Error("invalid validator function");
806
+ var bitMask = /* @__PURE__ */ __name((n) => (_1n << BigInt(n)) - _1n, "bitMask");
807
+ function validateObject(object, fields = {}, optFields = {}) {
808
+ if (!object || typeof object !== "object")
809
+ throw new Error("expected valid options object");
810
+ function checkField(fieldName, expectedType, isOpt) {
696
811
  const val = object[fieldName];
697
- if (isOptional && val === void 0)
812
+ if (isOpt && val === void 0)
698
813
  return;
699
- if (!checkVal(val, object)) {
700
- throw new Error("param " + String(fieldName) + " is invalid. Expected " + type + ", got " + val);
701
- }
702
- }, "checkField");
703
- for (const [fieldName, type] of Object.entries(validators))
704
- checkField(fieldName, type, false);
705
- for (const [fieldName, type] of Object.entries(optValidators))
706
- checkField(fieldName, type, true);
707
- return object;
814
+ const current = typeof val;
815
+ if (current !== expectedType || val === null)
816
+ throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
817
+ }
818
+ __name(checkField, "checkField");
819
+ const iter = /* @__PURE__ */ __name((f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt)), "iter");
820
+ iter(fields, false);
821
+ iter(optFields, true);
708
822
  }
709
823
  __name(validateObject, "validateObject");
710
824
  function memoized(fn) {
@@ -720,13 +834,14 @@ var NearUtils = (() => {
720
834
  }
721
835
  __name(memoized, "memoized");
722
836
 
723
- // ../../node_modules/@noble/curves/esm/abstract/modular.js
724
- var _0n2 = BigInt(0);
725
- var _1n2 = BigInt(1);
726
- var _2n2 = /* @__PURE__ */ BigInt(2);
837
+ // node_modules/@noble/curves/abstract/modular.js
838
+ var _0n2 = /* @__PURE__ */ BigInt(0);
839
+ var _1n2 = /* @__PURE__ */ BigInt(1);
840
+ var _2n = /* @__PURE__ */ BigInt(2);
727
841
  var _3n = /* @__PURE__ */ BigInt(3);
728
842
  var _4n = /* @__PURE__ */ BigInt(4);
729
843
  var _5n = /* @__PURE__ */ BigInt(5);
844
+ var _7n = /* @__PURE__ */ BigInt(7);
730
845
  var _8n = /* @__PURE__ */ BigInt(8);
731
846
  var _9n = /* @__PURE__ */ BigInt(9);
732
847
  var _16n = /* @__PURE__ */ BigInt(16);
@@ -735,23 +850,6 @@ var NearUtils = (() => {
735
850
  return result >= _0n2 ? result : b + result;
736
851
  }
737
852
  __name(mod, "mod");
738
- function pow(num, power, modulo) {
739
- if (power < _0n2)
740
- throw new Error("invalid exponent, negatives unsupported");
741
- if (modulo <= _0n2)
742
- throw new Error("invalid modulus");
743
- if (modulo === _1n2)
744
- return _0n2;
745
- let res = _1n2;
746
- while (power > _0n2) {
747
- if (power & _1n2)
748
- res = res * num % modulo;
749
- num = num * num % modulo;
750
- power >>= _1n2;
751
- }
752
- return res;
753
- }
754
- __name(pow, "pow");
755
853
  function pow2(x, power, modulo) {
756
854
  let res = x;
757
855
  while (power-- > _0n2) {
@@ -782,76 +880,109 @@ var NearUtils = (() => {
782
880
  return mod(x, modulo);
783
881
  }
784
882
  __name(invert, "invert");
883
+ function assertIsSquare(Fp, root, n) {
884
+ if (!Fp.eql(Fp.sqr(root), n))
885
+ throw new Error("Cannot find square root");
886
+ }
887
+ __name(assertIsSquare, "assertIsSquare");
888
+ function sqrt3mod4(Fp, n) {
889
+ const p1div4 = (Fp.ORDER + _1n2) / _4n;
890
+ const root = Fp.pow(n, p1div4);
891
+ assertIsSquare(Fp, root, n);
892
+ return root;
893
+ }
894
+ __name(sqrt3mod4, "sqrt3mod4");
895
+ function sqrt5mod8(Fp, n) {
896
+ const p5div8 = (Fp.ORDER - _5n) / _8n;
897
+ const n2 = Fp.mul(n, _2n);
898
+ const v = Fp.pow(n2, p5div8);
899
+ const nv = Fp.mul(n, v);
900
+ const i = Fp.mul(Fp.mul(nv, _2n), v);
901
+ const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
902
+ assertIsSquare(Fp, root, n);
903
+ return root;
904
+ }
905
+ __name(sqrt5mod8, "sqrt5mod8");
906
+ function sqrt9mod16(P2) {
907
+ const Fp_ = Field(P2);
908
+ const tn = tonelliShanks(P2);
909
+ const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
910
+ const c2 = tn(Fp_, c1);
911
+ const c3 = tn(Fp_, Fp_.neg(c1));
912
+ const c4 = (P2 + _7n) / _16n;
913
+ return (Fp, n) => {
914
+ let tv1 = Fp.pow(n, c4);
915
+ let tv2 = Fp.mul(tv1, c1);
916
+ const tv3 = Fp.mul(tv1, c2);
917
+ const tv4 = Fp.mul(tv1, c3);
918
+ const e1 = Fp.eql(Fp.sqr(tv2), n);
919
+ const e2 = Fp.eql(Fp.sqr(tv3), n);
920
+ tv1 = Fp.cmov(tv1, tv2, e1);
921
+ tv2 = Fp.cmov(tv4, tv3, e2);
922
+ const e3 = Fp.eql(Fp.sqr(tv2), n);
923
+ const root = Fp.cmov(tv1, tv2, e3);
924
+ assertIsSquare(Fp, root, n);
925
+ return root;
926
+ };
927
+ }
928
+ __name(sqrt9mod16, "sqrt9mod16");
785
929
  function tonelliShanks(P2) {
786
- const legendreC = (P2 - _1n2) / _2n2;
787
- let Q, S, Z;
788
- for (Q = P2 - _1n2, S = 0; Q % _2n2 === _0n2; Q /= _2n2, S++)
789
- ;
790
- for (Z = _2n2; Z < P2 && pow(Z, legendreC, P2) !== P2 - _1n2; Z++) {
791
- if (Z > 1e3)
792
- throw new Error("Cannot find square root: likely non-prime P");
793
- }
794
- if (S === 1) {
795
- const p1div4 = (P2 + _1n2) / _4n;
796
- return /* @__PURE__ */ __name(function tonelliFast(Fp2, n) {
797
- const root = Fp2.pow(n, p1div4);
798
- if (!Fp2.eql(Fp2.sqr(root), n))
799
- throw new Error("Cannot find square root");
800
- return root;
801
- }, "tonelliFast");
802
- }
803
- const Q1div2 = (Q + _1n2) / _2n2;
804
- return /* @__PURE__ */ __name(function tonelliSlow(Fp2, n) {
805
- if (Fp2.pow(n, legendreC) === Fp2.neg(Fp2.ONE))
930
+ if (P2 < _3n)
931
+ throw new Error("sqrt is not defined for small field");
932
+ let Q = P2 - _1n2;
933
+ let S = 0;
934
+ while (Q % _2n === _0n2) {
935
+ Q /= _2n;
936
+ S++;
937
+ }
938
+ let Z = _2n;
939
+ const _Fp = Field(P2);
940
+ while (FpLegendre(_Fp, Z) === 1) {
941
+ if (Z++ > 1e3)
942
+ throw new Error("Cannot find square root: probably non-prime P");
943
+ }
944
+ if (S === 1)
945
+ return sqrt3mod4;
946
+ let cc = _Fp.pow(Z, Q);
947
+ const Q1div2 = (Q + _1n2) / _2n;
948
+ return /* @__PURE__ */ __name(function tonelliSlow(Fp, n) {
949
+ if (Fp.is0(n))
950
+ return n;
951
+ if (FpLegendre(Fp, n) !== 1)
806
952
  throw new Error("Cannot find square root");
807
- let r = S;
808
- let g = Fp2.pow(Fp2.mul(Fp2.ONE, Z), Q);
809
- let x = Fp2.pow(n, Q1div2);
810
- let b = Fp2.pow(n, Q);
811
- while (!Fp2.eql(b, Fp2.ONE)) {
812
- if (Fp2.eql(b, Fp2.ZERO))
813
- return Fp2.ZERO;
814
- let m = 1;
815
- for (let t2 = Fp2.sqr(b); m < r; m++) {
816
- if (Fp2.eql(t2, Fp2.ONE))
817
- break;
818
- t2 = Fp2.sqr(t2);
953
+ let M = S;
954
+ let c = Fp.mul(Fp.ONE, cc);
955
+ let t = Fp.pow(n, Q);
956
+ let R = Fp.pow(n, Q1div2);
957
+ while (!Fp.eql(t, Fp.ONE)) {
958
+ if (Fp.is0(t))
959
+ return Fp.ZERO;
960
+ let i = 1;
961
+ let t_tmp = Fp.sqr(t);
962
+ while (!Fp.eql(t_tmp, Fp.ONE)) {
963
+ i++;
964
+ t_tmp = Fp.sqr(t_tmp);
965
+ if (i === M)
966
+ throw new Error("Cannot find square root");
819
967
  }
820
- const ge = Fp2.pow(g, _1n2 << BigInt(r - m - 1));
821
- g = Fp2.sqr(ge);
822
- x = Fp2.mul(x, ge);
823
- b = Fp2.mul(b, g);
824
- r = m;
825
- }
826
- return x;
968
+ const exponent = _1n2 << BigInt(M - i - 1);
969
+ const b = Fp.pow(c, exponent);
970
+ M = i;
971
+ c = Fp.sqr(b);
972
+ t = Fp.mul(t, c);
973
+ R = Fp.mul(R, b);
974
+ }
975
+ return R;
827
976
  }, "tonelliSlow");
828
977
  }
829
978
  __name(tonelliShanks, "tonelliShanks");
830
979
  function FpSqrt(P2) {
831
- if (P2 % _4n === _3n) {
832
- const p1div4 = (P2 + _1n2) / _4n;
833
- return /* @__PURE__ */ __name(function sqrt3mod4(Fp2, n) {
834
- const root = Fp2.pow(n, p1div4);
835
- if (!Fp2.eql(Fp2.sqr(root), n))
836
- throw new Error("Cannot find square root");
837
- return root;
838
- }, "sqrt3mod4");
839
- }
840
- if (P2 % _8n === _5n) {
841
- const c1 = (P2 - _5n) / _8n;
842
- return /* @__PURE__ */ __name(function sqrt5mod8(Fp2, n) {
843
- const n2 = Fp2.mul(n, _2n2);
844
- const v = Fp2.pow(n2, c1);
845
- const nv = Fp2.mul(n, v);
846
- const i = Fp2.mul(Fp2.mul(nv, _2n2), v);
847
- const root = Fp2.mul(nv, Fp2.sub(i, Fp2.ONE));
848
- if (!Fp2.eql(Fp2.sqr(root), n))
849
- throw new Error("Cannot find square root");
850
- return root;
851
- }, "sqrt5mod8");
852
- }
853
- if (P2 % _16n === _9n) {
854
- }
980
+ if (P2 % _4n === _3n)
981
+ return sqrt3mod4;
982
+ if (P2 % _8n === _5n)
983
+ return sqrt5mod8;
984
+ if (P2 % _16n === _9n)
985
+ return sqrt9mod16(P2);
855
986
  return tonelliShanks(P2);
856
987
  }
857
988
  __name(FpSqrt, "FpSqrt");
@@ -878,422 +1009,506 @@ var NearUtils = (() => {
878
1009
  function validateField(field) {
879
1010
  const initial = {
880
1011
  ORDER: "bigint",
881
- MASK: "bigint",
882
- BYTES: "isSafeInteger",
883
- BITS: "isSafeInteger"
1012
+ BYTES: "number",
1013
+ BITS: "number"
884
1014
  };
885
1015
  const opts = FIELD_FIELDS.reduce((map, val) => {
886
1016
  map[val] = "function";
887
1017
  return map;
888
1018
  }, initial);
889
- return validateObject(field, opts);
1019
+ validateObject(field, opts);
1020
+ return field;
890
1021
  }
891
1022
  __name(validateField, "validateField");
892
- function FpPow(f, num, power) {
1023
+ function FpPow(Fp, num, power) {
893
1024
  if (power < _0n2)
894
1025
  throw new Error("invalid exponent, negatives unsupported");
895
1026
  if (power === _0n2)
896
- return f.ONE;
1027
+ return Fp.ONE;
897
1028
  if (power === _1n2)
898
1029
  return num;
899
- let p = f.ONE;
1030
+ let p = Fp.ONE;
900
1031
  let d = num;
901
1032
  while (power > _0n2) {
902
1033
  if (power & _1n2)
903
- p = f.mul(p, d);
904
- d = f.sqr(d);
1034
+ p = Fp.mul(p, d);
1035
+ d = Fp.sqr(d);
905
1036
  power >>= _1n2;
906
1037
  }
907
1038
  return p;
908
1039
  }
909
1040
  __name(FpPow, "FpPow");
910
- function FpInvertBatch(f, nums) {
911
- const tmp = new Array(nums.length);
912
- const lastMultiplied = nums.reduce((acc, num, i) => {
913
- if (f.is0(num))
1041
+ function FpInvertBatch(Fp, nums, passZero = false) {
1042
+ const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : void 0);
1043
+ const multipliedAcc = nums.reduce((acc, num, i) => {
1044
+ if (Fp.is0(num))
914
1045
  return acc;
915
- tmp[i] = acc;
916
- return f.mul(acc, num);
917
- }, f.ONE);
918
- const inverted = f.inv(lastMultiplied);
1046
+ inverted[i] = acc;
1047
+ return Fp.mul(acc, num);
1048
+ }, Fp.ONE);
1049
+ const invertedAcc = Fp.inv(multipliedAcc);
919
1050
  nums.reduceRight((acc, num, i) => {
920
- if (f.is0(num))
1051
+ if (Fp.is0(num))
921
1052
  return acc;
922
- tmp[i] = f.mul(acc, tmp[i]);
923
- return f.mul(acc, num);
924
- }, inverted);
925
- return tmp;
1053
+ inverted[i] = Fp.mul(acc, inverted[i]);
1054
+ return Fp.mul(acc, num);
1055
+ }, invertedAcc);
1056
+ return inverted;
926
1057
  }
927
1058
  __name(FpInvertBatch, "FpInvertBatch");
1059
+ function FpLegendre(Fp, n) {
1060
+ const p1mod2 = (Fp.ORDER - _1n2) / _2n;
1061
+ const powered = Fp.pow(n, p1mod2);
1062
+ const yes = Fp.eql(powered, Fp.ONE);
1063
+ const zero = Fp.eql(powered, Fp.ZERO);
1064
+ const no = Fp.eql(powered, Fp.neg(Fp.ONE));
1065
+ if (!yes && !zero && !no)
1066
+ throw new Error("invalid Legendre symbol result");
1067
+ return yes ? 1 : zero ? 0 : -1;
1068
+ }
1069
+ __name(FpLegendre, "FpLegendre");
928
1070
  function nLength(n, nBitLength) {
1071
+ if (nBitLength !== void 0)
1072
+ anumber(nBitLength);
929
1073
  const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length;
930
1074
  const nByteLength = Math.ceil(_nBitLength / 8);
931
1075
  return { nBitLength: _nBitLength, nByteLength };
932
1076
  }
933
1077
  __name(nLength, "nLength");
934
- function Field(ORDER, bitLen2, isLE = false, redef = {}) {
935
- if (ORDER <= _0n2)
936
- throw new Error("invalid field: expected ORDER > 0, got " + ORDER);
937
- const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen2);
938
- if (BYTES > 2048)
939
- throw new Error("invalid field: expected ORDER of <= 2048 bytes");
940
- let sqrtP;
941
- const f = Object.freeze({
942
- ORDER,
943
- isLE,
944
- BITS,
945
- BYTES,
946
- MASK: bitMask(BITS),
947
- ZERO: _0n2,
948
- ONE: _1n2,
949
- create: /* @__PURE__ */ __name((num) => mod(num, ORDER), "create"),
950
- isValid: /* @__PURE__ */ __name((num) => {
951
- if (typeof num !== "bigint")
952
- throw new Error("invalid field element: expected bigint, got " + typeof num);
953
- return _0n2 <= num && num < ORDER;
954
- }, "isValid"),
955
- is0: /* @__PURE__ */ __name((num) => num === _0n2, "is0"),
956
- isOdd: /* @__PURE__ */ __name((num) => (num & _1n2) === _1n2, "isOdd"),
957
- neg: /* @__PURE__ */ __name((num) => mod(-num, ORDER), "neg"),
958
- eql: /* @__PURE__ */ __name((lhs, rhs) => lhs === rhs, "eql"),
959
- sqr: /* @__PURE__ */ __name((num) => mod(num * num, ORDER), "sqr"),
960
- add: /* @__PURE__ */ __name((lhs, rhs) => mod(lhs + rhs, ORDER), "add"),
961
- sub: /* @__PURE__ */ __name((lhs, rhs) => mod(lhs - rhs, ORDER), "sub"),
962
- mul: /* @__PURE__ */ __name((lhs, rhs) => mod(lhs * rhs, ORDER), "mul"),
963
- pow: /* @__PURE__ */ __name((num, power) => FpPow(f, num, power), "pow"),
964
- div: /* @__PURE__ */ __name((lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER), "div"),
965
- // Same as above, but doesn't normalize
966
- sqrN: /* @__PURE__ */ __name((num) => num * num, "sqrN"),
967
- addN: /* @__PURE__ */ __name((lhs, rhs) => lhs + rhs, "addN"),
968
- subN: /* @__PURE__ */ __name((lhs, rhs) => lhs - rhs, "subN"),
969
- mulN: /* @__PURE__ */ __name((lhs, rhs) => lhs * rhs, "mulN"),
970
- inv: /* @__PURE__ */ __name((num) => invert(num, ORDER), "inv"),
971
- sqrt: redef.sqrt || ((n) => {
972
- if (!sqrtP)
973
- sqrtP = FpSqrt(ORDER);
974
- return sqrtP(f, n);
975
- }),
976
- invertBatch: /* @__PURE__ */ __name((lst) => FpInvertBatch(f, lst), "invertBatch"),
977
- // TODO: do we really need constant cmov?
978
- // We don't have const-time bigints anyway, so probably will be not very useful
979
- cmov: /* @__PURE__ */ __name((a, b, c) => c ? b : a, "cmov"),
980
- toBytes: /* @__PURE__ */ __name((num) => isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES), "toBytes"),
981
- fromBytes: /* @__PURE__ */ __name((bytes) => {
982
- if (bytes.length !== BYTES)
983
- throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
984
- return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
985
- }, "fromBytes")
986
- });
987
- return Object.freeze(f);
1078
+ var _Field = class {
1079
+ static {
1080
+ __name(this, "_Field");
1081
+ }
1082
+ ORDER;
1083
+ BITS;
1084
+ BYTES;
1085
+ isLE;
1086
+ ZERO = _0n2;
1087
+ ONE = _1n2;
1088
+ _lengths;
1089
+ _sqrt;
1090
+ // cached sqrt
1091
+ _mod;
1092
+ constructor(ORDER, opts = {}) {
1093
+ if (ORDER <= _0n2)
1094
+ throw new Error("invalid field: expected ORDER > 0, got " + ORDER);
1095
+ let _nbitLength = void 0;
1096
+ this.isLE = false;
1097
+ if (opts != null && typeof opts === "object") {
1098
+ if (typeof opts.BITS === "number")
1099
+ _nbitLength = opts.BITS;
1100
+ if (typeof opts.sqrt === "function")
1101
+ this.sqrt = opts.sqrt;
1102
+ if (typeof opts.isLE === "boolean")
1103
+ this.isLE = opts.isLE;
1104
+ if (opts.allowedLengths)
1105
+ this._lengths = opts.allowedLengths?.slice();
1106
+ if (typeof opts.modFromBytes === "boolean")
1107
+ this._mod = opts.modFromBytes;
1108
+ }
1109
+ const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);
1110
+ if (nByteLength > 2048)
1111
+ throw new Error("invalid field: expected ORDER of <= 2048 bytes");
1112
+ this.ORDER = ORDER;
1113
+ this.BITS = nBitLength;
1114
+ this.BYTES = nByteLength;
1115
+ this._sqrt = void 0;
1116
+ Object.preventExtensions(this);
1117
+ }
1118
+ create(num) {
1119
+ return mod(num, this.ORDER);
1120
+ }
1121
+ isValid(num) {
1122
+ if (typeof num !== "bigint")
1123
+ throw new Error("invalid field element: expected bigint, got " + typeof num);
1124
+ return _0n2 <= num && num < this.ORDER;
1125
+ }
1126
+ is0(num) {
1127
+ return num === _0n2;
1128
+ }
1129
+ // is valid and invertible
1130
+ isValidNot0(num) {
1131
+ return !this.is0(num) && this.isValid(num);
1132
+ }
1133
+ isOdd(num) {
1134
+ return (num & _1n2) === _1n2;
1135
+ }
1136
+ neg(num) {
1137
+ return mod(-num, this.ORDER);
1138
+ }
1139
+ eql(lhs, rhs) {
1140
+ return lhs === rhs;
1141
+ }
1142
+ sqr(num) {
1143
+ return mod(num * num, this.ORDER);
1144
+ }
1145
+ add(lhs, rhs) {
1146
+ return mod(lhs + rhs, this.ORDER);
1147
+ }
1148
+ sub(lhs, rhs) {
1149
+ return mod(lhs - rhs, this.ORDER);
1150
+ }
1151
+ mul(lhs, rhs) {
1152
+ return mod(lhs * rhs, this.ORDER);
1153
+ }
1154
+ pow(num, power) {
1155
+ return FpPow(this, num, power);
1156
+ }
1157
+ div(lhs, rhs) {
1158
+ return mod(lhs * invert(rhs, this.ORDER), this.ORDER);
1159
+ }
1160
+ // Same as above, but doesn't normalize
1161
+ sqrN(num) {
1162
+ return num * num;
1163
+ }
1164
+ addN(lhs, rhs) {
1165
+ return lhs + rhs;
1166
+ }
1167
+ subN(lhs, rhs) {
1168
+ return lhs - rhs;
1169
+ }
1170
+ mulN(lhs, rhs) {
1171
+ return lhs * rhs;
1172
+ }
1173
+ inv(num) {
1174
+ return invert(num, this.ORDER);
1175
+ }
1176
+ sqrt(num) {
1177
+ if (!this._sqrt)
1178
+ this._sqrt = FpSqrt(this.ORDER);
1179
+ return this._sqrt(this, num);
1180
+ }
1181
+ toBytes(num) {
1182
+ return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);
1183
+ }
1184
+ fromBytes(bytes, skipValidation = false) {
1185
+ abytes(bytes);
1186
+ const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;
1187
+ if (allowedLengths) {
1188
+ if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
1189
+ throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
1190
+ }
1191
+ const padded = new Uint8Array(BYTES);
1192
+ padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
1193
+ bytes = padded;
1194
+ }
1195
+ if (bytes.length !== BYTES)
1196
+ throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
1197
+ let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
1198
+ if (modFromBytes)
1199
+ scalar = mod(scalar, ORDER);
1200
+ if (!skipValidation) {
1201
+ if (!this.isValid(scalar))
1202
+ throw new Error("invalid field element: outside of range 0..ORDER");
1203
+ }
1204
+ return scalar;
1205
+ }
1206
+ // TODO: we don't need it here, move out to separate fn
1207
+ invertBatch(lst) {
1208
+ return FpInvertBatch(this, lst);
1209
+ }
1210
+ // We can't move this out because Fp6, Fp12 implement it
1211
+ // and it's unclear what to return in there.
1212
+ cmov(a, b, condition) {
1213
+ return condition ? b : a;
1214
+ }
1215
+ };
1216
+ function Field(ORDER, opts = {}) {
1217
+ return new _Field(ORDER, opts);
988
1218
  }
989
1219
  __name(Field, "Field");
990
1220
 
991
- // ../../node_modules/@noble/curves/esm/abstract/curve.js
992
- var _0n3 = BigInt(0);
993
- var _1n3 = BigInt(1);
994
- function constTimeNegate(condition, item) {
1221
+ // node_modules/@noble/curves/abstract/curve.js
1222
+ var _0n3 = /* @__PURE__ */ BigInt(0);
1223
+ var _1n3 = /* @__PURE__ */ BigInt(1);
1224
+ function negateCt(condition, item) {
995
1225
  const neg = item.negate();
996
1226
  return condition ? neg : item;
997
1227
  }
998
- __name(constTimeNegate, "constTimeNegate");
1228
+ __name(negateCt, "negateCt");
1229
+ function normalizeZ(c, points) {
1230
+ const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
1231
+ return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
1232
+ }
1233
+ __name(normalizeZ, "normalizeZ");
999
1234
  function validateW(W, bits) {
1000
1235
  if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
1001
1236
  throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
1002
1237
  }
1003
1238
  __name(validateW, "validateW");
1004
- function calcWOpts(W, bits) {
1005
- validateW(W, bits);
1006
- const windows = Math.ceil(bits / W) + 1;
1239
+ function calcWOpts(W, scalarBits) {
1240
+ validateW(W, scalarBits);
1241
+ const windows = Math.ceil(scalarBits / W) + 1;
1007
1242
  const windowSize = 2 ** (W - 1);
1008
- return { windows, windowSize };
1243
+ const maxNumber = 2 ** W;
1244
+ const mask = bitMask(W);
1245
+ const shiftBy = BigInt(W);
1246
+ return { windows, windowSize, mask, maxNumber, shiftBy };
1009
1247
  }
1010
1248
  __name(calcWOpts, "calcWOpts");
1011
- function validateMSMPoints(points, c) {
1012
- if (!Array.isArray(points))
1013
- throw new Error("array expected");
1014
- points.forEach((p, i) => {
1015
- if (!(p instanceof c))
1016
- throw new Error("invalid point at index " + i);
1017
- });
1018
- }
1019
- __name(validateMSMPoints, "validateMSMPoints");
1020
- function validateMSMScalars(scalars, field) {
1021
- if (!Array.isArray(scalars))
1022
- throw new Error("array of scalars expected");
1023
- scalars.forEach((s, i) => {
1024
- if (!field.isValid(s))
1025
- throw new Error("invalid scalar at index " + i);
1026
- });
1027
- }
1028
- __name(validateMSMScalars, "validateMSMScalars");
1249
+ function calcOffsets(n, window, wOpts) {
1250
+ const { windowSize, mask, maxNumber, shiftBy } = wOpts;
1251
+ let wbits = Number(n & mask);
1252
+ let nextN = n >> shiftBy;
1253
+ if (wbits > windowSize) {
1254
+ wbits -= maxNumber;
1255
+ nextN += _1n3;
1256
+ }
1257
+ const offsetStart = window * windowSize;
1258
+ const offset = offsetStart + Math.abs(wbits) - 1;
1259
+ const isZero = wbits === 0;
1260
+ const isNeg = wbits < 0;
1261
+ const isNegF = window % 2 !== 0;
1262
+ const offsetF = offsetStart;
1263
+ return { nextN, offset, isZero, isNeg, isNegF, offsetF };
1264
+ }
1265
+ __name(calcOffsets, "calcOffsets");
1029
1266
  var pointPrecomputes = /* @__PURE__ */ new WeakMap();
1030
1267
  var pointWindowSizes = /* @__PURE__ */ new WeakMap();
1031
1268
  function getW(P2) {
1032
1269
  return pointWindowSizes.get(P2) || 1;
1033
1270
  }
1034
1271
  __name(getW, "getW");
1035
- function wNAF(c, bits) {
1036
- return {
1037
- constTimeNegate,
1038
- hasPrecomputes(elm) {
1039
- return getW(elm) !== 1;
1040
- },
1041
- // non-const time multiplication ladder
1042
- unsafeLadder(elm, n, p = c.ZERO) {
1043
- let d = elm;
1044
- while (n > _0n3) {
1045
- if (n & _1n3)
1046
- p = p.add(d);
1047
- d = d.double();
1048
- n >>= _1n3;
1049
- }
1050
- return p;
1051
- },
1052
- /**
1053
- * Creates a wNAF precomputation window. Used for caching.
1054
- * Default window size is set by `utils.precompute()` and is equal to 8.
1055
- * Number of precomputed points depends on the curve size:
1056
- * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
1057
- * - 𝑊 is the window size
1058
- * - 𝑛 is the bitlength of the curve order.
1059
- * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
1060
- * @param elm Point instance
1061
- * @param W window size
1062
- * @returns precomputed point tables flattened to a single array
1063
- */
1064
- precomputeWindow(elm, W) {
1065
- const { windows, windowSize } = calcWOpts(W, bits);
1066
- const points = [];
1067
- let p = elm;
1068
- let base = p;
1069
- for (let window = 0; window < windows; window++) {
1070
- base = p;
1272
+ function assert0(n) {
1273
+ if (n !== _0n3)
1274
+ throw new Error("invalid wNAF");
1275
+ }
1276
+ __name(assert0, "assert0");
1277
+ var wNAF = class {
1278
+ static {
1279
+ __name(this, "wNAF");
1280
+ }
1281
+ BASE;
1282
+ ZERO;
1283
+ Fn;
1284
+ bits;
1285
+ // Parametrized with a given Point class (not individual point)
1286
+ constructor(Point, bits) {
1287
+ this.BASE = Point.BASE;
1288
+ this.ZERO = Point.ZERO;
1289
+ this.Fn = Point.Fn;
1290
+ this.bits = bits;
1291
+ }
1292
+ // non-const time multiplication ladder
1293
+ _unsafeLadder(elm, n, p = this.ZERO) {
1294
+ let d = elm;
1295
+ while (n > _0n3) {
1296
+ if (n & _1n3)
1297
+ p = p.add(d);
1298
+ d = d.double();
1299
+ n >>= _1n3;
1300
+ }
1301
+ return p;
1302
+ }
1303
+ /**
1304
+ * Creates a wNAF precomputation window. Used for caching.
1305
+ * Default window size is set by `utils.precompute()` and is equal to 8.
1306
+ * Number of precomputed points depends on the curve size:
1307
+ * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
1308
+ * - 𝑊 is the window size
1309
+ * - 𝑛 is the bitlength of the curve order.
1310
+ * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
1311
+ * @param point Point instance
1312
+ * @param W window size
1313
+ * @returns precomputed point tables flattened to a single array
1314
+ */
1315
+ precomputeWindow(point, W) {
1316
+ const { windows, windowSize } = calcWOpts(W, this.bits);
1317
+ const points = [];
1318
+ let p = point;
1319
+ let base = p;
1320
+ for (let window = 0; window < windows; window++) {
1321
+ base = p;
1322
+ points.push(base);
1323
+ for (let i = 1; i < windowSize; i++) {
1324
+ base = base.add(p);
1071
1325
  points.push(base);
1072
- for (let i = 1; i < windowSize; i++) {
1073
- base = base.add(p);
1074
- points.push(base);
1075
- }
1076
- p = base.double();
1077
1326
  }
1078
- return points;
1079
- },
1080
- /**
1081
- * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
1082
- * @param W window size
1083
- * @param precomputes precomputed tables
1084
- * @param n scalar (we don't check here, but should be less than curve order)
1085
- * @returns real and fake (for const-time) points
1086
- */
1087
- wNAF(W, precomputes, n) {
1088
- const { windows, windowSize } = calcWOpts(W, bits);
1089
- let p = c.ZERO;
1090
- let f = c.BASE;
1091
- const mask = BigInt(2 ** W - 1);
1092
- const maxNumber = 2 ** W;
1093
- const shiftBy = BigInt(W);
1094
- for (let window = 0; window < windows; window++) {
1095
- const offset = window * windowSize;
1096
- let wbits = Number(n & mask);
1097
- n >>= shiftBy;
1098
- if (wbits > windowSize) {
1099
- wbits -= maxNumber;
1100
- n += _1n3;
1101
- }
1102
- const offset1 = offset;
1103
- const offset2 = offset + Math.abs(wbits) - 1;
1104
- const cond1 = window % 2 !== 0;
1105
- const cond2 = wbits < 0;
1106
- if (wbits === 0) {
1107
- f = f.add(constTimeNegate(cond1, precomputes[offset1]));
1108
- } else {
1109
- p = p.add(constTimeNegate(cond2, precomputes[offset2]));
1110
- }
1327
+ p = base.double();
1328
+ }
1329
+ return points;
1330
+ }
1331
+ /**
1332
+ * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
1333
+ * More compact implementation:
1334
+ * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
1335
+ * @returns real and fake (for const-time) points
1336
+ */
1337
+ wNAF(W, precomputes, n) {
1338
+ if (!this.Fn.isValid(n))
1339
+ throw new Error("invalid scalar");
1340
+ let p = this.ZERO;
1341
+ let f = this.BASE;
1342
+ const wo = calcWOpts(W, this.bits);
1343
+ for (let window = 0; window < wo.windows; window++) {
1344
+ const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
1345
+ n = nextN;
1346
+ if (isZero) {
1347
+ f = f.add(negateCt(isNegF, precomputes[offsetF]));
1348
+ } else {
1349
+ p = p.add(negateCt(isNeg, precomputes[offset]));
1111
1350
  }
1112
- return { p, f };
1113
- },
1114
- /**
1115
- * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
1116
- * @param W window size
1117
- * @param precomputes precomputed tables
1118
- * @param n scalar (we don't check here, but should be less than curve order)
1119
- * @param acc accumulator point to add result of multiplication
1120
- * @returns point
1121
- */
1122
- wNAFUnsafe(W, precomputes, n, acc = c.ZERO) {
1123
- const { windows, windowSize } = calcWOpts(W, bits);
1124
- const mask = BigInt(2 ** W - 1);
1125
- const maxNumber = 2 ** W;
1126
- const shiftBy = BigInt(W);
1127
- for (let window = 0; window < windows; window++) {
1128
- const offset = window * windowSize;
1129
- if (n === _0n3)
1130
- break;
1131
- let wbits = Number(n & mask);
1132
- n >>= shiftBy;
1133
- if (wbits > windowSize) {
1134
- wbits -= maxNumber;
1135
- n += _1n3;
1136
- }
1137
- if (wbits === 0)
1138
- continue;
1139
- let curr = precomputes[offset + Math.abs(wbits) - 1];
1140
- if (wbits < 0)
1141
- curr = curr.negate();
1142
- acc = acc.add(curr);
1351
+ }
1352
+ assert0(n);
1353
+ return { p, f };
1354
+ }
1355
+ /**
1356
+ * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
1357
+ * @param acc accumulator point to add result of multiplication
1358
+ * @returns point
1359
+ */
1360
+ wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
1361
+ const wo = calcWOpts(W, this.bits);
1362
+ for (let window = 0; window < wo.windows; window++) {
1363
+ if (n === _0n3)
1364
+ break;
1365
+ const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
1366
+ n = nextN;
1367
+ if (isZero) {
1368
+ continue;
1369
+ } else {
1370
+ const item = precomputes[offset];
1371
+ acc = acc.add(isNeg ? item.negate() : item);
1143
1372
  }
1144
- return acc;
1145
- },
1146
- getPrecomputes(W, P2, transform) {
1147
- let comp = pointPrecomputes.get(P2);
1148
- if (!comp) {
1149
- comp = this.precomputeWindow(P2, W);
1150
- if (W !== 1)
1151
- pointPrecomputes.set(P2, transform(comp));
1373
+ }
1374
+ assert0(n);
1375
+ return acc;
1376
+ }
1377
+ getPrecomputes(W, point, transform) {
1378
+ let comp = pointPrecomputes.get(point);
1379
+ if (!comp) {
1380
+ comp = this.precomputeWindow(point, W);
1381
+ if (W !== 1) {
1382
+ if (typeof transform === "function")
1383
+ comp = transform(comp);
1384
+ pointPrecomputes.set(point, comp);
1152
1385
  }
1153
- return comp;
1154
- },
1155
- wNAFCached(P2, n, transform) {
1156
- const W = getW(P2);
1157
- return this.wNAF(W, this.getPrecomputes(W, P2, transform), n);
1158
- },
1159
- wNAFCachedUnsafe(P2, n, transform, prev) {
1160
- const W = getW(P2);
1161
- if (W === 1)
1162
- return this.unsafeLadder(P2, n, prev);
1163
- return this.wNAFUnsafe(W, this.getPrecomputes(W, P2, transform), n, prev);
1164
- },
1165
- // We calculate precomputes for elliptic curve point multiplication
1166
- // using windowed method. This specifies window size and
1167
- // stores precomputed values. Usually only base point would be precomputed.
1168
- setWindowSize(P2, W) {
1169
- validateW(W, bits);
1170
- pointWindowSizes.set(P2, W);
1171
- pointPrecomputes.delete(P2);
1172
1386
  }
1173
- };
1174
- }
1175
- __name(wNAF, "wNAF");
1176
- function pippenger(c, fieldN, points, scalars) {
1177
- validateMSMPoints(points, c);
1178
- validateMSMScalars(scalars, fieldN);
1179
- if (points.length !== scalars.length)
1180
- throw new Error("arrays of points and scalars must have equal length");
1181
- const zero = c.ZERO;
1182
- const wbits = bitLen(BigInt(points.length));
1183
- const windowSize = wbits > 12 ? wbits - 3 : wbits > 4 ? wbits - 2 : wbits ? 2 : 1;
1184
- const MASK = (1 << windowSize) - 1;
1185
- const buckets = new Array(MASK + 1).fill(zero);
1186
- const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
1187
- let sum = zero;
1188
- for (let i = lastBits; i >= 0; i -= windowSize) {
1189
- buckets.fill(zero);
1190
- for (let j = 0; j < scalars.length; j++) {
1191
- const scalar = scalars[j];
1192
- const wbits2 = Number(scalar >> BigInt(i) & BigInt(MASK));
1193
- buckets[wbits2] = buckets[wbits2].add(points[j]);
1194
- }
1195
- let resI = zero;
1196
- for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {
1197
- sumI = sumI.add(buckets[j]);
1198
- resI = resI.add(sumI);
1199
- }
1200
- sum = sum.add(resI);
1201
- if (i !== 0)
1202
- for (let j = 0; j < windowSize; j++)
1203
- sum = sum.double();
1204
- }
1205
- return sum;
1206
- }
1207
- __name(pippenger, "pippenger");
1208
- function validateBasic(curve) {
1209
- validateField(curve.Fp);
1210
- validateObject(curve, {
1211
- n: "bigint",
1212
- h: "bigint",
1213
- Gx: "field",
1214
- Gy: "field"
1215
- }, {
1216
- nBitLength: "isSafeInteger",
1217
- nByteLength: "isSafeInteger"
1218
- });
1219
- return Object.freeze({
1220
- ...nLength(curve.n, curve.nBitLength),
1221
- ...curve,
1222
- ...{ p: curve.Fp.ORDER }
1223
- });
1224
- }
1225
- __name(validateBasic, "validateBasic");
1387
+ return comp;
1388
+ }
1389
+ cached(point, scalar, transform) {
1390
+ const W = getW(point);
1391
+ return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
1392
+ }
1393
+ unsafe(point, scalar, transform, prev) {
1394
+ const W = getW(point);
1395
+ if (W === 1)
1396
+ return this._unsafeLadder(point, scalar, prev);
1397
+ return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
1398
+ }
1399
+ // We calculate precomputes for elliptic curve point multiplication
1400
+ // using windowed method. This specifies window size and
1401
+ // stores precomputed values. Usually only base point would be precomputed.
1402
+ createCache(P2, W) {
1403
+ validateW(W, this.bits);
1404
+ pointWindowSizes.set(P2, W);
1405
+ pointPrecomputes.delete(P2);
1406
+ }
1407
+ hasCache(elm) {
1408
+ return getW(elm) !== 1;
1409
+ }
1410
+ };
1411
+ function createField(order, field, isLE) {
1412
+ if (field) {
1413
+ if (field.ORDER !== order)
1414
+ throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
1415
+ validateField(field);
1416
+ return field;
1417
+ } else {
1418
+ return Field(order, { isLE });
1419
+ }
1420
+ }
1421
+ __name(createField, "createField");
1422
+ function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
1423
+ if (FpFnLE === void 0)
1424
+ FpFnLE = type === "edwards";
1425
+ if (!CURVE || typeof CURVE !== "object")
1426
+ throw new Error(`expected valid ${type} CURVE object`);
1427
+ for (const p of ["p", "n", "h"]) {
1428
+ const val = CURVE[p];
1429
+ if (!(typeof val === "bigint" && val > _0n3))
1430
+ throw new Error(`CURVE.${p} must be positive bigint`);
1431
+ }
1432
+ const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
1433
+ const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
1434
+ const _b = type === "weierstrass" ? "b" : "d";
1435
+ const params = ["Gx", "Gy", "a", _b];
1436
+ for (const p of params) {
1437
+ if (!Fp.isValid(CURVE[p]))
1438
+ throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
1439
+ }
1440
+ CURVE = Object.freeze(Object.assign({}, CURVE));
1441
+ return { CURVE, Fp, Fn };
1442
+ }
1443
+ __name(createCurveFields, "createCurveFields");
1444
+ function createKeygen(randomSecretKey, getPublicKey) {
1445
+ return /* @__PURE__ */ __name(function keygen(seed) {
1446
+ const secretKey = randomSecretKey(seed);
1447
+ return { secretKey, publicKey: getPublicKey(secretKey) };
1448
+ }, "keygen");
1449
+ }
1450
+ __name(createKeygen, "createKeygen");
1226
1451
 
1227
- // ../../node_modules/@noble/curves/esm/abstract/edwards.js
1452
+ // node_modules/@noble/curves/abstract/edwards.js
1228
1453
  var _0n4 = BigInt(0);
1229
1454
  var _1n4 = BigInt(1);
1230
- var _2n3 = BigInt(2);
1455
+ var _2n2 = BigInt(2);
1231
1456
  var _8n2 = BigInt(8);
1232
- var VERIFY_DEFAULT = { zip215: true };
1233
- function validateOpts(curve) {
1234
- const opts = validateBasic(curve);
1235
- validateObject(curve, {
1236
- hash: "function",
1237
- a: "bigint",
1238
- d: "bigint",
1239
- randomBytes: "function"
1240
- }, {
1241
- adjustScalarBytes: "function",
1242
- domain: "function",
1243
- uvRatio: "function",
1244
- mapToCurve: "function"
1245
- });
1246
- return Object.freeze({ ...opts });
1247
- }
1248
- __name(validateOpts, "validateOpts");
1249
- function twistedEdwards(curveDef) {
1250
- const CURVE = validateOpts(curveDef);
1251
- const { Fp: Fp2, n: CURVE_ORDER, prehash, hash: cHash, randomBytes: randomBytes2, nByteLength, h: cofactor } = CURVE;
1252
- const MASK = _2n3 << BigInt(nByteLength * 8) - _1n4;
1253
- const modP = Fp2.create;
1254
- const Fn = Field(CURVE.n, CURVE.nBitLength);
1255
- const uvRatio2 = CURVE.uvRatio || ((u, v) => {
1457
+ function isEdValidXY(Fp, CURVE, x, y) {
1458
+ const x2 = Fp.sqr(x);
1459
+ const y2 = Fp.sqr(y);
1460
+ const left = Fp.add(Fp.mul(CURVE.a, x2), y2);
1461
+ const right = Fp.add(Fp.ONE, Fp.mul(CURVE.d, Fp.mul(x2, y2)));
1462
+ return Fp.eql(left, right);
1463
+ }
1464
+ __name(isEdValidXY, "isEdValidXY");
1465
+ function edwards(params, extraOpts = {}) {
1466
+ const validated = createCurveFields("edwards", params, extraOpts, extraOpts.FpFnLE);
1467
+ const { Fp, Fn } = validated;
1468
+ let CURVE = validated.CURVE;
1469
+ const { h: cofactor } = CURVE;
1470
+ validateObject(extraOpts, {}, { uvRatio: "function" });
1471
+ const MASK = _2n2 << BigInt(Fn.BYTES * 8) - _1n4;
1472
+ const modP = /* @__PURE__ */ __name((n) => Fp.create(n), "modP");
1473
+ const uvRatio2 = extraOpts.uvRatio || ((u, v) => {
1256
1474
  try {
1257
- return { isValid: true, value: Fp2.sqrt(u * Fp2.inv(v)) };
1475
+ return { isValid: true, value: Fp.sqrt(Fp.div(u, v)) };
1258
1476
  } catch (e) {
1259
1477
  return { isValid: false, value: _0n4 };
1260
1478
  }
1261
1479
  });
1262
- const adjustScalarBytes2 = CURVE.adjustScalarBytes || ((bytes) => bytes);
1263
- const domain = CURVE.domain || ((data, ctx, phflag) => {
1264
- abool("phflag", phflag);
1265
- if (ctx.length || phflag)
1266
- throw new Error("Contexts/pre-hash are not supported");
1267
- return data;
1268
- });
1269
- function aCoordinate(title, n) {
1270
- aInRange("coordinate " + title, n, _0n4, MASK);
1271
- }
1272
- __name(aCoordinate, "aCoordinate");
1273
- function assertPoint(other) {
1480
+ if (!isEdValidXY(Fp, CURVE, CURVE.Gx, CURVE.Gy))
1481
+ throw new Error("bad curve params: generator point");
1482
+ function acoord(title, n, banZero = false) {
1483
+ const min = banZero ? _1n4 : _0n4;
1484
+ aInRange("coordinate " + title, n, min, MASK);
1485
+ return n;
1486
+ }
1487
+ __name(acoord, "acoord");
1488
+ function aedpoint(other) {
1274
1489
  if (!(other instanceof Point))
1275
- throw new Error("ExtendedPoint expected");
1490
+ throw new Error("EdwardsPoint expected");
1276
1491
  }
1277
- __name(assertPoint, "assertPoint");
1492
+ __name(aedpoint, "aedpoint");
1278
1493
  const toAffineMemo = memoized((p, iz) => {
1279
- const { ex: x, ey: y, ez: z } = p;
1494
+ const { X, Y, Z } = p;
1280
1495
  const is0 = p.is0();
1281
1496
  if (iz == null)
1282
- iz = is0 ? _8n2 : Fp2.inv(z);
1283
- const ax = modP(x * iz);
1284
- const ay = modP(y * iz);
1285
- const zz = modP(z * iz);
1497
+ iz = is0 ? _8n2 : Fp.inv(Z);
1498
+ const x = modP(X * iz);
1499
+ const y = modP(Y * iz);
1500
+ const zz = Fp.mul(Z, iz);
1286
1501
  if (is0)
1287
1502
  return { x: _0n4, y: _1n4 };
1288
1503
  if (zz !== _1n4)
1289
1504
  throw new Error("invZ was invalid");
1290
- return { x: ax, y: ay };
1505
+ return { x, y };
1291
1506
  });
1292
1507
  const assertValidMemo = memoized((p) => {
1293
1508
  const { a, d } = CURVE;
1294
1509
  if (p.is0())
1295
1510
  throw new Error("bad point: ZERO");
1296
- const { ex: X, ey: Y, ez: Z, et: T } = p;
1511
+ const { X, Y, Z, T } = p;
1297
1512
  const X2 = modP(X * X);
1298
1513
  const Y2 = modP(Y * Y);
1299
1514
  const Z2 = modP(Z * Z);
@@ -1313,53 +1528,87 @@ var NearUtils = (() => {
1313
1528
  static {
1314
1529
  __name(this, "Point");
1315
1530
  }
1316
- constructor(ex, ey, ez, et) {
1317
- this.ex = ex;
1318
- this.ey = ey;
1319
- this.ez = ez;
1320
- this.et = et;
1321
- aCoordinate("x", ex);
1322
- aCoordinate("y", ey);
1323
- aCoordinate("z", ez);
1324
- aCoordinate("t", et);
1531
+ // base / generator point
1532
+ static BASE = new Point(CURVE.Gx, CURVE.Gy, _1n4, modP(CURVE.Gx * CURVE.Gy));
1533
+ // zero / infinity / identity point
1534
+ static ZERO = new Point(_0n4, _1n4, _1n4, _0n4);
1535
+ // 0, 1, 1, 0
1536
+ // math field
1537
+ static Fp = Fp;
1538
+ // scalar field
1539
+ static Fn = Fn;
1540
+ X;
1541
+ Y;
1542
+ Z;
1543
+ T;
1544
+ constructor(X, Y, Z, T) {
1545
+ this.X = acoord("x", X);
1546
+ this.Y = acoord("y", Y);
1547
+ this.Z = acoord("z", Z, true);
1548
+ this.T = acoord("t", T);
1325
1549
  Object.freeze(this);
1326
1550
  }
1327
- get x() {
1328
- return this.toAffine().x;
1329
- }
1330
- get y() {
1331
- return this.toAffine().y;
1551
+ static CURVE() {
1552
+ return CURVE;
1332
1553
  }
1333
1554
  static fromAffine(p) {
1334
1555
  if (p instanceof Point)
1335
1556
  throw new Error("extended point not allowed");
1336
1557
  const { x, y } = p || {};
1337
- aCoordinate("x", x);
1338
- aCoordinate("y", y);
1558
+ acoord("x", x);
1559
+ acoord("y", y);
1339
1560
  return new Point(x, y, _1n4, modP(x * y));
1340
1561
  }
1341
- static normalizeZ(points) {
1342
- const toInv = Fp2.invertBatch(points.map((p) => p.ez));
1343
- return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);
1562
+ // Uses algo from RFC8032 5.1.3.
1563
+ static fromBytes(bytes, zip215 = false) {
1564
+ const len = Fp.BYTES;
1565
+ const { a, d } = CURVE;
1566
+ bytes = copyBytes(abytes(bytes, len, "point"));
1567
+ abool(zip215, "zip215");
1568
+ const normed = copyBytes(bytes);
1569
+ const lastByte = bytes[len - 1];
1570
+ normed[len - 1] = lastByte & ~128;
1571
+ const y = bytesToNumberLE(normed);
1572
+ const max = zip215 ? MASK : Fp.ORDER;
1573
+ aInRange("point.y", y, _0n4, max);
1574
+ const y2 = modP(y * y);
1575
+ const u = modP(y2 - _1n4);
1576
+ const v = modP(d * y2 - a);
1577
+ let { isValid, value: x } = uvRatio2(u, v);
1578
+ if (!isValid)
1579
+ throw new Error("bad point: invalid y coordinate");
1580
+ const isXOdd = (x & _1n4) === _1n4;
1581
+ const isLastByteOdd = (lastByte & 128) !== 0;
1582
+ if (!zip215 && x === _0n4 && isLastByteOdd)
1583
+ throw new Error("bad point: x=0 and x_0=1");
1584
+ if (isLastByteOdd !== isXOdd)
1585
+ x = modP(-x);
1586
+ return Point.fromAffine({ x, y });
1587
+ }
1588
+ static fromHex(hex, zip215 = false) {
1589
+ return Point.fromBytes(hexToBytes(hex), zip215);
1590
+ }
1591
+ get x() {
1592
+ return this.toAffine().x;
1344
1593
  }
1345
- // Multiscalar Multiplication
1346
- static msm(points, scalars) {
1347
- return pippenger(Point, Fn, points, scalars);
1594
+ get y() {
1595
+ return this.toAffine().y;
1348
1596
  }
1349
- // "Private method", don't use it directly
1350
- _setWindowSize(windowSize) {
1351
- wnaf.setWindowSize(this, windowSize);
1597
+ precompute(windowSize = 8, isLazy = true) {
1598
+ wnaf.createCache(this, windowSize);
1599
+ if (!isLazy)
1600
+ this.multiply(_2n2);
1601
+ return this;
1352
1602
  }
1353
- // Not required for fromHex(), which always creates valid points.
1354
- // Could be useful for fromAffine().
1603
+ // Useful in fromAffine() - not for fromBytes(), which always created valid points.
1355
1604
  assertValidity() {
1356
1605
  assertValidMemo(this);
1357
1606
  }
1358
1607
  // Compare one point to another.
1359
1608
  equals(other) {
1360
- assertPoint(other);
1361
- const { ex: X1, ey: Y1, ez: Z1 } = this;
1362
- const { ex: X2, ey: Y2, ez: Z2 } = other;
1609
+ aedpoint(other);
1610
+ const { X: X1, Y: Y1, Z: Z1 } = this;
1611
+ const { X: X2, Y: Y2, Z: Z2 } = other;
1363
1612
  const X1Z2 = modP(X1 * Z2);
1364
1613
  const X2Z1 = modP(X2 * Z1);
1365
1614
  const Y1Z2 = modP(Y1 * Z2);
@@ -1370,80 +1619,60 @@ var NearUtils = (() => {
1370
1619
  return this.equals(Point.ZERO);
1371
1620
  }
1372
1621
  negate() {
1373
- return new Point(modP(-this.ex), this.ey, this.ez, modP(-this.et));
1622
+ return new Point(modP(-this.X), this.Y, this.Z, modP(-this.T));
1374
1623
  }
1375
1624
  // Fast algo for doubling Extended Point.
1376
1625
  // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd
1377
1626
  // Cost: 4M + 4S + 1*a + 6add + 1*2.
1378
1627
  double() {
1379
1628
  const { a } = CURVE;
1380
- const { ex: X1, ey: Y1, ez: Z1 } = this;
1629
+ const { X: X1, Y: Y1, Z: Z1 } = this;
1381
1630
  const A = modP(X1 * X1);
1382
1631
  const B = modP(Y1 * Y1);
1383
- const C = modP(_2n3 * modP(Z1 * Z1));
1632
+ const C = modP(_2n2 * modP(Z1 * Z1));
1384
1633
  const D = modP(a * A);
1385
1634
  const x1y1 = X1 + Y1;
1386
1635
  const E = modP(modP(x1y1 * x1y1) - A - B);
1387
- const G2 = D + B;
1388
- const F = G2 - C;
1636
+ const G = D + B;
1637
+ const F = G - C;
1389
1638
  const H = D - B;
1390
1639
  const X3 = modP(E * F);
1391
- const Y3 = modP(G2 * H);
1640
+ const Y3 = modP(G * H);
1392
1641
  const T3 = modP(E * H);
1393
- const Z3 = modP(F * G2);
1642
+ const Z3 = modP(F * G);
1394
1643
  return new Point(X3, Y3, Z3, T3);
1395
1644
  }
1396
1645
  // Fast algo for adding 2 Extended Points.
1397
1646
  // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd
1398
1647
  // Cost: 9M + 1*a + 1*d + 7add.
1399
1648
  add(other) {
1400
- assertPoint(other);
1649
+ aedpoint(other);
1401
1650
  const { a, d } = CURVE;
1402
- const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this;
1403
- const { ex: X2, ey: Y2, ez: Z2, et: T2 } = other;
1404
- if (a === BigInt(-1)) {
1405
- const A2 = modP((Y1 - X1) * (Y2 + X2));
1406
- const B2 = modP((Y1 + X1) * (Y2 - X2));
1407
- const F2 = modP(B2 - A2);
1408
- if (F2 === _0n4)
1409
- return this.double();
1410
- const C2 = modP(Z1 * _2n3 * T2);
1411
- const D2 = modP(T1 * _2n3 * Z2);
1412
- const E2 = D2 + C2;
1413
- const G3 = B2 + A2;
1414
- const H2 = D2 - C2;
1415
- const X32 = modP(E2 * F2);
1416
- const Y32 = modP(G3 * H2);
1417
- const T32 = modP(E2 * H2);
1418
- const Z32 = modP(F2 * G3);
1419
- return new Point(X32, Y32, Z32, T32);
1420
- }
1651
+ const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;
1652
+ const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;
1421
1653
  const A = modP(X1 * X2);
1422
1654
  const B = modP(Y1 * Y2);
1423
1655
  const C = modP(T1 * d * T2);
1424
1656
  const D = modP(Z1 * Z2);
1425
1657
  const E = modP((X1 + Y1) * (X2 + Y2) - A - B);
1426
1658
  const F = D - C;
1427
- const G2 = D + C;
1659
+ const G = D + C;
1428
1660
  const H = modP(B - a * A);
1429
1661
  const X3 = modP(E * F);
1430
- const Y3 = modP(G2 * H);
1662
+ const Y3 = modP(G * H);
1431
1663
  const T3 = modP(E * H);
1432
- const Z3 = modP(F * G2);
1664
+ const Z3 = modP(F * G);
1433
1665
  return new Point(X3, Y3, Z3, T3);
1434
1666
  }
1435
1667
  subtract(other) {
1436
1668
  return this.add(other.negate());
1437
1669
  }
1438
- wNAF(n) {
1439
- return wnaf.wNAFCached(this, n, Point.normalizeZ);
1440
- }
1441
1670
  // Constant-time multiplication.
1442
1671
  multiply(scalar) {
1443
- const n = scalar;
1444
- aInRange("scalar", n, _1n4, CURVE_ORDER);
1445
- const { p, f } = this.wNAF(n);
1446
- return Point.normalizeZ([p, f])[0];
1672
+ if (!Fn.isValidNot0(scalar))
1673
+ throw new Error("invalid scalar: expected 1 <= sc < curve.n");
1674
+ const { p, f } = wnaf.cached(this, scalar, (p2) => normalizeZ(Point, p2));
1675
+ return normalizeZ(Point, [p, f])[0];
1447
1676
  }
1448
1677
  // Non-constant-time multiplication. Uses double-and-add algorithm.
1449
1678
  // It's faster, but should only be used when you don't care about
@@ -1451,13 +1680,13 @@ var NearUtils = (() => {
1451
1680
  // Does NOT allow scalars higher than CURVE.n.
1452
1681
  // Accepts optional accumulator to merge with multiply (important for sparse scalars)
1453
1682
  multiplyUnsafe(scalar, acc = Point.ZERO) {
1454
- const n = scalar;
1455
- aInRange("scalar", n, _0n4, CURVE_ORDER);
1456
- if (n === _0n4)
1457
- return I;
1458
- if (this.is0() || n === _1n4)
1683
+ if (!Fn.isValid(scalar))
1684
+ throw new Error("invalid scalar: expected 0 <= sc < curve.n");
1685
+ if (scalar === _0n4)
1686
+ return Point.ZERO;
1687
+ if (this.is0() || scalar === _1n4)
1459
1688
  return this;
1460
- return wnaf.wNAFCachedUnsafe(this, n, Point.normalizeZ, acc);
1689
+ return wnaf.unsafe(this, scalar, (p) => normalizeZ(Point, p), acc);
1461
1690
  }
1462
1691
  // Checks if point is of small order.
1463
1692
  // If you add something to small order point, you will have "dirty"
@@ -1469,176 +1698,216 @@ var NearUtils = (() => {
1469
1698
  // Multiplies point by curve order and checks if the result is 0.
1470
1699
  // Returns `false` is the point is dirty.
1471
1700
  isTorsionFree() {
1472
- return wnaf.unsafeLadder(this, CURVE_ORDER).is0();
1701
+ return wnaf.unsafe(this, CURVE.n).is0();
1473
1702
  }
1474
1703
  // Converts Extended point to default (x, y) coordinates.
1475
1704
  // Can accept precomputed Z^-1 - for example, from invertBatch.
1476
- toAffine(iz) {
1477
- return toAffineMemo(this, iz);
1705
+ toAffine(invertedZ) {
1706
+ return toAffineMemo(this, invertedZ);
1478
1707
  }
1479
1708
  clearCofactor() {
1480
- const { h: cofactor2 } = CURVE;
1481
- if (cofactor2 === _1n4)
1709
+ if (cofactor === _1n4)
1482
1710
  return this;
1483
- return this.multiplyUnsafe(cofactor2);
1484
- }
1485
- // Converts hash string or Uint8Array to Point.
1486
- // Uses algo from RFC8032 5.1.3.
1487
- static fromHex(hex, zip215 = false) {
1488
- const { d, a } = CURVE;
1489
- const len = Fp2.BYTES;
1490
- hex = ensureBytes("pointHex", hex, len);
1491
- abool("zip215", zip215);
1492
- const normed = hex.slice();
1493
- const lastByte = hex[len - 1];
1494
- normed[len - 1] = lastByte & ~128;
1495
- const y = bytesToNumberLE(normed);
1496
- const max = zip215 ? MASK : Fp2.ORDER;
1497
- aInRange("pointHex.y", y, _0n4, max);
1498
- const y2 = modP(y * y);
1499
- const u = modP(y2 - _1n4);
1500
- const v = modP(d * y2 - a);
1501
- let { isValid, value: x } = uvRatio2(u, v);
1502
- if (!isValid)
1503
- throw new Error("Point.fromHex: invalid y coordinate");
1504
- const isXOdd = (x & _1n4) === _1n4;
1505
- const isLastByteOdd = (lastByte & 128) !== 0;
1506
- if (!zip215 && x === _0n4 && isLastByteOdd)
1507
- throw new Error("Point.fromHex: x=0 and x_0=1");
1508
- if (isLastByteOdd !== isXOdd)
1509
- x = modP(-x);
1510
- return Point.fromAffine({ x, y });
1711
+ return this.multiplyUnsafe(cofactor);
1511
1712
  }
1512
- static fromPrivateKey(privKey) {
1513
- return getExtendedPublicKey(privKey).point;
1514
- }
1515
- toRawBytes() {
1713
+ toBytes() {
1516
1714
  const { x, y } = this.toAffine();
1517
- const bytes = numberToBytesLE(y, Fp2.BYTES);
1715
+ const bytes = Fp.toBytes(y);
1518
1716
  bytes[bytes.length - 1] |= x & _1n4 ? 128 : 0;
1519
1717
  return bytes;
1520
1718
  }
1521
1719
  toHex() {
1522
- return bytesToHex(this.toRawBytes());
1720
+ return bytesToHex(this.toBytes());
1721
+ }
1722
+ toString() {
1723
+ return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
1523
1724
  }
1524
1725
  }
1525
- Point.BASE = new Point(CURVE.Gx, CURVE.Gy, _1n4, modP(CURVE.Gx * CURVE.Gy));
1526
- Point.ZERO = new Point(_0n4, _1n4, _1n4, _0n4);
1527
- const { BASE: G, ZERO: I } = Point;
1528
- const wnaf = wNAF(Point, nByteLength * 8);
1529
- function modN(a) {
1530
- return mod(a, CURVE_ORDER);
1531
- }
1532
- __name(modN, "modN");
1726
+ const wnaf = new wNAF(Point, Fn.BITS);
1727
+ Point.BASE.precompute(8);
1728
+ return Point;
1729
+ }
1730
+ __name(edwards, "edwards");
1731
+ function eddsa(Point, cHash, eddsaOpts = {}) {
1732
+ if (typeof cHash !== "function")
1733
+ throw new Error('"hash" function param is required');
1734
+ validateObject(eddsaOpts, {}, {
1735
+ adjustScalarBytes: "function",
1736
+ randomBytes: "function",
1737
+ domain: "function",
1738
+ prehash: "function",
1739
+ mapToCurve: "function"
1740
+ });
1741
+ const { prehash } = eddsaOpts;
1742
+ const { BASE, Fp, Fn } = Point;
1743
+ const randomBytes2 = eddsaOpts.randomBytes || randomBytes;
1744
+ const adjustScalarBytes2 = eddsaOpts.adjustScalarBytes || ((bytes) => bytes);
1745
+ const domain = eddsaOpts.domain || ((data, ctx, phflag) => {
1746
+ abool(phflag, "phflag");
1747
+ if (ctx.length || phflag)
1748
+ throw new Error("Contexts/pre-hash are not supported");
1749
+ return data;
1750
+ });
1533
1751
  function modN_LE(hash) {
1534
- return modN(bytesToNumberLE(hash));
1752
+ return Fn.create(bytesToNumberLE(hash));
1535
1753
  }
1536
1754
  __name(modN_LE, "modN_LE");
1537
- function getExtendedPublicKey(key) {
1538
- const len = Fp2.BYTES;
1539
- key = ensureBytes("private key", key, len);
1540
- const hashed = ensureBytes("hashed private key", cHash(key), 2 * len);
1755
+ function getPrivateScalar(key) {
1756
+ const len = lengths.secretKey;
1757
+ abytes(key, lengths.secretKey, "secretKey");
1758
+ const hashed = abytes(cHash(key), 2 * len, "hashedSecretKey");
1541
1759
  const head = adjustScalarBytes2(hashed.slice(0, len));
1542
1760
  const prefix = hashed.slice(len, 2 * len);
1543
1761
  const scalar = modN_LE(head);
1544
- const point = G.multiply(scalar);
1545
- const pointBytes = point.toRawBytes();
1762
+ return { head, prefix, scalar };
1763
+ }
1764
+ __name(getPrivateScalar, "getPrivateScalar");
1765
+ function getExtendedPublicKey(secretKey) {
1766
+ const { head, prefix, scalar } = getPrivateScalar(secretKey);
1767
+ const point = BASE.multiply(scalar);
1768
+ const pointBytes = point.toBytes();
1546
1769
  return { head, prefix, scalar, point, pointBytes };
1547
1770
  }
1548
1771
  __name(getExtendedPublicKey, "getExtendedPublicKey");
1549
- function getPublicKey(privKey) {
1550
- return getExtendedPublicKey(privKey).pointBytes;
1772
+ function getPublicKey(secretKey) {
1773
+ return getExtendedPublicKey(secretKey).pointBytes;
1551
1774
  }
1552
1775
  __name(getPublicKey, "getPublicKey");
1553
- function hashDomainToScalar(context = new Uint8Array(), ...msgs) {
1776
+ function hashDomainToScalar(context = Uint8Array.of(), ...msgs) {
1554
1777
  const msg = concatBytes(...msgs);
1555
- return modN_LE(cHash(domain(msg, ensureBytes("context", context), !!prehash)));
1778
+ return modN_LE(cHash(domain(msg, abytes(context, void 0, "context"), !!prehash)));
1556
1779
  }
1557
1780
  __name(hashDomainToScalar, "hashDomainToScalar");
1558
- function sign(msg, privKey, options = {}) {
1559
- msg = ensureBytes("message", msg);
1781
+ function sign(msg, secretKey, options = {}) {
1782
+ msg = abytes(msg, void 0, "message");
1560
1783
  if (prehash)
1561
1784
  msg = prehash(msg);
1562
- const { prefix, scalar, pointBytes } = getExtendedPublicKey(privKey);
1785
+ const { prefix, scalar, pointBytes } = getExtendedPublicKey(secretKey);
1563
1786
  const r = hashDomainToScalar(options.context, prefix, msg);
1564
- const R = G.multiply(r).toRawBytes();
1787
+ const R = BASE.multiply(r).toBytes();
1565
1788
  const k = hashDomainToScalar(options.context, R, pointBytes, msg);
1566
- const s = modN(r + k * scalar);
1567
- aInRange("signature.s", s, _0n4, CURVE_ORDER);
1568
- const res = concatBytes(R, numberToBytesLE(s, Fp2.BYTES));
1569
- return ensureBytes("result", res, Fp2.BYTES * 2);
1789
+ const s = Fn.create(r + k * scalar);
1790
+ if (!Fn.isValid(s))
1791
+ throw new Error("sign failed: invalid s");
1792
+ const rs = concatBytes(R, Fn.toBytes(s));
1793
+ return abytes(rs, lengths.signature, "result");
1570
1794
  }
1571
1795
  __name(sign, "sign");
1572
- const verifyOpts = VERIFY_DEFAULT;
1796
+ const verifyOpts = { zip215: true };
1573
1797
  function verify(sig, msg, publicKey, options = verifyOpts) {
1574
1798
  const { context, zip215 } = options;
1575
- const len = Fp2.BYTES;
1576
- sig = ensureBytes("signature", sig, 2 * len);
1577
- msg = ensureBytes("message", msg);
1578
- publicKey = ensureBytes("publicKey", publicKey, len);
1799
+ const len = lengths.signature;
1800
+ sig = abytes(sig, len, "signature");
1801
+ msg = abytes(msg, void 0, "message");
1802
+ publicKey = abytes(publicKey, lengths.publicKey, "publicKey");
1579
1803
  if (zip215 !== void 0)
1580
- abool("zip215", zip215);
1804
+ abool(zip215, "zip215");
1581
1805
  if (prehash)
1582
1806
  msg = prehash(msg);
1583
- const s = bytesToNumberLE(sig.slice(len, 2 * len));
1807
+ const mid = len / 2;
1808
+ const r = sig.subarray(0, mid);
1809
+ const s = bytesToNumberLE(sig.subarray(mid, len));
1584
1810
  let A, R, SB;
1585
1811
  try {
1586
- A = Point.fromHex(publicKey, zip215);
1587
- R = Point.fromHex(sig.slice(0, len), zip215);
1588
- SB = G.multiplyUnsafe(s);
1812
+ A = Point.fromBytes(publicKey, zip215);
1813
+ R = Point.fromBytes(r, zip215);
1814
+ SB = BASE.multiplyUnsafe(s);
1589
1815
  } catch (error) {
1590
1816
  return false;
1591
1817
  }
1592
1818
  if (!zip215 && A.isSmallOrder())
1593
1819
  return false;
1594
- const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg);
1820
+ const k = hashDomainToScalar(context, R.toBytes(), A.toBytes(), msg);
1595
1821
  const RkA = R.add(A.multiplyUnsafe(k));
1596
- return RkA.subtract(SB).clearCofactor().equals(Point.ZERO);
1822
+ return RkA.subtract(SB).clearCofactor().is0();
1597
1823
  }
1598
1824
  __name(verify, "verify");
1599
- G._setWindowSize(8);
1825
+ const _size = Fp.BYTES;
1826
+ const lengths = {
1827
+ secretKey: _size,
1828
+ publicKey: _size,
1829
+ signature: 2 * _size,
1830
+ seed: _size
1831
+ };
1832
+ function randomSecretKey(seed = randomBytes2(lengths.seed)) {
1833
+ return abytes(seed, lengths.seed, "seed");
1834
+ }
1835
+ __name(randomSecretKey, "randomSecretKey");
1836
+ function isValidSecretKey(key) {
1837
+ return isBytes(key) && key.length === Fn.BYTES;
1838
+ }
1839
+ __name(isValidSecretKey, "isValidSecretKey");
1840
+ function isValidPublicKey(key, zip215) {
1841
+ try {
1842
+ return !!Point.fromBytes(key, zip215);
1843
+ } catch (error) {
1844
+ return false;
1845
+ }
1846
+ }
1847
+ __name(isValidPublicKey, "isValidPublicKey");
1600
1848
  const utils = {
1601
1849
  getExtendedPublicKey,
1602
- // ed25519 private keys are uniform 32b. No need to check for modulo bias, like in secp256k1.
1603
- randomPrivateKey: /* @__PURE__ */ __name(() => randomBytes2(Fp2.BYTES), "randomPrivateKey"),
1850
+ randomSecretKey,
1851
+ isValidSecretKey,
1852
+ isValidPublicKey,
1604
1853
  /**
1605
- * We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT
1606
- * values. This slows down first getPublicKey() by milliseconds (see Speed section),
1607
- * but allows to speed-up subsequent getPublicKey() calls up to 20x.
1608
- * @param windowSize 2, 4, 8, 16
1854
+ * Converts ed public key to x public key. Uses formula:
1855
+ * - ed25519:
1856
+ * - `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`
1857
+ * - `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`
1858
+ * - ed448:
1859
+ * - `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)`
1860
+ * - `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))`
1609
1861
  */
1610
- precompute(windowSize = 8, point = Point.BASE) {
1611
- point._setWindowSize(windowSize);
1612
- point.multiply(BigInt(3));
1613
- return point;
1862
+ toMontgomery(publicKey) {
1863
+ const { y } = Point.fromBytes(publicKey);
1864
+ const size = lengths.publicKey;
1865
+ const is25519 = size === 32;
1866
+ if (!is25519 && size !== 57)
1867
+ throw new Error("only defined for 25519 and 448");
1868
+ const u = is25519 ? Fp.div(_1n4 + y, _1n4 - y) : Fp.div(y - _1n4, y + _1n4);
1869
+ return Fp.toBytes(u);
1870
+ },
1871
+ toMontgomerySecret(secretKey) {
1872
+ const size = lengths.secretKey;
1873
+ abytes(secretKey, size);
1874
+ const hashed = cHash(secretKey.subarray(0, size));
1875
+ return adjustScalarBytes2(hashed).subarray(0, size);
1614
1876
  }
1615
1877
  };
1616
- return {
1617
- CURVE,
1878
+ return Object.freeze({
1879
+ keygen: createKeygen(randomSecretKey, getPublicKey),
1618
1880
  getPublicKey,
1619
1881
  sign,
1620
1882
  verify,
1621
- ExtendedPoint: Point,
1622
- utils
1623
- };
1883
+ utils,
1884
+ Point,
1885
+ lengths
1886
+ });
1624
1887
  }
1625
- __name(twistedEdwards, "twistedEdwards");
1888
+ __name(eddsa, "eddsa");
1626
1889
 
1627
- // ../../node_modules/@noble/curves/esm/ed25519.js
1628
- var ED25519_P = BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949");
1629
- var ED25519_SQRT_M1 = /* @__PURE__ */ BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");
1630
- var _0n5 = BigInt(0);
1890
+ // node_modules/@noble/curves/ed25519.js
1631
1891
  var _1n5 = BigInt(1);
1632
- var _2n4 = BigInt(2);
1633
- var _3n2 = BigInt(3);
1892
+ var _2n3 = BigInt(2);
1634
1893
  var _5n2 = BigInt(5);
1635
1894
  var _8n3 = BigInt(8);
1895
+ var ed25519_CURVE_p = BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed");
1896
+ var ed25519_CURVE = /* @__PURE__ */ (() => ({
1897
+ p: ed25519_CURVE_p,
1898
+ n: BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),
1899
+ h: _8n3,
1900
+ a: BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),
1901
+ d: BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),
1902
+ Gx: BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),
1903
+ Gy: BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")
1904
+ }))();
1636
1905
  function ed25519_pow_2_252_3(x) {
1637
1906
  const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);
1638
- const P2 = ED25519_P;
1907
+ const P2 = ed25519_CURVE_p;
1639
1908
  const x2 = x * x % P2;
1640
1909
  const b2 = x2 * x % P2;
1641
- const b4 = pow2(b2, _2n4, P2) * b2 % P2;
1910
+ const b4 = pow2(b2, _2n3, P2) * b2 % P2;
1642
1911
  const b5 = pow2(b4, _1n5, P2) * x % P2;
1643
1912
  const b10 = pow2(b5, _5n2, P2) * b5 % P2;
1644
1913
  const b20 = pow2(b10, _10n, P2) * b10 % P2;
@@ -1647,7 +1916,7 @@ var NearUtils = (() => {
1647
1916
  const b160 = pow2(b80, _80n, P2) * b80 % P2;
1648
1917
  const b240 = pow2(b160, _80n, P2) * b80 % P2;
1649
1918
  const b250 = pow2(b240, _10n, P2) * b10 % P2;
1650
- const pow_p_5_8 = pow2(b250, _2n4, P2) * x % P2;
1919
+ const pow_p_5_8 = pow2(b250, _2n3, P2) * x % P2;
1651
1920
  return { pow_p_5_8, b2 };
1652
1921
  }
1653
1922
  __name(ed25519_pow_2_252_3, "ed25519_pow_2_252_3");
@@ -1658,12 +1927,13 @@ var NearUtils = (() => {
1658
1927
  return bytes;
1659
1928
  }
1660
1929
  __name(adjustScalarBytes, "adjustScalarBytes");
1930
+ var ED25519_SQRT_M1 = /* @__PURE__ */ BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");
1661
1931
  function uvRatio(u, v) {
1662
- const P2 = ED25519_P;
1932
+ const P2 = ed25519_CURVE_p;
1663
1933
  const v3 = mod(v * v * v, P2);
1664
1934
  const v7 = mod(v3 * v3 * v, P2);
1665
- const pow3 = ed25519_pow_2_252_3(u * v7).pow_p_5_8;
1666
- let x = mod(u * v3 * pow3, P2);
1935
+ const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;
1936
+ let x = mod(u * v3 * pow, P2);
1667
1937
  const vx2 = mod(v * x * x, P2);
1668
1938
  const root1 = x;
1669
1939
  const root2 = mod(x * ED25519_SQRT_M1, P2);
@@ -1679,186 +1949,12 @@ var NearUtils = (() => {
1679
1949
  return { isValid: useRoot1 || useRoot2, value: x };
1680
1950
  }
1681
1951
  __name(uvRatio, "uvRatio");
1682
- var Fp = /* @__PURE__ */ (() => Field(ED25519_P, void 0, true))();
1683
- var ed25519Defaults = /* @__PURE__ */ (() => ({
1684
- // Param: a
1685
- a: BigInt(-1),
1686
- // Fp.create(-1) is proper; our way still works and is faster
1687
- // d is equal to -121665/121666 over finite field.
1688
- // Negative number is P - number, and division is invert(number, P)
1689
- d: BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),
1690
- // Finite field 𝔽p over which we'll do calculations; 2n**255n - 19n
1691
- Fp,
1692
- // Subgroup order: how many points curve has
1693
- // 2n**252n + 27742317777372353535851937790883648493n;
1694
- n: BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),
1695
- // Cofactor
1696
- h: _8n3,
1697
- // Base point (x, y) aka generator point
1698
- Gx: BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),
1699
- Gy: BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),
1700
- hash: sha512,
1701
- randomBytes,
1702
- adjustScalarBytes,
1703
- // dom2
1704
- // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3.
1705
- // Constant-time, u/√v
1706
- uvRatio
1707
- }))();
1708
- var ed25519 = /* @__PURE__ */ (() => twistedEdwards(ed25519Defaults))();
1709
-
1710
- // ../../node_modules/@noble/hashes/esm/sha256.js
1711
- var SHA256_K = /* @__PURE__ */ new Uint32Array([
1712
- 1116352408,
1713
- 1899447441,
1714
- 3049323471,
1715
- 3921009573,
1716
- 961987163,
1717
- 1508970993,
1718
- 2453635748,
1719
- 2870763221,
1720
- 3624381080,
1721
- 310598401,
1722
- 607225278,
1723
- 1426881987,
1724
- 1925078388,
1725
- 2162078206,
1726
- 2614888103,
1727
- 3248222580,
1728
- 3835390401,
1729
- 4022224774,
1730
- 264347078,
1731
- 604807628,
1732
- 770255983,
1733
- 1249150122,
1734
- 1555081692,
1735
- 1996064986,
1736
- 2554220882,
1737
- 2821834349,
1738
- 2952996808,
1739
- 3210313671,
1740
- 3336571891,
1741
- 3584528711,
1742
- 113926993,
1743
- 338241895,
1744
- 666307205,
1745
- 773529912,
1746
- 1294757372,
1747
- 1396182291,
1748
- 1695183700,
1749
- 1986661051,
1750
- 2177026350,
1751
- 2456956037,
1752
- 2730485921,
1753
- 2820302411,
1754
- 3259730800,
1755
- 3345764771,
1756
- 3516065817,
1757
- 3600352804,
1758
- 4094571909,
1759
- 275423344,
1760
- 430227734,
1761
- 506948616,
1762
- 659060556,
1763
- 883997877,
1764
- 958139571,
1765
- 1322822218,
1766
- 1537002063,
1767
- 1747873779,
1768
- 1955562222,
1769
- 2024104815,
1770
- 2227730452,
1771
- 2361852424,
1772
- 2428436474,
1773
- 2756734187,
1774
- 3204031479,
1775
- 3329325298
1776
- ]);
1777
- var SHA256_IV = /* @__PURE__ */ new Uint32Array([
1778
- 1779033703,
1779
- 3144134277,
1780
- 1013904242,
1781
- 2773480762,
1782
- 1359893119,
1783
- 2600822924,
1784
- 528734635,
1785
- 1541459225
1786
- ]);
1787
- var SHA256_W = /* @__PURE__ */ new Uint32Array(64);
1788
- var SHA256 = class extends HashMD {
1789
- static {
1790
- __name(this, "SHA256");
1791
- }
1792
- constructor() {
1793
- super(64, 32, 8, false);
1794
- this.A = SHA256_IV[0] | 0;
1795
- this.B = SHA256_IV[1] | 0;
1796
- this.C = SHA256_IV[2] | 0;
1797
- this.D = SHA256_IV[3] | 0;
1798
- this.E = SHA256_IV[4] | 0;
1799
- this.F = SHA256_IV[5] | 0;
1800
- this.G = SHA256_IV[6] | 0;
1801
- this.H = SHA256_IV[7] | 0;
1802
- }
1803
- get() {
1804
- const { A, B, C, D, E, F, G, H } = this;
1805
- return [A, B, C, D, E, F, G, H];
1806
- }
1807
- // prettier-ignore
1808
- set(A, B, C, D, E, F, G, H) {
1809
- this.A = A | 0;
1810
- this.B = B | 0;
1811
- this.C = C | 0;
1812
- this.D = D | 0;
1813
- this.E = E | 0;
1814
- this.F = F | 0;
1815
- this.G = G | 0;
1816
- this.H = H | 0;
1817
- }
1818
- process(view, offset) {
1819
- for (let i = 0; i < 16; i++, offset += 4)
1820
- SHA256_W[i] = view.getUint32(offset, false);
1821
- for (let i = 16; i < 64; i++) {
1822
- const W15 = SHA256_W[i - 15];
1823
- const W2 = SHA256_W[i - 2];
1824
- const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
1825
- const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
1826
- SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
1827
- }
1828
- let { A, B, C, D, E, F, G, H } = this;
1829
- for (let i = 0; i < 64; i++) {
1830
- const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
1831
- const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
1832
- const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
1833
- const T2 = sigma0 + Maj(A, B, C) | 0;
1834
- H = G;
1835
- G = F;
1836
- F = E;
1837
- E = D + T1 | 0;
1838
- D = C;
1839
- C = B;
1840
- B = A;
1841
- A = T1 + T2 | 0;
1842
- }
1843
- A = A + this.A | 0;
1844
- B = B + this.B | 0;
1845
- C = C + this.C | 0;
1846
- D = D + this.D | 0;
1847
- E = E + this.E | 0;
1848
- F = F + this.F | 0;
1849
- G = G + this.G | 0;
1850
- H = H + this.H | 0;
1851
- this.set(A, B, C, D, E, F, G, H);
1852
- }
1853
- roundClean() {
1854
- SHA256_W.fill(0);
1855
- }
1856
- destroy() {
1857
- this.set(0, 0, 0, 0, 0, 0, 0, 0);
1858
- this.buffer.fill(0);
1859
- }
1860
- };
1861
- var sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256());
1952
+ var ed25519_Point = /* @__PURE__ */ edwards(ed25519_CURVE, { uvRatio });
1953
+ function ed(opts) {
1954
+ return eddsa(ed25519_Point, sha512, Object.assign({ adjustScalarBytes }, opts));
1955
+ }
1956
+ __name(ed, "ed");
1957
+ var ed25519 = /* @__PURE__ */ ed({});
1862
1958
 
1863
1959
  // node_modules/base58-js/base58_chars.js
1864
1960
  var base58_chars = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
@@ -3546,22 +3642,22 @@ var NearUtils = (() => {
3546
3642
  })();
3547
3643
  /*! Bundled license information:
3548
3644
 
3549
- @noble/hashes/esm/utils.js:
3645
+ @noble/hashes/utils.js:
3550
3646
  (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
3551
3647
 
3552
- @noble/curves/esm/abstract/utils.js:
3648
+ @noble/curves/utils.js:
3553
3649
  (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
3554
3650
 
3555
- @noble/curves/esm/abstract/modular.js:
3651
+ @noble/curves/abstract/modular.js:
3556
3652
  (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
3557
3653
 
3558
- @noble/curves/esm/abstract/curve.js:
3654
+ @noble/curves/abstract/curve.js:
3559
3655
  (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
3560
3656
 
3561
- @noble/curves/esm/abstract/edwards.js:
3657
+ @noble/curves/abstract/edwards.js:
3562
3658
  (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
3563
3659
 
3564
- @noble/curves/esm/ed25519.js:
3660
+ @noble/curves/ed25519.js:
3565
3661
  (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
3566
3662
  */
3567
3663