@leofcoin/peernet 0.9.10 → 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.
@@ -280,7 +280,7 @@ class LeofcoinStorage$1 {
280
280
 
281
281
  }
282
282
 
283
- var version = "0.9.9";
283
+ var version = "0.9.10";
284
284
 
285
285
  var api$1 = {
286
286
  version: ({send}) => send({client: '@peernet/api/http', version}),
@@ -1971,656 +1971,659 @@ const nothingFoundError = (hash) => {
1971
1971
  return new Error(`nothing found for ${hash}`)
1972
1972
  };
1973
1973
 
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
- this._peerHandler.discover(peer);
2153
- peer.on('peernet.data', async (message) => {
2154
- const id = message.id;
2155
- message = new PeernetMessage(Buffer.from(message.data.data));
2156
- const proto = protoFor(message.decoded.data);
2157
- await this._protoHandler({id, proto}, peer);
2158
- const fulldId = this._getPeerId(peer.id);
2159
- if (fulldId && this._discovered.indexOf(peer.id) === -1) {
2160
- this._discovered.push(peer.id);
2161
- pubsub.publish('peer:connected', peer);
2162
- }
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
- return this
2197
- }
2198
-
2199
- _getPeerId(id) {
2200
- for (const entry of [...this.peerMap.entries()]) {
2201
- for (const _id of entry[1]) {
2202
- if (_id === id) return entry[0]
2203
- }
2204
- }
2205
- }
2206
-
2207
- addRequestHandler(name, method) {
2208
- this.requestProtos[name] = method;
2209
- }
2210
-
2211
- /**
2212
- * @private
2213
- *
2214
- * @param {Buffer} message - peernet message
2215
- * @param {PeernetPeer} peer - peernet peer
2216
- */
2217
- async _protoHandler(message, peer) {
2218
- const {id, proto} = message;
2219
- if (proto.name === 'peernet-peer') {
2220
- const from = proto.decoded.id;
2221
- if (!this.peerMap.has(from)) this.peerMap.set(from, [peer.id]);
2222
- else {
2223
- const connections = this.peerMap.get(from);
2224
- if (connections.indexOf(peer.id) === -1) {
2225
- connections.push(peer.id);
2226
- this.peerMap.set(from, connections);
2227
- }
2228
- }
2229
- const data = new PeerMessageResponse({id: this.id});
2230
- const node = await this.prepareMessage(from, data.encoded);
2231
-
2232
- peer.write(Buffer.from(JSON.stringify({id, data: node.encoded})));
2233
- } else if (proto.name === 'peernet-peer-response') {
2234
- const from = proto.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
- } else {
2244
- let from = this._getPeerId(peer.id);
2245
- if (!from) {
2246
- const data = new PeerMessage({id: this.id});
2247
- const node = await this.prepareMessage(peer.id, data.encoded);
2248
-
2249
- let response = await peer.request(node.encoded);
2250
- response = protoFor(response);
2251
- response = new PeerMessageResponse(response.decoded.data);
2252
-
2253
- from = response.decoded.id;
2254
- if (!this.peerMap.has(from)) this.peerMap.set(from, [peer.id]);
2255
- else {
2256
- const connections = this.peerMap.get(from);
2257
- if (connections.indexOf(peer.id) === -1) {
2258
- connections.push(peer.id);
2259
- this.peerMap.set(from, connections);
2260
- }
2261
- }
2262
- }
2263
- if (proto.name === 'peernet-dht') {
2264
- let { hash, store } = proto.decoded;
2265
- let has;
2266
-
2267
- if (!store) {
2268
- has = await this.has(hash);
2269
- } else {
2270
- store = globalThis[`${store}Store`];
2271
- if (store.private) has = false;
2272
- else has = await store.has(hash);
2273
- }
2274
- const data = new DHTMessageResponse({hash, has});
2275
- const node = await this.prepareMessage(from, data.encoded);
2276
-
2277
- peer.write(Buffer.from(JSON.stringify({id, data: node.encoded})));
2278
- } else if (proto.name === 'peernet-data') {
2279
- let { hash, store } = proto.decoded;
2280
- let data;
2281
-
2282
- if (!store) {
2283
- data = await this.get(hash);
2284
- } else {
2285
- store = globalThis[`${store}Store`];
2286
- if (store.private) {
2287
- // TODO: ban
2288
- return
2289
- } else data = await store.get(hash);
2290
- }
2291
-
2292
- if (data) {
2293
- data = new DataMessageResponse({hash, data: data.decoded ? Buffer.from(JSON.stringify(data)) : Buffer.from(data)});
2294
-
2295
- const node = await this.prepareMessage(from, data.encoded);
2296
- peer.write(Buffer.from(JSON.stringify({id, data: node.encoded})));
2297
- }
2298
- } else if (proto.name === 'peernet-peer') {
2299
- const from = proto.decoded.id;
2300
- if (!this.peerMap.has(from)) this.peerMap.set(from, [peer.id]);
2301
- else {
2302
- const connections = this.peerMap.get(from);
2303
- connections.push(peer.id);
2304
- this.peerMap.set(from, connections);
2305
- }
2306
- const data = new PeerMessage({id: this.id});
2307
- const node = await this.prepareMessage(from, data.encoded);
2308
-
2309
- peer.write(Buffer.from(JSON.stringify({id, data: node.encoded})));
2310
- } else if (proto.name === 'peernet-request') {
2311
- // TODO: make dynamic
2312
- // exposeddevapi[proto.decoded.request](proto.decoded.params)
2313
- const method = this.requestProtos[proto.decoded.request];
2314
- if (method) {
2315
- const data = await method();
2316
- const node = await this.prepareMessage(from, data.encoded);
2317
- peer.write(Buffer.from(JSON.stringify({id, data: node.encoded})));
2318
- }
2319
- } else if (proto.name === 'peernet-ps' &&
2320
- this._getPeerId(peer.id) !== this.id.toString()) {
2321
- globalSub.publish(proto.decoded.topic.toString(), proto.decoded.data.toString());
2322
- }
2323
- }
2324
- }
2325
-
2326
- /**
2327
- * performs a walk and resolves first encounter
2328
- *
2329
- * @param {String} hash
2330
- */
2331
- async walk(hash) {
2332
- if (!hash) throw new Error('hash expected, received undefined')
2333
- const data = new DHTMessage({hash});
2334
- this.client.id;
2335
- for (const peer of this.peers) {
2336
- const node = await this.prepareMessage(peer.id, data.encoded);
2337
-
2338
- const result = await peer.request(node.encoded);
2339
-
2340
- let proto = protoFor(result.data);
2341
-
2342
- if (proto.name !== 'peernet-message') throw encapsulatedError()
2343
- const from = proto.decoded.from;
2344
- proto = protoFor(proto.decoded.data);
2345
-
2346
- if (proto.name !== 'peernet-dht-response') throw dhtError(proto.name)
2347
-
2348
- // TODO: give ip and port (just used for location)
2349
- if (!peer.connection.remoteAddress || !peer.connection.localAddress) {
2350
- peer.connection.remoteFamily = 'ipv4';
2351
- peer.connection.remoteAddress = '127.0.0.1';
2352
- peer.connection.remotePort = '0000';
2353
- }
2354
-
2355
- const peerInfo = {
2356
- family: peer.connection.remoteFamily || peer.connection.localFamily,
2357
- address: peer.connection.remoteAddress || peer.connection.localAddress,
2358
- port: peer.connection.remotePort || peer.connection.localPort,
2359
- id: from,
2360
- };
2361
-
2362
- if (proto.decoded.has) this.dht.addProvider(peerInfo, proto.decoded.hash);
2363
- }
2364
- return
2365
- }
2366
-
2367
- /**
2368
- * Override DHT behavior, try's finding the content three times
2369
- *
2370
- * @param {String} hash
2371
- */
2372
- async providersFor(hash) {
2373
- let providers = await this.dht.providersFor(hash);
2374
- // walk the network to find a provider
2375
- if (!providers || providers.length === 0) {
2376
- await this.walk(hash);
2377
- providers = await this.dht.providersFor(hash);
2378
- // second walk the network to find a provider
2379
- if (!providers || providers.length === 0) {
2380
- await this.walk(hash);
2381
- providers = await this.dht.providersFor(hash);
2382
- }
2383
- // last walk
2384
- if (!providers || providers.length === 0) {
2385
- await this.walk(hash);
2386
- providers = await this.dht.providersFor(hash);
2387
- }
2388
- }
2389
- // undefined if no providers given
2390
- return providers
2391
- }
2392
-
2393
- get block() {
2394
- return {
2395
- get: async (hash) => {
2396
- const data = await blockStore.has(hash);
2397
- if (data) return await blockStore.get(hash)
2398
- return this.requestData(hash)
2399
- },
2400
- put: async (hash, data) => {
2401
- if (await blockStore.has(hash)) return
2402
- return await blockStore.put(hash, data)
2403
- },
2404
- has: async (hash) => await blockStore.has(hash, 'block'),
2405
- }
2406
- }
2407
-
2408
- get transaction() {
2409
- return {
2410
- get: async (hash) => {
2411
- const data = await transactionStore.has(hash);
2412
- if (data) return await transactionStore.get(hash)
2413
- return this.requestData(hash, 'transaction')
2414
- },
2415
- put: async (hash, data) => {
2416
- if (await transactionStore.has(hash)) return
2417
- return await transactionStore.put(hash, data)
2418
- },
2419
- has: async (hash) => await transactionStore.has(hash),
2420
- }
2421
- }
2422
-
2423
- async requestData(hash, store) {
2424
- const providers = await this.providersFor(hash);
2425
- if (!providers || providers.size === 0) throw nothingFoundError(hash)
2426
- debug(`found ${providers.size} provider(s) for ${hash}`);
2427
- // get closest peer on earth
2428
- const closestPeer = await this.dht.closestPeer(providers);
2429
- // get peer instance by id
2430
- if (!closestPeer || !closestPeer.id) return this.requestData(hash, store)
2431
-
2432
- const id = closestPeer.id.toString();
2433
- if (this.peers) {
2434
- let closest = this.peers.filter((peer) => {
2435
- if (this._getPeerId(peer.id) === id) return peer
2436
- });
2437
-
2438
- let data = new DataMessage({hash, store});
2439
-
2440
- const node = await this.prepareMessage(id, data.encoded);
2441
- if (closest[0]) data = await closest[0].request(node.encoded);
2442
- else {
2443
- closest = this.peers.filter((peer) => {
2444
- if (peer.id.toString() === id) return peer
2445
- });
2446
- if (closest[0]) data = await closest[0].request(node.encoded);
2447
- }
2448
- if (data.data) {
2449
- let proto = protoFor(Buffer.from(data.data));
2450
- proto = protoFor(proto.decoded.data);
2451
- return proto.decoded.data
2452
- }
2453
-
2454
- // this.put(hash, proto.decoded.data)
2455
- }
2456
- return null
2457
- }
2458
-
2459
-
2460
- get message() {
2461
- return {
2462
- /**
2463
- * Get content for given message hash
2464
- *
2465
- * @param {String} hash
2466
- */
2467
- get: async (hash) => {
2468
- debug(`get message ${hash}`);
2469
- const message = await messageStore.has(hash);
2470
- if (message) return await messageStore.get(hash)
2471
- return this.requestData(hash, 'message')
2472
- },
2473
- /**
2474
- * put message content
2475
- *
2476
- * @param {String} hash
2477
- * @param {Buffer} message
2478
- */
2479
- put: async (hash, message) => await messageStore.put(hash, message),
2480
- /**
2481
- * @param {String} hash
2482
- * @return {Boolean}
2483
- */
2484
- has: async (hash) => await messageStore.has(hash),
2485
- }
2486
- }
2487
-
2488
- get data() {
2489
- return {
2490
- /**
2491
- * Get content for given data hash
2492
- *
2493
- * @param {String} hash
2494
- */
2495
- get: async (hash) => {
2496
- debug(`get data ${hash}`);
2497
- const data = await dataStore.has(hash);
2498
- if (data) return await dataStore.get(hash)
2499
- return this.requestData(hash, 'data')
2500
- },
2501
- /**
2502
- * put data content
2503
- *
2504
- * @param {String} hash
2505
- * @param {Buffer} data
2506
- */
2507
- put: async (hash, data) => await dataStore.put(hash, data),
2508
- /**
2509
- * @param {String} hash
2510
- * @return {Boolean}
2511
- */
2512
- has: async (hash) => await dataStore.has(hash),
2513
- }
2514
- }
2515
-
2516
- /**
2517
- * goes trough given stores and tries to find data for given hash
2518
- * @param {Array} stores
2519
- * @param {string} hash
2520
- */
2521
- async whichStore(stores, hash) {
2522
- let store = stores.pop();
2523
- store = globalThis[`${store}Store`];
2524
- if (store) {
2525
- const has = await store.has(hash);
2526
- if (has) return store
2527
- if (stores.length > 0) return this.whichStore(stores, hash)
2528
- } else return null
2529
- }
2530
-
2531
- /**
2532
- * Get content for given hash
2533
- *
2534
- * @param {String} hash
2535
- */
2536
- async get(hash, store) {
2537
- debug(`get ${hash}`);
2538
- let data;
2539
- if (store) store = globalThis[`${store}Store`];
2540
- if (!store) store = await this.whichStore([...this.stores], hash);
2541
- if (store && await store.has(hash)) data = await store.get(hash);
2542
- if (data) return data
2543
-
2544
- return this.requestData(hash, 'data')
2545
- }
2546
-
2547
- /**
2548
- * put content
2549
- *
2550
- * @param {String} hash
2551
- * @param {Buffer} data
2552
- */
2553
- async put(hash, data, store = 'data') {
2554
- store = globalThis[`${store}Store`];
2555
- return await store.put(hash, data)
2556
- }
2557
-
2558
- /**
2559
- * @param {String} hash
2560
- * @return {Boolean}
2561
- */
2562
- async has(hash) {
2563
- const store = await this.whichStore([...this.stores], hash);
2564
- if (store) {
2565
- if (store.private) return false
2566
- else return true
2567
- }
2568
- return false
2569
- }
2570
-
2571
- /**
2572
- *
2573
- * @param {String} topic
2574
- * @param {String|Object|Array|Boolean|Buffer} data
2575
- */
2576
- async publish(topic, data) {
2577
- // globalSub.publish(topic, data)
2578
- if (!Buffer.isBuffer(topic)) topic = Buffer.from(topic);
2579
- if (!Buffer.isBuffer(data)) data = Buffer.from(data);
2580
- const id = Math.random().toString(36).slice(-12);
2581
- data = new PsMessage({data, topic});
2582
- for (const peer of this.peers) {
2583
- if (peer.connection._connected) {
2584
- if (peer.id.toString() !== this.peerId.toString()) {
2585
- const node = await this.prepareMessage(peer.id, data.encoded);
2586
- peer.write(Buffer.from(JSON.stringify({id, data: node.encoded})));
2587
- }
2588
- } else {
2589
- this.removePeer(peer);
2590
- }
2591
- // TODO: if peer subscribed
2592
- }
2593
- }
2594
-
2595
- createHash(data, name) {
2596
- return new PeernetHash(data, {name})
2597
- }
2598
-
2599
- /**
2600
- *
2601
- * @param {String} topic
2602
- * @param {Method} cb
2603
- */
2604
- async subscribe(topic, cb) {
2605
- // TODO: if peer subscribed
2606
- globalSub.subscribe(topic, cb);
2607
- }
2608
-
2609
- async removePeer(peer) {
2610
- connections.delete(peer.id);
2611
- }
2612
-
2613
- get Buffer() {
2614
- return Buffer
2615
- }
2616
- // async block(index) {
2617
- // const _values = []
2618
- // for (const peer of this.peers) {
2619
- // const value = await peer.request({type: 'block', index})
2620
- // console.log(value);
2621
- // }
2622
- //
2623
- // }
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
+ // }
2624
2627
  }
2625
2628
 
2626
2629
  module.exports = Peernet;