libp2p 1.0.5-10ea19700 → 1.0.5-bcfa15993

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
@@ -45,7 +45,7 @@
45
45
  (?:${ke}:){1}(?:(?::${ke}){0,4}:${qt}|(?::${ke}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4
46
46
  (?::(?:(?::${ke}){0,5}:${qt}|(?::${ke}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4
47
47
  )(?:%[0-9a-zA-Z]{1,})? // %eth0 %1
48
- `.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),$w=new RegExp(`(?:^${qt}$)|(?:^${Io}$)`),zw=new RegExp(`^${qt}$`),Hw=new RegExp(`^${Io}$`),Zu=t=>t&&t.exact?$w:new RegExp(`(?:${Kr(t)}${qt}${Kr(t)})|(?:${Kr(t)}${Io}${Kr(t)})`,"g");Zu.v4=t=>t&&t.exact?zw:new RegExp(`${Kr(t)}${qt}${Kr(t)}`,"g");Zu.v6=t=>t&&t.exact?Hw:new RegExp(`${Kr(t)}${Io}${Kr(t)}`,"g");var rp=Zu;var ap=ve(ip(),1),{isValid:Gw,parse:Ww}=ap.default,Yw=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"],Qw=Yw.map(t=>new op.Netmask(t));function Xw(t){for(let e of Qw)if(e.contains(t))return!0;return!1}function sp(t){return/^::$/.test(t)||/^::1$/.test(t)||/^::f{4}:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(t)||/^::f{4}:0.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(t)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(t)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(t)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(t)||/^ff([0-9a-fA-F]{2,2}):/i.test(t)}var cp=t=>{if(Gw(t)){let e=Ww(t);if(e.kind()==="ipv4")return Xw(e.toNormalizedString());if(e.kind()==="ipv6")return sp(t)}else if(Xn(t)&&rp.v6().test(t))return sp(t)};var Co=cp;function up(t={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let r=e.stringTuples();return r[0][0]===4||r[0][0]===41?!!Co(`${r[0][1]}`):!1},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...t}}var Zw=t=>t.toString().split("/").slice(1),Xi=t=>({match:e=>e.length<1?!1:t(e[0])?e.slice(1):!1,pattern:"fn"}),Le=t=>({match:e=>Xi(r=>r===t).match(e),pattern:t}),Lo=()=>({match:t=>Xi(e=>typeof e=="string").match(t),pattern:"{string}"}),lp=()=>({match:t=>Xi(e=>!isNaN(parseInt(e))).match(t),pattern:"{number}"}),Ct=()=>({match:t=>{if(t.length<2||t[0]!=="p2p"&&t[0]!=="ipfs")return!1;if(t[1].startsWith("Q")||t[1].startsWith("1"))try{_e.decode(`z${t[1]}`)}catch{return!1}else return!1;return t.slice(2)},pattern:"/p2p/{peerid}"}),To=()=>({match:t=>{if(t.length<2||t[0]!=="certhash")return!1;try{ja.decode(t[1])}catch{return!1}return t.slice(2)},pattern:"/certhash/{certhash}"}),jt=t=>({match:e=>{let r=t.match(e);return r===!1?e:r},pattern:`optional(${t.pattern})`}),Jt=(...t)=>({match:e=>{let r;for(let n of t){let i=n.match(e);i!==!1&&(r==null||i.length<r.length)&&(r=i)}return r??!1},pattern:`or(${t.map(e=>e.pattern).join(", ")})`}),Pe=(...t)=>({match:e=>{for(let r of t){let n=r.match(e);if(n===!1)return!1;e=n}return e},pattern:`and(${t.map(e=>e.pattern).join(", ")})`});function Fe(...t){function e(i){let s=Zw(i);for(let o of t){let a=o.match(s);if(a===!1)return!1;s=a}return s}function r(i){return e(i)!==!1}function n(i){let s=e(i);return s===!1?!1:s.length===0}return{matches:r,exactMatch:n}}var Ju=Pe(Le("dns4"),Lo()),el=Pe(Le("dns6"),Lo()),tl=Pe(Le("dnsaddr"),Lo()),fp=Pe(Le("dns"),Lo()),T3=Fe(Ju),B3=Fe(el),L3=Fe(tl),P3=Fe(Jt(fp,tl,Ju,el)),hp=Pe(Le("ip4"),Xi(eo)),dp=Pe(Le("ip6"),Xi(to)),pp=Jt(hp,dp),Zi=Jt(pp,fp,Ju,el,tl),D3=Fe(Zi),N3=Fe(hp),k3=Fe(dp),O3=Fe(pp),Po=Pe(Zi,Le("tcp"),lp()),ji=Pe(Zi,Le("udp"),lp()),jw=Jt(Po,ji),M3=Fe(Po),U3=Fe(ji),rl=Pe(ji,Le("quic")),Do=Pe(ji,Le("quic-v1")),Jw=Jt(rl,Do),F3=Fe(rl),K3=Fe(Do),ju=Jt(Zi,Po,ji,rl,Do),mp=Jt(Pe(ju,Le("ws"),jt(Ct()))),q3=Fe(mp),yp=Jt(Pe(ju,Le("wss"),jt(Ct())),Pe(ju,Le("tls"),Le("ws"),jt(Ct()))),V3=Fe(yp),gp=Pe(jw,Le("webrtc-direct"),To(),jt(To()),jt(Ct())),$3=Fe(gp),xp=Pe(Do,Le("webtransport"),To(),To(),jt(Ct())),z3=Fe(xp),Bo=Jt(mp,yp,Pe(Po,jt(Ct())),Pe(Jw,jt(Ct())),Pe(Zi,jt(Ct())),gp,xp,Ct()),H3=Fe(Bo),eE=Pe(Bo,Le("p2p-circuit"),Ct()),nl=Fe(eE),tE=Jt(Pe(Bo,Le("p2p-circuit"),Le("webrtc"),Ct()),Pe(Bo,Le("webrtc"),jt(Ct())),Le("webrtc")),G3=Fe(tE);function il(t){try{let{address:e}=t.nodeAddress();return!!Co(e)}catch{return!0}}function rE(t,e){let r=il(t.multiaddr),n=il(e.multiaddr);return r&&!n?1:!r&&n?-1:0}function nE(t,e){return t.isCertified&&!e.isCertified?-1:!t.isCertified&&e.isCertified?1:0}function iE(t,e){let r=nl.exactMatch(t.multiaddr),n=nl.exactMatch(e.multiaddr);return r&&!n?1:!r&&n?-1:0}function ri(t,e){let r=rE(t,e);if(r!==0)return r;let n=iE(t,e);return n!==0?n:nE(t,e)}var ol=ve(ru(),1),al=ve(Ep(),1);function No(t,e,r){return`${t}?name=${e}&type=${r}`}async function vp(t,e){return await(await fetch(t,{headers:new Headers({accept:"application/dns-json"}),signal:e})).json()}function gn(t,e){return`${e}_${t}`}var sl=Object.assign((0,ol.default)("dns-over-http-resolver"),{error:(0,ol.default)("dns-over-http-resolver:error")}),cl=class{_cache;_TXTcache;_servers;_request;_abortControllers;constructor(e={}){this._cache=new al.default({max:e?.maxCache??100}),this._TXTcache=new al.default({max:e?.maxCache??100}),this._servers=["https://cloudflare-dns.com/dns-query","https://dns.google/resolve"],this._request=e.request??vp,this._abortControllers=[]}cancel(){this._abortControllers.forEach(e=>{e.abort()})}getServers(){return this._servers}_getShuffledServers(){let e=[...this._servers];for(let r=e.length-1;r>0;r--){let n=Math.floor(Math.random()*r),i=e[r];e[r]=e[n],e[n]=i}return e}setServers(e){this._servers=e}async resolve(e,r="A"){switch(r){case"A":return this.resolve4(e);case"AAAA":return this.resolve6(e);case"TXT":return this.resolveTxt(e);default:throw new Error(`${r} is not supported`)}}async resolve4(e){let r="A",n=this._cache.get(gn(e,r));if(n!=null)return n;let i=!1;for(let s of this._getShuffledServers()){let o=new AbortController;this._abortControllers.push(o);try{let a=await this._request(No(s,e,r),o.signal),c=a.Answer.map(l=>l.data),u=Math.min(...a.Answer.map(l=>l.TTL));return this._cache.set(gn(e,r),c,{ttl:u}),c}catch{o.signal.aborted&&(i=!0),sl.error(`${s} could not resolve ${e} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==o)}}throw i?Object.assign(new Error("queryA ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${r}`)}async resolve6(e){let r="AAAA",n=this._cache.get(gn(e,r));if(n!=null)return n;let i=!1;for(let s of this._getShuffledServers()){let o=new AbortController;this._abortControllers.push(o);try{let a=await this._request(No(s,e,r),o.signal),c=a.Answer.map(l=>l.data),u=Math.min(...a.Answer.map(l=>l.TTL));return this._cache.set(gn(e,r),c,{ttl:u}),c}catch{o.signal.aborted&&(i=!0),sl.error(`${s} could not resolve ${e} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==o)}}throw i?Object.assign(new Error("queryAaaa ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${r}`)}async resolveTxt(e){let r="TXT",n=this._TXTcache.get(gn(e,r));if(n!=null)return n;let i=!1;for(let s of this._getShuffledServers()){let o=new AbortController;this._abortControllers.push(o);try{let a=await this._request(No(s,e,r),o.signal),c=a.Answer.map(l=>[l.data.replace(/['"]+/g,"")]),u=Math.min(...a.Answer.map(l=>l.TTL));return this._TXTcache.set(gn(e,r),c,{ttl:u}),c}catch{o.signal.aborted&&(i=!0),sl.error(`${s} could not resolve ${e} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==o)}}throw i?Object.assign(new Error("queryTxt ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${r}`)}clearCache(){this._cache.clear(),this._TXTcache.clear()}},_p=cl;var Sp=_p;var{code:uE}=fe("dnsaddr");async function ni(t,e={}){let r=new Sp;e.signal!=null&&e.signal.addEventListener("abort",()=>{r.cancel()});let n=t.getPeerId(),[,i]=t.stringTuples().find(([a])=>a===uE)??[];if(i==null)throw new Error("No hostname found in multiaddr");let o=(await r.resolveTxt(`_dnsaddr.${i}`)).flat().map(a=>a.split("=")[1]).filter(Boolean);return n!=null&&(o=o.filter(a=>a.includes(n))),o}var Dp=ve(Pp(),1),Mo=Dp.default;var er;(function(t){t.NOT_STARTED_YET="The libp2p node is not started yet",t.DHT_DISABLED="DHT is not available",t.PUBSUB_DISABLED="PubSub is not available",t.CONN_ENCRYPTION_REQUIRED="At least one connection encryption module is required",t.ERR_TRANSPORTS_REQUIRED="At least one transport module is required",t.ERR_PROTECTOR_REQUIRED="Private network is enforced, but no protector was provided",t.NOT_FOUND="Not found"})(er||(er={}));var F;(function(t){t.DHT_DISABLED="ERR_DHT_DISABLED",t.ERR_PUBSUB_DISABLED="ERR_PUBSUB_DISABLED",t.PUBSUB_NOT_STARTED="ERR_PUBSUB_NOT_STARTED",t.DHT_NOT_STARTED="ERR_DHT_NOT_STARTED",t.CONN_ENCRYPTION_REQUIRED="ERR_CONN_ENCRYPTION_REQUIRED",t.ERR_TRANSPORTS_REQUIRED="ERR_TRANSPORTS_REQUIRED",t.ERR_PROTECTOR_REQUIRED="ERR_PROTECTOR_REQUIRED",t.ERR_PEER_DIAL_INTERCEPTED="ERR_PEER_DIAL_INTERCEPTED",t.ERR_CONNECTION_INTERCEPTED="ERR_CONNECTION_INTERCEPTED",t.ERR_INVALID_PROTOCOLS_FOR_STREAM="ERR_INVALID_PROTOCOLS_FOR_STREAM",t.ERR_CONNECTION_ENDED="ERR_CONNECTION_ENDED",t.ERR_CONNECTION_FAILED="ERR_CONNECTION_FAILED",t.ERR_NODE_NOT_STARTED="ERR_NODE_NOT_STARTED",t.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",t.ERR_TOO_MANY_ADDRESSES="ERR_TOO_MANY_ADDRESSES",t.ERR_NO_VALID_ADDRESSES="ERR_NO_VALID_ADDRESSES",t.ERR_RELAYED_DIAL="ERR_RELAYED_DIAL",t.ERR_DIALED_SELF="ERR_DIALED_SELF",t.ERR_DISCOVERED_SELF="ERR_DISCOVERED_SELF",t.ERR_DUPLICATE_TRANSPORT="ERR_DUPLICATE_TRANSPORT",t.ERR_ENCRYPTION_FAILED="ERR_ENCRYPTION_FAILED",t.ERR_HOP_REQUEST_FAILED="ERR_HOP_REQUEST_FAILED",t.ERR_INVALID_KEY="ERR_INVALID_KEY",t.ERR_INVALID_MESSAGE="ERR_INVALID_MESSAGE",t.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",t.ERR_INVALID_PEER="ERR_INVALID_PEER",t.ERR_MUXER_UNAVAILABLE="ERR_MUXER_UNAVAILABLE",t.ERR_NOT_FOUND="ERR_NOT_FOUND",t.ERR_TRANSPORT_UNAVAILABLE="ERR_TRANSPORT_UNAVAILABLE",t.ERR_TRANSPORT_DIAL_FAILED="ERR_TRANSPORT_DIAL_FAILED",t.ERR_UNSUPPORTED_PROTOCOL="ERR_UNSUPPORTED_PROTOCOL",t.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED="ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED",t.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",t.ERR_SIGNATURE_NOT_VALID="ERR_SIGNATURE_NOT_VALID",t.ERR_FIND_SELF="ERR_FIND_SELF",t.ERR_NO_ROUTERS_AVAILABLE="ERR_NO_ROUTERS_AVAILABLE",t.ERR_CONNECTION_NOT_MULTIPLEXED="ERR_CONNECTION_NOT_MULTIPLEXED",t.ERR_NO_DIAL_TOKENS="ERR_NO_DIAL_TOKENS",t.ERR_INVALID_CMS="ERR_INVALID_CMS",t.ERR_MISSING_KEYS="ERR_MISSING_KEYS",t.ERR_NO_KEY="ERR_NO_KEY",t.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",t.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",t.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",t.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",t.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",t.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",t.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",t.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",t.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",t.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",t.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",t.ERR_MISSING_PUBLIC_KEY="ERR_MISSING_PUBLIC_KEY",t.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",t.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",t.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH",t.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",t.ERR_WRONG_PING_ACK="ERR_WRONG_PING_ACK",t.ERR_INVALID_RECORD="ERR_INVALID_RECORD",t.ERR_ALREADY_SUCCEEDED="ERR_ALREADY_SUCCEEDED",t.ERR_NO_HANDLER_FOR_PROTOCOL="ERR_NO_HANDLER_FOR_PROTOCOL",t.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS",t.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",t.ERR_CONNECTION_DENIED="ERR_CONNECTION_DENIED",t.ERR_TRANSFER_LIMIT_EXCEEDED="ERR_TRANSFER_LIMIT_EXCEEDED"})(F||(F={}));var mE={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:t=>t},connectionManager:{resolvers:{dnsaddr:ni},addressSorter:ri},transportManager:{faultTolerance:Er.FATAL_ALL}};function Np(t){let e=Mo(mE,t);if(e.transports==null||e.transports.length<1)throw new S(er.ERR_TRANSPORTS_REQUIRED,F.ERR_TRANSPORTS_REQUIRED);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new S(er.ERR_PROTECTOR_REQUIRED,F.ERR_PROTECTOR_REQUIRED);return e}var Pm=ve(Cm(),1);function Fo(t){if(_s(t))return{peerId:t,multiaddrs:[]};Array.isArray(t)||(t=[t]);let e;if(t.length>0){let r=t[0].getPeerId();e=r==null?void 0:ce(r),t.forEach(n=>{if(!Nr(n))throw new S("Invalid Multiaddr",F.ERR_INVALID_MULTIADDR);let i=n.getPeerId();if(i==null){if(e!=null)throw new S("Multiaddrs must all have the same peer id or have no peer id",F.ERR_INVALID_PARAMETERS)}else{let s=ce(i);if(e==null||!e.equals(s))throw new S("Multiaddrs must all have the same peer id or have no peer id",F.ERR_INVALID_PARAMETERS)}})}return{peerId:e,multiaddrs:t}}function ZE(t,e,r){let n=0,i=t.length;for(;i>0;){let s=Math.trunc(i/2),o=n+s;r(t[o],e)<=0?(n=++o,i-=s+1):i=s}return n}var Al=class{#e=[];enqueue(e,r){let n=r?.peerId,i=r?.priority??0;if(n==null)throw new S("missing peer id",x0);let s={priority:i,peerId:n,run:e};if(this.size>0&&this.#e[this.size-1].priority>=i){this.#e.push(s);return}let o=ZE(this.#e,s,(a,c)=>c.priority-a.priority);this.#e.splice(o,0,s)}dequeue(){return this.#e.shift()?.run}filter(e){if(e.peerId!=null){let r=e.peerId;return this.#e.filter(n=>r.equals(n.peerId)).map(n=>n.run)}return this.#e.filter(r=>r.priority===e.priority).map(r=>r.run)}get size(){return this.#e.length}},Ko=class extends Mr{constructor(e={}){super({...e,queueClass:Al})}hasJob(e){return this.sizeBy({peerId:e})>0}};var qo="last-dial-failure";var Vo=5,$o=100,zo=50,Tm=1e3*60*7;var xn={minConnections:Vo,maxQueueLength:100,autoDialConcurrency:25,autoDialPriority:0,autoDialInterval:5e3,autoDialPeerRetryThreshold:Tm,autoDialDiscoveredPeersDebounce:10},Ho=class{connectionManager;peerStore;queue;minConnections;autoDialPriority;autoDialIntervalMs;autoDialMaxQueueLength;autoDialPeerRetryThresholdMs;autoDialDiscoveredPeersDebounce;autoDialInterval;started;running;log;constructor(e,r){this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.minConnections=r.minConnections??xn.minConnections,this.autoDialPriority=r.autoDialPriority??xn.autoDialPriority,this.autoDialIntervalMs=r.autoDialInterval??xn.autoDialInterval,this.autoDialMaxQueueLength=r.maxQueueLength??xn.maxQueueLength,this.autoDialPeerRetryThresholdMs=r.autoDialPeerRetryThreshold??xn.autoDialPeerRetryThreshold,this.autoDialDiscoveredPeersDebounce=r.autoDialDiscoveredPeersDebounce??xn.autoDialDiscoveredPeersDebounce,this.log=e.logger.forComponent("libp2p:connection-manager:auto-dial"),this.started=!1,this.running=!1,this.queue=new Ko({concurrency:r.autoDialConcurrency??xn.autoDialConcurrency}),this.queue.addListener("error",i=>{this.log.error("error during auto-dial",i)}),e.events.addEventListener("connection:close",()=>{this.autoDial().catch(i=>{this.log.error(i)})});let n;e.events.addEventListener("peer:discovery",()=>{clearTimeout(n),n=setTimeout(()=>{this.autoDial().catch(i=>{this.log.error(i)})},this.autoDialDiscoveredPeersDebounce)})}isStarted(){return this.started}start(){this.autoDialInterval=setTimeout(()=>{this.autoDial().catch(e=>{this.log.error("error while autodialing",e)})},this.autoDialIntervalMs),this.started=!0}afterStart(){this.autoDial().catch(e=>{this.log.error("error while autodialing",e)})}stop(){this.queue.clear(),clearTimeout(this.autoDialInterval),this.started=!1,this.running=!1}async autoDial(){if(!this.started)return;let e=this.connectionManager.getConnectionsMap(),r=e.size;if(r>=this.minConnections){this.minConnections>0&&this.log.trace("have enough connections %d/%d",r,this.minConnections);return}if(this.queue.size>this.autoDialMaxQueueLength){this.log("not enough connections %d/%d but auto dial queue is full",r,this.minConnections);return}if(this.running){this.log("not enough connections %d/%d - but skipping autodial as it is already running",r,this.minConnections);return}this.running=!0,this.log("not enough connections %d/%d - will dial peers to increase the number of connections",r,this.minConnections);let n=new fn(this.connectionManager.getDialQueue().map(u=>u.peerId).filter(Boolean)),i=await this.peerStore.all({filters:[u=>u.addresses.length===0?(this.log.trace("not autodialing %p because they have no addresses",u.id),!1):e.has(u.id)?(this.log.trace("not autodialing %p because they are already connected",u.id),!1):n.has(u.id)?(this.log.trace("not autodialing %p because they are already being dialed",u.id),!1):this.queue.hasJob(u.id)?(this.log.trace("not autodialing %p because they are already being autodialed",u.id),!1):!0]}),s=i.sort(()=>Math.random()>.5?1:-1),o=new wt;for(let u of s)o.has(u.id)||o.set(u.id,[...u.tags.values()].reduce((l,f)=>l+f.value,0));let c=s.sort((u,l)=>{let f=o.get(u.id)??0,h=o.get(l.id)??0;return f>h?-1:f<h?1:0}).filter(u=>{let l=u.metadata.get(qo);if(l==null)return!0;let f=parseInt(se(l));return isNaN(f)?!0:Date.now()-f>this.autoDialPeerRetryThresholdMs});this.log("selected %d/%d peers to dial",c.length,i.length);for(let u of c)this.queue.add(async()=>{let l=this.connectionManager.getConnectionsMap().size;if(l>=this.minConnections){this.log("got enough connections now %d/%d",l,this.minConnections),this.queue.clear();return}this.log("connecting to a peerStore stored peer %p",u.id),await this.connectionManager.openConnection(u.id,{priority:this.autoDialPriority})},{peerId:u.id}).catch(l=>{this.log.error("could not connect to peerStore stored peer",l)});this.running=!1,this.started&&(this.autoDialInterval=setTimeout(()=>{this.autoDial().catch(u=>{this.log.error("error while autodialing",u)})},this.autoDialIntervalMs))}};var Bm={maxConnections:$o,allow:[]},Go=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(e,r={}){this.maxConnections=r.maxConnections??Bm.maxConnections,this.allow=r.allow??Bm.allow,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),e.events.addEventListener("connection:open",()=>{this.maybePruneConnections().catch(n=>{this.log.error(n)})})}async maybePruneConnections(){let e=this.connectionManager.getConnections(),r=e.length,n=Math.max(r-this.maxConnections,0);if(this.log("checking max connections limit %d/%d",r,this.maxConnections),r<=this.maxConnections)return;this.log("max connections limit exceeded %d/%d, pruning %d connection(s)",r,this.maxConnections,n);let i=new wt;for(let a of e){let c=a.remotePeer;if(!i.has(c)){i.set(c,0);try{let u=await this.peerStore.get(c);i.set(c,[...u.tags.values()].reduce((l,f)=>l+f.value,0))}catch(u){u.code!=="ERR_NOT_FOUND"&&this.log.error("error loading peer tags",u)}}}let s=e.sort((a,c)=>{let u=i.get(a.remotePeer)??0,l=i.get(c.remotePeer)??0;if(u>l)return 1;if(u<l)return-1;let f=a.timeline.open,h=c.timeline.open;return f<h?1:f>h?-1:0}),o=[];for(let a of s)if(this.log("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(u=>a.remoteAddr.toString().startsWith(u.toString()))||o.push(a),o.length===n)break;await Promise.all(o.map(async a=>{try{await a.close()}catch(c){this.log.error(c)}})),this.events.safeDispatchEvent("connection:prune",{detail:o})}};function Wo(t){let e=new globalThis.AbortController;function r(){e.abort();for(let s of t)s?.removeEventListener!=null&&s.removeEventListener("abort",r)}for(let s of t){if(s?.aborted===!0){r();break}s?.addEventListener!=null&&s.addEventListener("abort",r)}function n(){for(let s of t)s?.removeEventListener!=null&&s.removeEventListener("abort",r)}let i=e.signal;return i.clear=n,i}function ut(){let t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}async function Tl(t,e){if(!t.protoNames().includes("dnsaddr"))return[t];let n=await ev(t,e),o=(await Promise.all(n.map(async a=>Tl(a,e)))).flat().reduce((a,c)=>(a.find(u=>u.equals(c))==null&&a.push(c),a),[]);return e.log("resolved %s to",t,o.map(a=>a.toString())),o}async function ev(t,e){try{return t=Ue(t.toString()),await t.resolve(e)}catch(r){return e.log.error(`multiaddr ${t.toString()} could not be resolved`,r),[]}}function Lm(...t){let e=[];for(let n of t)n!=null&&(pt(1/0,n),e.push(n));let r=Wo(e);return pt(1/0,r),r}var Yo={addressSorter:ri,maxParallelDials:zo,maxPeerAddrsToDial:25,dialTimeout:3e4,resolvers:{dnsaddr:ni}},Qo=class{pendingDials;queue;peerId;peerStore;connectionGater;transportManager;addressSorter;maxPeerAddrsToDial;dialTimeout;inProgressDialCount;pendingDialCount;shutDownController;connections;log;constructor(e,r={}){this.addressSorter=r.addressSorter??Yo.addressSorter,this.maxPeerAddrsToDial=r.maxPeerAddrsToDial??Yo.maxPeerAddrsToDial,this.dialTimeout=r.dialTimeout??Yo.dialTimeout,this.connections=r.connections??new wt,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.connectionGater=e.connectionGater,this.transportManager=e.transportManager,this.shutDownController=new AbortController,pt(1/0,this.shutDownController.signal),this.pendingDialCount=e.metrics?.registerMetric("libp2p_dial_queue_pending_dials"),this.inProgressDialCount=e.metrics?.registerMetric("libp2p_dial_queue_in_progress_dials"),this.pendingDials=[];for(let[n,i]of Object.entries(r.resolvers??{}))no.set(n,i);this.queue=new Mr({concurrency:r.maxParallelDials??Yo.maxParallelDials}),this.queue.on("add",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("active",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("completed",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("error",n=>{this.log.error("error in dial queue",n),this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("empty",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("idle",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)})}stop(){this.shutDownController.abort()}async dial(e,r={}){let{peerId:n,multiaddrs:i}=Fo(e),s=i.map(h=>({multiaddr:h,isCertified:!1})),o=this.createDialAbortControllers(r.signal),a;try{a=await this.calculateMultiaddrs(n,s,{...r,signal:o})}catch(h){throw o.clear(),h}let c=Array.from(this.connections.values()).flat().find(h=>r.force===!0?!1:a.find(p=>p.multiaddr.equals(h.remoteAddr)));if(c!=null)return this.log("already connected to %a",c.remoteAddr),c;let u=this.pendingDials.find(h=>!!(h.peerId!=null&&n!=null&&h.peerId.equals(n)||a.map(({multiaddr:p})=>p.toString()).join()===h.multiaddrs.map(p=>p.toString()).join()));if(u!=null)return this.log("joining existing dial target for %p",n),o.clear(),u.promise;this.log("creating dial target for",a.map(({multiaddr:h})=>h.toString()));let l={id:tv(),status:"queued",peerId:n,multiaddrs:a.map(({multiaddr:h})=>h)};l.promise=this.performDial(l,{...r,signal:o}).finally(()=>{this.pendingDials=this.pendingDials.filter(h=>h.id!==l.id),o.clear()}).catch(async h=>{if(this.log.error("dial failed to %s",l.multiaddrs.map(p=>p.toString()).join(", "),h),n!=null)try{await this.peerStore.patch(n,{metadata:{[qo]:Q(Date.now().toString())}})}catch(p){this.log.error("could not update last dial failure key for %p",n,p)}throw o.aborted?new S(h.message,Ss):h}),this.pendingDials.push(l);let f=await l.promise;return c=Array.from(this.connections.values()).flat().find(h=>r.force===!0?!1:h.id!==f.id&&h.remoteAddr.equals(f.remoteAddr)),c!=null?(this.log("already connected to %a",c.remoteAddr),await f.close(),c):(this.log("connection opened to %a",f.remoteAddr),f)}createDialAbortControllers(e){let r=Wo([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e]);try{pt?.(1/0,r)}catch{}return r}async calculateMultiaddrs(e,r=[],n={}){if(e!=null){if(this.peerId.equals(e))throw new S("Tried to dial self",F.ERR_DIALED_SELF);if(await this.connectionGater.denyDialPeer?.(e)===!0)throw new S("The dial request is blocked by gater.allowDialPeer",F.ERR_PEER_DIAL_INTERCEPTED);if(r.length===0){this.log("loading multiaddrs for %p",e);try{let l=await this.peerStore.get(e);r.push(...l.addresses),this.log("loaded multiaddrs for %p",e,r.map(({multiaddr:f})=>f.toString()))}catch(l){if(l.code!==F.ERR_NOT_FOUND)throw l}}}let i=(await Promise.all(r.map(async l=>{let f=await Tl(l.multiaddr,{...n,log:this.log});return f.length===1&&f[0].equals(l.multiaddr)?l:f.map(h=>({multiaddr:h,isCertified:!1}))}))).flat();if(e!=null){let l=`/p2p/${e.toString()}`;i=i.map(f=>f.multiaddr.protos().pop()?.path===!0?f:f.multiaddr.getPeerId()==null?{multiaddr:f.multiaddr.encapsulate(l),isCertified:f.isCertified}:f)}let s=i.filter(l=>{if(this.transportManager.transportForMultiaddr(l.multiaddr)==null)return!1;let f=l.multiaddr.getPeerId();return e!=null&&f!=null?e.equals(f):!0}),o=new Map;for(let l of s){let f=l.multiaddr.toString(),h=o.get(f);if(h!=null){h.isCertified=h.isCertified||l.isCertified||!1;continue}o.set(f,l)}let a=[...o.values()];if((a.length===0||a.length>this.maxPeerAddrsToDial)&&(this.log("addresses for %p before filtering",e??"unknown peer",i.map(({multiaddr:l})=>l.toString())),this.log("addresses for %p after filtering",e??"unknown peer",a.map(({multiaddr:l})=>l.toString()))),a.length===0)throw new S("The dial request has no valid addresses",F.ERR_NO_VALID_ADDRESSES);if(a.length>this.maxPeerAddrsToDial)throw new S("dial with more addresses than allowed",F.ERR_TOO_MANY_ADDRESSES);let c=[];for(let l of a)this.connectionGater.denyDialMultiaddr!=null&&await this.connectionGater.denyDialMultiaddr(l.multiaddr)||c.push(l);let u=c.sort(this.addressSorter);if(u.length===0)throw new S("The connection gater denied all addresses in the dial request",F.ERR_NO_VALID_ADDRESSES);return u}async performDial(e,r={}){let n=e.multiaddrs.map(()=>new AbortController);try{let i=new Mr({concurrency:1});i.on("error",o=>{this.log.error("error dialing %s %o",e.multiaddrs,o)});let s=await Promise.any(e.multiaddrs.map(async(o,a)=>{let c=n[a];if(c==null)throw new S("dialAction did not come with an AbortController",F.ERR_INVALID_PARAMETERS);let u=Lm(c.signal,r.signal);u.addEventListener("abort",()=>{this.log("dial to %a aborted",o)});let l=ut();return await i.add(async()=>{if(u.aborted){this.log("dial to %a was aborted before reaching the head of the peer dial queue",o),l.reject(new Cn);return}await this.queue.add(async()=>{try{if(u.aborted){this.log("dial to %a was aborted before reaching the head of the dial queue",o),l.reject(new Cn);return}e.status="active";let f=await this.transportManager.dial(o,{...r,signal:u});if(c.signal.aborted){this.log("multiple dials succeeded, closing superfluous connection"),f.close().catch(h=>{this.log.error("error closing superfluous connection",h)}),l.reject(new Cn);return}n[a]=void 0,n.forEach(h=>{h!==void 0&&h.abort()}),this.log("dial to %a succeeded",o),l.resolve(f)}catch(f){this.log.error("error during dial of %a",o,f),l.reject(f)}},{...r,signal:u}).catch(f=>{l.reject(f)})},{signal:u}).catch(f=>{l.reject(f)}).finally(()=>{u.clear()}),l.promise}));if(s==null)throw new S("successful dial led to empty object returned from peer dial queue",F.ERR_TRANSPORT_DIAL_FAILED);return e.status="success",s}catch(i){throw e.status="error",e.multiaddrs.length===1&&i.name==="AggregateError"?i.errors[0]:i}}};function tv(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var iv=50,bn={minConnections:Vo,maxConnections:$o,inboundConnectionThreshold:5,maxIncomingPendingConnections:10,autoDialConcurrency:25,autoDialPriority:0,autoDialMaxQueueLength:100},Xo=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;autoDial;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;constructor(e,r={}){this.maxConnections=r.maxConnections??bn.maxConnections;let n=r.minConnections??bn.minConnections;if(this.maxConnections<n)throw new S("Connection Manager maxConnections must be greater than minConnections",F.ERR_INVALID_PARAMETERS);this.connections=new wt,this.started=!1,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),this.allow=(r.allow??[]).map(i=>Ue(i)),this.deny=(r.deny??[]).map(i=>Ue(i)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=r.maxIncomingPendingConnections??bn.maxIncomingPendingConnections,this.inboundConnectionRateLimiter=new Pm.RateLimiterMemory({points:r.inboundConnectionThreshold??bn.inboundConnectionThreshold,duration:1}),this.autoDial=new Ho({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{minConnections:n,autoDialConcurrency:r.autoDialConcurrency??bn.autoDialConcurrency,autoDialPriority:r.autoDialPriority??bn.autoDialPriority,maxQueueLength:r.autoDialMaxQueueLength??bn.autoDialMaxQueueLength}),this.connectionPruner=new Go({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new Qo({peerId:e.peerId,metrics:e.metrics,peerStore:e.peerStore,transportManager:e.transportManager,connectionGater:e.connectionGater,logger:e.logger},{addressSorter:r.addressSorter??ri,maxParallelDials:r.maxParallelDials??zo,maxPeerAddrsToDial:r.maxPeerAddrsToDial??25,dialTimeout:r.dialTimeout??3e4,resolvers:r.resolvers??{dnsaddr:ni},connections:this.connections})}isStarted(){return this.started}async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,outbound:0};for(let r of this.connections.values())for(let n of r)n.direction==="inbound"?e.inbound++:e.outbound++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let r of this.connections.values())for(let n of r)for(let i of n.streams){let s=`${i.direction} ${i.protocol??"unnegotiated"}`;e[s]=(e[s]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let e={};for(let n of this.connections.values())for(let i of n){let s={};for(let o of i.streams){let a=`${o.direction} ${o.protocol??"unnegotiated"}`;s[a]=(s[a]??0)+1}for(let[o,a]of Object.entries(s))e[o]=e[o]??[],e[o].push(a)}let r={};for(let[n,i]of Object.entries(e)){i=i.sort((o,a)=>o-a);let s=Math.floor(i.length*.9);r[n]=i[s]}return r}}),this.autoDial.start(),this.started=!0,this.log("started")}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[r=>r.tags.has(y0)]});await Promise.all(e.map(async r=>{await this.openConnection(r.id).catch(n=>{this.log.error(n)})}))}).catch(e=>{this.log.error(e)}),this.autoDial.afterStart()}async stop(){this.dialQueue.stop(),this.autoDial.stop();let e=[];for(let r of this.connections.values())for(let n of r)e.push((async()=>{try{await n.close()}catch(i){this.log.error(i)}})());this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}onConnect(e){this._onConnect(e).catch(r=>{this.log.error(r)})}async _onConnect(e){let{detail:r}=e;if(!this.started){await r.close();return}let n=r.remotePeer,i=this.connections.get(n),s=!1;i!=null?i.push(r):(s=!0,this.connections.set(n,[r])),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),s&&this.events.safeDispatchEvent("peer:connect",{detail:r.remotePeer})}onDisconnect(e){let{detail:r}=e;if(!this.started)return;let n=r.remotePeer,i=this.connections.get(n);i!=null&&i.length>1?(i=i.filter(s=>s.id!==r.id),this.connections.set(n,i)):i!=null&&(this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:r.remotePeer}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let r=[];for(let n of this.connections.values())r=r.concat(n);return r}getConnectionsMap(){return this.connections}async openConnection(e,r={}){if(!this.isStarted())throw new S("Not started",F.ERR_NODE_NOT_STARTED);r.signal?.throwIfAborted();let{peerId:n}=Fo(e);if(n!=null&&r.force!==!0){this.log("dial %p",n);let a=this.getConnections(n).find(c=>!c.transient);if(a!=null)return this.log("had an existing non-transient connection to %p",n),a}let i=await this.dialQueue.dial(e,{...r,priority:r.priority??iv}),s=this.connections.get(i.remotePeer);s==null&&(s=[],this.connections.set(i.remotePeer,s));let o=!1;for(let a of s)a.id===i.id&&(o=!0);return o||s.push(i),i}async closeConnections(e,r={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async i=>{try{await i.close(r)}catch(s){i.abort(s)}}))}async acceptIncomingConnection(e){if(this.deny.some(i=>e.remoteAddr.toString().startsWith(i.toString())))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(i=>e.remoteAddr.toString().startsWith(i.toString())))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){let i=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(i,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,i),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){return this.dialQueue.pendingDials}};var Zo=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},li=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Zo(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let r=this.head;this.head=r.next=new Zo(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let r=this.tail.next;this.tail.next=null,this.tail=r,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var Pl=class extends Error{type;code;constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function jo(t={}){return sv(r=>{let n=r.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},t)}function sv(t,e){e=e??{};let r=e.onEnd,n=new li,i,s,o,a=ut(),c=async()=>{try{return n.isEmpty()?o?{done:!0}:await new Promise((y,g)=>{s=x=>{s=null,n.push(x);try{y(t(n))}catch(b){g(b)}return i}}):t(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=ut()})}},u=y=>s!=null?s(y):(n.push(y),i),l=y=>(n=new li,s!=null?s({error:y}):(n.push({error:y}),i)),f=y=>{if(o)return i;if(e?.objectMode!==!0&&y?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:y})},h=y=>o?i:(o=!0,y!=null?l(y):u({done:!0})),p=()=>(n=new li,h(),{done:!0}),d=y=>(h(y),{done:!0});if(i={[Symbol.asyncIterator](){return this},next:c,return:p,throw:d,push:f,end:h,get readableLength(){return n.size},onEmpty:async y=>{let g=y?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let x,b;g!=null&&(x=new Promise((I,v)=>{b=()=>{v(new Pl)},g.addEventListener("abort",b)}));try{await Promise.race([a.promise,x])}finally{b!=null&&g!=null&&g?.removeEventListener("abort",b)}}},r==null)return i;let m=i;return i={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(y){return m.throw(y),r!=null&&(r(y),r=void 0),{done:!0}},return(){return m.return(),r!=null&&(r(),r=void 0),{done:!0}},push:f,end(y){return m.end(y),r!=null&&(r(y),r=void 0),i},get readableLength(){return m.readableLength},onEmpty:y=>m.onEmpty(y)},i}function ov(t){return t[Symbol.asyncIterator]!=null}function av(...t){let e=[];for(let r of t)ov(r)||e.push(r);return e.length===t.length?function*(){for(let r of e)yield*r}():async function*(){let r=jo({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(t.map(async n=>{for await(let i of n)r.push(i)})),r.end()}catch(n){r.end(n)}}),yield*r}()}var wn=av;function es(t,...e){if(t==null)throw new Error("Empty pipeline");if(Dl(t)){let n=t;t=()=>n.source}else if(Nm(t)||Dm(t)){let n=t;t=()=>n}let r=[t,...e];if(r.length>1&&Dl(r[r.length-1])&&(r[r.length-1]=r[r.length-1].sink),r.length>2)for(let n=1;n<r.length-1;n++)Dl(r[n])&&(r[n]=uv(r[n]));return cv(...r)}var cv=(...t)=>{let e;for(;t.length>0;)e=t.shift()(e);return e},Dm=t=>t?.[Symbol.asyncIterator]!=null,Nm=t=>t?.[Symbol.iterator]!=null,Dl=t=>t==null?!1:t.sink!=null&&t.source!=null,uv=t=>e=>{let r=t.sink(e);if(r?.then!=null){let n=jo({objectMode:!0});r.then(()=>{n.end()},o=>{n.end(o)});let i,s=t.source;if(Dm(s))i=async function*(){yield*s,n.end()};else if(Nm(s))i=function*(){yield*s,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return wn(n,i())}return t.source};function lv(t){return t[Symbol.asyncIterator]!=null}function fv(t,e){if(lv(t))return async function*(){for await(let a of t)yield e(a)}();let r=vo(t),{value:n,done:i}=r.next();if(i===!0)return function*(){}();let s=e(n);if(typeof s.then=="function")return async function*(){yield await s;for await(let a of r)yield e(a)}();let o=e;return function*(){yield s;for(let a of r)yield o(a)}()}var km=fv;async function*ts(t,e){yield*km(t,async r=>(await e.merge(r.id,{multiaddrs:r.multiaddrs}),r))}function Jo(t){let e=new Set;return Kt(t,r=>e.has(r.id.toString())?!1:(e.add(r.id.toString()),!0))}async function*ea(t,e=1){let r=0;for await(let n of t)r++,yield n;if(r<e)throw new S(`more peers required, seen: ${r} min: ${e}`,"NOT_FOUND")}var ta=class{routers;started;components;constructor(e,r){this.routers=r.routers??[],this.started=!1,this.components=e}isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,r={}){if(this.routers.length===0)throw new S("No content routers available",F.ERR_NO_ROUTERS_AVAILABLE);yield*es(wn(...this.routers.map(n=>n.findProviders(e,r))),n=>ts(n,this.components.peerStore),n=>Jo(n),n=>ea(n))}async provide(e,r={}){if(this.routers.length===0)throw new S("No content routers available",F.ERR_NO_ROUTERS_AVAILABLE);await Promise.all(this.routers.map(async n=>{await n.provide(e,r)}))}async put(e,r,n){if(!this.isStarted())throw new S(er.NOT_STARTED_YET,F.DHT_NOT_STARTED);await Promise.all(this.routers.map(async i=>{await i.put(e,r,n)}))}async get(e,r){if(!this.isStarted())throw new S(er.NOT_STARTED_YET,F.DHT_NOT_STARTED);return Promise.any(this.routers.map(async n=>n.get(e,r)))}};function hv(t){return t[Symbol.asyncIterator]!=null}function dv(t){if(hv(t))return(async()=>{for await(let e of t)return e})();for(let e of t)return e}var Om=dv;var ra=class{log;peerId;peerStore;routers;constructor(e,r){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=r.routers??[]}async findPeer(e,r){if(this.routers.length===0)throw new S("No peer routers available",F.ERR_NO_ROUTERS_AVAILABLE);if(e.toString()===this.peerId.toString())throw new S("Should not try to find self",F.ERR_FIND_SELF);let n=this,i=await es(wn(...this.routers.map(s=>async function*(){try{yield await s.findPeer(e,r)}catch(o){n.log.error(o)}}())),s=>Kt(s,Boolean),s=>ts(s,this.peerStore),async s=>Om(s));if(i!=null)return i;throw new S(er.NOT_FOUND,F.ERR_NOT_FOUND)}async*getClosestPeers(e,r){if(this.routers.length===0)throw new S("No peer routers available",F.ERR_NO_ROUTERS_AVAILABLE);yield*es(wn(...this.routers.map(n=>n.getClosestPeers(e,r))),n=>ts(n,this.peerStore),n=>Jo(n),n=>ea(n))}};var Nl=32,kl=64,na=class{log;topologies;handlers;components;constructor(e){this.log=e.logger.forComponent("libp2p:registrar"),this.topologies=new Map,this.handlers=new Map,this.components=e,this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let r=this.handlers.get(e);if(r==null)throw new S(`No handler registered for protocol ${e}`,F.ERR_NO_HANDLER_FOR_PROTOCOL);return r}getTopologies(e){let r=this.topologies.get(e);return r==null?[]:[...r.values()]}async handle(e,r,n){if(this.handlers.has(e))throw new S(`Handler already registered for protocol ${e}`,F.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);let i=Mo.bind({ignoreUndefined:!0})({maxInboundStreams:Nl,maxOutboundStreams:kl},n);this.handlers.set(e,{handler:r,options:i}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]})}async unhandle(e){(Array.isArray(e)?e:[e]).forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()})}async register(e,r){if(r==null)throw new S("invalid topology",F.ERR_INVALID_PARAMETERS);let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,i=this.topologies.get(e);return i==null&&(i=new Map,this.topologies.set(e,i)),i.set(n,r),n}unregister(e){for(let[r,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(r))}_onDisconnect(e){let r=e.detail;this.components.peerStore.get(r).then(n=>{for(let i of n.protocols){let s=this.topologies.get(i);if(s!=null)for(let o of s.values())o.onDisconnect?.(r)}}).catch(n=>{n.code!==F.ERR_NOT_FOUND&&this.log.error("could not inform topologies of disconnecting peer %p",r,n)})}_onPeerUpdate(e){let{peer:r,previous:n}=e.detail,i=(n?.protocols??[]).filter(s=>!r.protocols.includes(s));for(let s of i){let o=this.topologies.get(s);if(o!=null)for(let a of o.values())a.onDisconnect?.(r.id)}}_onPeerIdentify(e){let r=e.detail.protocols,n=e.detail.connection,i=e.detail.peerId;for(let s of r){let o=this.topologies.get(s);if(o!=null)for(let a of o.values())n.transient&&a.notifyOnTransient!==!0||a.onConnect?.(i,n)}}};var Ol=class extends Map{metric;constructor(e){super();let{name:r,metrics:n}=e;this.metric=n.registerMetric(r),this.updateComponentMetric()}set(e,r){return super.set(e,r),this.updateComponentMetric(),this}delete(e){let r=super.delete(e);return this.updateComponentMetric(),r}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Mm(t){let{name:e,metrics:r}=t,n;return r!=null?n=new Ol({name:e,metrics:r}):n=new Map,n}var ia=class{log;components;transports;listeners;faultTolerance;started;constructor(e,r={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=new Map,this.listeners=Mm({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=r.faultTolerance??Er.FATAL_ALL}add(e){let r=e[Symbol.toStringTag];if(r==null)throw new S("Transport must have a valid tag",F.ERR_INVALID_KEY);if(this.transports.has(r))throw new S(`There is already a transport with the tag ${r}`,F.ERR_DUPLICATE_TRANSPORT);this.log("adding transport %s",r),this.transports.set(r,e),this.listeners.has(r)||this.listeners.set(r,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){let e=[];for(let[r,n]of this.listeners)for(this.log("closing listeners for %s",r);n.length>0;){let i=n.pop();i!=null&&e.push(i.close())}await Promise.all(e),this.log("all listeners closed");for(let r of this.listeners.keys())this.listeners.set(r,[]);this.started=!1}async dial(e,r){let n=this.transportForMultiaddr(e);if(n==null)throw new S(`No transport available for address ${String(e)}`,F.ERR_TRANSPORT_UNAVAILABLE);try{return await n.dial(e,{...r,upgrader:this.components.upgrader})}catch(i){throw i.code==null&&(i.code=F.ERR_TRANSPORT_DIAL_FAILED),i}}getAddrs(){let e=[];for(let r of this.listeners.values())for(let n of r)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}transportForMultiaddr(e){for(let r of this.transports.values())if(r.filter([e]).length>0)return r}async listen(e){if(!this.isStarted())throw new S("Not started",F.ERR_NODE_NOT_STARTED);if(e==null||e.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let r=[];for(let[n,i]of this.transports.entries()){let s=i.filter(e),o=[];for(let u of s){this.log("creating listener for %s on %a",n,u);let l=i.createListener({upgrader:this.components.upgrader}),f=this.listeners.get(n)??[];f==null&&(f=[],this.listeners.set(n,f)),f.push(l),l.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:l})}),l.addEventListener("close",()=>{let h=f.findIndex(p=>p===l);f.splice(h,1),this.components.events.safeDispatchEvent("transport:close",{detail:l})}),o.push(l.listen(u))}if(o.length===0){r.push(n);continue}if((await Promise.allSettled(o)).find(u=>u.status==="fulfilled")==null&&this.faultTolerance!==Er.NO_FATAL)throw new S(`Transport (${n}) could not listen on any available address`,F.ERR_NO_VALID_ADDRESSES)}if(r.length===this.transports.size){let n=`no valid addresses were provided for transports [${r.join(", ")}]`;if(this.faultTolerance===Er.FATAL_ALL)throw new S(n,F.ERR_NO_VALID_ADDRESSES);this.log(`libp2p in dial mode only: ${n}`)}}async remove(e){let r=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);let n=[];for(this.log.trace("closing listeners for %s",e);r.length>0;){let i=r.pop();i!=null&&n.push(i.close())}await Promise.all(n),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let r of this.transports.keys())e.push(this.remove(r));await Promise.all(e)}};var Je="/multistream/1.0.0";var sa=class extends Error{type;code;constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=r??"ABORT_ERR"}};async function Um(t,e,r){if(e==null)return t;if(e.aborted)return Promise.reject(new sa(r?.errorMessage,r?.errorCode));let n,i=new sa(r?.errorMessage,r?.errorCode);try{return await Promise.race([t,new Promise((s,o)=>{n=()=>{o(i)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var Ml=class{needNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.needNext=ut(),this.needNext.resolve(),this.haveNext=ut()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("Have next but next was undefined");let e=this.nextResult;return this.nextResult=void 0,this.needNext.resolve(),this.needNext=ut(),e}async throw(e){return this.ended=!0,e!=null&&this.haveNext.reject(e),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return await this._push(void 0),e}async push(e,r){await this._push(e,r)}async end(e,r){e!=null?await this.throw(e):await this._push(void 0,r)}async _push(e,r){if(e!=null&&this.ended)throw new Error("Cannot push value onto an ended pushable");this.nextResult!=null&&await this.needNext.promise,e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=ut(),await Um(this.needNext.promise,r?.signal,r)}};function Fm(){return new Ml}var oa=class extends Error{code;constructor(e,r){super(e),this.code=r}},Ul=class extends oa{type;constructor(e){super(e,"ABORT_ERR"),this.type="aborted"}};function Km(t,e){let r=Fm();t.sink(r).catch(async o=>{await r.end(o)}),t.sink=async o=>{for await(let a of o)await r.push(a);await r.end()};let n=t.source;t.source[Symbol.iterator]!=null?n=t.source[Symbol.iterator]():t.source[Symbol.asyncIterator]!=null&&(n=t.source[Symbol.asyncIterator]());let i=new ze;return{read:async(o,a)=>{a?.signal?.throwIfAborted();let c,u=new Promise((l,f)=>{c=()=>{f(new Ul("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(o==null){let{done:f,value:h}=await Promise.race([n.next(),u]);return f===!0?new ze:h}for(;i.byteLength<o;){let{value:f,done:h}=await Promise.race([n.next(),u]);if(h===!0)throw new oa("unexpected end of input","ERR_UNEXPECTED_EOF");i.append(f)}let l=i.sublist(0,o);return i.consume(o),l}finally{c!=null&&a?.signal?.removeEventListener("abort",c)}},write:async(o,a)=>{a?.signal?.throwIfAborted(),o instanceof Uint8Array?await r.push(o,a):await r.push(o.subarray(),a)},unwrap:()=>{if(i.byteLength>0){let o=t.source;t.source=async function*(){e?.yieldBytes===!1?yield i:yield*i,yield*o}()}return t}}}function aa(t){return t[Symbol.asyncIterator]!=null}var ca=t=>{let e=it(t),r=tt(e);return dt(t,r),ca.bytes=e,r};ca.bytes=0;function En(t,e){e=e??{};let r=e.lengthEncoder??ca;function*n(i){let s=r(i.byteLength);s instanceof Uint8Array?yield s:yield*s,i instanceof Uint8Array?yield i:yield*i}return aa(t)?async function*(){for await(let i of t)yield*n(i)}():function*(){for(let i of t)yield*n(i)}()}En.single=(t,e)=>{e=e??{};let r=e.lengthEncoder??ca;return new ze(r(t.byteLength),t)};var fi=ve(Yu(),1);var pv=8,mv=1024*1024*4,vn;(function(t){t[t.LENGTH=0]="LENGTH",t[t.DATA=1]="DATA"})(vn||(vn={}));var Kl=t=>{let e=Ut(t);return Kl.bytes=it(e),e};Kl.bytes=0;function Fl(t,e){let r=new ze,n=vn.LENGTH,i=-1,s=e?.lengthDecoder??Kl,o=e?.maxLengthLength??pv,a=e?.maxDataLength??mv;function*c(){for(;r.byteLength>0;){if(n===vn.LENGTH)try{if(i=s(r),i<0)throw(0,fi.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(i>a)throw(0,fi.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let u=s.bytes;r.consume(u),e?.onLength!=null&&e.onLength(i),n=vn.DATA}catch(u){if(u instanceof RangeError){if(r.byteLength>o)throw(0,fi.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw u}if(n===vn.DATA){if(r.byteLength<i)break;let u=r.sublist(0,i);r.consume(i),e?.onData!=null&&e.onData(u),yield u,n=vn.LENGTH}}}return aa(t)?async function*(){for await(let u of t)r.append(u),yield*c();if(r.byteLength>0)throw(0,fi.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let u of t)r.append(u),yield*c();if(r.byteLength>0)throw(0,fi.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}Fl.fromReader=(t,e)=>{let r=1,n=async function*(){for(;;)try{let{done:s,value:o}=await t.next(r);if(s===!0)return;o!=null&&(yield o)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{r=1}}();return Fl(n,{...e??{},onLength:s=>{r=s}})};var ua=class extends Error{code;constructor(e,r){super(e),this.code=r}},qm=t=>Ut(t);qm.bytes=0;function rs(t,e={}){let r=Km(t,e);return e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=it(e.maxDataLength)),{read:async i=>{let s=-1,o=new ze,a=e?.lengthDecoder??qm;for(;;){o.append(await r.read(1,i));try{s=a(o)}catch(c){if(c instanceof RangeError)continue;throw c}if(e?.maxLengthLength!=null&&o.byteLength>e.maxLengthLength)throw new ua("message length length too long","ERR_MSG_LENGTH_TOO_LONG");if(s>-1)break}if(e?.maxDataLength!=null&&s>e.maxDataLength)throw new ua("message length too long","ERR_MSG_DATA_TOO_LONG");return r.read(s,i)},write:async(i,s)=>{await r.write(En.single(i,e),s)},writeV:async(i,s)=>{let o=new ze(...i.map(a=>En.single(a,e)));await r.write(o,s)},unwrap:()=>r.unwrap()}}var gv=Q(`
48
+ `.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),$w=new RegExp(`(?:^${qt}$)|(?:^${Io}$)`),zw=new RegExp(`^${qt}$`),Hw=new RegExp(`^${Io}$`),Zu=t=>t&&t.exact?$w:new RegExp(`(?:${Kr(t)}${qt}${Kr(t)})|(?:${Kr(t)}${Io}${Kr(t)})`,"g");Zu.v4=t=>t&&t.exact?zw:new RegExp(`${Kr(t)}${qt}${Kr(t)}`,"g");Zu.v6=t=>t&&t.exact?Hw:new RegExp(`${Kr(t)}${Io}${Kr(t)}`,"g");var rp=Zu;var ap=ve(ip(),1),{isValid:Gw,parse:Ww}=ap.default,Yw=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"],Qw=Yw.map(t=>new op.Netmask(t));function Xw(t){for(let e of Qw)if(e.contains(t))return!0;return!1}function sp(t){return/^::$/.test(t)||/^::1$/.test(t)||/^::f{4}:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(t)||/^::f{4}:0.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(t)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(t)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(t)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(t)||/^ff([0-9a-fA-F]{2,2}):/i.test(t)}var cp=t=>{if(Gw(t)){let e=Ww(t);if(e.kind()==="ipv4")return Xw(e.toNormalizedString());if(e.kind()==="ipv6")return sp(t)}else if(Xn(t)&&rp.v6().test(t))return sp(t)};var Co=cp;function up(t={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let r=e.stringTuples();return r[0][0]===4||r[0][0]===41?!!Co(`${r[0][1]}`):!1},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...t}}var Zw=t=>t.toString().split("/").slice(1),Xi=t=>({match:e=>e.length<1?!1:t(e[0])?e.slice(1):!1,pattern:"fn"}),Le=t=>({match:e=>Xi(r=>r===t).match(e),pattern:t}),Lo=()=>({match:t=>Xi(e=>typeof e=="string").match(t),pattern:"{string}"}),lp=()=>({match:t=>Xi(e=>!isNaN(parseInt(e))).match(t),pattern:"{number}"}),Ct=()=>({match:t=>{if(t.length<2||t[0]!=="p2p"&&t[0]!=="ipfs")return!1;if(t[1].startsWith("Q")||t[1].startsWith("1"))try{_e.decode(`z${t[1]}`)}catch{return!1}else return!1;return t.slice(2)},pattern:"/p2p/{peerid}"}),To=()=>({match:t=>{if(t.length<2||t[0]!=="certhash")return!1;try{ja.decode(t[1])}catch{return!1}return t.slice(2)},pattern:"/certhash/{certhash}"}),jt=t=>({match:e=>{let r=t.match(e);return r===!1?e:r},pattern:`optional(${t.pattern})`}),Jt=(...t)=>({match:e=>{let r;for(let n of t){let i=n.match(e);i!==!1&&(r==null||i.length<r.length)&&(r=i)}return r??!1},pattern:`or(${t.map(e=>e.pattern).join(", ")})`}),Pe=(...t)=>({match:e=>{for(let r of t){let n=r.match(e);if(n===!1)return!1;e=n}return e},pattern:`and(${t.map(e=>e.pattern).join(", ")})`});function Fe(...t){function e(i){let s=Zw(i);for(let o of t){let a=o.match(s);if(a===!1)return!1;s=a}return s}function r(i){return e(i)!==!1}function n(i){let s=e(i);return s===!1?!1:s.length===0}return{matches:r,exactMatch:n}}var Ju=Pe(Le("dns4"),Lo()),el=Pe(Le("dns6"),Lo()),tl=Pe(Le("dnsaddr"),Lo()),fp=Pe(Le("dns"),Lo()),T3=Fe(Ju),B3=Fe(el),L3=Fe(tl),P3=Fe(Jt(fp,tl,Ju,el)),hp=Pe(Le("ip4"),Xi(eo)),dp=Pe(Le("ip6"),Xi(to)),pp=Jt(hp,dp),Zi=Jt(pp,fp,Ju,el,tl),D3=Fe(Zi),N3=Fe(hp),k3=Fe(dp),O3=Fe(pp),Po=Pe(Zi,Le("tcp"),lp()),ji=Pe(Zi,Le("udp"),lp()),jw=Jt(Po,ji),M3=Fe(Po),U3=Fe(ji),rl=Pe(ji,Le("quic")),Do=Pe(ji,Le("quic-v1")),Jw=Jt(rl,Do),F3=Fe(rl),K3=Fe(Do),ju=Jt(Zi,Po,ji,rl,Do),mp=Jt(Pe(ju,Le("ws"),jt(Ct()))),q3=Fe(mp),yp=Jt(Pe(ju,Le("wss"),jt(Ct())),Pe(ju,Le("tls"),Le("ws"),jt(Ct()))),V3=Fe(yp),gp=Pe(jw,Le("webrtc-direct"),To(),jt(To()),jt(Ct())),$3=Fe(gp),xp=Pe(Do,Le("webtransport"),To(),To(),jt(Ct())),z3=Fe(xp),Bo=Jt(mp,yp,Pe(Po,jt(Ct())),Pe(Jw,jt(Ct())),Pe(Zi,jt(Ct())),gp,xp,Ct()),H3=Fe(Bo),eE=Pe(Bo,Le("p2p-circuit"),Ct()),nl=Fe(eE),tE=Jt(Pe(Bo,Le("p2p-circuit"),Le("webrtc"),Ct()),Pe(Bo,Le("webrtc"),jt(Ct())),Le("webrtc")),G3=Fe(tE);function il(t){try{let{address:e}=t.nodeAddress();return!!Co(e)}catch{return!0}}function rE(t,e){let r=il(t.multiaddr),n=il(e.multiaddr);return r&&!n?1:!r&&n?-1:0}function nE(t,e){return t.isCertified&&!e.isCertified?-1:!t.isCertified&&e.isCertified?1:0}function iE(t,e){let r=nl.exactMatch(t.multiaddr),n=nl.exactMatch(e.multiaddr);return r&&!n?1:!r&&n?-1:0}function ri(t,e){let r=rE(t,e);if(r!==0)return r;let n=iE(t,e);return n!==0?n:nE(t,e)}var ol=ve(ru(),1),al=ve(Ep(),1);function No(t,e,r){return`${t}?name=${e}&type=${r}`}async function vp(t,e){return await(await fetch(t,{headers:new Headers({accept:"application/dns-json"}),signal:e})).json()}function gn(t,e){return`${e}_${t}`}var sl=Object.assign((0,ol.default)("dns-over-http-resolver"),{error:(0,ol.default)("dns-over-http-resolver:error")}),cl=class{_cache;_TXTcache;_servers;_request;_abortControllers;constructor(e={}){this._cache=new al.default({max:e?.maxCache??100}),this._TXTcache=new al.default({max:e?.maxCache??100}),this._servers=["https://cloudflare-dns.com/dns-query","https://dns.google/resolve"],this._request=e.request??vp,this._abortControllers=[]}cancel(){this._abortControllers.forEach(e=>{e.abort()})}getServers(){return this._servers}_getShuffledServers(){let e=[...this._servers];for(let r=e.length-1;r>0;r--){let n=Math.floor(Math.random()*r),i=e[r];e[r]=e[n],e[n]=i}return e}setServers(e){this._servers=e}async resolve(e,r="A"){switch(r){case"A":return this.resolve4(e);case"AAAA":return this.resolve6(e);case"TXT":return this.resolveTxt(e);default:throw new Error(`${r} is not supported`)}}async resolve4(e){let r="A",n=this._cache.get(gn(e,r));if(n!=null)return n;let i=!1;for(let s of this._getShuffledServers()){let o=new AbortController;this._abortControllers.push(o);try{let a=await this._request(No(s,e,r),o.signal),c=a.Answer.map(l=>l.data),u=Math.min(...a.Answer.map(l=>l.TTL));return this._cache.set(gn(e,r),c,{ttl:u}),c}catch{o.signal.aborted&&(i=!0),sl.error(`${s} could not resolve ${e} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==o)}}throw i?Object.assign(new Error("queryA ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${r}`)}async resolve6(e){let r="AAAA",n=this._cache.get(gn(e,r));if(n!=null)return n;let i=!1;for(let s of this._getShuffledServers()){let o=new AbortController;this._abortControllers.push(o);try{let a=await this._request(No(s,e,r),o.signal),c=a.Answer.map(l=>l.data),u=Math.min(...a.Answer.map(l=>l.TTL));return this._cache.set(gn(e,r),c,{ttl:u}),c}catch{o.signal.aborted&&(i=!0),sl.error(`${s} could not resolve ${e} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==o)}}throw i?Object.assign(new Error("queryAaaa ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${r}`)}async resolveTxt(e){let r="TXT",n=this._TXTcache.get(gn(e,r));if(n!=null)return n;let i=!1;for(let s of this._getShuffledServers()){let o=new AbortController;this._abortControllers.push(o);try{let a=await this._request(No(s,e,r),o.signal),c=a.Answer.map(l=>[l.data.replace(/['"]+/g,"")]),u=Math.min(...a.Answer.map(l=>l.TTL));return this._TXTcache.set(gn(e,r),c,{ttl:u}),c}catch{o.signal.aborted&&(i=!0),sl.error(`${s} could not resolve ${e} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==o)}}throw i?Object.assign(new Error("queryTxt ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${r}`)}clearCache(){this._cache.clear(),this._TXTcache.clear()}},_p=cl;var Sp=_p;var{code:uE}=fe("dnsaddr");async function ni(t,e={}){let r=new Sp;e.signal!=null&&e.signal.addEventListener("abort",()=>{r.cancel()});let n=t.getPeerId(),[,i]=t.stringTuples().find(([a])=>a===uE)??[];if(i==null)throw new Error("No hostname found in multiaddr");let o=(await r.resolveTxt(`_dnsaddr.${i}`)).flat().map(a=>a.split("=")[1]).filter(Boolean);return n!=null&&(o=o.filter(a=>a.includes(n))),o}var Dp=ve(Pp(),1),Mo=Dp.default;var er;(function(t){t.NOT_STARTED_YET="The libp2p node is not started yet",t.DHT_DISABLED="DHT is not available",t.PUBSUB_DISABLED="PubSub is not available",t.CONN_ENCRYPTION_REQUIRED="At least one connection encryption module is required",t.ERR_TRANSPORTS_REQUIRED="At least one transport module is required",t.ERR_PROTECTOR_REQUIRED="Private network is enforced, but no protector was provided",t.NOT_FOUND="Not found"})(er||(er={}));var F;(function(t){t.DHT_DISABLED="ERR_DHT_DISABLED",t.ERR_PUBSUB_DISABLED="ERR_PUBSUB_DISABLED",t.PUBSUB_NOT_STARTED="ERR_PUBSUB_NOT_STARTED",t.DHT_NOT_STARTED="ERR_DHT_NOT_STARTED",t.CONN_ENCRYPTION_REQUIRED="ERR_CONN_ENCRYPTION_REQUIRED",t.ERR_TRANSPORTS_REQUIRED="ERR_TRANSPORTS_REQUIRED",t.ERR_PROTECTOR_REQUIRED="ERR_PROTECTOR_REQUIRED",t.ERR_PEER_DIAL_INTERCEPTED="ERR_PEER_DIAL_INTERCEPTED",t.ERR_CONNECTION_INTERCEPTED="ERR_CONNECTION_INTERCEPTED",t.ERR_INVALID_PROTOCOLS_FOR_STREAM="ERR_INVALID_PROTOCOLS_FOR_STREAM",t.ERR_CONNECTION_ENDED="ERR_CONNECTION_ENDED",t.ERR_CONNECTION_FAILED="ERR_CONNECTION_FAILED",t.ERR_NODE_NOT_STARTED="ERR_NODE_NOT_STARTED",t.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",t.ERR_TOO_MANY_ADDRESSES="ERR_TOO_MANY_ADDRESSES",t.ERR_NO_VALID_ADDRESSES="ERR_NO_VALID_ADDRESSES",t.ERR_RELAYED_DIAL="ERR_RELAYED_DIAL",t.ERR_DIALED_SELF="ERR_DIALED_SELF",t.ERR_DISCOVERED_SELF="ERR_DISCOVERED_SELF",t.ERR_DUPLICATE_TRANSPORT="ERR_DUPLICATE_TRANSPORT",t.ERR_ENCRYPTION_FAILED="ERR_ENCRYPTION_FAILED",t.ERR_HOP_REQUEST_FAILED="ERR_HOP_REQUEST_FAILED",t.ERR_INVALID_KEY="ERR_INVALID_KEY",t.ERR_INVALID_MESSAGE="ERR_INVALID_MESSAGE",t.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",t.ERR_INVALID_PEER="ERR_INVALID_PEER",t.ERR_MUXER_UNAVAILABLE="ERR_MUXER_UNAVAILABLE",t.ERR_NOT_FOUND="ERR_NOT_FOUND",t.ERR_TRANSPORT_UNAVAILABLE="ERR_TRANSPORT_UNAVAILABLE",t.ERR_TRANSPORT_DIAL_FAILED="ERR_TRANSPORT_DIAL_FAILED",t.ERR_UNSUPPORTED_PROTOCOL="ERR_UNSUPPORTED_PROTOCOL",t.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED="ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED",t.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",t.ERR_SIGNATURE_NOT_VALID="ERR_SIGNATURE_NOT_VALID",t.ERR_FIND_SELF="ERR_FIND_SELF",t.ERR_NO_ROUTERS_AVAILABLE="ERR_NO_ROUTERS_AVAILABLE",t.ERR_CONNECTION_NOT_MULTIPLEXED="ERR_CONNECTION_NOT_MULTIPLEXED",t.ERR_NO_DIAL_TOKENS="ERR_NO_DIAL_TOKENS",t.ERR_INVALID_CMS="ERR_INVALID_CMS",t.ERR_MISSING_KEYS="ERR_MISSING_KEYS",t.ERR_NO_KEY="ERR_NO_KEY",t.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",t.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",t.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",t.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",t.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",t.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",t.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",t.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",t.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",t.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",t.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",t.ERR_MISSING_PUBLIC_KEY="ERR_MISSING_PUBLIC_KEY",t.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",t.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",t.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH",t.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",t.ERR_WRONG_PING_ACK="ERR_WRONG_PING_ACK",t.ERR_INVALID_RECORD="ERR_INVALID_RECORD",t.ERR_ALREADY_SUCCEEDED="ERR_ALREADY_SUCCEEDED",t.ERR_NO_HANDLER_FOR_PROTOCOL="ERR_NO_HANDLER_FOR_PROTOCOL",t.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS",t.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",t.ERR_CONNECTION_DENIED="ERR_CONNECTION_DENIED",t.ERR_TRANSFER_LIMIT_EXCEEDED="ERR_TRANSFER_LIMIT_EXCEEDED"})(F||(F={}));var mE={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:t=>t},connectionManager:{resolvers:{dnsaddr:ni},addressSorter:ri},transportManager:{faultTolerance:Er.FATAL_ALL}};function Np(t){let e=Mo(mE,t);if(e.transports==null||e.transports.length<1)throw new S(er.ERR_TRANSPORTS_REQUIRED,F.ERR_TRANSPORTS_REQUIRED);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new S(er.ERR_PROTECTOR_REQUIRED,F.ERR_PROTECTOR_REQUIRED);return e}var Pm=ve(Cm(),1);function Fo(t){if(_s(t))return{peerId:t,multiaddrs:[]};Array.isArray(t)||(t=[t]);let e;if(t.length>0){let r=t[0].getPeerId();e=r==null?void 0:ce(r),t.forEach(n=>{if(!Nr(n))throw new S("Invalid Multiaddr",F.ERR_INVALID_MULTIADDR);let i=n.getPeerId();if(i==null){if(e!=null)throw new S("Multiaddrs must all have the same peer id or have no peer id",F.ERR_INVALID_PARAMETERS)}else{let s=ce(i);if(e==null||!e.equals(s))throw new S("Multiaddrs must all have the same peer id or have no peer id",F.ERR_INVALID_PARAMETERS)}})}return{peerId:e,multiaddrs:t}}function ZE(t,e,r){let n=0,i=t.length;for(;i>0;){let s=Math.trunc(i/2),o=n+s;r(t[o],e)<=0?(n=++o,i-=s+1):i=s}return n}var Al=class{#e=[];enqueue(e,r){let n=r?.peerId,i=r?.priority??0;if(n==null)throw new S("missing peer id",x0);let s={priority:i,peerId:n,run:e};if(this.size>0&&this.#e[this.size-1].priority>=i){this.#e.push(s);return}let o=ZE(this.#e,s,(a,c)=>c.priority-a.priority);this.#e.splice(o,0,s)}dequeue(){return this.#e.shift()?.run}filter(e){if(e.peerId!=null){let r=e.peerId;return this.#e.filter(n=>r.equals(n.peerId)).map(n=>n.run)}return this.#e.filter(r=>r.priority===e.priority).map(r=>r.run)}get size(){return this.#e.length}},Ko=class extends Mr{constructor(e={}){super({...e,queueClass:Al})}hasJob(e){return this.sizeBy({peerId:e})>0}};var qo="last-dial-failure";var Vo=5,$o=100,zo=50,Tm=1e3*60*7;var xn={minConnections:Vo,maxQueueLength:100,autoDialConcurrency:25,autoDialPriority:0,autoDialInterval:5e3,autoDialPeerRetryThreshold:Tm,autoDialDiscoveredPeersDebounce:10},Ho=class{connectionManager;peerStore;queue;minConnections;autoDialPriority;autoDialIntervalMs;autoDialMaxQueueLength;autoDialPeerRetryThresholdMs;autoDialDiscoveredPeersDebounce;autoDialInterval;started;running;log;constructor(e,r){this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.minConnections=r.minConnections??xn.minConnections,this.autoDialPriority=r.autoDialPriority??xn.autoDialPriority,this.autoDialIntervalMs=r.autoDialInterval??xn.autoDialInterval,this.autoDialMaxQueueLength=r.maxQueueLength??xn.maxQueueLength,this.autoDialPeerRetryThresholdMs=r.autoDialPeerRetryThreshold??xn.autoDialPeerRetryThreshold,this.autoDialDiscoveredPeersDebounce=r.autoDialDiscoveredPeersDebounce??xn.autoDialDiscoveredPeersDebounce,this.log=e.logger.forComponent("libp2p:connection-manager:auto-dial"),this.started=!1,this.running=!1,this.queue=new Ko({concurrency:r.autoDialConcurrency??xn.autoDialConcurrency}),this.queue.addListener("error",i=>{this.log.error("error during auto-dial",i)}),e.events.addEventListener("connection:close",()=>{this.autoDial().catch(i=>{this.log.error(i)})});let n;e.events.addEventListener("peer:discovery",()=>{clearTimeout(n),n=setTimeout(()=>{this.autoDial().catch(i=>{this.log.error(i)})},this.autoDialDiscoveredPeersDebounce)})}isStarted(){return this.started}start(){this.started=!0}afterStart(){this.autoDial().catch(e=>{this.log.error("error while autodialing",e)})}stop(){this.queue.clear(),clearTimeout(this.autoDialInterval),this.started=!1,this.running=!1}async autoDial(){if(!this.started||this.running)return;let e=this.connectionManager.getConnectionsMap(),r=e.size;if(r>=this.minConnections){this.minConnections>0&&this.log.trace("have enough connections %d/%d",r,this.minConnections);return}if(this.queue.size>this.autoDialMaxQueueLength){this.log("not enough connections %d/%d but auto dial queue is full",r,this.minConnections),this.sheduleNextAutodial();return}this.running=!0,this.log("not enough connections %d/%d - will dial peers to increase the number of connections",r,this.minConnections);let n=new fn(this.connectionManager.getDialQueue().map(u=>u.peerId).filter(Boolean)),i=await this.peerStore.all({filters:[u=>u.addresses.length===0?(this.log.trace("not autodialing %p because they have no addresses",u.id),!1):e.has(u.id)?(this.log.trace("not autodialing %p because they are already connected",u.id),!1):n.has(u.id)?(this.log.trace("not autodialing %p because they are already being dialed",u.id),!1):this.queue.hasJob(u.id)?(this.log.trace("not autodialing %p because they are already being autodialed",u.id),!1):!0]}),s=i.sort(()=>Math.random()>.5?1:-1),o=new wt;for(let u of s)o.has(u.id)||o.set(u.id,[...u.tags.values()].reduce((l,f)=>l+f.value,0));let c=s.sort((u,l)=>{let f=o.get(u.id)??0,h=o.get(l.id)??0;return f>h?-1:f<h?1:0}).filter(u=>{let l=u.metadata.get(qo);if(l==null)return!0;let f=parseInt(se(l));return isNaN(f)?!0:Date.now()-f>this.autoDialPeerRetryThresholdMs});this.log("selected %d/%d peers to dial",c.length,i.length);for(let u of c)this.queue.add(async()=>{let l=this.connectionManager.getConnectionsMap().size;if(l>=this.minConnections){this.log("got enough connections now %d/%d",l,this.minConnections),this.queue.clear();return}this.log("connecting to a peerStore stored peer %p",u.id),await this.connectionManager.openConnection(u.id,{priority:this.autoDialPriority})},{peerId:u.id}).catch(l=>{this.log.error("could not connect to peerStore stored peer",l)});this.running=!1,this.sheduleNextAutodial()}sheduleNextAutodial(){this.started&&(this.autoDialInterval=setTimeout(()=>{this.autoDial().catch(e=>{this.log.error("error while autodialing",e)})},this.autoDialIntervalMs))}};var Bm={maxConnections:$o,allow:[]},Go=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(e,r={}){this.maxConnections=r.maxConnections??Bm.maxConnections,this.allow=r.allow??Bm.allow,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),e.events.addEventListener("connection:open",()=>{this.maybePruneConnections().catch(n=>{this.log.error(n)})})}async maybePruneConnections(){let e=this.connectionManager.getConnections(),r=e.length,n=Math.max(r-this.maxConnections,0);if(this.log("checking max connections limit %d/%d",r,this.maxConnections),r<=this.maxConnections)return;this.log("max connections limit exceeded %d/%d, pruning %d connection(s)",r,this.maxConnections,n);let i=new wt;for(let a of e){let c=a.remotePeer;if(!i.has(c)){i.set(c,0);try{let u=await this.peerStore.get(c);i.set(c,[...u.tags.values()].reduce((l,f)=>l+f.value,0))}catch(u){u.code!=="ERR_NOT_FOUND"&&this.log.error("error loading peer tags",u)}}}let s=e.sort((a,c)=>{let u=i.get(a.remotePeer)??0,l=i.get(c.remotePeer)??0;if(u>l)return 1;if(u<l)return-1;let f=a.timeline.open,h=c.timeline.open;return f<h?1:f>h?-1:0}),o=[];for(let a of s)if(this.log("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(u=>a.remoteAddr.toString().startsWith(u.toString()))||o.push(a),o.length===n)break;await Promise.all(o.map(async a=>{try{await a.close()}catch(c){this.log.error(c)}})),this.events.safeDispatchEvent("connection:prune",{detail:o})}};function Wo(t){let e=new globalThis.AbortController;function r(){e.abort();for(let s of t)s?.removeEventListener!=null&&s.removeEventListener("abort",r)}for(let s of t){if(s?.aborted===!0){r();break}s?.addEventListener!=null&&s.addEventListener("abort",r)}function n(){for(let s of t)s?.removeEventListener!=null&&s.removeEventListener("abort",r)}let i=e.signal;return i.clear=n,i}function ut(){let t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}async function Tl(t,e){if(!t.protoNames().includes("dnsaddr"))return[t];let n=await ev(t,e),o=(await Promise.all(n.map(async a=>Tl(a,e)))).flat().reduce((a,c)=>(a.find(u=>u.equals(c))==null&&a.push(c),a),[]);return e.log("resolved %s to",t,o.map(a=>a.toString())),o}async function ev(t,e){try{return t=Ue(t.toString()),await t.resolve(e)}catch(r){return e.log.error(`multiaddr ${t.toString()} could not be resolved`,r),[]}}function Lm(...t){let e=[];for(let n of t)n!=null&&(pt(1/0,n),e.push(n));let r=Wo(e);return pt(1/0,r),r}var Yo={addressSorter:ri,maxParallelDials:zo,maxPeerAddrsToDial:25,dialTimeout:3e4,resolvers:{dnsaddr:ni}},Qo=class{pendingDials;queue;peerId;peerStore;connectionGater;transportManager;addressSorter;maxPeerAddrsToDial;dialTimeout;inProgressDialCount;pendingDialCount;shutDownController;connections;log;constructor(e,r={}){this.addressSorter=r.addressSorter??Yo.addressSorter,this.maxPeerAddrsToDial=r.maxPeerAddrsToDial??Yo.maxPeerAddrsToDial,this.dialTimeout=r.dialTimeout??Yo.dialTimeout,this.connections=r.connections??new wt,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.connectionGater=e.connectionGater,this.transportManager=e.transportManager,this.shutDownController=new AbortController,pt(1/0,this.shutDownController.signal),this.pendingDialCount=e.metrics?.registerMetric("libp2p_dial_queue_pending_dials"),this.inProgressDialCount=e.metrics?.registerMetric("libp2p_dial_queue_in_progress_dials"),this.pendingDials=[];for(let[n,i]of Object.entries(r.resolvers??{}))no.set(n,i);this.queue=new Mr({concurrency:r.maxParallelDials??Yo.maxParallelDials}),this.queue.on("add",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("active",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("completed",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("error",n=>{this.log.error("error in dial queue",n),this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("empty",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("idle",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)})}stop(){this.shutDownController.abort()}async dial(e,r={}){let{peerId:n,multiaddrs:i}=Fo(e),s=i.map(h=>({multiaddr:h,isCertified:!1})),o=this.createDialAbortControllers(r.signal),a;try{a=await this.calculateMultiaddrs(n,s,{...r,signal:o})}catch(h){throw o.clear(),h}let c=Array.from(this.connections.values()).flat().find(h=>r.force===!0?!1:a.find(p=>p.multiaddr.equals(h.remoteAddr)));if(c!=null)return this.log("already connected to %a",c.remoteAddr),c;let u=this.pendingDials.find(h=>!!(h.peerId!=null&&n!=null&&h.peerId.equals(n)||a.map(({multiaddr:p})=>p.toString()).join()===h.multiaddrs.map(p=>p.toString()).join()));if(u!=null)return this.log("joining existing dial target for %p",n),o.clear(),u.promise;this.log("creating dial target for",a.map(({multiaddr:h})=>h.toString()));let l={id:tv(),status:"queued",peerId:n,multiaddrs:a.map(({multiaddr:h})=>h)};l.promise=this.performDial(l,{...r,signal:o}).finally(()=>{this.pendingDials=this.pendingDials.filter(h=>h.id!==l.id),o.clear()}).catch(async h=>{if(this.log.error("dial failed to %s",l.multiaddrs.map(p=>p.toString()).join(", "),h),n!=null)try{await this.peerStore.patch(n,{metadata:{[qo]:Q(Date.now().toString())}})}catch(p){this.log.error("could not update last dial failure key for %p",n,p)}throw o.aborted?new S(h.message,Ss):h}),this.pendingDials.push(l);let f=await l.promise;return c=Array.from(this.connections.values()).flat().find(h=>r.force===!0?!1:h.id!==f.id&&h.remoteAddr.equals(f.remoteAddr)),c!=null?(this.log("already connected to %a",c.remoteAddr),await f.close(),c):(this.log("connection opened to %a",f.remoteAddr),f)}createDialAbortControllers(e){let r=Wo([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e]);try{pt?.(1/0,r)}catch{}return r}async calculateMultiaddrs(e,r=[],n={}){if(e!=null){if(this.peerId.equals(e))throw new S("Tried to dial self",F.ERR_DIALED_SELF);if(await this.connectionGater.denyDialPeer?.(e)===!0)throw new S("The dial request is blocked by gater.allowDialPeer",F.ERR_PEER_DIAL_INTERCEPTED);if(r.length===0){this.log("loading multiaddrs for %p",e);try{let l=await this.peerStore.get(e);r.push(...l.addresses),this.log("loaded multiaddrs for %p",e,r.map(({multiaddr:f})=>f.toString()))}catch(l){if(l.code!==F.ERR_NOT_FOUND)throw l}}}let i=(await Promise.all(r.map(async l=>{let f=await Tl(l.multiaddr,{...n,log:this.log});return f.length===1&&f[0].equals(l.multiaddr)?l:f.map(h=>({multiaddr:h,isCertified:!1}))}))).flat();if(e!=null){let l=`/p2p/${e.toString()}`;i=i.map(f=>f.multiaddr.protos().pop()?.path===!0?f:f.multiaddr.getPeerId()==null?{multiaddr:f.multiaddr.encapsulate(l),isCertified:f.isCertified}:f)}let s=i.filter(l=>{if(this.transportManager.transportForMultiaddr(l.multiaddr)==null)return!1;let f=l.multiaddr.getPeerId();return e!=null&&f!=null?e.equals(f):!0}),o=new Map;for(let l of s){let f=l.multiaddr.toString(),h=o.get(f);if(h!=null){h.isCertified=h.isCertified||l.isCertified||!1;continue}o.set(f,l)}let a=[...o.values()];if((a.length===0||a.length>this.maxPeerAddrsToDial)&&(this.log("addresses for %p before filtering",e??"unknown peer",i.map(({multiaddr:l})=>l.toString())),this.log("addresses for %p after filtering",e??"unknown peer",a.map(({multiaddr:l})=>l.toString()))),a.length===0)throw new S("The dial request has no valid addresses",F.ERR_NO_VALID_ADDRESSES);if(a.length>this.maxPeerAddrsToDial)throw new S("dial with more addresses than allowed",F.ERR_TOO_MANY_ADDRESSES);let c=[];for(let l of a)this.connectionGater.denyDialMultiaddr!=null&&await this.connectionGater.denyDialMultiaddr(l.multiaddr)||c.push(l);let u=c.sort(this.addressSorter);if(u.length===0)throw new S("The connection gater denied all addresses in the dial request",F.ERR_NO_VALID_ADDRESSES);return u}async performDial(e,r={}){let n=e.multiaddrs.map(()=>new AbortController);try{let i=new Mr({concurrency:1});i.on("error",o=>{this.log.error("error dialing %s %o",e.multiaddrs,o)});let s=await Promise.any(e.multiaddrs.map(async(o,a)=>{let c=n[a];if(c==null)throw new S("dialAction did not come with an AbortController",F.ERR_INVALID_PARAMETERS);let u=Lm(c.signal,r.signal);u.addEventListener("abort",()=>{this.log("dial to %a aborted",o)});let l=ut();return await i.add(async()=>{if(u.aborted){this.log("dial to %a was aborted before reaching the head of the peer dial queue",o),l.reject(new Cn);return}await this.queue.add(async()=>{try{if(u.aborted){this.log("dial to %a was aborted before reaching the head of the dial queue",o),l.reject(new Cn);return}e.status="active";let f=await this.transportManager.dial(o,{...r,signal:u});if(c.signal.aborted){this.log("multiple dials succeeded, closing superfluous connection"),f.close().catch(h=>{this.log.error("error closing superfluous connection",h)}),l.reject(new Cn);return}n[a]=void 0,n.forEach(h=>{h!==void 0&&h.abort()}),this.log("dial to %a succeeded",o),l.resolve(f)}catch(f){this.log.error("error during dial of %a",o,f),l.reject(f)}},{...r,signal:u}).catch(f=>{l.reject(f)})},{signal:u}).catch(f=>{l.reject(f)}).finally(()=>{u.clear()}),l.promise}));if(s==null)throw new S("successful dial led to empty object returned from peer dial queue",F.ERR_TRANSPORT_DIAL_FAILED);return e.status="success",s}catch(i){throw e.status="error",e.multiaddrs.length===1&&i.name==="AggregateError"?i.errors[0]:i}}};function tv(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var iv=50,bn={minConnections:Vo,maxConnections:$o,inboundConnectionThreshold:5,maxIncomingPendingConnections:10,autoDialConcurrency:25,autoDialPriority:0,autoDialMaxQueueLength:100},Xo=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;autoDial;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;constructor(e,r={}){this.maxConnections=r.maxConnections??bn.maxConnections;let n=r.minConnections??bn.minConnections;if(this.maxConnections<n)throw new S("Connection Manager maxConnections must be greater than minConnections",F.ERR_INVALID_PARAMETERS);this.connections=new wt,this.started=!1,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),this.allow=(r.allow??[]).map(i=>Ue(i)),this.deny=(r.deny??[]).map(i=>Ue(i)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=r.maxIncomingPendingConnections??bn.maxIncomingPendingConnections,this.inboundConnectionRateLimiter=new Pm.RateLimiterMemory({points:r.inboundConnectionThreshold??bn.inboundConnectionThreshold,duration:1}),this.autoDial=new Ho({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{minConnections:n,autoDialConcurrency:r.autoDialConcurrency??bn.autoDialConcurrency,autoDialPriority:r.autoDialPriority??bn.autoDialPriority,maxQueueLength:r.autoDialMaxQueueLength??bn.autoDialMaxQueueLength}),this.connectionPruner=new Go({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new Qo({peerId:e.peerId,metrics:e.metrics,peerStore:e.peerStore,transportManager:e.transportManager,connectionGater:e.connectionGater,logger:e.logger},{addressSorter:r.addressSorter??ri,maxParallelDials:r.maxParallelDials??zo,maxPeerAddrsToDial:r.maxPeerAddrsToDial??25,dialTimeout:r.dialTimeout??3e4,resolvers:r.resolvers??{dnsaddr:ni},connections:this.connections})}isStarted(){return this.started}async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,outbound:0};for(let r of this.connections.values())for(let n of r)n.direction==="inbound"?e.inbound++:e.outbound++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let r of this.connections.values())for(let n of r)for(let i of n.streams){let s=`${i.direction} ${i.protocol??"unnegotiated"}`;e[s]=(e[s]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let e={};for(let n of this.connections.values())for(let i of n){let s={};for(let o of i.streams){let a=`${o.direction} ${o.protocol??"unnegotiated"}`;s[a]=(s[a]??0)+1}for(let[o,a]of Object.entries(s))e[o]=e[o]??[],e[o].push(a)}let r={};for(let[n,i]of Object.entries(e)){i=i.sort((o,a)=>o-a);let s=Math.floor(i.length*.9);r[n]=i[s]}return r}}),this.autoDial.start(),this.started=!0,this.log("started")}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[r=>r.tags.has(y0)]});await Promise.all(e.map(async r=>{await this.openConnection(r.id).catch(n=>{this.log.error(n)})}))}).catch(e=>{this.log.error(e)}),this.autoDial.afterStart()}async stop(){this.dialQueue.stop(),this.autoDial.stop();let e=[];for(let r of this.connections.values())for(let n of r)e.push((async()=>{try{await n.close()}catch(i){this.log.error(i)}})());this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}onConnect(e){this._onConnect(e).catch(r=>{this.log.error(r)})}async _onConnect(e){let{detail:r}=e;if(!this.started){await r.close();return}let n=r.remotePeer,i=this.connections.get(n),s=!1;i!=null?i.push(r):(s=!0,this.connections.set(n,[r])),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),s&&this.events.safeDispatchEvent("peer:connect",{detail:r.remotePeer})}onDisconnect(e){let{detail:r}=e;if(!this.started)return;let n=r.remotePeer,i=this.connections.get(n);i!=null&&i.length>1?(i=i.filter(s=>s.id!==r.id),this.connections.set(n,i)):i!=null&&(this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:r.remotePeer}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let r=[];for(let n of this.connections.values())r=r.concat(n);return r}getConnectionsMap(){return this.connections}async openConnection(e,r={}){if(!this.isStarted())throw new S("Not started",F.ERR_NODE_NOT_STARTED);r.signal?.throwIfAborted();let{peerId:n}=Fo(e);if(n!=null&&r.force!==!0){this.log("dial %p",n);let a=this.getConnections(n).find(c=>!c.transient);if(a!=null)return this.log("had an existing non-transient connection to %p",n),a}let i=await this.dialQueue.dial(e,{...r,priority:r.priority??iv}),s=this.connections.get(i.remotePeer);s==null&&(s=[],this.connections.set(i.remotePeer,s));let o=!1;for(let a of s)a.id===i.id&&(o=!0);return o||s.push(i),i}async closeConnections(e,r={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async i=>{try{await i.close(r)}catch(s){i.abort(s)}}))}async acceptIncomingConnection(e){if(this.deny.some(i=>e.remoteAddr.toString().startsWith(i.toString())))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(i=>e.remoteAddr.toString().startsWith(i.toString())))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){let i=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(i,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,i),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){return this.dialQueue.pendingDials}};var Zo=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},li=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Zo(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let r=this.head;this.head=r.next=new Zo(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let r=this.tail.next;this.tail.next=null,this.tail=r,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var Pl=class extends Error{type;code;constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function jo(t={}){return sv(r=>{let n=r.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},t)}function sv(t,e){e=e??{};let r=e.onEnd,n=new li,i,s,o,a=ut(),c=async()=>{try{return n.isEmpty()?o?{done:!0}:await new Promise((y,g)=>{s=x=>{s=null,n.push(x);try{y(t(n))}catch(b){g(b)}return i}}):t(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=ut()})}},u=y=>s!=null?s(y):(n.push(y),i),l=y=>(n=new li,s!=null?s({error:y}):(n.push({error:y}),i)),f=y=>{if(o)return i;if(e?.objectMode!==!0&&y?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:y})},h=y=>o?i:(o=!0,y!=null?l(y):u({done:!0})),p=()=>(n=new li,h(),{done:!0}),d=y=>(h(y),{done:!0});if(i={[Symbol.asyncIterator](){return this},next:c,return:p,throw:d,push:f,end:h,get readableLength(){return n.size},onEmpty:async y=>{let g=y?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let x,b;g!=null&&(x=new Promise((I,v)=>{b=()=>{v(new Pl)},g.addEventListener("abort",b)}));try{await Promise.race([a.promise,x])}finally{b!=null&&g!=null&&g?.removeEventListener("abort",b)}}},r==null)return i;let m=i;return i={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(y){return m.throw(y),r!=null&&(r(y),r=void 0),{done:!0}},return(){return m.return(),r!=null&&(r(),r=void 0),{done:!0}},push:f,end(y){return m.end(y),r!=null&&(r(y),r=void 0),i},get readableLength(){return m.readableLength},onEmpty:y=>m.onEmpty(y)},i}function ov(t){return t[Symbol.asyncIterator]!=null}function av(...t){let e=[];for(let r of t)ov(r)||e.push(r);return e.length===t.length?function*(){for(let r of e)yield*r}():async function*(){let r=jo({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(t.map(async n=>{for await(let i of n)r.push(i)})),r.end()}catch(n){r.end(n)}}),yield*r}()}var wn=av;function es(t,...e){if(t==null)throw new Error("Empty pipeline");if(Dl(t)){let n=t;t=()=>n.source}else if(Nm(t)||Dm(t)){let n=t;t=()=>n}let r=[t,...e];if(r.length>1&&Dl(r[r.length-1])&&(r[r.length-1]=r[r.length-1].sink),r.length>2)for(let n=1;n<r.length-1;n++)Dl(r[n])&&(r[n]=uv(r[n]));return cv(...r)}var cv=(...t)=>{let e;for(;t.length>0;)e=t.shift()(e);return e},Dm=t=>t?.[Symbol.asyncIterator]!=null,Nm=t=>t?.[Symbol.iterator]!=null,Dl=t=>t==null?!1:t.sink!=null&&t.source!=null,uv=t=>e=>{let r=t.sink(e);if(r?.then!=null){let n=jo({objectMode:!0});r.then(()=>{n.end()},o=>{n.end(o)});let i,s=t.source;if(Dm(s))i=async function*(){yield*s,n.end()};else if(Nm(s))i=function*(){yield*s,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return wn(n,i())}return t.source};function lv(t){return t[Symbol.asyncIterator]!=null}function fv(t,e){if(lv(t))return async function*(){for await(let a of t)yield e(a)}();let r=vo(t),{value:n,done:i}=r.next();if(i===!0)return function*(){}();let s=e(n);if(typeof s.then=="function")return async function*(){yield await s;for await(let a of r)yield e(a)}();let o=e;return function*(){yield s;for(let a of r)yield o(a)}()}var km=fv;async function*ts(t,e){yield*km(t,async r=>(await e.merge(r.id,{multiaddrs:r.multiaddrs}),r))}function Jo(t){let e=new Set;return Kt(t,r=>e.has(r.id.toString())?!1:(e.add(r.id.toString()),!0))}async function*ea(t,e=1){let r=0;for await(let n of t)r++,yield n;if(r<e)throw new S(`more peers required, seen: ${r} min: ${e}`,"NOT_FOUND")}var ta=class{routers;started;components;constructor(e,r){this.routers=r.routers??[],this.started=!1,this.components=e}isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,r={}){if(this.routers.length===0)throw new S("No content routers available",F.ERR_NO_ROUTERS_AVAILABLE);yield*es(wn(...this.routers.map(n=>n.findProviders(e,r))),n=>ts(n,this.components.peerStore),n=>Jo(n),n=>ea(n))}async provide(e,r={}){if(this.routers.length===0)throw new S("No content routers available",F.ERR_NO_ROUTERS_AVAILABLE);await Promise.all(this.routers.map(async n=>{await n.provide(e,r)}))}async put(e,r,n){if(!this.isStarted())throw new S(er.NOT_STARTED_YET,F.DHT_NOT_STARTED);await Promise.all(this.routers.map(async i=>{await i.put(e,r,n)}))}async get(e,r){if(!this.isStarted())throw new S(er.NOT_STARTED_YET,F.DHT_NOT_STARTED);return Promise.any(this.routers.map(async n=>n.get(e,r)))}};function hv(t){return t[Symbol.asyncIterator]!=null}function dv(t){if(hv(t))return(async()=>{for await(let e of t)return e})();for(let e of t)return e}var Om=dv;var ra=class{log;peerId;peerStore;routers;constructor(e,r){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=r.routers??[]}async findPeer(e,r){if(this.routers.length===0)throw new S("No peer routers available",F.ERR_NO_ROUTERS_AVAILABLE);if(e.toString()===this.peerId.toString())throw new S("Should not try to find self",F.ERR_FIND_SELF);let n=this,i=await es(wn(...this.routers.map(s=>async function*(){try{yield await s.findPeer(e,r)}catch(o){n.log.error(o)}}())),s=>Kt(s,Boolean),s=>ts(s,this.peerStore),async s=>Om(s));if(i!=null)return i;throw new S(er.NOT_FOUND,F.ERR_NOT_FOUND)}async*getClosestPeers(e,r){if(this.routers.length===0)throw new S("No peer routers available",F.ERR_NO_ROUTERS_AVAILABLE);yield*es(wn(...this.routers.map(n=>n.getClosestPeers(e,r))),n=>ts(n,this.peerStore),n=>Jo(n),n=>ea(n))}};var Nl=32,kl=64,na=class{log;topologies;handlers;components;constructor(e){this.log=e.logger.forComponent("libp2p:registrar"),this.topologies=new Map,this.handlers=new Map,this.components=e,this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let r=this.handlers.get(e);if(r==null)throw new S(`No handler registered for protocol ${e}`,F.ERR_NO_HANDLER_FOR_PROTOCOL);return r}getTopologies(e){let r=this.topologies.get(e);return r==null?[]:[...r.values()]}async handle(e,r,n){if(this.handlers.has(e))throw new S(`Handler already registered for protocol ${e}`,F.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);let i=Mo.bind({ignoreUndefined:!0})({maxInboundStreams:Nl,maxOutboundStreams:kl},n);this.handlers.set(e,{handler:r,options:i}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]})}async unhandle(e){(Array.isArray(e)?e:[e]).forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()})}async register(e,r){if(r==null)throw new S("invalid topology",F.ERR_INVALID_PARAMETERS);let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,i=this.topologies.get(e);return i==null&&(i=new Map,this.topologies.set(e,i)),i.set(n,r),n}unregister(e){for(let[r,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(r))}_onDisconnect(e){let r=e.detail;this.components.peerStore.get(r).then(n=>{for(let i of n.protocols){let s=this.topologies.get(i);if(s!=null)for(let o of s.values())o.onDisconnect?.(r)}}).catch(n=>{n.code!==F.ERR_NOT_FOUND&&this.log.error("could not inform topologies of disconnecting peer %p",r,n)})}_onPeerUpdate(e){let{peer:r,previous:n}=e.detail,i=(n?.protocols??[]).filter(s=>!r.protocols.includes(s));for(let s of i){let o=this.topologies.get(s);if(o!=null)for(let a of o.values())a.onDisconnect?.(r.id)}}_onPeerIdentify(e){let r=e.detail.protocols,n=e.detail.connection,i=e.detail.peerId;for(let s of r){let o=this.topologies.get(s);if(o!=null)for(let a of o.values())n.transient&&a.notifyOnTransient!==!0||a.onConnect?.(i,n)}}};var Ol=class extends Map{metric;constructor(e){super();let{name:r,metrics:n}=e;this.metric=n.registerMetric(r),this.updateComponentMetric()}set(e,r){return super.set(e,r),this.updateComponentMetric(),this}delete(e){let r=super.delete(e);return this.updateComponentMetric(),r}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Mm(t){let{name:e,metrics:r}=t,n;return r!=null?n=new Ol({name:e,metrics:r}):n=new Map,n}var ia=class{log;components;transports;listeners;faultTolerance;started;constructor(e,r={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=new Map,this.listeners=Mm({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=r.faultTolerance??Er.FATAL_ALL}add(e){let r=e[Symbol.toStringTag];if(r==null)throw new S("Transport must have a valid tag",F.ERR_INVALID_KEY);if(this.transports.has(r))throw new S(`There is already a transport with the tag ${r}`,F.ERR_DUPLICATE_TRANSPORT);this.log("adding transport %s",r),this.transports.set(r,e),this.listeners.has(r)||this.listeners.set(r,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){let e=[];for(let[r,n]of this.listeners)for(this.log("closing listeners for %s",r);n.length>0;){let i=n.pop();i!=null&&e.push(i.close())}await Promise.all(e),this.log("all listeners closed");for(let r of this.listeners.keys())this.listeners.set(r,[]);this.started=!1}async dial(e,r){let n=this.transportForMultiaddr(e);if(n==null)throw new S(`No transport available for address ${String(e)}`,F.ERR_TRANSPORT_UNAVAILABLE);try{return await n.dial(e,{...r,upgrader:this.components.upgrader})}catch(i){throw i.code==null&&(i.code=F.ERR_TRANSPORT_DIAL_FAILED),i}}getAddrs(){let e=[];for(let r of this.listeners.values())for(let n of r)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}transportForMultiaddr(e){for(let r of this.transports.values())if(r.filter([e]).length>0)return r}async listen(e){if(!this.isStarted())throw new S("Not started",F.ERR_NODE_NOT_STARTED);if(e==null||e.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let r=[];for(let[n,i]of this.transports.entries()){let s=i.filter(e),o=[];for(let u of s){this.log("creating listener for %s on %a",n,u);let l=i.createListener({upgrader:this.components.upgrader}),f=this.listeners.get(n)??[];f==null&&(f=[],this.listeners.set(n,f)),f.push(l),l.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:l})}),l.addEventListener("close",()=>{let h=f.findIndex(p=>p===l);f.splice(h,1),this.components.events.safeDispatchEvent("transport:close",{detail:l})}),o.push(l.listen(u))}if(o.length===0){r.push(n);continue}if((await Promise.allSettled(o)).find(u=>u.status==="fulfilled")==null&&this.faultTolerance!==Er.NO_FATAL)throw new S(`Transport (${n}) could not listen on any available address`,F.ERR_NO_VALID_ADDRESSES)}if(r.length===this.transports.size){let n=`no valid addresses were provided for transports [${r.join(", ")}]`;if(this.faultTolerance===Er.FATAL_ALL)throw new S(n,F.ERR_NO_VALID_ADDRESSES);this.log(`libp2p in dial mode only: ${n}`)}}async remove(e){let r=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);let n=[];for(this.log.trace("closing listeners for %s",e);r.length>0;){let i=r.pop();i!=null&&n.push(i.close())}await Promise.all(n),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let r of this.transports.keys())e.push(this.remove(r));await Promise.all(e)}};var Je="/multistream/1.0.0";var sa=class extends Error{type;code;constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=r??"ABORT_ERR"}};async function Um(t,e,r){if(e==null)return t;if(e.aborted)return Promise.reject(new sa(r?.errorMessage,r?.errorCode));let n,i=new sa(r?.errorMessage,r?.errorCode);try{return await Promise.race([t,new Promise((s,o)=>{n=()=>{o(i)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var Ml=class{needNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.needNext=ut(),this.needNext.resolve(),this.haveNext=ut()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("Have next but next was undefined");let e=this.nextResult;return this.nextResult=void 0,this.needNext.resolve(),this.needNext=ut(),e}async throw(e){return this.ended=!0,e!=null&&this.haveNext.reject(e),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return await this._push(void 0),e}async push(e,r){await this._push(e,r)}async end(e,r){e!=null?await this.throw(e):await this._push(void 0,r)}async _push(e,r){if(e!=null&&this.ended)throw new Error("Cannot push value onto an ended pushable");this.nextResult!=null&&await this.needNext.promise,e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=ut(),await Um(this.needNext.promise,r?.signal,r)}};function Fm(){return new Ml}var oa=class extends Error{code;constructor(e,r){super(e),this.code=r}},Ul=class extends oa{type;constructor(e){super(e,"ABORT_ERR"),this.type="aborted"}};function Km(t,e){let r=Fm();t.sink(r).catch(async o=>{await r.end(o)}),t.sink=async o=>{for await(let a of o)await r.push(a);await r.end()};let n=t.source;t.source[Symbol.iterator]!=null?n=t.source[Symbol.iterator]():t.source[Symbol.asyncIterator]!=null&&(n=t.source[Symbol.asyncIterator]());let i=new ze;return{read:async(o,a)=>{a?.signal?.throwIfAborted();let c,u=new Promise((l,f)=>{c=()=>{f(new Ul("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(o==null){let{done:f,value:h}=await Promise.race([n.next(),u]);return f===!0?new ze:h}for(;i.byteLength<o;){let{value:f,done:h}=await Promise.race([n.next(),u]);if(h===!0)throw new oa("unexpected end of input","ERR_UNEXPECTED_EOF");i.append(f)}let l=i.sublist(0,o);return i.consume(o),l}finally{c!=null&&a?.signal?.removeEventListener("abort",c)}},write:async(o,a)=>{a?.signal?.throwIfAborted(),o instanceof Uint8Array?await r.push(o,a):await r.push(o.subarray(),a)},unwrap:()=>{if(i.byteLength>0){let o=t.source;t.source=async function*(){e?.yieldBytes===!1?yield i:yield*i,yield*o}()}return t}}}function aa(t){return t[Symbol.asyncIterator]!=null}var ca=t=>{let e=it(t),r=tt(e);return dt(t,r),ca.bytes=e,r};ca.bytes=0;function En(t,e){e=e??{};let r=e.lengthEncoder??ca;function*n(i){let s=r(i.byteLength);s instanceof Uint8Array?yield s:yield*s,i instanceof Uint8Array?yield i:yield*i}return aa(t)?async function*(){for await(let i of t)yield*n(i)}():function*(){for(let i of t)yield*n(i)}()}En.single=(t,e)=>{e=e??{};let r=e.lengthEncoder??ca;return new ze(r(t.byteLength),t)};var fi=ve(Yu(),1);var pv=8,mv=1024*1024*4,vn;(function(t){t[t.LENGTH=0]="LENGTH",t[t.DATA=1]="DATA"})(vn||(vn={}));var Kl=t=>{let e=Ut(t);return Kl.bytes=it(e),e};Kl.bytes=0;function Fl(t,e){let r=new ze,n=vn.LENGTH,i=-1,s=e?.lengthDecoder??Kl,o=e?.maxLengthLength??pv,a=e?.maxDataLength??mv;function*c(){for(;r.byteLength>0;){if(n===vn.LENGTH)try{if(i=s(r),i<0)throw(0,fi.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(i>a)throw(0,fi.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let u=s.bytes;r.consume(u),e?.onLength!=null&&e.onLength(i),n=vn.DATA}catch(u){if(u instanceof RangeError){if(r.byteLength>o)throw(0,fi.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw u}if(n===vn.DATA){if(r.byteLength<i)break;let u=r.sublist(0,i);r.consume(i),e?.onData!=null&&e.onData(u),yield u,n=vn.LENGTH}}}return aa(t)?async function*(){for await(let u of t)r.append(u),yield*c();if(r.byteLength>0)throw(0,fi.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let u of t)r.append(u),yield*c();if(r.byteLength>0)throw(0,fi.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}Fl.fromReader=(t,e)=>{let r=1,n=async function*(){for(;;)try{let{done:s,value:o}=await t.next(r);if(s===!0)return;o!=null&&(yield o)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{r=1}}();return Fl(n,{...e??{},onLength:s=>{r=s}})};var ua=class extends Error{code;constructor(e,r){super(e),this.code=r}},qm=t=>Ut(t);qm.bytes=0;function rs(t,e={}){let r=Km(t,e);return e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=it(e.maxDataLength)),{read:async i=>{let s=-1,o=new ze,a=e?.lengthDecoder??qm;for(;;){o.append(await r.read(1,i));try{s=a(o)}catch(c){if(c instanceof RangeError)continue;throw c}if(e?.maxLengthLength!=null&&o.byteLength>e.maxLengthLength)throw new ua("message length length too long","ERR_MSG_LENGTH_TOO_LONG");if(s>-1)break}if(e?.maxDataLength!=null&&s>e.maxDataLength)throw new ua("message length too long","ERR_MSG_DATA_TOO_LONG");return r.read(s,i)},write:async(i,s)=>{await r.write(En.single(i,e),s)},writeV:async(i,s)=>{let o=new ze(...i.map(a=>En.single(a,e)));await r.write(o,s)},unwrap:()=>r.unwrap()}}var gv=Q(`
49
49
  `);async function _n(t,e,r){await t.write(e,r)}async function Vm(t,e,r){await t.writeV(e,r)}async function xv(t,e){let r=await t.read(e);if(r.byteLength===0||r.get(r.byteLength-1)!==gv[0])throw e.log.error("Invalid mss message - missing newline",r),new S("missing newline","ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");return r.sublist(0,-1)}async function Vr(t,e){let r=await xv(t,e);return se(r.subarray())}async function ns(t,e,r){if(e=Array.isArray(e)?[...e]:[e],e.length===1)return bv(t,e[0],r);let n=rs(t,{...r,maxDataLength:1024}),i=e.shift();if(i==null)throw new Error("At least one protocol must be specified");r.log.trace('select: write ["%s", "%s"]',Je,i);let s=Q(`${Je}
50
50
  `),o=Q(`${i}
51
51
  `);await Vm(n,[s,o],r),r.log.trace("select: reading multistream-select header");let a=await Vr(n,r);if(r.log.trace('select: read "%s"',a),a===Je&&(r.log.trace("select: reading protocol response"),a=await Vr(n,r),r.log.trace('select: read "%s"',a)),a===i)return{stream:n.unwrap(),protocol:i};for(let c of e){r.log.trace('select: write "%s"',c),await _n(n,Q(`${c}
@@ -58,7 +58,7 @@
58
58
  `),r),r.log.trace('handle: responded with "%s" for "%s"',i,i),{stream:n.unwrap(),protocol:i};if(i==="ls"){let s=new ze(...e.map(o=>En.single(Q(`${o}
59
59
  `))),Q(`
60
60
  `));r.log.trace('handle: respond with "%s" for %s',e,i),await _n(n,s,r),r.log.trace('handle: responded with "%s" for %s',e,i);continue}r.log('handle: respond with "na" for "%s"',i),await _n(n,Q(`na
61
- `),r),r.log('handle: responded with "na" for "%s"',i)}}var Ev=500,ql=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;transient;log;tags;_newStream;_close;_abort;_getStreams;constructor(e){let{remoteAddr:r,remotePeer:n,newStream:i,close:s,abort:o,getStreams:a}=e;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=r,this.remotePeer=n,this.direction=e.direction,this.status="open",this.timeline=e.timeline,this.multiplexer=e.multiplexer,this.encryption=e.encryption,this.transient=e.transient??!1,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=i,this._close=s,this._abort=o,this._getStreams=a,this.tags=[]}[Symbol.toStringTag]="Connection";[m0]=!0;get streams(){return this._getStreams()}async newStream(e,r){if(this.status==="closing")throw new S("the connection is being closed","ERR_CONNECTION_BEING_CLOSED");if(this.status==="closed")throw new S("the connection is closed","ERR_CONNECTION_CLOSED");if(Array.isArray(e)||(e=[e]),this.transient&&r?.runOnTransientConnection!==!0)throw new S("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");let n=await this._newStream(e,r);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 r=AbortSignal.timeout(Ev);pt(1/0,r),e={...e,signal:r}}try{this.log.trace("closing all streams"),await Promise.all(this.streams.map(async r=>r.close(e))),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(r){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,r),this.abort(r)}}}abort(e){this.log.error("aborting connection to %a due to error",this.remoteAddr,e),this.status="closing",this.streams.forEach(r=>{r.abort(e)}),this.log.error("all streams aborted",this.streams.length),this._abort(e),this.timeline.close=Date.now(),this.status="closed"}};function zm(t){return new ql(t)}var _v=3e4;function Sv(t,e){try{let{options:r}=e.getHandler(t);return r.maxInboundStreams}catch(r){if(r.code!==F.ERR_NO_HANDLER_FOR_PROTOCOL)throw r}return Nl}function Av(t,e,r={}){try{let{options:n}=e.getHandler(t);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.code!==F.ERR_NO_HANDLER_FOR_PROTOCOL)throw n}return r.maxOutboundStreams??kl}function Hm(t,e,r){let n=0;return r.streams.forEach(i=>{i.direction===e&&i.protocol===t&&n++}),n}var fa=class{components;connectionEncryption;muxers;inboundUpgradeTimeout;events;constructor(e,r){this.components=e,this.connectionEncryption=new Map,r.connectionEncryption.forEach(n=>{this.connectionEncryption.set(n.protocol,n)}),this.muxers=new Map,r.muxers.forEach(n=>{this.muxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=r.inboundUpgradeTimeout??3e4,this.events=e.events}async shouldBlockConnection(e,r,n){let i=this.components.connectionGater[n];if(i!==void 0&&await i(e,r))throw new S(`The multiaddr connection is blocked by gater.${n}`,F.ERR_CONNECTION_INTERCEPTED)}async upgradeInbound(e,r){if(!await this.components.connectionManager.acceptIncomingConnection(e))throw new S("connection denied",F.ERR_CONNECTION_DENIED);let i,s,o,a,c,u=AbortSignal.timeout(this.inboundUpgradeTimeout),l=()=>{e.abort(new S("inbound upgrade timeout",Ss))};u.addEventListener("abort",l,{once:!0}),pt(1/0,u);try{if(await this.components.connectionGater.denyInboundConnection?.(e)===!0)throw new S("The multiaddr connection is blocked by gater.acceptConnection",F.ERR_CONNECTION_INTERCEPTED);this.components.metrics?.trackMultiaddrConnection(e),e.log("starting the inbound connection upgrade");let f=e;if(r?.skipProtection!==!0){let h=this.components.connectionProtector;h!=null&&(e.log("protecting the inbound connection"),f=await h.protect(e))}try{if(i=f,r?.skipEncryption!==!0){({conn:i,remotePeer:s,protocol:c}=await this._encryptInbound(f));let h={...f,...i};await this.shouldBlockConnection(s,h,"denyInboundEncryptedConnection")}else{let h=e.remoteAddr.getPeerId();if(h==null)throw new S("inbound connection that skipped encryption must have a peer id",F.ERR_INVALID_MULTIADDR);let p=ce(h);c="native",s=p}if(o=i,r?.muxerFactory!=null)a=r.muxerFactory;else if(this.muxers.size>0){let h=await this._multiplexInbound({...f,...i},this.muxers);a=h.muxerFactory,o=h.stream}}catch(h){throw e.log.error("failed to upgrade inbound connection",h),h}return await this.shouldBlockConnection(s,e,"denyInboundUpgradedConnection"),e.log("successfully upgraded inbound connection"),this._createConnection({cryptoProtocol:c,direction:"inbound",maConn:e,upgradedConn:o,muxerFactory:a,remotePeer:s,transient:r?.transient})}finally{u.removeEventListener("abort",l),this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,r){let n=e.remoteAddr.getPeerId(),i;n!=null&&(i=ce(n),await this.shouldBlockConnection(i,e,"denyOutboundConnection"));let s,o,a,c,u;this.components.metrics?.trackMultiaddrConnection(e),e.log("starting the outbound connection upgrade");let l=e;if(r?.skipProtection!==!0){let f=this.components.connectionProtector;f!=null&&(l=await f.protect(e))}try{if(s=l,r?.skipEncryption!==!0){({conn:s,remotePeer:o,protocol:c}=await this._encryptOutbound(l,i));let f={...l,...s};await this.shouldBlockConnection(o,f,"denyOutboundEncryptedConnection")}else{if(i==null)throw new S("Encryption was skipped but no peer id was passed",F.ERR_INVALID_PEER);c="native",o=i}if(a=s,r?.muxerFactory!=null)u=r.muxerFactory;else if(this.muxers.size>0){let f=await this._multiplexOutbound({...l,...s},this.muxers);u=f.muxerFactory,a=f.stream}}catch(f){throw e.log.error("failed to upgrade outbound connection",f),await e.close(f),f}return await this.shouldBlockConnection(o,e,"denyOutboundUpgradedConnection"),e.log("successfully upgraded outbound connection"),this._createConnection({cryptoProtocol:c,direction:"outbound",maConn:e,upgradedConn:a,muxerFactory:u,remotePeer:o,transient:r?.transient})}_createConnection(e){let{cryptoProtocol:r,direction:n,maConn:i,upgradedConn:s,remotePeer:o,muxerFactory:a,transient:c}=e,u,l,f;a!=null&&(u=a.createStreamMuxer({direction:n,onIncomingStream:d=>{f!=null&&Promise.resolve().then(async()=>{let m=this.components.registrar.getProtocols(),{stream:y,protocol:g}=await is(d,m,{log:d.log,yieldBytes:!1});if(f==null)return;f.log("incoming stream opened on %s",g);let x=Sv(g,this.components.registrar);if(Hm(g,"inbound",f)===x){let I=new S(`Too many inbound protocol streams for protocol "${g}" - limit ${x}`,F.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS);throw d.abort(I),I}d.source=y.source,d.sink=y.sink,d.protocol=g,y.closeWrite!=null&&(d.closeWrite=y.closeWrite),y.closeRead!=null&&(d.closeRead=y.closeRead),y.close!=null&&(d.close=y.close),await this.components.peerStore.merge(o,{protocols:[g]}),this.components.metrics?.trackProtocolStream(d,f),this._onStream({connection:f,stream:d,protocol:g})}).catch(async m=>{f.log.error("error handling incoming stream id %s",d.id,m.message,m.code,m.stack),d.timeline.close==null&&await d.close()})}}),l=async(d,m={})=>{if(u==null)throw new S("Stream is not multiplexed",F.ERR_MUXER_UNAVAILABLE);f.log("starting new stream for protocols %s",d);let y=await u.newStream();f.log.trace("started new stream %s for protocols %s",y.id,d);try{if(m.signal==null){y.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",d);let v=AbortSignal.timeout(_v);pt(1/0,v),m={...m,signal:v}}y.log.trace("selecting protocol from protocols %s",d);let{stream:g,protocol:x}=await ns(y,d,{...m,log:y.log,yieldBytes:!0});y.log("selected protocol %s",x);let b=Av(x,this.components.registrar,m);if(Hm(x,"outbound",f)>=b){let v=new S(`Too many outbound protocol streams for protocol "${x}" - limit ${b}`,F.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);throw y.abort(v),v}return await this.components.peerStore.merge(o,{protocols:[x]}),y.source=g.source,y.sink=g.sink,y.protocol=x,g.closeWrite!=null&&(y.closeWrite=g.closeWrite),g.closeRead!=null&&(y.closeRead=g.closeRead),g.close!=null&&(y.close=g.close),this.components.metrics?.trackProtocolStream(y,f),y}catch(g){throw f.log.error("could not create new stream for protocols %s",d,g),y.timeline.close==null&&y.abort(g),g.code!=null?g:new S(String(g),F.ERR_UNSUPPORTED_PROTOCOL)}},Promise.all([u.sink(s.source),s.sink(u.source)]).catch(d=>{f.log.error("error piping data through muxer",d)}));let h=i.timeline;i.timeline=new Proxy(h,{set:(...d)=>(f!=null&&d[1]==="close"&&d[2]!=null&&h.close==null&&(async()=>{try{f.status==="open"&&await f.close()}catch(m){f.log.error("error closing connection after timeline close",m)}finally{this.events.safeDispatchEvent("connection:close",{detail:f})}})().catch(m=>{f.log.error("error thrown while dispatching connection:close event",m)}),Reflect.set(...d))}),i.timeline.upgraded=Date.now();let p=()=>{throw new S("connection is not multiplexed",F.ERR_CONNECTION_NOT_MULTIPLEXED)};return f=zm({remoteAddr:i.remoteAddr,remotePeer:o,status:"open",direction:n,timeline:i.timeline,multiplexer:u?.protocol,encryption:r,transient:c,logger:this.components.logger,newStream:l??p,getStreams:()=>u!=null?u.streams:[],close:async d=>{u!=null&&(f.log.trace("close muxer"),await u.close(d)),f.log.trace("close maconn"),await i.close(d),f.log.trace("closed maconn")},abort:d=>{i.abort(d),u?.abort(d)}}),this.events.safeDispatchEvent("connection:open",{detail:f}),f}_onStream(e){let{connection:r,stream:n,protocol:i}=e,{handler:s,options:o}=this.components.registrar.getHandler(i);if(r.transient&&o.runOnTransientConnection!==!0)throw new S("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");s({connection:r,stream:n})}async _encryptInbound(e){let r=Array.from(this.connectionEncryption.keys());e.log("handling inbound crypto protocol selection",r);try{let{stream:n,protocol:i}=await is(e,r,{log:e.log}),s=this.connectionEncryption.get(i);if(s==null)throw new Error(`no crypto module found for ${i}`);return e.log("encrypting inbound connection using",i),{...await s.secureInbound(this.components.peerId,n),protocol:i}}catch(n){throw new S(String(n),F.ERR_ENCRYPTION_FAILED)}}async _encryptOutbound(e,r){let n=Array.from(this.connectionEncryption.keys());e.log("selecting outbound crypto protocol",n);try{e.log.trace("selecting encrypter from %s",n);let{stream:i,protocol:s}=await ns(e,n,{log:e.log,yieldBytes:!0}),o=this.connectionEncryption.get(s);if(o==null)throw new Error(`no crypto module found for ${s}`);return e.log("encrypting outbound connection to %p using %p",r),{...await o.secureOutbound(this.components.peerId,i,r),protocol:s}}catch(i){throw new S(String(i),F.ERR_ENCRYPTION_FAILED)}}async _multiplexOutbound(e,r){let n=Array.from(r.keys());e.log("outbound selecting muxer %s",n);try{e.log.trace("selecting stream muxer from %s",n);let{stream:i,protocol:s}=await ns(e,n,{log:e.log,yieldBytes:!0});e.log("selected %s as muxer protocol",s);let o=r.get(s);return{stream:i,muxerFactory:o}}catch(i){throw e.log.error("error multiplexing outbound connection",i),new S(String(i),F.ERR_MUXER_UNAVAILABLE)}}async _multiplexInbound(e,r){let n=Array.from(r.keys());e.log("inbound handling muxers %s",n);try{let{stream:i,protocol:s}=await is(e,n,{log:e.log}),o=r.get(s);return{stream:i,muxerFactory:o}}catch(i){throw e.log.error("error multiplexing inbound connection",i),new S(String(i),F.ERR_MUXER_UNAVAILABLE)}}};var Gm="1.0.5-10ea19700",Wm="libp2p";var Vl=class extends wi{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let r=new wi,n=r.dispatchEvent.bind(r);r.dispatchEvent=a=>{let c=n(a),u=this.dispatchEvent(new Ka(a.type,{detail:a.detail}));return c||u},pt(1/0,r),this.peerId=e.peerId,this.logger=e.logger??Qs(),this.log=this.logger.forComponent("libp2p"),this.services={};let i=this.components=Jd({peerId:e.peerId,nodeInfo:e.nodeInfo??{name:Wm,version:Gm},logger:this.logger,events:r,datastore:e.datastore??new So,connectionGater:up(e.connectionGater)});this.peerStore=this.configureComponent("peerStore",new Eo(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",a=>{if(a.detail.previous==null){let c={id:a.detail.peer.id,multiaddrs:a.detail.peer.addresses.map(u=>u.multiaddr)};i.events.safeDispatchEvent("peer:discovery",{detail:c})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new fa(this.components,{connectionEncryption:(e.connectionEncryption??[]).map((a,c)=>this.configureComponent(`connection-encryption-${c}`,a(this.components))),muxers:(e.streamMuxers??[]).map((a,c)=>this.configureComponent(`stream-muxers-${c}`,a(this.components))),inboundUpgradeTimeout:e.connectionManager.inboundUpgradeTimeout}),this.configureComponent("transportManager",new ia(this.components,e.transportManager)),this.configureComponent("connectionManager",new Xo(this.components,e.connectionManager)),this.configureComponent("registrar",new na(this.components)),this.configureComponent("addressManager",new Ao(this.components,e.addresses));let s=(e.peerRouters??[]).map((a,c)=>this.configureComponent(`peer-router-${c}`,a(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new ra(this.components,{routers:s}));let o=(e.contentRouters??[]).map((a,c)=>this.configureComponent(`content-router-${c}`,a(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new ta(this.components,{routers:o})),(e.peerDiscovery??[]).forEach((a,c)=>{this.configureComponent(`peer-discovery-${c}`,a(this.components)).addEventListener("peer",l=>{this.#e(l)})}),e.transports.forEach((a,c)=>{this.components.transportManager.add(this.configureComponent(`transport-${c}`,a(this.components)))}),e.services!=null)for(let a of Object.keys(e.services)){let c=e.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[ka]!=null&&(this.log("registering service %s for content routing",a),o.push(u[ka])),u[Ua]!=null&&(this.log("registering service %s for peer routing",a),s.push(u[Ua])),u[Oa]!=null&&(this.log("registering service %s for peer discovery",a),u[Oa].addEventListener("peer",l=>{this.#e(l)}))}}configureComponent(e,r){return r==null&&this.log.error("component %s was null or undefined",e),this.components[e]=r,r}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 fn;for(let r of this.components.connectionManager.getConnections())e.add(r.remotePeer);return Array.from(e)}async dial(e,r={}){return this.components.connectionManager.openConnection(e,r)}async dialProtocol(e,r,n={}){if(r==null)throw new S("no protocols were provided to open a stream",F.ERR_INVALID_PROTOCOLS_FOR_STREAM);if(r=Array.isArray(r)?r:[r],r.length===0)throw new S("no protocols were provided to open a stream",F.ERR_INVALID_PROTOCOLS_FOR_STREAM);return(await this.dial(e,n)).newStream(r,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,r={}){Nr(e)&&(e=ce(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e,r)}async getPublicKey(e,r={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;let n=await this.peerStore.get(e);if(n.id.publicKey!=null)return n.id.publicKey;let i=Te([Q("/pk/"),e.multihash.digest]),s=await this.contentRouting.get(i,r);return Mi(s),await this.peerStore.patch(e,{publicKey:s}),s}async handle(e,r,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async i=>{await this.components.registrar.handle(i,r,n)}))}async unhandle(e){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async r=>{await this.components.registrar.unhandle(r)}))}async register(e,r){return this.components.registrar.register(e,r)}unregister(e){this.components.registrar.unregister(e)}#e(e){let{detail:r}=e;if(r.id.toString()===this.peerId.toString()){this.log.error(new Error(F.ERR_DISCOVERED_SELF));return}this.components.peerStore.merge(r.id,{multiaddrs:r.multiaddrs}).catch(n=>{this.log.error(n)})}};async function Ym(t){return t.peerId??=await id(),new Vl(Np(t))}async function Rv(t){let e=await Ym(t);return t.start!==!1&&await e.start(),e}return cy(Cv);})();
61
+ `),r),r.log('handle: responded with "na" for "%s"',i)}}var Ev=500,ql=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;transient;log;tags;_newStream;_close;_abort;_getStreams;constructor(e){let{remoteAddr:r,remotePeer:n,newStream:i,close:s,abort:o,getStreams:a}=e;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=r,this.remotePeer=n,this.direction=e.direction,this.status="open",this.timeline=e.timeline,this.multiplexer=e.multiplexer,this.encryption=e.encryption,this.transient=e.transient??!1,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=i,this._close=s,this._abort=o,this._getStreams=a,this.tags=[]}[Symbol.toStringTag]="Connection";[m0]=!0;get streams(){return this._getStreams()}async newStream(e,r){if(this.status==="closing")throw new S("the connection is being closed","ERR_CONNECTION_BEING_CLOSED");if(this.status==="closed")throw new S("the connection is closed","ERR_CONNECTION_CLOSED");if(Array.isArray(e)||(e=[e]),this.transient&&r?.runOnTransientConnection!==!0)throw new S("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");let n=await this._newStream(e,r);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 r=AbortSignal.timeout(Ev);pt(1/0,r),e={...e,signal:r}}try{this.log.trace("closing all streams"),await Promise.all(this.streams.map(async r=>r.close(e))),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(r){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,r),this.abort(r)}}}abort(e){this.log.error("aborting connection to %a due to error",this.remoteAddr,e),this.status="closing",this.streams.forEach(r=>{r.abort(e)}),this.log.error("all streams aborted",this.streams.length),this._abort(e),this.timeline.close=Date.now(),this.status="closed"}};function zm(t){return new ql(t)}var _v=3e4;function Sv(t,e){try{let{options:r}=e.getHandler(t);return r.maxInboundStreams}catch(r){if(r.code!==F.ERR_NO_HANDLER_FOR_PROTOCOL)throw r}return Nl}function Av(t,e,r={}){try{let{options:n}=e.getHandler(t);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.code!==F.ERR_NO_HANDLER_FOR_PROTOCOL)throw n}return r.maxOutboundStreams??kl}function Hm(t,e,r){let n=0;return r.streams.forEach(i=>{i.direction===e&&i.protocol===t&&n++}),n}var fa=class{components;connectionEncryption;muxers;inboundUpgradeTimeout;events;constructor(e,r){this.components=e,this.connectionEncryption=new Map,r.connectionEncryption.forEach(n=>{this.connectionEncryption.set(n.protocol,n)}),this.muxers=new Map,r.muxers.forEach(n=>{this.muxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=r.inboundUpgradeTimeout??3e4,this.events=e.events}async shouldBlockConnection(e,r,n){let i=this.components.connectionGater[n];if(i!==void 0&&await i(e,r))throw new S(`The multiaddr connection is blocked by gater.${n}`,F.ERR_CONNECTION_INTERCEPTED)}async upgradeInbound(e,r){if(!await this.components.connectionManager.acceptIncomingConnection(e))throw new S("connection denied",F.ERR_CONNECTION_DENIED);let i,s,o,a,c,u=AbortSignal.timeout(this.inboundUpgradeTimeout),l=()=>{e.abort(new S("inbound upgrade timeout",Ss))};u.addEventListener("abort",l,{once:!0}),pt(1/0,u);try{if(await this.components.connectionGater.denyInboundConnection?.(e)===!0)throw new S("The multiaddr connection is blocked by gater.acceptConnection",F.ERR_CONNECTION_INTERCEPTED);this.components.metrics?.trackMultiaddrConnection(e),e.log("starting the inbound connection upgrade");let f=e;if(r?.skipProtection!==!0){let h=this.components.connectionProtector;h!=null&&(e.log("protecting the inbound connection"),f=await h.protect(e))}try{if(i=f,r?.skipEncryption!==!0){({conn:i,remotePeer:s,protocol:c}=await this._encryptInbound(f));let h={...f,...i};await this.shouldBlockConnection(s,h,"denyInboundEncryptedConnection")}else{let h=e.remoteAddr.getPeerId();if(h==null)throw new S("inbound connection that skipped encryption must have a peer id",F.ERR_INVALID_MULTIADDR);let p=ce(h);c="native",s=p}if(o=i,r?.muxerFactory!=null)a=r.muxerFactory;else if(this.muxers.size>0){let h=await this._multiplexInbound({...f,...i},this.muxers);a=h.muxerFactory,o=h.stream}}catch(h){throw e.log.error("failed to upgrade inbound connection",h),h}return await this.shouldBlockConnection(s,e,"denyInboundUpgradedConnection"),e.log("successfully upgraded inbound connection"),this._createConnection({cryptoProtocol:c,direction:"inbound",maConn:e,upgradedConn:o,muxerFactory:a,remotePeer:s,transient:r?.transient})}finally{u.removeEventListener("abort",l),this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,r){let n=e.remoteAddr.getPeerId(),i;n!=null&&(i=ce(n),await this.shouldBlockConnection(i,e,"denyOutboundConnection"));let s,o,a,c,u;this.components.metrics?.trackMultiaddrConnection(e),e.log("starting the outbound connection upgrade");let l=e;if(r?.skipProtection!==!0){let f=this.components.connectionProtector;f!=null&&(l=await f.protect(e))}try{if(s=l,r?.skipEncryption!==!0){({conn:s,remotePeer:o,protocol:c}=await this._encryptOutbound(l,i));let f={...l,...s};await this.shouldBlockConnection(o,f,"denyOutboundEncryptedConnection")}else{if(i==null)throw new S("Encryption was skipped but no peer id was passed",F.ERR_INVALID_PEER);c="native",o=i}if(a=s,r?.muxerFactory!=null)u=r.muxerFactory;else if(this.muxers.size>0){let f=await this._multiplexOutbound({...l,...s},this.muxers);u=f.muxerFactory,a=f.stream}}catch(f){throw e.log.error("failed to upgrade outbound connection",f),await e.close(f),f}return await this.shouldBlockConnection(o,e,"denyOutboundUpgradedConnection"),e.log("successfully upgraded outbound connection"),this._createConnection({cryptoProtocol:c,direction:"outbound",maConn:e,upgradedConn:a,muxerFactory:u,remotePeer:o,transient:r?.transient})}_createConnection(e){let{cryptoProtocol:r,direction:n,maConn:i,upgradedConn:s,remotePeer:o,muxerFactory:a,transient:c}=e,u,l,f;a!=null&&(u=a.createStreamMuxer({direction:n,onIncomingStream:d=>{f!=null&&Promise.resolve().then(async()=>{let m=this.components.registrar.getProtocols(),{stream:y,protocol:g}=await is(d,m,{log:d.log,yieldBytes:!1});if(f==null)return;f.log("incoming stream opened on %s",g);let x=Sv(g,this.components.registrar);if(Hm(g,"inbound",f)===x){let I=new S(`Too many inbound protocol streams for protocol "${g}" - limit ${x}`,F.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS);throw d.abort(I),I}d.source=y.source,d.sink=y.sink,d.protocol=g,y.closeWrite!=null&&(d.closeWrite=y.closeWrite),y.closeRead!=null&&(d.closeRead=y.closeRead),y.close!=null&&(d.close=y.close),await this.components.peerStore.merge(o,{protocols:[g]}),this.components.metrics?.trackProtocolStream(d,f),this._onStream({connection:f,stream:d,protocol:g})}).catch(async m=>{f.log.error("error handling incoming stream id %s",d.id,m.message,m.code,m.stack),d.timeline.close==null&&await d.close()})}}),l=async(d,m={})=>{if(u==null)throw new S("Stream is not multiplexed",F.ERR_MUXER_UNAVAILABLE);f.log("starting new stream for protocols %s",d);let y=await u.newStream();f.log.trace("started new stream %s for protocols %s",y.id,d);try{if(m.signal==null){y.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",d);let v=AbortSignal.timeout(_v);pt(1/0,v),m={...m,signal:v}}y.log.trace("selecting protocol from protocols %s",d);let{stream:g,protocol:x}=await ns(y,d,{...m,log:y.log,yieldBytes:!0});y.log("selected protocol %s",x);let b=Av(x,this.components.registrar,m);if(Hm(x,"outbound",f)>=b){let v=new S(`Too many outbound protocol streams for protocol "${x}" - limit ${b}`,F.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);throw y.abort(v),v}return await this.components.peerStore.merge(o,{protocols:[x]}),y.source=g.source,y.sink=g.sink,y.protocol=x,g.closeWrite!=null&&(y.closeWrite=g.closeWrite),g.closeRead!=null&&(y.closeRead=g.closeRead),g.close!=null&&(y.close=g.close),this.components.metrics?.trackProtocolStream(y,f),y}catch(g){throw f.log.error("could not create new stream for protocols %s",d,g),y.timeline.close==null&&y.abort(g),g.code!=null?g:new S(String(g),F.ERR_UNSUPPORTED_PROTOCOL)}},Promise.all([u.sink(s.source),s.sink(u.source)]).catch(d=>{f.log.error("error piping data through muxer",d)}));let h=i.timeline;i.timeline=new Proxy(h,{set:(...d)=>(f!=null&&d[1]==="close"&&d[2]!=null&&h.close==null&&(async()=>{try{f.status==="open"&&await f.close()}catch(m){f.log.error("error closing connection after timeline close",m)}finally{this.events.safeDispatchEvent("connection:close",{detail:f})}})().catch(m=>{f.log.error("error thrown while dispatching connection:close event",m)}),Reflect.set(...d))}),i.timeline.upgraded=Date.now();let p=()=>{throw new S("connection is not multiplexed",F.ERR_CONNECTION_NOT_MULTIPLEXED)};return f=zm({remoteAddr:i.remoteAddr,remotePeer:o,status:"open",direction:n,timeline:i.timeline,multiplexer:u?.protocol,encryption:r,transient:c,logger:this.components.logger,newStream:l??p,getStreams:()=>u!=null?u.streams:[],close:async d=>{u!=null&&(f.log.trace("close muxer"),await u.close(d)),f.log.trace("close maconn"),await i.close(d),f.log.trace("closed maconn")},abort:d=>{i.abort(d),u?.abort(d)}}),this.events.safeDispatchEvent("connection:open",{detail:f}),f}_onStream(e){let{connection:r,stream:n,protocol:i}=e,{handler:s,options:o}=this.components.registrar.getHandler(i);if(r.transient&&o.runOnTransientConnection!==!0)throw new S("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");s({connection:r,stream:n})}async _encryptInbound(e){let r=Array.from(this.connectionEncryption.keys());e.log("handling inbound crypto protocol selection",r);try{let{stream:n,protocol:i}=await is(e,r,{log:e.log}),s=this.connectionEncryption.get(i);if(s==null)throw new Error(`no crypto module found for ${i}`);return e.log("encrypting inbound connection using",i),{...await s.secureInbound(this.components.peerId,n),protocol:i}}catch(n){throw new S(String(n),F.ERR_ENCRYPTION_FAILED)}}async _encryptOutbound(e,r){let n=Array.from(this.connectionEncryption.keys());e.log("selecting outbound crypto protocol",n);try{e.log.trace("selecting encrypter from %s",n);let{stream:i,protocol:s}=await ns(e,n,{log:e.log,yieldBytes:!0}),o=this.connectionEncryption.get(s);if(o==null)throw new Error(`no crypto module found for ${s}`);return e.log("encrypting outbound connection to %p using %p",r),{...await o.secureOutbound(this.components.peerId,i,r),protocol:s}}catch(i){throw new S(String(i),F.ERR_ENCRYPTION_FAILED)}}async _multiplexOutbound(e,r){let n=Array.from(r.keys());e.log("outbound selecting muxer %s",n);try{e.log.trace("selecting stream muxer from %s",n);let{stream:i,protocol:s}=await ns(e,n,{log:e.log,yieldBytes:!0});e.log("selected %s as muxer protocol",s);let o=r.get(s);return{stream:i,muxerFactory:o}}catch(i){throw e.log.error("error multiplexing outbound connection",i),new S(String(i),F.ERR_MUXER_UNAVAILABLE)}}async _multiplexInbound(e,r){let n=Array.from(r.keys());e.log("inbound handling muxers %s",n);try{let{stream:i,protocol:s}=await is(e,n,{log:e.log}),o=r.get(s);return{stream:i,muxerFactory:o}}catch(i){throw e.log.error("error multiplexing inbound connection",i),new S(String(i),F.ERR_MUXER_UNAVAILABLE)}}};var Gm="1.0.5-bcfa15993",Wm="libp2p";var Vl=class extends wi{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let r=new wi,n=r.dispatchEvent.bind(r);r.dispatchEvent=a=>{let c=n(a),u=this.dispatchEvent(new Ka(a.type,{detail:a.detail}));return c||u},pt(1/0,r),this.peerId=e.peerId,this.logger=e.logger??Qs(),this.log=this.logger.forComponent("libp2p"),this.services={};let i=this.components=Jd({peerId:e.peerId,nodeInfo:e.nodeInfo??{name:Wm,version:Gm},logger:this.logger,events:r,datastore:e.datastore??new So,connectionGater:up(e.connectionGater)});this.peerStore=this.configureComponent("peerStore",new Eo(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",a=>{if(a.detail.previous==null){let c={id:a.detail.peer.id,multiaddrs:a.detail.peer.addresses.map(u=>u.multiaddr)};i.events.safeDispatchEvent("peer:discovery",{detail:c})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new fa(this.components,{connectionEncryption:(e.connectionEncryption??[]).map((a,c)=>this.configureComponent(`connection-encryption-${c}`,a(this.components))),muxers:(e.streamMuxers??[]).map((a,c)=>this.configureComponent(`stream-muxers-${c}`,a(this.components))),inboundUpgradeTimeout:e.connectionManager.inboundUpgradeTimeout}),this.configureComponent("transportManager",new ia(this.components,e.transportManager)),this.configureComponent("connectionManager",new Xo(this.components,e.connectionManager)),this.configureComponent("registrar",new na(this.components)),this.configureComponent("addressManager",new Ao(this.components,e.addresses));let s=(e.peerRouters??[]).map((a,c)=>this.configureComponent(`peer-router-${c}`,a(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new ra(this.components,{routers:s}));let o=(e.contentRouters??[]).map((a,c)=>this.configureComponent(`content-router-${c}`,a(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new ta(this.components,{routers:o})),(e.peerDiscovery??[]).forEach((a,c)=>{this.configureComponent(`peer-discovery-${c}`,a(this.components)).addEventListener("peer",l=>{this.#e(l)})}),e.transports.forEach((a,c)=>{this.components.transportManager.add(this.configureComponent(`transport-${c}`,a(this.components)))}),e.services!=null)for(let a of Object.keys(e.services)){let c=e.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[ka]!=null&&(this.log("registering service %s for content routing",a),o.push(u[ka])),u[Ua]!=null&&(this.log("registering service %s for peer routing",a),s.push(u[Ua])),u[Oa]!=null&&(this.log("registering service %s for peer discovery",a),u[Oa].addEventListener("peer",l=>{this.#e(l)}))}}configureComponent(e,r){return r==null&&this.log.error("component %s was null or undefined",e),this.components[e]=r,r}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 fn;for(let r of this.components.connectionManager.getConnections())e.add(r.remotePeer);return Array.from(e)}async dial(e,r={}){return this.components.connectionManager.openConnection(e,r)}async dialProtocol(e,r,n={}){if(r==null)throw new S("no protocols were provided to open a stream",F.ERR_INVALID_PROTOCOLS_FOR_STREAM);if(r=Array.isArray(r)?r:[r],r.length===0)throw new S("no protocols were provided to open a stream",F.ERR_INVALID_PROTOCOLS_FOR_STREAM);return(await this.dial(e,n)).newStream(r,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,r={}){Nr(e)&&(e=ce(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e,r)}async getPublicKey(e,r={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;let n=await this.peerStore.get(e);if(n.id.publicKey!=null)return n.id.publicKey;let i=Te([Q("/pk/"),e.multihash.digest]),s=await this.contentRouting.get(i,r);return Mi(s),await this.peerStore.patch(e,{publicKey:s}),s}async handle(e,r,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async i=>{await this.components.registrar.handle(i,r,n)}))}async unhandle(e){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async r=>{await this.components.registrar.unhandle(r)}))}async register(e,r){return this.components.registrar.register(e,r)}unregister(e){this.components.registrar.unregister(e)}#e(e){let{detail:r}=e;if(r.id.toString()===this.peerId.toString()){this.log.error(new Error(F.ERR_DISCOVERED_SELF));return}this.components.peerStore.merge(r.id,{multiaddrs:r.multiaddrs}).catch(n=>{this.log.error(n)})}};async function Ym(t){return t.peerId??=await id(),new Vl(Np(t))}async function Rv(t){let e=await Ym(t);return t.start!==!1&&await e.start(),e}return cy(Cv);})();
62
62
  /*! Bundled license information:
63
63
 
64
64
  @noble/hashes/esm/utils.js:
@@ -40,6 +40,7 @@ export declare class AutoDial implements Startable {
40
40
  afterStart(): void;
41
41
  stop(): void;
42
42
  autoDial(): Promise<void>;
43
+ private sheduleNextAutodial;
43
44
  }
44
45
  export {};
45
46
  //# sourceMappingURL=auto-dial.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"auto-dial.d.ts","sourceRoot":"","sources":["../../../src/connection-manager/auto-dial.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,YAAY,EAAU,eAAe,EAAE,gBAAgB,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAA;AACtH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,4BAA4B,CAAA;AAEnE,UAAU,YAAY;IACpB,cAAc,CAAC,EAAE,MAAM,CAAA;IACvB,cAAc,CAAC,EAAE,MAAM,CAAA;IACvB,mBAAmB,CAAC,EAAE,MAAM,CAAA;IAC5B,gBAAgB,CAAC,EAAE,MAAM,CAAA;IACzB,gBAAgB,CAAC,EAAE,MAAM,CAAA;IACzB,0BAA0B,CAAC,EAAE,MAAM,CAAA;IACnC,+BAA+B,CAAC,EAAE,MAAM,CAAA;CACzC;AAED,UAAU,kBAAkB;IAC1B,iBAAiB,EAAE,iBAAiB,CAAA;IACpC,SAAS,EAAE,SAAS,CAAA;IACpB,MAAM,EAAE,gBAAgB,CAAC,YAAY,CAAC,CAAA;IACtC,MAAM,EAAE,eAAe,CAAA;CACxB;AAYD,qBAAa,QAAS,YAAW,SAAS;IACxC,OAAO,CAAC,QAAQ,CAA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EAAE,MAAM,CAAA;IACnC,+BAA+B,CAAC,EAAE,MAAM,CAAA;CACzC;AAED,UAAU,kBAAkB;IAC1B,iBAAiB,EAAE,iBAAiB,CAAA;IACpC,SAAS,EAAE,SAAS,CAAA;IACpB,MAAM,EAAE,gBAAgB,CAAC,YAAY,CAAC,CAAA;IACtC,MAAM,EAAE,eAAe,CAAA;CACxB;AAYD,qBAAa,QAAS,YAAW,SAAS;IACxC,OAAO,CAAC,QAAQ,CAAC,iBAAiB,CAAmB;IACrD,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAW;IACrC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAc;IACpC,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAQ;IACvC,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAAQ;IACzC,OAAO,CAAC,QAAQ,CAAC,kBAAkB,CAAQ;IAC3C,OAAO,CAAC,QAAQ,CAAC,sBAAsB,CAAQ;IAC/C,OAAO,CAAC,QAAQ,CAAC,4BAA4B,CAAQ;IACrD,OAAO,CAAC,QAAQ,CAAC,+BAA+B,CAAQ;IACxD,OAAO,CAAC,gBAAgB,CAAC,CAAgC;IACzD,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAQ;IAE5B;;;;OAIG;gBACU,UAAU,EAAE,kBAAkB,EAAE,IAAI,EAAE,YAAY;IA4C/D,SAAS,IAAK,OAAO;IAIrB,KAAK,IAAK,IAAI;IAId,UAAU,IAAK,IAAI;IAOnB,IAAI,IAAK,IAAI;IAQP,QAAQ,IAAK,OAAO,CAAC,IAAI,CAAC;IAoJhC,OAAO,CAAC,mBAAmB;CAY5B"}
@@ -74,12 +74,6 @@ export class AutoDial {
74
74
  return this.started;
75
75
  }
76
76
  start() {
77
- this.autoDialInterval = setTimeout(() => {
78
- this.autoDial()
79
- .catch(err => {
80
- this.log.error('error while autodialing', err);
81
- });
82
- }, this.autoDialIntervalMs);
83
77
  this.started = true;
84
78
  }
85
79
  afterStart() {
@@ -96,24 +90,23 @@ export class AutoDial {
96
90
  this.running = false;
97
91
  }
98
92
  async autoDial() {
99
- if (!this.started) {
93
+ if (!this.started || this.running) {
100
94
  return;
101
95
  }
102
96
  const connections = this.connectionManager.getConnectionsMap();
103
97
  const numConnections = connections.size;
104
- // Already has enough connections
98
+ // already have enough connections
105
99
  if (numConnections >= this.minConnections) {
106
100
  if (this.minConnections > 0) {
107
101
  this.log.trace('have enough connections %d/%d', numConnections, this.minConnections);
108
102
  }
103
+ // no need to schedule next autodial as it will be run when on
104
+ // connection:close event
109
105
  return;
110
106
  }
111
107
  if (this.queue.size > this.autoDialMaxQueueLength) {
112
108
  this.log('not enough connections %d/%d but auto dial queue is full', numConnections, this.minConnections);
113
- return;
114
- }
115
- if (this.running) {
116
- this.log('not enough connections %d/%d - but skipping autodial as it is already running', numConnections, this.minConnections);
109
+ this.sheduleNextAutodial();
117
110
  return;
118
111
  }
119
112
  this.running = true;
@@ -123,12 +116,12 @@ export class AutoDial {
123
116
  this.connectionManager.getDialQueue()
124
117
  .map(queue => queue.peerId)
125
118
  .filter(Boolean));
126
- // Sort peers on whether we know protocols or public keys for them
119
+ // sort peers on whether we know protocols or public keys for them
127
120
  const peers = await this.peerStore.all({
128
121
  filters: [
129
- // Remove some peers
122
+ // remove some peers
130
123
  (peer) => {
131
- // Remove peers without addresses
124
+ // remove peers without addresses
132
125
  if (peer.addresses.length === 0) {
133
126
  this.log.trace('not autodialing %p because they have no addresses', peer.id);
134
127
  return false;
@@ -155,7 +148,7 @@ export class AutoDial {
155
148
  // shuffle the peers - this is so peers with the same tag values will be
156
149
  // dialled in a different order each time
157
150
  const shuffledPeers = peers.sort(() => Math.random() > 0.5 ? 1 : -1);
158
- // Sort shuffled peers by tag value
151
+ // sort shuffled peers by tag value
159
152
  const peerValues = new PeerMap();
160
153
  for (const peer of shuffledPeers) {
161
154
  if (peerValues.has(peer.id)) {
@@ -211,14 +204,18 @@ export class AutoDial {
211
204
  });
212
205
  }
213
206
  this.running = false;
214
- if (this.started) {
215
- this.autoDialInterval = setTimeout(() => {
216
- this.autoDial()
217
- .catch(err => {
218
- this.log.error('error while autodialing', err);
219
- });
220
- }, this.autoDialIntervalMs);
207
+ this.sheduleNextAutodial();
208
+ }
209
+ sheduleNextAutodial() {
210
+ if (!this.started) {
211
+ return;
221
212
  }
213
+ this.autoDialInterval = setTimeout(() => {
214
+ this.autoDial()
215
+ .catch(err => {
216
+ this.log.error('error while autodialing', err);
217
+ });
218
+ }, this.autoDialIntervalMs);
222
219
  }
223
220
  }
224
221
  //# sourceMappingURL=auto-dial.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"auto-dial.js","sourceRoot":"","sources":["../../../src/connection-manager/auto-dial.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,0BAA0B,CAAA;AAC3D,OAAO,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAA;AAC3D,OAAO,EAAE,QAAQ,IAAI,kBAAkB,EAAE,MAAM,uBAAuB,CAAA;AACtE,OAAO,EAAE,qBAAqB,EAAE,mCAAmC,EAAE,kBAAkB,EAAE,0BAA0B,EAAE,8BAA8B,EAAE,kBAAkB,EAAE,qBAAqB,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAA;AAqBvO,MAAM,cAAc,GAAG;IACrB,cAAc,EAAE,eAAe;IAC/B,cAAc,EAAE,0BAA0B;IAC1C,mBAAmB,EAAE,qBAAqB;IAC1C,gBAAgB,EAAE,kBAAkB;IACpC,gBAAgB,EAAE,kBAAkB;IACpC,0BAA0B,EAAE,8BAA8B;IAC1D,+BAA+B,EAAE,mCAAmC;CACrE,CAAA;AAED,MAAM,OAAO,QAAQ;IACF,iBAAiB,CAAmB;IACpC,SAAS,CAAW;IACpB,KAAK,CAAc;IACnB,cAAc,CAAQ;IACtB,gBAAgB,CAAQ;IACxB,kBAAkB,CAAQ;IAC1B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iBAChC,CAAC,CAAA;YACJ,CAAC,EAAE;gBACD,MAAM,EAAE,IAAI,CAAC,EAAE;aAChB,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE;gBACb,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,4CAA4C,EAAE,GAAG,CAAC,CAAA;YACnE,CAAC,CAAC,CAAA;QACJ,CAAC;QAED,IAAI,CAAC,OAAO,GAAG,KAAK,CAAA;QACpB,IAAI,CAAC,mBAAmB,EAAE,CAAA;IAC5B,CAAC;IAEO,mBAAmB;QACzB,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;YAClB,OAAM;QACR,CAAC;QAED,IAAI,CAAC,gBAAgB,GAAG,UAAU,CAAC,GAAG,EAAE;YACtC,IAAI,CAAC,QAAQ,EAAE;iBACZ,KAAK,CAAC,GAAG,CAAC,EAAE;gBACX,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,yBAAyB,EAAE,GAAG,CAAC,CAAA;YAChD,CAAC,CAAC,CAAA;QACN,CAAC,EAAE,IAAI,CAAC,kBAAkB,CAAC,CAAA;IAC7B,CAAC;CACF"}
@@ -1,3 +1,3 @@
1
- export declare const version = "1.0.5-10ea19700";
1
+ export declare const version = "1.0.5-bcfa15993";
2
2
  export declare const name = "libp2p";
3
3
  //# sourceMappingURL=version.d.ts.map
@@ -1,3 +1,3 @@
1
- export const version = '1.0.5-10ea19700';
1
+ export const version = '1.0.5-bcfa15993';
2
2
  export const name = 'libp2p';
3
3
  //# sourceMappingURL=version.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "libp2p",
3
- "version": "1.0.5-10ea19700",
3
+ "version": "1.0.5-bcfa15993",
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",
@@ -84,16 +84,16 @@
84
84
  "test:webkit": "aegir test -t browser -f \"./dist/test/**/*.spec.js\" -- --browser webkit"
85
85
  },
86
86
  "dependencies": {
87
- "@libp2p/crypto": "3.0.1-10ea19700",
88
- "@libp2p/interface": "1.0.1-10ea19700",
89
- "@libp2p/interface-internal": "1.0.1-10ea19700",
90
- "@libp2p/logger": "4.0.1-10ea19700",
91
- "@libp2p/multistream-select": "5.0.0-10ea19700",
92
- "@libp2p/peer-collections": "5.0.0-10ea19700",
93
- "@libp2p/peer-id": "4.0.1-10ea19700",
94
- "@libp2p/peer-id-factory": "4.0.0-10ea19700",
95
- "@libp2p/peer-store": "10.0.0-10ea19700",
96
- "@libp2p/utils": "5.0.2-10ea19700",
87
+ "@libp2p/crypto": "3.0.1-bcfa15993",
88
+ "@libp2p/interface": "1.0.1-bcfa15993",
89
+ "@libp2p/interface-internal": "1.0.1-bcfa15993",
90
+ "@libp2p/logger": "4.0.1-bcfa15993",
91
+ "@libp2p/multistream-select": "5.0.0-bcfa15993",
92
+ "@libp2p/peer-collections": "5.0.0-bcfa15993",
93
+ "@libp2p/peer-id": "4.0.1-bcfa15993",
94
+ "@libp2p/peer-id-factory": "4.0.0-bcfa15993",
95
+ "@libp2p/peer-store": "10.0.0-bcfa15993",
96
+ "@libp2p/utils": "5.0.2-bcfa15993",
97
97
  "@multiformats/mafmt": "^12.1.6",
98
98
  "@multiformats/multiaddr": "^12.1.10",
99
99
  "@multiformats/multiaddr-matcher": "^1.1.0",
@@ -121,16 +121,16 @@
121
121
  "devDependencies": {
122
122
  "@chainsafe/libp2p-noise": "^14.0.0",
123
123
  "@chainsafe/libp2p-yamux": "^6.0.1",
124
- "@libp2p/bootstrap": "10.0.4-10ea19700",
125
- "@libp2p/circuit-relay-v2": "1.0.4-10ea19700",
126
- "@libp2p/identify": "1.0.3-10ea19700",
127
- "@libp2p/interface-compliance-tests": "5.0.4-10ea19700",
128
- "@libp2p/kad-dht": "11.0.4-10ea19700",
129
- "@libp2p/mdns": "10.0.4-10ea19700",
130
- "@libp2p/mplex": "10.0.4-10ea19700",
131
- "@libp2p/plaintext": "1.0.4-10ea19700",
132
- "@libp2p/tcp": "9.0.4-10ea19700",
133
- "@libp2p/websockets": "8.0.4-10ea19700",
124
+ "@libp2p/bootstrap": "10.0.4-bcfa15993",
125
+ "@libp2p/circuit-relay-v2": "1.0.4-bcfa15993",
126
+ "@libp2p/identify": "1.0.3-bcfa15993",
127
+ "@libp2p/interface-compliance-tests": "5.0.4-bcfa15993",
128
+ "@libp2p/kad-dht": "11.0.4-bcfa15993",
129
+ "@libp2p/mdns": "10.0.4-bcfa15993",
130
+ "@libp2p/mplex": "10.0.4-bcfa15993",
131
+ "@libp2p/plaintext": "1.0.4-bcfa15993",
132
+ "@libp2p/tcp": "9.0.4-bcfa15993",
133
+ "@libp2p/websockets": "8.0.4-bcfa15993",
134
134
  "aegir": "^41.0.2",
135
135
  "it-pushable": "^3.2.1",
136
136
  "p-event": "^6.0.0",
@@ -101,12 +101,6 @@ export class AutoDial implements Startable {
101
101
  }
102
102
 
103
103
  start (): void {
104
- this.autoDialInterval = setTimeout(() => {
105
- this.autoDial()
106
- .catch(err => {
107
- this.log.error('error while autodialing', err)
108
- })
109
- }, this.autoDialIntervalMs)
110
104
  this.started = true
111
105
  }
112
106
 
@@ -126,28 +120,27 @@ export class AutoDial implements Startable {
126
120
  }
127
121
 
128
122
  async autoDial (): Promise<void> {
129
- if (!this.started) {
123
+ if (!this.started || this.running) {
130
124
  return
131
125
  }
132
126
 
133
127
  const connections = this.connectionManager.getConnectionsMap()
134
128
  const numConnections = connections.size
135
129
 
136
- // Already has enough connections
130
+ // already have enough connections
137
131
  if (numConnections >= this.minConnections) {
138
132
  if (this.minConnections > 0) {
139
133
  this.log.trace('have enough connections %d/%d', numConnections, this.minConnections)
140
134
  }
135
+
136
+ // no need to schedule next autodial as it will be run when on
137
+ // connection:close event
141
138
  return
142
139
  }
143
140
 
144
141
  if (this.queue.size > this.autoDialMaxQueueLength) {
145
142
  this.log('not enough connections %d/%d but auto dial queue is full', numConnections, this.minConnections)
146
- return
147
- }
148
-
149
- if (this.running) {
150
- this.log('not enough connections %d/%d - but skipping autodial as it is already running', numConnections, this.minConnections)
143
+ this.sheduleNextAutodial()
151
144
  return
152
145
  }
153
146
 
@@ -162,12 +155,12 @@ export class AutoDial implements Startable {
162
155
  .filter(Boolean)
163
156
  )
164
157
 
165
- // Sort peers on whether we know protocols or public keys for them
158
+ // sort peers on whether we know protocols or public keys for them
166
159
  const peers = await this.peerStore.all({
167
160
  filters: [
168
- // Remove some peers
161
+ // remove some peers
169
162
  (peer) => {
170
- // Remove peers without addresses
163
+ // remove peers without addresses
171
164
  if (peer.addresses.length === 0) {
172
165
  this.log.trace('not autodialing %p because they have no addresses', peer.id)
173
166
  return false
@@ -200,7 +193,7 @@ export class AutoDial implements Startable {
200
193
  // dialled in a different order each time
201
194
  const shuffledPeers = peers.sort(() => Math.random() > 0.5 ? 1 : -1)
202
195
 
203
- // Sort shuffled peers by tag value
196
+ // sort shuffled peers by tag value
204
197
  const peerValues = new PeerMap<number>()
205
198
  for (const peer of shuffledPeers) {
206
199
  if (peerValues.has(peer.id)) {
@@ -271,14 +264,19 @@ export class AutoDial implements Startable {
271
264
  }
272
265
 
273
266
  this.running = false
267
+ this.sheduleNextAutodial()
268
+ }
274
269
 
275
- if (this.started) {
276
- this.autoDialInterval = setTimeout(() => {
277
- this.autoDial()
278
- .catch(err => {
279
- this.log.error('error while autodialing', err)
280
- })
281
- }, this.autoDialIntervalMs)
270
+ private sheduleNextAutodial (): void {
271
+ if (!this.started) {
272
+ return
282
273
  }
274
+
275
+ this.autoDialInterval = setTimeout(() => {
276
+ this.autoDial()
277
+ .catch(err => {
278
+ this.log.error('error while autodialing', err)
279
+ })
280
+ }, this.autoDialIntervalMs)
283
281
  }
284
282
  }
package/src/version.ts CHANGED
@@ -1,2 +1,2 @@
1
- export const version = '1.0.5-10ea19700'
1
+ export const version = '1.0.5-bcfa15993'
2
2
  export const name = 'libp2p'