libp2p 2.0.0-7cd984569 → 2.0.0

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
@@ -16,7 +16,7 @@ ${t.join(`
16
16
  `),e),e.log.trace('handle: responded with "%s" for "%s"',o,o),{stream:n.unwrap(),protocol:o};if(o==="ls"){let s=new wt(...t.map(i=>Sa.single(P(`${i}
17
17
  `))),P(`
18
18
  `));e.log.trace('handle: respond with "%s" for %s',t,o),await Tr(n,s,e),e.log.trace('handle: responded with "%s" for %s',t,o);continue}e.log('handle: respond with "na" for "%s"',o),await Tr(n,P(`na
19
- `),e),e.log('handle: responded with "na" for "%s"',o)}}var cb=500,_u=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;limits;log;tags;_newStream;_close;_abort;_getStreams;constructor(t){let{remoteAddr:e,remotePeer:n,newStream:o,close:s,abort:i,getStreams:a}=t;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=e,this.remotePeer=n,this.direction=t.direction,this.status="open",this.timeline=t.timeline,this.multiplexer=t.multiplexer,this.encryption=t.encryption,this.limits=t.limits,this.log=t.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`),this.remoteAddr.getPeerId()==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this._newStream=o,this._close=s,this._abort=i,this._getStreams=a,this.tags=[]}[Symbol.toStringTag]="Connection";[Ru]=!0;get streams(){return this._getStreams()}async newStream(t,e){if(this.status==="closing")throw new Ro("the connection is being closed");if(this.status==="closed")throw new Do("the connection is closed");if(Array.isArray(t)||(t=[t]),this.limits!=null&&e?.runOnLimitedConnection!==!0)throw new Mr("Cannot open protocol stream on limited connection");let n=await this._newStream(t,e);return n.direction="outbound",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(cb);tt(1/0,e),t={...t,signal:e}}try{this.log.trace("closing all streams"),await Promise.all(this.streams.map(async e=>e.close(t))),this.log.trace("closing underlying transport"),await this._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.log.error("aborting connection to %a due to error",this.remoteAddr,t),this.status="closing",this.streams.forEach(e=>{e.abort(t)}),this.log.error("all streams aborted",this.streams.length),this._abort(t),this.timeline.close=Date.now(),this.status="closed"}};function Np(r){return new _u(r)}var lb=3e4;function ub(r,t){try{let{options:e}=t.getHandler(r);return e.maxInboundStreams}catch(e){if(e.name!=="UnhandledProtocolError")throw e}return bu}function fb(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??xu}function Pp(r,t,e){let n=0;return e.streams.forEach(o=>{o.direction===t&&o.protocol===r&&n++}),n}var ka=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;events;constructor(t,e){this.components=t,this.connectionEncrypters=new Map,e.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=new Map,e.streamMuxers.forEach(n=>{this.streamMuxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=e.inboundUpgradeTimeout??2e3,this.events=t.events}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(t,e,n){let o=this.components.connectionGater[n];if(o!==void 0&&await o(t,e))throw new Ao(`The multiaddr connection is blocked by gater.${n}`)}async upgradeInbound(t,e){if(!await this.components.connectionManager.acceptIncomingConnection(t))throw new zi("connection denied");let o,s,i,a,c,u=AbortSignal.timeout(this.inboundUpgradeTimeout),f=()=>{t.abort(new Rr("inbound upgrade timeout"))};u.addEventListener("abort",f,{once:!0}),tt(1/0,u);try{if(await this.components.connectionGater.denyInboundConnection?.(t)===!0)throw new Ao("The multiaddr connection is blocked by gater.acceptConnection");this.components.metrics?.trackMultiaddrConnection(t),t.log("starting the inbound connection upgrade");let l=t;if(e?.skipProtection!==!0){let d=this.components.connectionProtector;d!=null&&(t.log("protecting the inbound connection"),l=await d.protect(t))}try{if(o=l,e?.skipEncryption!==!0){e?.onProgress?.(new ft("upgrader:encrypt-inbound-connection")),{conn:o,remotePeer:s,protocol:c}=await this._encryptInbound(l);let d={...l,...o};await this.shouldBlockConnection(s,d,"denyInboundEncryptedConnection")}else{let d=t.remoteAddr.getPeerId();if(d==null)throw new Pr("inbound connection that skipped encryption must have a peer id");let h=ge(d);c="native",s=h}if(i=o,e?.muxerFactory!=null)a=e.muxerFactory;else if(this.streamMuxers.size>0){e?.onProgress?.(new ft("upgrader:multiplex-inbound-connection"));let d=await this._multiplexInbound({...l,...o},this.streamMuxers);a=d.muxerFactory,i=d.stream}}catch(d){throw t.log.error("failed to upgrade inbound connection",d),d}return await this.shouldBlockConnection(s,t,"denyInboundUpgradedConnection"),t.log("successfully upgraded inbound connection"),this._createConnection({cryptoProtocol:c,direction:"inbound",maConn:t,upgradedConn:i,muxerFactory:a,remotePeer:s,limits:e?.limits})}finally{u.removeEventListener("abort",f),this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(t,e){let n=t.remoteAddr.getPeerId(),o;n!=null&&(o=ge(n),await this.shouldBlockConnection(o,t,"denyOutboundConnection"));let s,i,a,c,u;this.components.metrics?.trackMultiaddrConnection(t),t.log("starting the outbound connection upgrade");let f=t;if(e?.skipProtection!==!0){let l=this.components.connectionProtector;l!=null&&(f=await l.protect(t))}try{if(s=f,e?.skipEncryption!==!0){({conn:s,remotePeer:i,protocol:c}=await this._encryptOutbound(f,{...e,remotePeer:o}));let l={...f,...s};await this.shouldBlockConnection(i,l,"denyOutboundEncryptedConnection")}else{if(o==null)throw new Uo("Encryption was skipped but no peer id was passed");c="native",i=o}if(a=s,e?.muxerFactory!=null)u=e.muxerFactory;else if(this.streamMuxers.size>0){let l=await this._multiplexOutbound({...f,...s},this.streamMuxers);u=l.muxerFactory,a=l.stream}}catch(l){throw t.log.error("failed to upgrade outbound connection",l),await t.close(l),l}return await this.shouldBlockConnection(i,t,"denyOutboundUpgradedConnection"),t.log("successfully upgraded outbound connection"),this._createConnection({cryptoProtocol:c,direction:"outbound",maConn:t,upgradedConn:a,muxerFactory:u,remotePeer:i,limits:e?.limits})}_createConnection(t){let{cryptoProtocol:e,direction:n,maConn:o,upgradedConn:s,remotePeer:i,muxerFactory:a,limits:c}=t,u,f,l;a!=null&&(u=a.createStreamMuxer({direction:n,onIncomingStream:p=>{l!=null&&Promise.resolve().then(async()=>{let m=this.components.registrar.getProtocols(),{stream:g,protocol:y}=await To(p,m,{log:p.log,yieldBytes:!1});if(l==null)return;l.log("incoming stream opened on %s",y);let b=ub(y,this.components.registrar);if(Pp(y,"inbound",l)===b){let x=new Ho(`Too many inbound protocol streams for protocol "${y}" - limit ${b}`);throw p.abort(x),x}p.source=g.source,p.sink=g.sink,p.protocol=y,g.closeWrite!=null&&(p.closeWrite=g.closeWrite),g.closeRead!=null&&(p.closeRead=g.closeRead),g.close!=null&&(p.close=g.close),await this.components.peerStore.merge(i,{protocols:[y]}),this.components.metrics?.trackProtocolStream(p,l),this._onStream({connection:l,stream:p,protocol:y})}).catch(async m=>{l.log.error("error handling incoming stream id %s",p.id,m.message,m.code,m.stack),p.timeline.close==null&&await p.close()})}}),f=async(p,m={})=>{if(u==null)throw new Ir("Connection is not multiplexed");l.log("starting new stream for protocols %s",p);let g=await u.newStream();l.log.trace("started new stream %s for protocols %s",g.id,p);try{if(m.signal==null){g.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",p);let A=AbortSignal.timeout(lb);tt(1/0,A),m={...m,signal:A}}g.log.trace("selecting protocol from protocols %s",p);let{stream:y,protocol:b}=await ko(g,p,{...m,log:g.log,yieldBytes:!0});g.log("selected protocol %s",b);let w=fb(b,this.components.registrar,m),x=Pp(b,"outbound",l);if(x>=w){let A=new $o(`Too many outbound protocol streams for protocol "${b}" - ${x}/${w}`);throw g.abort(A),A}return await this.components.peerStore.merge(i,{protocols:[b]}),g.source=y.source,g.sink=y.sink,g.protocol=b,y.closeWrite!=null&&(g.closeWrite=y.closeWrite),y.closeRead!=null&&(g.closeRead=y.closeRead),y.close!=null&&(g.close=y.close),this.components.metrics?.trackProtocolStream(g,l),g}catch(y){throw l.log.error("could not create new stream for protocols %s",p,y),g.timeline.close==null&&g.abort(y),y}},Promise.all([u.sink(s.source),s.sink(u.source)]).catch(p=>{l.log.error("error piping data through muxer",p)}));let d=o.timeline;o.timeline=new Proxy(d,{set:(...p)=>(l!=null&&p[1]==="close"&&p[2]!=null&&d.close==null&&(async()=>{try{l.status==="open"&&await l.close()}catch(m){l.log.error("error closing connection after timeline close",m)}finally{this.events.safeDispatchEvent("connection:close",{detail:l})}})().catch(m=>{l.log.error("error thrown while dispatching connection:close event",m)}),Reflect.set(...p))}),o.timeline.upgraded=Date.now();let h=()=>{throw new Ir("Connection is not multiplexed")};return l=Np({remoteAddr:o.remoteAddr,remotePeer:i,status:"open",direction:n,timeline:o.timeline,multiplexer:u?.protocol,encryption:e,limits:c,logger:this.components.logger,newStream:f??h,getStreams:()=>u!=null?u.streams:[],close:async p=>{u!=null&&(l.log.trace("close muxer"),await u.close(p)),l.log.trace("close maconn"),await o.close(p),l.log.trace("closed maconn")},abort:p=>{o.abort(p),u?.abort(p)}}),this.events.safeDispatchEvent("connection:open",{detail:l}),l}_onStream(t){let{connection:e,stream:n,protocol:o}=t,{handler:s,options:i}=this.components.registrar.getHandler(o);if(e.limits!=null&&i.runOnLimitedConnection!==!0)throw new Mr("Cannot open protocol stream on limited connection");s({connection:e,stream:n})}async _encryptInbound(t,e){let n=Array.from(this.connectionEncrypters.keys());t.log("handling inbound crypto protocol selection",n);try{let{stream:o,protocol:s}=await To(t,n,{log:t.log}),i=this.connectionEncrypters.get(s);if(i==null)throw new Error(`no crypto module found for ${s}`);return t.log("encrypting inbound connection using",s),{...await i.secureInbound(o,e),protocol:s}}catch(o){throw t.log.error("encrypting inbound connection failed",o),new So(o.message)}}async _encryptOutbound(t,e){let n=Array.from(this.connectionEncrypters.keys());t.log("selecting outbound crypto protocol",n);try{t.log.trace("selecting encrypter from %s",n);let{stream:o,protocol:s}=await ko(t,n,{log:t.log,yieldBytes:!0}),i=this.connectionEncrypters.get(s);if(i==null)throw new Error(`no crypto module found for ${s}`);return t.log("encrypting outbound connection to %p using %s",e?.remotePeer,i),{...await i.secureOutbound(o,e),protocol:s}}catch(o){throw t.log.error("encrypting outbound connection to %p failed",e?.remotePeer,o),new So(o.message)}}async _multiplexOutbound(t,e){let n=Array.from(e.keys());t.log("outbound selecting muxer %s",n);try{t.log.trace("selecting stream muxer from %s",n);let{stream:o,protocol:s}=await ko(t,n,{log:t.log,yieldBytes:!0});t.log("selected %s as muxer protocol",s);let i=e.get(s);return{stream:o,muxerFactory:i}}catch(o){throw t.log.error("error multiplexing outbound connection",o),new Ir(String(o))}}async _multiplexInbound(t,e){let n=Array.from(e.keys());t.log("inbound handling muxers %s",n);try{let{stream:o,protocol:s}=await To(t,n,{log:t.log}),i=e.get(s);return{stream:o,muxerFactory:i}}catch(o){throw t.log.error("error multiplexing inbound connection",o),new Ir(String(o))}}};var Rp="2.0.0-7cd984569",Dp="libp2p";var Ca=class extends ve{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(t){super(),this.status="stopped";let e=new ve,n=e.dispatchEvent.bind(e);e.dispatchEvent=a=>{let c=n(a),u=this.dispatchEvent(new CustomEvent(a.type,{detail:a.detail}));return c||u},tt(1/0,e),this.peerId=t.peerId,this.logger=t.logger??Ei(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=this.components=up({peerId:t.peerId,privateKey:t.privateKey,nodeInfo:t.nodeInfo??{name:Dp,version:Rp},logger:this.logger,events:e,datastore:t.datastore??new Oi,connectionGater:hp(t.connectionGater),dns:t.dns});this.peerStore=this.configureComponent("peerStore",new Di(o,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...t.peerStore})),t.metrics!=null&&(this.metrics=this.configureComponent("metrics",t.metrics(this.components))),o.events.addEventListener("peer:update",a=>{if(a.detail.previous==null){let c={id:a.detail.peer.id,multiaddrs:a.detail.peer.addresses.map(u=>u.multiaddr)};o.events.safeDispatchEvent("peer:discovery",{detail:c})}}),t.connectionProtector!=null&&this.configureComponent("connectionProtector",t.connectionProtector(o)),this.components.upgrader=new ka(this.components,{connectionEncrypters:(t.connectionEncrypters??[]).map((a,c)=>this.configureComponent(`connection-encryption-${c}`,a(this.components))),streamMuxers:(t.streamMuxers??[]).map((a,c)=>this.configureComponent(`stream-muxers-${c}`,a(this.components))),inboundUpgradeTimeout:t.connectionManager?.inboundUpgradeTimeout}),this.configureComponent("transportManager",new wa(this.components,t.transportManager)),this.configureComponent("connectionManager",new ca(this.components,t.connectionManager)),t.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new ha(this.components,t.connectionMonitor)),this.configureComponent("registrar",new ya(this.components)),this.configureComponent("addressManager",new Fi(this.components,t.addresses));let s=(t.peerRouters??[]).map((a,c)=>this.configureComponent(`peer-router-${c}`,a(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new ma(this.components,{routers:s}));let i=(t.contentRouters??[]).map((a,c)=>this.configureComponent(`content-router-${c}`,a(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new da(this.components,{routers:i})),this.configureComponent("randomWalk",new ga(this.components)),(t.peerDiscovery??[]).forEach((a,c)=>{this.configureComponent(`peer-discovery-${c}`,a(this.components)).addEventListener("peer",f=>{this.#t(f)})}),t.transports?.forEach((a,c)=>{this.components.transportManager.add(this.configureComponent(`transport-${c}`,a(this.components)))}),t.services!=null)for(let a of Object.keys(t.services)){let c=t.services[a],u=c(this.components);if(u==null){this.log.error("service factory %s returned null or undefined instance",a);continue}this.services[a]=u,this.configureComponent(a,u),u[La]!=null&&(this.log("registering service %s for content routing",a),i.push(u[La])),u[Pa]!=null&&(this.log("registering service %s for peer routing",a),s.push(u[Pa])),u[Na]!=null&&(this.log("registering service %s for peer discovery",a),u[Na].addEventListener?.("peer",f=>{this.#t(f)}))}fp(o)}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 br;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 D("no protocols were provided to open a stream");if(e=Array.isArray(e)?e:[e],e.length===0)throw new D("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={}){Qe(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);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let n=Ft([P("/pk/"),t.toMultihash().bytes]),o=await this.contentRouting.get(n,e),s=nn(o);return await this.peerStore.patch(t,{publicKey:s}),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){Array.isArray(t)||(t=[t]),await Promise.all(t.map(async e=>{await this.components.registrar.unhandle(e)}))}async register(t,e){return this.components.registrar.register(t,e)}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 db(r={}){r.privateKey??=await Wh("Ed25519");let t=new Ca({...await Od(r),peerId:Yh(r.privateKey)});return r.start!==!1&&await t.start(),t}return Zp(pb);})();
19
+ `),e),e.log('handle: responded with "na" for "%s"',o)}}var cb=500,_u=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;limits;log;tags;_newStream;_close;_abort;_getStreams;constructor(t){let{remoteAddr:e,remotePeer:n,newStream:o,close:s,abort:i,getStreams:a}=t;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=e,this.remotePeer=n,this.direction=t.direction,this.status="open",this.timeline=t.timeline,this.multiplexer=t.multiplexer,this.encryption=t.encryption,this.limits=t.limits,this.log=t.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`),this.remoteAddr.getPeerId()==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this._newStream=o,this._close=s,this._abort=i,this._getStreams=a,this.tags=[]}[Symbol.toStringTag]="Connection";[Ru]=!0;get streams(){return this._getStreams()}async newStream(t,e){if(this.status==="closing")throw new Ro("the connection is being closed");if(this.status==="closed")throw new Do("the connection is closed");if(Array.isArray(t)||(t=[t]),this.limits!=null&&e?.runOnLimitedConnection!==!0)throw new Mr("Cannot open protocol stream on limited connection");let n=await this._newStream(t,e);return n.direction="outbound",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(cb);tt(1/0,e),t={...t,signal:e}}try{this.log.trace("closing all streams"),await Promise.all(this.streams.map(async e=>e.close(t))),this.log.trace("closing underlying transport"),await this._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.log.error("aborting connection to %a due to error",this.remoteAddr,t),this.status="closing",this.streams.forEach(e=>{e.abort(t)}),this.log.error("all streams aborted",this.streams.length),this._abort(t),this.timeline.close=Date.now(),this.status="closed"}};function Np(r){return new _u(r)}var lb=3e4;function ub(r,t){try{let{options:e}=t.getHandler(r);return e.maxInboundStreams}catch(e){if(e.name!=="UnhandledProtocolError")throw e}return bu}function fb(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??xu}function Pp(r,t,e){let n=0;return e.streams.forEach(o=>{o.direction===t&&o.protocol===r&&n++}),n}var ka=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;events;constructor(t,e){this.components=t,this.connectionEncrypters=new Map,e.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=new Map,e.streamMuxers.forEach(n=>{this.streamMuxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=e.inboundUpgradeTimeout??2e3,this.events=t.events}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(t,e,n){let o=this.components.connectionGater[n];if(o!==void 0&&await o(t,e))throw new Ao(`The multiaddr connection is blocked by gater.${n}`)}async upgradeInbound(t,e){if(!await this.components.connectionManager.acceptIncomingConnection(t))throw new zi("connection denied");let o,s,i,a,c,u=AbortSignal.timeout(this.inboundUpgradeTimeout),f=()=>{t.abort(new Rr("inbound upgrade timeout"))};u.addEventListener("abort",f,{once:!0}),tt(1/0,u);try{if(await this.components.connectionGater.denyInboundConnection?.(t)===!0)throw new Ao("The multiaddr connection is blocked by gater.acceptConnection");this.components.metrics?.trackMultiaddrConnection(t),t.log("starting the inbound connection upgrade");let l=t;if(e?.skipProtection!==!0){let d=this.components.connectionProtector;d!=null&&(t.log("protecting the inbound connection"),l=await d.protect(t))}try{if(o=l,e?.skipEncryption!==!0){e?.onProgress?.(new ft("upgrader:encrypt-inbound-connection")),{conn:o,remotePeer:s,protocol:c}=await this._encryptInbound(l);let d={...l,...o};await this.shouldBlockConnection(s,d,"denyInboundEncryptedConnection")}else{let d=t.remoteAddr.getPeerId();if(d==null)throw new Pr("inbound connection that skipped encryption must have a peer id");let h=ge(d);c="native",s=h}if(i=o,e?.muxerFactory!=null)a=e.muxerFactory;else if(this.streamMuxers.size>0){e?.onProgress?.(new ft("upgrader:multiplex-inbound-connection"));let d=await this._multiplexInbound({...l,...o},this.streamMuxers);a=d.muxerFactory,i=d.stream}}catch(d){throw t.log.error("failed to upgrade inbound connection",d),d}return await this.shouldBlockConnection(s,t,"denyInboundUpgradedConnection"),t.log("successfully upgraded inbound connection"),this._createConnection({cryptoProtocol:c,direction:"inbound",maConn:t,upgradedConn:i,muxerFactory:a,remotePeer:s,limits:e?.limits})}finally{u.removeEventListener("abort",f),this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(t,e){let n=t.remoteAddr.getPeerId(),o;n!=null&&(o=ge(n),await this.shouldBlockConnection(o,t,"denyOutboundConnection"));let s,i,a,c,u;this.components.metrics?.trackMultiaddrConnection(t),t.log("starting the outbound connection upgrade");let f=t;if(e?.skipProtection!==!0){let l=this.components.connectionProtector;l!=null&&(f=await l.protect(t))}try{if(s=f,e?.skipEncryption!==!0){({conn:s,remotePeer:i,protocol:c}=await this._encryptOutbound(f,{...e,remotePeer:o}));let l={...f,...s};await this.shouldBlockConnection(i,l,"denyOutboundEncryptedConnection")}else{if(o==null)throw new Uo("Encryption was skipped but no peer id was passed");c="native",i=o}if(a=s,e?.muxerFactory!=null)u=e.muxerFactory;else if(this.streamMuxers.size>0){let l=await this._multiplexOutbound({...f,...s},this.streamMuxers);u=l.muxerFactory,a=l.stream}}catch(l){throw t.log.error("failed to upgrade outbound connection",l),await t.close(l),l}return await this.shouldBlockConnection(i,t,"denyOutboundUpgradedConnection"),t.log("successfully upgraded outbound connection"),this._createConnection({cryptoProtocol:c,direction:"outbound",maConn:t,upgradedConn:a,muxerFactory:u,remotePeer:i,limits:e?.limits})}_createConnection(t){let{cryptoProtocol:e,direction:n,maConn:o,upgradedConn:s,remotePeer:i,muxerFactory:a,limits:c}=t,u,f,l;a!=null&&(u=a.createStreamMuxer({direction:n,onIncomingStream:p=>{l!=null&&Promise.resolve().then(async()=>{let m=this.components.registrar.getProtocols(),{stream:g,protocol:y}=await To(p,m,{log:p.log,yieldBytes:!1});if(l==null)return;l.log("incoming stream opened on %s",y);let b=ub(y,this.components.registrar);if(Pp(y,"inbound",l)===b){let x=new Ho(`Too many inbound protocol streams for protocol "${y}" - limit ${b}`);throw p.abort(x),x}p.source=g.source,p.sink=g.sink,p.protocol=y,g.closeWrite!=null&&(p.closeWrite=g.closeWrite),g.closeRead!=null&&(p.closeRead=g.closeRead),g.close!=null&&(p.close=g.close),await this.components.peerStore.merge(i,{protocols:[y]}),this.components.metrics?.trackProtocolStream(p,l),this._onStream({connection:l,stream:p,protocol:y})}).catch(async m=>{l.log.error("error handling incoming stream id %s",p.id,m.message,m.code,m.stack),p.timeline.close==null&&await p.close()})}}),f=async(p,m={})=>{if(u==null)throw new Ir("Connection is not multiplexed");l.log("starting new stream for protocols %s",p);let g=await u.newStream();l.log.trace("started new stream %s for protocols %s",g.id,p);try{if(m.signal==null){g.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",p);let A=AbortSignal.timeout(lb);tt(1/0,A),m={...m,signal:A}}g.log.trace("selecting protocol from protocols %s",p);let{stream:y,protocol:b}=await ko(g,p,{...m,log:g.log,yieldBytes:!0});g.log("selected protocol %s",b);let w=fb(b,this.components.registrar,m),x=Pp(b,"outbound",l);if(x>=w){let A=new $o(`Too many outbound protocol streams for protocol "${b}" - ${x}/${w}`);throw g.abort(A),A}return await this.components.peerStore.merge(i,{protocols:[b]}),g.source=y.source,g.sink=y.sink,g.protocol=b,y.closeWrite!=null&&(g.closeWrite=y.closeWrite),y.closeRead!=null&&(g.closeRead=y.closeRead),y.close!=null&&(g.close=y.close),this.components.metrics?.trackProtocolStream(g,l),g}catch(y){throw l.log.error("could not create new stream for protocols %s",p,y),g.timeline.close==null&&g.abort(y),y}},Promise.all([u.sink(s.source),s.sink(u.source)]).catch(p=>{l.log.error("error piping data through muxer",p)}));let d=o.timeline;o.timeline=new Proxy(d,{set:(...p)=>(l!=null&&p[1]==="close"&&p[2]!=null&&d.close==null&&(async()=>{try{l.status==="open"&&await l.close()}catch(m){l.log.error("error closing connection after timeline close",m)}finally{this.events.safeDispatchEvent("connection:close",{detail:l})}})().catch(m=>{l.log.error("error thrown while dispatching connection:close event",m)}),Reflect.set(...p))}),o.timeline.upgraded=Date.now();let h=()=>{throw new Ir("Connection is not multiplexed")};return l=Np({remoteAddr:o.remoteAddr,remotePeer:i,status:"open",direction:n,timeline:o.timeline,multiplexer:u?.protocol,encryption:e,limits:c,logger:this.components.logger,newStream:f??h,getStreams:()=>u!=null?u.streams:[],close:async p=>{u!=null&&(l.log.trace("close muxer"),await u.close(p)),l.log.trace("close maconn"),await o.close(p),l.log.trace("closed maconn")},abort:p=>{o.abort(p),u?.abort(p)}}),this.events.safeDispatchEvent("connection:open",{detail:l}),l}_onStream(t){let{connection:e,stream:n,protocol:o}=t,{handler:s,options:i}=this.components.registrar.getHandler(o);if(e.limits!=null&&i.runOnLimitedConnection!==!0)throw new Mr("Cannot open protocol stream on limited connection");s({connection:e,stream:n})}async _encryptInbound(t,e){let n=Array.from(this.connectionEncrypters.keys());t.log("handling inbound crypto protocol selection",n);try{let{stream:o,protocol:s}=await To(t,n,{log:t.log}),i=this.connectionEncrypters.get(s);if(i==null)throw new Error(`no crypto module found for ${s}`);return t.log("encrypting inbound connection using",s),{...await i.secureInbound(o,e),protocol:s}}catch(o){throw t.log.error("encrypting inbound connection failed",o),new So(o.message)}}async _encryptOutbound(t,e){let n=Array.from(this.connectionEncrypters.keys());t.log("selecting outbound crypto protocol",n);try{t.log.trace("selecting encrypter from %s",n);let{stream:o,protocol:s}=await ko(t,n,{log:t.log,yieldBytes:!0}),i=this.connectionEncrypters.get(s);if(i==null)throw new Error(`no crypto module found for ${s}`);return t.log("encrypting outbound connection to %p using %s",e?.remotePeer,i),{...await i.secureOutbound(o,e),protocol:s}}catch(o){throw t.log.error("encrypting outbound connection to %p failed",e?.remotePeer,o),new So(o.message)}}async _multiplexOutbound(t,e){let n=Array.from(e.keys());t.log("outbound selecting muxer %s",n);try{t.log.trace("selecting stream muxer from %s",n);let{stream:o,protocol:s}=await ko(t,n,{log:t.log,yieldBytes:!0});t.log("selected %s as muxer protocol",s);let i=e.get(s);return{stream:o,muxerFactory:i}}catch(o){throw t.log.error("error multiplexing outbound connection",o),new Ir(String(o))}}async _multiplexInbound(t,e){let n=Array.from(e.keys());t.log("inbound handling muxers %s",n);try{let{stream:o,protocol:s}=await To(t,n,{log:t.log}),i=e.get(s);return{stream:o,muxerFactory:i}}catch(o){throw t.log.error("error multiplexing inbound connection",o),new Ir(String(o))}}};var Rp="2.0.0",Dp="libp2p";var Ca=class extends ve{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(t){super(),this.status="stopped";let e=new ve,n=e.dispatchEvent.bind(e);e.dispatchEvent=a=>{let c=n(a),u=this.dispatchEvent(new CustomEvent(a.type,{detail:a.detail}));return c||u},tt(1/0,e),this.peerId=t.peerId,this.logger=t.logger??Ei(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=this.components=up({peerId:t.peerId,privateKey:t.privateKey,nodeInfo:t.nodeInfo??{name:Dp,version:Rp},logger:this.logger,events:e,datastore:t.datastore??new Oi,connectionGater:hp(t.connectionGater),dns:t.dns});this.peerStore=this.configureComponent("peerStore",new Di(o,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...t.peerStore})),t.metrics!=null&&(this.metrics=this.configureComponent("metrics",t.metrics(this.components))),o.events.addEventListener("peer:update",a=>{if(a.detail.previous==null){let c={id:a.detail.peer.id,multiaddrs:a.detail.peer.addresses.map(u=>u.multiaddr)};o.events.safeDispatchEvent("peer:discovery",{detail:c})}}),t.connectionProtector!=null&&this.configureComponent("connectionProtector",t.connectionProtector(o)),this.components.upgrader=new ka(this.components,{connectionEncrypters:(t.connectionEncrypters??[]).map((a,c)=>this.configureComponent(`connection-encryption-${c}`,a(this.components))),streamMuxers:(t.streamMuxers??[]).map((a,c)=>this.configureComponent(`stream-muxers-${c}`,a(this.components))),inboundUpgradeTimeout:t.connectionManager?.inboundUpgradeTimeout}),this.configureComponent("transportManager",new wa(this.components,t.transportManager)),this.configureComponent("connectionManager",new ca(this.components,t.connectionManager)),t.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new ha(this.components,t.connectionMonitor)),this.configureComponent("registrar",new ya(this.components)),this.configureComponent("addressManager",new Fi(this.components,t.addresses));let s=(t.peerRouters??[]).map((a,c)=>this.configureComponent(`peer-router-${c}`,a(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new ma(this.components,{routers:s}));let i=(t.contentRouters??[]).map((a,c)=>this.configureComponent(`content-router-${c}`,a(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new da(this.components,{routers:i})),this.configureComponent("randomWalk",new ga(this.components)),(t.peerDiscovery??[]).forEach((a,c)=>{this.configureComponent(`peer-discovery-${c}`,a(this.components)).addEventListener("peer",f=>{this.#t(f)})}),t.transports?.forEach((a,c)=>{this.components.transportManager.add(this.configureComponent(`transport-${c}`,a(this.components)))}),t.services!=null)for(let a of Object.keys(t.services)){let c=t.services[a],u=c(this.components);if(u==null){this.log.error("service factory %s returned null or undefined instance",a);continue}this.services[a]=u,this.configureComponent(a,u),u[La]!=null&&(this.log("registering service %s for content routing",a),i.push(u[La])),u[Pa]!=null&&(this.log("registering service %s for peer routing",a),s.push(u[Pa])),u[Na]!=null&&(this.log("registering service %s for peer discovery",a),u[Na].addEventListener?.("peer",f=>{this.#t(f)}))}fp(o)}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 br;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 D("no protocols were provided to open a stream");if(e=Array.isArray(e)?e:[e],e.length===0)throw new D("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={}){Qe(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);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let n=Ft([P("/pk/"),t.toMultihash().bytes]),o=await this.contentRouting.get(n,e),s=nn(o);return await this.peerStore.patch(t,{publicKey:s}),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){Array.isArray(t)||(t=[t]),await Promise.all(t.map(async e=>{await this.components.registrar.unhandle(e)}))}async register(t,e){return this.components.registrar.register(t,e)}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 db(r={}){r.privateKey??=await Wh("Ed25519");let t=new Ca({...await Od(r),peerId:Yh(r.privateKey)});return r.start!==!1&&await t.start(),t}return Zp(pb);})();
20
20
  /*! Bundled license information:
21
21
 
22
22
  pvtsutils/build/index.js:
@@ -1,3 +1,3 @@
1
- export declare const version = "2.0.0-7cd984569";
1
+ export declare const version = "2.0.0";
2
2
  export declare const name = "libp2p";
3
3
  //# sourceMappingURL=version.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,OAAO,oBAAoB,CAAA;AACxC,eAAO,MAAM,IAAI,WAAW,CAAA"}
1
+ {"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,OAAO,UAAU,CAAA;AAC9B,eAAO,MAAM,IAAI,WAAW,CAAA"}
@@ -1,3 +1,3 @@
1
- export const version = '2.0.0-7cd984569';
1
+ export const version = '2.0.0';
2
2
  export const name = 'libp2p';
3
3
  //# sourceMappingURL=version.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,OAAO,GAAG,iBAAiB,CAAA;AACxC,MAAM,CAAC,MAAM,IAAI,GAAG,QAAQ,CAAA"}
1
+ {"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,OAAO,GAAG,OAAO,CAAA;AAC9B,MAAM,CAAC,MAAM,IAAI,GAAG,QAAQ,CAAA"}
@@ -0,0 +1,14 @@
1
+ {
2
+ "Libp2pInit": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.index.Libp2pInit.html",
3
+ ".:Libp2pInit": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.index.Libp2pInit.html",
4
+ "Libp2pOptions": "https://libp2p.github.io/js-libp2p/types/libp2p.index.Libp2pOptions.html",
5
+ ".:Libp2pOptions": "https://libp2p.github.io/js-libp2p/types/libp2p.index.Libp2pOptions.html",
6
+ "ServiceFactoryMap": "https://libp2p.github.io/js-libp2p/types/libp2p.index.ServiceFactoryMap.html",
7
+ ".:ServiceFactoryMap": "https://libp2p.github.io/js-libp2p/types/libp2p.index.ServiceFactoryMap.html",
8
+ "createLibp2p": "https://libp2p.github.io/js-libp2p/functions/libp2p.index.createLibp2p.html",
9
+ ".:createLibp2p": "https://libp2p.github.io/js-libp2p/functions/libp2p.index.createLibp2p.html",
10
+ "name": "https://libp2p.github.io/js-libp2p/variables/libp2p.version.name.html",
11
+ "./version:name": "https://libp2p.github.io/js-libp2p/variables/libp2p.version.name.html",
12
+ "version": "https://libp2p.github.io/js-libp2p/variables/libp2p.version.version.html",
13
+ "./version:version": "https://libp2p.github.io/js-libp2p/variables/libp2p.version.version.html"
14
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "libp2p",
3
- "version": "2.0.0-7cd984569",
3
+ "version": "2.0.0",
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",
@@ -85,15 +85,15 @@
85
85
  "test:webkit": "aegir test -t browser -f \"./dist/test/**/*.spec.js\" -- --browser webkit"
86
86
  },
87
87
  "dependencies": {
88
- "@libp2p/crypto": "5.0.0-7cd984569",
89
- "@libp2p/interface": "2.0.0-7cd984569",
90
- "@libp2p/interface-internal": "2.0.0-7cd984569",
91
- "@libp2p/logger": "5.0.0-7cd984569",
92
- "@libp2p/multistream-select": "6.0.0-7cd984569",
93
- "@libp2p/peer-collections": "6.0.0-7cd984569",
94
- "@libp2p/peer-id": "5.0.0-7cd984569",
95
- "@libp2p/peer-store": "11.0.0-7cd984569",
96
- "@libp2p/utils": "6.0.0-7cd984569",
88
+ "@libp2p/crypto": "^5.0.0",
89
+ "@libp2p/interface": "^2.0.0",
90
+ "@libp2p/interface-internal": "^2.0.0",
91
+ "@libp2p/logger": "^5.0.0",
92
+ "@libp2p/multistream-select": "^6.0.0",
93
+ "@libp2p/peer-collections": "^6.0.0",
94
+ "@libp2p/peer-id": "^5.0.0",
95
+ "@libp2p/peer-store": "^11.0.0",
96
+ "@libp2p/utils": "^6.0.0",
97
97
  "@multiformats/dns": "^1.0.6",
98
98
  "@multiformats/multiaddr": "^12.2.3",
99
99
  "@multiformats/multiaddr-matcher": "^1.2.1",
@@ -113,14 +113,14 @@
113
113
  "uint8arrays": "^5.1.0"
114
114
  },
115
115
  "devDependencies": {
116
- "@chainsafe/libp2p-yamux": "^7.0.0",
117
- "@libp2p/circuit-relay-v2": "2.0.0-7cd984569",
118
- "@libp2p/identify": "3.0.0-7cd984569",
119
- "@libp2p/interface-compliance-tests": "6.0.0-7cd984569",
120
- "@libp2p/mplex": "11.0.0-7cd984569",
121
- "@libp2p/plaintext": "2.0.0-7cd984569",
122
- "@libp2p/tcp": "10.0.0-7cd984569",
123
- "@libp2p/websockets": "9.0.0-7cd984569",
116
+ "@chainsafe/libp2p-yamux": "^6.0.2",
117
+ "@libp2p/circuit-relay-v2": "^2.0.0",
118
+ "@libp2p/identify": "^3.0.0",
119
+ "@libp2p/interface-compliance-tests": "^6.0.0",
120
+ "@libp2p/mplex": "^11.0.0",
121
+ "@libp2p/plaintext": "^2.0.0",
122
+ "@libp2p/tcp": "^10.0.0",
123
+ "@libp2p/websockets": "^9.0.0",
124
124
  "@multiformats/mafmt": "^12.1.6",
125
125
  "aegir": "^44.0.1",
126
126
  "delay": "^6.0.0",
package/src/version.ts CHANGED
@@ -1,2 +1,2 @@
1
- export const version = '2.0.0-7cd984569'
1
+ export const version = '2.0.0'
2
2
  export const name = 'libp2p'