libp2p 0.41.0-19e96cc → 0.41.0-3e53c19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.min.js CHANGED
@@ -46,5 +46,13 @@
46
46
  (?::(?:(?::${et}){0,5}:${tr}|(?::${et}){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
48
  `.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),gS=new RegExp(`(?:^${tr}$)|(?:^${Ya}$)`),ES=new RegExp(`^${tr}$`),vS=new RegExp(`^${Ya}$`),hf=t=>t&&t.exact?gS:new RegExp(`(?:${xn(t)}${tr}${xn(t)})|(?:${xn(t)}${Ya}${xn(t)})`,"g");hf.v4=t=>t&&t.exact?ES:new RegExp(`${xn(t)}${tr}${xn(t)}`,"g");hf.v6=t=>t&&t.exact?vS:new RegExp(`${xn(t)}${Ya}${xn(t)}`,"g");var xy=hf;var Cy=C(Sy(),1),{isValid:wS,parse:xS}=Cy.default,bS=["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"],SS=bS.map(t=>new Ay.Netmask(t));function _S(t){for(let e of SS)if(e.contains(t))return!0;return!1}function _y(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 Iy=t=>{if(wS(t)){let e=xS(t);if(e.kind()==="ipv4")return _S(e.toNormalizedString());if(e.kind()==="ipv6")return _y(t)}else if(Fi(t)&&xy.v6().test(t))return _y(t)};var Qa=Iy;function df(t){let{address:e}=t.nodeAddress();return Boolean(Qa(e))}function Ji(t,e){let r=df(t.multiaddr),n=df(e.multiaddr);return r&&!n?1:!r&&n||t.isCertified&&!e.isCertified?-1:!t.isCertified&&e.isCertified?1:0}var ro=M("libp2p:auto-relay"),CS=()=>{},Xa=class{constructor(e,r){this.components=e,this.addressSorter=r.addressSorter??Ji,this.maxListeners=r.maxListeners??1,this.listenRelays=new Set,this.onError=r.onError??CS,this._onProtocolChange=this._onProtocolChange.bind(this),this._onPeerDisconnected=this._onPeerDisconnected.bind(this),this.components.peerStore.addEventListener("change:protocols",n=>{this._onProtocolChange(n).catch(i=>{ro.error(i)})}),this.components.connectionManager.addEventListener("peer:disconnect",this._onPeerDisconnected)}async _onProtocolChange(e){let{peerId:r,protocols:n}=e.detail,i=r.toString();if(n.find(o=>o===gr)==null){this.listenRelays.has(i)&&await this._removeListenRelay(i);return}if(!this.listenRelays.has(i))try{let o=this.components.connectionManager.getConnections(r);if(o.length===0)return;let a=o[0];if(a.remoteAddr.protoCodes().includes(290)){ro(`relayed connection to ${i} will not be used to hop on`);return}await dy({connection:a})&&(await this.components.peerStore.metadataBook.setValue(r,lf,q(ff)),await this._addListenRelay(a,i))}catch(o){this.onError(o)}}_onPeerDisconnected(e){let i=e.detail.remotePeer.toString();this.listenRelays.has(i)&&this._removeListenRelay(i).catch(s=>{ro.error(s)})}async _addListenRelay(e,r){try{if(this.listenRelays.size>=this.maxListeners)return;let n=await Ce(await this.components.peerStore.addressBook.get(e.remotePeer),s=>zs(s,this.addressSorter),async s=>await zr(s));(await Promise.all(n.map(async s=>{try{let o=s.multiaddr;return o.getPeerId()==null&&(o=o.encapsulate(`/p2p/${e.remotePeer.toString()}`)),o=o.encapsulate("/p2p-circuit"),await this.components.transportManager.listen([o]),!0}catch(o){ro.error("error listening on circuit address",o),this.onError(o)}return!1}))).includes(!0)&&this.listenRelays.add(r)}catch(n){this.onError(n),this.listenRelays.delete(r)}}async _removeListenRelay(e){this.listenRelays.delete(e)&&await this._listenOnAvailableHopRelays([e])}async _listenOnAvailableHopRelays(e=[]){if(this.listenRelays.size>=this.maxListeners)return;let r=[],n=await this.components.peerStore.all();for(let{id:i,metadata:s}of n){let o=i.toString();if(this.listenRelays.has(o)||e.includes(o))continue;let a=s.get(lf);if(a==null||Q(a)!==ff)continue;let c=this.components.connectionManager.getConnections(i);if(c.length===0){r.push(i);continue}if(await this._addListenRelay(c[0],o),this.listenRelays.size>=this.maxListeners)return}for(let i of r)if(await this._tryToListenOnRelay(i),this.listenRelays.size>=this.maxListeners)return;try{let i=await $a(Ga);for await(let s of this.components.contentRouting.findProviders(i)){if(s.multiaddrs.length===0)continue;let o=s.id;if(!o.equals(this.components.peerId)&&(await this.components.peerStore.addressBook.add(o,s.multiaddrs),await this._tryToListenOnRelay(o),this.listenRelays.size>=this.maxListeners))return}}catch(i){this.onError(i)}}async _tryToListenOnRelay(e){try{let r=await this.components.connectionManager.openConnection(e);await this._addListenRelay(r,e.toString())}catch(r){ro.error("Could not use %p as relay",e,r),this.onError(r,`could not connect and listen on known hop relay ${e.toString()}`)}}};var Ty=M("libp2p:relay"),ja=class{constructor(e,r){this.components=e,this.autoRelay=r.autoRelay?.enabled!==!1?new Xa(e,{addressSorter:r.addressSorter,...r.autoRelay}):void 0,this.started=!1,this.init=r,this._advertiseService=this._advertiseService.bind(this)}isStarted(){return this.started}async start(){this.init.hop.enabled!==!1&&this.init.advertise.enabled!==!1&&(this.timeout=(0,Za.setDelayedInterval)(this._advertiseService,this.init.advertise.ttl,this.init.advertise.bootDelay)),this.started=!0}async stop(){this.timeout!=null&&(0,Za.clearDelayedInterval)(this.timeout),this.started=!1}async _advertiseService(){try{let e=await $a(Ga);await this.components.contentRouting.provide(e)}catch(e){e.code===b.ERR_NO_ROUTERS_AVAILABLE?(Ty.error("a content router, such as a DHT, must be provided in order to advertise the relay service",e),await this.stop()):Ty.error(e)}}};var Av=C(Uy(),1);var i8=C(tE(),1),s8=C(Kf(),1),Qr=C(ie(),1);var r8=C(Of(),1),mE=C(ie(),1),pE=mE.default.pki,yE=(t,e)=>{let r=pE.rsa.setPublicKey(e.n,e.e),n=pE.createCertificate();n.publicKey=r,n.serialNumber="01",n.validity.notBefore=new Date,n.validity.notAfter=new Date,n.validity.notAfter.setFullYear(n.validity.notBefore.getFullYear()+10);let i=[{name:"organizationName",value:"ipfs"},{shortName:"OU",value:"keystore"},{name:"commonName",value:t.id}];return n.setSubject(i),n.setIssuer(i),n.setExtensions([{name:"basicConstraints",cA:!0},{name:"keyUsage",keyCertSign:!0,digitalSignature:!0,nonRepudiation:!0,keyEncipherment:!0,dataEncipherment:!0},{name:"extKeyUsage",serverAuth:!0,clientAuth:!0,codeSigning:!0,emailProtection:!0,timeStamping:!0},{name:"nsCertType",client:!0,server:!0,email:!0,objsign:!0,sslCA:!0,emailCA:!0,objCA:!0}]),n.sign(e),n};async function gE(t,e){let r=t.map(e),i=(await Promise.all(r)).findIndex(s=>s);return t[i]}var Xr=C(G(),1);var CC=M("libp2p:keychain:cms"),Vf=new WeakMap,vc=class{constructor(e,r){if(e==null)throw(0,Xr.default)(new Error("keychain is required"),b.ERR_KEYCHAIN_REQUIRED);this.keychain=e,Vf.set(this,{dek:r})}async encrypt(e,r){if(!(r instanceof Uint8Array))throw(0,Xr.default)(new Error("Plain data must be a Uint8Array"),b.ERR_INVALID_PARAMETERS);let n=await this.keychain.findKeyByName(e),i=await this.keychain.getPrivateKey(e),s=Vf.get(this);if(s==null)throw(0,Xr.default)(new Error("dek missing"),b.ERR_INVALID_PARAMETERS);let o=s.dek,a=Qr.default.pki.decryptRsaPrivateKey(i,o),c=await yE(n,a),u=Qr.default.pkcs7.createEnvelopedData();u.addRecipient(c),u.content=Qr.default.util.createBuffer(r),u.encrypt();let l=Qr.default.asn1.toDer(u.toAsn1()).getBytes();return q(l,"ascii")}async decrypt(e){if(!(e instanceof Uint8Array))throw(0,Xr.default)(new Error("CMS data is required"),b.ERR_INVALID_PARAMETERS);let r;try{let l=Qr.default.util.createBuffer(Q(e,"ascii")),f=Qr.default.asn1.fromDer(l);r=Qr.default.pkcs7.messageFromAsn1(f)}catch(l){throw CC.error(l),(0,Xr.default)(new Error("Invalid CMS"),b.ERR_INVALID_CMS)}let n=r.recipients.filter(l=>l.issuer.find(f=>f.shortName==="O"&&f.value==="ipfs")).filter(l=>l.issuer.find(f=>f.shortName==="CN")).map(l=>({recipient:l,keyId:l.issuer.find(f=>f.shortName==="CN").value})),i=await gE(n,async l=>{try{if(await this.keychain.findKeyById(l.keyId)!=null)return!0}catch{return!1}return!1});if(i==null){let l=n.map(f=>f.keyId);throw(0,Xr.default)(new Error(`Decryption needs one of the key(s): ${l.join(", ")}`),b.ERR_MISSING_KEYS,{missingKeys:l})}let s=await this.keychain.findKeyById(i.keyId);if(s==null)throw(0,Xr.default)(new Error("No key available to decrypto"),b.ERR_NO_KEY);let o=await this.keychain.getPrivateKey(s.name),a=Vf.get(this);if(a==null)throw(0,Xr.default)(new Error("dek missing"),b.ERR_INVALID_PARAMETERS);let c=a.dek,u=Qr.default.pki.decryptRsaPrivateKey(o,c);return r.decrypt(i.recipient,u),q(r.content.getBytes(),"ascii")}};var ye=C(G(),1);var Fe;(function(t){t.RSA="RSA",t.Ed25519="Ed25519",t.Secp256k1="Secp256k1"})(Fe||(Fe={}));var qf;(function(t){t[t.RSA=0]="RSA",t[t.Ed25519=1]="Ed25519",t[t.Secp256k1=2]="Secp256k1"})(qf||(qf={}));(function(t){t.codec=()=>wn(qf)})(Fe||(Fe={}));var _r;(function(t){let e;t.codec=()=>(e==null&&(e=Ne((r,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),r.Type!=null&&(n.uint32(8),Fe.codec().encode(r.Type,n)),r.Data!=null&&(n.uint32(18),n.bytes(r.Data)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={},s=n==null?r.len:r.pos+n;for(;r.pos<s;){let o=r.uint32();switch(o>>>3){case 1:i.Type=Fe.codec().decode(r);break;case 2:i.Data=r.bytes();break;default:r.skipType(o&7);break}}return i})),e),t.encode=r=>Re(r,t.codec()),t.decode=r=>Te(r,t.codec())})(_r||(_r={}));var Ar;(function(t){let e;t.codec=()=>(e==null&&(e=Ne((r,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),r.Type!=null&&(n.uint32(8),Fe.codec().encode(r.Type,n)),r.Data!=null&&(n.uint32(18),n.bytes(r.Data)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={},s=n==null?r.len:r.pos+n;for(;r.pos<s;){let o=r.uint32();switch(o>>>3){case 1:i.Type=Fe.codec().decode(r);break;case 2:i.Data=r.bytes();break;default:r.skipType(o&7);break}}return i})),e),t.encode=r=>Re(r,t.codec()),t.decode=r=>Te(r,t.codec())})(Ar||(Ar={}));var AO=C(_n(),1),CO=C(Kf(),1),Lc=C(ie(),1),dh=C(G(),1);var IC=C(G(),1);var _t={get(t=globalThis){let e=t.crypto;if(e==null||e.subtle==null)throw Object.assign(new Error("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p-crypto/blob/master/README.md#web-crypto-api"),{code:"ERR_MISSING_WEB_CRYPTO"});return e}};var TC=C(G(),1);var b8=C(De(),1),S8=C(pc(),1),vE=C(ie(),1);function ir(t,e){let r=Uint8Array.from(t.abs().toByteArray());if(r=r[0]===0?r.subarray(1):r,e!=null){if(r.length>e)throw new Error("byte array longer than desired length");r=Xe([new Uint8Array(e-r.length),r])}return Q(r,"base64url")}function Bt(t){let e=wE(t);return new vE.default.jsbn.BigInteger(Q(e,"base16"),16)}function wE(t,e){let r=q(t,"base64urlpad");if(e!=null){if(r.length>e)throw new Error("byte array longer than desired length");r=Xe([new Uint8Array(e-r.length),r])}return r}var RC={"P-256":256,"P-384":384,"P-521":521},NC=Object.keys(RC),P8=NC.join(" / ");function xc(t){let e=t?.algorithm??"AES-GCM",r=t?.keyLength??16,n=t?.nonceLength??12,i=t?.digest??"SHA-256",s=t?.saltLength??16,o=t?.iterations??32767,a=_t.get();r*=8;async function c(f,h){let d=a.getRandomValues(new Uint8Array(s)),p=a.getRandomValues(new Uint8Array(n)),y={name:e,iv:p};typeof h=="string"&&(h=q(h));let g={name:"PBKDF2",salt:d,iterations:o,hash:{name:i}},E=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey","deriveBits"]),x=await a.subtle.deriveKey(g,E,{name:e,length:r},!0,["encrypt"]),_=await a.subtle.encrypt(y,x,f);return Xe([d,y.iv,new Uint8Array(_)])}async function u(f,h){let d=f.subarray(0,s),p=f.subarray(s,s+n),y=f.subarray(s+n),g={name:e,iv:p};typeof h=="string"&&(h=q(h));let E={name:"PBKDF2",salt:d,iterations:o,hash:{name:i}},x=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey","deriveBits"]),_=await a.subtle.deriveKey(E,x,{name:e,length:r},!0,["decrypt"]),B=await a.subtle.decrypt(g,_,y);return new Uint8Array(B)}return{encrypt:c,decrypt:u}}async function bE(t,e){let r=Vn.decode(t);return await xc().decrypt(r,e)}var eh={};pt(eh,{RsaPrivateKey:()=>ys,RsaPublicKey:()=>mo,fromJwk:()=>tI,generateKeyPair:()=>rI,unmarshalRsaPrivateKey:()=>JC,unmarshalRsaPublicKey:()=>eI});var Jf=C(G(),1);var lO=C(IE(),1),po=C(ie(),1);var LC=C(Zn(),1);var le=BigInt(0),ke=BigInt(1),Rn=BigInt(2),lo=BigInt(3),PC=BigInt(8),Ke=Object.freeze({a:le,b:BigInt(7),P:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:ke,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee")});function TE(t){let{a:e,b:r}=Ke,n=K(t*t),i=K(n*t);return K(i+e*t+r)}var bc=Ke.a===le,_c=class extends Error{constructor(e){super(e)}},ge=class{constructor(e,r,n){this.x=e,this.y=r,this.z=n}static fromAffine(e){if(!(e instanceof we))throw new TypeError("JacobianPoint#fromAffine: expected Point");return new ge(e.x,e.y,ke)}static toAffineBatch(e){let r=MC(e.map(n=>n.z));return e.map((n,i)=>n.toAffine(r[i]))}static normalizeZ(e){return ge.toAffineBatch(e).map(ge.fromAffine)}equals(e){if(!(e instanceof ge))throw new TypeError("JacobianPoint expected");let{x:r,y:n,z:i}=this,{x:s,y:o,z:a}=e,c=K(i*i),u=K(a*a),l=K(r*u),f=K(s*c),h=K(K(n*a)*u),d=K(K(o*i)*c);return l===f&&h===d}negate(){return new ge(this.x,K(-this.y),this.z)}double(){let{x:e,y:r,z:n}=this,i=K(e*e),s=K(r*r),o=K(s*s),a=e+s,c=K(Rn*(K(a*a)-i-o)),u=K(lo*i),l=K(u*u),f=K(l-Rn*c),h=K(u*(c-f)-PC*o),d=K(Rn*r*n);return new ge(f,h,d)}add(e){if(!(e instanceof ge))throw new TypeError("JacobianPoint expected");let{x:r,y:n,z:i}=this,{x:s,y:o,z:a}=e;if(s===le||o===le)return this;if(r===le||n===le)return e;let c=K(i*i),u=K(a*a),l=K(r*u),f=K(s*c),h=K(K(n*a)*u),d=K(K(o*i)*c),p=K(f-l),y=K(d-h);if(p===le)return y===le?this.double():ge.ZERO;let g=K(p*p),E=K(p*g),x=K(l*g),_=K(y*y-E-Rn*x),B=K(y*(x-_)-h*E),D=K(i*a*p);return new ge(_,B,D)}subtract(e){return this.add(e.negate())}multiplyUnsafe(e){let r=ge.ZERO;if(typeof e=="bigint"&&e===le)return r;let n=DE(e);if(n===ke)return this;if(!bc){let f=r,h=this;for(;n>le;)n&ke&&(f=f.add(h)),h=h.double(),n>>=ke;return f}let{k1neg:i,k1:s,k2neg:o,k2:a}=PE(n),c=r,u=r,l=this;for(;s>le||a>le;)s&ke&&(c=c.add(l)),a&ke&&(u=u.add(l)),l=l.double(),s>>=ke,a>>=ke;return i&&(c=c.negate()),o&&(u=u.negate()),u=new ge(K(u.x*Ke.beta),u.y,u.z),c.add(u)}precomputeWindow(e){let r=bc?128/e+1:256/e+1,n=[],i=this,s=i;for(let o=0;o<r;o++){s=i,n.push(s);for(let a=1;a<2**(e-1);a++)s=s.add(i),n.push(s);i=s.double()}return n}wNAF(e,r){!r&&this.equals(ge.BASE)&&(r=we.BASE);let n=r&&r._WINDOW_SIZE||1;if(256%n)throw new Error("Point#wNAF: Invalid precomputation window, must be power of 2");let i=r&&Gf.get(r);i||(i=this.precomputeWindow(n),r&&n!==1&&(i=ge.normalizeZ(i),Gf.set(r,i)));let s=ge.ZERO,o=ge.ZERO,a=1+(bc?128/n:256/n),c=2**(n-1),u=BigInt(2**n-1),l=2**n,f=BigInt(n);for(let h=0;h<a;h++){let d=h*c,p=Number(e&u);if(e>>=f,p>c&&(p-=l,e+=ke),p===0){let y=i[d];h%2&&(y=y.negate()),o=o.add(y)}else{let y=i[d+Math.abs(p)-1];p<0&&(y=y.negate()),s=s.add(y)}}return{p:s,f:o}}multiply(e,r){let n=DE(e),i,s;if(bc){let{k1neg:o,k1:a,k2neg:c,k2:u}=PE(n),{p:l,f}=this.wNAF(a,r),{p:h,f:d}=this.wNAF(u,r);o&&(l=l.negate()),c&&(h=h.negate()),h=new ge(K(h.x*Ke.beta),h.y,h.z),i=l.add(h),s=f.add(d)}else{let{p:o,f:a}=this.wNAF(n,r);i=o,s=a}return ge.normalizeZ([i,s])[0]}toAffine(e=ps(this.z)){let{x:r,y:n,z:i}=this,s=e,o=K(s*s),a=K(o*s),c=K(r*o),u=K(n*a);if(K(i*s)!==ke)throw new Error("invZ was invalid");return new we(c,u)}};ge.BASE=new ge(Ke.Gx,Ke.Gy,ke);ge.ZERO=new ge(le,ke,le);var Gf=new WeakMap,we=class{constructor(e,r){this.x=e,this.y=r}_setWindowSize(e){this._WINDOW_SIZE=e,Gf.delete(this)}hasEvenY(){return this.y%Rn===le}static fromCompressedHex(e){let r=e.length===32,n=jr(r?e:e.subarray(1));if(!$f(n))throw new Error("Point is not on curve");let i=TE(n),s=UC(i),o=(s&ke)===ke;r?o&&(s=K(-s)):(e[0]&1)===1!==o&&(s=K(-s));let a=new we(n,s);return a.assertValidity(),a}static fromUncompressedHex(e){let r=jr(e.subarray(1,33)),n=jr(e.subarray(33,65)),i=new we(r,n);return i.assertValidity(),i}static fromHex(e){let r=ds(e),n=r.length,i=r[0];if(n===32||n===33&&(i===2||i===3))return this.fromCompressedHex(r);if(n===65&&i===4)return this.fromUncompressedHex(r);throw new Error(`Point.fromHex: received invalid point. Expected 32-33 compressed bytes or 65 uncompressed bytes, not ${n}`)}static fromPrivateKey(e){return we.BASE.multiply(Cc(e))}static fromSignature(e,r,n){e=ds(e);let i=BE(e),{r:s,s:o}=OE(r);if(n!==0&&n!==1)throw new Error("Cannot recover signature: invalid recovery bit");let a=n&1?"03":"02",c=we.fromHex(a+ls(s)),{n:u}=Ke,l=ps(s,u),f=K(-i*l,u),h=K(o*l,u),d=we.BASE.multiplyAndAddUnsafe(c,f,h);if(!d)throw new Error("Cannot recover signature: point at infinify");return d.assertValidity(),d}toRawBytes(e=!1){return di(this.toHex(e))}toHex(e=!1){let r=ls(this.x);return e?`${this.hasEvenY()?"02":"03"}${r}`:`04${r}${ls(this.y)}`}toHexX(){return this.toHex(!0).slice(2)}toRawX(){return this.toRawBytes(!0).slice(1)}assertValidity(){let e="Point is not on elliptic curve",{x:r,y:n}=this;if(!$f(r)||!$f(n))throw new Error(e);let i=K(n*n),s=TE(r);if(K(i-s)!==le)throw new Error(e)}equals(e){return this.x===e.x&&this.y===e.y}negate(){return new we(this.x,K(-this.y))}double(){return ge.fromAffine(this).double().toAffine()}add(e){return ge.fromAffine(this).add(ge.fromAffine(e)).toAffine()}subtract(e){return this.add(e.negate())}multiply(e){return ge.fromAffine(this).multiply(e,this).toAffine()}multiplyAndAddUnsafe(e,r,n){let i=ge.fromAffine(this),s=r===le||r===ke||this!==we.BASE?i.multiplyUnsafe(r):i.multiply(r),o=ge.fromAffine(e).multiplyUnsafe(n),a=s.add(o);return a.equals(ge.ZERO)?void 0:a.toAffine()}};we.BASE=new we(Ke.Gx,Ke.Gy);we.ZERO=new we(le,le);function RE(t){return Number.parseInt(t[0],16)>=8?"00"+t:t}function NE(t){if(t.length<2||t[0]!==2)throw new Error(`Invalid signature integer tag: ${hs(t)}`);let e=t[1],r=t.subarray(2,e+2);if(!e||r.length!==e)throw new Error("Invalid signature integer: wrong length");if(r[0]===0&&r[1]<=127)throw new Error("Invalid signature integer: trailing length");return{data:jr(r),left:t.subarray(e+2)}}function BC(t){if(t.length<2||t[0]!=48)throw new Error(`Invalid signature tag: ${hs(t)}`);if(t[1]!==t.length-2)throw new Error("Invalid signature: incorrect length");let{data:e,left:r}=NE(t.subarray(2)),{data:n,left:i}=NE(r);if(i.length)throw new Error(`Invalid signature: left bytes after parsing: ${hs(i)}`);return{r:e,s:n}}var Cr=class{constructor(e,r){this.r=e,this.s=r,this.assertValidity()}static fromCompact(e){let r=e instanceof Uint8Array,n="Signature.fromCompact";if(typeof e!="string"&&!r)throw new TypeError(`${n}: Expected string or Uint8Array`);let i=r?hs(e):e;if(i.length!==128)throw new Error(`${n}: Expected 64-byte hex`);return new Cr(Ac(i.slice(0,64)),Ac(i.slice(64,128)))}static fromDER(e){let r=e instanceof Uint8Array;if(typeof e!="string"&&!r)throw new TypeError("Signature.fromDER: Expected string or Uint8Array");let{r:n,s:i}=BC(r?e:di(e));return new Cr(n,i)}static fromHex(e){return this.fromDER(e)}assertValidity(){let{r:e,s:r}=this;if(!ho(e))throw new Error("Invalid Signature: r must be 0 < r < n");if(!ho(r))throw new Error("Invalid Signature: s must be 0 < s < n")}hasHighS(){let e=Ke.n>>ke;return this.s>e}normalizeS(){return this.hasHighS()?new Cr(this.r,Ke.n-this.s):this}toDERRawBytes(e=!1){return di(this.toDERHex(e))}toDERHex(e=!1){let r=RE(uo(this.s));if(e)return r;let n=RE(uo(this.r)),i=uo(n.length/2),s=uo(r.length/2);return`30${uo(n.length/2+r.length/2+4)}02${i}${n}02${s}${r}`}toRawBytes(){return this.toDERRawBytes()}toHex(){return this.toDERHex()}toCompactRawBytes(){return di(this.toCompactHex())}toCompactHex(){return ls(this.r)+ls(this.s)}};function us(...t){if(!t.every(n=>n instanceof Uint8Array))throw new Error("Uint8Array list expected");if(t.length===1)return t[0];let e=t.reduce((n,i)=>n+i.length,0),r=new Uint8Array(e);for(let n=0,i=0;n<t.length;n++){let s=t[n];r.set(s,i),i+=s.length}return r}var OC=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function hs(t){if(!(t instanceof Uint8Array))throw new Error("Expected Uint8Array");let e="";for(let r=0;r<t.length;r++)e+=OC[t[r]];return e}var kC=BigInt("0x10000000000000000000000000000000000000000000000000000000000000000");function ls(t){if(typeof t!="bigint")throw new Error("Expected bigint");if(!(le<=t&&t<kC))throw new Error("Expected number < 2^256");return t.toString(16).padStart(64,"0")}function Yf(t){let e=di(ls(t));if(e.length!==32)throw new Error("Error: expected 32 bytes");return e}function uo(t){let e=t.toString(16);return e.length&1?`0${e}`:e}function Ac(t){if(typeof t!="string")throw new TypeError("hexToNumber: expected string, got "+typeof t);return BigInt(`0x${t}`)}function di(t){if(typeof t!="string")throw new TypeError("hexToBytes: expected string, got "+typeof t);if(t.length%2)throw new Error("hexToBytes: received invalid unpadded hex"+t.length);let e=new Uint8Array(t.length/2);for(let r=0;r<e.length;r++){let n=r*2,i=t.slice(n,n+2),s=Number.parseInt(i,16);if(Number.isNaN(s)||s<0)throw new Error("Invalid byte sequence");e[r]=s}return e}function jr(t){return Ac(hs(t))}function ds(t){return t instanceof Uint8Array?Uint8Array.from(t):di(t)}function DE(t){if(typeof t=="number"&&Number.isSafeInteger(t)&&t>0)return BigInt(t);if(typeof t=="bigint"&&ho(t))return t;throw new TypeError("Expected valid private scalar: 0 < scalar < curve.n")}function K(t,e=Ke.P){let r=t%e;return r>=le?r:e+r}function Yt(t,e){let{P:r}=Ke,n=t;for(;e-- >le;)n*=n,n%=r;return n}function UC(t){let{P:e}=Ke,r=BigInt(6),n=BigInt(11),i=BigInt(22),s=BigInt(23),o=BigInt(44),a=BigInt(88),c=t*t*t%e,u=c*c*t%e,l=Yt(u,lo)*u%e,f=Yt(l,lo)*u%e,h=Yt(f,Rn)*c%e,d=Yt(h,n)*h%e,p=Yt(d,i)*d%e,y=Yt(p,o)*p%e,g=Yt(y,a)*y%e,E=Yt(g,o)*p%e,x=Yt(E,lo)*u%e,_=Yt(x,s)*d%e,B=Yt(_,r)*c%e;return Yt(B,Rn)}function ps(t,e=Ke.P){if(t===le||e<=le)throw new Error(`invert: expected positive integers, got n=${t} mod=${e}`);let r=K(t,e),n=e,i=le,s=ke,o=ke,a=le;for(;r!==le;){let u=n/r,l=n%r,f=i-o*u,h=s-a*u;n=r,r=l,i=o,s=a,o=f,a=h}if(n!==ke)throw new Error("invert: does not exist");return K(i,e)}function MC(t,e=Ke.P){let r=new Array(t.length),n=t.reduce((s,o,a)=>o===le?s:(r[a]=s,K(s*o,e)),ke),i=ps(n,e);return t.reduceRight((s,o,a)=>o===le?s:(r[a]=K(s*r[a],e),K(s*o,e)),i),r}var LE=(t,e)=>(t+e/Rn)/e,FC={a1:BigInt("0x3086d221a7d46bcde86c90e49284eb15"),b1:-ke*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),a2:BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),b2:BigInt("0x3086d221a7d46bcde86c90e49284eb15"),POW_2_128:BigInt("0x100000000000000000000000000000000")};function PE(t){let{n:e}=Ke,{a1:r,b1:n,a2:i,b2:s,POW_2_128:o}=FC,a=LE(s*t,e),c=LE(-n*t,e),u=K(t-a*r-c*i,e),l=K(-a*n-c*s,e),f=u>o,h=l>o;if(f&&(u=e-u),h&&(l=e-l),u>o||l>o)throw new Error("splitScalarEndo: Endomorphism failed, k="+t);return{k1neg:f,k1:u,k2neg:h,k2:l}}function BE(t){let{n:e}=Ke,n=t.length*8-256,i=jr(t);return n>0&&(i=i>>BigInt(n)),i>=e&&(i-=e),i}var fs,fo,Wf=class{constructor(){this.v=new Uint8Array(32).fill(1),this.k=new Uint8Array(32).fill(0),this.counter=0}hmac(...e){return sr.hmacSha256(this.k,...e)}hmacSync(...e){return fo(this.k,...e)}checkSync(){if(typeof fo!="function")throw new _c("hmacSha256Sync needs to be set")}incr(){if(this.counter>=1e3)throw new Error("Tried 1,000 k values for sign(), all were invalid");this.counter+=1}async reseed(e=new Uint8Array){this.k=await this.hmac(this.v,Uint8Array.from([0]),e),this.v=await this.hmac(this.v),e.length!==0&&(this.k=await this.hmac(this.v,Uint8Array.from([1]),e),this.v=await this.hmac(this.v))}reseedSync(e=new Uint8Array){this.checkSync(),this.k=this.hmacSync(this.v,Uint8Array.from([0]),e),this.v=this.hmacSync(this.v),e.length!==0&&(this.k=this.hmacSync(this.v,Uint8Array.from([1]),e),this.v=this.hmacSync(this.v))}async generate(){return this.incr(),this.v=await this.hmac(this.v),this.v}generateSync(){return this.checkSync(),this.incr(),this.v=this.hmacSync(this.v),this.v}};function ho(t){return le<t&&t<Ke.n}function $f(t){return le<t&&t<Ke.P}function KC(t,e,r){let n=jr(t);if(!ho(n))return;let{n:i}=Ke,s=we.BASE.multiply(n),o=K(s.x,i);if(o===le)return;let a=K(ps(n,i)*K(e+r*o,i),i);if(a===le)return;let c=new Cr(o,a),u=(s.x===c.r?0:2)|Number(s.y&ke);return{sig:c,recovery:u}}function Cc(t){let e;if(typeof t=="bigint")e=t;else if(typeof t=="number"&&Number.isSafeInteger(t)&&t>0)e=BigInt(t);else if(typeof t=="string"){if(t.length!==64)throw new Error("Expected 32 bytes of private key");e=Ac(t)}else if(t instanceof Uint8Array){if(t.length!==32)throw new Error("Expected 32 bytes of private key");e=jr(t)}else throw new TypeError("Expected valid private key");if(!ho(e))throw new Error("Expected private key: 0 < key < n");return e}function VC(t){return t instanceof we?(t.assertValidity(),t):we.fromHex(t)}function OE(t){if(t instanceof Cr)return t.assertValidity(),t;try{return Cr.fromDER(t)}catch{return Cr.fromCompact(t)}}function Qf(t,e=!1){return we.fromPrivateKey(t).toRawBytes(e)}function kE(t){let e=t.length>32?t.slice(0,32):t;return jr(e)}function qC(t){let e=kE(t),r=K(e,Ke.n);return UE(r<le?e:r)}function UE(t){return Yf(t)}function HC(t,e,r){if(t==null)throw new Error(`sign: expected valid message hash, not "${t}"`);let n=ds(t),i=Cc(e),s=[UE(i),qC(n)];if(r!=null){r===!0&&(r=sr.randomBytes(32));let c=ds(r);if(c.length!==32)throw new Error("sign: Expected 32 bytes of extra data");s.push(c)}let o=us(...s),a=kE(n);return{seed:o,m:a,d:i}}function zC(t,e){let{sig:r,recovery:n}=t,{canonical:i,der:s,recovered:o}=Object.assign({canonical:!0,der:!0},e);i&&r.hasHighS()&&(r=r.normalizeS(),n^=1);let a=s?r.toDERRawBytes():r.toCompactRawBytes();return o?[a,n]:a}async function ME(t,e,r={}){let{seed:n,m:i,d:s}=HC(t,e,r.extraEntropy),o,a=new Wf;for(await a.reseed(n);!(o=KC(await a.generate(),i,s));)await a.reseed();return zC(o,r)}var $C={strict:!0};function FE(t,e,r,n=$C){let i;try{i=OE(t),e=ds(e)}catch{return!1}let{r:s,s:o}=i;if(n.strict&&i.hasHighS())return!1;let a=BE(e),c;try{c=VC(r)}catch{return!1}let{n:u}=Ke,l=ps(o,u),f=K(a*l,u),h=K(s*l,u),d=we.BASE.multiplyAndAddUnsafe(c,f,h);return d?K(d.x,u)===s:!1}we.BASE._setWindowSize(8);var Ot={node:LC,web:typeof self=="object"&&"crypto"in self?self.crypto:void 0};var Sc={},sr={bytesToHex:hs,hexToBytes:di,concatBytes:us,mod:K,invert:ps,isValidPrivateKey(t){try{return Cc(t),!0}catch{return!1}},_bigintTo32Bytes:Yf,_normalizePrivateKey:Cc,hashToPrivateKey:t=>{if(t=ds(t),t.length<40||t.length>1024)throw new Error("Expected 40-1024 bytes of private key as per FIPS 186");let e=K(jr(t),Ke.n-ke)+ke;return Yf(e)},randomBytes:(t=32)=>{if(Ot.web)return Ot.web.getRandomValues(new Uint8Array(t));if(Ot.node){let{randomBytes:e}=Ot.node;return Uint8Array.from(e(t))}else throw new Error("The environment doesn't have randomBytes function")},randomPrivateKey:()=>sr.hashToPrivateKey(sr.randomBytes(40)),sha256:async(...t)=>{if(Ot.web){let e=await Ot.web.subtle.digest("SHA-256",us(...t));return new Uint8Array(e)}else if(Ot.node){let{createHash:e}=Ot.node,r=e("sha256");return t.forEach(n=>r.update(n)),Uint8Array.from(r.digest())}else throw new Error("The environment doesn't have sha256 function")},hmacSha256:async(t,...e)=>{if(Ot.web){let r=await Ot.web.subtle.importKey("raw",t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),n=us(...e),i=await Ot.web.subtle.sign("HMAC",r,n);return new Uint8Array(i)}else if(Ot.node){let{createHmac:r}=Ot.node,n=r("sha256",t);return e.forEach(i=>n.update(i)),Uint8Array.from(n.digest())}else throw new Error("The environment doesn't have hmac-sha256 function")},sha256Sync:void 0,hmacSha256Sync:void 0,taggedHash:async(t,...e)=>{let r=Sc[t];if(r===void 0){let n=await sr.sha256(Uint8Array.from(t,i=>i.charCodeAt(0)));r=us(n,n),Sc[t]=r}return sr.sha256(r,...e)},taggedHashSync:(t,...e)=>{if(typeof fs!="function")throw new _c("sha256Sync is undefined, you need to set it");let r=Sc[t];if(r===void 0){let n=fs(Uint8Array.from(t,i=>i.charCodeAt(0)));r=us(n,n),Sc[t]=r}return fs(r,...e)},precompute(t=8,e=we.BASE){let r=e===we.BASE?e:new we(e.x,e.y);return r._setWindowSize(t),r.multiply(lo),r}};Object.defineProperties(sr,{sha256Sync:{configurable:!1,get(){return fs},set(t){fs||(fs=t)}},hmacSha256Sync:{configurable:!1,get(){return fo},set(t){fo||(fo=t)}}});var KE=C(G(),1);function Zr(t){if(isNaN(t)||t<=0)throw(0,KE.default)(new Error("random bytes length must be a Number bigger than 0"),"ERR_INVALID_LENGTH");return sr.randomBytes(t)}var pi={};pt(pi,{jwkToPkcs1:()=>WC,jwkToPkix:()=>XC,pkcs1ToJwk:()=>YC,pkixToJwk:()=>QC});var G8=C(_n(),1),Y8=C(ao(),1),Jr=C(ie(),1);var Xf=C(G(),1);function YC(t){let e=Jr.default.asn1.fromDer(Q(t,"ascii")),r=Jr.default.pki.privateKeyFromAsn1(e);return{kty:"RSA",n:ir(r.n),e:ir(r.e),d:ir(r.d),p:ir(r.p),q:ir(r.q),dp:ir(r.dP),dq:ir(r.dQ),qi:ir(r.qInv),alg:"RS256"}}function WC(t){if(t.n==null||t.e==null||t.d==null||t.p==null||t.q==null||t.dp==null||t.dq==null||t.qi==null)throw(0,Xf.default)(new Error("JWK was missing components"),"ERR_INVALID_PARAMETERS");let e=Jr.default.pki.privateKeyToAsn1({n:Bt(t.n),e:Bt(t.e),d:Bt(t.d),p:Bt(t.p),q:Bt(t.q),dP:Bt(t.dp),dQ:Bt(t.dq),qInv:Bt(t.qi)});return q(Jr.default.asn1.toDer(e).getBytes(),"ascii")}function QC(t){let e=Jr.default.asn1.fromDer(Q(t,"ascii")),r=Jr.default.pki.publicKeyFromAsn1(e);return{kty:"RSA",n:ir(r.n),e:ir(r.e)}}function XC(t){if(t.n==null||t.e==null)throw(0,Xf.default)(new Error("JWK was missing components"),"ERR_INVALID_PARAMETERS");let e=Jr.default.pki.publicKeyToAsn1({n:Bt(t.n),e:Bt(t.e)});return q(Jr.default.asn1.toDer(e).getBytes(),"ascii")}var j8=C(ao(),1),jf=C(ie(),1);function VE(t,e){return e.map(r=>Bt(t[r]))}function qE(t){return jf.default.pki.setRsaPrivateKey(...VE(t,["n","e","d","p","q","dp","dq","qi"]))}function HE(t){return jf.default.pki.setRsaPublicKey(...VE(t,["n","e"]))}var zE=C(G(),1);async function $E(t){let e=await _t.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:t,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),r=await WE(e);return{privateKey:r[0],publicKey:r[1]}}async function Zf(t){let r=[await _t.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await jC(t)],n=await WE({privateKey:r[0],publicKey:r[1]});return{privateKey:n[0],publicKey:n[1]}}async function GE(t,e){let r=await _t.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await _t.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,Uint8Array.from(e));return new Uint8Array(n,0,n.byteLength)}async function YE(t,e,r){let n=await _t.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return await _t.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,r)}async function WE(t){if(t.privateKey==null||t.publicKey==null)throw(0,zE.default)(new Error("Private and public key are required"),"ERR_INVALID_PARAMETERS");return await Promise.all([_t.get().subtle.exportKey("jwk",t.privateKey),_t.get().subtle.exportKey("jwk",t.publicKey)])}async function jC(t){return await _t.get().subtle.importKey("jwk",{kty:t.kty,n:t.n,e:t.e},{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])}function QE(t,e,r,n){let i=e?HE(t):qE(t),s=Q(Uint8Array.from(r),"ascii"),o=n(s,i);return q(o,"ascii")}function XE(t,e){return QE(t,!0,e,(r,n)=>n.encrypt(r))}function jE(t,e){return QE(t,!1,e,(r,n)=>n.decrypt(r))}async function ms(t,e){let n=await xc().encrypt(t,e);return Vn.encode(n)}var mo=class{constructor(e){this._key=e}async verify(e,r){return await YE(this._key,r,e)}marshal(){return pi.jwkToPkix(this._key)}get bytes(){return _r.encode({Type:Fe.RSA,Data:this.marshal()}).subarray()}encrypt(e){return XE(this._key,e)}equals(e){return _e(this.bytes,e.bytes)}async hash(){let{bytes:e}=await st.digest(this.bytes);return e}},ys=class{constructor(e,r){this._key=e,this._publicKey=r}genSecret(){return Zr(16)}async sign(e){return await GE(this._key,e)}get public(){if(this._publicKey==null)throw(0,Jf.default)(new Error("public key not provided"),"ERR_PUBKEY_NOT_PROVIDED");return new mo(this._publicKey)}decrypt(e){return jE(this._key,e)}marshal(){return pi.jwkToPkcs1(this._key)}get bytes(){return Ar.encode({Type:Fe.RSA,Data:this.marshal()}).subarray()}equals(e){return _e(this.bytes,e.bytes)}async hash(){let{bytes:e}=await st.digest(this.bytes);return e}async id(){let e=await this.public.hash();return Q(e,"base58btc")}async export(e,r="pkcs-8"){if(r==="pkcs-8"){let n=new po.default.util.ByteBuffer(this.marshal()),i=po.default.asn1.fromDer(n),s=po.default.pki.privateKeyFromAsn1(i),o={algorithm:"aes256",count:1e4,saltSize:128/8,prfAlgorithm:"sha512"};return po.default.pki.encryptRsaPrivateKey(s,e,o)}else{if(r==="libp2p-key")return await ms(this.bytes,e);throw(0,Jf.default)(new Error(`export format '${r}' is not supported`),"ERR_INVALID_EXPORT_FORMAT")}}};async function JC(t){let e=pi.pkcs1ToJwk(t),r=await Zf(e);return new ys(r.privateKey,r.publicKey)}function eI(t){let e=pi.pkixToJwk(t);return new mo(e)}async function tI(t){let e=await Zf(t);return new ys(e.privateKey,e.publicKey)}async function rI(t){let e=await $E(t);return new ys(e.privateKey,e.publicKey)}var lh={};pt(lh,{Ed25519PrivateKey:()=>yi,Ed25519PublicKey:()=>wo,generateKeyPair:()=>bI,generateKeyPairFromSeed:()=>fv,unmarshalEd25519PrivateKey:()=>wI,unmarshalEd25519PublicKey:()=>xI});var uh=C(G(),1);var nI=C(Zn(),1);var dt=BigInt(0),he=BigInt(1),gs=BigInt(2),ZE=BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),Ve=Object.freeze({a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),P:BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),l:ZE,n:ZE,h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960")});var rv=BigInt("0x10000000000000000000000000000000000000000000000000000000000000000"),yo=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),hO=BigInt("6853475219497561581579357271197624642482790079785650197046958215289687604742"),iI=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),sI=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),oI=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),aI=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),fe=class{constructor(e,r,n,i){this.x=e,this.y=r,this.z=n,this.t=i}static fromAffine(e){if(!(e instanceof qe))throw new TypeError("ExtendedPoint#fromAffine: expected Point");return e.equals(qe.ZERO)?fe.ZERO:new fe(e.x,e.y,he,T(e.x*e.y))}static toAffineBatch(e){let r=lI(e.map(n=>n.z));return e.map((n,i)=>n.toAffine(r[i]))}static normalizeZ(e){return this.toAffineBatch(e).map(this.fromAffine)}equals(e){JE(e);let{x:r,y:n,z:i}=this,{x:s,y:o,z:a}=e,c=T(r*a),u=T(s*i),l=T(n*a),f=T(o*i);return c===u&&l===f}negate(){return new fe(T(-this.x),this.y,this.z,T(-this.t))}double(){let{x:e,y:r,z:n}=this,{a:i}=Ve,s=T(e*e),o=T(r*r),a=T(gs*T(n*n)),c=T(i*s),u=e+r,l=T(T(u*u)-s-o),f=c+o,h=f-a,d=c-o,p=T(l*h),y=T(f*d),g=T(l*d),E=T(h*f);return new fe(p,y,E,g)}add(e){JE(e);let{x:r,y:n,z:i,t:s}=this,{x:o,y:a,z:c,t:u}=e,l=T((n-r)*(a+o)),f=T((n+r)*(a-o)),h=T(f-l);if(h===dt)return this.double();let d=T(i*gs*u),p=T(s*gs*c),y=p+d,g=f+l,E=p-d,x=T(y*h),_=T(g*E),B=T(y*E),D=T(h*g);return new fe(x,_,D,B)}subtract(e){return this.add(e.negate())}precomputeWindow(e){let r=1+256/e,n=[],i=this,s=i;for(let o=0;o<r;o++){s=i,n.push(s);for(let a=1;a<2**(e-1);a++)s=s.add(i),n.push(s);i=s.double()}return n}wNAF(e,r){!r&&this.equals(fe.BASE)&&(r=qe.BASE);let n=r&&r._WINDOW_SIZE||1;if(256%n)throw new Error("Point#wNAF: Invalid precomputation window, must be power of 2");let i=r&&sh.get(r);i||(i=this.precomputeWindow(n),r&&n!==1&&(i=fe.normalizeZ(i),sh.set(r,i)));let s=fe.ZERO,o=fe.ZERO,a=1+256/n,c=2**(n-1),u=BigInt(2**n-1),l=2**n,f=BigInt(n);for(let h=0;h<a;h++){let d=h*c,p=Number(e&u);if(e>>=f,p>c&&(p-=l,e+=he),p===0){let y=i[d];h%2&&(y=y.negate()),o=o.add(y)}else{let y=i[d+Math.abs(p)-1];p<0&&(y=y.negate()),s=s.add(y)}}return fe.normalizeZ([s,o])[0]}multiply(e,r){return this.wNAF(Tc(e,Ve.l),r)}multiplyUnsafe(e){let r=Tc(e,Ve.l,!1),n=fe.BASE,i=fe.ZERO;if(r===dt)return i;if(this.equals(i)||r===he)return this;if(this.equals(n))return this.wNAF(r);let s=i,o=this;for(;r>dt;)r&he&&(s=s.add(o)),o=o.double(),r>>=he;return s}isSmallOrder(){return this.multiplyUnsafe(Ve.h).equals(fe.ZERO)}isTorsionFree(){return this.multiplyUnsafe(Ve.l).equals(fe.ZERO)}toAffine(e=Rc(this.z)){let{x:r,y:n,z:i}=this,s=T(r*e),o=T(n*e);if(T(i*e)!==he)throw new Error("invZ was invalid");return new qe(s,o)}fromRistrettoBytes(){rh()}toRistrettoBytes(){rh()}fromRistrettoHash(){rh()}};fe.BASE=new fe(Ve.Gx,Ve.Gy,he,T(Ve.Gx*Ve.Gy));fe.ZERO=new fe(dt,he,he,dt);function JE(t){if(!(t instanceof fe))throw new TypeError("ExtendedPoint expected")}function th(t){if(!(t instanceof At))throw new TypeError("RistrettoPoint expected")}function rh(){throw new Error("Legacy method: switch to RistrettoPoint")}var At=class{constructor(e){this.ep=e}static calcElligatorRistrettoMap(e){let{d:r}=Ve,n=T(yo*e*e),i=T((n+he)*oI),s=BigInt(-1),o=T((s-r*n)*T(n+r)),{isValid:a,value:c}=ah(i,o),u=T(c*e);Dn(u)||(u=T(-u)),a||(c=u),a||(s=n);let l=T(s*(n-he)*aI-o),f=c*c,h=T((c+c)*o),d=T(l*iI),p=T(he-f),y=T(he+f);return new fe(T(h*y),T(p*d),T(d*y),T(h*p))}static hashToCurve(e){e=Ln(e,64);let r=nh(e.slice(0,32)),n=this.calcElligatorRistrettoMap(r),i=nh(e.slice(32,64)),s=this.calcElligatorRistrettoMap(i);return new At(n.add(s))}static fromHex(e){e=Ln(e,32);let{a:r,d:n}=Ve,i="RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint",s=nh(e);if(!hI(go(s),e)||Dn(s))throw new Error(i);let o=T(s*s),a=T(he+r*o),c=T(he-r*o),u=T(a*a),l=T(c*c),f=T(r*n*u-l),{isValid:h,value:d}=tv(T(f*l)),p=T(d*c),y=T(d*p*f),g=T((s+s)*p);Dn(g)&&(g=T(-g));let E=T(a*y),x=T(g*E);if(!h||Dn(x)||E===dt)throw new Error(i);return new At(new fe(g,E,he,x))}toRawBytes(){let{x:e,y:r,z:n,t:i}=this.ep,s=T(T(n+r)*T(n-r)),o=T(e*r),a=T(o*o),{value:c}=tv(T(s*a)),u=T(c*s),l=T(c*o),f=T(u*l*i),h;if(Dn(i*f)){let p=T(r*yo),y=T(e*yo);e=p,r=y,h=T(u*sI)}else h=l;Dn(e*f)&&(r=T(-r));let d=T((n-r)*h);return Dn(d)&&(d=T(-d)),go(d)}toHex(){return Eo(this.toRawBytes())}toString(){return this.toHex()}equals(e){th(e);let r=this.ep,n=e.ep,i=T(r.x*n.y)===T(r.y*n.x),s=T(r.y*n.y)===T(r.x*n.x);return i||s}add(e){return th(e),new At(this.ep.add(e.ep))}subtract(e){return th(e),new At(this.ep.subtract(e.ep))}multiply(e){return new At(this.ep.multiply(e))}multiplyUnsafe(e){return new At(this.ep.multiplyUnsafe(e))}};At.BASE=new At(fe.BASE);At.ZERO=new At(fe.ZERO);var sh=new WeakMap,qe=class{constructor(e,r){this.x=e,this.y=r}_setWindowSize(e){this._WINDOW_SIZE=e,sh.delete(this)}static fromHex(e,r=!0){let{d:n,P:i}=Ve;e=Ln(e,32);let s=e.slice();s[31]=e[31]&-129;let o=vo(s);if(r&&o>=i)throw new Error("Expected 0 < hex < P");if(!r&&o>=rv)throw new Error("Expected 0 < hex < 2**256");let a=T(o*o),c=T(a-he),u=T(n*a+he),{isValid:l,value:f}=ah(c,u);if(!l)throw new Error("Point.fromHex: invalid y coordinate");let h=(f&he)===he;return(e[31]&128)!==0!==h&&(f=T(-f)),new qe(f,o)}static async fromPrivateKey(e){return(await Nc(e)).point}toRawBytes(){let e=go(this.y);return e[31]|=this.x&he?128:0,e}toHex(){return Eo(this.toRawBytes())}toX25519(){let{y:e}=this,r=T((he+e)*Rc(he-e));return go(r)}isTorsionFree(){return fe.fromAffine(this).isTorsionFree()}equals(e){return this.x===e.x&&this.y===e.y}negate(){return new qe(T(-this.x),this.y)}add(e){return fe.fromAffine(this).add(fe.fromAffine(e)).toAffine()}subtract(e){return this.add(e.negate())}multiply(e){return fe.fromAffine(this).multiply(e,this).toAffine()}};qe.BASE=new qe(Ve.Gx,Ve.Gy);qe.ZERO=new qe(dt,he);var mi=class{constructor(e,r){this.r=e,this.s=r,this.assertValidity()}static fromHex(e){let r=Ln(e,64),n=qe.fromHex(r.slice(0,32),!1),i=vo(r.slice(32,64));return new mi(n,i)}assertValidity(){let{r:e,s:r}=this;if(!(e instanceof qe))throw new Error("Expected Point instance");return Tc(r,Ve.l,!1),this}toRawBytes(){let e=new Uint8Array(64);return e.set(this.r.toRawBytes()),e.set(go(this.s),32),e}toHex(){return Eo(this.toRawBytes())}};function ev(...t){if(!t.every(n=>n instanceof Uint8Array))throw new Error("Expected Uint8Array list");if(t.length===1)return t[0];let e=t.reduce((n,i)=>n+i.length,0),r=new Uint8Array(e);for(let n=0,i=0;n<t.length;n++){let s=t[n];r.set(s,i),i+=s.length}return r}var cI=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Eo(t){if(!(t instanceof Uint8Array))throw new Error("Uint8Array expected");let e="";for(let r=0;r<t.length;r++)e+=cI[t[r]];return e}function oh(t){if(typeof t!="string")throw new TypeError("hexToBytes: expected string, got "+typeof t);if(t.length%2)throw new Error("hexToBytes: received invalid unpadded hex");let e=new Uint8Array(t.length/2);for(let r=0;r<e.length;r++){let n=r*2,i=t.slice(n,n+2),s=Number.parseInt(i,16);if(Number.isNaN(s)||s<0)throw new Error("Invalid byte sequence");e[r]=s}return e}function nv(t){let r=t.toString(16).padStart(64,"0");return oh(r)}function go(t){return nv(t).reverse()}function Dn(t){return(T(t)&he)===he}function vo(t){if(!(t instanceof Uint8Array))throw new Error("Expected Uint8Array");return BigInt("0x"+Eo(Uint8Array.from(t).reverse()))}var uI=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");function nh(t){return T(vo(t)&uI)}function T(t,e=Ve.P){let r=t%e;return r>=dt?r:e+r}function Rc(t,e=Ve.P){if(t===dt||e<=dt)throw new Error(`invert: expected positive integers, got n=${t} mod=${e}`);let r=T(t,e),n=e,i=dt,s=he,o=he,a=dt;for(;r!==dt;){let u=n/r,l=n%r,f=i-o*u,h=s-a*u;n=r,r=l,i=o,s=a,o=f,a=h}if(n!==he)throw new Error("invert: does not exist");return T(i,e)}function lI(t,e=Ve.P){let r=new Array(t.length),n=t.reduce((s,o,a)=>o===dt?s:(r[a]=s,T(s*o,e)),he),i=Rc(n,e);return t.reduceRight((s,o,a)=>o===dt?s:(r[a]=T(s*r[a],e),T(s*o,e)),i),r}function Ir(t,e){let{P:r}=Ve,n=t;for(;e-- >dt;)n*=n,n%=r;return n}function fI(t){let{P:e}=Ve,r=BigInt(5),n=BigInt(10),i=BigInt(20),s=BigInt(40),o=BigInt(80),c=t*t%e*t%e,u=Ir(c,gs)*c%e,l=Ir(u,he)*t%e,f=Ir(l,r)*l%e,h=Ir(f,n)*f%e,d=Ir(h,i)*h%e,p=Ir(d,s)*d%e,y=Ir(p,o)*p%e,g=Ir(y,o)*p%e,E=Ir(g,n)*f%e;return{pow_p_5_8:Ir(E,gs)*t%e,b2:c}}function ah(t,e){let r=T(e*e*e),n=T(r*r*e),i=fI(t*n).pow_p_5_8,s=T(t*r*i),o=T(e*s*s),a=s,c=T(s*yo),u=o===t,l=o===T(-t),f=o===T(-t*yo);return u&&(s=a),(l||f)&&(s=c),Dn(s)&&(s=T(-s)),{isValid:u||l,value:s}}function tv(t){return ah(he,t)}function Ic(t){return T(vo(t),Ve.l)}function hI(t,e){if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(t[r]!==e[r])return!1;return!0}function Ln(t,e){let r=t instanceof Uint8Array?Uint8Array.from(t):oh(t);if(typeof e=="number"&&r.length!==e)throw new Error(`Expected ${e} bytes`);return r}function Tc(t,e,r=!0){if(!e)throw new TypeError("Specify max value");if(typeof t=="number"&&Number.isSafeInteger(t)&&(t=BigInt(t)),typeof t=="bigint"&&t<e){if(r){if(dt<t)return t}else if(dt<=t)return t}throw new TypeError("Expected valid scalar: 0 < scalar < max")}function dI(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}function pI(t){if(t=typeof t=="bigint"||typeof t=="number"?nv(Tc(t,rv)):Ln(t),t.length!==32)throw new Error("Expected 32 bytes");return t}function mI(t){let e=dI(t.slice(0,32)),r=t.slice(32,64),n=Ic(e),i=qe.BASE.multiply(n),s=i.toRawBytes();return{head:e,prefix:r,scalar:n,point:i,pointBytes:s}}var ih;async function Nc(t){return mI(await Pn.sha512(pI(t)))}async function ch(t){return(await Nc(t)).pointBytes}async function iv(t,e){t=Ln(t);let{prefix:r,scalar:n,pointBytes:i}=await Nc(e),s=Ic(await Pn.sha512(r,t)),o=qe.BASE.multiply(s),a=Ic(await Pn.sha512(o.toRawBytes(),i,t)),c=T(s+a*n,Ve.l);return new mi(o,c).toRawBytes()}function yI(t,e,r){e=Ln(e),r instanceof qe||(r=qe.fromHex(r,!1));let{r:n,s:i}=t instanceof mi?t.assertValidity():mi.fromHex(t),s=fe.BASE.multiplyUnsafe(i);return{r:n,s:i,SB:s,pub:r,msg:e}}function gI(t,e,r,n){let i=Ic(n),s=fe.fromAffine(t).multiplyUnsafe(i);return fe.fromAffine(e).add(s).subtract(r).multiplyUnsafe(Ve.h).equals(fe.ZERO)}async function sv(t,e,r){let{r:n,SB:i,msg:s,pub:o}=yI(t,e,r),a=await Pn.sha512(n.toRawBytes(),o.toRawBytes(),s);return gI(o,n,i,a)}qe.BASE._setWindowSize(8);var Nn={node:nI,web:typeof self=="object"&&"crypto"in self?self.crypto:void 0},Pn={bytesToHex:Eo,hexToBytes:oh,concatBytes:ev,getExtendedPublicKey:Nc,mod:T,invert:Rc,TORSION_SUBGROUP:["0100000000000000000000000000000000000000000000000000000000000000","c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a","0000000000000000000000000000000000000000000000000000000000000080","26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05","ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f","26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85","0000000000000000000000000000000000000000000000000000000000000000","c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa"],hashToPrivateScalar:t=>{if(t=Ln(t),t.length<40||t.length>1024)throw new Error("Expected 40-1024 bytes of private key as per FIPS 186");return T(vo(t),Ve.l-he)+he},randomBytes:(t=32)=>{if(Nn.web)return Nn.web.getRandomValues(new Uint8Array(t));if(Nn.node){let{randomBytes:e}=Nn.node;return new Uint8Array(e(t).buffer)}else throw new Error("The environment doesn't have randomBytes function")},randomPrivateKey:()=>Pn.randomBytes(32),sha512:async(...t)=>{let e=ev(...t);if(Nn.web){let r=await Nn.web.subtle.digest("SHA-512",e.buffer);return new Uint8Array(r)}else{if(Nn.node)return Uint8Array.from(Nn.node.createHash("sha512").update(e).digest());throw new Error("The environment doesn't have sha512 function")}},precompute(t=8,e=qe.BASE){let r=e.equals(qe.BASE)?e:new qe(e.x,e.y);return r._setWindowSize(t),r.multiply(gs),r},sha512Sync:void 0};Object.defineProperties(Pn,{sha512Sync:{configurable:!1,get(){return ih},set(t){ih||(ih=t)}}});var Es=32,en=64,Dc=32;async function ov(){let t=Pn.randomPrivateKey(),e=await ch(t);return{privateKey:lv(t,e),publicKey:e}}async function av(t){if(t.length!==Dc)throw new TypeError('"seed" must be 32 bytes in length.');if(!(t instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');let e=t,r=await ch(e);return{privateKey:lv(e,r),publicKey:r}}async function cv(t,e){let r=t.subarray(0,Dc);return await iv(e,r)}async function uv(t,e,r){return await sv(e,r,t)}function lv(t,e){let r=new Uint8Array(en);for(let n=0;n<Dc;n++)r[n]=t[n],r[Dc+n]=e[n];return r}var wo=class{constructor(e){this._key=vs(e,Es)}async verify(e,r){return await uv(this._key,r,e)}marshal(){return this._key}get bytes(){return _r.encode({Type:Fe.Ed25519,Data:this.marshal()}).subarray()}equals(e){return _e(this.bytes,e.bytes)}async hash(){let{bytes:e}=await st.digest(this.bytes);return e}},yi=class{constructor(e,r){this._key=vs(e,en),this._publicKey=vs(r,Es)}async sign(e){return await cv(this._key,e)}get public(){return new wo(this._publicKey)}marshal(){return this._key}get bytes(){return Ar.encode({Type:Fe.Ed25519,Data:this.marshal()}).subarray()}equals(e){return _e(this.bytes,e.bytes)}async hash(){let{bytes:e}=await st.digest(this.bytes);return e}async id(){let e=await fn.digest(this.public.bytes);return We.encode(e.bytes).substring(1)}async export(e,r="libp2p-key"){if(r==="libp2p-key")return await ms(this.bytes,e);throw(0,uh.default)(new Error(`export format '${r}' is not supported`),"ERR_INVALID_EXPORT_FORMAT")}};function wI(t){if(t.length>en){t=vs(t,en+Es);let n=t.subarray(0,en),i=t.subarray(en,t.length);return new yi(n,i)}t=vs(t,en);let e=t.subarray(0,en),r=t.subarray(Es);return new yi(e,r)}function xI(t){return t=vs(t,Es),new wo(t)}async function bI(){let{privateKey:t,publicKey:e}=await ov();return new yi(t,e)}async function fv(t){let{privateKey:e,publicKey:r}=await av(t);return new yi(e,r)}function vs(t,e){if(t=Uint8Array.from(t??[]),t.length!==e)throw(0,uh.default)(new Error(`Key must be a Uint8Array of length ${e}, got ${t.length}`),"ERR_INVALID_KEY_TYPE");return t}var hh={};pt(hh,{Secp256k1PrivateKey:()=>bo,Secp256k1PublicKey:()=>xo,generateKeyPair:()=>CI,unmarshalSecp256k1PrivateKey:()=>_I,unmarshalSecp256k1PublicKey:()=>AI});var Ev=C(G(),1);var ws=C(G(),1);function hv(){return sr.randomPrivateKey()}async function dv(t,e){let{digest:r}=await st.digest(e);try{return await ME(r,t)}catch(n){throw(0,ws.default)(n,"ERR_INVALID_INPUT")}}async function pv(t,e,r){try{let{digest:n}=await st.digest(r);return FE(e,n,t)}catch(n){throw(0,ws.default)(n,"ERR_INVALID_INPUT")}}function mv(t){return we.fromHex(t).toRawBytes(!0)}function yv(t){try{Qf(t,!0)}catch(e){throw(0,ws.default)(e,"ERR_INVALID_PRIVATE_KEY")}}function fh(t){try{we.fromHex(t)}catch(e){throw(0,ws.default)(e,"ERR_INVALID_PUBLIC_KEY")}}function gv(t){try{return Qf(t,!0)}catch(e){throw(0,ws.default)(e,"ERR_INVALID_PRIVATE_KEY")}}var xo=class{constructor(e){fh(e),this._key=e}async verify(e,r){return await pv(this._key,r,e)}marshal(){return mv(this._key)}get bytes(){return _r.encode({Type:Fe.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return _e(this.bytes,e.bytes)}async hash(){let{bytes:e}=await st.digest(this.bytes);return e}},bo=class{constructor(e,r){this._key=e,this._publicKey=r??gv(e),yv(this._key),fh(this._publicKey)}async sign(e){return await dv(this._key,e)}get public(){return new xo(this._publicKey)}marshal(){return this._key}get bytes(){return Ar.encode({Type:Fe.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return _e(this.bytes,e.bytes)}async hash(){let{bytes:e}=await st.digest(this.bytes);return e}async id(){let e=await this.public.hash();return Q(e,"base58btc")}async export(e,r="libp2p-key"){if(r==="libp2p-key")return await ms(this.bytes,e);throw(0,Ev.default)(new Error(`export format '${r}' is not supported`),"ERR_INVALID_EXPORT_FORMAT")}};function _I(t){return new bo(t)}function AI(t){return new xo(t)}async function CI(){let t=await hv();return new bo(t)}var tn={rsa:eh,ed25519:lh,secp256k1:hh};function ph(t){let e=Object.keys(tn).join(" / ");return(0,dh.default)(new Error(`invalid or unsupported key type ${t}. Must be ${e}`),"ERR_UNSUPPORTED_KEY_TYPE")}function mh(t){if(t=t.toLowerCase(),t==="rsa"||t==="ed25519"||t==="secp256k1")return tn[t];throw ph(t)}async function Pc(t,e){return await mh(t).generateKeyPair(e??2048)}function So(t){let e=_r.decode(t),r=e.Data??new Uint8Array;switch(e.Type){case Fe.RSA:return tn.rsa.unmarshalRsaPublicKey(r);case Fe.Ed25519:return tn.ed25519.unmarshalEd25519PublicKey(r);case Fe.Secp256k1:return tn.secp256k1.unmarshalSecp256k1PublicKey(r);default:throw ph(e.Type??"RSA")}}function vv(t,e){return e=(e??"rsa").toLowerCase(),mh(e),t.bytes}async function xs(t){let e=Ar.decode(t),r=e.Data??new Uint8Array;switch(e.Type){case Fe.RSA:return await tn.rsa.unmarshalRsaPrivateKey(r);case Fe.Ed25519:return tn.ed25519.unmarshalEd25519PrivateKey(r);case Fe.Secp256k1:return tn.secp256k1.unmarshalSecp256k1PrivateKey(r);default:throw ph(e.Type??"RSA")}}function wv(t,e){return e=(e??"rsa").toLowerCase(),mh(e),t.bytes}async function Bc(t,e){try{let i=await bE(t,e);return await xs(i)}catch{}let r=Lc.default.pki.decryptRsaPrivateKey(t,e);if(r===null)throw(0,dh.default)(new Error("Cannot read the key, most likely the password is wrong or not a RSA key"),"ERR_CANNOT_DECRYPT_PEM");let n=Lc.default.asn1.toDer(Lc.default.pki.privateKeyToAsn1(r));return n=q(n.getBytes(),"ascii"),await tn.rsa.unmarshalRsaPrivateKey(n)}var DO=C(rs(),1),TI=C(ie(),1);var NI=C(G(),1);var bv=C(Mf(),1),Sv=C(De(),1),_v=C(G(),1),xv={sha1:"sha1","sha2-256":"sha256","sha2-512":"sha512"};function _o(t,e,r,n,i){if(i!=="sha1"&&i!=="sha2-256"&&i!=="sha2-512"){let a=Object.keys(xv).join(" / ");throw(0,_v.default)(new Error(`Hash '${i}' is unknown or not supported. Must be ${a}`),"ERR_UNSUPPORTED_HASH_TYPE")}let s=xv[i],o=(0,bv.default)(t,e,r,n,s);return Sv.default.encode64(o,null)}var Oc=M("libp2p:keychain"),LI="/pkcs8/",Cv="/info/",Bn=new WeakMap,gi={minKeyLength:112/8,minSaltLength:128/8,minIterationCount:1e3},yh={dek:{keyLength:512/8,iterationCount:1e4,salt:"you should override this value with a crypto secure random number",hash:"sha2-512"}};function rn(t){return t==null||typeof t!="string"?!1:t===(0,Av.default)(t.trim())&&t.length>0}async function be(){let r=Math.random()*800+200;await new Promise(n=>setTimeout(n,r))}function Tr(t){return new $e(LI+t)}function nn(t){return new $e(Cv+t)}var Ao=class{constructor(e,r){if(this.components=e,this.init=pr(yh,r),this.init.pass!=null&&this.init.pass?.length<20)throw new Error("pass must be least 20 characters");if(this.init.dek?.keyLength!=null&&this.init.dek.keyLength<gi.minKeyLength)throw new Error(`dek.keyLength must be least ${gi.minKeyLength} bytes`);if(this.init.dek?.salt?.length!=null&&this.init.dek.salt.length<gi.minSaltLength)throw new Error(`dek.saltLength must be least ${gi.minSaltLength} bytes`);if(this.init.dek?.iterationCount!=null&&this.init.dek.iterationCount<gi.minIterationCount)throw new Error(`dek.iterationCount must be least ${gi.minIterationCount}`);let n=this.init.pass!=null&&this.init.dek?.salt!=null?_o(this.init.pass,this.init.dek?.salt,this.init.dek?.iterationCount,this.init.dek?.keyLength,this.init.dek?.hash):"";Bn.set(this,{dek:n}),this.started=!1}isStarted(){return this.started}async start(){let e=nn("self");await this.components.datastore.has(e)||await this.importPeer("self",this.components.peerId),this.started=!0}stop(){this.started=!1}get cms(){let e=Bn.get(this);if(e==null)throw(0,ye.default)(new Error("dek missing"),b.ERR_INVALID_PARAMETERS);let r=e.dek;return new vc(this,r)}static generateOptions(){let e=Object.assign({},yh),r=Math.ceil(gi.minSaltLength/3)*3;return e.dek.salt=Q(Zr(r),"base64"),e}static get options(){return yh}async createKey(e,r,n=2048){if(!rn(e)||e==="self")throw await be(),(0,ye.default)(new Error("Invalid key name"),b.ERR_INVALID_KEY_NAME);if(typeof r!="string")throw await be(),(0,ye.default)(new Error("Invalid key type"),b.ERR_INVALID_KEY_TYPE);let i=Tr(e);if(await this.components.datastore.has(i))throw await be(),(0,ye.default)(new Error("Key name already exists"),b.ERR_KEY_ALREADY_EXISTS);switch(r.toLowerCase()){case"rsa":if(!Number.isSafeInteger(n)||n<2048)throw await be(),(0,ye.default)(new Error("Invalid RSA key size"),b.ERR_INVALID_KEY_SIZE);break;default:break}let o;try{let a=await Pc(r,n),c=await a.id(),u=Bn.get(this);if(u==null)throw(0,ye.default)(new Error("dek missing"),b.ERR_INVALID_PARAMETERS);let l=u.dek,f=await a.export(l);o={name:e,id:c};let h=this.components.datastore.batch();h.put(i,q(f)),h.put(nn(e),q(JSON.stringify(o))),await h.commit()}catch(a){throw await be(),a}return o}async listKeys(){let e={prefix:Cv},r=[];for await(let n of this.components.datastore.query(e))r.push(JSON.parse(Q(n.value)));return r}async findKeyById(e){try{return(await this.listKeys()).find(n=>n.id===e)}catch(r){throw await be(),r}}async findKeyByName(e){if(!rn(e))throw await be(),(0,ye.default)(new Error(`Invalid key name '${e}'`),b.ERR_INVALID_KEY_NAME);let r=nn(e);try{let n=await this.components.datastore.get(r);return JSON.parse(Q(n))}catch(n){throw await be(),Oc.error(n),(0,ye.default)(new Error(`Key '${e}' does not exist.`),b.ERR_KEY_NOT_FOUND)}}async removeKey(e){if(!rn(e)||e==="self")throw await be(),(0,ye.default)(new Error(`Invalid key name '${e}'`),b.ERR_INVALID_KEY_NAME);let r=Tr(e),n=await this.findKeyByName(e),i=this.components.datastore.batch();return i.delete(r),i.delete(nn(e)),await i.commit(),n}async renameKey(e,r){if(!rn(e)||e==="self")throw await be(),(0,ye.default)(new Error(`Invalid old key name '${e}'`),b.ERR_OLD_KEY_NAME_INVALID);if(!rn(r)||r==="self")throw await be(),(0,ye.default)(new Error(`Invalid new key name '${r}'`),b.ERR_NEW_KEY_NAME_INVALID);let n=Tr(e),i=Tr(r),s=nn(e),o=nn(r);if(await this.components.datastore.has(i))throw await be(),(0,ye.default)(new Error(`Key '${r}' already exists`),b.ERR_KEY_ALREADY_EXISTS);try{let c=await this.components.datastore.get(n),u=await this.components.datastore.get(s),l=JSON.parse(Q(u));l.name=r;let f=this.components.datastore.batch();return f.put(i,c),f.put(o,q(JSON.stringify(l))),f.delete(n),f.delete(s),await f.commit(),l}catch(c){throw await be(),c}}async exportKey(e,r){if(!rn(e))throw await be(),(0,ye.default)(new Error(`Invalid key name '${e}'`),b.ERR_INVALID_KEY_NAME);if(r==null)throw await be(),(0,ye.default)(new Error("Password is required"),b.ERR_PASSWORD_REQUIRED);let n=Tr(e);try{let i=await this.components.datastore.get(n),s=Q(i),o=Bn.get(this);if(o==null)throw(0,ye.default)(new Error("dek missing"),b.ERR_INVALID_PARAMETERS);let a=o.dek;return await(await Bc(s,a)).export(r)}catch(i){throw await be(),i}}async importKey(e,r,n){if(!rn(e)||e==="self")throw await be(),(0,ye.default)(new Error(`Invalid key name '${e}'`),b.ERR_INVALID_KEY_NAME);if(r==null)throw await be(),(0,ye.default)(new Error("PEM encoded key is required"),b.ERR_PEM_REQUIRED);let i=Tr(e);if(await this.components.datastore.has(i))throw await be(),(0,ye.default)(new Error(`Key '${e}' already exists`),b.ERR_KEY_ALREADY_EXISTS);let o;try{o=await Bc(r,n)}catch{throw await be(),(0,ye.default)(new Error("Cannot read the key, most likely the password is wrong"),b.ERR_CANNOT_READ_KEY)}let a;try{a=await o.id();let l=Bn.get(this);if(l==null)throw(0,ye.default)(new Error("dek missing"),b.ERR_INVALID_PARAMETERS);let f=l.dek;r=await o.export(f)}catch(l){throw await be(),l}let c={name:e,id:a},u=this.components.datastore.batch();return u.put(i,q(r)),u.put(nn(e),q(JSON.stringify(c))),await u.commit(),c}async importPeer(e,r){try{if(!rn(e))throw(0,ye.default)(new Error(`Invalid key name '${e}'`),b.ERR_INVALID_KEY_NAME);if(r==null)throw(0,ye.default)(new Error("PeerId is required"),b.ERR_MISSING_PRIVATE_KEY);if(r.privateKey==null)throw(0,ye.default)(new Error("PeerId.privKey is required"),b.ERR_MISSING_PRIVATE_KEY);let n=await xs(r.privateKey),i=Tr(e);if(await this.components.datastore.has(i))throw await be(),(0,ye.default)(new Error(`Key '${e}' already exists`),b.ERR_KEY_ALREADY_EXISTS);let o=Bn.get(this);if(o==null)throw(0,ye.default)(new Error("dek missing"),b.ERR_INVALID_PARAMETERS);let a=o.dek,c=await n.export(a),u={name:e,id:r.toString()},l=this.components.datastore.batch();return l.put(i,q(c)),l.put(nn(e),q(JSON.stringify(u))),await l.commit(),u}catch(n){throw await be(),n}}async getPrivateKey(e){if(!rn(e))throw await be(),(0,ye.default)(new Error(`Invalid key name '${e}'`),b.ERR_INVALID_KEY_NAME);try{let r=Tr(e),n=await this.components.datastore.get(r);return Q(n)}catch(r){throw await be(),Oc.error(r),(0,ye.default)(new Error(`Key '${e}' does not exist.`),b.ERR_KEY_NOT_FOUND)}}async rotateKeychainPass(e,r){if(typeof e!="string")throw await be(),(0,ye.default)(new Error(`Invalid old pass type '${typeof e}'`),b.ERR_INVALID_OLD_PASS_TYPE);if(typeof r!="string")throw await be(),(0,ye.default)(new Error(`Invalid new pass type '${typeof r}'`),b.ERR_INVALID_NEW_PASS_TYPE);if(r.length<20)throw await be(),(0,ye.default)(new Error(`Invalid pass length ${r.length}`),b.ERR_INVALID_PASS_LENGTH);Oc("recreating keychain");let n=Bn.get(this);if(n==null)throw(0,ye.default)(new Error("dek missing"),b.ERR_INVALID_PARAMETERS);let i=n.dek;this.init.pass=r;let s=r!=null&&this.init.dek?.salt!=null?_o(r,this.init.dek.salt,this.init.dek?.iterationCount,this.init.dek?.keyLength,this.init.dek?.hash):"";Bn.set(this,{dek:s});let o=await this.listKeys();for(let a of o){let c=await this.components.datastore.get(Tr(a.name)),u=Q(c),l=await Bc(u,i),f=s.toString(),h=await l.export(f),d=this.components.datastore.batch(),p={name:a.name,id:a.id};d.put(Tr(a.name),q(h)),d.put(nn(a.name),q(JSON.stringify(p))),await d.commit()}Oc("keychain reconstructed")}};async function Co(t){try{return{status:"fulfilled",value:await t,isFulfilled:!0,isRejected:!1}}catch(e){return{status:"rejected",reason:e,isFulfilled:!1,isRejected:!0}}}var gh=class{value;next;constructor(e){this.value=e}},Io=class{#e;#t;#r;constructor(){this.clear()}enqueue(e){let r=new gh(e);this.#e?(this.#t.next=r,this.#t=r):(this.#e=r,this.#t=r),this.#r++}dequeue(){let e=this.#e;if(e)return this.#e=this.#e.next,this.#r--,e.value}clear(){this.#e=void 0,this.#t=void 0,this.#r=0}get size(){return this.#r}*[Symbol.iterator](){let e=this.#e;for(;e;)yield e.value,e=e.next}};function Eh(t){if(!((Number.isInteger(t)||t===Number.POSITIVE_INFINITY)&&t>0))throw new TypeError("Expected `concurrency` to be a number from 1 and up");let e=new Io,r=0,n=()=>{r--,e.size>0&&e.dequeue()()},i=async(a,c,u)=>{r++;let l=(async()=>a(...u))();c(l);try{await l}catch{}n()},s=(a,c,u)=>{e.enqueue(i.bind(void 0,a,c,u)),(async()=>(await Promise.resolve(),r<t&&e.size>0&&e.dequeue()()))()},o=(a,...c)=>new Promise(u=>{s(a,u,c)});return Object.defineProperties(o,{activeCount:{get:()=>r},pendingCount:{get:()=>e.size},clearQueue:{value:()=>{e.clear()}}}),o}async function vh(t,e={}){let{concurrency:r=Number.POSITIVE_INFINITY}=e,n=Eh(r);return Promise.all(t.map(i=>i&&typeof i.then=="function"?Co(i):typeof i=="function"?Co(n(()=>i())):Co(Promise.resolve(i))))}var bs=C(G(),1);var wh=class extends Map{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 To(t){let{name:e,metrics:r}=t,n;return r!=null?n=new wh({name:e,metrics:r}):n=new Map,n}var Ei=M("libp2p:transports"),kc=class extends Ue{constructor(e,r={}){super(),this.components=e,this.started=!1,this.transports=new Map,this.listeners=To({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=r.faultTolerance??vi.FATAL_ALL}add(e){let r=e[Symbol.toStringTag];if(r==null)throw(0,bs.default)(new Error("Transport must have a valid tag"),b.ERR_INVALID_KEY);if(this.transports.has(r))throw(0,bs.default)(new Error("There is already a transport with this tag"),b.ERR_DUPLICATE_TRANSPORT);Ei("adding transport %s",r),this.transports.set(r,e),this.listeners.has(r)||this.listeners.set(r,[])}isStarted(){return this.started}async start(){let e=this.components.addressManager.getListenAddrs();await this.listen(e),this.started=!0}async stop(){let e=[];for(let[r,n]of this.listeners)for(Ei("closing listeners for %s",r);n.length>0;){let i=n.pop();i!=null&&e.push(i.close())}await Promise.all(e),Ei("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(0,bs.default)(new Error(`No transport available for address ${String(e)}`),b.ERR_TRANSPORT_UNAVAILABLE);try{return await n.dial(e,{...r,upgrader:this.components.upgrader})}catch(i){throw i.code==null&&(i.code=b.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())}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){Ei("no addresses were provided for listening, this node is dial only");return}let r=[];for(let[n,i]of this.transports.entries()){let s=i.filter(e),o=[];for(let u of s){Ei("creating listener for %s on %s",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.dispatchEvent(new Z("listener:listening",{detail:l}))}),l.addEventListener("close",()=>{this.dispatchEvent(new Z("listener:close",{detail:l}))}),o.push(l.listen(u))}if(o.length===0){r.push(n);continue}if((await vh(o)).find(u=>u.isFulfilled)==null&&this.faultTolerance!==vi.NO_FATAL)throw(0,bs.default)(new Error(`Transport (${n}) could not listen on any available address`),b.ERR_NO_VALID_ADDRESSES)}if(r.length===this.transports.size){let n=`no valid addresses were provided for transports [${r.join(", ")}]`;if(this.faultTolerance===vi.FATAL_ALL)throw(0,bs.default)(new Error(n),b.ERR_NO_VALID_ADDRESSES);Ei(`libp2p in dial mode only: ${n}`)}}async remove(e){Ei("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)}},vi;(function(t){t[t.FATAL_ALL=0]="FATAL_ALL",t[t.NO_FATAL=1]="NO_FATAL"})(vi||(vi={}));var at=C(G(),1);var sn="/multistream/1.0.0";var Nv=C(G(),1);var xh=C(G(),1);var BI=M("libp2p:mss"),Iv=q(`
49
- `);function Ro(t){let e=new Ge(t,Iv);return Vt.single(e)}function wi(t,e,r={}){let n=Ro(e);r.writeBytes===!0?t.push(n.subarray()):t.push(n)}function Tv(t,e,r={}){let n=new Ge;for(let i of e)n.append(Ro(i));r.writeBytes===!0?t.push(n.subarray()):t.push(n)}async function OI(t,e){let r=1,n={[Symbol.asyncIterator]:()=>n,next:async()=>await t.next(r)},i=n;e?.signal!=null&&(i=ni(n,e.signal));let o=await Ce(i,Pt({onLength:a=>{r=a},maxDataLength:1024}),async a=>await Rt(a));if(o==null||o.length===0)throw(0,xh.default)(new Error("no buffer returned"),"ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");if(o.get(o.byteLength-1)!==Iv[0])throw BI.error("Invalid mss message - missing newline - %s",o.subarray()),(0,xh.default)(new Error("missing newline"),"ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");return o.sublist(0,-1)}async function Ss(t,e){let r=await OI(t,e);return Q(r.subarray())}var No=M("libp2p:mss:select");async function Do(t,e,r={}){e=Array.isArray(e)?[...e]:[e];let{reader:n,writer:i,rest:s,stream:o}=Zi(t),a=e.shift();if(a==null)throw new Error("At least one protocol must be specified");No('select: write ["%s", "%s"]',sn,a);let c=q(sn),u=q(a);Tv(i,[c,u],r);let l=await Ss(n,r);if(No('select: read "%s"',l),l===sn&&(l=await Ss(n,r),No('select: read "%s"',l)),l===a)return s(),{stream:o,protocol:a};for(let f of e){No('select: write "%s"',f),wi(i,q(f),r);let h=await Ss(n,r);if(No('select: read "%s" for "%s"',h,f),h===f)return s(),{stream:o,protocol:f}}throw s(),(0,Nv.default)(new Error("protocol selection failed"),"ERR_UNSUPPORTED_PROTOCOL")}var Lo=M("libp2p:mss:handle");async function Po(t,e,r){e=Array.isArray(e)?e:[e];let{writer:n,reader:i,rest:s,stream:o}=Zi(t);for(;;){let a=await Ss(i,r);if(Lo('read "%s"',a),a===sn){Lo('respond with "%s" for "%s"',sn,a),wi(n,q(sn),r);continue}if(e.includes(a))return wi(n,q(a),r),Lo('respond with "%s" for "%s"',a,a),s(),{stream:o,protocol:a};if(a==="ls"){wi(n,new Ge(...e.map(c=>Ro(q(c)))),r),Lo('respond with "%s" for %s',e,a);continue}wi(n,q("na"),r),Lo('respond with "na" for "%s"',a)}}var bh=C(G(),1);var Dv=Symbol.for("@libp2p/connection");var UI=M("libp2p:connection"),Sh=class{constructor(e){let{remoteAddr:r,remotePeer:n,newStream:i,close:s,getStreams:o,stat:a}=e;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=r,this.remotePeer=n,this.stat={...a,status:Ca},this._newStream=i,this._close=s,this._getStreams=o,this.tags=[],this._closing=!1}get[Symbol.toStringTag](){return"Connection"}get[Dv](){return!0}get streams(){return this._getStreams()}async newStream(e,r){if(this.stat.status===_l)throw(0,bh.default)(new Error("the connection is being closed"),"ERR_CONNECTION_BEING_CLOSED");if(this.stat.status===Ia)throw(0,bh.default)(new Error("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===Ia||this._closing)){this.stat.status=_l;try{this.streams.forEach(e=>e.close())}catch(e){UI.error(e)}this._closing=!0,await this._close(),this._closing=!1,this.stat.timeline.close=Date.now(),this.stat.status=Ia}}};function Lv(t){return new Sh(t)}var Uc=C(G(),1);var MI=Symbol.for("@libp2p/topology");function Pv(t){return t!=null&&Boolean(t[MI])}var _h=M("libp2p:registrar"),Ah=32,Ch=64,Mc=class{constructor(e){this.topologies=new Map,this.handlers=new Map,this.components=e,this._onDisconnect=this._onDisconnect.bind(this),this._onProtocolChange=this._onProtocolChange.bind(this),this._onConnect=this._onConnect.bind(this),this.components.connectionManager.addEventListener("peer:disconnect",this._onDisconnect),this.components.connectionManager.addEventListener("peer:connect",this._onConnect),this.components.peerStore.addEventListener("change:protocols",this._onProtocolChange)}getProtocols(){return Array.from(new Set([...this.topologies.keys(),...this.handlers.keys()])).sort()}getHandler(e){let r=this.handlers.get(e);if(r==null)throw(0,Uc.default)(new Error(`No handler registered for protocol ${e}`),b.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(0,Uc.default)(new Error(`Handler already registered for protocol ${e}`),b.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);let i=pr.bind({ignoreUndefined:!0})({maxInboundStreams:Ah,maxOutboundStreams:Ch},n);this.handlers.set(e,{handler:r,options:i}),await this.components.peerStore.protoBook.add(this.components.peerId,[e])}async unhandle(e){let r=Array.isArray(e)?e:[e];r.forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.protoBook.remove(this.components.peerId,r)}async register(e,r){if(!Pv(r))throw _h.error("topology must be an instance of interfaces/topology"),(0,Uc.default)(new Error("topology must be an instance of interfaces/topology"),b.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),await r.setRegistrar(this),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.protoBook.get(r.remotePeer).then(n=>{for(let i of n){let s=this.topologies.get(i);if(s!=null)for(let o of s.values())o.onDisconnect(r.remotePeer)}}).catch(n=>{_h.error(n)})}_onConnect(e){let r=e.detail;this.components.peerStore.protoBook.get(r.remotePeer).then(n=>{for(let i of n){let s=this.topologies.get(i);if(s!=null)for(let o of s.values())o.onConnect(r.remotePeer,r)}}).catch(n=>{_h.error(n)})}_onProtocolChange(e){let{peerId:r,protocols:n,oldProtocols:i}=e.detail,s=i.filter(a=>!n.includes(a)),o=n.filter(a=>!i.includes(a));for(let a of s){let c=this.topologies.get(a);if(c!=null)for(let u of c.values())u.onDisconnect(r)}for(let a of o){let c=this.topologies.get(a);if(c!=null)for(let u of c.values()){let l=this.components.connectionManager.getConnections(r)[0];l!=null&&u.onConnect(r,l)}}}};var Ih=C(Ur(),1);var Th=C(fr(),1),Pe=M("libp2p:upgrader");function FI(t,e){try{let{options:r}=e.getHandler(t);return r.maxInboundStreams}catch(r){if(r.code!==b.ERR_NO_HANDLER_FOR_PROTOCOL)throw r}return Ah}function KI(t,e){try{let{options:r}=e.getHandler(t);return r.maxOutboundStreams}catch(r){if(r.code!==b.ERR_NO_HANDLER_FOR_PROTOCOL)throw r}return Ch}function Bv(t,e,r){let n=0;return r.streams.forEach(i=>{i.stat.direction===e&&i.stat.protocol===t&&n++}),n}var Fc=class extends Ue{constructor(e,r){super(),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}async upgradeInbound(e,r){if(!await this.components.connectionManager.acceptIncomingConnection(e))throw(0,at.default)(new Error("connection denied"),b.ERR_CONNECTION_DENIED);let i,s,o,a,c,u=new Ih.TimeoutController(this.inboundUpgradeTimeout);try{(0,Th.setMaxListeners)?.(1/0,u.signal)}catch{}try{let l=Dt(e,u.signal);if(e.source=l.source,e.sink=l.sink,await this.components.connectionGater.denyInboundConnection(e))throw(0,at.default)(new Error("The multiaddr connection is blocked by gater.acceptConnection"),b.ERR_CONNECTION_INTERCEPTED);this.components.metrics?.trackMultiaddrConnection(e),Pe("starting the inbound connection upgrade");let f=e;if(r?.skipProtection!==!0){let h=this.components.connectionProtector;h!=null&&(Pe("protecting the inbound connection"),f=await h.protect(e))}try{if(i=f,r?.skipEncryption!==!0){if({conn:i,remotePeer:s,protocol:c}=await this._encryptInbound(f),await this.components.connectionGater.denyInboundEncryptedConnection(s,{...f,...i}))throw(0,at.default)(new Error("The multiaddr connection is blocked by gater.acceptEncryptedConnection"),b.ERR_CONNECTION_INTERCEPTED)}else{let h=e.remoteAddr.getPeerId();if(h==null)throw(0,at.default)(new Error("inbound connection that skipped encryption must have a peer id"),b.ERR_INVALID_MULTIADDR);let d=me(h);c="native",s=d}if(o=i,r?.muxerFactory!=null)a=r.muxerFactory;else if(this.muxers.size>0){let h=await this._multiplexInbound({...f,...i},this.muxers);a=h.muxerFactory,o=h.stream}}catch(h){throw Pe.error("Failed to upgrade inbound connection",h),h}if(await this.components.connectionGater.denyInboundUpgradedConnection(s,{...f,...i}))throw(0,at.default)(new Error("The multiaddr connection is blocked by gater.acceptEncryptedConnection"),b.ERR_CONNECTION_INTERCEPTED);return Pe("Successfully upgraded inbound connection"),this._createConnection({cryptoProtocol:c,direction:"inbound",maConn:e,upgradedConn:o,muxerFactory:a,remotePeer:s})}finally{this.components.connectionManager.afterUpgradeInbound(),u.clear()}}async upgradeOutbound(e,r){let n=e.remoteAddr.getPeerId();if(n==null)throw(0,at.default)(new Error("outbound connection must have a peer id"),b.ERR_INVALID_MULTIADDR);let i=me(n);if(await this.components.connectionGater.denyOutboundConnection(i,e))throw(0,at.default)(new Error("The multiaddr connection is blocked by connectionGater.denyOutboundConnection"),b.ERR_CONNECTION_INTERCEPTED);let s,o,a,c,u;this.components.metrics?.trackMultiaddrConnection(e),Pe("Starting the outbound connection upgrade");let l=e;if(r?.skipProtection!==!0){let f=this.components.connectionProtector;f!=null&&(l=await f.protect(e))}try{if(s=l,r?.skipEncryption!==!0){if({conn:s,remotePeer:o,protocol:c}=await this._encryptOutbound(l,i),await this.components.connectionGater.denyOutboundEncryptedConnection(o,{...l,...s}))throw(0,at.default)(new Error("The multiaddr connection is blocked by gater.acceptEncryptedConnection"),b.ERR_CONNECTION_INTERCEPTED)}else c="native",o=i;if(a=s,r?.muxerFactory!=null)u=r.muxerFactory;else if(this.muxers.size>0){let f=await this._multiplexOutbound({...l,...s},this.muxers);u=f.muxerFactory,a=f.stream}}catch(f){throw Pe.error("Failed to upgrade outbound connection",f),await e.close(f),f}if(await this.components.connectionGater.denyOutboundUpgradedConnection(o,{...l,...s}))throw(0,at.default)(new Error("The multiaddr connection is blocked by gater.acceptEncryptedConnection"),b.ERR_CONNECTION_INTERCEPTED);return Pe("Successfully upgraded outbound connection"),this._createConnection({cryptoProtocol:c,direction:"outbound",maConn:e,upgradedConn:a,muxerFactory:u,remotePeer:o})}_createConnection(e){let{cryptoProtocol:r,direction:n,maConn:i,upgradedConn:s,remotePeer:o,muxerFactory:a}=e,c,u,l;a!=null&&(c=a.createStreamMuxer({direction:n,onIncomingStream:d=>{l!=null&&Promise.resolve().then(async()=>{let p=this.components.registrar.getProtocols(),{stream:y,protocol:g}=await Po(d,p);if(Pe("%s: incoming stream opened on %s",n,g),l==null)return;let E=FI(g,this.components.registrar);if(Bv(g,"inbound",l)===E){d.abort((0,at.default)(new Error(`Too many inbound protocol streams for protocol "${g}" - limit ${E}`),b.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS));return}d.source=y.source,d.sink=y.sink,d.stat.protocol=g,this.components.peerStore.protoBook.add(o,[g]).catch(_=>Pe.error(_)),l.addStream(d),this.components.metrics?.trackProtocolStream(d,l),this._onStream({connection:l,stream:d,protocol:g})}).catch(p=>{Pe.error(p),d.stat.timeline.close==null&&d.close()})},onStreamEnd:d=>{l?.removeStream(d.id)}}),u=async(d,p={})=>{if(c==null)throw(0,at.default)(new Error("Stream is not multiplexed"),b.ERR_MUXER_UNAVAILABLE);Pe("%s: starting new stream on %s",n,d);let y=await c.newStream(),g;try{if(p.signal==null){Pe("No abort signal was passed while trying to negotiate protocols %s falling back to default timeout",d),g=new Ih.TimeoutController(3e4),p.signal=g.signal;try{(0,Th.setMaxListeners)?.(1/0,g.signal)}catch{}}let{stream:E,protocol:x}=await Do(y,d,p),_=KI(x,this.components.registrar);if(Bv(x,"outbound",l)===_){let D=(0,at.default)(new Error(`Too many outbound protocol streams for protocol "${x}" - limit ${_}`),b.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);throw y.abort(D),D}return this.components.peerStore.protoBook.add(o,[x]).catch(D=>Pe.error(D)),y.source=E.source,y.sink=E.sink,y.stat.protocol=x,this.components.metrics?.trackProtocolStream(y,l),y}catch(E){throw Pe.error("could not create new stream",E),y.stat.timeline.close==null&&y.close(),E.code!=null?E:(0,at.default)(E,b.ERR_UNSUPPORTED_PROTOCOL)}finally{g?.clear()}},Promise.all([c.sink(s.source),s.sink(c.source)]).catch(d=>{Pe.error(d)}));let f=i.timeline;i.timeline=new Proxy(f,{set:(...d)=>(l!=null&&d[1]==="close"&&d[2]!=null&&f.close==null&&(async()=>{try{l.stat.status==="OPEN"&&await l.close()}catch(p){Pe.error(p)}finally{this.dispatchEvent(new Z("connectionEnd",{detail:l}))}})().catch(p=>{Pe.error(p)}),Reflect.set(...d))}),i.timeline.upgraded=Date.now();let h=()=>{throw(0,at.default)(new Error("connection is not multiplexed"),b.ERR_CONNECTION_NOT_MULTIPLEXED)};return l=Lv({remoteAddr:i.remoteAddr,remotePeer:o,stat:{status:"OPEN",direction:n,timeline:i.timeline,multiplexer:c?.protocol,encryption:r},newStream:u??h,getStreams:()=>c!=null?c.streams:h(),close:async()=>{await i.close(),c?.close()}}),this.dispatchEvent(new Z("connection",{detail:l})),l}_onStream(e){let{connection:r,stream:n,protocol:i}=e,{handler:s}=this.components.registrar.getHandler(i);s({connection:r,stream:n})}async _encryptInbound(e){let r=Array.from(this.connectionEncryption.keys());Pe("handling inbound crypto protocol selection",r);try{let{stream:n,protocol:i}=await Po(e,r,{writeBytes:!0}),s=this.connectionEncryption.get(i);if(s==null)throw new Error(`no crypto module found for ${i}`);return Pe("encrypting inbound connection..."),{...await s.secureInbound(this.components.peerId,n),protocol:i}}catch(n){throw(0,at.default)(n,b.ERR_ENCRYPTION_FAILED)}}async _encryptOutbound(e,r){let n=Array.from(this.connectionEncryption.keys());Pe("selecting outbound crypto protocol",n);try{let{stream:i,protocol:s}=await Do(e,n,{writeBytes:!0}),o=this.connectionEncryption.get(s);if(o==null)throw new Error(`no crypto module found for ${s}`);return Pe("encrypting outbound connection to %p",r),{...await o.secureOutbound(this.components.peerId,i,r),protocol:s}}catch(i){throw(0,at.default)(i,b.ERR_ENCRYPTION_FAILED)}}async _multiplexOutbound(e,r){let n=Array.from(r.keys());Pe("outbound selecting muxer %s",n);try{let{stream:i,protocol:s}=await Do(e,n,{writeBytes:!0});Pe("%s selected as muxer protocol",s);let o=r.get(s);return{stream:i,muxerFactory:o}}catch(i){throw Pe.error("error multiplexing outbound stream",i),(0,at.default)(i,b.ERR_MUXER_UNAVAILABLE)}}async _multiplexInbound(e,r){let n=Array.from(r.keys());Pe("inbound handling muxers %s",n);try{let{stream:i,protocol:s}=await Po(e,n,{writeBytes:!0}),o=r.get(s);return{stream:i,muxerFactory:o}}catch(i){throw Pe.error("error multiplexing inbound stream",i),(0,at.default)(i,b.ERR_MUXER_UNAVAILABLE)}}};var bi=C(G(),1);var xi;(function(t){let e;t.codec=()=>(e==null&&(e=Ne((r,n,i={})=>{if(i.lengthDelimited!==!1&&n.fork(),r.protocolVersion!=null&&(n.uint32(42),n.string(r.protocolVersion)),r.agentVersion!=null&&(n.uint32(50),n.string(r.agentVersion)),r.publicKey!=null&&(n.uint32(10),n.bytes(r.publicKey)),r.listenAddrs!=null)for(let s of r.listenAddrs)n.uint32(18),n.bytes(s);if(r.observedAddr!=null&&(n.uint32(34),n.bytes(r.observedAddr)),r.protocols!=null)for(let s of r.protocols)n.uint32(26),n.string(s);r.signedPeerRecord!=null&&(n.uint32(66),n.bytes(r.signedPeerRecord)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={listenAddrs:[],protocols:[]},s=n==null?r.len:r.pos+n;for(;r.pos<s;){let o=r.uint32();switch(o>>>3){case 5:i.protocolVersion=r.string();break;case 6:i.agentVersion=r.string();break;case 1:i.publicKey=r.bytes();break;case 2:i.listenAddrs.push(r.bytes());break;case 4:i.observedAddr=r.bytes();break;case 3:i.protocols.push(r.string());break;case 8:i.signedPeerRecord=r.bytes();break;default:r.skipType(o&7);break}}return i})),e),t.encode=r=>Re(r,t.codec()),t.decode=r=>Te(r,t.codec())})(xi||(xi={}));var kv=C(G(),1);var Ov={ERR_SIGNATURE_NOT_VALID:"ERR_SIGNATURE_NOT_VALID"};var Bo;(function(t){let e;t.codec=()=>(e==null&&(e=Ne((r,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),(i.writeDefaults===!0||r.publicKey!=null&&r.publicKey.byteLength>0)&&(n.uint32(10),n.bytes(r.publicKey)),(i.writeDefaults===!0||r.payloadType!=null&&r.payloadType.byteLength>0)&&(n.uint32(18),n.bytes(r.payloadType)),(i.writeDefaults===!0||r.payload!=null&&r.payload.byteLength>0)&&(n.uint32(26),n.bytes(r.payload)),(i.writeDefaults===!0||r.signature!=null&&r.signature.byteLength>0)&&(n.uint32(42),n.bytes(r.signature)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={publicKey:new Uint8Array(0),payloadType:new Uint8Array(0),payload:new Uint8Array(0),signature:new Uint8Array(0)},s=n==null?r.len:r.pos+n;for(;r.pos<s;){let o=r.uint32();switch(o>>>3){case 1:i.publicKey=r.bytes();break;case 2:i.payloadType=r.bytes();break;case 3:i.payload=r.bytes();break;case 5:i.signature=r.bytes();break;default:r.skipType(o&7);break}}return i})),e),t.encode=r=>Re(r,t.codec()),t.decode=r=>Te(r,t.codec())})(Bo||(Bo={}));var VI,ct=class{constructor(e){let{peerId:r,payloadType:n,payload:i,signature:s}=e;this.peerId=r,this.payloadType=n,this.payload=i,this.signature=s}marshal(){if(this.peerId.publicKey==null)throw new Error("Missing public key");return this.marshaled==null&&(this.marshaled=Bo.encode({publicKey:this.peerId.publicKey,payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return _e(this.marshal(),e.marshal())}async validate(e){let r=Uv(e,this.payloadType,this.payload);if(this.peerId.publicKey==null)throw new Error("Missing public key");return await So(this.peerId.publicKey).verify(r.subarray(),this.signature)}};VI=ct;ct.createFromProtobuf=async t=>{let e=Bo.decode(t),r=await Ui(e.publicKey);return new ct({peerId:r,payloadType:e.payloadType,payload:e.payload,signature:e.signature})};ct.seal=async(t,e)=>{if(e.privateKey==null)throw new Error("Missing private key");let r=t.domain,n=t.codec,i=t.marshal(),s=Uv(r,n,i),a=await(await xs(e.privateKey)).sign(s.subarray());return new ct({peerId:e,payloadType:n,payload:i,signature:a})};ct.openAndCertify=async(t,e)=>{let r=await ct.createFromProtobuf(t);if(!await r.validate(e))throw(0,kv.default)(new Error("envelope signature is not valid for the given domain"),Ov.ERR_SIGNATURE_NOT_VALID);return r};var Uv=(t,e,r)=>{let n=q(t),i=er.encode(n.byteLength),s=er.encode(e.length),o=er.encode(r.length);return new Ge(i,n,s,e,o,r)};function Mv(t,e){let r=(n,i)=>n.toString().localeCompare(i.toString());return t.length!==e.length?!1:(e.sort(r),t.sort(r).every((n,i)=>e[i].equals(n)))}var Oo;(function(t){let e;(function(n){let i;n.codec=()=>(i==null&&(i=Ne((s,o,a={})=>{a.lengthDelimited!==!1&&o.fork(),(a.writeDefaults===!0||s.multiaddr!=null&&s.multiaddr.byteLength>0)&&(o.uint32(10),o.bytes(s.multiaddr)),a.lengthDelimited!==!1&&o.ldelim()},(s,o)=>{let a={multiaddr:new Uint8Array(0)},c=o==null?s.len:s.pos+o;for(;s.pos<c;){let u=s.uint32();switch(u>>>3){case 1:a.multiaddr=s.bytes();break;default:s.skipType(u&7);break}}return a})),i),n.encode=s=>Re(s,n.codec()),n.decode=s=>Te(s,n.codec())})(e=t.AddressInfo||(t.AddressInfo={}));let r;t.codec=()=>(r==null&&(r=Ne((n,i,s={})=>{if(s.lengthDelimited!==!1&&i.fork(),(s.writeDefaults===!0||n.peerId!=null&&n.peerId.byteLength>0)&&(i.uint32(10),i.bytes(n.peerId)),(s.writeDefaults===!0||n.seq!==0n)&&(i.uint32(16),i.uint64(n.seq)),n.addresses!=null)for(let o of n.addresses)i.uint32(26),t.AddressInfo.codec().encode(o,i,{writeDefaults:!0});s.lengthDelimited!==!1&&i.ldelim()},(n,i)=>{let s={peerId:new Uint8Array(0),seq:0n,addresses:[]},o=i==null?n.len:n.pos+i;for(;n.pos<o;){let a=n.uint32();switch(a>>>3){case 1:s.peerId=n.bytes();break;case 2:s.seq=n.uint64();break;case 3:s.addresses.push(t.AddressInfo.codec().decode(n,n.uint32()));break;default:n.skipType(a&7);break}}return s})),r),t.encode=n=>Re(n,t.codec()),t.decode=n=>Te(n,t.codec())})(Oo||(Oo={}));var Fv="libp2p-peer-record",Kv=Uint8Array.from([3,1]);var tt=class{constructor(e){this.domain=tt.DOMAIN,this.codec=tt.CODEC;let{peerId:r,multiaddrs:n,seqNumber:i}=e;this.peerId=r,this.multiaddrs=n??[],this.seqNumber=i??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=Oo.encode({peerId:this.peerId.toBytes(),seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))})),this.marshaled}equals(e){return!(!(e instanceof tt)||!this.peerId.equals(e.peerId)||this.seqNumber!==e.seqNumber||!Mv(this.multiaddrs,e.multiaddrs))}};tt.createFromProtobuf=t=>{let e=Oo.decode(t),r=mn(e.peerId),n=(e.addresses??[]).map(s=>oe(s.multiaddr)),i=e.seq;return new tt({peerId:r,multiaddrs:n,seqNumber:i})};tt.DOMAIN=Fv;tt.CODEC=Kv;var Kc="0.0.0",Vv="libp2p";var Rh=`js-libp2p/${Kc}`;var qv="0.1.0",Hv="id",zv="id/push",$v="1.0.0",Gv="1.0.0";var ko=C(Ur(),1);var Uo=C(fr(),1),Ae=M("libp2p:identify"),Yv=1024*8,_s=class{constructor(e,r){this.components=e,this.started=!1,this.init=r,this.identifyProtocolStr=`/${r.protocolPrefix}/${Hv}/${$v}`,this.identifyPushProtocolStr=`/${r.protocolPrefix}/${zv}/${Gv}`,this.host={protocolVersion:`${r.protocolPrefix}/${qv}`,...r.host},this.components.connectionManager.addEventListener("peer:connect",n=>{let i=n.detail;this.identify(i).catch(Ae.error)}),this.components.peerStore.addEventListener("change:multiaddrs",n=>{let{peerId:i}=n.detail;this.components.peerId.equals(i)&&this.pushToPeerStore().catch(s=>Ae.error(s))}),this.components.peerStore.addEventListener("change:protocols",n=>{let{peerId:i}=n.detail;this.components.peerId.equals(i)&&this.pushToPeerStore().catch(s=>Ae.error(s))})}isStarted(){return this.started}async start(){this.started||(await this.components.peerStore.metadataBook.setValue(this.components.peerId,"AgentVersion",q(this.host.agentVersion)),await this.components.peerStore.metadataBook.setValue(this.components.peerId,"ProtocolVersion",q(this.host.protocolVersion)),await this.components.registrar.handle(this.identifyProtocolStr,e=>{this._handleIdentify(e).catch(r=>{Ae.error(r)})},{maxInboundStreams:this.init.maxInboundStreams,maxOutboundStreams:this.init.maxOutboundStreams}),await this.components.registrar.handle(this.identifyPushProtocolStr,e=>{this._handlePush(e).catch(r=>{Ae.error(r)})},{maxInboundStreams:this.init.maxPushIncomingStreams,maxOutboundStreams:this.init.maxPushOutgoingStreams}),this.started=!0)}async stop(){await this.components.registrar.unhandle(this.identifyProtocolStr),await this.components.registrar.unhandle(this.identifyPushProtocolStr),this.started=!1}async push(e){let r=await this.components.peerStore.addressBook.getRawEnvelope(this.components.peerId),n=this.components.addressManager.getAddresses().map(o=>o.bytes),i=await this.components.peerStore.protoBook.get(this.components.peerId),s=e.map(async o=>{let a,c=new ko.TimeoutController(this.init.timeout);try{(0,Uo.setMaxListeners)?.(1/0,c.signal)}catch{}try{a=await o.newStream([this.identifyPushProtocolStr],{signal:c.signal}),await Dt(a,c.signal).sink(Ce([xi.encode({listenAddrs:n,signedPeerRecord:r,protocols:i})],Vt()))}catch(u){Ae.error("could not push identify update to peer",u)}finally{a?.close(),c.clear()}});await Promise.all(s)}async pushToPeerStore(){if(!this.isStarted())return;let e=[];for(let r of this.components.connectionManager.getConnections()){let n=r.remotePeer;(await this.components.peerStore.get(n)).protocols.includes(this.identifyPushProtocolStr)&&e.push(r)}await this.push(e)}async _identify(e,r={}){let n,i=r.signal,s;if(i==null){n=new ko.TimeoutController(this.init.timeout),i=n.signal;try{(0,Uo.setMaxListeners)?.(1/0,n.signal)}catch{}}try{s=await e.newStream([this.identifyProtocolStr],{signal:i});let o=Dt(s,i),a=await Ce([],o,Pt({maxDataLength:this.init.maxIdentifyMessageSize??Yv}),async c=>await Rt(c));if(a==null)throw(0,bi.default)(new Error("No data could be retrieved"),b.ERR_CONNECTION_ENDED);try{return xi.decode(a)}catch(c){throw(0,bi.default)(c,b.ERR_INVALID_MESSAGE)}}finally{n?.clear(),s?.close()}}async identify(e,r={}){let n=await this._identify(e,r),{publicKey:i,listenAddrs:s,protocols:o,observedAddr:a,signedPeerRecord:c,agentVersion:u,protocolVersion:l}=n;if(i==null)throw(0,bi.default)(new Error("public key was missing from identify message"),b.ERR_MISSING_PUBLIC_KEY);let f=await Ui(i);if(!e.remotePeer.equals(f))throw(0,bi.default)(new Error("identified peer does not match the expected peer"),b.ERR_INVALID_PEER);if(this.components.peerId.equals(f))throw(0,bi.default)(new Error("identified peer is our own peer id?"),b.ERR_INVALID_PEER);let h=_s.getCleanMultiaddr(a);if(c!=null){Ae("received signed peer record from %p",f);try{let d=await ct.openAndCertify(c,tt.DOMAIN);if(!d.peerId.equals(f))throw(0,bi.default)(new Error("identified peer does not match the expected peer"),b.ERR_INVALID_PEER);if(await this.components.peerStore.addressBook.consumePeerRecord(d)){await this.components.peerStore.protoBook.set(f,o),u!=null&&await this.components.peerStore.metadataBook.setValue(f,"AgentVersion",q(u)),l!=null&&await this.components.peerStore.metadataBook.setValue(f,"ProtocolVersion",q(l)),Ae("identify completed for peer %p and protocols %o",f,o);return}}catch(d){Ae("received invalid envelope, discard it and fallback to listenAddrs is available",d)}}else Ae("no signed peer record received from %p",f);Ae("falling back to legacy addresses from %p",f);try{await this.components.peerStore.addressBook.set(f,s.map(d=>oe(d)))}catch(d){Ae.error("received invalid addrs",d)}await this.components.peerStore.protoBook.set(f,o),u!=null&&await this.components.peerStore.metadataBook.setValue(f,"AgentVersion",q(u)),l!=null&&await this.components.peerStore.metadataBook.setValue(f,"ProtocolVersion",q(l)),Ae("identify completed for peer %p and protocols %o",f,o),Ae("received observed address of %s",h?.toString())}async _handleIdentify(e){let{connection:r,stream:n}=e,i=new ko.TimeoutController(this.init.timeout);try{(0,Uo.setMaxListeners)?.(1/0,i.signal)}catch{}try{let s=this.components.peerId.publicKey??new Uint8Array(0),o=await this.components.peerStore.get(this.components.peerId),a=this.components.addressManager.getAddresses().map(h=>h.decapsulateCode(Ie("p2p").code)),c=o.peerRecordEnvelope;if(a.length>0&&c==null){let h=new tt({peerId:this.components.peerId,multiaddrs:a}),d=await ct.seal(h,this.components.peerId);await this.components.peerStore.addressBook.consumePeerRecord(d),c=d.marshal().subarray()}let u=xi.encode({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:s,listenAddrs:a.map(h=>h.bytes),signedPeerRecord:c,observedAddr:r.remoteAddr.bytes,protocols:o.protocols}),l=Dt(n,i.signal),f=Ce([u],Vt());await l.sink(f)}catch(s){Ae.error("could not respond to identify request",s)}finally{n.close(),i.clear()}}async _handlePush(e){let{connection:r,stream:n}=e,i=new ko.TimeoutController(this.init.timeout);try{(0,Uo.setMaxListeners)?.(1/0,i.signal)}catch{}let s;try{let a=Dt(n,i.signal),c=await Ce([],a,Pt({maxDataLength:this.init.maxIdentifyMessageSize??Yv}),async u=>await Rt(u));c!=null&&(s=xi.decode(c))}catch(a){return Ae.error("received invalid message",a)}finally{n.close(),i.clear()}if(s==null)return Ae.error("received invalid message");let o=r.remotePeer;if(this.components.peerId.equals(o)){Ae("received push from ourselves?");return}if(Ae("received push from %p",o),s.signedPeerRecord!=null){Ae("received signedPeerRecord in push");try{let a=await ct.openAndCertify(s.signedPeerRecord,tt.DOMAIN);if(await this.components.peerStore.addressBook.consumePeerRecord(a)){Ae("consumed signedPeerRecord sent in push"),await this.components.peerStore.protoBook.set(o,s.protocols);return}else Ae("failed to consume signedPeerRecord sent in push")}catch(a){Ae("received invalid envelope, discard it and fallback to listenAddrs is available",a)}}else Ae("did not receive signedPeerRecord in push");try{await this.components.peerStore.addressBook.set(o,s.listenAddrs.map(a=>oe(a)))}catch(a){Ae.error("received invalid addrs",a)}try{await this.components.peerStore.protoBook.set(o,s.protocols)}catch(a){Ae.error("received invalid protocols",a)}Ae("handled push from %p",o)}static getCleanMultiaddr(e){if(e!=null&&e.length>0)try{return oe(e)}catch{}}};var As=C(G(),1);var Mo;(function(t){let e;t.codec=()=>(e==null&&(e=Ne((r,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),(i.writeDefaults===!0||r.identifier!=="")&&(n.uint32(10),n.string(r.identifier)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={identifier:""},s=n==null?r.len:r.pos+n;for(;r.pos<s;){let o=r.uint32();switch(o>>>3){case 1:i.identifier=r.string();break;default:r.skipType(o&7);break}}return i})),e),t.encode=r=>Re(r,t.codec()),t.decode=r=>Te(r,t.codec())})(Mo||(Mo={}));var or;(function(t){let e;(function(i){i.OK="OK",i.NOT_FOUND="NOT_FOUND",i.ERROR="ERROR"})(e=t.StatusCode||(t.StatusCode={}));let r;(function(i){i[i.OK=0]="OK",i[i.NOT_FOUND=1]="NOT_FOUND",i[i.ERROR=2]="ERROR"})(r||(r={})),function(i){i.codec=()=>wn(r)}(e=t.StatusCode||(t.StatusCode={}));let n;t.codec=()=>(n==null&&(n=Ne((i,s,o={})=>{o.lengthDelimited!==!1&&s.fork(),(o.writeDefaults===!0||i.status!=null&&r[i.status]!==0)&&(s.uint32(8),t.StatusCode.codec().encode(i.status,s)),(o.writeDefaults===!0||i.data!=null&&i.data.byteLength>0)&&(s.uint32(18),s.bytes(i.data)),o.lengthDelimited!==!1&&s.ldelim()},(i,s)=>{let o={status:e.OK,data:new Uint8Array(0)},a=s==null?i.len:i.pos+s;for(;i.pos<a;){let c=i.uint32();switch(c>>>3){case 1:o.status=t.StatusCode.codec().decode(i);break;case 2:o.data=i.bytes();break;default:i.skipType(c&7);break}}return o})),n),t.encode=i=>Re(i,t.codec()),t.decode=i=>Te(i,t.codec())})(or||(or={}));var Wv="0.0.1",Qv="fetch";var Xv=C(Ur(),1),jv=C(fr(),1);var Wt=M("libp2p:fetch"),Vc=class{constructor(e,r){this.started=!1,this.components=e,this.protocol=`/${r.protocolPrefix??"libp2p"}/${Qv}/${Wv}`,this.lookupFunctions=new Map,this.handleMessage=this.handleMessage.bind(this),this.init=r}async start(){await this.components.registrar.handle(this.protocol,e=>{this.handleMessage(e).catch(r=>{Wt.error(r)}).finally(()=>{e.stream.close()})},{maxInboundStreams:this.init.maxInboundStreams,maxOutboundStreams:this.init.maxOutboundStreams}),this.started=!0}async stop(){await this.components.registrar.unhandle(this.protocol),this.started=!1}isStarted(){return this.started}async fetch(e,r,n={}){Wt("dialing %s to %p",this.protocol,e);let i=await this.components.connectionManager.openConnection(e,n),s,o=n.signal,a;if(o==null){Wt("using default timeout of %d ms",this.init.timeout),s=new Xv.TimeoutController(this.init.timeout),o=s.signal;try{(0,jv.setMaxListeners)?.(1/0,s.signal)}catch{}}try{a=await i.newStream(this.protocol,{signal:o});let c=Dt(a,o);return Wt("fetch %s",r),await Ce([Mo.encode({identifier:r})],Vt(),c,Pt(),async function(l){let f=await Rt(l);if(f==null)throw(0,As.default)(new Error("No data received"),b.ERR_INVALID_MESSAGE);let h=or.decode(f);switch(h.status){case or.StatusCode.OK:return Wt("received status for %s ok",r),h.data;case or.StatusCode.NOT_FOUND:return Wt("received status for %s not found",r),null;case or.StatusCode.ERROR:{Wt("received status for %s error",r);let d=Q(h.data);throw(0,As.default)(new Error("Error in fetch protocol response: "+d),b.ERR_INVALID_PARAMETERS)}default:throw Wt("received status for %s unknown",r),(0,As.default)(new Error("Unknown response status"),b.ERR_INVALID_MESSAGE)}})??null}finally{s?.clear(),a?.close()}}async handleMessage(e){let{stream:r}=e,n=this;await Ce(r,Pt(),async function*(i){let s=await Rt(i);if(s==null)throw(0,As.default)(new Error("No data received"),b.ERR_INVALID_MESSAGE);let o=Mo.decode(s),a,c=n._getLookupFunction(o.identifier);if(c!=null){Wt("look up data with identifier %s",o.identifier);let u=await c(o.identifier);u!=null?(Wt("sending status for %s ok",o.identifier),a={status:or.StatusCode.OK,data:u}):(Wt("sending status for %s not found",o.identifier),a={status:or.StatusCode.NOT_FOUND,data:new Uint8Array(0)})}else{Wt("sending status for %s error",o.identifier);let u=q(`No lookup function registered for key: ${o.identifier}`);a={status:or.StatusCode.ERROR,data:u}}yield or.encode(a)},Vt(),r)}_getLookupFunction(e){for(let r of this.lookupFunctions.keys())if(e.startsWith(r))return this.lookupFunctions.get(r)}registerLookupFunction(e,r){if(this.lookupFunctions.has(e))throw(0,As.default)(new Error("Fetch protocol handler for key prefix '"+e+"' already registered"),b.ERR_KEY_ALREADY_EXISTS);this.lookupFunctions.set(e,r)}unregisterLookupFunction(e,r){r!=null&&this.lookupFunctions.get(e)!==r||this.lookupFunctions.delete(e)}};var tw=C(G(),1);var Zv="1.0.0",Jv="ping";var rw=C(Ur(),1),nw=C(fr(),1),ew=M("libp2p:ping"),qc=class{constructor(e,r){this.components=e,this.started=!1,this.protocol=`/${r.protocolPrefix}/${Jv}/${Zv}`,this.init=r}async start(){await this.components.registrar.handle(this.protocol,this.handleMessage,{maxInboundStreams:this.init.maxInboundStreams,maxOutboundStreams:this.init.maxOutboundStreams}),this.started=!0}async stop(){await this.components.registrar.unhandle(this.protocol),this.started=!1}isStarted(){return this.started}handleMessage(e){let{stream:r}=e;Ce(r,r).catch(n=>{ew.error(n)})}async ping(e,r={}){ew("dialing %s to %p",this.protocol,e);let n=Date.now(),i=Zr(32),s=await this.components.connectionManager.openConnection(e,r),o,a=r.signal,c;if(a==null){o=new rw.TimeoutController(this.init.timeout),a=o.signal;try{(0,nw.setMaxListeners)?.(1/0,o.signal)}catch{}}try{c=await s.newStream([this.protocol],{signal:a});let u=Dt(c,a),l=await Ce([i],u,async h=>await Rt(h)),f=Date.now();if(l==null||!_e(i,l.subarray()))throw(0,tw.default)(new Error("Received wrong ping ack"),b.ERR_WRONG_PING_ACK);return f-n}finally{o?.clear(),c?.close()}}};async function iw(){throw new Error("Not supported in browsers")}var aw=C(ow(),1),Nh=typeof window=="object"&&typeof document=="object"&&document.nodeType===9,Hc=(0,aw.default)(),Fo=Nh&&!Hc,cw=Hc&&!Nh,uw=Hc&&Nh,lw=typeof globalThis.process<"u"&&typeof globalThis.process.release<"u"&&globalThis.process.release.name==="node"&&!Hc,fw=typeof importScripts=="function"&&typeof self<"u"&&typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope,w6=typeof globalThis.process<"u"&&typeof globalThis.process.env<"u"&&globalThis.process.env["NODE"+(()=>"_")()+"ENV"]==="test",hw=typeof navigator<"u"&&navigator.product==="ReactNative";var mw=C(G(),1);function dw(t){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(t)||/^::1$/.test(t)}function pw(t){let{address:e}=t.nodeAddress();return dw(e)}var Dh=M("libp2p:nat"),Lh=7200;function $I(t=1024,e=65535){return Math.floor(Math.random()*(e-t+1)+t)}var zc=class{constructor(e,r){if(this.components=e,this.started=!1,this.enabled=r.enabled,this.externalAddress=r.externalAddress,this.localAddress=r.localAddress,this.description=r.description??`${Vv}@${Kc} ${this.components.peerId.toString()}`,this.ttl=r.ttl??Lh,this.keepAlive=r.keepAlive??!0,this.gateway=r.gateway,this.ttl<Lh)throw(0,mw.default)(new Error(`NatManager ttl should be at least ${Lh} seconds`),b.ERR_INVALID_PARAMETERS)}isStarted(){return this.started}start(){}afterStart(){Fo||!this.enabled||this.started||(this.started=!0,this._start().catch(e=>{Dh.error(e)}))}async _start(){let e=this.components.transportManager.getAddrs();for(let r of e){let{family:n,host:i,port:s,transport:o}=r.toOptions();if(!r.isThinWaistAddress()||o!=="tcp"||pw(r)||n!==4)continue;let a=await this._getClient(),c=this.externalAddress??await a.externalIp(),u=Qa(c);if(u===!0)throw new Error(`${c} is private - please set config.nat.externalIp to an externally routable IP or ensure you are not behind a double NAT`);if(u==null)throw new Error(`${c} is not an IP address`);let l=$I();Dh(`opening uPnP connection from ${c}:${l} to ${i}:${s}`),await a.map({publicPort:l,localPort:s,localAddress:this.localAddress,protocol:o.toUpperCase()==="TCP"?"TCP":"UDP"}),this.components.addressManager.addObservedAddr(Zp({family:4,address:c,port:l},o))}}async _getClient(){return this.client!=null?this.client:(this.client=await iw({description:this.description,ttl:this.ttl,keepAlive:this.keepAlive,gateway:this.gateway}),this.client)}async stop(){if(!(Fo||this.client==null))try{await this.client.close(),this.client=void 0}catch(e){Dh.error(e)}}};var GI=M("libp2p:peer-record-updater"),$c=class{constructor(e){this.components=e,this.started=!1,this.update=this.update.bind(this)}isStarted(){return this.started}async start(){this.started=!0,this.components.transportManager.addEventListener("listener:listening",this.update),this.components.transportManager.addEventListener("listener:close",this.update),this.components.addressManager.addEventListener("change:addresses",this.update)}async stop(){this.started=!1,this.components.transportManager.removeEventListener("listener:listening",this.update),this.components.transportManager.removeEventListener("listener:close",this.update),this.components.addressManager.removeEventListener("change:addresses",this.update)}update(){Promise.resolve().then(async()=>{let e=new tt({peerId:this.components.peerId,multiaddrs:this.components.addressManager.getAddresses().map(n=>n.decapsulateCode(Ie("p2p").code))}),r=await ct.seal(e,this.components.peerId);await this.components.peerStore.addressBook.consumePeerRecord(r)}).catch(e=>{GI.error("Could not update self peer record: %o",e)})}};var yw=C(G(),1);var Gc=class{constructor(e){this.dht=e}async findPeer(e,r={}){for await(let n of this.dht.findPeer(e,r))if(n.name==="FINAL_PEER")return n.peer;throw(0,yw.default)(new Error(ne.NOT_FOUND),b.ERR_NOT_FOUND)}async*getClosestPeers(e,r={}){for await(let n of this.dht.getClosestPeers(e,r))n.name==="FINAL_PEER"&&(yield n.peer)}};var Wc=C(G(),1);var re={ERR_INVALID_PARAMETERS:"ERR_INVALID_PARAMETERS",ERR_NOT_FOUND:"ERR_NOT_FOUND"};async function*Ph(t,e){for await(let r of t)await e(r),yield r}var Se=M("libp2p:peer-store:address-book"),Yc="change:multiaddrs";async function YI(){return!0}var Qc=class{constructor(e,r,n){this.dispatchEvent=e,this.store=r,this.addressFilter=n??YI}async consumePeerRecord(e){Se.trace("consumePeerRecord await write lock");let r=await this.store.lock.writeLock();Se.trace("consumePeerRecord got write lock");let n,i,s;try{let o;try{o=tt.createFromProtobuf(e.payload)}catch{return Se.error("invalid peer record received"),!1}n=o.peerId;let a=o.multiaddrs;if(!n.equals(e.peerId))return Se("signing key does not match PeerId in the PeerRecord"),!1;if(a==null||a.length===0)return!1;if(await this.store.has(n)&&(i=await this.store.load(n),i.peerRecordEnvelope!=null)){let u=await ct.createFromProtobuf(i.peerRecordEnvelope),l=tt.createFromProtobuf(u.payload);if(l.seqNumber>=o.seqNumber)return Se("sequence number was lower or equal to existing sequence number - stored: %d received: %d",l.seqNumber,o.seqNumber),!1}let c=await Bh(n,a,this.addressFilter,!0);s=await this.store.patchOrCreate(n,{addresses:c,peerRecordEnvelope:e.marshal().subarray()}),Se("stored provided peer record for %p",o.peerId)}finally{Se.trace("consumePeerRecord release write lock"),r()}return this.dispatchEvent(new Z(Yc,{detail:{peerId:n,multiaddrs:s.addresses.map(({multiaddr:o})=>o),oldMultiaddrs:i==null?[]:i.addresses.map(({multiaddr:o})=>o)}})),!0}async getRawEnvelope(e){Se.trace("getRawEnvelope await read lock");let r=await this.store.lock.readLock();Se.trace("getRawEnvelope got read lock");try{return(await this.store.load(e)).peerRecordEnvelope}catch(n){if(n.code!==re.ERR_NOT_FOUND)throw n}finally{Se.trace("getRawEnvelope release read lock"),r()}}async getPeerRecord(e){let r=await this.getRawEnvelope(e);if(r!=null)return await ct.createFromProtobuf(r)}async get(e){e=Qe(e),Se.trace("get wait for read lock");let r=await this.store.lock.readLock();Se.trace("get got read lock");try{return(await this.store.load(e)).addresses}catch(n){if(n.code!==re.ERR_NOT_FOUND)throw n}finally{Se.trace("get release read lock"),r()}return[]}async set(e,r){if(e=Qe(e),!Array.isArray(r))throw Se.error("multiaddrs must be an array of Multiaddrs"),(0,Wc.default)(new Error("multiaddrs must be an array of Multiaddrs"),re.ERR_INVALID_PARAMETERS);Se.trace("set await write lock");let n=await this.store.lock.writeLock();Se.trace("set got write lock");let i=!1,s,o;try{let a=await Bh(e,r,this.addressFilter);if(a.length===0)return;try{if(s=await this.store.load(e),i=!0,new Set([...a.map(({multiaddr:c})=>c.toString()),...s.addresses.map(({multiaddr:c})=>c.toString())]).size===s.addresses.length&&a.length===s.addresses.length)return}catch(c){if(c.code!==re.ERR_NOT_FOUND)throw c}o=await this.store.patchOrCreate(e,{addresses:a}),Se("set multiaddrs for %p",e)}finally{Se.trace("set multiaddrs for %p",e),Se("set release write lock"),n()}this.dispatchEvent(new Z(Yc,{detail:{peerId:e,multiaddrs:o.addresses.map(a=>a.multiaddr),oldMultiaddrs:s==null?[]:s.addresses.map(({multiaddr:a})=>a)}})),i||this.dispatchEvent(new Z("peer",{detail:{id:e,multiaddrs:o.addresses.map(a=>a.multiaddr),protocols:o.protocols}}))}async add(e,r){if(e=Qe(e),!Array.isArray(r))throw Se.error("multiaddrs must be an array of Multiaddrs"),(0,Wc.default)(new Error("multiaddrs must be an array of Multiaddrs"),re.ERR_INVALID_PARAMETERS);Se.trace("add await write lock");let n=await this.store.lock.writeLock();Se.trace("add got write lock");let i,s,o;try{let a=await Bh(e,r,this.addressFilter);if(a.length===0)return;try{if(s=await this.store.load(e),i=!0,new Set([...a.map(({multiaddr:c})=>c.toString()),...s.addresses.map(({multiaddr:c})=>c.toString())]).size===s.addresses.length)return}catch(c){if(c.code!==re.ERR_NOT_FOUND)throw c}o=await this.store.mergeOrCreate(e,{addresses:a}),Se("added multiaddrs for %p",e)}finally{Se.trace("set release write lock"),n()}this.dispatchEvent(new Z(Yc,{detail:{peerId:e,multiaddrs:o.addresses.map(a=>a.multiaddr),oldMultiaddrs:s==null?[]:s.addresses.map(({multiaddr:a})=>a)}})),i===!0&&this.dispatchEvent(new Z("peer",{detail:{id:e,multiaddrs:o.addresses.map(a=>a.multiaddr),protocols:o.protocols}}))}async delete(e){e=Qe(e),Se.trace("delete await write lock");let r=await this.store.lock.writeLock();Se.trace("delete got write lock");let n;try{try{n=await this.store.load(e)}catch(i){if(i.code!==re.ERR_NOT_FOUND)throw i}await this.store.patchOrCreate(e,{addresses:[]})}finally{Se.trace("delete release write lock"),r()}n!=null&&this.dispatchEvent(new Z(Yc,{detail:{peerId:e,multiaddrs:[],oldMultiaddrs:n==null?[]:n.addresses.map(({multiaddr:i})=>i)}}))}};async function Bh(t,e,r,n=!1){return await Ce(e,i=>Ph(i,s=>{if(!Fr(s))throw Se.error("multiaddr must be an instance of Multiaddr"),(0,Wc.default)(new Error("multiaddr must be an instance of Multiaddr"),re.ERR_INVALID_PARAMETERS)}),i=>kr(i,async s=>await r(t,s)),i=>Ls(i,s=>({multiaddr:s,isCertified:n})),async i=>await zr(i))}var Ew=C(G(),1);var Rr=M("libp2p:peer-store:key-book"),gw="change:pubkey",Xc=class{constructor(e,r){this.dispatchEvent=e,this.store=r}async set(e,r){if(e=Qe(e),!(r instanceof Uint8Array))throw Rr.error("publicKey must be an instance of Uint8Array to store data"),(0,Ew.default)(new Error("publicKey must be an instance of PublicKey"),re.ERR_INVALID_PARAMETERS);Rr.trace("set await write lock");let n=await this.store.lock.writeLock();Rr.trace("set got write lock");let i=!1,s;try{try{if(s=await this.store.load(e),s.pubKey!=null&&_e(s.pubKey,r))return}catch(o){if(o.code!==re.ERR_NOT_FOUND)throw o}await this.store.patchOrCreate(e,{pubKey:r}),i=!0}finally{Rr.trace("set release write lock"),n()}i&&this.dispatchEvent(new Z(gw,{detail:{peerId:e,publicKey:r,oldPublicKey:s?.pubKey}}))}async get(e){e=Qe(e),Rr.trace("get await write lock");let r=await this.store.lock.readLock();Rr.trace("get got write lock");try{return(await this.store.load(e)).pubKey}catch(n){if(n.code!==re.ERR_NOT_FOUND)throw n}finally{Rr("get release write lock"),r()}}async delete(e){e=Qe(e),Rr.trace("delete await write lock");let r=await this.store.lock.writeLock();Rr.trace("delete got write lock");let n;try{try{n=await this.store.load(e)}catch(i){if(i.code!==re.ERR_NOT_FOUND)throw i}await this.store.patchOrCreate(e,{pubKey:void 0})}catch(i){if(i.code!==re.ERR_NOT_FOUND)throw i}finally{Rr.trace("delete release write lock"),r()}this.dispatchEvent(new Z(gw,{detail:{peerId:e,publicKey:void 0,oldPublicKey:n?.pubKey}}))}};var Oh=C(G(),1);var rt=M("libp2p:peer-store:metadata-book"),jc="change:metadata",Zc=class{constructor(e,r){this.dispatchEvent=e,this.store=r}async get(e){e=Qe(e),rt.trace("get await read lock");let r=await this.store.lock.readLock();rt.trace("get got read lock");try{return(await this.store.load(e)).metadata}catch(n){if(n.code!==re.ERR_NOT_FOUND)throw n}finally{rt.trace("get release read lock"),r()}return new Map}async getValue(e,r){e=Qe(e),rt.trace("getValue await read lock");let n=await this.store.lock.readLock();rt.trace("getValue got read lock");try{return(await this.store.load(e)).metadata.get(r)}catch(i){if(i.code!==re.ERR_NOT_FOUND)throw i}finally{rt.trace("getValue release write lock"),n()}}async set(e,r){if(e=Qe(e),!(r instanceof Map))throw rt.error("valid metadata must be provided to store data"),(0,Oh.default)(new Error("valid metadata must be provided"),re.ERR_INVALID_PARAMETERS);rt.trace("set await write lock");let n=await this.store.lock.writeLock();rt.trace("set got write lock");let i;try{try{i=await this.store.load(e)}catch(s){if(s.code!==re.ERR_NOT_FOUND)throw s}await this.store.mergeOrCreate(e,{metadata:r})}finally{rt.trace("set release write lock"),n()}this.dispatchEvent(new Z(jc,{detail:{peerId:e,metadata:r,oldMetadata:i==null?new Map:i.metadata}}))}async setValue(e,r,n){if(e=Qe(e),typeof r!="string"||!(n instanceof Uint8Array))throw rt.error("valid key and value must be provided to store data"),(0,Oh.default)(new Error("valid key and value must be provided"),re.ERR_INVALID_PARAMETERS);rt.trace("setValue await write lock");let i=await this.store.lock.writeLock();rt.trace("setValue got write lock");let s,o;try{try{s=await this.store.load(e);let a=s.metadata.get(r);if(a!=null&&_e(n,a))return}catch(a){if(a.code!==re.ERR_NOT_FOUND)throw a}o=await this.store.mergeOrCreate(e,{metadata:new Map([[r,n]])})}finally{rt.trace("setValue release write lock"),i()}this.dispatchEvent(new Z(jc,{detail:{peerId:e,metadata:o.metadata,oldMetadata:s==null?new Map:s.metadata}}))}async delete(e){e=Qe(e),rt.trace("delete await write lock");let r=await this.store.lock.writeLock();rt.trace("delete got write lock");let n;try{try{n=await this.store.load(e)}catch(i){if(i.code!==re.ERR_NOT_FOUND)throw i}n!=null&&await this.store.patch(e,{metadata:new Map})}finally{rt.trace("delete release write lock"),r()}n!=null&&this.dispatchEvent(new Z(jc,{detail:{peerId:e,metadata:new Map,oldMetadata:n.metadata}}))}async deleteValue(e,r){e=Qe(e),rt.trace("deleteValue await write lock");let n=await this.store.lock.writeLock();rt.trace("deleteValue got write lock");let i,s;try{s=await this.store.load(e),i=s.metadata,i.delete(r),await this.store.patch(e,{metadata:i})}catch(o){if(o.code!==re.ERR_NOT_FOUND)throw o}finally{rt.trace("deleteValue release write lock"),n()}i!=null&&this.dispatchEvent(new Z(jc,{detail:{peerId:e,metadata:i,oldMetadata:s==null?new Map:s.metadata}}))}};var eu=C(G(),1);var nt=M("libp2p:peer-store:proto-book"),Jc="change:protocols",tu=class{constructor(e,r){this.dispatchEvent=e,this.store=r}async get(e){nt.trace("get wait for read lock");let r=await this.store.lock.readLock();nt.trace("get got read lock");try{return(await this.store.load(e)).protocols}catch(n){if(n.code!==re.ERR_NOT_FOUND)throw n}finally{nt.trace("get release read lock"),r()}return[]}async set(e,r){if(e=Qe(e),!Array.isArray(r))throw nt.error("protocols must be provided to store data"),(0,eu.default)(new Error("protocols must be provided"),re.ERR_INVALID_PARAMETERS);nt.trace("set await write lock");let n=await this.store.lock.writeLock();nt.trace("set got write lock");let i,s;try{try{if(i=await this.store.load(e),new Set([...r]).size===i.protocols.length)return}catch(o){if(o.code!==re.ERR_NOT_FOUND)throw o}s=await this.store.patchOrCreate(e,{protocols:r}),nt("stored provided protocols for %p",e)}finally{nt.trace("set release write lock"),n()}this.dispatchEvent(new Z(Jc,{detail:{peerId:e,protocols:s.protocols,oldProtocols:i==null?[]:i.protocols}}))}async add(e,r){if(e=Qe(e),!Array.isArray(r))throw nt.error("protocols must be provided to store data"),(0,eu.default)(new Error("protocols must be provided"),re.ERR_INVALID_PARAMETERS);nt.trace("add await write lock");let n=await this.store.lock.writeLock();nt.trace("add got write lock");let i,s;try{try{if(i=await this.store.load(e),new Set([...i.protocols,...r]).size===i.protocols.length)return}catch(o){if(o.code!==re.ERR_NOT_FOUND)throw o}s=await this.store.mergeOrCreate(e,{protocols:r}),nt("added provided protocols for %p",e)}finally{nt.trace("add release write lock"),n()}this.dispatchEvent(new Z(Jc,{detail:{peerId:e,protocols:s.protocols,oldProtocols:i==null?[]:i.protocols}}))}async remove(e,r){if(e=Qe(e),!Array.isArray(r))throw nt.error("protocols must be provided to store data"),(0,eu.default)(new Error("protocols must be provided"),re.ERR_INVALID_PARAMETERS);nt.trace("remove await write lock");let n=await this.store.lock.writeLock();nt.trace("remove got write lock");let i,s;try{try{i=await this.store.load(e);let o=new Set(i.protocols);for(let a of r)o.delete(a);if(i.protocols.length===o.size)return;r=Array.from(o)}catch(o){if(o.code!==re.ERR_NOT_FOUND)throw o}s=await this.store.patchOrCreate(e,{protocols:r})}finally{nt.trace("remove release write lock"),n()}this.dispatchEvent(new Z(Jc,{detail:{peerId:e,protocols:s.protocols,oldProtocols:i==null?[]:i.protocols}}))}async delete(e){e=Qe(e),nt.trace("delete await write lock");let r=await this.store.lock.writeLock();nt.trace("delete got write lock");let n;try{try{n=await this.store.load(e)}catch(i){if(i.code!==re.ERR_NOT_FOUND)throw i}await this.store.patchOrCreate(e,{protocols:[]})}finally{nt.trace("delete release write lock"),r()}n!=null&&this.dispatchEvent(new Z(Jc,{detail:{peerId:e,protocols:[],oldProtocols:n.protocols}}))}};var td=C(G(),1);var Ko;(function(t){let e;t.codec=()=>(e==null&&(e=Ne((r,n,i={})=>{if(i.lengthDelimited!==!1&&n.fork(),r.addresses!=null)for(let s of r.addresses)n.uint32(10),ru.codec().encode(s,n,{writeDefaults:!0});if(r.protocols!=null)for(let s of r.protocols)n.uint32(18),n.string(s);if(r.metadata!=null)for(let s of r.metadata)n.uint32(26),nu.codec().encode(s,n,{writeDefaults:!0});r.pubKey!=null&&(n.uint32(34),n.bytes(r.pubKey)),r.peerRecordEnvelope!=null&&(n.uint32(42),n.bytes(r.peerRecordEnvelope)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={addresses:[],protocols:[],metadata:[]},s=n==null?r.len:r.pos+n;for(;r.pos<s;){let o=r.uint32();switch(o>>>3){case 1:i.addresses.push(ru.codec().decode(r,r.uint32()));break;case 2:i.protocols.push(r.string());break;case 3:i.metadata.push(nu.codec().decode(r,r.uint32()));break;case 4:i.pubKey=r.bytes();break;case 5:i.peerRecordEnvelope=r.bytes();break;default:r.skipType(o&7);break}}return i})),e),t.encode=r=>Re(r,t.codec()),t.decode=r=>Te(r,t.codec())})(Ko||(Ko={}));var ru;(function(t){let e;t.codec=()=>(e==null&&(e=Ne((r,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),(i.writeDefaults===!0||r.multiaddr!=null&&r.multiaddr.byteLength>0)&&(n.uint32(10),n.bytes(r.multiaddr)),r.isCertified!=null&&(n.uint32(16),n.bool(r.isCertified)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={multiaddr:new Uint8Array(0)},s=n==null?r.len:r.pos+n;for(;r.pos<s;){let o=r.uint32();switch(o>>>3){case 1:i.multiaddr=r.bytes();break;case 2:i.isCertified=r.bool();break;default:r.skipType(o&7);break}}return i})),e),t.encode=r=>Re(r,t.codec()),t.decode=r=>Te(r,t.codec())})(ru||(ru={}));var nu;(function(t){let e;t.codec=()=>(e==null&&(e=Ne((r,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),(i.writeDefaults===!0||r.key!=="")&&(n.uint32(10),n.string(r.key)),(i.writeDefaults===!0||r.value!=null&&r.value.byteLength>0)&&(n.uint32(18),n.bytes(r.value)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={key:"",value:new Uint8Array(0)},s=n==null?r.len:r.pos+n;for(;r.pos<s;){let o=r.uint32();switch(o>>>3){case 1:i.key=r.string();break;case 2:i.value=r.bytes();break;default:r.skipType(o&7);break}}return i})),e),t.encode=r=>Re(r,t.codec()),t.decode=r=>Te(r,t.codec())})(nu||(nu={}));var Rw=C(ww(),1);var qo=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Uh=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},xw=t=>globalThis.DOMException===void 0?new Uh(t):new DOMException(t),bw=t=>{let e=t.reason===void 0?xw("This operation was aborted."):t.reason;return e instanceof Error?e:xw(e)};function Mh(t,e,r,n){let i,s=new Promise((o,a)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(e===Number.POSITIVE_INFINITY){o(t);return}if(n={customTimers:{setTimeout,clearTimeout},...n},n.signal){let{signal:c}=n;c.aborted&&a(bw(c)),c.addEventListener("abort",()=>{a(bw(c))})}i=n.customTimers.setTimeout.call(void 0,()=>{if(typeof r=="function"){try{o(r())}catch(l){a(l)}return}let c=typeof r=="string"?r:`Promise timed out after ${e} milliseconds`,u=r instanceof Error?r:new qo(c);typeof t.cancel=="function"&&t.cancel(),a(u)},e),(async()=>{try{o(await t)}catch(c){a(c)}finally{n.customTimers.clearTimeout.call(void 0,i)}})()});return s.clear=()=>{clearTimeout(i),i=void 0},s}function Fh(t,e,r){let n=0,i=t.length;for(;i>0;){let s=Math.trunc(i/2),o=n+s;r(t[o],e)<=0?(n=++o,i-=s+1):i=s}return n}var Si=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},on,Ho=class{constructor(){on.set(this,[])}enqueue(e,r){r={priority:0,...r};let n={priority:r.priority,run:e};if(this.size&&Si(this,on,"f")[this.size-1].priority>=r.priority){Si(this,on,"f").push(n);return}let i=Fh(Si(this,on,"f"),n,(s,o)=>o.priority-s.priority);Si(this,on,"f").splice(i,0,n)}dequeue(){let e=Si(this,on,"f").shift();return e?.run}filter(e){return Si(this,on,"f").filter(r=>r.priority===e.priority).map(r=>r.run)}get size(){return Si(this,on,"f").length}};on=new WeakMap;var He=function(t,e,r,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(t,r):i?i.value=r:e.set(t,r),r},V=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},Ze,$o,Go,kn,lu,Yo,su,ar,zo,kt,ou,Ut,Wo,On,au,Sw,_w,Tw,Aw,Cw,Iw,cu,Kh,Vh,fu,uu,XI=new qo,qh=class extends Error{},Cs=class extends Rw.default{constructor(e){var r,n,i,s;if(super(),Ze.add(this),$o.set(this,void 0),Go.set(this,void 0),kn.set(this,0),lu.set(this,void 0),Yo.set(this,void 0),su.set(this,0),ar.set(this,void 0),zo.set(this,void 0),kt.set(this,void 0),ou.set(this,void 0),Ut.set(this,0),Wo.set(this,void 0),On.set(this,void 0),au.set(this,void 0),Object.defineProperty(this,"timeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:Ho,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(n=(r=e.intervalCap)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(s=(i=e.interval)===null||i===void 0?void 0:i.toString())!==null&&s!==void 0?s:""}\` (${typeof e.interval})`);He(this,$o,e.carryoverConcurrencyCount,"f"),He(this,Go,e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,"f"),He(this,lu,e.intervalCap,"f"),He(this,Yo,e.interval,"f"),He(this,kt,new e.queueClass,"f"),He(this,ou,e.queueClass,"f"),this.concurrency=e.concurrency,this.timeout=e.timeout,He(this,au,e.throwOnTimeout===!0,"f"),He(this,On,e.autoStart===!1,"f")}get concurrency(){return V(this,Wo,"f")}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);He(this,Wo,e,"f"),V(this,Ze,"m",fu).call(this)}async add(e,r={}){return new Promise((n,i)=>{let s=async()=>{var o,a,c;He(this,Ut,(a=V(this,Ut,"f"),a++,a),"f"),He(this,kn,(c=V(this,kn,"f"),c++,c),"f");try{if(!((o=r.signal)===null||o===void 0)&&o.aborted){i(new qh("The task was aborted."));return}let l=await(this.timeout===void 0&&r.timeout===void 0?e({signal:r.signal}):Mh(Promise.resolve(e({signal:r.signal})),r.timeout===void 0?this.timeout:r.timeout,()=>{(r.throwOnTimeout===void 0?V(this,au,"f"):r.throwOnTimeout)&&i(XI)}));n(l),this.emit("completed",l)}catch(u){i(u),this.emit("error",u)}V(this,Ze,"m",Tw).call(this)};V(this,kt,"f").enqueue(s,r),V(this,Ze,"m",cu).call(this),this.emit("add")})}async addAll(e,r){return Promise.all(e.map(async n=>this.add(n,r)))}start(){return V(this,On,"f")?(He(this,On,!1,"f"),V(this,Ze,"m",fu).call(this),this):this}pause(){He(this,On,!0,"f")}clear(){He(this,kt,new(V(this,ou,"f")),"f")}async onEmpty(){V(this,kt,"f").size!==0&&await V(this,Ze,"m",uu).call(this,"empty")}async onSizeLessThan(e){V(this,kt,"f").size<e||await V(this,Ze,"m",uu).call(this,"next",()=>V(this,kt,"f").size<e)}async onIdle(){V(this,Ut,"f")===0&&V(this,kt,"f").size===0||await V(this,Ze,"m",uu).call(this,"idle")}get size(){return V(this,kt,"f").size}sizeBy(e){return V(this,kt,"f").filter(e).length}get pending(){return V(this,Ut,"f")}get isPaused(){return V(this,On,"f")}};$o=new WeakMap,Go=new WeakMap,kn=new WeakMap,lu=new WeakMap,Yo=new WeakMap,su=new WeakMap,ar=new WeakMap,zo=new WeakMap,kt=new WeakMap,ou=new WeakMap,Ut=new WeakMap,Wo=new WeakMap,On=new WeakMap,au=new WeakMap,Ze=new WeakSet,Sw=function(){return V(this,Go,"f")||V(this,kn,"f")<V(this,lu,"f")},_w=function(){return V(this,Ut,"f")<V(this,Wo,"f")},Tw=function(){var e;He(this,Ut,(e=V(this,Ut,"f"),e--,e),"f"),V(this,Ze,"m",cu).call(this),this.emit("next")},Aw=function(){this.emit("empty"),V(this,Ut,"f")===0&&this.emit("idle")},Cw=function(){V(this,Ze,"m",Vh).call(this),V(this,Ze,"m",Kh).call(this),He(this,zo,void 0,"f")},Iw=function(){let e=Date.now();if(V(this,ar,"f")===void 0){let r=V(this,su,"f")-e;if(r<0)He(this,kn,V(this,$o,"f")?V(this,Ut,"f"):0,"f");else return V(this,zo,"f")===void 0&&He(this,zo,setTimeout(()=>{V(this,Ze,"m",Cw).call(this)},r),"f"),!0}return!1},cu=function(){if(V(this,kt,"f").size===0)return V(this,ar,"f")&&clearInterval(V(this,ar,"f")),He(this,ar,void 0,"f"),V(this,Ze,"m",Aw).call(this),!1;if(!V(this,On,"f")){let e=!V(this,Ze,"a",Iw);if(V(this,Ze,"a",Sw)&&V(this,Ze,"a",_w)){let r=V(this,kt,"f").dequeue();return r?(this.emit("active"),r(),e&&V(this,Ze,"m",Kh).call(this),!0):!1}}return!1},Kh=function(){V(this,Go,"f")||V(this,ar,"f")!==void 0||(He(this,ar,setInterval(()=>{V(this,Ze,"m",Vh).call(this)},V(this,Yo,"f")),"f"),He(this,su,Date.now()+V(this,Yo,"f"),"f"))},Vh=function(){V(this,kn,"f")===0&&V(this,Ut,"f")===0&&V(this,ar,"f")&&(clearInterval(V(this,ar,"f")),He(this,ar,void 0,"f")),He(this,kn,V(this,$o,"f")?V(this,Ut,"f"):0,"f"),V(this,Ze,"m",fu).call(this)},fu=function(){for(;V(this,Ze,"m",cu).call(this););},uu=async function(e,r){return new Promise(n=>{let i=()=>{r&&!r()||(this.off(e,i),n())};this.on(e,i)})};var Hh=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},zh=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},Nw=t=>globalThis.DOMException===void 0?new zh(t):new DOMException(t),Dw=t=>{let e=t.reason===void 0?Nw("This operation was aborted."):t.reason;return e instanceof Error?e:Nw(e)};function $h(t,e){let{milliseconds:r,fallback:n,message:i,customTimers:s={setTimeout,clearTimeout}}=e,o,a=new Promise((c,u)=>{if(typeof r!="number"||Math.sign(r)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(r===Number.POSITIVE_INFINITY){c(t);return}if(e.signal){let{signal:l}=e;l.aborted&&u(Dw(l)),l.addEventListener("abort",()=>{u(Dw(l))})}o=s.setTimeout.call(void 0,()=>{if(n){try{c(n())}catch(h){u(h)}return}let l=typeof i=="string"?i:`Promise timed out after ${r} milliseconds`,f=i instanceof Error?i:new Hh(l);typeof t.cancel=="function"&&t.cancel(),u(f)},r),(async()=>{try{c(await t)}catch(l){u(l)}finally{s.clearTimeout.call(void 0,o)}})()});return a.clear=()=>{s.clearTimeout.call(void 0,o),o=void 0},a}var Gh="lock:worker:request-read",Yh="lock:worker:release-read",Wh="lock:master:grant-read",Qh="lock:worker:request-write",Xh="lock:worker:release-write",jh="lock:master:grant-write";var Un={},Is=t=>{t.addEventListener("message",e=>{Is.dispatchEvent("message",t,e)}),t.port!=null&&t.port.addEventListener("message",e=>{Is.dispatchEvent("message",t,e)})};Is.addEventListener=(t,e)=>{Un[t]==null&&(Un[t]=[]),Un[t].push(e)};Is.removeEventListener=(t,e)=>{Un[t]!=null&&(Un[t]=Un[t].filter(r=>r===e))};Is.dispatchEvent=function(t,e,r){Un[t]!=null&&Un[t].forEach(n=>n(e,r))};var Zh=Is;var Lw=(t,e,r,n,i)=>(s,o)=>{if(o.data.type!==r)return;let a={type:o.data.type,name:o.data.name,identifier:o.data.identifier};t.dispatchEvent(new MessageEvent(e,{data:{name:a.name,handler:async()=>(s.postMessage({type:i,name:a.name,identifier:a.identifier}),await new Promise(c=>{let u=l=>{if(l==null||l.data==null)return;let f={type:l.data.type,name:l.data.name,identifier:l.data.identifier};f.type===n&&f.identifier===a.identifier&&(s.removeEventListener("message",u),c())};s.addEventListener("message",u)}))}}))},Pw=(t,e,r,n)=>async()=>{let i=ra();return globalThis.postMessage({type:e,identifier:i,name:t}),await new Promise(s=>{let o=a=>{if(a==null||a.data==null)return;let c={type:a.data.type,identifier:a.data.identifier};c.type===r&&c.identifier===i&&(globalThis.removeEventListener("message",o),s(()=>{globalThis.postMessage({type:n,identifier:i,name:t})}))};globalThis.addEventListener("message",o)})},jI={singleProcess:!1},Bw=t=>{if(t=Object.assign({},jI,t),Boolean(globalThis.document)||t.singleProcess){let r=new EventTarget;return Zh.addEventListener("message",Lw(r,"requestReadLock",Gh,Yh,Wh)),Zh.addEventListener("message",Lw(r,"requestWriteLock",Qh,Xh,jh)),r}return{isWorker:!0,readLock:r=>Pw(r,Gh,Wh,Yh),writeLock:r=>Pw(r,Qh,jh,Xh)}};var _i={},Mn;async function Jh(t,e){let r,n=new Promise(i=>{r=i});return t.add(async()=>await $h((async()=>await new Promise(i=>{r(()=>{i()})}))(),{milliseconds:e.timeout})),await n}var ZI=(t,e)=>{if(Mn.isWorker===!0)return{readLock:Mn.readLock(t,e),writeLock:Mn.writeLock(t,e)};let r=new Cs({concurrency:1}),n;return{async readLock(){if(n!=null)return await Jh(n,e);n=new Cs({concurrency:e.concurrency,autoStart:!1});let i=n,s=Jh(n,e);return r.add(async()=>(i.start(),await i.onIdle().then(()=>{n===i&&(n=null)}))),await s},async writeLock(){return n=null,await Jh(r,e)}}},JI={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function ed(t){let e=Object.assign({},JI,t);return Mn==null&&(Mn=Bw(e),Mn.isWorker!==!0&&(Mn.addEventListener("requestReadLock",r=>{_i[r.data.name]!=null&&_i[r.data.name].readLock().then(async n=>await r.data.handler().finally(()=>n()))}),Mn.addEventListener("requestWriteLock",async r=>{_i[r.data.name]!=null&&_i[r.data.name].writeLock().then(async n=>await r.data.handler().finally(()=>n()))}))),_i[e.name]==null&&(_i[e.name]=ZI(e.name,e)),_i[e.name]}var Ow=M("libp2p:peer-store:store"),kw="/peers/",hu=class{constructor(e){this.components=e,this.lock=ed({name:"peer-store",singleProcess:!0})}_peerIdToDatastoreKey(e){if(e.type==null)throw Ow.error("peerId must be an instance of peer-id to store data"),(0,td.default)(new Error("peerId must be an instance of peer-id"),re.ERR_INVALID_PARAMETERS);let r=e.toCID().toString();return new $e(`${kw}${r}`)}async has(e){return await this.components.datastore.has(this._peerIdToDatastoreKey(e))}async delete(e){await this.components.datastore.delete(this._peerIdToDatastoreKey(e))}async load(e){let r=await this.components.datastore.get(this._peerIdToDatastoreKey(e)),n=Ko.decode(r),i=new Map;for(let s of n.metadata)i.set(s.key,s.value);return{...n,id:e,addresses:n.addresses.map(({multiaddr:s,isCertified:o})=>({multiaddr:oe(s),isCertified:o??!1})),metadata:i,pubKey:n.pubKey??void 0,peerRecordEnvelope:n.peerRecordEnvelope??void 0}}async save(e){if(e.pubKey!=null&&e.id.publicKey!=null&&!_e(e.pubKey,e.id.publicKey))throw Ow.error("peer publicKey bytes do not match peer id publicKey bytes"),(0,td.default)(new Error("publicKey bytes do not match peer id publicKey bytes"),re.ERR_INVALID_PARAMETERS);let r=new Set,n=e.addresses.filter(o=>r.has(o.multiaddr.toString())?!1:(r.add(o.multiaddr.toString()),!0)).sort((o,a)=>o.multiaddr.toString().localeCompare(a.multiaddr.toString())).map(({multiaddr:o,isCertified:a})=>({multiaddr:o.bytes,isCertified:a})),i=[];[...e.metadata.keys()].sort().forEach(o=>{let a=e.metadata.get(o);a!=null&&i.push({key:o,value:a})});let s=Ko.encode({addresses:n,protocols:e.protocols.sort(),pubKey:e.pubKey,metadata:i,peerRecordEnvelope:e.peerRecordEnvelope});return await this.components.datastore.put(this._peerIdToDatastoreKey(e.id),s.subarray()),await this.load(e.id)}async patch(e,r){let n=await this.load(e);return await this._patch(e,r,n)}async patchOrCreate(e,r){let n;try{n=await this.load(e)}catch(i){if(i.code!==re.ERR_NOT_FOUND)throw i;n={id:e,addresses:[],protocols:[],metadata:new Map}}return await this._patch(e,r,n)}async _patch(e,r,n){return await this.save({...n,...r,id:e})}async merge(e,r){let n=await this.load(e);return await this._merge(e,r,n)}async mergeOrCreate(e,r){let n;try{n=await this.load(e)}catch(i){if(i.code!==re.ERR_NOT_FOUND)throw i;n={id:e,addresses:[],protocols:[],metadata:new Map}}return await this._merge(e,r,n)}async _merge(e,r,n){let i=new Map;return n.addresses.forEach(s=>{i.set(s.multiaddr.toString(),s.isCertified)}),(r.addresses??[]).forEach(s=>{let o=s.multiaddr.toString(),c=Boolean(i.get(o))||s.isCertified;i.set(o,c)}),await this.save({id:e,addresses:Array.from(i.entries()).map(([s,o])=>({multiaddr:oe(s),isCertified:o})),protocols:Array.from(new Set([...n.protocols??[],...r.protocols??[]])),metadata:new Map([...n.metadata?.entries()??[],...r.metadata?.entries()??[]]),pubKey:r.pubKey??n?.pubKey,peerRecordEnvelope:r.peerRecordEnvelope??n?.peerRecordEnvelope})}async*all(){for await(let e of this.components.datastore.queryKeys({prefix:kw})){let r=e.toString().split("/")[2],n=Tt.decode(r);yield this.load(mn(n))}}};var rd=C(G(),1);var an;(function(t){let e;t.codec=()=>(e==null&&(e=Ne((r,n,i={})=>{if(i.lengthDelimited!==!1&&n.fork(),r.tags!=null)for(let s of r.tags)n.uint32(10),du.codec().encode(s,n,{writeDefaults:!0});i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={tags:[]},s=n==null?r.len:r.pos+n;for(;r.pos<s;){let o=r.uint32();switch(o>>>3){case 1:i.tags.push(du.codec().decode(r,r.uint32()));break;default:r.skipType(o&7);break}}return i})),e),t.encode=r=>Re(r,t.codec()),t.decode=r=>Te(r,t.codec())})(an||(an={}));var du;(function(t){let e;t.codec=()=>(e==null&&(e=Ne((r,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),(i.writeDefaults===!0||r.name!=="")&&(n.uint32(10),n.string(r.name)),r.value!=null&&(n.uint32(16),n.uint32(r.value)),r.expiry!=null&&(n.uint32(24),n.uint64(r.expiry)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={name:""},s=n==null?r.len:r.pos+n;for(;r.pos<s;){let o=r.uint32();switch(o>>>3){case 1:i.name=r.string();break;case 2:i.value=r.uint32();break;case 3:i.expiry=r.uint64();break;default:r.skipType(o&7);break}}return i})),e),t.encode=r=>Re(r,t.codec()),t.decode=r=>Te(r,t.codec())})(du||(du={}));var Qt=M("libp2p:peer-store"),pu=class extends Ue{constructor(e,r={}){super(),this.components=e,this.store=new hu(e),this.addressBook=new Qc(this.dispatchEvent.bind(this),this.store,r.addressFilter),this.keyBook=new Xc(this.dispatchEvent.bind(this),this.store),this.metadataBook=new Zc(this.dispatchEvent.bind(this),this.store),this.protoBook=new tu(this.dispatchEvent.bind(this),this.store)}async forEach(e){Qt.trace("getPeers await read lock");let r=await this.store.lock.readLock();Qt.trace("getPeers got read lock");try{for await(let n of this.store.all())n.id.equals(this.components.peerId)||e(n)}finally{Qt.trace("getPeers release read lock"),r()}}async all(){let e=[];return await this.forEach(r=>{e.push(r)}),e}async delete(e){Qt.trace("delete await write lock");let r=await this.store.lock.writeLock();Qt.trace("delete got write lock");try{await this.store.delete(e)}finally{Qt.trace("delete release write lock"),r()}}async get(e){Qt.trace("get await read lock");let r=await this.store.lock.readLock();Qt.trace("get got read lock");try{return await this.store.load(e)}finally{Qt.trace("get release read lock"),r()}}async has(e){Qt.trace("has await read lock");let r=await this.store.lock.readLock();Qt.trace("has got read lock");try{return await this.store.has(e)}finally{Qt.trace("has release read lock"),r()}}async tagPeer(e,r,n={}){let i=n.value??0,s=Math.round(i),o=n.ttl??void 0;if(s!==i||s<0||s>100)throw(0,rd.default)(new Error("Tag value must be between 0-100"),"ERR_TAG_VALUE_OUT_OF_BOUNDS");let a=await this.metadataBook.getValue(e,"tags"),c=[];a!=null&&(c=an.decode(a).tags);for(let u of c)if(u.name===r)throw(0,rd.default)(new Error("Peer already tagged"),"ERR_DUPLICATE_TAG");c.push({name:r,value:s,expiry:o==null?void 0:BigInt(Date.now()+o)}),await this.metadataBook.setValue(e,"tags",an.encode({tags:c}).subarray())}async unTagPeer(e,r){let n=await this.metadataBook.getValue(e,"tags"),i=[];n!=null&&(i=an.decode(n).tags),i=i.filter(s=>s.name!==r),await this.metadataBook.setValue(e,"tags",an.encode({tags:i}).subarray())}async getTags(e){let r=await this.metadataBook.getValue(e,"tags"),n=[];r!=null&&(n=an.decode(r).tags);let i=BigInt(Date.now()),s=n.filter(o=>o.expiry==null||o.expiry>i);return s.length!==n.length&&await this.metadataBook.setValue(e,"tags",an.encode({tags:s}).subarray()),s.map(o=>({name:o.name,value:o.value??0}))}};var Uw=C(G(),1),mu=class{constructor(e){this.dht=e}async provide(e){await dn(this.dht.provide(e))}async*findProviders(e,r={}){for await(let n of this.dht.findProviders(e,r))n.name==="PROVIDER"&&(yield*n.providers)}async put(e,r,n){await dn(this.dht.put(e,r,n))}async get(e,r){for await(let n of this.dht.get(e,r))if(n.name==="VALUE")return n.value;throw(0,Uw.default)(new Error("Not found"),"ERR_NOT_FOUND")}};var Mt=C(G(),1);var yu=class{constructor(e={}){this._started=!1,this._peerId=e.peerId,this._addressManager=e.addressManager,this._peerStore=e.peerStore,this._upgrader=e.upgrader,this._metrics=e.metrics,this._registrar=e.registrar,this._connectionManager=e.connectionManager,this._transportManager=e.transportManager,this._connectionGater=e.connectionGater,this._contentRouting=e.contentRouting,this._peerRouting=e.peerRouting,this._datastore=e.datastore,this._connectionProtector=e.connectionProtector,this._dht=e.dht,this._pubsub=e.pubsub,this._dialer=e.dialer}isStarted(){return this._started}async beforeStart(){await Promise.all(Object.values(this).filter(e=>Lr(e)).map(async e=>{e.beforeStart!=null&&await e.beforeStart()}))}async start(){await Promise.all(Object.values(this).filter(e=>Lr(e)).map(async e=>{await e.start()})),this._started=!0}async afterStart(){await Promise.all(Object.values(this).filter(e=>Lr(e)).map(async e=>{e.afterStart!=null&&await e.afterStart()}))}async beforeStop(){await Promise.all(Object.values(this).filter(e=>Lr(e)).map(async e=>{e.beforeStop!=null&&await e.beforeStop()}))}async stop(){await Promise.all(Object.values(this).filter(e=>Lr(e)).map(async e=>{await e.stop()})),this._started=!1}async afterStop(){await Promise.all(Object.values(this).filter(e=>Lr(e)).map(async e=>{e.afterStop!=null&&await e.afterStop()}))}get peerId(){if(this._peerId==null)throw(0,Mt.default)(new Error("peerId not set"),"ERR_SERVICE_MISSING");return this._peerId}set peerId(e){this._peerId=e}get addressManager(){if(this._addressManager==null)throw(0,Mt.default)(new Error("addressManager not set"),"ERR_SERVICE_MISSING");return this._addressManager}set addressManager(e){this._addressManager=e}get peerStore(){if(this._peerStore==null)throw(0,Mt.default)(new Error("peerStore not set"),"ERR_SERVICE_MISSING");return this._peerStore}set peerStore(e){this._peerStore=e}get upgrader(){if(this._upgrader==null)throw(0,Mt.default)(new Error("upgrader not set"),"ERR_SERVICE_MISSING");return this._upgrader}set upgrader(e){this._upgrader=e}get registrar(){if(this._registrar==null)throw(0,Mt.default)(new Error("registrar not set"),"ERR_SERVICE_MISSING");return this._registrar}set registrar(e){this._registrar=e}get connectionManager(){if(this._connectionManager==null)throw(0,Mt.default)(new Error("connectionManager not set"),"ERR_SERVICE_MISSING");return this._connectionManager}set connectionManager(e){this._connectionManager=e}get transportManager(){if(this._transportManager==null)throw(0,Mt.default)(new Error("transportManager not set"),"ERR_SERVICE_MISSING");return this._transportManager}set transportManager(e){this._transportManager=e}get connectionGater(){if(this._connectionGater==null)throw(0,Mt.default)(new Error("connectionGater not set"),"ERR_SERVICE_MISSING");return this._connectionGater}set connectionGater(e){this._connectionGater=e}get contentRouting(){if(this._contentRouting==null)throw(0,Mt.default)(new Error("contentRouting not set"),"ERR_SERVICE_MISSING");return this._contentRouting}set contentRouting(e){this._contentRouting=e}get peerRouting(){if(this._peerRouting==null)throw(0,Mt.default)(new Error("peerRouting not set"),"ERR_SERVICE_MISSING");return this._peerRouting}set peerRouting(e){this._peerRouting=e}get datastore(){if(this._datastore==null)throw(0,Mt.default)(new Error("datastore not set"),"ERR_SERVICE_MISSING");return this._datastore}set datastore(e){this._datastore=e}get connectionProtector(){return this._connectionProtector}set connectionProtector(e){this._connectionProtector=e}get dialer(){if(this._dialer==null)throw(0,Mt.default)(new Error("dialer not set"),"ERR_SERVICE_MISSING");return this._dialer}set dialer(e){this._dialer=e}get metrics(){return this._metrics}set metrics(e){this._metrics=e}get dht(){return this._dht}set dht(e){this._dht=e}get pubsub(){return this._pubsub}set pubsub(e){this._pubsub=e}};var id=C(Tu(),1),sd=C(Kw(),1);var Vw=globalThis.fetch,qw=globalThis.Headers,uU=globalThis.Request,lU=globalThis.Response;function gu(t,e,r){return`${t}?name=${e}&type=${r}`}async function Hw(t,e){return await(await Vw(t,{headers:new qw({accept:"application/dns-json"}),signal:e})).json()}function Ai(t,e){return`${e}_${t}`}var nd=Object.assign((0,id.default)("dns-over-http-resolver"),{error:(0,id.default)("dns-over-http-resolver:error")}),od=class{constructor(e={}){this._cache=new sd.default({max:e?.maxCache??100}),this._TXTcache=new sd.default({max:e?.maxCache??100}),this._servers=["https://cloudflare-dns.com/dns-query","https://dns.google/resolve"],this._request=e.request??Hw,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(Ai(e,r));if(n!=null)return n;let i=!1;for(let s of this._getShuffledServers()){let o=new AbortController;this._abortControllers.push(o);try{let a=await this._request(gu(s,e,r),o.signal),c=a.Answer.map(l=>l.data),u=Math.min(...a.Answer.map(l=>l.TTL));return this._cache.set(Ai(e,r),c,{ttl:u}),c}catch{o.signal.aborted&&(i=!0),nd.error(`${s} could not resolve ${e} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==o)}}throw i?Object.assign(new Error("queryA ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${r}`)}async resolve6(e){let r="AAAA",n=this._cache.get(Ai(e,r));if(n!=null)return n;let i=!1;for(let s of this._getShuffledServers()){let o=new AbortController;this._abortControllers.push(o);try{let a=await this._request(gu(s,e,r),o.signal),c=a.Answer.map(l=>l.data),u=Math.min(...a.Answer.map(l=>l.TTL));return this._cache.set(Ai(e,r),c,{ttl:u}),c}catch{o.signal.aborted&&(i=!0),nd.error(`${s} could not resolve ${e} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==o)}}throw i?Object.assign(new Error("queryAaaa ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${r}`)}async resolveTxt(e){let r="TXT",n=this._TXTcache.get(Ai(e,r));if(n!=null)return n;let i=!1;for(let s of this._getShuffledServers()){let o=new AbortController;this._abortControllers.push(o);try{let a=await this._request(gu(s,e,r),o.signal),c=a.Answer.map(l=>[l.data.replace(/['"]+/g,"")]),u=Math.min(...a.Answer.map(l=>l.TTL));return this._TXTcache.set(Ai(e,r),c,{ttl:u}),c}catch{o.signal.aborted&&(i=!0),nd.error(`${s} could not resolve ${e} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==o)}}throw i?Object.assign(new Error("queryTxt ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${r}`)}clearCache(){this._cache.clear(),this._TXTcache.clear()}},zw=od;var $w=zw;var{code:iT}=Ie("dnsaddr");async function Gw(t,e={}){let r=new $w;e.signal!=null&&e.signal.addEventListener("abort",()=>{r.cancel()});let n=t.getPeerId(),[,i]=t.stringTuples().find(([a])=>a===iT)??[];if(i==null)throw new Error("No hostname found in multiaddr");let o=(await r.resolveTxt(`_dnsaddr.${i}`)).flat().map(a=>a.split("=")[1]);return n!=null&&(o=o.filter(a=>a.includes(n))),o}var Eu=C(G(),1);var uT={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:t=>t},connectionManager:{maxConnections:300,minConnections:50,autoDial:!0,autoDialInterval:1e4,maxParallelDials:100,maxDialsPerPeer:4,dialTimeout:3e4,inboundUpgradeTimeout:3e4,resolvers:{dnsaddr:Gw},addressSorter:Ji},connectionGater:{},transportManager:{faultTolerance:vi.FATAL_ALL},peerRouting:{refreshManager:{enabled:!0,interval:6e5,bootDelay:1e4}},nat:{enabled:!0,ttl:7200,keepAlive:!0},relay:{enabled:!0,advertise:{bootDelay:9e5,enabled:!1,ttl:18e5},hop:{enabled:!1,active:!1,timeout:3e4},autoRelay:{enabled:!1,maxListeners:2}},identify:{protocolPrefix:"ipfs",host:{agentVersion:Rh},timeout:6e4,maxInboundStreams:1,maxOutboundStreams:1,maxPushIncomingStreams:1,maxPushOutgoingStreams:1},ping:{protocolPrefix:"ipfs",maxInboundStreams:1,maxOutboundStreams:1,timeout:1e4},fetch:{protocolPrefix:"libp2p",maxInboundStreams:1,maxOutboundStreams:1,timeout:1e4}};function Yw(t){let e=pr(uT,t);if(e.transports==null||e.transports.length<1)throw(0,Eu.default)(new Error(ne.ERR_TRANSPORTS_REQUIRED),b.ERR_TRANSPORTS_REQUIRED);if(e.connectionEncryption==null||e.connectionEncryption.length===0)throw(0,Eu.default)(new Error(ne.CONN_ENCRYPTION_REQUIRED),b.CONN_ENCRYPTION_REQUIRED);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw(0,Eu.default)(new Error(ne.ERR_PROTECTOR_REQUIRED),b.ERR_PROTECTOR_REQUIRED);return e.identify.host.agentVersion===Rh&&(lw||cw?e.identify.host.agentVersion+=` UserAgent=${globalThis.process.version}`:(Fo||fw||uw||hw)&&(e.identify.host.agentVersion+=` UserAgent=${globalThis.navigator.userAgent}`)),e}var ld;(function(t){let e;t.codec=()=>(e==null&&(e=Ne((r,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),(i.writeDefaults===!0||r.id!=null&&r.id.byteLength>0)&&(n.uint32(10),n.bytes(r.id)),r.pubKey!=null&&(n.uint32(18),n.bytes(r.pubKey)),r.privKey!=null&&(n.uint32(26),n.bytes(r.privKey)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={id:new Uint8Array(0)},s=n==null?r.len:r.pos+n;for(;r.pos<s;){let o=r.uint32();switch(o>>>3){case 1:i.id=r.bytes();break;case 2:i.pubKey=r.bytes();break;case 3:i.privKey=r.bytes();break;default:r.skipType(o&7);break}}return i})),e),t.encode=r=>Re(r,t.codec()),t.decode=r=>Te(r,t.codec())})(ld||(ld={}));var Ww=async()=>{let t=await Pc("Ed25519"),e=await lT(t);if(e.type==="Ed25519")return e;throw new Error(`Generated unexpected PeerId type "${e.type}"`)};async function lT(t){return await Ui(vv(t.public),wv(t))}var Xo=C(G(),1);var Xt=C(G(),1);var Qw=Symbol.for("@libp2p/peer-discovery");var vu=class extends Ue{get[Qw](){return!0}get[Symbol.toStringTag](){return"@libp2p/dummy-dht"}get wan(){throw(0,Xt.default)(new Error(ne.DHT_DISABLED),b.DHT_DISABLED)}get lan(){throw(0,Xt.default)(new Error(ne.DHT_DISABLED),b.DHT_DISABLED)}get(){throw(0,Xt.default)(new Error(ne.DHT_DISABLED),b.DHT_DISABLED)}findProviders(){throw(0,Xt.default)(new Error(ne.DHT_DISABLED),b.DHT_DISABLED)}findPeer(){throw(0,Xt.default)(new Error(ne.DHT_DISABLED),b.DHT_DISABLED)}getClosestPeers(){throw(0,Xt.default)(new Error(ne.DHT_DISABLED),b.DHT_DISABLED)}provide(){throw(0,Xt.default)(new Error(ne.DHT_DISABLED),b.DHT_DISABLED)}put(){throw(0,Xt.default)(new Error(ne.DHT_DISABLED),b.DHT_DISABLED)}async getMode(){throw(0,Xt.default)(new Error(ne.DHT_DISABLED),b.DHT_DISABLED)}async setMode(){throw(0,Xt.default)(new Error(ne.DHT_DISABLED),b.DHT_DISABLED)}async refreshRoutingTable(){throw(0,Xt.default)(new Error(ne.DHT_DISABLED),b.DHT_DISABLED)}};var cn=C(G(),1);var wu=class extends Ue{constructor(){super(...arguments),this.topicValidators=new Map}isStarted(){return!1}start(){}stop(){}get globalSignaturePolicy(){throw(0,cn.default)(new Error(ne.PUBSUB_DISABLED),b.ERR_PUBSUB_DISABLED)}get multicodecs(){throw(0,cn.default)(new Error(ne.PUBSUB_DISABLED),b.ERR_PUBSUB_DISABLED)}getPeers(){throw(0,cn.default)(new Error(ne.PUBSUB_DISABLED),b.ERR_PUBSUB_DISABLED)}getTopics(){throw(0,cn.default)(new Error(ne.PUBSUB_DISABLED),b.ERR_PUBSUB_DISABLED)}subscribe(){throw(0,cn.default)(new Error(ne.PUBSUB_DISABLED),b.ERR_PUBSUB_DISABLED)}unsubscribe(){throw(0,cn.default)(new Error(ne.PUBSUB_DISABLED),b.ERR_PUBSUB_DISABLED)}getSubscribers(){throw(0,cn.default)(new Error(ne.PUBSUB_DISABLED),b.ERR_PUBSUB_DISABLED)}async publish(){throw(0,cn.default)(new Error(ne.PUBSUB_DISABLED),b.ERR_PUBSUB_DISABLED)}};var Ts=C(G(),1);var h1=C(Ur(),1),pd=C(hd(),1),d1=C(fr(),1);var Qo=C(G(),1),u1=C(hd(),1),l1=C(a1(),1),dd=C(fr(),1);var c1=M("libp2p:dialer:dial-request"),xu=class{constructor(e){let{addrs:r,dialAction:n,dialer:i}=e;this.addrs=r,this.dialer=i,this.dialAction=n}async run(e={}){let r=this.dialer.getTokens(this.addrs.length);if(r.length<1)throw(0,Qo.default)(new Error("No dial tokens available"),b.ERR_NO_DIAL_TOKENS);let n=new l1.default;for(let a of r)n.push(a).catch(c=>{c1.error(c)});let i=this.addrs.map(()=>{let a=new AbortController;try{(0,dd.setMaxListeners)?.(1/0,a.signal)}catch{}return a});if(e.signal!=null)try{(0,dd.setMaxListeners)?.(1/0,e.signal)}catch{}let s=0,o=!1;try{return await Promise.any(this.addrs.map(async(a,c)=>{let u=await n.shift();if(o)throw this.dialer.releaseToken(r.splice(r.indexOf(u),1)[0]),(0,Qo.default)(new Error("dialAction already succeeded"),b.ERR_ALREADY_SUCCEEDED);let l=i[c];if(l==null)throw(0,Qo.default)(new Error("dialAction did not come with an AbortController"),b.ERR_INVALID_PARAMETERS);let f;try{let h=l.signal;f=await this.dialAction(a,{...e,signal:e.signal!=null?(0,u1.anySignal)([h,e.signal]):h}),i[c]=void 0}finally{s++,this.addrs.length-s>=r.length?n.push(u).catch(h=>{c1.error(h)}):this.dialer.releaseToken(r.splice(r.indexOf(u),1)[0])}if(f==null)throw(0,Qo.default)(new Error("dialAction led to empty object"),b.ERR_TRANSPORT_DIAL_FAILED);return o=!0,f}))}finally{i.forEach(a=>{a!==void 0&&a.abort()}),r.forEach(a=>this.dialer.releaseToken(a))}}};var cr=M("libp2p:dialer"),bu=class{constructor(e,r={}){this.started=!1,this.addressSorter=r.addressSorter??Ji,this.maxAddrsToDial=r.maxAddrsToDial??25,this.timeout=r.dialTimeout??3e4,this.maxDialsPerPeer=r.maxDialsPerPeer??4,this.tokens=[...new Array(r.maxParallelDials??100)].map((n,i)=>i),this.components=e,this.pendingDials=To({name:"libp2p_dialler_pending_dials",metrics:e.metrics}),this.pendingDialTargets=To({name:"libp2p_dialler_pending_dial_targets",metrics:e.metrics});for(let[n,i]of Object.entries(r.resolvers??{}))xl.set(n,i)}isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1;for(let e of this.pendingDials.values())try{e.controller.abort()}catch(r){cr.error(r)}this.pendingDials.clear();for(let e of this.pendingDialTargets.values())e.abort();this.pendingDialTargets.clear()}async dial(e,r={}){let{id:n,multiaddrs:i}=Kr(e);if(this.components.peerId.equals(n))throw(0,Ts.default)(new Error("Tried to dial self"),b.ERR_DIALED_SELF);if(cr("check multiaddrs %p",n),i!=null&&i.length>0&&(cr("storing multiaddrs %p",n,i),await this.components.peerStore.addressBook.add(n,i)),await this.components.connectionGater.denyDialPeer(n))throw(0,Ts.default)(new Error("The dial request is blocked by gater.allowDialPeer"),b.ERR_PEER_DIAL_INTERCEPTED);cr("creating dial target for %p",n);let s=new AbortController,o=f1();this.pendingDialTargets.set(o,s);let a=s.signal;r.signal!=null&&(a=(0,pd.anySignal)([a,r.signal]));let c;try{c=await this._createDialTarget(e,{...r,signal:a})}finally{this.pendingDialTargets.delete(o)}if(c.addrs.length===0)throw(0,Ts.default)(new Error("The dial request has no valid addresses"),b.ERR_NO_VALID_ADDRESSES);let u=this.pendingDials.get(c.id.toString())??this._createPendingDial(c,r);try{let l=await u.promise;return cr("dial succeeded to %s",c.id),l}catch(l){throw cr("dial failed to %s",c.id,l),u.controller.signal.aborted&&(l.code=b.ERR_TIMEOUT),cr.error(l),l}finally{u.destroy()}}async _createDialTarget(e,r){let n=this._resolve.bind(this),i=Fr(e)?[e]:await this._loadAddresses(e);if(i=(await Promise.all(i.map(async o=>await n(o,r)))).flat().filter(o=>Boolean(this.components.transportManager.transportForMultiaddr(o))),i=[...new Set(i)],i.length>this.maxAddrsToDial)throw(0,Ts.default)(new Error("dial with more addresses than allowed"),b.ERR_TOO_MANY_ADDRESSES);let s=Wn(e)?e:void 0;if(s!=null){let o=`/p2p/${s.toString()}`;i=i.map(a=>{let c=a.getPeerId();return c==null||!s.equals(c)?a.encapsulate(o):a})}return{id:s==null?f1():s.toString(),addrs:i}}async _loadAddresses(e){let r=await this.components.peerStore.addressBook.get(e);return(await Promise.all(r.map(async n=>await this.components.connectionGater.denyDialMultiaddr(e,n.multiaddr)?!1:n))).filter(dT).sort(this.addressSorter).map(n=>n.multiaddr)}_createPendingDial(e,r={}){let n=async(u,l={})=>{if(l.signal?.aborted===!0)throw(0,Ts.default)(new Error("already aborted"),b.ERR_ALREADY_ABORTED);return await this.components.transportManager.dial(u,l).catch(f=>{throw cr.error("dial to %s failed",u,f),f})},i=new xu({addrs:e.addrs,dialAction:n,dialer:this}),s=new h1.TimeoutController(this.timeout),o=[s.signal];r.signal!=null&&o.push(r.signal);let a=(0,pd.anySignal)(o);try{(0,d1.setMaxListeners)?.(1/0,a)}catch{}let c={dialRequest:i,controller:s,promise:i.run({...r,signal:a}),destroy:()=>{s.clear(),this.pendingDials.delete(e.id)}};return this.pendingDials.set(e.id,c),c}getTokens(e){let r=Math.min(e,this.maxDialsPerPeer,this.tokens.length),n=this.tokens.splice(0,r);return cr("%d tokens request, returning %d, %d remaining",e,r,this.tokens.length),n}releaseToken(e){this.tokens.includes(e)||(cr("token %d released",e),this.tokens.push(e))}async _resolve(e,r){if(!e.protoNames().includes("dnsaddr"))return[e];let i=await this._resolveRecord(e,r);return(await Promise.all(i.map(async a=>await this._resolve(a,r)))).flat().reduce((a,c)=>(a.find(u=>u.equals(c))==null&&a.push(c),a),[])}async _resolveRecord(e,r){try{return e=oe(e.toString()),await e.resolve(r)}catch(n){return cr.error(`multiaddr ${e.toString()} could not be resolved`,n),[]}}};function dT(t){return Boolean(t)}function f1(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var un=M("libp2p"),md=class extends Ue{constructor(e){super(),this.started=!1,this.peerId=e.peerId;let r=this.components=new yu({peerId:e.peerId,datastore:e.datastore??new oa,connectionGater:{denyDialPeer:async()=>await Promise.resolve(!1),denyDialMultiaddr:async()=>await Promise.resolve(!1),denyInboundConnection:async()=>await Promise.resolve(!1),denyOutboundConnection:async()=>await Promise.resolve(!1),denyInboundEncryptedConnection:async()=>await Promise.resolve(!1),denyOutboundEncryptedConnection:async()=>await Promise.resolve(!1),denyInboundUpgradedConnection:async()=>await Promise.resolve(!1),denyOutboundUpgradedConnection:async()=>await Promise.resolve(!1),filterMultiaddrForPeer:async()=>await Promise.resolve(!0),...e.connectionGater}});r.peerStore=new pu(r,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore}),this.services=[r],e.metrics!=null&&(this.metrics=this.components.metrics=this.configureComponent(e.metrics(this.components))),this.peerStore=this.components.peerStore,this.peerStore.addEventListener("peer",o=>{let{detail:a}=o;this.dispatchEvent(new Z("peer:discovery",{detail:a}))}),e.connectionProtector!=null&&(this.components.connectionProtector=e.connectionProtector(r)),this.components.upgrader=new Fc(this.components,{connectionEncryption:(e.connectionEncryption??[]).map(o=>this.configureComponent(o(this.components))),muxers:(e.streamMuxers??[]).map(o=>this.configureComponent(o(this.components))),inboundUpgradeTimeout:e.connectionManager.inboundUpgradeTimeout}),this.components.dialer=new bu(this.components,e.connectionManager),this.connectionManager=this.components.connectionManager=new Da(this.components,e.connectionManager),this.registrar=this.components.registrar=new Mc(this.components),this.components.transportManager=new kc(this.components,e.transportManager),this.components.addressManager=new xa(this.components,e.addresses),this.configureComponent(new $c(this.components)),this.configureComponent(new La(this.components,{enabled:e.connectionManager.autoDial,minConnections:e.connectionManager.minConnections,autoDialInterval:e.connectionManager.autoDialInterval}));let n=Ao.generateOptions();this.keychain=this.configureComponent(new Ao(this.components,{...n,...e.keychain})),this.services.push(new zc(this.components,e.nat)),e.transports.forEach(o=>{this.components.transportManager.add(this.configureComponent(o(this.components)))}),this.identifyService=new _s(this.components,{...e.identify}),this.configureComponent(this.identifyService),e.dht!=null?this.dht=this.components.dht=e.dht(this.components):this.dht=new vu,e.pubsub!=null?this.pubsub=this.components.pubsub=e.pubsub(this.components):this.pubsub=new wu;let i=(e.peerRouters??[]).map(o=>this.configureComponent(o(this.components)));e.dht!=null&&(i.push(this.configureComponent(new Gc(this.dht))),this.dht.addEventListener("peer",o=>{this.onDiscoveryPeer(o)})),this.peerRouting=this.components.peerRouting=this.configureComponent(new da(this.components,{...e.peerRouting,routers:i}));let s=(e.contentRouters??[]).map(o=>this.configureComponent(o(this.components)));e.dht!=null&&s.push(this.configureComponent(new mu(this.dht))),this.contentRouting=this.components.contentRouting=this.configureComponent(new ma(this.components,{routers:s})),e.relay.enabled&&(this.components.transportManager.add(this.configureComponent(new za(this.components,e.relay))),this.configureComponent(new ja(this.components,{addressSorter:e.connectionManager.addressSorter,...e.relay}))),this.fetchService=this.configureComponent(new Vc(this.components,{...e.fetch})),this.pingService=this.configureComponent(new qc(this.components,{...e.ping}));for(let o of e.peerDiscovery??[])this.configureComponent(o(this.components)).addEventListener("peer",c=>{this.onDiscoveryPeer(c)})}configureComponent(e){return Lr(e)&&this.services.push(e),e}async start(){if(!this.started){this.started=!0,un("libp2p is starting");try{await Promise.all(this.services.map(async e=>{e.beforeStart!=null&&await e.beforeStart()})),await Promise.all(this.services.map(e=>e.start())),await Promise.all(this.services.map(async e=>{e.afterStart!=null&&await e.afterStart()})),un("libp2p has started")}catch(e){throw un.error("An error occurred starting libp2p",e),await this.stop(),e}}}async stop(){this.started&&(un("libp2p is stopping"),this.started=!1,await Promise.all(this.services.map(async e=>{e.beforeStop!=null&&await e.beforeStop()})),await Promise.all(this.services.map(e=>e.stop())),await Promise.all(this.services.map(async e=>{e.afterStop!=null&&await e.afterStop()})),un("libp2p has stopped"))}isStarted(){return this.started}getConnections(e){return this.components.connectionManager.getConnections(e)}getPeers(){let e=new Hr;for(let r of this.components.connectionManager.getConnections())e.add(r.remotePeer);return Array.from(e)}async dial(e,r={}){let{id:n,multiaddrs:i}=Kr(e);return await this.components.peerStore.addressBook.add(n,i),await this.components.connectionManager.openConnection(n,r)}async dialProtocol(e,r,n={}){if(r==null)throw(0,Xo.default)(new Error("no protocols were provided to open a stream"),b.ERR_INVALID_PROTOCOLS_FOR_STREAM);if(r=Array.isArray(r)?r:[r],r.length===0)throw(0,Xo.default)(new Error("no protocols were provided to open a stream"),b.ERR_INVALID_PROTOCOLS_FOR_STREAM);return await(await this.dial(e,n)).newStream(r,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}async hangUp(e){let{id:r}=Kr(e);await this.components.connectionManager.closeConnections(r)}async getPublicKey(e,r={}){if(un("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;let n=await this.peerStore.get(e);if(n.pubKey!=null)return n.pubKey;if(this.dht==null)throw(0,Xo.default)(new Error("Public key was not in the peer store and the DHT is not enabled"),b.ERR_NO_ROUTERS_AVAILABLE);let i=Xe([q("/pk/"),e.multihash.digest]);for await(let s of this.dht.get(i,r))if(s.name==="VALUE"){let o=So(s.value);return await this.peerStore.keyBook.set(e,s.value),o.bytes}throw(0,Xo.default)(new Error(`Node not responding with its public key: ${e.toString()}`),b.ERR_INVALID_RECORD)}async fetch(e,r,n={}){let{id:i,multiaddrs:s}=Kr(e);return s!=null&&await this.components.peerStore.addressBook.add(i,s),await this.fetchService.fetch(i,r,n)}async ping(e,r={}){let{id:n,multiaddrs:i}=Kr(e);return i.length>0&&await this.components.peerStore.addressBook.add(n,i),await this.pingService.ping(n,r)}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)}))}onDiscoveryPeer(e){let{detail:r}=e;if(r.id.toString()===this.peerId.toString()){un.error(new Error(b.ERR_DISCOVERED_SELF));return}r.multiaddrs.length>0&&this.components.peerStore.addressBook.add(r.id,r.multiaddrs).catch(n=>un.error(n)),r.protocols.length>0&&this.components.peerStore.protoBook.set(r.id,r.protocols).catch(n=>un.error(n)),this.dispatchEvent(new Z("peer:discovery",{detail:r}))}};async function p1(t){return t.peerId==null&&(t.peerId=await Ww()),new md(Yw(t))}async function pT(t){let e=await p1(t);return t.start!==!1&&await e.start(),e}return w1(mT);})();
49
+ `);function Ro(t){let e=new Ge(t,Iv);return Vt.single(e)}function wi(t,e,r={}){let n=Ro(e);r.writeBytes===!0?t.push(n.subarray()):t.push(n)}function Tv(t,e,r={}){let n=new Ge;for(let i of e)n.append(Ro(i));r.writeBytes===!0?t.push(n.subarray()):t.push(n)}async function OI(t,e){let r=1,n={[Symbol.asyncIterator]:()=>n,next:async()=>await t.next(r)},i=n;e?.signal!=null&&(i=ni(n,e.signal));let o=await Ce(i,Pt({onLength:a=>{r=a},maxDataLength:1024}),async a=>await Rt(a));if(o==null||o.length===0)throw(0,xh.default)(new Error("no buffer returned"),"ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");if(o.get(o.byteLength-1)!==Iv[0])throw BI.error("Invalid mss message - missing newline - %s",o.subarray()),(0,xh.default)(new Error("missing newline"),"ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");return o.sublist(0,-1)}async function Ss(t,e){let r=await OI(t,e);return Q(r.subarray())}var No=M("libp2p:mss:select");async function Do(t,e,r={}){e=Array.isArray(e)?[...e]:[e];let{reader:n,writer:i,rest:s,stream:o}=Zi(t),a=e.shift();if(a==null)throw new Error("At least one protocol must be specified");No('select: write ["%s", "%s"]',sn,a);let c=q(sn),u=q(a);Tv(i,[c,u],r);let l=await Ss(n,r);if(No('select: read "%s"',l),l===sn&&(l=await Ss(n,r),No('select: read "%s"',l)),l===a)return s(),{stream:o,protocol:a};for(let f of e){No('select: write "%s"',f),wi(i,q(f),r);let h=await Ss(n,r);if(No('select: read "%s" for "%s"',h,f),h===f)return s(),{stream:o,protocol:f}}throw s(),(0,Nv.default)(new Error("protocol selection failed"),"ERR_UNSUPPORTED_PROTOCOL")}var Lo=M("libp2p:mss:handle");async function Po(t,e,r){e=Array.isArray(e)?e:[e];let{writer:n,reader:i,rest:s,stream:o}=Zi(t);for(;;){let a=await Ss(i,r);if(Lo('read "%s"',a),a===sn){Lo('respond with "%s" for "%s"',sn,a),wi(n,q(sn),r);continue}if(e.includes(a))return wi(n,q(a),r),Lo('respond with "%s" for "%s"',a,a),s(),{stream:o,protocol:a};if(a==="ls"){wi(n,new Ge(...e.map(c=>Ro(q(c)))),r),Lo('respond with "%s" for %s',e,a);continue}wi(n,q("na"),r),Lo('respond with "na" for "%s"',a)}}var bh=C(G(),1);var Dv=Symbol.for("@libp2p/connection");var UI=M("libp2p:connection"),Sh=class{constructor(e){let{remoteAddr:r,remotePeer:n,newStream:i,close:s,getStreams:o,stat:a}=e;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=r,this.remotePeer=n,this.stat={...a,status:Ca},this._newStream=i,this._close=s,this._getStreams=o,this.tags=[],this._closing=!1}get[Symbol.toStringTag](){return"Connection"}get[Dv](){return!0}get streams(){return this._getStreams()}async newStream(e,r){if(this.stat.status===_l)throw(0,bh.default)(new Error("the connection is being closed"),"ERR_CONNECTION_BEING_CLOSED");if(this.stat.status===Ia)throw(0,bh.default)(new Error("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===Ia||this._closing)){this.stat.status=_l;try{this.streams.forEach(e=>e.close())}catch(e){UI.error(e)}this._closing=!0,await this._close(),this._closing=!1,this.stat.timeline.close=Date.now(),this.stat.status=Ia}}};function Lv(t){return new Sh(t)}var Uc=C(G(),1);var MI=Symbol.for("@libp2p/topology");function Pv(t){return t!=null&&Boolean(t[MI])}var _h=M("libp2p:registrar"),Ah=32,Ch=64,Mc=class{constructor(e){this.topologies=new Map,this.handlers=new Map,this.components=e,this._onDisconnect=this._onDisconnect.bind(this),this._onProtocolChange=this._onProtocolChange.bind(this),this._onConnect=this._onConnect.bind(this),this.components.connectionManager.addEventListener("peer:disconnect",this._onDisconnect),this.components.connectionManager.addEventListener("peer:connect",this._onConnect),this.components.peerStore.addEventListener("change:protocols",this._onProtocolChange)}getProtocols(){return Array.from(new Set([...this.topologies.keys(),...this.handlers.keys()])).sort()}getHandler(e){let r=this.handlers.get(e);if(r==null)throw(0,Uc.default)(new Error(`No handler registered for protocol ${e}`),b.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(0,Uc.default)(new Error(`Handler already registered for protocol ${e}`),b.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);let i=pr.bind({ignoreUndefined:!0})({maxInboundStreams:Ah,maxOutboundStreams:Ch},n);this.handlers.set(e,{handler:r,options:i}),await this.components.peerStore.protoBook.add(this.components.peerId,[e])}async unhandle(e){let r=Array.isArray(e)?e:[e];r.forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.protoBook.remove(this.components.peerId,r)}async register(e,r){if(!Pv(r))throw _h.error("topology must be an instance of interfaces/topology"),(0,Uc.default)(new Error("topology must be an instance of interfaces/topology"),b.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),await r.setRegistrar(this),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.protoBook.get(r.remotePeer).then(n=>{for(let i of n){let s=this.topologies.get(i);if(s!=null)for(let o of s.values())o.onDisconnect(r.remotePeer)}}).catch(n=>{_h.error(n)})}_onConnect(e){let r=e.detail;this.components.peerStore.protoBook.get(r.remotePeer).then(n=>{for(let i of n){let s=this.topologies.get(i);if(s!=null)for(let o of s.values())o.onConnect(r.remotePeer,r)}}).catch(n=>{_h.error(n)})}_onProtocolChange(e){let{peerId:r,protocols:n,oldProtocols:i}=e.detail,s=i.filter(a=>!n.includes(a)),o=n.filter(a=>!i.includes(a));for(let a of s){let c=this.topologies.get(a);if(c!=null)for(let u of c.values())u.onDisconnect(r)}for(let a of o){let c=this.topologies.get(a);if(c!=null)for(let u of c.values()){let l=this.components.connectionManager.getConnections(r)[0];l!=null&&u.onConnect(r,l)}}}};var Ih=C(Ur(),1);var Th=C(fr(),1),Pe=M("libp2p:upgrader");function FI(t,e){try{let{options:r}=e.getHandler(t);return r.maxInboundStreams}catch(r){if(r.code!==b.ERR_NO_HANDLER_FOR_PROTOCOL)throw r}return Ah}function KI(t,e){try{let{options:r}=e.getHandler(t);return r.maxOutboundStreams}catch(r){if(r.code!==b.ERR_NO_HANDLER_FOR_PROTOCOL)throw r}return Ch}function Bv(t,e,r){let n=0;return r.streams.forEach(i=>{i.stat.direction===e&&i.stat.protocol===t&&n++}),n}var Fc=class extends Ue{constructor(e,r){super(),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}async upgradeInbound(e,r){if(!await this.components.connectionManager.acceptIncomingConnection(e))throw(0,at.default)(new Error("connection denied"),b.ERR_CONNECTION_DENIED);let i,s,o,a,c,u=new Ih.TimeoutController(this.inboundUpgradeTimeout);try{(0,Th.setMaxListeners)?.(1/0,u.signal)}catch{}try{let l=Dt(e,u.signal);if(e.source=l.source,e.sink=l.sink,await this.components.connectionGater.denyInboundConnection(e))throw(0,at.default)(new Error("The multiaddr connection is blocked by gater.acceptConnection"),b.ERR_CONNECTION_INTERCEPTED);this.components.metrics?.trackMultiaddrConnection(e),Pe("starting the inbound connection upgrade");let f=e;if(r?.skipProtection!==!0){let h=this.components.connectionProtector;h!=null&&(Pe("protecting the inbound connection"),f=await h.protect(e))}try{if(i=f,r?.skipEncryption!==!0){if({conn:i,remotePeer:s,protocol:c}=await this._encryptInbound(f),await this.components.connectionGater.denyInboundEncryptedConnection(s,{...f,...i}))throw(0,at.default)(new Error("The multiaddr connection is blocked by gater.acceptEncryptedConnection"),b.ERR_CONNECTION_INTERCEPTED)}else{let h=e.remoteAddr.getPeerId();if(h==null)throw(0,at.default)(new Error("inbound connection that skipped encryption must have a peer id"),b.ERR_INVALID_MULTIADDR);let d=me(h);c="native",s=d}if(o=i,r?.muxerFactory!=null)a=r.muxerFactory;else if(this.muxers.size>0){let h=await this._multiplexInbound({...f,...i},this.muxers);a=h.muxerFactory,o=h.stream}}catch(h){throw Pe.error("Failed to upgrade inbound connection",h),h}if(await this.components.connectionGater.denyInboundUpgradedConnection(s,{...f,...i}))throw(0,at.default)(new Error("The multiaddr connection is blocked by gater.acceptEncryptedConnection"),b.ERR_CONNECTION_INTERCEPTED);return Pe("Successfully upgraded inbound connection"),this._createConnection({cryptoProtocol:c,direction:"inbound",maConn:e,upgradedConn:o,muxerFactory:a,remotePeer:s})}finally{this.components.connectionManager.afterUpgradeInbound(),u.clear()}}async upgradeOutbound(e,r){let n=e.remoteAddr.getPeerId();if(n==null)throw(0,at.default)(new Error("outbound connection must have a peer id"),b.ERR_INVALID_MULTIADDR);let i=me(n);if(await this.components.connectionGater.denyOutboundConnection(i,e))throw(0,at.default)(new Error("The multiaddr connection is blocked by connectionGater.denyOutboundConnection"),b.ERR_CONNECTION_INTERCEPTED);let s,o,a,c,u;this.components.metrics?.trackMultiaddrConnection(e),Pe("Starting the outbound connection upgrade");let l=e;if(r?.skipProtection!==!0){let f=this.components.connectionProtector;f!=null&&(l=await f.protect(e))}try{if(s=l,r?.skipEncryption!==!0){if({conn:s,remotePeer:o,protocol:c}=await this._encryptOutbound(l,i),await this.components.connectionGater.denyOutboundEncryptedConnection(o,{...l,...s}))throw(0,at.default)(new Error("The multiaddr connection is blocked by gater.acceptEncryptedConnection"),b.ERR_CONNECTION_INTERCEPTED)}else c="native",o=i;if(a=s,r?.muxerFactory!=null)u=r.muxerFactory;else if(this.muxers.size>0){let f=await this._multiplexOutbound({...l,...s},this.muxers);u=f.muxerFactory,a=f.stream}}catch(f){throw Pe.error("Failed to upgrade outbound connection",f),await e.close(f),f}if(await this.components.connectionGater.denyOutboundUpgradedConnection(o,{...l,...s}))throw(0,at.default)(new Error("The multiaddr connection is blocked by gater.acceptEncryptedConnection"),b.ERR_CONNECTION_INTERCEPTED);return Pe("Successfully upgraded outbound connection"),this._createConnection({cryptoProtocol:c,direction:"outbound",maConn:e,upgradedConn:a,muxerFactory:u,remotePeer:o})}_createConnection(e){let{cryptoProtocol:r,direction:n,maConn:i,upgradedConn:s,remotePeer:o,muxerFactory:a}=e,c,u,l;a!=null&&(c=a.createStreamMuxer({direction:n,onIncomingStream:d=>{l!=null&&Promise.resolve().then(async()=>{let p=this.components.registrar.getProtocols(),{stream:y,protocol:g}=await Po(d,p);if(Pe("%s: incoming stream opened on %s",n,g),l==null)return;let E=FI(g,this.components.registrar);if(Bv(g,"inbound",l)===E){d.abort((0,at.default)(new Error(`Too many inbound protocol streams for protocol "${g}" - limit ${E}`),b.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS));return}d.source=y.source,d.sink=y.sink,d.stat.protocol=g,this.components.peerStore.protoBook.add(o,[g]).catch(_=>Pe.error(_)),l.addStream(d),this.components.metrics?.trackProtocolStream(d,l),this._onStream({connection:l,stream:d,protocol:g})}).catch(p=>{Pe.error(p),d.stat.timeline.close==null&&d.close()})},onStreamEnd:d=>{l?.removeStream(d.id)}}),u=async(d,p={})=>{if(c==null)throw(0,at.default)(new Error("Stream is not multiplexed"),b.ERR_MUXER_UNAVAILABLE);Pe("%s: starting new stream on %s",n,d);let y=await c.newStream(),g;try{if(p.signal==null){Pe("No abort signal was passed while trying to negotiate protocols %s falling back to default timeout",d),g=new Ih.TimeoutController(3e4),p.signal=g.signal;try{(0,Th.setMaxListeners)?.(1/0,g.signal)}catch{}}let{stream:E,protocol:x}=await Do(y,d,p),_=KI(x,this.components.registrar);if(Bv(x,"outbound",l)===_){let D=(0,at.default)(new Error(`Too many outbound protocol streams for protocol "${x}" - limit ${_}`),b.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);throw y.abort(D),D}return this.components.peerStore.protoBook.add(o,[x]).catch(D=>Pe.error(D)),y.source=E.source,y.sink=E.sink,y.stat.protocol=x,this.components.metrics?.trackProtocolStream(y,l),y}catch(E){throw Pe.error("could not create new stream",E),y.stat.timeline.close==null&&y.close(),E.code!=null?E:(0,at.default)(E,b.ERR_UNSUPPORTED_PROTOCOL)}finally{g?.clear()}},Promise.all([c.sink(s.source),s.sink(c.source)]).catch(d=>{Pe.error(d)}));let f=i.timeline;i.timeline=new Proxy(f,{set:(...d)=>(l!=null&&d[1]==="close"&&d[2]!=null&&f.close==null&&(async()=>{try{l.stat.status==="OPEN"&&await l.close()}catch(p){Pe.error(p)}finally{this.dispatchEvent(new Z("connectionEnd",{detail:l}))}})().catch(p=>{Pe.error(p)}),Reflect.set(...d))}),i.timeline.upgraded=Date.now();let h=()=>{throw(0,at.default)(new Error("connection is not multiplexed"),b.ERR_CONNECTION_NOT_MULTIPLEXED)};return l=Lv({remoteAddr:i.remoteAddr,remotePeer:o,stat:{status:"OPEN",direction:n,timeline:i.timeline,multiplexer:c?.protocol,encryption:r},newStream:u??h,getStreams:()=>c!=null?c.streams:h(),close:async()=>{await i.close(),c?.close()}}),this.dispatchEvent(new Z("connection",{detail:l})),l}_onStream(e){let{connection:r,stream:n,protocol:i}=e,{handler:s}=this.components.registrar.getHandler(i);s({connection:r,stream:n})}async _encryptInbound(e){let r=Array.from(this.connectionEncryption.keys());Pe("handling inbound crypto protocol selection",r);try{let{stream:n,protocol:i}=await Po(e,r,{writeBytes:!0}),s=this.connectionEncryption.get(i);if(s==null)throw new Error(`no crypto module found for ${i}`);return Pe("encrypting inbound connection..."),{...await s.secureInbound(this.components.peerId,n),protocol:i}}catch(n){throw(0,at.default)(n,b.ERR_ENCRYPTION_FAILED)}}async _encryptOutbound(e,r){let n=Array.from(this.connectionEncryption.keys());Pe("selecting outbound crypto protocol",n);try{let{stream:i,protocol:s}=await Do(e,n,{writeBytes:!0}),o=this.connectionEncryption.get(s);if(o==null)throw new Error(`no crypto module found for ${s}`);return Pe("encrypting outbound connection to %p",r),{...await o.secureOutbound(this.components.peerId,i,r),protocol:s}}catch(i){throw(0,at.default)(i,b.ERR_ENCRYPTION_FAILED)}}async _multiplexOutbound(e,r){let n=Array.from(r.keys());Pe("outbound selecting muxer %s",n);try{let{stream:i,protocol:s}=await Do(e,n,{writeBytes:!0});Pe("%s selected as muxer protocol",s);let o=r.get(s);return{stream:i,muxerFactory:o}}catch(i){throw Pe.error("error multiplexing outbound stream",i),(0,at.default)(i,b.ERR_MUXER_UNAVAILABLE)}}async _multiplexInbound(e,r){let n=Array.from(r.keys());Pe("inbound handling muxers %s",n);try{let{stream:i,protocol:s}=await Po(e,n,{writeBytes:!0}),o=r.get(s);return{stream:i,muxerFactory:o}}catch(i){throw Pe.error("error multiplexing inbound stream",i),(0,at.default)(i,b.ERR_MUXER_UNAVAILABLE)}}};var bi=C(G(),1);var xi;(function(t){let e;t.codec=()=>(e==null&&(e=Ne((r,n,i={})=>{if(i.lengthDelimited!==!1&&n.fork(),r.protocolVersion!=null&&(n.uint32(42),n.string(r.protocolVersion)),r.agentVersion!=null&&(n.uint32(50),n.string(r.agentVersion)),r.publicKey!=null&&(n.uint32(10),n.bytes(r.publicKey)),r.listenAddrs!=null)for(let s of r.listenAddrs)n.uint32(18),n.bytes(s);if(r.observedAddr!=null&&(n.uint32(34),n.bytes(r.observedAddr)),r.protocols!=null)for(let s of r.protocols)n.uint32(26),n.string(s);r.signedPeerRecord!=null&&(n.uint32(66),n.bytes(r.signedPeerRecord)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={listenAddrs:[],protocols:[]},s=n==null?r.len:r.pos+n;for(;r.pos<s;){let o=r.uint32();switch(o>>>3){case 5:i.protocolVersion=r.string();break;case 6:i.agentVersion=r.string();break;case 1:i.publicKey=r.bytes();break;case 2:i.listenAddrs.push(r.bytes());break;case 4:i.observedAddr=r.bytes();break;case 3:i.protocols.push(r.string());break;case 8:i.signedPeerRecord=r.bytes();break;default:r.skipType(o&7);break}}return i})),e),t.encode=r=>Re(r,t.codec()),t.decode=r=>Te(r,t.codec())})(xi||(xi={}));var kv=C(G(),1);var Ov={ERR_SIGNATURE_NOT_VALID:"ERR_SIGNATURE_NOT_VALID"};var Bo;(function(t){let e;t.codec=()=>(e==null&&(e=Ne((r,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),(i.writeDefaults===!0||r.publicKey!=null&&r.publicKey.byteLength>0)&&(n.uint32(10),n.bytes(r.publicKey)),(i.writeDefaults===!0||r.payloadType!=null&&r.payloadType.byteLength>0)&&(n.uint32(18),n.bytes(r.payloadType)),(i.writeDefaults===!0||r.payload!=null&&r.payload.byteLength>0)&&(n.uint32(26),n.bytes(r.payload)),(i.writeDefaults===!0||r.signature!=null&&r.signature.byteLength>0)&&(n.uint32(42),n.bytes(r.signature)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={publicKey:new Uint8Array(0),payloadType:new Uint8Array(0),payload:new Uint8Array(0),signature:new Uint8Array(0)},s=n==null?r.len:r.pos+n;for(;r.pos<s;){let o=r.uint32();switch(o>>>3){case 1:i.publicKey=r.bytes();break;case 2:i.payloadType=r.bytes();break;case 3:i.payload=r.bytes();break;case 5:i.signature=r.bytes();break;default:r.skipType(o&7);break}}return i})),e),t.encode=r=>Re(r,t.codec()),t.decode=r=>Te(r,t.codec())})(Bo||(Bo={}));var VI,ct=class{constructor(e){let{peerId:r,payloadType:n,payload:i,signature:s}=e;this.peerId=r,this.payloadType=n,this.payload=i,this.signature=s}marshal(){if(this.peerId.publicKey==null)throw new Error("Missing public key");return this.marshaled==null&&(this.marshaled=Bo.encode({publicKey:this.peerId.publicKey,payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return _e(this.marshal(),e.marshal())}async validate(e){let r=Uv(e,this.payloadType,this.payload);if(this.peerId.publicKey==null)throw new Error("Missing public key");return await So(this.peerId.publicKey).verify(r.subarray(),this.signature)}};VI=ct;ct.createFromProtobuf=async t=>{let e=Bo.decode(t),r=await Ui(e.publicKey);return new ct({peerId:r,payloadType:e.payloadType,payload:e.payload,signature:e.signature})};ct.seal=async(t,e)=>{if(e.privateKey==null)throw new Error("Missing private key");let r=t.domain,n=t.codec,i=t.marshal(),s=Uv(r,n,i),a=await(await xs(e.privateKey)).sign(s.subarray());return new ct({peerId:e,payloadType:n,payload:i,signature:a})};ct.openAndCertify=async(t,e)=>{let r=await ct.createFromProtobuf(t);if(!await r.validate(e))throw(0,kv.default)(new Error("envelope signature is not valid for the given domain"),Ov.ERR_SIGNATURE_NOT_VALID);return r};var Uv=(t,e,r)=>{let n=q(t),i=er.encode(n.byteLength),s=er.encode(e.length),o=er.encode(r.length);return new Ge(i,n,s,e,o,r)};function Mv(t,e){let r=(n,i)=>n.toString().localeCompare(i.toString());return t.length!==e.length?!1:(e.sort(r),t.sort(r).every((n,i)=>e[i].equals(n)))}var Oo;(function(t){let e;(function(n){let i;n.codec=()=>(i==null&&(i=Ne((s,o,a={})=>{a.lengthDelimited!==!1&&o.fork(),(a.writeDefaults===!0||s.multiaddr!=null&&s.multiaddr.byteLength>0)&&(o.uint32(10),o.bytes(s.multiaddr)),a.lengthDelimited!==!1&&o.ldelim()},(s,o)=>{let a={multiaddr:new Uint8Array(0)},c=o==null?s.len:s.pos+o;for(;s.pos<c;){let u=s.uint32();switch(u>>>3){case 1:a.multiaddr=s.bytes();break;default:s.skipType(u&7);break}}return a})),i),n.encode=s=>Re(s,n.codec()),n.decode=s=>Te(s,n.codec())})(e=t.AddressInfo||(t.AddressInfo={}));let r;t.codec=()=>(r==null&&(r=Ne((n,i,s={})=>{if(s.lengthDelimited!==!1&&i.fork(),(s.writeDefaults===!0||n.peerId!=null&&n.peerId.byteLength>0)&&(i.uint32(10),i.bytes(n.peerId)),(s.writeDefaults===!0||n.seq!==0n)&&(i.uint32(16),i.uint64(n.seq)),n.addresses!=null)for(let o of n.addresses)i.uint32(26),t.AddressInfo.codec().encode(o,i,{writeDefaults:!0});s.lengthDelimited!==!1&&i.ldelim()},(n,i)=>{let s={peerId:new Uint8Array(0),seq:0n,addresses:[]},o=i==null?n.len:n.pos+i;for(;n.pos<o;){let a=n.uint32();switch(a>>>3){case 1:s.peerId=n.bytes();break;case 2:s.seq=n.uint64();break;case 3:s.addresses.push(t.AddressInfo.codec().decode(n,n.uint32()));break;default:n.skipType(a&7);break}}return s})),r),t.encode=n=>Re(n,t.codec()),t.decode=n=>Te(n,t.codec())})(Oo||(Oo={}));var Fv="libp2p-peer-record",Kv=Uint8Array.from([3,1]);var tt=class{constructor(e){this.domain=tt.DOMAIN,this.codec=tt.CODEC;let{peerId:r,multiaddrs:n,seqNumber:i}=e;this.peerId=r,this.multiaddrs=n??[],this.seqNumber=i??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=Oo.encode({peerId:this.peerId.toBytes(),seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))})),this.marshaled}equals(e){return!(!(e instanceof tt)||!this.peerId.equals(e.peerId)||this.seqNumber!==e.seqNumber||!Mv(this.multiaddrs,e.multiaddrs))}};tt.createFromProtobuf=t=>{let e=Oo.decode(t),r=mn(e.peerId),n=(e.addresses??[]).map(s=>oe(s.multiaddr)),i=e.seq;return new tt({peerId:r,multiaddrs:n,seqNumber:i})};tt.DOMAIN=Fv;tt.CODEC=Kv;var Kc="0.0.0",Vv="libp2p";var Rh=`js-libp2p/${Kc}`;var qv="0.1.0",Hv="id",zv="id/push",$v="1.0.0",Gv="1.0.0";var ko=C(Ur(),1);var Uo=C(fr(),1),Ae=M("libp2p:identify"),Yv=1024*8,_s=class{constructor(e,r){this.components=e,this.started=!1,this.init=r,this.identifyProtocolStr=`/${r.protocolPrefix}/${Hv}/${$v}`,this.identifyPushProtocolStr=`/${r.protocolPrefix}/${zv}/${Gv}`,this.host={protocolVersion:`${r.protocolPrefix}/${qv}`,...r.host},this.components.connectionManager.addEventListener("peer:connect",n=>{let i=n.detail;this.identify(i).catch(Ae.error)}),this.components.peerStore.addEventListener("change:multiaddrs",n=>{let{peerId:i}=n.detail;this.components.peerId.equals(i)&&this.pushToPeerStore().catch(s=>Ae.error(s))}),this.components.peerStore.addEventListener("change:protocols",n=>{let{peerId:i}=n.detail;this.components.peerId.equals(i)&&this.pushToPeerStore().catch(s=>Ae.error(s))})}isStarted(){return this.started}async start(){this.started||(await this.components.peerStore.metadataBook.setValue(this.components.peerId,"AgentVersion",q(this.host.agentVersion)),await this.components.peerStore.metadataBook.setValue(this.components.peerId,"ProtocolVersion",q(this.host.protocolVersion)),await this.components.registrar.handle(this.identifyProtocolStr,e=>{this._handleIdentify(e).catch(r=>{Ae.error(r)})},{maxInboundStreams:this.init.maxInboundStreams,maxOutboundStreams:this.init.maxOutboundStreams}),await this.components.registrar.handle(this.identifyPushProtocolStr,e=>{this._handlePush(e).catch(r=>{Ae.error(r)})},{maxInboundStreams:this.init.maxPushIncomingStreams,maxOutboundStreams:this.init.maxPushOutgoingStreams}),this.started=!0)}async stop(){await this.components.registrar.unhandle(this.identifyProtocolStr),await this.components.registrar.unhandle(this.identifyPushProtocolStr),this.started=!1}async push(e){let r=await this.components.peerStore.addressBook.getRawEnvelope(this.components.peerId),n=this.components.addressManager.getAddresses().map(o=>o.bytes),i=await this.components.peerStore.protoBook.get(this.components.peerId),s=e.map(async o=>{let a,c=new ko.TimeoutController(this.init.timeout);try{(0,Uo.setMaxListeners)?.(1/0,c.signal)}catch{}try{a=await o.newStream([this.identifyPushProtocolStr],{signal:c.signal}),await Dt(a,c.signal).sink(Ce([xi.encode({listenAddrs:n,signedPeerRecord:r,protocols:i})],Vt()))}catch(u){Ae.error("could not push identify update to peer",u)}finally{a?.close(),c.clear()}});await Promise.all(s)}async pushToPeerStore(){if(!this.isStarted())return;let e=[];for(let r of this.components.connectionManager.getConnections()){let n=r.remotePeer;(await this.components.peerStore.get(n)).protocols.includes(this.identifyPushProtocolStr)&&e.push(r)}await this.push(e)}async _identify(e,r={}){let n,i=r.signal,s;if(i==null){n=new ko.TimeoutController(this.init.timeout),i=n.signal;try{(0,Uo.setMaxListeners)?.(1/0,n.signal)}catch{}}try{s=await e.newStream([this.identifyProtocolStr],{signal:i});let o=Dt(s,i),a=await Ce([],o,Pt({maxDataLength:this.init.maxIdentifyMessageSize??Yv}),async c=>await Rt(c));if(a==null)throw(0,bi.default)(new Error("No data could be retrieved"),b.ERR_CONNECTION_ENDED);try{return xi.decode(a)}catch(c){throw(0,bi.default)(c,b.ERR_INVALID_MESSAGE)}}finally{n?.clear(),s?.close()}}async identify(e,r={}){let n=await this._identify(e,r),{publicKey:i,listenAddrs:s,protocols:o,observedAddr:a,signedPeerRecord:c,agentVersion:u,protocolVersion:l}=n;if(i==null)throw(0,bi.default)(new Error("public key was missing from identify message"),b.ERR_MISSING_PUBLIC_KEY);let f=await Ui(i);if(!e.remotePeer.equals(f))throw(0,bi.default)(new Error("identified peer does not match the expected peer"),b.ERR_INVALID_PEER);if(this.components.peerId.equals(f))throw(0,bi.default)(new Error("identified peer is our own peer id?"),b.ERR_INVALID_PEER);let h=_s.getCleanMultiaddr(a);if(c!=null){Ae("received signed peer record from %p",f);try{let d=await ct.openAndCertify(c,tt.DOMAIN);if(!d.peerId.equals(f))throw(0,bi.default)(new Error("identified peer does not match the expected peer"),b.ERR_INVALID_PEER);if(await this.components.peerStore.addressBook.consumePeerRecord(d)){await this.components.peerStore.protoBook.set(f,o),u!=null&&await this.components.peerStore.metadataBook.setValue(f,"AgentVersion",q(u)),l!=null&&await this.components.peerStore.metadataBook.setValue(f,"ProtocolVersion",q(l)),Ae("identify completed for peer %p and protocols %o",f,o);return}}catch(d){Ae("received invalid envelope, discard it and fallback to listenAddrs is available",d)}}else Ae("no signed peer record received from %p",f);Ae("falling back to legacy addresses from %p",f);try{await this.components.peerStore.addressBook.set(f,s.map(d=>oe(d)))}catch(d){Ae.error("received invalid addrs",d)}await this.components.peerStore.protoBook.set(f,o),u!=null&&await this.components.peerStore.metadataBook.setValue(f,"AgentVersion",q(u)),l!=null&&await this.components.peerStore.metadataBook.setValue(f,"ProtocolVersion",q(l)),Ae("identify completed for peer %p and protocols %o",f,o),Ae("received observed address of %s",h?.toString())}async _handleIdentify(e){let{connection:r,stream:n}=e,i=new ko.TimeoutController(this.init.timeout);try{(0,Uo.setMaxListeners)?.(1/0,i.signal)}catch{}try{let s=this.components.peerId.publicKey??new Uint8Array(0),o=await this.components.peerStore.get(this.components.peerId),a=this.components.addressManager.getAddresses().map(h=>h.decapsulateCode(Ie("p2p").code)),c=o.peerRecordEnvelope;if(a.length>0&&c==null){let h=new tt({peerId:this.components.peerId,multiaddrs:a}),d=await ct.seal(h,this.components.peerId);await this.components.peerStore.addressBook.consumePeerRecord(d),c=d.marshal().subarray()}let u=xi.encode({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:s,listenAddrs:a.map(h=>h.bytes),signedPeerRecord:c,observedAddr:r.remoteAddr.bytes,protocols:o.protocols}),l=Dt(n,i.signal),f=Ce([u],Vt());await l.sink(f)}catch(s){Ae.error("could not respond to identify request",s)}finally{n.close(),i.clear()}}async _handlePush(e){let{connection:r,stream:n}=e,i=new ko.TimeoutController(this.init.timeout);try{(0,Uo.setMaxListeners)?.(1/0,i.signal)}catch{}let s;try{let a=Dt(n,i.signal),c=await Ce([],a,Pt({maxDataLength:this.init.maxIdentifyMessageSize??Yv}),async u=>await Rt(u));c!=null&&(s=xi.decode(c))}catch(a){return Ae.error("received invalid message",a)}finally{n.close(),i.clear()}if(s==null)return Ae.error("received invalid message");let o=r.remotePeer;if(this.components.peerId.equals(o)){Ae("received push from ourselves?");return}if(Ae("received push from %p",o),s.signedPeerRecord!=null){Ae("received signedPeerRecord in push");try{let a=await ct.openAndCertify(s.signedPeerRecord,tt.DOMAIN);if(await this.components.peerStore.addressBook.consumePeerRecord(a)){Ae("consumed signedPeerRecord sent in push"),await this.components.peerStore.protoBook.set(o,s.protocols);return}else Ae("failed to consume signedPeerRecord sent in push")}catch(a){Ae("received invalid envelope, discard it and fallback to listenAddrs is available",a)}}else Ae("did not receive signedPeerRecord in push");try{await this.components.peerStore.addressBook.set(o,s.listenAddrs.map(a=>oe(a)))}catch(a){Ae.error("received invalid addrs",a)}try{await this.components.peerStore.protoBook.set(o,s.protocols)}catch(a){Ae.error("received invalid protocols",a)}Ae("handled push from %p",o)}static getCleanMultiaddr(e){if(e!=null&&e.length>0)try{return oe(e)}catch{}}};var As=C(G(),1);var Mo;(function(t){let e;t.codec=()=>(e==null&&(e=Ne((r,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),(i.writeDefaults===!0||r.identifier!=="")&&(n.uint32(10),n.string(r.identifier)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={identifier:""},s=n==null?r.len:r.pos+n;for(;r.pos<s;){let o=r.uint32();switch(o>>>3){case 1:i.identifier=r.string();break;default:r.skipType(o&7);break}}return i})),e),t.encode=r=>Re(r,t.codec()),t.decode=r=>Te(r,t.codec())})(Mo||(Mo={}));var or;(function(t){let e;(function(i){i.OK="OK",i.NOT_FOUND="NOT_FOUND",i.ERROR="ERROR"})(e=t.StatusCode||(t.StatusCode={}));let r;(function(i){i[i.OK=0]="OK",i[i.NOT_FOUND=1]="NOT_FOUND",i[i.ERROR=2]="ERROR"})(r||(r={})),function(i){i.codec=()=>wn(r)}(e=t.StatusCode||(t.StatusCode={}));let n;t.codec=()=>(n==null&&(n=Ne((i,s,o={})=>{o.lengthDelimited!==!1&&s.fork(),(o.writeDefaults===!0||i.status!=null&&r[i.status]!==0)&&(s.uint32(8),t.StatusCode.codec().encode(i.status,s)),(o.writeDefaults===!0||i.data!=null&&i.data.byteLength>0)&&(s.uint32(18),s.bytes(i.data)),o.lengthDelimited!==!1&&s.ldelim()},(i,s)=>{let o={status:e.OK,data:new Uint8Array(0)},a=s==null?i.len:i.pos+s;for(;i.pos<a;){let c=i.uint32();switch(c>>>3){case 1:o.status=t.StatusCode.codec().decode(i);break;case 2:o.data=i.bytes();break;default:i.skipType(c&7);break}}return o})),n),t.encode=i=>Re(i,t.codec()),t.decode=i=>Te(i,t.codec())})(or||(or={}));var Wv="0.0.1",Qv="fetch";var Xv=C(Ur(),1),jv=C(fr(),1);var Wt=M("libp2p:fetch"),Vc=class{constructor(e,r){this.started=!1,this.components=e,this.protocol=`/${r.protocolPrefix??"libp2p"}/${Qv}/${Wv}`,this.lookupFunctions=new Map,this.handleMessage=this.handleMessage.bind(this),this.init=r}async start(){await this.components.registrar.handle(this.protocol,e=>{this.handleMessage(e).catch(r=>{Wt.error(r)}).finally(()=>{e.stream.close()})},{maxInboundStreams:this.init.maxInboundStreams,maxOutboundStreams:this.init.maxOutboundStreams}),this.started=!0}async stop(){await this.components.registrar.unhandle(this.protocol),this.started=!1}isStarted(){return this.started}async fetch(e,r,n={}){Wt("dialing %s to %p",this.protocol,e);let i=await this.components.connectionManager.openConnection(e,n),s,o=n.signal,a;if(o==null){Wt("using default timeout of %d ms",this.init.timeout),s=new Xv.TimeoutController(this.init.timeout),o=s.signal;try{(0,jv.setMaxListeners)?.(1/0,s.signal)}catch{}}try{a=await i.newStream(this.protocol,{signal:o});let c=Dt(a,o);return Wt("fetch %s",r),await Ce([Mo.encode({identifier:r})],Vt(),c,Pt(),async function(l){let f=await Rt(l);if(f==null)throw(0,As.default)(new Error("No data received"),b.ERR_INVALID_MESSAGE);let h=or.decode(f);switch(h.status){case or.StatusCode.OK:return Wt("received status for %s ok",r),h.data;case or.StatusCode.NOT_FOUND:return Wt("received status for %s not found",r),null;case or.StatusCode.ERROR:{Wt("received status for %s error",r);let d=Q(h.data);throw(0,As.default)(new Error("Error in fetch protocol response: "+d),b.ERR_INVALID_PARAMETERS)}default:throw Wt("received status for %s unknown",r),(0,As.default)(new Error("Unknown response status"),b.ERR_INVALID_MESSAGE)}})??null}finally{s?.clear(),a?.close()}}async handleMessage(e){let{stream:r}=e,n=this;await Ce(r,Pt(),async function*(i){let s=await Rt(i);if(s==null)throw(0,As.default)(new Error("No data received"),b.ERR_INVALID_MESSAGE);let o=Mo.decode(s),a,c=n._getLookupFunction(o.identifier);if(c!=null){Wt("look up data with identifier %s",o.identifier);let u=await c(o.identifier);u!=null?(Wt("sending status for %s ok",o.identifier),a={status:or.StatusCode.OK,data:u}):(Wt("sending status for %s not found",o.identifier),a={status:or.StatusCode.NOT_FOUND,data:new Uint8Array(0)})}else{Wt("sending status for %s error",o.identifier);let u=q(`No lookup function registered for key: ${o.identifier}`);a={status:or.StatusCode.ERROR,data:u}}yield or.encode(a)},Vt(),r)}_getLookupFunction(e){for(let r of this.lookupFunctions.keys())if(e.startsWith(r))return this.lookupFunctions.get(r)}registerLookupFunction(e,r){if(this.lookupFunctions.has(e))throw(0,As.default)(new Error("Fetch protocol handler for key prefix '"+e+"' already registered"),b.ERR_KEY_ALREADY_EXISTS);this.lookupFunctions.set(e,r)}unregisterLookupFunction(e,r){r!=null&&this.lookupFunctions.get(e)!==r||this.lookupFunctions.delete(e)}};var tw=C(G(),1);var Zv="1.0.0",Jv="ping";var rw=C(Ur(),1),nw=C(fr(),1),ew=M("libp2p:ping"),qc=class{constructor(e,r){this.components=e,this.started=!1,this.protocol=`/${r.protocolPrefix}/${Jv}/${Zv}`,this.init=r}async start(){await this.components.registrar.handle(this.protocol,this.handleMessage,{maxInboundStreams:this.init.maxInboundStreams,maxOutboundStreams:this.init.maxOutboundStreams}),this.started=!0}async stop(){await this.components.registrar.unhandle(this.protocol),this.started=!1}isStarted(){return this.started}handleMessage(e){let{stream:r}=e;Ce(r,r).catch(n=>{ew.error(n)})}async ping(e,r={}){ew("dialing %s to %p",this.protocol,e);let n=Date.now(),i=Zr(32),s=await this.components.connectionManager.openConnection(e,r),o,a=r.signal,c;if(a==null){o=new rw.TimeoutController(this.init.timeout),a=o.signal;try{(0,nw.setMaxListeners)?.(1/0,o.signal)}catch{}}try{c=await s.newStream([this.protocol],{signal:a});let u=Dt(c,a),l=await Ce([i],u,async h=>await Rt(h)),f=Date.now();if(l==null||!_e(i,l.subarray()))throw(0,tw.default)(new Error("Received wrong ping ack"),b.ERR_WRONG_PING_ACK);return f-n}finally{o?.clear(),c?.close()}}};async function iw(){throw new Error("Not supported in browsers")}var aw=C(ow(),1),Nh=typeof window=="object"&&typeof document=="object"&&document.nodeType===9,Hc=(0,aw.default)(),Fo=Nh&&!Hc,cw=Hc&&!Nh,uw=Hc&&Nh,lw=typeof globalThis.process<"u"&&typeof globalThis.process.release<"u"&&globalThis.process.release.name==="node"&&!Hc,fw=typeof importScripts=="function"&&typeof self<"u"&&typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope,w6=typeof globalThis.process<"u"&&typeof globalThis.process.env<"u"&&globalThis.process.env["NODE"+(()=>"_")()+"ENV"]==="test",hw=typeof navigator<"u"&&navigator.product==="ReactNative";var mw=C(G(),1);function dw(t){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(t)||/^::1$/.test(t)}function pw(t){let{address:e}=t.nodeAddress();return dw(e)}var Dh=M("libp2p:nat"),Lh=7200;function $I(t=1024,e=65535){return Math.floor(Math.random()*(e-t+1)+t)}var zc=class{constructor(e,r){if(this.components=e,this.started=!1,this.enabled=r.enabled,this.externalAddress=r.externalAddress,this.localAddress=r.localAddress,this.description=r.description??`${Vv}@${Kc} ${this.components.peerId.toString()}`,this.ttl=r.ttl??Lh,this.keepAlive=r.keepAlive??!0,this.gateway=r.gateway,this.ttl<Lh)throw(0,mw.default)(new Error(`NatManager ttl should be at least ${Lh} seconds`),b.ERR_INVALID_PARAMETERS)}isStarted(){return this.started}start(){}afterStart(){Fo||!this.enabled||this.started||(this.started=!0,this._start().catch(e=>{Dh.error(e)}))}async _start(){let e=this.components.transportManager.getAddrs();for(let r of e){let{family:n,host:i,port:s,transport:o}=r.toOptions();if(!r.isThinWaistAddress()||o!=="tcp"||pw(r)||n!==4)continue;let a=await this._getClient(),c=this.externalAddress??await a.externalIp(),u=Qa(c);if(u===!0)throw new Error(`${c} is private - please set config.nat.externalIp to an externally routable IP or ensure you are not behind a double NAT`);if(u==null)throw new Error(`${c} is not an IP address`);let l=$I();Dh(`opening uPnP connection from ${c}:${l} to ${i}:${s}`),await a.map({publicPort:l,localPort:s,localAddress:this.localAddress,protocol:o.toUpperCase()==="TCP"?"TCP":"UDP"}),this.components.addressManager.addObservedAddr(Zp({family:4,address:c,port:l},o))}}async _getClient(){return this.client!=null?this.client:(this.client=await iw({description:this.description,ttl:this.ttl,keepAlive:this.keepAlive,gateway:this.gateway}),this.client)}async stop(){if(!(Fo||this.client==null))try{await this.client.close(),this.client=void 0}catch(e){Dh.error(e)}}};var GI=M("libp2p:peer-record-updater"),$c=class{constructor(e){this.components=e,this.started=!1,this.update=this.update.bind(this)}isStarted(){return this.started}async start(){this.started=!0,this.components.transportManager.addEventListener("listener:listening",this.update),this.components.transportManager.addEventListener("listener:close",this.update),this.components.addressManager.addEventListener("change:addresses",this.update)}async stop(){this.started=!1,this.components.transportManager.removeEventListener("listener:listening",this.update),this.components.transportManager.removeEventListener("listener:close",this.update),this.components.addressManager.removeEventListener("change:addresses",this.update)}update(){Promise.resolve().then(async()=>{let e=new tt({peerId:this.components.peerId,multiaddrs:this.components.addressManager.getAddresses().map(n=>n.decapsulateCode(Ie("p2p").code))}),r=await ct.seal(e,this.components.peerId);await this.components.peerStore.addressBook.consumePeerRecord(r)}).catch(e=>{GI.error("Could not update self peer record: %o",e)})}};var yw=C(G(),1);var Gc=class{constructor(e){this.dht=e}async findPeer(e,r={}){for await(let n of this.dht.findPeer(e,r))if(n.name==="FINAL_PEER")return n.peer;throw(0,yw.default)(new Error(ne.NOT_FOUND),b.ERR_NOT_FOUND)}async*getClosestPeers(e,r={}){for await(let n of this.dht.getClosestPeers(e,r))n.name==="FINAL_PEER"&&(yield n.peer)}};var Wc=C(G(),1);var re={ERR_INVALID_PARAMETERS:"ERR_INVALID_PARAMETERS",ERR_NOT_FOUND:"ERR_NOT_FOUND"};async function*Ph(t,e){for await(let r of t)await e(r),yield r}var Se=M("libp2p:peer-store:address-book"),Yc="change:multiaddrs";async function YI(){return!0}var Qc=class{constructor(e,r,n){this.dispatchEvent=e,this.store=r,this.addressFilter=n??YI}async consumePeerRecord(e){Se.trace("consumePeerRecord await write lock");let r=await this.store.lock.writeLock();Se.trace("consumePeerRecord got write lock");let n,i,s;try{let o;try{o=tt.createFromProtobuf(e.payload)}catch{return Se.error("invalid peer record received"),!1}n=o.peerId;let a=o.multiaddrs;if(!n.equals(e.peerId))return Se("signing key does not match PeerId in the PeerRecord"),!1;if(a==null||a.length===0)return!1;if(await this.store.has(n)&&(i=await this.store.load(n),i.peerRecordEnvelope!=null)){let u=await ct.createFromProtobuf(i.peerRecordEnvelope),l=tt.createFromProtobuf(u.payload);if(l.seqNumber>=o.seqNumber)return Se("sequence number was lower or equal to existing sequence number - stored: %d received: %d",l.seqNumber,o.seqNumber),!1}let c=await Bh(n,a,this.addressFilter,!0);s=await this.store.patchOrCreate(n,{addresses:c,peerRecordEnvelope:e.marshal().subarray()}),Se("stored provided peer record for %p",o.peerId)}finally{Se.trace("consumePeerRecord release write lock"),r()}return this.dispatchEvent(new Z(Yc,{detail:{peerId:n,multiaddrs:s.addresses.map(({multiaddr:o})=>o),oldMultiaddrs:i==null?[]:i.addresses.map(({multiaddr:o})=>o)}})),!0}async getRawEnvelope(e){Se.trace("getRawEnvelope await read lock");let r=await this.store.lock.readLock();Se.trace("getRawEnvelope got read lock");try{return(await this.store.load(e)).peerRecordEnvelope}catch(n){if(n.code!==re.ERR_NOT_FOUND)throw n}finally{Se.trace("getRawEnvelope release read lock"),r()}}async getPeerRecord(e){let r=await this.getRawEnvelope(e);if(r!=null)return await ct.createFromProtobuf(r)}async get(e){e=Qe(e),Se.trace("get wait for read lock");let r=await this.store.lock.readLock();Se.trace("get got read lock");try{return(await this.store.load(e)).addresses}catch(n){if(n.code!==re.ERR_NOT_FOUND)throw n}finally{Se.trace("get release read lock"),r()}return[]}async set(e,r){if(e=Qe(e),!Array.isArray(r))throw Se.error("multiaddrs must be an array of Multiaddrs"),(0,Wc.default)(new Error("multiaddrs must be an array of Multiaddrs"),re.ERR_INVALID_PARAMETERS);Se.trace("set await write lock");let n=await this.store.lock.writeLock();Se.trace("set got write lock");let i=!1,s,o;try{let a=await Bh(e,r,this.addressFilter);if(a.length===0)return;try{if(s=await this.store.load(e),i=!0,new Set([...a.map(({multiaddr:c})=>c.toString()),...s.addresses.map(({multiaddr:c})=>c.toString())]).size===s.addresses.length&&a.length===s.addresses.length)return}catch(c){if(c.code!==re.ERR_NOT_FOUND)throw c}o=await this.store.patchOrCreate(e,{addresses:a}),Se("set multiaddrs for %p",e)}finally{Se.trace("set multiaddrs for %p",e),Se("set release write lock"),n()}this.dispatchEvent(new Z(Yc,{detail:{peerId:e,multiaddrs:o.addresses.map(a=>a.multiaddr),oldMultiaddrs:s==null?[]:s.addresses.map(({multiaddr:a})=>a)}})),i||this.dispatchEvent(new Z("peer",{detail:{id:e,multiaddrs:o.addresses.map(a=>a.multiaddr),protocols:o.protocols}}))}async add(e,r){if(e=Qe(e),!Array.isArray(r))throw Se.error("multiaddrs must be an array of Multiaddrs"),(0,Wc.default)(new Error("multiaddrs must be an array of Multiaddrs"),re.ERR_INVALID_PARAMETERS);Se.trace("add await write lock");let n=await this.store.lock.writeLock();Se.trace("add got write lock");let i,s,o;try{let a=await Bh(e,r,this.addressFilter);if(a.length===0)return;try{if(s=await this.store.load(e),i=!0,new Set([...a.map(({multiaddr:c})=>c.toString()),...s.addresses.map(({multiaddr:c})=>c.toString())]).size===s.addresses.length)return}catch(c){if(c.code!==re.ERR_NOT_FOUND)throw c}o=await this.store.mergeOrCreate(e,{addresses:a}),Se("added multiaddrs for %p",e)}finally{Se.trace("set release write lock"),n()}this.dispatchEvent(new Z(Yc,{detail:{peerId:e,multiaddrs:o.addresses.map(a=>a.multiaddr),oldMultiaddrs:s==null?[]:s.addresses.map(({multiaddr:a})=>a)}})),i===!0&&this.dispatchEvent(new Z("peer",{detail:{id:e,multiaddrs:o.addresses.map(a=>a.multiaddr),protocols:o.protocols}}))}async delete(e){e=Qe(e),Se.trace("delete await write lock");let r=await this.store.lock.writeLock();Se.trace("delete got write lock");let n;try{try{n=await this.store.load(e)}catch(i){if(i.code!==re.ERR_NOT_FOUND)throw i}await this.store.patchOrCreate(e,{addresses:[]})}finally{Se.trace("delete release write lock"),r()}n!=null&&this.dispatchEvent(new Z(Yc,{detail:{peerId:e,multiaddrs:[],oldMultiaddrs:n==null?[]:n.addresses.map(({multiaddr:i})=>i)}}))}};async function Bh(t,e,r,n=!1){return await Ce(e,i=>Ph(i,s=>{if(!Fr(s))throw Se.error("multiaddr must be an instance of Multiaddr"),(0,Wc.default)(new Error("multiaddr must be an instance of Multiaddr"),re.ERR_INVALID_PARAMETERS)}),i=>kr(i,async s=>await r(t,s)),i=>Ls(i,s=>({multiaddr:s,isCertified:n})),async i=>await zr(i))}var Ew=C(G(),1);var Rr=M("libp2p:peer-store:key-book"),gw="change:pubkey",Xc=class{constructor(e,r){this.dispatchEvent=e,this.store=r}async set(e,r){if(e=Qe(e),!(r instanceof Uint8Array))throw Rr.error("publicKey must be an instance of Uint8Array to store data"),(0,Ew.default)(new Error("publicKey must be an instance of PublicKey"),re.ERR_INVALID_PARAMETERS);Rr.trace("set await write lock");let n=await this.store.lock.writeLock();Rr.trace("set got write lock");let i=!1,s;try{try{if(s=await this.store.load(e),s.pubKey!=null&&_e(s.pubKey,r))return}catch(o){if(o.code!==re.ERR_NOT_FOUND)throw o}await this.store.patchOrCreate(e,{pubKey:r}),i=!0}finally{Rr.trace("set release write lock"),n()}i&&this.dispatchEvent(new Z(gw,{detail:{peerId:e,publicKey:r,oldPublicKey:s?.pubKey}}))}async get(e){e=Qe(e),Rr.trace("get await write lock");let r=await this.store.lock.readLock();Rr.trace("get got write lock");try{return(await this.store.load(e)).pubKey}catch(n){if(n.code!==re.ERR_NOT_FOUND)throw n}finally{Rr("get release write lock"),r()}}async delete(e){e=Qe(e),Rr.trace("delete await write lock");let r=await this.store.lock.writeLock();Rr.trace("delete got write lock");let n;try{try{n=await this.store.load(e)}catch(i){if(i.code!==re.ERR_NOT_FOUND)throw i}await this.store.patchOrCreate(e,{pubKey:void 0})}catch(i){if(i.code!==re.ERR_NOT_FOUND)throw i}finally{Rr.trace("delete release write lock"),r()}this.dispatchEvent(new Z(gw,{detail:{peerId:e,publicKey:void 0,oldPublicKey:n?.pubKey}}))}};var Oh=C(G(),1);var rt=M("libp2p:peer-store:metadata-book"),jc="change:metadata",Zc=class{constructor(e,r){this.dispatchEvent=e,this.store=r}async get(e){e=Qe(e),rt.trace("get await read lock");let r=await this.store.lock.readLock();rt.trace("get got read lock");try{return(await this.store.load(e)).metadata}catch(n){if(n.code!==re.ERR_NOT_FOUND)throw n}finally{rt.trace("get release read lock"),r()}return new Map}async getValue(e,r){e=Qe(e),rt.trace("getValue await read lock");let n=await this.store.lock.readLock();rt.trace("getValue got read lock");try{return(await this.store.load(e)).metadata.get(r)}catch(i){if(i.code!==re.ERR_NOT_FOUND)throw i}finally{rt.trace("getValue release write lock"),n()}}async set(e,r){if(e=Qe(e),!(r instanceof Map))throw rt.error("valid metadata must be provided to store data"),(0,Oh.default)(new Error("valid metadata must be provided"),re.ERR_INVALID_PARAMETERS);rt.trace("set await write lock");let n=await this.store.lock.writeLock();rt.trace("set got write lock");let i;try{try{i=await this.store.load(e)}catch(s){if(s.code!==re.ERR_NOT_FOUND)throw s}await this.store.mergeOrCreate(e,{metadata:r})}finally{rt.trace("set release write lock"),n()}this.dispatchEvent(new Z(jc,{detail:{peerId:e,metadata:r,oldMetadata:i==null?new Map:i.metadata}}))}async setValue(e,r,n){if(e=Qe(e),typeof r!="string"||!(n instanceof Uint8Array))throw rt.error("valid key and value must be provided to store data"),(0,Oh.default)(new Error("valid key and value must be provided"),re.ERR_INVALID_PARAMETERS);rt.trace("setValue await write lock");let i=await this.store.lock.writeLock();rt.trace("setValue got write lock");let s,o;try{try{s=await this.store.load(e);let a=s.metadata.get(r);if(a!=null&&_e(n,a))return}catch(a){if(a.code!==re.ERR_NOT_FOUND)throw a}o=await this.store.mergeOrCreate(e,{metadata:new Map([[r,n]])})}finally{rt.trace("setValue release write lock"),i()}this.dispatchEvent(new Z(jc,{detail:{peerId:e,metadata:o.metadata,oldMetadata:s==null?new Map:s.metadata}}))}async delete(e){e=Qe(e),rt.trace("delete await write lock");let r=await this.store.lock.writeLock();rt.trace("delete got write lock");let n;try{try{n=await this.store.load(e)}catch(i){if(i.code!==re.ERR_NOT_FOUND)throw i}n!=null&&await this.store.patch(e,{metadata:new Map})}finally{rt.trace("delete release write lock"),r()}n!=null&&this.dispatchEvent(new Z(jc,{detail:{peerId:e,metadata:new Map,oldMetadata:n.metadata}}))}async deleteValue(e,r){e=Qe(e),rt.trace("deleteValue await write lock");let n=await this.store.lock.writeLock();rt.trace("deleteValue got write lock");let i,s;try{s=await this.store.load(e),i=s.metadata,i.delete(r),await this.store.patch(e,{metadata:i})}catch(o){if(o.code!==re.ERR_NOT_FOUND)throw o}finally{rt.trace("deleteValue release write lock"),n()}i!=null&&this.dispatchEvent(new Z(jc,{detail:{peerId:e,metadata:i,oldMetadata:s==null?new Map:s.metadata}}))}};var eu=C(G(),1);var nt=M("libp2p:peer-store:proto-book"),Jc="change:protocols",tu=class{constructor(e,r){this.dispatchEvent=e,this.store=r}async get(e){nt.trace("get wait for read lock");let r=await this.store.lock.readLock();nt.trace("get got read lock");try{return(await this.store.load(e)).protocols}catch(n){if(n.code!==re.ERR_NOT_FOUND)throw n}finally{nt.trace("get release read lock"),r()}return[]}async set(e,r){if(e=Qe(e),!Array.isArray(r))throw nt.error("protocols must be provided to store data"),(0,eu.default)(new Error("protocols must be provided"),re.ERR_INVALID_PARAMETERS);nt.trace("set await write lock");let n=await this.store.lock.writeLock();nt.trace("set got write lock");let i,s;try{try{if(i=await this.store.load(e),new Set([...r]).size===i.protocols.length)return}catch(o){if(o.code!==re.ERR_NOT_FOUND)throw o}s=await this.store.patchOrCreate(e,{protocols:r}),nt("stored provided protocols for %p",e)}finally{nt.trace("set release write lock"),n()}this.dispatchEvent(new Z(Jc,{detail:{peerId:e,protocols:s.protocols,oldProtocols:i==null?[]:i.protocols}}))}async add(e,r){if(e=Qe(e),!Array.isArray(r))throw nt.error("protocols must be provided to store data"),(0,eu.default)(new Error("protocols must be provided"),re.ERR_INVALID_PARAMETERS);nt.trace("add await write lock");let n=await this.store.lock.writeLock();nt.trace("add got write lock");let i,s;try{try{if(i=await this.store.load(e),new Set([...i.protocols,...r]).size===i.protocols.length)return}catch(o){if(o.code!==re.ERR_NOT_FOUND)throw o}s=await this.store.mergeOrCreate(e,{protocols:r}),nt("added provided protocols for %p",e)}finally{nt.trace("add release write lock"),n()}this.dispatchEvent(new Z(Jc,{detail:{peerId:e,protocols:s.protocols,oldProtocols:i==null?[]:i.protocols}}))}async remove(e,r){if(e=Qe(e),!Array.isArray(r))throw nt.error("protocols must be provided to store data"),(0,eu.default)(new Error("protocols must be provided"),re.ERR_INVALID_PARAMETERS);nt.trace("remove await write lock");let n=await this.store.lock.writeLock();nt.trace("remove got write lock");let i,s;try{try{i=await this.store.load(e);let o=new Set(i.protocols);for(let a of r)o.delete(a);if(i.protocols.length===o.size)return;r=Array.from(o)}catch(o){if(o.code!==re.ERR_NOT_FOUND)throw o}s=await this.store.patchOrCreate(e,{protocols:r})}finally{nt.trace("remove release write lock"),n()}this.dispatchEvent(new Z(Jc,{detail:{peerId:e,protocols:s.protocols,oldProtocols:i==null?[]:i.protocols}}))}async delete(e){e=Qe(e),nt.trace("delete await write lock");let r=await this.store.lock.writeLock();nt.trace("delete got write lock");let n;try{try{n=await this.store.load(e)}catch(i){if(i.code!==re.ERR_NOT_FOUND)throw i}await this.store.patchOrCreate(e,{protocols:[]})}finally{nt.trace("delete release write lock"),r()}n!=null&&this.dispatchEvent(new Z(Jc,{detail:{peerId:e,protocols:[],oldProtocols:n.protocols}}))}};var td=C(G(),1);var Ko;(function(t){let e;t.codec=()=>(e==null&&(e=Ne((r,n,i={})=>{if(i.lengthDelimited!==!1&&n.fork(),r.addresses!=null)for(let s of r.addresses)n.uint32(10),ru.codec().encode(s,n,{writeDefaults:!0});if(r.protocols!=null)for(let s of r.protocols)n.uint32(18),n.string(s);if(r.metadata!=null)for(let s of r.metadata)n.uint32(26),nu.codec().encode(s,n,{writeDefaults:!0});r.pubKey!=null&&(n.uint32(34),n.bytes(r.pubKey)),r.peerRecordEnvelope!=null&&(n.uint32(42),n.bytes(r.peerRecordEnvelope)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={addresses:[],protocols:[],metadata:[]},s=n==null?r.len:r.pos+n;for(;r.pos<s;){let o=r.uint32();switch(o>>>3){case 1:i.addresses.push(ru.codec().decode(r,r.uint32()));break;case 2:i.protocols.push(r.string());break;case 3:i.metadata.push(nu.codec().decode(r,r.uint32()));break;case 4:i.pubKey=r.bytes();break;case 5:i.peerRecordEnvelope=r.bytes();break;default:r.skipType(o&7);break}}return i})),e),t.encode=r=>Re(r,t.codec()),t.decode=r=>Te(r,t.codec())})(Ko||(Ko={}));var ru;(function(t){let e;t.codec=()=>(e==null&&(e=Ne((r,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),(i.writeDefaults===!0||r.multiaddr!=null&&r.multiaddr.byteLength>0)&&(n.uint32(10),n.bytes(r.multiaddr)),r.isCertified!=null&&(n.uint32(16),n.bool(r.isCertified)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={multiaddr:new Uint8Array(0)},s=n==null?r.len:r.pos+n;for(;r.pos<s;){let o=r.uint32();switch(o>>>3){case 1:i.multiaddr=r.bytes();break;case 2:i.isCertified=r.bool();break;default:r.skipType(o&7);break}}return i})),e),t.encode=r=>Re(r,t.codec()),t.decode=r=>Te(r,t.codec())})(ru||(ru={}));var nu;(function(t){let e;t.codec=()=>(e==null&&(e=Ne((r,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),(i.writeDefaults===!0||r.key!=="")&&(n.uint32(10),n.string(r.key)),(i.writeDefaults===!0||r.value!=null&&r.value.byteLength>0)&&(n.uint32(18),n.bytes(r.value)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={key:"",value:new Uint8Array(0)},s=n==null?r.len:r.pos+n;for(;r.pos<s;){let o=r.uint32();switch(o>>>3){case 1:i.key=r.string();break;case 2:i.value=r.bytes();break;default:r.skipType(o&7);break}}return i})),e),t.encode=r=>Re(r,t.codec()),t.decode=r=>Te(r,t.codec())})(nu||(nu={}));var Rw=C(ww(),1);var qo=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Uh=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},xw=t=>globalThis.DOMException===void 0?new Uh(t):new DOMException(t),bw=t=>{let e=t.reason===void 0?xw("This operation was aborted."):t.reason;return e instanceof Error?e:xw(e)};function Mh(t,e,r,n){let i,s=new Promise((o,a)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(e===Number.POSITIVE_INFINITY){o(t);return}if(n={customTimers:{setTimeout,clearTimeout},...n},n.signal){let{signal:c}=n;c.aborted&&a(bw(c)),c.addEventListener("abort",()=>{a(bw(c))})}i=n.customTimers.setTimeout.call(void 0,()=>{if(typeof r=="function"){try{o(r())}catch(l){a(l)}return}let c=typeof r=="string"?r:`Promise timed out after ${e} milliseconds`,u=r instanceof Error?r:new qo(c);typeof t.cancel=="function"&&t.cancel(),a(u)},e),(async()=>{try{o(await t)}catch(c){a(c)}finally{n.customTimers.clearTimeout.call(void 0,i)}})()});return s.clear=()=>{clearTimeout(i),i=void 0},s}function Fh(t,e,r){let n=0,i=t.length;for(;i>0;){let s=Math.trunc(i/2),o=n+s;r(t[o],e)<=0?(n=++o,i-=s+1):i=s}return n}var Si=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},on,Ho=class{constructor(){on.set(this,[])}enqueue(e,r){r={priority:0,...r};let n={priority:r.priority,run:e};if(this.size&&Si(this,on,"f")[this.size-1].priority>=r.priority){Si(this,on,"f").push(n);return}let i=Fh(Si(this,on,"f"),n,(s,o)=>o.priority-s.priority);Si(this,on,"f").splice(i,0,n)}dequeue(){let e=Si(this,on,"f").shift();return e?.run}filter(e){return Si(this,on,"f").filter(r=>r.priority===e.priority).map(r=>r.run)}get size(){return Si(this,on,"f").length}};on=new WeakMap;var He=function(t,e,r,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(t,r):i?i.value=r:e.set(t,r),r},V=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},Ze,$o,Go,kn,lu,Yo,su,ar,zo,kt,ou,Ut,Wo,On,au,Sw,_w,Tw,Aw,Cw,Iw,cu,Kh,Vh,fu,uu,XI=new qo,qh=class extends Error{},Cs=class extends Rw.default{constructor(e){var r,n,i,s;if(super(),Ze.add(this),$o.set(this,void 0),Go.set(this,void 0),kn.set(this,0),lu.set(this,void 0),Yo.set(this,void 0),su.set(this,0),ar.set(this,void 0),zo.set(this,void 0),kt.set(this,void 0),ou.set(this,void 0),Ut.set(this,0),Wo.set(this,void 0),On.set(this,void 0),au.set(this,void 0),Object.defineProperty(this,"timeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:Ho,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(n=(r=e.intervalCap)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(s=(i=e.interval)===null||i===void 0?void 0:i.toString())!==null&&s!==void 0?s:""}\` (${typeof e.interval})`);He(this,$o,e.carryoverConcurrencyCount,"f"),He(this,Go,e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,"f"),He(this,lu,e.intervalCap,"f"),He(this,Yo,e.interval,"f"),He(this,kt,new e.queueClass,"f"),He(this,ou,e.queueClass,"f"),this.concurrency=e.concurrency,this.timeout=e.timeout,He(this,au,e.throwOnTimeout===!0,"f"),He(this,On,e.autoStart===!1,"f")}get concurrency(){return V(this,Wo,"f")}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);He(this,Wo,e,"f"),V(this,Ze,"m",fu).call(this)}async add(e,r={}){return new Promise((n,i)=>{let s=async()=>{var o,a,c;He(this,Ut,(a=V(this,Ut,"f"),a++,a),"f"),He(this,kn,(c=V(this,kn,"f"),c++,c),"f");try{if(!((o=r.signal)===null||o===void 0)&&o.aborted){i(new qh("The task was aborted."));return}let l=await(this.timeout===void 0&&r.timeout===void 0?e({signal:r.signal}):Mh(Promise.resolve(e({signal:r.signal})),r.timeout===void 0?this.timeout:r.timeout,()=>{(r.throwOnTimeout===void 0?V(this,au,"f"):r.throwOnTimeout)&&i(XI)}));n(l),this.emit("completed",l)}catch(u){i(u),this.emit("error",u)}V(this,Ze,"m",Tw).call(this)};V(this,kt,"f").enqueue(s,r),V(this,Ze,"m",cu).call(this),this.emit("add")})}async addAll(e,r){return Promise.all(e.map(async n=>this.add(n,r)))}start(){return V(this,On,"f")?(He(this,On,!1,"f"),V(this,Ze,"m",fu).call(this),this):this}pause(){He(this,On,!0,"f")}clear(){He(this,kt,new(V(this,ou,"f")),"f")}async onEmpty(){V(this,kt,"f").size!==0&&await V(this,Ze,"m",uu).call(this,"empty")}async onSizeLessThan(e){V(this,kt,"f").size<e||await V(this,Ze,"m",uu).call(this,"next",()=>V(this,kt,"f").size<e)}async onIdle(){V(this,Ut,"f")===0&&V(this,kt,"f").size===0||await V(this,Ze,"m",uu).call(this,"idle")}get size(){return V(this,kt,"f").size}sizeBy(e){return V(this,kt,"f").filter(e).length}get pending(){return V(this,Ut,"f")}get isPaused(){return V(this,On,"f")}};$o=new WeakMap,Go=new WeakMap,kn=new WeakMap,lu=new WeakMap,Yo=new WeakMap,su=new WeakMap,ar=new WeakMap,zo=new WeakMap,kt=new WeakMap,ou=new WeakMap,Ut=new WeakMap,Wo=new WeakMap,On=new WeakMap,au=new WeakMap,Ze=new WeakSet,Sw=function(){return V(this,Go,"f")||V(this,kn,"f")<V(this,lu,"f")},_w=function(){return V(this,Ut,"f")<V(this,Wo,"f")},Tw=function(){var e;He(this,Ut,(e=V(this,Ut,"f"),e--,e),"f"),V(this,Ze,"m",cu).call(this),this.emit("next")},Aw=function(){this.emit("empty"),V(this,Ut,"f")===0&&this.emit("idle")},Cw=function(){V(this,Ze,"m",Vh).call(this),V(this,Ze,"m",Kh).call(this),He(this,zo,void 0,"f")},Iw=function(){let e=Date.now();if(V(this,ar,"f")===void 0){let r=V(this,su,"f")-e;if(r<0)He(this,kn,V(this,$o,"f")?V(this,Ut,"f"):0,"f");else return V(this,zo,"f")===void 0&&He(this,zo,setTimeout(()=>{V(this,Ze,"m",Cw).call(this)},r),"f"),!0}return!1},cu=function(){if(V(this,kt,"f").size===0)return V(this,ar,"f")&&clearInterval(V(this,ar,"f")),He(this,ar,void 0,"f"),V(this,Ze,"m",Aw).call(this),!1;if(!V(this,On,"f")){let e=!V(this,Ze,"a",Iw);if(V(this,Ze,"a",Sw)&&V(this,Ze,"a",_w)){let r=V(this,kt,"f").dequeue();return r?(this.emit("active"),r(),e&&V(this,Ze,"m",Kh).call(this),!0):!1}}return!1},Kh=function(){V(this,Go,"f")||V(this,ar,"f")!==void 0||(He(this,ar,setInterval(()=>{V(this,Ze,"m",Vh).call(this)},V(this,Yo,"f")),"f"),He(this,su,Date.now()+V(this,Yo,"f"),"f"))},Vh=function(){V(this,kn,"f")===0&&V(this,Ut,"f")===0&&V(this,ar,"f")&&(clearInterval(V(this,ar,"f")),He(this,ar,void 0,"f")),He(this,kn,V(this,$o,"f")?V(this,Ut,"f"):0,"f"),V(this,Ze,"m",fu).call(this)},fu=function(){for(;V(this,Ze,"m",cu).call(this););},uu=async function(e,r){return new Promise(n=>{let i=()=>{r&&!r()||(this.off(e,i),n())};this.on(e,i)})};var Hh=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},zh=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},Nw=t=>globalThis.DOMException===void 0?new zh(t):new DOMException(t),Dw=t=>{let e=t.reason===void 0?Nw("This operation was aborted."):t.reason;return e instanceof Error?e:Nw(e)};function $h(t,e){let{milliseconds:r,fallback:n,message:i,customTimers:s={setTimeout,clearTimeout}}=e,o,a=new Promise((c,u)=>{if(typeof r!="number"||Math.sign(r)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(r===Number.POSITIVE_INFINITY){c(t);return}if(e.signal){let{signal:l}=e;l.aborted&&u(Dw(l)),l.addEventListener("abort",()=>{u(Dw(l))})}o=s.setTimeout.call(void 0,()=>{if(n){try{c(n())}catch(h){u(h)}return}let l=typeof i=="string"?i:`Promise timed out after ${r} milliseconds`,f=i instanceof Error?i:new Hh(l);typeof t.cancel=="function"&&t.cancel(),u(f)},r),(async()=>{try{c(await t)}catch(l){u(l)}finally{s.clearTimeout.call(void 0,o)}})()});return a.clear=()=>{s.clearTimeout.call(void 0,o),o=void 0},a}var Gh="lock:worker:request-read",Yh="lock:worker:release-read",Wh="lock:master:grant-read",Qh="lock:worker:request-write",Xh="lock:worker:release-write",jh="lock:master:grant-write";var Un={},Is=t=>{t.addEventListener("message",e=>{Is.dispatchEvent("message",t,e)}),t.port!=null&&t.port.addEventListener("message",e=>{Is.dispatchEvent("message",t,e)})};Is.addEventListener=(t,e)=>{Un[t]==null&&(Un[t]=[]),Un[t].push(e)};Is.removeEventListener=(t,e)=>{Un[t]!=null&&(Un[t]=Un[t].filter(r=>r===e))};Is.dispatchEvent=function(t,e,r){Un[t]!=null&&Un[t].forEach(n=>n(e,r))};var Zh=Is;var Lw=(t,e,r,n,i)=>(s,o)=>{if(o.data.type!==r)return;let a={type:o.data.type,name:o.data.name,identifier:o.data.identifier};t.dispatchEvent(new MessageEvent(e,{data:{name:a.name,handler:async()=>(s.postMessage({type:i,name:a.name,identifier:a.identifier}),await new Promise(c=>{let u=l=>{if(l==null||l.data==null)return;let f={type:l.data.type,name:l.data.name,identifier:l.data.identifier};f.type===n&&f.identifier===a.identifier&&(s.removeEventListener("message",u),c())};s.addEventListener("message",u)}))}}))},Pw=(t,e,r,n)=>async()=>{let i=ra();return globalThis.postMessage({type:e,identifier:i,name:t}),await new Promise(s=>{let o=a=>{if(a==null||a.data==null)return;let c={type:a.data.type,identifier:a.data.identifier};c.type===r&&c.identifier===i&&(globalThis.removeEventListener("message",o),s(()=>{globalThis.postMessage({type:n,identifier:i,name:t})}))};globalThis.addEventListener("message",o)})},jI={singleProcess:!1},Bw=t=>{if(t=Object.assign({},jI,t),Boolean(globalThis.document)||t.singleProcess){let r=new EventTarget;return Zh.addEventListener("message",Lw(r,"requestReadLock",Gh,Yh,Wh)),Zh.addEventListener("message",Lw(r,"requestWriteLock",Qh,Xh,jh)),r}return{isWorker:!0,readLock:r=>Pw(r,Gh,Wh,Yh),writeLock:r=>Pw(r,Qh,jh,Xh)}};var _i={},Mn;async function Jh(t,e){let r,n=new Promise(i=>{r=i});return t.add(async()=>await $h((async()=>await new Promise(i=>{r(()=>{i()})}))(),{milliseconds:e.timeout})),await n}var ZI=(t,e)=>{if(Mn.isWorker===!0)return{readLock:Mn.readLock(t,e),writeLock:Mn.writeLock(t,e)};let r=new Cs({concurrency:1}),n;return{async readLock(){if(n!=null)return await Jh(n,e);n=new Cs({concurrency:e.concurrency,autoStart:!1});let i=n,s=Jh(n,e);return r.add(async()=>(i.start(),await i.onIdle().then(()=>{n===i&&(n=null)}))),await s},async writeLock(){return n=null,await Jh(r,e)}}},JI={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function ed(t){let e=Object.assign({},JI,t);return Mn==null&&(Mn=Bw(e),Mn.isWorker!==!0&&(Mn.addEventListener("requestReadLock",r=>{_i[r.data.name]!=null&&_i[r.data.name].readLock().then(async n=>await r.data.handler().finally(()=>n()))}),Mn.addEventListener("requestWriteLock",async r=>{_i[r.data.name]!=null&&_i[r.data.name].writeLock().then(async n=>await r.data.handler().finally(()=>n()))}))),_i[e.name]==null&&(_i[e.name]=ZI(e.name,e)),_i[e.name]}var Ow=M("libp2p:peer-store:store"),kw="/peers/",hu=class{constructor(e){this.components=e,this.lock=ed({name:"peer-store",singleProcess:!0})}_peerIdToDatastoreKey(e){if(e.type==null)throw Ow.error("peerId must be an instance of peer-id to store data"),(0,td.default)(new Error("peerId must be an instance of peer-id"),re.ERR_INVALID_PARAMETERS);let r=e.toCID().toString();return new $e(`${kw}${r}`)}async has(e){return await this.components.datastore.has(this._peerIdToDatastoreKey(e))}async delete(e){await this.components.datastore.delete(this._peerIdToDatastoreKey(e))}async load(e){let r=await this.components.datastore.get(this._peerIdToDatastoreKey(e)),n=Ko.decode(r),i=new Map;for(let s of n.metadata)i.set(s.key,s.value);return{...n,id:e,addresses:n.addresses.map(({multiaddr:s,isCertified:o})=>({multiaddr:oe(s),isCertified:o??!1})),metadata:i,pubKey:n.pubKey??void 0,peerRecordEnvelope:n.peerRecordEnvelope??void 0}}async save(e){if(e.pubKey!=null&&e.id.publicKey!=null&&!_e(e.pubKey,e.id.publicKey))throw Ow.error("peer publicKey bytes do not match peer id publicKey bytes"),(0,td.default)(new Error("publicKey bytes do not match peer id publicKey bytes"),re.ERR_INVALID_PARAMETERS);let r=new Set,n=e.addresses.filter(o=>r.has(o.multiaddr.toString())?!1:(r.add(o.multiaddr.toString()),!0)).sort((o,a)=>o.multiaddr.toString().localeCompare(a.multiaddr.toString())).map(({multiaddr:o,isCertified:a})=>({multiaddr:o.bytes,isCertified:a})),i=[];[...e.metadata.keys()].sort().forEach(o=>{let a=e.metadata.get(o);a!=null&&i.push({key:o,value:a})});let s=Ko.encode({addresses:n,protocols:e.protocols.sort(),pubKey:e.pubKey,metadata:i,peerRecordEnvelope:e.peerRecordEnvelope});return await this.components.datastore.put(this._peerIdToDatastoreKey(e.id),s.subarray()),await this.load(e.id)}async patch(e,r){let n=await this.load(e);return await this._patch(e,r,n)}async patchOrCreate(e,r){let n;try{n=await this.load(e)}catch(i){if(i.code!==re.ERR_NOT_FOUND)throw i;n={id:e,addresses:[],protocols:[],metadata:new Map}}return await this._patch(e,r,n)}async _patch(e,r,n){return await this.save({...n,...r,id:e})}async merge(e,r){let n=await this.load(e);return await this._merge(e,r,n)}async mergeOrCreate(e,r){let n;try{n=await this.load(e)}catch(i){if(i.code!==re.ERR_NOT_FOUND)throw i;n={id:e,addresses:[],protocols:[],metadata:new Map}}return await this._merge(e,r,n)}async _merge(e,r,n){let i=new Map;return n.addresses.forEach(s=>{i.set(s.multiaddr.toString(),s.isCertified)}),(r.addresses??[]).forEach(s=>{let o=s.multiaddr.toString(),c=Boolean(i.get(o))||s.isCertified;i.set(o,c)}),await this.save({id:e,addresses:Array.from(i.entries()).map(([s,o])=>({multiaddr:oe(s),isCertified:o})),protocols:Array.from(new Set([...n.protocols??[],...r.protocols??[]])),metadata:new Map([...n.metadata?.entries()??[],...r.metadata?.entries()??[]]),pubKey:r.pubKey??n?.pubKey,peerRecordEnvelope:r.peerRecordEnvelope??n?.peerRecordEnvelope})}async*all(){for await(let e of this.components.datastore.queryKeys({prefix:kw})){let r=e.toString().split("/")[2],n=Tt.decode(r);yield this.load(mn(n))}}};var rd=C(G(),1);var an;(function(t){let e;t.codec=()=>(e==null&&(e=Ne((r,n,i={})=>{if(i.lengthDelimited!==!1&&n.fork(),r.tags!=null)for(let s of r.tags)n.uint32(10),du.codec().encode(s,n,{writeDefaults:!0});i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={tags:[]},s=n==null?r.len:r.pos+n;for(;r.pos<s;){let o=r.uint32();switch(o>>>3){case 1:i.tags.push(du.codec().decode(r,r.uint32()));break;default:r.skipType(o&7);break}}return i})),e),t.encode=r=>Re(r,t.codec()),t.decode=r=>Te(r,t.codec())})(an||(an={}));var du;(function(t){let e;t.codec=()=>(e==null&&(e=Ne((r,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),(i.writeDefaults===!0||r.name!=="")&&(n.uint32(10),n.string(r.name)),r.value!=null&&(n.uint32(16),n.uint32(r.value)),r.expiry!=null&&(n.uint32(24),n.uint64(r.expiry)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={name:""},s=n==null?r.len:r.pos+n;for(;r.pos<s;){let o=r.uint32();switch(o>>>3){case 1:i.name=r.string();break;case 2:i.value=r.uint32();break;case 3:i.expiry=r.uint64();break;default:r.skipType(o&7);break}}return i})),e),t.encode=r=>Re(r,t.codec()),t.decode=r=>Te(r,t.codec())})(du||(du={}));var Qt=M("libp2p:peer-store"),pu=class extends Ue{constructor(e,r={}){super(),this.components=e,this.store=new hu(e),this.addressBook=new Qc(this.dispatchEvent.bind(this),this.store,r.addressFilter),this.keyBook=new Xc(this.dispatchEvent.bind(this),this.store),this.metadataBook=new Zc(this.dispatchEvent.bind(this),this.store),this.protoBook=new tu(this.dispatchEvent.bind(this),this.store)}async forEach(e){Qt.trace("getPeers await read lock");let r=await this.store.lock.readLock();Qt.trace("getPeers got read lock");try{for await(let n of this.store.all())n.id.equals(this.components.peerId)||e(n)}finally{Qt.trace("getPeers release read lock"),r()}}async all(){let e=[];return await this.forEach(r=>{e.push(r)}),e}async delete(e){Qt.trace("delete await write lock");let r=await this.store.lock.writeLock();Qt.trace("delete got write lock");try{await this.store.delete(e)}finally{Qt.trace("delete release write lock"),r()}}async get(e){Qt.trace("get await read lock");let r=await this.store.lock.readLock();Qt.trace("get got read lock");try{return await this.store.load(e)}finally{Qt.trace("get release read lock"),r()}}async has(e){Qt.trace("has await read lock");let r=await this.store.lock.readLock();Qt.trace("has got read lock");try{return await this.store.has(e)}finally{Qt.trace("has release read lock"),r()}}async tagPeer(e,r,n={}){let i=n.value??0,s=Math.round(i),o=n.ttl??void 0;if(s!==i||s<0||s>100)throw(0,rd.default)(new Error("Tag value must be between 0-100"),"ERR_TAG_VALUE_OUT_OF_BOUNDS");let a=await this.metadataBook.getValue(e,"tags"),c=[];a!=null&&(c=an.decode(a).tags);for(let u of c)if(u.name===r)throw(0,rd.default)(new Error("Peer already tagged"),"ERR_DUPLICATE_TAG");c.push({name:r,value:s,expiry:o==null?void 0:BigInt(Date.now()+o)}),await this.metadataBook.setValue(e,"tags",an.encode({tags:c}).subarray())}async unTagPeer(e,r){let n=await this.metadataBook.getValue(e,"tags"),i=[];n!=null&&(i=an.decode(n).tags),i=i.filter(s=>s.name!==r),await this.metadataBook.setValue(e,"tags",an.encode({tags:i}).subarray())}async getTags(e){let r=await this.metadataBook.getValue(e,"tags"),n=[];r!=null&&(n=an.decode(r).tags);let i=BigInt(Date.now()),s=n.filter(o=>o.expiry==null||o.expiry>i);return s.length!==n.length&&await this.metadataBook.setValue(e,"tags",an.encode({tags:s}).subarray()),s.map(o=>({name:o.name,value:o.value??0}))}};var Uw=C(G(),1),mu=class{constructor(e){this.dht=e}async provide(e){await dn(this.dht.provide(e))}async*findProviders(e,r={}){for await(let n of this.dht.findProviders(e,r))n.name==="PROVIDER"&&(yield*n.providers)}async put(e,r,n){await dn(this.dht.put(e,r,n))}async get(e,r){for await(let n of this.dht.get(e,r))if(n.name==="VALUE")return n.value;throw(0,Uw.default)(new Error("Not found"),"ERR_NOT_FOUND")}};var Mt=C(G(),1);var yu=class{constructor(e={}){this._started=!1,this._peerId=e.peerId,this._addressManager=e.addressManager,this._peerStore=e.peerStore,this._upgrader=e.upgrader,this._metrics=e.metrics,this._registrar=e.registrar,this._connectionManager=e.connectionManager,this._transportManager=e.transportManager,this._connectionGater=e.connectionGater,this._contentRouting=e.contentRouting,this._peerRouting=e.peerRouting,this._datastore=e.datastore,this._connectionProtector=e.connectionProtector,this._dht=e.dht,this._pubsub=e.pubsub,this._dialer=e.dialer}isStarted(){return this._started}async beforeStart(){await Promise.all(Object.values(this).filter(e=>Lr(e)).map(async e=>{e.beforeStart!=null&&await e.beforeStart()}))}async start(){await Promise.all(Object.values(this).filter(e=>Lr(e)).map(async e=>{await e.start()})),this._started=!0}async afterStart(){await Promise.all(Object.values(this).filter(e=>Lr(e)).map(async e=>{e.afterStart!=null&&await e.afterStart()}))}async beforeStop(){await Promise.all(Object.values(this).filter(e=>Lr(e)).map(async e=>{e.beforeStop!=null&&await e.beforeStop()}))}async stop(){await Promise.all(Object.values(this).filter(e=>Lr(e)).map(async e=>{await e.stop()})),this._started=!1}async afterStop(){await Promise.all(Object.values(this).filter(e=>Lr(e)).map(async e=>{e.afterStop!=null&&await e.afterStop()}))}get peerId(){if(this._peerId==null)throw(0,Mt.default)(new Error("peerId not set"),"ERR_SERVICE_MISSING");return this._peerId}set peerId(e){this._peerId=e}get addressManager(){if(this._addressManager==null)throw(0,Mt.default)(new Error("addressManager not set"),"ERR_SERVICE_MISSING");return this._addressManager}set addressManager(e){this._addressManager=e}get peerStore(){if(this._peerStore==null)throw(0,Mt.default)(new Error("peerStore not set"),"ERR_SERVICE_MISSING");return this._peerStore}set peerStore(e){this._peerStore=e}get upgrader(){if(this._upgrader==null)throw(0,Mt.default)(new Error("upgrader not set"),"ERR_SERVICE_MISSING");return this._upgrader}set upgrader(e){this._upgrader=e}get registrar(){if(this._registrar==null)throw(0,Mt.default)(new Error("registrar not set"),"ERR_SERVICE_MISSING");return this._registrar}set registrar(e){this._registrar=e}get connectionManager(){if(this._connectionManager==null)throw(0,Mt.default)(new Error("connectionManager not set"),"ERR_SERVICE_MISSING");return this._connectionManager}set connectionManager(e){this._connectionManager=e}get transportManager(){if(this._transportManager==null)throw(0,Mt.default)(new Error("transportManager not set"),"ERR_SERVICE_MISSING");return this._transportManager}set transportManager(e){this._transportManager=e}get connectionGater(){if(this._connectionGater==null)throw(0,Mt.default)(new Error("connectionGater not set"),"ERR_SERVICE_MISSING");return this._connectionGater}set connectionGater(e){this._connectionGater=e}get contentRouting(){if(this._contentRouting==null)throw(0,Mt.default)(new Error("contentRouting not set"),"ERR_SERVICE_MISSING");return this._contentRouting}set contentRouting(e){this._contentRouting=e}get peerRouting(){if(this._peerRouting==null)throw(0,Mt.default)(new Error("peerRouting not set"),"ERR_SERVICE_MISSING");return this._peerRouting}set peerRouting(e){this._peerRouting=e}get datastore(){if(this._datastore==null)throw(0,Mt.default)(new Error("datastore not set"),"ERR_SERVICE_MISSING");return this._datastore}set datastore(e){this._datastore=e}get connectionProtector(){return this._connectionProtector}set connectionProtector(e){this._connectionProtector=e}get dialer(){if(this._dialer==null)throw(0,Mt.default)(new Error("dialer not set"),"ERR_SERVICE_MISSING");return this._dialer}set dialer(e){this._dialer=e}get metrics(){return this._metrics}set metrics(e){this._metrics=e}get dht(){return this._dht}set dht(e){this._dht=e}get pubsub(){return this._pubsub}set pubsub(e){this._pubsub=e}};var id=C(Tu(),1),sd=C(Kw(),1);var Vw=globalThis.fetch,qw=globalThis.Headers,uU=globalThis.Request,lU=globalThis.Response;function gu(t,e,r){return`${t}?name=${e}&type=${r}`}async function Hw(t,e){return await(await Vw(t,{headers:new qw({accept:"application/dns-json"}),signal:e})).json()}function Ai(t,e){return`${e}_${t}`}var nd=Object.assign((0,id.default)("dns-over-http-resolver"),{error:(0,id.default)("dns-over-http-resolver:error")}),od=class{constructor(e={}){this._cache=new sd.default({max:e?.maxCache??100}),this._TXTcache=new sd.default({max:e?.maxCache??100}),this._servers=["https://cloudflare-dns.com/dns-query","https://dns.google/resolve"],this._request=e.request??Hw,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(Ai(e,r));if(n!=null)return n;let i=!1;for(let s of this._getShuffledServers()){let o=new AbortController;this._abortControllers.push(o);try{let a=await this._request(gu(s,e,r),o.signal),c=a.Answer.map(l=>l.data),u=Math.min(...a.Answer.map(l=>l.TTL));return this._cache.set(Ai(e,r),c,{ttl:u}),c}catch{o.signal.aborted&&(i=!0),nd.error(`${s} could not resolve ${e} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==o)}}throw i?Object.assign(new Error("queryA ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${r}`)}async resolve6(e){let r="AAAA",n=this._cache.get(Ai(e,r));if(n!=null)return n;let i=!1;for(let s of this._getShuffledServers()){let o=new AbortController;this._abortControllers.push(o);try{let a=await this._request(gu(s,e,r),o.signal),c=a.Answer.map(l=>l.data),u=Math.min(...a.Answer.map(l=>l.TTL));return this._cache.set(Ai(e,r),c,{ttl:u}),c}catch{o.signal.aborted&&(i=!0),nd.error(`${s} could not resolve ${e} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==o)}}throw i?Object.assign(new Error("queryAaaa ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${r}`)}async resolveTxt(e){let r="TXT",n=this._TXTcache.get(Ai(e,r));if(n!=null)return n;let i=!1;for(let s of this._getShuffledServers()){let o=new AbortController;this._abortControllers.push(o);try{let a=await this._request(gu(s,e,r),o.signal),c=a.Answer.map(l=>[l.data.replace(/['"]+/g,"")]),u=Math.min(...a.Answer.map(l=>l.TTL));return this._TXTcache.set(Ai(e,r),c,{ttl:u}),c}catch{o.signal.aborted&&(i=!0),nd.error(`${s} could not resolve ${e} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==o)}}throw i?Object.assign(new Error("queryTxt ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${r}`)}clearCache(){this._cache.clear(),this._TXTcache.clear()}},zw=od;var $w=zw;var{code:iT}=Ie("dnsaddr");async function Gw(t,e={}){let r=new $w;e.signal!=null&&e.signal.addEventListener("abort",()=>{r.cancel()});let n=t.getPeerId(),[,i]=t.stringTuples().find(([a])=>a===iT)??[];if(i==null)throw new Error("No hostname found in multiaddr");let o=(await r.resolveTxt(`_dnsaddr.${i}`)).flat().map(a=>a.split("=")[1]);return n!=null&&(o=o.filter(a=>a.includes(n))),o}var Eu=C(G(),1);var uT={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:t=>t},connectionManager:{maxConnections:300,minConnections:50,autoDial:!0,autoDialInterval:1e4,maxParallelDials:100,maxDialsPerPeer:4,dialTimeout:3e4,inboundUpgradeTimeout:3e4,resolvers:{dnsaddr:Gw},addressSorter:Ji,maxEventLoopDelay:1/0,pollInterval:1/0,maxAddrsToDial:1/0,startupReconnectTimeout:1/0,allow:[],deny:[],maxIncomingPendingConnections:1/0,inboundConnectionThreshold:1/0},connectionGater:{},transportManager:{faultTolerance:vi.FATAL_ALL},peerRouting:{refreshManager:{enabled:!0,interval:6e5,bootDelay:1e4},routers:[]},nat:{enabled:!0,ttl:7200,keepAlive:!0},relay:{enabled:!0,advertise:{bootDelay:9e5,enabled:!1,ttl:18e5},hop:{enabled:!1,active:!1,timeout:3e4},autoRelay:{enabled:!1,maxListeners:2}},identify:{protocolPrefix:"ipfs",host:{agentVersion:Rh},timeout:6e4,maxInboundStreams:1,maxOutboundStreams:1,maxPushIncomingStreams:1,maxPushOutgoingStreams:1},ping:{protocolPrefix:"ipfs",maxInboundStreams:1,maxOutboundStreams:1,timeout:1e4},fetch:{protocolPrefix:"libp2p",maxInboundStreams:1,maxOutboundStreams:1,timeout:1e4}};function Yw(t){let e=pr(uT,t);if(e.transports==null||e.transports.length<1)throw(0,Eu.default)(new Error(ne.ERR_TRANSPORTS_REQUIRED),b.ERR_TRANSPORTS_REQUIRED);if(e.connectionEncryption==null||e.connectionEncryption.length===0)throw(0,Eu.default)(new Error(ne.CONN_ENCRYPTION_REQUIRED),b.CONN_ENCRYPTION_REQUIRED);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw(0,Eu.default)(new Error(ne.ERR_PROTECTOR_REQUIRED),b.ERR_PROTECTOR_REQUIRED);return e.identify.host.agentVersion===Rh&&(lw||cw?e.identify.host.agentVersion+=` UserAgent=${globalThis.process.version}`:(Fo||fw||uw||hw)&&(e.identify.host.agentVersion+=` UserAgent=${globalThis.navigator.userAgent}`)),e}var ld;(function(t){let e;t.codec=()=>(e==null&&(e=Ne((r,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),(i.writeDefaults===!0||r.id!=null&&r.id.byteLength>0)&&(n.uint32(10),n.bytes(r.id)),r.pubKey!=null&&(n.uint32(18),n.bytes(r.pubKey)),r.privKey!=null&&(n.uint32(26),n.bytes(r.privKey)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={id:new Uint8Array(0)},s=n==null?r.len:r.pos+n;for(;r.pos<s;){let o=r.uint32();switch(o>>>3){case 1:i.id=r.bytes();break;case 2:i.pubKey=r.bytes();break;case 3:i.privKey=r.bytes();break;default:r.skipType(o&7);break}}return i})),e),t.encode=r=>Re(r,t.codec()),t.decode=r=>Te(r,t.codec())})(ld||(ld={}));var Ww=async()=>{let t=await Pc("Ed25519"),e=await lT(t);if(e.type==="Ed25519")return e;throw new Error(`Generated unexpected PeerId type "${e.type}"`)};async function lT(t){return await Ui(vv(t.public),wv(t))}var Xo=C(G(),1);var Xt=C(G(),1);var Qw=Symbol.for("@libp2p/peer-discovery");var vu=class extends Ue{get[Qw](){return!0}get[Symbol.toStringTag](){return"@libp2p/dummy-dht"}get wan(){throw(0,Xt.default)(new Error(ne.DHT_DISABLED),b.DHT_DISABLED)}get lan(){throw(0,Xt.default)(new Error(ne.DHT_DISABLED),b.DHT_DISABLED)}get(){throw(0,Xt.default)(new Error(ne.DHT_DISABLED),b.DHT_DISABLED)}findProviders(){throw(0,Xt.default)(new Error(ne.DHT_DISABLED),b.DHT_DISABLED)}findPeer(){throw(0,Xt.default)(new Error(ne.DHT_DISABLED),b.DHT_DISABLED)}getClosestPeers(){throw(0,Xt.default)(new Error(ne.DHT_DISABLED),b.DHT_DISABLED)}provide(){throw(0,Xt.default)(new Error(ne.DHT_DISABLED),b.DHT_DISABLED)}put(){throw(0,Xt.default)(new Error(ne.DHT_DISABLED),b.DHT_DISABLED)}async getMode(){throw(0,Xt.default)(new Error(ne.DHT_DISABLED),b.DHT_DISABLED)}async setMode(){throw(0,Xt.default)(new Error(ne.DHT_DISABLED),b.DHT_DISABLED)}async refreshRoutingTable(){throw(0,Xt.default)(new Error(ne.DHT_DISABLED),b.DHT_DISABLED)}};var cn=C(G(),1);var wu=class extends Ue{constructor(){super(...arguments),this.topicValidators=new Map}isStarted(){return!1}start(){}stop(){}get globalSignaturePolicy(){throw(0,cn.default)(new Error(ne.PUBSUB_DISABLED),b.ERR_PUBSUB_DISABLED)}get multicodecs(){throw(0,cn.default)(new Error(ne.PUBSUB_DISABLED),b.ERR_PUBSUB_DISABLED)}getPeers(){throw(0,cn.default)(new Error(ne.PUBSUB_DISABLED),b.ERR_PUBSUB_DISABLED)}getTopics(){throw(0,cn.default)(new Error(ne.PUBSUB_DISABLED),b.ERR_PUBSUB_DISABLED)}subscribe(){throw(0,cn.default)(new Error(ne.PUBSUB_DISABLED),b.ERR_PUBSUB_DISABLED)}unsubscribe(){throw(0,cn.default)(new Error(ne.PUBSUB_DISABLED),b.ERR_PUBSUB_DISABLED)}getSubscribers(){throw(0,cn.default)(new Error(ne.PUBSUB_DISABLED),b.ERR_PUBSUB_DISABLED)}async publish(){throw(0,cn.default)(new Error(ne.PUBSUB_DISABLED),b.ERR_PUBSUB_DISABLED)}};var Ts=C(G(),1);var h1=C(Ur(),1),pd=C(hd(),1),d1=C(fr(),1);var Qo=C(G(),1),u1=C(hd(),1),l1=C(a1(),1),dd=C(fr(),1);var c1=M("libp2p:dialer:dial-request"),xu=class{constructor(e){let{addrs:r,dialAction:n,dialer:i}=e;this.addrs=r,this.dialer=i,this.dialAction=n}async run(e={}){let r=this.dialer.getTokens(this.addrs.length);if(r.length<1)throw(0,Qo.default)(new Error("No dial tokens available"),b.ERR_NO_DIAL_TOKENS);let n=new l1.default;for(let a of r)n.push(a).catch(c=>{c1.error(c)});let i=this.addrs.map(()=>{let a=new AbortController;try{(0,dd.setMaxListeners)?.(1/0,a.signal)}catch{}return a});if(e.signal!=null)try{(0,dd.setMaxListeners)?.(1/0,e.signal)}catch{}let s=0,o=!1;try{return await Promise.any(this.addrs.map(async(a,c)=>{let u=await n.shift();if(o)throw this.dialer.releaseToken(r.splice(r.indexOf(u),1)[0]),(0,Qo.default)(new Error("dialAction already succeeded"),b.ERR_ALREADY_SUCCEEDED);let l=i[c];if(l==null)throw(0,Qo.default)(new Error("dialAction did not come with an AbortController"),b.ERR_INVALID_PARAMETERS);let f;try{let h=l.signal;f=await this.dialAction(a,{...e,signal:e.signal!=null?(0,u1.anySignal)([h,e.signal]):h}),i[c]=void 0}finally{s++,this.addrs.length-s>=r.length?n.push(u).catch(h=>{c1.error(h)}):this.dialer.releaseToken(r.splice(r.indexOf(u),1)[0])}if(f==null)throw(0,Qo.default)(new Error("dialAction led to empty object"),b.ERR_TRANSPORT_DIAL_FAILED);return o=!0,f}))}finally{i.forEach(a=>{a!==void 0&&a.abort()}),r.forEach(a=>this.dialer.releaseToken(a))}}};var cr=M("libp2p:dialer"),bu=class{constructor(e,r={}){this.started=!1,this.addressSorter=r.addressSorter??Ji,this.maxAddrsToDial=r.maxAddrsToDial??25,this.timeout=r.dialTimeout??3e4,this.maxDialsPerPeer=r.maxDialsPerPeer??4,this.tokens=[...new Array(r.maxParallelDials??100)].map((n,i)=>i),this.components=e,this.pendingDials=To({name:"libp2p_dialler_pending_dials",metrics:e.metrics}),this.pendingDialTargets=To({name:"libp2p_dialler_pending_dial_targets",metrics:e.metrics});for(let[n,i]of Object.entries(r.resolvers??{}))xl.set(n,i)}isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1;for(let e of this.pendingDials.values())try{e.controller.abort()}catch(r){cr.error(r)}this.pendingDials.clear();for(let e of this.pendingDialTargets.values())e.abort();this.pendingDialTargets.clear()}async dial(e,r={}){let{id:n,multiaddrs:i}=Kr(e);if(this.components.peerId.equals(n))throw(0,Ts.default)(new Error("Tried to dial self"),b.ERR_DIALED_SELF);if(cr("check multiaddrs %p",n),i!=null&&i.length>0&&(cr("storing multiaddrs %p",n,i),await this.components.peerStore.addressBook.add(n,i)),await this.components.connectionGater.denyDialPeer(n))throw(0,Ts.default)(new Error("The dial request is blocked by gater.allowDialPeer"),b.ERR_PEER_DIAL_INTERCEPTED);cr("creating dial target for %p",n);let s=new AbortController,o=f1();this.pendingDialTargets.set(o,s);let a=s.signal;r.signal!=null&&(a=(0,pd.anySignal)([a,r.signal]));let c;try{c=await this._createDialTarget(e,{...r,signal:a})}finally{this.pendingDialTargets.delete(o)}if(c.addrs.length===0)throw(0,Ts.default)(new Error("The dial request has no valid addresses"),b.ERR_NO_VALID_ADDRESSES);let u=this.pendingDials.get(c.id.toString())??this._createPendingDial(c,r);try{let l=await u.promise;return cr("dial succeeded to %s",c.id),l}catch(l){throw cr("dial failed to %s",c.id,l),u.controller.signal.aborted&&(l.code=b.ERR_TIMEOUT),cr.error(l),l}finally{u.destroy()}}async _createDialTarget(e,r){let n=this._resolve.bind(this),i=Fr(e)?[e]:await this._loadAddresses(e);if(i=(await Promise.all(i.map(async o=>await n(o,r)))).flat().filter(o=>Boolean(this.components.transportManager.transportForMultiaddr(o))),i=[...new Set(i)],i.length>this.maxAddrsToDial)throw(0,Ts.default)(new Error("dial with more addresses than allowed"),b.ERR_TOO_MANY_ADDRESSES);let s=Wn(e)?e:void 0;if(s!=null){let o=`/p2p/${s.toString()}`;i=i.map(a=>{let c=a.getPeerId();return c==null||!s.equals(c)?a.encapsulate(o):a})}return{id:s==null?f1():s.toString(),addrs:i}}async _loadAddresses(e){let r=await this.components.peerStore.addressBook.get(e);return(await Promise.all(r.map(async n=>await this.components.connectionGater.denyDialMultiaddr(e,n.multiaddr)?!1:n))).filter(dT).sort(this.addressSorter).map(n=>n.multiaddr)}_createPendingDial(e,r={}){let n=async(u,l={})=>{if(l.signal?.aborted===!0)throw(0,Ts.default)(new Error("already aborted"),b.ERR_ALREADY_ABORTED);return await this.components.transportManager.dial(u,l).catch(f=>{throw cr.error("dial to %s failed",u,f),f})},i=new xu({addrs:e.addrs,dialAction:n,dialer:this}),s=new h1.TimeoutController(this.timeout),o=[s.signal];r.signal!=null&&o.push(r.signal);let a=(0,pd.anySignal)(o);try{(0,d1.setMaxListeners)?.(1/0,a)}catch{}let c={dialRequest:i,controller:s,promise:i.run({...r,signal:a}),destroy:()=>{s.clear(),this.pendingDials.delete(e.id)}};return this.pendingDials.set(e.id,c),c}getTokens(e){let r=Math.min(e,this.maxDialsPerPeer,this.tokens.length),n=this.tokens.splice(0,r);return cr("%d tokens request, returning %d, %d remaining",e,r,this.tokens.length),n}releaseToken(e){this.tokens.includes(e)||(cr("token %d released",e),this.tokens.push(e))}async _resolve(e,r){if(!e.protoNames().includes("dnsaddr"))return[e];let i=await this._resolveRecord(e,r);return(await Promise.all(i.map(async a=>await this._resolve(a,r)))).flat().reduce((a,c)=>(a.find(u=>u.equals(c))==null&&a.push(c),a),[])}async _resolveRecord(e,r){try{return e=oe(e.toString()),await e.resolve(r)}catch(n){return cr.error(`multiaddr ${e.toString()} could not be resolved`,n),[]}}};function dT(t){return Boolean(t)}function f1(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var un=M("libp2p"),md=class extends Ue{constructor(e){super(),this.started=!1,this.peerId=e.peerId;let r=this.components=new yu({peerId:e.peerId,datastore:e.datastore??new oa,connectionGater:{denyDialPeer:async()=>await Promise.resolve(!1),denyDialMultiaddr:async()=>await Promise.resolve(!1),denyInboundConnection:async()=>await Promise.resolve(!1),denyOutboundConnection:async()=>await Promise.resolve(!1),denyInboundEncryptedConnection:async()=>await Promise.resolve(!1),denyOutboundEncryptedConnection:async()=>await Promise.resolve(!1),denyInboundUpgradedConnection:async()=>await Promise.resolve(!1),denyOutboundUpgradedConnection:async()=>await Promise.resolve(!1),filterMultiaddrForPeer:async()=>await Promise.resolve(!0),...e.connectionGater}});r.peerStore=new pu(r,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore}),this.services=[r],e.metrics!=null&&(this.metrics=this.components.metrics=this.configureComponent(e.metrics(this.components))),this.peerStore=this.components.peerStore,this.peerStore.addEventListener("peer",o=>{let{detail:a}=o;this.dispatchEvent(new Z("peer:discovery",{detail:a}))}),e.connectionProtector!=null&&(this.components.connectionProtector=e.connectionProtector(r)),this.components.upgrader=new Fc(this.components,{connectionEncryption:(e.connectionEncryption??[]).map(o=>this.configureComponent(o(this.components))),muxers:(e.streamMuxers??[]).map(o=>this.configureComponent(o(this.components))),inboundUpgradeTimeout:e.connectionManager.inboundUpgradeTimeout}),this.components.dialer=new bu(this.components,e.connectionManager),this.connectionManager=this.components.connectionManager=new Da(this.components,e.connectionManager),this.registrar=this.components.registrar=new Mc(this.components),this.components.transportManager=new kc(this.components,e.transportManager),this.components.addressManager=new xa(this.components,e.addresses),this.configureComponent(new $c(this.components)),this.configureComponent(new La(this.components,{enabled:e.connectionManager.autoDial,minConnections:e.connectionManager.minConnections,autoDialInterval:e.connectionManager.autoDialInterval}));let n=Ao.generateOptions();this.keychain=this.configureComponent(new Ao(this.components,{...n,...e.keychain})),this.services.push(new zc(this.components,e.nat)),e.transports.forEach(o=>{this.components.transportManager.add(this.configureComponent(o(this.components)))}),this.identifyService=new _s(this.components,{...e.identify}),this.configureComponent(this.identifyService),e.dht!=null?this.dht=this.components.dht=e.dht(this.components):this.dht=new vu,e.pubsub!=null?this.pubsub=this.components.pubsub=e.pubsub(this.components):this.pubsub=new wu;let i=(e.peerRouters??[]).map(o=>this.configureComponent(o(this.components)));e.dht!=null&&(i.push(this.configureComponent(new Gc(this.dht))),this.dht.addEventListener("peer",o=>{this.onDiscoveryPeer(o)})),this.peerRouting=this.components.peerRouting=this.configureComponent(new da(this.components,{...e.peerRouting,routers:i}));let s=(e.contentRouters??[]).map(o=>this.configureComponent(o(this.components)));e.dht!=null&&s.push(this.configureComponent(new mu(this.dht))),this.contentRouting=this.components.contentRouting=this.configureComponent(new ma(this.components,{routers:s})),e.relay.enabled&&(this.components.transportManager.add(this.configureComponent(new za(this.components,e.relay))),this.configureComponent(new ja(this.components,{addressSorter:e.connectionManager.addressSorter,...e.relay}))),this.fetchService=this.configureComponent(new Vc(this.components,{...e.fetch})),this.pingService=this.configureComponent(new qc(this.components,{...e.ping}));for(let o of e.peerDiscovery??[])this.configureComponent(o(this.components)).addEventListener("peer",c=>{this.onDiscoveryPeer(c)})}configureComponent(e){return Lr(e)&&this.services.push(e),e}async start(){if(!this.started){this.started=!0,un("libp2p is starting");try{await Promise.all(this.services.map(async e=>{e.beforeStart!=null&&await e.beforeStart()})),await Promise.all(this.services.map(e=>e.start())),await Promise.all(this.services.map(async e=>{e.afterStart!=null&&await e.afterStart()})),un("libp2p has started")}catch(e){throw un.error("An error occurred starting libp2p",e),await this.stop(),e}}}async stop(){this.started&&(un("libp2p is stopping"),this.started=!1,await Promise.all(this.services.map(async e=>{e.beforeStop!=null&&await e.beforeStop()})),await Promise.all(this.services.map(e=>e.stop())),await Promise.all(this.services.map(async e=>{e.afterStop!=null&&await e.afterStop()})),un("libp2p has stopped"))}isStarted(){return this.started}getConnections(e){return this.components.connectionManager.getConnections(e)}getPeers(){let e=new Hr;for(let r of this.components.connectionManager.getConnections())e.add(r.remotePeer);return Array.from(e)}async dial(e,r={}){let{id:n,multiaddrs:i}=Kr(e);return await this.components.peerStore.addressBook.add(n,i),await this.components.connectionManager.openConnection(n,r)}async dialProtocol(e,r,n={}){if(r==null)throw(0,Xo.default)(new Error("no protocols were provided to open a stream"),b.ERR_INVALID_PROTOCOLS_FOR_STREAM);if(r=Array.isArray(r)?r:[r],r.length===0)throw(0,Xo.default)(new Error("no protocols were provided to open a stream"),b.ERR_INVALID_PROTOCOLS_FOR_STREAM);return await(await this.dial(e,n)).newStream(r,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}async hangUp(e){let{id:r}=Kr(e);await this.components.connectionManager.closeConnections(r)}async getPublicKey(e,r={}){if(un("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;let n=await this.peerStore.get(e);if(n.pubKey!=null)return n.pubKey;if(this.dht==null)throw(0,Xo.default)(new Error("Public key was not in the peer store and the DHT is not enabled"),b.ERR_NO_ROUTERS_AVAILABLE);let i=Xe([q("/pk/"),e.multihash.digest]);for await(let s of this.dht.get(i,r))if(s.name==="VALUE"){let o=So(s.value);return await this.peerStore.keyBook.set(e,s.value),o.bytes}throw(0,Xo.default)(new Error(`Node not responding with its public key: ${e.toString()}`),b.ERR_INVALID_RECORD)}async fetch(e,r,n={}){let{id:i,multiaddrs:s}=Kr(e);return s!=null&&await this.components.peerStore.addressBook.add(i,s),await this.fetchService.fetch(i,r,n)}async ping(e,r={}){let{id:n,multiaddrs:i}=Kr(e);return i.length>0&&await this.components.peerStore.addressBook.add(n,i),await this.pingService.ping(n,r)}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)}))}onDiscoveryPeer(e){let{detail:r}=e;if(r.id.toString()===this.peerId.toString()){un.error(new Error(b.ERR_DISCOVERED_SELF));return}r.multiaddrs.length>0&&this.components.peerStore.addressBook.add(r.id,r.multiaddrs).catch(n=>un.error(n)),r.protocols.length>0&&this.components.peerStore.protoBook.set(r.id,r.protocols).catch(n=>un.error(n)),this.dispatchEvent(new Z("peer:discovery",{detail:r}))}};async function p1(t){return t.peerId==null&&(t.peerId=await Ww()),new md(Yw(t))}async function pT(t){let e=await p1(t);return t.start!==!1&&await e.start(),e}return w1(mT);})();
50
+ /*! Bundled license information:
51
+
52
+ @noble/secp256k1/lib/esm/index.js:
53
+ (*! noble-secp256k1 - MIT License (c) 2019 Paul Miller (paulmillr.com) *)
54
+
55
+ @noble/ed25519/lib/esm/index.js:
56
+ (*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) *)
57
+ */
50
58
  return Libp2P}));