2022-02-04 14:12:00 +11:00
|
|
|
import Libp2p from "libp2p";
|
|
|
|
|
import { Peer } from "libp2p/src/peer-store";
|
2021-06-16 23:37:13 +10:00
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Returns a pseudo-random peer that supports the given protocol.
|
|
|
|
|
* Useful for protocols such as store and light push
|
|
|
|
|
*/
|
2022-02-02 15:12:08 +11:00
|
|
|
export async function selectRandomPeer(
|
|
|
|
|
peersIter: AsyncIterable<Peer>
|
|
|
|
|
): Promise<Peer | undefined> {
|
|
|
|
|
const peers = [];
|
|
|
|
|
for await (const peer of peersIter) {
|
|
|
|
|
peers.push(peer);
|
|
|
|
|
}
|
|
|
|
|
|
2021-06-16 23:37:13 +10:00
|
|
|
if (peers.length === 0) return;
|
2021-07-12 13:11:43 +10:00
|
|
|
|
|
|
|
|
const index = Math.round(Math.random() * (peers.length - 1));
|
|
|
|
|
return peers[index];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Returns the list of peers that supports the given protocol.
|
|
|
|
|
*/
|
2022-02-02 15:12:08 +11:00
|
|
|
export async function* getPeersForProtocol(
|
|
|
|
|
libp2p: Libp2p,
|
|
|
|
|
protocol: string
|
|
|
|
|
): AsyncIterable<Peer> {
|
|
|
|
|
for await (const peer of libp2p.peerStore.getPeers()) {
|
|
|
|
|
if (!peer.protocols.includes(protocol)) {
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
yield peer;
|
|
|
|
|
}
|
2021-06-16 23:37:13 +10:00
|
|
|
}
|