Mathias Buus
4 years ago
4 changed files with 86 additions and 0 deletions
@ -0,0 +1,6 @@ |
|||
const DHT = require('../') |
|||
|
|||
// Set ephemeral: true so other peers do not add us to the peer list, simply bootstrap
|
|||
const bootstrap = new DHT({ ephemeral: true }) |
|||
|
|||
bootstrap.bind(10001) |
@ -0,0 +1,25 @@ |
|||
const DHT = require('../') |
|||
const crypto = require('crypto') |
|||
|
|||
const hex = process.argv[2] |
|||
const node = new DHT({ ephemeral: true, bootstrap: ['localhost:10001'] }) |
|||
|
|||
run() |
|||
|
|||
async function run () { |
|||
const q = node.query(Buffer.from(hex, 'hex'), 'values') |
|||
|
|||
for await (const data of q) { |
|||
if (data.value && sha256(data.value).toString('hex') === hex) { |
|||
// We found the value! Destroy the query stream as there is no need to continue.
|
|||
console.log(hex, '-->', data.value.toString()) |
|||
break |
|||
} |
|||
} |
|||
|
|||
console.log('(query finished)') |
|||
} |
|||
|
|||
function sha256 (val) { |
|||
return crypto.createHash('sha256').update(val).digest() |
|||
} |
@ -0,0 +1,19 @@ |
|||
const DHT = require('../') |
|||
const crypto = require('crypto') |
|||
|
|||
// Set ephemeral: true as we are not part of the network.
|
|||
const node = new DHT({ ephemeral: true, bootstrap: ['localhost:10001'] }) |
|||
const val = Buffer.from(process.argv[2]) |
|||
|
|||
run() |
|||
|
|||
async function run () { |
|||
const q = node.query(sha256(val), 'values') |
|||
await q.finished() |
|||
await q.commit('values', val) |
|||
console.log('Inserted', sha256(val).toString('hex')) |
|||
} |
|||
|
|||
function sha256 (val) { |
|||
return crypto.createHash('sha256').update(val).digest() |
|||
} |
@ -0,0 +1,36 @@ |
|||
const DHT = require('../') |
|||
const crypto = require('crypto') |
|||
|
|||
// Let's create 100 dht nodes for our example.
|
|||
const swarm = [] |
|||
for (let i = 0; i < 100; i++) swarm[i] = createNode() |
|||
|
|||
function createNode () { |
|||
const node = new DHT({ |
|||
bootstrap: [ |
|||
'localhost:10001' |
|||
] |
|||
}) |
|||
|
|||
const values = new Map() |
|||
|
|||
node.on('request', function (req) { |
|||
if (req.command === 'values') { |
|||
if (req.update) { |
|||
const key = sha256(req.value).toString('hex') |
|||
values.set(key, req.value) |
|||
console.log('Storing', key, '-->', req.value.toString()) |
|||
return req.reply(null) |
|||
} |
|||
|
|||
const value = values.get(req.target.toString('hex')) |
|||
req.reply(value) |
|||
} |
|||
}) |
|||
|
|||
return node |
|||
} |
|||
|
|||
function sha256 (val) { |
|||
return crypto.createHash('sha256').update(val).digest() |
|||
} |
Loading…
Reference in new issue