@leofcoin/peernet 1.1.58 → 1.1.59

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.
package/src/peernet.ts CHANGED
@@ -1,34 +1,34 @@
1
- import "@vandeurenglenn/debug";
2
- import PubSub from "@vandeurenglenn/little-pubsub";
3
- import PeerDiscovery from "./discovery/peer-discovery.js";
4
- import DHT, { DHTProvider, DHTProviderDistanceResult } from "./dht/dht.js";
5
- import { BufferToUint8Array, protoFor, target } from "./utils/utils.js";
6
- import MessageHandler from "./handlers/message.js";
7
- import dataHandler from "./handlers/data.js";
8
- import { dhtError, nothingFoundError } from "./errors/errors.js";
9
- import LeofcoinStorageClass from "@leofcoin/storage";
10
- import { utils as codecUtils } from "@leofcoin/codecs";
11
- import Identity from "./identity.js";
12
- import swarm, { PeerId } from "@netpeer/p2pt-swarm";
13
- import P2PTPeer from "@netpeer/p2pt-swarm/peer";
14
-
15
- globalThis.LeofcoinStorage = LeofcoinStorageClass;
16
-
17
- globalThis.leofcoin = globalThis.leofcoin || {};
18
- globalThis.pubsub = globalThis.pubsub || new PubSub();
19
- globalThis.globalSub = globalThis.globalSub || new PubSub();
1
+ import '@vandeurenglenn/debug'
2
+ import PubSub from '@vandeurenglenn/little-pubsub'
3
+ import PeerDiscovery from './discovery/peer-discovery.js'
4
+ import DHT, { DHTProvider, DHTProviderDistanceResult } from './dht/dht.js'
5
+ import { BufferToUint8Array, protoFor, target } from './utils/utils.js'
6
+ import MessageHandler from './handlers/message.js'
7
+ import dataHandler from './handlers/data.js'
8
+ import { dhtError, nothingFoundError } from './errors/errors.js'
9
+ import { Storage as LeofcoinStorageClass } from '@leofcoin/storage'
10
+ import { utils as codecUtils } from '@leofcoin/codecs'
11
+ import Identity from './identity.js'
12
+ import swarm, { PeerId } from '@netpeer/p2pt-swarm'
13
+ import P2PTPeer from '@netpeer/p2pt-swarm/peer'
14
+
15
+ globalThis.LeofcoinStorage = LeofcoinStorageClass
16
+
17
+ globalThis.leofcoin = globalThis.leofcoin || {}
18
+ globalThis.pubsub = globalThis.pubsub || new PubSub()
19
+ globalThis.globalSub = globalThis.globalSub || new PubSub()
20
20
 
21
21
  declare global {
22
- var LeofcoinStorage: typeof LeofcoinStorageClass;
23
- var peernet: Peernet;
24
- var pubsub: PubSub;
25
- var globalSub: PubSub;
26
- var blockStore: LeofcoinStorageClass;
27
- var transactionStore: LeofcoinStorageClass;
28
- var messageStore: LeofcoinStorageClass;
29
- var dataStore: LeofcoinStorageClass;
30
- var walletStore: LeofcoinStorageClass;
31
- var chainStore: LeofcoinStorageClass;
22
+ var LeofcoinStorage: typeof LeofcoinStorageClass
23
+ var peernet: Peernet
24
+ var pubsub: PubSub
25
+ var globalSub: PubSub
26
+ var blockStore: LeofcoinStorageClass
27
+ var transactionStore: LeofcoinStorageClass
28
+ var messageStore: LeofcoinStorageClass
29
+ var dataStore: LeofcoinStorageClass
30
+ var walletStore: LeofcoinStorageClass
31
+ var chainStore: LeofcoinStorageClass
32
32
  }
33
33
 
34
34
  /**
@@ -37,34 +37,34 @@ declare global {
37
37
  * const peernet = new Peernet();
38
38
  */
39
39
  export default class Peernet {
40
- storePrefix: string;
41
- root: string;
42
- identity: Identity;
43
- stores: string[] = [];
44
- peerId: string;
40
+ storePrefix: string
41
+ root: string
42
+ identity: Identity
43
+ stores: string[] = []
44
+ peerId: string
45
45
  /**
46
46
  * @type {Object}
47
47
  * @property {Object} peer Instance of Peer
48
48
  */
49
- dht: DHT = new DHT();
49
+ dht: DHT = new DHT()
50
50
  /** @leofcoin/peernet-swarm/client */
51
- client: swarm;
52
- network: string;
53
- stars: string[];
54
- networkVersion: string;
51
+ client: swarm
52
+ network: string
53
+ stars: string[]
54
+ networkVersion: string
55
55
  bw: {
56
- up: number;
57
- down: number;
58
- };
59
- hasDaemon: boolean = false;
60
- autoStart: boolean = true;
61
- #starting: boolean = false;
62
- #started: boolean = false;
63
- #connections: { [index: PeerId]: P2PTPeer } = {};
64
- requestProtos = {};
65
- _messageHandler: MessageHandler;
66
- _peerHandler: PeerDiscovery;
67
- protos: {};
56
+ up: number
57
+ down: number
58
+ }
59
+ hasDaemon: boolean = false
60
+ autoStart: boolean = true
61
+ #starting: boolean = false
62
+ #started: boolean = false
63
+ #connections: { [index: PeerId]: P2PTPeer } = {}
64
+ requestProtos = {}
65
+ _messageHandler: MessageHandler
66
+ _peerHandler: PeerDiscovery
67
+ protos: {}
68
68
 
69
69
  /**
70
70
  * @access public
@@ -83,99 +83,77 @@ export default class Peernet {
83
83
  /**
84
84
  * @property {String} network - current network
85
85
  */
86
- this.network = options.network || "leofcoin";
87
- this.autoStart = options.autoStart === undefined ? true : options.autoStart;
88
- this.stars = options.stars;
89
- const parts = this.network.split(":");
90
- this.networkVersion =
91
- options.networkVersion || parts.length > 1 ? parts[1] : "mainnet";
92
-
93
- if (!options.storePrefix) options.storePrefix = "lfc";
94
- if (!options.port) options.port = 2000;
86
+ this.network = options.network || 'leofcoin'
87
+ this.autoStart = options.autoStart === undefined ? true : options.autoStart
88
+ this.stars = options.stars
89
+ const parts = this.network.split(':')
90
+ this.networkVersion = options.networkVersion || parts.length > 1 ? parts[1] : 'mainnet'
91
+
92
+ if (!options.storePrefix) options.storePrefix = 'lfc'
93
+ if (!options.port) options.port = 2000
95
94
  if (!options.root) {
96
- parts[1]
97
- ? (options.root = `.${parts[0]}/${parts[1]}`)
98
- : (options.root = `.${this.network}`);
95
+ parts[1] ? (options.root = `.${parts[0]}/${parts[1]}`) : (options.root = `.${this.network}`)
99
96
  }
100
97
 
101
- globalThis.peernet = this;
98
+ globalThis.peernet = this
102
99
  this.bw = {
103
100
  up: 0,
104
- down: 0,
105
- };
101
+ down: 0
102
+ }
106
103
  // @ts-ignore
107
- return this._init(options, password);
104
+ return this._init(options, password)
108
105
  }
109
106
 
110
107
  get id() {
111
- return this.identity.id;
108
+ return this.identity.id
112
109
  }
113
110
 
114
111
  get selectedAccount(): string {
115
- return this.identity.selectedAccount;
112
+ return this.identity.selectedAccount
116
113
  }
117
114
 
118
- get accounts(): Promise<
119
- [[name: string, externalAddress: string, internalAddress: string]]
120
- > {
121
- return this.identity.accounts;
115
+ get accounts(): Promise<[[name: string, externalAddress: string, internalAddress: string]]> {
116
+ return this.identity.accounts
122
117
  }
123
118
 
124
119
  get defaultStores() {
125
- return [
126
- "account",
127
- "wallet",
128
- "block",
129
- "transaction",
130
- "chain",
131
- "data",
132
- "message",
133
- ];
120
+ return ['account', 'wallet', 'block', 'transaction', 'chain', 'data', 'message']
134
121
  }
135
122
 
136
123
  selectAccount(account: string) {
137
- return this.identity.selectAccount(account);
124
+ return this.identity.selectAccount(account)
138
125
  }
139
126
 
140
127
  addProto(name, proto) {
141
- if (!globalThis.peernet.protos[name])
142
- globalThis.peernet.protos[name] = proto;
128
+ if (!globalThis.peernet.protos[name]) globalThis.peernet.protos[name] = proto
143
129
  }
144
130
 
145
131
  addCodec(codec) {
146
- return codecUtils.addCodec(codec);
132
+ return codecUtils.addCodec(codec)
147
133
  }
148
134
 
149
135
  async addStore(name, prefix, root, isPrivate = true) {
150
- if (
151
- name === "block" ||
152
- name === "transaction" ||
153
- name === "chain" ||
154
- name === "data" ||
155
- name === "message"
156
- )
157
- isPrivate = false;
136
+ if (name === 'block' || name === 'transaction' || name === 'chain' || name === 'data' || name === 'message')
137
+ isPrivate = false
158
138
 
159
- let Storage;
139
+ let Storage
160
140
 
161
- this.hasDaemon
162
- ? (Storage = LeofcoinStorageClient)
163
- : (Storage = LeofcoinStorage);
141
+ this.hasDaemon ? (Storage = LeofcoinStorageClient) : (Storage = LeofcoinStorage)
164
142
 
165
143
  if (!globalThis[`${name}Store`]) {
166
- globalThis[`${name}Store`] = new Storage(name, root);
167
- await globalThis[`${name}Store`].init();
144
+ globalThis[`${name}Store`] = new Storage(name, root)
145
+ await globalThis[`${name}Store`].init()
168
146
  }
169
147
 
170
- globalThis[`${name}Store`].private = isPrivate;
171
- if (!isPrivate) this.stores.push(name);
148
+ globalThis[`${name}Store`].private = isPrivate
149
+ if (!isPrivate) this.stores.push(name)
172
150
  }
173
151
 
174
152
  /**
175
153
  * @see MessageHandler
176
154
  */
177
155
  prepareMessage(data) {
178
- return this._messageHandler.prepareMessage(data);
156
+ return this._messageHandler.prepareMessage(data)
179
157
  }
180
158
 
181
159
  /**
@@ -184,22 +162,22 @@ export default class Peernet {
184
162
  * @return {Array} peerId
185
163
  */
186
164
  get peers() {
187
- return Object.entries(this.#connections);
165
+ return Object.entries(this.#connections)
188
166
  }
189
167
 
190
168
  get connections() {
191
- return Object.values(this.#connections);
169
+ return Object.values(this.#connections)
192
170
  }
193
171
 
194
172
  get peerEntries() {
195
- return Object.values(this.#connections);
173
+ return Object.values(this.#connections)
196
174
  }
197
175
 
198
176
  /**
199
177
  * @return {String} id - peerId
200
178
  */
201
179
  getConnection(id) {
202
- return this.connections[id];
180
+ return this.connections[id]
203
181
  }
204
182
 
205
183
  /**
@@ -210,12 +188,9 @@ export default class Peernet {
210
188
  *
211
189
  * @return {Promise} instance of Peernet
212
190
  */
213
- async _init(
214
- options: { storePrefix?: string; root?: string },
215
- password: string
216
- ): Promise<Peernet> {
217
- this.storePrefix = options.storePrefix;
218
- this.root = options.root;
191
+ async _init(options: { storePrefix?: string; root?: string }, password: string): Promise<Peernet> {
192
+ this.storePrefix = options.storePrefix
193
+ this.root = options.root
219
194
 
220
195
  const {
221
196
  RequestMessage,
@@ -229,9 +204,9 @@ export default class Peernet {
229
204
  DataMessageResponse,
230
205
  PsMessage,
231
206
  ChatMessage,
232
- PeernetFile,
207
+ PeernetFile
233
208
  // FolderMessageResponse
234
- } = await import(/* webpackChunkName: "messages" */ "./messages.js");
209
+ } = await import(/* webpackChunkName: "messages" */ './messages.js')
235
210
 
236
211
  /**
237
212
  * proto Object containing protos
@@ -244,180 +219,164 @@ export default class Peernet {
244
219
  */
245
220
 
246
221
  globalThis.peernet.protos = {
247
- "peernet-request": RequestMessage,
248
- "peernet-response": ResponseMessage,
249
- "peernet-peer": PeerMessage,
250
- "peernet-peer-response": PeerMessageResponse,
251
- "peernet-message": PeernetMessage,
252
- "peernet-dht": DHTMessage,
253
- "peernet-dht-response": DHTMessageResponse,
254
- "peernet-data": DataMessage,
255
- "peernet-data-response": DataMessageResponse,
256
- "peernet-ps": PsMessage,
257
- "chat-message": ChatMessage,
258
- "peernet-file": PeernetFile,
259
- };
260
-
261
- this._messageHandler = new MessageHandler(this.network);
262
-
263
- const { daemon, environment } = await target();
264
- this.hasDaemon = daemon;
222
+ 'peernet-request': RequestMessage,
223
+ 'peernet-response': ResponseMessage,
224
+ 'peernet-peer': PeerMessage,
225
+ 'peernet-peer-response': PeerMessageResponse,
226
+ 'peernet-message': PeernetMessage,
227
+ 'peernet-dht': DHTMessage,
228
+ 'peernet-dht-response': DHTMessageResponse,
229
+ 'peernet-data': DataMessage,
230
+ 'peernet-data-response': DataMessageResponse,
231
+ 'peernet-ps': PsMessage,
232
+ 'chat-message': ChatMessage,
233
+ 'peernet-file': PeernetFile
234
+ }
235
+
236
+ this._messageHandler = new MessageHandler(this.network)
237
+
238
+ const { daemon, environment } = await target()
239
+ this.hasDaemon = daemon
265
240
 
266
241
  for (const store of this.defaultStores) {
267
- await this.addStore(store, options.storePrefix, options.root);
242
+ await this.addStore(store, options.storePrefix, options.root)
268
243
  }
269
244
 
270
- this.identity = new Identity(this.network);
271
- await this.identity.load(password);
245
+ this.identity = new Identity(this.network)
246
+ await this.identity.load(password)
272
247
 
273
- this._peerHandler = new PeerDiscovery(this.id);
274
- this.peerId = this.id;
248
+ this._peerHandler = new PeerDiscovery(this.id)
249
+ this.peerId = this.id
275
250
 
276
- this.addRequestHandler("handshake", () => {
277
- return new peernet.protos["peernet-response"]({
278
- response: { peerId: this.id },
279
- });
280
- });
251
+ this.addRequestHandler('handshake', () => {
252
+ return new peernet.protos['peernet-response']({
253
+ response: { peerId: this.id }
254
+ })
255
+ })
281
256
 
282
- pubsub.subscribe("peer:discovered", async (peer) => {
257
+ pubsub.subscribe('peer:discovered', async (peer) => {
283
258
  // console.log(peer);
284
259
 
285
- if (this.requestProtos["version"]) {
286
- let data = await new globalThis.peernet.protos["peernet-request"]({
287
- request: "version",
288
- });
289
- let node = await globalThis.peernet.prepareMessage(data);
290
- let response = await peer.request(node.encoded);
291
- response = await new globalThis.peernet.protos["peernet-response"](
292
- new Uint8Array(Object.values(response))
293
- );
294
- peer.version = response.decoded.response.version;
260
+ if (this.requestProtos['version']) {
261
+ let data = await new globalThis.peernet.protos['peernet-request']({
262
+ request: 'version'
263
+ })
264
+ let node = await globalThis.peernet.prepareMessage(data)
265
+ let response = await peer.request(node.encoded)
266
+ response = await new globalThis.peernet.protos['peernet-response'](new Uint8Array(Object.values(response)))
267
+ peer.version = response.decoded.response.version
295
268
  }
296
269
 
297
- let data = await new globalThis.peernet.protos["peernet-request"]({
298
- request: "handshake",
299
- });
300
- let node = await globalThis.peernet.prepareMessage(data);
301
- let response = await peer.request(node.encoded);
270
+ let data = await new globalThis.peernet.protos['peernet-request']({
271
+ request: 'handshake'
272
+ })
273
+ let node = await globalThis.peernet.prepareMessage(data)
274
+ let response = await peer.request(node.encoded)
302
275
 
303
- response = await new globalThis.peernet.protos["peernet-response"](
304
- new Uint8Array(Object.values(response))
305
- );
276
+ response = await new globalThis.peernet.protos['peernet-response'](new Uint8Array(Object.values(response)))
306
277
  // todo: response.decoded should be the response and not response.peerId
307
278
 
308
- this.#connections[response.decoded.response.peerId] = peer;
309
- pubsub.publish("peer:connected", peer);
279
+ this.#connections[response.decoded.response.peerId] = peer
280
+ pubsub.publish('peer:connected', peer)
310
281
  // todo: cleanup discovered
311
- });
282
+ })
312
283
 
313
- pubsub.subscribe("peer:left", this.#peerLeft.bind(this));
284
+ pubsub.subscribe('peer:left', this.#peerLeft.bind(this))
314
285
 
315
286
  /**
316
287
  * converts data -> message -> proto
317
288
  * @see DataHandler
318
289
  */
319
- pubsub.subscribe("peer:data", dataHandler);
290
+ pubsub.subscribe('peer:data', dataHandler)
320
291
 
321
292
  if (globalThis.navigator) {
322
- globalThis.addEventListener("beforeunload", async () =>
323
- this.client.destroy()
324
- );
293
+ globalThis.addEventListener('beforeunload', async () => this.client.destroy())
325
294
  } else {
326
- process.on("SIGTERM", async () => {
327
- process.stdin.resume();
295
+ process.on('SIGTERM', async () => {
296
+ process.stdin.resume()
328
297
  try {
329
- await this.client.destroy();
298
+ await this.client.destroy()
330
299
  } catch (error) {
331
300
  // @ts-ignore
332
- await this.client.close();
301
+ await this.client.close()
333
302
  }
334
- process.exit();
335
- });
303
+ process.exit()
304
+ })
336
305
  }
337
- if (this.autoStart) await this.start();
338
- return this;
306
+ if (this.autoStart) await this.start()
307
+ return this
339
308
  }
340
309
 
341
310
  async start() {
342
- if (this.#starting || this.#started) return;
311
+ if (this.#starting || this.#started) return
343
312
 
344
- this.#starting = true;
345
- const importee = await import("@netpeer/p2pt-swarm");
313
+ this.#starting = true
314
+ const importee = await import('@netpeer/p2pt-swarm')
346
315
  /**
347
316
  * @access public
348
317
  * @type {PeernetClient}
349
318
  */
350
- this.client = new importee.default(
351
- this.id,
352
- this.networkVersion,
353
- this.stars
354
- );
355
- this.#started = true;
356
- this.#starting = false;
319
+ this.client = new importee.default(this.id, this.networkVersion, this.stars)
320
+ this.#started = true
321
+ this.#starting = false
357
322
  }
358
323
 
359
324
  #peerLeft(peer: P2PTPeer) {
360
325
  for (const [id, _peer] of Object.entries(this.#connections)) {
361
- if (
362
- _peer.id === peer.id &&
363
- this.#connections[id] &&
364
- !this.#connections[id].connected
365
- ) {
366
- delete this.#connections[id];
367
- this.removePeer(_peer);
326
+ if (_peer.id === peer.id && this.#connections[id] && !this.#connections[id].connected) {
327
+ delete this.#connections[id]
328
+ this.removePeer(_peer)
368
329
  }
369
330
  }
370
331
  }
371
332
 
372
333
  addRequestHandler(name, method) {
373
- this.requestProtos[name] = method;
334
+ this.requestProtos[name] = method
374
335
  }
375
336
 
376
337
  async sendMessage(peer, id, data) {
377
338
  if (peer.connected) {
378
- await peer.send(data, id);
379
- this.bw.up += data.length;
380
- } else this.removePeer(peer);
339
+ await peer.send(data, id)
340
+ this.bw.up += data.length
341
+ } else this.removePeer(peer)
381
342
  }
382
343
 
383
344
  async handleDHT(peer, id, proto) {
384
- let { hash, store } = proto.decoded;
385
- let has;
345
+ let { hash, store } = proto.decoded
346
+ let has
386
347
 
387
348
  if (store) {
388
- store = globalThis[`${store}Store`];
389
- has = store.private ? false : await store.has(hash);
349
+ store = globalThis[`${store}Store`]
350
+ has = store.private ? false : await store.has(hash)
390
351
  } else {
391
- has = await this.has(hash);
352
+ has = await this.has(hash)
392
353
  }
393
354
 
394
- const data = await new globalThis.peernet.protos["peernet-dht-response"]({
355
+ const data = await new globalThis.peernet.protos['peernet-dht-response']({
395
356
  hash,
396
- has,
397
- });
398
- const node = await this.prepareMessage(data);
357
+ has
358
+ })
359
+ const node = await this.prepareMessage(data)
399
360
 
400
- this.sendMessage(peer, id, node.encoded);
361
+ this.sendMessage(peer, id, node.encoded)
401
362
  }
402
363
 
403
364
  async handleData(peer, id, proto) {
404
- let { hash, store } = proto.decoded;
405
- let data;
406
- store =
407
- globalThis[`${store}Store`] ||
408
- (await this.whichStore([...this.stores], hash));
365
+ let { hash, store } = proto.decoded
366
+ let data
367
+ store = globalThis[`${store}Store`] || (await this.whichStore([...this.stores], hash))
409
368
 
410
369
  if (store && !store.private) {
411
- data = await store.get(hash);
370
+ data = await store.get(hash)
412
371
 
413
372
  if (data) {
414
- data = await new globalThis.peernet.protos["peernet-data-response"]({
373
+ data = await new globalThis.peernet.protos['peernet-data-response']({
415
374
  hash,
416
- data,
417
- });
375
+ data
376
+ })
418
377
 
419
- const node = await this.prepareMessage(data);
420
- this.sendMessage(peer, id, node.encoded);
378
+ const node = await this.prepareMessage(data)
379
+ this.sendMessage(peer, id, node.encoded)
421
380
  }
422
381
  } else {
423
382
  // ban (trying to access private st)
@@ -425,11 +384,11 @@ export default class Peernet {
425
384
  }
426
385
 
427
386
  async handleRequest(peer, id, proto) {
428
- const method = this.requestProtos[proto.decoded.request];
387
+ const method = this.requestProtos[proto.decoded.request]
429
388
  if (method) {
430
- const data = await method(proto.decoded.requested);
431
- const node = await this.prepareMessage(data);
432
- this.sendMessage(peer, id, node.encoded);
389
+ const data = await method(proto.decoded.requested)
390
+ const node = await this.prepareMessage(data)
391
+ this.sendMessage(peer, id, node.encoded)
433
392
  }
434
393
  }
435
394
 
@@ -440,28 +399,25 @@ export default class Peernet {
440
399
  * @param {PeernetPeer} peer - peernet peer
441
400
  */
442
401
  async _protoHandler(message, peer, from) {
443
- const { id, proto } = message;
402
+ const { id, proto } = message
444
403
 
445
- this.bw.down += proto.encoded.length;
404
+ this.bw.down += proto.encoded.length
446
405
  switch (proto.name) {
447
- case "peernet-dht": {
448
- this.handleDHT(peer, id, proto);
449
- break;
406
+ case 'peernet-dht': {
407
+ this.handleDHT(peer, id, proto)
408
+ break
450
409
  }
451
- case "peernet-data": {
452
- this.handleData(peer, id, proto);
453
- break;
410
+ case 'peernet-data': {
411
+ this.handleData(peer, id, proto)
412
+ break
454
413
  }
455
- case "peernet-request": {
456
- this.handleRequest(peer, id, proto);
457
- break;
414
+ case 'peernet-request': {
415
+ this.handleRequest(peer, id, proto)
416
+ break
458
417
  }
459
418
 
460
- case "peernet-ps": {
461
- globalSub.publish(
462
- new TextDecoder().decode(proto.decoded.topic),
463
- proto.decoded.data
464
- );
419
+ case 'peernet-ps': {
420
+ globalSub.publish(new TextDecoder().decode(proto.decoded.topic), proto.decoded.data)
465
421
  }
466
422
  }
467
423
  }
@@ -472,29 +428,29 @@ export default class Peernet {
472
428
  * @param {String} hash
473
429
  */
474
430
  async walk(hash) {
475
- if (!hash) throw new Error("hash expected, received undefined");
476
- const data = await new globalThis.peernet.protos["peernet-dht"]({ hash });
431
+ if (!hash) throw new Error('hash expected, received undefined')
432
+ const data = await new globalThis.peernet.protos['peernet-dht']({ hash })
477
433
  const walk = async (peer, peerId) => {
478
- const node = await this.prepareMessage(data);
479
- let result = await peer.request(node.encoded);
480
- result = new Uint8Array(Object.values(result));
481
- const proto = await protoFor(result);
482
- if (proto.name !== "peernet-dht-response") throw dhtError(proto.name);
434
+ const node = await this.prepareMessage(data)
435
+ let result = await peer.request(node.encoded)
436
+ result = new Uint8Array(Object.values(result))
437
+ const proto = await protoFor(result)
438
+ if (proto.name !== 'peernet-dht-response') throw dhtError(proto.name)
483
439
 
484
440
  const peerInfo = {
485
441
  ...peer.connectionStats,
486
- id: peerId,
487
- };
442
+ id: peerId
443
+ }
488
444
 
489
- if (proto.decoded.has) this.dht.addProvider(peerInfo, proto.decoded.hash);
490
- };
491
- let walks = [];
445
+ if (proto.decoded.has) this.dht.addProvider(peerInfo, proto.decoded.hash)
446
+ }
447
+ let walks = []
492
448
  for (const [peerId, peer] of Object.entries(this.#connections)) {
493
449
  if (peerId !== this.id) {
494
- walks.push(walk(peer, peerId));
450
+ walks.push(walk(peer, peerId))
495
451
  }
496
452
  }
497
- return Promise.all(walks);
453
+ return Promise.all(walks)
498
454
  }
499
455
 
500
456
  /**
@@ -503,97 +459,92 @@ export default class Peernet {
503
459
  * @param {String} hash
504
460
  */
505
461
  async providersFor(hash: string, store?: undefined) {
506
- let providers = this.dht.providersFor(hash);
462
+ let providers = this.dht.providersFor(hash)
507
463
  // walk the network to find a provider
508
- let tries = 0;
509
- while (
510
- (!providers && tries < 3) ||
511
- (Object.keys(providers).length === 0 && tries < 3)
512
- ) {
513
- tries += 1;
514
- await this.walk(hash);
515
- providers = this.dht.providersFor(hash);
464
+ let tries = 0
465
+ while ((!providers && tries < 3) || (Object.keys(providers).length === 0 && tries < 3)) {
466
+ tries += 1
467
+ await this.walk(hash)
468
+ providers = this.dht.providersFor(hash)
516
469
  }
517
470
  // undefined if no providers given
518
- return providers;
471
+ return providers
519
472
  }
520
473
 
521
474
  get block() {
522
475
  return {
523
476
  get: async (hash: string) => {
524
- const data = await blockStore.has(hash);
525
- if (data) return blockStore.get(hash);
526
- return this.requestData(hash, "block");
477
+ const data = await blockStore.has(hash)
478
+ if (data) return blockStore.get(hash)
479
+ return this.requestData(hash, 'block')
527
480
  },
528
481
  put: async (hash: string, data: Uint8Array) => {
529
- if (await blockStore.has(hash)) return;
530
- return await blockStore.put(hash, data);
482
+ if (await blockStore.has(hash)) return
483
+ return await blockStore.put(hash, data)
531
484
  },
532
- has: async (hash: string) => await blockStore.has(hash),
533
- };
485
+ has: async (hash: string) => await blockStore.has(hash)
486
+ }
534
487
  }
535
488
 
536
489
  get transaction() {
537
490
  return {
538
491
  get: async (hash: string) => {
539
- const data = await transactionStore.has(hash);
540
- if (data) return await transactionStore.get(hash);
541
- return this.requestData(hash, "transaction");
492
+ const data = await transactionStore.has(hash)
493
+ if (data) return await transactionStore.get(hash)
494
+ return this.requestData(hash, 'transaction')
542
495
  },
543
496
  put: async (hash: string, data: Uint8Array) => {
544
- if (await transactionStore.has(hash)) return;
545
- return await transactionStore.put(hash, data);
497
+ if (await transactionStore.has(hash)) return
498
+ return await transactionStore.put(hash, data)
546
499
  },
547
- has: async (hash: string) => await transactionStore.has(hash),
548
- };
500
+ has: async (hash: string) => await transactionStore.has(hash)
501
+ }
549
502
  }
550
503
 
551
504
  async requestData(hash, store) {
552
- const providers = await this.providersFor(hash);
553
- if (!providers || (providers && Object.keys(providers).length === 0))
554
- throw nothingFoundError(hash);
555
- debug(`found ${Object.keys(providers).length} provider(s) for ${hash}`);
505
+ const providers = await this.providersFor(hash)
506
+ if (!providers || (providers && Object.keys(providers).length === 0)) throw nothingFoundError(hash)
507
+ debug(`found ${Object.keys(providers).length} provider(s) for ${hash}`)
556
508
  // get closest peer on earth
557
- const closestPeer: DHTProvider = Object.values(providers)[0];
509
+ const closestPeer: DHTProvider = Object.values(providers)[0]
558
510
 
559
511
  // get peer instance by id
560
- if (!closestPeer || !closestPeer.id)
561
- return this.requestData(hash, store?.name || store);
512
+ if (!closestPeer || !closestPeer.id) return this.requestData(hash, store?.name || store)
562
513
 
563
- const id = closestPeer.id;
564
- const peer = this.#connections[id];
514
+ const id = closestPeer.id
515
+ const peer = this.#connections[id]
565
516
 
566
517
  if (peer?.connected) {
567
- let data = await new globalThis.peernet.protos["peernet-data"]({
518
+ let data = await new globalThis.peernet.protos['peernet-data']({
568
519
  hash,
569
- store: store?.name || store,
570
- });
520
+ store: store?.name || store
521
+ })
571
522
 
572
- const node = await this.prepareMessage(data);
523
+ const node = await this.prepareMessage(data)
573
524
 
574
- if (peer) data = await peer.request(node.encoded);
525
+ if (peer) data = await peer.request(node.encoded)
575
526
  else {
576
527
  // fallback and try every provider found
577
- const promises = [];
578
- const providers = await this.providersFor(hash, store);
528
+ const promises = []
529
+ const providers = await this.providersFor(hash, store)
579
530
  for (const provider of Object.values(providers)) {
580
- const peer = this.#connections[provider.id];
531
+ const peer = this.#connections[provider.id]
581
532
 
582
- if (peer) promises.push(peer.request(node.encoded));
533
+ if (peer) promises.push(peer.request(node.encoded))
583
534
  }
584
- data = await Promise.race(promises);
535
+ data = await Promise.race(promises)
585
536
  }
586
- if (data) data = new Uint8Array(Object.values(data));
537
+ if (data) data = new Uint8Array(Object.values(data))
587
538
 
588
- const proto = await protoFor(data);
539
+ const proto = await protoFor(data)
589
540
  // TODO: store data automaticly or not
590
- return BufferToUint8Array(proto.decoded.data);
541
+ return BufferToUint8Array(proto.decoded.data)
591
542
 
592
543
  // this.put(hash, proto.decoded.data)
593
544
  } else {
594
- this.dht.removeProvider(id, hash);
545
+ this.dht.removeProvider(id, hash)
595
546
  }
596
- return;
547
+ return
597
548
  }
598
549
 
599
550
  get message() {
@@ -604,10 +555,10 @@ export default class Peernet {
604
555
  * @param {String} hash
605
556
  */
606
557
  get: async (hash) => {
607
- debug(`get message ${hash}`);
608
- const message = await messageStore.has(hash);
609
- if (message) return await messageStore.get(hash);
610
- return this.requestData(hash, "message");
558
+ debug(`get message ${hash}`)
559
+ const message = await messageStore.has(hash)
560
+ if (message) return await messageStore.get(hash)
561
+ return this.requestData(hash, 'message')
611
562
  },
612
563
  /**
613
564
  * put message content
@@ -620,8 +571,8 @@ export default class Peernet {
620
571
  * @param {String} hash
621
572
  * @return {Boolean}
622
573
  */
623
- has: async (hash) => await messageStore.has(hash),
624
- };
574
+ has: async (hash) => await messageStore.has(hash)
575
+ }
625
576
  }
626
577
 
627
578
  get data() {
@@ -632,10 +583,10 @@ export default class Peernet {
632
583
  * @param {String} hash
633
584
  */
634
585
  get: async (hash) => {
635
- debug(`get data ${hash}`);
636
- const data = await dataStore.has(hash);
637
- if (data) return await dataStore.get(hash);
638
- return this.requestData(hash, "data");
586
+ debug(`get data ${hash}`)
587
+ const data = await dataStore.has(hash)
588
+ if (data) return await dataStore.get(hash)
589
+ return this.requestData(hash, 'data')
639
590
  },
640
591
  /**
641
592
  * put data content
@@ -648,8 +599,8 @@ export default class Peernet {
648
599
  * @param {String} hash
649
600
  * @return {Boolean}
650
601
  */
651
- has: async (hash) => await dataStore.has(hash),
652
- };
602
+ has: async (hash) => await dataStore.has(hash)
603
+ }
653
604
  }
654
605
 
655
606
  get folder() {
@@ -660,10 +611,10 @@ export default class Peernet {
660
611
  * @param {String} hash
661
612
  */
662
613
  get: async (hash) => {
663
- debug(`get data ${hash}`);
664
- const data = await dataStore.has(hash);
665
- if (data) return await dataStore.get(hash);
666
- return this.requestData(hash, "data");
614
+ debug(`get data ${hash}`)
615
+ const data = await dataStore.has(hash)
616
+ if (data) return await dataStore.get(hash)
617
+ return this.requestData(hash, 'data')
667
618
  },
668
619
  /**
669
620
  * put data content
@@ -676,61 +627,54 @@ export default class Peernet {
676
627
  * @param {String} hash
677
628
  * @return {Boolean}
678
629
  */
679
- has: async (hash) => await dataStore.has(hash),
680
- };
630
+ has: async (hash) => await dataStore.has(hash)
631
+ }
681
632
  }
682
633
 
683
634
  async addFolder(files) {
684
- const links = [];
635
+ const links = []
685
636
  for (const file of files) {
686
- const fileNode = await new globalThis.peernet.protos["peernet-file"](
687
- file
688
- );
689
- const hash = await fileNode.hash;
690
- await dataStore.put(hash, fileNode.encoded);
691
- links.push({ hash, path: file.path });
637
+ const fileNode = await new globalThis.peernet.protos['peernet-file'](file)
638
+ const hash = await fileNode.hash
639
+ await dataStore.put(hash, fileNode.encoded)
640
+ links.push({ hash, path: file.path })
692
641
  }
693
- const node = await new globalThis.peernet.protos["peernet-file"]({
694
- path: "/",
695
- links,
696
- });
697
- const hash = await node.hash;
698
- await dataStore.put(hash, node.encoded);
642
+ const node = await new globalThis.peernet.protos['peernet-file']({
643
+ path: '/',
644
+ links
645
+ })
646
+ const hash = await node.hash
647
+ await dataStore.put(hash, node.encoded)
699
648
 
700
- return hash;
649
+ return hash
701
650
  }
702
651
 
703
652
  async ls(hash, options) {
704
- let data;
705
- const has = await dataStore.has(hash);
706
- data = has
707
- ? await dataStore.get(hash)
708
- : await this.requestData(hash, "data");
709
-
710
- const node = await new peernet.protos["peernet-file"](data);
711
- await node.decode();
712
- console.log(data);
713
- const paths = [];
714
- if (node.decoded?.links.length === 0) throw new Error(`${hash} is a file`);
653
+ let data
654
+ const has = await dataStore.has(hash)
655
+ data = has ? await dataStore.get(hash) : await this.requestData(hash, 'data')
656
+
657
+ const node = await new peernet.protos['peernet-file'](data)
658
+ await node.decode()
659
+ console.log(data)
660
+ const paths = []
661
+ if (node.decoded?.links.length === 0) throw new Error(`${hash} is a file`)
715
662
  for (const { path, hash } of node.decoded.links) {
716
- paths.push({ path, hash });
663
+ paths.push({ path, hash })
717
664
  }
718
- if (options?.pin) await dataStore.put(hash, node.encoded);
719
- return paths;
665
+ if (options?.pin) await dataStore.put(hash, node.encoded)
666
+ return paths
720
667
  }
721
668
 
722
669
  async cat(hash, options) {
723
- let data;
724
- const has = await dataStore.has(hash);
725
- data = has
726
- ? await dataStore.get(hash)
727
- : await this.requestData(hash, "data");
728
- const node = await new peernet.protos["peernet-file"](data);
670
+ let data
671
+ const has = await dataStore.has(hash)
672
+ data = has ? await dataStore.get(hash) : await this.requestData(hash, 'data')
673
+ const node = await new peernet.protos['peernet-file'](data)
729
674
 
730
- if (node.decoded?.links.length > 0)
731
- throw new Error(`${hash} is a directory`);
732
- if (options?.pin) await dataStore.put(hash, node.encoded);
733
- return node.decoded.content;
675
+ if (node.decoded?.links.length > 0) throw new Error(`${hash} is a directory`)
676
+ if (options?.pin) await dataStore.put(hash, node.encoded)
677
+ return node.decoded.content
734
678
  }
735
679
 
736
680
  /**
@@ -739,14 +683,14 @@ export default class Peernet {
739
683
  * @param {string} hash
740
684
  */
741
685
  async whichStore(stores, hash) {
742
- let store = stores.pop();
743
- const name = store;
744
- store = globalThis[`${store}Store`];
686
+ let store = stores.pop()
687
+ const name = store
688
+ store = globalThis[`${store}Store`]
745
689
  if (store) {
746
- const has = await store.has(hash);
747
- if (has) return store;
748
- if (stores.length > 0) return this.whichStore(stores, hash);
749
- } else return;
690
+ const has = await store.has(hash)
691
+ if (has) return store
692
+ if (stores.length > 0) return this.whichStore(stores, hash)
693
+ } else return
750
694
  }
751
695
 
752
696
  /**
@@ -756,14 +700,14 @@ export default class Peernet {
756
700
  * @param {String} store - storeName to access
757
701
  */
758
702
  async get(hash, store) {
759
- debug(`get ${hash}`);
760
- let data;
761
- if (store) store = globalThis[`${store}Store`];
762
- if (!store) store = await this.whichStore([...this.stores], hash);
763
- if (store && (await store.has(hash))) data = await store.get(hash);
764
- if (data) return data;
703
+ debug(`get ${hash}`)
704
+ let data
705
+ if (store) store = globalThis[`${store}Store`]
706
+ if (!store) store = await this.whichStore([...this.stores], hash)
707
+ if (store && (await store.has(hash))) data = await store.get(hash)
708
+ if (data) return data
765
709
 
766
- return this.requestData(hash, store?.name || store);
710
+ return this.requestData(hash, store?.name || store)
767
711
  }
768
712
 
769
713
  /**
@@ -773,13 +717,9 @@ export default class Peernet {
773
717
  * @param {Buffer} data
774
718
  * @param {String} storeName - storeName to access
775
719
  */
776
- async put(
777
- hash: string,
778
- data: Uint8Array,
779
- storeName: string | LeofcoinStorageClass = "data"
780
- ) {
781
- const store: LeofcoinStorageClass = globalThis[`${storeName}Store`];
782
- return store.put(hash, data);
720
+ async put(hash: string, data: Uint8Array, storeName: string | LeofcoinStorageClass = 'data') {
721
+ const store: LeofcoinStorageClass = globalThis[`${storeName}Store`]
722
+ return store.put(hash, data)
783
723
  }
784
724
 
785
725
  /**
@@ -787,11 +727,11 @@ export default class Peernet {
787
727
  * @return {Boolean}
788
728
  */
789
729
  async has(hash) {
790
- const store = await this.whichStore([...this.stores], hash);
730
+ const store = await this.whichStore([...this.stores], hash)
791
731
  if (store) {
792
- return store.private ? false : true;
732
+ return store.private ? false : true
793
733
  }
794
- return false;
734
+ return false
795
735
  }
796
736
 
797
737
  /**
@@ -801,12 +741,12 @@ export default class Peernet {
801
741
  */
802
742
  async publish(topic, data) {
803
743
  // globalSub.publish(topic, data)
804
- const id = Math.random().toString(36).slice(-12);
805
- data = await new globalThis.peernet.protos["peernet-ps"]({ data, topic });
744
+ const id = Math.random().toString(36).slice(-12)
745
+ data = await new globalThis.peernet.protos['peernet-ps']({ data, topic })
806
746
  for (const [peerId, peer] of Object.entries(this.#connections)) {
807
747
  if (peerId !== this.id) {
808
- const node = await this.prepareMessage(data);
809
- this.sendMessage(peer, id, node.encoded);
748
+ const node = await this.prepareMessage(data)
749
+ this.sendMessage(peer, id, node.encoded)
810
750
  }
811
751
  // TODO: if peer subscribed
812
752
  }
@@ -823,26 +763,25 @@ export default class Peernet {
823
763
  */
824
764
  async subscribe(topic: string, callback: Function) {
825
765
  // TODO: if peer subscribed
826
- globalSub.subscribe(topic, callback);
766
+ globalSub.subscribe(topic, callback)
827
767
  }
828
768
 
829
769
  async removePeer(peer) {
830
- console.log("removepeer", peer.id);
831
- const id = peer.id;
832
- await this.client._removePeer(peer);
770
+ console.log('removepeer', peer.id)
771
+ const id = peer.id
772
+ await this.client._removePeer(peer)
833
773
  if (this.client.peers[id]) {
834
774
  for (const connection of Object.keys(this.client.peers[id])) {
835
775
  // if (this.client.peers[id][connection].connected === false) delete this.client.peers[id][connection]
836
776
  // @ts-ignore
837
- if (this.client.peers[id][connection].connected)
838
- return this.client.emit("peerconnect", connection);
777
+ if (this.client.peers[id][connection].connected) return this.client.emit('peerconnect', connection)
839
778
  }
840
779
  }
841
780
  }
842
781
 
843
782
  get Buffer() {
844
- return Buffer;
783
+ return Buffer
845
784
  }
846
785
  }
847
786
 
848
- globalThis.Peernet = Peernet;
787
+ globalThis.Peernet = Peernet