libp2p 2.6.0 → 2.6.1
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 +1 -1
- package/dist/src/version.d.ts +1 -1
- package/dist/src/version.js +1 -1
- package/package.json +2 -1
- package/src/version.ts +1 -1
package/dist/index.min.js
CHANGED
|
@@ -16,7 +16,7 @@ ${e.join(`
|
|
|
16
16
|
`),t),t.log.trace('handle: responded with "%s" for "%s"',s,s),{stream:n.unwrap(),protocol:s};if(s==="ls"){let o=new ye(...e.map(i=>za.single(N(`${i}
|
|
17
17
|
`))),N(`
|
|
18
18
|
`));t.log.trace('handle: respond with "%s" for %s',e,s),await Fr(n,o,t),t.log.trace('handle: responded with "%s" for %s',e,s);continue}t.log.trace('handle: respond with "na" for "%s"',s),await Fr(n,N(`na
|
|
19
|
-
`),t),t.log('handle: responded with "na" for "%s"',s)}}var lx=500,tf=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;limits;log;tags;_newStream;_close;_abort;_getStreams;constructor(e){let{remoteAddr:t,remotePeer:n,newStream:s,close:o,abort:i,getStreams:a}=e;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=t,this.remotePeer=n,this.direction=e.direction,this.status="open",this.timeline=e.timeline,this.multiplexer=e.multiplexer,this.encryption=e.encryption,this.limits=e.limits,this.log=e.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`),this.remoteAddr.getPeerId()==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this._newStream=s,this._close=o,this._abort=i,this._getStreams=a,this.tags=[]}[Symbol.toStringTag]="Connection";[ff]=!0;get streams(){return this._getStreams()}async newStream(e,t){if(this.status==="closing")throw new Ws("the connection is being closed");if(this.status==="closed")throw new $r("the connection is closed");if(Array.isArray(e)||(e=[e]),this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new Gr("Cannot open protocol stream on limited connection");let n=await this._newStream(e,t);return n.direction="outbound",n}async close(e={}){if(!(this.status==="closed"||this.status==="closing")){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",e.signal==null){let t=AbortSignal.timeout(lx);e={...e,signal:t}}try{this.log.trace("closing underlying transport"),await this._close(e),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(t){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,t),this.abort(t)}}}abort(e){this.status!=="closed"&&(this.log.error("aborting connection to %a due to error",this.remoteAddr,e),this.status="closing",this._abort(e),this.status="closed",this.timeline.close=Date.now())}};function mm(r){return new tf(r)}function hx(r,e){try{let{options:t}=e.getHandler(r);return t.maxInboundStreams}catch(t){if(t.name!=="UnhandledProtocolError")throw t}return Zu}function dx(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.name!=="UnhandledProtocolError")throw n}return t.maxOutboundStreams??Xu}function gm(r,e,t){let n=0;return t.streams.forEach(s=>{s.direction===e&&s.protocol===r&&n++}),n}var Za=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;outboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;constructor(e,t){this.components=e,this.connectionEncrypters=new Map,t.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=new Map,t.streamMuxers.forEach(n=>{this.streamMuxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??3e3,this.outboundUpgradeTimeout=t.outboundUpgradeTimeout??3e3,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??2e3,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??2e3,this.events=e.events,this.metrics={dials:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,...t){let n=this.components.connectionGater[e];if(n==null)return;if(await n.apply(this.components.connectionGater,t)===!0)throw new la(`The multiaddr connection is blocked by gater.${e}`)}async upgradeInbound(e,t={}){let n=!1;try{if(this.metrics.dials?.increment({inbound:!0}),n=await this.components.connectionManager.acceptIncomingConnection(e),!n)throw new ua("Connection denied");await this.shouldBlockConnection("denyInboundConnection",e),await this._performUpgrade(e,"inbound",t)}catch(s){throw this.metrics.errors?.increment({inbound:!0}),s}finally{n&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t={}){try{this.metrics.dials?.increment({outbound:!0});let n=e.remoteAddr.getPeerId(),s;n!=null&&(s=gt(n),await this.shouldBlockConnection("denyOutboundConnection",s,e));let o="outbound";return t.initiator===!1&&(o="inbound"),await this._performUpgrade(e,o,t)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),n}}async _performUpgrade(e,t,n){let s,o,i,a,c,u=AbortSignal.timeout(t==="inbound"?this.inboundUpgradeTimeout:this.outboundUpgradeTimeout),f=Ft([u,n.signal]);n.signal=f,this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t);let l=e;if(n?.skipProtection!==!0){let h=this.components.connectionProtector;h!=null&&(e.log("protecting the %s connection",t),l=await h.protect(e,n))}try{if(s=l,n?.skipEncryption!==!0){n?.onProgress?.(new fe(`upgrader:encrypt-${t}-connection`)),{conn:s,remotePeer:o,protocol:c}=await(t==="inbound"?this._encryptInbound(l,{...n,signal:f}):this._encryptOutbound(l,{...n,signal:f}));let h={...l,...s};await this.shouldBlockConnection(t==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",o,h)}else{let h=e.remoteAddr.getPeerId();if(h==null)throw new Ht(`${t} connection that skipped encryption must have a peer id`);let p=gt(h);c="native",o=p}if(o.equals(this.components.peerId)){let h=new qr("Can not dial self");throw e.abort(h),h}if(i=s,n?.muxerFactory!=null)a=n.muxerFactory;else if(this.streamMuxers.size>0){n?.onProgress?.(new fe(`upgrader:multiplex-${t}-connection`));let h=await(t==="inbound"?this._multiplexInbound({...l,...s},this.streamMuxers,n):this._multiplexOutbound({...l,...s},this.streamMuxers,n));a=h.muxerFactory,i=h.stream}}catch(h){throw e.log.error("failed to upgrade inbound connection %s %a - %e",t==="inbound"?"from":"to",e.remoteAddr,h),h}finally{f.clear()}return await this.shouldBlockConnection(t==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",o,e),e.log("successfully upgraded %s connection",t),this._createConnection({cryptoProtocol:c,direction:t,maConn:e,upgradedConn:i,muxerFactory:a,remotePeer:o,limits:n?.limits})}_createConnection(e){let{cryptoProtocol:t,direction:n,maConn:s,upgradedConn:o,remotePeer:i,muxerFactory:a,limits:c}=e,u,f,l;a!=null&&(u=a.createStreamMuxer({direction:n,onIncomingStream:m=>{l!=null&&Promise.resolve().then(async()=>{let g=this.components.registrar.getProtocols(),d=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);let{stream:w,protocol:x}=await Ks(m,g,{signal:d,log:m.log,yieldBytes:!1});if(l==null)return;l.log("incoming stream opened on %s",x);let y=hx(x,this.components.registrar);if(gm(x,"inbound",l)===y){let _=new Qs(`Too many inbound protocol streams for protocol "${x}" - limit ${y}`);throw m.abort(_),_}m.source=w.source,m.sink=w.sink,m.protocol=x,w.closeWrite!=null&&(m.closeWrite=w.closeWrite),w.closeRead!=null&&(m.closeRead=w.closeRead),w.close!=null&&(m.close=w.close),await this.components.peerStore.merge(i,{protocols:[x]}),this.components.metrics?.trackProtocolStream(m,l),this._onStream({connection:l,stream:m,protocol:x})}).catch(async g=>{l.log.error("error handling incoming stream id %s - %e",m.id,g),m.timeline.close==null&&await m.close()})}}),f=async(m,g={})=>{if(u==null)throw new Mr("Connection is not multiplexed");l.log.trace("starting new stream for protocols %s",m);let d=await u.newStream();l.log.trace("started new stream %s for protocols %s",d.id,m);try{if(g.signal==null){d.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",m);let _=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);g={...g,signal:_}}d.log.trace("selecting protocol from protocols %s",m);let{stream:w,protocol:x}=await Vs(d,m,{...g,log:d.log,yieldBytes:!0});d.log.trace("selected protocol %s",x);let y=dx(x,this.components.registrar,g),E=gm(x,"outbound",l);if(E>=y){let _=new eo(`Too many outbound protocol streams for protocol "${x}" - ${E}/${y}`);throw d.abort(_),_}return await this.components.peerStore.merge(i,{protocols:[x]}),d.source=w.source,d.sink=w.sink,d.protocol=x,w.closeWrite!=null&&(d.closeWrite=w.closeWrite),w.closeRead!=null&&(d.closeRead=w.closeRead),w.close!=null&&(d.close=w.close),this.components.metrics?.trackProtocolStream(d,l),d}catch(w){throw l.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",n==="inbound"?"from":"to",e.maConn.remoteAddr,m,w),d.timeline.close==null&&d.abort(w),w}},Promise.all([u.sink(o.source),o.sink(u.source)]).catch(m=>{l.log.error("error piping data through muxer - %e",m)}));let h=s.timeline;s.timeline=new Proxy(h,{set:(...m)=>(m[1]==="close"&&m[2]!=null&&h.close==null&&(async()=>{try{l.status==="open"&&await l.close()}catch(g){l.log.error("error closing connection after timeline close %e",g)}finally{this.events.safeDispatchEvent("connection:close",{detail:l})}})().catch(g=>{l.log.error("error thrown while dispatching connection:close event %e",g)}),Reflect.set(...m))}),s.timeline.upgraded=Date.now();let p=()=>{throw new Mr("Connection is not multiplexed")};return l=mm({remoteAddr:s.remoteAddr,remotePeer:i,status:"open",direction:n,timeline:s.timeline,multiplexer:u?.protocol,encryption:t,limits:c,logger:this.components.logger,newStream:f??p,getStreams:()=>u?.streams??[],close:async m=>{await u?.close(m),await s.close(m)},abort:m=>{s.abort(m),u?.abort(m)}}),this.events.safeDispatchEvent("connection:open",{detail:l}),l.__maConnTimeline=h,l}_onStream(e){let{connection:t,stream:n,protocol:s}=e,{handler:o,options:i}=this.components.registrar.getHandler(s);if(t.limits!=null&&i.runOnLimitedConnection!==!0)throw new Gr("Cannot open protocol stream on limited connection");o({connection:t,stream:n})}async _encryptInbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{let{stream:s,protocol:o}=await Ks(e,n,{...t,log:e.log}),i=this.connectionEncrypters.get(o);if(i==null)throw new Or(`no crypto module found for ${o}`);return e.log("encrypting inbound connection to %a using %s",e.remoteAddr,o),{...await i.secureInbound(s,t),protocol:o}}catch(s){throw e.log.error("encrypting inbound connection from %a failed",e.remoteAddr,s),new Or(s.message)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",n);let{stream:s,protocol:o}=await Vs(e,n,{...t,log:e.log,yieldBytes:!0}),i=this.connectionEncrypters.get(o);if(i==null)throw new Or(`no crypto module found for ${o}`);return e.log("encrypting outbound connection to %a using %s",e.remoteAddr,o),{...await i.secureOutbound(s,t),protocol:o}}catch(s){throw e.log.error("encrypting outbound connection to %a failed",e.remoteAddr,s),new Or(s.message)}}async _multiplexOutbound(e,t,n){let s=Array.from(t.keys());e.log("outbound selecting muxer %s",s);try{e.log.trace("selecting stream muxer from %s",s);let{stream:o,protocol:i}=await Vs(e,s,{...n,log:e.log,yieldBytes:!0});e.log("selected %s as muxer protocol",i);let a=t.get(i);return{stream:o,muxerFactory:a}}catch(o){throw e.log.error("error multiplexing outbound connection",o),new Mr(String(o))}}async _multiplexInbound(e,t,n){let s=Array.from(t.keys());e.log("inbound handling muxers %s",s);try{let{stream:o,protocol:i}=await Ks(e,s,{...n,log:e.log}),a=t.get(i);return{stream:o,muxerFactory:a}}catch(o){throw e.log.error("error multiplexing inbound connection",o),new Mr(String(o))}}};var ym="2.6.0",$s="js-libp2p";function bm(r,e){return`${r??$s}/${e??ym} browser/${globalThis.navigator.userAgent}`}var Xa=class extends xt{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new xt,n=t.dispatchEvent.bind(t);t.dispatchEvent=u=>{let f=n(u),l=this.dispatchEvent(new CustomEvent(u.type,{detail:u.detail}));return f||l},this.peerId=e.peerId,this.logger=e.logger??Ni(),this.log=this.logger.forComponent("libp2p"),this.services={};let s=e.nodeInfo?.name??$s,o=e.nodeInfo?.version??$s,i=this.components=Gp({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:s,version:o,userAgent:e.nodeInfo?.userAgent??bm(s,o)},logger:this.logger,events:t,datastore:e.datastore??new Wi,connectionGater:jp(e.connectionGater),dns:e.dns});this.peerStore=this.configureComponent("peerStore",kp(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),i.events.addEventListener("peer:update",u=>{if(u.detail.previous==null){let f={id:u.detail.peer.id,multiaddrs:u.detail.peer.addresses.map(l=>l.multiaddr)};i.events.safeDispatchEvent("peer:discovery",{detail:f})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new Za(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map((u,f)=>this.configureComponent(`connection-encryption-${f}`,u(this.components))),streamMuxers:(e.streamMuxers??[]).map((u,f)=>this.configureComponent(`stream-muxers-${f}`,u(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,outboundUpgradeTimeout:e.connectionManager?.outboundUpgradeTimeout}),this.configureComponent("transportManager",new Fa(this.components,e.transportManager)),this.configureComponent("connectionManager",new ka(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new Na(this.components,e.connectionMonitor)),this.configureComponent("registrar",new Ua(this.components)),this.configureComponent("addressManager",new na(this.components,e.addresses));let a=(e.peerRouters??[]).map((u,f)=>this.configureComponent(`peer-router-${f}`,u(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new Ma(this.components,{routers:a}));let c=(e.contentRouters??[]).map((u,f)=>this.configureComponent(`content-router-${f}`,u(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new Da(this.components,{routers:c})),this.configureComponent("randomWalk",new Oa(this.components)),(e.peerDiscovery??[]).forEach((u,f)=>{this.configureComponent(`peer-discovery-${f}`,u(this.components)).addEventListener("peer",h=>{this.#e(h)})}),e.transports?.forEach((u,f)=>{this.components.transportManager.add(this.configureComponent(`transport-${f}`,u(this.components)))}),e.services!=null)for(let u of Object.keys(e.services)){let f=e.services[u],l=f(this.components);if(l==null){this.log.error("service factory %s returned null or undefined instance",u);continue}this.services[u]=l,this.configureComponent(u,l),l[Ja]!=null&&(this.log("registering service %s for content routing",u),c.push(l[Ja])),l[ec]!=null&&(this.log("registering service %s for peer routing",u),a.push(l[ec])),l[Qa]!=null&&(this.log("registering service %s for peer discovery",u),l[Qa].addEventListener?.("peer",h=>{this.#e(h)}))}Wp(i)}configureComponent(e,t){return t==null&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}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(e){throw this.log.error("An error occurred starting libp2p",e),this.status="started",await this.stop(),e}}}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(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new _r;for(let t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,n={}){if(t==null)throw new D("no protocols were provided to open a stream");if(t=Array.isArray(t)?t:[t],t.length===0)throw new D("no protocols were provided to open a stream");return(await this.dial(e,n)).newStream(t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){nr(e)&&(e=gt(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;try{let i=await this.peerStore.get(e);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let n=Fe([N("/pk/"),e.toMultihash().bytes]),s=await this.contentRouting.get(n,t),o=pn(s);return await this.peerStore.patch(e,{publicKey:o}),o}async handle(e,t,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async s=>{await this.components.registrar.handle(s,t,n)}))}async unhandle(e){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async t=>{await this.components.registrar.unhandle(t)}))}async register(e,t){return this.components.registrar.register(e,t)}unregister(e){this.components.registrar.unregister(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#e(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error(n)})}};async function px(r={}){r.privateKey??=await _d("Ed25519");let e=new Xa({...await cp(r),peerId:kd(r.privateKey)});return r.start!==!1&&await e.start(),e}return Nm(mx);})();
|
|
19
|
+
`),t),t.log('handle: responded with "na" for "%s"',s)}}var lx=500,tf=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;limits;log;tags;_newStream;_close;_abort;_getStreams;constructor(e){let{remoteAddr:t,remotePeer:n,newStream:s,close:o,abort:i,getStreams:a}=e;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=t,this.remotePeer=n,this.direction=e.direction,this.status="open",this.timeline=e.timeline,this.multiplexer=e.multiplexer,this.encryption=e.encryption,this.limits=e.limits,this.log=e.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`),this.remoteAddr.getPeerId()==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this._newStream=s,this._close=o,this._abort=i,this._getStreams=a,this.tags=[]}[Symbol.toStringTag]="Connection";[ff]=!0;get streams(){return this._getStreams()}async newStream(e,t){if(this.status==="closing")throw new Ws("the connection is being closed");if(this.status==="closed")throw new $r("the connection is closed");if(Array.isArray(e)||(e=[e]),this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new Gr("Cannot open protocol stream on limited connection");let n=await this._newStream(e,t);return n.direction="outbound",n}async close(e={}){if(!(this.status==="closed"||this.status==="closing")){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",e.signal==null){let t=AbortSignal.timeout(lx);e={...e,signal:t}}try{this.log.trace("closing underlying transport"),await this._close(e),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(t){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,t),this.abort(t)}}}abort(e){this.status!=="closed"&&(this.log.error("aborting connection to %a due to error",this.remoteAddr,e),this.status="closing",this._abort(e),this.status="closed",this.timeline.close=Date.now())}};function mm(r){return new tf(r)}function hx(r,e){try{let{options:t}=e.getHandler(r);return t.maxInboundStreams}catch(t){if(t.name!=="UnhandledProtocolError")throw t}return Zu}function dx(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.name!=="UnhandledProtocolError")throw n}return t.maxOutboundStreams??Xu}function gm(r,e,t){let n=0;return t.streams.forEach(s=>{s.direction===e&&s.protocol===r&&n++}),n}var Za=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;outboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;constructor(e,t){this.components=e,this.connectionEncrypters=new Map,t.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=new Map,t.streamMuxers.forEach(n=>{this.streamMuxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??3e3,this.outboundUpgradeTimeout=t.outboundUpgradeTimeout??3e3,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??2e3,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??2e3,this.events=e.events,this.metrics={dials:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,...t){let n=this.components.connectionGater[e];if(n==null)return;if(await n.apply(this.components.connectionGater,t)===!0)throw new la(`The multiaddr connection is blocked by gater.${e}`)}async upgradeInbound(e,t={}){let n=!1;try{if(this.metrics.dials?.increment({inbound:!0}),n=await this.components.connectionManager.acceptIncomingConnection(e),!n)throw new ua("Connection denied");await this.shouldBlockConnection("denyInboundConnection",e),await this._performUpgrade(e,"inbound",t)}catch(s){throw this.metrics.errors?.increment({inbound:!0}),s}finally{n&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t={}){try{this.metrics.dials?.increment({outbound:!0});let n=e.remoteAddr.getPeerId(),s;n!=null&&(s=gt(n),await this.shouldBlockConnection("denyOutboundConnection",s,e));let o="outbound";return t.initiator===!1&&(o="inbound"),await this._performUpgrade(e,o,t)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),n}}async _performUpgrade(e,t,n){let s,o,i,a,c,u=AbortSignal.timeout(t==="inbound"?this.inboundUpgradeTimeout:this.outboundUpgradeTimeout),f=Ft([u,n.signal]);n.signal=f,this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t);let l=e;if(n?.skipProtection!==!0){let h=this.components.connectionProtector;h!=null&&(e.log("protecting the %s connection",t),l=await h.protect(e,n))}try{if(s=l,n?.skipEncryption!==!0){n?.onProgress?.(new fe(`upgrader:encrypt-${t}-connection`)),{conn:s,remotePeer:o,protocol:c}=await(t==="inbound"?this._encryptInbound(l,{...n,signal:f}):this._encryptOutbound(l,{...n,signal:f}));let h={...l,...s};await this.shouldBlockConnection(t==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",o,h)}else{let h=e.remoteAddr.getPeerId();if(h==null)throw new Ht(`${t} connection that skipped encryption must have a peer id`);let p=gt(h);c="native",o=p}if(o.equals(this.components.peerId)){let h=new qr("Can not dial self");throw e.abort(h),h}if(i=s,n?.muxerFactory!=null)a=n.muxerFactory;else if(this.streamMuxers.size>0){n?.onProgress?.(new fe(`upgrader:multiplex-${t}-connection`));let h=await(t==="inbound"?this._multiplexInbound({...l,...s},this.streamMuxers,n):this._multiplexOutbound({...l,...s},this.streamMuxers,n));a=h.muxerFactory,i=h.stream}}catch(h){throw e.log.error("failed to upgrade inbound connection %s %a - %e",t==="inbound"?"from":"to",e.remoteAddr,h),h}finally{f.clear()}return await this.shouldBlockConnection(t==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",o,e),e.log("successfully upgraded %s connection",t),this._createConnection({cryptoProtocol:c,direction:t,maConn:e,upgradedConn:i,muxerFactory:a,remotePeer:o,limits:n?.limits})}_createConnection(e){let{cryptoProtocol:t,direction:n,maConn:s,upgradedConn:o,remotePeer:i,muxerFactory:a,limits:c}=e,u,f,l;a!=null&&(u=a.createStreamMuxer({direction:n,onIncomingStream:m=>{l!=null&&Promise.resolve().then(async()=>{let g=this.components.registrar.getProtocols(),d=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);let{stream:w,protocol:x}=await Ks(m,g,{signal:d,log:m.log,yieldBytes:!1});if(l==null)return;l.log("incoming stream opened on %s",x);let y=hx(x,this.components.registrar);if(gm(x,"inbound",l)===y){let _=new Qs(`Too many inbound protocol streams for protocol "${x}" - limit ${y}`);throw m.abort(_),_}m.source=w.source,m.sink=w.sink,m.protocol=x,w.closeWrite!=null&&(m.closeWrite=w.closeWrite),w.closeRead!=null&&(m.closeRead=w.closeRead),w.close!=null&&(m.close=w.close),await this.components.peerStore.merge(i,{protocols:[x]}),this.components.metrics?.trackProtocolStream(m,l),this._onStream({connection:l,stream:m,protocol:x})}).catch(async g=>{l.log.error("error handling incoming stream id %s - %e",m.id,g),m.timeline.close==null&&await m.close()})}}),f=async(m,g={})=>{if(u==null)throw new Mr("Connection is not multiplexed");l.log.trace("starting new stream for protocols %s",m);let d=await u.newStream();l.log.trace("started new stream %s for protocols %s",d.id,m);try{if(g.signal==null){d.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",m);let _=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);g={...g,signal:_}}d.log.trace("selecting protocol from protocols %s",m);let{stream:w,protocol:x}=await Vs(d,m,{...g,log:d.log,yieldBytes:!0});d.log.trace("selected protocol %s",x);let y=dx(x,this.components.registrar,g),E=gm(x,"outbound",l);if(E>=y){let _=new eo(`Too many outbound protocol streams for protocol "${x}" - ${E}/${y}`);throw d.abort(_),_}return await this.components.peerStore.merge(i,{protocols:[x]}),d.source=w.source,d.sink=w.sink,d.protocol=x,w.closeWrite!=null&&(d.closeWrite=w.closeWrite),w.closeRead!=null&&(d.closeRead=w.closeRead),w.close!=null&&(d.close=w.close),this.components.metrics?.trackProtocolStream(d,l),d}catch(w){throw l.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",n==="inbound"?"from":"to",e.maConn.remoteAddr,m,w),d.timeline.close==null&&d.abort(w),w}},Promise.all([u.sink(o.source),o.sink(u.source)]).catch(m=>{l.log.error("error piping data through muxer - %e",m)}));let h=s.timeline;s.timeline=new Proxy(h,{set:(...m)=>(m[1]==="close"&&m[2]!=null&&h.close==null&&(async()=>{try{l.status==="open"&&await l.close()}catch(g){l.log.error("error closing connection after timeline close %e",g)}finally{this.events.safeDispatchEvent("connection:close",{detail:l})}})().catch(g=>{l.log.error("error thrown while dispatching connection:close event %e",g)}),Reflect.set(...m))}),s.timeline.upgraded=Date.now();let p=()=>{throw new Mr("Connection is not multiplexed")};return l=mm({remoteAddr:s.remoteAddr,remotePeer:i,status:"open",direction:n,timeline:s.timeline,multiplexer:u?.protocol,encryption:t,limits:c,logger:this.components.logger,newStream:f??p,getStreams:()=>u?.streams??[],close:async m=>{await u?.close(m),await s.close(m)},abort:m=>{s.abort(m),u?.abort(m)}}),this.events.safeDispatchEvent("connection:open",{detail:l}),l.__maConnTimeline=h,l}_onStream(e){let{connection:t,stream:n,protocol:s}=e,{handler:o,options:i}=this.components.registrar.getHandler(s);if(t.limits!=null&&i.runOnLimitedConnection!==!0)throw new Gr("Cannot open protocol stream on limited connection");o({connection:t,stream:n})}async _encryptInbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{let{stream:s,protocol:o}=await Ks(e,n,{...t,log:e.log}),i=this.connectionEncrypters.get(o);if(i==null)throw new Or(`no crypto module found for ${o}`);return e.log("encrypting inbound connection to %a using %s",e.remoteAddr,o),{...await i.secureInbound(s,t),protocol:o}}catch(s){throw e.log.error("encrypting inbound connection from %a failed",e.remoteAddr,s),new Or(s.message)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",n);let{stream:s,protocol:o}=await Vs(e,n,{...t,log:e.log,yieldBytes:!0}),i=this.connectionEncrypters.get(o);if(i==null)throw new Or(`no crypto module found for ${o}`);return e.log("encrypting outbound connection to %a using %s",e.remoteAddr,o),{...await i.secureOutbound(s,t),protocol:o}}catch(s){throw e.log.error("encrypting outbound connection to %a failed",e.remoteAddr,s),new Or(s.message)}}async _multiplexOutbound(e,t,n){let s=Array.from(t.keys());e.log("outbound selecting muxer %s",s);try{e.log.trace("selecting stream muxer from %s",s);let{stream:o,protocol:i}=await Vs(e,s,{...n,log:e.log,yieldBytes:!0});e.log("selected %s as muxer protocol",i);let a=t.get(i);return{stream:o,muxerFactory:a}}catch(o){throw e.log.error("error multiplexing outbound connection",o),new Mr(String(o))}}async _multiplexInbound(e,t,n){let s=Array.from(t.keys());e.log("inbound handling muxers %s",s);try{let{stream:o,protocol:i}=await Ks(e,s,{...n,log:e.log}),a=t.get(i);return{stream:o,muxerFactory:a}}catch(o){throw e.log.error("error multiplexing inbound connection",o),new Mr(String(o))}}};var ym="2.6.1",$s="js-libp2p";function bm(r,e){return`${r??$s}/${e??ym} browser/${globalThis.navigator.userAgent}`}var Xa=class extends xt{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new xt,n=t.dispatchEvent.bind(t);t.dispatchEvent=u=>{let f=n(u),l=this.dispatchEvent(new CustomEvent(u.type,{detail:u.detail}));return f||l},this.peerId=e.peerId,this.logger=e.logger??Ni(),this.log=this.logger.forComponent("libp2p"),this.services={};let s=e.nodeInfo?.name??$s,o=e.nodeInfo?.version??$s,i=this.components=Gp({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:s,version:o,userAgent:e.nodeInfo?.userAgent??bm(s,o)},logger:this.logger,events:t,datastore:e.datastore??new Wi,connectionGater:jp(e.connectionGater),dns:e.dns});this.peerStore=this.configureComponent("peerStore",kp(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),i.events.addEventListener("peer:update",u=>{if(u.detail.previous==null){let f={id:u.detail.peer.id,multiaddrs:u.detail.peer.addresses.map(l=>l.multiaddr)};i.events.safeDispatchEvent("peer:discovery",{detail:f})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new Za(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map((u,f)=>this.configureComponent(`connection-encryption-${f}`,u(this.components))),streamMuxers:(e.streamMuxers??[]).map((u,f)=>this.configureComponent(`stream-muxers-${f}`,u(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,outboundUpgradeTimeout:e.connectionManager?.outboundUpgradeTimeout}),this.configureComponent("transportManager",new Fa(this.components,e.transportManager)),this.configureComponent("connectionManager",new ka(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new Na(this.components,e.connectionMonitor)),this.configureComponent("registrar",new Ua(this.components)),this.configureComponent("addressManager",new na(this.components,e.addresses));let a=(e.peerRouters??[]).map((u,f)=>this.configureComponent(`peer-router-${f}`,u(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new Ma(this.components,{routers:a}));let c=(e.contentRouters??[]).map((u,f)=>this.configureComponent(`content-router-${f}`,u(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new Da(this.components,{routers:c})),this.configureComponent("randomWalk",new Oa(this.components)),(e.peerDiscovery??[]).forEach((u,f)=>{this.configureComponent(`peer-discovery-${f}`,u(this.components)).addEventListener("peer",h=>{this.#e(h)})}),e.transports?.forEach((u,f)=>{this.components.transportManager.add(this.configureComponent(`transport-${f}`,u(this.components)))}),e.services!=null)for(let u of Object.keys(e.services)){let f=e.services[u],l=f(this.components);if(l==null){this.log.error("service factory %s returned null or undefined instance",u);continue}this.services[u]=l,this.configureComponent(u,l),l[Ja]!=null&&(this.log("registering service %s for content routing",u),c.push(l[Ja])),l[ec]!=null&&(this.log("registering service %s for peer routing",u),a.push(l[ec])),l[Qa]!=null&&(this.log("registering service %s for peer discovery",u),l[Qa].addEventListener?.("peer",h=>{this.#e(h)}))}Wp(i)}configureComponent(e,t){return t==null&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}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(e){throw this.log.error("An error occurred starting libp2p",e),this.status="started",await this.stop(),e}}}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(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new _r;for(let t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,n={}){if(t==null)throw new D("no protocols were provided to open a stream");if(t=Array.isArray(t)?t:[t],t.length===0)throw new D("no protocols were provided to open a stream");return(await this.dial(e,n)).newStream(t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){nr(e)&&(e=gt(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;try{let i=await this.peerStore.get(e);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let n=Fe([N("/pk/"),e.toMultihash().bytes]),s=await this.contentRouting.get(n,t),o=pn(s);return await this.peerStore.patch(e,{publicKey:o}),o}async handle(e,t,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async s=>{await this.components.registrar.handle(s,t,n)}))}async unhandle(e){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async t=>{await this.components.registrar.unhandle(t)}))}async register(e,t){return this.components.registrar.register(e,t)}unregister(e){this.components.registrar.unregister(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#e(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error(n)})}};async function px(r={}){r.privateKey??=await _d("Ed25519");let e=new Xa({...await cp(r),peerId:kd(r.privateKey)});return r.start!==!1&&await e.start(),e}return Nm(mx);})();
|
|
20
20
|
/*! Bundled license information:
|
|
21
21
|
|
|
22
22
|
pvtsutils/build/index.js:
|
package/dist/src/version.d.ts
CHANGED
package/dist/src/version.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "libp2p",
|
|
3
|
-
"version": "2.6.
|
|
3
|
+
"version": "2.6.1",
|
|
4
4
|
"description": "JavaScript implementation of libp2p, a modular peer to peer network stack",
|
|
5
5
|
"license": "Apache-2.0 OR MIT",
|
|
6
6
|
"homepage": "https://github.com/libp2p/js-libp2p/tree/main/packages/libp2p#readme",
|
|
@@ -54,6 +54,7 @@
|
|
|
54
54
|
},
|
|
55
55
|
"./user-agent": {
|
|
56
56
|
"types": "./dist/src/user-agent.d.ts",
|
|
57
|
+
"browser": "./dist/src/user-agent.browser.js",
|
|
57
58
|
"import": "./dist/src/user-agent.js"
|
|
58
59
|
},
|
|
59
60
|
"./version": {
|
package/src/version.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export const version = '2.6.
|
|
1
|
+
export const version = '2.6.1'
|
|
2
2
|
export const name = 'js-libp2p'
|