2022-12-20 12:27:13 +00:00
|
|
|
import b4a from "b4a";
|
|
|
|
|
|
|
|
export interface Peer {
|
|
|
|
host: string;
|
|
|
|
port: number;
|
|
|
|
}
|
|
|
|
|
2023-01-15 07:58:08 +00:00
|
|
|
export type PeerSource = (
|
|
|
|
pubkey: Buffer,
|
|
|
|
options?: any
|
|
|
|
) => Promise<boolean | Peer>;
|
2022-12-20 12:27:13 +00:00
|
|
|
|
|
|
|
export class PeerDiscovery {
|
|
|
|
private _sources: Map<string, PeerSource> = new Map<string, PeerSource>();
|
|
|
|
|
|
|
|
public registerSource(name: string, source: PeerSource): boolean {
|
|
|
|
if (this._sources.has(name)) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
this._sources.set(name, source);
|
|
|
|
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
public removeSource(name: string): boolean {
|
|
|
|
if (!this._sources.has(name)) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
this._sources.delete(name);
|
|
|
|
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2023-01-15 07:58:08 +00:00
|
|
|
public async discover(
|
|
|
|
pubkey: string | Buffer,
|
|
|
|
options = {}
|
|
|
|
): Promise<Peer | boolean> {
|
2022-12-20 12:27:13 +00:00
|
|
|
if (!b4a.isBuffer(pubkey)) {
|
|
|
|
pubkey = b4a.from(pubkey, "hex") as Buffer;
|
|
|
|
}
|
|
|
|
|
|
|
|
for (const source of this._sources.values()) {
|
2023-01-15 07:58:08 +00:00
|
|
|
const result = await source(pubkey, options);
|
2022-12-20 12:27:13 +00:00
|
|
|
|
|
|
|
if (result) {
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|