@leofcoin/peernet 0.9.8 → 0.9.11

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.
@@ -32,6 +32,7 @@ var MultiWallet__default = /*#__PURE__*/_interopDefaultLegacy(MultiWallet);
32
32
 
33
33
  class PeernetPeer {
34
34
  constructor(id, connection) {
35
+ this._events = {};
35
36
  this.id = id;
36
37
  this.connection = connection;
37
38
 
@@ -65,13 +66,27 @@ class PeernetPeer {
65
66
  }
66
67
 
67
68
  on(event = 'peernet.data', cb) {
69
+ this._events[event] = cb;
68
70
  pubsub.subscribe(event, cb);
69
71
  // this.connection.on(event, cb)
70
72
  }
71
73
 
72
74
  removeListener(event = 'data', cb) {
75
+ delete this._events[event];
73
76
  pubsub.unsubscribe(event, cb);
74
77
  }
78
+
79
+ close() {
80
+ for (const event of Object.keys(this._events)) {
81
+ pubsub.unsubscribe(event, this._events[event]);
82
+ }
83
+ this._events = [];
84
+
85
+ for (const event of this.connection._events.data) {
86
+ this.connection.removeListener('data', event);
87
+ }
88
+ this.connection.destroy();
89
+ }
75
90
  }
76
91
 
77
92
  /**
@@ -106,6 +121,10 @@ class PeernetClient {
106
121
 
107
122
  this.p2p.on('peerclose', (peer) => {
108
123
  // TODO: close peernetPeer
124
+ const peernetPeer = connections.get(peer.id);
125
+ if (peernetPeer) {
126
+ peernetPeer.close();
127
+ }
109
128
  connections.delete(peer.id);
110
129
  pubsub.publish('peer:disconnected', peer);
111
130
  });
@@ -261,7 +280,7 @@ class LeofcoinStorage$1 {
261
280
 
262
281
  }
263
282
 
264
- var version = "0.9.7";
283
+ var version = "0.9.10";
265
284
 
266
285
  var api$1 = {
267
286
  version: ({send}) => send({client: '@peernet/api/http', version}),
@@ -1689,7 +1708,7 @@ class PeerDiscovery {
1689
1708
  const connections = peernet.peerMap.get(id);
1690
1709
  if (connections.indexOf(peer.id) === -1) {
1691
1710
  connections.push(peer.id);
1692
- peernet.peerMap.set(from, connections);
1711
+ peernet.peerMap.set(peer.id, connections);
1693
1712
  }
1694
1713
  }
1695
1714
  return id
@@ -1952,656 +1971,659 @@ const nothingFoundError = (hash) => {
1952
1971
  return new Error(`nothing found for ${hash}`)
1953
1972
  };
1954
1973
 
1955
- globalThis.leofcoin = globalThis.leofcoin || {};
1956
- globalThis.globalSub = globalThis.globalSub || new PubSub__default['default']({verbose: true});
1957
-
1958
- /**
1959
- * @access public
1960
- * @example
1961
- * const peernet = new Peernet();
1962
- */
1963
- class Peernet {
1964
- /**
1965
- * @access public
1966
- * @param {Object} options
1967
- * @param {String} options.network - desired network
1968
- * @param {String} options.root - path to root directory
1969
- * @param {String} options.storePrefix - prefix for datatores (lfc)
1970
- *
1971
- * @return {Promise} instance of Peernet
1972
- *
1973
- * @example
1974
- * const peernet = new Peernet({network: 'leofcoin', root: '.leofcoin'});
1975
- */
1976
- constructor(options = {}) {
1977
- this._discovered = [];
1978
- /**
1979
- * @property {String} network - current network
1980
- */
1981
- this.network = options.network || 'leofcoin';
1982
- const parts = this.network.split(':');
1983
-
1984
- if (!options.storePrefix) options.storePrefix = 'lfc';
1985
- if (!options.port) options.port = 2000;
1986
- if (!options.root) {
1987
- if (parts[1]) options.root = `.${parts[0]}/peernet/${parts[1]}`;
1988
- else options.root = `.${this.network}/peernet`;
1989
- }
1990
- globalThis.peernet = this;
1991
- return this._init(options)
1992
- }
1993
-
1994
- get defaultStores() {
1995
- return ['account', 'wallet', 'block', 'transaction', 'chain', 'data', 'message']
1996
- }
1997
-
1998
- addProto(name, proto) {
1999
- if (!this.protos[name]) this.protos[name] = proto;
2000
- }
2001
-
2002
- addCodec(name, codec) {
2003
- if (!this.codecs[name]) this.codecs[name] = codec;
2004
- }
2005
-
2006
- async addStore(name, prefix, root, isPrivate = true) {
2007
- if (name === 'block' || name === 'transaction' || name === 'chain' ||
2008
- name === 'data' || name === 'message') isPrivate = false;
2009
-
2010
- let Storage;
2011
- if (this.hasDaemon) {
2012
- Storage = LeofcoinStorageClient;
2013
- } else {
2014
- Storage = LeofcoinStorage$1;
2015
- }
2016
- globalThis[`${name}Store`] = globalThis[`${name}Store`] ||
2017
- await new Storage(`${prefix}-${name}`, root);
2018
-
2019
- globalThis[`${name}Store`].private = isPrivate;
2020
- if (!isPrivate) this.stores.push(name);
2021
- }
2022
-
2023
-
2024
- /**
2025
- * @see MessageHandler
2026
- */
2027
- prepareMessage(to, data) {
2028
- return this._messageHandler.prepareMessage(this.id, to, data)
2029
- }
2030
-
2031
- /**
2032
- * @access public
2033
- *
2034
- * @return {Array} peerId
2035
- */
2036
- get peers() {
2037
- return [...connections.values()]
2038
- }
2039
-
2040
- /**
2041
- * @private
2042
- *
2043
- * @param {Object} options
2044
- * @param {String} options.root - path to root directory
2045
- *
2046
- * @return {Promise} instance of Peernet
2047
- */
2048
- async _init(options) {
2049
- // peernetDHT aka closesPeer by coordinates
2050
- /**
2051
- * @type {Object}
2052
- * @property {Object} peer Instance of Peer
2053
- */
2054
- this.dht = new DhtEarth();
2055
- /**
2056
- * @type {Map}
2057
- * @property {Object} peer Instance of Peer
2058
- */
2059
- this.peerMap = new Map();
2060
- this.stores = [];
2061
- this.requestProtos = {};
2062
- this.storePrefix = options.storePrefix;
2063
- this.root = options.root;
2064
-
2065
- /**
2066
- * proto Object containing protos
2067
- * @type {Object}
2068
- * @property {PeernetMessage} protos[peernet-message] messageNode
2069
- * @property {DHTMessage} protos[peernet-dht] messageNode
2070
- * @property {DHTMessageResponse} protos[peernet-dht-response] messageNode
2071
- * @property {DataMessage} protos[peernet-data] messageNode
2072
- * @property {DataMessageResponse} protos[peernet-data-response] messageNode
2073
- */
2074
- globalThis.peernet.protos = {
2075
- 'peernet-request': RequestMessage,
2076
- 'peernet-response': ResponseMessage,
2077
- 'peernet-peer': PeerMessage,
2078
- 'peernet-peer-response': PeerMessageResponse,
2079
- 'peernet-message': PeernetMessage,
2080
- 'peernet-dht': DHTMessage,
2081
- 'peernet-dht-response': DHTMessageResponse,
2082
- 'peernet-data': DataMessage,
2083
- 'peernet-data-response': DataMessageResponse,
2084
- 'peernet-ps': PsMessage,
2085
- 'chat-message': ChatMessage,
2086
- };
2087
-
2088
- this.protos = globalThis.peernet.protos;
2089
- this.codecs = codecs;
2090
-
2091
- this._messageHandler = new MessageHandler(this.network);
2092
-
2093
- const {daemon, environment} = await target();
2094
- this.hasDaemon = daemon;
2095
-
2096
- if (this.hasDaemon) {
2097
- globalThis.peernet.client = await httpClient({
2098
- protocol: 'peernet-v0.1.0', host: '127.0.0.1', port: options.port,
2099
- });
2100
- } else {
2101
- if (environment !== 'browser') http(options);
2102
- }
2103
-
2104
- for (const store of this.defaultStores) {
2105
- await this.addStore(store, options.storePrefix, options.root);
2106
- }
2107
-
2108
- try {
2109
- const pub = await accountStore.get('public');
2110
- this.id = pub.walletId;
2111
- } catch (e) {
2112
- if (e.code === 'ERR_NOT_FOUND') {
2113
- const wallet = {};
2114
- const {identity, accounts, config} = await generateAccount(this.network);
2115
- wallet.identity = identity;
2116
- wallet.accounts = accounts;
2117
- wallet.version = 1;
2118
- walletStore.put(wallet);
2119
- await accountStore.put('config', config);
2120
- await accountStore.put('public', {walletId: wallet.identity.walletId});
2121
-
2122
- this.id = wallet.identity.walletId;
2123
- } else {
2124
- throw e
2125
- }
2126
- }
2127
- this._peerHandler = new PeerDiscovery(this.id);
2128
- // peernet id
2129
- const id = Buffer.from(this.id.slice(0, 32));
2130
- this.peerId = id;
2131
-
2132
- pubsub.subscribe('peer:discovered', async (peer) => {
2133
- this._peerHandler.discover(peer);
2134
- peer.on('peernet.data', async (message) => {
2135
- const id = message.id;
2136
- message = new PeernetMessage(Buffer.from(message.data.data));
2137
- const proto = protoFor(message.decoded.data);
2138
- await this._protoHandler({id, proto}, peer);
2139
- const fulldId = this._getPeerId(peer.id);
2140
- if (fulldId && this._discovered.indexOf(peer.id) === -1) {
2141
- this._discovered.push(peer.id);
2142
- pubsub.publish('peer:connected', peer);
2143
- }
2144
- });
2145
- });
2146
- pubsub.subscribe('peer:disconnected', async (peer) => {
2147
- let index = this._discovered.indexOf(peer.id);
2148
- if (index !== -1) this._discovered.splice(index, 1);
2149
- const id = this._getPeerId(peer.id);
2150
- let peerIds = this.peerMap.get(id);
2151
-
2152
- if (peerIds) {
2153
- index = peerIds.indexOf(peer.id);
2154
- if (index !== -1) peerIds.splice(index, 1);
2155
- } else {
2156
- peerIds = [];
2157
- }
2158
-
2159
- if (peerIds.length === 0) this.peerMap.delete(id);
2160
- else this.peerMap.set(id, peerIds);
2161
- });
2162
- pubsub.subscribe('peer:connected', async (peer) => {
2163
- console.log({connected: peer.id, as: this._getPeerId(peer.id) });
2164
- // peer.on('peernet.data', async (message) => {
2165
- // const id = message.id
2166
- // message = new PeernetMessage(Buffer.from(message.data.data))
2167
- // const proto = protoFor(message.decoded.data)
2168
- // this._protoHandler({id, proto}, peer)
2169
- // })
2170
- });
2171
-
2172
- /**
2173
- * @access public
2174
- * @type {PeernetClient}
2175
- */
2176
- this.client = new PeernetClient({...options, id});
2177
- return this
2178
- }
2179
-
2180
- _getPeerId(id) {
2181
- for (const entry of [...this.peerMap.entries()]) {
2182
- for (const _id of entry[1]) {
2183
- if (_id === id) return entry[0]
2184
- }
2185
- }
2186
- }
2187
-
2188
- addRequestHandler(name, method) {
2189
- this.requestProtos[name] = method;
2190
- }
2191
-
2192
- /**
2193
- * @private
2194
- *
2195
- * @param {Buffer} message - peernet message
2196
- * @param {PeernetPeer} peer - peernet peer
2197
- */
2198
- async _protoHandler(message, peer) {
2199
- const {id, proto} = message;
2200
- if (proto.name === 'peernet-peer') {
2201
- const from = proto.decoded.id;
2202
- if (!this.peerMap.has(from)) this.peerMap.set(from, [peer.id]);
2203
- else {
2204
- const connections = this.peerMap.get(from);
2205
- if (connections.indexOf(peer.id) === -1) {
2206
- connections.push(peer.id);
2207
- this.peerMap.set(from, connections);
2208
- }
2209
- }
2210
- const data = new PeerMessageResponse({id: this.id});
2211
- const node = await this.prepareMessage(from, data.encoded);
2212
-
2213
- peer.write(Buffer.from(JSON.stringify({id, data: node.encoded})));
2214
- } else if (proto.name === 'peernet-peer-response') {
2215
- const from = proto.decoded.id;
2216
- if (!this.peerMap.has(from)) this.peerMap.set(from, [peer.id]);
2217
- else {
2218
- const connections = this.peerMap.get(from);
2219
- if (connections.indexOf(peer.id) === -1) {
2220
- connections.push(peer.id);
2221
- this.peerMap.set(from, connections);
2222
- }
2223
- }
2224
- } else {
2225
- let from = this._getPeerId(peer.id);
2226
- if (!from) {
2227
- const data = new PeerMessage({id: this.id});
2228
- const node = await this.prepareMessage(peer.id, data.encoded);
2229
-
2230
- let response = await peer.request(node.encoded);
2231
- response = protoFor(response);
2232
- response = new PeerMessageResponse(response.decoded.data);
2233
-
2234
- from = response.decoded.id;
2235
- if (!this.peerMap.has(from)) this.peerMap.set(from, [peer.id]);
2236
- else {
2237
- const connections = this.peerMap.get(from);
2238
- if (connections.indexOf(peer.id) === -1) {
2239
- connections.push(peer.id);
2240
- this.peerMap.set(from, connections);
2241
- }
2242
- }
2243
- }
2244
- if (proto.name === 'peernet-dht') {
2245
- let { hash, store } = proto.decoded;
2246
- let has;
2247
-
2248
- if (!store) {
2249
- has = await this.has(hash);
2250
- } else {
2251
- store = globalThis[`${store}Store`];
2252
- if (store.private) has = false;
2253
- else has = await store.has(hash);
2254
- }
2255
- const data = new DHTMessageResponse({hash, has});
2256
- const node = await this.prepareMessage(from, data.encoded);
2257
-
2258
- peer.write(Buffer.from(JSON.stringify({id, data: node.encoded})));
2259
- } else if (proto.name === 'peernet-data') {
2260
- let { hash, store } = proto.decoded;
2261
- let data;
2262
-
2263
- if (!store) {
2264
- data = await this.get(hash);
2265
- } else {
2266
- store = globalThis[`${store}Store`];
2267
- if (store.private) {
2268
- // TODO: ban
2269
- return
2270
- } else data = await store.get(hash);
2271
- }
2272
-
2273
- if (data) {
2274
- data = new DataMessageResponse({hash, data: Buffer.from(data)});
2275
-
2276
- const node = await this.prepareMessage(from, data.encoded);
2277
- peer.write(Buffer.from(JSON.stringify({id, data: node.encoded})));
2278
- }
2279
- } else if (proto.name === 'peernet-peer') {
2280
- const from = proto.decoded.id;
2281
- if (!this.peerMap.has(from)) this.peerMap.set(from, [peer.id]);
2282
- else {
2283
- const connections = this.peerMap.get(from);
2284
- connections.push(peer.id);
2285
- this.peerMap.set(from, connections);
2286
- }
2287
- const data = new PeerMessage({id: this.id});
2288
- const node = await this.prepareMessage(from, data.encoded);
2289
-
2290
- peer.write(Buffer.from(JSON.stringify({id, data: node.encoded})));
2291
- } else if (proto.name === 'peernet-request') {
2292
- // TODO: make dynamic
2293
- // exposeddevapi[proto.decoded.request](proto.decoded.params)
2294
- const method = this.requestProtos[proto.decoded.request];
2295
- if (method) {
2296
- const data = await method();
2297
- const node = await this.prepareMessage(from, data.encoded);
2298
- peer.write(Buffer.from(JSON.stringify({id, data: node.encoded})));
2299
- }
2300
- } else if (proto.name === 'peernet-ps' &&
2301
- this._getPeerId(peer.id) !== this.id.toString()) {
2302
- globalSub.publish(proto.decoded.topic.toString(), proto.decoded.data.toString());
2303
- }
2304
- }
2305
- }
2306
-
2307
- /**
2308
- * performs a walk and resolves first encounter
2309
- *
2310
- * @param {String} hash
2311
- */
2312
- async walk(hash) {
2313
- if (!hash) throw new Error('hash expected, received undefined')
2314
- const data = new DHTMessage({hash});
2315
- this.client.id;
2316
- for (const peer of this.peers) {
2317
- const node = await this.prepareMessage(peer.id, data.encoded);
2318
-
2319
- const result = await peer.request(node.encoded);
2320
-
2321
- let proto = protoFor(result.data);
2322
-
2323
- if (proto.name !== 'peernet-message') throw encapsulatedError()
2324
- const from = proto.decoded.from;
2325
- proto = protoFor(proto.decoded.data);
2326
-
2327
- if (proto.name !== 'peernet-dht-response') throw dhtError(proto.name)
2328
-
2329
- // TODO: give ip and port (just used for location)
2330
- if (!peer.connection.remoteAddress || !peer.connection.localAddress) {
2331
- peer.connection.remoteFamily = 'ipv4';
2332
- peer.connection.remoteAddress = '127.0.0.1';
2333
- peer.connection.remotePort = '0000';
2334
- }
2335
-
2336
- const peerInfo = {
2337
- family: peer.connection.remoteFamily || peer.connection.localFamily,
2338
- address: peer.connection.remoteAddress || peer.connection.localAddress,
2339
- port: peer.connection.remotePort || peer.connection.localPort,
2340
- id: from,
2341
- };
2342
-
2343
- if (proto.decoded.has) this.dht.addProvider(peerInfo, proto.decoded.hash);
2344
- }
2345
- return
2346
- }
2347
-
2348
- /**
2349
- * Override DHT behavior, try's finding the content three times
2350
- *
2351
- * @param {String} hash
2352
- */
2353
- async providersFor(hash) {
2354
- let providers = await this.dht.providersFor(hash);
2355
- // walk the network to find a provider
2356
- if (!providers || providers.length === 0) {
2357
- await this.walk(hash);
2358
- providers = await this.dht.providersFor(hash);
2359
- // second walk the network to find a provider
2360
- if (!providers || providers.length === 0) {
2361
- await this.walk(hash);
2362
- providers = await this.dht.providersFor(hash);
2363
- }
2364
- // last walk
2365
- if (!providers || providers.length === 0) {
2366
- await this.walk(hash);
2367
- providers = await this.dht.providersFor(hash);
2368
- }
2369
- }
2370
- // undefined if no providers given
2371
- return providers
2372
- }
2373
-
2374
- get block() {
2375
- return {
2376
- get: async (hash) => {
2377
- const data = await blockStore.has(hash);
2378
- if (data) return await blockStore.get(hash)
2379
- return this.requestData(hash)
2380
- },
2381
- put: async (hash, data) => {
2382
- if (await blockStore.has(hash)) return
2383
- return await blockStore.put(hash, data)
2384
- },
2385
- has: async (hash) => await blockStore.has(hash, 'block'),
2386
- }
2387
- }
2388
-
2389
- get transaction() {
2390
- return {
2391
- get: async (hash) => {
2392
- const data = await transactionStore.has(hash);
2393
- if (data) return await transactionStore.get(hash)
2394
- return this.requestData(hash, 'transaction')
2395
- },
2396
- put: async (hash, data) => {
2397
- if (await transactionStore.has(hash)) return
2398
- return await transactionStore.put(hash, data)
2399
- },
2400
- has: async (hash) => await transactionStore.has(hash),
2401
- }
2402
- }
2403
-
2404
- async requestData(hash, store) {
2405
- const providers = await this.providersFor(hash);
2406
- if (!providers || providers.size === 0) throw nothingFoundError(hash)
2407
- debug(`found ${providers.size} provider(s) for ${hash}`);
2408
- // get closest peer on earth
2409
- const closestPeer = await this.dht.closestPeer(providers);
2410
- // get peer instance by id
2411
- if (!closestPeer || !closestPeer.id) return this.requestData(hash, store)
2412
-
2413
- const id = closestPeer.id.toString();
2414
- if (this.peers) {
2415
- let closest = this.peers.filter((peer) => {
2416
- if (this._getPeerId(peer.id) === id) return peer
2417
- });
2418
-
2419
- let data = new DataMessage({hash, store});
2420
-
2421
- const node = await this.prepareMessage(id, data.encoded);
2422
- if (closest[0]) data = await closest[0].request(node.encoded);
2423
- else {
2424
- closest = this.peers.filter((peer) => {
2425
- if (peer.id.toString() === id) return peer
2426
- });
2427
- if (closest[0]) data = await closest[0].request(node.encoded);
2428
- }
2429
- if (data.data) {
2430
- let proto = protoFor(Buffer.from(data.data));
2431
- proto = protoFor(proto.decoded.data);
2432
- return proto.decoded.data
2433
- }
2434
-
2435
- // this.put(hash, proto.decoded.data)
2436
- }
2437
- return null
2438
- }
2439
-
2440
-
2441
- get message() {
2442
- return {
2443
- /**
2444
- * Get content for given message hash
2445
- *
2446
- * @param {String} hash
2447
- */
2448
- get: async (hash) => {
2449
- debug(`get message ${hash}`);
2450
- const message = await messageStore.has(hash);
2451
- if (message) return await messageStore.get(hash)
2452
- return this.requestData(hash, 'message')
2453
- },
2454
- /**
2455
- * put message content
2456
- *
2457
- * @param {String} hash
2458
- * @param {Buffer} message
2459
- */
2460
- put: async (hash, message) => await messageStore.put(hash, message),
2461
- /**
2462
- * @param {String} hash
2463
- * @return {Boolean}
2464
- */
2465
- has: async (hash) => await messageStore.has(hash),
2466
- }
2467
- }
2468
-
2469
- get data() {
2470
- return {
2471
- /**
2472
- * Get content for given data hash
2473
- *
2474
- * @param {String} hash
2475
- */
2476
- get: async (hash) => {
2477
- debug(`get data ${hash}`);
2478
- const data = await dataStore.has(hash);
2479
- if (data) return await dataStore.get(hash)
2480
- return this.requestData(hash, 'data')
2481
- },
2482
- /**
2483
- * put data content
2484
- *
2485
- * @param {String} hash
2486
- * @param {Buffer} data
2487
- */
2488
- put: async (hash, data) => await dataStore.put(hash, data),
2489
- /**
2490
- * @param {String} hash
2491
- * @return {Boolean}
2492
- */
2493
- has: async (hash) => await dataStore.has(hash),
2494
- }
2495
- }
2496
-
2497
- /**
2498
- * goes trough given stores and tries to find data for given hash
2499
- * @param {Array} stores
2500
- * @param {string} hash
2501
- */
2502
- async whichStore(stores, hash) {
2503
- let store = stores.pop();
2504
- store = globalThis[`${store}Store`];
2505
- if (store) {
2506
- const has = await store.has(hash);
2507
- if (has) return store
2508
- if (stores.length > 0) return this.whichStore(stores, hash)
2509
- } else return null
2510
- }
2511
-
2512
- /**
2513
- * Get content for given hash
2514
- *
2515
- * @param {String} hash
2516
- */
2517
- async get(hash, store) {
2518
- debug(`get ${hash}`);
2519
- let data;
2520
- if (store) store = globalThis[`${store}Store`];
2521
- if (!store) store = await this.whichStore([...this.stores], hash);
2522
- if (store && await store.has(hash)) data = await store.get(hash);
2523
- if (data) return data
2524
-
2525
- return this.requestData(hash, 'data')
2526
- }
2527
-
2528
- /**
2529
- * put content
2530
- *
2531
- * @param {String} hash
2532
- * @param {Buffer} data
2533
- */
2534
- async put(hash, data, store = 'data') {
2535
- store = globalThis[`${store}Store`];
2536
- return await store.put(hash, data)
2537
- }
2538
-
2539
- /**
2540
- * @param {String} hash
2541
- * @return {Boolean}
2542
- */
2543
- async has(hash) {
2544
- const store = await this.whichStore([...this.stores], hash);
2545
- if (store) {
2546
- if (store.private) return false
2547
- else return true
2548
- }
2549
- return false
2550
- }
2551
-
2552
- /**
2553
- *
2554
- * @param {String} topic
2555
- * @param {String|Object|Array|Boolean|Buffer} data
2556
- */
2557
- async publish(topic, data) {
2558
- // globalSub.publish(topic, data)
2559
- if (!Buffer.isBuffer(topic)) topic = Buffer.from(topic);
2560
- if (!Buffer.isBuffer(data)) data = Buffer.from(data);
2561
- const id = Math.random().toString(36).slice(-12);
2562
- data = new PsMessage({data, topic});
2563
- for (const peer of this.peers) {
2564
- if (peer.connection._connected) {
2565
- if (peer.id.toString() !== this.peerId.toString()) {
2566
- const node = await this.prepareMessage(peer.id, data.encoded);
2567
- peer.write(Buffer.from(JSON.stringify({id, data: node.encoded})));
2568
- }
2569
- } else {
2570
- this.removePeer(peer);
2571
- }
2572
- // TODO: if peer subscribed
2573
- }
2574
- }
2575
-
2576
- createHash(data, name) {
2577
- return new PeernetHash(data, {name})
2578
- }
2579
-
2580
- /**
2581
- *
2582
- * @param {String} topic
2583
- * @param {Method} cb
2584
- */
2585
- async subscribe(topic, cb) {
2586
- // TODO: if peer subscribed
2587
- globalSub.subscribe(topic, cb);
2588
- }
2589
-
2590
- async removePeer(peer) {
2591
- connections.delete(peer.id);
2592
- }
2593
-
2594
- get Buffer() {
2595
- return Buffer
2596
- }
2597
- // async block(index) {
2598
- // const _values = []
2599
- // for (const peer of this.peers) {
2600
- // const value = await peer.request({type: 'block', index})
2601
- // console.log(value);
2602
- // }
2603
- //
2604
- // }
1974
+ globalThis.leofcoin = globalThis.leofcoin || {};
1975
+ globalThis.globalSub = globalThis.globalSub || new PubSub__default['default']({verbose: true});
1976
+
1977
+ /**
1978
+ * @access public
1979
+ * @example
1980
+ * const peernet = new Peernet();
1981
+ */
1982
+ class Peernet {
1983
+ /**
1984
+ * @access public
1985
+ * @param {Object} options
1986
+ * @param {String} options.network - desired network
1987
+ * @param {String} options.root - path to root directory
1988
+ * @param {String} options.storePrefix - prefix for datatores (lfc)
1989
+ *
1990
+ * @return {Promise} instance of Peernet
1991
+ *
1992
+ * @example
1993
+ * const peernet = new Peernet({network: 'leofcoin', root: '.leofcoin'});
1994
+ */
1995
+ constructor(options = {}) {
1996
+ this._discovered = [];
1997
+ /**
1998
+ * @property {String} network - current network
1999
+ */
2000
+ this.network = options.network || 'leofcoin';
2001
+ const parts = this.network.split(':');
2002
+
2003
+ if (!options.storePrefix) options.storePrefix = 'lfc';
2004
+ if (!options.port) options.port = 2000;
2005
+ if (!options.root) {
2006
+ if (parts[1]) options.root = `.${parts[0]}/peernet/${parts[1]}`;
2007
+ else options.root = `.${this.network}/peernet`;
2008
+ }
2009
+ globalThis.peernet = this;
2010
+ return this._init(options)
2011
+ }
2012
+
2013
+ get defaultStores() {
2014
+ return ['account', 'wallet', 'block', 'transaction', 'chain', 'data', 'message']
2015
+ }
2016
+
2017
+ addProto(name, proto) {
2018
+ if (!this.protos[name]) this.protos[name] = proto;
2019
+ }
2020
+
2021
+ addCodec(name, codec) {
2022
+ if (!this.codecs[name]) this.codecs[name] = codec;
2023
+ }
2024
+
2025
+ async addStore(name, prefix, root, isPrivate = true) {
2026
+ if (name === 'block' || name === 'transaction' || name === 'chain' ||
2027
+ name === 'data' || name === 'message') isPrivate = false;
2028
+
2029
+ let Storage;
2030
+ if (this.hasDaemon) {
2031
+ Storage = LeofcoinStorageClient;
2032
+ } else {
2033
+ Storage = LeofcoinStorage$1;
2034
+ }
2035
+ globalThis[`${name}Store`] = globalThis[`${name}Store`] ||
2036
+ await new Storage(`${prefix}-${name}`, root);
2037
+
2038
+ globalThis[`${name}Store`].private = isPrivate;
2039
+ if (!isPrivate) this.stores.push(name);
2040
+ }
2041
+
2042
+
2043
+ /**
2044
+ * @see MessageHandler
2045
+ */
2046
+ prepareMessage(to, data) {
2047
+ return this._messageHandler.prepareMessage(this.id, to, data)
2048
+ }
2049
+
2050
+ /**
2051
+ * @access public
2052
+ *
2053
+ * @return {Array} peerId
2054
+ */
2055
+ get peers() {
2056
+ return [...connections.values()]
2057
+ }
2058
+
2059
+ /**
2060
+ * @private
2061
+ *
2062
+ * @param {Object} options
2063
+ * @param {String} options.root - path to root directory
2064
+ *
2065
+ * @return {Promise} instance of Peernet
2066
+ */
2067
+ async _init(options) {
2068
+ // peernetDHT aka closesPeer by coordinates
2069
+ /**
2070
+ * @type {Object}
2071
+ * @property {Object} peer Instance of Peer
2072
+ */
2073
+ this.dht = new DhtEarth();
2074
+ /**
2075
+ * @type {Map}
2076
+ * @property {Object} peer Instance of Peer
2077
+ */
2078
+ this.peerMap = new Map();
2079
+ this.stores = [];
2080
+ this.requestProtos = {};
2081
+ this.storePrefix = options.storePrefix;
2082
+ this.root = options.root;
2083
+
2084
+ /**
2085
+ * proto Object containing protos
2086
+ * @type {Object}
2087
+ * @property {PeernetMessage} protos[peernet-message] messageNode
2088
+ * @property {DHTMessage} protos[peernet-dht] messageNode
2089
+ * @property {DHTMessageResponse} protos[peernet-dht-response] messageNode
2090
+ * @property {DataMessage} protos[peernet-data] messageNode
2091
+ * @property {DataMessageResponse} protos[peernet-data-response] messageNode
2092
+ */
2093
+ globalThis.peernet.protos = {
2094
+ 'peernet-request': RequestMessage,
2095
+ 'peernet-response': ResponseMessage,
2096
+ 'peernet-peer': PeerMessage,
2097
+ 'peernet-peer-response': PeerMessageResponse,
2098
+ 'peernet-message': PeernetMessage,
2099
+ 'peernet-dht': DHTMessage,
2100
+ 'peernet-dht-response': DHTMessageResponse,
2101
+ 'peernet-data': DataMessage,
2102
+ 'peernet-data-response': DataMessageResponse,
2103
+ 'peernet-ps': PsMessage,
2104
+ 'chat-message': ChatMessage,
2105
+ };
2106
+
2107
+ this.protos = globalThis.peernet.protos;
2108
+ this.codecs = codecs;
2109
+
2110
+ this._messageHandler = new MessageHandler(this.network);
2111
+
2112
+ const {daemon, environment} = await target();
2113
+ this.hasDaemon = daemon;
2114
+
2115
+ if (this.hasDaemon) {
2116
+ globalThis.peernet.client = await httpClient({
2117
+ protocol: 'peernet-v0.1.0', host: '127.0.0.1', port: options.port,
2118
+ });
2119
+ } else {
2120
+ if (environment !== 'browser') http(options);
2121
+ }
2122
+
2123
+ for (const store of this.defaultStores) {
2124
+ await this.addStore(store, options.storePrefix, options.root);
2125
+ }
2126
+
2127
+ try {
2128
+ const pub = await accountStore.get('public');
2129
+ this.id = pub.walletId;
2130
+ } catch (e) {
2131
+ if (e.code === 'ERR_NOT_FOUND') {
2132
+ const wallet = {};
2133
+ const {identity, accounts, config} = await generateAccount(this.network);
2134
+ wallet.identity = identity;
2135
+ wallet.accounts = accounts;
2136
+ wallet.version = 1;
2137
+ walletStore.put(wallet);
2138
+ await accountStore.put('config', config);
2139
+ await accountStore.put('public', {walletId: wallet.identity.walletId});
2140
+
2141
+ this.id = wallet.identity.walletId;
2142
+ } else {
2143
+ throw e
2144
+ }
2145
+ }
2146
+ this._peerHandler = new PeerDiscovery(this.id);
2147
+ // peernet id
2148
+ const id = Buffer.from(this.id.slice(0, 32));
2149
+ this.peerId = id;
2150
+
2151
+ pubsub.subscribe('peer:discovered', async (peer) => {
2152
+ peer.on('peernet.data', async (message) => {
2153
+ const id = message.id;
2154
+ message = new PeernetMessage(Buffer.from(message.data.data));
2155
+ const proto = protoFor(message.decoded.data);
2156
+ await this._protoHandler({id, proto}, peer);
2157
+ });
2158
+ await this._peerHandler.discover(peer);
2159
+ const fulldId = this._getPeerId(peer.id);
2160
+ if (fulldId && this._discovered.indexOf(peer.id) === -1) {
2161
+ this._discovered.push(peer.id);
2162
+ pubsub.publish('peer:connected', peer);
2163
+ }
2164
+ });
2165
+ pubsub.subscribe('peer:disconnected', async (peer) => {
2166
+ let index = this._discovered.indexOf(peer.id);
2167
+ if (index !== -1) this._discovered.splice(index, 1);
2168
+ const id = this._getPeerId(peer.id);
2169
+ let peerIds = this.peerMap.get(id);
2170
+
2171
+ if (peerIds) {
2172
+ index = peerIds.indexOf(peer.id);
2173
+ if (index !== -1) peerIds.splice(index, 1);
2174
+ } else {
2175
+ peerIds = [];
2176
+ }
2177
+
2178
+ if (peerIds.length === 0) this.peerMap.delete(id);
2179
+ else this.peerMap.set(id, peerIds);
2180
+ });
2181
+ pubsub.subscribe('peer:connected', async (peer) => {
2182
+ console.log({connected: peer.id, as: this._getPeerId(peer.id) });
2183
+ // peer.on('peernet.data', async (message) => {
2184
+ // const id = message.id
2185
+ // message = new PeernetMessage(Buffer.from(message.data.data))
2186
+ // const proto = protoFor(message.decoded.data)
2187
+ // this._protoHandler({id, proto}, peer)
2188
+ // })
2189
+ });
2190
+
2191
+ /**
2192
+ * @access public
2193
+ * @type {PeernetClient}
2194
+ */
2195
+ this.client = new PeernetClient({...options, id});
2196
+ if (globalThis.onbeforeunload) {
2197
+ globalThisaddEventListener("beforeunload", async () => this.client.close());
2198
+ }
2199
+ return this
2200
+ }
2201
+
2202
+ _getPeerId(id) {
2203
+ for (const entry of [...this.peerMap.entries()]) {
2204
+ for (const _id of entry[1]) {
2205
+ if (_id === id) return entry[0]
2206
+ }
2207
+ }
2208
+ }
2209
+
2210
+ addRequestHandler(name, method) {
2211
+ this.requestProtos[name] = method;
2212
+ }
2213
+
2214
+ /**
2215
+ * @private
2216
+ *
2217
+ * @param {Buffer} message - peernet message
2218
+ * @param {PeernetPeer} peer - peernet peer
2219
+ */
2220
+ async _protoHandler(message, peer) {
2221
+ const {id, proto} = message;
2222
+ if (proto.name === 'peernet-peer') {
2223
+ const from = proto.decoded.id;
2224
+ if (!this.peerMap.has(from)) this.peerMap.set(from, [peer.id]);
2225
+ else {
2226
+ const connections = this.peerMap.get(from);
2227
+ if (connections.indexOf(peer.id) === -1) {
2228
+ connections.push(peer.id);
2229
+ this.peerMap.set(from, connections);
2230
+ }
2231
+ }
2232
+ const data = new PeerMessageResponse({id: this.id});
2233
+ const node = await this.prepareMessage(from, data.encoded);
2234
+
2235
+ peer.write(Buffer.from(JSON.stringify({id, data: node.encoded})));
2236
+ } else if (proto.name === 'peernet-peer-response') {
2237
+ const from = proto.decoded.id;
2238
+ if (!this.peerMap.has(from)) this.peerMap.set(from, [peer.id]);
2239
+ else {
2240
+ const connections = this.peerMap.get(from);
2241
+ if (connections.indexOf(peer.id) === -1) {
2242
+ connections.push(peer.id);
2243
+ this.peerMap.set(from, connections);
2244
+ }
2245
+ }
2246
+ } else {
2247
+ let from = this._getPeerId(peer.id);
2248
+ if (!from) {
2249
+ const data = new PeerMessage({id: this.id});
2250
+ const node = await this.prepareMessage(peer.id, data.encoded);
2251
+
2252
+ let response = await peer.request(node.encoded);
2253
+ response = protoFor(response);
2254
+ response = new PeerMessageResponse(response.decoded.data);
2255
+
2256
+ from = response.decoded.id;
2257
+ if (!this.peerMap.has(from)) this.peerMap.set(from, [peer.id]);
2258
+ else {
2259
+ const connections = this.peerMap.get(from);
2260
+ if (connections.indexOf(peer.id) === -1) {
2261
+ connections.push(peer.id);
2262
+ this.peerMap.set(from, connections);
2263
+ }
2264
+ }
2265
+ }
2266
+ if (proto.name === 'peernet-dht') {
2267
+ let { hash, store } = proto.decoded;
2268
+ let has;
2269
+
2270
+ if (!store) {
2271
+ has = await this.has(hash);
2272
+ } else {
2273
+ store = globalThis[`${store}Store`];
2274
+ if (store.private) has = false;
2275
+ else has = await store.has(hash);
2276
+ }
2277
+ const data = new DHTMessageResponse({hash, has});
2278
+ const node = await this.prepareMessage(from, data.encoded);
2279
+
2280
+ peer.write(Buffer.from(JSON.stringify({id, data: node.encoded})));
2281
+ } else if (proto.name === 'peernet-data') {
2282
+ let { hash, store } = proto.decoded;
2283
+ let data;
2284
+
2285
+ if (!store) {
2286
+ data = await this.get(hash);
2287
+ } else {
2288
+ store = globalThis[`${store}Store`];
2289
+ if (store.private) {
2290
+ // TODO: ban
2291
+ return
2292
+ } else data = await store.get(hash);
2293
+ }
2294
+
2295
+ if (data) {
2296
+ data = new DataMessageResponse({hash, data: data.decoded ? Buffer.from(JSON.stringify(data)) : Buffer.from(data)});
2297
+
2298
+ const node = await this.prepareMessage(from, data.encoded);
2299
+ peer.write(Buffer.from(JSON.stringify({id, data: node.encoded})));
2300
+ }
2301
+ } else if (proto.name === 'peernet-peer') {
2302
+ const from = proto.decoded.id;
2303
+ if (!this.peerMap.has(from)) this.peerMap.set(from, [peer.id]);
2304
+ else {
2305
+ const connections = this.peerMap.get(from);
2306
+ connections.push(peer.id);
2307
+ this.peerMap.set(from, connections);
2308
+ }
2309
+ const data = new PeerMessage({id: this.id});
2310
+ const node = await this.prepareMessage(from, data.encoded);
2311
+
2312
+ peer.write(Buffer.from(JSON.stringify({id, data: node.encoded})));
2313
+ } else if (proto.name === 'peernet-request') {
2314
+ // TODO: make dynamic
2315
+ // exposeddevapi[proto.decoded.request](proto.decoded.params)
2316
+ const method = this.requestProtos[proto.decoded.request];
2317
+ if (method) {
2318
+ const data = await method();
2319
+ const node = await this.prepareMessage(from, data.encoded);
2320
+ peer.write(Buffer.from(JSON.stringify({id, data: node.encoded})));
2321
+ }
2322
+ } else if (proto.name === 'peernet-ps' &&
2323
+ this._getPeerId(peer.id) !== this.id.toString()) {
2324
+ globalSub.publish(proto.decoded.topic.toString(), proto.decoded.data.toString());
2325
+ }
2326
+ }
2327
+ }
2328
+
2329
+ /**
2330
+ * performs a walk and resolves first encounter
2331
+ *
2332
+ * @param {String} hash
2333
+ */
2334
+ async walk(hash) {
2335
+ if (!hash) throw new Error('hash expected, received undefined')
2336
+ const data = new DHTMessage({hash});
2337
+ this.client.id;
2338
+ for (const peer of this.peers) {
2339
+ const node = await this.prepareMessage(peer.id, data.encoded);
2340
+
2341
+ const result = await peer.request(node.encoded);
2342
+
2343
+ let proto = protoFor(result.data);
2344
+
2345
+ if (proto.name !== 'peernet-message') throw encapsulatedError()
2346
+ const from = proto.decoded.from;
2347
+ proto = protoFor(proto.decoded.data);
2348
+
2349
+ if (proto.name !== 'peernet-dht-response') throw dhtError(proto.name)
2350
+
2351
+ // TODO: give ip and port (just used for location)
2352
+ if (!peer.connection.remoteAddress || !peer.connection.localAddress) {
2353
+ peer.connection.remoteFamily = 'ipv4';
2354
+ peer.connection.remoteAddress = '127.0.0.1';
2355
+ peer.connection.remotePort = '0000';
2356
+ }
2357
+
2358
+ const peerInfo = {
2359
+ family: peer.connection.remoteFamily || peer.connection.localFamily,
2360
+ address: peer.connection.remoteAddress || peer.connection.localAddress,
2361
+ port: peer.connection.remotePort || peer.connection.localPort,
2362
+ id: from,
2363
+ };
2364
+
2365
+ if (proto.decoded.has) this.dht.addProvider(peerInfo, proto.decoded.hash);
2366
+ }
2367
+ return
2368
+ }
2369
+
2370
+ /**
2371
+ * Override DHT behavior, try's finding the content three times
2372
+ *
2373
+ * @param {String} hash
2374
+ */
2375
+ async providersFor(hash) {
2376
+ let providers = await this.dht.providersFor(hash);
2377
+ // walk the network to find a provider
2378
+ if (!providers || providers.length === 0) {
2379
+ await this.walk(hash);
2380
+ providers = await this.dht.providersFor(hash);
2381
+ // second walk the network to find a provider
2382
+ if (!providers || providers.length === 0) {
2383
+ await this.walk(hash);
2384
+ providers = await this.dht.providersFor(hash);
2385
+ }
2386
+ // last walk
2387
+ if (!providers || providers.length === 0) {
2388
+ await this.walk(hash);
2389
+ providers = await this.dht.providersFor(hash);
2390
+ }
2391
+ }
2392
+ // undefined if no providers given
2393
+ return providers
2394
+ }
2395
+
2396
+ get block() {
2397
+ return {
2398
+ get: async (hash) => {
2399
+ const data = await blockStore.has(hash);
2400
+ if (data) return await blockStore.get(hash)
2401
+ return this.requestData(hash)
2402
+ },
2403
+ put: async (hash, data) => {
2404
+ if (await blockStore.has(hash)) return
2405
+ return await blockStore.put(hash, data)
2406
+ },
2407
+ has: async (hash) => await blockStore.has(hash, 'block'),
2408
+ }
2409
+ }
2410
+
2411
+ get transaction() {
2412
+ return {
2413
+ get: async (hash) => {
2414
+ const data = await transactionStore.has(hash);
2415
+ if (data) return await transactionStore.get(hash)
2416
+ return this.requestData(hash, 'transaction')
2417
+ },
2418
+ put: async (hash, data) => {
2419
+ if (await transactionStore.has(hash)) return
2420
+ return await transactionStore.put(hash, data)
2421
+ },
2422
+ has: async (hash) => await transactionStore.has(hash),
2423
+ }
2424
+ }
2425
+
2426
+ async requestData(hash, store) {
2427
+ const providers = await this.providersFor(hash);
2428
+ if (!providers || providers.size === 0) throw nothingFoundError(hash)
2429
+ debug(`found ${providers.size} provider(s) for ${hash}`);
2430
+ // get closest peer on earth
2431
+ const closestPeer = await this.dht.closestPeer(providers);
2432
+ // get peer instance by id
2433
+ if (!closestPeer || !closestPeer.id) return this.requestData(hash, store)
2434
+
2435
+ const id = closestPeer.id.toString();
2436
+ if (this.peers) {
2437
+ let closest = this.peers.filter((peer) => {
2438
+ if (this._getPeerId(peer.id) === id) return peer
2439
+ });
2440
+
2441
+ let data = new DataMessage({hash, store});
2442
+
2443
+ const node = await this.prepareMessage(id, data.encoded);
2444
+ if (closest[0]) data = await closest[0].request(node.encoded);
2445
+ else {
2446
+ closest = this.peers.filter((peer) => {
2447
+ if (peer.id.toString() === id) return peer
2448
+ });
2449
+ if (closest[0]) data = await closest[0].request(node.encoded);
2450
+ }
2451
+ if (data.data) {
2452
+ let proto = protoFor(Buffer.from(data.data));
2453
+ proto = protoFor(proto.decoded.data);
2454
+ return proto.decoded.data
2455
+ }
2456
+
2457
+ // this.put(hash, proto.decoded.data)
2458
+ }
2459
+ return null
2460
+ }
2461
+
2462
+
2463
+ get message() {
2464
+ return {
2465
+ /**
2466
+ * Get content for given message hash
2467
+ *
2468
+ * @param {String} hash
2469
+ */
2470
+ get: async (hash) => {
2471
+ debug(`get message ${hash}`);
2472
+ const message = await messageStore.has(hash);
2473
+ if (message) return await messageStore.get(hash)
2474
+ return this.requestData(hash, 'message')
2475
+ },
2476
+ /**
2477
+ * put message content
2478
+ *
2479
+ * @param {String} hash
2480
+ * @param {Buffer} message
2481
+ */
2482
+ put: async (hash, message) => await messageStore.put(hash, message),
2483
+ /**
2484
+ * @param {String} hash
2485
+ * @return {Boolean}
2486
+ */
2487
+ has: async (hash) => await messageStore.has(hash),
2488
+ }
2489
+ }
2490
+
2491
+ get data() {
2492
+ return {
2493
+ /**
2494
+ * Get content for given data hash
2495
+ *
2496
+ * @param {String} hash
2497
+ */
2498
+ get: async (hash) => {
2499
+ debug(`get data ${hash}`);
2500
+ const data = await dataStore.has(hash);
2501
+ if (data) return await dataStore.get(hash)
2502
+ return this.requestData(hash, 'data')
2503
+ },
2504
+ /**
2505
+ * put data content
2506
+ *
2507
+ * @param {String} hash
2508
+ * @param {Buffer} data
2509
+ */
2510
+ put: async (hash, data) => await dataStore.put(hash, data),
2511
+ /**
2512
+ * @param {String} hash
2513
+ * @return {Boolean}
2514
+ */
2515
+ has: async (hash) => await dataStore.has(hash),
2516
+ }
2517
+ }
2518
+
2519
+ /**
2520
+ * goes trough given stores and tries to find data for given hash
2521
+ * @param {Array} stores
2522
+ * @param {string} hash
2523
+ */
2524
+ async whichStore(stores, hash) {
2525
+ let store = stores.pop();
2526
+ store = globalThis[`${store}Store`];
2527
+ if (store) {
2528
+ const has = await store.has(hash);
2529
+ if (has) return store
2530
+ if (stores.length > 0) return this.whichStore(stores, hash)
2531
+ } else return null
2532
+ }
2533
+
2534
+ /**
2535
+ * Get content for given hash
2536
+ *
2537
+ * @param {String} hash
2538
+ */
2539
+ async get(hash, store) {
2540
+ debug(`get ${hash}`);
2541
+ let data;
2542
+ if (store) store = globalThis[`${store}Store`];
2543
+ if (!store) store = await this.whichStore([...this.stores], hash);
2544
+ if (store && await store.has(hash)) data = await store.get(hash);
2545
+ if (data) return data
2546
+
2547
+ return this.requestData(hash, 'data')
2548
+ }
2549
+
2550
+ /**
2551
+ * put content
2552
+ *
2553
+ * @param {String} hash
2554
+ * @param {Buffer} data
2555
+ */
2556
+ async put(hash, data, store = 'data') {
2557
+ store = globalThis[`${store}Store`];
2558
+ return await store.put(hash, data)
2559
+ }
2560
+
2561
+ /**
2562
+ * @param {String} hash
2563
+ * @return {Boolean}
2564
+ */
2565
+ async has(hash) {
2566
+ const store = await this.whichStore([...this.stores], hash);
2567
+ if (store) {
2568
+ if (store.private) return false
2569
+ else return true
2570
+ }
2571
+ return false
2572
+ }
2573
+
2574
+ /**
2575
+ *
2576
+ * @param {String} topic
2577
+ * @param {String|Object|Array|Boolean|Buffer} data
2578
+ */
2579
+ async publish(topic, data) {
2580
+ // globalSub.publish(topic, data)
2581
+ if (!Buffer.isBuffer(topic)) topic = Buffer.from(topic);
2582
+ if (!Buffer.isBuffer(data)) data = Buffer.from(data);
2583
+ const id = Math.random().toString(36).slice(-12);
2584
+ data = new PsMessage({data, topic});
2585
+ for (const peer of this.peers) {
2586
+ if (peer.connection._connected) {
2587
+ if (peer.id.toString() !== this.peerId.toString()) {
2588
+ const node = await this.prepareMessage(peer.id, data.encoded);
2589
+ peer.write(Buffer.from(JSON.stringify({id, data: node.encoded})));
2590
+ }
2591
+ } else {
2592
+ this.removePeer(peer);
2593
+ }
2594
+ // TODO: if peer subscribed
2595
+ }
2596
+ }
2597
+
2598
+ createHash(data, name) {
2599
+ return new PeernetHash(data, {name})
2600
+ }
2601
+
2602
+ /**
2603
+ *
2604
+ * @param {String} topic
2605
+ * @param {Method} cb
2606
+ */
2607
+ async subscribe(topic, cb) {
2608
+ // TODO: if peer subscribed
2609
+ globalSub.subscribe(topic, cb);
2610
+ }
2611
+
2612
+ async removePeer(peer) {
2613
+ connections.delete(peer.id);
2614
+ }
2615
+
2616
+ get Buffer() {
2617
+ return Buffer
2618
+ }
2619
+ // async block(index) {
2620
+ // const _values = []
2621
+ // for (const peer of this.peers) {
2622
+ // const value = await peer.request({type: 'block', index})
2623
+ // console.log(value);
2624
+ // }
2625
+ //
2626
+ // }
2605
2627
  }
2606
2628
 
2607
2629
  module.exports = Peernet;