import PeerId from "peer-id" ; import { CID } from "multiformats/basics.js" ; import { Peer } from "../core" ; export interface Options { timeout : number ; maxNumProviders : number ; } export class Dht { constructor ( private parent ) { } param peer async findPeer ( id , options = { } ) { if ( ! this . parent . isOnline ( ) ) { throw new Error ( "peer is not online" ) ; } if ( typeof id === "string" ) { id = PeerId . createFromB58String ( id ) ; } return this . parent . host . peerRouting . findPeer ( id , options ) ; } param cid async findProvs ( cid , options = { } ) { if ( ! this . parent . isOnline ( ) ) { throw new Error ( "peer is not online" ) ; } if ( typeof cid === "string" ) { try { cid = new CID ( cid ) ; } catch ( err ) { throw "invalid cid" ; } } return this . parent . host . contentRouting . findProviders ( cid as never , options ) ; } param cids param options async provide ( cids , options = { } ) { if ( ! this . parent . isOnline ( ) ) { throw new Error ( "peer is not online" ) ; } if ( ! Array . isArray ( cids ) ) { cids = [ cids ] ; } try { cids = cids . map ( ( cid ) => new CID ( cid ) ) ; } catch ( err ) { throw new Error ( "invalid cid" ) ; } const all = await Promise . all ( cids . map ( ( cid ) => this . parent . hasBlock ( cid ) ) ) ; if ( ! all . every ( ( has ) => has ) ) { throw new Error ( "block(s) not found locally, cannot provide" ) ; } if ( options . recursive ) { throw new Error ( "not implemented yet" ) ; } else { await Promise . all ( cids . map ( ( cid ) => this . parent . host . contentRouting . provide ( cid as never ) ) ) ; } } }