@leofcoin/peernet 0.11.7 → 0.11.10

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.
@@ -10,7 +10,7 @@ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'defau
10
10
  var PubSub__default = /*#__PURE__*/_interopDefaultLegacy(PubSub);
11
11
  var Koa__default = /*#__PURE__*/_interopDefaultLegacy(Koa);
12
12
 
13
- var version = "0.11.6";
13
+ var version = "0.11.9";
14
14
 
15
15
  var api$1 = {
16
16
  version: ({send}) => send({client: '@peernet/api/http', version}),
@@ -1,5 +1,6 @@
1
1
  'use strict';
2
2
 
3
+ require('@vandeurenglenn/debug');
3
4
  var LeofcoinStorage = require('@leofcoin/storage');
4
5
  var peernetMessage = require('./peernet-message.js');
5
6
  var dht = require('./dht.js');
@@ -307,6 +308,7 @@ class Peer {
307
308
  #senderMap = new Map()
308
309
  #iceCompleteTimer
309
310
  #channel
311
+ #peerId
310
312
 
311
313
  get connection() {
312
314
  return this.#connection
@@ -333,12 +335,17 @@ constructor(options = {}) {
333
335
  down: 0
334
336
  };
335
337
 
336
- this.channelName = options.channelName || Buffer.from(Math.random().toString(36).slice(-12)).toString('hex');
337
- console.log(this.channelName);
338
+ this.channelName = options.channelName;
339
+
340
+ this.#peerId = options.peerId;
338
341
  this.options = options;
339
342
  this.#init();
340
343
  }
341
344
 
345
+ get peerId() {
346
+ return this.#peerId
347
+ }
348
+
342
349
  set socketClient(value) {
343
350
  // this.socketClient?.pubsub.unsubscribe('signal', this._in)
344
351
  this._socketClient = value;
@@ -350,28 +357,29 @@ constructor(options = {}) {
350
357
  }
351
358
 
352
359
  send(message) {
353
- this.bw.up += message.length;
360
+ this.bw.up += message.length || message.byteLength;
354
361
  this.channel.send(message);
355
362
  }
356
363
 
357
364
  request(data) {
358
365
  return new Promise((resolve, reject) => {
359
366
  const id = Math.random().toString(36).slice(-12);
367
+ // TODO: get rid of JSON
360
368
  data = new TextEncoder().encode(JSON.stringify({id, data}));
361
369
  const _onData = message => {
362
370
  message = JSON.parse(new TextDecoder().decode(message.data));
363
371
  if (message.id === id) {
364
372
  resolve(message.data);
365
- pubsub.unsubscribe('peer:data', _onData);
373
+ pubsub.unsubscribe(`peer:data`, _onData);
366
374
  }
367
375
  };
368
376
 
369
- pubsub.subscribe('peer:data', _onData);
377
+ pubsub.subscribe(`peer:data`, _onData);
370
378
 
371
379
  // cleanup subscriptions
372
- setTimeout(() => {
373
- pubsub.unsubscribe('peer:data', _onData);
374
- }, 5000);
380
+ // setTimeout(() => {
381
+ // pubsub.unsubscribe(`peer:data-request-${id}`, _onData)
382
+ // }, 5000);
375
383
 
376
384
  this.send(data);
377
385
  });
@@ -400,12 +408,13 @@ constructor(options = {}) {
400
408
  this.#connected = true;
401
409
  pubsub.publish('peer:connected', this);
402
410
  };
403
- message.channel.onclose = () => console.log('close');
411
+ message.channel.onclose = () => this.close.bind(this);
412
+
404
413
  message.channel.onmessage = (message) => {
405
- if (message.to) {
406
- if (message.to === this.id) pubsub.publish('peer:data', message);
407
- } else pubsub.publish('peer:data', message);
408
- this.bw.down += message.length;
414
+ pubsub.publish('peer:data', message);
415
+ debug(`incoming message from ${this.id}`);
416
+ debug(message);
417
+ this.bw.down += message.length || message.byteLength;
409
418
  };
410
419
  this.channel = message.channel;
411
420
  };
@@ -420,10 +429,10 @@ constructor(options = {}) {
420
429
  this.channel.onclose = () => this.close.bind(this);
421
430
 
422
431
  this.channel.onmessage = (message) => {
423
- if (message.to) {
424
- if (message.to === this.id) pubsub.publish('peer:data', message);
425
- } else pubsub.publish('peer:data', message);
426
- this.bw.down += message.length;
432
+ pubsub.publish('peer:data', message);
433
+ debug(`incoming message from ${this.peerId}`);
434
+ debug(message);
435
+ this.bw.down += message.length || message.byteLength;
427
436
  };
428
437
 
429
438
  const offer = await this.#connection.createOffer();
@@ -453,6 +462,8 @@ constructor(options = {}) {
453
462
  // if (data.videocall) return this._startStream(true, false); // start video and audio stream
454
463
  // if (data.call) return this._startStream(true, true); // start audio stream
455
464
  if (message.candidate) {
465
+ debug(`incoming candidate ${this.channelName}`);
466
+ debug(message.candidate.candidate);
456
467
  this.remoteAddress = message.candidate.address;
457
468
  this.remotePort = message.candidate.port;
458
469
  this.remoteProtocol = message.candidate.protocol;
@@ -462,12 +473,14 @@ constructor(options = {}) {
462
473
  try {
463
474
  if (message.sdp) {
464
475
  if (message.sdp.type === 'offer') {
476
+ debug(`incoming offer ${this.channelName}`);
465
477
  await this.#connection.setRemoteDescription(new wrtc.RTCSessionDescription(message.sdp));
466
478
  const answer = await this.#connection.createAnswer();
467
479
  await this.#connection.setLocalDescription(answer);
468
480
  this._sendMessage({'sdp': this.#connection.localDescription});
469
481
  }
470
482
  if (message.sdp.type === 'answer') {
483
+ debug(`incoming answer ${this.channelName}`);
471
484
  await this.#connection.setRemoteDescription(new wrtc.RTCSessionDescription(message.sdp));
472
485
  }
473
486
  }
@@ -477,6 +490,7 @@ constructor(options = {}) {
477
490
  }
478
491
 
479
492
  close() {
493
+ debug(`closing ${this.peerId}`);
480
494
  this.channel?.close();
481
495
  this.#connection?.close();
482
496
 
@@ -507,7 +521,6 @@ class Client {
507
521
  async _init(identifiers, stars = []) {
508
522
  if (stars.length === 0) {
509
523
  stars.push('wss://star.leofcoin.org');
510
- stars.push('ws://localhost:44444');
511
524
  }
512
525
  this.identifiers = identifiers;
513
526
  this.starsConfig = stars;
@@ -526,17 +539,9 @@ class Client {
526
539
  }
527
540
  const peers = await this.socketClient.peernet.join({id: this.id});
528
541
  for (const id of peers) {
529
- if (id !== this.id && !this.#connections[id]) this.#connections[id] = new Peer({channelName: `${id}:${this.id}`, socketClient: this.socketClient, id: this.id, to: id});
542
+ if (id !== this.id && !this.#connections[id]) this.#connections[id] = new Peer({channelName: `${id}:${this.id}`, socketClient: this.socketClient, id: this.id, to: id, peerId: id});
530
543
  }
531
544
  this.setupListeners();
532
-
533
- pubsub.subscribe('peer:connected', (peer) => {
534
- // peer.send(JSON.stringify({data: 'hello', from: this.id, to: peer.to}))
535
- console.log({peer: peer.to});
536
- console.log({id: peer.id});
537
- console.log({id: this.id});
538
- });
539
- // pubsub.subscribe('peer:data', (data) => console.log({data}))
540
545
  }
541
546
 
542
547
  setupListeners() {
@@ -585,7 +590,7 @@ class Client {
585
590
  delete this.#connections[id];
586
591
  }
587
592
  // reconnect
588
- if (id !== this.id) this.#connections[id] = new Peer({channelName: `${id}:${this.id}`, socketClient: this.socketClient, id: this.id, to: id});
593
+ if (id !== this.id) this.#connections[id] = new Peer({channelName: `${id}:${this.id}`, socketClient: this.socketClient, id: this.id, to: id, peerId: id});
589
594
  }
590
595
 
591
596
  }
@@ -595,10 +600,7 @@ class Client {
595
600
  }
596
601
  }
597
602
  }
598
-
599
- console.log(`star ${id} left`);
600
-
601
-
603
+ debug(`star ${id} left`);
602
604
  }
603
605
 
604
606
  peerLeft(id) {
@@ -606,7 +608,7 @@ class Client {
606
608
  this.#connections[id].close();
607
609
  delete this.#connections[id];
608
610
  }
609
- console.log(`peer ${id} left`);
611
+ debug(`peer ${id} left`);
610
612
  }
611
613
 
612
614
  peerJoined(id, signal) {
@@ -615,8 +617,8 @@ class Client {
615
617
  delete this.#connections[id];
616
618
  }
617
619
  // RTCPeerConnection
618
- this.#connections[id] = new Peer({initiator: true, channelName: `${this.id}:${id}`, socketClient: this.socketClient, id: this.id, to: id});
619
- console.log(`peer ${id} joined`);
620
+ this.#connections[id] = new Peer({initiator: true, channelName: `${this.id}:${id}`, socketClient: this.socketClient, id: this.id, to: id, peerId: id});
621
+ debug(`peer ${id} joined`);
620
622
  }
621
623
 
622
624
 
@@ -774,7 +776,7 @@ class ChatMessage extends codecFormatInterface {
774
776
  }
775
777
  }
776
778
 
777
- const debug = (log) => {
779
+ const debug$1 = (log) => {
778
780
  if (globalThis.DEBUG || globalThis.debug) console.log(`%c ${log}`, 'color: #0080ff;');
779
781
  };
780
782
 
@@ -1636,7 +1638,7 @@ class Peernet {
1636
1638
  protocol: 'peernet-v0.1.0', host: '127.0.0.1', port: options.port
1637
1639
  });
1638
1640
  } else {
1639
- const http = await Promise.resolve().then(function () { return require('./http-906864ff.js'); });
1641
+ const http = await Promise.resolve().then(function () { return require('./http-e330b910.js'); });
1640
1642
  if (environment !== 'browser') http.default(options);
1641
1643
  }
1642
1644
 
@@ -1719,9 +1721,9 @@ class Peernet {
1719
1721
  * @param {PeernetPeer} peer - peernet peer
1720
1722
  */
1721
1723
  async _protoHandler(message, peer, from) {
1724
+
1722
1725
  const {id, proto} = message;
1723
1726
  this.bw.down += proto.encoded.length;
1724
-
1725
1727
  if (proto.name === 'peernet-dht') {
1726
1728
  let { hash, store } = proto.decoded;
1727
1729
  let has;
@@ -1769,9 +1771,8 @@ class Peernet {
1769
1771
 
1770
1772
  this.bw.up += node.encoded.length;
1771
1773
  }
1772
- } else if (proto.name === 'peernet-ps' &&
1773
- this._getPeerId(peer.id) !== this.id.toString()) {
1774
- globalSub.publish(proto.decoded.topic.toString(), proto.decoded.data.toString());
1774
+ } else if (proto.name === 'peernet-ps' && peer.peerId !== this.id) {
1775
+ globalSub.publish(new TextDecoder().decode(proto.decoded.topic), proto.decoded.data);
1775
1776
  }
1776
1777
  // }
1777
1778
  }
@@ -1785,17 +1786,14 @@ class Peernet {
1785
1786
  if (!hash) throw new Error('hash expected, received undefined')
1786
1787
  const data = new dht({hash});
1787
1788
  this.client.id;
1788
- for (const peer of this.connections) {
1789
- const node = await this.prepareMessage(peer.id, data.encoded);
1790
-
1791
- const result = await peer.request(node.encoded);
1792
-
1793
- let proto = protoFor(result.data);
1794
-
1789
+ const walk = async peer => {
1790
+ const node = await this.prepareMessage(peer.peerId, data.encoded);
1791
+ let result = await peer.request(node.encoded);
1792
+ result = new Uint8Array(Object.values(result));
1793
+ let proto = protoFor(result);
1795
1794
  if (proto.name !== 'peernet-message') throw encapsulatedError()
1796
1795
  const from = proto.decoded.from;
1797
1796
  proto = protoFor(proto.decoded.data);
1798
-
1799
1797
  if (proto.name !== 'peernet-dht-response') throw dhtError(proto.name)
1800
1798
 
1801
1799
  // TODO: give ip and port (just used for location)
@@ -1813,8 +1811,14 @@ class Peernet {
1813
1811
  };
1814
1812
 
1815
1813
  if (proto.decoded.has) this.dht.addProvider(peerInfo, proto.decoded.hash);
1814
+ };
1815
+ let walks = [];
1816
+ for (const peer of this.connections) {
1817
+ if (peer.peerId !== this.id) {
1818
+ walks.push(walk(peer));
1819
+ }
1816
1820
  }
1817
- return
1821
+ return Promise.all(walks)
1818
1822
  }
1819
1823
 
1820
1824
  /**
@@ -1876,34 +1880,33 @@ class Peernet {
1876
1880
  async requestData(hash, store) {
1877
1881
  const providers = await this.providersFor(hash);
1878
1882
  if (!providers || providers.size === 0) throw nothingFoundError(hash)
1879
- debug(`found ${providers.size} provider(s) for ${hash}`);
1883
+ debug$1(`found ${providers.size} provider(s) for ${hash}`);
1880
1884
  // get closest peer on earth
1881
1885
  const closestPeer = await this.dht.closestPeer(providers);
1882
1886
  // get peer instance by id
1883
- if (!closestPeer || !closestPeer.id) return this.requestData(hash, store.name ? store.name : store)
1887
+ if (!closestPeer || !closestPeer.id) return this.requestData(hash, store?.name ? store?.name : store)
1884
1888
 
1885
- const id = closestPeer.id.toString();
1889
+ const id = closestPeer.id;
1886
1890
  if (this.connections) {
1887
1891
  let closest = this.connections.filter((peer) => {
1888
- if (peer.id === id) return peer
1892
+ if (peer.peerId === id) return peer
1889
1893
  });
1890
1894
 
1891
- let data = new DataMessage({hash, store: store.name ? store.name : store});
1895
+ let data = new DataMessage({hash, store: store?.name ? store?.name : store});
1892
1896
 
1893
1897
  const node = await this.prepareMessage(id, data.encoded);
1894
1898
  if (closest[0]) data = await closest[0].request(node.encoded);
1895
1899
  else {
1896
1900
  closest = this.connections.filter((peer) => {
1897
- if (peer.id === id) return peer
1901
+ if (peer.peerId === id) return peer
1898
1902
  });
1899
1903
  if (closest[0]) data = await closest[0].request(node.encoded);
1900
1904
  }
1901
- if (data.data) {
1902
- console.log(data.data);
1903
- let proto = protoFor(data.data);
1904
- proto = protoFor(proto.decoded.data);
1905
- return proto.decoded.data
1906
- }
1905
+ data = new Uint8Array(Object.values(data));
1906
+ let proto = protoFor(data);
1907
+ proto = protoFor(proto.decoded.data);
1908
+ // TODO: store data automaticly or not
1909
+ return proto.decoded.data
1907
1910
 
1908
1911
  // this.put(hash, proto.decoded.data)
1909
1912
  }
@@ -1919,7 +1922,7 @@ class Peernet {
1919
1922
  * @param {String} hash
1920
1923
  */
1921
1924
  get: async (hash) => {
1922
- debug(`get message ${hash}`);
1925
+ debug$1(`get message ${hash}`);
1923
1926
  const message = await messageStore.has(hash);
1924
1927
  if (message) return await messageStore.get(hash)
1925
1928
  return this.requestData(hash, 'message')
@@ -1947,7 +1950,7 @@ class Peernet {
1947
1950
  * @param {String} hash
1948
1951
  */
1949
1952
  get: async (hash) => {
1950
- debug(`get data ${hash}`);
1953
+ debug$1(`get data ${hash}`);
1951
1954
  const data = await dataStore.has(hash);
1952
1955
  if (data) return await dataStore.get(hash)
1953
1956
  return this.requestData(hash, 'data')
@@ -1989,14 +1992,14 @@ class Peernet {
1989
1992
  * @param {String} store - storeName to access
1990
1993
  */
1991
1994
  async get(hash, store) {
1992
- debug(`get ${hash}`);
1995
+ debug$1(`get ${hash}`);
1993
1996
  let data;
1994
1997
  if (store) store = globalThis[`${store}Store`];
1995
1998
  if (!store) store = await this.whichStore([...this.stores], hash);
1996
1999
  if (store && await store.has(hash)) data = await store.get(hash);
1997
2000
  if (data) return data
1998
2001
 
1999
- return this.requestData(hash, store.name ? store.name : store)
2002
+ return this.requestData(hash, store?.name ? store.name : store)
2000
2003
  }
2001
2004
 
2002
2005
  /**
@@ -2037,8 +2040,8 @@ class Peernet {
2037
2040
  data = new PsMessage({data, topic});
2038
2041
  for (const peer of this.connections) {
2039
2042
  if (peer.connected) {
2040
- if (peer.id !== this.peerId) {
2041
- const node = await this.prepareMessage(peer.id, data.encoded);
2043
+ if (peer.peerId !== this.peerId) {
2044
+ const node = await this.prepareMessage(peer.peerId, data.encoded);
2042
2045
  peer.send(new TextEncoder().encode(JSON.stringify({id, data: node.encoded})));
2043
2046
  }
2044
2047
  } else {
@@ -2063,7 +2066,7 @@ class Peernet {
2063
2066
  }
2064
2067
 
2065
2068
  async removePeer(peer) {
2066
- delete this.client.connections[peer.id];
2069
+ delete this.client.connections[peer.peerId];
2067
2070
  }
2068
2071
 
2069
2072
  get Buffer() {