libp2p 2.9.0-7ce083dca → 2.9.0-aa770ab81

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.min.js CHANGED
@@ -17,7 +17,7 @@ ${[...e.errors.entries()].map(([s,i])=>`
17
17
  `),e),e.log.trace('handle: responded with "%s" for "%s"',o,o),{stream:n.unwrap(),protocol:o};if(o==="ls"){let s=new W(...t.map(i=>ka.single(C(`${i}
18
18
  `))),C(`
19
19
  `));e.log.trace('handle: respond with "%s" for %s',t,o),await Ur(n,s,e),e.log.trace('handle: responded with "%s" for %s',t,o);continue}e.log.trace('handle: respond with "na" for "%s"',o),await Ur(n,C(`na
20
- `),e),e.log('handle: responded with "na" for "%s"',o)}}var Qw=500,of=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;limits;log;tags;maConn;muxer;components;outboundStreamProtocolNegotiationTimeout;inboundStreamProtocolNegotiationTimeout;constructor(t,e){this.components=t,this.id=e.id,this.remoteAddr=e.maConn.remoteAddr,this.remotePeer=e.remotePeer,this.direction=e.direction??"outbound",this.status="open",this.timeline=e.maConn.timeline,this.encryption=e.encryption,this.limits=e.limits,this.maConn=e.maConn,this.log=e.maConn.log,this.outboundStreamProtocolNegotiationTimeout=e.outboundStreamProtocolNegotiationTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=e.inboundStreamProtocolNegotiationTimeout??1e4,this.remoteAddr.getPeerId()==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this.tags=[],e.muxerFactory!=null&&(this.multiplexer=e.muxerFactory.protocol,this.muxer=e.muxerFactory.createStreamMuxer({direction:this.direction,log:this.log,onIncomingStream:n=>{this.onIncomingStream(n)}}),Promise.all([this.muxer.sink(this.maConn.source),this.maConn.sink(this.muxer.source)]).catch(n=>{this.log.error("error piping data through muxer - %e",n)}))}[Symbol.toStringTag]="Connection";[lf]=!0;get streams(){return this.muxer?.streams??[]}newStream=async(t,e={})=>{if(this.status==="closing")throw new rs("the connection is being closed");if(this.status==="closed")throw new Vr("the connection is closed");if(Array.isArray(t)||(t=[t]),this.limits!=null&&e?.runOnLimitedConnection!==!0)throw new Un("Cannot open protocol stream on limited connection");if(this.muxer==null)throw new Mr("Connection is not multiplexed");this.log.trace("starting new stream for protocols %s",t);let n=await this.muxer.newStream();this.log.trace("started new stream %s for protocols %s",n.id,t);try{if(e.signal==null){n.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",t);let c=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);e={...e,signal:c}}n.log.trace("selecting protocol from protocols %s",t);let{stream:o,protocol:s}=await On(n,t,{...e,log:n.log,yieldBytes:!0});n.log("selected protocol %s",s);let i=tx(s,this.components.registrar,e),a=um(s,"outbound",this);if(a>=i){let c=new cs(`Too many outbound protocol streams for protocol "${s}" - ${a}/${i}`);throw n.abort(c),c}return await this.components.peerStore.merge(this.remotePeer,{protocols:[s]}),n.source=o.source,n.sink=o.sink,n.protocol=s,o.closeWrite!=null&&(n.closeWrite=o.closeWrite),o.closeRead!=null&&(n.closeRead=o.closeRead),o.close!=null&&(n.close=o.close),this.components.metrics?.trackProtocolStream(n,this),n.direction="outbound",n}catch(o){throw this.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",this.direction==="inbound"?"from":"to",this.remoteAddr,t,o),n.timeline.close==null&&n.abort(o),o}};onIncomingStream(t){let e=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);Promise.resolve().then(async()=>{let n=this.components.registrar.getProtocols(),{stream:o,protocol:s}=await Mn(t,n,{signal:e,log:t.log,yieldBytes:!1});this.log("incoming %s stream opened",s);let i=Jw(s,this.components.registrar);if(um(s,"inbound",this)===i){let u=new as(`Too many inbound protocol streams for protocol "${s}" - limit ${i}`);throw t.abort(u),u}t.source=o.source,t.sink=o.sink,t.protocol=s,o.closeWrite!=null&&(t.closeWrite=o.closeWrite),o.closeRead!=null&&(t.closeRead=o.closeRead),o.close!=null&&(t.close=o.close),await this.components.peerStore.merge(this.remotePeer,{protocols:[s]},{signal:e}),this.components.metrics?.trackProtocolStream(t,this);let{handler:c,options:l}=this.components.registrar.getHandler(s);if(this.limits!=null&&l.runOnLimitedConnection!==!0)throw new Un("Cannot open protocol stream on limited connection");await c({connection:this,stream:t})}).catch(async n=>{this.log.error("error handling incoming stream id %s - %e",t.id,n),t.abort(n)})}async close(t={}){if(!(this.status==="closed"||this.status==="closing")){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",t.signal==null){let e=AbortSignal.timeout(Qw);t={...t,signal:e}}try{this.log.trace("closing underlying transport"),await this.muxer?.close(t),await this.maConn.close(t),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(e){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,e),this.abort(e)}}}abort(t){this.status!=="closed"&&(this.log.error("aborting connection to %a due to error",this.remoteAddr,t),this.status="closing",this.muxer?.abort(t),this.maConn.abort(t),this.status="closed",this.timeline.close=Date.now())}};function fm(r,t){return new of(r,t)}function Jw(r,t){try{let{options:e}=t.getHandler(r);return e.maxInboundStreams}catch(e){if(e.name!=="UnhandledProtocolError")throw e}return Qu}function tx(r,t,e={}){try{let{options:n}=t.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.name!=="UnhandledProtocolError")throw n}return e.maxOutboundStreams??Ju}function um(r,t,e){let n=0;return e.streams.forEach(o=>{o.direction===t&&o.protocol===r&&n++}),n}var Ma=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;constructor(t,e){this.components=t,this.connectionEncrypters=Tt({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),e.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=Tt({name:"libp2p_upgrader_stream_multiplexers",metrics:this.components.metrics}),e.streamMuxers.forEach(n=>{this.streamMuxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=e.inboundUpgradeTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=e.inboundStreamProtocolNegotiationTimeout??1e4,this.outboundStreamProtocolNegotiationTimeout=e.outboundStreamProtocolNegotiationTimeout??1e4,this.events=t.events,this.metrics={dials:t.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:t.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total"),inboundErrors:t.metrics?.registerCounterGroup("libp2p_connection_manager_dials_inbound_errors_total"),outboundErrors:t.metrics?.registerCounterGroup("libp2p_connection_manager_dials_outbound_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(t,...e){let n=this.components.connectionGater[t];if(n==null)return;if(await n.apply(this.components.connectionGater,e)===!0)throw new Qi(`The multiaddr connection is blocked by gater.${t}`)}createInboundAbortSignal(t){let e=Fe([AbortSignal.timeout(this.inboundUpgradeTimeout),t]);return e}async upgradeInbound(t,e){let n=!1,o=this.createInboundAbortSignal(e.signal);try{if(this.metrics.dials?.increment({inbound:!0}),n=await xt(this.components.connectionManager.acceptIncomingConnection(t),o),!n)throw new Ji("Connection denied");await xt(this.shouldBlockConnection("denyInboundConnection",t),o),await this._performUpgrade(t,"inbound",{...e,signal:o})}catch(s){throw this.metrics.errors?.increment({inbound:!0}),this.metrics.inboundErrors?.increment({[s.name??"Error"]:!0}),s}finally{o.clear(),n&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(t,e){try{this.metrics.dials?.increment({outbound:!0});let n=t.remoteAddr.getPeerId(),o;n!=null&&(o=ge(n),await xt(this.shouldBlockConnection("denyOutboundConnection",o,t),e.signal));let s="outbound";return e.initiator===!1&&(s="inbound"),await this._performUpgrade(t,s,e)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),this.metrics.outboundErrors?.increment({[n.name??"Error"]:!0}),n}}async _performUpgrade(t,e,n){let o,s,i,a,c,l=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`;t.log=t.log.newScope(`${e}:${l}`),this.components.metrics?.trackMultiaddrConnection(t),t.log.trace("starting the %s connection upgrade",e);let u=t;if(n?.skipProtection!==!0){let d=this.components.connectionProtector;d!=null&&(t.log("protecting the %s connection",e),u=await d.protect(t,n))}try{if(o=u,n?.skipEncryption!==!0){n?.onProgress?.(new dt(`upgrader:encrypt-${e}-connection`)),{conn:o,remotePeer:s,protocol:c,streamMuxer:a}=await(e==="inbound"?this._encryptInbound(u,n):this._encryptOutbound(u,n));let d={...u,...o};await this.shouldBlockConnection(e==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,d)}else{let d=t.remoteAddr.getPeerId();if(d==null)throw new qe(`${e} connection that skipped encryption must have a peer id`);let h=ge(d);c="native",s=h}if(s.equals(this.components.peerId)){let d=new zr("Can not dial self");throw t.abort(d),d}if(i=o,n?.muxerFactory!=null)a=n.muxerFactory;else if(a==null&&this.streamMuxers.size>0){n?.onProgress?.(new dt(`upgrader:multiplex-${e}-connection`));let d=await(e==="inbound"?this._multiplexInbound({...u,...o},this.streamMuxers,n):this._multiplexOutbound({...u,...o},this.streamMuxers,n));a=d.muxerFactory,i=d.stream}}catch(d){throw t.log.error("failed to upgrade inbound connection %s %a - %e",e==="inbound"?"from":"to",t.remoteAddr,d),d}await this.shouldBlockConnection(e==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,t);let f=this._createConnection({id:l,cryptoProtocol:c,direction:e,maConn:t,upgradedConn:i,muxerFactory:a,remotePeer:s,limits:n?.limits});return f.log("successfully upgraded %s connection",e),f}_createConnection(t){let{id:e,cryptoProtocol:n,direction:o,maConn:s,upgradedConn:i,remotePeer:a,muxerFactory:c,limits:l}=t,u,f=s.timeline;return s.timeline=new Proxy(f,{set:(...d)=>(d[1]==="close"&&d[2]!=null&&f.close==null&&(async()=>{try{u.status==="open"&&await u.close()}catch(h){u.log.error("error closing connection after timeline close %e",h)}finally{this.events.safeDispatchEvent("connection:close",{detail:u})}})().catch(h=>{u.log.error("error thrown while dispatching connection:close event %e",h)}),Reflect.set(...d))}),s.timeline.upgraded=Date.now(),u=fm(this.components,{id:e,maConn:i,remotePeer:a,direction:o,muxerFactory:c,encryption:n,limits:l,outboundStreamProtocolNegotiationTimeout:this.outboundStreamProtocolNegotiationTimeout,inboundStreamProtocolNegotiationTimeout:this.inboundStreamProtocolNegotiationTimeout}),this.events.safeDispatchEvent("connection:open",{detail:u}),u}async _encryptInbound(t,e){let n=Array.from(this.connectionEncrypters.keys());try{let{stream:o,protocol:s}=await Mn(t,n,{...e,log:t.log}),i=this.connectionEncrypters.get(s);if(i==null)throw new Nr(`no crypto module found for ${s}`);return t.log("encrypting inbound connection to %a using %s",t.remoteAddr,s),{...await i.secureInbound(o,e),protocol:s}}catch(o){throw t.log.error("encrypting inbound connection from %a failed",t.remoteAddr,o),new Nr(o.message)}}async _encryptOutbound(t,e){let n=Array.from(this.connectionEncrypters.keys());try{t.log.trace("selecting encrypter from %s",n);let{stream:o,protocol:s}=await On(t,n,{...e,log:t.log,yieldBytes:!0}),i=this.connectionEncrypters.get(s);if(i==null)throw new Nr(`no crypto module found for ${s}`);return t.log("encrypting outbound connection to %a using %s",t.remoteAddr,s),{...await i.secureOutbound(o,e),protocol:s}}catch(o){throw t.log.error("encrypting outbound connection to %a failed",t.remoteAddr,o),new Nr(o.message)}}async _multiplexOutbound(t,e,n){let o=Array.from(e.keys());t.log("outbound selecting muxer %s",o);try{t.log.trace("selecting stream muxer from %s",o);let{stream:s,protocol:i}=await On(t,o,{...n,log:t.log,yieldBytes:!0});t.log("selected %s as muxer protocol",i);let a=e.get(i);return{stream:s,muxerFactory:a}}catch(s){throw t.log.error("error multiplexing outbound connection",s),new Mr(String(s))}}async _multiplexInbound(t,e,n){let o=Array.from(e.keys());t.log("inbound handling muxers %s",o);try{let{stream:s,protocol:i}=await Mn(t,o,{...n,log:t.log}),a=e.get(i);return{stream:s,muxerFactory:a}}catch(s){throw t.log.error("error multiplexing inbound connection",s),new Mr(String(s))}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}};var Na="2.9.0-7ce083dca",Ba="js-libp2p";function hm(r,t){return`${r??Ba}/${t??Na} browser/${globalThis.navigator.userAgent}`}var Yo=class extends Vt{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(t){super(),this.status="stopped";let e=new Vt,n=e.dispatchEvent.bind(e);e.dispatchEvent=l=>{let u=n(l),f=this.dispatchEvent(new CustomEvent(l.type,{detail:l.detail}));return u||f},this.peerId=t.peerId,this.logger=t.logger??ei(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=t.nodeInfo?.name??Ba,s=t.nodeInfo?.version??Na,i=this.components=Kp({peerId:t.peerId,privateKey:t.privateKey,nodeInfo:{name:o,version:s,userAgent:t.nodeInfo?.userAgent??hm(o,s)},logger:this.logger,events:e,datastore:t.datastore??new Ri,connectionGater:Vp(t.connectionGater),dns:t.dns});t.metrics!=null&&(this.metrics=this.configureComponent("metrics",t.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",_p(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...t.peerStore})),i.events.addEventListener("peer:update",l=>{if(l.detail.previous==null){let u={id:l.detail.peer.id,multiaddrs:l.detail.peer.addresses.map(f=>f.multiaddr)};i.events.safeDispatchEvent("peer:discovery",{detail:u})}}),t.connectionProtector!=null&&this.configureComponent("connectionProtector",t.connectionProtector(i)),this.components.upgrader=new Ma(this.components,{connectionEncrypters:(t.connectionEncrypters??[]).map((l,u)=>this.configureComponent(`connection-encryption-${u}`,l(this.components))),streamMuxers:(t.streamMuxers??[]).map((l,u)=>this.configureComponent(`stream-muxers-${u}`,l(this.components))),inboundUpgradeTimeout:t.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:t.connectionManager?.inboundStreamProtocolNegotiationTimeout??t.connectionManager?.protocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:t.connectionManager?.outboundStreamProtocolNegotiationTimeout??t.connectionManager?.protocolNegotiationTimeout}),this.configureComponent("transportManager",new Aa(this.components,t.transportManager)),this.configureComponent("connectionManager",new pa(this.components,t.connectionManager)),t.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new wa(this.components,t.connectionMonitor)),this.configureComponent("registrar",new Sa(this.components)),this.configureComponent("addressManager",new zi(this.components,t.addresses));let a=(t.peerRouters??[]).map((l,u)=>this.configureComponent(`peer-router-${u}`,l(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new va(this.components,{routers:a}));let c=(t.contentRouters??[]).map((l,u)=>this.configureComponent(`content-router-${u}`,l(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new xa(this.components,{routers:c})),this.configureComponent("randomWalk",new _a(this.components)),(t.peerDiscovery??[]).forEach((l,u)=>{this.configureComponent(`peer-discovery-${u}`,l(this.components)).addEventListener("peer",d=>{this.#t(d)})}),t.transports?.forEach((l,u)=>{this.components.transportManager.add(this.configureComponent(`transport-${u}`,l(this.components)))}),t.services!=null)for(let l of Object.keys(t.services)){let u=t.services[l],f=u(this.components);if(f==null){this.log.error("service factory %s returned null or undefined instance",l);continue}this.services[l]=f,this.configureComponent(l,f),f[Ua]!=null&&(this.log("registering service %s for content routing",l),c.push(f[Ua])),f[Ka]!=null&&(this.log("registering service %s for peer routing",l),a.push(f[Ka])),f[Fa]!=null&&(this.log("registering service %s for peer discovery",l),f[Fa].addEventListener?.("peer",d=>{this.#t(d)}))}qp(i)}configureComponent(t,e){return e==null&&this.log.error("component %s was null or undefined",t),this.components[t]=e,e}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started")}catch(t){throw this.log.error("An error occurred starting libp2p",t),this.status="started",await this.stop(),t}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(t){return this.components.connectionManager.getConnections(t)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let t=new Ar;for(let e of this.components.connectionManager.getConnections())t.add(e.remotePeer);return Array.from(t)}async dial(t,e={}){return this.components.connectionManager.openConnection(t,{priority:75,...e})}async dialProtocol(t,e,n={}){if(e==null)throw new k("no protocols were provided to open a stream");if(e=Array.isArray(e)?e:[e],e.length===0)throw new k("no protocols were provided to open a stream");return(await this.dial(t,n)).newStream(e,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(t,e={}){er(t)&&(t=ge(t.getPeerId()??"")),await this.components.connectionManager.closeConnections(t,e)}async getPublicKey(t,e={}){if(this.log("getPublicKey %p",t),t.publicKey!=null)return t.publicKey;try{let i=await this.peerStore.get(t,e);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let n=oe([C("/pk/"),t.toMultihash().bytes]),o=await this.contentRouting.get(n,e),s=pn(o);return await this.peerStore.patch(t,{publicKey:s},e),s}async handle(t,e,n){Array.isArray(t)||(t=[t]),await Promise.all(t.map(async o=>{await this.components.registrar.handle(o,e,n)}))}async unhandle(t,e){Array.isArray(t)||(t=[t]),await Promise.all(t.map(async n=>{await this.components.registrar.unhandle(n,e)}))}async register(t,e,n){return this.components.registrar.register(t,e,n)}unregister(t){this.components.registrar.unregister(t)}async isDialable(t,e={}){return this.components.connectionManager.isDialable(t,e)}#t(t){let{detail:e}=t;if(e.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(e.id,{multiaddrs:e.multiaddrs}).catch(n=>{this.log.error(n)})}};async function ex(r={}){r.privateKey??=await dh("Ed25519");let t=new Yo({...await Xh(r),peerId:gh(r.privateKey)});return r.start!==!1&&await t.start(),t}var rx=["dial","dialProtocol","hangUp","handle","unhandle","getMultiaddrs","getProtocols"];function nx(r){return r==null?!1:r instanceof Yo?!0:rx.every(t=>typeof r[t]=="function")}return wm(ox);})();
20
+ `),e),e.log('handle: responded with "na" for "%s"',o)}}var Qw=500,of=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;limits;log;tags;maConn;muxer;components;outboundStreamProtocolNegotiationTimeout;inboundStreamProtocolNegotiationTimeout;constructor(t,e){this.components=t,this.id=e.id,this.remoteAddr=e.maConn.remoteAddr,this.remotePeer=e.remotePeer,this.direction=e.direction??"outbound",this.status="open",this.timeline=e.maConn.timeline,this.encryption=e.encryption,this.limits=e.limits,this.maConn=e.maConn,this.log=e.maConn.log,this.outboundStreamProtocolNegotiationTimeout=e.outboundStreamProtocolNegotiationTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=e.inboundStreamProtocolNegotiationTimeout??1e4,this.remoteAddr.getPeerId()==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this.tags=[],e.muxerFactory!=null&&(this.multiplexer=e.muxerFactory.protocol,this.muxer=e.muxerFactory.createStreamMuxer({direction:this.direction,log:this.log,onIncomingStream:n=>{this.onIncomingStream(n)}}),Promise.all([this.muxer.sink(this.maConn.source),this.maConn.sink(this.muxer.source)]).catch(n=>{this.log.error("error piping data through muxer - %e",n)}))}[Symbol.toStringTag]="Connection";[lf]=!0;get streams(){return this.muxer?.streams??[]}newStream=async(t,e={})=>{if(this.status==="closing")throw new rs("the connection is being closed");if(this.status==="closed")throw new Vr("the connection is closed");if(Array.isArray(t)||(t=[t]),this.limits!=null&&e?.runOnLimitedConnection!==!0)throw new Un("Cannot open protocol stream on limited connection");if(this.muxer==null)throw new Mr("Connection is not multiplexed");this.log.trace("starting new stream for protocols %s",t);let n=await this.muxer.newStream();this.log.trace("started new stream %s for protocols %s",n.id,t);try{if(e.signal==null){n.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",t);let c=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);e={...e,signal:c}}n.log.trace("selecting protocol from protocols %s",t);let{stream:o,protocol:s}=await On(n,t,{...e,log:n.log,yieldBytes:!0});n.log("selected protocol %s",s);let i=tx(s,this.components.registrar,e),a=um(s,"outbound",this);if(a>=i){let c=new cs(`Too many outbound protocol streams for protocol "${s}" - ${a}/${i}`);throw n.abort(c),c}return await this.components.peerStore.merge(this.remotePeer,{protocols:[s]}),n.source=o.source,n.sink=o.sink,n.protocol=s,o.closeWrite!=null&&(n.closeWrite=o.closeWrite),o.closeRead!=null&&(n.closeRead=o.closeRead),o.close!=null&&(n.close=o.close),this.components.metrics?.trackProtocolStream(n,this),n.direction="outbound",n}catch(o){throw this.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",this.direction==="inbound"?"from":"to",this.remoteAddr,t,o),n.timeline.close==null&&n.abort(o),o}};onIncomingStream(t){let e=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);Promise.resolve().then(async()=>{let n=this.components.registrar.getProtocols(),{stream:o,protocol:s}=await Mn(t,n,{signal:e,log:t.log,yieldBytes:!1});this.log("incoming %s stream opened",s);let i=Jw(s,this.components.registrar);if(um(s,"inbound",this)===i){let u=new as(`Too many inbound protocol streams for protocol "${s}" - limit ${i}`);throw t.abort(u),u}t.source=o.source,t.sink=o.sink,t.protocol=s,o.closeWrite!=null&&(t.closeWrite=o.closeWrite),o.closeRead!=null&&(t.closeRead=o.closeRead),o.close!=null&&(t.close=o.close),await this.components.peerStore.merge(this.remotePeer,{protocols:[s]},{signal:e}),this.components.metrics?.trackProtocolStream(t,this);let{handler:c,options:l}=this.components.registrar.getHandler(s);if(this.limits!=null&&l.runOnLimitedConnection!==!0)throw new Un("Cannot open protocol stream on limited connection");await c({connection:this,stream:t})}).catch(async n=>{this.log.error("error handling incoming stream id %s - %e",t.id,n),t.abort(n)})}async close(t={}){if(!(this.status==="closed"||this.status==="closing")){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",t.signal==null){let e=AbortSignal.timeout(Qw);t={...t,signal:e}}try{this.log.trace("closing underlying transport"),await this.muxer?.close(t),await this.maConn.close(t),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(e){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,e),this.abort(e)}}}abort(t){this.status!=="closed"&&(this.log.error("aborting connection to %a due to error",this.remoteAddr,t),this.status="closing",this.muxer?.abort(t),this.maConn.abort(t),this.status="closed",this.timeline.close=Date.now())}};function fm(r,t){return new of(r,t)}function Jw(r,t){try{let{options:e}=t.getHandler(r);return e.maxInboundStreams}catch(e){if(e.name!=="UnhandledProtocolError")throw e}return Qu}function tx(r,t,e={}){try{let{options:n}=t.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.name!=="UnhandledProtocolError")throw n}return e.maxOutboundStreams??Ju}function um(r,t,e){let n=0;return e.streams.forEach(o=>{o.direction===t&&o.protocol===r&&n++}),n}var Ma=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;constructor(t,e){this.components=t,this.connectionEncrypters=Tt({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),e.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=Tt({name:"libp2p_upgrader_stream_multiplexers",metrics:this.components.metrics}),e.streamMuxers.forEach(n=>{this.streamMuxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=e.inboundUpgradeTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=e.inboundStreamProtocolNegotiationTimeout??1e4,this.outboundStreamProtocolNegotiationTimeout=e.outboundStreamProtocolNegotiationTimeout??1e4,this.events=t.events,this.metrics={dials:t.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:t.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total"),inboundErrors:t.metrics?.registerCounterGroup("libp2p_connection_manager_dials_inbound_errors_total"),outboundErrors:t.metrics?.registerCounterGroup("libp2p_connection_manager_dials_outbound_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(t,...e){let n=this.components.connectionGater[t];if(n==null)return;if(await n.apply(this.components.connectionGater,e)===!0)throw new Qi(`The multiaddr connection is blocked by gater.${t}`)}createInboundAbortSignal(t){let e=Fe([AbortSignal.timeout(this.inboundUpgradeTimeout),t]);return e}async upgradeInbound(t,e){let n=!1,o=this.createInboundAbortSignal(e.signal);try{if(this.metrics.dials?.increment({inbound:!0}),n=await xt(this.components.connectionManager.acceptIncomingConnection(t),o),!n)throw new Ji("Connection denied");await xt(this.shouldBlockConnection("denyInboundConnection",t),o),await this._performUpgrade(t,"inbound",{...e,signal:o})}catch(s){throw this.metrics.errors?.increment({inbound:!0}),this.metrics.inboundErrors?.increment({[s.name??"Error"]:!0}),s}finally{o.clear(),n&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(t,e){try{this.metrics.dials?.increment({outbound:!0});let n=t.remoteAddr.getPeerId(),o;n!=null&&(o=ge(n),await xt(this.shouldBlockConnection("denyOutboundConnection",o,t),e.signal));let s="outbound";return e.initiator===!1&&(s="inbound"),await this._performUpgrade(t,s,e)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),this.metrics.outboundErrors?.increment({[n.name??"Error"]:!0}),n}}async _performUpgrade(t,e,n){let o,s,i,a,c,l=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`;t.log=t.log.newScope(`${e}:${l}`),this.components.metrics?.trackMultiaddrConnection(t),t.log.trace("starting the %s connection upgrade",e);let u=t;if(n?.skipProtection!==!0){let d=this.components.connectionProtector;d!=null&&(t.log("protecting the %s connection",e),u=await d.protect(t,n))}try{if(o=u,n?.skipEncryption!==!0){n?.onProgress?.(new dt(`upgrader:encrypt-${e}-connection`)),{conn:o,remotePeer:s,protocol:c,streamMuxer:a}=await(e==="inbound"?this._encryptInbound(u,n):this._encryptOutbound(u,n));let d={...u,...o};await this.shouldBlockConnection(e==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,d)}else{let d=t.remoteAddr.getPeerId();if(d==null)throw new qe(`${e} connection that skipped encryption must have a peer id`);let h=ge(d);c="native",s=h}if(s.equals(this.components.peerId)){let d=new zr("Can not dial self");throw t.abort(d),d}if(i=o,n?.muxerFactory!=null)a=n.muxerFactory;else if(a==null&&this.streamMuxers.size>0){n?.onProgress?.(new dt(`upgrader:multiplex-${e}-connection`));let d=await(e==="inbound"?this._multiplexInbound({...u,...o},this.streamMuxers,n):this._multiplexOutbound({...u,...o},this.streamMuxers,n));a=d.muxerFactory,i=d.stream}}catch(d){throw t.log.error("failed to upgrade inbound connection %s %a - %e",e==="inbound"?"from":"to",t.remoteAddr,d),d}await this.shouldBlockConnection(e==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,t);let f=this._createConnection({id:l,cryptoProtocol:c,direction:e,maConn:t,upgradedConn:i,muxerFactory:a,remotePeer:s,limits:n?.limits});return f.log("successfully upgraded %s connection",e),f}_createConnection(t){let{id:e,cryptoProtocol:n,direction:o,maConn:s,upgradedConn:i,remotePeer:a,muxerFactory:c,limits:l}=t,u,f=s.timeline;return s.timeline=new Proxy(f,{set:(...d)=>(d[1]==="close"&&d[2]!=null&&f.close==null&&(async()=>{try{u.status==="open"&&await u.close()}catch(h){u.log.error("error closing connection after timeline close %e",h)}finally{this.events.safeDispatchEvent("connection:close",{detail:u})}})().catch(h=>{u.log.error("error thrown while dispatching connection:close event %e",h)}),Reflect.set(...d))}),s.timeline.upgraded=Date.now(),u=fm(this.components,{id:e,maConn:i,remotePeer:a,direction:o,muxerFactory:c,encryption:n,limits:l,outboundStreamProtocolNegotiationTimeout:this.outboundStreamProtocolNegotiationTimeout,inboundStreamProtocolNegotiationTimeout:this.inboundStreamProtocolNegotiationTimeout}),this.events.safeDispatchEvent("connection:open",{detail:u}),u}async _encryptInbound(t,e){let n=Array.from(this.connectionEncrypters.keys());try{let{stream:o,protocol:s}=await Mn(t,n,{...e,log:t.log}),i=this.connectionEncrypters.get(s);if(i==null)throw new Nr(`no crypto module found for ${s}`);return t.log("encrypting inbound connection to %a using %s",t.remoteAddr,s),{...await i.secureInbound(o,e),protocol:s}}catch(o){throw t.log.error("encrypting inbound connection from %a failed",t.remoteAddr,o),new Nr(o.message)}}async _encryptOutbound(t,e){let n=Array.from(this.connectionEncrypters.keys());try{t.log.trace("selecting encrypter from %s",n);let{stream:o,protocol:s}=await On(t,n,{...e,log:t.log,yieldBytes:!0}),i=this.connectionEncrypters.get(s);if(i==null)throw new Nr(`no crypto module found for ${s}`);return t.log("encrypting outbound connection to %a using %s",t.remoteAddr,s),{...await i.secureOutbound(o,e),protocol:s}}catch(o){throw t.log.error("encrypting outbound connection to %a failed",t.remoteAddr,o),new Nr(o.message)}}async _multiplexOutbound(t,e,n){let o=Array.from(e.keys());t.log("outbound selecting muxer %s",o);try{t.log.trace("selecting stream muxer from %s",o);let{stream:s,protocol:i}=await On(t,o,{...n,log:t.log,yieldBytes:!0});t.log("selected %s as muxer protocol",i);let a=e.get(i);return{stream:s,muxerFactory:a}}catch(s){throw t.log.error("error multiplexing outbound connection",s),new Mr(String(s))}}async _multiplexInbound(t,e,n){let o=Array.from(e.keys());t.log("inbound handling muxers %s",o);try{let{stream:s,protocol:i}=await Mn(t,o,{...n,log:t.log}),a=e.get(i);return{stream:s,muxerFactory:a}}catch(s){throw t.log.error("error multiplexing inbound connection",s),new Mr(String(s))}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}};var Na="2.9.0-aa770ab81",Ba="js-libp2p";function hm(r,t){return`${r??Ba}/${t??Na} browser/${globalThis.navigator.userAgent}`}var Yo=class extends Vt{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(t){super(),this.status="stopped";let e=new Vt,n=e.dispatchEvent.bind(e);e.dispatchEvent=l=>{let u=n(l),f=this.dispatchEvent(new CustomEvent(l.type,{detail:l.detail}));return u||f},this.peerId=t.peerId,this.logger=t.logger??ei(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=t.nodeInfo?.name??Ba,s=t.nodeInfo?.version??Na,i=this.components=Kp({peerId:t.peerId,privateKey:t.privateKey,nodeInfo:{name:o,version:s,userAgent:t.nodeInfo?.userAgent??hm(o,s)},logger:this.logger,events:e,datastore:t.datastore??new Ri,connectionGater:Vp(t.connectionGater),dns:t.dns});t.metrics!=null&&(this.metrics=this.configureComponent("metrics",t.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",_p(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...t.peerStore})),i.events.addEventListener("peer:update",l=>{if(l.detail.previous==null){let u={id:l.detail.peer.id,multiaddrs:l.detail.peer.addresses.map(f=>f.multiaddr)};i.events.safeDispatchEvent("peer:discovery",{detail:u})}}),t.connectionProtector!=null&&this.configureComponent("connectionProtector",t.connectionProtector(i)),this.components.upgrader=new Ma(this.components,{connectionEncrypters:(t.connectionEncrypters??[]).map((l,u)=>this.configureComponent(`connection-encryption-${u}`,l(this.components))),streamMuxers:(t.streamMuxers??[]).map((l,u)=>this.configureComponent(`stream-muxers-${u}`,l(this.components))),inboundUpgradeTimeout:t.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:t.connectionManager?.inboundStreamProtocolNegotiationTimeout??t.connectionManager?.protocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:t.connectionManager?.outboundStreamProtocolNegotiationTimeout??t.connectionManager?.protocolNegotiationTimeout}),this.configureComponent("transportManager",new Aa(this.components,t.transportManager)),this.configureComponent("connectionManager",new pa(this.components,t.connectionManager)),t.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new wa(this.components,t.connectionMonitor)),this.configureComponent("registrar",new Sa(this.components)),this.configureComponent("addressManager",new zi(this.components,t.addresses));let a=(t.peerRouters??[]).map((l,u)=>this.configureComponent(`peer-router-${u}`,l(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new va(this.components,{routers:a}));let c=(t.contentRouters??[]).map((l,u)=>this.configureComponent(`content-router-${u}`,l(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new xa(this.components,{routers:c})),this.configureComponent("randomWalk",new _a(this.components)),(t.peerDiscovery??[]).forEach((l,u)=>{this.configureComponent(`peer-discovery-${u}`,l(this.components)).addEventListener("peer",d=>{this.#t(d)})}),t.transports?.forEach((l,u)=>{this.components.transportManager.add(this.configureComponent(`transport-${u}`,l(this.components)))}),t.services!=null)for(let l of Object.keys(t.services)){let u=t.services[l],f=u(this.components);if(f==null){this.log.error("service factory %s returned null or undefined instance",l);continue}this.services[l]=f,this.configureComponent(l,f),f[Ua]!=null&&(this.log("registering service %s for content routing",l),c.push(f[Ua])),f[Ka]!=null&&(this.log("registering service %s for peer routing",l),a.push(f[Ka])),f[Fa]!=null&&(this.log("registering service %s for peer discovery",l),f[Fa].addEventListener?.("peer",d=>{this.#t(d)}))}qp(i)}configureComponent(t,e){return e==null&&this.log.error("component %s was null or undefined",t),this.components[t]=e,e}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started")}catch(t){throw this.log.error("An error occurred starting libp2p",t),this.status="started",await this.stop(),t}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(t){return this.components.connectionManager.getConnections(t)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let t=new Ar;for(let e of this.components.connectionManager.getConnections())t.add(e.remotePeer);return Array.from(t)}async dial(t,e={}){return this.components.connectionManager.openConnection(t,{priority:75,...e})}async dialProtocol(t,e,n={}){if(e==null)throw new k("no protocols were provided to open a stream");if(e=Array.isArray(e)?e:[e],e.length===0)throw new k("no protocols were provided to open a stream");return(await this.dial(t,n)).newStream(e,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(t,e={}){er(t)&&(t=ge(t.getPeerId()??"")),await this.components.connectionManager.closeConnections(t,e)}async getPublicKey(t,e={}){if(this.log("getPublicKey %p",t),t.publicKey!=null)return t.publicKey;try{let i=await this.peerStore.get(t,e);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let n=oe([C("/pk/"),t.toMultihash().bytes]),o=await this.contentRouting.get(n,e),s=pn(o);return await this.peerStore.patch(t,{publicKey:s},e),s}async handle(t,e,n){Array.isArray(t)||(t=[t]),await Promise.all(t.map(async o=>{await this.components.registrar.handle(o,e,n)}))}async unhandle(t,e){Array.isArray(t)||(t=[t]),await Promise.all(t.map(async n=>{await this.components.registrar.unhandle(n,e)}))}async register(t,e,n){return this.components.registrar.register(t,e,n)}unregister(t){this.components.registrar.unregister(t)}async isDialable(t,e={}){return this.components.connectionManager.isDialable(t,e)}#t(t){let{detail:e}=t;if(e.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(e.id,{multiaddrs:e.multiaddrs}).catch(n=>{this.log.error(n)})}};async function ex(r={}){r.privateKey??=await dh("Ed25519");let t=new Yo({...await Xh(r),peerId:gh(r.privateKey)});return r.start!==!1&&await t.start(),t}var rx=["dial","dialProtocol","hangUp","handle","unhandle","getMultiaddrs","getProtocols"];function nx(r){return r==null?!1:r instanceof Yo?!0:rx.every(t=>typeof r[t]=="function")}return wm(ox);})();
21
21
  /*! Bundled license information:
22
22
 
23
23
  @noble/hashes/esm/utils.js: