Mathias Buus
6 years ago
4 changed files with 79 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 = dht({ ephemeral: true }) |
|||
|
|||
bootstrap.listen(10001) |
@ -0,0 +1,21 @@ |
|||
const dht = require('../') |
|||
const crypto = require('crypto') |
|||
|
|||
const hex = process.argv[2] |
|||
const node = dht({ ephemeral: true, bootstrap: ['localhost:10001'] }) |
|||
|
|||
node.query('values', Buffer.from(hex, 'hex')) |
|||
.on('data', function (data) { |
|||
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()) |
|||
this.destroy() |
|||
} |
|||
}) |
|||
.on('end', function () { |
|||
console.log('(query finished)') |
|||
}) |
|||
|
|||
function sha256 (val) { |
|||
return crypto.createHash('sha256').update(val).digest() |
|||
} |
@ -0,0 +1,15 @@ |
|||
const dht = require('../') |
|||
const crypto = require('crypto') |
|||
|
|||
// Set ephemeral: true as we are not part of the network.
|
|||
const node = dht({ ephemeral: true, bootstrap: ['localhost:10001'] }) |
|||
const val = Buffer.from(process.argv[2]) |
|||
|
|||
node.update('values', sha256(val), val, function (err, res) { |
|||
if (err) throw err |
|||
console.log('Inserted', sha256(val).toString('hex')) |
|||
}) |
|||
|
|||
function sha256 (val) { |
|||
return crypto.createHash('sha256').update(val).digest() |
|||
} |
@ -0,0 +1,37 @@ |
|||
const dht = require('../') |
|||
const crypto = require('crypto') |
|||
|
|||
// Let's create 100 dht nodes for our example.
|
|||
for (var i = 0; i < 100; i++) createNode() |
|||
|
|||
function createNode () { |
|||
const node = dht({ |
|||
bootstrap: [ |
|||
'localhost:10001' |
|||
] |
|||
}) |
|||
|
|||
const values = new Map() |
|||
|
|||
node.command('values', { |
|||
// When we are the closest node and someone is sending us a "store" command
|
|||
update (query, cb) { |
|||
if (!query.value) return cb() |
|||
|
|||
// Use the hash of the value as the key
|
|||
const key = sha256(query.value).toString('hex') |
|||
values.set(key, query.value) |
|||
console.log('Storing', key, '-->', query.value.toString()) |
|||
cb() |
|||
}, |
|||
// When someone is querying for a "lookup" command
|
|||
query (query, cb) { |
|||
const value = values.get(query.target.toString('hex')) |
|||
cb(null, value) |
|||
} |
|||
}) |
|||
} |
|||
|
|||
function sha256 (val) { |
|||
return crypto.createHash('sha256').update(val).digest() |
|||
} |
Loading…
Reference in new issue