diff --git a/src/index.ts b/src/index.ts index 4299a53..ff4f60e 100644 --- a/src/index.ts +++ b/src/index.ts @@ -61,9 +61,7 @@ export default class DHTCache extends EventEmitter { this.flood.on("peer-remove", (peer) => this.removePeerHandler(peer)); this.flood.on("message", (message, id) => this.onGetBroadcast(message, id)); - this.swarm.on("connection", (peer: any) => - this.send(peer, b4a.from("hello")) - ); + this.swarm.on("connection", this._hello.bind(this)); [...this.swarm.peers.values()] .map((item) => { @@ -398,25 +396,36 @@ export default class DHTCache extends EventEmitter { } private _bootstrapFrom(bootstrap: Bootstrap) { - if (this.bootstrapped) { - return; - } - for (const id in bootstrap) { const { connectedTo } = bootstrap[id]; if (id === this.id.toString("hex")) { continue; } + if (!this.connectedTo.has(id)) { + this.swarm.joinPeer(id); + } + for (const connection of connectedTo) { const peer = b4a.from(connection) as Buffer; + + if (b4a.equals(peer, this.id)) { + continue; + } + this._ensurePeer(peer); this._addEntityConnection(id, peer); + + if (!this.connectedTo.has(peer.toString("hex"))) { + this.swarm.joinPeer(peer); + } } } - this.bootstrapped = true; - this.emit("bootstrapped"); + if (!this.bootstrapped) { + this.bootstrapped = true; + this.emit("bootstrapped"); + } this._recalculate(); } @@ -574,4 +583,9 @@ export default class DHTCache extends EventEmitter { ); } } + + private _hello(peer: any) { + this.send(peer, b4a.from("hello")); + this.swarm.leavePeer(peer.remotePublicKey); + } }