@leofcoin/peernet 0.11.12 → 0.11.15

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.
@@ -6,20 +6,16 @@ import bs58 from '@vandeurenglenn/base58';
6
6
  import isHex from '@vandeurenglenn/is-hex';
7
7
  import varint from 'varint';
8
8
  import createKeccakHash from 'keccak';
9
- import fetch from 'node-fetch';
10
9
  import generateAccount from '@leofcoin/generate-account';
11
10
  import * as bs58check from 'bs58check';
12
11
  import bs58check__default from 'bs58check';
13
- import { generateMnemonic, mnemonicToSeed } from 'bip39';
14
12
  import * as bip32 from 'bip32';
15
- import { publicKeyConvert } from 'secp256k1';
16
13
  import ecc from 'tiny-secp256k1';
14
+ import Mnemonic from '@leofcoin/mnemonic';
17
15
  import MultiSignature from 'multi-signature';
18
- import AES from 'crypto-js/aes.js';
19
- import 'crypto-js/sha512.js';
20
- import ENC from 'crypto-js/enc-utf8.js';
16
+ import randombytes from 'randombytes';
21
17
 
22
- /* socket-request-client version 1.6.1 */
18
+ /* socket-request-client version 1.6.3 */
23
19
 
24
20
  class LittlePubSub {
25
21
  constructor(verbose = true) {
@@ -206,9 +202,6 @@ const socketRequestClient = (url, protocols = 'echo-protocol', options = { retry
206
202
  peernet: api.peernet(client),
207
203
  server: api.server(client),
208
204
  close: exit => {
209
- client.onclose = message => {
210
- if (exit) process.exit();
211
- };
212
205
  client.close();
213
206
  }
214
207
  }
@@ -275,6 +268,10 @@ class Peer {
275
268
  return this.#connected
276
269
  }
277
270
 
271
+ get readyState() {
272
+ return this.channel?.readyState
273
+ }
274
+
278
275
  /**
279
276
  * @params {Object} options
280
277
  * @params {string} options.channelName - this peerid : otherpeer id
@@ -314,8 +311,19 @@ constructor(options = {}) {
314
311
  }
315
312
 
316
313
  send(message) {
317
- this.bw.up += message.length || message.byteLength;
318
- this.channel.send(message);
314
+ switch (this.channel?.readyState) {
315
+ case 'open':
316
+ this.bw.up += message.length || message.byteLength;
317
+ this.channel.send(message);
318
+ break;
319
+ case 'closed':
320
+ case 'closing':
321
+ debug('channel already closed, this usually means a bad implementation, try checking the readyState or check if the peer is connected before sending');
322
+ break;
323
+ case undefined:
324
+ debug(`trying to send before a channel is created`);
325
+ break;
326
+ }
319
327
  }
320
328
 
321
329
  request(data) {
@@ -388,7 +396,6 @@ constructor(options = {}) {
388
396
  this.channel.onmessage = (message) => {
389
397
  pubsub.publish('peer:data', message);
390
398
  debug(`incoming message from ${this.peerId}`);
391
- debug(message);
392
399
  this.bw.down += message.length || message.byteLength;
393
400
  };
394
401
 
@@ -448,6 +455,7 @@ constructor(options = {}) {
448
455
 
449
456
  close() {
450
457
  debug(`closing ${this.peerId}`);
458
+ this.#connected = false;
451
459
  this.channel?.close();
452
460
  this.#connection?.close();
453
461
 
@@ -464,6 +472,10 @@ class Client {
464
472
  return { ...this.#connections }
465
473
  }
466
474
 
475
+ get peers() {
476
+ return Object.entries(this.#connections)
477
+ }
478
+
467
479
  constructor(id, identifiers = ['peernet-v0.1.0'], stars = []) {
468
480
  this.id = id || Math.random().toString(36).slice(-12);
469
481
  if (!Array.isArray(identifiers)) identifiers = [identifiers];
@@ -578,6 +590,15 @@ class Client {
578
590
  debug(`peer ${id} joined`);
579
591
  }
580
592
 
593
+ removePeer(peer) {
594
+ const id = peer.peerId || peer;
595
+ if (this.#connections[id]) {
596
+ this.#connections[id].connected && this.#connections[id].close();
597
+ delete this.#connections[id];
598
+ }
599
+ debug(`peer ${id} removed`);
600
+ }
601
+
581
602
 
582
603
  }
583
604
 
@@ -984,14 +1005,14 @@ class FormatInterface {
984
1005
  this.protoDecode = proto.decode;
985
1006
  this.hashFormat = options.hashFormat || 'bs32';
986
1007
  if (options.name) this.name = options.name;
987
- if (buffer instanceof Uint8Array) return this.fromUint8Array(buffer)
988
- else if (buffer instanceof ArrayBuffer) return this.fromArrayBuffer(buffer)
1008
+ if (buffer instanceof Uint8Array) this.fromUint8Array(buffer);
1009
+ else if (buffer instanceof ArrayBuffer) this.fromArrayBuffer(buffer);
989
1010
  else if (buffer.name === options.name) return buffer
990
- else if (typeof buffer === 'string') {
991
- if (isHex(buffer)) this.fromHex(buffer);
992
- else if (bs32.isBase32(buffer)) this.fromBs32(buffer);
993
- else if (bs58.isBase58(buffer)) this.fromBs58(buffer);
994
- else throw new Error(`unsupported string ${buffer}`)
1011
+ else if (buffer instanceof String) {
1012
+ if (isHex(buffer)) this.fromHex(buffer);
1013
+ else if (bs32.isBase32(buffer)) this.fromBs32(buffer);
1014
+ else if (bs58.isBase58(buffer)) this.fromBs58(buffer);
1015
+ else throw new Error(`unsupported string ${buffer}`)
995
1016
  } else {
996
1017
  this.create(buffer);
997
1018
  }
@@ -1677,6 +1698,7 @@ const bitcoin = {
1677
1698
  messagePrefix: '\x18Bitcoin Signed Message:\n',
1678
1699
  bech32: 'bc',
1679
1700
  pubKeyHash: 0x00,
1701
+ multiCodec: 0x00,
1680
1702
  scriptHash: 0x05,
1681
1703
  wif: 0x80,
1682
1704
  coin_type: 0,
@@ -1725,12 +1747,15 @@ const fromNetworkString = network => {
1725
1747
  network = networks[parts[0]];
1726
1748
  if (parts[1]) {
1727
1749
  if (network[parts[1]]) network = network[parts[1]];
1728
-
1750
+
1729
1751
  network.coin_type = 1;
1730
1752
  }
1731
1753
  return network;
1732
1754
  };
1733
1755
 
1756
+ // import { createHash } from 'crypto'
1757
+ // import { createHash as _createHash } from './hash'
1758
+
1734
1759
  const { encode: encode$1, decode: decode$1 } = bs58check__default;
1735
1760
  class HDWallet {
1736
1761
 
@@ -1758,20 +1783,48 @@ class HDWallet {
1758
1783
  return this.ifNotLocked(() => this.publicKeyBuffer.toString('hex'))
1759
1784
  }
1760
1785
 
1786
+ get ethereumAddress() {
1787
+ const buffer = ecc.pointFromScalar(this.hdnode.__D, false);
1788
+ let hash = createKeccakHash('keccak256').update(buffer.slice(1)).digest();
1789
+ return `0x${hash.slice(-20).toString('hex')}`
1790
+ }
1791
+
1792
+ // async bitcoinAddress() {
1793
+ // const chainCode = this.privateKeyBuffer
1794
+ //
1795
+ // const node = bip32.fromPrivateKey(this.privateKeyBuffer, chainCode, networks['bitcoin'])
1796
+ // let buffer = await _createHash(node.publicKey, 'SHA-256')
1797
+ // buffer = createHash('ripemd160').update(buffer).digest()
1798
+ // // buffer = Buffer.from(`0x00${buffer.toString('hex')}`, 'hex')
1799
+ // // buffer = createHash('sha256').update(buffer).digest()
1800
+ // // const mainHash = buffer
1801
+ // // buffer = createHash('sha256').update(buffer).digest()
1802
+ // // const checksum = buffer.toString('hex').substring(0, 8)
1803
+ // // return base58.encode(Buffer.concat([mainHash, Buffer.from(checksum, 'hex')]))
1804
+ // const payload = Buffer.allocUnsafe(21)
1805
+ // payload.writeUInt8(networks['bitcoin'].pubKeyHash, 0)
1806
+ // buffer.copy(payload, 1)
1807
+ //
1808
+ // return encode(payload)
1809
+ // }
1810
+
1811
+ get leofcoinAddress() {
1812
+ return encode$1(this.neutered.publicKeyBuffer)
1813
+ }
1814
+
1761
1815
  get address() {
1762
- // override testnet coin_type
1763
- let coin_type = this.hdnode.network.coin_type;
1816
+ return this.getAddressForCoin()
1817
+ }
1818
+
1819
+ getAddressForCoin(coin_type) {
1820
+ if (!coin_type) coin_type = this.hdnode.network.coin_type;
1764
1821
  if (coin_type === 1) {
1765
1822
  if (this.networkName?.split(':')[0] === 'ethereum') coin_type = 60;
1766
1823
  if (this.networkName?.split(':')[0] === 'leofcoin') coin_type = 640;
1767
1824
  }
1768
- if (coin_type === 60 || coin_type === 640) {
1769
- let buffer = ecc.pointFromScalar(this.hdnode.__D, false);
1770
- buffer = Buffer.from(publicKeyConvert(buffer, false)).slice(1);
1771
- let hash = createKeccakHash('keccak256').update(buffer).digest();
1772
- return hash.slice(-20).toString('hex')
1773
- }
1774
- return encode$1(this.neutered.publicKeyBuffer)
1825
+ // if (coin_type === 0) return this.bitcoinAddress
1826
+ if (coin_type === 60) return this.ethereumAddress
1827
+ if (coin_type === 640) return this.leofcoinAddress
1775
1828
  }
1776
1829
 
1777
1830
  get accountAddress() {
@@ -1818,10 +1871,10 @@ class HDWallet {
1818
1871
 
1819
1872
  async generate(password, network) {
1820
1873
  network = this.validateNetwork(network);
1821
- const mnemonic = generateMnemonic(256);
1822
- const seed = await mnemonicToSeed(mnemonic, password);
1874
+ const mnemonic = new Mnemonic().generate();
1875
+ const seed = new Mnemonic().seedFromMnemonic(mnemonic, password);
1823
1876
  this.defineHDNode(bip32.fromSeed(seed, network));
1824
- return mnemonic; // userpw
1877
+ return mnemonic;
1825
1878
  }
1826
1879
 
1827
1880
  /**
@@ -1829,7 +1882,7 @@ class HDWallet {
1829
1882
  */
1830
1883
  async recover(mnemonic, password, network) {
1831
1884
  network = this.validateNetwork(network, password);
1832
- const seed = await mnemonicToSeed(mnemonic);
1885
+ const seed = new Mnemonic().seedFromMnemonic(mnemonic, password);
1833
1886
  this.defineHDNode(bip32.fromSeed(seed, network));
1834
1887
  }
1835
1888
 
@@ -1862,6 +1915,71 @@ class HDWallet {
1862
1915
  }
1863
1916
  }
1864
1917
 
1918
+ const { subtle } = crypto;
1919
+
1920
+ const generateAesKey = async (length = 256) => {
1921
+ const key = await subtle.generateKey({
1922
+ name: 'AES-CBC',
1923
+ length
1924
+ }, true, ['encrypt', 'decrypt']);
1925
+
1926
+ return key;
1927
+ };
1928
+
1929
+ const importAesKey = async (exported, format = 'raw', length = 256) => {
1930
+ return await subtle.importKey(format, exported, {
1931
+ name: 'AES-CBC',
1932
+ length
1933
+ }, true, ['encrypt', 'decrypt'])
1934
+ };
1935
+
1936
+ const exportAesKey = async (key, format = 'raw') => {
1937
+ return await subtle.exportKey(format, key)
1938
+ };
1939
+
1940
+ const encryptAes = async (uint8Array, key, iv) => subtle.encrypt({
1941
+ name: 'AES-CBC',
1942
+ iv,
1943
+ }, key, uint8Array);
1944
+
1945
+ const uint8ArrayToHex = uint8Array =>
1946
+ [...uint8Array].map(x => x.toString(16).padStart(2, '0')).join('');
1947
+
1948
+ const arrayBufferToHex = arrayBuffer =>
1949
+ uint8ArrayToHex(new Uint8Array(arrayBuffer));
1950
+
1951
+ const hexToUint8Array = hex =>
1952
+ new Uint8Array(hex.match(/[\da-f]{2}/gi).map(x => parseInt(x, 16)));
1953
+
1954
+ const encrypt = async string => {
1955
+ const ec = new TextEncoder();
1956
+ const key = await generateAesKey();
1957
+ const iv = await randombytes(16);
1958
+
1959
+ const ciphertext = await encryptAes(ec.encode(string), key, iv);
1960
+ const exported = await exportAesKey(key);
1961
+
1962
+ return {
1963
+ key: arrayBufferToHex(exported),
1964
+ iv: iv.toString('hex'),
1965
+ cipher: arrayBufferToHex(ciphertext)
1966
+ }
1967
+ };
1968
+
1969
+ const decrypt = async (cipher, key, iv) => {
1970
+ if (!key.type) key = await importAesKey(hexToUint8Array(key));
1971
+ cipher = new Uint8Array(hexToUint8Array(cipher));
1972
+ iv = new Uint8Array(hexToUint8Array(iv));
1973
+
1974
+ const dec = new TextDecoder();
1975
+ const plaintext = await subtle.decrypt({
1976
+ name: 'AES-CBC',
1977
+ iv,
1978
+ }, key, cipher);
1979
+
1980
+ return dec.decode(plaintext);
1981
+ };
1982
+
1865
1983
  const { encode, decode } = bs58check;
1866
1984
 
1867
1985
  // TODO: multihash addresses
@@ -1892,9 +2010,7 @@ class HDAccount {
1892
2010
 
1893
2011
  class MultiWallet extends HDWallet {
1894
2012
  constructor(network, hdnode) {
1895
- const networkName = network;
1896
2013
  super(network, hdnode);
1897
- if (typeof networkName === 'string') this.networkName = networkName;
1898
2014
  this.multiCodec = this.network.multiCodec;
1899
2015
  this.version = 0x00;
1900
2016
  }
@@ -1912,7 +2028,7 @@ class MultiWallet extends HDWallet {
1912
2028
  }
1913
2029
 
1914
2030
  get neutered() {
1915
- const neutered = this.ifNotLocked(() => new MultiWallet(this.network, this.hdnode.neutered()));
2031
+ const neutered = this.ifNotLocked(() => new MultiWallet(this.networkName, this.hdnode.neutered()));
1916
2032
  if (neutered) this._neutered = neutered;
1917
2033
  return this._neutered
1918
2034
  }
@@ -1921,18 +2037,19 @@ class MultiWallet extends HDWallet {
1921
2037
  let buffer = decode(id);
1922
2038
  varint.decode(buffer);
1923
2039
  buffer = buffer.slice(varint.decode.bytes);
1924
- this.fromPublicKey(buffer, null, this.network);
2040
+ this.fromPublicKey(buffer, null, this.networkName);
1925
2041
  }
1926
2042
 
1927
- lock(key, multiWIF) {
2043
+ async lock(multiWIF) {
1928
2044
  if (!multiWIF) multiWIF = this.multiWIF;
1929
- this.encrypted = AES.encrypt(multiWIF.toString('hex'), key).toString();
2045
+ this.encrypted = await encrypt(multiWIF.toString('hex'));
1930
2046
  this.locked = true;
2047
+ return this.encrypted
1931
2048
  }
1932
2049
 
1933
- unlock(key, encrypted) {
1934
- if (!encrypted) encrypted = this.encrypted;
1935
- this.import(AES.decrypt(encrypted, key).toString(ENC));
2050
+ async unlock({key, iv, cipher}) {
2051
+ const decrypted = await decrypt(cipher, key, iv);
2052
+ this.import(decrypted);
1936
2053
  this.locked = false;
1937
2054
  }
1938
2055
 
@@ -1952,7 +2069,7 @@ class MultiWallet extends HDWallet {
1952
2069
  else if (c.testnet && c.testnet.multiCodec === multiCodec) return c.testnet
1953
2070
  else return p
1954
2071
  }, networks['leofcoin']);
1955
- this.load(bs58, this.network);
2072
+ this.load(bs58, this.networkName);
1956
2073
  }
1957
2074
 
1958
2075
  /**
@@ -1995,7 +2112,7 @@ class MultiWallet extends HDWallet {
1995
2112
  * @return { internal(addressIndex), external(addressIndex) }
1996
2113
  */
1997
2114
  account(index) {
1998
- return new HDAccount(new MultiWallet(this.network, this.hdnode), index);
2115
+ return new HDAccount(new MultiWallet(this.networkName, this.hdnode), index);
1999
2116
  }
2000
2117
 
2001
2118
  /**
@@ -2004,11 +2121,11 @@ class MultiWallet extends HDWallet {
2004
2121
  * see https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki
2005
2122
  */
2006
2123
  derivePath(path) {
2007
- return new MultiWallet(this.network, this.hdnode.derivePath(path))
2124
+ return new MultiWallet(this.networkName, this.hdnode.derivePath(path))
2008
2125
  }
2009
2126
 
2010
2127
  derive(index) {
2011
- return new MultiWallet(this.network, this.hdnode.derive(index));
2128
+ return new MultiWallet(this.networkName, this.hdnode.derive(index));
2012
2129
  }
2013
2130
  }
2014
2131
 
@@ -2138,7 +2255,7 @@ class Peernet {
2138
2255
  Storage = globalThis.LeofcoinStorage?.default ? globalThis.LeofcoinStorage.default : LeofcoinStorage;
2139
2256
  }
2140
2257
  globalThis[`${name}Store`] = globalThis[`${name}Store`] ||
2141
- await new Storage(`${prefix}-${name}`, root);
2258
+ await new Storage(name, root);
2142
2259
 
2143
2260
  globalThis[`${name}Store`].private = isPrivate;
2144
2261
  if (!isPrivate) this.stores.push(name);
@@ -2169,6 +2286,13 @@ class Peernet {
2169
2286
  return Object.entries(this.client.connections)
2170
2287
  }
2171
2288
 
2289
+ /**
2290
+ * @return {String} id - peerId
2291
+ */
2292
+ getConnection(id) {
2293
+ return this.client.connections[id]
2294
+ }
2295
+
2172
2296
  /**
2173
2297
  * @private
2174
2298
  *
@@ -2224,7 +2348,7 @@ class Peernet {
2224
2348
  const {daemon, environment} = await target();
2225
2349
  this.hasDaemon = daemon;
2226
2350
 
2227
- HTTP_IMPORT;
2351
+
2228
2352
 
2229
2353
  for (const store of this.defaultStores) {
2230
2354
  await this.addStore(store, options.storePrefix, options.root);
@@ -2290,6 +2414,16 @@ class Peernet {
2290
2414
  this.requestProtos[name] = method;
2291
2415
  }
2292
2416
 
2417
+ sendMessage(peer, id, data) {
2418
+ if (peer.readyState === 'open') {
2419
+ peer.send(new TextEncoder().encode(JSON.stringify({id, data})));
2420
+ this.bw.up += data.length;
2421
+ } else if (peer.readyState === 'closed') {
2422
+ this.removePeer(peer);
2423
+ }
2424
+
2425
+ }
2426
+
2293
2427
  /**
2294
2428
  * @private
2295
2429
  *
@@ -2314,8 +2448,7 @@ class Peernet {
2314
2448
  const data = new DHTMessageResponse({hash, has});
2315
2449
  const node = await this.prepareMessage(from, data.encoded);
2316
2450
 
2317
- peer.send(new TextEncoder().encode(JSON.stringify({id, data: node.encoded})));
2318
- this.bw.up += node.encoded.length;
2451
+ sendMessage(peer, id, node.encoded);
2319
2452
  } else if (proto.name === 'peernet-data') {
2320
2453
  let { hash, store } = proto.decoded;
2321
2454
  let data;
@@ -2328,24 +2461,19 @@ class Peernet {
2328
2461
  data = await store.get(hash);
2329
2462
 
2330
2463
  if (data) {
2331
- data = new DataMessageResponse({hash, data: data.decoded ? new TextEncoder().encode(JSON.stringify(data.decoded)) : data});
2464
+ data = new DataMessageResponse({hash, data});
2332
2465
 
2333
2466
  const node = await this.prepareMessage(from, data.encoded);
2334
- peer.send(new TextEncoder().encode(JSON.stringify({id, data: node.encoded})));
2335
- this.bw.up += node.encoded.length;
2467
+ sendMessage(peer, id, node.encoded);
2336
2468
  }
2337
2469
  }
2338
2470
 
2339
2471
  } else if (proto.name === 'peernet-request') {
2340
- // TODO: make dynamic
2341
- // exposeddevapi[proto.decoded.request](proto.decoded.params)
2342
2472
  const method = this.requestProtos[proto.decoded.request];
2343
2473
  if (method) {
2344
2474
  const data = await method();
2345
2475
  const node = await this.prepareMessage(from, data.encoded);
2346
- peer.send(new TextEncoder().encode(JSON.stringify({id, data: node.encoded})));
2347
-
2348
- this.bw.up += node.encoded.length;
2476
+ sendMessage(peer, id, node.encoded);
2349
2477
  }
2350
2478
  } else if (proto.name === 'peernet-ps' && peer.peerId !== this.id) {
2351
2479
  globalSub.publish(new TextDecoder().decode(proto.decoded.topic), proto.decoded.data);
@@ -2615,13 +2743,9 @@ class Peernet {
2615
2743
  const id = Math.random().toString(36).slice(-12);
2616
2744
  data = new PsMessage({data, topic});
2617
2745
  for (const peer of this.connections) {
2618
- if (peer.connected) {
2619
- if (peer.peerId !== this.peerId) {
2620
- const node = await this.prepareMessage(peer.peerId, data.encoded);
2621
- peer.send(new TextEncoder().encode(JSON.stringify({id, data: node.encoded})));
2622
- }
2623
- } else {
2624
- this.removePeer(peer);
2746
+ if (peer.peerId !== this.peerId) {
2747
+ const node = await this.prepareMessage(peer.peerId, data.encoded);
2748
+ sendMessage(peer, id, node.encoded);
2625
2749
  }
2626
2750
  // TODO: if peer subscribed
2627
2751
  }
@@ -2642,7 +2766,7 @@ class Peernet {
2642
2766
  }
2643
2767
 
2644
2768
  async removePeer(peer) {
2645
- delete this.client.connections[peer.peerId];
2769
+ return this.client.removePeer(peer)
2646
2770
  }
2647
2771
 
2648
2772
  get Buffer() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@leofcoin/peernet",
3
- "version": "0.11.12",
3
+ "version": "0.11.15",
4
4
  "description": "",
5
5
  "main": "dist/commonjs/peernet.js",
6
6
  "module": "dist/module/peernet.js",
@@ -25,7 +25,7 @@
25
25
  "dependencies": {
26
26
  "@leofcoin/generate-account": "^1.0.2",
27
27
  "@leofcoin/multi-wallet": "^2.1.2",
28
- "@leofcoin/peernet-swarm": "^0.1.16",
28
+ "@leofcoin/peernet-swarm": "^0.1.17",
29
29
  "@leofcoin/storage": "^2.3.0",
30
30
  "@vandeurenglenn/base32": "^1.1.0",
31
31
  "@vandeurenglenn/base58": "^1.1.0",
@@ -42,15 +42,10 @@
42
42
  },
43
43
  "devDependencies": {
44
44
  "@babel/plugin-proposal-private-methods": "^7.16.11",
45
- "@rollup/plugin-commonjs": "^19.0.1",
46
45
  "@rollup/plugin-eslint": "^8.0.1",
47
46
  "@rollup/plugin-json": "^4.1.0",
48
- "@rollup/plugin-node-resolve": "^13.0.4",
49
47
  "@vandeurenglenn/debug": "^1.0.0",
50
48
  "coveralls": "^3.1.1",
51
- "esdoc": "^1.1.0",
52
- "esdoc-ecmascript-proposal-plugin": "^1.0.0",
53
- "esdoc-standard-plugin": "^1.0.0",
54
49
  "eslint": "^7.31.0",
55
50
  "eslint-config-google": "^0.14.0",
56
51
  "nyc": "^15.1.0",
@@ -58,10 +53,8 @@
58
53
  "path-browserify": "^1.0.1",
59
54
  "rollup": "^2.70.2",
60
55
  "rollup-plugin-modify": "^3.0.0",
61
- "rollup-plugin-natives": "^0.7.5",
62
- "rollup-plugin-node-globals": "^1.4.0",
63
- "rollup-plugin-node-polyfills": "^0.2.1",
64
56
  "tape": "^5.2.2",
57
+ "vm-browserify": "^1.1.2",
65
58
  "webpack": "^5.72.0",
66
59
  "webpack-cli": "^4.9.2",
67
60
  "webpack-node-externals": "^3.0.0"
package/rollup.config.js CHANGED
@@ -1,11 +1,7 @@
1
1
  import { execSync } from 'child_process';
2
2
  import lint from '@rollup/plugin-eslint'
3
- import resolve from '@rollup/plugin-node-resolve'
4
- import cjs from '@rollup/plugin-commonjs'
5
3
  import json from '@rollup/plugin-json'
6
4
  import modify from 'rollup-plugin-modify'
7
- import nativePlugin from 'rollup-plugin-natives';
8
- import polyfills from 'rollup-plugin-node-polyfills'
9
5
 
10
6
  try {
11
7
  execSync('rm dist -r')
@@ -31,7 +27,8 @@ export default [{
31
27
  } else {
32
28
  const http = await import('./http/http.js')
33
29
  if (environment !== 'browser') http.default(options)
34
- }`
30
+ }`,
31
+ SUBTLE_IMPORT: `const { subtle } = require('crypto').webcrypto`
35
32
  })
36
33
  ]
37
34
  }, {
@@ -44,25 +41,13 @@ export default [{
44
41
  json(),
45
42
  modify({
46
43
  "import fetch from 'node-fetch'": '',
47
- HTTP_IMPORT: ``
44
+ HTTP_IMPORT: ``,
45
+ SUBTLE_IMPORT: `const { subtle } = crypto`
48
46
  }),
49
- // nativePlugin(),
50
- // polyfills(),
51
- // resolve({
52
- // preferBuiltins: true,
53
- // mainFields: ["browser", "module", "main"],
54
- // extensions: ['.mjs', '.js', '.json']
55
- // }),
56
- // cjs({
57
- // exclude: ['*.node'],
58
- // extensions: ['.js']
59
- // }),
60
47
  // lint({
61
48
  // fix: true,
62
49
  // exclude: ['package.json', "package-lock.json"]
63
50
  // })
64
-
65
-
66
51
  ]
67
52
  }, {
68
53
  input: 'src/peernet.js',
@@ -71,6 +56,11 @@ export default [{
71
56
  format: 'es'
72
57
  },
73
58
  plugins: [
74
- json()
59
+ json(),
60
+ modify({
61
+ "import fetch from 'node-fetch'": '',
62
+ HTTP_IMPORT: ``,
63
+ SUBTLE_IMPORT: `const { subtle } = crypto`
64
+ }),
75
65
  ]
76
66
  }]
@@ -15,14 +15,14 @@ export default class FormatInterface {
15
15
  this.protoDecode = proto.decode
16
16
  this.hashFormat = options.hashFormat || 'bs32'
17
17
  if (options.name) this.name = options.name
18
- if (buffer instanceof Uint8Array) return this.fromUint8Array(buffer)
19
- else if (buffer instanceof ArrayBuffer) return this.fromArrayBuffer(buffer)
18
+ if (buffer instanceof Uint8Array) this.fromUint8Array(buffer)
19
+ else if (buffer instanceof ArrayBuffer) this.fromArrayBuffer(buffer)
20
20
  else if (buffer.name === options.name) return buffer
21
- else if (typeof buffer === 'string') {
22
- if (isHex(buffer)) this.fromHex(buffer)
23
- else if (bs32.isBase32(buffer)) this.fromBs32(buffer)
24
- else if (bs58.isBase58(buffer)) this.fromBs58(buffer)
25
- else throw new Error(`unsupported string ${buffer}`)
21
+ else if (buffer instanceof String) {
22
+ if (isHex(buffer)) this.fromHex(buffer)
23
+ else if (bs32.isBase32(buffer)) this.fromBs32(buffer)
24
+ else if (bs58.isBase58(buffer)) this.fromBs58(buffer)
25
+ else throw new Error(`unsupported string ${buffer}`)
26
26
  } else {
27
27
  this.create(buffer)
28
28
  }