@leofcoin/peernet 0.18.7 → 1.0.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.
@@ -1,5 +1,2379 @@
1
- import { b as base58$1, i as index$1, a as index$2, c as index$3, d as index$4, e as createRIPEMD160, f as createHMAC, g as createSHA512, h as createKeccak } from './peernet-29c659a0.js';
2
- import './value-40634404.js';
1
+ import { K as KeyValue } from './value-157ab062.js';
2
+
3
+ if (!globalThis.DEBUG) {
4
+ if (globalThis.localStorage) globalThis.DEBUG = Boolean(globalThis.localStorage.getItem('DEBUG') === 'true');
5
+ }
6
+
7
+ globalThis.debug = text => {
8
+ if (globalThis.DEBUG) console.log('\x1b[34m\x1b[1m%s', text, '\x1b[0m'); // bright blue
9
+ };
10
+
11
+ class LittlePubSub {
12
+ subscribers = {};
13
+ verbose;
14
+ constructor(verbose = false) {
15
+ this.verbose = verbose;
16
+ }
17
+ #handleContext(handler, context) {
18
+ if (typeof context === 'undefined') {
19
+ context = handler;
20
+ }
21
+ return context;
22
+ }
23
+ hasSubscribers(event) {
24
+ return this.subscribers[event] ? true : false;
25
+ }
26
+ subscribe(event, handler, context) {
27
+ if (!this.hasSubscribers(event))
28
+ this.subscribers[event] = { handlers: [], value: undefined };
29
+ context = this.#handleContext(handler, context);
30
+ this.subscribers[event].handlers.push(handler.bind(context));
31
+ }
32
+ unsubscribe(event, handler, context) {
33
+ if (!this.hasSubscribers(event))
34
+ return;
35
+ context = this.#handleContext(handler, context);
36
+ const index = this.subscribers[event].handlers.indexOf(handler.bind(context));
37
+ this.subscribers[event].handlers.splice(index);
38
+ if (this.subscribers[event].handlers.length === 0)
39
+ delete this.subscribers[event];
40
+ }
41
+ publish(event, change) {
42
+ if (!this.hasSubscribers(event))
43
+ return;
44
+ if (this.verbose || this.subscribers[event].value !== change) {
45
+ this.subscribers[event].value = change;
46
+ this.subscribers[event].handlers.forEach((handler) => {
47
+ handler(change, this.subscribers[event].value);
48
+ });
49
+ }
50
+ }
51
+ once(event) {
52
+ return new Promise((resolve) => {
53
+ const cb = (value) => {
54
+ this.unsubscribe(event, cb);
55
+ resolve(value);
56
+ };
57
+ this.subscribe(event, cb);
58
+ });
59
+ }
60
+ }
61
+
62
+ // base-x encoding / decoding
63
+ // Copyright (c) 2018 base-x contributors
64
+ // Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)
65
+ // Distributed under the MIT software license, see the accompanying
66
+ // file LICENSE or http://www.opensource.org/licenses/mit-license.php.
67
+ const base$1 = (ALPHABET) => {
68
+ if (ALPHABET.length >= 255) {
69
+ throw new TypeError('Alphabet too long');
70
+ }
71
+ const BASE_MAP = new Uint8Array(256);
72
+ for (let j = 0; j < BASE_MAP.length; j++) {
73
+ BASE_MAP[j] = 255;
74
+ }
75
+ for (let i = 0; i < ALPHABET.length; i++) {
76
+ const x = ALPHABET.charAt(i);
77
+ const xc = x.charCodeAt(0);
78
+ if (BASE_MAP[xc] !== 255) {
79
+ throw new TypeError(x + ' is ambiguous');
80
+ }
81
+ BASE_MAP[xc] = i;
82
+ }
83
+ const BASE = ALPHABET.length;
84
+ const LEADER = ALPHABET.charAt(0);
85
+ const FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up
86
+ const iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up
87
+ const encode = (source) => {
88
+ if (source instanceof Uint8Array) ;
89
+ else if (ArrayBuffer.isView(source)) {
90
+ source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
91
+ }
92
+ else if (Array.isArray(source)) {
93
+ source = Uint8Array.from(source);
94
+ }
95
+ if (!(source instanceof Uint8Array)) {
96
+ throw new TypeError('Expected Uint8Array');
97
+ }
98
+ if (source.length === 0) {
99
+ return '';
100
+ }
101
+ // Skip & count leading zeroes.
102
+ let zeroes = 0;
103
+ let length = 0;
104
+ let pbegin = 0;
105
+ const pend = source.length;
106
+ while (pbegin !== pend && source[pbegin] === 0) {
107
+ pbegin++;
108
+ zeroes++;
109
+ }
110
+ // Allocate enough space in big-endian base58 representation.
111
+ const size = ((pend - pbegin) * iFACTOR + 1) >>> 0;
112
+ const b58 = new Uint8Array(size);
113
+ // Process the bytes.
114
+ while (pbegin !== pend) {
115
+ let carry = source[pbegin];
116
+ // Apply "b58 = b58 * 256 + ch".
117
+ let i = 0;
118
+ for (let it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {
119
+ carry += (256 * b58[it1]) >>> 0;
120
+ b58[it1] = (carry % BASE) >>> 0;
121
+ carry = (carry / BASE) >>> 0;
122
+ }
123
+ if (carry !== 0) {
124
+ throw new Error('Non-zero carry');
125
+ }
126
+ length = i;
127
+ pbegin++;
128
+ }
129
+ // Skip leading zeroes in base58 result.
130
+ let it2 = size - length;
131
+ while (it2 !== size && b58[it2] === 0) {
132
+ it2++;
133
+ }
134
+ // Translate the result into a string.
135
+ let str = LEADER.repeat(zeroes);
136
+ for (; it2 < size; ++it2) {
137
+ str += ALPHABET.charAt(b58[it2]);
138
+ }
139
+ return str;
140
+ };
141
+ const decodeUnsafe = (source) => {
142
+ if (typeof source !== 'string') {
143
+ throw new TypeError('Expected String');
144
+ }
145
+ if (source.length === 0) {
146
+ return new Uint8Array();
147
+ }
148
+ let psz = 0;
149
+ // Skip and count leading '1's.
150
+ let zeroes = 0;
151
+ let length = 0;
152
+ while (source[psz] === LEADER) {
153
+ zeroes++;
154
+ psz++;
155
+ }
156
+ // Allocate enough space in big-endian base256 representation.
157
+ const size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.
158
+ let b256 = new Uint8Array(size);
159
+ // Process the characters.
160
+ while (source[psz]) {
161
+ // Decode character
162
+ let carry = BASE_MAP[source.charCodeAt(psz)];
163
+ // Invalid character
164
+ if (carry === 255) {
165
+ return;
166
+ }
167
+ let i = 0;
168
+ for (let it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {
169
+ carry += (BASE * b256[it3]) >>> 0;
170
+ b256[it3] = (carry % 256) >>> 0;
171
+ carry = (carry / 256) >>> 0;
172
+ }
173
+ if (carry !== 0) {
174
+ throw new Error('Non-zero carry');
175
+ }
176
+ length = i;
177
+ psz++;
178
+ }
179
+ // Skip leading zeroes in b256.
180
+ let it4 = size - length;
181
+ while (it4 !== size && b256[it4] === 0) {
182
+ it4++;
183
+ }
184
+ let vch = new Uint8Array(zeroes + (size - it4));
185
+ let j = zeroes;
186
+ while (it4 !== size) {
187
+ vch[j++] = b256[it4++];
188
+ }
189
+ return vch;
190
+ };
191
+ const decode = (string) => {
192
+ const buffer = decodeUnsafe(string);
193
+ if (buffer) {
194
+ return buffer;
195
+ }
196
+ throw new Error('Non-base' + BASE + ' character');
197
+ };
198
+ return {
199
+ encode,
200
+ decodeUnsafe,
201
+ decode
202
+ };
203
+ };
204
+
205
+ const ALPHABET$3 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
206
+ const ALPHABET_HEX$1 = '0123456789ABCDEFGHIJKLMNOPQRSTUV';
207
+ const base32 = base$1(ALPHABET$3);
208
+ const base32Hex = base$1(ALPHABET_HEX$1);
209
+ const decode$9 = base32.decode;
210
+ const decodeHex$2 = base32Hex.decode;
211
+ const encode$8 = base32.encode;
212
+ const encodeHex$2 = base32Hex.encode;
213
+ const isBase32 = (string, hex = false) => {
214
+ try {
215
+ if (hex)
216
+ decodeHex$2(string);
217
+ else
218
+ decode$9(string);
219
+ return true;
220
+ }
221
+ catch (e) {
222
+ return false;
223
+ }
224
+ };
225
+ const isBase32Hex = (string) => {
226
+ return isBase32(string, true);
227
+ };
228
+ var index$9 = {
229
+ encode: encode$8,
230
+ decode: decode$9,
231
+ encodeHex: encodeHex$2,
232
+ decodeHex: decodeHex$2,
233
+ isBase32,
234
+ isBase32Hex
235
+ };
236
+
237
+ var ALPHABET$2 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
238
+ var ALPHABET_HEX = '0123456789ABCDEFGHJKLMNPQRSTUVabcdefghijklmnopqrstuv';
239
+ var base58 = base$1(ALPHABET$2);
240
+ var base58Hex = base$1(ALPHABET_HEX);
241
+ var encode$7 = base58.encode;
242
+ var decode$8 = base58.decode;
243
+ var encodeHex$1 = base58Hex.encode;
244
+ var decodeHex$1 = base58Hex.decode;
245
+ var isBase58 = function (string) {
246
+ try {
247
+ decode$8(string);
248
+ return true;
249
+ }
250
+ catch (e) {
251
+ return false;
252
+ }
253
+ };
254
+ var isBase58Hex = function (string) {
255
+ try {
256
+ decodeHex$1(string);
257
+ return true;
258
+ }
259
+ catch (e) {
260
+ return false;
261
+ }
262
+ };
263
+ var whatType = function (string) {
264
+ try {
265
+ decode$8(string);
266
+ return 'base58';
267
+ }
268
+ catch (e) {
269
+ try {
270
+ decodeHex$1(string);
271
+ return 'base58Hex';
272
+ }
273
+ catch (_a) {
274
+ return;
275
+ }
276
+ }
277
+ };
278
+ var base58$1 = { encode: encode$7, decode: decode$8, isBase58: isBase58, isBase58Hex: isBase58Hex, encodeHex: encodeHex$1, decodeHex: decodeHex$1, whatType: whatType };
279
+
280
+ const MSB$1 = 0x80;
281
+ const REST$1 = 0x7F;
282
+ const MSBALL = ~REST$1;
283
+ const INT = Math.pow(2, 31);
284
+ const encode$6 = (num, out, offset) => {
285
+ if (Number.MAX_SAFE_INTEGER && num > Number.MAX_SAFE_INTEGER) {
286
+ encode$6.bytes = 0;
287
+ throw new RangeError('Could not encode varint');
288
+ }
289
+ out = out || [];
290
+ offset = offset || 0;
291
+ const oldOffset = offset;
292
+ while (num >= INT) {
293
+ out[offset++] = (num & 0xFF) | MSB$1;
294
+ num /= 128;
295
+ }
296
+ while (num & MSBALL) {
297
+ out[offset++] = (num & 0xFF) | MSB$1;
298
+ num >>>= 7;
299
+ }
300
+ out[offset] = num | 0;
301
+ encode$6.bytes = offset - oldOffset + 1;
302
+ return out;
303
+ };
304
+
305
+ const MSB = 0x80;
306
+ const REST = 0x7F;
307
+ const decode$7 = (buf, offset) => {
308
+ offset = offset || 0;
309
+ const l = buf.length;
310
+ let counter = offset;
311
+ let result = 0;
312
+ let shift = 0;
313
+ let b;
314
+ do {
315
+ if (counter >= l || shift > 49) {
316
+ decode$7.bytes = 0;
317
+ throw new RangeError('Could not decode varint');
318
+ }
319
+ b = buf[counter++];
320
+ result += shift < 28
321
+ ? (b & REST) << shift
322
+ : (b & REST) * Math.pow(2, shift);
323
+ shift += 7;
324
+ } while (b >= MSB);
325
+ decode$7.bytes = counter - offset;
326
+ return result;
327
+ };
328
+
329
+ const N1 = Math.pow(2, 7);
330
+ const N2 = Math.pow(2, 14);
331
+ const N3 = Math.pow(2, 21);
332
+ const N4 = Math.pow(2, 28);
333
+ const N5 = Math.pow(2, 35);
334
+ const N6 = Math.pow(2, 42);
335
+ const N7 = Math.pow(2, 49);
336
+ const N8 = Math.pow(2, 56);
337
+ const N9 = Math.pow(2, 63);
338
+ var encodingLength = (value) => (value < N1 ? 1
339
+ : value < N2 ? 2
340
+ : value < N3 ? 3
341
+ : value < N4 ? 4
342
+ : value < N5 ? 5
343
+ : value < N6 ? 6
344
+ : value < N7 ? 7
345
+ : value < N8 ? 8
346
+ : value < N9 ? 9
347
+ : 10);
348
+
349
+ var index$8 = {
350
+ encode: encode$6,
351
+ decode: decode$7,
352
+ encodingLength
353
+ };
354
+
355
+ var index$7 = (input, prefix) => {
356
+ const encodedArray = [];
357
+ const length = input.reduce((total, current) => {
358
+ const encoded = index$8.encode(current.length);
359
+ encodedArray.push(encoded);
360
+ total += current.length + encoded.length;
361
+ return total;
362
+ }, 0);
363
+ const typedArray = new Uint8Array(prefix ? prefix.length + length : length);
364
+ let currentIndex = 0;
365
+ let index = 0;
366
+ if (prefix) {
367
+ typedArray.set(prefix);
368
+ currentIndex += prefix.length;
369
+ }
370
+ for (const source of input) {
371
+ typedArray.set(encodedArray[index], currentIndex);
372
+ currentIndex += encodedArray[index].length;
373
+ typedArray.set(source, currentIndex);
374
+ currentIndex += source.length;
375
+ index += 1;
376
+ }
377
+ return typedArray;
378
+ };
379
+
380
+ var index$6 = (typedArray, prefix) => {
381
+ const set = [];
382
+ if (prefix)
383
+ typedArray = typedArray.subarray(prefix.length);
384
+ const varintAndSub = (typedArray) => {
385
+ const length = index$8.decode(typedArray);
386
+ // remove length
387
+ typedArray = typedArray.subarray(index$8.decode.bytes);
388
+ // push value
389
+ set.push(typedArray.subarray(0, length));
390
+ // remove value
391
+ typedArray = typedArray.subarray(length);
392
+ if (typedArray.length !== 0)
393
+ return varintAndSub(typedArray);
394
+ return set;
395
+ };
396
+ return varintAndSub(typedArray);
397
+ };
398
+
399
+ const ALPHABET$1 = '0123456789ABCDEF';
400
+ const base16 = base$1(ALPHABET$1);
401
+ const decode$6 = base16.decode;
402
+ const encode$5 = base16.encode;
403
+ const isBase16 = (string) => {
404
+ try {
405
+ decode$6(string);
406
+ return true;
407
+ }
408
+ catch (e) {
409
+ return false;
410
+ }
411
+ };
412
+ var index$5 = {
413
+ encode: encode$5,
414
+ decode: decode$6,
415
+ isBase16
416
+ };
417
+
418
+ const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
419
+ const base64 = base$1(ALPHABET);
420
+ const decode$5 = base64.decode;
421
+ const encode$4 = base64.encode;
422
+ const isBase64 = (string) => {
423
+ try {
424
+ decode$5(string);
425
+ return true;
426
+ }
427
+ catch (e) {
428
+ return false;
429
+ }
430
+ };
431
+ var index$4 = {
432
+ encode: encode$4,
433
+ decode: decode$5,
434
+ isBase64
435
+ };
436
+
437
+ const isTypedArrayCompatible = (possibleUint8Array) => {
438
+ if (typeof possibleUint8Array === 'string') {
439
+ possibleUint8Array = possibleUint8Array.split(',').map(number => Number(number));
440
+ for (const number of possibleUint8Array) {
441
+ if (isNaN(number))
442
+ return false;
443
+ }
444
+ }
445
+ for (const number of possibleUint8Array) {
446
+ if (isNaN(number))
447
+ return false;
448
+ }
449
+ return true;
450
+ };
451
+ /**
452
+ * Returns a String as Uint8Array
453
+ * @param string string to encode to Uint8Array
454
+ * @returns Uint8Array
455
+ */
456
+ const fromString$1 = (string) => new TextEncoder().encode(string);
457
+ /**
458
+ * Returns a Uint8Array as String
459
+ * @param uint8Array Uint8Array to encode to String
460
+ * @returns String
461
+ */
462
+ const toString$1 = (uint8Array) => new TextDecoder().decode(uint8Array);
463
+ /**
464
+ * Returns a String as Uint8Array
465
+ * @param string string to encode to Uint8Array
466
+ * @returns Uint8Array
467
+ */
468
+ const fromUintArrayString = (string) => Uint8Array.from(string.split(',').map(string => Number(string)));
469
+ /**
470
+ * Returns a Uint8Array as String
471
+ * @param uint8Array Uint8Array to encode to String
472
+ * @returns String
473
+ */
474
+ const toUintArrayString = (uint8Array) => uint8Array.toString();
475
+ /**
476
+ * hexString -> uint8Array
477
+ * @param string hex encoded string
478
+ * @returns UintArray
479
+ */
480
+ const fromHex = (string) => Uint8Array.from(string.match(/.{1,2}/g).map((byte) => parseInt(byte, 16)));
481
+ /**
482
+ * uint8Array -> hexString
483
+ * @param bytes number[]
484
+ * @returns hexString
485
+ */
486
+ const toHex$1 = (bytes) => bytes.reduce((string, byte) => string + byte.toString(16).padStart(2, '0'), '');
487
+ /**
488
+ * number[] -> Uint8Array
489
+ * @param array number[]
490
+ * @returns Uint8Array
491
+ */
492
+ const fromArrayLike = (array) => Uint8Array.from(array);
493
+ /**
494
+ * Uint8Array -> number[]
495
+ * @param uint8Array Uint8Array
496
+ * @returns Uint8Array
497
+ */
498
+ const toArrayLike = (uint8Array) => [...uint8Array.values()];
499
+ const toBase64 = (uint8Array) => index$4.encode(uint8Array);
500
+ const fromBase64 = (string) => index$4.decode(string);
501
+ const toBase58 = (uint8Array) => base58$1.encode(uint8Array);
502
+ const fromBase58 = (string) => base58$1.decode(string);
503
+ const toBase32 = (uint8Array) => index$9.encode(uint8Array);
504
+ const fromBase32 = (string) => index$9.decode(string);
505
+ const toBase16 = (uint8Array) => index$5.encode(uint8Array);
506
+ const fromBase16 = (string) => index$5.decode(string);
507
+ let FormatInterface$2 = class FormatInterface {
508
+ encoded;
509
+ constructor(input) {
510
+ if (input) {
511
+ if (index$5.isBase16(input))
512
+ this.encoded = this.fromBase16(input);
513
+ else if (index$9.isBase32(input))
514
+ this.encoded = this.fromBase32(input);
515
+ else if (base58$1.isBase58(input))
516
+ this.encoded = this.fromBase58(input);
517
+ else if (index$4.isBase64(input))
518
+ this.encoded = this.fromBase64(input);
519
+ else if (typeof input === 'string') {
520
+ let isCompatible = isTypedArrayCompatible(input);
521
+ if (isCompatible)
522
+ this.encoded = fromUintArrayString(input);
523
+ else
524
+ this.encoded = this.fromString(input); // normal string
525
+ }
526
+ else if (typeof input === 'object')
527
+ this.encoded = this.fromObject(input);
528
+ else if (input instanceof Uint8Array)
529
+ this.encoded = input;
530
+ else if (Array.isArray(input) && isTypedArrayCompatible(input))
531
+ this.encoded = this.fromArrayLike(input);
532
+ }
533
+ }
534
+ /**
535
+ * Returns a String as Uint8Array
536
+ * @param string string to encode to Uint8Array
537
+ * @returns Uint8Array
538
+ */
539
+ fromString(string) {
540
+ return new TextEncoder().encode(string);
541
+ }
542
+ /**
543
+ * Returns a Uint8Array as String
544
+ * @param uint8Array Uint8Array to encode to String
545
+ * @returns String
546
+ */
547
+ toString(uint8Array) {
548
+ return new TextDecoder().decode(uint8Array);
549
+ }
550
+ /**
551
+ * Returns a String as Uint8Array
552
+ * @param string string to encode to Uint8Array
553
+ * @returns Uint8Array
554
+ */
555
+ fromUintArrayString(string) {
556
+ return Uint8Array.from(string.split(',').map(string => Number(string)));
557
+ }
558
+ /**
559
+ * Returns a Uint8Array as String
560
+ * @param uint8Array Uint8Array to encode to String
561
+ * @returns String
562
+ */
563
+ toUintArrayString(uint8Array) {
564
+ return uint8Array.toString();
565
+ }
566
+ /**
567
+ * hexString -> uint8Array
568
+ * @param string hex encoded string
569
+ * @returns UintArray
570
+ */
571
+ fromHex(string) {
572
+ return Uint8Array.from(string.match(/.{1,2}/g).map((byte) => parseInt(byte, 16)));
573
+ }
574
+ /**
575
+ * uint8Array -> hexString
576
+ * @param bytes number[]
577
+ * @returns hexString
578
+ */
579
+ toHex(bytes) {
580
+ return bytes.reduce((string, byte) => string + byte.toString(16).padStart(2, '0'), '');
581
+ }
582
+ /**
583
+ * number[] -> Uint8Array
584
+ * @param array number[]
585
+ * @returns Uint8Array
586
+ */
587
+ fromArrayLike(array) {
588
+ return Uint8Array.from(array);
589
+ }
590
+ /**
591
+ * Uint8Array -> number[]
592
+ * @param uint8Array Uint8Array
593
+ * @returns Uint8Array
594
+ */
595
+ toArrayLike(uint8Array) {
596
+ return [...uint8Array.values()];
597
+ }
598
+ fromObject(object) {
599
+ return new TextEncoder().encode(JSON.stringify(object));
600
+ }
601
+ toObject(uint8Array) {
602
+ return JSON.parse(new TextDecoder().decode(uint8Array));
603
+ }
604
+ toBase64(uint8Array) {
605
+ return index$4.encode(uint8Array);
606
+ }
607
+ fromBase64(string) {
608
+ return index$4.decode(string);
609
+ }
610
+ toBase58(uint8Array) {
611
+ return base58$1.encode(uint8Array);
612
+ }
613
+ fromBase58(string) {
614
+ return base58$1.decode(string);
615
+ }
616
+ toBase32(uint8Array) {
617
+ return index$9.encode(uint8Array);
618
+ }
619
+ fromBase32(string) {
620
+ return index$9.decode(string);
621
+ }
622
+ toBase16(uint8Array) {
623
+ return index$5.encode(uint8Array);
624
+ }
625
+ fromBase16(string) {
626
+ return index$5.decode(string);
627
+ }
628
+ };
629
+ var index$3 = {
630
+ fromString: fromString$1,
631
+ toString: toString$1,
632
+ fromHex,
633
+ toHex: toHex$1,
634
+ fromArrayLike,
635
+ toArrayLike,
636
+ fromUintArrayString,
637
+ toUintArrayString,
638
+ toBase64,
639
+ fromBase64,
640
+ toBase58,
641
+ fromBase58,
642
+ toBase32,
643
+ fromBase32,
644
+ toBase16,
645
+ fromBase16,
646
+ FormatInterface: FormatInterface$2
647
+ };
648
+
649
+ const { fromString, toString } = index$3;
650
+ const isJson = (type) => type === 'object' || 'array';
651
+ const isString = (type) => type === 'string';
652
+ const isNumber = (type) => type === 'number';
653
+ const isBoolean = (type) => type === 'boolean';
654
+ const isUint8Array$1 = (type) => type === 'uint8Array';
655
+ const tokenize = (key, value) => {
656
+ const optional = key.endsWith('?');
657
+ let type = value;
658
+ type = Array.isArray(type) ? 'array' : typeof type;
659
+ if (value instanceof Uint8Array)
660
+ type = 'uint8Array';
661
+ const parts = key.split('?');
662
+ const minimumLength = parts[2]?.includes('min') ? parts[2].split['min:'][1] : 0;
663
+ return { type, optional, key: parts[0], minimumLength };
664
+ };
665
+ const toType = (data) => {
666
+ // always return uint8Arrays as they are
667
+ if (data instanceof Uint8Array)
668
+ return data;
669
+ // returns the ArrayBuffer as a UintArray
670
+ if (data instanceof ArrayBuffer)
671
+ return new Uint8Array(data);
672
+ // returns the string as a UintArray
673
+ if (typeof data === 'string')
674
+ return new TextEncoder().encode(data);
675
+ // returns the object as a UintArray
676
+ if (typeof data === 'object')
677
+ return new TextEncoder().encode(JSON.stringify(data));
678
+ // returns the number as a UintArray
679
+ if (typeof data === 'number' || typeof data === 'boolean')
680
+ return new TextEncoder().encode(data.toString());
681
+ throw new Error(`unsuported type ${typeof data || data}`);
682
+ };
683
+ const encode$3 = (proto, input) => {
684
+ const keys = Object.keys(proto);
685
+ const values = Object.values(proto);
686
+ const set = [];
687
+ for (let i = 0; i < keys.length; i++) {
688
+ const token = tokenize(keys[i], values[i]);
689
+ const data = input[token.key];
690
+ if (!token.optional && data === undefined)
691
+ throw new Error(`missing required property: ${token.key}`);
692
+ if (token.type === 'array' && token.minimumLength > data.length || token.type === 'object' && token.minimumLength > Object.keys(data).length)
693
+ throw new Error(`minimumLength for ${token.key} is set to ${token.minimumLength} but got ${data.length}`);
694
+ // always push data to the set.
695
+ // when data is undefined push the default value of the proto
696
+ set.push(toType(data || values[i]));
697
+ }
698
+ return index$7(set);
699
+ };
700
+ const decode$4 = (proto, uint8Array) => {
701
+ let deconcated = index$6(uint8Array);
702
+ const output = {};
703
+ const keys = Object.keys(proto);
704
+ const values = Object.values(proto);
705
+ if (keys.length !== deconcated.length)
706
+ console.warn(`length mismatch: expected ${keys.length} got ${uint8Array.length}`);
707
+ for (let i = 0; i < keys.length; i++) {
708
+ const token = tokenize(keys[i], values[i]);
709
+ if (isUint8Array$1(token.type))
710
+ output[token.key] = deconcated[i];
711
+ else if (isString(token.type))
712
+ output[token.key] = toString(deconcated[i]);
713
+ else if (isBoolean(token.type))
714
+ output[token.key] = Boolean(new TextDecoder().decode(deconcated[i]));
715
+ else if (isNumber(token.type))
716
+ output[token.key] = Number(new TextDecoder().decode(deconcated[i]));
717
+ else if (isJson(token.type))
718
+ output[token.key] = JSON.parse(new TextDecoder().decode(deconcated[i]));
719
+ if (token.optional) {
720
+ if (!output[token.key] || output[token.key].length === 0)
721
+ delete output[token.key];
722
+ }
723
+ if (!token.optional && output[token.key] === undefined)
724
+ throw new Error(`missing required property: ${token.key}`);
725
+ }
726
+ return output;
727
+ };
728
+ var index$2 = {
729
+ encode: encode$3,
730
+ decode: decode$4
731
+ };
732
+
733
+ /*!
734
+ * hash-wasm (https://www.npmjs.com/package/hash-wasm)
735
+ * (c) Dani Biro
736
+ * @license MIT
737
+ */
738
+
739
+ /*! *****************************************************************************
740
+ Copyright (c) Microsoft Corporation.
741
+
742
+ Permission to use, copy, modify, and/or distribute this software for any
743
+ purpose with or without fee is hereby granted.
744
+
745
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
746
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
747
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
748
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
749
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
750
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
751
+ PERFORMANCE OF THIS SOFTWARE.
752
+ ***************************************************************************** */
753
+
754
+ function __awaiter(thisArg, _arguments, P, generator) {
755
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
756
+ return new (P || (P = Promise))(function (resolve, reject) {
757
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
758
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
759
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
760
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
761
+ });
762
+ }
763
+
764
+ class Mutex {
765
+ constructor() {
766
+ this.mutex = Promise.resolve();
767
+ }
768
+ lock() {
769
+ let begin = () => { };
770
+ this.mutex = this.mutex.then(() => new Promise(begin));
771
+ return new Promise((res) => {
772
+ begin = res;
773
+ });
774
+ }
775
+ dispatch(fn) {
776
+ return __awaiter(this, void 0, void 0, function* () {
777
+ const unlock = yield this.lock();
778
+ try {
779
+ return yield Promise.resolve(fn());
780
+ }
781
+ finally {
782
+ unlock();
783
+ }
784
+ });
785
+ }
786
+ }
787
+
788
+ /* eslint-disable import/prefer-default-export */
789
+ /* eslint-disable no-bitwise */
790
+ var _a;
791
+ function getGlobal() {
792
+ if (typeof globalThis !== 'undefined')
793
+ return globalThis;
794
+ // eslint-disable-next-line no-restricted-globals
795
+ if (typeof self !== 'undefined')
796
+ return self;
797
+ if (typeof window !== 'undefined')
798
+ return window;
799
+ return global;
800
+ }
801
+ const globalObject = getGlobal();
802
+ const nodeBuffer = (_a = globalObject.Buffer) !== null && _a !== void 0 ? _a : null;
803
+ const textEncoder = globalObject.TextEncoder ? new globalObject.TextEncoder() : null;
804
+ function hexCharCodesToInt(a, b) {
805
+ return (((a & 0xF) + ((a >> 6) | ((a >> 3) & 0x8))) << 4) | ((b & 0xF) + ((b >> 6) | ((b >> 3) & 0x8)));
806
+ }
807
+ function writeHexToUInt8(buf, str) {
808
+ const size = str.length >> 1;
809
+ for (let i = 0; i < size; i++) {
810
+ const index = i << 1;
811
+ buf[i] = hexCharCodesToInt(str.charCodeAt(index), str.charCodeAt(index + 1));
812
+ }
813
+ }
814
+ function hexStringEqualsUInt8(str, buf) {
815
+ if (str.length !== buf.length * 2) {
816
+ return false;
817
+ }
818
+ for (let i = 0; i < buf.length; i++) {
819
+ const strIndex = i << 1;
820
+ if (buf[i] !== hexCharCodesToInt(str.charCodeAt(strIndex), str.charCodeAt(strIndex + 1))) {
821
+ return false;
822
+ }
823
+ }
824
+ return true;
825
+ }
826
+ const alpha = 'a'.charCodeAt(0) - 10;
827
+ const digit = '0'.charCodeAt(0);
828
+ function getDigestHex(tmpBuffer, input, hashLength) {
829
+ let p = 0;
830
+ /* eslint-disable no-plusplus */
831
+ for (let i = 0; i < hashLength; i++) {
832
+ let nibble = input[i] >>> 4;
833
+ tmpBuffer[p++] = nibble > 9 ? nibble + alpha : nibble + digit;
834
+ nibble = input[i] & 0xF;
835
+ tmpBuffer[p++] = nibble > 9 ? nibble + alpha : nibble + digit;
836
+ }
837
+ /* eslint-enable no-plusplus */
838
+ return String.fromCharCode.apply(null, tmpBuffer);
839
+ }
840
+ const getUInt8Buffer = nodeBuffer !== null
841
+ ? (data) => {
842
+ if (typeof data === 'string') {
843
+ const buf = nodeBuffer.from(data, 'utf8');
844
+ return new Uint8Array(buf.buffer, buf.byteOffset, buf.length);
845
+ }
846
+ if (nodeBuffer.isBuffer(data)) {
847
+ return new Uint8Array(data.buffer, data.byteOffset, data.length);
848
+ }
849
+ if (ArrayBuffer.isView(data)) {
850
+ return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
851
+ }
852
+ throw new Error('Invalid data type!');
853
+ }
854
+ : (data) => {
855
+ if (typeof data === 'string') {
856
+ return textEncoder.encode(data);
857
+ }
858
+ if (ArrayBuffer.isView(data)) {
859
+ return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
860
+ }
861
+ throw new Error('Invalid data type!');
862
+ };
863
+ const base64Chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
864
+ const base64Lookup = new Uint8Array(256);
865
+ for (let i = 0; i < base64Chars.length; i++) {
866
+ base64Lookup[base64Chars.charCodeAt(i)] = i;
867
+ }
868
+ function getDecodeBase64Length(data) {
869
+ let bufferLength = Math.floor(data.length * 0.75);
870
+ const len = data.length;
871
+ if (data[len - 1] === '=') {
872
+ bufferLength -= 1;
873
+ if (data[len - 2] === '=') {
874
+ bufferLength -= 1;
875
+ }
876
+ }
877
+ return bufferLength;
878
+ }
879
+ function decodeBase64(data) {
880
+ const bufferLength = getDecodeBase64Length(data);
881
+ const len = data.length;
882
+ const bytes = new Uint8Array(bufferLength);
883
+ let p = 0;
884
+ for (let i = 0; i < len; i += 4) {
885
+ const encoded1 = base64Lookup[data.charCodeAt(i)];
886
+ const encoded2 = base64Lookup[data.charCodeAt(i + 1)];
887
+ const encoded3 = base64Lookup[data.charCodeAt(i + 2)];
888
+ const encoded4 = base64Lookup[data.charCodeAt(i + 3)];
889
+ bytes[p] = (encoded1 << 2) | (encoded2 >> 4);
890
+ p += 1;
891
+ bytes[p] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
892
+ p += 1;
893
+ bytes[p] = ((encoded3 & 3) << 6) | (encoded4 & 63);
894
+ p += 1;
895
+ }
896
+ return bytes;
897
+ }
898
+
899
+ const MAX_HEAP = 16 * 1024;
900
+ const WASM_FUNC_HASH_LENGTH = 4;
901
+ const wasmMutex = new Mutex();
902
+ const wasmModuleCache = new Map();
903
+ function WASMInterface(binary, hashLength) {
904
+ return __awaiter(this, void 0, void 0, function* () {
905
+ let wasmInstance = null;
906
+ let memoryView = null;
907
+ let initialized = false;
908
+ if (typeof WebAssembly === 'undefined') {
909
+ throw new Error('WebAssembly is not supported in this environment!');
910
+ }
911
+ const writeMemory = (data, offset = 0) => {
912
+ memoryView.set(data, offset);
913
+ };
914
+ const getMemory = () => memoryView;
915
+ const getExports = () => wasmInstance.exports;
916
+ const setMemorySize = (totalSize) => {
917
+ wasmInstance.exports.Hash_SetMemorySize(totalSize);
918
+ const arrayOffset = wasmInstance.exports.Hash_GetBuffer();
919
+ const memoryBuffer = wasmInstance.exports.memory.buffer;
920
+ memoryView = new Uint8Array(memoryBuffer, arrayOffset, totalSize);
921
+ };
922
+ const getStateSize = () => {
923
+ const view = new DataView(wasmInstance.exports.memory.buffer);
924
+ const stateSize = view.getUint32(wasmInstance.exports.STATE_SIZE, true);
925
+ return stateSize;
926
+ };
927
+ const loadWASMPromise = wasmMutex.dispatch(() => __awaiter(this, void 0, void 0, function* () {
928
+ if (!wasmModuleCache.has(binary.name)) {
929
+ const asm = decodeBase64(binary.data);
930
+ const promise = WebAssembly.compile(asm);
931
+ wasmModuleCache.set(binary.name, promise);
932
+ }
933
+ const module = yield wasmModuleCache.get(binary.name);
934
+ wasmInstance = yield WebAssembly.instantiate(module, {
935
+ // env: {
936
+ // emscripten_memcpy_big: (dest, src, num) => {
937
+ // const memoryBuffer = wasmInstance.exports.memory.buffer;
938
+ // const memView = new Uint8Array(memoryBuffer, 0);
939
+ // memView.set(memView.subarray(src, src + num), dest);
940
+ // },
941
+ // print_memory: (offset, len) => {
942
+ // const memoryBuffer = wasmInstance.exports.memory.buffer;
943
+ // const memView = new Uint8Array(memoryBuffer, 0);
944
+ // console.log('print_int32', memView.subarray(offset, offset + len));
945
+ // },
946
+ // },
947
+ });
948
+ // wasmInstance.exports._start();
949
+ }));
950
+ const setupInterface = () => __awaiter(this, void 0, void 0, function* () {
951
+ if (!wasmInstance) {
952
+ yield loadWASMPromise;
953
+ }
954
+ const arrayOffset = wasmInstance.exports.Hash_GetBuffer();
955
+ const memoryBuffer = wasmInstance.exports.memory.buffer;
956
+ memoryView = new Uint8Array(memoryBuffer, arrayOffset, MAX_HEAP);
957
+ });
958
+ const init = (bits = null) => {
959
+ initialized = true;
960
+ wasmInstance.exports.Hash_Init(bits);
961
+ };
962
+ const updateUInt8Array = (data) => {
963
+ let read = 0;
964
+ while (read < data.length) {
965
+ const chunk = data.subarray(read, read + MAX_HEAP);
966
+ read += chunk.length;
967
+ memoryView.set(chunk);
968
+ wasmInstance.exports.Hash_Update(chunk.length);
969
+ }
970
+ };
971
+ const update = (data) => {
972
+ if (!initialized) {
973
+ throw new Error('update() called before init()');
974
+ }
975
+ const Uint8Buffer = getUInt8Buffer(data);
976
+ updateUInt8Array(Uint8Buffer);
977
+ };
978
+ const digestChars = new Uint8Array(hashLength * 2);
979
+ const digest = (outputType, padding = null) => {
980
+ if (!initialized) {
981
+ throw new Error('digest() called before init()');
982
+ }
983
+ initialized = false;
984
+ wasmInstance.exports.Hash_Final(padding);
985
+ if (outputType === 'binary') {
986
+ // the data is copied to allow GC of the original memory object
987
+ return memoryView.slice(0, hashLength);
988
+ }
989
+ return getDigestHex(digestChars, memoryView, hashLength);
990
+ };
991
+ const save = () => {
992
+ if (!initialized) {
993
+ throw new Error('save() can only be called after init() and before digest()');
994
+ }
995
+ const stateOffset = wasmInstance.exports.Hash_GetState();
996
+ const stateLength = getStateSize();
997
+ const memoryBuffer = wasmInstance.exports.memory.buffer;
998
+ const internalState = new Uint8Array(memoryBuffer, stateOffset, stateLength);
999
+ // prefix is 4 bytes from SHA1 hash of the WASM binary
1000
+ // it is used to detect incompatible internal states between different versions of hash-wasm
1001
+ const prefixedState = new Uint8Array(WASM_FUNC_HASH_LENGTH + stateLength);
1002
+ writeHexToUInt8(prefixedState, binary.hash);
1003
+ prefixedState.set(internalState, WASM_FUNC_HASH_LENGTH);
1004
+ return prefixedState;
1005
+ };
1006
+ const load = (state) => {
1007
+ if (!(state instanceof Uint8Array)) {
1008
+ throw new Error('load() expects an Uint8Array generated by save()');
1009
+ }
1010
+ const stateOffset = wasmInstance.exports.Hash_GetState();
1011
+ const stateLength = getStateSize();
1012
+ const overallLength = WASM_FUNC_HASH_LENGTH + stateLength;
1013
+ const memoryBuffer = wasmInstance.exports.memory.buffer;
1014
+ if (state.length !== overallLength) {
1015
+ throw new Error(`Bad state length (expected ${overallLength} bytes, got ${state.length})`);
1016
+ }
1017
+ if (!hexStringEqualsUInt8(binary.hash, state.subarray(0, WASM_FUNC_HASH_LENGTH))) {
1018
+ throw new Error('This state was written by an incompatible hash implementation');
1019
+ }
1020
+ const internalState = state.subarray(WASM_FUNC_HASH_LENGTH);
1021
+ new Uint8Array(memoryBuffer, stateOffset, stateLength).set(internalState);
1022
+ initialized = true;
1023
+ };
1024
+ const isDataShort = (data) => {
1025
+ if (typeof data === 'string') {
1026
+ // worst case is 4 bytes / char
1027
+ return data.length < MAX_HEAP / 4;
1028
+ }
1029
+ return data.byteLength < MAX_HEAP;
1030
+ };
1031
+ let canSimplify = isDataShort;
1032
+ switch (binary.name) {
1033
+ case 'argon2':
1034
+ case 'scrypt':
1035
+ canSimplify = () => true;
1036
+ break;
1037
+ case 'blake2b':
1038
+ case 'blake2s':
1039
+ // if there is a key at blake2 then cannot simplify
1040
+ canSimplify = (data, initParam) => initParam <= 512 && isDataShort(data);
1041
+ break;
1042
+ case 'blake3':
1043
+ // if there is a key at blake3 then cannot simplify
1044
+ canSimplify = (data, initParam) => initParam === 0 && isDataShort(data);
1045
+ break;
1046
+ case 'xxhash64': // cannot simplify
1047
+ case 'xxhash3':
1048
+ case 'xxhash128':
1049
+ canSimplify = () => false;
1050
+ break;
1051
+ }
1052
+ // shorthand for (init + update + digest) for better performance
1053
+ const calculate = (data, initParam = null, digestParam = null) => {
1054
+ if (!canSimplify(data, initParam)) {
1055
+ init(initParam);
1056
+ update(data);
1057
+ return digest('hex', digestParam);
1058
+ }
1059
+ const buffer = getUInt8Buffer(data);
1060
+ memoryView.set(buffer);
1061
+ wasmInstance.exports.Hash_Calculate(buffer.length, initParam, digestParam);
1062
+ return getDigestHex(digestChars, memoryView, hashLength);
1063
+ };
1064
+ yield setupInterface();
1065
+ return {
1066
+ getMemory,
1067
+ writeMemory,
1068
+ getExports,
1069
+ setMemorySize,
1070
+ init,
1071
+ update,
1072
+ digest,
1073
+ save,
1074
+ load,
1075
+ calculate,
1076
+ hashLength,
1077
+ };
1078
+ });
1079
+ }
1080
+
1081
+ new Mutex();
1082
+
1083
+ new Mutex();
1084
+
1085
+ new Mutex();
1086
+
1087
+ new Mutex();
1088
+
1089
+ new Mutex();
1090
+
1091
+ new Mutex();
1092
+
1093
+ new Mutex();
1094
+
1095
+ new Mutex();
1096
+
1097
+ new Mutex();
1098
+
1099
+ var name$b = "sha3";
1100
+ var data$b = "AGFzbQEAAAABDwNgAAF/YAF/AGADf39/AAMIBwABAQIBAAIEBQFwAQEBBQQBAQICBg4CfwFBkI0FC38AQcAJCwdwCAZtZW1vcnkCAA5IYXNoX0dldEJ1ZmZlcgAACUhhc2hfSW5pdAABC0hhc2hfVXBkYXRlAAIKSGFzaF9GaW5hbAAEDUhhc2hfR2V0U3RhdGUABQ5IYXNoX0NhbGN1bGF0ZQAGClNUQVRFX1NJWkUDAQrLFwcFAEGACgvXAwBBAEIANwOAjQFBAEIANwP4jAFBAEIANwPwjAFBAEIANwPojAFBAEIANwPgjAFBAEIANwPYjAFBAEIANwPQjAFBAEIANwPIjAFBAEIANwPAjAFBAEIANwO4jAFBAEIANwOwjAFBAEIANwOojAFBAEIANwOgjAFBAEIANwOYjAFBAEIANwOQjAFBAEIANwOIjAFBAEIANwOAjAFBAEIANwP4iwFBAEIANwPwiwFBAEIANwPoiwFBAEIANwPgiwFBAEIANwPYiwFBAEIANwPQiwFBAEIANwPIiwFBAEIANwPAiwFBAEIANwO4iwFBAEIANwOwiwFBAEIANwOoiwFBAEIANwOgiwFBAEIANwOYiwFBAEIANwOQiwFBAEIANwOIiwFBAEIANwOAiwFBAEIANwP4igFBAEIANwPwigFBAEIANwPoigFBAEIANwPgigFBAEIANwPYigFBAEIANwPQigFBAEIANwPIigFBAEIANwPAigFBAEIANwO4igFBAEIANwOwigFBAEIANwOoigFBAEIANwOgigFBAEIANwOYigFBAEIANwOQigFBAE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ACACcjoAACABQceLAWoiACAALQAAQYABcjoAAEGAigFByIsBIAEQA0EAQYCAgIB4NgKIjQELAkAgA0ECdiIBRQ0AQQAhAANAIABBgApqIABBgIoBaigCADYCACAAQQRqIQAgAUF/aiIBDQALCwsLzAEBAEGACAvEAQEAAAAAAAAAgoAAAAAAAACKgAAAAAAAgACAAIAAAACAi4AAAAAAAAABAACAAAAAAIGAAIAAAACACYAAAAAAAICKAAAAAAAAAIgAAAAAAAAACYAAgAAAAAAKAACAAAAAAIuAAIAAAAAAiwAAAAAAAICJgAAAAAAAgAOAAAAAAACAAoAAAAAAAICAAAAAAAAAgAqAAAAAAAAACgAAgAAAAICBgACAAAAAgICAAAAAAACAAQAAgAAAAAAIgACAAAAAgJABAAA=";
1101
+ var hash$b = "ec266d91";
1102
+ var wasmJson$b = {
1103
+ name: name$b,
1104
+ data: data$b,
1105
+ hash: hash$b
1106
+ };
1107
+
1108
+ new Mutex();
1109
+
1110
+ new Mutex();
1111
+ function validateBits(bits) {
1112
+ if (![224, 256, 384, 512].includes(bits)) {
1113
+ return new Error('Invalid variant! Valid values: 224, 256, 384, 512');
1114
+ }
1115
+ return null;
1116
+ }
1117
+ /**
1118
+ * Creates a new Keccak hash instance
1119
+ * @param bits Number of output bits. Valid values: 224, 256, 384, 512
1120
+ */
1121
+ function createKeccak(bits = 512) {
1122
+ if (validateBits(bits)) {
1123
+ return Promise.reject(validateBits(bits));
1124
+ }
1125
+ const outputSize = bits / 8;
1126
+ return WASMInterface(wasmJson$b, outputSize).then((wasm) => {
1127
+ wasm.init(bits);
1128
+ const obj = {
1129
+ init: () => { wasm.init(bits); return obj; },
1130
+ update: (data) => { wasm.update(data); return obj; },
1131
+ digest: (outputType) => wasm.digest(outputType, 0x01),
1132
+ save: () => wasm.save(),
1133
+ load: (data) => { wasm.load(data); return obj; },
1134
+ blockSize: 200 - 2 * outputSize,
1135
+ digestSize: outputSize,
1136
+ };
1137
+ return obj;
1138
+ });
1139
+ }
1140
+
1141
+ new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CwEAQYAICwTQAAAA";
1147
+ var hash$9 = "a5d1ca7c";
1148
+ var wasmJson$9 = {
1149
+ name: name$9,
1150
+ data: data$9,
1151
+ hash: hash$9
1152
+ };
1153
+
1154
+ new Mutex();
1155
+
1156
+ new Mutex();
1157
+ /**
1158
+ * Creates a new SHA-2 (SHA-512) hash instance
1159
+ */
1160
+ function createSHA512() {
1161
+ return WASMInterface(wasmJson$9, 64).then((wasm) => {
1162
+ wasm.init(512);
1163
+ const obj = {
1164
+ init: () => { wasm.init(512); return obj; },
1165
+ update: (data) => { wasm.update(data); return obj; },
1166
+ digest: (outputType) => wasm.digest(outputType),
1167
+ save: () => wasm.save(),
1168
+ load: (data) => { wasm.load(data); return obj; },
1169
+ blockSize: 128,
1170
+ digestSize: 64,
1171
+ };
1172
+ return obj;
1173
+ });
1174
+ }
1175
+
1176
+ new Mutex();
1177
+
1178
+ new Mutex();
1179
+
1180
+ new Mutex();
1181
+
1182
+ new Mutex();
1183
+
1184
+ var name$4 = "ripemd160";
1185
+ var data$4 = "AGFzbQEAAAABEQRgAAF/YAAAYAF/AGACf38AAwkIAAECAwIBAAIEBQFwAQEBBQQBAQICBg4CfwFB4IkFC38AQcAICweDAQkGbWVtb3J5AgAOSGFzaF9HZXRCdWZmZXIAAAlIYXNoX0luaXQAARByaXBlbWQxNjBfdXBkYXRlAAMLSGFzaF9VcGRhdGUABApIYXNoX0ZpbmFsAAUNSGFzaF9HZXRTdGF0ZQAGDkhhc2hfQ2FsY3VsYXRlAAcKU1RBVEVfU0laRQMBCtAxCAUAQYAJCzoAQQBB8MPLnnw2ApiJAUEAQv6568XpjpWZEDcCkIkBQQBCgcaUupbx6uZvNwKIiQFBAEIANwKAiQELpiwBHn9BACAAKAIkIgEgACgCACICIAAoAhAiAyACIAAoAiwiBCAAKAIMIgUgACgCBCIGIAAoAjwiByACIAAoAjAiCCAHIAAoAggiCUEAKAKIiQEiCkEAKAKQiQEiC0EAKAKUiQEiDEF/c3JBACgCjIkBIg1za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kBEAIgASACayEBIAAgAmohAEEAIQILAkAgAUHAAEkNAANAIAAQAiAAQcAAaiEAIAFBQGoiAUE/Sw0ACwsgAUUNAEEAIQNBACEEA0AgAyACakGciQFqIAAgA2otAAA6AAAgASAEQQFqIgRB/wFxIgNLDQALCwsJAEGACSAAEAMLggEBAn8jAEEQayIAJAAgAEEAKAKAiQEiAUEDdDYCCCAAQQAoAoSJAUEDdCABQR12cjYCDEGACEE4QfgAIAFBP3EiAUE4SRsgAWsQAyAAQQhqQQgQA0EAQQAoAoiJATYCgAlBAEEAKQKMiQE3AoQJQQBBACkClIkBNwKMCSAAQRBqJAALBgBBgIkBC8EBAQF/IwBBEGsiASQAQQBB8MPLnnw2ApiJAUEAQv6568XpjpWZEDcCkIkBQQBCgcaUupbx6uZvNwKIiQFBAEIANwKAiQFBgAkgABADIAFBACgCgIkBIgBBA3Q2AgggAUEAKAKEiQFBA3QgAEEddnI2AgxBgAhBOEH4ACAAQT9xIgBBOEkbIABrEAMgAUEIakEIEANBAEEAKAKIiQE2AoAJQQBBACkCjIkBNwKECUEAQQApApSJATcCjAkgAUEQaiQACwtLAQBBgAgLRIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABcAAAA";
1186
+ var hash$4 = "42f1de39";
1187
+ var wasmJson$4 = {
1188
+ name: name$4,
1189
+ data: data$4,
1190
+ hash: hash$4
1191
+ };
1192
+
1193
+ new Mutex();
1194
+ /**
1195
+ * Creates a new RIPEMD-160 hash instance
1196
+ */
1197
+ function createRIPEMD160() {
1198
+ return WASMInterface(wasmJson$4, 20).then((wasm) => {
1199
+ wasm.init();
1200
+ const obj = {
1201
+ init: () => { wasm.init(); return obj; },
1202
+ update: (data) => { wasm.update(data); return obj; },
1203
+ digest: (outputType) => wasm.digest(outputType),
1204
+ save: () => wasm.save(),
1205
+ load: (data) => { wasm.load(data); return obj; },
1206
+ blockSize: 64,
1207
+ digestSize: 20,
1208
+ };
1209
+ return obj;
1210
+ });
1211
+ }
1212
+
1213
+ function calculateKeyBuffer(hasher, key) {
1214
+ const { blockSize } = hasher;
1215
+ const buf = getUInt8Buffer(key);
1216
+ if (buf.length > blockSize) {
1217
+ hasher.update(buf);
1218
+ const uintArr = hasher.digest('binary');
1219
+ hasher.init();
1220
+ return uintArr;
1221
+ }
1222
+ return new Uint8Array(buf.buffer, buf.byteOffset, buf.length);
1223
+ }
1224
+ function calculateHmac(hasher, key) {
1225
+ hasher.init();
1226
+ const { blockSize } = hasher;
1227
+ const keyBuf = calculateKeyBuffer(hasher, key);
1228
+ const keyBuffer = new Uint8Array(blockSize);
1229
+ keyBuffer.set(keyBuf);
1230
+ const opad = new Uint8Array(blockSize);
1231
+ for (let i = 0; i < blockSize; i++) {
1232
+ const v = keyBuffer[i];
1233
+ opad[i] = v ^ 0x5C;
1234
+ keyBuffer[i] = v ^ 0x36;
1235
+ }
1236
+ hasher.update(keyBuffer);
1237
+ const obj = {
1238
+ init: () => {
1239
+ hasher.init();
1240
+ hasher.update(keyBuffer);
1241
+ return obj;
1242
+ },
1243
+ update: (data) => {
1244
+ hasher.update(data);
1245
+ return obj;
1246
+ },
1247
+ digest: ((outputType) => {
1248
+ const uintArr = hasher.digest('binary');
1249
+ hasher.init();
1250
+ hasher.update(opad);
1251
+ hasher.update(uintArr);
1252
+ return hasher.digest(outputType);
1253
+ }),
1254
+ save: () => {
1255
+ throw new Error('save() not supported');
1256
+ },
1257
+ load: () => {
1258
+ throw new Error('load() not supported');
1259
+ },
1260
+ blockSize: hasher.blockSize,
1261
+ digestSize: hasher.digestSize,
1262
+ };
1263
+ return obj;
1264
+ }
1265
+ /**
1266
+ * Calculates HMAC hash
1267
+ * @param hash Hash algorithm to use. It has to be the return value of a function like createSHA1()
1268
+ * @param key Key (string, Buffer or TypedArray)
1269
+ */
1270
+ function createHMAC(hash, key) {
1271
+ if (!hash || !hash.then) {
1272
+ throw new Error('Invalid hash function is provided! Usage: createHMAC(createMD5(), "key").');
1273
+ }
1274
+ return hash.then((hasher) => calculateHmac(hasher, key));
1275
+ }
1276
+
1277
+ new Mutex();
1278
+
1279
+ new Mutex();
1280
+
1281
+ const blockchainCodecs = [
1282
+ {
1283
+ name: 'leofcoin-block',
1284
+ codec: '0x6c62',
1285
+ hashAlg: 'dbl-keccak-512',
1286
+ },
1287
+ {
1288
+ name: 'leofcoin-tx',
1289
+ codec: '0x6c74',
1290
+ hashAlg: 'dbl-keccak-512',
1291
+ },
1292
+ {
1293
+ name: 'leofcoin-itx',
1294
+ codec: '0x6c69',
1295
+ hashAlg: 'keccak-512',
1296
+ },
1297
+ {
1298
+ name: 'leofcoin-pr',
1299
+ codec: '0x6c70',
1300
+ hashAlg: 'keccak-256',
1301
+ },
1302
+ {
1303
+ name: 'contract-message',
1304
+ codec: '0x63636d',
1305
+ hashAlg: 'keccak-256'
1306
+ },
1307
+ {
1308
+ name: 'transaction-message',
1309
+ codec: '0x746d',
1310
+ hashAlg: 'keccak-256'
1311
+ },
1312
+ {
1313
+ name: 'block-message',
1314
+ codec: '0x626d',
1315
+ hashAlg: 'keccak-256'
1316
+ },
1317
+ {
1318
+ name: 'bw-message',
1319
+ codec: '0x62776d',
1320
+ hashAlg: 'keccak-256'
1321
+ },
1322
+ {
1323
+ name: 'bw-request-message',
1324
+ codec: '0x6277726d',
1325
+ hashAlg: 'keccak-256'
1326
+ },
1327
+ {
1328
+ name: 'validator-message',
1329
+ codec: '0x766d',
1330
+ hashAlg: 'keccak-256'
1331
+ }
1332
+ ];
1333
+
1334
+ const internalCodecs = [
1335
+ {
1336
+ name: 'disco-hash',
1337
+ codec: '0x30',
1338
+ hashAlg: 'dbl-keccak-256',
1339
+ },
1340
+ {
1341
+ name: 'peernet-peer-response',
1342
+ codec: '0x707072',
1343
+ hashAlg: 'keccak-256',
1344
+ },
1345
+ {
1346
+ name: 'peernet-peer',
1347
+ codec: '0x7070',
1348
+ hashAlg: 'keccak-256',
1349
+ },
1350
+ {
1351
+ name: 'peernet-dht',
1352
+ codec: '0x706468',
1353
+ hashAlg: 'keccak-256',
1354
+ },
1355
+ {
1356
+ name: 'peernet-dht-response',
1357
+ codec: '0x706472',
1358
+ hashAlg: 'keccak-256',
1359
+ },
1360
+ {
1361
+ name: 'peernet-data',
1362
+ codec: '0x706461',
1363
+ hashAlg: 'keccak-256',
1364
+ },
1365
+ {
1366
+ name: 'peernet-data-response',
1367
+ codec: '0x70646172',
1368
+ hashAlg: 'keccak-256',
1369
+ },
1370
+ {
1371
+ name: 'peernet-message',
1372
+ codec: '0x706d65',
1373
+ hashAlg: 'keccak-256',
1374
+ },
1375
+ {
1376
+ name: 'peernet-ps',
1377
+ codec: '707073',
1378
+ hashAlg: 'keccak-256',
1379
+ },
1380
+ {
1381
+ name: 'peernet-response',
1382
+ codec: '0x7072',
1383
+ hashAlg: 'keccak-256',
1384
+ },
1385
+ {
1386
+ name: 'peernet-request',
1387
+ codec: '0x707271',
1388
+ hashAlg: 'keccak-256',
1389
+ },
1390
+ {
1391
+ name: 'peernet-file',
1392
+ codec: '0x7066',
1393
+ hashAlg: 'keccak-256',
1394
+ },
1395
+ {
1396
+ name: 'peernet-file-response',
1397
+ codec: '0x706672',
1398
+ hashAlg: 'keccak-256',
1399
+ }
1400
+ ];
1401
+
1402
+ const codecs = [
1403
+ ...internalCodecs,
1404
+ ...blockchainCodecs,
1405
+ {
1406
+ name: 'chat-message',
1407
+ codec: '0x70636d',
1408
+ hashAlg: 'dbl-keccak-256',
1409
+ }
1410
+ ];
1411
+
1412
+ globalThis.peernetCodecs = globalThis.peernetCodecs || {};
1413
+ const addCodec = (codecInput) => {
1414
+ let { hashAlg, codec, name } = codecInput;
1415
+ if (!globalThis.peernetCodecs[name])
1416
+ globalThis.peernetCodecs[name] = {
1417
+ hashAlg,
1418
+ codec: typeof codec === 'string' ? parseInt(codec, 16) : codec
1419
+ };
1420
+ };
1421
+ const getCodec = (name) => {
1422
+ if (typeof name === 'number')
1423
+ return name;
1424
+ return getCodecByName(name).codec;
1425
+ };
1426
+ const getCodecName = (codec) => {
1427
+ return Object.keys(globalThis.peernetCodecs).reduce((p, c) => {
1428
+ const item = globalThis.peernetCodecs[c];
1429
+ if (item.codec === codec)
1430
+ return c;
1431
+ else
1432
+ return p;
1433
+ }, undefined);
1434
+ };
1435
+ const getCodecByName = (name) => globalThis.peernetCodecs[name];
1436
+ const getHashAlg = (name) => {
1437
+ if (typeof name === 'number')
1438
+ return getCodecByName(getCodecName(name)).hashAlg;
1439
+ return getCodecByName(name).hashAlg;
1440
+ };
1441
+ const isCodec = (codec) => {
1442
+ if (codec.codec !== undefined && codec.hashAlg)
1443
+ return true;
1444
+ return false;
1445
+ };
1446
+ const validateCodec = (codec) => {
1447
+ if (codec.codec === undefined ||
1448
+ codec.hashAlg === undefined ||
1449
+ codec.name === undefined)
1450
+ throw new Error(`invalid codecInput: ${codec}`);
1451
+ };
1452
+ for (const codec of codecs) {
1453
+ addCodec(codec);
1454
+ }
1455
+ var utils$1 = {
1456
+ isCodec,
1457
+ addCodec,
1458
+ getCodec,
1459
+ getHashAlg,
1460
+ getCodecName,
1461
+ validateCodec,
1462
+ codecs: globalThis.peernetCodecs
1463
+ };
1464
+
1465
+ /**
1466
+ * @param {string}
1467
+ */
1468
+ var isHex = (function (string) { return /^[A-F0-9]+$/i.test(string); });
1469
+
1470
+ let BasicInterface$1 = class BasicInterface {
1471
+ encoded;
1472
+ decoded;
1473
+ keys;
1474
+ name;
1475
+ #proto;
1476
+ set proto(value) {
1477
+ this.#proto = value;
1478
+ this.keys = Object.keys(value);
1479
+ }
1480
+ get proto() {
1481
+ return this.#proto;
1482
+ }
1483
+ decode(encoded) {
1484
+ encoded = encoded || this.encoded;
1485
+ return new Object();
1486
+ }
1487
+ encode(decoded) {
1488
+ decoded = decoded || this.decoded;
1489
+ return new Uint8Array();
1490
+ }
1491
+ // get Codec(): Codec {}
1492
+ protoEncode(data) {
1493
+ // check schema
1494
+ return index$2.encode(this.proto, data);
1495
+ }
1496
+ protoDecode(data) {
1497
+ // check schema
1498
+ return index$2.decode(this.proto, data);
1499
+ }
1500
+ isHex(string) {
1501
+ return isHex(string);
1502
+ }
1503
+ isBase32(string) {
1504
+ return index$9.isBase32(string);
1505
+ }
1506
+ isBase58(string) {
1507
+ return base58$1.isBase58(string);
1508
+ }
1509
+ fromBs32(encoded) {
1510
+ return this.decode(index$9.decode(encoded));
1511
+ }
1512
+ fromBs58(encoded) {
1513
+ return this.decode(fromBase58(encoded));
1514
+ }
1515
+ async toArray() {
1516
+ const array = [];
1517
+ for await (const value of this.encoded.values()) {
1518
+ array.push(value);
1519
+ }
1520
+ return array;
1521
+ }
1522
+ fromString(string) {
1523
+ const array = string.split(',');
1524
+ const arrayLike = array.map(string => Number(string));
1525
+ return this.decode(Uint8Array.from(arrayLike));
1526
+ }
1527
+ fromHex(string) {
1528
+ return this.decode(fromHex(string));
1529
+ }
1530
+ fromArray(array) {
1531
+ return this.decode(Uint8Array.from([...array]));
1532
+ }
1533
+ fromEncoded(encoded) {
1534
+ return this.decode(encoded);
1535
+ }
1536
+ toString() {
1537
+ if (!this.encoded)
1538
+ this.encode();
1539
+ return this.encoded.toString();
1540
+ }
1541
+ toHex() {
1542
+ if (!this.encoded)
1543
+ this.encode();
1544
+ return toHex$1(this.encoded.toString().split(',').map(number => Number(number)));
1545
+ }
1546
+ /**
1547
+ * @return {String} encoded
1548
+ */
1549
+ toBs32() {
1550
+ if (!this.encoded)
1551
+ this.encode();
1552
+ return toBase32(this.encoded);
1553
+ }
1554
+ /**
1555
+ * @return {String} encoded
1556
+ */
1557
+ toBs58() {
1558
+ if (!this.encoded)
1559
+ this.encode();
1560
+ return toBase58(this.encoded);
1561
+ }
1562
+ };
1563
+
1564
+ let Codec$1 = class Codec extends BasicInterface$1 {
1565
+ codecBuffer;
1566
+ codec;
1567
+ hashAlg;
1568
+ constructor(buffer) {
1569
+ super();
1570
+ if (buffer) {
1571
+ if (buffer instanceof Uint8Array) {
1572
+ const codec = index$8.decode(buffer);
1573
+ const name = this.getCodecName(codec);
1574
+ if (name) {
1575
+ this.name = name;
1576
+ this.encoded = buffer;
1577
+ this.decode(buffer);
1578
+ }
1579
+ else {
1580
+ this.encode(Number(new TextDecoder().decode(buffer)));
1581
+ }
1582
+ }
1583
+ else if (buffer instanceof ArrayBuffer) {
1584
+ const codec = index$8.decode(buffer);
1585
+ const name = this.getCodecName(codec);
1586
+ if (name) {
1587
+ this.name = name;
1588
+ this.decode(buffer);
1589
+ }
1590
+ else {
1591
+ this.encode(Number(new TextDecoder().decode(new Uint8Array(buffer))));
1592
+ }
1593
+ }
1594
+ else if (typeof buffer === 'string') {
1595
+ if (utils$1.getCodec(buffer))
1596
+ this.fromName(buffer);
1597
+ else if (this.isHex(buffer))
1598
+ this.fromHex(buffer);
1599
+ else if (this.isBase32(buffer))
1600
+ this.fromBs32(buffer);
1601
+ else if (this.isBase58(buffer))
1602
+ this.fromBs58(buffer);
1603
+ else
1604
+ this.fromString(buffer);
1605
+ }
1606
+ if (!isNaN(buffer))
1607
+ if (utils$1.getCodec(buffer))
1608
+ this.fromCodec(buffer);
1609
+ }
1610
+ }
1611
+ fromEncoded(encoded) {
1612
+ const codec = index$8.decode(encoded);
1613
+ const name = this.getCodecName(codec);
1614
+ this.name = name;
1615
+ this.encoded = encoded;
1616
+ return this.decode(encoded);
1617
+ }
1618
+ getCodec(name) {
1619
+ return utils$1.getCodec(name);
1620
+ }
1621
+ getCodecName(codec) {
1622
+ return utils$1.getCodecName(codec);
1623
+ }
1624
+ getHashAlg(name) {
1625
+ return utils$1.getHashAlg(name);
1626
+ }
1627
+ fromCodec(codec) {
1628
+ this.name = this.getCodecName(codec);
1629
+ this.hashAlg = this.getHashAlg(this.name);
1630
+ this.codec = this.getCodec(this.name);
1631
+ this.codecBuffer = index$8.encode(this.codec);
1632
+ }
1633
+ fromName(name) {
1634
+ const codec = this.getCodec(name);
1635
+ this.name = name;
1636
+ this.codec = codec;
1637
+ this.hashAlg = this.getHashAlg(name);
1638
+ this.codecBuffer = index$8.encode(this.codec);
1639
+ }
1640
+ decode(encoded) {
1641
+ encoded = encoded || this.encoded;
1642
+ const codec = index$8.decode(encoded);
1643
+ this.fromCodec(codec);
1644
+ return this.decoded;
1645
+ }
1646
+ encode(codec) {
1647
+ codec = codec || this.codec;
1648
+ this.encoded = index$8.encode(codec);
1649
+ return this.encoded;
1650
+ }
1651
+ };
1652
+
1653
+ let CodecHash$1 = class CodecHash extends BasicInterface$1 {
1654
+ constructor(buffer, options = {}) {
1655
+ super();
1656
+ if (options.name)
1657
+ this.name = options.name;
1658
+ else
1659
+ this.name = 'disco-hash';
1660
+ if (options.codecs)
1661
+ this.codecs = options.codecs;
1662
+ return this.init(buffer);
1663
+ }
1664
+ async init(uint8Array) {
1665
+ if (uint8Array) {
1666
+ if (uint8Array instanceof Uint8Array) {
1667
+ this.discoCodec = new Codec$1(uint8Array, this.codecs);
1668
+ const name = this.discoCodec.name;
1669
+ if (name) {
1670
+ this.name = name;
1671
+ this.decode(uint8Array);
1672
+ }
1673
+ else {
1674
+ await this.encode(uint8Array);
1675
+ }
1676
+ }
1677
+ if (typeof uint8Array === 'string') {
1678
+ if (this.isHex(uint8Array))
1679
+ await this.fromHex(uint8Array);
1680
+ if (this.isBase32(uint8Array))
1681
+ await this.fromBs32(uint8Array);
1682
+ else if (this.isBase58(uint8Array))
1683
+ await this.fromBs58(uint8Array);
1684
+ else
1685
+ throw new Error(`unsupported string ${uint8Array}`);
1686
+ }
1687
+ else if (typeof uint8Array === 'object')
1688
+ await this.fromJSON(uint8Array);
1689
+ }
1690
+ return this;
1691
+ }
1692
+ get prefix() {
1693
+ const length = this.length;
1694
+ const uint8Array = new Uint8Array(length.length + this.discoCodec.codecBuffer.length);
1695
+ uint8Array.set(length);
1696
+ uint8Array.set(this.discoCodec.codecBuffer, length.length);
1697
+ return uint8Array;
1698
+ }
1699
+ get length() {
1700
+ return index$8.encode(this.size);
1701
+ }
1702
+ get buffer() {
1703
+ return this.encoded;
1704
+ }
1705
+ get hash() {
1706
+ return this.encoded;
1707
+ }
1708
+ fromJSON(json) {
1709
+ return this.encode(Buffer.from(JSON.stringify(json)));
1710
+ }
1711
+ async encode(buffer, name) {
1712
+ if (!this.name && name)
1713
+ this.name = name;
1714
+ if (!buffer)
1715
+ buffer = this.buffer;
1716
+ this.discoCodec = new Codec$1(this.name, this.codecs);
1717
+ this.discoCodec.fromName(this.name);
1718
+ let hashAlg = this.discoCodec.hashAlg;
1719
+ const hashVariant = Number(hashAlg.split('-')[hashAlg.split('-').length - 1]);
1720
+ if (hashAlg.includes('dbl')) {
1721
+ hashAlg = hashAlg.replace('dbl-', '');
1722
+ const hasher = await createKeccak(hashVariant);
1723
+ await hasher.init();
1724
+ hasher.update(buffer);
1725
+ buffer = hasher.digest('binary');
1726
+ }
1727
+ const hasher = await createKeccak(hashVariant);
1728
+ await hasher.init();
1729
+ hasher.update(buffer);
1730
+ this.digest = hasher.digest('binary');
1731
+ this.size = this.digest.length;
1732
+ this.codec = this.discoCodec.encode();
1733
+ this.codec = this.discoCodec.codecBuffer;
1734
+ const uint8Array = new Uint8Array(this.digest.length + this.prefix.length);
1735
+ uint8Array.set(this.prefix);
1736
+ uint8Array.set(this.digest, this.prefix.length);
1737
+ this.encoded = uint8Array;
1738
+ return this.encoded;
1739
+ }
1740
+ async validate(buffer) {
1741
+ if (Buffer.isBuffer(buffer)) {
1742
+ const codec = index$8.decode(buffer);
1743
+ if (this.codecs[codec]) {
1744
+ this.decode(buffer);
1745
+ }
1746
+ else {
1747
+ await this.encode(buffer);
1748
+ }
1749
+ }
1750
+ if (typeof buffer === 'string') {
1751
+ if (this.isHex(buffer))
1752
+ this.fromHex(buffer);
1753
+ if (this.isBase32(buffer))
1754
+ this.fromBs32(buffer);
1755
+ }
1756
+ if (typeof buffer === 'object')
1757
+ this.fromJSON(buffer);
1758
+ }
1759
+ decode(buffer) {
1760
+ this.encoded = buffer;
1761
+ const codec = index$8.decode(buffer);
1762
+ this.discoCodec = new Codec$1(codec, this.codecs);
1763
+ // TODO: validate codec
1764
+ buffer = buffer.slice(index$8.decode.bytes);
1765
+ this.size = index$8.decode(buffer);
1766
+ this.digest = buffer.slice(index$8.decode.bytes);
1767
+ if (this.digest.length !== this.size) {
1768
+ throw new Error(`hash length inconsistent: 0x${this.encoded.toString('hex')}`);
1769
+ }
1770
+ // const discoCodec = new Codec(codec, this.codecs)
1771
+ this.name = this.discoCodec.name;
1772
+ this.size = this.digest.length;
1773
+ return {
1774
+ codec: this.codec,
1775
+ name: this.name,
1776
+ size: this.size,
1777
+ length: this.length,
1778
+ digest: this.digest,
1779
+ };
1780
+ }
1781
+ };
1782
+
1783
+ let FormatInterface$1 = class FormatInterface extends BasicInterface$1 {
1784
+ hashFormat;
1785
+ init(buffer) {
1786
+ if (buffer instanceof Uint8Array)
1787
+ this.fromUint8Array(buffer);
1788
+ else if (buffer instanceof ArrayBuffer)
1789
+ this.fromArrayBuffer(buffer);
1790
+ else if (buffer instanceof FormatInterface$1 && buffer?.name === this.name)
1791
+ return buffer;
1792
+ else if (typeof buffer === 'string') {
1793
+ if (this.isHex(buffer))
1794
+ this.fromHex(buffer);
1795
+ else if (this.isBase58(buffer))
1796
+ this.fromBs58(buffer);
1797
+ else if (this.isBase32(buffer))
1798
+ this.fromBs32(buffer);
1799
+ else
1800
+ this.fromString(buffer);
1801
+ }
1802
+ else {
1803
+ this.create(buffer);
1804
+ }
1805
+ return this;
1806
+ }
1807
+ hasCodec() {
1808
+ if (!this.encoded)
1809
+ return false;
1810
+ const codec = new Codec$1(this.encoded);
1811
+ if (codec.name)
1812
+ return true;
1813
+ }
1814
+ decode(encoded) {
1815
+ encoded = encoded || this.encoded;
1816
+ const codec = new Codec$1(this.encoded);
1817
+ if (codec.codecBuffer) {
1818
+ encoded = encoded.slice(codec.codecBuffer.length);
1819
+ this.name = codec.name;
1820
+ this.decoded = this.protoDecode(encoded);
1821
+ // try {
1822
+ // this.decoded = JSON.parse(this.decoded)
1823
+ // } catch {
1824
+ // }
1825
+ }
1826
+ else {
1827
+ throw new Error(`no codec found`);
1828
+ }
1829
+ return this.decoded;
1830
+ }
1831
+ encode(decoded) {
1832
+ let encoded;
1833
+ if (!decoded)
1834
+ decoded = this.decoded;
1835
+ const codec = new Codec$1(this.name);
1836
+ if (decoded instanceof Uint8Array)
1837
+ encoded = decoded;
1838
+ else
1839
+ encoded = this.protoEncode(decoded);
1840
+ if (codec.codecBuffer) {
1841
+ const uint8Array = new Uint8Array(encoded.length + codec.codecBuffer.length);
1842
+ uint8Array.set(codec.codecBuffer);
1843
+ uint8Array.set(encoded, codec.codecBuffer.length);
1844
+ this.encoded = uint8Array;
1845
+ }
1846
+ else {
1847
+ throw new Error(`invalid codec`);
1848
+ }
1849
+ return this.encoded;
1850
+ }
1851
+ /**
1852
+ * @param {Buffer|String|Object} buffer - data - The data needed to create the desired message
1853
+ * @param {Object} proto - {protoObject}
1854
+ * @param {Object} options - {hashFormat, name}
1855
+ */
1856
+ constructor(buffer, proto, options) {
1857
+ super();
1858
+ this.proto = proto;
1859
+ this.hashFormat = options?.hashFormat ? options.hashFormat : 'bs32';
1860
+ if (options?.name)
1861
+ this.name = options.name;
1862
+ this.init(buffer);
1863
+ }
1864
+ /**
1865
+ * @return {PeernetHash}
1866
+ */
1867
+ get peernetHash() {
1868
+ return new CodecHash$1(this.decoded, { name: this.name });
1869
+ }
1870
+ /**
1871
+ * @return {peernetHash}
1872
+ */
1873
+ async hash() {
1874
+ const upper = this.hashFormat.charAt(0).toUpperCase();
1875
+ const format = `${upper}${this.hashFormat.substring(1, this.hashFormat.length)}`;
1876
+ return (await this.peernetHash)[`to${format}`]();
1877
+ }
1878
+ fromUint8Array(buffer) {
1879
+ this.encoded = buffer;
1880
+ return this.hasCodec() ? this.decode() : this.create(JSON.parse(new TextDecoder().decode(this.encoded)));
1881
+ }
1882
+ fromArrayBuffer(buffer) {
1883
+ this.encoded = new Uint8Array(buffer, buffer.byteOffset, buffer.byteLength);
1884
+ return this.hasCodec() ? this.decode() : this.create(JSON.parse(new TextDecoder().decode(this.encoded)));
1885
+ }
1886
+ /**
1887
+ * @param {Object} data
1888
+ */
1889
+ create(data) {
1890
+ const decoded = {};
1891
+ if (this.keys?.length > 0) {
1892
+ for (const key of this.keys) {
1893
+ Object.defineProperties(decoded, {
1894
+ [key]: {
1895
+ enumerable: true,
1896
+ configurable: true,
1897
+ set: (value) => data[key],
1898
+ get: () => data[key]
1899
+ }
1900
+ });
1901
+ }
1902
+ this.decoded = decoded;
1903
+ return this.encode(decoded);
1904
+ }
1905
+ }
1906
+ };
1907
+ const FormatInterface = FormatInterface$1;
1908
+ const Codec = Codec$1;
1909
+
1910
+ const BufferToUint8Array = data => {
1911
+ if (data.type === 'Buffer') {
1912
+ data = new Uint8Array(data.data);
1913
+ }
1914
+ return data;
1915
+ };
1916
+ const protoFor = (message) => {
1917
+ const codec = new Codec(message);
1918
+ if (!codec.name)
1919
+ throw new Error('proto not found');
1920
+ const Proto = globalThis.peernet.protos[codec.name];
1921
+ if (!Proto)
1922
+ throw (new Error(`No proto defined for ${codec.name}`));
1923
+ return new Proto(message);
1924
+ };
1925
+ /**
1926
+ * wether or not a peernet daemon is active
1927
+ * @return {Boolean}
1928
+ */
1929
+ const hasDaemon = async () => {
1930
+ try {
1931
+ let response = await fetch('http://127.0.0.1:1000/api/version');
1932
+ response = await response.json();
1933
+ return Boolean(response.client === '@peernet/api/http');
1934
+ }
1935
+ catch (e) {
1936
+ return false;
1937
+ }
1938
+ };
1939
+ const https = () => {
1940
+ if (!globalThis.location)
1941
+ return false;
1942
+ return Boolean(globalThis.location.protocol === 'https:');
1943
+ };
1944
+ /**
1945
+ * Get current environment
1946
+ * @return {String} current environment [node, electron, browser]
1947
+ */
1948
+ const environment = () => {
1949
+ const _navigator = globalThis.navigator;
1950
+ if (!_navigator) {
1951
+ return 'node';
1952
+ }
1953
+ else if (_navigator && /electron/i.test(_navigator.userAgent)) {
1954
+ return 'electron';
1955
+ }
1956
+ else {
1957
+ return 'browser';
1958
+ }
1959
+ };
1960
+ /**
1961
+ * * Get current environment
1962
+ * @return {Object} result
1963
+ * @property {Boolean} reult.daemon whether or not daemon is running
1964
+ * @property {Boolean} reult.environment Current environment
1965
+ */
1966
+ const target = async () => {
1967
+ let daemon = false;
1968
+ if (!https())
1969
+ daemon = await hasDaemon();
1970
+ return { daemon, environment: environment() };
1971
+ };
1972
+
1973
+ class PeerDiscovery {
1974
+ constructor(id) {
1975
+ this.id = id;
1976
+ }
1977
+ _getPeerId(id) {
1978
+ if (!peernet.peerMap || peernet.peerMap && peernet.peerMap.size === 0)
1979
+ return false;
1980
+ for (const entry of [...peernet.peerMap.entries()]) {
1981
+ for (const _id of entry[1]) {
1982
+ if (_id === id)
1983
+ return entry[0];
1984
+ }
1985
+ }
1986
+ }
1987
+ async discover(peer) {
1988
+ let id = this._getPeerId(peer.id);
1989
+ if (id)
1990
+ return id;
1991
+ const data = await new peernet.protos['peernet-peer']({ id: this.id });
1992
+ const node = await peernet.prepareMessage(peer.id, data.encoded);
1993
+ let response = await peer.request(node.encoded);
1994
+ response = await protoFor(response);
1995
+ response = await new peernet.protos['peernet-peer-response'](response.decoded.data);
1996
+ id = response.decoded.id;
1997
+ if (id === this.id)
1998
+ return;
1999
+ if (!peernet.peerMap.has(id))
2000
+ peernet.peerMap.set(id, [peer.id]);
2001
+ else {
2002
+ const connections = peernet.peerMap.get(id);
2003
+ if (connections.indexOf(peer.id) === -1) {
2004
+ connections.push(peer.id);
2005
+ peernet.peerMap.set(peer.id, connections);
2006
+ }
2007
+ }
2008
+ return id;
2009
+ }
2010
+ async discoverHandler(message, peer) {
2011
+ const { id, proto } = message;
2012
+ // if (typeof message.data === 'string') message.data = Buffer.from(message.data)
2013
+ if (proto.name === 'peernet-peer') {
2014
+ const from = proto.decoded.id;
2015
+ if (from === this.id)
2016
+ return;
2017
+ if (!peernet.peerMap.has(from))
2018
+ peernet.peerMap.set(from, [peer.id]);
2019
+ else {
2020
+ const connections = peernet.peerMap.get(from);
2021
+ if (connections.indexOf(peer.id) === -1) {
2022
+ connections.push(peer.id);
2023
+ peernet.peerMap.set(from, connections);
2024
+ }
2025
+ }
2026
+ const data = await new peernet.protos['peernet-peer-response']({ id: this.id });
2027
+ const node = await peernet.prepareMessage(from, data.encoded);
2028
+ peer.write(Buffer.from(JSON.stringify({ id, data: node.encoded })));
2029
+ }
2030
+ else if (proto.name === 'peernet-peer-response') {
2031
+ const from = proto.decoded.id;
2032
+ if (from === this.id)
2033
+ return;
2034
+ if (!peernet.peerMap.has(from))
2035
+ peernet.peerMap.set(from, [peer.id]);
2036
+ else {
2037
+ const connections = peernet.peerMap.get(from);
2038
+ if (connections.indexOf(peer.id) === -1) {
2039
+ connections.push(peer.id);
2040
+ peernet.peerMap.set(from, connections);
2041
+ }
2042
+ }
2043
+ }
2044
+ }
2045
+ }
2046
+
2047
+ /**
2048
+ * Keep history of fetched address and ptr
2049
+ * @property {Object} address
2050
+ * @property {Object} ptr
2051
+ */
2052
+ const lastFetched = {
2053
+ address: {
2054
+ value: undefined,
2055
+ timestamp: 0,
2056
+ },
2057
+ ptr: {
2058
+ value: undefined,
2059
+ timestamp: 0,
2060
+ },
2061
+ };
2062
+ const getAddress = async () => {
2063
+ const { address } = lastFetched;
2064
+ const now = Math.round(new Date().getTime() / 1000);
2065
+ if (now - address.timestamp > 1200000) {
2066
+ address.value = await fetch('https://icanhazip.com/');
2067
+ address.value = await address.value.text();
2068
+ address.timestamp = Math.round(new Date().getTime() / 1000);
2069
+ lastFetched.address = address;
2070
+ }
2071
+ return address.value;
2072
+ };
2073
+ const degreesToRadians = (degrees) => {
2074
+ return degrees * Math.PI / 180;
2075
+ };
2076
+ const distanceInKmBetweenEarthCoordinates = (lat1, lon1, lat2, lon2) => {
2077
+ const earthRadiusKm = 6371;
2078
+ const dLat = degreesToRadians(lat2 - lat1);
2079
+ const dLon = degreesToRadians(lon2 - lon1);
2080
+ lat1 = degreesToRadians(lat1);
2081
+ lat2 = degreesToRadians(lat2);
2082
+ const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
2083
+ Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
2084
+ const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
2085
+ return earthRadiusKm * c;
2086
+ };
2087
+ class DhtEarth {
2088
+ /**
2089
+ *
2090
+ */
2091
+ constructor() {
2092
+ this.providerMap = new Map();
2093
+ }
2094
+ /**
2095
+ * @param {Object} address
2096
+ * @return {Object} {latitude: lat, longitude: lon}
2097
+ */
2098
+ async getCoordinates(address) {
2099
+ // const {address} = parseAddress(provider)
2100
+ const request = `https://whereis.leofcoin.org/?ip=${address}`;
2101
+ let response = await fetch(request);
2102
+ response = await response.json();
2103
+ const { lat, lon } = response;
2104
+ return { latitude: lat, longitude: lon };
2105
+ }
2106
+ /**
2107
+ * @param {Object} peer
2108
+ * @param {Object} provider
2109
+ * @return {Object} {provider, distance}
2110
+ */
2111
+ async getDistance(peer, provider) {
2112
+ const { latitude, longitude } = await this.getCoordinates(provider.address);
2113
+ return { provider, distance: distanceInKmBetweenEarthCoordinates(peer.latitude, peer.longitude, latitude, longitude) };
2114
+ }
2115
+ /**
2116
+ * @param {Array} providers
2117
+ * @return {Object} closestPeer
2118
+ */
2119
+ async closestPeer(providers) {
2120
+ let all = [];
2121
+ const address = await getAddress();
2122
+ const peerLoc = await this.getCoordinates(address);
2123
+ for (const provider of providers) {
2124
+ if (provider.address === '127.0.0.1')
2125
+ all.push({ provider, distance: 0 });
2126
+ else
2127
+ all.push(this.getDistance(peerLoc, provider));
2128
+ }
2129
+ all = await Promise.all(all);
2130
+ all = all.sort((previous, current) => previous.distance - current.distance);
2131
+ return all[0].provider;
2132
+ }
2133
+ /**
2134
+ * @param {String} hash
2135
+ * @return {Array} providers
2136
+ */
2137
+ providersFor(hash) {
2138
+ return this.providerMap.get(hash);
2139
+ }
2140
+ /**
2141
+ * @param {String} address
2142
+ * @param {String} hash
2143
+ * @return {Array} providers
2144
+ */
2145
+ async addProvider(address, hash) {
2146
+ let providers = [];
2147
+ if (this.providerMap.has(hash))
2148
+ providers = this.providerMap.get(hash);
2149
+ providers = new Set([...providers, address]);
2150
+ this.providerMap.set(hash, providers);
2151
+ return providers;
2152
+ }
2153
+ }
2154
+
2155
+ class MessageHandler {
2156
+ constructor(network) {
2157
+ this.network = network;
2158
+ }
2159
+ /**
2160
+ * hash and sign message
2161
+ *
2162
+ * @param {object} message
2163
+ * @param {Buffer} message.from peer id
2164
+ * @param {Buffer} message.to peer id
2165
+ * @param {string} message.data Peernet message
2166
+ * (PeernetMessage excluded) encoded as a string
2167
+ * @return message
2168
+ */
2169
+ async hashAndSignMessage(message) {
2170
+ let identity = await walletStore.get('identity');
2171
+ identity = JSON.parse(identity);
2172
+ if (!globalThis.MultiWallet) {
2173
+ const importee = await Promise.resolve().then(function () { return index; });
2174
+ globalThis.MultiWallet = importee.default;
2175
+ }
2176
+ const wallet = new MultiWallet(this.network);
2177
+ wallet.recover(identity.mnemonic);
2178
+ const hash = await message.hash();
2179
+ message.decoded.signature = wallet.sign(hash.subarray(0, 32));
2180
+ return message;
2181
+ }
2182
+ /**
2183
+ * @param {String} from - peer id
2184
+ * @param {String} to - peer id
2185
+ * @param {String|PeernetMessage} data - data encoded message string
2186
+ * or the messageNode itself
2187
+ */
2188
+ async prepareMessage(message) {
2189
+ if (message.keys.includes('signature')) {
2190
+ message = await this.hashAndSignMessage(message);
2191
+ }
2192
+ return message;
2193
+ }
2194
+ }
2195
+
2196
+ const dataHandler = async (message) => {
2197
+ if (!message)
2198
+ return;
2199
+ const { data, id, from } = message;
2200
+ const proto = await protoFor(data);
2201
+ peernet._protoHandler({ id, proto }, peernet.client.connections[from], from);
2202
+ };
2203
+
2204
+ const dhtError = (proto) => {
2205
+ const text = `Received proto ${proto.name} expected peernet-dht-response`;
2206
+ return new Error(`Routing error: ${text}`);
2207
+ };
2208
+ const nothingFoundError = (hash) => {
2209
+ return new Error(`nothing found for ${hash}`);
2210
+ };
2211
+
2212
+ // import base32 from '@vandeurenglenn/base32'
2213
+ // import base58 from '@vandeurenglenn/base58'
2214
+
2215
+ // export const encodings = {
2216
+ // base58,
2217
+ // base32
2218
+ // }
2219
+
2220
+ const encode$2 = (string, encoding = 'utf-8') => {
2221
+ if (typeof string === 'string') {
2222
+ let encoded;
2223
+
2224
+ // if (encodings[encoding]) encoded = encodings[encoding].encode(encoded)
2225
+ encoded = new TextEncoder().encode(string);
2226
+ return encoded
2227
+ }
2228
+ throw Error(`expected typeof String instead got ${string}`)
2229
+ };
2230
+
2231
+ const decode$3 = (uint8Array, encoding) => {
2232
+ if (uint8Array instanceof Uint8Array) {
2233
+ let decoded;
2234
+ // if (encodings[encoding]) decoded = encodings[encoding].decode(decoded)
2235
+ decoded = new TextDecoder().decode(uint8Array);
2236
+
2237
+ return decoded
2238
+ }
2239
+ throw Error(`expected typeof uint8Array instead got ${uint8Array}`)
2240
+ };
2241
+
2242
+ const pathSepS = '/';
2243
+ class KeyPath {
2244
+
2245
+ /**
2246
+ * @param {string | Uint8Array} input
2247
+ */
2248
+ constructor(input) {
2249
+ if (typeof input === 'string') {
2250
+ this.uint8Array = encode$2(input);
2251
+ } else if (input instanceof Uint8Array) {
2252
+ this.uint8Array = input;
2253
+ } else if (input instanceof KeyPath) {
2254
+ this.uint8Array = input.uint8Array;
2255
+ } else {
2256
+ throw new Error('Invalid keyPath, should be a String, Uint8Array or KeyPath')
2257
+ }
2258
+ }
2259
+
2260
+ isKeyPath() {
2261
+ return true
2262
+ }
2263
+
2264
+ /**
2265
+ * Convert to the string representation
2266
+ *
2267
+ * @param {import('uint8arrays/to-string').SupportedEncodings} [encoding='utf8'] - The encoding to use.
2268
+ * @returns {string}
2269
+ */
2270
+ toString(encoding = 'hex') {
2271
+ return decode$3(this.uint8Array)
2272
+ }
2273
+
2274
+ /**
2275
+ * Returns the `list` representation of this path.
2276
+ *
2277
+ * @returns string[]
2278
+ *
2279
+ * @example
2280
+ * ```js
2281
+ * new Key('/Comedy/MontyPython/Actor:JohnCleese').list()
2282
+ * // => ['Comedy', 'MontyPythong', 'Actor:JohnCleese']
2283
+ * ```
2284
+ */
2285
+ list() {
2286
+ return this.toString().split(pathSepS).slice(1)
2287
+ }
2288
+
2289
+ }
2290
+
2291
+ class LeofcoinStorage {
2292
+
2293
+ constructor(name = 'storage', root = '.leofcoin') {
2294
+ this.name = name;
2295
+ this.root = root;
2296
+ }
2297
+
2298
+ async init(name, root) {
2299
+ const importee = await import(globalThis.navigator ? './browser-store.js' : './store.js');
2300
+ const Store = importee.default;
2301
+ this.db = new Store(this.name, this.root);
2302
+ }
2303
+
2304
+ async get(key) {
2305
+ if (typeof key === 'object') return this.many('get', key);
2306
+ return this.db.get(new KeyPath(key))
2307
+ }
2308
+
2309
+ /**
2310
+ *
2311
+ * @param {*} key
2312
+ * @param {*} value
2313
+ * @returns Promise
2314
+ */
2315
+ put(key, value) {
2316
+ if (typeof key === 'object') return this.many('put', key);
2317
+ return this.db.put(new KeyPath(key), new KeyValue(value));
2318
+ }
2319
+
2320
+ async has(key) {
2321
+ if (typeof key === 'object') return this.many('has', key);
2322
+
2323
+ try {
2324
+ const has = await this.db.get(new KeyPath(key));
2325
+
2326
+ return Boolean(has);
2327
+ } catch (e) {
2328
+ return false
2329
+ }
2330
+ }
2331
+
2332
+ async delete(key) {
2333
+ return this.db.delete(new KeyPath(key))
2334
+ }
2335
+
2336
+ keys(limit = -1) {
2337
+ return this.db.keys(limit)
2338
+ }
2339
+
2340
+ async values(limit = -1) {
2341
+ return this.db.values(limit)
2342
+ }
2343
+
2344
+ async many(type, _value) {
2345
+ const jobs = [];
2346
+
2347
+ for (const key of Object.keys(_value)) {
2348
+ jobs.push(this[type](key, _value[key]));
2349
+ }
2350
+
2351
+ return Promise.all(jobs)
2352
+ }
2353
+
2354
+ async length() {
2355
+ const keys = await this.keys();
2356
+ return keys.length
2357
+ }
2358
+
2359
+ async size() {
2360
+ let size = 0;
2361
+ const query = await this.db.iterate();
2362
+ for await (const item of query) {
2363
+ size += item.value ? item.value.length : item[1].length;
2364
+ }
2365
+ return size
2366
+ }
2367
+
2368
+ async clear() {
2369
+ return this.db.clear()
2370
+ }
2371
+
2372
+ async iterate() {
2373
+ return this.db.iterate()
2374
+ }
2375
+
2376
+ }
3
2377
 
4
2378
  const randombytes = strength => crypto.getRandomValues(new Uint8Array(strength));
5
2379
 
@@ -193,7 +2567,7 @@ var base58check = { encode: encode$1, decode: decode$2, encodeHex, decodeHex, is
193
2567
 
194
2568
  const decode$1 = (multiWif, expectedVersion, expectedCodec) => {
195
2569
  const decoded = base58$1.decode(multiWif);
196
- let [version, codec, privateKey] = index$2(decoded);
2570
+ let [version, codec, privateKey] = index$6(decoded);
197
2571
  version = Number(new TextDecoder().decode(version));
198
2572
  codec = Number(new TextDecoder().decode(codec));
199
2573
  if (expectedVersion && version !== expectedVersion)
@@ -202,9 +2576,9 @@ const decode$1 = (multiWif, expectedVersion, expectedCodec) => {
202
2576
  throw new Error(`invalid codec: expected ${expectedCodec} but got ${codec}`);
203
2577
  return { version, codec, privateKey };
204
2578
  };
205
- var index = {
2579
+ var index$1 = {
206
2580
  encode: (version, codec, privateKey) => {
207
- return base58$1.encode(index$1([
2581
+ return base58$1.encode(index$7([
208
2582
  new TextEncoder().encode(version.toString()),
209
2583
  new TextEncoder().encode(codec.toString()),
210
2584
  privateKey
@@ -9799,253 +12173,55 @@ var elliptic$1 = {
9799
12173
 
9800
12174
  if (sigr.isZero() || sigs.isZero()) return 2
9801
12175
 
9802
- // Can throw `throw new Error('Unable to find sencond key candinate');`
9803
- let point;
9804
- try {
9805
- point = ec.recoverPubKey(msg32, sigObj, recid);
9806
- } catch (err) {
9807
- return 2
9808
- }
9809
-
9810
- savePublicKey(output, point);
9811
-
9812
- return 0
9813
- },
9814
-
9815
- ecdh (output, pubkey, seckey, data, hashfn, xbuf, ybuf) {
9816
- const pair = loadPublicKey(pubkey);
9817
- if (pair === null) return 1
9818
-
9819
- const scalar = new BN(seckey);
9820
- if (scalar.cmp(ecparams.n) >= 0 || scalar.isZero()) return 2
9821
-
9822
- const point = pair.getPublic().mul(scalar);
9823
-
9824
- if (hashfn === undefined) {
9825
- const data = point.encode(null, true);
9826
- const sha256 = ec.hash().update(data).digest();
9827
- for (let i = 0; i < 32; ++i) output[i] = sha256[i];
9828
- } else {
9829
- if (!xbuf) xbuf = new Uint8Array(32);
9830
- const x = point.getX().toArray('be', 32);
9831
- for (let i = 0; i < 32; ++i) xbuf[i] = x[i];
9832
-
9833
- if (!ybuf) ybuf = new Uint8Array(32);
9834
- const y = point.getY().toArray('be', 32);
9835
- for (let i = 0; i < 32; ++i) ybuf[i] = y[i];
9836
-
9837
- const hash = hashfn(xbuf, ybuf, data);
9838
-
9839
- const isValid = hash instanceof Uint8Array && hash.length === output.length;
9840
- if (!isValid) return 2
9841
-
9842
- output.set(hash);
9843
- }
9844
-
9845
- return 0
9846
- }
9847
- };
9848
-
9849
- var elliptic = lib(elliptic$1);
9850
-
9851
- const encode = (version, privateKey, compressed) => {
9852
- if (privateKey.length !== 32)
9853
- throw new TypeError(`Invalid privateKey length: expected 32 got ${privateKey.length}`);
9854
- const uint8Array = new Uint8Array(compressed ? 34 : 33);
9855
- uint8Array.set([Number(version)]);
9856
- uint8Array.set(privateKey, 1);
9857
- if (compressed) {
9858
- uint8Array.set([Number(version)], 33);
9859
- }
9860
- return base58check.encode(uint8Array);
9861
- };
9862
- const decode = async (wif, version) => {
9863
- wif = (await base58check.decode(wif)).data;
9864
- if (version && wif[0] !== version)
9865
- throw new Error('Invalid network version');
9866
- if (wif.length < 33 || wif.length > 34)
9867
- throw new Error('Invalid WIF length');
9868
- const comp = new TextEncoder().encode('1');
9869
- if (wif.length === 34 && wif[33] !== comp[0])
9870
- throw new Error('Invalid compression flag');
9871
- return {
9872
- version: wif[0],
9873
- privateKey: wif.subarray(1, 33),
9874
- compressed: wif.length === 33 ? false : true
9875
- };
9876
- };
9877
- var wif = { encode, decode };
9878
-
9879
- // see https://github.com/bitcoin/bips/blob/master/bip-0039/english.txt
9880
- var wordlist = ["abandon", "ability", "able", "about", "above", "absent", "absorb", "abstract", "absurd", "abuse", "access", "accident", "account", "accuse", "achieve", "acid", "acoustic", "acquire", "across", "act", "action", "actor", "actress", "actual", "adapt", "add", "addict", "address", "adjust", "admit", "adult", "advance", "advice", "aerobic", "affair", "afford", "afraid", "again", "age", "agent", "agree", "ahead", "aim", "air", "airport", "aisle", "alarm", "album", "alcohol", "alert", "alien", "all", "alley", "allow", "almost", "alone", "alpha", "already", "also", "alter", "always", "amateur", "amazing", "among", "amount", "amused", "analyst", "anchor", "ancient", "anger", "angle", "angry", "animal", "ankle", "announce", "annual", "another", "answer", "antenna", "antique", "anxiety", "any", "apart", "apology", "appear", "apple", "approve", "april", "arch", "arctic", "area", "arena", "argue", "arm", "armed", "armor", "army", "around", "arrange", "arrest", "arrive", "arrow", "art", "artefact", "artist", "artwork", "ask", "aspect", "assault", "asset", "assist", "assume", "asthma", "athlete", "atom", "attack", "attend", "attitude", "attract", "auction", "audit", "august", "aunt", "author", "auto", "autumn", "average", "avocado", "avoid", "awake", "aware", "away", "awesome", "awful", "awkward", "axis", "baby", "bachelor", "bacon", "badge", "bag", "balance", "balcony", "ball", "bamboo", "banana", "banner", "bar", "barely", "bargain", "barrel", "base", "basic", "basket", "battle", "beach", "bean", "beauty", "because", "become", "beef", "before", "begin", "behave", "behind", "believe", "below", "belt", "bench", "benefit", "best", "betray", "better", "between", "beyond", "bicycle", "bid", "bike", "bind", "biology", "bird", "birth", "bitter", "black", "blade", "blame", "blanket", "blast", "bleak", "bless", "blind", "blood", "blossom", "blouse", "blue", "blur", "blush", "board", "boat", "body", "boil", "bomb", "bone", "bonus", "book", "boost", "border", "boring", "borrow", "boss", "bottom", "bounce", "box", "boy", "bracket", "brain", "brand", "brass", "brave", "bread", "breeze", "brick", "bridge", "brief", "bright", "bring", "brisk", "broccoli", "broken", "bronze", "broom", "brother", "brown", "brush", "bubble", "buddy", "budget", "buffalo", "build", "bulb", "bulk", "bullet", "bundle", "bunker", "burden", "burger", "burst", "bus", "business", "busy", "butter", "buyer", "buzz", "cabbage", "cabin", "cable", "cactus", "cage", "cake", "call", "calm", "camera", "camp", "can", "canal", "cancel", "candy", "cannon", "canoe", "canvas", "canyon", "capable", "capital", "captain", "car", "carbon", "card", "cargo", "carpet", "carry", "cart", "case", "cash", "casino", "castle", "casual", "cat", "catalog", "catch", "category", "cattle", "caught", "cause", "caution", "cave", "ceiling", "celery", "cement", "census", "century", "cereal", "certain", "chair", "chalk", "champion", "change", "chaos", "chapter", "charge", "chase", "chat", "cheap", "check", "cheese", "chef", "cherry", "chest", "chicken", "chief", "child", "chimney", "choice", "choose", "chronic", "chuckle", "chunk", "churn", "cigar", "cinnamon", "circle", "citizen", "city", "civil", "claim", "clap", "clarify", "claw", "clay", "clean", "clerk", "clever", "click", "client", "cliff", "climb", "clinic", "clip", "clock", "clog", "close", "cloth", "cloud", "clown", "club", "clump", "cluster", "clutch", "coach", "coast", "coconut", "code", "coffee", "coil", "coin", "collect", "color", "column", "combine", "come", "comfort", "comic", "common", "company", "concert", "conduct", "confirm", "congress", "connect", "consider", "control", "convince", "cook", "cool", "copper", "copy", "coral", "core", "corn", "correct", "cost", "cotton", "couch", "country", "couple", "course", "cousin", "cover", "coyote", "crack", "cradle", "craft", "cram", "crane", "crash", "crater", "crawl", "crazy", "cream", "credit", "creek", "crew", "cricket", "crime", "crisp", "critic", "crop", "cross", "crouch", "crowd", "crucial", "cruel", "cruise", "crumble", "crunch", "crush", "cry", "crystal", "cube", "culture", "cup", "cupboard", "curious", "current", "curtain", "curve", "cushion", "custom", "cute", "cycle", "dad", "damage", "damp", "dance", "danger", "daring", "dash", "daughter", "dawn", "day", "deal", "debate", "debris", "decade", "december", "decide", "decline", "decorate", "decrease", "deer", "defense", "define", "defy", "degree", "delay", "deliver", "demand", "demise", "denial", "dentist", "deny", "depart", "depend", "deposit", "depth", "deputy", "derive", "describe", "desert", "design", "desk", "despair", "destroy", "detail", "detect", "develop", "device", "devote", "diagram", "dial", "diamond", "diary", "dice", "diesel", "diet", "differ", "digital", "dignity", "dilemma", "dinner", "dinosaur", "direct", "dirt", "disagree", "discover", "disease", "dish", "dismiss", "disorder", "display", "distance", "divert", "divide", "divorce", "dizzy", "doctor", "document", "dog", "doll", "dolphin", "domain", "donate", "donkey", "donor", "door", "dose", "double", "dove", "draft", "dragon", "drama", "drastic", "draw", "dream", "dress", "drift", "drill", "drink", "drip", "drive", "drop", "drum", "dry", "duck", "dumb", "dune", "during", "dust", "dutch", "duty", "dwarf", "dynamic", "eager", "eagle", "early", "earn", "earth", "easily", "east", "easy", "echo", "ecology", "economy", "edge", "edit", "educate", "effort", "egg", "eight", "either", "elbow", "elder", "electric", "elegant", "element", "elephant", "elevator", "elite", "else", "embark", "embody", "embrace", "emerge", "emotion", "employ", "empower", "empty", "enable", "enact", "end", "endless", "endorse", "enemy", "energy", "enforce", "engage", "engine", "enhance", "enjoy", "enlist", "enough", "enrich", "enroll", "ensure", "enter", "entire", "entry", "envelope", "episode", "equal", "equip", "era", "erase", "erode", "erosion", "error", "erupt", "escape", "essay", "essence", "estate", "eternal", "ethics", "evidence", "evil", "evoke", "evolve", "exact", "example", "excess", "exchange", "excite", "exclude", "excuse", "execute", "exercise", "exhaust", "exhibit", "exile", "exist", "exit", "exotic", "expand", "expect", "expire", "explain", "expose", "express", "extend", "extra", "eye", "eyebrow", "fabric", "face", "faculty", "fade", "faint", "faith", "fall", "false", "fame", "family", "famous", "fan", "fancy", "fantasy", "farm", "fashion", "fat", "fatal", "father", "fatigue", "fault", "favorite", "feature", "february", "federal", "fee", "feed", "feel", "female", "fence", "festival", "fetch", "fever", "few", "fiber", "fiction", "field", "figure", "file", "film", "filter", "final", "find", "fine", "finger", "finish", "fire", "firm", "first", "fiscal", "fish", "fit", "fitness", "fix", "flag", "flame", "flash", "flat", "flavor", "flee", "flight", "flip", "float", "flock", "floor", "flower", "fluid", "flush", "fly", "foam", "focus", "fog", "foil", "fold", "follow", "food", "foot", "force", "forest", "forget", "fork", "fortune", "forum", "forward", "fossil", "foster", "found", "fox", "fragile", "frame", "frequent", "fresh", "friend", "fringe", "frog", "front", "frost", "frown", "frozen", "fruit", "fuel", "fun", "funny", "furnace", "fury", "future", "gadget", "gain", "galaxy", "gallery", "game", "gap", "garage", "garbage", "garden", "garlic", "garment", "gas", "gasp", "gate", "gather", "gauge", "gaze", "general", "genius", "genre", "gentle", "genuine", "gesture", "ghost", "giant", "gift", "giggle", "ginger", "giraffe", "girl", "give", "glad", "glance", "glare", "glass", "glide", "glimpse", "globe", "gloom", "glory", "glove", "glow", "glue", "goat", "goddess", "gold", "good", "goose", "gorilla", "gospel", "gossip", "govern", "gown", "grab", "grace", "grain", "grant", "grape", "grass", "gravity", "great", "green", "grid", "grief", "grit", "grocery", "group", "grow", "grunt", "guard", "guess", "guide", "guilt", "guitar", "gun", "gym", "habit", "hair", "half", "hammer", "hamster", "hand", "happy", "harbor", "hard", "harsh", "harvest", "hat", "have", "hawk", "hazard", "head", "health", "heart", "heavy", "hedgehog", "height", "hello", "helmet", "help", "hen", "hero", "hidden", "high", "hill", "hint", "hip", "hire", "history", "hobby", "hockey", "hold", "hole", "holiday", "hollow", "home", "honey", "hood", "hope", "horn", "horror", "horse", "hospital", "host", "hotel", "hour", "hover", "hub", "huge", "human", "humble", "humor", "hundred", "hungry", "hunt", "hurdle", "hurry", "hurt", "husband", "hybrid", "ice", "icon", "idea", "identify", "idle", "ignore", "ill", "illegal", "illness", "image", "imitate", "immense", "immune", "impact", "impose", "improve", "impulse", "inch", "include", "income", "increase", "index", "indicate", "indoor", "industry", "infant", "inflict", "inform", "inhale", "inherit", "initial", "inject", "injury", "inmate", "inner", "innocent", "input", "inquiry", "insane", "insect", "inside", "inspire", "install", "intact", "interest", "into", "invest", "invite", "involve", "iron", "island", "isolate", "issue", "item", "ivory", "jacket", "jaguar", "jar", "jazz", "jealous", "jeans", "jelly", "jewel", "job", "join", "joke", "journey", "joy", "judge", "juice", "jump", "jungle", "junior", "junk", "just", "kangaroo", "keen", "keep", "ketchup", "key", "kick", "kid", "kidney", "kind", "kingdom", "kiss", "kit", "kitchen", "kite", "kitten", "kiwi", "knee", "knife", "knock", "know", "lab", "label", "labor", "ladder", "lady", "lake", "lamp", "language", "laptop", "large", "later", "latin", "laugh", "laundry", "lava", "law", "lawn", "lawsuit", "layer", "lazy", "leader", "leaf", "learn", "leave", "lecture", "left", "leg", "legal", "legend", "leisure", "lemon", "lend", "length", "lens", "leopard", "lesson", "letter", "level", "liar", "liberty", "library", "license", "life", "lift", "light", "like", "limb", "limit", "link", "lion", "liquid", "list", "little", "live", "lizard", "load", "loan", "lobster", "local", "lock", "logic", "lonely", "long", "loop", "lottery", "loud", "lounge", "love", "loyal", "lucky", "luggage", "lumber", "lunar", "lunch", "luxury", "lyrics", "machine", "mad", "magic", "magnet", "maid", "mail", "main", "major", "make", "mammal", "man", "manage", "mandate", "mango", "mansion", "manual", "maple", "marble", "march", "margin", "marine", "market", "marriage", "mask", "mass", "master", "match", "material", "math", "matrix", "matter", "maximum", "maze", "meadow", "mean", "measure", "meat", "mechanic", "medal", "media", "melody", "melt", "member", "memory", "mention", "menu", "mercy", "merge", "merit", "merry", "mesh", "message", "metal", "method", "middle", "midnight", "milk", "million", "mimic", "mind", "minimum", "minor", "minute", "miracle", "mirror", "misery", "miss", "mistake", "mix", "mixed", "mixture", "mobile", "model", "modify", "mom", "moment", "monitor", "monkey", "monster", "month", "moon", "moral", "more", "morning", "mosquito", "mother", "motion", "motor", "mountain", "mouse", "move", "movie", "much", "muffin", "mule", "multiply", "muscle", "museum", "mushroom", "music", "must", "mutual", "myself", "mystery", "myth", "naive", "name", "napkin", "narrow", "nasty", "nation", "nature", "near", "neck", "need", "negative", "neglect", "neither", "nephew", "nerve", "nest", "net", "network", "neutral", "never", "news", "next", "nice", "night", "noble", "noise", "nominee", "noodle", "normal", "north", "nose", "notable", "note", "nothing", "notice", "novel", "now", "nuclear", "number", "nurse", "nut", "oak", "obey", "object", "oblige", "obscure", "observe", "obtain", "obvious", "occur", "ocean", "october", "odor", "off", "offer", "office", "often", "oil", "okay", "old", "olive", "olympic", "omit", "once", "one", "onion", "online", "only", "open", "opera", "opinion", "oppose", "option", "orange", "orbit", "orchard", "order", "ordinary", "organ", "orient", "original", "orphan", "ostrich", "other", "outdoor", "outer", "output", "outside", "oval", "oven", "over", "own", "owner", "oxygen", "oyster", "ozone", "pact", "paddle", "page", "pair", "palace", "palm", "panda", "panel", "panic", "panther", "paper", "parade", "parent", "park", "parrot", "party", "pass", "patch", "path", "patient", "patrol", "pattern", "pause", "pave", "payment", "peace", "peanut", "pear", "peasant", "pelican", "pen", "penalty", "pencil", "people", "pepper", "perfect", "permit", "person", "pet", "phone", "photo", "phrase", "physical", "piano", "picnic", "picture", "piece", "pig", "pigeon", "pill", "pilot", "pink", "pioneer", "pipe", "pistol", "pitch", "pizza", "place", "planet", "plastic", "plate", "play", "please", "pledge", "pluck", "plug", "plunge", "poem", "poet", "point", "polar", "pole", "police", "pond", "pony", "pool", "popular", "portion", "position", "possible", "post", "potato", "pottery", "poverty", "powder", "power", "practice", "praise", "predict", "prefer", "prepare", "present", "pretty", "prevent", "price", "pride", "primary", "print", "priority", "prison", "private", "prize", "problem", "process", "produce", "profit", "program", "project", "promote", "proof", "property", "prosper", "protect", "proud", "provide", "public", "pudding", "pull", "pulp", "pulse", "pumpkin", "punch", "pupil", "puppy", "purchase", "purity", "purpose", "purse", "push", "put", "puzzle", "pyramid", "quality", "quantum", "quarter", "question", "quick", "quit", "quiz", "quote", "rabbit", "raccoon", "race", "rack", "radar", "radio", "rail", "rain", "raise", "rally", "ramp", "ranch", "random", "range", "rapid", "rare", "rate", "rather", "raven", "raw", "razor", "ready", "real", "reason", "rebel", "rebuild", "recall", "receive", "recipe", "record", "recycle", "reduce", "reflect", "reform", "refuse", "region", "regret", "regular", "reject", "relax", "release", "relief", "rely", "remain", "remember", "remind", "remove", "render", "renew", "rent", "reopen", "repair", "repeat", "replace", "report", "require", "rescue", "resemble", "resist", "resource", "response", "result", "retire", "retreat", "return", "reunion", "reveal", "review", "reward", "rhythm", "rib", "ribbon", "rice", "rich", "ride", "ridge", "rifle", "right", "rigid", "ring", "riot", "ripple", "risk", "ritual", "rival", "river", "road", "roast", "robot", "robust", "rocket", "romance", "roof", "rookie", "room", "rose", "rotate", "rough", "round", "route", "royal", "rubber", "rude", "rug", "rule", "run", "runway", "rural", "sad", "saddle", "sadness", "safe", "sail", "salad", "salmon", "salon", "salt", "salute", "same", "sample", "sand", "satisfy", "satoshi", "sauce", "sausage", "save", "say", "scale", "scan", "scare", "scatter", "scene", "scheme", "school", "science", "scissors", "scorpion", "scout", "scrap", "screen", "script", "scrub", "sea", "search", "season", "seat", "second", "secret", "section", "security", "seed", "seek", "segment", "select", "sell", "seminar", "senior", "sense", "sentence", "series", "service", "session", "settle", "setup", "seven", "shadow", "shaft", "shallow", "share", "shed", "shell", "sheriff", "shield", "shift", "shine", "ship", "shiver", "shock", "shoe", "shoot", "shop", "short", "shoulder", "shove", "shrimp", "shrug", "shuffle", "shy", "sibling", "sick", "side", "siege", "sight", "sign", "silent", "silk", "silly", "silver", "similar", "simple", "since", "sing", "siren", "sister", "situate", "six", "size", "skate", "sketch", "ski", "skill", "skin", "skirt", "skull", "slab", "slam", "sleep", "slender", "slice", "slide", "slight", "slim", "slogan", "slot", "slow", "slush", "small", "smart", "smile", "smoke", "smooth", "snack", "snake", "snap", "sniff", "snow", "soap", "soccer", "social", "sock", "soda", "soft", "solar", "soldier", "solid", "solution", "solve", "someone", "song", "soon", "sorry", "sort", "soul", "sound", "soup", "source", "south", "space", "spare", "spatial", "spawn", "speak", "special", "speed", "spell", "spend", "sphere", "spice", "spider", "spike", "spin", "spirit", "split", "spoil", "sponsor", "spoon", "sport", "spot", "spray", "spread", "spring", "spy", "square", "squeeze", "squirrel", "stable", "stadium", "staff", "stage", "stairs", "stamp", "stand", "start", "state", "stay", "steak", "steel", "stem", "step", "stereo", "stick", "still", "sting", "stock", "stomach", "stone", "stool", "story", "stove", "strategy", "street", "strike", "strong", "struggle", "student", "stuff", "stumble", "style", "subject", "submit", "subway", "success", "such", "sudden", "suffer", "sugar", "suggest", "suit", "summer", "sun", "sunny", "sunset", "super", "supply", "supreme", "sure", "surface", "surge", "surprise", "surround", "survey", "suspect", "sustain", "swallow", "swamp", "swap", "swarm", "swear", "sweet", "swift", "swim", "swing", "switch", "sword", "symbol", "symptom", "syrup", "system", "table", "tackle", "tag", "tail", "talent", "talk", "tank", "tape", "target", "task", "taste", "tattoo", "taxi", "teach", "team", "tell", "ten", "tenant", "tennis", "tent", "term", "test", "text", "thank", "that", "theme", "then", "theory", "there", "they", "thing", "this", "thought", "three", "thrive", "throw", "thumb", "thunder", "ticket", "tide", "tiger", "tilt", "timber", "time", "tiny", "tip", "tired", "tissue", "title", "toast", "tobacco", "today", "toddler", "toe", "together", "toilet", "token", "tomato", "tomorrow", "tone", "tongue", "tonight", "tool", "tooth", "top", "topic", "topple", "torch", "tornado", "tortoise", "toss", "total", "tourist", "toward", "tower", "town", "toy", "track", "trade", "traffic", "tragic", "train", "transfer", "trap", "trash", "travel", "tray", "treat", "tree", "trend", "trial", "tribe", "trick", "trigger", "trim", "trip", "trophy", "trouble", "truck", "true", "truly", "trumpet", "trust", "truth", "try", "tube", "tuition", "tumble", "tuna", "tunnel", "turkey", "turn", "turtle", "twelve", "twenty", "twice", "twin", "twist", "two", "type", "typical", "ugly", "umbrella", "unable", "unaware", "uncle", "uncover", "under", "undo", "unfair", "unfold", "unhappy", "uniform", "unique", "unit", "universe", "unknown", "unlock", "until", "unusual", "unveil", "update", "upgrade", "uphold", "upon", "upper", "upset", "urban", "urge", "usage", "use", "used", "useful", "useless", "usual", "utility", "vacant", "vacuum", "vague", "valid", "valley", "valve", "van", "vanish", "vapor", "various", "vast", "vault", "vehicle", "velvet", "vendor", "venture", "venue", "verb", "verify", "version", "very", "vessel", "veteran", "viable", "vibrant", "vicious", "victory", "video", "view", "village", "vintage", "violin", "virtual", "virus", "visa", "visit", "visual", "vital", "vivid", "vocal", "voice", "void", "volcano", "volume", "vote", "voyage", "wage", "wagon", "wait", "walk", "wall", "walnut", "want", "warfare", "warm", "warrior", "wash", "wasp", "waste", "water", "wave", "way", "wealth", "weapon", "wear", "weasel", "weather", "web", "wedding", "weekend", "weird", "welcome", "west", "wet", "whale", "what", "wheat", "wheel", "when", "where", "whip", "whisper", "wide", "width", "wife", "wild", "will", "win", "window", "wine", "wing", "wink", "winner", "winter", "wire", "wisdom", "wise", "wish", "witness", "wolf", "woman", "wonder", "wood", "wool", "word", "work", "world", "worry", "worth", "wrap", "wreck", "wrestle", "wrist", "write", "wrong", "yard", "year", "yellow", "you", "young", "youth", "zebra", "zero", "zone", "zoo"];
9881
-
9882
- class Mnemonic {
9883
- wordlist;
9884
- constructor(options) {
9885
- // english always loaded, rest included by dev
9886
- this.wordlist = options?.wordlist || wordlist;
9887
- }
9888
- lpad(string, padString, length) {
9889
- while (string.length < length) {
9890
- string = padString + string;
9891
- }
9892
- return string;
9893
- }
9894
- normalize(string) {
9895
- return (string || '').normalize('NFKD');
9896
- }
9897
- bytesToBinary(bytes) {
9898
- return bytes.map((byte) => this.lpad(byte.toString(2), '0', 8)).join('');
9899
- }
9900
- async deriveChecksumBits(entropyBuffer) {
9901
- const entropy = entropyBuffer.length * 8;
9902
- const cs = entropy / 32;
9903
- const hash = await createHash(entropyBuffer, 'SHA-512');
9904
- return this.bytesToBinary(Array.from(hash)).slice(0, cs);
9905
- }
9906
- async mnemonicFromEntropy(entropyBuffer) {
9907
- let checksum = await this.deriveChecksumBits(entropyBuffer);
9908
- const entropy = this.bytesToBinary(Array.from(entropyBuffer));
9909
- let bits = entropy + checksum;
9910
- return bits
9911
- .match(/(.{1,11})/g)
9912
- .map((binary) => {
9913
- const index = parseInt(binary, 2);
9914
- return this.wordlist[index];
9915
- }).join(' ');
9916
- }
9917
- generate(strength = 256) {
9918
- return this.mnemonicFromEntropy(randombytes(strength / 8));
9919
- }
9920
- salt(password) {
9921
- return 'mnemonic' + this.normalize(password);
9922
- }
9923
- seedFromMnemonic(mnemonic, password, strength = 256, iterations = 2048) {
9924
- const encoder = new TextEncoder();
9925
- return pbkdf2(encoder.encode(this.salt(password)), encoder.encode(this.normalize(mnemonic)), iterations, strength, 'SHA-512');
9926
- }
9927
- }
9928
-
9929
- class MultiSignature {
9930
- multiCodec;
9931
- version;
9932
- decoded;
9933
- encoded;
9934
- #multiSignature;
9935
- constructor(version, multiCodec) {
9936
- if (version === undefined)
9937
- throw ReferenceError('version undefined');
9938
- if (multiCodec === undefined)
9939
- throw ReferenceError('multicodec undefined');
9940
- this.multiCodec = multiCodec;
9941
- this.version = version;
9942
- }
9943
- get signature() {
9944
- return this.decoded.signature;
9945
- }
9946
- get multiSignature() {
9947
- return this.#multiSignature || this.encoded || this.encode(this.signature);
9948
- }
9949
- export() {
9950
- return base58$1.encode(this.multiSignature);
9951
- }
9952
- import(encoded) {
9953
- return base58$1.decode(encoded);
9954
- }
9955
- sign(hash, privateKey) {
9956
- if (!hash || !privateKey)
9957
- throw ReferenceError(`${hash ? 'privateKey' : 'hash'} undefined`);
9958
- const { signature } = elliptic.ecdsaSign(hash, privateKey);
9959
- this.decoded = {
9960
- version: this.version,
9961
- multiCodec: this.multiCodec,
9962
- signature
9963
- };
9964
- return this.encode(signature);
9965
- }
9966
- /**
9967
- * verify signature (multiSignature.signature)
9968
- */
9969
- verifySignature(signature, hash, publicKey) {
9970
- return elliptic.ecdsaVerify(signature, hash, publicKey);
9971
- }
9972
- /**
9973
- * verify multiSignature
9974
- */
9975
- verify(multiSignature, hash, publicKey) {
9976
- multiSignature = this.decode(multiSignature);
9977
- return elliptic.ecdsaVerify(multiSignature.signature, hash, publicKey);
9978
- }
9979
- encode(signature) {
9980
- signature = signature || this.signature;
9981
- if (!signature)
9982
- throw ReferenceError('signature undefined');
9983
- this.#multiSignature = typedArrayConcat([
9984
- index$3.encode(this.version),
9985
- index$3.encode(this.multiCodec),
9986
- signature
9987
- ]);
9988
- return this.multiSignature;
9989
- }
9990
- /**
9991
- * decode exported multi signature to object
9992
- * @param {multiSignature} multiSignature base58 encoded string
9993
- * @return {decodedMultiSignature} { version, multiCodec, signature }
9994
- */
9995
- decode(multiSignature) {
9996
- if (multiSignature)
9997
- this.#multiSignature = multiSignature;
9998
- if (!this.multiSignature)
9999
- throw ReferenceError('multiSignature undefined');
10000
- let buffer = this.multiSignature;
10001
- const version = index$3.decode(buffer);
10002
- buffer = buffer.subarray(index$3.decode.bytes);
10003
- const codec = index$3.decode(buffer);
10004
- buffer = buffer.subarray(index$3.decode.bytes);
10005
- const signature = buffer.subarray(0, buffer.length);
10006
- if (version !== this.version)
10007
- throw TypeError('Invalid version');
10008
- if (this.multiCodec !== codec)
10009
- throw TypeError('Invalid multiCodec');
10010
- this.decoded = {
10011
- version,
10012
- multiCodec: codec,
10013
- signature
10014
- };
10015
- return this.decoded;
10016
- }
10017
- toString() {
10018
- return this.multiSignature.toString();
10019
- }
10020
- fromString(string) {
10021
- return this.decode(new Uint8Array(string.split(',')));
10022
- }
10023
- toBs58() {
10024
- return base58$1.encode(this.multiSignature);
10025
- }
10026
- fromBs58(string) {
10027
- return this.decode(base58$1.decode(string));
10028
- }
10029
- toBs32() {
10030
- return index$4.encode(this.multiSignature);
10031
- }
10032
- fromBs32(string) {
10033
- return this.decode(index$4.decode(string));
10034
- }
10035
- toBs32Hex() {
10036
- return index$4.encodeHex(this.multiSignature);
10037
- }
10038
- fromBs32Hex(string) {
10039
- return this.decode(index$4.decodeHex(string));
10040
- }
10041
- toBs58Hex() {
10042
- return base58$1.encodeHex(this.multiSignature);
10043
- }
10044
- fromBs58Hex(string) {
10045
- return this.decode(base58$1.decodeHex(string));
10046
- }
10047
- }
10048
-
12176
+ // Can throw `throw new Error('Unable to find sencond key candinate');`
12177
+ let point;
12178
+ try {
12179
+ point = ec.recoverPubKey(msg32, sigObj, recid);
12180
+ } catch (err) {
12181
+ return 2
12182
+ }
12183
+
12184
+ savePublicKey(output, point);
12185
+
12186
+ return 0
12187
+ },
12188
+
12189
+ ecdh (output, pubkey, seckey, data, hashfn, xbuf, ybuf) {
12190
+ const pair = loadPublicKey(pubkey);
12191
+ if (pair === null) return 1
12192
+
12193
+ const scalar = new BN(seckey);
12194
+ if (scalar.cmp(ecparams.n) >= 0 || scalar.isZero()) return 2
12195
+
12196
+ const point = pair.getPublic().mul(scalar);
12197
+
12198
+ if (hashfn === undefined) {
12199
+ const data = point.encode(null, true);
12200
+ const sha256 = ec.hash().update(data).digest();
12201
+ for (let i = 0; i < 32; ++i) output[i] = sha256[i];
12202
+ } else {
12203
+ if (!xbuf) xbuf = new Uint8Array(32);
12204
+ const x = point.getX().toArray('be', 32);
12205
+ for (let i = 0; i < 32; ++i) xbuf[i] = x[i];
12206
+
12207
+ if (!ybuf) ybuf = new Uint8Array(32);
12208
+ const y = point.getY().toArray('be', 32);
12209
+ for (let i = 0; i < 32; ++i) ybuf[i] = y[i];
12210
+
12211
+ const hash = hashfn(xbuf, ybuf, data);
12212
+
12213
+ const isValid = hash instanceof Uint8Array && hash.length === output.length;
12214
+ if (!isValid) return 2
12215
+
12216
+ output.set(hash);
12217
+ }
12218
+
12219
+ return 0
12220
+ }
12221
+ };
12222
+
12223
+ var elliptic = lib(elliptic$1);
12224
+
10049
12225
  const leofcoinOlivia = {
10050
12226
  messagePrefix: '\u0019Leofcoin Signed Message:',
10051
12227
  version: 1,
@@ -10149,6 +12325,34 @@ var networks = {
10149
12325
  ethereum
10150
12326
  };
10151
12327
 
12328
+ const encode = (version, privateKey, compressed) => {
12329
+ if (privateKey.length !== 32)
12330
+ throw new TypeError(`Invalid privateKey length: expected 32 got ${privateKey.length}`);
12331
+ const uint8Array = new Uint8Array(compressed ? 34 : 33);
12332
+ uint8Array.set([Number(version)]);
12333
+ uint8Array.set(privateKey, 1);
12334
+ if (compressed) {
12335
+ uint8Array.set([Number(version)], 33);
12336
+ }
12337
+ return base58check.encode(uint8Array);
12338
+ };
12339
+ const decode = async (wif, version) => {
12340
+ wif = (await base58check.decode(wif)).data;
12341
+ if (version && wif[0] !== version)
12342
+ throw new Error('Invalid network version');
12343
+ if (wif.length < 33 || wif.length > 34)
12344
+ throw new Error('Invalid WIF length');
12345
+ const comp = new TextEncoder().encode('1');
12346
+ if (wif.length === 34 && wif[33] !== comp[0])
12347
+ throw new Error('Invalid compression flag');
12348
+ return {
12349
+ version: wif[0],
12350
+ privateKey: wif.subarray(1, 33),
12351
+ compressed: wif.length === 33 ? false : true
12352
+ };
12353
+ };
12354
+ var wif = { encode, decode };
12355
+
10152
12356
  const HIGHEST_BIT = 0x80000000;
10153
12357
  const { publicKeyCreate, publicKeyVerify, privateKeyVerify, privateKeyTweakAdd, ecdh } = elliptic;
10154
12358
  class HdNode {
@@ -10239,7 +12443,7 @@ class HdNode {
10239
12443
  else {
10240
12444
  set.push(new Uint8Array(this.publicKey));
10241
12445
  }
10242
- return base58check.encode(index$1(set));
12446
+ return base58check.encode(index$7(set));
10243
12447
  }
10244
12448
  toWIF() {
10245
12449
  if (!this.#privateKey)
@@ -10255,14 +12459,14 @@ class HdNode {
10255
12459
  if (this.isNeutered)
10256
12460
  throw new TypeError('Missing private key for hardened child key');
10257
12461
  // data = 0x00 || ser256(kpar) || ser32(index)
10258
- data = index$1([
12462
+ data = index$7([
10259
12463
  new TextEncoder().encode('0'),
10260
12464
  this.privateKey,
10261
12465
  new TextEncoder().encode(index.toString())
10262
12466
  ]);
10263
12467
  }
10264
12468
  else {
10265
- data = index$1([
12469
+ data = index$7([
10266
12470
  this.publicKey,
10267
12471
  new TextEncoder().encode(index.toString())
10268
12472
  ]);
@@ -10326,7 +12530,7 @@ class HdNode {
10326
12530
  let buffer = (await base58check.decode(string)).data;
10327
12531
  network = network || networks.leofcoin;
10328
12532
  // 4 bytes: version bytes
10329
- let [version, depth, parentFingerprint, index, chainCode, k, privateKey] = index$2(buffer);
12533
+ let [version, depth, parentFingerprint, index, chainCode, k, privateKey] = index$6(buffer);
10330
12534
  version = Number(new TextDecoder().decode(version));
10331
12535
  depth = Number(new TextDecoder().decode(depth));
10332
12536
  parentFingerprint = Number(new TextDecoder().decode(parentFingerprint));
@@ -10350,6 +12554,56 @@ class HdNode {
10350
12554
  }
10351
12555
  }
10352
12556
 
12557
+ // see https://github.com/bitcoin/bips/blob/master/bip-0039/english.txt
12558
+ var wordlist = ["abandon", "ability", "able", "about", "above", "absent", "absorb", "abstract", "absurd", "abuse", "access", "accident", "account", "accuse", "achieve", "acid", "acoustic", "acquire", "across", "act", "action", "actor", "actress", "actual", "adapt", "add", "addict", "address", "adjust", "admit", "adult", "advance", "advice", "aerobic", "affair", "afford", "afraid", "again", "age", "agent", "agree", "ahead", "aim", "air", "airport", "aisle", "alarm", "album", "alcohol", "alert", "alien", "all", "alley", "allow", "almost", "alone", "alpha", "already", "also", "alter", "always", "amateur", "amazing", "among", "amount", "amused", "analyst", "anchor", "ancient", "anger", "angle", "angry", "animal", "ankle", "announce", "annual", "another", "answer", "antenna", "antique", "anxiety", "any", "apart", "apology", "appear", "apple", "approve", "april", "arch", "arctic", "area", "arena", "argue", "arm", "armed", "armor", "army", "around", "arrange", "arrest", "arrive", "arrow", "art", "artefact", "artist", "artwork", "ask", "aspect", "assault", "asset", "assist", "assume", "asthma", "athlete", "atom", "attack", "attend", "attitude", "attract", "auction", "audit", "august", "aunt", "author", "auto", "autumn", "average", "avocado", "avoid", "awake", "aware", "away", "awesome", "awful", "awkward", "axis", "baby", "bachelor", "bacon", "badge", "bag", "balance", "balcony", "ball", "bamboo", "banana", "banner", "bar", "barely", "bargain", "barrel", "base", "basic", "basket", "battle", "beach", "bean", "beauty", "because", "become", "beef", "before", "begin", "behave", "behind", "believe", "below", "belt", "bench", "benefit", "best", "betray", "better", "between", "beyond", "bicycle", "bid", "bike", "bind", "biology", "bird", "birth", "bitter", "black", "blade", "blame", "blanket", "blast", "bleak", "bless", "blind", "blood", "blossom", "blouse", "blue", "blur", "blush", "board", "boat", "body", "boil", "bomb", "bone", "bonus", "book", "boost", "border", "boring", "borrow", "boss", "bottom", "bounce", "box", "boy", "bracket", "brain", "brand", "brass", "brave", "bread", "breeze", "brick", "bridge", "brief", "bright", "bring", "brisk", "broccoli", "broken", "bronze", "broom", "brother", "brown", "brush", "bubble", "buddy", "budget", "buffalo", "build", "bulb", "bulk", "bullet", "bundle", "bunker", "burden", "burger", "burst", "bus", "business", "busy", "butter", "buyer", "buzz", "cabbage", "cabin", "cable", "cactus", "cage", "cake", "call", "calm", "camera", "camp", "can", "canal", "cancel", "candy", "cannon", "canoe", "canvas", "canyon", "capable", "capital", "captain", "car", "carbon", "card", "cargo", "carpet", "carry", "cart", "case", "cash", "casino", "castle", "casual", "cat", "catalog", "catch", "category", "cattle", "caught", "cause", "caution", "cave", "ceiling", "celery", "cement", "census", "century", "cereal", "certain", "chair", "chalk", "champion", "change", "chaos", "chapter", "charge", "chase", "chat", "cheap", "check", "cheese", "chef", "cherry", "chest", "chicken", "chief", "child", "chimney", "choice", "choose", "chronic", "chuckle", "chunk", "churn", "cigar", "cinnamon", "circle", "citizen", "city", "civil", "claim", "clap", "clarify", "claw", "clay", "clean", "clerk", "clever", "click", "client", "cliff", "climb", "clinic", "clip", "clock", "clog", "close", "cloth", "cloud", "clown", "club", "clump", "cluster", "clutch", "coach", "coast", "coconut", "code", "coffee", "coil", "coin", "collect", "color", "column", "combine", "come", "comfort", "comic", "common", "company", "concert", "conduct", "confirm", "congress", "connect", "consider", "control", "convince", "cook", "cool", "copper", "copy", "coral", "core", "corn", "correct", "cost", "cotton", "couch", "country", "couple", "course", "cousin", "cover", "coyote", "crack", "cradle", "craft", "cram", "crane", "crash", "crater", "crawl", "crazy", "cream", "credit", "creek", "crew", "cricket", "crime", "crisp", "critic", "crop", "cross", "crouch", "crowd", "crucial", "cruel", "cruise", "crumble", "crunch", "crush", "cry", "crystal", "cube", "culture", "cup", "cupboard", "curious", "current", "curtain", "curve", "cushion", "custom", "cute", "cycle", "dad", "damage", "damp", "dance", "danger", "daring", "dash", "daughter", "dawn", "day", "deal", "debate", "debris", "decade", "december", "decide", "decline", "decorate", "decrease", "deer", "defense", "define", "defy", "degree", "delay", "deliver", "demand", "demise", "denial", "dentist", "deny", "depart", "depend", "deposit", "depth", "deputy", "derive", "describe", "desert", "design", "desk", "despair", "destroy", "detail", "detect", "develop", "device", "devote", "diagram", "dial", "diamond", "diary", "dice", "diesel", "diet", "differ", "digital", "dignity", "dilemma", "dinner", "dinosaur", "direct", "dirt", "disagree", "discover", "disease", "dish", "dismiss", "disorder", "display", "distance", "divert", "divide", "divorce", "dizzy", "doctor", "document", "dog", "doll", "dolphin", "domain", "donate", "donkey", "donor", "door", "dose", "double", "dove", "draft", "dragon", "drama", "drastic", "draw", "dream", "dress", "drift", "drill", "drink", "drip", "drive", "drop", "drum", "dry", "duck", "dumb", "dune", "during", "dust", "dutch", "duty", "dwarf", "dynamic", "eager", "eagle", "early", "earn", "earth", "easily", "east", "easy", "echo", "ecology", "economy", "edge", "edit", "educate", "effort", "egg", "eight", "either", "elbow", "elder", "electric", "elegant", "element", "elephant", "elevator", "elite", "else", "embark", "embody", "embrace", "emerge", "emotion", "employ", "empower", "empty", "enable", "enact", "end", "endless", "endorse", "enemy", "energy", "enforce", "engage", "engine", "enhance", "enjoy", "enlist", "enough", "enrich", "enroll", "ensure", "enter", "entire", "entry", "envelope", "episode", "equal", "equip", "era", "erase", "erode", "erosion", "error", "erupt", "escape", "essay", "essence", "estate", "eternal", "ethics", "evidence", "evil", "evoke", "evolve", "exact", "example", "excess", "exchange", "excite", "exclude", "excuse", "execute", "exercise", "exhaust", "exhibit", "exile", "exist", "exit", "exotic", "expand", "expect", "expire", "explain", "expose", "express", "extend", "extra", "eye", "eyebrow", "fabric", "face", "faculty", "fade", "faint", "faith", "fall", "false", "fame", "family", "famous", "fan", "fancy", "fantasy", "farm", "fashion", "fat", "fatal", "father", "fatigue", "fault", "favorite", "feature", "february", "federal", "fee", "feed", "feel", "female", "fence", "festival", "fetch", "fever", "few", "fiber", "fiction", "field", "figure", "file", "film", "filter", "final", "find", "fine", "finger", "finish", "fire", "firm", "first", "fiscal", "fish", "fit", "fitness", "fix", "flag", "flame", "flash", "flat", "flavor", "flee", "flight", "flip", "float", "flock", "floor", "flower", "fluid", "flush", "fly", "foam", "focus", "fog", "foil", "fold", "follow", "food", "foot", "force", "forest", "forget", "fork", "fortune", "forum", "forward", "fossil", "foster", "found", "fox", "fragile", "frame", "frequent", "fresh", "friend", "fringe", "frog", "front", "frost", "frown", "frozen", "fruit", "fuel", "fun", "funny", "furnace", "fury", "future", "gadget", "gain", "galaxy", "gallery", "game", "gap", "garage", "garbage", "garden", "garlic", "garment", "gas", "gasp", "gate", "gather", "gauge", "gaze", "general", "genius", "genre", "gentle", "genuine", "gesture", "ghost", "giant", "gift", "giggle", "ginger", "giraffe", "girl", "give", "glad", "glance", "glare", "glass", "glide", "glimpse", "globe", "gloom", "glory", "glove", "glow", "glue", "goat", "goddess", "gold", "good", "goose", "gorilla", "gospel", "gossip", "govern", "gown", "grab", "grace", "grain", "grant", "grape", "grass", "gravity", "great", "green", "grid", "grief", "grit", "grocery", "group", "grow", "grunt", "guard", "guess", "guide", "guilt", "guitar", "gun", "gym", "habit", "hair", "half", "hammer", "hamster", "hand", "happy", "harbor", "hard", "harsh", "harvest", "hat", "have", "hawk", "hazard", "head", "health", "heart", "heavy", "hedgehog", "height", "hello", "helmet", "help", "hen", "hero", "hidden", "high", "hill", "hint", "hip", "hire", "history", "hobby", "hockey", "hold", "hole", "holiday", "hollow", "home", "honey", "hood", "hope", "horn", "horror", "horse", "hospital", "host", "hotel", "hour", "hover", "hub", "huge", "human", "humble", "humor", "hundred", "hungry", "hunt", "hurdle", "hurry", "hurt", "husband", "hybrid", "ice", "icon", "idea", "identify", "idle", "ignore", "ill", "illegal", "illness", "image", "imitate", "immense", "immune", "impact", "impose", "improve", "impulse", "inch", "include", "income", "increase", "index", "indicate", "indoor", "industry", "infant", "inflict", "inform", "inhale", "inherit", "initial", "inject", "injury", "inmate", "inner", "innocent", "input", "inquiry", "insane", "insect", "inside", "inspire", "install", "intact", "interest", "into", "invest", "invite", "involve", "iron", "island", "isolate", "issue", "item", "ivory", "jacket", "jaguar", "jar", "jazz", "jealous", "jeans", "jelly", "jewel", "job", "join", "joke", "journey", "joy", "judge", "juice", "jump", "jungle", "junior", "junk", "just", "kangaroo", "keen", "keep", "ketchup", "key", "kick", "kid", "kidney", "kind", "kingdom", "kiss", "kit", "kitchen", "kite", "kitten", "kiwi", "knee", "knife", "knock", "know", "lab", "label", "labor", "ladder", "lady", "lake", "lamp", "language", "laptop", "large", "later", "latin", "laugh", "laundry", "lava", "law", "lawn", "lawsuit", "layer", "lazy", "leader", "leaf", "learn", "leave", "lecture", "left", "leg", "legal", "legend", "leisure", "lemon", "lend", "length", "lens", "leopard", "lesson", "letter", "level", "liar", "liberty", "library", "license", "life", "lift", "light", "like", "limb", "limit", "link", "lion", "liquid", "list", "little", "live", "lizard", "load", "loan", "lobster", "local", "lock", "logic", "lonely", "long", "loop", "lottery", "loud", "lounge", "love", "loyal", "lucky", "luggage", "lumber", "lunar", "lunch", "luxury", "lyrics", "machine", "mad", "magic", "magnet", "maid", "mail", "main", "major", "make", "mammal", "man", "manage", "mandate", "mango", "mansion", "manual", "maple", "marble", "march", "margin", "marine", "market", "marriage", "mask", "mass", "master", "match", "material", "math", "matrix", "matter", "maximum", "maze", "meadow", "mean", "measure", "meat", "mechanic", "medal", "media", "melody", "melt", "member", "memory", "mention", "menu", "mercy", "merge", "merit", "merry", "mesh", "message", "metal", "method", "middle", "midnight", "milk", "million", "mimic", "mind", "minimum", "minor", "minute", "miracle", "mirror", "misery", "miss", "mistake", "mix", "mixed", "mixture", "mobile", "model", "modify", "mom", "moment", "monitor", "monkey", "monster", "month", "moon", "moral", "more", "morning", "mosquito", "mother", "motion", "motor", "mountain", "mouse", "move", "movie", "much", "muffin", "mule", "multiply", "muscle", "museum", "mushroom", "music", "must", "mutual", "myself", "mystery", "myth", "naive", "name", "napkin", "narrow", "nasty", "nation", "nature", "near", "neck", "need", "negative", "neglect", "neither", "nephew", "nerve", "nest", "net", "network", "neutral", "never", "news", "next", "nice", "night", "noble", "noise", "nominee", "noodle", "normal", "north", "nose", "notable", "note", "nothing", "notice", "novel", "now", "nuclear", "number", "nurse", "nut", "oak", "obey", "object", "oblige", "obscure", "observe", "obtain", "obvious", "occur", "ocean", "october", "odor", "off", "offer", "office", "often", "oil", "okay", "old", "olive", "olympic", "omit", "once", "one", "onion", "online", "only", "open", "opera", "opinion", "oppose", "option", "orange", "orbit", "orchard", "order", "ordinary", "organ", "orient", "original", "orphan", "ostrich", "other", "outdoor", "outer", "output", "outside", "oval", "oven", "over", "own", "owner", "oxygen", "oyster", "ozone", "pact", "paddle", "page", "pair", "palace", "palm", "panda", "panel", "panic", "panther", "paper", "parade", "parent", "park", "parrot", "party", "pass", "patch", "path", "patient", "patrol", "pattern", "pause", "pave", "payment", "peace", "peanut", "pear", "peasant", "pelican", "pen", "penalty", "pencil", "people", "pepper", "perfect", "permit", "person", "pet", "phone", "photo", "phrase", "physical", "piano", "picnic", "picture", "piece", "pig", "pigeon", "pill", "pilot", "pink", "pioneer", "pipe", "pistol", "pitch", "pizza", "place", "planet", "plastic", "plate", "play", "please", "pledge", "pluck", "plug", "plunge", "poem", "poet", "point", "polar", "pole", "police", "pond", "pony", "pool", "popular", "portion", "position", "possible", "post", "potato", "pottery", "poverty", "powder", "power", "practice", "praise", "predict", "prefer", "prepare", "present", "pretty", "prevent", "price", "pride", "primary", "print", "priority", "prison", "private", "prize", "problem", "process", "produce", "profit", "program", "project", "promote", "proof", "property", "prosper", "protect", "proud", "provide", "public", "pudding", "pull", "pulp", "pulse", "pumpkin", "punch", "pupil", "puppy", "purchase", "purity", "purpose", "purse", "push", "put", "puzzle", "pyramid", "quality", "quantum", "quarter", "question", "quick", "quit", "quiz", "quote", "rabbit", "raccoon", "race", "rack", "radar", "radio", "rail", "rain", "raise", "rally", "ramp", "ranch", "random", "range", "rapid", "rare", "rate", "rather", "raven", "raw", "razor", "ready", "real", "reason", "rebel", "rebuild", "recall", "receive", "recipe", "record", "recycle", "reduce", "reflect", "reform", "refuse", "region", "regret", "regular", "reject", "relax", "release", "relief", "rely", "remain", "remember", "remind", "remove", "render", "renew", "rent", "reopen", "repair", "repeat", "replace", "report", "require", "rescue", "resemble", "resist", "resource", "response", "result", "retire", "retreat", "return", "reunion", "reveal", "review", "reward", "rhythm", "rib", "ribbon", "rice", "rich", "ride", "ridge", "rifle", "right", "rigid", "ring", "riot", "ripple", "risk", "ritual", "rival", "river", "road", "roast", "robot", "robust", "rocket", "romance", "roof", "rookie", "room", "rose", "rotate", "rough", "round", "route", "royal", "rubber", "rude", "rug", "rule", "run", "runway", "rural", "sad", "saddle", "sadness", "safe", "sail", "salad", "salmon", "salon", "salt", "salute", "same", "sample", "sand", "satisfy", "satoshi", "sauce", "sausage", "save", "say", "scale", "scan", "scare", "scatter", "scene", "scheme", "school", "science", "scissors", "scorpion", "scout", "scrap", "screen", "script", "scrub", "sea", "search", "season", "seat", "second", "secret", "section", "security", "seed", "seek", "segment", "select", "sell", "seminar", "senior", "sense", "sentence", "series", "service", "session", "settle", "setup", "seven", "shadow", "shaft", "shallow", "share", "shed", "shell", "sheriff", "shield", "shift", "shine", "ship", "shiver", "shock", "shoe", "shoot", "shop", "short", "shoulder", "shove", "shrimp", "shrug", "shuffle", "shy", "sibling", "sick", "side", "siege", "sight", "sign", "silent", "silk", "silly", "silver", "similar", "simple", "since", "sing", "siren", "sister", "situate", "six", "size", "skate", "sketch", "ski", "skill", "skin", "skirt", "skull", "slab", "slam", "sleep", "slender", "slice", "slide", "slight", "slim", "slogan", "slot", "slow", "slush", "small", "smart", "smile", "smoke", "smooth", "snack", "snake", "snap", "sniff", "snow", "soap", "soccer", "social", "sock", "soda", "soft", "solar", "soldier", "solid", "solution", "solve", "someone", "song", "soon", "sorry", "sort", "soul", "sound", "soup", "source", "south", "space", "spare", "spatial", "spawn", "speak", "special", "speed", "spell", "spend", "sphere", "spice", "spider", "spike", "spin", "spirit", "split", "spoil", "sponsor", "spoon", "sport", "spot", "spray", "spread", "spring", "spy", "square", "squeeze", "squirrel", "stable", "stadium", "staff", "stage", "stairs", "stamp", "stand", "start", "state", "stay", "steak", "steel", "stem", "step", "stereo", "stick", "still", "sting", "stock", "stomach", "stone", "stool", "story", "stove", "strategy", "street", "strike", "strong", "struggle", "student", "stuff", "stumble", "style", "subject", "submit", "subway", "success", "such", "sudden", "suffer", "sugar", "suggest", "suit", "summer", "sun", "sunny", "sunset", "super", "supply", "supreme", "sure", "surface", "surge", "surprise", "surround", "survey", "suspect", "sustain", "swallow", "swamp", "swap", "swarm", "swear", "sweet", "swift", "swim", "swing", "switch", "sword", "symbol", "symptom", "syrup", "system", "table", "tackle", "tag", "tail", "talent", "talk", "tank", "tape", "target", "task", "taste", "tattoo", "taxi", "teach", "team", "tell", "ten", "tenant", "tennis", "tent", "term", "test", "text", "thank", "that", "theme", "then", "theory", "there", "they", "thing", "this", "thought", "three", "thrive", "throw", "thumb", "thunder", "ticket", "tide", "tiger", "tilt", "timber", "time", "tiny", "tip", "tired", "tissue", "title", "toast", "tobacco", "today", "toddler", "toe", "together", "toilet", "token", "tomato", "tomorrow", "tone", "tongue", "tonight", "tool", "tooth", "top", "topic", "topple", "torch", "tornado", "tortoise", "toss", "total", "tourist", "toward", "tower", "town", "toy", "track", "trade", "traffic", "tragic", "train", "transfer", "trap", "trash", "travel", "tray", "treat", "tree", "trend", "trial", "tribe", "trick", "trigger", "trim", "trip", "trophy", "trouble", "truck", "true", "truly", "trumpet", "trust", "truth", "try", "tube", "tuition", "tumble", "tuna", "tunnel", "turkey", "turn", "turtle", "twelve", "twenty", "twice", "twin", "twist", "two", "type", "typical", "ugly", "umbrella", "unable", "unaware", "uncle", "uncover", "under", "undo", "unfair", "unfold", "unhappy", "uniform", "unique", "unit", "universe", "unknown", "unlock", "until", "unusual", "unveil", "update", "upgrade", "uphold", "upon", "upper", "upset", "urban", "urge", "usage", "use", "used", "useful", "useless", "usual", "utility", "vacant", "vacuum", "vague", "valid", "valley", "valve", "van", "vanish", "vapor", "various", "vast", "vault", "vehicle", "velvet", "vendor", "venture", "venue", "verb", "verify", "version", "very", "vessel", "veteran", "viable", "vibrant", "vicious", "victory", "video", "view", "village", "vintage", "violin", "virtual", "virus", "visa", "visit", "visual", "vital", "vivid", "vocal", "voice", "void", "volcano", "volume", "vote", "voyage", "wage", "wagon", "wait", "walk", "wall", "walnut", "want", "warfare", "warm", "warrior", "wash", "wasp", "waste", "water", "wave", "way", "wealth", "weapon", "wear", "weasel", "weather", "web", "wedding", "weekend", "weird", "welcome", "west", "wet", "whale", "what", "wheat", "wheel", "when", "where", "whip", "whisper", "wide", "width", "wife", "wild", "will", "win", "window", "wine", "wing", "wink", "winner", "winter", "wire", "wisdom", "wise", "wish", "witness", "wolf", "woman", "wonder", "wood", "wool", "word", "work", "world", "worry", "worth", "wrap", "wreck", "wrestle", "wrist", "write", "wrong", "yard", "year", "yellow", "you", "young", "youth", "zebra", "zero", "zone", "zoo"];
12559
+
12560
+ class Mnemonic {
12561
+ wordlist;
12562
+ constructor(options) {
12563
+ // english always loaded, rest included by dev
12564
+ this.wordlist = options?.wordlist || wordlist;
12565
+ }
12566
+ lpad(string, padString, length) {
12567
+ while (string.length < length) {
12568
+ string = padString + string;
12569
+ }
12570
+ return string;
12571
+ }
12572
+ normalize(string) {
12573
+ return (string || '').normalize('NFKD');
12574
+ }
12575
+ bytesToBinary(bytes) {
12576
+ return bytes.map((byte) => this.lpad(byte.toString(2), '0', 8)).join('');
12577
+ }
12578
+ async deriveChecksumBits(entropyBuffer) {
12579
+ const entropy = entropyBuffer.length * 8;
12580
+ const cs = entropy / 32;
12581
+ const hash = await createHash(entropyBuffer, 'SHA-512');
12582
+ return this.bytesToBinary(Array.from(hash)).slice(0, cs);
12583
+ }
12584
+ async mnemonicFromEntropy(entropyBuffer) {
12585
+ let checksum = await this.deriveChecksumBits(entropyBuffer);
12586
+ const entropy = this.bytesToBinary(Array.from(entropyBuffer));
12587
+ let bits = entropy + checksum;
12588
+ return bits
12589
+ .match(/(.{1,11})/g)
12590
+ .map((binary) => {
12591
+ const index = parseInt(binary, 2);
12592
+ return this.wordlist[index];
12593
+ }).join(' ');
12594
+ }
12595
+ generate(strength = 256) {
12596
+ return this.mnemonicFromEntropy(randombytes(strength / 8));
12597
+ }
12598
+ salt(password) {
12599
+ return 'mnemonic' + this.normalize(password);
12600
+ }
12601
+ seedFromMnemonic(mnemonic, password, strength = 256, iterations = 2048) {
12602
+ const encoder = new TextEncoder();
12603
+ return pbkdf2(encoder.encode(this.salt(password)), encoder.encode(this.normalize(mnemonic)), iterations, strength, 'SHA-512');
12604
+ }
12605
+ }
12606
+
10353
12607
  const fromNetworkString = network => {
10354
12608
  const parts = network.split(':');
10355
12609
  network = networks[parts[0]];
@@ -10452,51 +12706,171 @@ class HDWallet {
10452
12706
  await this.defineHDNode(await (new HdNode()).fromSeed(new Uint8Array(seed), network));
10453
12707
  return mnemonic;
10454
12708
  }
10455
- /**
10456
- * recover using mnemonic (recovery word list)
10457
- */
10458
- async recover(mnemonic, password, network) {
10459
- network = this.validateNetwork(network || password);
10460
- const seed = await new Mnemonic().seedFromMnemonic(mnemonic, password, 512);
10461
- let node = new HdNode();
10462
- node = await node.fromSeed(new Uint8Array(seed), network);
10463
- await this.defineHDNode(await node.fromSeed(new Uint8Array(seed), network));
12709
+ /**
12710
+ * recover using mnemonic (recovery word list)
12711
+ */
12712
+ async recover(mnemonic, password, network) {
12713
+ network = this.validateNetwork(network || password);
12714
+ const seed = await new Mnemonic().seedFromMnemonic(mnemonic, password, 512);
12715
+ let node = new HdNode();
12716
+ node = await node.fromSeed(new Uint8Array(seed), network);
12717
+ await this.defineHDNode(await node.fromSeed(new Uint8Array(seed), network));
12718
+ }
12719
+ async load(base58, network) {
12720
+ network = this.validateNetwork(network);
12721
+ await this.defineHDNode(await (new HdNode()).fromBase58(base58, network));
12722
+ }
12723
+ save() {
12724
+ return this.hdnode.toBase58();
12725
+ }
12726
+ async fromAddress(address, chainCode, network) {
12727
+ network = this.validateNetwork(network);
12728
+ address = (await base58check.decode(address)).data;
12729
+ if (!chainCode || chainCode && !Buffer.isBuffer(chainCode))
12730
+ chainCode = address.slice(1);
12731
+ await this.defineHDNode(await (new HdNode()).fromPublicKey(address, chainCode, network));
12732
+ }
12733
+ async fromPublicKey(hex, chainCode, network) {
12734
+ network = this.validateNetwork(network);
12735
+ if (!chainCode || chainCode)
12736
+ chainCode = hex.slice(1);
12737
+ let node = new HdNode();
12738
+ node = await node.fromPublicKey(hex, chainCode, network);
12739
+ await this.defineHDNode(node);
12740
+ return this;
12741
+ }
12742
+ async fromPrivateKey(privateKey, chainCode, network) {
12743
+ await this.defineHDNode(await (new HdNode()).fromPrivateKey(privateKey, chainCode, network));
12744
+ }
12745
+ }
12746
+
12747
+ class MultiSignature {
12748
+ multiCodec;
12749
+ version;
12750
+ decoded;
12751
+ encoded;
12752
+ #multiSignature;
12753
+ constructor(version, multiCodec) {
12754
+ if (version === undefined)
12755
+ throw ReferenceError('version undefined');
12756
+ if (multiCodec === undefined)
12757
+ throw ReferenceError('multicodec undefined');
12758
+ this.multiCodec = multiCodec;
12759
+ this.version = version;
12760
+ }
12761
+ get signature() {
12762
+ return this.decoded.signature;
12763
+ }
12764
+ get multiSignature() {
12765
+ return this.#multiSignature || this.encoded || this.encode(this.signature);
12766
+ }
12767
+ export() {
12768
+ return base58$1.encode(this.multiSignature);
12769
+ }
12770
+ import(encoded) {
12771
+ return base58$1.decode(encoded);
12772
+ }
12773
+ sign(hash, privateKey) {
12774
+ if (!hash || !privateKey)
12775
+ throw ReferenceError(`${hash ? 'privateKey' : 'hash'} undefined`);
12776
+ const { signature } = elliptic.ecdsaSign(hash, privateKey);
12777
+ this.decoded = {
12778
+ version: this.version,
12779
+ multiCodec: this.multiCodec,
12780
+ signature
12781
+ };
12782
+ return this.encode(signature);
12783
+ }
12784
+ /**
12785
+ * verify signature (multiSignature.signature)
12786
+ */
12787
+ verifySignature(signature, hash, publicKey) {
12788
+ return elliptic.ecdsaVerify(signature, hash, publicKey);
12789
+ }
12790
+ /**
12791
+ * verify multiSignature
12792
+ */
12793
+ verify(multiSignature, hash, publicKey) {
12794
+ multiSignature = this.decode(multiSignature);
12795
+ return elliptic.ecdsaVerify(multiSignature.signature, hash, publicKey);
12796
+ }
12797
+ encode(signature) {
12798
+ signature = signature || this.signature;
12799
+ if (!signature)
12800
+ throw ReferenceError('signature undefined');
12801
+ this.#multiSignature = typedArrayConcat([
12802
+ index$8.encode(this.version),
12803
+ index$8.encode(this.multiCodec),
12804
+ signature
12805
+ ]);
12806
+ return this.multiSignature;
12807
+ }
12808
+ /**
12809
+ * decode exported multi signature to object
12810
+ * @param {multiSignature} multiSignature base58 encoded string
12811
+ * @return {decodedMultiSignature} { version, multiCodec, signature }
12812
+ */
12813
+ decode(multiSignature) {
12814
+ if (multiSignature)
12815
+ this.#multiSignature = multiSignature;
12816
+ if (!this.multiSignature)
12817
+ throw ReferenceError('multiSignature undefined');
12818
+ let buffer = this.multiSignature;
12819
+ const version = index$8.decode(buffer);
12820
+ buffer = buffer.subarray(index$8.decode.bytes);
12821
+ const codec = index$8.decode(buffer);
12822
+ buffer = buffer.subarray(index$8.decode.bytes);
12823
+ const signature = buffer.subarray(0, buffer.length);
12824
+ if (version !== this.version)
12825
+ throw TypeError('Invalid version');
12826
+ if (this.multiCodec !== codec)
12827
+ throw TypeError('Invalid multiCodec');
12828
+ this.decoded = {
12829
+ version,
12830
+ multiCodec: codec,
12831
+ signature
12832
+ };
12833
+ return this.decoded;
12834
+ }
12835
+ toString() {
12836
+ return this.multiSignature.toString();
12837
+ }
12838
+ fromString(string) {
12839
+ return this.decode(new Uint8Array(string.split(',')));
12840
+ }
12841
+ toBs58() {
12842
+ return base58$1.encode(this.multiSignature);
12843
+ }
12844
+ fromBs58(string) {
12845
+ return this.decode(base58$1.decode(string));
10464
12846
  }
10465
- async load(base58, network) {
10466
- network = this.validateNetwork(network);
10467
- await this.defineHDNode(await (new HdNode()).fromBase58(base58, network));
12847
+ toBs32() {
12848
+ return index$9.encode(this.multiSignature);
10468
12849
  }
10469
- save() {
10470
- return this.hdnode.toBase58();
12850
+ fromBs32(string) {
12851
+ return this.decode(index$9.decode(string));
10471
12852
  }
10472
- async fromAddress(address, chainCode, network) {
10473
- network = this.validateNetwork(network);
10474
- address = (await base58check.decode(address)).data;
10475
- if (!chainCode || chainCode && !Buffer.isBuffer(chainCode))
10476
- chainCode = address.slice(1);
10477
- await this.defineHDNode(await (new HdNode()).fromPublicKey(address, chainCode, network));
12853
+ toBs32Hex() {
12854
+ return index$9.encodeHex(this.multiSignature);
10478
12855
  }
10479
- async fromPublicKey(hex, chainCode, network) {
10480
- network = this.validateNetwork(network);
10481
- if (!chainCode || chainCode)
10482
- chainCode = hex.slice(1);
10483
- let node = new HdNode();
10484
- node = await node.fromPublicKey(hex, chainCode, network);
10485
- await this.defineHDNode(node);
10486
- return this;
12856
+ fromBs32Hex(string) {
12857
+ return this.decode(index$9.decodeHex(string));
10487
12858
  }
10488
- async fromPrivateKey(privateKey, chainCode, network) {
10489
- await this.defineHDNode(await (new HdNode()).fromPrivateKey(privateKey, chainCode, network));
12859
+ toBs58Hex() {
12860
+ return base58$1.encodeHex(this.multiSignature);
12861
+ }
12862
+ fromBs58Hex(string) {
12863
+ return this.decode(base58$1.decodeHex(string));
10490
12864
  }
10491
12865
  }
10492
12866
 
10493
- class MultiWallet extends HDWallet {
12867
+ class MultiHDNode extends HDWallet {
10494
12868
  #encrypted;
10495
12869
  constructor(network, hdnode) {
10496
12870
  super(network, hdnode);
10497
12871
  }
10498
12872
  get id() {
10499
- return base58check.encode(index$1([
12873
+ return base58check.encode(index$7([
10500
12874
  new TextEncoder().encode(this.version.toString()),
10501
12875
  this.account(0).hdnode.neutered.publicKey
10502
12876
  ]));
@@ -10504,13 +12878,10 @@ class MultiWallet extends HDWallet {
10504
12878
  get multiWIF() {
10505
12879
  return this.toMultiWif();
10506
12880
  }
10507
- get neutered() {
10508
- return new HDAccount(this.networkName, this, this.hdnode.depth);
10509
- }
10510
12881
  async fromId(id) {
10511
12882
  let buffer = (await base58check.decode(id)).data;
10512
- index$3.decode(buffer);
10513
- buffer = buffer.slice(index$3.decode.bytes);
12883
+ index$8.decode(buffer);
12884
+ buffer = buffer.slice(index$8.decode.bytes);
10514
12885
  this.fromPublicKey(buffer, null, this.networkName);
10515
12886
  }
10516
12887
  async lock(multiWIF) {
@@ -10526,7 +12897,7 @@ class MultiWallet extends HDWallet {
10526
12897
  this.locked = false;
10527
12898
  }
10528
12899
  fromMultiWif(string) {
10529
- const { version, codec, privateKey } = index.decode(string);
12900
+ const { version, codec, privateKey } = index$1.decode(string);
10530
12901
  this.network = Object.values(networks).reduce((p, c) => {
10531
12902
  if (c.multiCodec === codec)
10532
12903
  return c;
@@ -10540,7 +12911,7 @@ class MultiWallet extends HDWallet {
10540
12911
  return this.fromPrivateKey(privateKey, undefined, this.network);
10541
12912
  }
10542
12913
  toMultiWif() {
10543
- return index.encode(this.network.version, this.network.multiCodec, this.privateKey);
12914
+ return index$1.encode(this.network.version, this.network.multiCodec, this.privateKey);
10544
12915
  }
10545
12916
  sign(hash) {
10546
12917
  return new MultiSignature(this.version, this.network.multiCodec)
@@ -10550,6 +12921,51 @@ class MultiWallet extends HDWallet {
10550
12921
  return new MultiSignature(this.version, this.network.multiCodec)
10551
12922
  .verify(multiSignature, hash, this.publicKey);
10552
12923
  }
12924
+ }
12925
+
12926
+ class HDAccount extends MultiHDNode {
12927
+ /**
12928
+ * @param {number} depth - acount depth
12929
+ */
12930
+ constructor(network, hdnode, depth = 0) {
12931
+ super(network, hdnode);
12932
+ this.hdnode = hdnode;
12933
+ this.depth = depth;
12934
+ this._prefix = `m/44'/${hdnode.network.coin_type}'/${depth}'/`;
12935
+ }
12936
+ get neutered() {
12937
+ return this.hdnode.neutered;
12938
+ }
12939
+ /**
12940
+ * @param {number} index - address index
12941
+ */
12942
+ async internal(index = 0) {
12943
+ return this.hdnode.derivePath(`${this._prefix}1/${index}`);
12944
+ }
12945
+ /**
12946
+ * @param {number} index - address index
12947
+ */
12948
+ async external(index = 0) {
12949
+ return this.hdnode.derivePath(`${this._prefix}0/${index}`);
12950
+ }
12951
+ }
12952
+
12953
+ let MultiWallet$1 = class MultiWallet extends MultiHDNode {
12954
+ constructor(network, hdnode) {
12955
+ super(network, hdnode);
12956
+ }
12957
+ get id() {
12958
+ return base58check.encode(index$7([
12959
+ new TextEncoder().encode(this.version.toString()),
12960
+ this.account(0).hdnode.neutered.publicKey
12961
+ ]));
12962
+ }
12963
+ get multiWIF() {
12964
+ return this.toMultiWif();
12965
+ }
12966
+ get neutered() {
12967
+ return new HDAccount(this.networkName, this, this.hdnode.depth);
12968
+ }
10553
12969
  /**
10554
12970
  * @param {number} account - account to return chain for
10555
12971
  * @return internal(addressIndex), external(addressIndex)
@@ -10557,45 +12973,725 @@ class MultiWallet extends HDWallet {
10557
12973
  account(index) {
10558
12974
  return new HDAccount(this.networkName, this, index);
10559
12975
  }
12976
+ async fromAccount(privateKey, depth, network) {
12977
+ const node = await new MultiWallet$1(network).fromPrivateKey(privateKey);
12978
+ return new HDAccount(node, depth);
12979
+ }
10560
12980
  /**
10561
12981
  * m / purpose' / coin_type' / account' / change / aadress_index
10562
12982
  *
10563
12983
  * see https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki
10564
12984
  */
10565
12985
  async derivePath(path) {
10566
- return new MultiWallet(this.networkName, await this.hdnode.derivePath(path));
12986
+ return new MultiWallet$1(this.networkName, await this.hdnode.derivePath(path));
10567
12987
  }
10568
12988
  async derive(index) {
10569
- return new MultiWallet(this.networkName, await this.hdnode.derive(index));
12989
+ return new MultiWallet$1(this.networkName, await this.hdnode.derive(index));
10570
12990
  }
10571
- async fromAccount(privateKey, depth, network) {
10572
- const node = await new MultiWallet(network).fromPrivateKey(privateKey);
10573
- return new HDAccount(node, depth);
12991
+ };
12992
+
12993
+ var index = /*#__PURE__*/Object.freeze({
12994
+ __proto__: null,
12995
+ default: MultiWallet$1
12996
+ });
12997
+
12998
+ const walletStore$1 = globalThis.walletStore;
12999
+ const accountStore = globalThis.accountStore;
13000
+ class Identity {
13001
+ #wallet;
13002
+ network;
13003
+ id;
13004
+ constructor(network) {
13005
+ this.network = network;
13006
+ }
13007
+ get accounts() {
13008
+ return this.getAccounts();
13009
+ }
13010
+ async getAccounts() {
13011
+ let accounts = await walletStore$1.get('accounts');
13012
+ accounts = new TextDecoder().decode(accounts);
13013
+ return JSON.parse(accounts);
13014
+ }
13015
+ async load(password) {
13016
+ let importee;
13017
+ if (!password) {
13018
+ if (globalThis.navigator)
13019
+ importee = await import('./browser.js');
13020
+ else {
13021
+ const path = await import('node:path');
13022
+ const { fileURLToPath } = await import('node:url');
13023
+ const __filename = fileURLToPath(import.meta.url);
13024
+ const __dirname = path.dirname(__filename);
13025
+ const url = path.join(__dirname, './prompts/password/node.js');
13026
+ importee = await import(url);
13027
+ }
13028
+ password = await importee.default();
13029
+ }
13030
+ const accountExists = await accountStore.has('public');
13031
+ if (accountExists) {
13032
+ const pub = await accountStore.get('public');
13033
+ this.id = JSON.parse(new TextDecoder().decode(pub)).walletId;
13034
+ const selected = await walletStore$1.get('selected-account');
13035
+ globalThis.peernet.selectedAccount = new TextDecoder().decode(selected);
13036
+ }
13037
+ else {
13038
+ const importee = await import(/* webpackChunkName: "generate-account" */ './index-5a93c9c3.js');
13039
+ const { identity, accounts } = await importee.default(password, this.network);
13040
+ await accountStore.put('public', JSON.stringify({ walletId: identity.walletId }));
13041
+ await walletStore$1.put('version', String(1));
13042
+ await walletStore$1.put('accounts', JSON.stringify(accounts));
13043
+ await walletStore$1.put('selected-account', accounts[0][1]);
13044
+ await walletStore$1.put('identity', JSON.stringify(identity));
13045
+ globalThis.peernet.selectedAccount = accounts[0][1];
13046
+ this.id = identity.walletId;
13047
+ }
13048
+ const identity = JSON.parse(new TextDecoder().decode(await walletStore$1.get('identity')));
13049
+ this.#wallet = new MultiWallet$1(this.network);
13050
+ await this.#wallet.recover(identity.mnemonic, password, this.network);
13051
+ }
13052
+ async export(password) {
13053
+ if (!password)
13054
+ throw new Error('IdentityExportError: password required');
13055
+ const identity = JSON.parse(new TextDecoder().decode(await walletStore$1.get('identity')));
13056
+ this.#wallet = new MultiWallet$1(this.network);
13057
+ await this.#wallet.recover(identity.mnemonic, password, this.network);
13058
+ return this.#wallet.toMultiWif();
13059
+ }
13060
+ async import(multiWIF) {
13061
+ this.#wallet = new MultiWallet$1(this.network);
13062
+ await this.#wallet.fromMultiWif(multiWIF);
13063
+ }
13064
+ async unlock({ key, iv, cipher }) {
10574
13065
  }
10575
- }
10576
- // TODO: multihash addresses
10577
- class HDAccount extends MultiWallet {
10578
13066
  /**
10579
- * @param {number} depth - acount depth
13067
+ * Lock current wallet or import wallet using a MultiWIF and lock
13068
+ *
13069
+ * @param password
13070
+ * @param multiWIF
10580
13071
  */
10581
- constructor(network, hdnode, depth = 0) {
10582
- super(network, hdnode);
10583
- this.hdnode = hdnode;
10584
- this.depth = depth;
10585
- this._prefix = `m/44'/${hdnode.network.coin_type}'/${depth}'/`;
13072
+ async lock(password, multiWIF) {
10586
13073
  }
13074
+ }
13075
+
13076
+ globalThis.LeofcoinStorage = LeofcoinStorage;
13077
+ globalThis.leofcoin = globalThis.leofcoin || {};
13078
+ globalThis.pubsub = globalThis.pubsub || new LittlePubSub();
13079
+ globalThis.globalSub = globalThis.globalSub || new LittlePubSub(true);
13080
+ /**
13081
+ * @access public
13082
+ * @example
13083
+ * const peernet = new Peernet();
13084
+ */
13085
+ class Peernet {
13086
+ identity;
13087
+ stores = [];
10587
13088
  /**
10588
- * @param {number} index - address index
13089
+ * @type {Object}
13090
+ * @property {Object} peer Instance of Peer
10589
13091
  */
10590
- async internal(index = 0) {
10591
- return this.hdnode.derivePath(`${this._prefix}1/${index}`);
13092
+ dht = new DhtEarth();
13093
+ /** @leofcoin/peernet-swarm/client */
13094
+ client;
13095
+ network;
13096
+ stars;
13097
+ networkVersion;
13098
+ bw;
13099
+ /**
13100
+ * @access public
13101
+ * @param {Object} options
13102
+ * @param {String} options.network - desired network
13103
+ * @param {String} options.stars - star list for selected network (these should match, don't mix networks)
13104
+ * @param {String} options.root - path to root directory
13105
+ * @param {String} options.storePrefix - prefix for datatores (lfc)
13106
+ *
13107
+ * @return {Promise} instance of Peernet
13108
+ *
13109
+ * @example
13110
+ * const peernet = new Peernet({network: 'leofcoin', root: '.leofcoin'});
13111
+ */
13112
+ constructor(options) {
13113
+ /**
13114
+ * @property {String} network - current network
13115
+ */
13116
+ this.network = options.network || 'leofcoin';
13117
+ this.stars = options.stars;
13118
+ const parts = this.network.split(':');
13119
+ this.networkVersion = options.networkVersion || parts.length > 1 ? parts[1] : 'mainnet';
13120
+ if (!options.storePrefix)
13121
+ options.storePrefix = 'lfc';
13122
+ if (!options.port)
13123
+ options.port = 2000;
13124
+ if (!options.root) {
13125
+ parts[1] ? options.root = `.${parts[0]}/${parts[1]}` : options.root = `.${this.network}`;
13126
+ }
13127
+ globalThis.peernet = this;
13128
+ this.bw = {
13129
+ up: 0,
13130
+ down: 0,
13131
+ };
13132
+ return this._init(options);
13133
+ }
13134
+ get id() {
13135
+ return this.identity.id;
13136
+ }
13137
+ get accounts() {
13138
+ return this.identity.accounts;
13139
+ }
13140
+ get defaultStores() {
13141
+ return ['account', 'wallet', 'block', 'transaction', 'chain', 'data', 'message'];
13142
+ }
13143
+ addProto(name, proto) {
13144
+ if (!globalThis.peernet.protos[name])
13145
+ globalThis.peernet.protos[name] = proto;
13146
+ }
13147
+ addCodec(codec) {
13148
+ return utils$1.addCodec(codec);
13149
+ }
13150
+ async addStore(name, prefix, root, isPrivate = true) {
13151
+ if (name === 'block' || name === 'transaction' || name === 'chain' ||
13152
+ name === 'data' || name === 'message')
13153
+ isPrivate = false;
13154
+ let Storage;
13155
+ this.hasDaemon ? Storage = LeofcoinStorageClient : Storage = LeofcoinStorage;
13156
+ if (!globalThis[`${name}Store`]) {
13157
+ globalThis[`${name}Store`] = new Storage(name, root);
13158
+ await globalThis[`${name}Store`].init();
13159
+ }
13160
+ globalThis[`${name}Store`].private = isPrivate;
13161
+ if (!isPrivate)
13162
+ this.stores.push(name);
10592
13163
  }
10593
13164
  /**
10594
- * @param {number} index - address index
13165
+ * @see MessageHandler
10595
13166
  */
10596
- async external(index = 0) {
10597
- return this.hdnode.derivePath(`${this._prefix}0/${index}`);
13167
+ prepareMessage(data) {
13168
+ return this._messageHandler.prepareMessage(data);
10598
13169
  }
10599
- }
13170
+ /**
13171
+ * @access public
13172
+ *
13173
+ * @return {Array} peerId
13174
+ */
13175
+ get peers() {
13176
+ return Object.keys(this.client.connections);
13177
+ }
13178
+ get connections() {
13179
+ return Object.values(this.client.connections);
13180
+ }
13181
+ get peerEntries() {
13182
+ return Object.entries(this.client.connections);
13183
+ }
13184
+ /**
13185
+ * @return {String} id - peerId
13186
+ */
13187
+ getConnection(id) {
13188
+ return this.client.connections[id];
13189
+ }
13190
+ /**
13191
+ * @private
13192
+ *
13193
+ * @param {Object} options
13194
+ * @param {String} options.root - path to root directory
13195
+ *
13196
+ * @return {Promise} instance of Peernet
13197
+ */
13198
+ async _init(options) {
13199
+ this.requestProtos = {};
13200
+ this.storePrefix = options.storePrefix;
13201
+ this.root = options.root;
13202
+ const { RequestMessage, ResponseMessage, PeerMessage, PeerMessageResponse, PeernetMessage, DHTMessage, DHTMessageResponse, DataMessage, DataMessageResponse, PsMessage, ChatMessage, PeernetFile
13203
+ // FolderMessageResponse
13204
+ } = await import(/* webpackChunkName: "messages" */ './messages-c820f513.js');
13205
+ /**
13206
+ * proto Object containing protos
13207
+ * @type {Object}
13208
+ * @property {PeernetMessage} protos[peernet-message] messageNode
13209
+ * @property {DHTMessage} protos[peernet-dht] messageNode
13210
+ * @property {DHTMessageResponse} protos[peernet-dht-response] messageNode
13211
+ * @property {DataMessage} protos[peernet-data] messageNode
13212
+ * @property {DataMessageResponse} protos[peernet-data-response] messageNode
13213
+ */
13214
+ globalThis.peernet.protos = {
13215
+ 'peernet-request': RequestMessage,
13216
+ 'peernet-response': ResponseMessage,
13217
+ 'peernet-peer': PeerMessage,
13218
+ 'peernet-peer-response': PeerMessageResponse,
13219
+ 'peernet-message': PeernetMessage,
13220
+ 'peernet-dht': DHTMessage,
13221
+ 'peernet-dht-response': DHTMessageResponse,
13222
+ 'peernet-data': DataMessage,
13223
+ 'peernet-data-response': DataMessageResponse,
13224
+ 'peernet-ps': PsMessage,
13225
+ 'chat-message': ChatMessage,
13226
+ 'peernet-file': PeernetFile
13227
+ };
13228
+ this._messageHandler = new MessageHandler(this.network);
13229
+ const { daemon, environment } = await target();
13230
+ this.hasDaemon = daemon;
13231
+ for (const store of this.defaultStores) {
13232
+ await this.addStore(store, options.storePrefix, options.root);
13233
+ }
13234
+ this.identity = new Identity(this.network);
13235
+ await this.identity.load();
13236
+ this._peerHandler = new PeerDiscovery(this.id);
13237
+ this.peerId = this.id;
13238
+ pubsub.subscribe('peer:connected', async (peer) => {
13239
+ // console.log(peer);
13240
+ // console.log({connected: peer.id, as: this._getPeerId(peer.id) });
13241
+ // peer.on('peernet.data', async (message) => {
13242
+ // const id = message.id
13243
+ // message = new PeernetMessage(Buffer.from(message.data.data))
13244
+ // const proto = protoFor(message.decoded.data)
13245
+ // this._protoHandler({id, proto}, peer)
13246
+ // })
13247
+ });
13248
+ /**
13249
+ * converts data -> message -> proto
13250
+ * @see DataHandler
13251
+ */
13252
+ pubsub.subscribe('peer:data', dataHandler);
13253
+ const importee = await import('./client-94d84d27.js');
13254
+ /**
13255
+ * @access public
13256
+ * @type {PeernetClient}
13257
+ */
13258
+ this.client = new importee.default(this.id, this.networkVersion, this.stars);
13259
+ if (globalThis.navigator) {
13260
+ globalThis.addEventListener('beforeunload', async () => this.client.close());
13261
+ }
13262
+ else {
13263
+ process.on('SIGTERM', async () => {
13264
+ process.stdin.resume();
13265
+ await this.client.close();
13266
+ process.exit();
13267
+ });
13268
+ }
13269
+ return this;
13270
+ }
13271
+ addRequestHandler(name, method) {
13272
+ this.requestProtos[name] = method;
13273
+ }
13274
+ sendMessage(peer, id, data) {
13275
+ if (peer.readyState === 'open') {
13276
+ peer.send(data, id);
13277
+ this.bw.up += data.length;
13278
+ }
13279
+ else if (peer.readyState === 'closed') ;
13280
+ }
13281
+ async handleDHT(peer, id, proto) {
13282
+ let { hash, store } = proto.decoded;
13283
+ let has;
13284
+ if (store) {
13285
+ store = globalThis[`${store}Store`];
13286
+ has = store.private ? false : await store.has(hash);
13287
+ }
13288
+ else {
13289
+ has = await this.has(hash);
13290
+ }
13291
+ const data = await new globalThis.peernet.protos['peernet-dht-response']({ hash, has });
13292
+ const node = await this.prepareMessage(data);
13293
+ this.sendMessage(peer, id, node.encoded);
13294
+ }
13295
+ async handleData(peer, id, proto) {
13296
+ let { hash, store } = proto.decoded;
13297
+ let data;
13298
+ store = globalThis[`${store}Store`] || await this.whichStore([...this.stores], hash);
13299
+ if (store && !store.private) {
13300
+ data = await store.get(hash);
13301
+ if (data) {
13302
+ data = await new globalThis.peernet.protos['peernet-data-response']({ hash, data });
13303
+ const node = await this.prepareMessage(data);
13304
+ this.sendMessage(peer, id, node.encoded);
13305
+ }
13306
+ }
13307
+ }
13308
+ async handleRequest(peer, id, proto) {
13309
+ const method = this.requestProtos[proto.decoded.request];
13310
+ if (method) {
13311
+ const data = await method();
13312
+ const node = await this.prepareMessage(data);
13313
+ this.sendMessage(peer, id, node.encoded);
13314
+ }
13315
+ }
13316
+ /**
13317
+ * @private
13318
+ *
13319
+ * @param {Buffer} message - peernet message
13320
+ * @param {PeernetPeer} peer - peernet peer
13321
+ */
13322
+ async _protoHandler(message, peer, from) {
13323
+ const { id, proto } = message;
13324
+ this.bw.down += proto.encoded.length;
13325
+ switch (proto.name) {
13326
+ case 'peernet-dht': {
13327
+ this.handleDHT(peer, id, proto);
13328
+ break;
13329
+ }
13330
+ case 'peernet-data': {
13331
+ this.handleData(peer, id, proto);
13332
+ break;
13333
+ }
13334
+ case 'peernet-request': {
13335
+ this.handleRequest(peer, id, proto);
13336
+ }
13337
+ case 'peernet-ps': {
13338
+ if (peer.peerId !== this.id)
13339
+ globalSub.publish(proto.decoded.topic, proto.decoded.data);
13340
+ }
13341
+ }
13342
+ }
13343
+ /**
13344
+ * performs a walk and resolves first encounter
13345
+ *
13346
+ * @param {String} hash
13347
+ */
13348
+ async walk(hash) {
13349
+ if (!hash)
13350
+ throw new Error('hash expected, received undefined');
13351
+ const data = await new globalThis.peernet.protos['peernet-dht']({ hash });
13352
+ this.client.id;
13353
+ const walk = async (peer) => {
13354
+ const node = await this.prepareMessage(data);
13355
+ let result = await peer.request(node.encoded);
13356
+ result = new Uint8Array(Object.values(result));
13357
+ const proto = await protoFor(result);
13358
+ if (proto.name !== 'peernet-dht-response')
13359
+ throw dhtError(proto.name);
13360
+ // TODO: give ip and port (just used for location)
13361
+ if (!peer.connection.remoteAddress || !peer.connection.localAddress) {
13362
+ peer.connection.remoteFamily = 'ipv4';
13363
+ peer.connection.remoteAddress = '127.0.0.1';
13364
+ peer.connection.remotePort = '0000';
13365
+ }
13366
+ const peerInfo = {
13367
+ family: peer.connection.remoteFamily || peer.connection.localFamily,
13368
+ address: peer.connection.remoteAddress || peer.connection.localAddress,
13369
+ port: peer.connection.remotePort || peer.connection.localPort,
13370
+ id: peer.peerId,
13371
+ };
13372
+ if (proto.decoded.has)
13373
+ this.dht.addProvider(peerInfo, proto.decoded.hash);
13374
+ };
13375
+ let walks = [];
13376
+ for (const peer of this.connections) {
13377
+ if (peer.peerId !== this.id) {
13378
+ walks.push(walk(peer));
13379
+ }
13380
+ }
13381
+ return Promise.all(walks);
13382
+ }
13383
+ /**
13384
+ * Override DHT behavior, try's finding the content three times
13385
+ *
13386
+ * @param {String} hash
13387
+ */
13388
+ async providersFor(hash) {
13389
+ let providers = await this.dht.providersFor(hash);
13390
+ // walk the network to find a provider
13391
+ if (!providers || providers.length === 0) {
13392
+ await this.walk(hash);
13393
+ providers = await this.dht.providersFor(hash);
13394
+ // second walk the network to find a provider
13395
+ if (!providers || providers.length === 0) {
13396
+ await this.walk(hash);
13397
+ providers = await this.dht.providersFor(hash);
13398
+ }
13399
+ // last walk
13400
+ if (!providers || providers.length === 0) {
13401
+ await this.walk(hash);
13402
+ providers = await this.dht.providersFor(hash);
13403
+ }
13404
+ }
13405
+ // undefined if no providers given
13406
+ return providers;
13407
+ }
13408
+ get block() {
13409
+ return {
13410
+ get: async (hash) => {
13411
+ const data = await blockStore.has(hash);
13412
+ if (data)
13413
+ return blockStore.get(hash);
13414
+ return this.requestData(hash, 'block');
13415
+ },
13416
+ put: async (hash, data) => {
13417
+ if (await blockStore.has(hash))
13418
+ return;
13419
+ return await blockStore.put(hash, data);
13420
+ },
13421
+ has: async (hash) => await blockStore.has(hash, 'block'),
13422
+ };
13423
+ }
13424
+ get transaction() {
13425
+ return {
13426
+ get: async (hash) => {
13427
+ const data = await transactionStore.has(hash);
13428
+ if (data)
13429
+ return await transactionStore.get(hash);
13430
+ return this.requestData(hash, 'transaction');
13431
+ },
13432
+ put: async (hash, data) => {
13433
+ if (await transactionStore.has(hash))
13434
+ return;
13435
+ return await transactionStore.put(hash, data);
13436
+ },
13437
+ has: async (hash) => await transactionStore.has(hash),
13438
+ };
13439
+ }
13440
+ async requestData(hash, store) {
13441
+ const providers = await this.providersFor(hash);
13442
+ if (!providers || providers.size === 0)
13443
+ throw nothingFoundError(hash);
13444
+ debug(`found ${providers.size} provider(s) for ${hash}`);
13445
+ // get closest peer on earth
13446
+ const closestPeer = await this.dht.closestPeer(providers);
13447
+ // get peer instance by id
13448
+ if (!closestPeer || !closestPeer.id)
13449
+ return this.requestData(hash, store?.name || store);
13450
+ const id = closestPeer.id;
13451
+ if (this.connections) {
13452
+ let closest = this.connections.filter((peer) => {
13453
+ if (peer.peerId === id)
13454
+ return peer;
13455
+ });
13456
+ let data = await new globalThis.peernet.protos['peernet-data']({ hash, store: store?.name || store });
13457
+ const node = await this.prepareMessage(data);
13458
+ if (closest[0])
13459
+ data = await closest[0].request(node.encoded);
13460
+ else {
13461
+ closest = this.connections.filter((peer) => {
13462
+ if (peer.peerId === id)
13463
+ return peer;
13464
+ });
13465
+ if (closest[0])
13466
+ data = await closest[0].request(node.encoded);
13467
+ }
13468
+ const proto = await protoFor(data);
13469
+ // TODO: store data automaticly or not
13470
+ return BufferToUint8Array(proto.decoded.data);
13471
+ // this.put(hash, proto.decoded.data)
13472
+ }
13473
+ return;
13474
+ }
13475
+ get message() {
13476
+ return {
13477
+ /**
13478
+ * Get content for given message hash
13479
+ *
13480
+ * @param {String} hash
13481
+ */
13482
+ get: async (hash) => {
13483
+ debug(`get message ${hash}`);
13484
+ const message = await messageStore.has(hash);
13485
+ if (message)
13486
+ return await messageStore.get(hash);
13487
+ return this.requestData(hash, 'message');
13488
+ },
13489
+ /**
13490
+ * put message content
13491
+ *
13492
+ * @param {String} hash
13493
+ * @param {Buffer} message
13494
+ */
13495
+ put: async (hash, message) => await messageStore.put(hash, message),
13496
+ /**
13497
+ * @param {String} hash
13498
+ * @return {Boolean}
13499
+ */
13500
+ has: async (hash) => await messageStore.has(hash),
13501
+ };
13502
+ }
13503
+ get data() {
13504
+ return {
13505
+ /**
13506
+ * Get content for given data hash
13507
+ *
13508
+ * @param {String} hash
13509
+ */
13510
+ get: async (hash) => {
13511
+ debug(`get data ${hash}`);
13512
+ const data = await dataStore.has(hash);
13513
+ if (data)
13514
+ return await dataStore.get(hash);
13515
+ return this.requestData(hash, 'data');
13516
+ },
13517
+ /**
13518
+ * put data content
13519
+ *
13520
+ * @param {String} hash
13521
+ * @param {Buffer} data
13522
+ */
13523
+ put: async (hash, data) => await dataStore.put(hash, data),
13524
+ /**
13525
+ * @param {String} hash
13526
+ * @return {Boolean}
13527
+ */
13528
+ has: async (hash) => await dataStore.has(hash),
13529
+ };
13530
+ }
13531
+ get folder() {
13532
+ return {
13533
+ /**
13534
+ * Get content for given data hash
13535
+ *
13536
+ * @param {String} hash
13537
+ */
13538
+ get: async (hash) => {
13539
+ debug(`get data ${hash}`);
13540
+ const data = await dataStore.has(hash);
13541
+ if (data)
13542
+ return await dataStore.get(hash);
13543
+ return this.requestData(hash, 'data');
13544
+ },
13545
+ /**
13546
+ * put data content
13547
+ *
13548
+ * @param {String} hash
13549
+ * @param {Buffer} data
13550
+ */
13551
+ put: async (hash, data) => await dataStore.put(hash, data),
13552
+ /**
13553
+ * @param {String} hash
13554
+ * @return {Boolean}
13555
+ */
13556
+ has: async (hash) => await dataStore.has(hash),
13557
+ };
13558
+ }
13559
+ async addFolder(files) {
13560
+ const links = [];
13561
+ for (const file of files) {
13562
+ const fileNode = await new globalThis.peernet.protos['peernet-file'](file);
13563
+ const hash = await fileNode.hash;
13564
+ await dataStore.put(hash, fileNode.encoded);
13565
+ links.push({ hash, path: file.path });
13566
+ }
13567
+ const node = await new globalThis.peernet.protos['peernet-file']({ path: '/', links });
13568
+ const hash = await node.hash;
13569
+ await dataStore.put(hash, node.encoded);
13570
+ return hash;
13571
+ }
13572
+ async ls(hash, options) {
13573
+ let data;
13574
+ const has = await dataStore.has(hash);
13575
+ data = has ? await dataStore.get(hash) : await this.requestData(hash, 'data');
13576
+ const node = await new peernet.protos['peernet-file'](data);
13577
+ await node.decode();
13578
+ console.log(data);
13579
+ const paths = [];
13580
+ if (node.decoded?.links.length === 0)
13581
+ throw new Error(`${hash} is a file`);
13582
+ for (const { path, hash } of node.decoded.links) {
13583
+ paths.push({ path, hash });
13584
+ }
13585
+ if (options?.pin)
13586
+ await dataStore.put(hash, node.encoded);
13587
+ return paths;
13588
+ }
13589
+ async cat(hash, options) {
13590
+ let data;
13591
+ const has = await dataStore.has(hash);
13592
+ data = has ? await dataStore.get(hash) : await this.requestData(hash, 'data');
13593
+ const node = await new peernet.protos['peernet-file'](data);
13594
+ if (node.decoded?.links.length > 0)
13595
+ throw new Error(`${hash} is a directory`);
13596
+ if (options?.pin)
13597
+ await dataStore.put(hash, node.encoded);
13598
+ return node.decoded.content;
13599
+ }
13600
+ /**
13601
+ * goes trough given stores and tries to find data for given hash
13602
+ * @param {Array} stores
13603
+ * @param {string} hash
13604
+ */
13605
+ async whichStore(stores, hash) {
13606
+ let store = stores.pop();
13607
+ store = globalThis[`${store}Store`];
13608
+ if (store) {
13609
+ const has = await store.has(hash);
13610
+ if (has)
13611
+ return store;
13612
+ if (stores.length > 0)
13613
+ return this.whichStore(stores, hash);
13614
+ }
13615
+ else
13616
+ return;
13617
+ }
13618
+ /**
13619
+ * Get content for given hash
13620
+ *
13621
+ * @param {String} hash - the hash of the wanted data
13622
+ * @param {String} store - storeName to access
13623
+ */
13624
+ async get(hash, store) {
13625
+ debug(`get ${hash}`);
13626
+ let data;
13627
+ if (store)
13628
+ store = globalThis[`${store}Store`];
13629
+ if (!store)
13630
+ store = await this.whichStore([...this.stores], hash);
13631
+ if (store && await store.has(hash))
13632
+ data = await store.get(hash);
13633
+ if (data)
13634
+ return data;
13635
+ return this.requestData(hash, store?.name || store);
13636
+ }
13637
+ /**
13638
+ * put content
13639
+ *
13640
+ * @param {String} hash
13641
+ * @param {Buffer} data
13642
+ * @param {String} store - storeName to access
13643
+ */
13644
+ async put(hash, data, store = 'data') {
13645
+ store = globalThis[`${store}Store`];
13646
+ return store.put(hash, data);
13647
+ }
13648
+ /**
13649
+ * @param {String} hash
13650
+ * @return {Boolean}
13651
+ */
13652
+ async has(hash) {
13653
+ const store = await this.whichStore([...this.stores], hash);
13654
+ if (store) {
13655
+ return store.private ? false : true;
13656
+ }
13657
+ return false;
13658
+ }
13659
+ /**
13660
+ *
13661
+ * @param {String} topic
13662
+ * @param {String|Object|Array|Boolean|Buffer} data
13663
+ */
13664
+ async publish(topic, data) {
13665
+ // globalSub.publish(topic, data)
13666
+ const id = Math.random().toString(36).slice(-12);
13667
+ data = await new globalThis.peernet.protos['peernet-ps']({ data, topic });
13668
+ for (const peer of this.connections) {
13669
+ if (peer.peerId !== this.peerId) {
13670
+ const node = await this.prepareMessage(data);
13671
+ this.sendMessage(peer, id, node.encoded);
13672
+ }
13673
+ // TODO: if peer subscribed
13674
+ }
13675
+ }
13676
+ createHash(data, name) {
13677
+ return new CodeHash(data, { name });
13678
+ }
13679
+ /**
13680
+ *
13681
+ * @param {String} topic
13682
+ * @param {Method} cb
13683
+ */
13684
+ async subscribe(topic, callback) {
13685
+ // TODO: if peer subscribed
13686
+ globalSub.subscribe(topic, callback);
13687
+ }
13688
+ async removePeer(peer) {
13689
+ return this.client.removePeer(peer);
13690
+ }
13691
+ get Buffer() {
13692
+ return Buffer;
13693
+ }
13694
+ }
13695
+ globalThis.Peernet = Peernet;
10600
13696
 
10601
- export { MultiWallet as default };
13697
+ export { FormatInterface as F, LittlePubSub as L, MultiWallet$1 as M, Peernet as P };