@leofcoin/peernet 0.9.2 → 0.9.5

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