Skip to content

Instantly share code, notes, and snippets.

@Nuhvi
Last active September 9, 2023 03:56
Show Gist options
  • Save Nuhvi/f5d14b769d2561008d7e89d1109bd06c to your computer and use it in GitHub Desktop.
Save Nuhvi/f5d14b769d2561008d7e89d1109bd06c to your computer and use it in GitHub Desktop.
Mainline peer discovery
import DHT from 'bittorrent-dht'
const BOOTSTRAP = [
{ host: 'router.bittorrent.com', port: 6881 },
{ host: 'router.utorrent.com', port: 6881 },
{ host: 'dht.transmissionbt.com', port: 6881 },
{ host: 'router.nuh.dev', port: 6881 }
]
const infoHash = random()
const a = new DHT({ bootstrap: BOOTSTRAP }) // provider
const b = new DHT({ bootstrap: BOOTSTRAP }) // client
await new Promise((resolve, reject) => {
a.announce(infoHash, 9090, (err, nodes) => {
if (err) reject(err)
resolve(nodes)
})
})
console.log('announced', infoHash, "on", 9090)
await new Promise((resolve, reject) => {
setTimeout(() => reject("GET_PEERS TIMEOUT"), 10000)
console.log("Looking for peers on", infoHash)
const start = Date.now()
b.lookup(
infoHash,
(err, nodes) => {
if (err) reject(err)
console.log("Got responses from", nodes, "nodes")
resolve(nodes)
}
)
let end;
b.on('peer', function(peer, _infoHash, from) {
if (!end) {
end = Date.now()
console.log("Found first peer in", end - start, "ms")
}
console.log('found potential peer ' + peer.host + ':' + peer.port + ' through ' + from.address + ':' + from.port)
})
})
a.destroy()
b.destroy()
function random() {
return Buffer.from(
new Array(4).fill(0).map(() => Math.random().toString(16).slice(2)).join(''),
'hex'
).slice(0, 20)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment