@waku/message-encryption 0.0.24-4c5a8a9.0 → 0.0.24-7eb3375.0

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.
Files changed (46) hide show
  1. package/bundle/crypto.js +1 -0
  2. package/bundle/ecies-137fdfde.js +124 -0
  3. package/bundle/ecies.js +3 -1
  4. package/bundle/{index-62691783.js → encryption-d94ff773.js} +12872 -17157
  5. package/bundle/index-268375db.js +17 -0
  6. package/bundle/index.js +5 -1
  7. package/bundle/symmetric-58d457ca.js +2836 -0
  8. package/bundle/symmetric-d25c7b7a.js +124 -0
  9. package/bundle/symmetric.js +3 -1
  10. package/dist/.tsbuildinfo +1 -1
  11. package/dist/crypto/ecies.js +1 -1
  12. package/dist/crypto/index.d.ts +3 -29
  13. package/dist/crypto/index.js +3 -59
  14. package/dist/crypto/index.js.map +1 -1
  15. package/dist/crypto/symmetric.js +2 -2
  16. package/dist/crypto/symmetric.js.map +1 -1
  17. package/dist/crypto/utils.d.ts +29 -0
  18. package/dist/crypto/utils.js +60 -0
  19. package/dist/crypto/utils.js.map +1 -0
  20. package/dist/ecies.d.ts +8 -9
  21. package/dist/ecies.js +7 -6
  22. package/dist/ecies.js.map +1 -1
  23. package/dist/{waku_payload.d.ts → encryption.d.ts} +5 -1
  24. package/dist/{waku_payload.js → encryption.js} +3 -5
  25. package/dist/encryption.js.map +1 -0
  26. package/dist/index.d.ts +1 -6
  27. package/dist/index.js +1 -2
  28. package/dist/index.js.map +1 -1
  29. package/dist/{constants.d.ts → misc.d.ts} +2 -0
  30. package/dist/{constants.js → misc.js} +3 -1
  31. package/dist/misc.js.map +1 -0
  32. package/dist/symmetric.d.ts +8 -8
  33. package/dist/symmetric.js +7 -6
  34. package/dist/symmetric.js.map +1 -1
  35. package/package.json +1 -1
  36. package/src/crypto/ecies.ts +1 -1
  37. package/src/crypto/index.ts +3 -76
  38. package/src/crypto/symmetric.ts +2 -2
  39. package/src/crypto/utils.ts +76 -0
  40. package/src/ecies.ts +18 -17
  41. package/src/{waku_payload.ts → encryption.ts} +13 -6
  42. package/src/index.ts +1 -9
  43. package/src/{constants.ts → misc.ts} +4 -0
  44. package/src/symmetric.ts +16 -11
  45. package/dist/constants.js.map +0 -1
  46. package/dist/waku_payload.js.map +0 -1
@@ -0,0 +1,2836 @@
1
+ var nodeCrypto = {};
2
+
3
+ var _nodeResolve_empty = /*#__PURE__*/Object.freeze({
4
+ __proto__: null,
5
+ default: nodeCrypto
6
+ });
7
+
8
+ /*! noble-secp256k1 - MIT License (c) 2019 Paul Miller (paulmillr.com) */
9
+ const _0n = BigInt(0);
10
+ const _1n = BigInt(1);
11
+ const _2n = BigInt(2);
12
+ const _3n = BigInt(3);
13
+ const _8n = BigInt(8);
14
+ const CURVE = Object.freeze({
15
+ a: _0n,
16
+ b: BigInt(7),
17
+ P: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'),
18
+ n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'),
19
+ h: _1n,
20
+ Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),
21
+ Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),
22
+ beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),
23
+ });
24
+ const divNearest = (a, b) => (a + b / _2n) / b;
25
+ const endo = {
26
+ beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),
27
+ splitScalar(k) {
28
+ const { n } = CURVE;
29
+ const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15');
30
+ const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3');
31
+ const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8');
32
+ const b2 = a1;
33
+ const POW_2_128 = BigInt('0x100000000000000000000000000000000');
34
+ const c1 = divNearest(b2 * k, n);
35
+ const c2 = divNearest(-b1 * k, n);
36
+ let k1 = mod(k - c1 * a1 - c2 * a2, n);
37
+ let k2 = mod(-c1 * b1 - c2 * b2, n);
38
+ const k1neg = k1 > POW_2_128;
39
+ const k2neg = k2 > POW_2_128;
40
+ if (k1neg)
41
+ k1 = n - k1;
42
+ if (k2neg)
43
+ k2 = n - k2;
44
+ if (k1 > POW_2_128 || k2 > POW_2_128) {
45
+ throw new Error('splitScalarEndo: Endomorphism failed, k=' + k);
46
+ }
47
+ return { k1neg, k1, k2neg, k2 };
48
+ },
49
+ };
50
+ const fieldLen = 32;
51
+ const groupLen = 32;
52
+ const hashLen = 32;
53
+ const compressedLen = fieldLen + 1;
54
+ const uncompressedLen = 2 * fieldLen + 1;
55
+ function weierstrass(x) {
56
+ const { a, b } = CURVE;
57
+ const x2 = mod(x * x);
58
+ const x3 = mod(x2 * x);
59
+ return mod(x3 + a * x + b);
60
+ }
61
+ const USE_ENDOMORPHISM = CURVE.a === _0n;
62
+ class ShaError extends Error {
63
+ constructor(message) {
64
+ super(message);
65
+ }
66
+ }
67
+ function assertJacPoint(other) {
68
+ if (!(other instanceof JacobianPoint))
69
+ throw new TypeError('JacobianPoint expected');
70
+ }
71
+ class JacobianPoint {
72
+ constructor(x, y, z) {
73
+ this.x = x;
74
+ this.y = y;
75
+ this.z = z;
76
+ }
77
+ static fromAffine(p) {
78
+ if (!(p instanceof Point)) {
79
+ throw new TypeError('JacobianPoint#fromAffine: expected Point');
80
+ }
81
+ if (p.equals(Point.ZERO))
82
+ return JacobianPoint.ZERO;
83
+ return new JacobianPoint(p.x, p.y, _1n);
84
+ }
85
+ static toAffineBatch(points) {
86
+ const toInv = invertBatch(points.map((p) => p.z));
87
+ return points.map((p, i) => p.toAffine(toInv[i]));
88
+ }
89
+ static normalizeZ(points) {
90
+ return JacobianPoint.toAffineBatch(points).map(JacobianPoint.fromAffine);
91
+ }
92
+ equals(other) {
93
+ assertJacPoint(other);
94
+ const { x: X1, y: Y1, z: Z1 } = this;
95
+ const { x: X2, y: Y2, z: Z2 } = other;
96
+ const Z1Z1 = mod(Z1 * Z1);
97
+ const Z2Z2 = mod(Z2 * Z2);
98
+ const U1 = mod(X1 * Z2Z2);
99
+ const U2 = mod(X2 * Z1Z1);
100
+ const S1 = mod(mod(Y1 * Z2) * Z2Z2);
101
+ const S2 = mod(mod(Y2 * Z1) * Z1Z1);
102
+ return U1 === U2 && S1 === S2;
103
+ }
104
+ negate() {
105
+ return new JacobianPoint(this.x, mod(-this.y), this.z);
106
+ }
107
+ double() {
108
+ const { x: X1, y: Y1, z: Z1 } = this;
109
+ const A = mod(X1 * X1);
110
+ const B = mod(Y1 * Y1);
111
+ const C = mod(B * B);
112
+ const x1b = X1 + B;
113
+ const D = mod(_2n * (mod(x1b * x1b) - A - C));
114
+ const E = mod(_3n * A);
115
+ const F = mod(E * E);
116
+ const X3 = mod(F - _2n * D);
117
+ const Y3 = mod(E * (D - X3) - _8n * C);
118
+ const Z3 = mod(_2n * Y1 * Z1);
119
+ return new JacobianPoint(X3, Y3, Z3);
120
+ }
121
+ add(other) {
122
+ assertJacPoint(other);
123
+ const { x: X1, y: Y1, z: Z1 } = this;
124
+ const { x: X2, y: Y2, z: Z2 } = other;
125
+ if (X2 === _0n || Y2 === _0n)
126
+ return this;
127
+ if (X1 === _0n || Y1 === _0n)
128
+ return other;
129
+ const Z1Z1 = mod(Z1 * Z1);
130
+ const Z2Z2 = mod(Z2 * Z2);
131
+ const U1 = mod(X1 * Z2Z2);
132
+ const U2 = mod(X2 * Z1Z1);
133
+ const S1 = mod(mod(Y1 * Z2) * Z2Z2);
134
+ const S2 = mod(mod(Y2 * Z1) * Z1Z1);
135
+ const H = mod(U2 - U1);
136
+ const r = mod(S2 - S1);
137
+ if (H === _0n) {
138
+ if (r === _0n) {
139
+ return this.double();
140
+ }
141
+ else {
142
+ return JacobianPoint.ZERO;
143
+ }
144
+ }
145
+ const HH = mod(H * H);
146
+ const HHH = mod(H * HH);
147
+ const V = mod(U1 * HH);
148
+ const X3 = mod(r * r - HHH - _2n * V);
149
+ const Y3 = mod(r * (V - X3) - S1 * HHH);
150
+ const Z3 = mod(Z1 * Z2 * H);
151
+ return new JacobianPoint(X3, Y3, Z3);
152
+ }
153
+ subtract(other) {
154
+ return this.add(other.negate());
155
+ }
156
+ multiplyUnsafe(scalar) {
157
+ const P0 = JacobianPoint.ZERO;
158
+ if (typeof scalar === 'bigint' && scalar === _0n)
159
+ return P0;
160
+ let n = normalizeScalar(scalar);
161
+ if (n === _1n)
162
+ return this;
163
+ if (!USE_ENDOMORPHISM) {
164
+ let p = P0;
165
+ let d = this;
166
+ while (n > _0n) {
167
+ if (n & _1n)
168
+ p = p.add(d);
169
+ d = d.double();
170
+ n >>= _1n;
171
+ }
172
+ return p;
173
+ }
174
+ let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);
175
+ let k1p = P0;
176
+ let k2p = P0;
177
+ let d = this;
178
+ while (k1 > _0n || k2 > _0n) {
179
+ if (k1 & _1n)
180
+ k1p = k1p.add(d);
181
+ if (k2 & _1n)
182
+ k2p = k2p.add(d);
183
+ d = d.double();
184
+ k1 >>= _1n;
185
+ k2 >>= _1n;
186
+ }
187
+ if (k1neg)
188
+ k1p = k1p.negate();
189
+ if (k2neg)
190
+ k2p = k2p.negate();
191
+ k2p = new JacobianPoint(mod(k2p.x * endo.beta), k2p.y, k2p.z);
192
+ return k1p.add(k2p);
193
+ }
194
+ precomputeWindow(W) {
195
+ const windows = USE_ENDOMORPHISM ? 128 / W + 1 : 256 / W + 1;
196
+ const points = [];
197
+ let p = this;
198
+ let base = p;
199
+ for (let window = 0; window < windows; window++) {
200
+ base = p;
201
+ points.push(base);
202
+ for (let i = 1; i < 2 ** (W - 1); i++) {
203
+ base = base.add(p);
204
+ points.push(base);
205
+ }
206
+ p = base.double();
207
+ }
208
+ return points;
209
+ }
210
+ wNAF(n, affinePoint) {
211
+ if (!affinePoint && this.equals(JacobianPoint.BASE))
212
+ affinePoint = Point.BASE;
213
+ const W = (affinePoint && affinePoint._WINDOW_SIZE) || 1;
214
+ if (256 % W) {
215
+ throw new Error('Point#wNAF: Invalid precomputation window, must be power of 2');
216
+ }
217
+ let precomputes = affinePoint && pointPrecomputes.get(affinePoint);
218
+ if (!precomputes) {
219
+ precomputes = this.precomputeWindow(W);
220
+ if (affinePoint && W !== 1) {
221
+ precomputes = JacobianPoint.normalizeZ(precomputes);
222
+ pointPrecomputes.set(affinePoint, precomputes);
223
+ }
224
+ }
225
+ let p = JacobianPoint.ZERO;
226
+ let f = JacobianPoint.BASE;
227
+ const windows = 1 + (USE_ENDOMORPHISM ? 128 / W : 256 / W);
228
+ const windowSize = 2 ** (W - 1);
229
+ const mask = BigInt(2 ** W - 1);
230
+ const maxNumber = 2 ** W;
231
+ const shiftBy = BigInt(W);
232
+ for (let window = 0; window < windows; window++) {
233
+ const offset = window * windowSize;
234
+ let wbits = Number(n & mask);
235
+ n >>= shiftBy;
236
+ if (wbits > windowSize) {
237
+ wbits -= maxNumber;
238
+ n += _1n;
239
+ }
240
+ const offset1 = offset;
241
+ const offset2 = offset + Math.abs(wbits) - 1;
242
+ const cond1 = window % 2 !== 0;
243
+ const cond2 = wbits < 0;
244
+ if (wbits === 0) {
245
+ f = f.add(constTimeNegate(cond1, precomputes[offset1]));
246
+ }
247
+ else {
248
+ p = p.add(constTimeNegate(cond2, precomputes[offset2]));
249
+ }
250
+ }
251
+ return { p, f };
252
+ }
253
+ multiply(scalar, affinePoint) {
254
+ let n = normalizeScalar(scalar);
255
+ let point;
256
+ let fake;
257
+ if (USE_ENDOMORPHISM) {
258
+ const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);
259
+ let { p: k1p, f: f1p } = this.wNAF(k1, affinePoint);
260
+ let { p: k2p, f: f2p } = this.wNAF(k2, affinePoint);
261
+ k1p = constTimeNegate(k1neg, k1p);
262
+ k2p = constTimeNegate(k2neg, k2p);
263
+ k2p = new JacobianPoint(mod(k2p.x * endo.beta), k2p.y, k2p.z);
264
+ point = k1p.add(k2p);
265
+ fake = f1p.add(f2p);
266
+ }
267
+ else {
268
+ const { p, f } = this.wNAF(n, affinePoint);
269
+ point = p;
270
+ fake = f;
271
+ }
272
+ return JacobianPoint.normalizeZ([point, fake])[0];
273
+ }
274
+ toAffine(invZ) {
275
+ const { x, y, z } = this;
276
+ const is0 = this.equals(JacobianPoint.ZERO);
277
+ if (invZ == null)
278
+ invZ = is0 ? _8n : invert(z);
279
+ const iz1 = invZ;
280
+ const iz2 = mod(iz1 * iz1);
281
+ const iz3 = mod(iz2 * iz1);
282
+ const ax = mod(x * iz2);
283
+ const ay = mod(y * iz3);
284
+ const zz = mod(z * iz1);
285
+ if (is0)
286
+ return Point.ZERO;
287
+ if (zz !== _1n)
288
+ throw new Error('invZ was invalid');
289
+ return new Point(ax, ay);
290
+ }
291
+ }
292
+ JacobianPoint.BASE = new JacobianPoint(CURVE.Gx, CURVE.Gy, _1n);
293
+ JacobianPoint.ZERO = new JacobianPoint(_0n, _1n, _0n);
294
+ function constTimeNegate(condition, item) {
295
+ const neg = item.negate();
296
+ return condition ? neg : item;
297
+ }
298
+ const pointPrecomputes = new WeakMap();
299
+ class Point {
300
+ constructor(x, y) {
301
+ this.x = x;
302
+ this.y = y;
303
+ }
304
+ _setWindowSize(windowSize) {
305
+ this._WINDOW_SIZE = windowSize;
306
+ pointPrecomputes.delete(this);
307
+ }
308
+ hasEvenY() {
309
+ return this.y % _2n === _0n;
310
+ }
311
+ static fromCompressedHex(bytes) {
312
+ const isShort = bytes.length === 32;
313
+ const x = bytesToNumber(isShort ? bytes : bytes.subarray(1));
314
+ if (!isValidFieldElement(x))
315
+ throw new Error('Point is not on curve');
316
+ const y2 = weierstrass(x);
317
+ let y = sqrtMod(y2);
318
+ const isYOdd = (y & _1n) === _1n;
319
+ if (isShort) {
320
+ if (isYOdd)
321
+ y = mod(-y);
322
+ }
323
+ else {
324
+ const isFirstByteOdd = (bytes[0] & 1) === 1;
325
+ if (isFirstByteOdd !== isYOdd)
326
+ y = mod(-y);
327
+ }
328
+ const point = new Point(x, y);
329
+ point.assertValidity();
330
+ return point;
331
+ }
332
+ static fromUncompressedHex(bytes) {
333
+ const x = bytesToNumber(bytes.subarray(1, fieldLen + 1));
334
+ const y = bytesToNumber(bytes.subarray(fieldLen + 1, fieldLen * 2 + 1));
335
+ const point = new Point(x, y);
336
+ point.assertValidity();
337
+ return point;
338
+ }
339
+ static fromHex(hex) {
340
+ const bytes = ensureBytes(hex);
341
+ const len = bytes.length;
342
+ const header = bytes[0];
343
+ if (len === fieldLen)
344
+ return this.fromCompressedHex(bytes);
345
+ if (len === compressedLen && (header === 0x02 || header === 0x03)) {
346
+ return this.fromCompressedHex(bytes);
347
+ }
348
+ if (len === uncompressedLen && header === 0x04)
349
+ return this.fromUncompressedHex(bytes);
350
+ throw new Error(`Point.fromHex: received invalid point. Expected 32-${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes, not ${len}`);
351
+ }
352
+ static fromPrivateKey(privateKey) {
353
+ return Point.BASE.multiply(normalizePrivateKey(privateKey));
354
+ }
355
+ static fromSignature(msgHash, signature, recovery) {
356
+ const { r, s } = normalizeSignature(signature);
357
+ if (![0, 1, 2, 3].includes(recovery))
358
+ throw new Error('Cannot recover: invalid recovery bit');
359
+ const h = truncateHash(ensureBytes(msgHash));
360
+ const { n } = CURVE;
361
+ const radj = recovery === 2 || recovery === 3 ? r + n : r;
362
+ const rinv = invert(radj, n);
363
+ const u1 = mod(-h * rinv, n);
364
+ const u2 = mod(s * rinv, n);
365
+ const prefix = recovery & 1 ? '03' : '02';
366
+ const R = Point.fromHex(prefix + numTo32bStr(radj));
367
+ const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2);
368
+ if (!Q)
369
+ throw new Error('Cannot recover signature: point at infinify');
370
+ Q.assertValidity();
371
+ return Q;
372
+ }
373
+ toRawBytes(isCompressed = false) {
374
+ return hexToBytes$1(this.toHex(isCompressed));
375
+ }
376
+ toHex(isCompressed = false) {
377
+ const x = numTo32bStr(this.x);
378
+ if (isCompressed) {
379
+ const prefix = this.hasEvenY() ? '02' : '03';
380
+ return `${prefix}${x}`;
381
+ }
382
+ else {
383
+ return `04${x}${numTo32bStr(this.y)}`;
384
+ }
385
+ }
386
+ toHexX() {
387
+ return this.toHex(true).slice(2);
388
+ }
389
+ toRawX() {
390
+ return this.toRawBytes(true).slice(1);
391
+ }
392
+ assertValidity() {
393
+ const msg = 'Point is not on elliptic curve';
394
+ const { x, y } = this;
395
+ if (!isValidFieldElement(x) || !isValidFieldElement(y))
396
+ throw new Error(msg);
397
+ const left = mod(y * y);
398
+ const right = weierstrass(x);
399
+ if (mod(left - right) !== _0n)
400
+ throw new Error(msg);
401
+ }
402
+ equals(other) {
403
+ return this.x === other.x && this.y === other.y;
404
+ }
405
+ negate() {
406
+ return new Point(this.x, mod(-this.y));
407
+ }
408
+ double() {
409
+ return JacobianPoint.fromAffine(this).double().toAffine();
410
+ }
411
+ add(other) {
412
+ return JacobianPoint.fromAffine(this).add(JacobianPoint.fromAffine(other)).toAffine();
413
+ }
414
+ subtract(other) {
415
+ return this.add(other.negate());
416
+ }
417
+ multiply(scalar) {
418
+ return JacobianPoint.fromAffine(this).multiply(scalar, this).toAffine();
419
+ }
420
+ multiplyAndAddUnsafe(Q, a, b) {
421
+ const P = JacobianPoint.fromAffine(this);
422
+ const aP = a === _0n || a === _1n || this !== Point.BASE ? P.multiplyUnsafe(a) : P.multiply(a);
423
+ const bQ = JacobianPoint.fromAffine(Q).multiplyUnsafe(b);
424
+ const sum = aP.add(bQ);
425
+ return sum.equals(JacobianPoint.ZERO) ? undefined : sum.toAffine();
426
+ }
427
+ }
428
+ Point.BASE = new Point(CURVE.Gx, CURVE.Gy);
429
+ Point.ZERO = new Point(_0n, _0n);
430
+ function sliceDER(s) {
431
+ return Number.parseInt(s[0], 16) >= 8 ? '00' + s : s;
432
+ }
433
+ function parseDERInt(data) {
434
+ if (data.length < 2 || data[0] !== 0x02) {
435
+ throw new Error(`Invalid signature integer tag: ${bytesToHex(data)}`);
436
+ }
437
+ const len = data[1];
438
+ const res = data.subarray(2, len + 2);
439
+ if (!len || res.length !== len) {
440
+ throw new Error(`Invalid signature integer: wrong length`);
441
+ }
442
+ if (res[0] === 0x00 && res[1] <= 0x7f) {
443
+ throw new Error('Invalid signature integer: trailing length');
444
+ }
445
+ return { data: bytesToNumber(res), left: data.subarray(len + 2) };
446
+ }
447
+ function parseDERSignature(data) {
448
+ if (data.length < 2 || data[0] != 0x30) {
449
+ throw new Error(`Invalid signature tag: ${bytesToHex(data)}`);
450
+ }
451
+ if (data[1] !== data.length - 2) {
452
+ throw new Error('Invalid signature: incorrect length');
453
+ }
454
+ const { data: r, left: sBytes } = parseDERInt(data.subarray(2));
455
+ const { data: s, left: rBytesLeft } = parseDERInt(sBytes);
456
+ if (rBytesLeft.length) {
457
+ throw new Error(`Invalid signature: left bytes after parsing: ${bytesToHex(rBytesLeft)}`);
458
+ }
459
+ return { r, s };
460
+ }
461
+ class Signature {
462
+ constructor(r, s) {
463
+ this.r = r;
464
+ this.s = s;
465
+ this.assertValidity();
466
+ }
467
+ static fromCompact(hex) {
468
+ const arr = hex instanceof Uint8Array;
469
+ const name = 'Signature.fromCompact';
470
+ if (typeof hex !== 'string' && !arr)
471
+ throw new TypeError(`${name}: Expected string or Uint8Array`);
472
+ const str = arr ? bytesToHex(hex) : hex;
473
+ if (str.length !== 128)
474
+ throw new Error(`${name}: Expected 64-byte hex`);
475
+ return new Signature(hexToNumber(str.slice(0, 64)), hexToNumber(str.slice(64, 128)));
476
+ }
477
+ static fromDER(hex) {
478
+ const arr = hex instanceof Uint8Array;
479
+ if (typeof hex !== 'string' && !arr)
480
+ throw new TypeError(`Signature.fromDER: Expected string or Uint8Array`);
481
+ const { r, s } = parseDERSignature(arr ? hex : hexToBytes$1(hex));
482
+ return new Signature(r, s);
483
+ }
484
+ static fromHex(hex) {
485
+ return this.fromDER(hex);
486
+ }
487
+ assertValidity() {
488
+ const { r, s } = this;
489
+ if (!isWithinCurveOrder(r))
490
+ throw new Error('Invalid Signature: r must be 0 < r < n');
491
+ if (!isWithinCurveOrder(s))
492
+ throw new Error('Invalid Signature: s must be 0 < s < n');
493
+ }
494
+ hasHighS() {
495
+ const HALF = CURVE.n >> _1n;
496
+ return this.s > HALF;
497
+ }
498
+ normalizeS() {
499
+ return this.hasHighS() ? new Signature(this.r, mod(-this.s, CURVE.n)) : this;
500
+ }
501
+ toDERRawBytes() {
502
+ return hexToBytes$1(this.toDERHex());
503
+ }
504
+ toDERHex() {
505
+ const sHex = sliceDER(numberToHexUnpadded(this.s));
506
+ const rHex = sliceDER(numberToHexUnpadded(this.r));
507
+ const sHexL = sHex.length / 2;
508
+ const rHexL = rHex.length / 2;
509
+ const sLen = numberToHexUnpadded(sHexL);
510
+ const rLen = numberToHexUnpadded(rHexL);
511
+ const length = numberToHexUnpadded(rHexL + sHexL + 4);
512
+ return `30${length}02${rLen}${rHex}02${sLen}${sHex}`;
513
+ }
514
+ toRawBytes() {
515
+ return this.toDERRawBytes();
516
+ }
517
+ toHex() {
518
+ return this.toDERHex();
519
+ }
520
+ toCompactRawBytes() {
521
+ return hexToBytes$1(this.toCompactHex());
522
+ }
523
+ toCompactHex() {
524
+ return numTo32bStr(this.r) + numTo32bStr(this.s);
525
+ }
526
+ }
527
+ function concatBytes(...arrays) {
528
+ if (!arrays.every((b) => b instanceof Uint8Array))
529
+ throw new Error('Uint8Array list expected');
530
+ if (arrays.length === 1)
531
+ return arrays[0];
532
+ const length = arrays.reduce((a, arr) => a + arr.length, 0);
533
+ const result = new Uint8Array(length);
534
+ for (let i = 0, pad = 0; i < arrays.length; i++) {
535
+ const arr = arrays[i];
536
+ result.set(arr, pad);
537
+ pad += arr.length;
538
+ }
539
+ return result;
540
+ }
541
+ const hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0'));
542
+ function bytesToHex(uint8a) {
543
+ if (!(uint8a instanceof Uint8Array))
544
+ throw new Error('Expected Uint8Array');
545
+ let hex = '';
546
+ for (let i = 0; i < uint8a.length; i++) {
547
+ hex += hexes[uint8a[i]];
548
+ }
549
+ return hex;
550
+ }
551
+ const POW_2_256 = BigInt('0x10000000000000000000000000000000000000000000000000000000000000000');
552
+ function numTo32bStr(num) {
553
+ if (typeof num !== 'bigint')
554
+ throw new Error('Expected bigint');
555
+ if (!(_0n <= num && num < POW_2_256))
556
+ throw new Error('Expected number 0 <= n < 2^256');
557
+ return num.toString(16).padStart(64, '0');
558
+ }
559
+ function numTo32b(num) {
560
+ const b = hexToBytes$1(numTo32bStr(num));
561
+ if (b.length !== 32)
562
+ throw new Error('Error: expected 32 bytes');
563
+ return b;
564
+ }
565
+ function numberToHexUnpadded(num) {
566
+ const hex = num.toString(16);
567
+ return hex.length & 1 ? `0${hex}` : hex;
568
+ }
569
+ function hexToNumber(hex) {
570
+ if (typeof hex !== 'string') {
571
+ throw new TypeError('hexToNumber: expected string, got ' + typeof hex);
572
+ }
573
+ return BigInt(`0x${hex}`);
574
+ }
575
+ function hexToBytes$1(hex) {
576
+ if (typeof hex !== 'string') {
577
+ throw new TypeError('hexToBytes: expected string, got ' + typeof hex);
578
+ }
579
+ if (hex.length % 2)
580
+ throw new Error('hexToBytes: received invalid unpadded hex' + hex.length);
581
+ const array = new Uint8Array(hex.length / 2);
582
+ for (let i = 0; i < array.length; i++) {
583
+ const j = i * 2;
584
+ const hexByte = hex.slice(j, j + 2);
585
+ const byte = Number.parseInt(hexByte, 16);
586
+ if (Number.isNaN(byte) || byte < 0)
587
+ throw new Error('Invalid byte sequence');
588
+ array[i] = byte;
589
+ }
590
+ return array;
591
+ }
592
+ function bytesToNumber(bytes) {
593
+ return hexToNumber(bytesToHex(bytes));
594
+ }
595
+ function ensureBytes(hex) {
596
+ return hex instanceof Uint8Array ? Uint8Array.from(hex) : hexToBytes$1(hex);
597
+ }
598
+ function normalizeScalar(num) {
599
+ if (typeof num === 'number' && Number.isSafeInteger(num) && num > 0)
600
+ return BigInt(num);
601
+ if (typeof num === 'bigint' && isWithinCurveOrder(num))
602
+ return num;
603
+ throw new TypeError('Expected valid private scalar: 0 < scalar < curve.n');
604
+ }
605
+ function mod(a, b = CURVE.P) {
606
+ const result = a % b;
607
+ return result >= _0n ? result : b + result;
608
+ }
609
+ function pow2(x, power) {
610
+ const { P } = CURVE;
611
+ let res = x;
612
+ while (power-- > _0n) {
613
+ res *= res;
614
+ res %= P;
615
+ }
616
+ return res;
617
+ }
618
+ function sqrtMod(x) {
619
+ const { P } = CURVE;
620
+ const _6n = BigInt(6);
621
+ const _11n = BigInt(11);
622
+ const _22n = BigInt(22);
623
+ const _23n = BigInt(23);
624
+ const _44n = BigInt(44);
625
+ const _88n = BigInt(88);
626
+ const b2 = (x * x * x) % P;
627
+ const b3 = (b2 * b2 * x) % P;
628
+ const b6 = (pow2(b3, _3n) * b3) % P;
629
+ const b9 = (pow2(b6, _3n) * b3) % P;
630
+ const b11 = (pow2(b9, _2n) * b2) % P;
631
+ const b22 = (pow2(b11, _11n) * b11) % P;
632
+ const b44 = (pow2(b22, _22n) * b22) % P;
633
+ const b88 = (pow2(b44, _44n) * b44) % P;
634
+ const b176 = (pow2(b88, _88n) * b88) % P;
635
+ const b220 = (pow2(b176, _44n) * b44) % P;
636
+ const b223 = (pow2(b220, _3n) * b3) % P;
637
+ const t1 = (pow2(b223, _23n) * b22) % P;
638
+ const t2 = (pow2(t1, _6n) * b2) % P;
639
+ const rt = pow2(t2, _2n);
640
+ const xc = (rt * rt) % P;
641
+ if (xc !== x)
642
+ throw new Error('Cannot find square root');
643
+ return rt;
644
+ }
645
+ function invert(number, modulo = CURVE.P) {
646
+ if (number === _0n || modulo <= _0n) {
647
+ throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);
648
+ }
649
+ let a = mod(number, modulo);
650
+ let b = modulo;
651
+ let x = _0n, u = _1n;
652
+ while (a !== _0n) {
653
+ const q = b / a;
654
+ const r = b % a;
655
+ const m = x - u * q;
656
+ b = a, a = r, x = u, u = m;
657
+ }
658
+ const gcd = b;
659
+ if (gcd !== _1n)
660
+ throw new Error('invert: does not exist');
661
+ return mod(x, modulo);
662
+ }
663
+ function invertBatch(nums, p = CURVE.P) {
664
+ const scratch = new Array(nums.length);
665
+ const lastMultiplied = nums.reduce((acc, num, i) => {
666
+ if (num === _0n)
667
+ return acc;
668
+ scratch[i] = acc;
669
+ return mod(acc * num, p);
670
+ }, _1n);
671
+ const inverted = invert(lastMultiplied, p);
672
+ nums.reduceRight((acc, num, i) => {
673
+ if (num === _0n)
674
+ return acc;
675
+ scratch[i] = mod(acc * scratch[i], p);
676
+ return mod(acc * num, p);
677
+ }, inverted);
678
+ return scratch;
679
+ }
680
+ function bits2int_2(bytes) {
681
+ const delta = bytes.length * 8 - groupLen * 8;
682
+ const num = bytesToNumber(bytes);
683
+ return delta > 0 ? num >> BigInt(delta) : num;
684
+ }
685
+ function truncateHash(hash, truncateOnly = false) {
686
+ const h = bits2int_2(hash);
687
+ if (truncateOnly)
688
+ return h;
689
+ const { n } = CURVE;
690
+ return h >= n ? h - n : h;
691
+ }
692
+ let _sha256Sync;
693
+ let _hmacSha256Sync;
694
+ class HmacDrbg {
695
+ constructor(hashLen, qByteLen) {
696
+ this.hashLen = hashLen;
697
+ this.qByteLen = qByteLen;
698
+ if (typeof hashLen !== 'number' || hashLen < 2)
699
+ throw new Error('hashLen must be a number');
700
+ if (typeof qByteLen !== 'number' || qByteLen < 2)
701
+ throw new Error('qByteLen must be a number');
702
+ this.v = new Uint8Array(hashLen).fill(1);
703
+ this.k = new Uint8Array(hashLen).fill(0);
704
+ this.counter = 0;
705
+ }
706
+ hmac(...values) {
707
+ return utils.hmacSha256(this.k, ...values);
708
+ }
709
+ hmacSync(...values) {
710
+ return _hmacSha256Sync(this.k, ...values);
711
+ }
712
+ checkSync() {
713
+ if (typeof _hmacSha256Sync !== 'function')
714
+ throw new ShaError('hmacSha256Sync needs to be set');
715
+ }
716
+ incr() {
717
+ if (this.counter >= 1000)
718
+ throw new Error('Tried 1,000 k values for sign(), all were invalid');
719
+ this.counter += 1;
720
+ }
721
+ async reseed(seed = new Uint8Array()) {
722
+ this.k = await this.hmac(this.v, Uint8Array.from([0x00]), seed);
723
+ this.v = await this.hmac(this.v);
724
+ if (seed.length === 0)
725
+ return;
726
+ this.k = await this.hmac(this.v, Uint8Array.from([0x01]), seed);
727
+ this.v = await this.hmac(this.v);
728
+ }
729
+ reseedSync(seed = new Uint8Array()) {
730
+ this.checkSync();
731
+ this.k = this.hmacSync(this.v, Uint8Array.from([0x00]), seed);
732
+ this.v = this.hmacSync(this.v);
733
+ if (seed.length === 0)
734
+ return;
735
+ this.k = this.hmacSync(this.v, Uint8Array.from([0x01]), seed);
736
+ this.v = this.hmacSync(this.v);
737
+ }
738
+ async generate() {
739
+ this.incr();
740
+ let len = 0;
741
+ const out = [];
742
+ while (len < this.qByteLen) {
743
+ this.v = await this.hmac(this.v);
744
+ const sl = this.v.slice();
745
+ out.push(sl);
746
+ len += this.v.length;
747
+ }
748
+ return concatBytes(...out);
749
+ }
750
+ generateSync() {
751
+ this.checkSync();
752
+ this.incr();
753
+ let len = 0;
754
+ const out = [];
755
+ while (len < this.qByteLen) {
756
+ this.v = this.hmacSync(this.v);
757
+ const sl = this.v.slice();
758
+ out.push(sl);
759
+ len += this.v.length;
760
+ }
761
+ return concatBytes(...out);
762
+ }
763
+ }
764
+ function isWithinCurveOrder(num) {
765
+ return _0n < num && num < CURVE.n;
766
+ }
767
+ function isValidFieldElement(num) {
768
+ return _0n < num && num < CURVE.P;
769
+ }
770
+ function kmdToSig(kBytes, m, d, lowS = true) {
771
+ const { n } = CURVE;
772
+ const k = truncateHash(kBytes, true);
773
+ if (!isWithinCurveOrder(k))
774
+ return;
775
+ const kinv = invert(k, n);
776
+ const q = Point.BASE.multiply(k);
777
+ const r = mod(q.x, n);
778
+ if (r === _0n)
779
+ return;
780
+ const s = mod(kinv * mod(m + d * r, n), n);
781
+ if (s === _0n)
782
+ return;
783
+ let sig = new Signature(r, s);
784
+ let recovery = (q.x === sig.r ? 0 : 2) | Number(q.y & _1n);
785
+ if (lowS && sig.hasHighS()) {
786
+ sig = sig.normalizeS();
787
+ recovery ^= 1;
788
+ }
789
+ return { sig, recovery };
790
+ }
791
+ function normalizePrivateKey(key) {
792
+ let num;
793
+ if (typeof key === 'bigint') {
794
+ num = key;
795
+ }
796
+ else if (typeof key === 'number' && Number.isSafeInteger(key) && key > 0) {
797
+ num = BigInt(key);
798
+ }
799
+ else if (typeof key === 'string') {
800
+ if (key.length !== 2 * groupLen)
801
+ throw new Error('Expected 32 bytes of private key');
802
+ num = hexToNumber(key);
803
+ }
804
+ else if (key instanceof Uint8Array) {
805
+ if (key.length !== groupLen)
806
+ throw new Error('Expected 32 bytes of private key');
807
+ num = bytesToNumber(key);
808
+ }
809
+ else {
810
+ throw new TypeError('Expected valid private key');
811
+ }
812
+ if (!isWithinCurveOrder(num))
813
+ throw new Error('Expected private key: 0 < key < n');
814
+ return num;
815
+ }
816
+ function normalizePublicKey(publicKey) {
817
+ if (publicKey instanceof Point) {
818
+ publicKey.assertValidity();
819
+ return publicKey;
820
+ }
821
+ else {
822
+ return Point.fromHex(publicKey);
823
+ }
824
+ }
825
+ function normalizeSignature(signature) {
826
+ if (signature instanceof Signature) {
827
+ signature.assertValidity();
828
+ return signature;
829
+ }
830
+ try {
831
+ return Signature.fromDER(signature);
832
+ }
833
+ catch (error) {
834
+ return Signature.fromCompact(signature);
835
+ }
836
+ }
837
+ function getPublicKey$1(privateKey, isCompressed = false) {
838
+ return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);
839
+ }
840
+ function recoverPublicKey(msgHash, signature, recovery, isCompressed = false) {
841
+ return Point.fromSignature(msgHash, signature, recovery).toRawBytes(isCompressed);
842
+ }
843
+ function isProbPub(item) {
844
+ const arr = item instanceof Uint8Array;
845
+ const str = typeof item === 'string';
846
+ const len = (arr || str) && item.length;
847
+ if (arr)
848
+ return len === compressedLen || len === uncompressedLen;
849
+ if (str)
850
+ return len === compressedLen * 2 || len === uncompressedLen * 2;
851
+ if (item instanceof Point)
852
+ return true;
853
+ return false;
854
+ }
855
+ function getSharedSecret(privateA, publicB, isCompressed = false) {
856
+ if (isProbPub(privateA))
857
+ throw new TypeError('getSharedSecret: first arg must be private key');
858
+ if (!isProbPub(publicB))
859
+ throw new TypeError('getSharedSecret: second arg must be public key');
860
+ const b = normalizePublicKey(publicB);
861
+ b.assertValidity();
862
+ return b.multiply(normalizePrivateKey(privateA)).toRawBytes(isCompressed);
863
+ }
864
+ function bits2int(bytes) {
865
+ const slice = bytes.length > fieldLen ? bytes.slice(0, fieldLen) : bytes;
866
+ return bytesToNumber(slice);
867
+ }
868
+ function bits2octets(bytes) {
869
+ const z1 = bits2int(bytes);
870
+ const z2 = mod(z1, CURVE.n);
871
+ return int2octets(z2 < _0n ? z1 : z2);
872
+ }
873
+ function int2octets(num) {
874
+ return numTo32b(num);
875
+ }
876
+ function initSigArgs(msgHash, privateKey, extraEntropy) {
877
+ if (msgHash == null)
878
+ throw new Error(`sign: expected valid message hash, not "${msgHash}"`);
879
+ const h1 = ensureBytes(msgHash);
880
+ const d = normalizePrivateKey(privateKey);
881
+ const seedArgs = [int2octets(d), bits2octets(h1)];
882
+ if (extraEntropy != null) {
883
+ if (extraEntropy === true)
884
+ extraEntropy = utils.randomBytes(fieldLen);
885
+ const e = ensureBytes(extraEntropy);
886
+ if (e.length !== fieldLen)
887
+ throw new Error(`sign: Expected ${fieldLen} bytes of extra data`);
888
+ seedArgs.push(e);
889
+ }
890
+ const seed = concatBytes(...seedArgs);
891
+ const m = bits2int(h1);
892
+ return { seed, m, d };
893
+ }
894
+ function finalizeSig(recSig, opts) {
895
+ const { sig, recovery } = recSig;
896
+ const { der, recovered } = Object.assign({ canonical: true, der: true }, opts);
897
+ const hashed = der ? sig.toDERRawBytes() : sig.toCompactRawBytes();
898
+ return recovered ? [hashed, recovery] : hashed;
899
+ }
900
+ async function sign$1(msgHash, privKey, opts = {}) {
901
+ const { seed, m, d } = initSigArgs(msgHash, privKey, opts.extraEntropy);
902
+ const drbg = new HmacDrbg(hashLen, groupLen);
903
+ await drbg.reseed(seed);
904
+ let sig;
905
+ while (!(sig = kmdToSig(await drbg.generate(), m, d, opts.canonical)))
906
+ await drbg.reseed();
907
+ return finalizeSig(sig, opts);
908
+ }
909
+ Point.BASE._setWindowSize(8);
910
+ const crypto$1 = {
911
+ node: _nodeResolve_empty,
912
+ web: typeof self === 'object' && 'crypto' in self ? self.crypto : undefined,
913
+ };
914
+ const TAGGED_HASH_PREFIXES = {};
915
+ const utils = {
916
+ bytesToHex,
917
+ hexToBytes: hexToBytes$1,
918
+ concatBytes,
919
+ mod,
920
+ invert,
921
+ isValidPrivateKey(privateKey) {
922
+ try {
923
+ normalizePrivateKey(privateKey);
924
+ return true;
925
+ }
926
+ catch (error) {
927
+ return false;
928
+ }
929
+ },
930
+ _bigintTo32Bytes: numTo32b,
931
+ _normalizePrivateKey: normalizePrivateKey,
932
+ hashToPrivateKey: (hash) => {
933
+ hash = ensureBytes(hash);
934
+ const minLen = groupLen + 8;
935
+ if (hash.length < minLen || hash.length > 1024) {
936
+ throw new Error(`Expected valid bytes of private key as per FIPS 186`);
937
+ }
938
+ const num = mod(bytesToNumber(hash), CURVE.n - _1n) + _1n;
939
+ return numTo32b(num);
940
+ },
941
+ randomBytes: (bytesLength = 32) => {
942
+ if (crypto$1.web) {
943
+ return crypto$1.web.getRandomValues(new Uint8Array(bytesLength));
944
+ }
945
+ else if (crypto$1.node) {
946
+ const { randomBytes } = crypto$1.node;
947
+ return Uint8Array.from(randomBytes(bytesLength));
948
+ }
949
+ else {
950
+ throw new Error("The environment doesn't have randomBytes function");
951
+ }
952
+ },
953
+ randomPrivateKey: () => utils.hashToPrivateKey(utils.randomBytes(groupLen + 8)),
954
+ precompute(windowSize = 8, point = Point.BASE) {
955
+ const cached = point === Point.BASE ? point : new Point(point.x, point.y);
956
+ cached._setWindowSize(windowSize);
957
+ cached.multiply(_3n);
958
+ return cached;
959
+ },
960
+ sha256: async (...messages) => {
961
+ if (crypto$1.web) {
962
+ const buffer = await crypto$1.web.subtle.digest('SHA-256', concatBytes(...messages));
963
+ return new Uint8Array(buffer);
964
+ }
965
+ else if (crypto$1.node) {
966
+ const { createHash } = crypto$1.node;
967
+ const hash = createHash('sha256');
968
+ messages.forEach((m) => hash.update(m));
969
+ return Uint8Array.from(hash.digest());
970
+ }
971
+ else {
972
+ throw new Error("The environment doesn't have sha256 function");
973
+ }
974
+ },
975
+ hmacSha256: async (key, ...messages) => {
976
+ if (crypto$1.web) {
977
+ const ckey = await crypto$1.web.subtle.importKey('raw', key, { name: 'HMAC', hash: { name: 'SHA-256' } }, false, ['sign']);
978
+ const message = concatBytes(...messages);
979
+ const buffer = await crypto$1.web.subtle.sign('HMAC', ckey, message);
980
+ return new Uint8Array(buffer);
981
+ }
982
+ else if (crypto$1.node) {
983
+ const { createHmac } = crypto$1.node;
984
+ const hash = createHmac('sha256', key);
985
+ messages.forEach((m) => hash.update(m));
986
+ return Uint8Array.from(hash.digest());
987
+ }
988
+ else {
989
+ throw new Error("The environment doesn't have hmac-sha256 function");
990
+ }
991
+ },
992
+ sha256Sync: undefined,
993
+ hmacSha256Sync: undefined,
994
+ taggedHash: async (tag, ...messages) => {
995
+ let tagP = TAGGED_HASH_PREFIXES[tag];
996
+ if (tagP === undefined) {
997
+ const tagH = await utils.sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0)));
998
+ tagP = concatBytes(tagH, tagH);
999
+ TAGGED_HASH_PREFIXES[tag] = tagP;
1000
+ }
1001
+ return utils.sha256(tagP, ...messages);
1002
+ },
1003
+ taggedHashSync: (tag, ...messages) => {
1004
+ if (typeof _sha256Sync !== 'function')
1005
+ throw new ShaError('sha256Sync is undefined, you need to set it');
1006
+ let tagP = TAGGED_HASH_PREFIXES[tag];
1007
+ if (tagP === undefined) {
1008
+ const tagH = _sha256Sync(Uint8Array.from(tag, (c) => c.charCodeAt(0)));
1009
+ tagP = concatBytes(tagH, tagH);
1010
+ TAGGED_HASH_PREFIXES[tag] = tagP;
1011
+ }
1012
+ return _sha256Sync(tagP, ...messages);
1013
+ },
1014
+ _JacobianPoint: JacobianPoint,
1015
+ };
1016
+ Object.defineProperties(utils, {
1017
+ sha256Sync: {
1018
+ configurable: false,
1019
+ get() {
1020
+ return _sha256Sync;
1021
+ },
1022
+ set(val) {
1023
+ if (!_sha256Sync)
1024
+ _sha256Sync = val;
1025
+ },
1026
+ },
1027
+ hmacSha256Sync: {
1028
+ configurable: false,
1029
+ get() {
1030
+ return _hmacSha256Sync;
1031
+ },
1032
+ set(val) {
1033
+ if (!_hmacSha256Sync)
1034
+ _hmacSha256Sync = val;
1035
+ },
1036
+ },
1037
+ });
1038
+
1039
+ /**
1040
+ * To guarantee Uint8Array semantics, convert nodejs Buffers
1041
+ * into vanilla Uint8Arrays
1042
+ */
1043
+ function asUint8Array(buf) {
1044
+ if (globalThis.Buffer != null) {
1045
+ return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
1046
+ }
1047
+ return buf;
1048
+ }
1049
+
1050
+ // base-x encoding / decoding
1051
+ // Copyright (c) 2018 base-x contributors
1052
+ // Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)
1053
+ // Distributed under the MIT software license, see the accompanying
1054
+ // file LICENSE or http://www.opensource.org/licenses/mit-license.php.
1055
+ function base (ALPHABET, name) {
1056
+ if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }
1057
+ var BASE_MAP = new Uint8Array(256);
1058
+ for (var j = 0; j < BASE_MAP.length; j++) {
1059
+ BASE_MAP[j] = 255;
1060
+ }
1061
+ for (var i = 0; i < ALPHABET.length; i++) {
1062
+ var x = ALPHABET.charAt(i);
1063
+ var xc = x.charCodeAt(0);
1064
+ if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }
1065
+ BASE_MAP[xc] = i;
1066
+ }
1067
+ var BASE = ALPHABET.length;
1068
+ var LEADER = ALPHABET.charAt(0);
1069
+ var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up
1070
+ var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up
1071
+ function encode (source) {
1072
+ if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {
1073
+ source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
1074
+ } else if (Array.isArray(source)) {
1075
+ source = Uint8Array.from(source);
1076
+ }
1077
+ if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }
1078
+ if (source.length === 0) { return '' }
1079
+ // Skip & count leading zeroes.
1080
+ var zeroes = 0;
1081
+ var length = 0;
1082
+ var pbegin = 0;
1083
+ var pend = source.length;
1084
+ while (pbegin !== pend && source[pbegin] === 0) {
1085
+ pbegin++;
1086
+ zeroes++;
1087
+ }
1088
+ // Allocate enough space in big-endian base58 representation.
1089
+ var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;
1090
+ var b58 = new Uint8Array(size);
1091
+ // Process the bytes.
1092
+ while (pbegin !== pend) {
1093
+ var carry = source[pbegin];
1094
+ // Apply "b58 = b58 * 256 + ch".
1095
+ var i = 0;
1096
+ for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {
1097
+ carry += (256 * b58[it1]) >>> 0;
1098
+ b58[it1] = (carry % BASE) >>> 0;
1099
+ carry = (carry / BASE) >>> 0;
1100
+ }
1101
+ if (carry !== 0) { throw new Error('Non-zero carry') }
1102
+ length = i;
1103
+ pbegin++;
1104
+ }
1105
+ // Skip leading zeroes in base58 result.
1106
+ var it2 = size - length;
1107
+ while (it2 !== size && b58[it2] === 0) {
1108
+ it2++;
1109
+ }
1110
+ // Translate the result into a string.
1111
+ var str = LEADER.repeat(zeroes);
1112
+ for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); }
1113
+ return str
1114
+ }
1115
+ function decodeUnsafe (source) {
1116
+ if (typeof source !== 'string') { throw new TypeError('Expected String') }
1117
+ if (source.length === 0) { return new Uint8Array() }
1118
+ var psz = 0;
1119
+ // Skip leading spaces.
1120
+ if (source[psz] === ' ') { return }
1121
+ // Skip and count leading '1's.
1122
+ var zeroes = 0;
1123
+ var length = 0;
1124
+ while (source[psz] === LEADER) {
1125
+ zeroes++;
1126
+ psz++;
1127
+ }
1128
+ // Allocate enough space in big-endian base256 representation.
1129
+ var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.
1130
+ var b256 = new Uint8Array(size);
1131
+ // Process the characters.
1132
+ while (source[psz]) {
1133
+ // Decode character
1134
+ var carry = BASE_MAP[source.charCodeAt(psz)];
1135
+ // Invalid character
1136
+ if (carry === 255) { return }
1137
+ var i = 0;
1138
+ for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {
1139
+ carry += (BASE * b256[it3]) >>> 0;
1140
+ b256[it3] = (carry % 256) >>> 0;
1141
+ carry = (carry / 256) >>> 0;
1142
+ }
1143
+ if (carry !== 0) { throw new Error('Non-zero carry') }
1144
+ length = i;
1145
+ psz++;
1146
+ }
1147
+ // Skip trailing spaces.
1148
+ if (source[psz] === ' ') { return }
1149
+ // Skip leading zeroes in b256.
1150
+ var it4 = size - length;
1151
+ while (it4 !== size && b256[it4] === 0) {
1152
+ it4++;
1153
+ }
1154
+ var vch = new Uint8Array(zeroes + (size - it4));
1155
+ var j = zeroes;
1156
+ while (it4 !== size) {
1157
+ vch[j++] = b256[it4++];
1158
+ }
1159
+ return vch
1160
+ }
1161
+ function decode (string) {
1162
+ var buffer = decodeUnsafe(string);
1163
+ if (buffer) { return buffer }
1164
+ throw new Error(`Non-${name} character`)
1165
+ }
1166
+ return {
1167
+ encode: encode,
1168
+ decodeUnsafe: decodeUnsafe,
1169
+ decode: decode
1170
+ }
1171
+ }
1172
+ var src = base;
1173
+
1174
+ var _brrp__multiformats_scope_baseX = src;
1175
+
1176
+ /**
1177
+ * @param {ArrayBufferView|ArrayBuffer|Uint8Array} o
1178
+ * @returns {Uint8Array}
1179
+ */
1180
+ const coerce = o => {
1181
+ if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') return o
1182
+ if (o instanceof ArrayBuffer) return new Uint8Array(o)
1183
+ if (ArrayBuffer.isView(o)) {
1184
+ return new Uint8Array(o.buffer, o.byteOffset, o.byteLength)
1185
+ }
1186
+ throw new Error('Unknown type, must be binary type')
1187
+ };
1188
+
1189
+ /**
1190
+ * @param {string} str
1191
+ * @returns {Uint8Array}
1192
+ */
1193
+ const fromString$1 = str => (new TextEncoder()).encode(str);
1194
+
1195
+ /**
1196
+ * @param {Uint8Array} b
1197
+ * @returns {string}
1198
+ */
1199
+ const toString = b => (new TextDecoder()).decode(b);
1200
+
1201
+ /**
1202
+ * Class represents both BaseEncoder and MultibaseEncoder meaning it
1203
+ * can be used to encode to multibase or base encode without multibase
1204
+ * prefix.
1205
+ *
1206
+ * @class
1207
+ * @template {string} Base
1208
+ * @template {string} Prefix
1209
+ * @implements {API.MultibaseEncoder<Prefix>}
1210
+ * @implements {API.BaseEncoder}
1211
+ */
1212
+ class Encoder {
1213
+ /**
1214
+ * @param {Base} name
1215
+ * @param {Prefix} prefix
1216
+ * @param {(bytes:Uint8Array) => string} baseEncode
1217
+ */
1218
+ constructor (name, prefix, baseEncode) {
1219
+ this.name = name;
1220
+ this.prefix = prefix;
1221
+ this.baseEncode = baseEncode;
1222
+ }
1223
+
1224
+ /**
1225
+ * @param {Uint8Array} bytes
1226
+ * @returns {API.Multibase<Prefix>}
1227
+ */
1228
+ encode (bytes) {
1229
+ if (bytes instanceof Uint8Array) {
1230
+ return `${this.prefix}${this.baseEncode(bytes)}`
1231
+ } else {
1232
+ throw Error('Unknown type, must be binary type')
1233
+ }
1234
+ }
1235
+ }
1236
+
1237
+ /**
1238
+ * @template {string} Prefix
1239
+ */
1240
+ /**
1241
+ * Class represents both BaseDecoder and MultibaseDecoder so it could be used
1242
+ * to decode multibases (with matching prefix) or just base decode strings
1243
+ * with corresponding base encoding.
1244
+ *
1245
+ * @class
1246
+ * @template {string} Base
1247
+ * @template {string} Prefix
1248
+ * @implements {API.MultibaseDecoder<Prefix>}
1249
+ * @implements {API.UnibaseDecoder<Prefix>}
1250
+ * @implements {API.BaseDecoder}
1251
+ */
1252
+ class Decoder {
1253
+ /**
1254
+ * @param {Base} name
1255
+ * @param {Prefix} prefix
1256
+ * @param {(text:string) => Uint8Array} baseDecode
1257
+ */
1258
+ constructor (name, prefix, baseDecode) {
1259
+ this.name = name;
1260
+ this.prefix = prefix;
1261
+ /* c8 ignore next 3 */
1262
+ if (prefix.codePointAt(0) === undefined) {
1263
+ throw new Error('Invalid prefix character')
1264
+ }
1265
+ /** @private */
1266
+ this.prefixCodePoint = /** @type {number} */ (prefix.codePointAt(0));
1267
+ this.baseDecode = baseDecode;
1268
+ }
1269
+
1270
+ /**
1271
+ * @param {string} text
1272
+ */
1273
+ decode (text) {
1274
+ if (typeof text === 'string') {
1275
+ if (text.codePointAt(0) !== this.prefixCodePoint) {
1276
+ throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`)
1277
+ }
1278
+ return this.baseDecode(text.slice(this.prefix.length))
1279
+ } else {
1280
+ throw Error('Can only multibase decode strings')
1281
+ }
1282
+ }
1283
+
1284
+ /**
1285
+ * @template {string} OtherPrefix
1286
+ * @param {API.UnibaseDecoder<OtherPrefix>|ComposedDecoder<OtherPrefix>} decoder
1287
+ * @returns {ComposedDecoder<Prefix|OtherPrefix>}
1288
+ */
1289
+ or (decoder) {
1290
+ return or(this, decoder)
1291
+ }
1292
+ }
1293
+
1294
+ /**
1295
+ * @template {string} Prefix
1296
+ * @typedef {Record<Prefix, API.UnibaseDecoder<Prefix>>} Decoders
1297
+ */
1298
+
1299
+ /**
1300
+ * @template {string} Prefix
1301
+ * @implements {API.MultibaseDecoder<Prefix>}
1302
+ * @implements {API.CombobaseDecoder<Prefix>}
1303
+ */
1304
+ class ComposedDecoder {
1305
+ /**
1306
+ * @param {Decoders<Prefix>} decoders
1307
+ */
1308
+ constructor (decoders) {
1309
+ this.decoders = decoders;
1310
+ }
1311
+
1312
+ /**
1313
+ * @template {string} OtherPrefix
1314
+ * @param {API.UnibaseDecoder<OtherPrefix>|ComposedDecoder<OtherPrefix>} decoder
1315
+ * @returns {ComposedDecoder<Prefix|OtherPrefix>}
1316
+ */
1317
+ or (decoder) {
1318
+ return or(this, decoder)
1319
+ }
1320
+
1321
+ /**
1322
+ * @param {string} input
1323
+ * @returns {Uint8Array}
1324
+ */
1325
+ decode (input) {
1326
+ const prefix = /** @type {Prefix} */ (input[0]);
1327
+ const decoder = this.decoders[prefix];
1328
+ if (decoder) {
1329
+ return decoder.decode(input)
1330
+ } else {
1331
+ throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)
1332
+ }
1333
+ }
1334
+ }
1335
+
1336
+ /**
1337
+ * @template {string} L
1338
+ * @template {string} R
1339
+ * @param {API.UnibaseDecoder<L>|API.CombobaseDecoder<L>} left
1340
+ * @param {API.UnibaseDecoder<R>|API.CombobaseDecoder<R>} right
1341
+ * @returns {ComposedDecoder<L|R>}
1342
+ */
1343
+ const or = (left, right) => new ComposedDecoder(/** @type {Decoders<L|R>} */({
1344
+ ...(left.decoders || { [/** @type API.UnibaseDecoder<L> */(left).prefix]: left }),
1345
+ ...(right.decoders || { [/** @type API.UnibaseDecoder<R> */(right).prefix]: right })
1346
+ }));
1347
+
1348
+ /**
1349
+ * @class
1350
+ * @template {string} Base
1351
+ * @template {string} Prefix
1352
+ * @implements {API.MultibaseCodec<Prefix>}
1353
+ * @implements {API.MultibaseEncoder<Prefix>}
1354
+ * @implements {API.MultibaseDecoder<Prefix>}
1355
+ * @implements {API.BaseCodec}
1356
+ * @implements {API.BaseEncoder}
1357
+ * @implements {API.BaseDecoder}
1358
+ */
1359
+ class Codec {
1360
+ /**
1361
+ * @param {Base} name
1362
+ * @param {Prefix} prefix
1363
+ * @param {(bytes:Uint8Array) => string} baseEncode
1364
+ * @param {(text:string) => Uint8Array} baseDecode
1365
+ */
1366
+ constructor (name, prefix, baseEncode, baseDecode) {
1367
+ this.name = name;
1368
+ this.prefix = prefix;
1369
+ this.baseEncode = baseEncode;
1370
+ this.baseDecode = baseDecode;
1371
+ this.encoder = new Encoder(name, prefix, baseEncode);
1372
+ this.decoder = new Decoder(name, prefix, baseDecode);
1373
+ }
1374
+
1375
+ /**
1376
+ * @param {Uint8Array} input
1377
+ */
1378
+ encode (input) {
1379
+ return this.encoder.encode(input)
1380
+ }
1381
+
1382
+ /**
1383
+ * @param {string} input
1384
+ */
1385
+ decode (input) {
1386
+ return this.decoder.decode(input)
1387
+ }
1388
+ }
1389
+
1390
+ /**
1391
+ * @template {string} Base
1392
+ * @template {string} Prefix
1393
+ * @param {object} options
1394
+ * @param {Base} options.name
1395
+ * @param {Prefix} options.prefix
1396
+ * @param {(bytes:Uint8Array) => string} options.encode
1397
+ * @param {(input:string) => Uint8Array} options.decode
1398
+ * @returns {Codec<Base, Prefix>}
1399
+ */
1400
+ const from = ({ name, prefix, encode, decode }) =>
1401
+ new Codec(name, prefix, encode, decode);
1402
+
1403
+ /**
1404
+ * @template {string} Base
1405
+ * @template {string} Prefix
1406
+ * @param {object} options
1407
+ * @param {Base} options.name
1408
+ * @param {Prefix} options.prefix
1409
+ * @param {string} options.alphabet
1410
+ * @returns {Codec<Base, Prefix>}
1411
+ */
1412
+ const baseX = ({ prefix, name, alphabet }) => {
1413
+ const { encode, decode } = _brrp__multiformats_scope_baseX(alphabet, name);
1414
+ return from({
1415
+ prefix,
1416
+ name,
1417
+ encode,
1418
+ /**
1419
+ * @param {string} text
1420
+ */
1421
+ decode: text => coerce(decode(text))
1422
+ })
1423
+ };
1424
+
1425
+ /**
1426
+ * @param {string} string
1427
+ * @param {string} alphabet
1428
+ * @param {number} bitsPerChar
1429
+ * @param {string} name
1430
+ * @returns {Uint8Array}
1431
+ */
1432
+ const decode$1 = (string, alphabet, bitsPerChar, name) => {
1433
+ // Build the character lookup table:
1434
+ /** @type {Record<string, number>} */
1435
+ const codes = {};
1436
+ for (let i = 0; i < alphabet.length; ++i) {
1437
+ codes[alphabet[i]] = i;
1438
+ }
1439
+
1440
+ // Count the padding bytes:
1441
+ let end = string.length;
1442
+ while (string[end - 1] === '=') {
1443
+ --end;
1444
+ }
1445
+
1446
+ // Allocate the output:
1447
+ const out = new Uint8Array((end * bitsPerChar / 8) | 0);
1448
+
1449
+ // Parse the data:
1450
+ let bits = 0; // Number of bits currently in the buffer
1451
+ let buffer = 0; // Bits waiting to be written out, MSB first
1452
+ let written = 0; // Next byte to write
1453
+ for (let i = 0; i < end; ++i) {
1454
+ // Read one character from the string:
1455
+ const value = codes[string[i]];
1456
+ if (value === undefined) {
1457
+ throw new SyntaxError(`Non-${name} character`)
1458
+ }
1459
+
1460
+ // Append the bits to the buffer:
1461
+ buffer = (buffer << bitsPerChar) | value;
1462
+ bits += bitsPerChar;
1463
+
1464
+ // Write out some bits if the buffer has a byte's worth:
1465
+ if (bits >= 8) {
1466
+ bits -= 8;
1467
+ out[written++] = 0xff & (buffer >> bits);
1468
+ }
1469
+ }
1470
+
1471
+ // Verify that we have received just enough bits:
1472
+ if (bits >= bitsPerChar || 0xff & (buffer << (8 - bits))) {
1473
+ throw new SyntaxError('Unexpected end of data')
1474
+ }
1475
+
1476
+ return out
1477
+ };
1478
+
1479
+ /**
1480
+ * @param {Uint8Array} data
1481
+ * @param {string} alphabet
1482
+ * @param {number} bitsPerChar
1483
+ * @returns {string}
1484
+ */
1485
+ const encode$1 = (data, alphabet, bitsPerChar) => {
1486
+ const pad = alphabet[alphabet.length - 1] === '=';
1487
+ const mask = (1 << bitsPerChar) - 1;
1488
+ let out = '';
1489
+
1490
+ let bits = 0; // Number of bits currently in the buffer
1491
+ let buffer = 0; // Bits waiting to be written out, MSB first
1492
+ for (let i = 0; i < data.length; ++i) {
1493
+ // Slurp data into the buffer:
1494
+ buffer = (buffer << 8) | data[i];
1495
+ bits += 8;
1496
+
1497
+ // Write out as much as we can:
1498
+ while (bits > bitsPerChar) {
1499
+ bits -= bitsPerChar;
1500
+ out += alphabet[mask & (buffer >> bits)];
1501
+ }
1502
+ }
1503
+
1504
+ // Partial character:
1505
+ if (bits) {
1506
+ out += alphabet[mask & (buffer << (bitsPerChar - bits))];
1507
+ }
1508
+
1509
+ // Add padding characters until we hit a byte boundary:
1510
+ if (pad) {
1511
+ while ((out.length * bitsPerChar) & 7) {
1512
+ out += '=';
1513
+ }
1514
+ }
1515
+
1516
+ return out
1517
+ };
1518
+
1519
+ /**
1520
+ * RFC4648 Factory
1521
+ *
1522
+ * @template {string} Base
1523
+ * @template {string} Prefix
1524
+ * @param {object} options
1525
+ * @param {Base} options.name
1526
+ * @param {Prefix} options.prefix
1527
+ * @param {string} options.alphabet
1528
+ * @param {number} options.bitsPerChar
1529
+ */
1530
+ const rfc4648 = ({ name, prefix, bitsPerChar, alphabet }) => {
1531
+ return from({
1532
+ prefix,
1533
+ name,
1534
+ encode (input) {
1535
+ return encode$1(input, alphabet, bitsPerChar)
1536
+ },
1537
+ decode (input) {
1538
+ return decode$1(input, alphabet, bitsPerChar, name)
1539
+ }
1540
+ })
1541
+ };
1542
+
1543
+ const base10 = baseX({
1544
+ prefix: '9',
1545
+ name: 'base10',
1546
+ alphabet: '0123456789'
1547
+ });
1548
+
1549
+ var base10$1 = /*#__PURE__*/Object.freeze({
1550
+ __proto__: null,
1551
+ base10: base10
1552
+ });
1553
+
1554
+ // @ts-check
1555
+
1556
+
1557
+ const base16 = rfc4648({
1558
+ prefix: 'f',
1559
+ name: 'base16',
1560
+ alphabet: '0123456789abcdef',
1561
+ bitsPerChar: 4
1562
+ });
1563
+
1564
+ const base16upper = rfc4648({
1565
+ prefix: 'F',
1566
+ name: 'base16upper',
1567
+ alphabet: '0123456789ABCDEF',
1568
+ bitsPerChar: 4
1569
+ });
1570
+
1571
+ var base16$1 = /*#__PURE__*/Object.freeze({
1572
+ __proto__: null,
1573
+ base16: base16,
1574
+ base16upper: base16upper
1575
+ });
1576
+
1577
+ // @ts-check
1578
+
1579
+
1580
+ const base2 = rfc4648({
1581
+ prefix: '0',
1582
+ name: 'base2',
1583
+ alphabet: '01',
1584
+ bitsPerChar: 1
1585
+ });
1586
+
1587
+ var base2$1 = /*#__PURE__*/Object.freeze({
1588
+ __proto__: null,
1589
+ base2: base2
1590
+ });
1591
+
1592
+ const alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂');
1593
+ const alphabetBytesToChars = /** @type {string[]} */ (alphabet.reduce((p, c, i) => { p[i] = c; return p }, /** @type {string[]} */([])));
1594
+ const alphabetCharsToBytes = /** @type {number[]} */ (alphabet.reduce((p, c, i) => { p[/** @type {number} */ (c.codePointAt(0))] = i; return p }, /** @type {number[]} */([])));
1595
+
1596
+ /**
1597
+ * @param {Uint8Array} data
1598
+ * @returns {string}
1599
+ */
1600
+ function encode (data) {
1601
+ return data.reduce((p, c) => {
1602
+ p += alphabetBytesToChars[c];
1603
+ return p
1604
+ }, '')
1605
+ }
1606
+
1607
+ /**
1608
+ * @param {string} str
1609
+ * @returns {Uint8Array}
1610
+ */
1611
+ function decode (str) {
1612
+ const byts = [];
1613
+ for (const char of str) {
1614
+ const byt = alphabetCharsToBytes[/** @type {number} */ (char.codePointAt(0))];
1615
+ if (byt === undefined) {
1616
+ throw new Error(`Non-base256emoji character: ${char}`)
1617
+ }
1618
+ byts.push(byt);
1619
+ }
1620
+ return new Uint8Array(byts)
1621
+ }
1622
+
1623
+ const base256emoji = from({
1624
+ prefix: '🚀',
1625
+ name: 'base256emoji',
1626
+ encode,
1627
+ decode
1628
+ });
1629
+
1630
+ var base256emoji$1 = /*#__PURE__*/Object.freeze({
1631
+ __proto__: null,
1632
+ base256emoji: base256emoji
1633
+ });
1634
+
1635
+ const base32 = rfc4648({
1636
+ prefix: 'b',
1637
+ name: 'base32',
1638
+ alphabet: 'abcdefghijklmnopqrstuvwxyz234567',
1639
+ bitsPerChar: 5
1640
+ });
1641
+
1642
+ const base32upper = rfc4648({
1643
+ prefix: 'B',
1644
+ name: 'base32upper',
1645
+ alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',
1646
+ bitsPerChar: 5
1647
+ });
1648
+
1649
+ const base32pad = rfc4648({
1650
+ prefix: 'c',
1651
+ name: 'base32pad',
1652
+ alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',
1653
+ bitsPerChar: 5
1654
+ });
1655
+
1656
+ const base32padupper = rfc4648({
1657
+ prefix: 'C',
1658
+ name: 'base32padupper',
1659
+ alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',
1660
+ bitsPerChar: 5
1661
+ });
1662
+
1663
+ const base32hex = rfc4648({
1664
+ prefix: 'v',
1665
+ name: 'base32hex',
1666
+ alphabet: '0123456789abcdefghijklmnopqrstuv',
1667
+ bitsPerChar: 5
1668
+ });
1669
+
1670
+ const base32hexupper = rfc4648({
1671
+ prefix: 'V',
1672
+ name: 'base32hexupper',
1673
+ alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',
1674
+ bitsPerChar: 5
1675
+ });
1676
+
1677
+ const base32hexpad = rfc4648({
1678
+ prefix: 't',
1679
+ name: 'base32hexpad',
1680
+ alphabet: '0123456789abcdefghijklmnopqrstuv=',
1681
+ bitsPerChar: 5
1682
+ });
1683
+
1684
+ const base32hexpadupper = rfc4648({
1685
+ prefix: 'T',
1686
+ name: 'base32hexpadupper',
1687
+ alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',
1688
+ bitsPerChar: 5
1689
+ });
1690
+
1691
+ const base32z = rfc4648({
1692
+ prefix: 'h',
1693
+ name: 'base32z',
1694
+ alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',
1695
+ bitsPerChar: 5
1696
+ });
1697
+
1698
+ var base32$1 = /*#__PURE__*/Object.freeze({
1699
+ __proto__: null,
1700
+ base32: base32,
1701
+ base32hex: base32hex,
1702
+ base32hexpad: base32hexpad,
1703
+ base32hexpadupper: base32hexpadupper,
1704
+ base32hexupper: base32hexupper,
1705
+ base32pad: base32pad,
1706
+ base32padupper: base32padupper,
1707
+ base32upper: base32upper,
1708
+ base32z: base32z
1709
+ });
1710
+
1711
+ const base36 = baseX({
1712
+ prefix: 'k',
1713
+ name: 'base36',
1714
+ alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'
1715
+ });
1716
+
1717
+ const base36upper = baseX({
1718
+ prefix: 'K',
1719
+ name: 'base36upper',
1720
+ alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
1721
+ });
1722
+
1723
+ var base36$1 = /*#__PURE__*/Object.freeze({
1724
+ __proto__: null,
1725
+ base36: base36,
1726
+ base36upper: base36upper
1727
+ });
1728
+
1729
+ const base58btc = baseX({
1730
+ name: 'base58btc',
1731
+ prefix: 'z',
1732
+ alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
1733
+ });
1734
+
1735
+ const base58flickr = baseX({
1736
+ name: 'base58flickr',
1737
+ prefix: 'Z',
1738
+ alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'
1739
+ });
1740
+
1741
+ var base58 = /*#__PURE__*/Object.freeze({
1742
+ __proto__: null,
1743
+ base58btc: base58btc,
1744
+ base58flickr: base58flickr
1745
+ });
1746
+
1747
+ // @ts-check
1748
+
1749
+
1750
+ const base64 = rfc4648({
1751
+ prefix: 'm',
1752
+ name: 'base64',
1753
+ alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
1754
+ bitsPerChar: 6
1755
+ });
1756
+
1757
+ const base64pad = rfc4648({
1758
+ prefix: 'M',
1759
+ name: 'base64pad',
1760
+ alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',
1761
+ bitsPerChar: 6
1762
+ });
1763
+
1764
+ const base64url = rfc4648({
1765
+ prefix: 'u',
1766
+ name: 'base64url',
1767
+ alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',
1768
+ bitsPerChar: 6
1769
+ });
1770
+
1771
+ const base64urlpad = rfc4648({
1772
+ prefix: 'U',
1773
+ name: 'base64urlpad',
1774
+ alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',
1775
+ bitsPerChar: 6
1776
+ });
1777
+
1778
+ var base64$1 = /*#__PURE__*/Object.freeze({
1779
+ __proto__: null,
1780
+ base64: base64,
1781
+ base64pad: base64pad,
1782
+ base64url: base64url,
1783
+ base64urlpad: base64urlpad
1784
+ });
1785
+
1786
+ // @ts-check
1787
+
1788
+
1789
+ const base8 = rfc4648({
1790
+ prefix: '7',
1791
+ name: 'base8',
1792
+ alphabet: '01234567',
1793
+ bitsPerChar: 3
1794
+ });
1795
+
1796
+ var base8$1 = /*#__PURE__*/Object.freeze({
1797
+ __proto__: null,
1798
+ base8: base8
1799
+ });
1800
+
1801
+ // @ts-check
1802
+
1803
+
1804
+ const identity = from({
1805
+ prefix: '\x00',
1806
+ name: 'identity',
1807
+ encode: (buf) => toString(buf),
1808
+ decode: (str) => fromString$1(str)
1809
+ });
1810
+
1811
+ var identityBase = /*#__PURE__*/Object.freeze({
1812
+ __proto__: null,
1813
+ identity: identity
1814
+ });
1815
+
1816
+ // @ts-check
1817
+
1818
+ /**
1819
+ * @template T
1820
+ * @typedef {import('./interface.js').ByteView<T>} ByteView
1821
+ */
1822
+
1823
+ new TextEncoder();
1824
+ new TextDecoder();
1825
+
1826
+ // @ts-check
1827
+
1828
+
1829
+ const bases = { ...identityBase, ...base2$1, ...base8$1, ...base10$1, ...base16$1, ...base32$1, ...base36$1, ...base58, ...base64$1, ...base256emoji$1 };
1830
+
1831
+ /**
1832
+ * Where possible returns a Uint8Array of the requested size that references
1833
+ * uninitialized memory. Only use if you are certain you will immediately
1834
+ * overwrite every value in the returned `Uint8Array`.
1835
+ */
1836
+ function allocUnsafe(size = 0) {
1837
+ if (globalThis.Buffer?.allocUnsafe != null) {
1838
+ return asUint8Array(globalThis.Buffer.allocUnsafe(size));
1839
+ }
1840
+ return new Uint8Array(size);
1841
+ }
1842
+
1843
+ function createCodec(name, prefix, encode, decode) {
1844
+ return {
1845
+ name,
1846
+ prefix,
1847
+ encoder: {
1848
+ name,
1849
+ prefix,
1850
+ encode
1851
+ },
1852
+ decoder: {
1853
+ decode
1854
+ }
1855
+ };
1856
+ }
1857
+ const string = createCodec('utf8', 'u', (buf) => {
1858
+ const decoder = new TextDecoder('utf8');
1859
+ return 'u' + decoder.decode(buf);
1860
+ }, (str) => {
1861
+ const encoder = new TextEncoder();
1862
+ return encoder.encode(str.substring(1));
1863
+ });
1864
+ const ascii = createCodec('ascii', 'a', (buf) => {
1865
+ let string = 'a';
1866
+ for (let i = 0; i < buf.length; i++) {
1867
+ string += String.fromCharCode(buf[i]);
1868
+ }
1869
+ return string;
1870
+ }, (str) => {
1871
+ str = str.substring(1);
1872
+ const buf = allocUnsafe(str.length);
1873
+ for (let i = 0; i < str.length; i++) {
1874
+ buf[i] = str.charCodeAt(i);
1875
+ }
1876
+ return buf;
1877
+ });
1878
+ const BASES = {
1879
+ utf8: string,
1880
+ 'utf-8': string,
1881
+ hex: bases.base16,
1882
+ latin1: ascii,
1883
+ ascii,
1884
+ binary: ascii,
1885
+ ...bases
1886
+ };
1887
+
1888
+ /**
1889
+ * Create a `Uint8Array` from the passed string
1890
+ *
1891
+ * Supports `utf8`, `utf-8`, `hex`, and any encoding supported by the multiformats module.
1892
+ *
1893
+ * Also `ascii` which is similar to node's 'binary' encoding.
1894
+ */
1895
+ function fromString(string, encoding = 'utf8') {
1896
+ const base = BASES[encoding];
1897
+ if (base == null) {
1898
+ throw new Error(`Unsupported encoding "${encoding}"`);
1899
+ }
1900
+ if ((encoding === 'utf8' || encoding === 'utf-8') && globalThis.Buffer != null && globalThis.Buffer.from != null) {
1901
+ return asUint8Array(globalThis.Buffer.from(string, 'utf-8'));
1902
+ }
1903
+ // add multibase prefix
1904
+ return base.decoder.decode(`${base.prefix}${string}`); // eslint-disable-line @typescript-eslint/restrict-template-expressions
1905
+ }
1906
+
1907
+ /**
1908
+ * Convert input to a byte array.
1909
+ *
1910
+ * Handles both `0x` prefixed and non-prefixed strings.
1911
+ */
1912
+ function hexToBytes(hex) {
1913
+ if (typeof hex === "string") {
1914
+ const _hex = hex.replace(/^0x/i, "");
1915
+ return fromString(_hex.toLowerCase(), "base16");
1916
+ }
1917
+ return hex;
1918
+ }
1919
+ /**
1920
+ * Concatenate using Uint8Arrays as `Buffer` has a different behavior with `DataView`
1921
+ */
1922
+ function concat(byteArrays, totalLength) {
1923
+ const len = totalLength ?? byteArrays.reduce((acc, curr) => acc + curr.length, 0);
1924
+ const res = new Uint8Array(len);
1925
+ let offset = 0;
1926
+ for (const bytes of byteArrays) {
1927
+ res.set(bytes, offset);
1928
+ offset += bytes.length;
1929
+ }
1930
+ return res;
1931
+ }
1932
+
1933
+ var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
1934
+
1935
+ function getDefaultExportFromCjs (x) {
1936
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
1937
+ }
1938
+
1939
+ function getAugmentedNamespace(n) {
1940
+ if (n.__esModule) return n;
1941
+ var f = n.default;
1942
+ if (typeof f == "function") {
1943
+ var a = function a () {
1944
+ if (this instanceof a) {
1945
+ return Reflect.construct(f, arguments, this.constructor);
1946
+ }
1947
+ return f.apply(this, arguments);
1948
+ };
1949
+ a.prototype = f.prototype;
1950
+ } else a = {};
1951
+ Object.defineProperty(a, '__esModule', {value: true});
1952
+ Object.keys(n).forEach(function (k) {
1953
+ var d = Object.getOwnPropertyDescriptor(n, k);
1954
+ Object.defineProperty(a, k, d.get ? d : {
1955
+ enumerable: true,
1956
+ get: function () {
1957
+ return n[k];
1958
+ }
1959
+ });
1960
+ });
1961
+ return a;
1962
+ }
1963
+
1964
+ var sha3$1 = {exports: {}};
1965
+
1966
+ /**
1967
+ * [js-sha3]{@link https://github.com/emn178/js-sha3}
1968
+ *
1969
+ * @version 0.9.2
1970
+ * @author Chen, Yi-Cyuan [emn178@gmail.com]
1971
+ * @copyright Chen, Yi-Cyuan 2015-2023
1972
+ * @license MIT
1973
+ */
1974
+
1975
+ (function (module) {
1976
+ /*jslint bitwise: true */
1977
+ (function () {
1978
+
1979
+ var INPUT_ERROR = 'input is invalid type';
1980
+ var FINALIZE_ERROR = 'finalize already called';
1981
+ var WINDOW = typeof window === 'object';
1982
+ var root = WINDOW ? window : {};
1983
+ if (root.JS_SHA3_NO_WINDOW) {
1984
+ WINDOW = false;
1985
+ }
1986
+ var WEB_WORKER = !WINDOW && typeof self === 'object';
1987
+ var NODE_JS = !root.JS_SHA3_NO_NODE_JS && typeof process === 'object' && process.versions && process.versions.node;
1988
+ if (NODE_JS) {
1989
+ root = commonjsGlobal;
1990
+ } else if (WEB_WORKER) {
1991
+ root = self;
1992
+ }
1993
+ var COMMON_JS = !root.JS_SHA3_NO_COMMON_JS && 'object' === 'object' && module.exports;
1994
+ var ARRAY_BUFFER = !root.JS_SHA3_NO_ARRAY_BUFFER && typeof ArrayBuffer !== 'undefined';
1995
+ var HEX_CHARS = '0123456789abcdef'.split('');
1996
+ var SHAKE_PADDING = [31, 7936, 2031616, 520093696];
1997
+ var CSHAKE_PADDING = [4, 1024, 262144, 67108864];
1998
+ var KECCAK_PADDING = [1, 256, 65536, 16777216];
1999
+ var PADDING = [6, 1536, 393216, 100663296];
2000
+ var SHIFT = [0, 8, 16, 24];
2001
+ var RC = [1, 0, 32898, 0, 32906, 2147483648, 2147516416, 2147483648, 32907, 0, 2147483649,
2002
+ 0, 2147516545, 2147483648, 32777, 2147483648, 138, 0, 136, 0, 2147516425, 0,
2003
+ 2147483658, 0, 2147516555, 0, 139, 2147483648, 32905, 2147483648, 32771,
2004
+ 2147483648, 32770, 2147483648, 128, 2147483648, 32778, 0, 2147483658, 2147483648,
2005
+ 2147516545, 2147483648, 32896, 2147483648, 2147483649, 0, 2147516424, 2147483648];
2006
+ var BITS = [224, 256, 384, 512];
2007
+ var SHAKE_BITS = [128, 256];
2008
+ var OUTPUT_TYPES = ['hex', 'buffer', 'arrayBuffer', 'array', 'digest'];
2009
+ var CSHAKE_BYTEPAD = {
2010
+ '128': 168,
2011
+ '256': 136
2012
+ };
2013
+
2014
+
2015
+ var isArray = root.JS_SHA3_NO_NODE_JS || !Array.isArray
2016
+ ? function (obj) {
2017
+ return Object.prototype.toString.call(obj) === '[object Array]';
2018
+ }
2019
+ : Array.isArray;
2020
+
2021
+ var isView = (ARRAY_BUFFER && (root.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW || !ArrayBuffer.isView))
2022
+ ? function (obj) {
2023
+ return typeof obj === 'object' && obj.buffer && obj.buffer.constructor === ArrayBuffer;
2024
+ }
2025
+ : ArrayBuffer.isView;
2026
+
2027
+ // [message: string, isString: bool]
2028
+ var formatMessage = function (message) {
2029
+ var type = typeof message;
2030
+ if (type === 'string') {
2031
+ return [message, true];
2032
+ }
2033
+ if (type !== 'object' || message === null) {
2034
+ throw new Error(INPUT_ERROR);
2035
+ }
2036
+ if (ARRAY_BUFFER && message.constructor === ArrayBuffer) {
2037
+ return [new Uint8Array(message), false];
2038
+ }
2039
+ if (!isArray(message) && !isView(message)) {
2040
+ throw new Error(INPUT_ERROR);
2041
+ }
2042
+ return [message, false];
2043
+ };
2044
+
2045
+ var empty = function (message) {
2046
+ return formatMessage(message)[0].length === 0;
2047
+ };
2048
+
2049
+ var createOutputMethod = function (bits, padding, outputType) {
2050
+ return function (message) {
2051
+ return new Keccak(bits, padding, bits).update(message)[outputType]();
2052
+ };
2053
+ };
2054
+
2055
+ var createShakeOutputMethod = function (bits, padding, outputType) {
2056
+ return function (message, outputBits) {
2057
+ return new Keccak(bits, padding, outputBits).update(message)[outputType]();
2058
+ };
2059
+ };
2060
+
2061
+ var createCshakeOutputMethod = function (bits, padding, outputType) {
2062
+ return function (message, outputBits, n, s) {
2063
+ return methods['cshake' + bits].update(message, outputBits, n, s)[outputType]();
2064
+ };
2065
+ };
2066
+
2067
+ var createKmacOutputMethod = function (bits, padding, outputType) {
2068
+ return function (key, message, outputBits, s) {
2069
+ return methods['kmac' + bits].update(key, message, outputBits, s)[outputType]();
2070
+ };
2071
+ };
2072
+
2073
+ var createOutputMethods = function (method, createMethod, bits, padding) {
2074
+ for (var i = 0; i < OUTPUT_TYPES.length; ++i) {
2075
+ var type = OUTPUT_TYPES[i];
2076
+ method[type] = createMethod(bits, padding, type);
2077
+ }
2078
+ return method;
2079
+ };
2080
+
2081
+ var createMethod = function (bits, padding) {
2082
+ var method = createOutputMethod(bits, padding, 'hex');
2083
+ method.create = function () {
2084
+ return new Keccak(bits, padding, bits);
2085
+ };
2086
+ method.update = function (message) {
2087
+ return method.create().update(message);
2088
+ };
2089
+ return createOutputMethods(method, createOutputMethod, bits, padding);
2090
+ };
2091
+
2092
+ var createShakeMethod = function (bits, padding) {
2093
+ var method = createShakeOutputMethod(bits, padding, 'hex');
2094
+ method.create = function (outputBits) {
2095
+ return new Keccak(bits, padding, outputBits);
2096
+ };
2097
+ method.update = function (message, outputBits) {
2098
+ return method.create(outputBits).update(message);
2099
+ };
2100
+ return createOutputMethods(method, createShakeOutputMethod, bits, padding);
2101
+ };
2102
+
2103
+ var createCshakeMethod = function (bits, padding) {
2104
+ var w = CSHAKE_BYTEPAD[bits];
2105
+ var method = createCshakeOutputMethod(bits, padding, 'hex');
2106
+ method.create = function (outputBits, n, s) {
2107
+ if (empty(n) && empty(s)) {
2108
+ return methods['shake' + bits].create(outputBits);
2109
+ } else {
2110
+ return new Keccak(bits, padding, outputBits).bytepad([n, s], w);
2111
+ }
2112
+ };
2113
+ method.update = function (message, outputBits, n, s) {
2114
+ return method.create(outputBits, n, s).update(message);
2115
+ };
2116
+ return createOutputMethods(method, createCshakeOutputMethod, bits, padding);
2117
+ };
2118
+
2119
+ var createKmacMethod = function (bits, padding) {
2120
+ var w = CSHAKE_BYTEPAD[bits];
2121
+ var method = createKmacOutputMethod(bits, padding, 'hex');
2122
+ method.create = function (key, outputBits, s) {
2123
+ return new Kmac(bits, padding, outputBits).bytepad(['KMAC', s], w).bytepad([key], w);
2124
+ };
2125
+ method.update = function (key, message, outputBits, s) {
2126
+ return method.create(key, outputBits, s).update(message);
2127
+ };
2128
+ return createOutputMethods(method, createKmacOutputMethod, bits, padding);
2129
+ };
2130
+
2131
+ var algorithms = [
2132
+ { name: 'keccak', padding: KECCAK_PADDING, bits: BITS, createMethod: createMethod },
2133
+ { name: 'sha3', padding: PADDING, bits: BITS, createMethod: createMethod },
2134
+ { name: 'shake', padding: SHAKE_PADDING, bits: SHAKE_BITS, createMethod: createShakeMethod },
2135
+ { name: 'cshake', padding: CSHAKE_PADDING, bits: SHAKE_BITS, createMethod: createCshakeMethod },
2136
+ { name: 'kmac', padding: CSHAKE_PADDING, bits: SHAKE_BITS, createMethod: createKmacMethod }
2137
+ ];
2138
+
2139
+ var methods = {}, methodNames = [];
2140
+
2141
+ for (var i = 0; i < algorithms.length; ++i) {
2142
+ var algorithm = algorithms[i];
2143
+ var bits = algorithm.bits;
2144
+ for (var j = 0; j < bits.length; ++j) {
2145
+ var methodName = algorithm.name + '_' + bits[j];
2146
+ methodNames.push(methodName);
2147
+ methods[methodName] = algorithm.createMethod(bits[j], algorithm.padding);
2148
+ if (algorithm.name !== 'sha3') {
2149
+ var newMethodName = algorithm.name + bits[j];
2150
+ methodNames.push(newMethodName);
2151
+ methods[newMethodName] = methods[methodName];
2152
+ }
2153
+ }
2154
+ }
2155
+
2156
+ function Keccak(bits, padding, outputBits) {
2157
+ this.blocks = [];
2158
+ this.s = [];
2159
+ this.padding = padding;
2160
+ this.outputBits = outputBits;
2161
+ this.reset = true;
2162
+ this.finalized = false;
2163
+ this.block = 0;
2164
+ this.start = 0;
2165
+ this.blockCount = (1600 - (bits << 1)) >> 5;
2166
+ this.byteCount = this.blockCount << 2;
2167
+ this.outputBlocks = outputBits >> 5;
2168
+ this.extraBytes = (outputBits & 31) >> 3;
2169
+
2170
+ for (var i = 0; i < 50; ++i) {
2171
+ this.s[i] = 0;
2172
+ }
2173
+ }
2174
+
2175
+ Keccak.prototype.update = function (message) {
2176
+ if (this.finalized) {
2177
+ throw new Error(FINALIZE_ERROR);
2178
+ }
2179
+ var result = formatMessage(message);
2180
+ message = result[0];
2181
+ var isString = result[1];
2182
+ var blocks = this.blocks, byteCount = this.byteCount, length = message.length,
2183
+ blockCount = this.blockCount, index = 0, s = this.s, i, code;
2184
+
2185
+ while (index < length) {
2186
+ if (this.reset) {
2187
+ this.reset = false;
2188
+ blocks[0] = this.block;
2189
+ for (i = 1; i < blockCount + 1; ++i) {
2190
+ blocks[i] = 0;
2191
+ }
2192
+ }
2193
+ if (isString) {
2194
+ for (i = this.start; index < length && i < byteCount; ++index) {
2195
+ code = message.charCodeAt(index);
2196
+ if (code < 0x80) {
2197
+ blocks[i >> 2] |= code << SHIFT[i++ & 3];
2198
+ } else if (code < 0x800) {
2199
+ blocks[i >> 2] |= (0xc0 | (code >> 6)) << SHIFT[i++ & 3];
2200
+ blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];
2201
+ } else if (code < 0xd800 || code >= 0xe000) {
2202
+ blocks[i >> 2] |= (0xe0 | (code >> 12)) << SHIFT[i++ & 3];
2203
+ blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3];
2204
+ blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];
2205
+ } else {
2206
+ code = 0x10000 + (((code & 0x3ff) << 10) | (message.charCodeAt(++index) & 0x3ff));
2207
+ blocks[i >> 2] |= (0xf0 | (code >> 18)) << SHIFT[i++ & 3];
2208
+ blocks[i >> 2] |= (0x80 | ((code >> 12) & 0x3f)) << SHIFT[i++ & 3];
2209
+ blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3];
2210
+ blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];
2211
+ }
2212
+ }
2213
+ } else {
2214
+ for (i = this.start; index < length && i < byteCount; ++index) {
2215
+ blocks[i >> 2] |= message[index] << SHIFT[i++ & 3];
2216
+ }
2217
+ }
2218
+ this.lastByteIndex = i;
2219
+ if (i >= byteCount) {
2220
+ this.start = i - byteCount;
2221
+ this.block = blocks[blockCount];
2222
+ for (i = 0; i < blockCount; ++i) {
2223
+ s[i] ^= blocks[i];
2224
+ }
2225
+ f(s);
2226
+ this.reset = true;
2227
+ } else {
2228
+ this.start = i;
2229
+ }
2230
+ }
2231
+ return this;
2232
+ };
2233
+
2234
+ Keccak.prototype.encode = function (x, right) {
2235
+ var o = x & 255, n = 1;
2236
+ var bytes = [o];
2237
+ x = x >> 8;
2238
+ o = x & 255;
2239
+ while (o > 0) {
2240
+ bytes.unshift(o);
2241
+ x = x >> 8;
2242
+ o = x & 255;
2243
+ ++n;
2244
+ }
2245
+ if (right) {
2246
+ bytes.push(n);
2247
+ } else {
2248
+ bytes.unshift(n);
2249
+ }
2250
+ this.update(bytes);
2251
+ return bytes.length;
2252
+ };
2253
+
2254
+ Keccak.prototype.encodeString = function (str) {
2255
+ var result = formatMessage(str);
2256
+ str = result[0];
2257
+ var isString = result[1];
2258
+ var bytes = 0, length = str.length;
2259
+ if (isString) {
2260
+ for (var i = 0; i < str.length; ++i) {
2261
+ var code = str.charCodeAt(i);
2262
+ if (code < 0x80) {
2263
+ bytes += 1;
2264
+ } else if (code < 0x800) {
2265
+ bytes += 2;
2266
+ } else if (code < 0xd800 || code >= 0xe000) {
2267
+ bytes += 3;
2268
+ } else {
2269
+ code = 0x10000 + (((code & 0x3ff) << 10) | (str.charCodeAt(++i) & 0x3ff));
2270
+ bytes += 4;
2271
+ }
2272
+ }
2273
+ } else {
2274
+ bytes = length;
2275
+ }
2276
+ bytes += this.encode(bytes * 8);
2277
+ this.update(str);
2278
+ return bytes;
2279
+ };
2280
+
2281
+ Keccak.prototype.bytepad = function (strs, w) {
2282
+ var bytes = this.encode(w);
2283
+ for (var i = 0; i < strs.length; ++i) {
2284
+ bytes += this.encodeString(strs[i]);
2285
+ }
2286
+ var paddingBytes = (w - bytes % w) % w;
2287
+ var zeros = [];
2288
+ zeros.length = paddingBytes;
2289
+ this.update(zeros);
2290
+ return this;
2291
+ };
2292
+
2293
+ Keccak.prototype.finalize = function () {
2294
+ if (this.finalized) {
2295
+ return;
2296
+ }
2297
+ this.finalized = true;
2298
+ var blocks = this.blocks, i = this.lastByteIndex, blockCount = this.blockCount, s = this.s;
2299
+ blocks[i >> 2] |= this.padding[i & 3];
2300
+ if (this.lastByteIndex === this.byteCount) {
2301
+ blocks[0] = blocks[blockCount];
2302
+ for (i = 1; i < blockCount + 1; ++i) {
2303
+ blocks[i] = 0;
2304
+ }
2305
+ }
2306
+ blocks[blockCount - 1] |= 0x80000000;
2307
+ for (i = 0; i < blockCount; ++i) {
2308
+ s[i] ^= blocks[i];
2309
+ }
2310
+ f(s);
2311
+ };
2312
+
2313
+ Keccak.prototype.toString = Keccak.prototype.hex = function () {
2314
+ this.finalize();
2315
+
2316
+ var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks,
2317
+ extraBytes = this.extraBytes, i = 0, j = 0;
2318
+ var hex = '', block;
2319
+ while (j < outputBlocks) {
2320
+ for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {
2321
+ block = s[i];
2322
+ hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F] +
2323
+ HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F] +
2324
+ HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F] +
2325
+ HEX_CHARS[(block >> 28) & 0x0F] + HEX_CHARS[(block >> 24) & 0x0F];
2326
+ }
2327
+ if (j % blockCount === 0) {
2328
+ f(s);
2329
+ i = 0;
2330
+ }
2331
+ }
2332
+ if (extraBytes) {
2333
+ block = s[i];
2334
+ hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F];
2335
+ if (extraBytes > 1) {
2336
+ hex += HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F];
2337
+ }
2338
+ if (extraBytes > 2) {
2339
+ hex += HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F];
2340
+ }
2341
+ }
2342
+ return hex;
2343
+ };
2344
+
2345
+ Keccak.prototype.arrayBuffer = function () {
2346
+ this.finalize();
2347
+
2348
+ var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks,
2349
+ extraBytes = this.extraBytes, i = 0, j = 0;
2350
+ var bytes = this.outputBits >> 3;
2351
+ var buffer;
2352
+ if (extraBytes) {
2353
+ buffer = new ArrayBuffer((outputBlocks + 1) << 2);
2354
+ } else {
2355
+ buffer = new ArrayBuffer(bytes);
2356
+ }
2357
+ var array = new Uint32Array(buffer);
2358
+ while (j < outputBlocks) {
2359
+ for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {
2360
+ array[j] = s[i];
2361
+ }
2362
+ if (j % blockCount === 0) {
2363
+ f(s);
2364
+ }
2365
+ }
2366
+ if (extraBytes) {
2367
+ array[i] = s[i];
2368
+ buffer = buffer.slice(0, bytes);
2369
+ }
2370
+ return buffer;
2371
+ };
2372
+
2373
+ Keccak.prototype.buffer = Keccak.prototype.arrayBuffer;
2374
+
2375
+ Keccak.prototype.digest = Keccak.prototype.array = function () {
2376
+ this.finalize();
2377
+
2378
+ var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks,
2379
+ extraBytes = this.extraBytes, i = 0, j = 0;
2380
+ var array = [], offset, block;
2381
+ while (j < outputBlocks) {
2382
+ for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {
2383
+ offset = j << 2;
2384
+ block = s[i];
2385
+ array[offset] = block & 0xFF;
2386
+ array[offset + 1] = (block >> 8) & 0xFF;
2387
+ array[offset + 2] = (block >> 16) & 0xFF;
2388
+ array[offset + 3] = (block >> 24) & 0xFF;
2389
+ }
2390
+ if (j % blockCount === 0) {
2391
+ f(s);
2392
+ }
2393
+ }
2394
+ if (extraBytes) {
2395
+ offset = j << 2;
2396
+ block = s[i];
2397
+ array[offset] = block & 0xFF;
2398
+ if (extraBytes > 1) {
2399
+ array[offset + 1] = (block >> 8) & 0xFF;
2400
+ }
2401
+ if (extraBytes > 2) {
2402
+ array[offset + 2] = (block >> 16) & 0xFF;
2403
+ }
2404
+ }
2405
+ return array;
2406
+ };
2407
+
2408
+ function Kmac(bits, padding, outputBits) {
2409
+ Keccak.call(this, bits, padding, outputBits);
2410
+ }
2411
+
2412
+ Kmac.prototype = new Keccak();
2413
+
2414
+ Kmac.prototype.finalize = function () {
2415
+ this.encode(this.outputBits, true);
2416
+ return Keccak.prototype.finalize.call(this);
2417
+ };
2418
+
2419
+ var f = function (s) {
2420
+ var h, l, n, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9,
2421
+ b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17,
2422
+ b18, b19, b20, b21, b22, b23, b24, b25, b26, b27, b28, b29, b30, b31, b32, b33,
2423
+ b34, b35, b36, b37, b38, b39, b40, b41, b42, b43, b44, b45, b46, b47, b48, b49;
2424
+ for (n = 0; n < 48; n += 2) {
2425
+ c0 = s[0] ^ s[10] ^ s[20] ^ s[30] ^ s[40];
2426
+ c1 = s[1] ^ s[11] ^ s[21] ^ s[31] ^ s[41];
2427
+ c2 = s[2] ^ s[12] ^ s[22] ^ s[32] ^ s[42];
2428
+ c3 = s[3] ^ s[13] ^ s[23] ^ s[33] ^ s[43];
2429
+ c4 = s[4] ^ s[14] ^ s[24] ^ s[34] ^ s[44];
2430
+ c5 = s[5] ^ s[15] ^ s[25] ^ s[35] ^ s[45];
2431
+ c6 = s[6] ^ s[16] ^ s[26] ^ s[36] ^ s[46];
2432
+ c7 = s[7] ^ s[17] ^ s[27] ^ s[37] ^ s[47];
2433
+ c8 = s[8] ^ s[18] ^ s[28] ^ s[38] ^ s[48];
2434
+ c9 = s[9] ^ s[19] ^ s[29] ^ s[39] ^ s[49];
2435
+
2436
+ h = c8 ^ ((c2 << 1) | (c3 >>> 31));
2437
+ l = c9 ^ ((c3 << 1) | (c2 >>> 31));
2438
+ s[0] ^= h;
2439
+ s[1] ^= l;
2440
+ s[10] ^= h;
2441
+ s[11] ^= l;
2442
+ s[20] ^= h;
2443
+ s[21] ^= l;
2444
+ s[30] ^= h;
2445
+ s[31] ^= l;
2446
+ s[40] ^= h;
2447
+ s[41] ^= l;
2448
+ h = c0 ^ ((c4 << 1) | (c5 >>> 31));
2449
+ l = c1 ^ ((c5 << 1) | (c4 >>> 31));
2450
+ s[2] ^= h;
2451
+ s[3] ^= l;
2452
+ s[12] ^= h;
2453
+ s[13] ^= l;
2454
+ s[22] ^= h;
2455
+ s[23] ^= l;
2456
+ s[32] ^= h;
2457
+ s[33] ^= l;
2458
+ s[42] ^= h;
2459
+ s[43] ^= l;
2460
+ h = c2 ^ ((c6 << 1) | (c7 >>> 31));
2461
+ l = c3 ^ ((c7 << 1) | (c6 >>> 31));
2462
+ s[4] ^= h;
2463
+ s[5] ^= l;
2464
+ s[14] ^= h;
2465
+ s[15] ^= l;
2466
+ s[24] ^= h;
2467
+ s[25] ^= l;
2468
+ s[34] ^= h;
2469
+ s[35] ^= l;
2470
+ s[44] ^= h;
2471
+ s[45] ^= l;
2472
+ h = c4 ^ ((c8 << 1) | (c9 >>> 31));
2473
+ l = c5 ^ ((c9 << 1) | (c8 >>> 31));
2474
+ s[6] ^= h;
2475
+ s[7] ^= l;
2476
+ s[16] ^= h;
2477
+ s[17] ^= l;
2478
+ s[26] ^= h;
2479
+ s[27] ^= l;
2480
+ s[36] ^= h;
2481
+ s[37] ^= l;
2482
+ s[46] ^= h;
2483
+ s[47] ^= l;
2484
+ h = c6 ^ ((c0 << 1) | (c1 >>> 31));
2485
+ l = c7 ^ ((c1 << 1) | (c0 >>> 31));
2486
+ s[8] ^= h;
2487
+ s[9] ^= l;
2488
+ s[18] ^= h;
2489
+ s[19] ^= l;
2490
+ s[28] ^= h;
2491
+ s[29] ^= l;
2492
+ s[38] ^= h;
2493
+ s[39] ^= l;
2494
+ s[48] ^= h;
2495
+ s[49] ^= l;
2496
+
2497
+ b0 = s[0];
2498
+ b1 = s[1];
2499
+ b32 = (s[11] << 4) | (s[10] >>> 28);
2500
+ b33 = (s[10] << 4) | (s[11] >>> 28);
2501
+ b14 = (s[20] << 3) | (s[21] >>> 29);
2502
+ b15 = (s[21] << 3) | (s[20] >>> 29);
2503
+ b46 = (s[31] << 9) | (s[30] >>> 23);
2504
+ b47 = (s[30] << 9) | (s[31] >>> 23);
2505
+ b28 = (s[40] << 18) | (s[41] >>> 14);
2506
+ b29 = (s[41] << 18) | (s[40] >>> 14);
2507
+ b20 = (s[2] << 1) | (s[3] >>> 31);
2508
+ b21 = (s[3] << 1) | (s[2] >>> 31);
2509
+ b2 = (s[13] << 12) | (s[12] >>> 20);
2510
+ b3 = (s[12] << 12) | (s[13] >>> 20);
2511
+ b34 = (s[22] << 10) | (s[23] >>> 22);
2512
+ b35 = (s[23] << 10) | (s[22] >>> 22);
2513
+ b16 = (s[33] << 13) | (s[32] >>> 19);
2514
+ b17 = (s[32] << 13) | (s[33] >>> 19);
2515
+ b48 = (s[42] << 2) | (s[43] >>> 30);
2516
+ b49 = (s[43] << 2) | (s[42] >>> 30);
2517
+ b40 = (s[5] << 30) | (s[4] >>> 2);
2518
+ b41 = (s[4] << 30) | (s[5] >>> 2);
2519
+ b22 = (s[14] << 6) | (s[15] >>> 26);
2520
+ b23 = (s[15] << 6) | (s[14] >>> 26);
2521
+ b4 = (s[25] << 11) | (s[24] >>> 21);
2522
+ b5 = (s[24] << 11) | (s[25] >>> 21);
2523
+ b36 = (s[34] << 15) | (s[35] >>> 17);
2524
+ b37 = (s[35] << 15) | (s[34] >>> 17);
2525
+ b18 = (s[45] << 29) | (s[44] >>> 3);
2526
+ b19 = (s[44] << 29) | (s[45] >>> 3);
2527
+ b10 = (s[6] << 28) | (s[7] >>> 4);
2528
+ b11 = (s[7] << 28) | (s[6] >>> 4);
2529
+ b42 = (s[17] << 23) | (s[16] >>> 9);
2530
+ b43 = (s[16] << 23) | (s[17] >>> 9);
2531
+ b24 = (s[26] << 25) | (s[27] >>> 7);
2532
+ b25 = (s[27] << 25) | (s[26] >>> 7);
2533
+ b6 = (s[36] << 21) | (s[37] >>> 11);
2534
+ b7 = (s[37] << 21) | (s[36] >>> 11);
2535
+ b38 = (s[47] << 24) | (s[46] >>> 8);
2536
+ b39 = (s[46] << 24) | (s[47] >>> 8);
2537
+ b30 = (s[8] << 27) | (s[9] >>> 5);
2538
+ b31 = (s[9] << 27) | (s[8] >>> 5);
2539
+ b12 = (s[18] << 20) | (s[19] >>> 12);
2540
+ b13 = (s[19] << 20) | (s[18] >>> 12);
2541
+ b44 = (s[29] << 7) | (s[28] >>> 25);
2542
+ b45 = (s[28] << 7) | (s[29] >>> 25);
2543
+ b26 = (s[38] << 8) | (s[39] >>> 24);
2544
+ b27 = (s[39] << 8) | (s[38] >>> 24);
2545
+ b8 = (s[48] << 14) | (s[49] >>> 18);
2546
+ b9 = (s[49] << 14) | (s[48] >>> 18);
2547
+
2548
+ s[0] = b0 ^ (~b2 & b4);
2549
+ s[1] = b1 ^ (~b3 & b5);
2550
+ s[10] = b10 ^ (~b12 & b14);
2551
+ s[11] = b11 ^ (~b13 & b15);
2552
+ s[20] = b20 ^ (~b22 & b24);
2553
+ s[21] = b21 ^ (~b23 & b25);
2554
+ s[30] = b30 ^ (~b32 & b34);
2555
+ s[31] = b31 ^ (~b33 & b35);
2556
+ s[40] = b40 ^ (~b42 & b44);
2557
+ s[41] = b41 ^ (~b43 & b45);
2558
+ s[2] = b2 ^ (~b4 & b6);
2559
+ s[3] = b3 ^ (~b5 & b7);
2560
+ s[12] = b12 ^ (~b14 & b16);
2561
+ s[13] = b13 ^ (~b15 & b17);
2562
+ s[22] = b22 ^ (~b24 & b26);
2563
+ s[23] = b23 ^ (~b25 & b27);
2564
+ s[32] = b32 ^ (~b34 & b36);
2565
+ s[33] = b33 ^ (~b35 & b37);
2566
+ s[42] = b42 ^ (~b44 & b46);
2567
+ s[43] = b43 ^ (~b45 & b47);
2568
+ s[4] = b4 ^ (~b6 & b8);
2569
+ s[5] = b5 ^ (~b7 & b9);
2570
+ s[14] = b14 ^ (~b16 & b18);
2571
+ s[15] = b15 ^ (~b17 & b19);
2572
+ s[24] = b24 ^ (~b26 & b28);
2573
+ s[25] = b25 ^ (~b27 & b29);
2574
+ s[34] = b34 ^ (~b36 & b38);
2575
+ s[35] = b35 ^ (~b37 & b39);
2576
+ s[44] = b44 ^ (~b46 & b48);
2577
+ s[45] = b45 ^ (~b47 & b49);
2578
+ s[6] = b6 ^ (~b8 & b0);
2579
+ s[7] = b7 ^ (~b9 & b1);
2580
+ s[16] = b16 ^ (~b18 & b10);
2581
+ s[17] = b17 ^ (~b19 & b11);
2582
+ s[26] = b26 ^ (~b28 & b20);
2583
+ s[27] = b27 ^ (~b29 & b21);
2584
+ s[36] = b36 ^ (~b38 & b30);
2585
+ s[37] = b37 ^ (~b39 & b31);
2586
+ s[46] = b46 ^ (~b48 & b40);
2587
+ s[47] = b47 ^ (~b49 & b41);
2588
+ s[8] = b8 ^ (~b0 & b2);
2589
+ s[9] = b9 ^ (~b1 & b3);
2590
+ s[18] = b18 ^ (~b10 & b12);
2591
+ s[19] = b19 ^ (~b11 & b13);
2592
+ s[28] = b28 ^ (~b20 & b22);
2593
+ s[29] = b29 ^ (~b21 & b23);
2594
+ s[38] = b38 ^ (~b30 & b32);
2595
+ s[39] = b39 ^ (~b31 & b33);
2596
+ s[48] = b48 ^ (~b40 & b42);
2597
+ s[49] = b49 ^ (~b41 & b43);
2598
+
2599
+ s[0] ^= RC[n];
2600
+ s[1] ^= RC[n + 1];
2601
+ }
2602
+ };
2603
+
2604
+ if (COMMON_JS) {
2605
+ module.exports = methods;
2606
+ } else {
2607
+ for (i = 0; i < methodNames.length; ++i) {
2608
+ root[methodNames[i]] = methods[methodNames[i]];
2609
+ }
2610
+ }
2611
+ })();
2612
+ } (sha3$1));
2613
+
2614
+ var sha3Exports = sha3$1.exports;
2615
+ var sha3 = /*@__PURE__*/getDefaultExportFromCjs(sha3Exports);
2616
+
2617
+ const Symmetric = {
2618
+ keySize: 32,
2619
+ ivSize: 12,
2620
+ tagSize: 16,
2621
+ algorithm: { name: "AES-GCM", length: 128 }
2622
+ };
2623
+ const Asymmetric = {
2624
+ keySize: 32
2625
+ };
2626
+ const OneMillion = BigInt(1000000);
2627
+ const Version = 1;
2628
+
2629
+ const crypto = {
2630
+ node: nodeCrypto,
2631
+ web: typeof self === "object" && "crypto" in self ? self.crypto : undefined
2632
+ };
2633
+ function getSubtle() {
2634
+ if (crypto.web) {
2635
+ return crypto.web.subtle;
2636
+ }
2637
+ else if (crypto.node) {
2638
+ return crypto.node.webcrypto.subtle;
2639
+ }
2640
+ else {
2641
+ throw new Error("The environment doesn't have Crypto Subtle API (if in the browser, be sure to use to be in a secure context, ie, https)");
2642
+ }
2643
+ }
2644
+ const randomBytes = utils.randomBytes;
2645
+ const sha256 = utils.sha256;
2646
+ /**
2647
+ * Generate a new private key to be used for asymmetric encryption.
2648
+ *
2649
+ * Use {@link getPublicKey} to get the corresponding Public Key.
2650
+ */
2651
+ function generatePrivateKey() {
2652
+ return randomBytes(Asymmetric.keySize);
2653
+ }
2654
+ /**
2655
+ * Generate a new symmetric key to be used for symmetric encryption.
2656
+ */
2657
+ function generateSymmetricKey() {
2658
+ return randomBytes(Symmetric.keySize);
2659
+ }
2660
+ /**
2661
+ * Return the public key for the given private key, to be used for asymmetric
2662
+ * encryption.
2663
+ */
2664
+ const getPublicKey = getPublicKey$1;
2665
+ /**
2666
+ * ECDSA Sign a message with the given private key.
2667
+ *
2668
+ * @param message The message to sign, usually a hash.
2669
+ * @param privateKey The ECDSA private key to use to sign the message.
2670
+ *
2671
+ * @returns The signature and the recovery id concatenated.
2672
+ */
2673
+ async function sign(message, privateKey) {
2674
+ const [signature, recoveryId] = await sign$1(message, privateKey, {
2675
+ recovered: true,
2676
+ der: false
2677
+ });
2678
+ return concat([signature, new Uint8Array([recoveryId])], signature.length + 1);
2679
+ }
2680
+ function keccak256(input) {
2681
+ return new Uint8Array(sha3.keccak256.arrayBuffer(input));
2682
+ }
2683
+
2684
+ /**
2685
+ * HKDF as implemented in go-ethereum.
2686
+ */
2687
+ function kdf(secret, outputLength) {
2688
+ let ctr = 1;
2689
+ let written = 0;
2690
+ let willBeResult = Promise.resolve(new Uint8Array());
2691
+ while (written < outputLength) {
2692
+ const counters = new Uint8Array([ctr >> 24, ctr >> 16, ctr >> 8, ctr]);
2693
+ const countersSecret = concat([counters, secret], counters.length + secret.length);
2694
+ const willBeHashResult = sha256(countersSecret);
2695
+ willBeResult = willBeResult.then((result) => willBeHashResult.then((hashResult) => {
2696
+ const _hashResult = new Uint8Array(hashResult);
2697
+ return concat([result, _hashResult], result.length + _hashResult.length);
2698
+ }));
2699
+ written += 32;
2700
+ ctr += 1;
2701
+ }
2702
+ return willBeResult;
2703
+ }
2704
+ function aesCtrEncrypt(counter, key, data) {
2705
+ return getSubtle()
2706
+ .importKey("raw", key, "AES-CTR", false, ["encrypt"])
2707
+ .then((cryptoKey) => getSubtle().encrypt({ name: "AES-CTR", counter: counter, length: 128 }, cryptoKey, data))
2708
+ .then((bytes) => new Uint8Array(bytes));
2709
+ }
2710
+ function aesCtrDecrypt(counter, key, data) {
2711
+ return getSubtle()
2712
+ .importKey("raw", key, "AES-CTR", false, ["decrypt"])
2713
+ .then((cryptoKey) => getSubtle().decrypt({ name: "AES-CTR", counter: counter, length: 128 }, cryptoKey, data))
2714
+ .then((bytes) => new Uint8Array(bytes));
2715
+ }
2716
+ function hmacSha256Sign(key, msg) {
2717
+ const algorithm = { name: "HMAC", hash: { name: "SHA-256" } };
2718
+ return getSubtle()
2719
+ .importKey("raw", key, algorithm, false, ["sign"])
2720
+ .then((cryptoKey) => getSubtle().sign(algorithm, cryptoKey, msg))
2721
+ .then((bytes) => new Uint8Array(bytes));
2722
+ }
2723
+ function hmacSha256Verify(key, msg, sig) {
2724
+ const algorithm = { name: "HMAC", hash: { name: "SHA-256" } };
2725
+ const _key = getSubtle().importKey("raw", key, algorithm, false, ["verify"]);
2726
+ return _key.then((cryptoKey) => getSubtle().verify(algorithm, cryptoKey, sig, msg));
2727
+ }
2728
+ /**
2729
+ * Derive shared secret for given private and public keys.
2730
+ *
2731
+ * @param privateKeyA Sender's private key (32 bytes)
2732
+ * @param publicKeyB Recipient's public key (65 bytes)
2733
+ * @returns A promise that resolves with the derived shared secret (Px, 32 bytes)
2734
+ * @throws Error If arguments are invalid
2735
+ */
2736
+ function derive(privateKeyA, publicKeyB) {
2737
+ if (privateKeyA.length !== 32) {
2738
+ throw new Error(`Bad private key, it should be 32 bytes but it's actually ${privateKeyA.length} bytes long`);
2739
+ }
2740
+ else if (publicKeyB.length !== 65) {
2741
+ throw new Error(`Bad public key, it should be 65 bytes but it's actually ${publicKeyB.length} bytes long`);
2742
+ }
2743
+ else if (publicKeyB[0] !== 4) {
2744
+ throw new Error("Bad public key, a valid public key would begin with 4");
2745
+ }
2746
+ else {
2747
+ const px = getSharedSecret(privateKeyA, publicKeyB, true);
2748
+ // Remove the compression prefix
2749
+ return new Uint8Array(hexToBytes(px).slice(1));
2750
+ }
2751
+ }
2752
+ /**
2753
+ * Encrypt message for given recipient's public key.
2754
+ *
2755
+ * @param publicKeyTo Recipient's public key (65 bytes)
2756
+ * @param msg The message being encrypted
2757
+ * @return A promise that resolves with the ECIES structure serialized
2758
+ */
2759
+ async function encrypt$1(publicKeyTo, msg) {
2760
+ const ephemPrivateKey = randomBytes(32);
2761
+ const sharedPx = derive(ephemPrivateKey, publicKeyTo);
2762
+ const hash = await kdf(sharedPx, 32);
2763
+ const iv = randomBytes(16);
2764
+ const encryptionKey = hash.slice(0, 16);
2765
+ const cipherText = await aesCtrEncrypt(iv, encryptionKey, msg);
2766
+ const ivCipherText = concat([iv, cipherText], iv.length + cipherText.length);
2767
+ const macKey = await sha256(hash.slice(16));
2768
+ const hmac = await hmacSha256Sign(macKey, ivCipherText);
2769
+ const ephemPublicKey = getPublicKey$1(ephemPrivateKey, false);
2770
+ return concat([ephemPublicKey, ivCipherText, hmac], ephemPublicKey.length + ivCipherText.length + hmac.length);
2771
+ }
2772
+ const metaLength = 1 + 64 + 16 + 32;
2773
+ /**
2774
+ * Decrypt message using given private key.
2775
+ *
2776
+ * @param privateKey A 32-byte private key of recipient of the message
2777
+ * @param encrypted ECIES serialized structure (result of ECIES encryption)
2778
+ * @returns The clear text
2779
+ * @throws Error If decryption fails
2780
+ */
2781
+ async function decrypt$1(privateKey, encrypted) {
2782
+ if (encrypted.length <= metaLength) {
2783
+ throw new Error(`Invalid Ciphertext. Data is too small. It should ba at least ${metaLength} bytes`);
2784
+ }
2785
+ else if (encrypted[0] !== 4) {
2786
+ throw new Error(`Not a valid ciphertext. It should begin with 4 but actually begin with ${encrypted[0]}`);
2787
+ }
2788
+ else {
2789
+ // deserialize
2790
+ const ephemPublicKey = encrypted.slice(0, 65);
2791
+ const cipherTextLength = encrypted.length - metaLength;
2792
+ const iv = encrypted.slice(65, 65 + 16);
2793
+ const cipherAndIv = encrypted.slice(65, 65 + 16 + cipherTextLength);
2794
+ const ciphertext = cipherAndIv.slice(16);
2795
+ const msgMac = encrypted.slice(65 + 16 + cipherTextLength);
2796
+ // check HMAC
2797
+ const px = derive(privateKey, ephemPublicKey);
2798
+ const hash = await kdf(px, 32);
2799
+ const [encryptionKey, macKey] = await sha256(hash.slice(16)).then((macKey) => [hash.slice(0, 16), macKey]);
2800
+ if (!(await hmacSha256Verify(macKey, cipherAndIv, msgMac))) {
2801
+ throw new Error("Incorrect MAC");
2802
+ }
2803
+ return aesCtrDecrypt(iv, encryptionKey, ciphertext);
2804
+ }
2805
+ }
2806
+
2807
+ var ecies = /*#__PURE__*/Object.freeze({
2808
+ __proto__: null,
2809
+ decrypt: decrypt$1,
2810
+ encrypt: encrypt$1
2811
+ });
2812
+
2813
+ async function encrypt(iv, key, clearText) {
2814
+ return getSubtle()
2815
+ .importKey("raw", key, Symmetric.algorithm, false, ["encrypt"])
2816
+ .then((cryptoKey) => getSubtle().encrypt({ iv, ...Symmetric.algorithm }, cryptoKey, clearText))
2817
+ .then((cipher) => new Uint8Array(cipher));
2818
+ }
2819
+ async function decrypt(iv, key, cipherText) {
2820
+ return getSubtle()
2821
+ .importKey("raw", key, Symmetric.algorithm, false, ["decrypt"])
2822
+ .then((cryptoKey) => getSubtle().decrypt({ iv, ...Symmetric.algorithm }, cryptoKey, cipherText))
2823
+ .then((clear) => new Uint8Array(clear));
2824
+ }
2825
+ function generateIv() {
2826
+ return randomBytes(Symmetric.ivSize);
2827
+ }
2828
+
2829
+ var symmetric = /*#__PURE__*/Object.freeze({
2830
+ __proto__: null,
2831
+ decrypt: decrypt,
2832
+ encrypt: encrypt,
2833
+ generateIv: generateIv
2834
+ });
2835
+
2836
+ export { OneMillion as O, Symmetric as S, Version as V, _nodeResolve_empty as _, generateSymmetricKey as a, getPublicKey as b, getSubtle as c, sign as d, ecies as e, symmetric as f, generatePrivateKey as g, bases as h, getDefaultExportFromCjs as i, commonjsGlobal as j, keccak256 as k, getAugmentedNamespace as l, encrypt$1 as m, hexToBytes as n, decrypt$1 as o, generateIv as p, encrypt as q, randomBytes as r, sha256 as s, concat as t, decrypt as u, Signature as v, recoverPublicKey as w };