const test = require("tape"); const Hyperswarm = require("hyperswarm"); const sodium = require("sodium-universal"); const b4a = require("b4a"); const { default: DHTData } = require("./"); const crypto = require("crypto"); const topicName = crypto.randomBytes(10); const topic = b4a.allocUnsafe(32); sodium.crypto_generichash(topic, b4a.from(topicName)); test("Basic presence test / data propagation", (t) => { t.plan(6); const peer1 = createPeer(); const peer2 = createPeer(); Promise.all([peer1, peer2]).then((peers) => { const peer1 = peers.shift(); const peer2 = peers.shift(); const p1 = new DHTData(peer1); const p2 = new DHTData(peer2); p1.data = { message: "Hello" }; p2.data = { message: "World!" }; t.ok(p1.id, "Generated id 1"); t.ok(p2.id, "Generated id 2"); p1.on("online", handleOnline); p2.on("online", handleOnline); p1.on("peer-remove", handleDisconnect); let hasFinished = false; function handleOnline(list) { if (list.length === 2) { const peerData1 = p1.getPeerData(p2.id); const peerData2 = p2.getPeerData(p1.id); const hasP1 = peerData1 && Object.keys(peerData1).length; const hasP2 = peerData2 && Object.keys(peerData2).length; if (!hasP1 || !hasP2) { return; } p1.removeListener("online", handleOnline); p2.removeListener("online", handleOnline); setTimeout(() => { t.pass("Seeing everyone online"); t.deepEqual(peerData1, p2.data, "Got peer data from peer 2"); t.deepEqual(peerData2, p1.data, "Got peer data from peer 2"); hasFinished = true; peer2._allConnections.get(peer1.keyPair.publicKey).end(); }, 1000); } } function handleDisconnect() { if (!hasFinished) return t.error("Disconnected before finished"); t.pass("Peer removed on disconnect"); t.end(); } t.teardown(() => { [peer1, peer2].forEach((item) => item.destroy()); }); }); }); async function createPeer() { const swarm = new Hyperswarm(); await swarm.dht.ready(); await swarm.listen(); swarm.join(topic); return swarm; }