// Minimal DHT announce/lookup test — no map filters, raw responses.
import createTestnet from 'hyperdht/testnet.js'
import HyperDHT from 'hyperdht'
import crypto from 'crypto'
const topic = crypto.createHash('sha256').update('test-p2p-layer2').digest()
async function main() {
const testnet = await createTestnet(3)
const bootstrap = testnet.bootstrap
console.log('bootstrap:', bootstrap.map(n => `${n.host}:${n.port}`))
// Server: announce
const server = new HyperDHT({ bootstrap, firewalled: false })
await server.fullyBootstrapped()
const kp = HyperDHT.keyPair()
console.log('server pk:', kp.publicKey.toString('hex').slice(0, 16))
console.log('topic:', topic.toString('hex').slice(0, 16))
const srv = server.createServer()
await srv.listen(kp)
console.log('server listening')
const ann = server.announce(topic, kp)
await ann.finished
console.log('announced')
// Client: raw query (no map filter)
const client = new HyperDHT({ bootstrap, firewalled: false })
await client.fullyBootstrapped()
console.log('\n--- Raw LOOKUP query ---')
const q1 = client.query({ target: topic, command: 3 /* LOOKUP */, value: null })
let count = 0
for await (const node of q1) {
count++
console.log('reply #' + count + ':',
'from=' + (node.from ? `${node.from.host}:${node.from.port}` : 'null'),
'value=' + (node.value ? `${node.value.length} bytes` : 'null'),
'token=' + (node.token ? 'yes' : 'no'))
}
console.log('raw LOOKUP replies:', count)
// Check the announce commit actually happened
console.log('\n--- Checking announce commit ---')
// Re-announce and monitor
const ann2 = server.announce(topic, kp)
let commitCount = 0
for await (const node of ann2) {
commitCount++
console.log('announce commit reply #' + commitCount + ':',
'from=' + (node.from ? `${node.from.host}:${node.from.port}` : 'null'),
'value=' + (node.value ? `${node.value.length}B` : 'null'),
'token=' + (node.token ? 'yes' : 'no'),
'peers=' + (node.peers ? node.peers.length : '?'))
}
console.log('announce commits:', commitCount)
// Now lookup again
console.log('\n--- LOOKUP after re-announce ---')
const q3 = client.query({ target: topic, command: 3, value: null })
count = 0
for await (const node of q3) {
count++
console.log('reply #' + count + ':',
'from=' + (node.from ? `${node.from.host}:${node.from.port}` : 'null'),
'value=' + (node.value ? `${node.value.length}B` : 'null'))
if (node.value) {
console.log(' raw value:', node.value.toString('hex'))
}
}
console.log('LOOKUP replies after re-announce:', count)
// Try findPeer via HyperDHT.findPeer()
console.log('\n--- findPeer via API ---')
const fp = client.findPeer(kp.publicKey)
count = 0
for await (const data of fp) {
count++
console.log('findPeer #' + count + ':', data.peer ?
'pk=' + data.peer.publicKey.toString('hex').slice(0, 16) : 'null')
}
console.log('findPeer results:', count)
await srv.close()
await server.destroy()
await client.destroy()
await testnet.destroy()
}
main().catch(console.error)