244 lines
6.6 KiB
TypeScript
Raw Normal View History

2022-06-22 15:12:14 +10:00
import type {
PeerDiscovery,
PeerDiscoveryEvents,
} from "@libp2p/interface-peer-discovery";
import { symbol } from "@libp2p/interface-peer-discovery";
import type { PeerInfo } from "@libp2p/interface-peer-info";
import { CustomEvent, EventEmitter } from "@libp2p/interfaces/events";
import { peerIdFromString } from "@libp2p/peer-id/src";
import { Multiaddr } from "@multiformats/multiaddr";
2022-02-04 14:12:00 +11:00
import debug from "debug";
2022-01-13 11:33:26 +11:00
2022-05-04 20:07:21 +10:00
import { DnsNodeDiscovery, NodeCapabilityCount } from "./dns";
2022-05-30 15:01:57 +10:00
import { getPredefinedBootstrapNodes } from "./predefined";
import { getPseudoRandomSubset } from "./random_subset";
2022-01-13 11:33:26 +11:00
2022-06-22 15:12:14 +10:00
const log = debug("waku:discovery:bootstrap");
2022-01-13 11:33:26 +11:00
/**
* Setup discovery method used to bootstrap.
*
2022-05-04 20:07:21 +10:00
* Only one method is used. [[default]], [[peers]], [[getPeers]] and [[enrUrl]] options are mutually exclusive.
2022-01-13 11:33:26 +11:00
*/
export interface BootstrapOptions {
/**
* The maximum of peers to connect to as part of the bootstrap process.
2022-05-04 20:07:21 +10:00
* This only applies if [[peers]] or [[getPeers]] is used.
2022-01-13 11:33:26 +11:00
*
* @default [[Bootstrap.DefaultMaxPeers]]
2022-01-13 11:33:26 +11:00
*/
maxPeers?: number;
/**
2022-01-13 14:28:45 +11:00
* Use the default discovery method. Overrides all other options but `maxPeers`
2022-01-13 11:33:26 +11:00
*
* The default discovery method is likely to change overtime as new discovery
* methods are implemented.
*
* @default false
*/
default?: boolean;
/**
* Multiaddrs of peers to connect to.
*/
peers?: string[] | Multiaddr[];
2022-01-13 11:33:26 +11:00
/**
* Getter that retrieve multiaddrs of peers to connect to.
2022-06-22 15:12:14 +10:00
* will be called once.
2022-01-13 11:33:26 +11:00
*/
2022-01-13 14:28:45 +11:00
getPeers?: () => Promise<string[] | Multiaddr[]>;
2022-06-22 15:12:14 +10:00
/**
* The interval between emitting addresses in milliseconds.
* Used if [[peers]] is passed or a sync function is passed for [[getPeers]]
*/
interval?: number;
2022-01-13 11:33:26 +11:00
/**
* An EIP-1459 ENR Tree URL. For example:
* "enrtree://AOFTICU2XWDULNLZGRMQS4RIZPAZEHYMV4FYHAPW563HNRAOERP7C@test.nodes.vac.dev"
2022-05-04 20:07:21 +10:00
*
* [[wantedNodeCapabilityCount]] MUST be passed when using this option.
2022-01-13 11:33:26 +11:00
*/
enrUrl?: string;
2022-05-04 20:07:21 +10:00
/**
* Specifies what node capabilities (protocol) must be returned.
* This only applies when [[enrUrl]] is passed (EIP-1459 DNS Discovery).
*/
wantedNodeCapabilityCount?: Partial<NodeCapabilityCount>;
2022-01-13 11:33:26 +11:00
}
/**
* Parse options and expose function to return bootstrap peer addresses.
2022-05-04 20:07:21 +10:00
*
* @throws if an invalid combination of options is passed, see [[BootstrapOptions]] for details.
2022-01-13 11:33:26 +11:00
*/
2022-06-22 15:12:14 +10:00
export class Bootstrap
extends EventEmitter<PeerDiscoveryEvents>
implements PeerDiscovery
{
static DefaultMaxPeers = 1;
2022-01-13 14:28:45 +11:00
2022-06-22 15:12:14 +10:00
private readonly asyncGetBootstrapPeers:
| (() => Promise<Multiaddr[]>)
| undefined;
private peers: PeerInfo[];
private timer?: ReturnType<typeof setInterval>;
private readonly interval: number;
2022-01-13 11:33:26 +11:00
constructor(opts: BootstrapOptions) {
2022-06-22 15:12:14 +10:00
super();
const methods = [
!!opts.default,
!!opts.peers,
!!opts.getPeers,
!!opts.enrUrl,
].filter((x) => x);
if (methods.length > 1) {
throw new Error(
"Bootstrap does not support several discovery methods (yet)"
);
}
this.interval = opts.interval ?? 10000;
opts.default =
opts.default ?? (!opts.peers && !opts.getPeers && !opts.enrUrl);
const maxPeers = opts.maxPeers ?? Bootstrap.DefaultMaxPeers;
2022-06-22 15:12:14 +10:00
this.peers = [];
2022-01-13 11:33:26 +11:00
if (opts.default) {
2022-06-22 15:12:14 +10:00
log("Use hosted list of peers.");
2022-01-13 11:33:26 +11:00
2022-06-22 15:12:14 +10:00
this.peers = multiaddrsToPeerInfo(
getPredefinedBootstrapNodes(undefined, maxPeers)
);
return;
}
if (!!opts.peers && opts.peers.length > 0) {
const allPeers: Multiaddr[] = opts.peers.map(
(node: string | Multiaddr) => {
if (typeof node === "string") {
return new Multiaddr(node);
} else {
return node;
}
}
);
2022-06-22 15:12:14 +10:00
this.peers = multiaddrsToPeerInfo(
getPseudoRandomSubset(allPeers, maxPeers)
);
log(
2022-02-04 14:12:00 +11:00
"Use provided list of peers (reduced to maxPeers)",
2022-06-22 15:12:14 +10:00
this.peers.map((ma) => ma.toString())
);
2022-06-22 15:12:14 +10:00
return;
}
if (typeof opts.getPeers === "function") {
log("Bootstrap: Use provided getPeers function.");
const getPeers = opts.getPeers;
2022-06-22 15:12:14 +10:00
this.asyncGetBootstrapPeers = async () => {
const allPeers = await getPeers();
return getPseudoRandomSubset<string | Multiaddr>(
allPeers,
maxPeers
).map((node) => new Multiaddr(node));
};
2022-06-22 15:12:14 +10:00
return;
}
if (opts.enrUrl) {
2022-05-04 20:07:21 +10:00
const wantedNodeCapabilityCount = opts.wantedNodeCapabilityCount;
if (!wantedNodeCapabilityCount)
throw "`wantedNodeCapabilityCount` must be defined when using `enrUrl`";
const enrUrl = opts.enrUrl;
2022-06-22 15:12:14 +10:00
log("Use provided EIP-1459 ENR Tree URL.");
2022-01-13 11:33:26 +11:00
const dns = DnsNodeDiscovery.dnsOverHttp();
2022-01-13 11:33:26 +11:00
2022-06-22 15:12:14 +10:00
this.asyncGetBootstrapPeers = async () => {
2022-05-04 20:07:21 +10:00
const enrs = await dns.getPeers([enrUrl], wantedNodeCapabilityCount);
2022-06-22 15:12:14 +10:00
log(`Found ${enrs.length} peers`);
2022-01-17 14:21:23 +11:00
return enrs.map((enr) => enr.getFullMultiaddrs()).flat();
};
2022-06-22 15:12:14 +10:00
return;
}
}
/**
* Start discovery process
*/
start(): void {
if (this.asyncGetBootstrapPeers) {
// TODO: This should emit the peer as they are discovered instead of having
// to wait for the full DNS discovery process to be done first.
// TODO: PeerInfo should be returned by discovery
this.asyncGetBootstrapPeers().then((peers) => {
this.peers = multiaddrsToPeerInfo(peers);
this._startTimer();
});
} else {
2022-06-22 15:12:14 +10:00
this._startTimer();
}
}
private _startTimer(): void {
if (this.peers) {
log("Starting bootstrap node discovery");
if (this.timer != null) {
return;
}
this.timer = setInterval(() => this._returnPeers(), this.interval);
this._returnPeers();
}
}
_returnPeers(): void {
if (this.timer == null) {
return;
}
this.peers.forEach((peerData) => {
this.dispatchEvent(
new CustomEvent<PeerInfo>("peer", { detail: peerData })
);
});
}
/**
* Stop emitting events
*/
stop(): void {
if (this.timer != null) {
clearInterval(this.timer);
}
2022-06-22 15:12:14 +10:00
this.timer = undefined;
}
get [symbol](): true {
return true;
2022-01-13 11:33:26 +11:00
}
2022-06-22 15:12:14 +10:00
get [Symbol.toStringTag](): string {
return "@waku/bootstrap";
}
}
function multiaddrsToPeerInfo(mas: Multiaddr[]): PeerInfo[] {
return mas
.map((ma) => {
const peerIdStr = ma.getPeerId();
const protocols: string[] = [];
return {
id: peerIdStr ? peerIdFromString(peerIdStr) : null,
multiaddrs: [ma.decapsulateCode(421)],
protocols,
};
})
.filter((peerInfo): peerInfo is PeerInfo => peerInfo.id !== null);
2022-01-13 11:33:26 +11:00
}