|
| 1 | +'use strict' |
| 2 | + |
| 3 | +const TCP = require('libp2p-tcp') |
| 4 | +const MulticastDNS = require('libp2p-mdns') |
| 5 | +const WS = require('libp2p-websockets') |
| 6 | +const Railing = require('libp2p-railing') |
| 7 | +const spdy = require('libp2p-spdy') |
| 8 | +const KadDHT = require('libp2p-kad-dht') |
| 9 | +const multiplex = require('libp2p-multiplex') |
| 10 | +const secio = require('libp2p-secio') |
| 11 | +const libp2p = require('libp2p') |
| 12 | + |
| 13 | +function mapMuxers (list) { |
| 14 | + return list.map((pref) => { |
| 15 | + if (typeof pref !== 'string') { |
| 16 | + return pref |
| 17 | + } |
| 18 | + switch (pref.trim().toLowerCase()) { |
| 19 | + case 'spdy': return spdy |
| 20 | + case 'multiplex': return multiplex |
| 21 | + default: |
| 22 | + throw new Error(pref + ' muxer not available') |
| 23 | + } |
| 24 | + }) |
| 25 | +} |
| 26 | + |
| 27 | +function getMuxers (muxers) { |
| 28 | + const muxerPrefs = process.env.LIBP2P_MUXER |
| 29 | + if (muxerPrefs && !muxers) { |
| 30 | + return mapMuxers(muxerPrefs.split(',')) |
| 31 | + } else if (muxers) { |
| 32 | + return mapMuxers(muxers) |
| 33 | + } else { |
| 34 | + return [multiplex, spdy] |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +class Node extends libp2p { |
| 39 | + constructor (peerInfo, peerBook, options) { |
| 40 | + options = options || {} |
| 41 | + |
| 42 | + const modules = { |
| 43 | + transport: [ |
| 44 | + new TCP(), |
| 45 | + new WS() |
| 46 | + ], |
| 47 | + connection: { |
| 48 | + muxer: getMuxers(options.muxer), |
| 49 | + crypto: [ secio ] |
| 50 | + }, |
| 51 | + discovery: [] |
| 52 | + } |
| 53 | + |
| 54 | + if (options.dht) { |
| 55 | + modules.DHT = KadDHT |
| 56 | + } |
| 57 | + |
| 58 | + if (options.mdns) { |
| 59 | + const mdns = new MulticastDNS(peerInfo, 'ipfs.local') |
| 60 | + modules.discovery.push(mdns) |
| 61 | + } |
| 62 | + |
| 63 | + if (options.bootstrap) { |
| 64 | + const r = new Railing(options.bootstrap) |
| 65 | + modules.discovery.push(r) |
| 66 | + } |
| 67 | + |
| 68 | + if (options.modules && options.modules.transport) { |
| 69 | + options.modules.transport.forEach((t) => modules.transport.push(t)) |
| 70 | + } |
| 71 | + |
| 72 | + if (options.modules && options.modules.discovery) { |
| 73 | + options.modules.discovery.forEach((d) => modules.discovery.push(d)) |
| 74 | + } |
| 75 | + |
| 76 | + super(modules, peerInfo, peerBook, options) |
| 77 | + } |
| 78 | +} |
| 79 | + |
| 80 | +module.exports = Node |
0 commit comments