@leofcoin/peernet 0.17.0 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/exports/browser/client-13d9b3de.js +645 -0
  2. package/exports/browser/{index-019272d8.js → index-19803d3b.js} +38 -923
  3. package/exports/browser/{index-3a25de4d.js → index-73b8d9b9.js} +3 -1
  4. package/exports/browser/{messages-4850566c.js → messages-bb950ed7.js} +51 -130
  5. package/exports/browser/peernet-24ed8563.js +2978 -0
  6. package/exports/browser/peernet.js +1 -1
  7. package/exports/{messages-796c4d5c.js → messages-d8852e16.js} +50 -129
  8. package/exports/peernet.js +1 -1
  9. package/package.json +2 -2
  10. package/src/messages/chat.js +0 -3
  11. package/src/messages/data-response.js +0 -3
  12. package/src/messages/data.js +0 -3
  13. package/src/messages/dht-response.js +0 -3
  14. package/src/messages/dht.js +0 -6
  15. package/src/messages/file-link.js +18 -0
  16. package/src/messages/file.js +0 -3
  17. package/src/messages/peer-response.js +0 -3
  18. package/src/messages/peer.js +0 -4
  19. package/src/messages/peernet.js +0 -3
  20. package/src/messages/ps.js +0 -4
  21. package/src/messages/request.js +0 -3
  22. package/src/messages/response.js +0 -3
  23. package/src/proto/chat-message.proto.js +6 -7
  24. package/src/proto/data-response.proto.js +3 -6
  25. package/src/proto/data.proto.js +3 -6
  26. package/src/proto/dht-response.proto.js +3 -6
  27. package/src/proto/dht.proto.js +3 -6
  28. package/src/proto/file-link.proto.js +5 -0
  29. package/src/proto/file.proto.js +4 -13
  30. package/src/proto/peer-response.proto.js +2 -5
  31. package/src/proto/peer.proto.js +2 -5
  32. package/src/proto/peernet.proto.js +7 -9
  33. package/src/proto/ps.proto.js +4 -6
  34. package/src/proto/request.proto.js +2 -5
  35. package/src/proto/response.proto.js +2 -5
  36. package/test.js +2 -2
  37. package/test2.js +1 -1
  38. package/exports/browser/client-29660363.js +0 -690
  39. package/exports/browser/peernet-379769d5.js +0 -2896
@@ -1,2896 +0,0 @@
1
- import { K as KeyValue } from './value-40634404.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
- /******************************************************************************
63
- Copyright (c) Microsoft Corporation.
64
-
65
- Permission to use, copy, modify, and/or distribute this software for any
66
- purpose with or without fee is hereby granted.
67
-
68
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
69
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
70
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
71
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
72
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
73
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
74
- PERFORMANCE OF THIS SOFTWARE.
75
- ***************************************************************************** */
76
- /* global Reflect, Promise */
77
-
78
- var extendStatics = function(d, b) {
79
- extendStatics = Object.setPrototypeOf ||
80
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
81
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
82
- return extendStatics(d, b);
83
- };
84
-
85
- function __extends(d, b) {
86
- if (typeof b !== "function" && b !== null)
87
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
88
- extendStatics(d, b);
89
- function __() { this.constructor = d; }
90
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
91
- }
92
-
93
- var __assign = function() {
94
- __assign = Object.assign || function __assign(t) {
95
- for (var s, i = 1, n = arguments.length; i < n; i++) {
96
- s = arguments[i];
97
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
98
- }
99
- return t;
100
- };
101
- return __assign.apply(this, arguments);
102
- };
103
-
104
- function __awaiter$1(thisArg, _arguments, P, generator) {
105
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
106
- return new (P || (P = Promise))(function (resolve, reject) {
107
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
108
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
109
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
110
- step((generator = generator.apply(thisArg, _arguments || [])).next());
111
- });
112
- }
113
-
114
- function __generator(thisArg, body) {
115
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
116
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
117
- function verb(n) { return function (v) { return step([n, v]); }; }
118
- function step(op) {
119
- if (f) throw new TypeError("Generator is already executing.");
120
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
121
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
122
- if (y = 0, t) op = [op[0] & 2, t.value];
123
- switch (op[0]) {
124
- case 0: case 1: t = op; break;
125
- case 4: _.label++; return { value: op[1], done: false };
126
- case 5: _.label++; y = op[1]; op = [0]; continue;
127
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
128
- default:
129
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
130
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
131
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
132
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
133
- if (t[2]) _.ops.pop();
134
- _.trys.pop(); continue;
135
- }
136
- op = body.call(thisArg, _);
137
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
138
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
139
- }
140
- }
141
-
142
- function __values(o) {
143
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
144
- if (m) return m.call(o);
145
- if (o && typeof o.length === "number") return {
146
- next: function () {
147
- if (o && i >= o.length) o = void 0;
148
- return { value: o && o[i++], done: !o };
149
- }
150
- };
151
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
152
- }
153
-
154
- function __spreadArray(to, from, pack) {
155
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
156
- if (ar || !(i in from)) {
157
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
158
- ar[i] = from[i];
159
- }
160
- }
161
- return to.concat(ar || Array.prototype.slice.call(from));
162
- }
163
-
164
- function __asyncValues(o) {
165
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
166
- var m = o[Symbol.asyncIterator], i;
167
- return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
168
- function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
169
- function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
170
- }
171
-
172
- // base-x encoding / decoding
173
- // Copyright (c) 2018 base-x contributors
174
- // Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)
175
- // Distributed under the MIT software license, see the accompanying
176
- // file LICENSE or http://www.opensource.org/licenses/mit-license.php.
177
- var base$1 = function (ALPHABET) {
178
- if (ALPHABET.length >= 255) {
179
- throw new TypeError('Alphabet too long');
180
- }
181
- var BASE_MAP = new Uint8Array(256);
182
- for (var j = 0; j < BASE_MAP.length; j++) {
183
- BASE_MAP[j] = 255;
184
- }
185
- for (var i = 0; i < ALPHABET.length; i++) {
186
- var x = ALPHABET.charAt(i);
187
- var xc = x.charCodeAt(0);
188
- if (BASE_MAP[xc] !== 255) {
189
- throw new TypeError(x + ' is ambiguous');
190
- }
191
- BASE_MAP[xc] = i;
192
- }
193
- var BASE = ALPHABET.length;
194
- var LEADER = ALPHABET.charAt(0);
195
- var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up
196
- var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up
197
- var encode = function (source) {
198
- if (source instanceof Uint8Array) ;
199
- else if (ArrayBuffer.isView(source)) {
200
- source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
201
- }
202
- else if (Array.isArray(source)) {
203
- source = Uint8Array.from(source);
204
- }
205
- if (!(source instanceof Uint8Array)) {
206
- throw new TypeError('Expected Uint8Array');
207
- }
208
- if (source.length === 0) {
209
- return '';
210
- }
211
- // Skip & count leading zeroes.
212
- var zeroes = 0;
213
- var length = 0;
214
- var pbegin = 0;
215
- var pend = source.length;
216
- while (pbegin !== pend && source[pbegin] === 0) {
217
- pbegin++;
218
- zeroes++;
219
- }
220
- // Allocate enough space in big-endian base58 representation.
221
- var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;
222
- var b58 = new Uint8Array(size);
223
- // Process the bytes.
224
- while (pbegin !== pend) {
225
- var carry = source[pbegin];
226
- // Apply "b58 = b58 * 256 + ch".
227
- var i = 0;
228
- for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {
229
- carry += (256 * b58[it1]) >>> 0;
230
- b58[it1] = (carry % BASE) >>> 0;
231
- carry = (carry / BASE) >>> 0;
232
- }
233
- if (carry !== 0) {
234
- throw new Error('Non-zero carry');
235
- }
236
- length = i;
237
- pbegin++;
238
- }
239
- // Skip leading zeroes in base58 result.
240
- var it2 = size - length;
241
- while (it2 !== size && b58[it2] === 0) {
242
- it2++;
243
- }
244
- // Translate the result into a string.
245
- var str = LEADER.repeat(zeroes);
246
- for (; it2 < size; ++it2) {
247
- str += ALPHABET.charAt(b58[it2]);
248
- }
249
- return str;
250
- };
251
- var decodeUnsafe = function (source) {
252
- if (typeof source !== 'string') {
253
- throw new TypeError('Expected String');
254
- }
255
- if (source.length === 0) {
256
- return new Uint8Array();
257
- }
258
- var psz = 0;
259
- // Skip and count leading '1's.
260
- var zeroes = 0;
261
- var length = 0;
262
- while (source[psz] === LEADER) {
263
- zeroes++;
264
- psz++;
265
- }
266
- // Allocate enough space in big-endian base256 representation.
267
- var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.
268
- var b256 = new Uint8Array(size);
269
- // Process the characters.
270
- while (source[psz]) {
271
- // Decode character
272
- var carry = BASE_MAP[source.charCodeAt(psz)];
273
- // Invalid character
274
- if (carry === 255) {
275
- return;
276
- }
277
- var i = 0;
278
- for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {
279
- carry += (BASE * b256[it3]) >>> 0;
280
- b256[it3] = (carry % 256) >>> 0;
281
- carry = (carry / 256) >>> 0;
282
- }
283
- if (carry !== 0) {
284
- throw new Error('Non-zero carry');
285
- }
286
- length = i;
287
- psz++;
288
- }
289
- // Skip leading zeroes in b256.
290
- var it4 = size - length;
291
- while (it4 !== size && b256[it4] === 0) {
292
- it4++;
293
- }
294
- var vch = new Uint8Array(zeroes + (size - it4));
295
- var j = zeroes;
296
- while (it4 !== size) {
297
- vch[j++] = b256[it4++];
298
- }
299
- return vch;
300
- };
301
- var decode = function (string) {
302
- var buffer = decodeUnsafe(string);
303
- if (buffer) {
304
- return buffer;
305
- }
306
- throw new Error('Non-base' + BASE + ' character');
307
- };
308
- return {
309
- encode: encode,
310
- decodeUnsafe: decodeUnsafe,
311
- decode: decode
312
- };
313
- };
314
-
315
- var base32 = 'abcdefghijklmnopqrstuvwxyz234567';
316
- var base32Hex = '0123456789abcdefghijklmnopqrstuv';
317
- var decode$2 = function (string, hex) {
318
- if (hex === void 0) { hex = false; }
319
- var decoder = hex ? base$1(base32Hex) : base$1(base32);
320
- return decoder.decode(string);
321
- };
322
- var base32$1 = {
323
- encode: function (uint8Array, hex) {
324
- if (hex === void 0) { hex = false; }
325
- var encoder = hex ? base$1(base32Hex) : base$1(base32);
326
- return encoder.encode(uint8Array);
327
- },
328
- decode: decode$2,
329
- isBase32: function (string, hex) {
330
- if (hex === void 0) { hex = false; }
331
- try {
332
- decode$2(string, hex);
333
- return true;
334
- }
335
- catch (e) {
336
- return false;
337
- }
338
- }
339
- };
340
-
341
- // base-x encoding / decoding
342
- // Copyright (c) 2018 base-x contributors
343
- // Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)
344
- // Distributed under the MIT software license, see the accompanying
345
- // file LICENSE or http://www.opensource.org/licenses/mit-license.php.
346
- var base = function (ALPHABET) {
347
- if (ALPHABET.length >= 255) {
348
- throw new TypeError('Alphabet too long');
349
- }
350
- var BASE_MAP = new Uint8Array(256);
351
- for (var j = 0; j < BASE_MAP.length; j++) {
352
- BASE_MAP[j] = 255;
353
- }
354
- for (var i = 0; i < ALPHABET.length; i++) {
355
- var x = ALPHABET.charAt(i);
356
- var xc = x.charCodeAt(0);
357
- if (BASE_MAP[xc] !== 255) {
358
- throw new TypeError(x + ' is ambiguous');
359
- }
360
- BASE_MAP[xc] = i;
361
- }
362
- var BASE = ALPHABET.length;
363
- var LEADER = ALPHABET.charAt(0);
364
- var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up
365
- var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up
366
- var encode = function (source) {
367
- if (source instanceof Uint8Array) ;
368
- else if (ArrayBuffer.isView(source)) {
369
- source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
370
- }
371
- else if (Array.isArray(source)) {
372
- source = Uint8Array.from(source);
373
- }
374
- if (!(source instanceof Uint8Array)) {
375
- throw new TypeError('Expected Uint8Array');
376
- }
377
- if (source.length === 0) {
378
- return '';
379
- }
380
- // Skip & count leading zeroes.
381
- var zeroes = 0;
382
- var length = 0;
383
- var pbegin = 0;
384
- var pend = source.length;
385
- while (pbegin !== pend && source[pbegin] === 0) {
386
- pbegin++;
387
- zeroes++;
388
- }
389
- // Allocate enough space in big-endian base58 representation.
390
- var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;
391
- var b58 = new Uint8Array(size);
392
- // Process the bytes.
393
- while (pbegin !== pend) {
394
- var carry = source[pbegin];
395
- // Apply "b58 = b58 * 256 + ch".
396
- var i = 0;
397
- for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {
398
- carry += (256 * b58[it1]) >>> 0;
399
- b58[it1] = (carry % BASE) >>> 0;
400
- carry = (carry / BASE) >>> 0;
401
- }
402
- if (carry !== 0) {
403
- throw new Error('Non-zero carry');
404
- }
405
- length = i;
406
- pbegin++;
407
- }
408
- // Skip leading zeroes in base58 result.
409
- var it2 = size - length;
410
- while (it2 !== size && b58[it2] === 0) {
411
- it2++;
412
- }
413
- // Translate the result into a string.
414
- var str = LEADER.repeat(zeroes);
415
- for (; it2 < size; ++it2) {
416
- str += ALPHABET.charAt(b58[it2]);
417
- }
418
- return str;
419
- };
420
- var decodeUnsafe = function (source) {
421
- if (typeof source !== 'string') {
422
- throw new TypeError('Expected String');
423
- }
424
- if (source.length === 0) {
425
- return new Uint8Array();
426
- }
427
- var psz = 0;
428
- // Skip and count leading '1's.
429
- var zeroes = 0;
430
- var length = 0;
431
- while (source[psz] === LEADER) {
432
- zeroes++;
433
- psz++;
434
- }
435
- // Allocate enough space in big-endian base256 representation.
436
- var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.
437
- var b256 = new Uint8Array(size);
438
- // Process the characters.
439
- while (source[psz]) {
440
- // Decode character
441
- var carry = BASE_MAP[source.charCodeAt(psz)];
442
- // Invalid character
443
- if (carry === 255) {
444
- return;
445
- }
446
- var i = 0;
447
- for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {
448
- carry += (BASE * b256[it3]) >>> 0;
449
- b256[it3] = (carry % 256) >>> 0;
450
- carry = (carry / 256) >>> 0;
451
- }
452
- if (carry !== 0) {
453
- throw new Error('Non-zero carry');
454
- }
455
- length = i;
456
- psz++;
457
- }
458
- // Skip leading zeroes in b256.
459
- var it4 = size - length;
460
- while (it4 !== size && b256[it4] === 0) {
461
- it4++;
462
- }
463
- var vch = new Uint8Array(zeroes + (size - it4));
464
- var j = zeroes;
465
- while (it4 !== size) {
466
- vch[j++] = b256[it4++];
467
- }
468
- return vch;
469
- };
470
- var decode = function (string) {
471
- var buffer = decodeUnsafe(string);
472
- if (buffer) {
473
- return buffer;
474
- }
475
- throw new Error('Non-base' + BASE + ' character');
476
- };
477
- return {
478
- encode: encode,
479
- decodeUnsafe: decodeUnsafe,
480
- decode: decode
481
- };
482
- };
483
-
484
- var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
485
- var base58 = base(ALPHABET);
486
- var decode$1 = function (string) { return base58.decode(string); };
487
- var base58$1 = {
488
- encode: function (uint8Array) { return base58.encode(uint8Array); },
489
- decode: decode$1,
490
- isBase58: function (string) {
491
- try {
492
- decode$1(string);
493
- return true;
494
- }
495
- catch (e) {
496
- return false;
497
- }
498
- }
499
- };
500
-
501
- /**
502
- * @param {string}
503
- */
504
- var isHex = (function (string) { return /^[A-F0-9]+$/i.test(string); });
505
-
506
- var BasicInterface$1 = /** @class */ (function () {
507
- function BasicInterface() {
508
- }
509
- // get Codec(): Codec {}
510
- BasicInterface.prototype.protoEncode = function (data) {
511
- return __awaiter$1(this, void 0, void 0, function () {
512
- return __generator(this, function (_a) {
513
- // check schema
514
- return [2 /*return*/, new TextEncoder().encode(data)];
515
- });
516
- });
517
- };
518
- BasicInterface.prototype.protoDecode = function (data) {
519
- return __awaiter$1(this, void 0, void 0, function () {
520
- return __generator(this, function (_a) {
521
- // check schema
522
- return [2 /*return*/, new TextDecoder().decode(data)];
523
- });
524
- });
525
- };
526
- BasicInterface.prototype.isHex = function (string) {
527
- return isHex(string);
528
- };
529
- BasicInterface.prototype.isBase32 = function (string) {
530
- return base32$1.isBase32(string);
531
- };
532
- BasicInterface.prototype.isBase58 = function (string) {
533
- return base58$1.isBase58(string);
534
- };
535
- BasicInterface.prototype.fromBs32 = function (encoded) {
536
- this.encoded = base32$1.decode(encoded);
537
- return this.decode();
538
- };
539
- BasicInterface.prototype.fromBs58 = function (encoded) {
540
- this.encoded = base58$1.decode(encoded);
541
- return this.decode();
542
- };
543
- BasicInterface.prototype.toArray = function () {
544
- var _a, e_1, _b, _c;
545
- return __awaiter$1(this, void 0, void 0, function () {
546
- var array, _d, _e, _f, value, e_1_1;
547
- return __generator(this, function (_g) {
548
- switch (_g.label) {
549
- case 0:
550
- array = [];
551
- _g.label = 1;
552
- case 1:
553
- _g.trys.push([1, 6, 7, 12]);
554
- _d = true, _e = __asyncValues(this.encoded.values());
555
- _g.label = 2;
556
- case 2: return [4 /*yield*/, _e.next()];
557
- case 3:
558
- if (!(_f = _g.sent(), _a = _f.done, !_a)) return [3 /*break*/, 5];
559
- _c = _f.value;
560
- _d = false;
561
- try {
562
- value = _c;
563
- array.push(value);
564
- }
565
- finally {
566
- _d = true;
567
- }
568
- _g.label = 4;
569
- case 4: return [3 /*break*/, 2];
570
- case 5: return [3 /*break*/, 12];
571
- case 6:
572
- e_1_1 = _g.sent();
573
- e_1 = { error: e_1_1 };
574
- return [3 /*break*/, 12];
575
- case 7:
576
- _g.trys.push([7, , 10, 11]);
577
- if (!(!_d && !_a && (_b = _e["return"]))) return [3 /*break*/, 9];
578
- return [4 /*yield*/, _b.call(_e)];
579
- case 8:
580
- _g.sent();
581
- _g.label = 9;
582
- case 9: return [3 /*break*/, 11];
583
- case 10:
584
- if (e_1) throw e_1.error;
585
- return [7 /*endfinally*/];
586
- case 11: return [7 /*endfinally*/];
587
- case 12: return [2 /*return*/, array];
588
- }
589
- });
590
- });
591
- };
592
- BasicInterface.prototype.fromString = function (string) {
593
- var array = string.split(',');
594
- var arrayLike = array.map(function (string) { return Number(string); });
595
- this.encoded = Uint8Array.from(arrayLike);
596
- return this.decode();
597
- };
598
- BasicInterface.prototype.fromArray = function (array) {
599
- this.encoded = Uint8Array.from(__spreadArray([], array, true));
600
- return this.decode();
601
- };
602
- BasicInterface.prototype.fromEncoded = function (encoded) {
603
- this.encoded = encoded;
604
- return this.decode();
605
- };
606
- BasicInterface.prototype.fromHex = function (encoded) {
607
- this.encoded = Buffer.from(encoded, 'hex');
608
- return this.decode();
609
- };
610
- BasicInterface.prototype.toString = function (encoding) {
611
- if (encoding === void 0) { encoding = 'utf8'; }
612
- return __awaiter$1(this, void 0, void 0, function () {
613
- return __generator(this, function (_a) {
614
- switch (_a.label) {
615
- case 0:
616
- if (!!this.encoded) return [3 /*break*/, 2];
617
- return [4 /*yield*/, this.encode()];
618
- case 1:
619
- _a.sent();
620
- _a.label = 2;
621
- case 2: return [2 /*return*/, this.encoded.toString(encoding)];
622
- }
623
- });
624
- });
625
- };
626
- /**
627
- * @return {String} encoded
628
- */
629
- BasicInterface.prototype.toHex = function () {
630
- return this.toString('hex');
631
- };
632
- /**
633
- * @return {String} encoded
634
- */
635
- BasicInterface.prototype.toBs32 = function () {
636
- return __awaiter$1(this, void 0, void 0, function () {
637
- return __generator(this, function (_a) {
638
- switch (_a.label) {
639
- case 0:
640
- if (!!this.encoded) return [3 /*break*/, 2];
641
- return [4 /*yield*/, this.encode()];
642
- case 1:
643
- _a.sent();
644
- _a.label = 2;
645
- case 2: return [2 /*return*/, base32$1.encode(this.encoded)];
646
- }
647
- });
648
- });
649
- };
650
- /**
651
- * @return {String} encoded
652
- */
653
- BasicInterface.prototype.toBs58 = function () {
654
- return __awaiter$1(this, void 0, void 0, function () {
655
- return __generator(this, function (_a) {
656
- switch (_a.label) {
657
- case 0:
658
- if (!!this.encoded) return [3 /*break*/, 2];
659
- return [4 /*yield*/, this.encode()];
660
- case 1:
661
- _a.sent();
662
- _a.label = 2;
663
- case 2: return [2 /*return*/, base58$1.encode(this.encoded)];
664
- }
665
- });
666
- });
667
- };
668
- /**
669
- * @param {Object} data
670
- */
671
- BasicInterface.prototype.create = function (data) {
672
- var _a;
673
- var decoded = {};
674
- if (((_a = this.keys) === null || _a === void 0 ? void 0 : _a.length) > 0) {
675
- var _loop_1 = function (key) {
676
- var _c;
677
- Object.defineProperties(decoded, (_c = {},
678
- _c[key] = {
679
- enumerable: true,
680
- configurable: true,
681
- set: function (value) { return data[key]; },
682
- get: function () { return data[key]; }
683
- },
684
- _c));
685
- };
686
- for (var _i = 0, _b = this.keys; _i < _b.length; _i++) {
687
- var key = _b[_i];
688
- _loop_1(key);
689
- }
690
- this.decoded = decoded;
691
- return this.encode();
692
- }
693
- };
694
- return BasicInterface;
695
- }());
696
-
697
- /*!
698
- * hash-wasm (https://www.npmjs.com/package/hash-wasm)
699
- * (c) Dani Biro
700
- * @license MIT
701
- */
702
-
703
- /*! *****************************************************************************
704
- Copyright (c) Microsoft Corporation.
705
-
706
- Permission to use, copy, modify, and/or distribute this software for any
707
- purpose with or without fee is hereby granted.
708
-
709
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
710
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
711
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
712
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
713
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
714
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
715
- PERFORMANCE OF THIS SOFTWARE.
716
- ***************************************************************************** */
717
-
718
- function __awaiter(thisArg, _arguments, P, generator) {
719
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
720
- return new (P || (P = Promise))(function (resolve, reject) {
721
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
722
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
723
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
724
- step((generator = generator.apply(thisArg, _arguments || [])).next());
725
- });
726
- }
727
-
728
- class Mutex {
729
- constructor() {
730
- this.mutex = Promise.resolve();
731
- }
732
- lock() {
733
- let begin = () => { };
734
- this.mutex = this.mutex.then(() => new Promise(begin));
735
- return new Promise((res) => {
736
- begin = res;
737
- });
738
- }
739
- dispatch(fn) {
740
- return __awaiter(this, void 0, void 0, function* () {
741
- const unlock = yield this.lock();
742
- try {
743
- return yield Promise.resolve(fn());
744
- }
745
- finally {
746
- unlock();
747
- }
748
- });
749
- }
750
- }
751
-
752
- /* eslint-disable import/prefer-default-export */
753
- /* eslint-disable no-bitwise */
754
- var _a;
755
- function getGlobal() {
756
- if (typeof globalThis !== 'undefined')
757
- return globalThis;
758
- // eslint-disable-next-line no-restricted-globals
759
- if (typeof self !== 'undefined')
760
- return self;
761
- if (typeof window !== 'undefined')
762
- return window;
763
- return global;
764
- }
765
- const globalObject = getGlobal();
766
- const nodeBuffer = (_a = globalObject.Buffer) !== null && _a !== void 0 ? _a : null;
767
- const textEncoder = globalObject.TextEncoder ? new globalObject.TextEncoder() : null;
768
- function hexCharCodesToInt(a, b) {
769
- return (((a & 0xF) + ((a >> 6) | ((a >> 3) & 0x8))) << 4) | ((b & 0xF) + ((b >> 6) | ((b >> 3) & 0x8)));
770
- }
771
- function writeHexToUInt8(buf, str) {
772
- const size = str.length >> 1;
773
- for (let i = 0; i < size; i++) {
774
- const index = i << 1;
775
- buf[i] = hexCharCodesToInt(str.charCodeAt(index), str.charCodeAt(index + 1));
776
- }
777
- }
778
- function hexStringEqualsUInt8(str, buf) {
779
- if (str.length !== buf.length * 2) {
780
- return false;
781
- }
782
- for (let i = 0; i < buf.length; i++) {
783
- const strIndex = i << 1;
784
- if (buf[i] !== hexCharCodesToInt(str.charCodeAt(strIndex), str.charCodeAt(strIndex + 1))) {
785
- return false;
786
- }
787
- }
788
- return true;
789
- }
790
- const alpha = 'a'.charCodeAt(0) - 10;
791
- const digit = '0'.charCodeAt(0);
792
- function getDigestHex(tmpBuffer, input, hashLength) {
793
- let p = 0;
794
- /* eslint-disable no-plusplus */
795
- for (let i = 0; i < hashLength; i++) {
796
- let nibble = input[i] >>> 4;
797
- tmpBuffer[p++] = nibble > 9 ? nibble + alpha : nibble + digit;
798
- nibble = input[i] & 0xF;
799
- tmpBuffer[p++] = nibble > 9 ? nibble + alpha : nibble + digit;
800
- }
801
- /* eslint-enable no-plusplus */
802
- return String.fromCharCode.apply(null, tmpBuffer);
803
- }
804
- const getUInt8Buffer = nodeBuffer !== null
805
- ? (data) => {
806
- if (typeof data === 'string') {
807
- const buf = nodeBuffer.from(data, 'utf8');
808
- return new Uint8Array(buf.buffer, buf.byteOffset, buf.length);
809
- }
810
- if (nodeBuffer.isBuffer(data)) {
811
- return new Uint8Array(data.buffer, data.byteOffset, data.length);
812
- }
813
- if (ArrayBuffer.isView(data)) {
814
- return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
815
- }
816
- throw new Error('Invalid data type!');
817
- }
818
- : (data) => {
819
- if (typeof data === 'string') {
820
- return textEncoder.encode(data);
821
- }
822
- if (ArrayBuffer.isView(data)) {
823
- return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
824
- }
825
- throw new Error('Invalid data type!');
826
- };
827
- const base64Chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
828
- const base64Lookup = new Uint8Array(256);
829
- for (let i = 0; i < base64Chars.length; i++) {
830
- base64Lookup[base64Chars.charCodeAt(i)] = i;
831
- }
832
- function getDecodeBase64Length(data) {
833
- let bufferLength = Math.floor(data.length * 0.75);
834
- const len = data.length;
835
- if (data[len - 1] === '=') {
836
- bufferLength -= 1;
837
- if (data[len - 2] === '=') {
838
- bufferLength -= 1;
839
- }
840
- }
841
- return bufferLength;
842
- }
843
- function decodeBase64(data) {
844
- const bufferLength = getDecodeBase64Length(data);
845
- const len = data.length;
846
- const bytes = new Uint8Array(bufferLength);
847
- let p = 0;
848
- for (let i = 0; i < len; i += 4) {
849
- const encoded1 = base64Lookup[data.charCodeAt(i)];
850
- const encoded2 = base64Lookup[data.charCodeAt(i + 1)];
851
- const encoded3 = base64Lookup[data.charCodeAt(i + 2)];
852
- const encoded4 = base64Lookup[data.charCodeAt(i + 3)];
853
- bytes[p] = (encoded1 << 2) | (encoded2 >> 4);
854
- p += 1;
855
- bytes[p] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
856
- p += 1;
857
- bytes[p] = ((encoded3 & 3) << 6) | (encoded4 & 63);
858
- p += 1;
859
- }
860
- return bytes;
861
- }
862
-
863
- const MAX_HEAP = 16 * 1024;
864
- const WASM_FUNC_HASH_LENGTH = 4;
865
- const wasmMutex = new Mutex();
866
- const wasmModuleCache = new Map();
867
- function WASMInterface(binary, hashLength) {
868
- return __awaiter(this, void 0, void 0, function* () {
869
- let wasmInstance = null;
870
- let memoryView = null;
871
- let initialized = false;
872
- if (typeof WebAssembly === 'undefined') {
873
- throw new Error('WebAssembly is not supported in this environment!');
874
- }
875
- const writeMemory = (data, offset = 0) => {
876
- memoryView.set(data, offset);
877
- };
878
- const getMemory = () => memoryView;
879
- const getExports = () => wasmInstance.exports;
880
- const setMemorySize = (totalSize) => {
881
- wasmInstance.exports.Hash_SetMemorySize(totalSize);
882
- const arrayOffset = wasmInstance.exports.Hash_GetBuffer();
883
- const memoryBuffer = wasmInstance.exports.memory.buffer;
884
- memoryView = new Uint8Array(memoryBuffer, arrayOffset, totalSize);
885
- };
886
- const getStateSize = () => {
887
- const view = new DataView(wasmInstance.exports.memory.buffer);
888
- const stateSize = view.getUint32(wasmInstance.exports.STATE_SIZE, true);
889
- return stateSize;
890
- };
891
- const loadWASMPromise = wasmMutex.dispatch(() => __awaiter(this, void 0, void 0, function* () {
892
- if (!wasmModuleCache.has(binary.name)) {
893
- const asm = decodeBase64(binary.data);
894
- const promise = WebAssembly.compile(asm);
895
- wasmModuleCache.set(binary.name, promise);
896
- }
897
- const module = yield wasmModuleCache.get(binary.name);
898
- wasmInstance = yield WebAssembly.instantiate(module, {
899
- // env: {
900
- // emscripten_memcpy_big: (dest, src, num) => {
901
- // const memoryBuffer = wasmInstance.exports.memory.buffer;
902
- // const memView = new Uint8Array(memoryBuffer, 0);
903
- // memView.set(memView.subarray(src, src + num), dest);
904
- // },
905
- // print_memory: (offset, len) => {
906
- // const memoryBuffer = wasmInstance.exports.memory.buffer;
907
- // const memView = new Uint8Array(memoryBuffer, 0);
908
- // console.log('print_int32', memView.subarray(offset, offset + len));
909
- // },
910
- // },
911
- });
912
- // wasmInstance.exports._start();
913
- }));
914
- const setupInterface = () => __awaiter(this, void 0, void 0, function* () {
915
- if (!wasmInstance) {
916
- yield loadWASMPromise;
917
- }
918
- const arrayOffset = wasmInstance.exports.Hash_GetBuffer();
919
- const memoryBuffer = wasmInstance.exports.memory.buffer;
920
- memoryView = new Uint8Array(memoryBuffer, arrayOffset, MAX_HEAP);
921
- });
922
- const init = (bits = null) => {
923
- initialized = true;
924
- wasmInstance.exports.Hash_Init(bits);
925
- };
926
- const updateUInt8Array = (data) => {
927
- let read = 0;
928
- while (read < data.length) {
929
- const chunk = data.subarray(read, read + MAX_HEAP);
930
- read += chunk.length;
931
- memoryView.set(chunk);
932
- wasmInstance.exports.Hash_Update(chunk.length);
933
- }
934
- };
935
- const update = (data) => {
936
- if (!initialized) {
937
- throw new Error('update() called before init()');
938
- }
939
- const Uint8Buffer = getUInt8Buffer(data);
940
- updateUInt8Array(Uint8Buffer);
941
- };
942
- const digestChars = new Uint8Array(hashLength * 2);
943
- const digest = (outputType, padding = null) => {
944
- if (!initialized) {
945
- throw new Error('digest() called before init()');
946
- }
947
- initialized = false;
948
- wasmInstance.exports.Hash_Final(padding);
949
- if (outputType === 'binary') {
950
- // the data is copied to allow GC of the original memory object
951
- return memoryView.slice(0, hashLength);
952
- }
953
- return getDigestHex(digestChars, memoryView, hashLength);
954
- };
955
- const save = () => {
956
- if (!initialized) {
957
- throw new Error('save() can only be called after init() and before digest()');
958
- }
959
- const stateOffset = wasmInstance.exports.Hash_GetState();
960
- const stateLength = getStateSize();
961
- const memoryBuffer = wasmInstance.exports.memory.buffer;
962
- const internalState = new Uint8Array(memoryBuffer, stateOffset, stateLength);
963
- // prefix is 4 bytes from SHA1 hash of the WASM binary
964
- // it is used to detect incompatible internal states between different versions of hash-wasm
965
- const prefixedState = new Uint8Array(WASM_FUNC_HASH_LENGTH + stateLength);
966
- writeHexToUInt8(prefixedState, binary.hash);
967
- prefixedState.set(internalState, WASM_FUNC_HASH_LENGTH);
968
- return prefixedState;
969
- };
970
- const load = (state) => {
971
- if (!(state instanceof Uint8Array)) {
972
- throw new Error('load() expects an Uint8Array generated by save()');
973
- }
974
- const stateOffset = wasmInstance.exports.Hash_GetState();
975
- const stateLength = getStateSize();
976
- const overallLength = WASM_FUNC_HASH_LENGTH + stateLength;
977
- const memoryBuffer = wasmInstance.exports.memory.buffer;
978
- if (state.length !== overallLength) {
979
- throw new Error(`Bad state length (expected ${overallLength} bytes, got ${state.length})`);
980
- }
981
- if (!hexStringEqualsUInt8(binary.hash, state.subarray(0, WASM_FUNC_HASH_LENGTH))) {
982
- throw new Error('This state was written by an incompatible hash implementation');
983
- }
984
- const internalState = state.subarray(WASM_FUNC_HASH_LENGTH);
985
- new Uint8Array(memoryBuffer, stateOffset, stateLength).set(internalState);
986
- initialized = true;
987
- };
988
- const isDataShort = (data) => {
989
- if (typeof data === 'string') {
990
- // worst case is 4 bytes / char
991
- return data.length < MAX_HEAP / 4;
992
- }
993
- return data.byteLength < MAX_HEAP;
994
- };
995
- let canSimplify = isDataShort;
996
- switch (binary.name) {
997
- case 'argon2':
998
- case 'scrypt':
999
- canSimplify = () => true;
1000
- break;
1001
- case 'blake2b':
1002
- case 'blake2s':
1003
- // if there is a key at blake2 then cannot simplify
1004
- canSimplify = (data, initParam) => initParam <= 512 && isDataShort(data);
1005
- break;
1006
- case 'blake3':
1007
- // if there is a key at blake3 then cannot simplify
1008
- canSimplify = (data, initParam) => initParam === 0 && isDataShort(data);
1009
- break;
1010
- case 'xxhash64': // cannot simplify
1011
- case 'xxhash3':
1012
- case 'xxhash128':
1013
- canSimplify = () => false;
1014
- break;
1015
- }
1016
- // shorthand for (init + update + digest) for better performance
1017
- const calculate = (data, initParam = null, digestParam = null) => {
1018
- if (!canSimplify(data, initParam)) {
1019
- init(initParam);
1020
- update(data);
1021
- return digest('hex', digestParam);
1022
- }
1023
- const buffer = getUInt8Buffer(data);
1024
- memoryView.set(buffer);
1025
- wasmInstance.exports.Hash_Calculate(buffer.length, initParam, digestParam);
1026
- return getDigestHex(digestChars, memoryView, hashLength);
1027
- };
1028
- yield setupInterface();
1029
- return {
1030
- getMemory,
1031
- writeMemory,
1032
- getExports,
1033
- setMemorySize,
1034
- init,
1035
- update,
1036
- digest,
1037
- save,
1038
- load,
1039
- calculate,
1040
- hashLength,
1041
- };
1042
- });
1043
- }
1044
-
1045
- new Mutex();
1046
-
1047
- new Mutex();
1048
-
1049
- new Mutex();
1050
-
1051
- new Mutex();
1052
-
1053
- new Mutex();
1054
-
1055
- new Mutex();
1056
-
1057
- new Mutex();
1058
-
1059
- new Mutex();
1060
-
1061
- new Mutex();
1062
-
1063
- var name$b = "sha3";
1064
- var data$b = "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";
1065
- var hash$b = "ec266d91";
1066
- var wasmJson$b = {
1067
- name: name$b,
1068
- data: data$b,
1069
- hash: hash$b
1070
- };
1071
-
1072
- new Mutex();
1073
-
1074
- new Mutex();
1075
- function validateBits(bits) {
1076
- if (![224, 256, 384, 512].includes(bits)) {
1077
- return new Error('Invalid variant! Valid values: 224, 256, 384, 512');
1078
- }
1079
- return null;
1080
- }
1081
- /**
1082
- * Creates a new Keccak hash instance
1083
- * @param bits Number of output bits. Valid values: 224, 256, 384, 512
1084
- */
1085
- function createKeccak(bits = 512) {
1086
- if (validateBits(bits)) {
1087
- return Promise.reject(validateBits(bits));
1088
- }
1089
- const outputSize = bits / 8;
1090
- return WASMInterface(wasmJson$b, outputSize).then((wasm) => {
1091
- wasm.init(bits);
1092
- const obj = {
1093
- init: () => { wasm.init(bits); return obj; },
1094
- update: (data) => { wasm.update(data); return obj; },
1095
- digest: (outputType) => wasm.digest(outputType, 0x01),
1096
- save: () => wasm.save(),
1097
- load: (data) => { wasm.load(data); return obj; },
1098
- blockSize: 200 - 2 * outputSize,
1099
- digestSize: outputSize,
1100
- };
1101
- return obj;
1102
- });
1103
- }
1104
-
1105
- new Mutex();
1106
-
1107
- new Mutex();
1108
-
1109
- new Mutex();
1110
-
1111
- new Mutex();
1112
-
1113
- new Mutex();
1114
-
1115
- new Mutex();
1116
-
1117
- new Mutex();
1118
-
1119
- new Mutex();
1120
-
1121
- new Mutex();
1122
-
1123
- new Mutex();
1124
-
1125
- new Mutex();
1126
-
1127
- var encode_1 = encode$1;
1128
-
1129
- var MSB$1 = 0x80
1130
- , REST$1 = 0x7F
1131
- , MSBALL = ~REST$1
1132
- , INT = Math.pow(2, 31);
1133
-
1134
- function encode$1(num, out, offset) {
1135
- if (Number.MAX_SAFE_INTEGER && num > Number.MAX_SAFE_INTEGER) {
1136
- encode$1.bytes = 0;
1137
- throw new RangeError('Could not encode varint')
1138
- }
1139
- out = out || [];
1140
- offset = offset || 0;
1141
- var oldOffset = offset;
1142
-
1143
- while(num >= INT) {
1144
- out[offset++] = (num & 0xFF) | MSB$1;
1145
- num /= 128;
1146
- }
1147
- while(num & MSBALL) {
1148
- out[offset++] = (num & 0xFF) | MSB$1;
1149
- num >>>= 7;
1150
- }
1151
- out[offset] = num | 0;
1152
-
1153
- encode$1.bytes = offset - oldOffset + 1;
1154
-
1155
- return out
1156
- }
1157
-
1158
- var decode$3 = read;
1159
-
1160
- var MSB = 0x80
1161
- , REST = 0x7F;
1162
-
1163
- function read(buf, offset) {
1164
- var res = 0
1165
- , offset = offset || 0
1166
- , shift = 0
1167
- , counter = offset
1168
- , b
1169
- , l = buf.length;
1170
-
1171
- do {
1172
- if (counter >= l || shift > 49) {
1173
- read.bytes = 0;
1174
- throw new RangeError('Could not decode varint')
1175
- }
1176
- b = buf[counter++];
1177
- res += shift < 28
1178
- ? (b & REST) << shift
1179
- : (b & REST) * Math.pow(2, shift);
1180
- shift += 7;
1181
- } while (b >= MSB)
1182
-
1183
- read.bytes = counter - offset;
1184
-
1185
- return res
1186
- }
1187
-
1188
- var N1 = Math.pow(2, 7);
1189
- var N2 = Math.pow(2, 14);
1190
- var N3 = Math.pow(2, 21);
1191
- var N4 = Math.pow(2, 28);
1192
- var N5 = Math.pow(2, 35);
1193
- var N6 = Math.pow(2, 42);
1194
- var N7 = Math.pow(2, 49);
1195
- var N8 = Math.pow(2, 56);
1196
- var N9 = Math.pow(2, 63);
1197
-
1198
- var length = function (value) {
1199
- return (
1200
- value < N1 ? 1
1201
- : value < N2 ? 2
1202
- : value < N3 ? 3
1203
- : value < N4 ? 4
1204
- : value < N5 ? 5
1205
- : value < N6 ? 6
1206
- : value < N7 ? 7
1207
- : value < N8 ? 8
1208
- : value < N9 ? 9
1209
- : 10
1210
- )
1211
- };
1212
-
1213
- var varint = {
1214
- encode: encode_1
1215
- , decode: decode$3
1216
- , encodingLength: length
1217
- };
1218
-
1219
- var codecs = {
1220
- // just a hash
1221
- 'disco-hash': {
1222
- codec: parseInt('30', 16),
1223
- hashAlg: 'dbl-keccak-256', // ,
1224
- // testnet: 'olivia'
1225
- },
1226
- 'peernet-peer-response': {
1227
- codec: parseInt('707072', 16),
1228
- hashAlg: 'keccak-256',
1229
- },
1230
- 'peernet-peer': {
1231
- codec: parseInt('7070', 16),
1232
- hashAlg: 'keccak-256',
1233
- },
1234
- 'peernet-dht': {
1235
- codec: parseInt('706468', 16),
1236
- hashAlg: 'keccak-256',
1237
- },
1238
- 'peernet-dht-response': {
1239
- codec: parseInt('706472', 16),
1240
- hashAlg: 'keccak-256',
1241
- },
1242
- // data
1243
- 'peernet-data': {
1244
- codec: parseInt('706461', 16),
1245
- hashAlg: 'keccak-256',
1246
- },
1247
- 'peernet-data-response': {
1248
- codec: parseInt('70646172', 16),
1249
- hashAlg: 'keccak-256',
1250
- },
1251
- // message
1252
- 'peernet-message': {
1253
- codec: parseInt('706d65', 16),
1254
- hashAlg: 'keccak-256',
1255
- },
1256
- // pubsub
1257
- 'peernet-ps': {
1258
- codec: parseInt('707073', 16),
1259
- hashAlg: 'keccak-256',
1260
- },
1261
- 'peernet-response': {
1262
- codec: parseInt('7072', 16),
1263
- hashAlg: 'keccak-256',
1264
- },
1265
- 'peernet-request': {
1266
- codec: parseInt('707271', 16),
1267
- hashAlg: 'keccak-256',
1268
- },
1269
- // normal block
1270
- 'leofcoin-block': {
1271
- codec: parseInt('6c62', 16),
1272
- hashAlg: 'dbl-keccak-512', // ,
1273
- // testnet: 'olivia'
1274
- },
1275
- 'leofcoin-tx': {
1276
- codec: parseInt('6c74', 16),
1277
- hashAlg: 'dbl-keccak-512', // ,
1278
- // testnet: 'olivia'
1279
- },
1280
- // itx
1281
- 'leofcoin-itx': {
1282
- codec: parseInt('6c69', 16),
1283
- hashAlg: 'keccak-512', // ,
1284
- // testnet: 'olivia'
1285
- },
1286
- // peer reputation
1287
- 'leofcoin-pr': {
1288
- codec: parseInt('6c70', 16),
1289
- hashAlg: 'keccak-256', // ,
1290
- // testnet: 'olivia'
1291
- },
1292
- // chat message
1293
- 'chat-message': {
1294
- codec: parseInt('70636d', 16),
1295
- hashAlg: 'dbl-keccak-256',
1296
- },
1297
- 'peernet-file' : {
1298
- codec: parseInt('7066', 16),
1299
- hashAlg: 'keccak-256',
1300
- },
1301
- 'peernet-file-response' : {
1302
- codec: parseInt('706672', 16),
1303
- hashAlg: 'keccak-256',
1304
- }
1305
- };
1306
-
1307
- var codecs$1 = /*#__PURE__*/Object.freeze({
1308
- __proto__: null,
1309
- default: codecs
1310
- });
1311
-
1312
- var Codec$1 = /** @class */ (function (_super) {
1313
- __extends(Codec, _super);
1314
- function Codec(buffer) {
1315
- var _this = _super.call(this) || this;
1316
- if (buffer) {
1317
- if (buffer instanceof Uint8Array) {
1318
- var codec = varint.decode(buffer);
1319
- var name_1 = _this.getCodecName(codec);
1320
- if (name_1) {
1321
- _this.name = name_1;
1322
- _this.encoded = buffer;
1323
- _this.decode(buffer);
1324
- }
1325
- else {
1326
- _this.encode(buffer);
1327
- }
1328
- }
1329
- else if (buffer instanceof ArrayBuffer) {
1330
- var encoded = new Uint8Array(buffer.byteLength);
1331
- for (var i = 0; i < buffer.byteLength; i++) {
1332
- encoded[i] = buffer[i];
1333
- }
1334
- _this.encoded = encoded;
1335
- // this.encoded = new Uint8Array(buffer, buffer.byteOffset, buffer.byteLength)
1336
- _this.decode(buffer);
1337
- return _this;
1338
- }
1339
- if (typeof buffer === 'string') {
1340
- if (_this.codecs[buffer])
1341
- _this.fromName(buffer);
1342
- else if (_this.isHex(buffer))
1343
- _this.fromHex(buffer);
1344
- else if (_this.isBase32(buffer))
1345
- _this.fromBs32(buffer);
1346
- else if (_this.isBase58(buffer))
1347
- _this.fromBs58(buffer);
1348
- else
1349
- throw new Error("unsupported string ".concat(buffer));
1350
- }
1351
- if (!isNaN(buffer))
1352
- if (_this.codecs[_this.getCodecName(buffer)])
1353
- _this.fromCodec(buffer);
1354
- }
1355
- return _this;
1356
- }
1357
- Object.defineProperty(Codec.prototype, "codecs", {
1358
- get: function () {
1359
- return __assign(__assign({}, globalThis.peernet.codecs), codecs);
1360
- },
1361
- enumerable: false,
1362
- configurable: true
1363
- });
1364
- Codec.prototype.fromEncoded = function (encoded) {
1365
- var codec = varint.decode(encoded);
1366
- var name = this.getCodecName(codec);
1367
- this.name = name;
1368
- this.encoded = encoded;
1369
- this.decode(encoded);
1370
- };
1371
- Codec.prototype.getCodec = function (name) {
1372
- return this.codecs[name].codec;
1373
- };
1374
- Codec.prototype.getCodecName = function (codec) {
1375
- var _this = this;
1376
- return Object.keys(this.codecs).reduce(function (p, c) {
1377
- var item = _this.codecs[c];
1378
- if (item.codec === codec)
1379
- return c;
1380
- else
1381
- return p;
1382
- }, undefined);
1383
- };
1384
- Codec.prototype.getHashAlg = function (name) {
1385
- return this.codecs[name].hashAlg;
1386
- };
1387
- Codec.prototype.fromCodec = function (codec) {
1388
- this.name = this.getCodecName(codec);
1389
- this.hashAlg = this.getHashAlg(this.name);
1390
- this.codec = this.getCodec(this.name);
1391
- this.codecBuffer = varint.encode(codec);
1392
- };
1393
- Codec.prototype.fromName = function (name) {
1394
- var codec = this.getCodec(name);
1395
- this.name = name;
1396
- this.codec = codec;
1397
- this.hashAlg = this.getHashAlg(name);
1398
- this.codecBuffer = varint.encode(codec);
1399
- };
1400
- Codec.prototype.decode = function () {
1401
- var codec = varint.decode(this.encoded);
1402
- this.fromCodec(codec);
1403
- };
1404
- Codec.prototype.encode = function () {
1405
- var codec = varint.encode(this.decoded);
1406
- this.encoded = codec;
1407
- return this.encoded;
1408
- };
1409
- return Codec;
1410
- }(BasicInterface$1));
1411
-
1412
- let CodecHash$1 = class CodecHash extends BasicInterface$1 {
1413
- constructor(buffer, options = {}) {
1414
- super();
1415
- if (options.name) this.name = options.name;
1416
- else this.name = 'disco-hash';
1417
- if (options.codecs) this.codecs = options.codecs;
1418
- return this.init(buffer)
1419
- }
1420
-
1421
- async init(uint8Array) {
1422
- if (uint8Array) {
1423
- if (uint8Array instanceof Uint8Array) {
1424
- this.discoCodec = new Codec$1(uint8Array, this.codecs);
1425
- const name = this.discoCodec.name;
1426
-
1427
- if (name) {
1428
- this.name = name;
1429
- this.decode(uint8Array);
1430
- } else {
1431
- await this.encode(uint8Array);
1432
- }
1433
- }
1434
-
1435
- if (typeof uint8Array === 'string') {
1436
- if (this.isHex(uint8Array)) await this.fromHex(uint8Array);
1437
- if (this.isBase32(uint8Array)) await this.fromBs32(uint8Array);
1438
- else if (this.isBase58(uint8Array)) await this.fromBs58(uint8Array);
1439
- else throw new Error(`unsupported string ${uint8Array}`)
1440
- } else if (typeof uint8Array === 'object') await this.fromJSON(uint8Array);
1441
- }
1442
- return this
1443
- }
1444
- get prefix() {
1445
- const length = this.length;
1446
- const uint8Array = new Uint8Array(length.length + this.discoCodec.codecBuffer.length);
1447
- uint8Array.set(length);
1448
- uint8Array.set(this.discoCodec.codecBuffer, length.length);
1449
-
1450
- return uint8Array
1451
- }
1452
-
1453
- get length() {
1454
- return varint.encode(this.size)
1455
- }
1456
-
1457
- get buffer() {
1458
- return this.encoded
1459
- }
1460
-
1461
- get hash() {
1462
- return this.encoded
1463
- }
1464
-
1465
- fromJSON(json) {
1466
- return this.encode(Buffer.from(JSON.stringify(json)))
1467
- }
1468
-
1469
- async encode(buffer, name) {
1470
- if (!this.name && name) this.name = name;
1471
- if (!buffer) buffer = this.buffer;
1472
- this.discoCodec = new Codec$1(this.name, this.codecs);
1473
- this.discoCodec.fromName(this.name);
1474
- let hashAlg = this.discoCodec.hashAlg;
1475
- const hashVariant = Number(hashAlg.split('-')[hashAlg.split('-').length - 1]);
1476
-
1477
- if (hashAlg.includes('dbl')) {
1478
- hashAlg = hashAlg.replace('dbl-', '');
1479
- const hasher = await createKeccak(hashVariant);
1480
- await hasher.init();
1481
- hasher.update(buffer);
1482
- buffer = hasher.digest('binary');
1483
- }
1484
- const hasher = await createKeccak(hashVariant);
1485
- await hasher.init();
1486
- hasher.update(buffer);
1487
- this.digest = hasher.digest('binary');
1488
- this.size = this.digest.length;
1489
-
1490
- this.codec = this.discoCodec.encode();
1491
- this.codec = this.discoCodec.codecBuffer;
1492
- const uint8Array = new Uint8Array(this.digest.length + this.prefix.length);
1493
- uint8Array.set(this.prefix);
1494
- uint8Array.set(this.digest, this.prefix.length);
1495
-
1496
- this.encoded = uint8Array;
1497
-
1498
- return this.encoded
1499
- }
1500
-
1501
- async validate(buffer) {
1502
- if (Buffer.isBuffer(buffer)) {
1503
- const codec = varint.decode(buffer);
1504
- if (this.codecs[codec]) {
1505
- this.decode(buffer);
1506
- } else {
1507
- await this.encode(buffer);
1508
- }
1509
- }
1510
- if (typeof buffer === 'string') {
1511
- if (this.isHex(buffer)) this.fromHex(buffer);
1512
- if (this.isBase32(buffer)) this.fromBs32(buffer);
1513
- }
1514
- if (typeof buffer === 'object') this.fromJSON(buffer);
1515
- }
1516
-
1517
- decode(buffer) {
1518
- this.encoded = buffer;
1519
- const codec = varint.decode(buffer);
1520
-
1521
- this.discoCodec = new Codec$1(codec, this.codecs);
1522
- // TODO: validate codec
1523
- buffer = buffer.slice(varint.decode.bytes);
1524
- this.size = varint.decode(buffer);
1525
- this.digest = buffer.slice(varint.decode.bytes);
1526
- if (this.digest.length !== this.size) {
1527
- throw new Error(`hash length inconsistent: 0x${this.encoded.toString('hex')}`)
1528
- }
1529
-
1530
- // const discoCodec = new Codec(codec, this.codecs)
1531
-
1532
- this.name = this.discoCodec.name;
1533
-
1534
-
1535
- this.size = this.digest.length;
1536
-
1537
- return {
1538
- codec: this.codec,
1539
- name: this.name,
1540
- size: this.size,
1541
- length: this.length,
1542
- digest: this.digest,
1543
- }
1544
- }
1545
- };
1546
-
1547
- var FormatInterface$1 = /** @class */ (function (_super) {
1548
- __extends(FormatInterface, _super);
1549
- /**
1550
- * @param {Buffer|String|Object} buffer - data - The data needed to create the desired message
1551
- * @param {Object} proto - {encode, decode}
1552
- * @param {Object} options - {hashFormat, name}
1553
- */
1554
- function FormatInterface(buffer, proto, options) {
1555
- if (options === void 0) { options = {}; }
1556
- var _this = _super.call(this) || this;
1557
- _this.proto = proto;
1558
- _this.hashFormat = options.hashFormat || 'bs32';
1559
- if (options.name)
1560
- _this.name = options.name;
1561
- return _this.init(buffer);
1562
- }
1563
- FormatInterface.prototype.init = function (buffer) {
1564
- return __awaiter$1(this, void 0, void 0, function () {
1565
- return __generator(this, function (_a) {
1566
- switch (_a.label) {
1567
- case 0:
1568
- if (!(buffer instanceof Uint8Array)) return [3 /*break*/, 2];
1569
- return [4 /*yield*/, this.fromUint8Array(buffer)];
1570
- case 1:
1571
- _a.sent();
1572
- return [3 /*break*/, 15];
1573
- case 2:
1574
- if (!(buffer instanceof ArrayBuffer)) return [3 /*break*/, 4];
1575
- return [4 /*yield*/, this.fromArrayBuffer(buffer)];
1576
- case 3:
1577
- _a.sent();
1578
- return [3 /*break*/, 15];
1579
- case 4:
1580
- if (!((buffer === null || buffer === void 0 ? void 0 : buffer.name) === this.name)) return [3 /*break*/, 5];
1581
- return [2 /*return*/, buffer];
1582
- case 5:
1583
- if (!(buffer instanceof String)) return [3 /*break*/, 13];
1584
- if (!this.isHex(buffer)) return [3 /*break*/, 7];
1585
- return [4 /*yield*/, this.fromHex(buffer)];
1586
- case 6:
1587
- _a.sent();
1588
- return [3 /*break*/, 12];
1589
- case 7:
1590
- if (!this.isBase32(buffer)) return [3 /*break*/, 9];
1591
- return [4 /*yield*/, this.fromBs32(buffer)];
1592
- case 8:
1593
- _a.sent();
1594
- return [3 /*break*/, 12];
1595
- case 9:
1596
- if (!this.isBase58(buffer)) return [3 /*break*/, 11];
1597
- return [4 /*yield*/, this.fromBs58(buffer)];
1598
- case 10:
1599
- _a.sent();
1600
- return [3 /*break*/, 12];
1601
- case 11: throw new Error("unsupported string ".concat(buffer));
1602
- case 12: return [3 /*break*/, 15];
1603
- case 13: return [4 /*yield*/, this.create(buffer)];
1604
- case 14:
1605
- _a.sent();
1606
- _a.label = 15;
1607
- case 15: return [2 /*return*/, this];
1608
- }
1609
- });
1610
- });
1611
- };
1612
- FormatInterface.prototype.hasCodec = function () {
1613
- if (!this.encoded)
1614
- return false;
1615
- var codec = new Codec$1(this.encoded);
1616
- if (codec.name)
1617
- return true;
1618
- };
1619
- FormatInterface.prototype.decode = function () {
1620
- return __awaiter$1(this, void 0, void 0, function () {
1621
- var encoded, codec, _a;
1622
- return __generator(this, function (_b) {
1623
- switch (_b.label) {
1624
- case 0:
1625
- encoded = this.encoded;
1626
- codec = new Codec$1(this.encoded);
1627
- if (!codec.codecBuffer) return [3 /*break*/, 2];
1628
- encoded = encoded.slice(codec.codecBuffer.length);
1629
- this.name = codec.name;
1630
- _a = this;
1631
- return [4 /*yield*/, this.protoDecode(encoded)];
1632
- case 1:
1633
- _a.decoded = _b.sent();
1634
- try {
1635
- this.decoded = JSON.parse(this.decoded);
1636
- }
1637
- catch (_c) {
1638
- }
1639
- return [3 /*break*/, 3];
1640
- case 2: throw new Error("no codec found");
1641
- case 3: return [2 /*return*/, this.decoded];
1642
- }
1643
- });
1644
- });
1645
- };
1646
- FormatInterface.prototype.encode = function (decoded) {
1647
- return __awaiter$1(this, void 0, void 0, function () {
1648
- var encoded, codec, uint8Array;
1649
- return __generator(this, function (_a) {
1650
- switch (_a.label) {
1651
- case 0:
1652
- if (!decoded)
1653
- decoded = this.decoded;
1654
- codec = new Codec$1(this.name);
1655
- if (!(decoded instanceof Uint8Array)) return [3 /*break*/, 1];
1656
- encoded = decoded;
1657
- return [3 /*break*/, 3];
1658
- case 1: return [4 /*yield*/, this.protoEncode(typeof decoded === 'object' ? JSON.stringify(decoded) : decoded)];
1659
- case 2:
1660
- encoded = _a.sent();
1661
- _a.label = 3;
1662
- case 3:
1663
- if (codec.codecBuffer) {
1664
- uint8Array = new Uint8Array(encoded.length + codec.codecBuffer.length);
1665
- uint8Array.set(codec.codecBuffer);
1666
- uint8Array.set(encoded, codec.codecBuffer.length);
1667
- this.encoded = uint8Array;
1668
- }
1669
- else {
1670
- throw new Error("invalid codec");
1671
- }
1672
- return [2 /*return*/, this.encoded];
1673
- }
1674
- });
1675
- });
1676
- };
1677
- Object.defineProperty(FormatInterface.prototype, "peernetHash", {
1678
- /**
1679
- * @return {PeernetHash}
1680
- */
1681
- get: function () {
1682
- return new CodecHash$1(this.decoded, { name: this.name });
1683
- },
1684
- enumerable: false,
1685
- configurable: true
1686
- });
1687
- /**
1688
- * @return {peernetHash}
1689
- */
1690
- FormatInterface.prototype.hash = function () {
1691
- return __awaiter$1(this, void 0, void 0, function () {
1692
- var upper, format;
1693
- return __generator(this, function (_a) {
1694
- switch (_a.label) {
1695
- case 0:
1696
- upper = this.hashFormat.charAt(0).toUpperCase();
1697
- format = "".concat(upper).concat(this.hashFormat.substring(1, this.hashFormat.length));
1698
- return [4 /*yield*/, this.peernetHash];
1699
- case 1: return [2 /*return*/, (_a.sent())["to".concat(format)]()];
1700
- }
1701
- });
1702
- });
1703
- };
1704
- FormatInterface.prototype.fromUint8Array = function (buffer) {
1705
- this.encoded = buffer;
1706
- return this.hasCodec() ? this.decode() : this.create(JSON.parse(new TextDecoder().decode(this.encoded)));
1707
- };
1708
- FormatInterface.prototype.fromArrayBuffer = function (buffer) {
1709
- this.encoded = new Uint8Array(buffer, buffer.byteOffset, buffer.byteLength);
1710
- return this.hasCodec() ? this.decode() : this.create(JSON.parse(new TextDecoder().decode(this.encoded)));
1711
- };
1712
- return FormatInterface;
1713
- }(BasicInterface$1));
1714
- var FormatInterface = FormatInterface$1;
1715
- var Codec = Codec$1;
1716
-
1717
- const BufferToUint8Array = data => {
1718
- if (data.type === 'Buffer') {
1719
- data = new Uint8Array(data.data);
1720
- }
1721
- return data
1722
- };
1723
-
1724
- const protoFor = (message) => {
1725
- const codec = new Codec(message);
1726
- if (!codec.name) throw new Error('proto not found')
1727
- const Proto = globalThis.peernet.protos[codec.name];
1728
- if (!Proto) throw (new Error(`No proto defined for ${codec.name}`))
1729
- return new Proto(message)
1730
- };
1731
-
1732
- /**
1733
- * wether or not a peernet daemon is active
1734
- * @return {Boolean}
1735
- */
1736
- const hasDaemon = async () => {
1737
- try {
1738
- let response = await fetch('http://127.0.0.1:1000/api/version');
1739
- response = await response.json();
1740
- return Boolean(response.client === '@peernet/api/http')
1741
- } catch (e) {
1742
- return false
1743
- }
1744
- };
1745
-
1746
- const https = () => {
1747
- if (!globalThis.location) return false;
1748
- return Boolean(globalThis.location.protocol === 'https:')
1749
- };
1750
-
1751
- /**
1752
- * Get current environment
1753
- * @return {String} current environment [node, electron, browser]
1754
- */
1755
- const environment = () => {
1756
- const _navigator = globalThis.navigator;
1757
- if (!_navigator) {
1758
- return 'node'
1759
- } else if (_navigator && /electron/i.test(_navigator.userAgent)) {
1760
- return 'electron'
1761
- } else {
1762
- return 'browser'
1763
- }
1764
- };
1765
-
1766
- /**
1767
- * * Get current environment
1768
- * @return {Object} result
1769
- * @property {Boolean} reult.daemon whether or not daemon is running
1770
- * @property {Boolean} reult.environment Current environment
1771
- */
1772
- const target = async () => {
1773
- let daemon = false;
1774
- if (!https()) daemon = await hasDaemon();
1775
-
1776
- return {daemon, environment: environment()}
1777
- };
1778
-
1779
- class PeerDiscovery {
1780
- constructor(id) {
1781
- this.id = id;
1782
- }
1783
-
1784
- _getPeerId(id) {
1785
- if (!peernet.peerMap || peernet.peerMap && peernet.peerMap.size === 0) return false
1786
-
1787
- for (const entry of [...peernet.peerMap.entries()]) {
1788
- for (const _id of entry[1]) {
1789
- if (_id === id) return entry[0]
1790
- }
1791
- }
1792
- }
1793
-
1794
- async discover(peer) {
1795
- let id = this._getPeerId(peer.id);
1796
- if (id) return id
1797
- const data = await new peernet.protos['peernet-peer']({id: this.id});
1798
- const node = await peernet.prepareMessage(peer.id, data.encoded);
1799
-
1800
- let response = await peer.request(node.encoded);
1801
- response = await protoFor(response);
1802
- response = await new peernet.protos['peernet-peer-response'](response.decoded.data);
1803
-
1804
- id = response.decoded.id;
1805
- if (id === this.id) return;
1806
-
1807
- if (!peernet.peerMap.has(id)) peernet.peerMap.set(id, [peer.id]);
1808
- else {
1809
- const connections = peernet.peerMap.get(id);
1810
- if (connections.indexOf(peer.id) === -1) {
1811
- connections.push(peer.id);
1812
- peernet.peerMap.set(peer.id, connections);
1813
- }
1814
- }
1815
- return id
1816
- }
1817
-
1818
- async discoverHandler(message, peer) {
1819
- const {id, proto} = message;
1820
- // if (typeof message.data === 'string') message.data = Buffer.from(message.data)
1821
- if (proto.name === 'peernet-peer') {
1822
- const from = proto.decoded.id;
1823
- if (from === this.id) return;
1824
-
1825
- if (!peernet.peerMap.has(from)) peernet.peerMap.set(from, [peer.id]);
1826
- else {
1827
- const connections = peernet.peerMap.get(from);
1828
- if (connections.indexOf(peer.id) === -1) {
1829
- connections.push(peer.id);
1830
- peernet.peerMap.set(from, connections);
1831
- }
1832
- }
1833
- const data = await new peernet.protos['peernet-peer-response']({id: this.id});
1834
- const node = await peernet.prepareMessage(from, data.encoded);
1835
-
1836
- peer.write(Buffer.from(JSON.stringify({id, data: node.encoded})));
1837
- } else if (proto.name === 'peernet-peer-response') {
1838
- const from = proto.decoded.id;
1839
- if (from === this.id) return;
1840
-
1841
- if (!peernet.peerMap.has(from)) peernet.peerMap.set(from, [peer.id]);
1842
- else {
1843
- const connections = peernet.peerMap.get(from);
1844
- if (connections.indexOf(peer.id) === -1) {
1845
- connections.push(peer.id);
1846
- peernet.peerMap.set(from, connections);
1847
- }
1848
- }
1849
- }
1850
- }
1851
- }
1852
-
1853
- /**
1854
- * Keep history of fetched address and ptr
1855
- * @property {Object} address
1856
- * @property {Object} ptr
1857
- */
1858
- const lastFetched = {
1859
- address: {
1860
- value: undefined,
1861
- timestamp: 0,
1862
- },
1863
- ptr: {
1864
- value: undefined,
1865
- timestamp: 0,
1866
- },
1867
- };
1868
-
1869
- const getAddress = async () => {
1870
- const {address} = lastFetched;
1871
- const now = Math.round(new Date().getTime() / 1000);
1872
- if (now - address.timestamp > 1200000) {
1873
- address.value = await fetch('https://icanhazip.com/');
1874
- address.value = await address.value.text();
1875
- address.timestamp = Math.round(new Date().getTime() / 1000);
1876
- lastFetched.address = address;
1877
- }
1878
-
1879
- return address.value
1880
- };
1881
-
1882
- const degreesToRadians = (degrees) => {
1883
- return degrees * Math.PI / 180;
1884
- };
1885
-
1886
- const distanceInKmBetweenEarthCoordinates = (lat1, lon1, lat2, lon2) => {
1887
- const earthRadiusKm = 6371;
1888
-
1889
- const dLat = degreesToRadians(lat2-lat1);
1890
- const dLon = degreesToRadians(lon2-lon1);
1891
-
1892
- lat1 = degreesToRadians(lat1);
1893
- lat2 = degreesToRadians(lat2);
1894
- const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
1895
- Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
1896
- const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
1897
- return earthRadiusKm * c;
1898
- };
1899
-
1900
- class DhtEarth {
1901
- /**
1902
- *
1903
- */
1904
- constructor() {
1905
- this.providerMap = new Map();
1906
- }
1907
-
1908
- /**
1909
- * @param {Object} address
1910
- * @return {Object} {latitude: lat, longitude: lon}
1911
- */
1912
- async getCoordinates(address) {
1913
- // const {address} = parseAddress(provider)
1914
- const request = `https://whereis.leofcoin.org/?ip=${address}`;
1915
- let response = await fetch(request);
1916
- response = await response.json();
1917
- const {lat, lon} = response;
1918
- return {latitude: lat, longitude: lon}
1919
- }
1920
-
1921
- /**
1922
- * @param {Object} peer
1923
- * @param {Object} provider
1924
- * @return {Object} {provider, distance}
1925
- */
1926
- async getDistance(peer, provider) {
1927
- const {latitude, longitude} = await this.getCoordinates(provider.address);
1928
- return {provider, distance: distanceInKmBetweenEarthCoordinates(peer.latitude, peer.longitude, latitude, longitude)}
1929
- }
1930
-
1931
- /**
1932
- * @param {Array} providers
1933
- * @return {Object} closestPeer
1934
- */
1935
- async closestPeer(providers) {
1936
- let all = [];
1937
- const address = await getAddress();
1938
- const peerLoc = await this.getCoordinates(address);
1939
-
1940
- for (const provider of providers) {
1941
- if (provider.address === '127.0.0.1') all.push({provider, distance: 0});
1942
- else all.push(this.getDistance(peerLoc, provider));
1943
- }
1944
-
1945
- all = await Promise.all(all);
1946
- all = all.sort((previous, current) => previous.distance - current.distance);
1947
- return all[0].provider;
1948
- }
1949
-
1950
- /**
1951
- * @param {String} hash
1952
- * @return {Array} providers
1953
- */
1954
- providersFor(hash) {
1955
- return this.providerMap.get(hash);
1956
- }
1957
-
1958
- /**
1959
- * @param {String} address
1960
- * @param {String} hash
1961
- * @return {Array} providers
1962
- */
1963
- async addProvider(address, hash) {
1964
- let providers = [];
1965
- if (this.providerMap.has(hash)) providers = this.providerMap.get(hash);
1966
-
1967
- providers = new Set([...providers, address]);
1968
- this.providerMap.set(hash, providers);
1969
- return providers;
1970
- }
1971
- }
1972
-
1973
- class MessageHandler {
1974
- constructor(network) {
1975
- this.network = network;
1976
- }
1977
- /**
1978
- * hash and sign message
1979
- *
1980
- * @param {object} message
1981
- * @param {Buffer} message.from peer id
1982
- * @param {Buffer} message.to peer id
1983
- * @param {string} message.data Peernet message
1984
- * (PeernetMessage excluded) encoded as a string
1985
- * @return message
1986
- */
1987
- async hashAndSignMessage(message) {
1988
- let identity = await walletStore.get('identity');
1989
- identity = JSON.parse(identity);
1990
- if (!globalThis.MultiWallet) {
1991
- const importee = await import(/* webpackChunkName: "multi-wallet" */ './index-019272d8.js');
1992
- globalThis.MultiWallet = importee.default;
1993
- }
1994
- const wallet = new MultiWallet(this.network);
1995
- wallet.recover(identity.mnemonic);
1996
- message.decoded.signature = wallet.sign(Buffer.from(await message.hash).slice(0, 32));
1997
- return message
1998
- }
1999
-
2000
- /**
2001
- * @param {String} from - peer id
2002
- * @param {String} to - peer id
2003
- * @param {String|PeernetMessage} data - data encoded message string
2004
- * or the messageNode itself
2005
- */
2006
- async prepareMessage(message) {
2007
- if (message.keys.includes('signature')) {
2008
- message = await this.hashAndSignMessage(message);
2009
- }
2010
-
2011
- return message
2012
- }
2013
- }
2014
-
2015
- const dataHandler = async message => {
2016
- if (!message) return
2017
-
2018
- const {data, id, from} = message;
2019
- const proto = await protoFor(data);
2020
-
2021
- peernet._protoHandler({id, proto}, peernet.client.connections[from], from);
2022
- };
2023
-
2024
- const dhtError = (proto) => {
2025
- const text = `Received proto ${proto.name} expected peernet-dht-response`;
2026
- return new Error(`Routing error: ${text}`)
2027
- };
2028
-
2029
- const nothingFoundError = (hash) => {
2030
- return new Error(`nothing found for ${hash}`)
2031
- };
2032
-
2033
- // import base32 from '@vandeurenglenn/base32'
2034
- // import base58 from '@vandeurenglenn/base58'
2035
-
2036
- // export const encodings = {
2037
- // base58,
2038
- // base32
2039
- // }
2040
-
2041
- const encode = (string, encoding = 'utf-8') => {
2042
- if (typeof string === 'string') {
2043
- let encoded;
2044
-
2045
- // if (encodings[encoding]) encoded = encodings[encoding].encode(encoded)
2046
- encoded = new TextEncoder().encode(string);
2047
- return encoded
2048
- }
2049
- throw Error(`expected typeof String instead got ${string}`)
2050
- };
2051
-
2052
- const decode = (uint8Array, encoding) => {
2053
- if (uint8Array instanceof Uint8Array) {
2054
- let decoded;
2055
- // if (encodings[encoding]) decoded = encodings[encoding].decode(decoded)
2056
- decoded = new TextDecoder().decode(uint8Array);
2057
-
2058
- return decoded
2059
- }
2060
- throw Error(`expected typeof uint8Array instead got ${uint8Array}`)
2061
- };
2062
-
2063
- const pathSepS = '/';
2064
- class KeyPath {
2065
-
2066
- /**
2067
- * @param {string | Uint8Array} input
2068
- */
2069
- constructor(input) {
2070
- if (typeof input === 'string') {
2071
- this.uint8Array = encode(input);
2072
- } else if (input instanceof Uint8Array) {
2073
- this.uint8Array = input;
2074
- } else if (input instanceof KeyPath) {
2075
- this.uint8Array = input.uint8Array;
2076
- } else {
2077
- throw new Error('Invalid keyPath, should be a String, Uint8Array or KeyPath')
2078
- }
2079
- }
2080
-
2081
- isKeyPath() {
2082
- return true
2083
- }
2084
-
2085
- /**
2086
- * Convert to the string representation
2087
- *
2088
- * @param {import('uint8arrays/to-string').SupportedEncodings} [encoding='utf8'] - The encoding to use.
2089
- * @returns {string}
2090
- */
2091
- toString(encoding = 'hex') {
2092
- return decode(this.uint8Array)
2093
- }
2094
-
2095
- /**
2096
- * Returns the `list` representation of this path.
2097
- *
2098
- * @returns string[]
2099
- *
2100
- * @example
2101
- * ```js
2102
- * new Key('/Comedy/MontyPython/Actor:JohnCleese').list()
2103
- * // => ['Comedy', 'MontyPythong', 'Actor:JohnCleese']
2104
- * ```
2105
- */
2106
- list() {
2107
- return this.toString().split(pathSepS).slice(1)
2108
- }
2109
-
2110
- }
2111
-
2112
- class LeofcoinStorage {
2113
-
2114
- constructor(name = 'storage', root = '.leofcoin') {
2115
- this.name = name;
2116
- this.root = root;
2117
- }
2118
-
2119
- async init(name, root) {
2120
- const importee = await import(globalThis.navigator ? './browser-store.js' : './store.js');
2121
- const Store = importee.default;
2122
- this.db = new Store(this.name, this.root);
2123
- }
2124
-
2125
- async get(key) {
2126
- if (typeof key === 'object') return this.many('get', key);
2127
- return this.db.get(new KeyPath(key))
2128
- }
2129
-
2130
- /**
2131
- *
2132
- * @param {*} key
2133
- * @param {*} value
2134
- * @returns Promise
2135
- */
2136
- put(key, value) {
2137
- if (typeof key === 'object') return this.many('put', key);
2138
- return this.db.put(new KeyPath(key), new KeyValue(value));
2139
- }
2140
-
2141
- async has(key) {
2142
- if (typeof key === 'object') return this.many('has', key);
2143
-
2144
- try {
2145
- const has = await this.db.get(new KeyPath(key));
2146
-
2147
- return Boolean(has);
2148
- } catch (e) {
2149
- return false
2150
- }
2151
- }
2152
-
2153
- async delete(key) {
2154
- return this.db.delete(new KeyPath(key))
2155
- }
2156
-
2157
- keys(limit = -1) {
2158
- return this.db.keys(limit)
2159
- }
2160
-
2161
- async values(limit = -1) {
2162
- return this.db.values(limit)
2163
- }
2164
-
2165
- async many(type, _value) {
2166
- const jobs = [];
2167
-
2168
- for (const key of Object.keys(_value)) {
2169
- jobs.push(this[type](key, _value[key]));
2170
- }
2171
-
2172
- return Promise.all(jobs)
2173
- }
2174
-
2175
- async length() {
2176
- const keys = await this.keys();
2177
- return keys.length
2178
- }
2179
-
2180
- async size() {
2181
- let size = 0;
2182
- const query = await this.db.iterate();
2183
- console.log(query);
2184
- for await (const item of query) {
2185
- size += item.value ? item.value.length : item[1].length;
2186
- }
2187
- return size
2188
- }
2189
-
2190
- async clear() {
2191
- return this.db.clear()
2192
- }
2193
-
2194
- async iterate() {
2195
- return this.db.iterate()
2196
- }
2197
-
2198
- }
2199
-
2200
- globalThis.LeofcoinStorage = LeofcoinStorage;
2201
-
2202
- globalThis.leofcoin = globalThis.leofcoin || {};
2203
- globalThis.pubsub = globalThis.pubsub || new LittlePubSub();
2204
- globalThis.globalSub = globalThis.globalSub || new LittlePubSub({verbose: true});
2205
-
2206
- /**
2207
- * @access public
2208
- * @example
2209
- * const peernet = new Peernet();
2210
- */
2211
- class Peernet {
2212
- /**
2213
- * @access public
2214
- * @param {Object} options
2215
- * @param {String} options.network - desired network
2216
- * @param {String} options.stars - star list for selected network (these should match, don't mix networks)
2217
- * @param {String} options.root - path to root directory
2218
- * @param {String} options.storePrefix - prefix for datatores (lfc)
2219
- *
2220
- * @return {Promise} instance of Peernet
2221
- *
2222
- * @example
2223
- * const peernet = new Peernet({network: 'leofcoin', root: '.leofcoin'});
2224
- */
2225
- constructor(options = {}) {
2226
- this._discovered = [];
2227
- /**
2228
- * @property {String} network - current network
2229
- */
2230
- this.network = options.network || 'leofcoin';
2231
- this.stars = options.stars;
2232
- const parts = this.network.split(':');
2233
- this.networkVersion = options.networkVersion || parts.length > 1 ? parts[1] : 'mainnet';
2234
-
2235
- if (!options.storePrefix) options.storePrefix = 'lfc';
2236
- if (!options.port) options.port = 2000;
2237
- if (!options.root) {
2238
- parts[1] ? options.root = `.${parts[0]}/${parts[1]}` : options.root = `.${this.network}`;
2239
- }
2240
-
2241
- globalThis.peernet = this;
2242
- this.bw = {
2243
- up: 0,
2244
- down: 0,
2245
- };
2246
- return this._init(options)
2247
- }
2248
-
2249
- get defaultStores() {
2250
- return ['account', 'wallet', 'block', 'transaction', 'chain', 'data', 'message']
2251
- }
2252
-
2253
- addProto(name, proto) {
2254
- if (!globalThis.peernet.protos[name]) globalThis.peernet.protos[name] = proto;
2255
- }
2256
-
2257
- addCodec(name, codec) {
2258
- if (!this.codecs[name]) this.codecs[name] = codec;
2259
- }
2260
-
2261
- async addStore(name, prefix, root, isPrivate = true) {
2262
- if (name === 'block' || name === 'transaction' || name === 'chain' ||
2263
- name === 'data' || name === 'message') isPrivate = false;
2264
-
2265
- let Storage;
2266
-
2267
- this.hasDaemon ? Storage = LeofcoinStorageClient : Storage = LeofcoinStorage;
2268
-
2269
- if (!globalThis[`${name}Store`]) {
2270
- globalThis[`${name}Store`] = new Storage(name, root);
2271
- await globalThis[`${name}Store`].init();
2272
- }
2273
-
2274
- globalThis[`${name}Store`].private = isPrivate;
2275
- if (!isPrivate) this.stores.push(name);
2276
- }
2277
-
2278
-
2279
- /**
2280
- * @see MessageHandler
2281
- */
2282
- prepareMessage(data) {
2283
- return this._messageHandler.prepareMessage(data)
2284
- }
2285
-
2286
- /**
2287
- * @access public
2288
- *
2289
- * @return {Array} peerId
2290
- */
2291
- get peers() {
2292
- return Object.keys(this.client.connections)
2293
- }
2294
-
2295
- get connections() {
2296
- return Object.values(this.client.connections)
2297
- }
2298
-
2299
- get peerEntries() {
2300
- return Object.entries(this.client.connections)
2301
- }
2302
-
2303
- /**
2304
- * @return {String} id - peerId
2305
- */
2306
- getConnection(id) {
2307
- return this.client.connections[id]
2308
- }
2309
-
2310
- /**
2311
- * @private
2312
- *
2313
- * @param {Object} options
2314
- * @param {String} options.root - path to root directory
2315
- *
2316
- * @return {Promise} instance of Peernet
2317
- */
2318
- async _init(options) {
2319
- // peernetDHT aka closesPeer by coordinates
2320
- /**
2321
- * @type {Object}
2322
- * @property {Object} peer Instance of Peer
2323
- */
2324
- this.dht = new DhtEarth();
2325
- /**
2326
- * @type {Map}
2327
- * @property {Object} peer Instance of Peer
2328
- */
2329
- this.stores = [];
2330
- this.codecs = {...codecs$1};
2331
- this.requestProtos = {};
2332
- this.storePrefix = options.storePrefix;
2333
- this.root = options.root;
2334
-
2335
- const {
2336
- RequestMessage,
2337
- ResponseMessage,
2338
- PeerMessage,
2339
- PeerMessageResponse,
2340
- PeernetMessage,
2341
- DHTMessage,
2342
- DHTMessageResponse,
2343
- DataMessage,
2344
- DataMessageResponse,
2345
- PsMessage,
2346
- ChatMessage,
2347
- PeernetFile
2348
- // FolderMessageResponse
2349
- } = await import(/* webpackChunkName: "messages" */ './messages-4850566c.js');
2350
-
2351
- /**
2352
- * proto Object containing protos
2353
- * @type {Object}
2354
- * @property {PeernetMessage} protos[peernet-message] messageNode
2355
- * @property {DHTMessage} protos[peernet-dht] messageNode
2356
- * @property {DHTMessageResponse} protos[peernet-dht-response] messageNode
2357
- * @property {DataMessage} protos[peernet-data] messageNode
2358
- * @property {DataMessageResponse} protos[peernet-data-response] messageNode
2359
- */
2360
-
2361
- globalThis.peernet.protos = {
2362
- 'peernet-request': RequestMessage,
2363
- 'peernet-response': ResponseMessage,
2364
- 'peernet-peer': PeerMessage,
2365
- 'peernet-peer-response': PeerMessageResponse,
2366
- 'peernet-message': PeernetMessage,
2367
- 'peernet-dht': DHTMessage,
2368
- 'peernet-dht-response': DHTMessageResponse,
2369
- 'peernet-data': DataMessage,
2370
- 'peernet-data-response': DataMessageResponse,
2371
- 'peernet-ps': PsMessage,
2372
- 'chat-message': ChatMessage,
2373
- 'peernet-file': PeernetFile
2374
- };
2375
-
2376
- this._messageHandler = new MessageHandler(this.network);
2377
-
2378
- const {daemon, environment} = await target();
2379
- this.hasDaemon = daemon;
2380
-
2381
- for (const store of this.defaultStores) {
2382
- await this.addStore(store, options.storePrefix, options.root);
2383
- }
2384
-
2385
- const accountExists = await accountStore.has('public');
2386
- if (accountExists) {
2387
- const pub = await accountStore.get('public');
2388
- this.id = JSON.parse(new TextDecoder().decode(pub)).walletId;
2389
- let accounts = await walletStore.get('accounts');
2390
- accounts = new TextDecoder().decode(accounts);
2391
- const selected = await walletStore.get('selected-account');
2392
- globalThis.peernet.selectedAccount = new TextDecoder().decode(selected);
2393
-
2394
- // fixing account issue (string while needs to be a JSON)
2395
- // TODO: remove when on mainnet
2396
- try {
2397
- this.accounts = JSON.parse(accounts);
2398
- } catch {
2399
- this.accounts = [accounts.split(',')];
2400
- }
2401
- } else {
2402
- const importee = await import(/* webpackChunkName: "generate-account" */ './index-3a25de4d.js');
2403
- const generateAccount = importee.default;
2404
- const {identity, accounts, config} = await generateAccount(this.network);
2405
- // await accountStore.put('config', JSON.stringify(config));
2406
- await accountStore.put('public', JSON.stringify({walletId: identity.walletId}));
2407
-
2408
- await walletStore.put('version', String(1));
2409
- await walletStore.put('accounts', JSON.stringify(accounts));
2410
- await walletStore.put('selected-account', accounts[0][1]);
2411
- await walletStore.put('identity', JSON.stringify(identity));
2412
-
2413
- globalThis.peernet.selectedAccount = accounts[0][1];
2414
- this.id = identity.walletId;
2415
- }
2416
- this._peerHandler = new PeerDiscovery(this.id);
2417
- this.peerId = this.id;
2418
-
2419
- pubsub.subscribe('peer:connected', async (peer) => {
2420
- // console.log(peer);
2421
- // console.log({connected: peer.id, as: this._getPeerId(peer.id) });
2422
- // peer.on('peernet.data', async (message) => {
2423
- // const id = message.id
2424
- // message = new PeernetMessage(Buffer.from(message.data.data))
2425
- // const proto = protoFor(message.decoded.data)
2426
- // this._protoHandler({id, proto}, peer)
2427
- // })
2428
- });
2429
-
2430
- /**
2431
- * converts data -> message -> proto
2432
- * @see DataHandler
2433
- */
2434
- pubsub.subscribe('peer:data', dataHandler);
2435
-
2436
-
2437
- const importee = await import(/* webpackChunkName: "peernet-swarm" */ './client-29660363.js');
2438
- /**
2439
- * @access public
2440
- * @type {PeernetClient}
2441
- */
2442
- this.client = new importee.default(this.id, this.networkVersion, this.stars);
2443
- if (globalThis.navigator) {
2444
- globalThis.addEventListener('beforeunload', async () => this.client.close());
2445
- } else {
2446
- process.on('SIGTERM', async () => {
2447
- process.stdin.resume();
2448
- await this.client.close();
2449
- process.exit();
2450
- });
2451
- }
2452
- return this
2453
- }
2454
-
2455
- addRequestHandler(name, method) {
2456
- this.requestProtos[name] = method;
2457
- }
2458
-
2459
- sendMessage(peer, id, data) {
2460
- if (peer.readyState === 'open') {
2461
- peer.send(data, id);
2462
- this.bw.up += data.length;
2463
- } else if (peer.readyState === 'closed') ;
2464
-
2465
- }
2466
-
2467
- async handleDHT(peer, id, proto) {
2468
- let { hash, store } = proto.decoded;
2469
- let has;
2470
-
2471
- if (store) {
2472
- store = globalThis[`${store}Store`];
2473
- has = store.private ? false : await store.has(hash);
2474
- } else {
2475
- has = await this.has(hash);
2476
- }
2477
-
2478
- const data = await new globalThis.peernet.protos['peernet-dht-response']({hash, has});
2479
- const node = await this.prepareMessage(data);
2480
-
2481
- this.sendMessage(peer, id, node.encoded);
2482
- }
2483
-
2484
- async handleData(peer, id, proto) {
2485
- let { hash, store } = proto.decoded;
2486
- let data;
2487
- store = globalThis[`${store}Store`] || await this.whichStore([...this.stores], hash);
2488
-
2489
- if (store && !store.private) {
2490
- data = await store.get(hash);
2491
-
2492
- if (data) {
2493
- data = await new globalThis.peernet.protos['peernet-data-response']({hash, data});
2494
-
2495
- const node = await this.prepareMessage(data);
2496
- this.sendMessage(peer, id, node.encoded);
2497
- }
2498
- }
2499
- }
2500
-
2501
- async handleRequest(peer, id, proto) {
2502
- const method = this.requestProtos[proto.decoded.request];
2503
- if (method) {
2504
- const data = await method();
2505
- const node = await this.prepareMessage(data);
2506
- this.sendMessage(peer, id, node.encoded);
2507
- }
2508
- }
2509
-
2510
- /**
2511
- * @private
2512
- *
2513
- * @param {Buffer} message - peernet message
2514
- * @param {PeernetPeer} peer - peernet peer
2515
- */
2516
- async _protoHandler(message, peer, from) {
2517
- const {id, proto} = message;
2518
- this.bw.down += proto.encoded.length;
2519
- switch(proto.name) {
2520
- case 'peernet-dht': {
2521
- this.handleDHT(peer, id, proto);
2522
- break
2523
- }
2524
- case 'peenet-data': {
2525
- this.handleData(peer, id, proto);
2526
- break
2527
- }
2528
- case 'peernet-request': {
2529
- this.handleRequest(peer, id, proto);
2530
- }
2531
-
2532
- case 'peernet-ps': {
2533
- if (peer.peerId !== this.id) globalSub.publish(proto.decoded.topic, proto.decoded.data);
2534
- }
2535
- }
2536
- }
2537
-
2538
- /**
2539
- * performs a walk and resolves first encounter
2540
- *
2541
- * @param {String} hash
2542
- */
2543
- async walk(hash) {
2544
- if (!hash) throw new Error('hash expected, received undefined')
2545
- const data = await new globalThis.peernet.protos['peernet-dht']({hash});
2546
- this.client.id;
2547
- const walk = async peer => {
2548
- const node = await this.prepareMessage(data);
2549
- let result = await peer.request(node.encoded);
2550
- result = new Uint8Array(Object.values(result));
2551
- const proto = await protoFor(result);
2552
- if (proto.name !== 'peernet-dht-response') throw dhtError(proto.name)
2553
-
2554
- // TODO: give ip and port (just used for location)
2555
- if (!peer.connection.remoteAddress || !peer.connection.localAddress) {
2556
- peer.connection.remoteFamily = 'ipv4';
2557
- peer.connection.remoteAddress = '127.0.0.1';
2558
- peer.connection.remotePort = '0000';
2559
- }
2560
-
2561
- const peerInfo = {
2562
- family: peer.connection.remoteFamily || peer.connection.localFamily,
2563
- address: peer.connection.remoteAddress || peer.connection.localAddress,
2564
- port: peer.connection.remotePort || peer.connection.localPort,
2565
- id: peer.peerId,
2566
- };
2567
-
2568
- if (proto.decoded.has) this.dht.addProvider(peerInfo, proto.decoded.hash);
2569
- };
2570
- let walks = [];
2571
- for (const peer of this.connections) {
2572
- if (peer.peerId !== this.id) {
2573
- walks.push(walk(peer));
2574
- }
2575
- }
2576
- return Promise.all(walks)
2577
- }
2578
-
2579
- /**
2580
- * Override DHT behavior, try's finding the content three times
2581
- *
2582
- * @param {String} hash
2583
- */
2584
- async providersFor(hash) {
2585
- let providers = await this.dht.providersFor(hash);
2586
- // walk the network to find a provider
2587
- if (!providers || providers.length === 0) {
2588
- await this.walk(hash);
2589
- providers = await this.dht.providersFor(hash);
2590
- // second walk the network to find a provider
2591
- if (!providers || providers.length === 0) {
2592
- await this.walk(hash);
2593
- providers = await this.dht.providersFor(hash);
2594
- }
2595
- // last walk
2596
- if (!providers || providers.length === 0) {
2597
- await this.walk(hash);
2598
- providers = await this.dht.providersFor(hash);
2599
- }
2600
- }
2601
- // undefined if no providers given
2602
- return providers
2603
- }
2604
-
2605
- get block() {
2606
- return {
2607
- get: async (hash) => {
2608
- const data = await blockStore.has(hash);
2609
- if (data) return blockStore.get(hash)
2610
- return this.requestData(hash, 'block')
2611
- },
2612
- put: async (hash, data) => {
2613
- if (await blockStore.has(hash)) return
2614
- return await blockStore.put(hash, data)
2615
- },
2616
- has: async (hash) => await blockStore.has(hash, 'block'),
2617
- }
2618
- }
2619
-
2620
- get transaction() {
2621
- return {
2622
- get: async (hash) => {
2623
- const data = await transactionStore.has(hash);
2624
- if (data) return await transactionStore.get(hash)
2625
- return this.requestData(hash, 'transaction')
2626
- },
2627
- put: async (hash, data) => {
2628
- if (await transactionStore.has(hash)) return
2629
- return await transactionStore.put(hash, data)
2630
- },
2631
- has: async (hash) => await transactionStore.has(hash),
2632
- }
2633
- }
2634
-
2635
- async requestData(hash, store) {
2636
- const providers = await this.providersFor(hash);
2637
- if (!providers || providers.size === 0) throw nothingFoundError(hash)
2638
- debug(`found ${providers.size} provider(s) for ${hash}`);
2639
- // get closest peer on earth
2640
- const closestPeer = await this.dht.closestPeer(providers);
2641
- // get peer instance by id
2642
- if (!closestPeer || !closestPeer.id) return this.requestData(hash, store?.name || store)
2643
-
2644
- const id = closestPeer.id;
2645
- if (this.connections) {
2646
- let closest = this.connections.filter((peer) => {
2647
- if (peer.peerId === id) return peer
2648
- });
2649
-
2650
- let data = await new globalThis.peernet.protos['peernet-data']({hash, store: store?.name || store});
2651
-
2652
- const node = await this.prepareMessage(data);
2653
- if (closest[0]) data = await closest[0].request(node.encoded);
2654
- else {
2655
- closest = this.connections.filter((peer) => {
2656
- if (peer.peerId === id) return peer
2657
- });
2658
- if (closest[0]) data = await closest[0].request(node.encoded);
2659
- }
2660
- data = new Uint8Array(Object.values(data));
2661
- const proto = await protoFor(data);
2662
- // TODO: store data automaticly or not
2663
- return BufferToUint8Array(proto.decoded.data)
2664
-
2665
- // this.put(hash, proto.decoded.data)
2666
- }
2667
- return
2668
- }
2669
-
2670
-
2671
- get message() {
2672
- return {
2673
- /**
2674
- * Get content for given message hash
2675
- *
2676
- * @param {String} hash
2677
- */
2678
- get: async (hash) => {
2679
- debug(`get message ${hash}`);
2680
- const message = await messageStore.has(hash);
2681
- if (message) return await messageStore.get(hash)
2682
- return this.requestData(hash, 'message')
2683
- },
2684
- /**
2685
- * put message content
2686
- *
2687
- * @param {String} hash
2688
- * @param {Buffer} message
2689
- */
2690
- put: async (hash, message) => await messageStore.put(hash, message),
2691
- /**
2692
- * @param {String} hash
2693
- * @return {Boolean}
2694
- */
2695
- has: async (hash) => await messageStore.has(hash),
2696
- }
2697
- }
2698
-
2699
- get data() {
2700
- return {
2701
- /**
2702
- * Get content for given data hash
2703
- *
2704
- * @param {String} hash
2705
- */
2706
- get: async (hash) => {
2707
- debug(`get data ${hash}`);
2708
- const data = await dataStore.has(hash);
2709
- if (data) return await dataStore.get(hash)
2710
- return this.requestData(hash, 'data')
2711
- },
2712
- /**
2713
- * put data content
2714
- *
2715
- * @param {String} hash
2716
- * @param {Buffer} data
2717
- */
2718
- put: async (hash, data) => await dataStore.put(hash, data),
2719
- /**
2720
- * @param {String} hash
2721
- * @return {Boolean}
2722
- */
2723
- has: async (hash) => await dataStore.has(hash),
2724
- }
2725
- }
2726
-
2727
- get folder() {
2728
- return {
2729
- /**
2730
- * Get content for given data hash
2731
- *
2732
- * @param {String} hash
2733
- */
2734
- get: async (hash) => {
2735
- debug(`get data ${hash}`);
2736
- const data = await dataStore.has(hash);
2737
- if (data) return await dataStore.get(hash)
2738
- return this.requestData(hash, 'data')
2739
- },
2740
- /**
2741
- * put data content
2742
- *
2743
- * @param {String} hash
2744
- * @param {Buffer} data
2745
- */
2746
- put: async (hash, data) => await dataStore.put(hash, data),
2747
- /**
2748
- * @param {String} hash
2749
- * @return {Boolean}
2750
- */
2751
- has: async (hash) => await dataStore.has(hash),
2752
- }
2753
- }
2754
-
2755
- async addFolder(files) {
2756
- const links = [];
2757
- for (const file of files) {
2758
- const fileNode = await new globalThis.peernet.protos['peernet-file'](file);
2759
- const hash = await fileNode.hash;
2760
- await dataStore.put(hash, fileNode.encoded);
2761
- links.push({hash, path: file.path});
2762
- }
2763
- const node = await new globalThis.peernet.protos['peernet-file']({path: '/', links});
2764
- const hash = await node.hash;
2765
- await dataStore.put(hash, node.encoded);
2766
-
2767
- return hash
2768
- }
2769
-
2770
- async ls(hash, options) {
2771
- let data;
2772
- const has = await dataStore.has(hash);
2773
- data = has ? await dataStore.get(hash) : await this.requestData(hash, 'data');
2774
-
2775
- const node = await new peernet.protos['peernet-file'](data);
2776
- await node.decode();
2777
- console.log(data);
2778
- const paths = [];
2779
- if (node.decoded?.links.length === 0) throw new Error(`${hash} is a file`)
2780
- for (const {path, hash} of node.decoded.links) {
2781
- paths.push({path, hash});
2782
- }
2783
- if (options?.pin) await dataStore.put(hash, node.encoded);
2784
- return paths
2785
- }
2786
-
2787
- async cat(hash, options) {
2788
- let data;
2789
- const has = await dataStore.has(hash);
2790
- data = has ? await dataStore.get(hash) : await this.requestData(hash, 'data');
2791
- const node = await new peernet.protos['peernet-file'](data);
2792
-
2793
- if (node.decoded?.links.length > 0) throw new Error(`${hash} is a directory`)
2794
- if (options?.pin) await dataStore.put(hash, node.encoded);
2795
- return node.decoded.content
2796
- }
2797
-
2798
- /**
2799
- * goes trough given stores and tries to find data for given hash
2800
- * @param {Array} stores
2801
- * @param {string} hash
2802
- */
2803
- async whichStore(stores, hash) {
2804
- let store = stores.pop();
2805
- store = globalThis[`${store}Store`];
2806
- if (store) {
2807
- const has = await store.has(hash);
2808
- if (has) return store
2809
- if (stores.length > 0) return this.whichStore(stores, hash)
2810
- } else return
2811
- }
2812
-
2813
- /**
2814
- * Get content for given hash
2815
- *
2816
- * @param {String} hash - the hash of the wanted data
2817
- * @param {String} store - storeName to access
2818
- */
2819
- async get(hash, store) {
2820
- debug(`get ${hash}`);
2821
- let data;
2822
- if (store) store = globalThis[`${store}Store`];
2823
- if (!store) store = await this.whichStore([...this.stores], hash);
2824
- if (store && await store.has(hash)) data = await store.get(hash);
2825
- if (data) return data
2826
-
2827
- return this.requestData(hash, store?.name || store)
2828
- }
2829
-
2830
- /**
2831
- * put content
2832
- *
2833
- * @param {String} hash
2834
- * @param {Buffer} data
2835
- * @param {String} store - storeName to access
2836
- */
2837
- async put(hash, data, store = 'data') {
2838
- store = globalThis[`${store}Store`];
2839
- return store.put(hash, data)
2840
- }
2841
-
2842
- /**
2843
- * @param {String} hash
2844
- * @return {Boolean}
2845
- */
2846
- async has(hash) {
2847
- const store = await this.whichStore([...this.stores], hash);
2848
- if (store) {
2849
- return store.private ? false : true
2850
- }
2851
- return false
2852
- }
2853
-
2854
- /**
2855
- *
2856
- * @param {String} topic
2857
- * @param {String|Object|Array|Boolean|Buffer} data
2858
- */
2859
- async publish(topic, data) {
2860
- // globalSub.publish(topic, data)
2861
- const id = Math.random().toString(36).slice(-12);
2862
- data = await new globalThis.peernet.protos['peernet-ps']({data, topic});
2863
- for (const peer of this.connections) {
2864
- if (peer.peerId !== this.peerId) {
2865
- const node = await this.prepareMessage(data);
2866
- this.sendMessage(peer, id, node.encoded);
2867
- }
2868
- // TODO: if peer subscribed
2869
- }
2870
- }
2871
-
2872
- createHash(data, name) {
2873
- return new CodeHash(data, {name})
2874
- }
2875
-
2876
- /**
2877
- *
2878
- * @param {String} topic
2879
- * @param {Method} cb
2880
- */
2881
- async subscribe(topic, callback) {
2882
- // TODO: if peer subscribed
2883
- globalSub.subscribe(topic, callback);
2884
- }
2885
-
2886
- async removePeer(peer) {
2887
- return this.client.removePeer(peer)
2888
- }
2889
-
2890
- get Buffer() {
2891
- return Buffer
2892
- }
2893
- }
2894
- globalThis.Peernet = Peernet;
2895
-
2896
- export { FormatInterface as F, LittlePubSub as L, Peernet as P };