libp2p 0.45.9-daeb43d8 → 0.45.9-e9cafd3d
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 +2 -2
- package/dist/src/connection/index.d.ts +12 -7
- package/dist/src/connection/index.d.ts.map +1 -1
- package/dist/src/connection/index.js +19 -17
- package/dist/src/connection/index.js.map +1 -1
- package/dist/src/connection-manager/connection-pruner.js +2 -2
- package/dist/src/connection-manager/connection-pruner.js.map +1 -1
- package/dist/src/connection-manager/index.js +3 -3
- package/dist/src/connection-manager/index.js.map +1 -1
- package/dist/src/identify/identify.d.ts +4 -4
- package/dist/src/identify/identify.d.ts.map +1 -1
- package/dist/src/identify/identify.js +10 -6
- package/dist/src/identify/identify.js.map +1 -1
- package/dist/src/identify/index.d.ts +18 -3
- package/dist/src/identify/index.d.ts.map +1 -1
- package/dist/src/identify/index.js.map +1 -1
- package/dist/src/upgrader.d.ts.map +1 -1
- package/dist/src/upgrader.js +11 -13
- package/dist/src/upgrader.js.map +1 -1
- package/dist/src/version.d.ts +1 -1
- package/dist/src/version.js +1 -1
- package/package.json +26 -26
- package/src/connection/index.ts +27 -20
- package/src/connection-manager/connection-pruner.ts +2 -2
- package/src/connection-manager/index.ts +3 -3
- package/src/identify/identify.ts +14 -9
- package/src/identify/index.ts +21 -2
- package/src/upgrader.ts +11 -13
- package/src/version.ts +1 -1
package/dist/index.min.js
CHANGED
|
@@ -45,8 +45,8 @@
|
|
|
45
45
|
(?:${Me}:){1}(?:(?::${Me}){0,4}:${Kt}|(?::${Me}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4
|
|
46
46
|
(?::(?:(?::${Me}){0,5}:${Kt}|(?::${Me}){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(),_I=new RegExp(`(?:^${Kt}$)|(?:^${Na}$)`),SI=new RegExp(`^${Kt}$`),AI=new RegExp(`^${Na}$`),Lf=t=>t&&t.exact?_I:new RegExp(`(?:${Qr(t)}${Kt}${Qr(t)})|(?:${Qr(t)}${Na}${Qr(t)})`,"g");Lf.v4=t=>t&&t.exact?SI:new RegExp(`${Qr(t)}${Kt}${Qr(t)}`,"g");Lf.v6=t=>t&&t.exact?AI:new RegExp(`${Qr(t)}${Na}${Qr(t)}`,"g");var Bg=Lf;var kg=z(Pg(),1),{isValid:II,parse:RI}=kg.default,CI=["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"],TI=CI.map(t=>new Ng.Netmask(t));function BI(t){for(let e of TI)if(e.contains(t))return!0;return!1}function Dg(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 Og=t=>{if(II(t)){let e=RI(t);if(e.kind()==="ipv4")return BI(e.toNormalizedString());if(e.kind()==="ipv6")return Dg(t)}else if(Ii(t)&&Bg.v6().test(t))return Dg(t)};var Oa=Og;function Mg(t={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let r=e.stringTuples();return r[0][0]===4||r[0][0]===41?!!Oa(`${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 eD=Symbol.for("@libp2p/transport");var Xr;(function(t){t[t.FATAL_ALL=0]="FATAL_ALL",t[t.NO_FATAL=1]="NO_FATAL"})(Xr||(Xr={}));function Pf(t){try{let{address:e}=t.nodeAddress();return!!Oa(e)}catch{return!0}}function Di(t,e){let r=Pf(t.multiaddr),n=Pf(e.multiaddr);return r&&!n?1:!r&&n||t.isCertified&&!e.isCertified?-1:!t.isCertified&&e.isCertified?1:0}var Nf=z(al(),1),kf=z(Kg(),1);var Vg=globalThis.fetch,qg=globalThis.Headers,aD=globalThis.Request,cD=globalThis.Response;function Ma(t,e,r){return`${t}?name=${e}&type=${r}`}async function zg(t,e){return await(await Vg(t,{headers:new qg({accept:"application/dns-json"}),signal:e})).json()}function Bn(t,e){return`${e}_${t}`}var Df=Object.assign((0,Nf.default)("dns-over-http-resolver"),{error:(0,Nf.default)("dns-over-http-resolver:error")}),Of=class{constructor(e={}){this._cache=new kf.default({max:e?.maxCache??100}),this._TXTcache=new kf.default({max:e?.maxCache??100}),this._servers=["https://cloudflare-dns.com/dns-query","https://dns.google/resolve"],this._request=e.request??zg,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 await this.resolve4(e);case"AAAA":return await this.resolve6(e);case"TXT":return await this.resolveTxt(e);default:throw new Error(`${r} is not supported`)}}async resolve4(e){let r="A",n=this._cache.get(Bn(e,r));if(n!=null)return n;let i=!1;for(let o of this._getShuffledServers()){let s=new AbortController;this._abortControllers.push(s);try{let a=await this._request(Ma(o,e,r),s.signal),c=a.Answer.map(l=>l.data),u=Math.min(...a.Answer.map(l=>l.TTL));return this._cache.set(Bn(e,r),c,{ttl:u}),c}catch{s.signal.aborted&&(i=!0),Df.error(`${o} could not resolve ${e} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==s)}}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(Bn(e,r));if(n!=null)return n;let i=!1;for(let o of this._getShuffledServers()){let s=new AbortController;this._abortControllers.push(s);try{let a=await this._request(Ma(o,e,r),s.signal),c=a.Answer.map(l=>l.data),u=Math.min(...a.Answer.map(l=>l.TTL));return this._cache.set(Bn(e,r),c,{ttl:u}),c}catch{s.signal.aborted&&(i=!0),Df.error(`${o} could not resolve ${e} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==s)}}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(Bn(e,r));if(n!=null)return n;let i=!1;for(let o of this._getShuffledServers()){let s=new AbortController;this._abortControllers.push(s);try{let a=await this._request(Ma(o,e,r),s.signal),c=a.Answer.map(l=>[l.data.replace(/['"]+/g,"")]),u=Math.min(...a.Answer.map(l=>l.TTL));return this._TXTcache.set(Bn(e,r),c,{ttl:u}),c}catch{s.signal.aborted&&(i=!0),Df.error(`${o} could not resolve ${e} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==s)}}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()}},$g=Of;var Hg=$g;var{code:kI}=le("dnsaddr");async function Ni(t,e={}){let r=new Hg;e.signal!=null&&e.signal.addEventListener("abort",()=>{r.cancel()});let n=t.getPeerId(),[,i]=t.stringTuples().find(([a])=>a===kI)??[];if(i==null)throw new Error("No hostname found in multiaddr");let s=(await r.resolveTxt(`_dnsaddr.${i}`)).flat().map(a=>a.split("=")[1]).filter(Boolean);return n!=null&&(s=s.filter(a=>a.includes(n))),s}var or;(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"})(or||(or={}));var N;(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_TIMEOUT="ERR_TIMEOUT",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_KEYCHAIN_REQUIRED="ERR_KEYCHAIN_REQUIRED",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"})(N||(N={}));var OI={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:t=>t},connectionManager:{resolvers:{dnsaddr:Ni},addressSorter:Di},transportManager:{faultTolerance:Xr.FATAL_ALL}};function Gg(t){let e=qr(OI,t);if(e.transports==null||e.transports.length<1)throw new v(or.ERR_TRANSPORTS_REQUIRED,N.ERR_TRANSPORTS_REQUIRED);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new v(or.ERR_PROTECTOR_REQUIRED,N.ERR_PROTECTOR_REQUIRED);return e}var Yg="keep-alive";var G1=z(q1(),1);var xR=W("libp2p:get-peer");function Fa(t){if(Zs(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:oe(r),t.forEach(n=>{if(!Rn(n))throw xR.error("multiaddr %s was invalid",n),new v("Invalid Multiaddr",N.ERR_INVALID_MULTIADDR);let i=n.getPeerId();if(i==null){if(e!=null)throw new v("Multiaddrs must all have the same peer id or have no peer id",N.ERR_INVALID_PARAMETERS)}else{let o=oe(i);if(e==null||!e.equals(o))throw new v("Multiaddrs must all have the same peer id or have no peer id",N.ERR_INVALID_PARAMETERS)}})}return{peerId:e,multiaddrs:t}}function wR(t,e,r){let n=0,i=t.length;for(;i>0;){let o=Math.trunc(i/2),s=n+o;r(t[s],e)<=0?(n=++s,i-=o+1):i=o}return n}var Xf=class{#e=[];enqueue(e,r){let n=r?.peerId,i=r?.priority??0;if(n==null)throw new v("missing peer id",N.ERR_INVALID_PARAMETERS);let o={priority:i,peerId:n,run:e};if(this.size>0&&this.#e[this.size-1].priority>=i){this.#e.push(o);return}let s=wR(this.#e,o,(a,c)=>c.priority-a.priority);this.#e.splice(s,0,o)}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}},Ka=class extends Ut{constructor(e={}){super({...e,queueClass:Xf})}hasJob(e){return this.sizeBy({peerId:e})>0}};var Xe=W("libp2p:connection-manager:auto-dial"),Yo={minConnections:50,maxQueueLength:100,autoDialConcurrency:25,autoDialPriority:0,autoDialInterval:5e3},Va=class{connectionManager;peerStore;queue;minConnections;autoDialPriority;autoDialIntervalMs;autoDialMaxQueueLength;autoDialInterval;started;running;constructor(e,r){this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.minConnections=r.minConnections??Yo.minConnections,this.autoDialPriority=r.autoDialPriority??Yo.autoDialPriority,this.autoDialIntervalMs=r.autoDialInterval??Yo.autoDialInterval,this.autoDialMaxQueueLength=r.maxQueueLength??Yo.maxQueueLength,this.started=!1,this.running=!1,this.queue=new Ka({concurrency:r.autoDialConcurrency??Yo.autoDialConcurrency}),this.queue.addListener("error",n=>{Xe.error("error during auto-dial",n)}),e.events.addEventListener("connection:close",()=>{this.autoDial().catch(n=>{Xe.error(n)})})}isStarted(){return this.started}start(){this.autoDialInterval=setTimeout(()=>{this.autoDial().catch(e=>{Xe.error("error while autodialing",e)})},this.autoDialIntervalMs),this.started=!0}afterStart(){this.autoDial().catch(e=>{Xe.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){Xe.trace("have enough connections %d/%d",r,this.minConnections);return}if(this.queue.size>this.autoDialMaxQueueLength){Xe("not enough connections %d/%d but auto dial queue is full",r,this.minConnections);return}if(this.running){Xe("not enough connections %d/%d - but skipping autodial as it is already running",r,this.minConnections);return}this.running=!0,Xe("not enough connections %d/%d - will dial peers to increase the number of connections",r,this.minConnections);let n=new kt(this.connectionManager.getDialQueue().map(c=>c.peerId).filter(Boolean)),i=await this.peerStore.all({filters:[c=>c.addresses.length===0?(Xe.trace("not autodialing %p because they have no addresses"),!1):e.has(c.id)?(Xe.trace("not autodialing %p because they are already connected"),!1):n.has(c.id)?(Xe.trace("not autodialing %p because they are already being dialed"),!1):this.queue.hasJob(c.id)?(Xe.trace("not autodialing %p because they are already being autodialed"),!1):!0]}),o=i.sort(()=>Math.random()>.5?1:-1),s=new Nt;for(let c of o)s.has(c.id)||s.set(c.id,[...c.tags.values()].reduce((u,l)=>u+l.value,0));let a=o.sort((c,u)=>{let l=s.get(c.id)??0,f=s.get(u.id)??0;return l>f?-1:l<f?1:0});Xe("selected %d/%d peers to dial",a.length,i.length);for(let c of a)this.queue.add(async()=>{let u=this.connectionManager.getConnectionsMap().size;if(u>=this.minConnections){Xe("got enough connections now %d/%d",u,this.minConnections),this.queue.clear();return}Xe("connecting to a peerStore stored peer %p",c.id),await this.connectionManager.openConnection(c.id,{priority:this.autoDialPriority})},{peerId:c.id}).catch(u=>{Xe.error("could not connect to peerStore stored peer",u)});this.running=!1,this.started&&(this.autoDialInterval=setTimeout(()=>{this.autoDial().catch(c=>{Xe.error("error while autodialing",c)})},this.autoDialIntervalMs))}};var Fi=W("libp2p:connection-manager:connection-pruner"),z1={maxConnections:300,allow:[]},qa=class{maxConnections;connectionManager;peerStore;allow;events;constructor(e,r={}){this.maxConnections=r.maxConnections??z1.maxConnections,this.allow=r.allow??z1.allow,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,e.events.addEventListener("connection:open",()=>{this.maybePruneConnections().catch(n=>{Fi.error(n)})})}async maybePruneConnections(){let e=this.connectionManager.getConnections(),r=e.length,n=Math.max(r-this.maxConnections,0);if(Fi("checking max connections limit %d/%d",r,this.maxConnections),r<=this.maxConnections)return;Fi("max connections limit exceeded %d/%d, pruning %d connection(s)",r,this.maxConnections,n);let i=new Nt;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"&&Fi.error("error loading peer tags",u)}}}let o=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.stat.timeline.open,d=c.stat.timeline.open;return f<d?1:f>d?-1:0}),s=[];for(let a of o)if(Fi("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(u=>a.remoteAddr.toString().startsWith(u.toString()))||s.push(a),s.length===n)break;await Promise.all(s.map(async a=>{try{await a.close()}catch(c){Fi.error(c)}})),this.events.safeDispatchEvent("connection:prune",{detail:s})}};var ih=z(Hi(),1);function Ki(t){let e=new globalThis.AbortController;function r(){e.abort();for(let o of t)o?.removeEventListener!=null&&o.removeEventListener("abort",r)}for(let o of t){if(o?.aborted===!0){r();break}o?.addEventListener!=null&&o.addEventListener("abort",r)}function n(){for(let o of t)o?.removeEventListener!=null&&o.removeEventListener("abort",r)}let i=e.signal;return i.clear=n,i}function jr(){let t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}var rh=z(Hi(),1);var $1=W("libp2p:connection-manager:utils");async function nh(t,e){if(!t.protoNames().includes("dnsaddr"))return[t];let n=await vR(t,e),s=(await Promise.all(n.map(async a=>nh(a,e)))).flat().reduce((a,c)=>(a.find(u=>u.equals(c))==null&&a.push(c),a),[]);return $1("resolved %s to",t,s.map(a=>a.toString())),s}async function vR(t,e){try{return t=Ue(t.toString()),await t.resolve(e)}catch(r){return $1.error(`multiaddr ${t.toString()} could not be resolved`,r),[]}}function H1(...t){let e=[];for(let n of t)if(n!=null){try{(0,rh.setMaxListeners)?.(1/0,n)}catch{}e.push(n)}let r=Ki(e);try{(0,rh.setMaxListeners)?.(1/0,r)}catch{}return r}var je=W("libp2p:connection-manager:dial-queue"),Wo={addressSorter:Di,maxParallelDials:100,maxPeerAddrsToDial:25,maxParallelDialsPerPeer:10,dialTimeout:3e4,resolvers:{dnsaddr:Ni}},za=class{pendingDials;queue;peerId;peerStore;connectionGater;transportManager;addressSorter;maxPeerAddrsToDial;maxParallelDialsPerPeer;dialTimeout;inProgressDialCount;pendingDialCount;shutDownController;constructor(e,r={}){this.addressSorter=r.addressSorter??Wo.addressSorter,this.maxPeerAddrsToDial=r.maxPeerAddrsToDial??Wo.maxPeerAddrsToDial,this.maxParallelDialsPerPeer=r.maxParallelDialsPerPeer??Wo.maxParallelDialsPerPeer,this.dialTimeout=r.dialTimeout??Wo.dialTimeout,this.peerId=e.peerId,this.peerStore=e.peerStore,this.connectionGater=e.connectionGater,this.transportManager=e.transportManager,this.shutDownController=new AbortController;try{(0,ih.setMaxListeners)?.(1/0,this.shutDownController.signal)}catch{}this.pendingDialCount=e.metrics?.registerMetric("libp2p_dialler_pending_dials"),this.inProgressDialCount=e.metrics?.registerMetric("libp2p_dialler_in_progress_dials"),this.pendingDials=[];for(let[n,i]of Object.entries(r.resolvers??{}))of.set(n,i);this.queue=new Ut({concurrency:r.maxParallelDials??Wo.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=>{je.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}=Fa(e),o=i.map(l=>({multiaddr:l,isCertified:!1})),s=this.createDialAbortControllers(r.signal),a;try{a=await this.calculateMultiaddrs(n,o,{...r,signal:s})}catch(l){throw s.clear(),l}let c=this.pendingDials.find(l=>!!(l.peerId!=null&&n!=null&&l.peerId.equals(n)||a.map(({multiaddr:f})=>f.toString()).join()===l.multiaddrs.map(f=>f.toString()).join()));if(c!=null)return je("joining existing dial target for %p",n),s.clear(),c.promise;je("creating dial target for",a.map(({multiaddr:l})=>l.toString()));let u={id:_R(),status:"queued",peerId:n,multiaddrs:a.map(({multiaddr:l})=>l)};return u.promise=this.performDial(u,{...r,signal:s}).finally(()=>{this.pendingDials=this.pendingDials.filter(l=>l.id!==u.id),s.clear()}).catch(l=>{throw je.error("dial failed to %s",u.multiaddrs.map(f=>f.toString()).join(", "),l),s.aborted?new v(l.message,N.ERR_TIMEOUT):l}),this.pendingDials.push(u),u.promise}createDialAbortControllers(e){let r=Ki([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e]);try{(0,ih.setMaxListeners)?.(1/0,r)}catch{}return r}async calculateMultiaddrs(e,r=[],n={}){if(e!=null){if(this.peerId.equals(e))throw new v("Tried to dial self",N.ERR_DIALED_SELF);if(await this.connectionGater.denyDialPeer?.(e)===!0)throw new v("The dial request is blocked by gater.allowDialPeer",N.ERR_PEER_DIAL_INTERCEPTED);if(r.length===0){je("loading multiaddrs for %p",e);try{let l=await this.peerStore.get(e);r.push(...l.addresses),je("loaded multiaddrs for %p",e,r.map(({multiaddr:f})=>f.toString()))}catch(l){if(l.code!==N.ERR_NOT_FOUND)throw l}}}let i=(await Promise.all(r.map(async l=>{let f=await nh(l.multiaddr,n);return f.length===1&&f[0].equals(l.multiaddr)?l:f.map(d=>({multiaddr:d,isCertified:!1}))}))).flat(),o=i.filter(l=>!!this.transportManager.transportForMultiaddr(l.multiaddr)),s=new Map;for(let l of o){let f=l.multiaddr.toString(),d=s.get(f);if(d!=null){d.isCertified=d.isCertified||l.isCertified||!1;continue}s.set(f,l)}let a=[...s.values()];if((a.length===0||a.length>this.maxPeerAddrsToDial)&&(je("addresses for %p before filtering",e??"unknown peer",i.map(({multiaddr:l})=>l.toString())),je("addresses for %p after filtering",e??"unknown peer",a.map(({multiaddr:l})=>l.toString()))),a.length===0)throw new v("The dial request has no valid addresses",N.ERR_NO_VALID_ADDRESSES);if(a.length>this.maxPeerAddrsToDial)throw new v("dial with more addresses than allowed",N.ERR_TOO_MANY_ADDRESSES);if(e!=null){let l=`/p2p/${e.toString()}`;a=a.map(f=>{let d=f.multiaddr.getPeerId();return f.multiaddr.protos().pop()?.path===!0?f:d!==e.toString()?{multiaddr:f.multiaddr.encapsulate(l),isCertified:f.isCertified}:f})}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 v("The connection gater denied all addresses in the dial request",N.ERR_NO_VALID_ADDRESSES);return u}async performDial(e,r={}){let n=e.multiaddrs.map(()=>new AbortController);try{let i=new Ut({concurrency:this.maxParallelDialsPerPeer});i.on("error",s=>{je.error("error dialling",s)});let o=await Promise.any(e.multiaddrs.map(async(s,a)=>{let c=n[a];if(c==null)throw new v("dialAction did not come with an AbortController",N.ERR_INVALID_PARAMETERS);let u=H1(c.signal,r.signal);u.addEventListener("abort",()=>{je("dial to %a aborted",s)});let l=jr();return await i.add(async()=>{if(u.aborted){je("dial to %a was aborted before reaching the head of the peer dial queue",s),l.reject(new Cr);return}await this.queue.add(async()=>{try{if(u.aborted){je("dial to %a was aborted before reaching the head of the dial queue",s),l.reject(new Cr);return}e.status="active";let f=await this.transportManager.dial(s,{...r,signal:u});if(c.signal.aborted){je("multiple dials succeeded, closing superfluous connection"),f.close().catch(d=>{je.error("error closing superfluous connection",d)}),l.reject(new Cr);return}n[a]=void 0,n.forEach(d=>{d!==void 0&&d.abort()}),je("dial to %a succeeded",s),l.resolve(f)}catch(f){je.error("error during dial of %a",s,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(o==null)throw new v("successful dial led to empty object returned from peer dial queue",N.ERR_TRANSPORT_DIAL_FAILED);return e.status="success",o}catch(i){throw e.status="error",e.multiaddrs.length===1&&i.name==="AggregateError"?i.errors[0]:i}}};function _R(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var xt=W("libp2p:connection-manager"),IR=50,Ln={minConnections:50,maxConnections:300,inboundConnectionThreshold:5,maxIncomingPendingConnections:10,autoDialConcurrency:25,autoDialPriority:0,autoDialMaxQueueLength:100},$a=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;autoDial;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;constructor(e,r={}){this.maxConnections=r.maxConnections??Ln.maxConnections;let n=r.minConnections??Ln.minConnections;if(this.maxConnections<n)throw new v("Connection Manager maxConnections must be greater than minConnections",N.ERR_INVALID_PARAMETERS);this.connections=new Nt,this.started=!1,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,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??Ln.maxIncomingPendingConnections,this.inboundConnectionRateLimiter=new G1.RateLimiterMemory({points:r.inboundConnectionThreshold??Ln.inboundConnectionThreshold,duration:1}),this.autoDial=new Va({connectionManager:this,peerStore:e.peerStore,events:e.events},{minConnections:n,autoDialConcurrency:r.autoDialConcurrency??Ln.autoDialConcurrency,autoDialPriority:r.autoDialPriority??Ln.autoDialPriority,maxQueueLength:r.autoDialMaxQueueLength??Ln.autoDialMaxQueueLength}),this.connectionPruner=new qa({connectionManager:this,peerStore:e.peerStore,events:e.events},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new za({peerId:e.peerId,metrics:e.metrics,peerStore:e.peerStore,transportManager:e.transportManager,connectionGater:e.connectionGater},{addressSorter:r.addressSorter??Di,maxParallelDials:r.maxParallelDials??100,maxPeerAddrsToDial:r.maxPeerAddrsToDial??25,dialTimeout:r.dialTimeout??3e4,resolvers:r.resolvers??{dnsaddr:Ni}})}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.stat.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 o=`${i.stat.direction} ${i.stat.protocol??"unnegotiated"}`;e[o]=(e[o]??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 o={};for(let s of i.streams){let a=`${s.stat.direction} ${s.stat.protocol??"unnegotiated"}`;o[a]=(o[a]??0)+1}for(let[s,a]of Object.entries(o))e[s]=e[s]??[],e[s].push(a)}let r={};for(let[n,i]of Object.entries(e)){i=i.sort((s,a)=>s-a);let o=Math.floor(i.length*.9);r[n]=i[o]}return r}}),this.autoDial.start(),this.started=!0,xt("started")}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[r=>r.tags.has(Yg)]});await Promise.all(e.map(async r=>{await this.openConnection(r.id).catch(n=>{xt.error(n)})}))}).catch(e=>{xt.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){xt.error(i)}})());xt("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),xt("stopped")}onConnect(e){this._onConnect(e).catch(r=>{xt.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),o=!1;i!=null?i.push(r):(o=!0,this.connections.set(n,[r])),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),o&&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(o=>o.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 v("Not started",N.ERR_NODE_NOT_STARTED);let{peerId:n}=Fa(e);if(n!=null){xt("dial %p",n);let a=this.getConnections(n);if(a.length>0)return xt("had an existing connection to %p",n),a[0]}let i=await this.dialQueue.dial(e,{...r,priority:r.priority??IR}),o=this.connections.get(i.remotePeer);o==null&&(o=[],this.connections.set(i.remotePeer,o));let s=!1;for(let a of o)a.id===i.id&&(s=!0);return s||o.push(i),i}async closeConnections(e){let r=this.connections.get(e)??[];await Promise.all(r.map(async n=>{await n.close()}))}async acceptIncomingConnection(e){if(this.deny.some(i=>e.remoteAddr.toString().startsWith(i.toString())))return xt("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 xt("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 xt("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,i),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(xt("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){return this.dialQueue.pendingDials}};var Ha=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}},Vi=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Ha(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 Ha(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 ch=class extends Error{type;code;constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function Pn(t={}){return RR(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 RR(t,e){e=e??{};let r=e.onEnd,n=new Vi,i,o,s,a=jr(),c=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((y,g)=>{o=x=>{o=null,n.push(x);try{y(t(n))}catch(E){g(E)}return i}}):t(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=jr()})}},u=y=>o!=null?o(y):(n.push(y),i),l=y=>(n=new Vi,o!=null?o({error:y}):(n.push({error:y}),i)),f=y=>{if(s)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})},d=y=>s?i:(s=!0,y!=null?l(y):u({done:!0})),p=()=>(n=new Vi,d(),{done:!0}),h=y=>(d(y),{done:!0});if(i={[Symbol.asyncIterator](){return this},next:c,return:p,throw:h,push:f,end:d,get readableLength(){return n.size},onEmpty:async y=>{let g=y?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let x,E;g!=null&&(x=new Promise((T,I)=>{E=()=>{I(new ch)},g.addEventListener("abort",E)}));try{await Promise.race([a.promise,x])}finally{E!=null&&g!=null&&g?.removeEventListener("abort",E)}}},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}},i}function CR(t){return t[Symbol.asyncIterator]!=null}function TR(...t){let e=[];for(let r of t)CR(r)||e.push(r);return e.length===t.length?function*(){for(let r of e)yield*r}():async function*(){let r=Pn({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 Jr=TR;function Dn(t,...e){if(t==null)throw new Error("Empty pipeline");if(uh(t)){let n=t;t=()=>n.source}else if(W1(t)||Y1(t)){let n=t;t=()=>n}let r=[t,...e];if(r.length>1&&uh(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++)uh(r[n])&&(r[n]=LR(r[n]));return BR(...r)}var BR=(...t)=>{let e;for(;t.length>0;)e=t.shift()(e);return e},Y1=t=>t?.[Symbol.asyncIterator]!=null,W1=t=>t?.[Symbol.iterator]!=null,uh=t=>t==null?!1:t.sink!=null&&t.source!=null,LR=t=>e=>{let r=t.sink(e);if(r?.then!=null){let n=Pn({objectMode:!0});r.then(()=>{n.end()},s=>{n.end(s)});let i,o=t.source;if(Y1(o))i=async function*(){yield*o,n.end()};else if(W1(o))i=function*(){yield*o,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Jr(n,i())}return t.source};function PR(t){return t[Symbol.asyncIterator]!=null}function DR(t,e){if(PR(t))return async function*(){for await(let a of t)yield e(a)}();let r=Ba(t),{value:n,done:i}=r.next();if(i===!0)return function*(){}();let o=e(n);if(typeof o.then=="function")return async function*(){yield await o;for await(let a of r)yield e(a)}();let s=e;return function*(){yield o;for(let a of r)yield s(a)}()}var Q1=DR;async function*Qo(t,e){yield*Q1(t,async r=>(await e.merge(r.id,{multiaddrs:r.multiaddrs}),r))}function Ga(t){let e=new Set;return Ft(t,r=>e.has(r.id.toString())?!1:(e.add(r.id.toString()),!0))}async function*Ya(t,e=1){let r=0;for await(let n of t)r++,yield n;if(r<e)throw new v(`more peers required, seen: ${r} min: ${e}`,"NOT_FOUND")}var Wa=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 v("No content routers available",N.ERR_NO_ROUTERS_AVAILABLE);yield*Dn(Jr(...this.routers.map(n=>n.findProviders(e,r))),n=>Qo(n,this.components.peerStore),n=>Ga(n),n=>Ya(n))}async provide(e,r={}){if(this.routers.length===0)throw new v("No content routers available",N.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 v(or.NOT_STARTED_YET,N.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 v(or.NOT_STARTED_YET,N.DHT_NOT_STARTED);return Promise.any(this.routers.map(async n=>n.get(e,r)))}};function NR(t){return t[Symbol.asyncIterator]!=null}function kR(t){if(NR(t))return(async()=>{for await(let e of t)return e})();for(let e of t)return e}var Qa=kR;var OR=W("libp2p:peer-routing"),Xa=class{components;routers;constructor(e,r){this.components=e,this.routers=r.routers??[]}async findPeer(e,r){if(this.routers.length===0)throw new v("No peer routers available",N.ERR_NO_ROUTERS_AVAILABLE);if(e.toString()===this.components.peerId.toString())throw new v("Should not try to find self",N.ERR_FIND_SELF);let n=await Dn(Jr(...this.routers.map(i=>async function*(){try{yield await i.findPeer(e,r)}catch(o){OR.error(o)}}())),i=>Ft(i,Boolean),i=>Qo(i,this.components.peerStore),async i=>Qa(i));if(n!=null)return n;throw new v(or.NOT_FOUND,N.ERR_NOT_FOUND)}async*getClosestPeers(e,r){if(this.routers.length===0)throw new v("No peer routers available",N.ERR_NO_ROUTERS_AVAILABLE);yield*Dn(Jr(...this.routers.map(n=>n.getClosestPeers(e,r))),n=>Qo(n,this.components.peerStore),n=>Ga(n),n=>Ya(n))}};var lh=W("libp2p:registrar"),fh=32,hh=64,Za=class{topologies;handlers;components;constructor(e){this.topologies=new Map,this.handlers=new Map,this.components=e,this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onConnect=this._onConnect.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:connect",this._onConnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate)}getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let r=this.handlers.get(e);if(r==null)throw new v(`No handler registered for protocol ${e}`,N.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 v(`Handler already registered for protocol ${e}`,N.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);let i=qr.bind({ignoreUndefined:!0})({maxInboundStreams:fh,maxOutboundStreams:hh},n);this.handlers.set(e,{handler:r,options:i}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]})}async unhandle(e){let r=Array.isArray(e)?e:[e];r.forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:r})}async register(e,r){if(r==null)throw new v("invalid topology",N.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 o=this.topologies.get(i);if(o!=null)for(let s of o.values())s.onDisconnect?.(r)}}).catch(n=>{n.code!==N.ERR_NOT_FOUND&&lh.error("could not inform topologies of disconnecting peer %p",r,n)})}_onConnect(e){let r=e.detail;this.components.peerStore.get(r).then(n=>{let i=this.components.connectionManager.getConnections(n.id)[0];if(i==null){lh("peer %p connected but the connection manager did not have a connection",n);return}for(let o of n.protocols){let s=this.topologies.get(o);if(s!=null)for(let a of s.values())a.onConnect?.(r,i)}}).catch(n=>{n.code!==N.ERR_NOT_FOUND&&lh.error("could not inform topologies of connecting peer %p",r,n)})}_onPeerUpdate(e){let{peer:r,previous:n}=e.detail,i=(n?.protocols??[]).filter(s=>!r.protocols.includes(s)),o=r.protocols.filter(s=>!(n?.protocols??[]).includes(s));for(let s of i){let a=this.topologies.get(s);if(a!=null)for(let c of a.values())c.onDisconnect?.(r.id)}for(let s of o){let a=this.topologies.get(s);if(a!=null)for(let c of a.values()){let u=this.components.connectionManager.getConnections(r.id)[0];u!=null&&c.onConnect?.(r.id,u)}}}};var dh=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 X1(t){let{name:e,metrics:r}=t,n;return r!=null?n=new dh({name:e,metrics:r}):n=new Map,n}var Nn=W("libp2p:transports"),ja=class{components;transports;listeners;faultTolerance;started;constructor(e,r={}){this.components=e,this.started=!1,this.transports=new Map,this.listeners=X1({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=r.faultTolerance??Xr.FATAL_ALL}add(e){let r=e[Symbol.toStringTag];if(r==null)throw new v("Transport must have a valid tag",N.ERR_INVALID_KEY);if(this.transports.has(r))throw new v(`There is already a transport with the tag ${r}`,N.ERR_DUPLICATE_TRANSPORT);Nn("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(Nn("closing listeners for %s",r);n.length>0;){let i=n.pop();i!=null&&e.push(i.close())}await Promise.all(e),Nn("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 v(`No transport available for address ${String(e)}`,N.ERR_TRANSPORT_UNAVAILABLE);try{return await n.dial(e,{...r,upgrader:this.components.upgrader})}catch(i){throw i.code==null&&(i.code=N.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(e==null||e.length===0){Nn("no addresses were provided for listening, this node is dial only");return}let r=[];for(let[n,i]of this.transports.entries()){let o=i.filter(e),s=[];for(let u of o){Nn("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 d=f.findIndex(p=>p===l);f.splice(d,1),this.components.events.safeDispatchEvent("transport:close",{detail:l})}),s.push(l.listen(u))}if(s.length===0){r.push(n);continue}if((await Promise.allSettled(s)).find(u=>u.status==="fulfilled")==null&&this.faultTolerance!==Xr.NO_FATAL)throw new v(`Transport (${n}) could not listen on any available address`,N.ERR_NO_VALID_ADDRESSES)}if(r.length===this.transports.size){let n=`no valid addresses were provided for transports [${r.join(", ")}]`;if(this.faultTolerance===Xr.FATAL_ALL)throw new v(n,N.ERR_NO_VALID_ADDRESSES);Nn(`libp2p in dial mode only: ${n}`)}}async remove(e){Nn("removing %s",e);for(let r of this.listeners.get(e)??[])await r.close();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 xh=z(Hi(),1);var _r="/multistream/1.0.0";function ph(t){let e=async function*(){let r=yield,n=new Te;for await(let i of t){if(r==null){n.append(i),r=yield n,n=new Te;continue}for(n.append(i);n.length>=r;){let o=n.sublist(0,r);if(n.consume(r),r=yield o,r==null){n.length>0&&(r=yield n,n=new Te);break}}}if(r!=null)throw Object.assign(new Error(`stream ended before ${r} bytes became available`),{code:"ERR_UNDER_READ",buffer:n})}();return e.next(),e}function Ja(t){let e=Pn(),r=ph(t.source),n=jr(),i,o=t.sink(async function*(){yield*e,yield*await n.promise}());return o.catch(a=>{i=a}),{reader:r,writer:e,stream:{sink:async a=>{if(i!=null){await Promise.reject(i);return}n.resolve(a),await o},source:r},rest:()=>e.end(),write:e.push,read:async()=>{let a=await r.next();if(a.value!=null)return a.value}}}var Xo=class extends Error{constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function Z1(t){if(t!=null){if(typeof t[Symbol.iterator]=="function")return t[Symbol.iterator]();if(typeof t[Symbol.asyncIterator]=="function")return t[Symbol.asyncIterator]();if(typeof t.next=="function")return t}throw new Error("argument is not an iterator or iterable")}function ec(t,e,r){let n=r??{},i=Z1(t);async function*o(){let s,a=()=>{s?.()};for(e.addEventListener("abort",a);;){let c;try{if(e.aborted){let{abortMessage:l,abortCode:f}=n;throw new Xo(l,f)}let u=new Promise((l,f)=>{s=()=>{let{abortMessage:d,abortCode:p}=n;f(new Xo(d,p))}});c=await Promise.race([u,i.next()]),s=null}catch(u){e.removeEventListener("abort",a);let l=u.type==="aborted"&&e.aborted;if(l&&n.onAbort!=null&&n.onAbort(t),typeof i.return=="function")try{let f=i.return();f instanceof Promise&&f.catch(d=>{n.onReturnError!=null&&n.onReturnError(d)})}catch(f){n.onReturnError!=null&&n.onReturnError(f)}if(l&&n.returnOnAbort===!0)return;throw u}if(c.done===!0)break;yield c.value}e.removeEventListener("abort",a)}return o()}function MR(t,e,r){return n=>t(ec(n,e,r))}function j1(t,e,r){return{sink:MR(t.sink,e,{...r,onAbort:void 0}),source:ec(t.source,e,r)}}function tc(t){return t[Symbol.asyncIterator]!=null}var rc=t=>{let e=Ot.encodingLength(t),r=Ct(e);return Ot.encode(t,r),rc.bytes=e,r};rc.bytes=0;function nc(t,e){e=e??{};let r=e.lengthEncoder??rc;function*n(i){let o=r(i.byteLength);o instanceof Uint8Array?yield o:yield*o,i instanceof Uint8Array?yield i:yield*i}return tc(t)?async function*(){for await(let i of t)yield*n(i)}():function*(){for(let i of t)yield*n(i)}()}nc.single=(t,e)=>{e=e??{};let r=e.lengthEncoder??rc;return new Te(r(t.byteLength),t)};var qi=z(Cf(),1);var UR=8,FR=1024*1024*4,kn;(function(t){t[t.LENGTH=0]="LENGTH",t[t.DATA=1]="DATA"})(kn||(kn={}));var mh=t=>{let e=Ot.decode(t);return mh.bytes=Ot.encodingLength(e),e};mh.bytes=0;function Zo(t,e){let r=new Te,n=kn.LENGTH,i=-1,o=e?.lengthDecoder??mh,s=e?.maxLengthLength??UR,a=e?.maxDataLength??FR;function*c(){for(;r.byteLength>0;){if(n===kn.LENGTH)try{if(i=o(r),i<0)throw(0,qi.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(i>a)throw(0,qi.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let u=o.bytes;r.consume(u),e?.onLength!=null&&e.onLength(i),n=kn.DATA}catch(u){if(u instanceof RangeError){if(r.byteLength>s)throw(0,qi.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw u}if(n===kn.DATA){if(r.byteLength<i)break;let u=r.sublist(0,i);r.consume(i),e?.onData!=null&&e.onData(u),yield u,n=kn.LENGTH}}}return tc(t)?async function*(){for await(let u of t)r.append(u),yield*c();if(r.byteLength>0)throw(0,qi.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,qi.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}Zo.fromReader=(t,e)=>{let r=1,n=async function*(){for(;;)try{let{done:o,value:s}=await t.next(r);if(o===!0)return;s!=null&&(yield s)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{r=1}}();return Zo(n,{...e??{},onLength:o=>{r=o}})};var qR=W("libp2p:mss"),J1=V(`
|
|
49
|
-
`);function jo(t){let e=new Te(t,J1);return nc.single(e)}function On(t,e,r={}){let n=jo(e);r.writeBytes===!0?t.push(n.subarray()):t.push(n)}function ex(t,e,r={}){let n=new Te;for(let i of e)n.append(jo(i));r.writeBytes===!0?t.push(n.subarray()):t.push(n)}async function zR(t,e){let r=1,n={[Symbol.asyncIterator]:()=>n,next:async()=>t.next(r)},i=n;e?.signal!=null&&(i=ec(n,e.signal));let o=a=>{r=a},s=await Dn(i,a=>Zo(a,{onLength:o,maxDataLength:1024}),async a=>Qa(a));if(s==null||s.length===0)throw new v("no buffer returned","ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");if(s.get(s.byteLength-1)!==J1[0])throw qR.error("Invalid mss message - missing newline - %s",s.subarray()),new v("missing newline","ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");return s.sublist(0,-1)}async function zi(t,e){let r=await zR(t,e);return G(r.subarray())}var Jo=W("libp2p:mss:select");async function es(t,e,r={}){e=Array.isArray(e)?[...e]:[e];let{reader:n,writer:i,rest:o,stream:s}=Ja(t),a=e.shift();if(a==null)throw new Error("At least one protocol must be specified");Jo.trace('select: write ["%s", "%s"]',_r,a);let c=V(_r),u=V(a);ex(i,[c,u],r);let l=await zi(n,r);if(Jo.trace('select: read "%s"',l),l===_r&&(l=await zi(n,r),Jo.trace('select: read "%s"',l)),l===a)return o(),{stream:s,protocol:a};for(let f of e){Jo.trace('select: write "%s"',f),On(i,V(f),r);let d=await zi(n,r);if(Jo.trace('select: read "%s" for "%s"',d,f),d===f)return o(),{stream:s,protocol:f}}throw o(),new v("protocol selection failed","ERR_UNSUPPORTED_PROTOCOL")}var ts=W("libp2p:mss:handle");async function rs(t,e,r){e=Array.isArray(e)?e:[e];let{writer:n,reader:i,rest:o,stream:s}=Ja(t);for(;;){let a=await zi(i,r);if(ts.trace('read "%s"',a),a===_r){ts.trace('respond with "%s" for "%s"',_r,a),On(n,V(_r),r);continue}if(e.includes(a))return On(n,V(a),r),ts.trace('respond with "%s" for "%s"',a,a),o(),{stream:s,protocol:a};if(a==="ls"){On(n,new Te(...e.map(c=>jo(V(c)))),r),ts.trace('respond with "%s" for %s',e,a);continue}On(n,V("na"),r),ts('respond with "na" for "%s"',a)}}var rx=Symbol.for("@libp2p/connection");var nx="OPEN",yh="CLOSING",ic="CLOSED";var HR=W("libp2p:connection"),gh=class{id;remoteAddr;remotePeer;stat;tags;_newStream;_close;_getStreams;_closing;constructor(e){let{remoteAddr:r,remotePeer:n,newStream:i,close:o,getStreams:s,stat:a}=e;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=r,this.remotePeer=n,this.stat={...a,status:nx},this._newStream=i,this._close=o,this._getStreams=s,this.tags=[],this._closing=!1}[Symbol.toStringTag]="Connection";[rx]=!0;get streams(){return this._getStreams()}async newStream(e,r){if(this.stat.status===yh)throw new v("the connection is being closed","ERR_CONNECTION_BEING_CLOSED");if(this.stat.status===ic)throw new v("the connection is closed","ERR_CONNECTION_CLOSED");Array.isArray(e)||(e=[e]);let n=await this._newStream(e,r);return n.stat.direction="outbound",n}addStream(e){e.stat.direction="inbound"}removeStream(e){}async close(){if(!(this.stat.status===ic||this._closing)){this.stat.status=yh;try{this.streams.forEach(e=>{e.close()})}catch(e){HR.error(e)}this._closing=!0,await this._close(),this._closing=!1,this.stat.timeline.close=Date.now(),this.stat.status=ic}}};function ix(t){return new gh(t)}var ve=W("libp2p:upgrader");function YR(t,e){try{let{options:r}=e.getHandler(t);return r.maxInboundStreams}catch(r){if(r.code!==N.ERR_NO_HANDLER_FOR_PROTOCOL)throw r}return fh}function WR(t,e,r={}){try{let{options:n}=e.getHandler(t);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.code!==N.ERR_NO_HANDLER_FOR_PROTOCOL)throw n}return r.maxOutboundStreams??hh}function ox(t,e,r){let n=0;return r.streams.forEach(i=>{i.stat.direction===e&&i.stat.protocol===t&&n++}),n}var oc=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 v(`The multiaddr connection is blocked by gater.${n}`,N.ERR_CONNECTION_INTERCEPTED)}async upgradeInbound(e,r){if(!await this.components.connectionManager.acceptIncomingConnection(e))throw new v("connection denied",N.ERR_CONNECTION_DENIED);let i,o,s,a,c,u=Ki([AbortSignal.timeout(this.inboundUpgradeTimeout)]);try{(0,xh.setMaxListeners)?.(1/0,u)}catch{}try{let l=j1(e,u);if(e.source=l.source,e.sink=l.sink,await this.components.connectionGater.denyInboundConnection?.(e)===!0)throw new v("The multiaddr connection is blocked by gater.acceptConnection",N.ERR_CONNECTION_INTERCEPTED);this.components.metrics?.trackMultiaddrConnection(e),ve("starting the inbound connection upgrade");let f=e;if(r?.skipProtection!==!0){let d=this.components.connectionProtector;d!=null&&(ve("protecting the inbound connection"),f=await d.protect(e))}try{if(i=f,r?.skipEncryption!==!0){({conn:i,remotePeer:o,protocol:c}=await this._encryptInbound(f));let d={...f,...i};await this.shouldBlockConnection(o,d,"denyInboundEncryptedConnection")}else{let d=e.remoteAddr.getPeerId();if(d==null)throw new v("inbound connection that skipped encryption must have a peer id",N.ERR_INVALID_MULTIADDR);let p=oe(d);c="native",o=p}if(s=i,r?.muxerFactory!=null)a=r.muxerFactory;else if(this.muxers.size>0){let d=await this._multiplexInbound({...f,...i},this.muxers);a=d.muxerFactory,s=d.stream}}catch(d){throw ve.error("Failed to upgrade inbound connection",d),d}return await this.shouldBlockConnection(o,e,"denyInboundUpgradedConnection"),ve("Successfully upgraded inbound connection"),this._createConnection({cryptoProtocol:c,direction:"inbound",maConn:e,upgradedConn:s,muxerFactory:a,remotePeer:o})}finally{this.components.connectionManager.afterUpgradeInbound(),u.clear()}}async upgradeOutbound(e,r){let n=e.remoteAddr.getPeerId(),i;n!=null&&(i=oe(n),await this.shouldBlockConnection(i,e,"denyOutboundConnection"));let o,s,a,c,u;this.components.metrics?.trackMultiaddrConnection(e),ve("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(o=l,r?.skipEncryption!==!0){({conn:o,remotePeer:s,protocol:c}=await this._encryptOutbound(l,i));let f={...l,...o};await this.shouldBlockConnection(s,f,"denyOutboundEncryptedConnection")}else{if(i==null)throw new v("Encryption was skipped but no peer id was passed",N.ERR_INVALID_PEER);c="native",s=i}if(a=o,r?.muxerFactory!=null)u=r.muxerFactory;else if(this.muxers.size>0){let f=await this._multiplexOutbound({...l,...o},this.muxers);u=f.muxerFactory,a=f.stream}}catch(f){throw ve.error("Failed to upgrade outbound connection",f),await e.close(f),f}return await this.shouldBlockConnection(s,e,"denyOutboundUpgradedConnection"),ve("Successfully upgraded outbound connection"),this._createConnection({cryptoProtocol:c,direction:"outbound",maConn:e,upgradedConn:a,muxerFactory:u,remotePeer:s})}_createConnection(e){let{cryptoProtocol:r,direction:n,maConn:i,upgradedConn:o,remotePeer:s,muxerFactory:a}=e,c,u,l;a!=null&&(c=a.createStreamMuxer({direction:n,onIncomingStream:p=>{l!=null&&Promise.resolve().then(async()=>{let h=this.components.registrar.getProtocols(),{stream:m,protocol:y}=await rs(p,h);if(ve("%s: incoming stream opened on %s",n,y),l==null)return;let g=YR(y,this.components.registrar);if(ox(y,"inbound",l)===g){let E=new v(`Too many inbound protocol streams for protocol "${y}" - limit ${g}`,N.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS);throw p.abort(E),E}p.source=m.source,p.sink=m.sink,p.stat.protocol=y,await this.components.peerStore.merge(s,{protocols:[y]}),l.addStream(p),this.components.metrics?.trackProtocolStream(p,l),this._onStream({connection:l,stream:p,protocol:y})}).catch(h=>{ve.error(h),p.stat.timeline.close==null&&p.close()})},onStreamEnd:p=>{l?.removeStream(p.id)}}),u=async(p,h={})=>{if(c==null)throw new v("Stream is not multiplexed",N.ERR_MUXER_UNAVAILABLE);ve("%s: starting new stream on %s",n,p);let m=await c.newStream();try{if(h.signal==null){ve("No abort signal was passed while trying to negotiate protocols %s falling back to default timeout",p),h.signal=AbortSignal.timeout(3e4);try{(0,xh.setMaxListeners)?.(1/0,h.signal)}catch{}}let{stream:y,protocol:g}=await es(m,p,h),x=WR(g,this.components.registrar,h);if(ox(g,"outbound",l)>=x){let T=new v(`Too many outbound protocol streams for protocol "${g}" - limit ${x}`,N.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);throw m.abort(T),T}return await this.components.peerStore.merge(s,{protocols:[g]}),m.source=y.source,m.sink=y.sink,m.stat.protocol=g,this.components.metrics?.trackProtocolStream(m,l),m}catch(y){throw ve.error("could not create new stream",y),m.stat.timeline.close==null&&m.close(),y.code!=null?y:new v(String(y),N.ERR_UNSUPPORTED_PROTOCOL)}},Promise.all([c.sink(o.source),o.sink(c.source)]).catch(p=>{ve.error(p)}));let f=i.timeline;i.timeline=new Proxy(f,{set:(...p)=>(l!=null&&p[1]==="close"&&p[2]!=null&&f.close==null&&(async()=>{try{l.stat.status==="OPEN"&&await l.close()}catch(h){ve.error(h)}finally{this.events.safeDispatchEvent("connection:close",{detail:l})}})().catch(h=>{ve.error(h)}),Reflect.set(...p))}),i.timeline.upgraded=Date.now();let d=()=>{throw new v("connection is not multiplexed",N.ERR_CONNECTION_NOT_MULTIPLEXED)};return l=ix({remoteAddr:i.remoteAddr,remotePeer:s,stat:{status:"OPEN",direction:n,timeline:i.timeline,multiplexer:c?.protocol,encryption:r},newStream:u??d,getStreams:()=>c!=null?c.streams:d(),close:async()=>{await i.close(),c?.close()}}),this.events.safeDispatchEvent("connection:open",{detail:l}),l}_onStream(e){let{connection:r,stream:n,protocol:i}=e,{handler:o}=this.components.registrar.getHandler(i);o({connection:r,stream:n})}async _encryptInbound(e){let r=Array.from(this.connectionEncryption.keys());ve("handling inbound crypto protocol selection",r);try{let{stream:n,protocol:i}=await rs(e,r,{writeBytes:!0}),o=this.connectionEncryption.get(i);if(o==null)throw new Error(`no crypto module found for ${i}`);return ve("encrypting inbound connection..."),{...await o.secureInbound(this.components.peerId,n),protocol:i}}catch(n){throw new v(String(n),N.ERR_ENCRYPTION_FAILED)}}async _encryptOutbound(e,r){let n=Array.from(this.connectionEncryption.keys());ve("selecting outbound crypto protocol",n);try{let{stream:i,protocol:o}=await es(e,n,{writeBytes:!0}),s=this.connectionEncryption.get(o);if(s==null)throw new Error(`no crypto module found for ${o}`);return ve("encrypting outbound connection to %p",r),{...await s.secureOutbound(this.components.peerId,i,r),protocol:o}}catch(i){throw new v(String(i),N.ERR_ENCRYPTION_FAILED)}}async _multiplexOutbound(e,r){let n=Array.from(r.keys());ve("outbound selecting muxer %s",n);try{let{stream:i,protocol:o}=await es(e,n,{writeBytes:!0});ve("%s selected as muxer protocol",o);let s=r.get(o);return{stream:i,muxerFactory:s}}catch(i){throw ve.error("error multiplexing outbound stream",i),new v(String(i),N.ERR_MUXER_UNAVAILABLE)}}async _multiplexInbound(e,r){let n=Array.from(r.keys());ve("inbound handling muxers %s",n);try{let{stream:i,protocol:o}=await rs(e,n,{writeBytes:!0}),s=r.get(o);return{stream:i,muxerFactory:s}}catch(i){throw ve.error("error multiplexing inbound stream",i),new v(String(i),N.ERR_MUXER_UNAVAILABLE)}}};var ct=W("libp2p"),wh=class extends So{peerId;peerStore;contentRouting;peerRouting;keychain;metrics;services;components;#e;constructor(e){super();let r=new So,n=r.dispatchEvent.bind(r);r.dispatchEvent=c=>{let u=n(c),l=this.dispatchEvent(new nl(c.type,{detail:c.detail}));return u||l};try{(0,sx.setMaxListeners)?.(1/0,r)}catch{}this.#e=!1,this.peerId=e.peerId,this.services={};let i=this.components=Rg({peerId:e.peerId,events:r,datastore:e.datastore??new Pa,connectionGater:Mg(e.connectionGater)});this.peerStore=this.configureComponent("peerStore",new Ta(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",c=>{c.detail.previous==null&&this.safeDispatchEvent("peer:discovery",{detail:c.detail.peer})}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new oc(this.components,{connectionEncryption:(e.connectionEncryption??[]).map((c,u)=>this.configureComponent(`connection-encryption-${u}`,c(this.components))),muxers:(e.streamMuxers??[]).map((c,u)=>this.configureComponent(`stream-muxers-${u}`,c(this.components))),inboundUpgradeTimeout:e.connectionManager.inboundUpgradeTimeout}),this.configureComponent("transportManager",new ja(this.components,e.transportManager)),this.configureComponent("connectionManager",new $a(this.components,e.connectionManager)),this.configureComponent("registrar",new Za(this.components)),this.configureComponent("addressManager",new Da(this.components,e.addresses));let o=An.generateOptions();this.keychain=this.configureComponent("keyChain",new An(this.components,{...o,...e.keychain}));let s=(e.peerRouters??[]).map((c,u)=>this.configureComponent(`peer-router-${u}`,c(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new Xa(this.components,{routers:s}));let a=(e.contentRouters??[]).map((c,u)=>this.configureComponent(`content-router-${u}`,c(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new Wa(this.components,{routers:a})),(e.peerDiscovery??[]).forEach((c,u)=>{this.configureComponent(`peer-discovery-${u}`,c(this.components)).addEventListener("peer",f=>{this.#t(f)})}),e.transports.forEach((c,u)=>{this.components.transportManager.add(this.configureComponent(`transport-${u}`,c(this.components)))}),e.services!=null)for(let c of Object.keys(e.services)){let u=e.services[c],l=u(this.components);if(l==null){ct.error("service factory %s returned null or undefined instance",c);continue}this.services[c]=l,this.configureComponent(c,l),l[tl]!=null&&(ct("registering service %s for content routing",c),a.push(l[tl])),l[ol]!=null&&(ct("registering service %s for peer routing",c),s.push(l[ol])),l[il]!=null&&(ct("registering service %s for peer discovery",c),l[il].addEventListener("peer",f=>{this.#t(f)}))}}configureComponent(e,r){return r==null&&ct.error("component %s was null or undefined",e),this.components[e]=r,r}async start(){if(this.#e)return;this.#e=!0,ct("libp2p is starting"),(await this.keychain.listKeys()).find(r=>r.name==="self")==null&&(ct("importing self key into keychain"),await this.keychain.importPeer("self",this.components.peerId));try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.safeDispatchEvent("start",{detail:this}),ct("libp2p has started")}catch(r){throw ct.error("An error occurred starting libp2p",r),await this.stop(),r}}async stop(){this.#e&&(ct("libp2p is stopping"),this.#e=!1,await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.safeDispatchEvent("stop",{detail:this}),ct("libp2p has stopped"))}isStarted(){return this.#e}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new kt;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 v("no protocols were provided to open a stream",N.ERR_INVALID_PROTOCOLS_FOR_STREAM);if(r=Array.isArray(r)?r:[r],r.length===0)throw new v("no protocols were provided to open a stream",N.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){Rn(e)&&(e=oe(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e)}async getPublicKey(e,r={}){if(ct("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=Pe([V("/pk/"),e.multihash.digest]),o=await this.contentRouting.get(i,r);return Eo(o),await this.peerStore.patch(e,{publicKey:o}),o}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)}#t(e){let{detail:r}=e;if(r.id.toString()===this.peerId.toString()){ct.error(new Error(N.ERR_DISCOVERED_SELF));return}this.components.peerStore.merge(r.id,{multiaddrs:r.multiaddrs,protocols:r.protocols}).catch(n=>{ct.error(n)})}};async function ax(t){if(t.peerId==null){let e=t.datastore;if(e!=null)try{let r=new An({datastore:e},qr(An.generateOptions(),t.keychain));t.peerId=await r.exportPeerId("self")}catch(r){if(r.code!=="ERR_NOT_FOUND")throw r}}return t.peerId==null&&(t.peerId=await ty()),new wh(Gg(t))}async function QR(t){let e=await ax(t);return t.start!==!1&&await e.start(),e}return px(XR);})();
|
|
48
|
+
`.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),_I=new RegExp(`(?:^${Kt}$)|(?:^${Na}$)`),SI=new RegExp(`^${Kt}$`),AI=new RegExp(`^${Na}$`),Lf=t=>t&&t.exact?_I:new RegExp(`(?:${Qr(t)}${Kt}${Qr(t)})|(?:${Qr(t)}${Na}${Qr(t)})`,"g");Lf.v4=t=>t&&t.exact?SI:new RegExp(`${Qr(t)}${Kt}${Qr(t)}`,"g");Lf.v6=t=>t&&t.exact?AI:new RegExp(`${Qr(t)}${Na}${Qr(t)}`,"g");var Bg=Lf;var kg=z(Pg(),1),{isValid:II,parse:RI}=kg.default,CI=["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"],TI=CI.map(t=>new Ng.Netmask(t));function BI(t){for(let e of TI)if(e.contains(t))return!0;return!1}function Dg(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 Og=t=>{if(II(t)){let e=RI(t);if(e.kind()==="ipv4")return BI(e.toNormalizedString());if(e.kind()==="ipv6")return Dg(t)}else if(Ii(t)&&Bg.v6().test(t))return Dg(t)};var Oa=Og;function Mg(t={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let r=e.stringTuples();return r[0][0]===4||r[0][0]===41?!!Oa(`${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 eD=Symbol.for("@libp2p/transport");var Xr;(function(t){t[t.FATAL_ALL=0]="FATAL_ALL",t[t.NO_FATAL=1]="NO_FATAL"})(Xr||(Xr={}));function Pf(t){try{let{address:e}=t.nodeAddress();return!!Oa(e)}catch{return!0}}function Di(t,e){let r=Pf(t.multiaddr),n=Pf(e.multiaddr);return r&&!n?1:!r&&n||t.isCertified&&!e.isCertified?-1:!t.isCertified&&e.isCertified?1:0}var Nf=z(al(),1),kf=z(Kg(),1);var Vg=globalThis.fetch,qg=globalThis.Headers,aD=globalThis.Request,cD=globalThis.Response;function Ma(t,e,r){return`${t}?name=${e}&type=${r}`}async function zg(t,e){return await(await Vg(t,{headers:new qg({accept:"application/dns-json"}),signal:e})).json()}function Bn(t,e){return`${e}_${t}`}var Df=Object.assign((0,Nf.default)("dns-over-http-resolver"),{error:(0,Nf.default)("dns-over-http-resolver:error")}),Of=class{constructor(e={}){this._cache=new kf.default({max:e?.maxCache??100}),this._TXTcache=new kf.default({max:e?.maxCache??100}),this._servers=["https://cloudflare-dns.com/dns-query","https://dns.google/resolve"],this._request=e.request??zg,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 await this.resolve4(e);case"AAAA":return await this.resolve6(e);case"TXT":return await this.resolveTxt(e);default:throw new Error(`${r} is not supported`)}}async resolve4(e){let r="A",n=this._cache.get(Bn(e,r));if(n!=null)return n;let i=!1;for(let o of this._getShuffledServers()){let s=new AbortController;this._abortControllers.push(s);try{let a=await this._request(Ma(o,e,r),s.signal),c=a.Answer.map(l=>l.data),u=Math.min(...a.Answer.map(l=>l.TTL));return this._cache.set(Bn(e,r),c,{ttl:u}),c}catch{s.signal.aborted&&(i=!0),Df.error(`${o} could not resolve ${e} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==s)}}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(Bn(e,r));if(n!=null)return n;let i=!1;for(let o of this._getShuffledServers()){let s=new AbortController;this._abortControllers.push(s);try{let a=await this._request(Ma(o,e,r),s.signal),c=a.Answer.map(l=>l.data),u=Math.min(...a.Answer.map(l=>l.TTL));return this._cache.set(Bn(e,r),c,{ttl:u}),c}catch{s.signal.aborted&&(i=!0),Df.error(`${o} could not resolve ${e} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==s)}}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(Bn(e,r));if(n!=null)return n;let i=!1;for(let o of this._getShuffledServers()){let s=new AbortController;this._abortControllers.push(s);try{let a=await this._request(Ma(o,e,r),s.signal),c=a.Answer.map(l=>[l.data.replace(/['"]+/g,"")]),u=Math.min(...a.Answer.map(l=>l.TTL));return this._TXTcache.set(Bn(e,r),c,{ttl:u}),c}catch{s.signal.aborted&&(i=!0),Df.error(`${o} could not resolve ${e} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==s)}}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()}},$g=Of;var Hg=$g;var{code:kI}=le("dnsaddr");async function Ni(t,e={}){let r=new Hg;e.signal!=null&&e.signal.addEventListener("abort",()=>{r.cancel()});let n=t.getPeerId(),[,i]=t.stringTuples().find(([a])=>a===kI)??[];if(i==null)throw new Error("No hostname found in multiaddr");let s=(await r.resolveTxt(`_dnsaddr.${i}`)).flat().map(a=>a.split("=")[1]).filter(Boolean);return n!=null&&(s=s.filter(a=>a.includes(n))),s}var or;(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"})(or||(or={}));var N;(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_TIMEOUT="ERR_TIMEOUT",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_KEYCHAIN_REQUIRED="ERR_KEYCHAIN_REQUIRED",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"})(N||(N={}));var OI={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:t=>t},connectionManager:{resolvers:{dnsaddr:Ni},addressSorter:Di},transportManager:{faultTolerance:Xr.FATAL_ALL}};function Gg(t){let e=qr(OI,t);if(e.transports==null||e.transports.length<1)throw new v(or.ERR_TRANSPORTS_REQUIRED,N.ERR_TRANSPORTS_REQUIRED);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new v(or.ERR_PROTECTOR_REQUIRED,N.ERR_PROTECTOR_REQUIRED);return e}var Yg="keep-alive";var G1=z(q1(),1);var xR=W("libp2p:get-peer");function Fa(t){if(Zs(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:oe(r),t.forEach(n=>{if(!Rn(n))throw xR.error("multiaddr %s was invalid",n),new v("Invalid Multiaddr",N.ERR_INVALID_MULTIADDR);let i=n.getPeerId();if(i==null){if(e!=null)throw new v("Multiaddrs must all have the same peer id or have no peer id",N.ERR_INVALID_PARAMETERS)}else{let o=oe(i);if(e==null||!e.equals(o))throw new v("Multiaddrs must all have the same peer id or have no peer id",N.ERR_INVALID_PARAMETERS)}})}return{peerId:e,multiaddrs:t}}function wR(t,e,r){let n=0,i=t.length;for(;i>0;){let o=Math.trunc(i/2),s=n+o;r(t[s],e)<=0?(n=++s,i-=o+1):i=o}return n}var Xf=class{#e=[];enqueue(e,r){let n=r?.peerId,i=r?.priority??0;if(n==null)throw new v("missing peer id",N.ERR_INVALID_PARAMETERS);let o={priority:i,peerId:n,run:e};if(this.size>0&&this.#e[this.size-1].priority>=i){this.#e.push(o);return}let s=wR(this.#e,o,(a,c)=>c.priority-a.priority);this.#e.splice(s,0,o)}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}},Ka=class extends Ut{constructor(e={}){super({...e,queueClass:Xf})}hasJob(e){return this.sizeBy({peerId:e})>0}};var Xe=W("libp2p:connection-manager:auto-dial"),Yo={minConnections:50,maxQueueLength:100,autoDialConcurrency:25,autoDialPriority:0,autoDialInterval:5e3},Va=class{connectionManager;peerStore;queue;minConnections;autoDialPriority;autoDialIntervalMs;autoDialMaxQueueLength;autoDialInterval;started;running;constructor(e,r){this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.minConnections=r.minConnections??Yo.minConnections,this.autoDialPriority=r.autoDialPriority??Yo.autoDialPriority,this.autoDialIntervalMs=r.autoDialInterval??Yo.autoDialInterval,this.autoDialMaxQueueLength=r.maxQueueLength??Yo.maxQueueLength,this.started=!1,this.running=!1,this.queue=new Ka({concurrency:r.autoDialConcurrency??Yo.autoDialConcurrency}),this.queue.addListener("error",n=>{Xe.error("error during auto-dial",n)}),e.events.addEventListener("connection:close",()=>{this.autoDial().catch(n=>{Xe.error(n)})})}isStarted(){return this.started}start(){this.autoDialInterval=setTimeout(()=>{this.autoDial().catch(e=>{Xe.error("error while autodialing",e)})},this.autoDialIntervalMs),this.started=!0}afterStart(){this.autoDial().catch(e=>{Xe.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){Xe.trace("have enough connections %d/%d",r,this.minConnections);return}if(this.queue.size>this.autoDialMaxQueueLength){Xe("not enough connections %d/%d but auto dial queue is full",r,this.minConnections);return}if(this.running){Xe("not enough connections %d/%d - but skipping autodial as it is already running",r,this.minConnections);return}this.running=!0,Xe("not enough connections %d/%d - will dial peers to increase the number of connections",r,this.minConnections);let n=new kt(this.connectionManager.getDialQueue().map(c=>c.peerId).filter(Boolean)),i=await this.peerStore.all({filters:[c=>c.addresses.length===0?(Xe.trace("not autodialing %p because they have no addresses"),!1):e.has(c.id)?(Xe.trace("not autodialing %p because they are already connected"),!1):n.has(c.id)?(Xe.trace("not autodialing %p because they are already being dialed"),!1):this.queue.hasJob(c.id)?(Xe.trace("not autodialing %p because they are already being autodialed"),!1):!0]}),o=i.sort(()=>Math.random()>.5?1:-1),s=new Nt;for(let c of o)s.has(c.id)||s.set(c.id,[...c.tags.values()].reduce((u,l)=>u+l.value,0));let a=o.sort((c,u)=>{let l=s.get(c.id)??0,f=s.get(u.id)??0;return l>f?-1:l<f?1:0});Xe("selected %d/%d peers to dial",a.length,i.length);for(let c of a)this.queue.add(async()=>{let u=this.connectionManager.getConnectionsMap().size;if(u>=this.minConnections){Xe("got enough connections now %d/%d",u,this.minConnections),this.queue.clear();return}Xe("connecting to a peerStore stored peer %p",c.id),await this.connectionManager.openConnection(c.id,{priority:this.autoDialPriority})},{peerId:c.id}).catch(u=>{Xe.error("could not connect to peerStore stored peer",u)});this.running=!1,this.started&&(this.autoDialInterval=setTimeout(()=>{this.autoDial().catch(c=>{Xe.error("error while autodialing",c)})},this.autoDialIntervalMs))}};var Fi=W("libp2p:connection-manager:connection-pruner"),z1={maxConnections:300,allow:[]},qa=class{maxConnections;connectionManager;peerStore;allow;events;constructor(e,r={}){this.maxConnections=r.maxConnections??z1.maxConnections,this.allow=r.allow??z1.allow,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,e.events.addEventListener("connection:open",()=>{this.maybePruneConnections().catch(n=>{Fi.error(n)})})}async maybePruneConnections(){let e=this.connectionManager.getConnections(),r=e.length,n=Math.max(r-this.maxConnections,0);if(Fi("checking max connections limit %d/%d",r,this.maxConnections),r<=this.maxConnections)return;Fi("max connections limit exceeded %d/%d, pruning %d connection(s)",r,this.maxConnections,n);let i=new Nt;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"&&Fi.error("error loading peer tags",u)}}}let o=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,d=c.timeline.open;return f<d?1:f>d?-1:0}),s=[];for(let a of o)if(Fi("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(u=>a.remoteAddr.toString().startsWith(u.toString()))||s.push(a),s.length===n)break;await Promise.all(s.map(async a=>{try{await a.close()}catch(c){Fi.error(c)}})),this.events.safeDispatchEvent("connection:prune",{detail:s})}};var ih=z(Hi(),1);function Ki(t){let e=new globalThis.AbortController;function r(){e.abort();for(let o of t)o?.removeEventListener!=null&&o.removeEventListener("abort",r)}for(let o of t){if(o?.aborted===!0){r();break}o?.addEventListener!=null&&o.addEventListener("abort",r)}function n(){for(let o of t)o?.removeEventListener!=null&&o.removeEventListener("abort",r)}let i=e.signal;return i.clear=n,i}function jr(){let t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}var rh=z(Hi(),1);var $1=W("libp2p:connection-manager:utils");async function nh(t,e){if(!t.protoNames().includes("dnsaddr"))return[t];let n=await vR(t,e),s=(await Promise.all(n.map(async a=>nh(a,e)))).flat().reduce((a,c)=>(a.find(u=>u.equals(c))==null&&a.push(c),a),[]);return $1("resolved %s to",t,s.map(a=>a.toString())),s}async function vR(t,e){try{return t=Ue(t.toString()),await t.resolve(e)}catch(r){return $1.error(`multiaddr ${t.toString()} could not be resolved`,r),[]}}function H1(...t){let e=[];for(let n of t)if(n!=null){try{(0,rh.setMaxListeners)?.(1/0,n)}catch{}e.push(n)}let r=Ki(e);try{(0,rh.setMaxListeners)?.(1/0,r)}catch{}return r}var je=W("libp2p:connection-manager:dial-queue"),Wo={addressSorter:Di,maxParallelDials:100,maxPeerAddrsToDial:25,maxParallelDialsPerPeer:10,dialTimeout:3e4,resolvers:{dnsaddr:Ni}},za=class{pendingDials;queue;peerId;peerStore;connectionGater;transportManager;addressSorter;maxPeerAddrsToDial;maxParallelDialsPerPeer;dialTimeout;inProgressDialCount;pendingDialCount;shutDownController;constructor(e,r={}){this.addressSorter=r.addressSorter??Wo.addressSorter,this.maxPeerAddrsToDial=r.maxPeerAddrsToDial??Wo.maxPeerAddrsToDial,this.maxParallelDialsPerPeer=r.maxParallelDialsPerPeer??Wo.maxParallelDialsPerPeer,this.dialTimeout=r.dialTimeout??Wo.dialTimeout,this.peerId=e.peerId,this.peerStore=e.peerStore,this.connectionGater=e.connectionGater,this.transportManager=e.transportManager,this.shutDownController=new AbortController;try{(0,ih.setMaxListeners)?.(1/0,this.shutDownController.signal)}catch{}this.pendingDialCount=e.metrics?.registerMetric("libp2p_dialler_pending_dials"),this.inProgressDialCount=e.metrics?.registerMetric("libp2p_dialler_in_progress_dials"),this.pendingDials=[];for(let[n,i]of Object.entries(r.resolvers??{}))of.set(n,i);this.queue=new Ut({concurrency:r.maxParallelDials??Wo.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=>{je.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}=Fa(e),o=i.map(l=>({multiaddr:l,isCertified:!1})),s=this.createDialAbortControllers(r.signal),a;try{a=await this.calculateMultiaddrs(n,o,{...r,signal:s})}catch(l){throw s.clear(),l}let c=this.pendingDials.find(l=>!!(l.peerId!=null&&n!=null&&l.peerId.equals(n)||a.map(({multiaddr:f})=>f.toString()).join()===l.multiaddrs.map(f=>f.toString()).join()));if(c!=null)return je("joining existing dial target for %p",n),s.clear(),c.promise;je("creating dial target for",a.map(({multiaddr:l})=>l.toString()));let u={id:_R(),status:"queued",peerId:n,multiaddrs:a.map(({multiaddr:l})=>l)};return u.promise=this.performDial(u,{...r,signal:s}).finally(()=>{this.pendingDials=this.pendingDials.filter(l=>l.id!==u.id),s.clear()}).catch(l=>{throw je.error("dial failed to %s",u.multiaddrs.map(f=>f.toString()).join(", "),l),s.aborted?new v(l.message,N.ERR_TIMEOUT):l}),this.pendingDials.push(u),u.promise}createDialAbortControllers(e){let r=Ki([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e]);try{(0,ih.setMaxListeners)?.(1/0,r)}catch{}return r}async calculateMultiaddrs(e,r=[],n={}){if(e!=null){if(this.peerId.equals(e))throw new v("Tried to dial self",N.ERR_DIALED_SELF);if(await this.connectionGater.denyDialPeer?.(e)===!0)throw new v("The dial request is blocked by gater.allowDialPeer",N.ERR_PEER_DIAL_INTERCEPTED);if(r.length===0){je("loading multiaddrs for %p",e);try{let l=await this.peerStore.get(e);r.push(...l.addresses),je("loaded multiaddrs for %p",e,r.map(({multiaddr:f})=>f.toString()))}catch(l){if(l.code!==N.ERR_NOT_FOUND)throw l}}}let i=(await Promise.all(r.map(async l=>{let f=await nh(l.multiaddr,n);return f.length===1&&f[0].equals(l.multiaddr)?l:f.map(d=>({multiaddr:d,isCertified:!1}))}))).flat(),o=i.filter(l=>!!this.transportManager.transportForMultiaddr(l.multiaddr)),s=new Map;for(let l of o){let f=l.multiaddr.toString(),d=s.get(f);if(d!=null){d.isCertified=d.isCertified||l.isCertified||!1;continue}s.set(f,l)}let a=[...s.values()];if((a.length===0||a.length>this.maxPeerAddrsToDial)&&(je("addresses for %p before filtering",e??"unknown peer",i.map(({multiaddr:l})=>l.toString())),je("addresses for %p after filtering",e??"unknown peer",a.map(({multiaddr:l})=>l.toString()))),a.length===0)throw new v("The dial request has no valid addresses",N.ERR_NO_VALID_ADDRESSES);if(a.length>this.maxPeerAddrsToDial)throw new v("dial with more addresses than allowed",N.ERR_TOO_MANY_ADDRESSES);if(e!=null){let l=`/p2p/${e.toString()}`;a=a.map(f=>{let d=f.multiaddr.getPeerId();return f.multiaddr.protos().pop()?.path===!0?f:d!==e.toString()?{multiaddr:f.multiaddr.encapsulate(l),isCertified:f.isCertified}:f})}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 v("The connection gater denied all addresses in the dial request",N.ERR_NO_VALID_ADDRESSES);return u}async performDial(e,r={}){let n=e.multiaddrs.map(()=>new AbortController);try{let i=new Ut({concurrency:this.maxParallelDialsPerPeer});i.on("error",s=>{je.error("error dialling",s)});let o=await Promise.any(e.multiaddrs.map(async(s,a)=>{let c=n[a];if(c==null)throw new v("dialAction did not come with an AbortController",N.ERR_INVALID_PARAMETERS);let u=H1(c.signal,r.signal);u.addEventListener("abort",()=>{je("dial to %a aborted",s)});let l=jr();return await i.add(async()=>{if(u.aborted){je("dial to %a was aborted before reaching the head of the peer dial queue",s),l.reject(new Cr);return}await this.queue.add(async()=>{try{if(u.aborted){je("dial to %a was aborted before reaching the head of the dial queue",s),l.reject(new Cr);return}e.status="active";let f=await this.transportManager.dial(s,{...r,signal:u});if(c.signal.aborted){je("multiple dials succeeded, closing superfluous connection"),f.close().catch(d=>{je.error("error closing superfluous connection",d)}),l.reject(new Cr);return}n[a]=void 0,n.forEach(d=>{d!==void 0&&d.abort()}),je("dial to %a succeeded",s),l.resolve(f)}catch(f){je.error("error during dial of %a",s,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(o==null)throw new v("successful dial led to empty object returned from peer dial queue",N.ERR_TRANSPORT_DIAL_FAILED);return e.status="success",o}catch(i){throw e.status="error",e.multiaddrs.length===1&&i.name==="AggregateError"?i.errors[0]:i}}};function _R(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var xt=W("libp2p:connection-manager"),IR=50,Ln={minConnections:50,maxConnections:300,inboundConnectionThreshold:5,maxIncomingPendingConnections:10,autoDialConcurrency:25,autoDialPriority:0,autoDialMaxQueueLength:100},$a=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;autoDial;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;constructor(e,r={}){this.maxConnections=r.maxConnections??Ln.maxConnections;let n=r.minConnections??Ln.minConnections;if(this.maxConnections<n)throw new v("Connection Manager maxConnections must be greater than minConnections",N.ERR_INVALID_PARAMETERS);this.connections=new Nt,this.started=!1,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,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??Ln.maxIncomingPendingConnections,this.inboundConnectionRateLimiter=new G1.RateLimiterMemory({points:r.inboundConnectionThreshold??Ln.inboundConnectionThreshold,duration:1}),this.autoDial=new Va({connectionManager:this,peerStore:e.peerStore,events:e.events},{minConnections:n,autoDialConcurrency:r.autoDialConcurrency??Ln.autoDialConcurrency,autoDialPriority:r.autoDialPriority??Ln.autoDialPriority,maxQueueLength:r.autoDialMaxQueueLength??Ln.autoDialMaxQueueLength}),this.connectionPruner=new qa({connectionManager:this,peerStore:e.peerStore,events:e.events},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new za({peerId:e.peerId,metrics:e.metrics,peerStore:e.peerStore,transportManager:e.transportManager,connectionGater:e.connectionGater},{addressSorter:r.addressSorter??Di,maxParallelDials:r.maxParallelDials??100,maxPeerAddrsToDial:r.maxPeerAddrsToDial??25,dialTimeout:r.dialTimeout??3e4,resolvers:r.resolvers??{dnsaddr:Ni}})}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 o=`${i.direction} ${i.protocol??"unnegotiated"}`;e[o]=(e[o]??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 o={};for(let s of i.streams){let a=`${s.direction} ${s.protocol??"unnegotiated"}`;o[a]=(o[a]??0)+1}for(let[s,a]of Object.entries(o))e[s]=e[s]??[],e[s].push(a)}let r={};for(let[n,i]of Object.entries(e)){i=i.sort((s,a)=>s-a);let o=Math.floor(i.length*.9);r[n]=i[o]}return r}}),this.autoDial.start(),this.started=!0,xt("started")}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[r=>r.tags.has(Yg)]});await Promise.all(e.map(async r=>{await this.openConnection(r.id).catch(n=>{xt.error(n)})}))}).catch(e=>{xt.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){xt.error(i)}})());xt("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),xt("stopped")}onConnect(e){this._onConnect(e).catch(r=>{xt.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),o=!1;i!=null?i.push(r):(o=!0,this.connections.set(n,[r])),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),o&&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(o=>o.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 v("Not started",N.ERR_NODE_NOT_STARTED);let{peerId:n}=Fa(e);if(n!=null){xt("dial %p",n);let a=this.getConnections(n);if(a.length>0)return xt("had an existing connection to %p",n),a[0]}let i=await this.dialQueue.dial(e,{...r,priority:r.priority??IR}),o=this.connections.get(i.remotePeer);o==null&&(o=[],this.connections.set(i.remotePeer,o));let s=!1;for(let a of o)a.id===i.id&&(s=!0);return s||o.push(i),i}async closeConnections(e){let r=this.connections.get(e)??[];await Promise.all(r.map(async n=>{await n.close()}))}async acceptIncomingConnection(e){if(this.deny.some(i=>e.remoteAddr.toString().startsWith(i.toString())))return xt("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 xt("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 xt("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,i),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(xt("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){return this.dialQueue.pendingDials}};var Ha=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}},Vi=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Ha(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 Ha(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 ch=class extends Error{type;code;constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function Pn(t={}){return RR(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 RR(t,e){e=e??{};let r=e.onEnd,n=new Vi,i,o,s,a=jr(),c=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((y,g)=>{o=x=>{o=null,n.push(x);try{y(t(n))}catch(E){g(E)}return i}}):t(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=jr()})}},u=y=>o!=null?o(y):(n.push(y),i),l=y=>(n=new Vi,o!=null?o({error:y}):(n.push({error:y}),i)),f=y=>{if(s)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})},d=y=>s?i:(s=!0,y!=null?l(y):u({done:!0})),p=()=>(n=new Vi,d(),{done:!0}),h=y=>(d(y),{done:!0});if(i={[Symbol.asyncIterator](){return this},next:c,return:p,throw:h,push:f,end:d,get readableLength(){return n.size},onEmpty:async y=>{let g=y?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let x,E;g!=null&&(x=new Promise((T,I)=>{E=()=>{I(new ch)},g.addEventListener("abort",E)}));try{await Promise.race([a.promise,x])}finally{E!=null&&g!=null&&g?.removeEventListener("abort",E)}}},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}},i}function CR(t){return t[Symbol.asyncIterator]!=null}function TR(...t){let e=[];for(let r of t)CR(r)||e.push(r);return e.length===t.length?function*(){for(let r of e)yield*r}():async function*(){let r=Pn({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 Jr=TR;function Dn(t,...e){if(t==null)throw new Error("Empty pipeline");if(uh(t)){let n=t;t=()=>n.source}else if(W1(t)||Y1(t)){let n=t;t=()=>n}let r=[t,...e];if(r.length>1&&uh(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++)uh(r[n])&&(r[n]=LR(r[n]));return BR(...r)}var BR=(...t)=>{let e;for(;t.length>0;)e=t.shift()(e);return e},Y1=t=>t?.[Symbol.asyncIterator]!=null,W1=t=>t?.[Symbol.iterator]!=null,uh=t=>t==null?!1:t.sink!=null&&t.source!=null,LR=t=>e=>{let r=t.sink(e);if(r?.then!=null){let n=Pn({objectMode:!0});r.then(()=>{n.end()},s=>{n.end(s)});let i,o=t.source;if(Y1(o))i=async function*(){yield*o,n.end()};else if(W1(o))i=function*(){yield*o,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Jr(n,i())}return t.source};function PR(t){return t[Symbol.asyncIterator]!=null}function DR(t,e){if(PR(t))return async function*(){for await(let a of t)yield e(a)}();let r=Ba(t),{value:n,done:i}=r.next();if(i===!0)return function*(){}();let o=e(n);if(typeof o.then=="function")return async function*(){yield await o;for await(let a of r)yield e(a)}();let s=e;return function*(){yield o;for(let a of r)yield s(a)}()}var Q1=DR;async function*Qo(t,e){yield*Q1(t,async r=>(await e.merge(r.id,{multiaddrs:r.multiaddrs}),r))}function Ga(t){let e=new Set;return Ft(t,r=>e.has(r.id.toString())?!1:(e.add(r.id.toString()),!0))}async function*Ya(t,e=1){let r=0;for await(let n of t)r++,yield n;if(r<e)throw new v(`more peers required, seen: ${r} min: ${e}`,"NOT_FOUND")}var Wa=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 v("No content routers available",N.ERR_NO_ROUTERS_AVAILABLE);yield*Dn(Jr(...this.routers.map(n=>n.findProviders(e,r))),n=>Qo(n,this.components.peerStore),n=>Ga(n),n=>Ya(n))}async provide(e,r={}){if(this.routers.length===0)throw new v("No content routers available",N.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 v(or.NOT_STARTED_YET,N.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 v(or.NOT_STARTED_YET,N.DHT_NOT_STARTED);return Promise.any(this.routers.map(async n=>n.get(e,r)))}};function NR(t){return t[Symbol.asyncIterator]!=null}function kR(t){if(NR(t))return(async()=>{for await(let e of t)return e})();for(let e of t)return e}var Qa=kR;var OR=W("libp2p:peer-routing"),Xa=class{components;routers;constructor(e,r){this.components=e,this.routers=r.routers??[]}async findPeer(e,r){if(this.routers.length===0)throw new v("No peer routers available",N.ERR_NO_ROUTERS_AVAILABLE);if(e.toString()===this.components.peerId.toString())throw new v("Should not try to find self",N.ERR_FIND_SELF);let n=await Dn(Jr(...this.routers.map(i=>async function*(){try{yield await i.findPeer(e,r)}catch(o){OR.error(o)}}())),i=>Ft(i,Boolean),i=>Qo(i,this.components.peerStore),async i=>Qa(i));if(n!=null)return n;throw new v(or.NOT_FOUND,N.ERR_NOT_FOUND)}async*getClosestPeers(e,r){if(this.routers.length===0)throw new v("No peer routers available",N.ERR_NO_ROUTERS_AVAILABLE);yield*Dn(Jr(...this.routers.map(n=>n.getClosestPeers(e,r))),n=>Qo(n,this.components.peerStore),n=>Ga(n),n=>Ya(n))}};var lh=W("libp2p:registrar"),fh=32,hh=64,Za=class{topologies;handlers;components;constructor(e){this.topologies=new Map,this.handlers=new Map,this.components=e,this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onConnect=this._onConnect.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:connect",this._onConnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate)}getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let r=this.handlers.get(e);if(r==null)throw new v(`No handler registered for protocol ${e}`,N.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 v(`Handler already registered for protocol ${e}`,N.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);let i=qr.bind({ignoreUndefined:!0})({maxInboundStreams:fh,maxOutboundStreams:hh},n);this.handlers.set(e,{handler:r,options:i}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]})}async unhandle(e){let r=Array.isArray(e)?e:[e];r.forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:r})}async register(e,r){if(r==null)throw new v("invalid topology",N.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 o=this.topologies.get(i);if(o!=null)for(let s of o.values())s.onDisconnect?.(r)}}).catch(n=>{n.code!==N.ERR_NOT_FOUND&&lh.error("could not inform topologies of disconnecting peer %p",r,n)})}_onConnect(e){let r=e.detail;this.components.peerStore.get(r).then(n=>{let i=this.components.connectionManager.getConnections(n.id)[0];if(i==null){lh("peer %p connected but the connection manager did not have a connection",n);return}for(let o of n.protocols){let s=this.topologies.get(o);if(s!=null)for(let a of s.values())a.onConnect?.(r,i)}}).catch(n=>{n.code!==N.ERR_NOT_FOUND&&lh.error("could not inform topologies of connecting peer %p",r,n)})}_onPeerUpdate(e){let{peer:r,previous:n}=e.detail,i=(n?.protocols??[]).filter(s=>!r.protocols.includes(s)),o=r.protocols.filter(s=>!(n?.protocols??[]).includes(s));for(let s of i){let a=this.topologies.get(s);if(a!=null)for(let c of a.values())c.onDisconnect?.(r.id)}for(let s of o){let a=this.topologies.get(s);if(a!=null)for(let c of a.values()){let u=this.components.connectionManager.getConnections(r.id)[0];u!=null&&c.onConnect?.(r.id,u)}}}};var dh=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 X1(t){let{name:e,metrics:r}=t,n;return r!=null?n=new dh({name:e,metrics:r}):n=new Map,n}var Nn=W("libp2p:transports"),ja=class{components;transports;listeners;faultTolerance;started;constructor(e,r={}){this.components=e,this.started=!1,this.transports=new Map,this.listeners=X1({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=r.faultTolerance??Xr.FATAL_ALL}add(e){let r=e[Symbol.toStringTag];if(r==null)throw new v("Transport must have a valid tag",N.ERR_INVALID_KEY);if(this.transports.has(r))throw new v(`There is already a transport with the tag ${r}`,N.ERR_DUPLICATE_TRANSPORT);Nn("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(Nn("closing listeners for %s",r);n.length>0;){let i=n.pop();i!=null&&e.push(i.close())}await Promise.all(e),Nn("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 v(`No transport available for address ${String(e)}`,N.ERR_TRANSPORT_UNAVAILABLE);try{return await n.dial(e,{...r,upgrader:this.components.upgrader})}catch(i){throw i.code==null&&(i.code=N.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(e==null||e.length===0){Nn("no addresses were provided for listening, this node is dial only");return}let r=[];for(let[n,i]of this.transports.entries()){let o=i.filter(e),s=[];for(let u of o){Nn("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 d=f.findIndex(p=>p===l);f.splice(d,1),this.components.events.safeDispatchEvent("transport:close",{detail:l})}),s.push(l.listen(u))}if(s.length===0){r.push(n);continue}if((await Promise.allSettled(s)).find(u=>u.status==="fulfilled")==null&&this.faultTolerance!==Xr.NO_FATAL)throw new v(`Transport (${n}) could not listen on any available address`,N.ERR_NO_VALID_ADDRESSES)}if(r.length===this.transports.size){let n=`no valid addresses were provided for transports [${r.join(", ")}]`;if(this.faultTolerance===Xr.FATAL_ALL)throw new v(n,N.ERR_NO_VALID_ADDRESSES);Nn(`libp2p in dial mode only: ${n}`)}}async remove(e){Nn("removing %s",e);for(let r of this.listeners.get(e)??[])await r.close();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 xh=z(Hi(),1);var _r="/multistream/1.0.0";function ph(t){let e=async function*(){let r=yield,n=new Te;for await(let i of t){if(r==null){n.append(i),r=yield n,n=new Te;continue}for(n.append(i);n.length>=r;){let o=n.sublist(0,r);if(n.consume(r),r=yield o,r==null){n.length>0&&(r=yield n,n=new Te);break}}}if(r!=null)throw Object.assign(new Error(`stream ended before ${r} bytes became available`),{code:"ERR_UNDER_READ",buffer:n})}();return e.next(),e}function Ja(t){let e=Pn(),r=ph(t.source),n=jr(),i,o=t.sink(async function*(){yield*e,yield*await n.promise}());return o.catch(a=>{i=a}),{reader:r,writer:e,stream:{sink:async a=>{if(i!=null){await Promise.reject(i);return}n.resolve(a),await o},source:r},rest:()=>e.end(),write:e.push,read:async()=>{let a=await r.next();if(a.value!=null)return a.value}}}var Xo=class extends Error{constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function Z1(t){if(t!=null){if(typeof t[Symbol.iterator]=="function")return t[Symbol.iterator]();if(typeof t[Symbol.asyncIterator]=="function")return t[Symbol.asyncIterator]();if(typeof t.next=="function")return t}throw new Error("argument is not an iterator or iterable")}function ec(t,e,r){let n=r??{},i=Z1(t);async function*o(){let s,a=()=>{s?.()};for(e.addEventListener("abort",a);;){let c;try{if(e.aborted){let{abortMessage:l,abortCode:f}=n;throw new Xo(l,f)}let u=new Promise((l,f)=>{s=()=>{let{abortMessage:d,abortCode:p}=n;f(new Xo(d,p))}});c=await Promise.race([u,i.next()]),s=null}catch(u){e.removeEventListener("abort",a);let l=u.type==="aborted"&&e.aborted;if(l&&n.onAbort!=null&&n.onAbort(t),typeof i.return=="function")try{let f=i.return();f instanceof Promise&&f.catch(d=>{n.onReturnError!=null&&n.onReturnError(d)})}catch(f){n.onReturnError!=null&&n.onReturnError(f)}if(l&&n.returnOnAbort===!0)return;throw u}if(c.done===!0)break;yield c.value}e.removeEventListener("abort",a)}return o()}function MR(t,e,r){return n=>t(ec(n,e,r))}function j1(t,e,r){return{sink:MR(t.sink,e,{...r,onAbort:void 0}),source:ec(t.source,e,r)}}function tc(t){return t[Symbol.asyncIterator]!=null}var rc=t=>{let e=Ot.encodingLength(t),r=Ct(e);return Ot.encode(t,r),rc.bytes=e,r};rc.bytes=0;function nc(t,e){e=e??{};let r=e.lengthEncoder??rc;function*n(i){let o=r(i.byteLength);o instanceof Uint8Array?yield o:yield*o,i instanceof Uint8Array?yield i:yield*i}return tc(t)?async function*(){for await(let i of t)yield*n(i)}():function*(){for(let i of t)yield*n(i)}()}nc.single=(t,e)=>{e=e??{};let r=e.lengthEncoder??rc;return new Te(r(t.byteLength),t)};var qi=z(Cf(),1);var UR=8,FR=1024*1024*4,kn;(function(t){t[t.LENGTH=0]="LENGTH",t[t.DATA=1]="DATA"})(kn||(kn={}));var mh=t=>{let e=Ot.decode(t);return mh.bytes=Ot.encodingLength(e),e};mh.bytes=0;function Zo(t,e){let r=new Te,n=kn.LENGTH,i=-1,o=e?.lengthDecoder??mh,s=e?.maxLengthLength??UR,a=e?.maxDataLength??FR;function*c(){for(;r.byteLength>0;){if(n===kn.LENGTH)try{if(i=o(r),i<0)throw(0,qi.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(i>a)throw(0,qi.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let u=o.bytes;r.consume(u),e?.onLength!=null&&e.onLength(i),n=kn.DATA}catch(u){if(u instanceof RangeError){if(r.byteLength>s)throw(0,qi.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw u}if(n===kn.DATA){if(r.byteLength<i)break;let u=r.sublist(0,i);r.consume(i),e?.onData!=null&&e.onData(u),yield u,n=kn.LENGTH}}}return tc(t)?async function*(){for await(let u of t)r.append(u),yield*c();if(r.byteLength>0)throw(0,qi.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,qi.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}Zo.fromReader=(t,e)=>{let r=1,n=async function*(){for(;;)try{let{done:o,value:s}=await t.next(r);if(o===!0)return;s!=null&&(yield s)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{r=1}}();return Zo(n,{...e??{},onLength:o=>{r=o}})};var qR=W("libp2p:mss"),J1=V(`
|
|
49
|
+
`);function jo(t){let e=new Te(t,J1);return nc.single(e)}function On(t,e,r={}){let n=jo(e);r.writeBytes===!0?t.push(n.subarray()):t.push(n)}function ex(t,e,r={}){let n=new Te;for(let i of e)n.append(jo(i));r.writeBytes===!0?t.push(n.subarray()):t.push(n)}async function zR(t,e){let r=1,n={[Symbol.asyncIterator]:()=>n,next:async()=>t.next(r)},i=n;e?.signal!=null&&(i=ec(n,e.signal));let o=a=>{r=a},s=await Dn(i,a=>Zo(a,{onLength:o,maxDataLength:1024}),async a=>Qa(a));if(s==null||s.length===0)throw new v("no buffer returned","ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");if(s.get(s.byteLength-1)!==J1[0])throw qR.error("Invalid mss message - missing newline - %s",s.subarray()),new v("missing newline","ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");return s.sublist(0,-1)}async function zi(t,e){let r=await zR(t,e);return G(r.subarray())}var Jo=W("libp2p:mss:select");async function es(t,e,r={}){e=Array.isArray(e)?[...e]:[e];let{reader:n,writer:i,rest:o,stream:s}=Ja(t),a=e.shift();if(a==null)throw new Error("At least one protocol must be specified");Jo.trace('select: write ["%s", "%s"]',_r,a);let c=V(_r),u=V(a);ex(i,[c,u],r);let l=await zi(n,r);if(Jo.trace('select: read "%s"',l),l===_r&&(l=await zi(n,r),Jo.trace('select: read "%s"',l)),l===a)return o(),{stream:s,protocol:a};for(let f of e){Jo.trace('select: write "%s"',f),On(i,V(f),r);let d=await zi(n,r);if(Jo.trace('select: read "%s" for "%s"',d,f),d===f)return o(),{stream:s,protocol:f}}throw o(),new v("protocol selection failed","ERR_UNSUPPORTED_PROTOCOL")}var ts=W("libp2p:mss:handle");async function rs(t,e,r){e=Array.isArray(e)?e:[e];let{writer:n,reader:i,rest:o,stream:s}=Ja(t);for(;;){let a=await zi(i,r);if(ts.trace('read "%s"',a),a===_r){ts.trace('respond with "%s" for "%s"',_r,a),On(n,V(_r),r);continue}if(e.includes(a))return On(n,V(a),r),ts.trace('respond with "%s" for "%s"',a,a),o(),{stream:s,protocol:a};if(a==="ls"){On(n,new Te(...e.map(c=>jo(V(c)))),r),ts.trace('respond with "%s" for %s',e,a);continue}On(n,V("na"),r),ts('respond with "na" for "%s"',a)}}var rx=Symbol.for("@libp2p/connection");var nx="OPEN",yh="CLOSING",ic="CLOSED";var HR=W("libp2p:connection"),gh=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;tags;_newStream;_close;_getStreams;_closing;constructor(e){let{remoteAddr:r,remotePeer:n,newStream:i,close:o,getStreams:s}=e;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=r,this.remotePeer=n,this.direction=e.direction,this.status=nx,this.timeline=e.timeline,this.multiplexer=e.multiplexer,this.encryption=e.encryption,this._newStream=i,this._close=o,this._getStreams=s,this.tags=[],this._closing=!1}[Symbol.toStringTag]="Connection";[rx]=!0;get streams(){return this._getStreams()}async newStream(e,r){if(this.status===yh)throw new v("the connection is being closed","ERR_CONNECTION_BEING_CLOSED");if(this.status===ic)throw new v("the connection is closed","ERR_CONNECTION_CLOSED");Array.isArray(e)||(e=[e]);let n=await this._newStream(e,r);return n.direction="outbound",n}addStream(e){e.direction="inbound"}removeStream(e){}async close(){if(!(this.status===ic||this._closing)){this.status=yh;try{this.streams.forEach(e=>{e.close()})}catch(e){HR.error(e)}this._closing=!0,await this._close(),this._closing=!1,this.timeline.close=Date.now(),this.status=ic}}};function ix(t){return new gh(t)}var ve=W("libp2p:upgrader");function YR(t,e){try{let{options:r}=e.getHandler(t);return r.maxInboundStreams}catch(r){if(r.code!==N.ERR_NO_HANDLER_FOR_PROTOCOL)throw r}return fh}function WR(t,e,r={}){try{let{options:n}=e.getHandler(t);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.code!==N.ERR_NO_HANDLER_FOR_PROTOCOL)throw n}return r.maxOutboundStreams??hh}function ox(t,e,r){let n=0;return r.streams.forEach(i=>{i.direction===e&&i.protocol===t&&n++}),n}var oc=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 v(`The multiaddr connection is blocked by gater.${n}`,N.ERR_CONNECTION_INTERCEPTED)}async upgradeInbound(e,r){if(!await this.components.connectionManager.acceptIncomingConnection(e))throw new v("connection denied",N.ERR_CONNECTION_DENIED);let i,o,s,a,c,u=Ki([AbortSignal.timeout(this.inboundUpgradeTimeout)]);try{(0,xh.setMaxListeners)?.(1/0,u)}catch{}try{let l=j1(e,u);if(e.source=l.source,e.sink=l.sink,await this.components.connectionGater.denyInboundConnection?.(e)===!0)throw new v("The multiaddr connection is blocked by gater.acceptConnection",N.ERR_CONNECTION_INTERCEPTED);this.components.metrics?.trackMultiaddrConnection(e),ve("starting the inbound connection upgrade");let f=e;if(r?.skipProtection!==!0){let d=this.components.connectionProtector;d!=null&&(ve("protecting the inbound connection"),f=await d.protect(e))}try{if(i=f,r?.skipEncryption!==!0){({conn:i,remotePeer:o,protocol:c}=await this._encryptInbound(f));let d={...f,...i};await this.shouldBlockConnection(o,d,"denyInboundEncryptedConnection")}else{let d=e.remoteAddr.getPeerId();if(d==null)throw new v("inbound connection that skipped encryption must have a peer id",N.ERR_INVALID_MULTIADDR);let p=oe(d);c="native",o=p}if(s=i,r?.muxerFactory!=null)a=r.muxerFactory;else if(this.muxers.size>0){let d=await this._multiplexInbound({...f,...i},this.muxers);a=d.muxerFactory,s=d.stream}}catch(d){throw ve.error("Failed to upgrade inbound connection",d),d}return await this.shouldBlockConnection(o,e,"denyInboundUpgradedConnection"),ve("Successfully upgraded inbound connection"),this._createConnection({cryptoProtocol:c,direction:"inbound",maConn:e,upgradedConn:s,muxerFactory:a,remotePeer:o})}finally{this.components.connectionManager.afterUpgradeInbound(),u.clear()}}async upgradeOutbound(e,r){let n=e.remoteAddr.getPeerId(),i;n!=null&&(i=oe(n),await this.shouldBlockConnection(i,e,"denyOutboundConnection"));let o,s,a,c,u;this.components.metrics?.trackMultiaddrConnection(e),ve("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(o=l,r?.skipEncryption!==!0){({conn:o,remotePeer:s,protocol:c}=await this._encryptOutbound(l,i));let f={...l,...o};await this.shouldBlockConnection(s,f,"denyOutboundEncryptedConnection")}else{if(i==null)throw new v("Encryption was skipped but no peer id was passed",N.ERR_INVALID_PEER);c="native",s=i}if(a=o,r?.muxerFactory!=null)u=r.muxerFactory;else if(this.muxers.size>0){let f=await this._multiplexOutbound({...l,...o},this.muxers);u=f.muxerFactory,a=f.stream}}catch(f){throw ve.error("Failed to upgrade outbound connection",f),await e.close(f),f}return await this.shouldBlockConnection(s,e,"denyOutboundUpgradedConnection"),ve("Successfully upgraded outbound connection"),this._createConnection({cryptoProtocol:c,direction:"outbound",maConn:e,upgradedConn:a,muxerFactory:u,remotePeer:s})}_createConnection(e){let{cryptoProtocol:r,direction:n,maConn:i,upgradedConn:o,remotePeer:s,muxerFactory:a}=e,c,u,l;a!=null&&(c=a.createStreamMuxer({direction:n,onIncomingStream:p=>{l!=null&&Promise.resolve().then(async()=>{let h=this.components.registrar.getProtocols(),{stream:m,protocol:y}=await rs(p,h);if(ve("%s: incoming stream opened on %s",n,y),l==null)return;let g=YR(y,this.components.registrar);if(ox(y,"inbound",l)===g){let E=new v(`Too many inbound protocol streams for protocol "${y}" - limit ${g}`,N.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS);throw p.abort(E),E}p.source=m.source,p.sink=m.sink,p.protocol=y,await this.components.peerStore.merge(s,{protocols:[y]}),l.addStream(p),this.components.metrics?.trackProtocolStream(p,l),this._onStream({connection:l,stream:p,protocol:y})}).catch(h=>{ve.error(h),p.timeline.close==null&&p.close()})},onStreamEnd:p=>{l?.removeStream(p.id)}}),u=async(p,h={})=>{if(c==null)throw new v("Stream is not multiplexed",N.ERR_MUXER_UNAVAILABLE);ve("%s: starting new stream on %s",n,p);let m=await c.newStream();try{if(h.signal==null){ve("No abort signal was passed while trying to negotiate protocols %s falling back to default timeout",p),h.signal=AbortSignal.timeout(3e4);try{(0,xh.setMaxListeners)?.(1/0,h.signal)}catch{}}let{stream:y,protocol:g}=await es(m,p,h),x=WR(g,this.components.registrar,h);if(ox(g,"outbound",l)>=x){let T=new v(`Too many outbound protocol streams for protocol "${g}" - limit ${x}`,N.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);throw m.abort(T),T}return await this.components.peerStore.merge(s,{protocols:[g]}),m.source=y.source,m.sink=y.sink,m.protocol=g,this.components.metrics?.trackProtocolStream(m,l),m}catch(y){throw ve.error("could not create new stream",y),m.timeline.close==null&&m.close(),y.code!=null?y:new v(String(y),N.ERR_UNSUPPORTED_PROTOCOL)}},Promise.all([c.sink(o.source),o.sink(c.source)]).catch(p=>{ve.error(p)}));let f=i.timeline;i.timeline=new Proxy(f,{set:(...p)=>(l!=null&&p[1]==="close"&&p[2]!=null&&f.close==null&&(async()=>{try{l.status==="OPEN"&&await l.close()}catch(h){ve.error(h)}finally{this.events.safeDispatchEvent("connection:close",{detail:l})}})().catch(h=>{ve.error(h)}),Reflect.set(...p))}),i.timeline.upgraded=Date.now();let d=()=>{throw new v("connection is not multiplexed",N.ERR_CONNECTION_NOT_MULTIPLEXED)};return l=ix({remoteAddr:i.remoteAddr,remotePeer:s,status:"OPEN",direction:n,timeline:i.timeline,multiplexer:c?.protocol,encryption:r,newStream:u??d,getStreams:()=>c!=null?c.streams:d(),close:async()=>{await i.close(),c?.close()}}),this.events.safeDispatchEvent("connection:open",{detail:l}),l}_onStream(e){let{connection:r,stream:n,protocol:i}=e,{handler:o}=this.components.registrar.getHandler(i);o({connection:r,stream:n})}async _encryptInbound(e){let r=Array.from(this.connectionEncryption.keys());ve("handling inbound crypto protocol selection",r);try{let{stream:n,protocol:i}=await rs(e,r,{writeBytes:!0}),o=this.connectionEncryption.get(i);if(o==null)throw new Error(`no crypto module found for ${i}`);return ve("encrypting inbound connection..."),{...await o.secureInbound(this.components.peerId,n),protocol:i}}catch(n){throw new v(String(n),N.ERR_ENCRYPTION_FAILED)}}async _encryptOutbound(e,r){let n=Array.from(this.connectionEncryption.keys());ve("selecting outbound crypto protocol",n);try{let{stream:i,protocol:o}=await es(e,n,{writeBytes:!0}),s=this.connectionEncryption.get(o);if(s==null)throw new Error(`no crypto module found for ${o}`);return ve("encrypting outbound connection to %p",r),{...await s.secureOutbound(this.components.peerId,i,r),protocol:o}}catch(i){throw new v(String(i),N.ERR_ENCRYPTION_FAILED)}}async _multiplexOutbound(e,r){let n=Array.from(r.keys());ve("outbound selecting muxer %s",n);try{let{stream:i,protocol:o}=await es(e,n,{writeBytes:!0});ve("%s selected as muxer protocol",o);let s=r.get(o);return{stream:i,muxerFactory:s}}catch(i){throw ve.error("error multiplexing outbound stream",i),new v(String(i),N.ERR_MUXER_UNAVAILABLE)}}async _multiplexInbound(e,r){let n=Array.from(r.keys());ve("inbound handling muxers %s",n);try{let{stream:i,protocol:o}=await rs(e,n,{writeBytes:!0}),s=r.get(o);return{stream:i,muxerFactory:s}}catch(i){throw ve.error("error multiplexing inbound stream",i),new v(String(i),N.ERR_MUXER_UNAVAILABLE)}}};var ct=W("libp2p"),wh=class extends So{peerId;peerStore;contentRouting;peerRouting;keychain;metrics;services;components;#e;constructor(e){super();let r=new So,n=r.dispatchEvent.bind(r);r.dispatchEvent=c=>{let u=n(c),l=this.dispatchEvent(new nl(c.type,{detail:c.detail}));return u||l};try{(0,sx.setMaxListeners)?.(1/0,r)}catch{}this.#e=!1,this.peerId=e.peerId,this.services={};let i=this.components=Rg({peerId:e.peerId,events:r,datastore:e.datastore??new Pa,connectionGater:Mg(e.connectionGater)});this.peerStore=this.configureComponent("peerStore",new Ta(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",c=>{c.detail.previous==null&&this.safeDispatchEvent("peer:discovery",{detail:c.detail.peer})}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new oc(this.components,{connectionEncryption:(e.connectionEncryption??[]).map((c,u)=>this.configureComponent(`connection-encryption-${u}`,c(this.components))),muxers:(e.streamMuxers??[]).map((c,u)=>this.configureComponent(`stream-muxers-${u}`,c(this.components))),inboundUpgradeTimeout:e.connectionManager.inboundUpgradeTimeout}),this.configureComponent("transportManager",new ja(this.components,e.transportManager)),this.configureComponent("connectionManager",new $a(this.components,e.connectionManager)),this.configureComponent("registrar",new Za(this.components)),this.configureComponent("addressManager",new Da(this.components,e.addresses));let o=An.generateOptions();this.keychain=this.configureComponent("keyChain",new An(this.components,{...o,...e.keychain}));let s=(e.peerRouters??[]).map((c,u)=>this.configureComponent(`peer-router-${u}`,c(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new Xa(this.components,{routers:s}));let a=(e.contentRouters??[]).map((c,u)=>this.configureComponent(`content-router-${u}`,c(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new Wa(this.components,{routers:a})),(e.peerDiscovery??[]).forEach((c,u)=>{this.configureComponent(`peer-discovery-${u}`,c(this.components)).addEventListener("peer",f=>{this.#t(f)})}),e.transports.forEach((c,u)=>{this.components.transportManager.add(this.configureComponent(`transport-${u}`,c(this.components)))}),e.services!=null)for(let c of Object.keys(e.services)){let u=e.services[c],l=u(this.components);if(l==null){ct.error("service factory %s returned null or undefined instance",c);continue}this.services[c]=l,this.configureComponent(c,l),l[tl]!=null&&(ct("registering service %s for content routing",c),a.push(l[tl])),l[ol]!=null&&(ct("registering service %s for peer routing",c),s.push(l[ol])),l[il]!=null&&(ct("registering service %s for peer discovery",c),l[il].addEventListener("peer",f=>{this.#t(f)}))}}configureComponent(e,r){return r==null&&ct.error("component %s was null or undefined",e),this.components[e]=r,r}async start(){if(this.#e)return;this.#e=!0,ct("libp2p is starting"),(await this.keychain.listKeys()).find(r=>r.name==="self")==null&&(ct("importing self key into keychain"),await this.keychain.importPeer("self",this.components.peerId));try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.safeDispatchEvent("start",{detail:this}),ct("libp2p has started")}catch(r){throw ct.error("An error occurred starting libp2p",r),await this.stop(),r}}async stop(){this.#e&&(ct("libp2p is stopping"),this.#e=!1,await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.safeDispatchEvent("stop",{detail:this}),ct("libp2p has stopped"))}isStarted(){return this.#e}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new kt;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 v("no protocols were provided to open a stream",N.ERR_INVALID_PROTOCOLS_FOR_STREAM);if(r=Array.isArray(r)?r:[r],r.length===0)throw new v("no protocols were provided to open a stream",N.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){Rn(e)&&(e=oe(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e)}async getPublicKey(e,r={}){if(ct("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=Pe([V("/pk/"),e.multihash.digest]),o=await this.contentRouting.get(i,r);return Eo(o),await this.peerStore.patch(e,{publicKey:o}),o}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)}#t(e){let{detail:r}=e;if(r.id.toString()===this.peerId.toString()){ct.error(new Error(N.ERR_DISCOVERED_SELF));return}this.components.peerStore.merge(r.id,{multiaddrs:r.multiaddrs,protocols:r.protocols}).catch(n=>{ct.error(n)})}};async function ax(t){if(t.peerId==null){let e=t.datastore;if(e!=null)try{let r=new An({datastore:e},qr(An.generateOptions(),t.keychain));t.peerId=await r.exportPeerId("self")}catch(r){if(r.code!=="ERR_NOT_FOUND")throw r}}return t.peerId==null&&(t.peerId=await ty()),new wh(Gg(t))}async function QR(t){let e=await ax(t);return t.start!==!1&&await e.start(),e}return px(XR);})();
|
|
50
50
|
/*! Bundled license information:
|
|
51
51
|
|
|
52
52
|
@noble/ed25519/lib/esm/index.js:
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { symbol } from '@libp2p/interface/connection';
|
|
1
|
+
import { type Direction, symbol, type Connection, type Stream, type ConnectionTimeline } from '@libp2p/interface/connection';
|
|
2
2
|
import type { AbortOptions } from '@libp2p/interface';
|
|
3
|
-
import type
|
|
3
|
+
import type * as Status from '@libp2p/interface/connection/status';
|
|
4
4
|
import type { PeerId } from '@libp2p/interface/peer-id';
|
|
5
5
|
import type { Multiaddr } from '@multiformats/multiaddr';
|
|
6
6
|
interface ConnectionInit {
|
|
@@ -9,7 +9,11 @@ interface ConnectionInit {
|
|
|
9
9
|
newStream: (protocols: string[], options?: AbortOptions) => Promise<Stream>;
|
|
10
10
|
close: () => Promise<void>;
|
|
11
11
|
getStreams: () => Stream[];
|
|
12
|
-
|
|
12
|
+
status: keyof typeof Status;
|
|
13
|
+
direction: Direction;
|
|
14
|
+
timeline: ConnectionTimeline;
|
|
15
|
+
multiplexer?: string;
|
|
16
|
+
encryption?: string;
|
|
13
17
|
}
|
|
14
18
|
/**
|
|
15
19
|
* An implementation of the js-libp2p connection.
|
|
@@ -28,10 +32,11 @@ export declare class ConnectionImpl implements Connection {
|
|
|
28
32
|
* Remote peer id
|
|
29
33
|
*/
|
|
30
34
|
readonly remotePeer: PeerId;
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
+
direction: Direction;
|
|
36
|
+
timeline: ConnectionTimeline;
|
|
37
|
+
multiplexer?: string;
|
|
38
|
+
encryption?: string;
|
|
39
|
+
status: keyof typeof Status;
|
|
35
40
|
/**
|
|
36
41
|
* User provided tags
|
|
37
42
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/connection/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,8BAA8B,CAAA;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/connection/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,SAAS,EAAE,MAAM,EAAE,KAAK,UAAU,EAAE,KAAK,MAAM,EAAE,KAAK,kBAAkB,EAAE,MAAM,8BAA8B,CAAA;AAI5H,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAA;AACrD,OAAO,KAAK,KAAK,MAAM,MAAM,qCAAqC,CAAA;AAClE,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,2BAA2B,CAAA;AACvD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAA;AAIxD,UAAU,cAAc;IACtB,UAAU,EAAE,SAAS,CAAA;IACrB,UAAU,EAAE,MAAM,CAAA;IAClB,SAAS,EAAE,CAAC,SAAS,EAAE,MAAM,EAAE,EAAE,OAAO,CAAC,EAAE,YAAY,KAAK,OAAO,CAAC,MAAM,CAAC,CAAA;IAC3E,KAAK,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAA;IAC1B,UAAU,EAAE,MAAM,MAAM,EAAE,CAAA;IAC1B,MAAM,EAAE,MAAM,OAAO,MAAM,CAAA;IAC3B,SAAS,EAAE,SAAS,CAAA;IACpB,QAAQ,EAAE,kBAAkB,CAAA;IAC5B,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,UAAU,CAAC,EAAE,MAAM,CAAA;CACpB;AAED;;;GAGG;AACH,qBAAa,cAAe,YAAW,UAAU;IAC/C;;OAEG;IACH,SAAgB,EAAE,EAAE,MAAM,CAAA;IAE1B;;OAEG;IACH,SAAgB,UAAU,EAAE,SAAS,CAAA;IAErC;;OAEG;IACH,SAAgB,UAAU,EAAE,MAAM,CAAA;IAE3B,SAAS,EAAE,SAAS,CAAA;IACpB,QAAQ,EAAE,kBAAkB,CAAA;IAC5B,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,MAAM,EAAE,MAAM,OAAO,MAAM,CAAA;IAElC;;;OAGG;IACI,IAAI,EAAE,MAAM,EAAE,CAAA;IAErB;;OAEG;IACH,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAkE;IAE7F;;OAEG;IACH,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAqB;IAE5C;;OAEG;IACH,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAgB;IAE5C,OAAO,CAAC,QAAQ,CAAS;IAEzB;;;OAGG;gBACU,IAAI,EAAE,cAAc;IAmBjC,QAAQ,CAAC,CAAC,MAAM,CAAC,WAAW,CAAC,gBAAe;IAE5C,QAAQ,CAAC,CAAC,MAAM,CAAC,QAAO;IAExB;;OAEG;IACH,IAAI,OAAO,IAAK,MAAM,EAAE,CAEvB;IAED;;OAEG;IACG,SAAS,CAAE,SAAS,EAAE,MAAM,GAAG,MAAM,EAAE,EAAE,OAAO,CAAC,EAAE,YAAY,GAAG,OAAO,CAAC,MAAM,CAAC;IAoBvF;;OAEG;IACH,SAAS,CAAE,MAAM,EAAE,MAAM,GAAG,IAAI;IAIhC;;OAEG;IACH,YAAY,CAAE,EAAE,EAAE,MAAM,GAAG,IAAI;IAI/B;;OAEG;IACG,KAAK,IAAK,OAAO,CAAC,IAAI,CAAC;CAsB9B;AAED,wBAAgB,gBAAgB,CAAE,IAAI,EAAE,cAAc,GAAG,UAAU,CAElE"}
|
|
@@ -20,10 +20,11 @@ export class ConnectionImpl {
|
|
|
20
20
|
* Remote peer id
|
|
21
21
|
*/
|
|
22
22
|
remotePeer;
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
23
|
+
direction;
|
|
24
|
+
timeline;
|
|
25
|
+
multiplexer;
|
|
26
|
+
encryption;
|
|
27
|
+
status;
|
|
27
28
|
/**
|
|
28
29
|
* User provided tags
|
|
29
30
|
*
|
|
@@ -47,14 +48,15 @@ export class ConnectionImpl {
|
|
|
47
48
|
* Any libp2p transport should use an upgrader to return this connection.
|
|
48
49
|
*/
|
|
49
50
|
constructor(init) {
|
|
50
|
-
const { remoteAddr, remotePeer, newStream, close, getStreams
|
|
51
|
+
const { remoteAddr, remotePeer, newStream, close, getStreams } = init;
|
|
51
52
|
this.id = `${(parseInt(String(Math.random() * 1e9))).toString(36)}${Date.now()}`;
|
|
52
53
|
this.remoteAddr = remoteAddr;
|
|
53
54
|
this.remotePeer = remotePeer;
|
|
54
|
-
this.
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
55
|
+
this.direction = init.direction;
|
|
56
|
+
this.status = OPEN;
|
|
57
|
+
this.timeline = init.timeline;
|
|
58
|
+
this.multiplexer = init.multiplexer;
|
|
59
|
+
this.encryption = init.encryption;
|
|
58
60
|
this._newStream = newStream;
|
|
59
61
|
this._close = close;
|
|
60
62
|
this._getStreams = getStreams;
|
|
@@ -73,24 +75,24 @@ export class ConnectionImpl {
|
|
|
73
75
|
* Create a new stream from this connection
|
|
74
76
|
*/
|
|
75
77
|
async newStream(protocols, options) {
|
|
76
|
-
if (this.
|
|
78
|
+
if (this.status === CLOSING) {
|
|
77
79
|
throw new CodeError('the connection is being closed', 'ERR_CONNECTION_BEING_CLOSED');
|
|
78
80
|
}
|
|
79
|
-
if (this.
|
|
81
|
+
if (this.status === CLOSED) {
|
|
80
82
|
throw new CodeError('the connection is closed', 'ERR_CONNECTION_CLOSED');
|
|
81
83
|
}
|
|
82
84
|
if (!Array.isArray(protocols)) {
|
|
83
85
|
protocols = [protocols];
|
|
84
86
|
}
|
|
85
87
|
const stream = await this._newStream(protocols, options);
|
|
86
|
-
stream.
|
|
88
|
+
stream.direction = 'outbound';
|
|
87
89
|
return stream;
|
|
88
90
|
}
|
|
89
91
|
/**
|
|
90
92
|
* Add a stream when it is opened to the registry
|
|
91
93
|
*/
|
|
92
94
|
addStream(stream) {
|
|
93
|
-
stream.
|
|
95
|
+
stream.direction = 'inbound';
|
|
94
96
|
}
|
|
95
97
|
/**
|
|
96
98
|
* Remove stream registry after it is closed
|
|
@@ -101,10 +103,10 @@ export class ConnectionImpl {
|
|
|
101
103
|
* Close the connection
|
|
102
104
|
*/
|
|
103
105
|
async close() {
|
|
104
|
-
if (this.
|
|
106
|
+
if (this.status === CLOSED || this._closing) {
|
|
105
107
|
return;
|
|
106
108
|
}
|
|
107
|
-
this.
|
|
109
|
+
this.status = CLOSING;
|
|
108
110
|
// close all streams - this can throw if we're not multiplexed
|
|
109
111
|
try {
|
|
110
112
|
this.streams.forEach(s => { s.close(); });
|
|
@@ -116,8 +118,8 @@ export class ConnectionImpl {
|
|
|
116
118
|
this._closing = true;
|
|
117
119
|
await this._close();
|
|
118
120
|
this._closing = false;
|
|
119
|
-
this.
|
|
120
|
-
this.
|
|
121
|
+
this.timeline.close = Date.now();
|
|
122
|
+
this.status = CLOSED;
|
|
121
123
|
}
|
|
122
124
|
}
|
|
123
125
|
export function createConnection(init) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/connection/index.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/connection/index.ts"],"names":[],"mappings":"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"}
|
|
@@ -74,8 +74,8 @@ export class ConnectionPruner {
|
|
|
74
74
|
return -1;
|
|
75
75
|
}
|
|
76
76
|
// if the peers have an equal tag value then we want to close short-lived connections first
|
|
77
|
-
const connectionALifespan = a.
|
|
78
|
-
const connectionBLifespan = b.
|
|
77
|
+
const connectionALifespan = a.timeline.open;
|
|
78
|
+
const connectionBLifespan = b.timeline.open;
|
|
79
79
|
if (connectionALifespan < connectionBLifespan) {
|
|
80
80
|
return 1;
|
|
81
81
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"connection-pruner.js","sourceRoot":"","sources":["../../../src/connection-manager/connection-pruner.ts"],"names":[],"mappings":"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
|
|
1
|
+
{"version":3,"file":"connection-pruner.js","sourceRoot":"","sources":["../../../src/connection-manager/connection-pruner.ts"],"names":[],"mappings":"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"}
|
|
@@ -122,7 +122,7 @@ export class DefaultConnectionManager {
|
|
|
122
122
|
};
|
|
123
123
|
for (const conns of this.connections.values()) {
|
|
124
124
|
for (const conn of conns) {
|
|
125
|
-
if (conn.
|
|
125
|
+
if (conn.direction === 'inbound') {
|
|
126
126
|
metric.inbound++;
|
|
127
127
|
}
|
|
128
128
|
else {
|
|
@@ -141,7 +141,7 @@ export class DefaultConnectionManager {
|
|
|
141
141
|
for (const conns of this.connections.values()) {
|
|
142
142
|
for (const conn of conns) {
|
|
143
143
|
for (const stream of conn.streams) {
|
|
144
|
-
const key = `${stream.
|
|
144
|
+
const key = `${stream.direction} ${stream.protocol ?? 'unnegotiated'}`;
|
|
145
145
|
metric[key] = (metric[key] ?? 0) + 1;
|
|
146
146
|
}
|
|
147
147
|
}
|
|
@@ -158,7 +158,7 @@ export class DefaultConnectionManager {
|
|
|
158
158
|
for (const conn of conns) {
|
|
159
159
|
const streams = {};
|
|
160
160
|
for (const stream of conn.streams) {
|
|
161
|
-
const key = `${stream.
|
|
161
|
+
const key = `${stream.direction} ${stream.protocol ?? 'unnegotiated'}`;
|
|
162
162
|
streams[key] = (streams[key] ?? 0) + 1;
|
|
163
163
|
}
|
|
164
164
|
for (const [protocol, count] of Object.entries(streams)) {
|