@leofcoin/peernet 0.16.7 → 0.17.1

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.
@@ -0,0 +1,1018 @@
1
+ import '@vandeurenglenn/debug';
2
+ import PubSub from '@vandeurenglenn/little-pubsub';
3
+ import { Codec, codecs } from '@leofcoin/codec-format-interface';
4
+ import LeofcoinStorage from '@leofcoin/storage';
5
+
6
+ const BufferToUint8Array = data => {
7
+ if (data.type === 'Buffer') {
8
+ data = new Uint8Array(data.data);
9
+ }
10
+ return data
11
+ };
12
+
13
+ const protoFor = (message) => {
14
+ const codec = new Codec(message);
15
+ if (!codec.name) throw new Error('proto not found')
16
+ const Proto = globalThis.peernet.protos[codec.name];
17
+ if (!Proto) throw (new Error(`No proto defined for ${codec.name}`))
18
+ return new Proto(message)
19
+ };
20
+
21
+ /**
22
+ * wether or not a peernet daemon is active
23
+ * @return {Boolean}
24
+ */
25
+ const hasDaemon = async () => {
26
+ try {
27
+ let response = await fetch('http://127.0.0.1:1000/api/version');
28
+ response = await response.json();
29
+ return Boolean(response.client === '@peernet/api/http')
30
+ } catch (e) {
31
+ return false
32
+ }
33
+ };
34
+
35
+ const https = () => {
36
+ if (!globalThis.location) return false;
37
+ return Boolean(globalThis.location.protocol === 'https:')
38
+ };
39
+
40
+ /**
41
+ * Get current environment
42
+ * @return {String} current environment [node, electron, browser]
43
+ */
44
+ const environment = () => {
45
+ const _navigator = globalThis.navigator;
46
+ if (!_navigator) {
47
+ return 'node'
48
+ } else if (_navigator && /electron/i.test(_navigator.userAgent)) {
49
+ return 'electron'
50
+ } else {
51
+ return 'browser'
52
+ }
53
+ };
54
+
55
+ /**
56
+ * * Get current environment
57
+ * @return {Object} result
58
+ * @property {Boolean} reult.daemon whether or not daemon is running
59
+ * @property {Boolean} reult.environment Current environment
60
+ */
61
+ const target = async () => {
62
+ let daemon = false;
63
+ if (!https()) daemon = await hasDaemon();
64
+
65
+ return {daemon, environment: environment()}
66
+ };
67
+
68
+ class PeerDiscovery {
69
+ constructor(id) {
70
+ this.id = id;
71
+ }
72
+
73
+ _getPeerId(id) {
74
+ if (!peernet.peerMap || peernet.peerMap && peernet.peerMap.size === 0) return false
75
+
76
+ for (const entry of [...peernet.peerMap.entries()]) {
77
+ for (const _id of entry[1]) {
78
+ if (_id === id) return entry[0]
79
+ }
80
+ }
81
+ }
82
+
83
+ async discover(peer) {
84
+ let id = this._getPeerId(peer.id);
85
+ if (id) return id
86
+ const data = await new peernet.protos['peernet-peer']({id: this.id});
87
+ const node = await peernet.prepareMessage(peer.id, data.encoded);
88
+
89
+ let response = await peer.request(node.encoded);
90
+ response = await protoFor(response);
91
+ response = await new peernet.protos['peernet-peer-response'](response.decoded.data);
92
+
93
+ id = response.decoded.id;
94
+ if (id === this.id) return;
95
+
96
+ if (!peernet.peerMap.has(id)) peernet.peerMap.set(id, [peer.id]);
97
+ else {
98
+ const connections = peernet.peerMap.get(id);
99
+ if (connections.indexOf(peer.id) === -1) {
100
+ connections.push(peer.id);
101
+ peernet.peerMap.set(peer.id, connections);
102
+ }
103
+ }
104
+ return id
105
+ }
106
+
107
+ async discoverHandler(message, peer) {
108
+ const {id, proto} = message;
109
+ // if (typeof message.data === 'string') message.data = Buffer.from(message.data)
110
+ if (proto.name === 'peernet-peer') {
111
+ const from = proto.decoded.id;
112
+ if (from === this.id) return;
113
+
114
+ if (!peernet.peerMap.has(from)) peernet.peerMap.set(from, [peer.id]);
115
+ else {
116
+ const connections = peernet.peerMap.get(from);
117
+ if (connections.indexOf(peer.id) === -1) {
118
+ connections.push(peer.id);
119
+ peernet.peerMap.set(from, connections);
120
+ }
121
+ }
122
+ const data = await new peernet.protos['peernet-peer-response']({id: this.id});
123
+ const node = await peernet.prepareMessage(from, data.encoded);
124
+
125
+ peer.write(Buffer.from(JSON.stringify({id, data: node.encoded})));
126
+ } else if (proto.name === 'peernet-peer-response') {
127
+ const from = proto.decoded.id;
128
+ if (from === this.id) return;
129
+
130
+ if (!peernet.peerMap.has(from)) peernet.peerMap.set(from, [peer.id]);
131
+ else {
132
+ const connections = peernet.peerMap.get(from);
133
+ if (connections.indexOf(peer.id) === -1) {
134
+ connections.push(peer.id);
135
+ peernet.peerMap.set(from, connections);
136
+ }
137
+ }
138
+ }
139
+ }
140
+ }
141
+
142
+ /**
143
+ * Keep history of fetched address and ptr
144
+ * @property {Object} address
145
+ * @property {Object} ptr
146
+ */
147
+ const lastFetched = {
148
+ address: {
149
+ value: undefined,
150
+ timestamp: 0,
151
+ },
152
+ ptr: {
153
+ value: undefined,
154
+ timestamp: 0,
155
+ },
156
+ };
157
+
158
+ const getAddress = async () => {
159
+ const {address} = lastFetched;
160
+ const now = Math.round(new Date().getTime() / 1000);
161
+ if (now - address.timestamp > 1200000) {
162
+ address.value = await fetch('https://icanhazip.com/');
163
+ address.value = await address.value.text();
164
+ address.timestamp = Math.round(new Date().getTime() / 1000);
165
+ lastFetched.address = address;
166
+ }
167
+
168
+ return address.value
169
+ };
170
+
171
+ const degreesToRadians = (degrees) => {
172
+ return degrees * Math.PI / 180;
173
+ };
174
+
175
+ const distanceInKmBetweenEarthCoordinates = (lat1, lon1, lat2, lon2) => {
176
+ const earthRadiusKm = 6371;
177
+
178
+ const dLat = degreesToRadians(lat2-lat1);
179
+ const dLon = degreesToRadians(lon2-lon1);
180
+
181
+ lat1 = degreesToRadians(lat1);
182
+ lat2 = degreesToRadians(lat2);
183
+ const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
184
+ Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
185
+ const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
186
+ return earthRadiusKm * c;
187
+ };
188
+
189
+ class DhtEarth {
190
+ /**
191
+ *
192
+ */
193
+ constructor() {
194
+ this.providerMap = new Map();
195
+ }
196
+
197
+ /**
198
+ * @param {Object} address
199
+ * @return {Object} {latitude: lat, longitude: lon}
200
+ */
201
+ async getCoordinates(address) {
202
+ // const {address} = parseAddress(provider)
203
+ const request = `https://whereis.leofcoin.org/?ip=${address}`;
204
+ let response = await fetch(request);
205
+ response = await response.json();
206
+ const {lat, lon} = response;
207
+ return {latitude: lat, longitude: lon}
208
+ }
209
+
210
+ /**
211
+ * @param {Object} peer
212
+ * @param {Object} provider
213
+ * @return {Object} {provider, distance}
214
+ */
215
+ async getDistance(peer, provider) {
216
+ const {latitude, longitude} = await this.getCoordinates(provider.address);
217
+ return {provider, distance: distanceInKmBetweenEarthCoordinates(peer.latitude, peer.longitude, latitude, longitude)}
218
+ }
219
+
220
+ /**
221
+ * @param {Array} providers
222
+ * @return {Object} closestPeer
223
+ */
224
+ async closestPeer(providers) {
225
+ let all = [];
226
+ const address = await getAddress();
227
+ const peerLoc = await this.getCoordinates(address);
228
+
229
+ for (const provider of providers) {
230
+ if (provider.address === '127.0.0.1') all.push({provider, distance: 0});
231
+ else all.push(this.getDistance(peerLoc, provider));
232
+ }
233
+
234
+ all = await Promise.all(all);
235
+ all = all.sort((previous, current) => previous.distance - current.distance);
236
+ return all[0].provider;
237
+ }
238
+
239
+ /**
240
+ * @param {String} hash
241
+ * @return {Array} providers
242
+ */
243
+ providersFor(hash) {
244
+ return this.providerMap.get(hash);
245
+ }
246
+
247
+ /**
248
+ * @param {String} address
249
+ * @param {String} hash
250
+ * @return {Array} providers
251
+ */
252
+ async addProvider(address, hash) {
253
+ let providers = [];
254
+ if (this.providerMap.has(hash)) providers = this.providerMap.get(hash);
255
+
256
+ providers = new Set([...providers, address]);
257
+ this.providerMap.set(hash, providers);
258
+ return providers;
259
+ }
260
+ }
261
+
262
+ class MessageHandler {
263
+ constructor(network) {
264
+ this.network = network;
265
+ }
266
+ /**
267
+ * hash and sign message
268
+ *
269
+ * @param {object} message
270
+ * @param {Buffer} message.from peer id
271
+ * @param {Buffer} message.to peer id
272
+ * @param {string} message.data Peernet message
273
+ * (PeernetMessage excluded) encoded as a string
274
+ * @return message
275
+ */
276
+ async hashAndSignMessage(message) {
277
+ let identity = await walletStore.get('identity');
278
+ identity = JSON.parse(identity);
279
+ if (!globalThis.MultiWallet) {
280
+ const importee = await import(/* webpackChunkName: "multi-wallet" */ '@leofcoin/multi-wallet');
281
+ globalThis.MultiWallet = importee.default;
282
+ }
283
+ const wallet = new MultiWallet(this.network);
284
+ wallet.recover(identity.mnemonic);
285
+ message.decoded.signature = wallet.sign(Buffer.from(await message.hash).slice(0, 32));
286
+ return message
287
+ }
288
+
289
+ /**
290
+ * @param {String} from - peer id
291
+ * @param {String} to - peer id
292
+ * @param {String|PeernetMessage} data - data encoded message string
293
+ * or the messageNode itself
294
+ */
295
+ async prepareMessage(message) {
296
+ if (message.keys.includes('signature')) {
297
+ message = await this.hashAndSignMessage(message);
298
+ }
299
+
300
+ return message
301
+ }
302
+ }
303
+
304
+ const dataHandler = async message => {
305
+ if (!message) return
306
+
307
+ const {data, id, from} = message;
308
+ const proto = await protoFor(data);
309
+
310
+ peernet._protoHandler({id, proto}, peernet.client.connections[from], from);
311
+ };
312
+
313
+ const dhtError = (proto) => {
314
+ const text = `Received proto ${proto.name} expected peernet-dht-response`;
315
+ return new Error(`Routing error: ${text}`)
316
+ };
317
+
318
+ const nothingFoundError = (hash) => {
319
+ return new Error(`nothing found for ${hash}`)
320
+ };
321
+
322
+ globalThis.LeofcoinStorage = LeofcoinStorage;
323
+
324
+ globalThis.leofcoin = globalThis.leofcoin || {};
325
+ globalThis.pubsub = globalThis.pubsub || new PubSub();
326
+ globalThis.globalSub = globalThis.globalSub || new PubSub({verbose: true});
327
+
328
+ /**
329
+ * @access public
330
+ * @example
331
+ * const peernet = new Peernet();
332
+ */
333
+ class Peernet {
334
+ /**
335
+ * @access public
336
+ * @param {Object} options
337
+ * @param {String} options.network - desired network
338
+ * @param {String} options.stars - star list for selected network (these should match, don't mix networks)
339
+ * @param {String} options.root - path to root directory
340
+ * @param {String} options.storePrefix - prefix for datatores (lfc)
341
+ *
342
+ * @return {Promise} instance of Peernet
343
+ *
344
+ * @example
345
+ * const peernet = new Peernet({network: 'leofcoin', root: '.leofcoin'});
346
+ */
347
+ constructor(options = {}) {
348
+ this._discovered = [];
349
+ /**
350
+ * @property {String} network - current network
351
+ */
352
+ this.network = options.network || 'leofcoin';
353
+ this.stars = options.stars;
354
+ const parts = this.network.split(':');
355
+ this.networkVersion = options.networkVersion || parts.length > 1 ? parts[1] : 'mainnet';
356
+
357
+ if (!options.storePrefix) options.storePrefix = 'lfc';
358
+ if (!options.port) options.port = 2000;
359
+ if (!options.root) {
360
+ parts[1] ? options.root = `.${parts[0]}/${parts[1]}` : options.root = `.${this.network}`;
361
+ }
362
+
363
+ globalThis.peernet = this;
364
+ this.bw = {
365
+ up: 0,
366
+ down: 0,
367
+ };
368
+ return this._init(options)
369
+ }
370
+
371
+ get defaultStores() {
372
+ return ['account', 'wallet', 'block', 'transaction', 'chain', 'data', 'message']
373
+ }
374
+
375
+ addProto(name, proto) {
376
+ if (!globalThis.peernet.protos[name]) globalThis.peernet.protos[name] = proto;
377
+ }
378
+
379
+ addCodec(name, codec) {
380
+ if (!this.codecs[name]) this.codecs[name] = codec;
381
+ }
382
+
383
+ async addStore(name, prefix, root, isPrivate = true) {
384
+ if (name === 'block' || name === 'transaction' || name === 'chain' ||
385
+ name === 'data' || name === 'message') isPrivate = false;
386
+
387
+ let Storage;
388
+
389
+ this.hasDaemon ? Storage = LeofcoinStorageClient : Storage = LeofcoinStorage;
390
+
391
+ if (!globalThis[`${name}Store`]) {
392
+ globalThis[`${name}Store`] = new Storage(name, root);
393
+ await globalThis[`${name}Store`].init();
394
+ }
395
+
396
+ globalThis[`${name}Store`].private = isPrivate;
397
+ if (!isPrivate) this.stores.push(name);
398
+ }
399
+
400
+
401
+ /**
402
+ * @see MessageHandler
403
+ */
404
+ prepareMessage(data) {
405
+ return this._messageHandler.prepareMessage(data)
406
+ }
407
+
408
+ /**
409
+ * @access public
410
+ *
411
+ * @return {Array} peerId
412
+ */
413
+ get peers() {
414
+ return Object.keys(this.client.connections)
415
+ }
416
+
417
+ get connections() {
418
+ return Object.values(this.client.connections)
419
+ }
420
+
421
+ get peerEntries() {
422
+ return Object.entries(this.client.connections)
423
+ }
424
+
425
+ /**
426
+ * @return {String} id - peerId
427
+ */
428
+ getConnection(id) {
429
+ return this.client.connections[id]
430
+ }
431
+
432
+ /**
433
+ * @private
434
+ *
435
+ * @param {Object} options
436
+ * @param {String} options.root - path to root directory
437
+ *
438
+ * @return {Promise} instance of Peernet
439
+ */
440
+ async _init(options) {
441
+ // peernetDHT aka closesPeer by coordinates
442
+ /**
443
+ * @type {Object}
444
+ * @property {Object} peer Instance of Peer
445
+ */
446
+ this.dht = new DhtEarth();
447
+ /**
448
+ * @type {Map}
449
+ * @property {Object} peer Instance of Peer
450
+ */
451
+ this.stores = [];
452
+ this.codecs = {...codecs};
453
+ this.requestProtos = {};
454
+ this.storePrefix = options.storePrefix;
455
+ this.root = options.root;
456
+
457
+ const {
458
+ RequestMessage,
459
+ ResponseMessage,
460
+ PeerMessage,
461
+ PeerMessageResponse,
462
+ PeernetMessage,
463
+ DHTMessage,
464
+ DHTMessageResponse,
465
+ DataMessage,
466
+ DataMessageResponse,
467
+ PsMessage,
468
+ ChatMessage,
469
+ PeernetFile
470
+ // FolderMessageResponse
471
+ } = await import(/* webpackChunkName: "messages" */ './messages-796c4d5c.js');
472
+
473
+ /**
474
+ * proto Object containing protos
475
+ * @type {Object}
476
+ * @property {PeernetMessage} protos[peernet-message] messageNode
477
+ * @property {DHTMessage} protos[peernet-dht] messageNode
478
+ * @property {DHTMessageResponse} protos[peernet-dht-response] messageNode
479
+ * @property {DataMessage} protos[peernet-data] messageNode
480
+ * @property {DataMessageResponse} protos[peernet-data-response] messageNode
481
+ */
482
+
483
+ globalThis.peernet.protos = {
484
+ 'peernet-request': RequestMessage,
485
+ 'peernet-response': ResponseMessage,
486
+ 'peernet-peer': PeerMessage,
487
+ 'peernet-peer-response': PeerMessageResponse,
488
+ 'peernet-message': PeernetMessage,
489
+ 'peernet-dht': DHTMessage,
490
+ 'peernet-dht-response': DHTMessageResponse,
491
+ 'peernet-data': DataMessage,
492
+ 'peernet-data-response': DataMessageResponse,
493
+ 'peernet-ps': PsMessage,
494
+ 'chat-message': ChatMessage,
495
+ 'peernet-file': PeernetFile
496
+ };
497
+
498
+ this._messageHandler = new MessageHandler(this.network);
499
+
500
+ const {daemon, environment} = await target();
501
+ this.hasDaemon = daemon;
502
+
503
+ for (const store of this.defaultStores) {
504
+ await this.addStore(store, options.storePrefix, options.root);
505
+ }
506
+
507
+ const accountExists = await accountStore.has('public');
508
+ if (accountExists) {
509
+ const pub = await accountStore.get('public');
510
+ this.id = JSON.parse(new TextDecoder().decode(pub)).walletId;
511
+ let accounts = await walletStore.get('accounts');
512
+ accounts = new TextDecoder().decode(accounts);
513
+ const selected = await walletStore.get('selected-account');
514
+ globalThis.peernet.selectedAccount = new TextDecoder().decode(selected);
515
+
516
+ // fixing account issue (string while needs to be a JSON)
517
+ // TODO: remove when on mainnet
518
+ try {
519
+ this.accounts = JSON.parse(accounts);
520
+ } catch {
521
+ this.accounts = [accounts.split(',')];
522
+ }
523
+ } else {
524
+ const importee = await import(/* webpackChunkName: "generate-account" */ '@leofcoin/generate-account');
525
+ const generateAccount = importee.default;
526
+ const {identity, accounts, config} = await generateAccount(this.network);
527
+ // await accountStore.put('config', JSON.stringify(config));
528
+ await accountStore.put('public', JSON.stringify({walletId: identity.walletId}));
529
+
530
+ await walletStore.put('version', String(1));
531
+ await walletStore.put('accounts', JSON.stringify(accounts));
532
+ await walletStore.put('selected-account', accounts[0][1]);
533
+ await walletStore.put('identity', JSON.stringify(identity));
534
+
535
+ globalThis.peernet.selectedAccount = accounts[0][1];
536
+ this.id = identity.walletId;
537
+ }
538
+ this._peerHandler = new PeerDiscovery(this.id);
539
+ this.peerId = this.id;
540
+
541
+ pubsub.subscribe('peer:connected', async (peer) => {
542
+ // console.log(peer);
543
+ // console.log({connected: peer.id, as: this._getPeerId(peer.id) });
544
+ // peer.on('peernet.data', async (message) => {
545
+ // const id = message.id
546
+ // message = new PeernetMessage(Buffer.from(message.data.data))
547
+ // const proto = protoFor(message.decoded.data)
548
+ // this._protoHandler({id, proto}, peer)
549
+ // })
550
+ });
551
+
552
+ /**
553
+ * converts data -> message -> proto
554
+ * @see DataHandler
555
+ */
556
+ pubsub.subscribe('peer:data', dataHandler);
557
+
558
+
559
+ const importee = await import(/* webpackChunkName: "peernet-swarm" */ '@leofcoin/peernet-swarm/client');
560
+ /**
561
+ * @access public
562
+ * @type {PeernetClient}
563
+ */
564
+ this.client = new importee.default(this.id, this.networkVersion, this.stars);
565
+ if (globalThis.navigator) {
566
+ globalThis.addEventListener('beforeunload', async () => this.client.close());
567
+ } else {
568
+ process.on('SIGTERM', async () => {
569
+ process.stdin.resume();
570
+ await this.client.close();
571
+ process.exit();
572
+ });
573
+ }
574
+ return this
575
+ }
576
+
577
+ addRequestHandler(name, method) {
578
+ this.requestProtos[name] = method;
579
+ }
580
+
581
+ sendMessage(peer, id, data) {
582
+ if (peer.readyState === 'open') {
583
+ peer.send(data, id);
584
+ this.bw.up += data.length;
585
+ } else if (peer.readyState === 'closed') ;
586
+
587
+ }
588
+
589
+ async handleDHT(peer, id, proto) {
590
+ let { hash, store } = proto.decoded;
591
+ let has;
592
+
593
+ if (store) {
594
+ store = globalThis[`${store}Store`];
595
+ has = store.private ? false : await store.has(hash);
596
+ } else {
597
+ has = await this.has(hash);
598
+ }
599
+
600
+ const data = await new globalThis.peernet.protos['peernet-dht-response']({hash, has});
601
+ const node = await this.prepareMessage(data);
602
+
603
+ this.sendMessage(peer, id, node.encoded);
604
+ }
605
+
606
+ async handleData(peer, id, proto) {
607
+ let { hash, store } = proto.decoded;
608
+ let data;
609
+ store = globalThis[`${store}Store`] || await this.whichStore([...this.stores], hash);
610
+
611
+ if (store && !store.private) {
612
+ data = await store.get(hash);
613
+
614
+ if (data) {
615
+ data = await new globalThis.peernet.protos['peernet-data-response']({hash, data});
616
+
617
+ const node = await this.prepareMessage(data);
618
+ this.sendMessage(peer, id, node.encoded);
619
+ }
620
+ }
621
+ }
622
+
623
+ async handleRequest(peer, id, proto) {
624
+ const method = this.requestProtos[proto.decoded.request];
625
+ if (method) {
626
+ const data = await method();
627
+ const node = await this.prepareMessage(data);
628
+ this.sendMessage(peer, id, node.encoded);
629
+ }
630
+ }
631
+
632
+ /**
633
+ * @private
634
+ *
635
+ * @param {Buffer} message - peernet message
636
+ * @param {PeernetPeer} peer - peernet peer
637
+ */
638
+ async _protoHandler(message, peer, from) {
639
+ const {id, proto} = message;
640
+ this.bw.down += proto.encoded.length;
641
+ switch(proto.name) {
642
+ case 'peernet-dht': {
643
+ this.handleDHT(peer, id, proto);
644
+ break
645
+ }
646
+ case 'peenet-data': {
647
+ this.handleData(peer, id, proto);
648
+ break
649
+ }
650
+ case 'peernet-request': {
651
+ this.handleRequest(peer, id, proto);
652
+ }
653
+
654
+ case 'peernet-ps': {
655
+ if (peer.peerId !== this.id) globalSub.publish(proto.decoded.topic, proto.decoded.data);
656
+ }
657
+ }
658
+ }
659
+
660
+ /**
661
+ * performs a walk and resolves first encounter
662
+ *
663
+ * @param {String} hash
664
+ */
665
+ async walk(hash) {
666
+ if (!hash) throw new Error('hash expected, received undefined')
667
+ const data = await new globalThis.peernet.protos['peernet-dht']({hash});
668
+ this.client.id;
669
+ const walk = async peer => {
670
+ const node = await this.prepareMessage(data);
671
+ let result = await peer.request(node.encoded);
672
+ result = new Uint8Array(Object.values(result));
673
+ const proto = await protoFor(result);
674
+ if (proto.name !== 'peernet-dht-response') throw dhtError(proto.name)
675
+
676
+ // TODO: give ip and port (just used for location)
677
+ if (!peer.connection.remoteAddress || !peer.connection.localAddress) {
678
+ peer.connection.remoteFamily = 'ipv4';
679
+ peer.connection.remoteAddress = '127.0.0.1';
680
+ peer.connection.remotePort = '0000';
681
+ }
682
+
683
+ const peerInfo = {
684
+ family: peer.connection.remoteFamily || peer.connection.localFamily,
685
+ address: peer.connection.remoteAddress || peer.connection.localAddress,
686
+ port: peer.connection.remotePort || peer.connection.localPort,
687
+ id: peer.peerId,
688
+ };
689
+
690
+ if (proto.decoded.has) this.dht.addProvider(peerInfo, proto.decoded.hash);
691
+ };
692
+ let walks = [];
693
+ for (const peer of this.connections) {
694
+ if (peer.peerId !== this.id) {
695
+ walks.push(walk(peer));
696
+ }
697
+ }
698
+ return Promise.all(walks)
699
+ }
700
+
701
+ /**
702
+ * Override DHT behavior, try's finding the content three times
703
+ *
704
+ * @param {String} hash
705
+ */
706
+ async providersFor(hash) {
707
+ let providers = await this.dht.providersFor(hash);
708
+ // walk the network to find a provider
709
+ if (!providers || providers.length === 0) {
710
+ await this.walk(hash);
711
+ providers = await this.dht.providersFor(hash);
712
+ // second walk the network to find a provider
713
+ if (!providers || providers.length === 0) {
714
+ await this.walk(hash);
715
+ providers = await this.dht.providersFor(hash);
716
+ }
717
+ // last walk
718
+ if (!providers || providers.length === 0) {
719
+ await this.walk(hash);
720
+ providers = await this.dht.providersFor(hash);
721
+ }
722
+ }
723
+ // undefined if no providers given
724
+ return providers
725
+ }
726
+
727
+ get block() {
728
+ return {
729
+ get: async (hash) => {
730
+ const data = await blockStore.has(hash);
731
+ if (data) return blockStore.get(hash)
732
+ return this.requestData(hash, 'block')
733
+ },
734
+ put: async (hash, data) => {
735
+ if (await blockStore.has(hash)) return
736
+ return await blockStore.put(hash, data)
737
+ },
738
+ has: async (hash) => await blockStore.has(hash, 'block'),
739
+ }
740
+ }
741
+
742
+ get transaction() {
743
+ return {
744
+ get: async (hash) => {
745
+ const data = await transactionStore.has(hash);
746
+ if (data) return await transactionStore.get(hash)
747
+ return this.requestData(hash, 'transaction')
748
+ },
749
+ put: async (hash, data) => {
750
+ if (await transactionStore.has(hash)) return
751
+ return await transactionStore.put(hash, data)
752
+ },
753
+ has: async (hash) => await transactionStore.has(hash),
754
+ }
755
+ }
756
+
757
+ async requestData(hash, store) {
758
+ const providers = await this.providersFor(hash);
759
+ if (!providers || providers.size === 0) throw nothingFoundError(hash)
760
+ debug(`found ${providers.size} provider(s) for ${hash}`);
761
+ // get closest peer on earth
762
+ const closestPeer = await this.dht.closestPeer(providers);
763
+ // get peer instance by id
764
+ if (!closestPeer || !closestPeer.id) return this.requestData(hash, store?.name || store)
765
+
766
+ const id = closestPeer.id;
767
+ if (this.connections) {
768
+ let closest = this.connections.filter((peer) => {
769
+ if (peer.peerId === id) return peer
770
+ });
771
+
772
+ let data = await new globalThis.peernet.protos['peernet-data']({hash, store: store?.name || store});
773
+
774
+ const node = await this.prepareMessage(data);
775
+ if (closest[0]) data = await closest[0].request(node.encoded);
776
+ else {
777
+ closest = this.connections.filter((peer) => {
778
+ if (peer.peerId === id) return peer
779
+ });
780
+ if (closest[0]) data = await closest[0].request(node.encoded);
781
+ }
782
+ data = new Uint8Array(Object.values(data));
783
+ const proto = await protoFor(data);
784
+ // TODO: store data automaticly or not
785
+ return BufferToUint8Array(proto.decoded.data)
786
+
787
+ // this.put(hash, proto.decoded.data)
788
+ }
789
+ return
790
+ }
791
+
792
+
793
+ get message() {
794
+ return {
795
+ /**
796
+ * Get content for given message hash
797
+ *
798
+ * @param {String} hash
799
+ */
800
+ get: async (hash) => {
801
+ debug(`get message ${hash}`);
802
+ const message = await messageStore.has(hash);
803
+ if (message) return await messageStore.get(hash)
804
+ return this.requestData(hash, 'message')
805
+ },
806
+ /**
807
+ * put message content
808
+ *
809
+ * @param {String} hash
810
+ * @param {Buffer} message
811
+ */
812
+ put: async (hash, message) => await messageStore.put(hash, message),
813
+ /**
814
+ * @param {String} hash
815
+ * @return {Boolean}
816
+ */
817
+ has: async (hash) => await messageStore.has(hash),
818
+ }
819
+ }
820
+
821
+ get data() {
822
+ return {
823
+ /**
824
+ * Get content for given data hash
825
+ *
826
+ * @param {String} hash
827
+ */
828
+ get: async (hash) => {
829
+ debug(`get data ${hash}`);
830
+ const data = await dataStore.has(hash);
831
+ if (data) return await dataStore.get(hash)
832
+ return this.requestData(hash, 'data')
833
+ },
834
+ /**
835
+ * put data content
836
+ *
837
+ * @param {String} hash
838
+ * @param {Buffer} data
839
+ */
840
+ put: async (hash, data) => await dataStore.put(hash, data),
841
+ /**
842
+ * @param {String} hash
843
+ * @return {Boolean}
844
+ */
845
+ has: async (hash) => await dataStore.has(hash),
846
+ }
847
+ }
848
+
849
+ get folder() {
850
+ return {
851
+ /**
852
+ * Get content for given data hash
853
+ *
854
+ * @param {String} hash
855
+ */
856
+ get: async (hash) => {
857
+ debug(`get data ${hash}`);
858
+ const data = await dataStore.has(hash);
859
+ if (data) return await dataStore.get(hash)
860
+ return this.requestData(hash, 'data')
861
+ },
862
+ /**
863
+ * put data content
864
+ *
865
+ * @param {String} hash
866
+ * @param {Buffer} data
867
+ */
868
+ put: async (hash, data) => await dataStore.put(hash, data),
869
+ /**
870
+ * @param {String} hash
871
+ * @return {Boolean}
872
+ */
873
+ has: async (hash) => await dataStore.has(hash),
874
+ }
875
+ }
876
+
877
+ async addFolder(files) {
878
+ const links = [];
879
+ for (const file of files) {
880
+ const fileNode = await new globalThis.peernet.protos['peernet-file'](file);
881
+ const hash = await fileNode.hash;
882
+ await dataStore.put(hash, fileNode.encoded);
883
+ links.push({hash, path: file.path});
884
+ }
885
+ const node = await new globalThis.peernet.protos['peernet-file']({path: '/', links});
886
+ const hash = await node.hash;
887
+ await dataStore.put(hash, node.encoded);
888
+
889
+ return hash
890
+ }
891
+
892
+ async ls(hash, options) {
893
+ let data;
894
+ const has = await dataStore.has(hash);
895
+ data = has ? await dataStore.get(hash) : await this.requestData(hash, 'data');
896
+
897
+ const node = await new peernet.protos['peernet-file'](data);
898
+ await node.decode();
899
+ console.log(data);
900
+ const paths = [];
901
+ if (node.decoded?.links.length === 0) throw new Error(`${hash} is a file`)
902
+ for (const {path, hash} of node.decoded.links) {
903
+ paths.push({path, hash});
904
+ }
905
+ if (options?.pin) await dataStore.put(hash, node.encoded);
906
+ return paths
907
+ }
908
+
909
+ async cat(hash, options) {
910
+ let data;
911
+ const has = await dataStore.has(hash);
912
+ data = has ? await dataStore.get(hash) : await this.requestData(hash, 'data');
913
+ const node = await new peernet.protos['peernet-file'](data);
914
+
915
+ if (node.decoded?.links.length > 0) throw new Error(`${hash} is a directory`)
916
+ if (options?.pin) await dataStore.put(hash, node.encoded);
917
+ return node.decoded.content
918
+ }
919
+
920
+ /**
921
+ * goes trough given stores and tries to find data for given hash
922
+ * @param {Array} stores
923
+ * @param {string} hash
924
+ */
925
+ async whichStore(stores, hash) {
926
+ let store = stores.pop();
927
+ store = globalThis[`${store}Store`];
928
+ if (store) {
929
+ const has = await store.has(hash);
930
+ if (has) return store
931
+ if (stores.length > 0) return this.whichStore(stores, hash)
932
+ } else return
933
+ }
934
+
935
+ /**
936
+ * Get content for given hash
937
+ *
938
+ * @param {String} hash - the hash of the wanted data
939
+ * @param {String} store - storeName to access
940
+ */
941
+ async get(hash, store) {
942
+ debug(`get ${hash}`);
943
+ let data;
944
+ if (store) store = globalThis[`${store}Store`];
945
+ if (!store) store = await this.whichStore([...this.stores], hash);
946
+ if (store && await store.has(hash)) data = await store.get(hash);
947
+ if (data) return data
948
+
949
+ return this.requestData(hash, store?.name || store)
950
+ }
951
+
952
+ /**
953
+ * put content
954
+ *
955
+ * @param {String} hash
956
+ * @param {Buffer} data
957
+ * @param {String} store - storeName to access
958
+ */
959
+ async put(hash, data, store = 'data') {
960
+ store = globalThis[`${store}Store`];
961
+ return store.put(hash, data)
962
+ }
963
+
964
+ /**
965
+ * @param {String} hash
966
+ * @return {Boolean}
967
+ */
968
+ async has(hash) {
969
+ const store = await this.whichStore([...this.stores], hash);
970
+ if (store) {
971
+ return store.private ? false : true
972
+ }
973
+ return false
974
+ }
975
+
976
+ /**
977
+ *
978
+ * @param {String} topic
979
+ * @param {String|Object|Array|Boolean|Buffer} data
980
+ */
981
+ async publish(topic, data) {
982
+ // globalSub.publish(topic, data)
983
+ const id = Math.random().toString(36).slice(-12);
984
+ data = await new globalThis.peernet.protos['peernet-ps']({data, topic});
985
+ for (const peer of this.connections) {
986
+ if (peer.peerId !== this.peerId) {
987
+ const node = await this.prepareMessage(data);
988
+ this.sendMessage(peer, id, node.encoded);
989
+ }
990
+ // TODO: if peer subscribed
991
+ }
992
+ }
993
+
994
+ createHash(data, name) {
995
+ return new CodeHash(data, {name})
996
+ }
997
+
998
+ /**
999
+ *
1000
+ * @param {String} topic
1001
+ * @param {Method} cb
1002
+ */
1003
+ async subscribe(topic, callback) {
1004
+ // TODO: if peer subscribed
1005
+ globalSub.subscribe(topic, callback);
1006
+ }
1007
+
1008
+ async removePeer(peer) {
1009
+ return this.client.removePeer(peer)
1010
+ }
1011
+
1012
+ get Buffer() {
1013
+ return Buffer
1014
+ }
1015
+ }
1016
+ globalThis.Peernet = Peernet;
1017
+
1018
+ export { Peernet as default };