/ examples / simple.js
simple.js
 1  const chalk = require('chalk')
 2  const { DPT } = require('../src')
 3  const Buffer = require('safe-buffer').Buffer
 4  
 5  const PRIVATE_KEY = 'd772e3d6a001a38064dd23964dd2836239fa0e6cec8b28972a87460a17210fe9'
 6  const BOOTNODES = require('ethereum-common').bootstrapNodes.map((node) => {
 7    return {
 8      address: node.ip,
 9      udpPort: node.port,
10      tcpPort: node.port
11    }
12  })
13  
14  const dpt = new DPT(Buffer.from(PRIVATE_KEY, 'hex'), {
15    endpoint: {
16      address: '0.0.0.0',
17      udpPort: null,
18      tcpPort: null
19    }
20  })
21  
22  dpt.on('error', (err) => console.error(chalk.red(err.stack || err)))
23  
24  dpt.on('peer:added', (peer) => {
25    const info = `(${peer.id.toString('hex')},${peer.address},${peer.udpPort},${peer.tcpPort})`
26    console.log(chalk.green(`New peer: ${info} (total: ${dpt.getPeers().length})`))
27  })
28  
29  dpt.on('peer:removed', (peer) => {
30    console.log(chalk.yellow(`Remove peer: ${peer.id.toString('hex')} (total: ${dpt.getPeers().length})`))
31  })
32  
33  // for accept incoming connections uncomment next line
34  // dpt.bind(30303, '0.0.0.0')
35  
36  for (let bootnode of BOOTNODES) {
37    dpt.bootstrap(bootnode).catch((err) => console.error(chalk.bold.red(err.stack || err)))
38  }