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