libp2p 3.1.7 → 3.2.0-b30baa93a
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 +13 -13
- package/dist/index.min.js.map +4 -4
- package/dist/src/connection-manager/dial-queue.d.ts +2 -2
- package/dist/src/connection-manager/dial-queue.d.ts.map +1 -1
- package/dist/src/connection-manager/dial-queue.js +1 -1
- package/dist/src/connection-manager/dial-queue.js.map +1 -1
- package/dist/src/connection-manager/index.d.ts +3 -3
- package/dist/src/connection-manager/index.d.ts.map +1 -1
- package/dist/src/connection-manager/index.js +3 -0
- package/dist/src/connection-manager/index.js.map +1 -1
- package/dist/src/connection.d.ts.map +1 -1
- package/dist/src/connection.js +11 -1
- package/dist/src/connection.js.map +1 -1
- package/dist/src/get-peer.d.ts +2 -2
- package/dist/src/get-peer.d.ts.map +1 -1
- package/dist/src/get-peer.js.map +1 -1
- package/dist/src/libp2p.d.ts +3 -3
- package/dist/src/libp2p.d.ts.map +1 -1
- package/dist/src/libp2p.js.map +1 -1
- package/dist/src/version.d.ts +1 -1
- package/dist/src/version.d.ts.map +1 -1
- package/dist/src/version.js +1 -1
- package/dist/src/version.js.map +1 -1
- package/package.json +12 -12
- package/src/connection-manager/dial-queue.ts +3 -3
- package/src/connection-manager/index.ts +8 -3
- package/src/connection.ts +15 -2
- package/src/get-peer.ts +2 -2
- package/src/libp2p.ts +3 -3
- package/src/version.ts +1 -1
- package/dist/typedoc-urls.json +0 -24
package/dist/index.min.js
CHANGED
|
@@ -1,29 +1,29 @@
|
|
|
1
1
|
(function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Libp2P = factory()}(typeof self !== 'undefined' ? self : this, function () {
|
|
2
|
-
"use strict";var Libp2P=(()=>{var Dp=Object.create;var Oo=Object.defineProperty;var kp=Object.getOwnPropertyDescriptor;var Rp=Object.getOwnPropertyNames;var Op=Object.getPrototypeOf,Np=Object.prototype.hasOwnProperty;var ua=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Be=(r,e)=>{for(var t in e)Oo(r,t,{get:e[t],enumerable:!0})},Ru=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Rp(e))!Np.call(r,o)&&o!==t&&Oo(r,o,{get:()=>e[o],enumerable:!(n=kp(e,o))||n.enumerable});return r};var fa=(r,e,t)=>(t=r!=null?Dp(Op(r)):{},Ru(e||!r||!r.__esModule?Oo(t,"default",{value:r,enumerable:!0}):t,r)),Mp=r=>Ru(Oo({},"__esModule",{value:!0}),r);var ih=ua(ao=>{(function(){var r,e,t,n,o,s,i,a;a=function(c){var l,u,f,d;return l=(c&255<<24)>>>24,u=(c&255<<16)>>>16,f=(c&65280)>>>8,d=c&255,[l,u,f,d].join(".")},i=function(c){var l,u,f,d,h,p;for(l=[],f=d=0;d<=3&&c.length!==0;f=++d){if(f>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}p=e(c),h=p[0],u=p[1],c=c.substring(u),l.push(h)}if(c.length!==0)throw new Error("Invalid IP");switch(l.length){case 1:if(l[0]>4294967295)throw new Error("Invalid IP");return l[0]>>>0;case 2:if(l[0]>255||l[1]>16777215)throw new Error("Invalid IP");return(l[0]<<24|l[1])>>>0;case 3:if(l[0]>255||l[1]>255||l[2]>65535)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2])>>>0;case 4:if(l[0]>255||l[1]>255||l[2]>255||l[3]>255)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2]<<8|l[3])>>>0;default:throw new Error("Invalid IP")}},t=function(c){return c.charCodeAt(0)},n=t("0"),s=t("a"),o=t("A"),e=function(c){var l,u,f,d,h;for(d=0,l=10,u="9",f=0,c.length>1&&c[f]==="0"&&(c[f+1]==="x"||c[f+1]==="X"?(f+=2,l=16):"0"<=c[f+1]&&c[f+1]<="9"&&(f++,l=8,u="7")),h=f;f<c.length;){if("0"<=c[f]&&c[f]<=u)d=d*l+(t(c[f])-n)>>>0;else if(l===16)if("a"<=c[f]&&c[f]<="f")d=d*l+(10+t(c[f])-s)>>>0;else if("A"<=c[f]&&c[f]<="F")d=d*l+(10+t(c[f])-o)>>>0;else break;else break;if(d>4294967295)throw new Error("too large");f++}if(f===h)throw new Error("empty octet");return[d,f]},r=(function(){function c(l,u){var f,d,h,p;if(typeof l!="string")throw new Error("Missing `net' parameter");if(u||(p=l.split("/",2),l=p[0],u=p[1]),u||(u=32),typeof u=="string"&&u.indexOf(".")>-1){try{this.maskLong=i(u)}catch(y){throw f=y,new Error("Invalid mask: "+u)}for(d=h=32;h>=0;d=--h)if(this.maskLong===4294967295<<32-d>>>0){this.bitmask=d;break}}else if(u||u===0)this.bitmask=parseInt(u,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(i(l)&this.maskLong)>>>0}catch(y){throw f=y,new Error("Invalid net address: "+l)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+u);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(l){return typeof l=="string"&&(l.indexOf("/")>0||l.split(".").length!==4)&&(l=new c(l)),l instanceof c?this.contains(l.base)&&this.contains(l.broadcast||l.last):(i(l)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(l){return l==null&&(l=1),new c(a(this.netLong+this.size*l),this.mask)},c.prototype.forEach=function(l){var u,f,d;for(d=i(this.first),f=i(this.last),u=0;d<=f;)l(a(d),d,u),u++,d++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c})(),ao.ip2long=i,ao.long2ip=a,ao.Netmask=r}).call(ao)});var pp=ua((MT,uu)=>{"use strict";var Ab=Object.prototype.hasOwnProperty,Me="~";function Io(){}Object.create&&(Io.prototype=Object.create(null),new Io().__proto__||(Me=!1));function Cb(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function hp(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var s=new Cb(t,n||r,o),i=Me?Me+e:e;return r._events[i]?r._events[i].fn?r._events[i]=[r._events[i],s]:r._events[i].push(s):(r._events[i]=s,r._eventsCount++),r}function Wi(r,e){--r._eventsCount===0?r._events=new Io:delete r._events[e]}function Te(){this._events=new Io,this._eventsCount=0}Te.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)Ab.call(t,n)&&e.push(Me?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Te.prototype.listeners=function(e){var t=Me?Me+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var o=0,s=n.length,i=new Array(s);o<s;o++)i[o]=n[o].fn;return i};Te.prototype.listenerCount=function(e){var t=Me?Me+e:e,n=this._events[t];return n?n.fn?1:n.length:0};Te.prototype.emit=function(e,t,n,o,s,i){var a=Me?Me+e:e;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,u,f;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,o),!0;case 5:return c.fn.call(c.context,t,n,o,s),!0;case 6:return c.fn.call(c.context,t,n,o,s,i),!0}for(f=1,u=new Array(l-1);f<l;f++)u[f-1]=arguments[f];c.fn.apply(c.context,u)}else{var d=c.length,h;for(f=0;f<d;f++)switch(c[f].once&&this.removeListener(e,c[f].fn,void 0,!0),l){case 1:c[f].fn.call(c[f].context);break;case 2:c[f].fn.call(c[f].context,t);break;case 3:c[f].fn.call(c[f].context,t,n);break;case 4:c[f].fn.call(c[f].context,t,n,o);break;default:if(!u)for(h=1,u=new Array(l-1);h<l;h++)u[h-1]=arguments[h];c[f].fn.apply(c[f].context,u)}}return!0};Te.prototype.on=function(e,t,n){return hp(this,e,t,n,!1)};Te.prototype.once=function(e,t,n){return hp(this,e,t,n,!0)};Te.prototype.removeListener=function(e,t,n,o){var s=Me?Me+e:e;if(!this._events[s])return this;if(!t)return Wi(this,s),this;var i=this._events[s];if(i.fn)i.fn===t&&(!o||i.once)&&(!n||i.context===n)&&Wi(this,s);else{for(var a=0,c=[],l=i.length;a<l;a++)(i[a].fn!==t||o&&!i[a].once||n&&i[a].context!==n)&&c.push(i[a]);c.length?this._events[s]=c.length===1?c[0]:c:Wi(this,s)}return this};Te.prototype.removeAllListeners=function(e){var t;return e?(t=Me?Me+e:e,this._events[t]&&Wi(this,t)):(this._events=new Io,this._eventsCount=0),this};Te.prototype.off=Te.prototype.removeListener;Te.prototype.addListener=Te.prototype.on;Te.prefixed=Me;Te.EventEmitter=Te;typeof uu<"u"&&(uu.exports=Te)});var yp=ua((o4,gp)=>{gp.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function o(s,i){t[s]=i,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(s){return t[s]!==void 0||n[s]!==void 0},remove:function(s){t[s]!==void 0&&(t[s]=void 0),n[s]!==void 0&&(n[s]=void 0)},get:function(s){var i=t[s];if(i!==void 0)return i;if((i=n[s])!==void 0)return o(s,i),i},set:function(s,i){t[s]!==void 0?t[s]=i:o(s,i)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var Zb={};Be(Zb,{createLibp2p:()=>Yb,dnsaddrResolver:()=>Ar,isLibp2p:()=>jb});var Ou=Symbol.for("@libp2p/connection");var da=Symbol.for("@libp2p/content-routing");var Xe=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var I=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Cr=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}},yn=class extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}};var Wt=class extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}};var Gt=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}},Ir=class extends Error{static name="InvalidPeerIdError";constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}},Lt=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},No=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Mo=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}},Bo=class extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}},Fo=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var Uo=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},dt=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}};var Tr=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}};var bn=class extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}},Ko=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}},qo=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}},Pt=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var $o=class extends Event{error;local;constructor(e,t,n){super("close",n),this.error=t,this.local=e}};var ha=Symbol.for("@libp2p/peer-discovery");var Vo=Symbol.for("@libp2p/peer-id");function Dt(r){return!!r?.[Vo]}var pa=Symbol.for("@libp2p/peer-routing");var ma="keep-alive";function zo(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function Nu(...r){let e=[];for(let t of r)zo(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStart!=null&&await t.beforeStart()})),await Promise.all(e.map(async t=>{await t.start()})),await Promise.all(e.map(async t=>{t.afterStart!=null&&await t.afterStart()}))}async function Mu(...r){let e=[];for(let t of r)zo(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStop!=null&&await t.beforeStop()})),await Promise.all(e.map(async t=>{await t.stop()})),await Promise.all(e.map(async t=>{t.afterStop!=null&&await t.afterStop()}))}var cw=Symbol.for("@libp2p/transport");var wn;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(wn||(wn={}));var Le=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){super.addEventListener(e,t,n);let o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==t),this.#e.set(e,o))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:o})=>!o),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var xn=Symbol.for("@libp2p/service-capabilities"),ga=Symbol.for("@libp2p/service-dependencies");var Ea={};Be(Ea,{base58btc:()=>J,base58flickr:()=>Vp});var Mw=new Uint8Array(0);function Bu(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function ht(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function Fu(r){return new TextEncoder().encode(r)}function Uu(r){return new TextDecoder().decode(r)}function Bp(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function f(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var y=0,m=0,g=0,_=p.length;g!==_&&p[g]===0;)g++,y++;for(var E=(_-g)*u+1>>>0,C=new Uint8Array(E);g!==_;){for(var O=p[g],$=0,q=E-1;(O!==0||$<m)&&q!==-1;q--,$++)O+=256*C[q]>>>0,C[q]=O%a>>>0,O=O/a>>>0;if(O!==0)throw new Error("Non-zero carry");m=$,g++}for(var S=E-m;S!==E&&C[S]===0;)S++;for(var v=c.repeat(y);S<E;++S)v+=r.charAt(C[S]);return v}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var y=0;if(p[y]!==" "){for(var m=0,g=0;p[y]===c;)m++,y++;for(var _=(p.length-y)*l+1>>>0,E=new Uint8Array(_);p[y];){var C=t[p.charCodeAt(y)];if(C===255)return;for(var O=0,$=_-1;(C!==0||O<g)&&$!==-1;$--,O++)C+=a*E[$]>>>0,E[$]=C%256>>>0,C=C/256>>>0;if(C!==0)throw new Error("Non-zero carry");g=O,y++}if(p[y]!==" "){for(var q=_-g;q!==_&&E[q]===0;)q++;for(var S=new Uint8Array(m+(_-q)),v=m;q!==_;)S[v++]=E[q++];return S}}}function h(p){var y=d(p);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:d,decode:h}}var Fp=Bp,Up=Fp,qu=Up;var ya=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},ba=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return $u(this,e)}},wa=class{decoders;constructor(e){this.decoders=e}or(e){return $u(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function $u(r,e){return new wa({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var xa=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new ya(e,t,n),this.decoder=new ba(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Lr({name:r,prefix:e,encode:t,decode:n}){return new xa(r,e,t,n)}function kt({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=qu(t,r);return Lr({prefix:e,name:r,encode:n,decode:s=>ht(o(s))})}function Kp(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let l=0;l<o;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function qp(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function $p(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function ce({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=$p(n);return Lr({prefix:e,name:r,encode(s){return qp(s,n,t)},decode(s){return Kp(s,o,t,r)}})}var J=kt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Vp=kt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var va={};Be(va,{base32:()=>He,base32hex:()=>Gp,base32hexpad:()=>Xp,base32hexpadupper:()=>jp,base32hexupper:()=>Yp,base32pad:()=>Hp,base32padupper:()=>Wp,base32upper:()=>zp,base32z:()=>Zp});var He=ce({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),zp=ce({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Hp=ce({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Wp=ce({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Gp=ce({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Yp=ce({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Xp=ce({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),jp=ce({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Zp=ce({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Sa={};Be(Sa,{base36:()=>En,base36upper:()=>Qp});var En=kt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Qp=kt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Jp=Hu,Vu=128,em=127,tm=~em,rm=Math.pow(2,31);function Hu(r,e,t){e=e||[],t=t||0;for(var n=t;r>=rm;)e[t++]=r&255|Vu,r/=128;for(;r&tm;)e[t++]=r&255|Vu,r>>>=7;return e[t]=r|0,Hu.bytes=t-n+1,e}var nm=_a,om=128,zu=127;function _a(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw _a.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&zu)<<o:(i&zu)*Math.pow(2,o),o+=7}while(i>=om);return _a.bytes=s-n,t}var sm=Math.pow(2,7),im=Math.pow(2,14),am=Math.pow(2,21),cm=Math.pow(2,28),lm=Math.pow(2,35),um=Math.pow(2,42),fm=Math.pow(2,49),dm=Math.pow(2,56),hm=Math.pow(2,63),pm=function(r){return r<sm?1:r<im?2:r<am?3:r<cm?4:r<lm?5:r<um?6:r<fm?7:r<dm?8:r<hm?9:10},mm={encode:Jp,decode:nm,encodingLength:pm},gm=mm,vn=gm;function Sn(r,e=0){return[vn.decode(r,e),vn.decode.bytes]}function Pr(r,e,t=0){return vn.encode(r,e,t),e}function Dr(r){return vn.encodingLength(r)}function it(r,e){let t=e.byteLength,n=Dr(r),o=n+Dr(t),s=new Uint8Array(o+t);return Pr(r,s,0),Pr(t,s,n),s.set(e,o),new kr(r,t,e,s)}function pt(r){let e=ht(r),[t,n]=Sn(e),[o,s]=Sn(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new kr(t,o,i,e)}function Wu(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Bu(r.bytes,t.bytes)}}var kr=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};function Gu(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return bm(t,Aa(r),e??J.encoder);default:return wm(t,Aa(r),e??He.encoder)}}var Yu=new WeakMap;function Aa(r){let e=Yu.get(r);if(e==null){let t=new Map;return Yu.set(r,t),t}return e}var ue=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==_n)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==xm)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=it(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&Wu(e.multihash,n.multihash)}toString(e){return Gu(this,e)}toJSON(){return{"/":Gu(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??Xu(n,o,s.bytes))}else if(t[Em]===!0){let{version:n,multihash:o,code:s}=t,i=pt(o);return r.create(n,s,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==_n)throw new Error(`Version 0 CID must use dag-pb (code: ${_n}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=Xu(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,_n,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=ht(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new kr(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,d]=Sn(e.subarray(t));return t+=d,f},o=n(),s=_n;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,o]=ym(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Aa(s).set(n,e),s}};function ym(r,e){switch(r[0]){case"Q":{let t=e??J;return[J.prefix,t.decode(`${J.prefix}${r}`)]}case J.prefix:{let t=e??J;return[J.prefix,t.decode(r)]}case He.prefix:{let t=e??He;return[He.prefix,t.decode(r)]}case En.prefix:{let t=e??En;return[En.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function bm(r,e,t){let{prefix:n}=t;if(n!==J.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function wm(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var _n=112,xm=18;function Xu(r,e,t){let n=Dr(r),o=n+Dr(e),s=new Uint8Array(o+t.byteLength);return Pr(r,s,0),Pr(e,s,n),s.set(t,o),s}var Em=Symbol.for("@ipld/js-cid/CID");var Ca={};Be(Ca,{identity:()=>je});var ju=0,vm="identity",Zu=ht;function Sm(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return it(ju,Zu(r))}var je={code:ju,name:vm,encode:Zu,digest:Sm};function Z(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function le(r=0){return new Uint8Array(r)}function Se(r=0){return new Uint8Array(r)}function Ze(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=Se(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}var Ju=Symbol.for("@achingbrain/uint8arraylist");function Qu(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function Wo(r){return!!r?.[Ju]}var Q=class r{bufs;length;[Ju]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(Wo(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(Wo(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=Qu(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Qu(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(Wo(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:o}=this._subList(e,t);return Ze(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:Ze(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=[...n],s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let l=e>=a&&e<c,u=t>a&&t<=c;if(l&&u){if(e===a&&t===c){n.push(i);break}let f=e-a;n.push(i.subarray(f,f+(t-e)));break}if(l){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(u){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!Wo(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let f=0;f<s;f++)i[f]=-1;for(let f=0;f<o;f++)i[n[f]]=f;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let f=t;f<=c;f+=u){u=0;for(let d=l;d>=0;d--){let h=this.get(f+d);if(n[d]!==h){u=Math.max(1,d-a[h]);break}}if(u===0)return f}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=Se(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=le(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=le(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=le(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=Se(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=le(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=le(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=le(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=le(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=le(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!Z(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,s)=>o+s.byteLength,0)),n.length=t,n}};var Ia={};Be(Ia,{base10:()=>_m});var _m=kt({prefix:"9",name:"base10",alphabet:"0123456789"});var Ta={};Be(Ta,{base16:()=>Am,base16upper:()=>Cm});var Am=ce({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Cm=ce({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var La={};Be(La,{base2:()=>Im});var Im=ce({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Pa={};Be(Pa,{base256emoji:()=>km});var ef=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),Tm=ef.reduce((r,e,t)=>(r[t]=e,r),[]),Lm=ef.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function Pm(r){return r.reduce((e,t)=>(e+=Tm[t],e),"")}function Dm(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=Lm[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var km=Lr({prefix:"\u{1F680}",name:"base256emoji",encode:Pm,decode:Dm});var Ra={};Be(Ra,{base64:()=>Da,base64pad:()=>Rm,base64url:()=>ka,base64urlpad:()=>Om});var Da=ce({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Rm=ce({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),ka=ce({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Om=ce({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Oa={};Be(Oa,{base8:()=>Nm});var Nm=ce({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Na={};Be(Na,{identity:()=>Mm});var Mm=Lr({prefix:"\0",name:"identity",encode:r=>Uu(r),decode:r=>Fu(r)});var wx=new TextEncoder,xx=new TextDecoder;var Fa={};Be(Fa,{sha256:()=>Rr,sha512:()=>Km});var Um=20;function Ba({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new Ma(r,e,t,n,o)}var Ma=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??Um,this.maxDigestLength=s}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?tf(n,this.code,t?.truncate):n.then(o=>tf(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function tf(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return it(e,r)}function nf(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Rr=Ba({name:"sha2-256",code:18,encode:nf("SHA-256")}),Km=Ba({name:"sha2-512",code:19,encode:nf("SHA-512")});var An={...Na,...La,...Oa,...Ia,...Ta,...va,...Sa,...Ea,...Ra,...Pa},kx={...Fa,...Ca};function sf(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var of=sf("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Ua=sf("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=Se(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),qm={utf8:of,"utf-8":of,hex:An.base16,latin1:Ua,ascii:Ua,binary:Ua,...An},Go=qm;function L(r,e="utf8"){let t=Go[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function U(r,e="utf8"){let t=Go[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var $m=parseInt("11111",2),Ka=parseInt("10000000",2),Vm=parseInt("01111111",2),af={0:Cn,1:Cn,2:zm,3:Gm,4:Ym,5:Wm,6:Hm,16:Cn,22:Cn,48:Cn};function mt(r,e={offset:0}){let t=r[e.offset]&$m;if(e.offset++,af[t]!=null)return af[t](r,e);throw new Error("No decoder for tag "+t)}function In(r,e){let t=0;if((r[e.offset]&Ka)===Ka){let n=r[e.offset]&Vm,o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++)o+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(o,16)}else t=r[e.offset],e.offset++;return t}function Cn(r,e){In(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=mt(r,e);if(n===null)break;t.push(n)}return t}function zm(r,e){let t=In(r,e),n=e.offset,o=e.offset+t,s=[];for(let i=n;i<o;i++)i===n&&r[i]===0||s.push(r[i]);return e.offset+=t,Uint8Array.from(s)}function Hm(r,e){let t=In(r,e),n=e.offset+t,o=r[e.offset];e.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,c=[];for(;e.offset<n;){let l=r[e.offset];if(e.offset++,c.push(l&127),l<128){c.reverse();let u=0;for(let f=0;f<c.length;f++)u+=c[f]<<f*7;a+=`.${u}`,c=[]}}return a}function Wm(r,e){return e.offset++,null}function Gm(r,e){let t=In(r,e),n=r[e.offset];e.offset++;let o=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function Ym(r,e){let t=In(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function Xm(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new Q;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function Yo(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=Xm(r.byteLength);return new Q(Uint8Array.from([e.byteLength|Ka]),e)}function Pe(r){let e=new Q,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new Q(Uint8Array.from([2]),Yo(e),e)}function Tn(r){let e=Uint8Array.from([0]),t=new Q(e,r);return new Q(Uint8Array.from([3]),Yo(t),t)}function cf(r){return new Q(Uint8Array.from([4]),Yo(r),r)}function Qe(r,e=48){let t=new Q;for(let n of r)t.append(n);return new Q(Uint8Array.from([e]),Yo(t),t)}async function lf(r="P-256"){let e=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:r},!0,["sign","verify"]);return{publicKey:await crypto.subtle.exportKey("jwk",e.publicKey),privateKey:await crypto.subtle.exportKey("jwk",e.privateKey)}}async function uf(r,e,t){let n=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["sign"]);t?.signal?.throwIfAborted();let o=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,e.subarray());return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function ff(r,e,t,n){let o=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,e,t.subarray());return n?.signal?.throwIfAborted(),s}var jm=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Zm=Uint8Array.from([6,5,43,129,4,0,34]),Qm=Uint8Array.from([6,5,43,129,4,0,35]),Jm={ext:!0,kty:"EC",crv:"P-256"},eg={ext:!0,kty:"EC",crv:"P-384"},tg={ext:!0,kty:"EC",crv:"P-521"},qa=32,$a=48,Va=66;function za(r){let e=mt(r);return df(e)}function df(r){let e=r[1][1][0],t=1,n,o;if(e.byteLength===qa*2+1)return n=U(e.subarray(t,t+qa),"base64url"),o=U(e.subarray(t+qa),"base64url"),new Yt({...Jm,key_ops:["verify"],x:n,y:o});if(e.byteLength===$a*2+1)return n=U(e.subarray(t,t+$a),"base64url"),o=U(e.subarray(t+$a),"base64url"),new Yt({...eg,key_ops:["verify"],x:n,y:o});if(e.byteLength===Va*2+1)return n=U(e.subarray(t,t+Va),"base64url"),o=U(e.subarray(t+Va),"base64url"),new Yt({...tg,key_ops:["verify"],x:n,y:o});throw new I(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function hf(r){return Qe([Pe(Uint8Array.from([1])),cf(L(r.d??"","base64url")),Qe([mf(r.crv)],160),Qe([Tn(new Q(Uint8Array.from([4]),L(r.x??"","base64url"),L(r.y??"","base64url")))],161)]).subarray()}function pf(r){return Qe([Pe(Uint8Array.from([1])),Qe([mf(r.crv)],160),Qe([Tn(new Q(Uint8Array.from([4]),L(r.x??"","base64url"),L(r.y??"","base64url")))],161)]).subarray()}function mf(r){if(r==="P-256")return jm;if(r==="P-384")return Zm;if(r==="P-521")return Qm;throw new I(`Invalid curve ${r}`)}async function gf(r="P-256"){let e=await lf(r);return new Xo(e.privateKey)}var Yt=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=pf(this.jwk)),this._raw}toMultihash(){return je.digest(We(this))}toCID(){return ue.createV1(114,this.toMultihash())}toString(){return J.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Z(this.raw,e.raw)}async verify(e,t,n){return ff(this.jwk,t,e,n)}},Xo=class{type="ECDSA";jwk;publicKey;_raw;constructor(e){this.jwk=e,this.publicKey=new Yt({crv:e.crv,ext:e.ext,key_ops:["verify"],kty:"EC",x:e.x,y:e.y})}get raw(){return this._raw==null&&(this._raw=hf(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Z(this.raw,e.raw)}async sign(e,t){return uf(this.jwk,e,t)}};function Xt(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function at(r,e=""){if(!Number.isSafeInteger(r)||r<0){let t=e&&`"${e}" `;throw new Error(`${t}expected integer >= 0, got ${r}`)}}function V(r,e,t=""){let n=Xt(r),o=r?.length,s=e!==void 0;if(!n||s&&o!==e){let i=t&&`"${t}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function jo(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");at(r.outputLen),at(r.blockLen)}function Or(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function bf(r,e){V(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length<t)throw new Error('"digestInto() output" expected to be of length >='+t)}function yt(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function Zo(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Je(r,e){return r<<32-e|r>>>e}var wf=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",rg=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function bt(r){if(V(r),wf)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=rg[r[t]];return e}var gt={_0:48,_9:57,A:65,F:70,a:97,f:102};function yf(r){if(r>=gt._0&&r<=gt._9)return r-gt._0;if(r>=gt.A&&r<=gt.F)return r-(gt.A-10);if(r>=gt.a&&r<=gt.f)return r-(gt.a-10)}function wt(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(wf)return Uint8Array.fromHex(r);let e=r.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let o=0,s=0;o<t;o++,s+=2){let i=yf(r.charCodeAt(s)),a=yf(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function Fe(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];V(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let s=r[n];t.set(s,o),o+=s.length}return t}function Ha(r,e={}){let t=(o,s)=>r(s).update(o).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=o=>r(o),Object.assign(t,e),Object.freeze(t)}function Ot(r=32){let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(r))}var Wa=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function xf(r,e,t){return r&e^~r&t}function Ef(r,e,t){return r&e^r&t^e&t}var Ln=class{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,o){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=Zo(this.buffer)}update(e){Or(this),V(e);let{view:t,buffer:n,blockLen:o}=this,s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=Zo(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Or(this),bf(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,yt(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let f=i;f<o;f++)t[f]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=Zo(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<l;f++)a.setUint32(4*f,u[f],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},xt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var we=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Qo=BigInt(4294967295),vf=BigInt(32);function ng(r,e=!1){return e?{h:Number(r&Qo),l:Number(r>>vf&Qo)}:{h:Number(r>>vf&Qo)|0,l:Number(r&Qo)|0}}function Sf(r,e=!1){let t=r.length,n=new Uint32Array(t),o=new Uint32Array(t);for(let s=0;s<t;s++){let{h:i,l:a}=ng(r[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var Ga=(r,e,t)=>r>>>t,Ya=(r,e,t)=>r<<32-t|e>>>t,jt=(r,e,t)=>r>>>t|e<<32-t,Zt=(r,e,t)=>r<<32-t|e>>>t,Pn=(r,e,t)=>r<<64-t|e>>>t-32,Dn=(r,e,t)=>r>>>t-32|e<<64-t;function ct(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var _f=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),Af=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,Cf=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),If=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,Tf=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),Lf=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var sg=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Nt=new Uint32Array(64),Xa=class extends Ln{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,t,n,o,s,i,a,c]}set(e,t,n,o,s,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let f=0;f<16;f++,t+=4)Nt[f]=e.getUint32(t,!1);for(let f=16;f<64;f++){let d=Nt[f-15],h=Nt[f-2],p=Je(d,7)^Je(d,18)^d>>>3,y=Je(h,17)^Je(h,19)^h>>>10;Nt[f]=y+Nt[f-7]+p+Nt[f-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){let d=Je(a,6)^Je(a,11)^Je(a,25),h=u+d+xf(a,c,l)+sg[f]+Nt[f]|0,y=(Je(n,2)^Je(n,13)^Je(n,22))+Ef(n,o,s)|0;u=l,l=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+y|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,o,s,i,a,c,l,u)}roundClean(){yt(Nt)}destroy(){this.set(0,0,0,0,0,0,0,0),yt(this.buffer)}},ja=class extends Xa{A=xt[0]|0;B=xt[1]|0;C=xt[2]|0;D=xt[3]|0;E=xt[4]|0;F=xt[5]|0;G=xt[6]|0;H=xt[7]|0;constructor(){super(32)}};var Pf=Sf(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(r=>BigInt(r))),ig=Pf[0],ag=Pf[1],Mt=new Uint32Array(80),Bt=new Uint32Array(80),Za=class extends Ln{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:l,El:u,Fh:f,Fl:d,Gh:h,Gl:p,Hh:y,Hl:m}=this;return[e,t,n,o,s,i,a,c,l,u,f,d,h,p,y,m]}set(e,t,n,o,s,i,a,c,l,u,f,d,h,p,y,m){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=f|0,this.Fl=d|0,this.Gh=h|0,this.Gl=p|0,this.Hh=y|0,this.Hl=m|0}process(e,t){for(let E=0;E<16;E++,t+=4)Mt[E]=e.getUint32(t),Bt[E]=e.getUint32(t+=4);for(let E=16;E<80;E++){let C=Mt[E-15]|0,O=Bt[E-15]|0,$=jt(C,O,1)^jt(C,O,8)^Ga(C,O,7),q=Zt(C,O,1)^Zt(C,O,8)^Ya(C,O,7),S=Mt[E-2]|0,v=Bt[E-2]|0,B=jt(S,v,19)^Pn(S,v,61)^Ga(S,v,6),z=Zt(S,v,19)^Dn(S,v,61)^Ya(S,v,6),k=Cf(q,z,Bt[E-7],Bt[E-16]),w=If(k,$,B,Mt[E-7],Mt[E-16]);Mt[E]=w|0,Bt[E]=k|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:f,El:d,Fh:h,Fl:p,Gh:y,Gl:m,Hh:g,Hl:_}=this;for(let E=0;E<80;E++){let C=jt(f,d,14)^jt(f,d,18)^Pn(f,d,41),O=Zt(f,d,14)^Zt(f,d,18)^Dn(f,d,41),$=f&h^~f&y,q=d&p^~d&m,S=Tf(_,O,q,ag[E],Bt[E]),v=Lf(S,g,C,$,ig[E],Mt[E]),B=S|0,z=jt(n,o,28)^Pn(n,o,34)^Pn(n,o,39),k=Zt(n,o,28)^Dn(n,o,34)^Dn(n,o,39),w=n&s^n&a^s&a,x=o&i^o&c^i&c;g=y|0,_=m|0,y=h|0,m=p|0,h=f|0,p=d|0,{h:f,l:d}=ct(l|0,u|0,v|0,B|0),l=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let b=_f(B,k,x);n=Af(b,v,z,w),o=b|0}({h:n,l:o}=ct(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=ct(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=ct(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=ct(this.Dh|0,this.Dl|0,l|0,u|0),{h:f,l:d}=ct(this.Eh|0,this.El|0,f|0,d|0),{h,l:p}=ct(this.Fh|0,this.Fl|0,h|0,p|0),{h:y,l:m}=ct(this.Gh|0,this.Gl|0,y|0,m|0),{h:g,l:_}=ct(this.Hh|0,this.Hl|0,g|0,_|0),this.set(n,o,s,i,a,c,l,u,f,d,h,p,y,m,g,_)}roundClean(){yt(Mt,Bt)}destroy(){yt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Qa=class extends Za{Ah=we[0]|0;Al=we[1]|0;Bh=we[2]|0;Bl=we[3]|0;Ch=we[4]|0;Cl=we[5]|0;Dh=we[6]|0;Dl=we[7]|0;Eh=we[8]|0;El=we[9]|0;Fh=we[10]|0;Fl=we[11]|0;Gh=we[12]|0;Gl=we[13]|0;Hh=we[14]|0;Hl=we[15]|0;constructor(){super(64)}};var Nr=Ha(()=>new ja,Wa(1));var Df=Ha(()=>new Qa,Wa(3));var ec=BigInt(0),Ja=BigInt(1);function Et(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}" `;throw new Error(t+"expected boolean, got type="+typeof r)}return r}function kf(r){if(typeof r=="bigint"){if(!Jo(r))throw new Error("positive bigint expected, got "+r)}else at(r);return r}function kn(r){let e=kf(r).toString(16);return e.length&1?"0"+e:e}function Rf(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?ec:BigInt("0x"+r)}function Mr(r){return Rf(bt(r))}function Qt(r){return Rf(bt(ts(V(r)).reverse()))}function es(r,e){at(e),r=kf(r);let t=wt(r.toString(16).padStart(e*2,"0"));if(t.length!==e)throw new Error("number too large");return t}function tc(r,e){return es(r,e).reverse()}function ts(r){return Uint8Array.from(r)}var Jo=r=>typeof r=="bigint"&&ec<=r;function cg(r,e,t){return Jo(r)&&Jo(e)&&Jo(t)&&e<=r&&r<t}function Rn(r,e,t,n){if(!cg(e,t,n))throw new Error("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function rc(r){let e;for(e=0;r>ec;r>>=Ja,e+=1);return e}var On=r=>(Ja<<BigInt(r))-Ja;function Of(r,e,t){if(at(r,"hashLen"),at(e,"qByteLen"),typeof t!="function")throw new Error("hmacFn must be a function");let n=m=>new Uint8Array(m),o=Uint8Array.of(),s=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(r),l=n(r),u=0,f=()=>{c.fill(1),l.fill(0),u=0},d=(...m)=>t(l,Fe(c,...m)),h=(m=o)=>{l=d(s,m),c=d(),m.length!==0&&(l=d(i,m),c=d())},p=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let m=0,g=[];for(;m<e;){c=d();let _=c.slice();g.push(_),m+=c.length}return Fe(...g)};return(m,g)=>{f(),h(m);let _;for(;!(_=g(p()));)h();return f(),_}}function Ft(r,e={},t={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function n(s,i,a){let c=r[s];if(a&&c===void 0)return;let l=typeof c;if(l!==i||c===null)throw new Error(`param "${s}" is invalid: expected ${i}, got ${l}`)}let o=(s,i)=>Object.entries(s).forEach(([a,c])=>n(a,c,i));o(e,!1),o(t,!0)}function Br(r){let e=new WeakMap;return(t,...n)=>{let o=e.get(t);if(o!==void 0)return o;let s=r(t,...n);return e.set(t,s),s}}var De=BigInt(0),he=BigInt(1),Jt=BigInt(2),Bf=BigInt(3),Ff=BigInt(4),Uf=BigInt(5),lg=BigInt(7),Kf=BigInt(8),ug=BigInt(9),qf=BigInt(16);function fe(r,e){let t=r%e;return t>=De?t:e+t}function ne(r,e,t){let n=r;for(;e-- >De;)n*=n,n%=t;return n}function Nf(r,e){if(r===De)throw new Error("invert: expected non-zero number");if(e<=De)throw new Error("invert: expected positive modulus, got "+e);let t=fe(r,e),n=e,o=De,s=he,i=he,a=De;for(;t!==De;){let l=n/t,u=n%t,f=o-i*l,d=s-a*l;n=t,t=u,o=i,s=a,i=f,a=d}if(n!==he)throw new Error("invert: does not exist");return fe(o,e)}function oc(r,e,t){if(!r.eql(r.sqr(e),t))throw new Error("Cannot find square root")}function $f(r,e){let t=(r.ORDER+he)/Ff,n=r.pow(e,t);return oc(r,n,e),n}function fg(r,e){let t=(r.ORDER-Uf)/Kf,n=r.mul(e,Jt),o=r.pow(n,t),s=r.mul(e,o),i=r.mul(r.mul(s,Jt),o),a=r.mul(s,r.sub(i,r.ONE));return oc(r,a,e),a}function dg(r){let e=Fr(r),t=Vf(r),n=t(e,e.neg(e.ONE)),o=t(e,n),s=t(e,e.neg(n)),i=(r+lg)/qf;return(a,c)=>{let l=a.pow(c,i),u=a.mul(l,n),f=a.mul(l,o),d=a.mul(l,s),h=a.eql(a.sqr(u),c),p=a.eql(a.sqr(f),c);l=a.cmov(l,u,h),u=a.cmov(d,f,p);let y=a.eql(a.sqr(u),c),m=a.cmov(l,u,y);return oc(a,m,c),m}}function Vf(r){if(r<Bf)throw new Error("sqrt is not defined for small field");let e=r-he,t=0;for(;e%Jt===De;)e/=Jt,t++;let n=Jt,o=Fr(r);for(;Mf(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return $f;let s=o.pow(n,e),i=(e+he)/Jt;return function(c,l){if(c.is0(l))return l;if(Mf(c,l)!==1)throw new Error("Cannot find square root");let u=t,f=c.mul(c.ONE,s),d=c.pow(l,e),h=c.pow(l,i);for(;!c.eql(d,c.ONE);){if(c.is0(d))return c.ZERO;let p=1,y=c.sqr(d);for(;!c.eql(y,c.ONE);)if(p++,y=c.sqr(y),p===u)throw new Error("Cannot find square root");let m=he<<BigInt(u-p-1),g=c.pow(f,m);u=p,f=c.sqr(g),d=c.mul(d,f),h=c.mul(h,g)}return h}}function hg(r){return r%Ff===Bf?$f:r%Kf===Uf?fg:r%qf===ug?dg(r):Vf(r)}var zf=(r,e)=>(fe(r,e)&he)===he,pg=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function sc(r){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=pg.reduce((n,o)=>(n[o]="function",n),e);return Ft(r,t),r}function mg(r,e,t){if(t<De)throw new Error("invalid exponent, negatives unsupported");if(t===De)return r.ONE;if(t===he)return e;let n=r.ONE,o=e;for(;t>De;)t&he&&(n=r.mul(n,o)),o=r.sqr(o),t>>=he;return n}function Nn(r,e,t=!1){let n=new Array(e.length).fill(t?r.ZERO:void 0),o=e.reduce((i,a,c)=>r.is0(a)?i:(n[c]=i,r.mul(i,a)),r.ONE),s=r.inv(o);return e.reduceRight((i,a,c)=>r.is0(a)?i:(n[c]=r.mul(i,n[c]),r.mul(i,a)),s),n}function Mf(r,e){let t=(r.ORDER-he)/Jt,n=r.pow(e,t),o=r.eql(n,r.ONE),s=r.eql(n,r.ZERO),i=r.eql(n,r.neg(r.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function gg(r,e){e!==void 0&&at(e);let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}var nc=class{ORDER;BITS;BYTES;isLE;ZERO=De;ONE=he;_lengths;_sqrt;_mod;constructor(e,t={}){if(e<=De)throw new Error("invalid field: expected ORDER > 0, got "+e);let n;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(n=t.BITS),typeof t.sqrt=="function"&&(this.sqrt=t.sqrt),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=t.allowedLengths?.slice()),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:o,nByteLength:s}=gg(e,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return fe(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return De<=e&&e<this.ORDER}is0(e){return e===De}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&he)===he}neg(e){return fe(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return fe(e*e,this.ORDER)}add(e,t){return fe(e+t,this.ORDER)}sub(e,t){return fe(e-t,this.ORDER)}mul(e,t){return fe(e*t,this.ORDER)}pow(e,t){return mg(this,e,t)}div(e,t){return fe(e*Nf(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return Nf(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=hg(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?tc(e,this.BYTES):es(e,this.BYTES)}fromBytes(e,t=!1){V(e);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(!n.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let l=new Uint8Array(o);l.set(e,s?0:l.length-e.length),e=l}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?Qt(e):Mr(e);if(a&&(c=fe(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Nn(this,e)}cmov(e,t,n){return n?t:e}};function Fr(r,e={}){return new nc(r,e)}function Hf(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let e=r.toString(2).length;return Math.ceil(e/8)}function ic(r){let e=Hf(r);return e+Math.ceil(e/2)}function ac(r,e,t=!1){V(r);let n=r.length,o=Hf(e),s=ic(e);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=t?Qt(r):Mr(r),a=fe(i,e-he)+he;return t?tc(a,o):es(a,o)}var Ur=BigInt(0),er=BigInt(1);function Mn(r,e){let t=e.negate();return r?t:e}function tr(r,e){let t=Nn(r.Fp,e.map(n=>n.Z));return e.map((n,o)=>r.fromAffine(n.toAffine(t[o])))}function Xf(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function cc(r,e){Xf(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1),o=2**r,s=On(r),i=BigInt(r);return{windows:t,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function Wf(r,e,t){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=t,a=Number(r&o),c=r>>i;a>n&&(a-=s,c+=er);let l=e*n,u=l+Math.abs(a)-1,f=a===0,d=a<0,h=e%2!==0;return{nextN:c,offset:u,isZero:f,isNeg:d,isNegF:h,offsetF:l}}var lc=new WeakMap,jf=new WeakMap;function uc(r){return jf.get(r)||1}function Gf(r){if(r!==Ur)throw new Error("invalid wNAF")}var Kr=class{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let o=e;for(;t>Ur;)t&er&&(n=n.add(o)),o=o.double(),t>>=er;return n}precomputeWindow(e,t){let{windows:n,windowSize:o}=cc(t,this.bits),s=[],i=e,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let l=1;l<o;l++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=cc(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:f,isNegF:d,offsetF:h}=Wf(n,a,i);n=c,u?s=s.add(Mn(d,t[h])):o=o.add(Mn(f,t[l]))}return Gf(n),{p:o,f:s}}wNAFUnsafe(e,t,n,o=this.ZERO){let s=cc(e,this.bits);for(let i=0;i<s.windows&&n!==Ur;i++){let{nextN:a,offset:c,isZero:l,isNeg:u}=Wf(n,i,s);if(n=a,!l){let f=t[c];o=o.add(u?f.negate():f)}}return Gf(n),o}getPrecomputes(e,t,n){let o=lc.get(t);return o||(o=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(o=n(o)),lc.set(t,o))),o}cached(e,t,n){let o=uc(e);return this.wNAF(o,this.getPrecomputes(o,e,n),t)}unsafe(e,t,n,o){let s=uc(e);return s===1?this._unsafeLadder(e,t,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),t,o)}createCache(e,t){Xf(t,this.bits),jf.set(e,t),lc.delete(e)}hasCache(e){return uc(e)!==1}};function Zf(r,e,t,n){let o=e,s=r.ZERO,i=r.ZERO;for(;t>Ur||n>Ur;)t&er&&(s=s.add(o)),n&er&&(i=i.add(o)),o=o.double(),t>>=er,n>>=er;return{p1:s,p2:i}}function Yf(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return sc(e),e}else return Fr(r,{isLE:t})}function rs(r,e,t={},n){if(n===void 0&&(n=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let l=e[c];if(!(typeof l=="bigint"&&l>Ur))throw new Error(`CURVE.${c} must be positive bigint`)}let o=Yf(e.p,t.Fp,n),s=Yf(e.n,t.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}function ns(r,e){return function(n){let o=r(n);return{secretKey:o,publicKey:e(o)}}}var Ut=BigInt(0),pe=BigInt(1),fc=BigInt(2),yg=BigInt(8);function bg(r,e,t,n){let o=r.sqr(t),s=r.sqr(n),i=r.add(r.mul(e.a,o),s),a=r.add(r.ONE,r.mul(e.d,r.mul(o,s)));return r.eql(i,a)}function Qf(r,e={}){let t=rs("edwards",r,e,e.FpFnLE),{Fp:n,Fn:o}=t,s=t.CURVE,{h:i}=s;Ft(e,{},{uvRatio:"function"});let a=fc<<BigInt(o.BYTES*8)-pe,c=m=>n.create(m),l=e.uvRatio||((m,g)=>{try{return{isValid:!0,value:n.sqrt(n.div(m,g))}}catch{return{isValid:!1,value:Ut}}});if(!bg(n,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function u(m,g,_=!1){let E=_?pe:Ut;return Rn("coordinate "+m,g,E,a),g}function f(m){if(!(m instanceof p))throw new Error("EdwardsPoint expected")}let d=Br((m,g)=>{let{X:_,Y:E,Z:C}=m,O=m.is0();g==null&&(g=O?yg:n.inv(C));let $=c(_*g),q=c(E*g),S=n.mul(C,g);if(O)return{x:Ut,y:pe};if(S!==pe)throw new Error("invZ was invalid");return{x:$,y:q}}),h=Br(m=>{let{a:g,d:_}=s;if(m.is0())throw new Error("bad point: ZERO");let{X:E,Y:C,Z:O,T:$}=m,q=c(E*E),S=c(C*C),v=c(O*O),B=c(v*v),z=c(q*g),k=c(v*c(z+S)),w=c(B+c(_*c(q*S)));if(k!==w)throw new Error("bad point: equation left != right (1)");let x=c(E*C),b=c(O*$);if(x!==b)throw new Error("bad point: equation left != right (2)");return!0});class p{static BASE=new p(s.Gx,s.Gy,pe,c(s.Gx*s.Gy));static ZERO=new p(Ut,pe,pe,Ut);static Fp=n;static Fn=o;X;Y;Z;T;constructor(g,_,E,C){this.X=u("x",g),this.Y=u("y",_),this.Z=u("z",E,!0),this.T=u("t",C),Object.freeze(this)}static CURVE(){return s}static fromAffine(g){if(g instanceof p)throw new Error("extended point not allowed");let{x:_,y:E}=g||{};return u("x",_),u("y",E),new p(_,E,pe,c(_*E))}static fromBytes(g,_=!1){let E=n.BYTES,{a:C,d:O}=s;g=ts(V(g,E,"point")),Et(_,"zip215");let $=ts(g),q=g[E-1];$[E-1]=q&-129;let S=Qt($),v=_?a:n.ORDER;Rn("point.y",S,Ut,v);let B=c(S*S),z=c(B-pe),k=c(O*B-C),{isValid:w,value:x}=l(z,k);if(!w)throw new Error("bad point: invalid y coordinate");let b=(x&pe)===pe,A=(q&128)!==0;if(!_&&x===Ut&&A)throw new Error("bad point: x=0 and x_0=1");return A!==b&&(x=c(-x)),p.fromAffine({x,y:S})}static fromHex(g,_=!1){return p.fromBytes(wt(g),_)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,_=!0){return y.createCache(this,g),_||this.multiply(fc),this}assertValidity(){h(this)}equals(g){f(g);let{X:_,Y:E,Z:C}=this,{X:O,Y:$,Z:q}=g,S=c(_*q),v=c(O*C),B=c(E*q),z=c($*C);return S===v&&B===z}is0(){return this.equals(p.ZERO)}negate(){return new p(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:g}=s,{X:_,Y:E,Z:C}=this,O=c(_*_),$=c(E*E),q=c(fc*c(C*C)),S=c(g*O),v=_+E,B=c(c(v*v)-O-$),z=S+$,k=z-q,w=S-$,x=c(B*k),b=c(z*w),A=c(B*w),T=c(k*z);return new p(x,b,T,A)}add(g){f(g);let{a:_,d:E}=s,{X:C,Y:O,Z:$,T:q}=this,{X:S,Y:v,Z:B,T:z}=g,k=c(C*S),w=c(O*v),x=c(q*E*z),b=c($*B),A=c((C+O)*(S+v)-k-w),T=b-x,D=b+x,R=c(w-_*k),P=c(A*T),M=c(D*R),K=c(A*R),se=c(T*D);return new p(P,M,se,K)}subtract(g){return this.add(g.negate())}multiply(g){if(!o.isValidNot0(g))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:_,f:E}=y.cached(this,g,C=>tr(p,C));return tr(p,[_,E])[0]}multiplyUnsafe(g,_=p.ZERO){if(!o.isValid(g))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return g===Ut?p.ZERO:this.is0()||g===pe?this:y.unsafe(this,g,E=>tr(p,E),_)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return y.unsafe(this,s.n).is0()}toAffine(g){return d(this,g)}clearCofactor(){return i===pe?this:this.multiplyUnsafe(i)}toBytes(){let{x:g,y:_}=this.toAffine(),E=n.toBytes(_);return E[E.length-1]|=g&pe?128:0,E}toHex(){return bt(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let y=new Kr(p,o.BITS);return p.BASE.precompute(8),p}function Jf(r,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');Ft(t,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=t,{BASE:o,Fp:s,Fn:i}=r,a=t.randomBytes||Ot,c=t.adjustScalarBytes||(S=>S),l=t.domain||((S,v,B)=>{if(Et(B,"phflag"),v.length||B)throw new Error("Contexts/pre-hash are not supported");return S});function u(S){return i.create(Qt(S))}function f(S){let v=E.secretKey;V(S,E.secretKey,"secretKey");let B=V(e(S),2*v,"hashedSecretKey"),z=c(B.slice(0,v)),k=B.slice(v,2*v),w=u(z);return{head:z,prefix:k,scalar:w}}function d(S){let{head:v,prefix:B,scalar:z}=f(S),k=o.multiply(z),w=k.toBytes();return{head:v,prefix:B,scalar:z,point:k,pointBytes:w}}function h(S){return d(S).pointBytes}function p(S=Uint8Array.of(),...v){let B=Fe(...v);return u(e(l(B,V(S,void 0,"context"),!!n)))}function y(S,v,B={}){S=V(S,void 0,"message"),n&&(S=n(S));let{prefix:z,scalar:k,pointBytes:w}=d(v),x=p(B.context,z,S),b=o.multiply(x).toBytes(),A=p(B.context,b,w,S),T=i.create(x+A*k);if(!i.isValid(T))throw new Error("sign failed: invalid s");let D=Fe(b,i.toBytes(T));return V(D,E.signature,"result")}let m={zip215:!0};function g(S,v,B,z=m){let{context:k,zip215:w}=z,x=E.signature;S=V(S,x,"signature"),v=V(v,void 0,"message"),B=V(B,E.publicKey,"publicKey"),w!==void 0&&Et(w,"zip215"),n&&(v=n(v));let b=x/2,A=S.subarray(0,b),T=Qt(S.subarray(b,x)),D,R,P;try{D=r.fromBytes(B,w),R=r.fromBytes(A,w),P=o.multiplyUnsafe(T)}catch{return!1}if(!w&&D.isSmallOrder())return!1;let M=p(k,R.toBytes(),D.toBytes(),v);return R.add(D.multiplyUnsafe(M)).subtract(P).clearCofactor().is0()}let _=s.BYTES,E={secretKey:_,publicKey:_,signature:2*_,seed:_};function C(S=a(E.seed)){return V(S,E.seed,"seed")}function O(S){return Xt(S)&&S.length===i.BYTES}function $(S,v){try{return!!r.fromBytes(S,v)}catch{return!1}}let q={getExtendedPublicKey:d,randomSecretKey:C,isValidSecretKey:O,isValidPublicKey:$,toMontgomery(S){let{y:v}=r.fromBytes(S),B=E.publicKey,z=B===32;if(!z&&B!==57)throw new Error("only defined for 25519 and 448");let k=z?s.div(pe+v,pe-v):s.div(v-pe,v+pe);return s.toBytes(k)},toMontgomerySecret(S){let v=E.secretKey;V(S,v);let B=e(S.subarray(0,v));return c(B).subarray(0,v)}};return Object.freeze({keygen:ns(C,h),getPublicKey:h,sign:y,verify:g,utils:q,Point:r,lengths:E})}var wg=BigInt(1),ed=BigInt(2);var xg=BigInt(5),Eg=BigInt(8),dc=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),vg={p:dc,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Eg,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Sg(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=dc,a=r*r%s*r%s,c=ne(a,ed,s)*a%s,l=ne(c,wg,s)*r%s,u=ne(l,xg,s)*l%s,f=ne(u,e,s)*u%s,d=ne(f,t,s)*f%s,h=ne(d,n,s)*d%s,p=ne(h,o,s)*h%s,y=ne(p,o,s)*h%s,m=ne(y,e,s)*u%s;return{pow_p_5_8:ne(m,ed,s)*r%s,b2:a}}function _g(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var td=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Ag(r,e){let t=dc,n=fe(e*e*e,t),o=fe(n*n*e,t),s=Sg(r*o).pow_p_5_8,i=fe(r*n*s,t),a=fe(e*i*i,t),c=i,l=fe(i*td,t),u=a===r,f=a===fe(-r,t),d=a===fe(-r*td,t);return u&&(i=c),(f||d)&&(i=l),zf(i,t)&&(i=fe(-i,t)),{isValid:u||f,value:i}}var Cg=Qf(vg,{uvRatio:Ag});function Ig(r){return Jf(Cg,Df,Object.assign({adjustScalarBytes:_g},r))}var Bn=Ig({});var Fn=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},Un=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},os=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var rd={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new os("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/blob/main/packages/crypto/README.md#web-crypto-api");return e}};var Ue=rd;var ss=32,Kn=64,hc=32;var qr,nd=(async()=>{try{return await Ue.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function od(){let r=Bn.utils.randomSecretKey(),e=Bn.getPublicKey(r);return{privateKey:kg(r,e),publicKey:e}}async function Tg(r,e){let t;r.length===Kn?t=r.subarray(0,32):t=r;let n={crv:"Ed25519",kty:"OKP",x:U(r.subarray(32),"base64url"),d:U(t,"base64url"),ext:!0,key_ops:["sign"]},o=await Ue.get().subtle.importKey("jwk",n,{name:"Ed25519"},!0,["sign"]),s=await Ue.get().subtle.sign({name:"Ed25519"},o,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(s,0,s.byteLength)}function Lg(r,e){let t=r.subarray(0,hc);return Bn.sign(e instanceof Uint8Array?e:e.subarray(),t)}async function sd(r,e){return qr==null&&(qr=await nd),qr?Tg(r,e):Lg(r,e)}async function Pg(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await Ue.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await Ue.get().subtle.verify({name:"Ed25519"},n,e,t instanceof Uint8Array?t:t.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function Dg(r,e,t){return Bn.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function id(r,e,t){return qr==null&&(qr=await nd),qr?Pg(r,e,t):Dg(r,e,t)}function kg(r,e){let t=new Uint8Array(Kn);for(let n=0;n<hc;n++)t[n]=r[n],t[hc+n]=e[n];return t}function $r(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var qn=class{type="Ed25519";raw;constructor(e){this.raw=as(e,ss)}toMultihash(){return je.digest(We(this))}toCID(){return ue.createV1(114,this.toMultihash())}toString(){return J.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Z(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let o=id(this.raw,t,e);return $r(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}},is=class{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=as(e,Kn),this.publicKey=new qn(t)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Z(this.raw,e.raw)}sign(e,t){t?.signal?.throwIfAborted();let n=sd(this.raw,e);return $r(n)?n.then(o=>(t?.signal?.throwIfAborted(),o)):(t?.signal?.throwIfAborted(),n)}};function pc(r){return r=as(r,ss),new qn(r)}async function cd(){let{privateKey:r,publicKey:e}=od();return new is(r,e)}function as(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new I(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var Rg=Math.pow(2,7),Og=Math.pow(2,14),Ng=Math.pow(2,21),mc=Math.pow(2,28),gc=Math.pow(2,35),yc=Math.pow(2,42),bc=Math.pow(2,49),Y=128,_e=127;function me(r){if(r<Rg)return 1;if(r<Og)return 2;if(r<Ng)return 3;if(r<mc)return 4;if(r<gc)return 5;if(r<yc)return 6;if(r<bc)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Vr(r,e,t=0){switch(me(r)){case 8:e[t++]=r&255|Y,r/=128;case 7:e[t++]=r&255|Y,r/=128;case 6:e[t++]=r&255|Y,r/=128;case 5:e[t++]=r&255|Y,r/=128;case 4:e[t++]=r&255|Y,r>>>=7;case 3:e[t++]=r&255|Y,r>>>=7;case 2:e[t++]=r&255|Y,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function Mg(r,e,t=0){switch(me(r)){case 8:e.set(t++,r&255|Y),r/=128;case 7:e.set(t++,r&255|Y),r/=128;case 6:e.set(t++,r&255|Y),r/=128;case 5:e.set(t++,r&255|Y),r/=128;case 4:e.set(t++,r&255|Y),r>>>=7;case 3:e.set(t++,r&255|Y),r>>>=7;case 2:e.set(t++,r&255|Y),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function wc(r,e){let t=r[e],n=0;if(n+=t&_e,t<Y||(t=r[e+1],n+=(t&_e)<<7,t<Y)||(t=r[e+2],n+=(t&_e)<<14,t<Y)||(t=r[e+3],n+=(t&_e)<<21,t<Y)||(t=r[e+4],n+=(t&_e)*mc,t<Y)||(t=r[e+5],n+=(t&_e)*gc,t<Y)||(t=r[e+6],n+=(t&_e)*yc,t<Y)||(t=r[e+7],n+=(t&_e)*bc,t<Y))return n;throw new RangeError("Could not decode varint")}function Bg(r,e){let t=r.get(e),n=0;if(n+=t&_e,t<Y||(t=r.get(e+1),n+=(t&_e)<<7,t<Y)||(t=r.get(e+2),n+=(t&_e)<<14,t<Y)||(t=r.get(e+3),n+=(t&_e)<<21,t<Y)||(t=r.get(e+4),n+=(t&_e)*mc,t<Y)||(t=r.get(e+5),n+=(t&_e)*gc,t<Y)||(t=r.get(e+6),n+=(t&_e)*yc,t<Y)||(t=r.get(e+7),n+=(t&_e)*bc,t<Y))return n;throw new RangeError("Could not decode varint")}function Kt(r,e,t=0){return e==null&&(e=Se(me(r))),e instanceof Uint8Array?Vr(r,e,t):Mg(r,e,t)}function rr(r,e=0){return r instanceof Uint8Array?wc(r,e):Bg(r,e)}var xc=new Float32Array([-0]),qt=new Uint8Array(xc.buffer);function ld(r,e,t){xc[0]=r,e[t]=qt[0],e[t+1]=qt[1],e[t+2]=qt[2],e[t+3]=qt[3]}function ud(r,e){return qt[0]=r[e],qt[1]=r[e+1],qt[2]=r[e+2],qt[3]=r[e+3],xc[0]}var Ec=new Float64Array([-0]),Ae=new Uint8Array(Ec.buffer);function fd(r,e,t){Ec[0]=r,e[t]=Ae[0],e[t+1]=Ae[1],e[t+2]=Ae[2],e[t+3]=Ae[3],e[t+4]=Ae[4],e[t+5]=Ae[5],e[t+6]=Ae[6],e[t+7]=Ae[7]}function dd(r,e){return Ae[0]=r[e],Ae[1]=r[e+1],Ae[2]=r[e+2],Ae[3]=r[e+3],Ae[4]=r[e+4],Ae[5]=r[e+5],Ae[6]=r[e+6],Ae[7]=r[e+7],Ec[0]}var Fg=BigInt(Number.MAX_SAFE_INTEGER),Ug=BigInt(Number.MIN_SAFE_INTEGER),qe=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return nr;if(e<Fg&&e>Ug)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>hd&&(o=0n,++n>hd&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return nr;let t=e<0;t&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):nr}},nr=new qe(0,0);nr.toBigInt=function(){return 0n};nr.zzEncode=nr.zzDecode=function(){return this};nr.length=function(){return 1};var hd=4294967296n;function pd(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function md(r,e,t){if(t-e<1)return"";let o,s=[],i=0,a;for(;e<t;)a=r[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function vc(r,e,t){let n=t,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function et(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function cs(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var Sc=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,et(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw et(this,4);return cs(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw et(this,4);return cs(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw et(this,4);let e=ud(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw et(this,4);let e=dd(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw et(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return md(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw et(this,e);this.pos+=e}else do if(this.pos>=this.len)throw et(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new qe(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw et(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw et(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw et(this,8);let e=cs(this.buf,this.pos+=4),t=cs(this.buf,this.pos+=4);return new qe(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=wc(this.buf,this.pos);return this.pos+=me(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function Vn(r){return new Sc(r instanceof Uint8Array?r:r.subarray())}function ke(r,e,t){let n=Vn(r);return e.decode(n,void 0,t)}function _c(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return Se(i);o+i>e&&(n=Se(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var or=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function Ac(){}var Ic=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},Kg=_c();function qg(r){return globalThis.Buffer!=null?Se(r):Kg(r)}var Hn=class{len;head;tail;states;constructor(){this.len=0,this.head=new or(Ac,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new or(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Tc((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(ls,10,qe.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=qe.fromBigInt(e);return this._push(ls,t.length(),t)}uint64Number(e){return this._push(Vr,me(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=qe.fromBigInt(e).zzEncode();return this._push(ls,t.length(),t)}sint64Number(e){let t=qe.fromNumber(e).zzEncode();return this._push(ls,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Cc,1,e?1:0)}fixed32(e){return this._push(zn,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=qe.fromBigInt(e);return this._push(zn,4,t.lo)._push(zn,4,t.hi)}fixed64Number(e){let t=qe.fromNumber(e);return this._push(zn,4,t.lo)._push(zn,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(ld,4,e)}double(e){return this._push(fd,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(Cc,1,0):this.uint32(t)._push(Vg,t,e)}string(e){let t=pd(e);return t!==0?this.uint32(t)._push(vc,t,e):this._push(Cc,1,0)}fork(){return this.states=new Ic(this),this.head=this.tail=new or(Ac,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new or(Ac,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=qg(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function Cc(r,e,t){e[t]=r&255}function $g(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var Tc=class extends or{next;constructor(e,t){super($g,e,t),this.next=void 0}};function ls(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function zn(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function Vg(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(Hn.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(zg,e,r),this},Hn.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(Hg,e,r),this});function zg(r,e,t){e.set(r,t)}function Hg(r,e,t){r.length<40?vc(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(L(r),t)}function Lc(){return new Hn}function Re(r,e){let t=Lc();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}function*Oe(r,e,t){let n=Vn(r);yield*e.stream(n,void 0,"$",t)}var us={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function fs(r,e,t,n,o){return{name:r,type:e,encode:t,decode:n,stream:o}}function Pc(r){function e(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let t=function(i,a){let c=e(i);a.int32(c)},n=function(i){let a=i.int32();return e(a)},o=function*(i){let a=i.int32();yield e(a)};return fs("enum",us.VARINT,t,n,o)}function Ne(r,e,t){return fs("message",us.LENGTH_DELIMITED,r,e,t)}var Ge=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},Wn=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var oe;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(oe||(oe={}));var Dc;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(Dc||(Dc={}));(function(r){r.codec=()=>Pc(Dc)})(oe||(oe={}));var lt;(function(r){let e;r.codec=()=>(e==null&&(e=Ne((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),oe.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.Type=oe.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:oe.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return Re(s,r.codec())}r.encode=t;function n(s,i){return ke(s,r.codec(),i)}r.decode=n;function o(s,i){return Oe(s,r.codec(),i)}r.stream=o})(lt||(lt={}));var kc;(function(r){let e;r.codec=()=>(e==null&&(e=Ne((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),oe.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.Type=oe.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:oe.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return Re(s,r.codec())}r.encode=t;function n(s,i){return ke(s,r.codec(),i)}r.decode=n;function o(s,i){return Oe(s,r.codec(),i)}r.stream=o})(kc||(kc={}));function zr(r){if(isNaN(r)||r<=0)throw new I("random bytes length must be a Number bigger than 0");return Ot(r)}var Yn={};Be(Yn,{MAX_RSA_KEY_SIZE:()=>Rc,generateRSAKeyPair:()=>$c,jwkToJWKKeyPair:()=>Ed,jwkToPkcs1:()=>Xg,jwkToPkix:()=>Bc,jwkToRSAPrivateKey:()=>qc,pkcs1MessageToJwk:()=>Nc,pkcs1MessageToRSAPrivateKey:()=>Fc,pkcs1ToJwk:()=>Yg,pkcs1ToRSAPrivateKey:()=>xd,pkixMessageToJwk:()=>Mc,pkixMessageToRSAPublicKey:()=>Kc,pkixToJwk:()=>jg,pkixToRSAPublicKey:()=>Uc});var Hr=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=Yn.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return ue.createV1(114,this._multihash)}toString(){return J.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Z(this.raw,e.raw)}verify(e,t,n){return wd(this.jwk,t,e,n)}},Gn=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=Yn.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Z(this.raw,e.raw)}sign(e,t){return bd(this.jwk,e,t)}};var Rc=8192,Oc=18,Wg=1062,Gg=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function Yg(r){let e=mt(r);return Nc(e)}function Nc(r){return{n:U(r[1],"base64url"),e:U(r[2],"base64url"),d:U(r[3],"base64url"),p:U(r[4],"base64url"),q:U(r[5],"base64url"),dp:U(r[6],"base64url"),dq:U(r[7],"base64url"),qi:U(r[8],"base64url"),kty:"RSA"}}function Xg(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new I("JWK was missing components");return Qe([Pe(Uint8Array.from([0])),Pe(L(r.n,"base64url")),Pe(L(r.e,"base64url")),Pe(L(r.d,"base64url")),Pe(L(r.p,"base64url")),Pe(L(r.q,"base64url")),Pe(L(r.dp,"base64url")),Pe(L(r.dq,"base64url")),Pe(L(r.qi,"base64url"))]).subarray()}function jg(r){let e=mt(r,{offset:0});return Mc(e)}function Mc(r){let e=mt(r[1],{offset:0});return{kty:"RSA",n:U(e[0],"base64url"),e:U(e[1],"base64url")}}function Bc(r){if(r.n==null||r.e==null)throw new I("JWK was missing components");return Qe([Gg,Tn(Qe([Pe(L(r.n,"base64url")),Pe(L(r.e,"base64url"))]))]).subarray()}function xd(r){let e=mt(r);return Fc(e)}function Fc(r){let e=Nc(r);return qc(e)}function Uc(r,e){if(r.byteLength>=Wg)throw new Cr("Key size is too large");let t=mt(r,{offset:0});return Kc(t,r,e)}function Kc(r,e,t){let n=Mc(r);if(t==null){let o=Nr(lt.encode({Type:oe.RSA,Data:e}));t=it(Oc,o)}return new Hr(n,t)}function qc(r){if(Sd(r)>Rc)throw new I("Key size is too large");let e=Ed(r),t=Nr(lt.encode({Type:oe.RSA,Data:Bc(e.publicKey)})),n=it(Oc,t);return new Gn(e.privateKey,new Hr(e.publicKey,n))}async function $c(r){if(r>Rc)throw new I("Key size is too large");let e=await vd(r),t=Nr(lt.encode({Type:oe.RSA,Data:Bc(e.publicKey)})),n=it(Oc,t);return new Gn(e.privateKey,new Hr(e.publicKey,n))}function Ed(r){if(r==null)throw new I("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function vd(r,e){let t=await Ue.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);e?.signal?.throwIfAborted();let n=await Zg(t,e);return{privateKey:n[0],publicKey:n[1]}}async function bd(r,e,t){let n=await Ue.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let o=await Ue.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,e instanceof Uint8Array?e:e.subarray());return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function wd(r,e,t,n){let o=await Ue.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let s=await Ue.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,e,t instanceof Uint8Array?t:t.subarray());return n?.signal?.throwIfAborted(),s}async function Zg(r,e){if(r.privateKey==null||r.publicKey==null)throw new I("Private and public key are required");let t=await Promise.all([Ue.get().subtle.exportKey("jwk",r.privateKey),Ue.get().subtle.exportKey("jwk",r.publicKey)]);return e?.signal?.throwIfAborted(),t}function Sd(r){if(r.kty!=="RSA")throw new I("invalid key type");if(r.n==null)throw new I("invalid key modulus");return L(r.n,"base64url").length*8}var ds=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if(jo(e),V(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(t.length>n?e.create().update(t).digest():t);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),yt(o)}update(e){return Or(this),this.iHash.update(e),this}digestInto(e){Or(this),V(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Vc=(r,e,t)=>new ds(r,e).update(t).digest();Vc.create=(r,e)=>new ds(r,e);var _d=(r,e)=>(r+(r>=0?e:-e)/Ad)/e;function Qg(r,e,t){let[[n,o],[s,i]]=e,a=_d(i*r,t),c=_d(-o*r,t),l=r-a*n-c*s,u=-a*o-c*i,f=l<vt,d=u<vt;f&&(l=-l),d&&(u=-u);let h=On(Math.ceil(rc(t)/2))+Wr;if(l<vt||l>=h||u<vt||u>=h)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:f,k1:l,k2neg:d,k2:u}}function Hc(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function zc(r,e){let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return Et(t.lowS,"lowS"),Et(t.prehash,"prehash"),t.format!==void 0&&Hc(t.format),t}var Wc=class extends Error{constructor(e=""){super(e)}},$t={Err:Wc,_tlv:{encode:(r,e)=>{let{Err:t}=$t;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,o=kn(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let s=n>127?kn(o.length/2|128):"";return kn(r)+s+o+e},decode(r,e){let{Err:t}=$t,n=0;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let o=e[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let l=e.subarray(n,n+c);if(l.length!==c)throw new t("tlv.decode: length bytes not complete");if(l[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let u of l)i=i<<8|u;if(n+=c,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(r){let{Err:e}=$t;if(r<vt)throw new e("integer: negative integers are not allowed");let t=kn(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(r){let{Err:e}=$t;if(r[0]&128)throw new e("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Mr(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=$t,o=V(r,void 0,"signature"),{v:s,l:i}=n.decode(48,o);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:l,l:u}=n.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(l)}},hexFromSig(r){let{_tlv:e,_int:t}=$t,n=e.encode(2,t.encode(r.r)),o=e.encode(2,t.encode(r.s)),s=n+o;return e.encode(48,s)}},vt=BigInt(0),Wr=BigInt(1),Ad=BigInt(2),hs=BigInt(3),Jg=BigInt(4);function Cd(r,e={}){let t=rs("weierstrass",r,e),{Fp:n,Fn:o}=t,s=t.CURVE,{h:i,n:a}=s;Ft(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c}=e;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=Td(n,o);function u(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(k,w,x){let{x:b,y:A}=w.toAffine(),T=n.toBytes(b);if(Et(x,"isCompressed"),x){u();let D=!n.isOdd(A);return Fe(Id(D),T)}else return Fe(Uint8Array.of(4),T,n.toBytes(A))}function d(k){V(k,void 0,"Point");let{publicKey:w,publicKeyUncompressed:x}=l,b=k.length,A=k[0],T=k.subarray(1);if(b===w&&(A===2||A===3)){let D=n.fromBytes(T);if(!n.isValid(D))throw new Error("bad point: is not on curve, wrong x");let R=y(D),P;try{P=n.sqrt(R)}catch(se){let re=se instanceof Error?": "+se.message:"";throw new Error("bad point: is not on curve, sqrt error"+re)}u();let M=n.isOdd(P);return(A&1)===1!==M&&(P=n.neg(P)),{x:D,y:P}}else if(b===x&&A===4){let D=n.BYTES,R=n.fromBytes(T.subarray(0,D)),P=n.fromBytes(T.subarray(D,D*2));if(!m(R,P))throw new Error("bad point: is not on curve");return{x:R,y:P}}else throw new Error(`bad point: got length ${b}, expected compressed=${w} or uncompressed=${x}`)}let h=e.toBytes||f,p=e.fromBytes||d;function y(k){let w=n.sqr(k),x=n.mul(w,k);return n.add(n.add(x,n.mul(k,s.a)),s.b)}function m(k,w){let x=n.sqr(w),b=y(k);return n.eql(x,b)}if(!m(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let g=n.mul(n.pow(s.a,hs),Jg),_=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(g,_)))throw new Error("bad curve params: a or b");function E(k,w,x=!1){if(!n.isValid(w)||x&&n.is0(w))throw new Error(`bad point coordinate ${k}`);return w}function C(k){if(!(k instanceof v))throw new Error("Weierstrass Point expected")}function O(k){if(!c||!c.basises)throw new Error("no endo");return Qg(k,c.basises,o.ORDER)}let $=Br((k,w)=>{let{X:x,Y:b,Z:A}=k;if(n.eql(A,n.ONE))return{x,y:b};let T=k.is0();w==null&&(w=T?n.ONE:n.inv(A));let D=n.mul(x,w),R=n.mul(b,w),P=n.mul(A,w);if(T)return{x:n.ZERO,y:n.ZERO};if(!n.eql(P,n.ONE))throw new Error("invZ was invalid");return{x:D,y:R}}),q=Br(k=>{if(k.is0()){if(e.allowInfinityPoint&&!n.is0(k.Y))return;throw new Error("bad point: ZERO")}let{x:w,y:x}=k.toAffine();if(!n.isValid(w)||!n.isValid(x))throw new Error("bad point: x or y not field elements");if(!m(w,x))throw new Error("bad point: equation left != right");if(!k.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function S(k,w,x,b,A){return x=new v(n.mul(x.X,k),x.Y,x.Z),w=Mn(b,w),x=Mn(A,x),w.add(x)}class v{static BASE=new v(s.Gx,s.Gy,n.ONE);static ZERO=new v(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(w,x,b){this.X=E("x",w),this.Y=E("y",x,!0),this.Z=E("z",b),Object.freeze(this)}static CURVE(){return s}static fromAffine(w){let{x,y:b}=w||{};if(!w||!n.isValid(x)||!n.isValid(b))throw new Error("invalid affine point");if(w instanceof v)throw new Error("projective point not allowed");return n.is0(x)&&n.is0(b)?v.ZERO:new v(x,b,n.ONE)}static fromBytes(w){let x=v.fromAffine(p(V(w,void 0,"point")));return x.assertValidity(),x}static fromHex(w){return v.fromBytes(wt(w))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(w=8,x=!0){return z.createCache(this,w),x||this.multiply(hs),this}assertValidity(){q(this)}hasEvenY(){let{y:w}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(w)}equals(w){C(w);let{X:x,Y:b,Z:A}=this,{X:T,Y:D,Z:R}=w,P=n.eql(n.mul(x,R),n.mul(T,A)),M=n.eql(n.mul(b,R),n.mul(D,A));return P&&M}negate(){return new v(this.X,n.neg(this.Y),this.Z)}double(){let{a:w,b:x}=s,b=n.mul(x,hs),{X:A,Y:T,Z:D}=this,R=n.ZERO,P=n.ZERO,M=n.ZERO,K=n.mul(A,A),se=n.mul(T,T),re=n.mul(D,D),G=n.mul(A,T);return G=n.add(G,G),M=n.mul(A,D),M=n.add(M,M),R=n.mul(w,M),P=n.mul(b,re),P=n.add(R,P),R=n.sub(se,P),P=n.add(se,P),P=n.mul(R,P),R=n.mul(G,R),M=n.mul(b,M),re=n.mul(w,re),G=n.sub(K,re),G=n.mul(w,G),G=n.add(G,M),M=n.add(K,K),K=n.add(M,K),K=n.add(K,re),K=n.mul(K,G),P=n.add(P,K),re=n.mul(T,D),re=n.add(re,re),K=n.mul(re,G),R=n.sub(R,K),M=n.mul(re,se),M=n.add(M,M),M=n.add(M,M),new v(R,P,M)}add(w){C(w);let{X:x,Y:b,Z:A}=this,{X:T,Y:D,Z:R}=w,P=n.ZERO,M=n.ZERO,K=n.ZERO,se=s.a,re=n.mul(s.b,hs),G=n.mul(x,T),ie=n.mul(b,D),be=n.mul(A,R),st=n.add(x,b),ae=n.add(T,D);st=n.mul(st,ae),ae=n.add(G,ie),st=n.sub(st,ae),ae=n.add(x,A);let ve=n.add(T,R);return ae=n.mul(ae,ve),ve=n.add(G,be),ae=n.sub(ae,ve),ve=n.add(b,A),P=n.add(D,R),ve=n.mul(ve,P),P=n.add(ie,be),ve=n.sub(ve,P),K=n.mul(se,ae),P=n.mul(re,be),K=n.add(P,K),P=n.sub(ie,K),K=n.add(ie,K),M=n.mul(P,K),ie=n.add(G,G),ie=n.add(ie,G),be=n.mul(se,be),ae=n.mul(re,ae),ie=n.add(ie,be),be=n.sub(G,be),be=n.mul(se,be),ae=n.add(ae,be),G=n.mul(ie,ae),M=n.add(M,G),G=n.mul(ve,ae),P=n.mul(st,P),P=n.sub(P,G),G=n.mul(st,ie),K=n.mul(ve,K),K=n.add(K,G),new v(P,M,K)}subtract(w){return this.add(w.negate())}is0(){return this.equals(v.ZERO)}multiply(w){let{endo:x}=e;if(!o.isValidNot0(w))throw new Error("invalid scalar: out of range");let b,A,T=D=>z.cached(this,D,R=>tr(v,R));if(x){let{k1neg:D,k1:R,k2neg:P,k2:M}=O(w),{p:K,f:se}=T(R),{p:re,f:G}=T(M);A=se.add(G),b=S(x.beta,K,re,D,P)}else{let{p:D,f:R}=T(w);b=D,A=R}return tr(v,[b,A])[0]}multiplyUnsafe(w){let{endo:x}=e,b=this;if(!o.isValid(w))throw new Error("invalid scalar: out of range");if(w===vt||b.is0())return v.ZERO;if(w===Wr)return b;if(z.hasCache(this))return this.multiply(w);if(x){let{k1neg:A,k1:T,k2neg:D,k2:R}=O(w),{p1:P,p2:M}=Zf(v,b,T,R);return S(x.beta,P,M,A,D)}else return z.unsafe(b,w)}toAffine(w){return $(this,w)}isTorsionFree(){let{isTorsionFree:w}=e;return i===Wr?!0:w?w(v,this):z.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:w}=e;return i===Wr?this:w?w(v,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(w=!0){return Et(w,"isCompressed"),this.assertValidity(),h(v,this,w)}toHex(w=!0){return bt(this.toBytes(w))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let B=o.BITS,z=new Kr(v,e.endo?Math.ceil(B/2):B);return v.BASE.precompute(8),v}function Id(r){return Uint8Array.of(r?2:3)}function Td(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function e0(r,e={}){let{Fn:t}=r,n=e.randomBytes||Ot,o=Object.assign(Td(r.Fp,t),{seed:ic(t.ORDER)});function s(h){try{let p=t.fromBytes(h);return t.isValidNot0(p)}catch{return!1}}function i(h,p){let{publicKey:y,publicKeyUncompressed:m}=o;try{let g=h.length;return p===!0&&g!==y||p===!1&&g!==m?!1:!!r.fromBytes(h)}catch{return!1}}function a(h=n(o.seed)){return ac(V(h,o.seed,"seed"),t.ORDER)}function c(h,p=!0){return r.BASE.multiply(t.fromBytes(h)).toBytes(p)}function l(h){let{secretKey:p,publicKey:y,publicKeyUncompressed:m}=o;if(!Xt(h)||"_lengths"in t&&t._lengths||p===y)return;let g=V(h,void 0,"key").length;return g===y||g===m}function u(h,p,y=!0){if(l(h)===!0)throw new Error("first arg must be private key");if(l(p)===!1)throw new Error("second arg must be public key");let m=t.fromBytes(h);return r.fromBytes(p).multiply(m).toBytes(y)}let f={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},d=ns(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:d,Point:r,utils:f,lengths:o})}function Ld(r,e,t={}){jo(e),Ft(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let n=t.randomBytes||Ot,o=t.hmac||((x,b)=>Vc(e,x,b)),{Fp:s,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:u,getSharedSecret:f,utils:d,lengths:h}=e0(r,t),p={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},y=a*Ad<s.ORDER;function m(x){let b=a>>Wr;return x>b}function g(x,b){if(!i.isValidNot0(b))throw new Error(`invalid signature ${x}: out of range 1..Point.Fn.ORDER`);return b}function _(){if(y)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function E(x,b){Hc(b);let A=h.signature,T=b==="compact"?A:b==="recovered"?A+1:void 0;return V(x,T)}class C{r;s;recovery;constructor(b,A,T){if(this.r=g("r",b),this.s=g("s",A),T!=null){if(_(),![0,1,2,3].includes(T))throw new Error("invalid recovery id");this.recovery=T}Object.freeze(this)}static fromBytes(b,A=p.format){E(b,A);let T;if(A==="der"){let{r:M,s:K}=$t.toSig(V(b));return new C(M,K)}A==="recovered"&&(T=b[0],A="compact",b=b.subarray(1));let D=h.signature/2,R=b.subarray(0,D),P=b.subarray(D,D*2);return new C(i.fromBytes(R),i.fromBytes(P),T)}static fromHex(b,A){return this.fromBytes(wt(b),A)}assertRecovery(){let{recovery:b}=this;if(b==null)throw new Error("invalid recovery id: must be present");return b}addRecoveryBit(b){return new C(this.r,this.s,b)}recoverPublicKey(b){let{r:A,s:T}=this,D=this.assertRecovery(),R=D===2||D===3?A+a:A;if(!s.isValid(R))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let P=s.toBytes(R),M=r.fromBytes(Fe(Id((D&1)===0),P)),K=i.inv(R),se=$(V(b,void 0,"msgHash")),re=i.create(-se*K),G=i.create(T*K),ie=r.BASE.multiplyUnsafe(re).add(M.multiplyUnsafe(G));if(ie.is0())throw new Error("invalid recovery: point at infinify");return ie.assertValidity(),ie}hasHighS(){return m(this.s)}toBytes(b=p.format){if(Hc(b),b==="der")return wt($t.hexFromSig(this));let{r:A,s:T}=this,D=i.toBytes(A),R=i.toBytes(T);return b==="recovered"?(_(),Fe(Uint8Array.of(this.assertRecovery()),D,R)):Fe(D,R)}toHex(b){return bt(this.toBytes(b))}}let O=t.bits2int||function(b){if(b.length>8192)throw new Error("input is too large");let A=Mr(b),T=b.length*8-c;return T>0?A>>BigInt(T):A},$=t.bits2int_modN||function(b){return i.create(O(b))},q=On(c);function S(x){return Rn("num < 2^"+c,x,vt,q),i.toBytes(x)}function v(x,b){return V(x,void 0,"message"),b?V(e(x),void 0,"prehashed message"):x}function B(x,b,A){let{lowS:T,prehash:D,extraEntropy:R}=zc(A,p);x=v(x,D);let P=$(x),M=i.fromBytes(b);if(!i.isValidNot0(M))throw new Error("invalid private key");let K=[S(M),S(P)];if(R!=null&&R!==!1){let ie=R===!0?n(h.secretKey):R;K.push(V(ie,void 0,"extraEntropy"))}let se=Fe(...K),re=P;function G(ie){let be=O(ie);if(!i.isValidNot0(be))return;let st=i.inv(be),ae=r.BASE.multiply(be).toAffine(),ve=i.create(ae.x);if(ve===vt)return;let Ro=i.create(st*i.create(re+ve*M));if(Ro===vt)return;let Du=(ae.x===ve?0:2)|Number(ae.y&Wr),ku=Ro;return T&&m(Ro)&&(ku=i.neg(Ro),Du^=1),new C(ve,ku,y?void 0:Du)}return{seed:se,k2sig:G}}function z(x,b,A={}){let{seed:T,k2sig:D}=B(x,b,A);return Of(e.outputLen,i.BYTES,o)(T,D).toBytes(A.format)}function k(x,b,A,T={}){let{lowS:D,prehash:R,format:P}=zc(T,p);if(A=V(A,void 0,"publicKey"),b=v(b,R),!Xt(x)){let M=x instanceof C?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+M)}E(x,P);try{let M=C.fromBytes(x,P),K=r.fromBytes(A);if(D&&M.hasHighS())return!1;let{r:se,s:re}=M,G=$(b),ie=i.inv(re),be=i.create(G*ie),st=i.create(se*ie),ae=r.BASE.multiplyUnsafe(be).add(K.multiplyUnsafe(st));return ae.is0()?!1:i.create(ae.x)===se}catch{return!1}}function w(x,b,A={}){let{prehash:T}=zc(A,p);return b=v(b,T),C.fromBytes(x,"recovered").recoverPublicKey(b).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:f,utils:d,lengths:h,Point:r,sign:z,verify:k,recoverPublicKey:w,Signature:C,hash:e})}var Yc={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},t0={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Pd=BigInt(2);function r0(r){let e=Yc.p,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,f=ne(u,t,e)*u%e,d=ne(f,t,e)*u%e,h=ne(d,Pd,e)*l%e,p=ne(h,o,e)*h%e,y=ne(p,s,e)*p%e,m=ne(y,a,e)*y%e,g=ne(m,c,e)*m%e,_=ne(g,a,e)*y%e,E=ne(_,t,e)*u%e,C=ne(E,i,e)*p%e,O=ne(C,n,e)*l%e,$=ne(O,Pd,e);if(!Gc.eql(Gc.sqr($),r))throw new Error("Cannot find square root");return $}var Gc=Fr(Yc.p,{sqrt:r0}),n0=Cd(Yc,{Fp:Gc,endo:t0}),tt=Ld(n0,Nr);function Dd(r,e,t){let n=Rr.digest(e instanceof Uint8Array?e:e.subarray());if($r(n))return n.then(({digest:o})=>(t?.signal?.throwIfAborted(),tt.sign(o,r,{prehash:!1,format:"der"}))).catch(o=>{throw o.name==="AbortError"?o:new Fn(String(o))});try{return tt.sign(n.digest,r,{prehash:!1,format:"der"})}catch(o){throw new Fn(String(o))}}function kd(r,e,t,n){let o=Rr.digest(t instanceof Uint8Array?t:t.subarray());if($r(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),tt.verify(e,s,r,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new Un(String(s))});try{return n?.signal?.throwIfAborted(),tt.verify(e,o.digest,r,{prehash:!1,format:"der"})}catch(s){throw new Un(String(s))}}var Xn=class{type="secp256k1";raw;_key;constructor(e){this._key=Nd(e),this.raw=Rd(this._key)}toMultihash(){return je.digest(We(this))}toCID(){return ue.createV1(114,this.toMultihash())}toString(){return J.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Z(this.raw,e.raw)}verify(e,t,n){return kd(this._key,t,e,n)}},ps=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=Od(e),this.publicKey=new Xn(t??Md(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Z(this.raw,e.raw)}sign(e,t){return Dd(this.raw,e,t)}};function Xc(r){return new Xn(r)}async function Bd(){let r=o0();return new ps(r)}function Rd(r){return tt.Point.fromBytes(r).toBytes()}function Od(r){try{return tt.getPublicKey(r,!0),r}catch(e){throw new yn(String(e))}}function Nd(r){try{return tt.Point.fromBytes(r),r}catch(e){throw new Cr(String(e))}}function Md(r){try{return tt.getPublicKey(r,!0)}catch(e){throw new yn(String(e))}}function o0(){return tt.utils.randomSecretKey()}async function Fd(r,e){if(r==="Ed25519")return cd();if(r==="secp256k1")return Bd();if(r==="RSA")return $c(s0(e));if(r==="ECDSA")return gf(i0(e));throw new Pt}function Gr(r,e){let{Type:t,Data:n}=lt.decode(r),o=n??new Uint8Array;switch(t){case oe.RSA:return Uc(o,e);case oe.Ed25519:return pc(o);case oe.secp256k1:return Xc(o);case oe.ECDSA:return za(o);default:throw new Pt}}function Ud(r){let{Type:e,Data:t}=lt.decode(r.digest),n=t??new Uint8Array;switch(e){case oe.Ed25519:return pc(n);case oe.secp256k1:return Xc(n);case oe.ECDSA:return za(n);default:throw new Pt}}function We(r){return lt.encode({Type:oe[r.type],Data:r.raw})}function s0(r){return r==null?2048:parseInt(r,10)}function i0(r){if(r==="P-256"||r==null)return"P-256";if(r==="P-384")return"P-384";if(r==="P-521")return"P-521";throw new I("Unsupported curve, should be P-256, P-384 or P-521")}var Kd=Symbol.for("nodejs.util.inspect.custom"),a0=114,jn=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Vo]=!0;toString(){return this.string==null&&(this.string=J.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return ue.createV1(a0,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return Z(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return Z(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Kd](){return`PeerId(${this.toString()})`}},Zn=class extends jn{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Qn=class extends jn{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},Jn=class extends jn{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},c0=2336,eo=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=je.digest(L(this.url))}[Kd](){return`PeerId(${this.url})`}[Vo]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return ue.createV1(c0,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=U(e)),e.toString()===this.toString())}};var l0=114,qd=2336;function ut(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=pt(J.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return to(ue.parse(r));if(e==null)throw new I('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=pt(e.decode(r))}return Yr(t)}function jc(r){if(r.type==="Ed25519")return new Qn({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new Jn({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new Zn({multihash:r.toCID().multihash,publicKey:r});throw new Pt}function $d(r){return jc(r.publicKey)}function Yr(r){if(f0(r))return new Zn({multihash:r});if(u0(r))try{let e=Ud(r);if(e.type==="Ed25519")return new Qn({multihash:r,publicKey:e});if(e.type==="secp256k1")return new Jn({multihash:r,publicKey:e})}catch{let t=U(r.digest);return new eo(new URL(t))}throw new Mo("Supplied PeerID Multihash is invalid")}function to(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==l0&&r.code!==qd)throw new No("Supplied PeerID CID is invalid");if(r.code===qd){let e=U(r.multihash.digest);return new eo(new URL(e))}return Yr(r.multihash)}function u0(r){return r.code===je.code}function f0(r){return r.code===Rr.code}async function Vd(r){if(r.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new I("Private network is enforced, but no protector was provided");return r}function d0(r,e){if(typeof r=="string")return h0(r);if(typeof r=="number")return g0(r,e);throw Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(r)}`)}var ms=d0;function h0(r){if(typeof r!="string"||r.length===0||r.length>100)throw Error(`Value provided to ms.parse() must be a string with length between 1 and 99. value=${JSON.stringify(r)}`);let e=/^(?<value>-?\d*\.?\d+) *(?<unit>milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)?$/i.exec(r);if(!e?.groups)return NaN;let{value:t,unit:n="ms"}=e.groups,o=parseFloat(t),s=n.toLowerCase();switch(s){case"years":case"year":case"yrs":case"yr":case"y":return o*315576e5;case"months":case"month":case"mo":return o*26298e5;case"weeks":case"week":case"w":return o*6048e5;case"days":case"day":case"d":return o*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return o*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return o*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return o*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return o;default:throw Error(`Unknown unit "${s}" provided to ms.parse(). value=${JSON.stringify(r)}`)}}function p0(r){let e=Math.abs(r);return e>=315576e5?`${Math.round(r/315576e5)}y`:e>=26298e5?`${Math.round(r/26298e5)}mo`:e>=6048e5?`${Math.round(r/6048e5)}w`:e>=864e5?`${Math.round(r/864e5)}d`:e>=36e5?`${Math.round(r/36e5)}h`:e>=6e4?`${Math.round(r/6e4)}m`:e>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function m0(r){let e=Math.abs(r);return e>=315576e5?sr(r,e,315576e5,"year"):e>=26298e5?sr(r,e,26298e5,"month"):e>=6048e5?sr(r,e,6048e5,"week"):e>=864e5?sr(r,e,864e5,"day"):e>=36e5?sr(r,e,36e5,"hour"):e>=6e4?sr(r,e,6e4,"minute"):e>=1e3?sr(r,e,1e3,"second"):`${r} ms`}function g0(r,e){if(typeof r!="number"||!Number.isFinite(r))throw Error("Value provided to ms.format() must be of type number.");return e?.long?m0(r):p0(r)}function sr(r,e,t,n){let o=e>=t*1.5;return`${Math.round(r/t)} ${n}${o?"s":""}`}function Zc(r){t.debug=t,t.default=t,t.coerce=c,t.disable=s,t.enable=o,t.enabled=i,t.humanize=ms,t.destroy=l,Object.keys(r).forEach(u=>{t[u]=r[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let f=0;for(let d=0;d<u.length;d++)f=(f<<5)-f+u.charCodeAt(d),f|=0;return t.colors[Math.abs(f)%t.colors.length]}t.selectColor=e;function t(u,f){let d,h=null,p,y;function m(...g){if(!m.enabled)return;let _=m,E=Number(new Date),C=E-(d||E);_.diff=C,_.prev=d,_.curr=E,d=E,g[0]=t.coerce(g[0]),typeof g[0]!="string"&&g.unshift("%O");let O=0;g[0]=g[0].replace(/%([a-zA-Z%])/g,(q,S)=>{if(q==="%%")return"%";O++;let v=t.formatters[S];if(typeof v=="function"){let B=g[O];q=v.call(_,B),g.splice(O,1),O--}return q}),t.formatArgs.call(_,g),f?.onLog!=null&&f.onLog(...g),(_.log||t.log).apply(_,g)}return m.namespace=u,m.useColors=t.useColors(),m.color=t.selectColor(u),m.extend=n,m.destroy=t.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>h!==null?h:(p!==t.namespaces&&(p=t.namespaces,y=t.enabled(u)),y),set:g=>{h=g}}),typeof t.init=="function"&&t.init(m),m}function n(u,f){let d=t(this.namespace+(typeof f>"u"?":":f)+u);return d.log=this.log,d}function o(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let f,d=(typeof u=="string"?u:"").split(/[\s,]+/),h=d.length;for(f=0;f<h;f++)d[f]&&(u=d[f].replace(/\*/g,".*?"),u[0]==="-"?t.skips.push(new RegExp("^"+u.substr(1)+"$")):t.names.push(new RegExp("^"+u+"$")))}function s(){let u=[...t.names.map(a),...t.skips.map(a).map(f=>"-"+f)].join(",");return t.enable(""),u}function i(u){if(u[u.length-1]==="*")return!0;let f,d;for(f=0,d=t.skips.length;f<d;f++)if(t.skips[f].test(u))return!1;for(f=0,d=t.names.length;f<d;f++)if(t.names[f].test(u))return!0;return!1}function a(u){return u.toString().substring(2,u.toString().length-2).replace(/\.\*\?$/,"*")}function c(u){return u instanceof Error?u.stack??u.message:u}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.setupFormatters(t.formatters),t.enable(t.load()),t}var gs=S0(),y0=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function b0(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/(edge|trident)\/(\d+)/)!=null?!1:typeof document<"u"&&document.documentElement?.style?.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/firefox\/(\d+)/)!=null&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/applewebkit\/(\d+)/)}function w0(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+ms(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(t++,o==="%c"&&(n=t))}),r.splice(n,0,e)}var x0=console.debug??console.log??(()=>{});function E0(r){try{r?gs?.setItem("debug",r):gs?.removeItem("debug")}catch{}}function v0(){let r;try{r=gs?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function S0(){try{return localStorage}catch{}}function _0(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var zd=Zc({formatArgs:w0,save:E0,load:v0,useColors:b0,setupFormatters:_0,colors:y0,storage:gs,log:x0});var Ke=zd;Ke.formatters.b=r=>r==null?"undefined":J.baseEncode(r);Ke.formatters.t=r=>r==null?"undefined":He.baseEncode(r);Ke.formatters.m=r=>r==null?"undefined":Da.baseEncode(r);Ke.formatters.p=r=>r==null?"undefined":r.toString();Ke.formatters.c=r=>r==null?"undefined":r.toString();Ke.formatters.k=r=>r==null?"undefined":r.toString();Ke.formatters.a=r=>r==null?"undefined":r.toString();function Hd(r,e=""){let t=Wd(r.message),n=Wd(r.stack);return t!=null&&n!=null?n.includes(t)?`${n.split(`
|
|
2
|
+
"use strict";var Libp2P=(()=>{var Gp=Object.create;var Ko=Object.defineProperty;var Yp=Object.getOwnPropertyDescriptor;var jp=Object.getOwnPropertyNames;var Xp=Object.getPrototypeOf,Zp=Object.prototype.hasOwnProperty;var _n=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Be=(r,e)=>{for(var t in e)Ko(r,t,{get:e[t],enumerable:!0})},Yu=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of jp(e))!Zp.call(r,o)&&o!==t&&Ko(r,o,{get:()=>e[o],enumerable:!(n=Yp(e,o))||n.enumerable});return r};var wa=(r,e,t)=>(t=r!=null?Gp(Xp(r)):{},Yu(e||!r||!r.__esModule?Ko(t,"default",{value:r,enumerable:!0}):t,r)),Qp=r=>Yu(Ko({},"__esModule",{value:!0}),r);var hl=_n(tn=>{"use strict";Object.defineProperty(tn,"__esModule",{value:!0});tn.Netmask4Impl=void 0;tn.ip2long=en;tn.long2ip=ft;function ft(r){let e=(r&-16777216)>>>24,t=(r&255<<16)>>>16,n=(r&65280)>>>8,o=r&255;return[e,t,n,o].join(".")}var Z0=48,Q0=97,J0=65;function ey(r){let e=0,t=10,n="9",o=0;r.length>1&&r[o]==="0"&&(r[o+1]==="x"||r[o+1]==="X"?(o+=2,t=16):"0"<=r[o+1]&&r[o+1]<="9"&&(o++,t=8,n="7"));let s=o;for(;o<r.length;){if("0"<=r[o]&&r[o]<=n)e=e*t+(r.charCodeAt(o)-Z0)>>>0;else if(t===16)if("a"<=r[o]&&r[o]<="f")e=e*t+(10+r.charCodeAt(o)-Q0)>>>0;else if("A"<=r[o]&&r[o]<="F")e=e*t+(10+r.charCodeAt(o)-J0)>>>0;else break;else break;if(e>4294967295)throw new Error("too large");o++}if(o===s)throw new Error("empty octet");return[e,o]}function en(r){let e=[];for(let t=0;t<=3&&r.length!==0;t++){if(t>0){if(r[0]!==".")throw new Error("Invalid IP");r=r.substring(1)}let[n,o]=ey(r);r=r.substring(o),e.push(n)}if(r.length!==0)throw new Error("Invalid IP");switch(e.length){case 1:if(e[0]>4294967295)throw new Error("Invalid IP");return e[0]>>>0;case 2:if(e[0]>255||e[1]>16777215)throw new Error("Invalid IP");return(e[0]<<24|e[1])>>>0;case 3:if(e[0]>255||e[1]>255||e[2]>65535)throw new Error("Invalid IP");return(e[0]<<24|e[1]<<16|e[2])>>>0;case 4:if(e[0]>255||e[1]>255||e[2]>255||e[3]>255)throw new Error("Invalid IP");return(e[0]<<24|e[1]<<16|e[2]<<8|e[3])>>>0;default:throw new Error("Invalid IP")}}var dl=class r{constructor(e,t){if(typeof e!="string")throw new Error("Missing `net' parameter");let n=t;if(!n){let o=e.split("/",2);e=o[0],n=o[1]}if(n||(n=32),typeof n=="string"&&n.indexOf(".")>-1){try{this.maskLong=en(n)}catch{throw new Error("Invalid mask: "+n)}this.bitmask=NaN;for(let o=32;o>=0;o--)if(this.maskLong===4294967295<<32-o>>>0){this.bitmask=o;break}}else if(n||n===0)this.bitmask=parseInt(n,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(en(e)&this.maskLong)>>>0}catch{throw new Error("Invalid net address: "+e)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+n);this.size=Math.pow(2,32-this.bitmask),this.base=ft(this.netLong),this.mask=ft(this.maskLong),this.hostmask=ft(~this.maskLong),this.first=this.bitmask<=30?ft(this.netLong+1):this.base,this.last=this.bitmask<=30?ft(this.netLong+this.size-2):ft(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?ft(this.netLong+this.size-1):void 0}contains(e){return typeof e=="string"&&(e.indexOf("/")>0||e.split(".").length!==4)&&(e=new r(e)),e instanceof r?this.contains(e.base)&&this.contains(e.broadcast||e.last):(en(e)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0}next(e=1){return new r(ft(this.netLong+this.size*e),this.mask)}forEach(e){let t=en(this.first),n=en(this.last),o=0;for(;t<=n;)e(ft(t),t,o),o++,t++}toString(){return this.base+"/"+this.bitmask}};tn.Netmask4Impl=dl});var vh=_n(rn=>{"use strict";Object.defineProperty(rn,"__esModule",{value:!0});rn.Netmask6Impl=void 0;rn.ip6bigint=ml;rn.bigint2ip6=mr;var ty=hl(),pl=(1n<<128n)-1n;function ml(r){let e=r.indexOf("%");e!==-1&&(r=r.substring(0,e));let t=r.lastIndexOf(":");if(t!==-1&&r.indexOf(".",t)!==-1){let n=r.substring(t+1),o=(0,ty.ip2long)(n),s=r.substring(0,t+1)+"0:0";return Eh(s)&~0xffffffffn|BigInt(o)}return Eh(r)}function Eh(r){let e=r.indexOf("::"),t;if(e!==-1){let o=r.substring(0,e),s=r.substring(e+2),i=o===""?[]:o.split(":"),a=s===""?[]:s.split(":"),c=8-i.length-a.length;if(c<0)throw new Error("Invalid IPv6: too many groups");t=[...i,...Array(c).fill("0"),...a]}else t=r.split(":");if(t.length!==8)throw new Error("Invalid IPv6: expected 8 groups, got "+t.length);let n=0n;for(let o=0;o<8;o++){let s=t[o];if(s.length===0||s.length>4)throw new Error('Invalid IPv6: bad group "'+s+'"');let i=parseInt(s,16);if(isNaN(i)||i<0||i>65535)throw new Error('Invalid IPv6: bad group "'+s+'"');n=n<<16n|BigInt(i)}return n}function mr(r){if(r<0n||r>pl)throw new Error("Invalid IPv6 address value");let e=[];for(let i=0;i<8;i++)e.unshift(Number(r&0xffffn)),r>>=16n;let t=-1,n=0,o=-1,s=0;for(let i=0;i<8;i++)e[i]===0?o===-1?(o=i,s=1):s++:(s>n&&s>=2&&(t=o,n=s),o=-1,s=0);if(s>n&&s>=2&&(t=o,n=s),t!==-1&&t+n===8&&t>0)return e.slice(0,t).map(a=>a.toString(16)).join(":")+"::";if(t===0)return"::"+e.slice(n).map(a=>a.toString(16)).join(":");if(t>0){let i=e.slice(0,t).map(c=>c.toString(16)),a=e.slice(t+n).map(c=>c.toString(16));return i.join(":")+"::"+a.join(":")}else return e.map(i=>i.toString(16)).join(":")}var gl=class r{constructor(e,t){if(typeof e!="string")throw new Error("Missing `net' parameter");let n=t;if(n==null){let o=e.indexOf("/");o!==-1?(n=parseInt(e.substring(o+1),10),e=e.substring(0,o)):n=128}if(isNaN(n)||n<0||n>128)throw new Error("Invalid mask for IPv6: "+n);this.bitmask=n,this.bitmask===0?this.maskBigint=0n:this.maskBigint=pl>>BigInt(128-this.bitmask)<<BigInt(128-this.bitmask);try{this.netBigint=ml(e)&this.maskBigint}catch{throw new Error("Invalid IPv6 net address: "+e)}this.size=Number(1n<<BigInt(128-this.bitmask)),this.base=mr(this.netBigint),this.mask=mr(this.maskBigint),this.hostmask=mr(~this.maskBigint&pl),this.first=this.base,this.last=mr(this.netBigint+(1n<<BigInt(128-this.bitmask))-1n),this.broadcast=void 0}contains(e){return typeof e=="string"&&e.indexOf("/")>0&&(e=new r(e)),e instanceof r?this.contains(e.base)&&this.contains(e.last):(ml(e)&this.maskBigint)===this.netBigint}next(e=1){let t=1n<<BigInt(128-this.bitmask);return new r(mr(this.netBigint+t*BigInt(e)),this.bitmask)}forEach(e){let t=this.netBigint,n=1n<<BigInt(128-this.bitmask),o=this.netBigint+n-1n,s=0;for(;t<=o;)e(mr(t),Number(t),s),s++,t++}toString(){return this.base+"/"+this.bitmask}};rn.Netmask6Impl=gl});var Sh=_n(Ht=>{"use strict";Object.defineProperty(Ht,"__esModule",{value:!0});Ht.long2ip=Ht.ip2long=Ht.Netmask=void 0;var Ps=hl();Object.defineProperty(Ht,"ip2long",{enumerable:!0,get:function(){return Ps.ip2long}});Object.defineProperty(Ht,"long2ip",{enumerable:!0,get:function(){return Ps.long2ip}});var ry=vh(),yl=class r{constructor(e,t){if(typeof e!="string")throw new Error("Missing `net' parameter");(e.indexOf("/")!==-1?e.substring(0,e.indexOf("/")):e).indexOf(":")!==-1?this._impl=new ry.Netmask6Impl(e,t):this._impl=new Ps.Netmask4Impl(e,t),this.base=this._impl.base,this.mask=this._impl.mask,this.hostmask=this._impl.hostmask,this.bitmask=this._impl.bitmask,this.size=this._impl.size,this.first=this._impl.first,this.last=this._impl.last,this.broadcast=this._impl.broadcast,this._impl instanceof Ps.Netmask4Impl?(this.maskLong=this._impl.maskLong,this.netLong=this._impl.netLong):(this.maskLong=0,this.netLong=0)}contains(e){return typeof e=="string"&&(e.indexOf("/")>0?e=new r(e):e.indexOf(":")===-1&&e.split(".").length!==4&&(e=new r(e))),e instanceof r?this.contains(e.base)&&this.contains(e.broadcast||e.last):this._impl.contains(e)}next(e=1){let t=this._impl.next(e);return new r(t.base,t.bitmask)}forEach(e){this._impl.forEach(e)}toString(){return this._impl.toString()}};Ht.Netmask=yl});var Dp=_n((s4,_u)=>{"use strict";var Wb=Object.prototype.hasOwnProperty,Me="~";function Oo(){}Object.create&&(Oo.prototype=Object.create(null),new Oo().__proto__||(Me=!1));function Gb(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function Pp(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var s=new Gb(t,n||r,o),i=Me?Me+e:e;return r._events[i]?r._events[i].fn?r._events[i]=[r._events[i],s]:r._events[i].push(s):(r._events[i]=s,r._eventsCount++),r}function ea(r,e){--r._eventsCount===0?r._events=new Oo:delete r._events[e]}function Te(){this._events=new Oo,this._eventsCount=0}Te.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)Wb.call(t,n)&&e.push(Me?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Te.prototype.listeners=function(e){var t=Me?Me+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var o=0,s=n.length,i=new Array(s);o<s;o++)i[o]=n[o].fn;return i};Te.prototype.listenerCount=function(e){var t=Me?Me+e:e,n=this._events[t];return n?n.fn?1:n.length:0};Te.prototype.emit=function(e,t,n,o,s,i){var a=Me?Me+e:e;if(!this._events[a])return!1;var c=this._events[a],u=arguments.length,l,f;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),u){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,o),!0;case 5:return c.fn.call(c.context,t,n,o,s),!0;case 6:return c.fn.call(c.context,t,n,o,s,i),!0}for(f=1,l=new Array(u-1);f<u;f++)l[f-1]=arguments[f];c.fn.apply(c.context,l)}else{var d=c.length,h;for(f=0;f<d;f++)switch(c[f].once&&this.removeListener(e,c[f].fn,void 0,!0),u){case 1:c[f].fn.call(c[f].context);break;case 2:c[f].fn.call(c[f].context,t);break;case 3:c[f].fn.call(c[f].context,t,n);break;case 4:c[f].fn.call(c[f].context,t,n,o);break;default:if(!l)for(h=1,l=new Array(u-1);h<u;h++)l[h-1]=arguments[h];c[f].fn.apply(c[f].context,l)}}return!0};Te.prototype.on=function(e,t,n){return Pp(this,e,t,n,!1)};Te.prototype.once=function(e,t,n){return Pp(this,e,t,n,!0)};Te.prototype.removeListener=function(e,t,n,o){var s=Me?Me+e:e;if(!this._events[s])return this;if(!t)return ea(this,s),this;var i=this._events[s];if(i.fn)i.fn===t&&(!o||i.once)&&(!n||i.context===n)&&ea(this,s);else{for(var a=0,c=[],u=i.length;a<u;a++)(i[a].fn!==t||o&&!i[a].once||n&&i[a].context!==n)&&c.push(i[a]);c.length?this._events[s]=c.length===1?c[0]:c:ea(this,s)}return this};Te.prototype.removeAllListeners=function(e){var t;return e?(t=Me?Me+e:e,this._events[t]&&ea(this,t)):(this._events=new Oo,this._eventsCount=0),this};Te.prototype.off=Te.prototype.removeListener;Te.prototype.addListener=Te.prototype.on;Te.prefixed=Me;Te.EventEmitter=Te;typeof _u<"u"&&(_u.exports=Te)});var Op=_n((C4,Rp)=>{Rp.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function o(s,i){t[s]=i,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(s){return t[s]!==void 0||n[s]!==void 0},remove:function(s){t[s]!==void 0&&(t[s]=void 0),n[s]!==void 0&&(n[s]=void 0)},get:function(s){var i=t[s];if(i!==void 0)return i;if((i=n[s])!==void 0)return o(s,i),i},set:function(s,i){t[s]!==void 0?t[s]=i:o(s,i)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var ww={};Be(ww,{createLibp2p:()=>gw,dnsaddrResolver:()=>Cr,isLibp2p:()=>bw});var ju=Symbol.for("@libp2p/connection");var xa=Symbol.for("@libp2p/content-routing");var je=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var C=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Tr=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}},An=class extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}};var jt=class extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}};var Xt=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}},Lr=class extends Error{static name="InvalidPeerIdError";constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}},Dt=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},qo=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},$o=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}},Vo=class extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}},zo=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var Ho=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},ht=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}};var Pr=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}};var In=class extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}},Wo=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}},Go=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}},kt=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var Yo=class extends Event{error;local;constructor(e,t,n){super("close",n),this.error=t,this.local=e}};var Ea=Symbol.for("@libp2p/peer-discovery");var jo=Symbol.for("@libp2p/peer-id");function Rt(r){return!!r?.[jo]}var va=Symbol.for("@libp2p/peer-routing");var Sa="keep-alive";function Xo(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function Xu(...r){let e=[];for(let t of r)Xo(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStart!=null&&await t.beforeStart()})),await Promise.all(e.map(async t=>{await t.start()})),await Promise.all(e.map(async t=>{t.afterStart!=null&&await t.afterStart()}))}async function Zu(...r){let e=[];for(let t of r)Xo(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStop!=null&&await t.beforeStop()})),await Promise.all(e.map(async t=>{await t.stop()})),await Promise.all(e.map(async t=>{t.afterStop!=null&&await t.afterStop()}))}var Cn;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Cn||(Cn={}));var Le=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){super.addEventListener(e,t,n);let o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==t),this.#e.set(e,o))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:o})=>!o),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var Tn=Symbol.for("@libp2p/service-capabilities"),_a=Symbol.for("@libp2p/service-dependencies");var La={};Be(La,{base58btc:()=>ee,base58flickr:()=>sm});var nx=new Uint8Array(0);function Qu(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function pt(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function Ju(r){return new TextEncoder().encode(r)}function ef(r){return new TextDecoder().decode(r)}function Jp(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function f(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var y=0,g=0,m=0,_=p.length;m!==_&&p[m]===0;)m++,y++;for(var E=(_-m)*l+1>>>0,I=new Uint8Array(E);m!==_;){for(var O=p[m],$=0,q=E-1;(O!==0||$<g)&&q!==-1;q--,$++)O+=256*I[q]>>>0,I[q]=O%a>>>0,O=O/a>>>0;if(O!==0)throw new Error("Non-zero carry");g=$,m++}for(var S=E-g;S!==E&&I[S]===0;)S++;for(var v=c.repeat(y);S<E;++S)v+=r.charAt(I[S]);return v}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var y=0;if(p[y]!==" "){for(var g=0,m=0;p[y]===c;)g++,y++;for(var _=(p.length-y)*u+1>>>0,E=new Uint8Array(_);p[y];){var I=t[p.charCodeAt(y)];if(I===255)return;for(var O=0,$=_-1;(I!==0||O<m)&&$!==-1;$--,O++)I+=a*E[$]>>>0,E[$]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");m=O,y++}if(p[y]!==" "){for(var q=_-m;q!==_&&E[q]===0;)q++;for(var S=new Uint8Array(g+(_-q)),v=g;q!==_;)S[v++]=E[q++];return S}}}function h(p){var y=d(p);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:d,decode:h}}var em=Jp,tm=em,rf=tm;var Aa=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Ia=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return nf(this,e)}},Ca=class{decoders;constructor(e){this.decoders=e}or(e){return nf(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function nf(r,e){return new Ca({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Ta=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new Aa(e,t,n),this.decoder=new Ia(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Dr({name:r,prefix:e,encode:t,decode:n}){return new Ta(r,e,t,n)}function Ot({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=rf(t,r);return Dr({prefix:e,name:r,encode:n,decode:s=>pt(o(s))})}function rm(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let u=0;u<o;++u){let l=e[r[u]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|l,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function nm(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function om(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function le({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=om(n);return Dr({prefix:e,name:r,encode(s){return nm(s,n,t)},decode(s){return rm(s,o,t,r)}})}var ee=Ot({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),sm=Ot({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Pa={};Be(Pa,{base32:()=>He,base32hex:()=>lm,base32hexpad:()=>fm,base32hexpadupper:()=>dm,base32hexupper:()=>um,base32pad:()=>am,base32padupper:()=>cm,base32upper:()=>im,base32z:()=>hm});var He=le({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),im=le({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),am=le({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),cm=le({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),lm=le({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),um=le({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),fm=le({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),dm=le({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),hm=le({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Da={};Be(Da,{base36:()=>Ln,base36upper:()=>pm});var Ln=Ot({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),pm=Ot({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var mm=af,of=128,gm=127,ym=~gm,bm=Math.pow(2,31);function af(r,e,t){e=e||[],t=t||0;for(var n=t;r>=bm;)e[t++]=r&255|of,r/=128;for(;r&ym;)e[t++]=r&255|of,r>>>=7;return e[t]=r|0,af.bytes=t-n+1,e}var wm=ka,xm=128,sf=127;function ka(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw ka.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&sf)<<o:(i&sf)*Math.pow(2,o),o+=7}while(i>=xm);return ka.bytes=s-n,t}var Em=Math.pow(2,7),vm=Math.pow(2,14),Sm=Math.pow(2,21),_m=Math.pow(2,28),Am=Math.pow(2,35),Im=Math.pow(2,42),Cm=Math.pow(2,49),Tm=Math.pow(2,56),Lm=Math.pow(2,63),Pm=function(r){return r<Em?1:r<vm?2:r<Sm?3:r<_m?4:r<Am?5:r<Im?6:r<Cm?7:r<Tm?8:r<Lm?9:10},Dm={encode:mm,decode:wm,encodingLength:Pm},km=Dm,Pn=km;function Dn(r,e=0){return[Pn.decode(r,e),Pn.decode.bytes]}function kr(r,e,t=0){return Pn.encode(r,e,t),e}function Rr(r){return Pn.encodingLength(r)}function it(r,e){let t=e.byteLength,n=Rr(r),o=n+Rr(t),s=new Uint8Array(o+t);return kr(r,s,0),kr(t,s,n),s.set(e,o),new Or(r,t,e,s)}function mt(r){let e=pt(r),[t,n]=Dn(e),[o,s]=Dn(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Or(t,o,i,e)}function cf(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Qu(r.bytes,t.bytes)}}var Or=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};function lf(r,e){let{bytes:t,version:n}=r;return n===0?Om(t,Ra(r),e??ee.encoder):Nm(t,Ra(r),e??He.encoder)}var uf=new WeakMap;function Ra(r){let e=uf.get(r);if(e==null){let t=new Map;return uf.set(r,t),t}return e}var fe=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==kn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Mm)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=it(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&cf(e.multihash,n.multihash)}toString(e){return lf(this,e)}toJSON(){return{"/":lf(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??ff(n,o,s.bytes))}else if(t[Bm]===!0){let{version:n,multihash:o,code:s}=t,i=mt(o);return r.create(n,s,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==kn)throw new Error(`Version 0 CID must use dag-pb (code: ${kn}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=ff(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,kn,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=pt(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new Or(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,d]=Dn(e.subarray(t));return t+=d,f},o=n(),s=kn;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),u=t+c,l=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(e,t){let[n,o]=Rm(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Ra(s).set(n,e),s}};function Rm(r,e){switch(r[0]){case"Q":{let t=e??ee;return[ee.prefix,t.decode(`${ee.prefix}${r}`)]}case ee.prefix:{let t=e??ee;return[ee.prefix,t.decode(r)]}case He.prefix:{let t=e??He;return[He.prefix,t.decode(r)]}case Ln.prefix:{let t=e??Ln;return[Ln.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function Om(r,e,t){let{prefix:n}=t;if(n!==ee.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function Nm(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var kn=112,Mm=18;function ff(r,e,t){let n=Rr(r),o=n+Rr(e),s=new Uint8Array(o+t.byteLength);return kr(r,s,0),kr(e,s,n),s.set(t,o),s}var Bm=Symbol.for("@ipld/js-cid/CID");var Oa={};Be(Oa,{identity:()=>Xe});var df=0,Fm="identity",hf=pt;function Um(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return it(df,hf(r))}var Xe={code:df,name:Fm,encode:hf,digest:Um};function Z(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function ue(r=0){return new Uint8Array(r)}function Se(r=0){return new Uint8Array(r)}function Ze(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=Se(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}var mf=Symbol.for("@achingbrain/uint8arraylist");function pf(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function Qo(r){return!!r?.[mf]}var Q=class r{bufs;length;[mf]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(Qo(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(Qo(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=pf(this.bufs,e);return t.buf[t.index]}set(e,t){let n=pf(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(Qo(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:o}=this._subList(e,t);return Ze(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:Ze(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=[...n],s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let u=e>=a&&e<c,l=t>a&&t<=c;if(u&&l){if(e===a&&t===c){n.push(i);break}let f=e-a;n.push(i.subarray(f,f+(t-e)));break}if(u){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(l){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!Qo(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let f=0;f<s;f++)i[f]=-1;for(let f=0;f<o;f++)i[n[f]]=f;let a=i,c=this.byteLength-n.byteLength,u=n.byteLength-1,l;for(let f=t;f<=c;f+=l){l=0;for(let d=u;d>=0;d--){let h=this.get(f+d);if(n[d]!==h){l=Math.max(1,d-a[h]);break}}if(l===0)return f}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=Se(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=ue(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=ue(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=ue(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=Se(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=ue(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=ue(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=ue(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=ue(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=ue(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!Z(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,s)=>o+s.byteLength,0)),n.length=t,n}};var Na={};Be(Na,{base10:()=>Km});var Km=Ot({prefix:"9",name:"base10",alphabet:"0123456789"});var Ma={};Be(Ma,{base16:()=>qm,base16upper:()=>$m});var qm=le({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),$m=le({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Ba={};Be(Ba,{base2:()=>Vm});var Vm=le({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Fa={};Be(Fa,{base256emoji:()=>Ym});var gf=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),zm=gf.reduce((r,e,t)=>(r[t]=e,r),[]),Hm=gf.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function Wm(r){return r.reduce((e,t)=>(e+=zm[t],e),"")}function Gm(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=Hm[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var Ym=Dr({prefix:"\u{1F680}",name:"base256emoji",encode:Wm,decode:Gm});var qa={};Be(qa,{base64:()=>Ua,base64pad:()=>jm,base64url:()=>Ka,base64urlpad:()=>Xm});var Ua=le({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),jm=le({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ka=le({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Xm=le({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var $a={};Be($a,{base8:()=>Zm});var Zm=le({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Va={};Be(Va,{identity:()=>Qm});var Qm=Dr({prefix:"\0",name:"identity",encode:r=>ef(r),decode:r=>Ju(r)});var Kx=new TextEncoder,qx=new TextDecoder;var Wa={};Be(Wa,{sha256:()=>Nr,sha512:()=>rg});var tg=20;function Ha({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new za(r,e,t,n,o)}var za=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??tg,this.maxDigestLength=s}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?yf(n,this.code,t?.truncate):n.then(o=>yf(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function yf(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return it(e,r)}function wf(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Nr=Ha({name:"sha2-256",code:18,encode:wf("SHA-256")}),rg=Ha({name:"sha2-512",code:19,encode:wf("SHA-512")});var Rn={...Va,...Ba,...$a,...Na,...Ma,...Pa,...Da,...La,...qa,...Fa},Jx={...Wa,...Oa};function Ef(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var xf=Ef("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Ga=Ef("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=Se(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),ng={utf8:xf,"utf-8":xf,hex:Rn.base16,latin1:Ga,ascii:Ga,binary:Ga,...Rn},Jo=ng;function L(r,e="utf8"){let t=Jo[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function U(r,e="utf8"){let t=Jo[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var og=parseInt("11111",2),Ya=parseInt("10000000",2),sg=parseInt("01111111",2),vf={0:On,1:On,2:ig,3:lg,4:ug,5:cg,6:ag,16:On,22:On,48:On};function gt(r,e={offset:0}){let t=r[e.offset]&og;if(e.offset++,vf[t]!=null)return vf[t](r,e);throw new Error("No decoder for tag "+t)}function Nn(r,e){let t=0;if((r[e.offset]&Ya)===Ya){let n=r[e.offset]&sg,o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++)o+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(o,16)}else t=r[e.offset],e.offset++;return t}function On(r,e){Nn(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=gt(r,e);if(n===null)break;t.push(n)}return t}function ig(r,e){let t=Nn(r,e),n=e.offset,o=e.offset+t,s=[];for(let i=n;i<o;i++)i===n&&r[i]===0||s.push(r[i]);return e.offset+=t,Uint8Array.from(s)}function ag(r,e){let t=Nn(r,e),n=e.offset+t,o=r[e.offset];e.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,c=[];for(;e.offset<n;){let u=r[e.offset];if(e.offset++,c.push(u&127),u<128){c.reverse();let l=0;for(let f=0;f<c.length;f++)l+=c[f]<<f*7;a+=`.${l}`,c=[]}}return a}function cg(r,e){return e.offset++,null}function lg(r,e){let t=Nn(r,e),n=r[e.offset];e.offset++;let o=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function ug(r,e){let t=Nn(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function fg(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new Q;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function es(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=fg(r.byteLength);return new Q(Uint8Array.from([e.byteLength|Ya]),e)}function Pe(r){let e=new Q,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new Q(Uint8Array.from([2]),es(e),e)}function Mn(r){let e=Uint8Array.from([0]),t=new Q(e,r);return new Q(Uint8Array.from([3]),es(t),t)}function Sf(r){return new Q(Uint8Array.from([4]),es(r),r)}function Qe(r,e=48){let t=new Q;for(let n of r)t.append(n);return new Q(Uint8Array.from([e]),es(t),t)}async function _f(r="P-256"){let e=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:r},!0,["sign","verify"]);return{publicKey:await crypto.subtle.exportKey("jwk",e.publicKey),privateKey:await crypto.subtle.exportKey("jwk",e.privateKey)}}async function Af(r,e,t){let n=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["sign"]);t?.signal?.throwIfAborted();let o=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,e.subarray());return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function If(r,e,t,n){let o=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,e,t.subarray());return n?.signal?.throwIfAborted(),s}var dg=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),hg=Uint8Array.from([6,5,43,129,4,0,34]),pg=Uint8Array.from([6,5,43,129,4,0,35]),mg={ext:!0,kty:"EC",crv:"P-256"},gg={ext:!0,kty:"EC",crv:"P-384"},yg={ext:!0,kty:"EC",crv:"P-521"},ja=32,Xa=48,Za=66;function Qa(r){let e=gt(r);return Cf(e)}function Cf(r){let e=r[1][1][0],t=1,n,o;if(e.byteLength===ja*2+1)return n=U(e.subarray(t,t+ja),"base64url"),o=U(e.subarray(t+ja),"base64url"),new Zt({...mg,key_ops:["verify"],x:n,y:o});if(e.byteLength===Xa*2+1)return n=U(e.subarray(t,t+Xa),"base64url"),o=U(e.subarray(t+Xa),"base64url"),new Zt({...gg,key_ops:["verify"],x:n,y:o});if(e.byteLength===Za*2+1)return n=U(e.subarray(t,t+Za),"base64url"),o=U(e.subarray(t+Za),"base64url"),new Zt({...yg,key_ops:["verify"],x:n,y:o});throw new C(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function Tf(r){return Qe([Pe(Uint8Array.from([1])),Sf(L(r.d??"","base64url")),Qe([Pf(r.crv)],160),Qe([Mn(new Q(Uint8Array.from([4]),L(r.x??"","base64url"),L(r.y??"","base64url")))],161)]).subarray()}function Lf(r){return Qe([Pe(Uint8Array.from([1])),Qe([Pf(r.crv)],160),Qe([Mn(new Q(Uint8Array.from([4]),L(r.x??"","base64url"),L(r.y??"","base64url")))],161)]).subarray()}function Pf(r){if(r==="P-256")return dg;if(r==="P-384")return hg;if(r==="P-521")return pg;throw new C(`Invalid curve ${r}`)}async function Df(r="P-256"){let e=await _f(r);return new ts(e.privateKey)}var Zt=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=Lf(this.jwk)),this._raw}toMultihash(){return Xe.digest(We(this))}toCID(){return fe.createV1(114,this.toMultihash())}toString(){return ee.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Z(this.raw,e.raw)}async verify(e,t,n){return If(this.jwk,t,e,n)}},ts=class{type="ECDSA";jwk;publicKey;_raw;constructor(e){this.jwk=e,this.publicKey=new Zt({crv:e.crv,ext:e.ext,key_ops:["verify"],kty:"EC",x:e.x,y:e.y})}get raw(){return this._raw==null&&(this._raw=Tf(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Z(this.raw,e.raw)}async sign(e,t){return Af(this.jwk,e,t)}};function Qt(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function at(r,e=""){if(!Number.isSafeInteger(r)||r<0){let t=e&&`"${e}" `;throw new Error(`${t}expected integer >= 0, got ${r}`)}}function V(r,e,t=""){let n=Qt(r),o=r?.length,s=e!==void 0;if(!n||s&&o!==e){let i=t&&`"${t}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function rs(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");at(r.outputLen),at(r.blockLen)}function Mr(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function Rf(r,e){V(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length<t)throw new Error('"digestInto() output" expected to be of length >='+t)}function bt(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function ns(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Je(r,e){return r<<32-e|r>>>e}var Of=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",bg=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function wt(r){if(V(r),Of)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=bg[r[t]];return e}var yt={_0:48,_9:57,A:65,F:70,a:97,f:102};function kf(r){if(r>=yt._0&&r<=yt._9)return r-yt._0;if(r>=yt.A&&r<=yt.F)return r-(yt.A-10);if(r>=yt.a&&r<=yt.f)return r-(yt.a-10)}function xt(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(Of)return Uint8Array.fromHex(r);let e=r.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let o=0,s=0;o<t;o++,s+=2){let i=kf(r.charCodeAt(s)),a=kf(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function Fe(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];V(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let s=r[n];t.set(s,o),o+=s.length}return t}function Ja(r,e={}){let t=(o,s)=>r(s).update(o).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=o=>r(o),Object.assign(t,e),Object.freeze(t)}function Mt(r=32){let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(r))}var ec=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function Nf(r,e,t){return r&e^~r&t}function Mf(r,e,t){return r&e^r&t^e&t}var Bn=class{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,o){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=ns(this.buffer)}update(e){Mr(this),V(e);let{view:t,buffer:n,blockLen:o}=this,s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=ns(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Mr(this),Rf(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,bt(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let f=i;f<o;f++)t[f]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=ns(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)a.setUint32(4*f,l[f],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},Et=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var we=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var os=BigInt(4294967295),Bf=BigInt(32);function wg(r,e=!1){return e?{h:Number(r&os),l:Number(r>>Bf&os)}:{h:Number(r>>Bf&os)|0,l:Number(r&os)|0}}function Ff(r,e=!1){let t=r.length,n=new Uint32Array(t),o=new Uint32Array(t);for(let s=0;s<t;s++){let{h:i,l:a}=wg(r[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var tc=(r,e,t)=>r>>>t,rc=(r,e,t)=>r<<32-t|e>>>t,Jt=(r,e,t)=>r>>>t|e<<32-t,er=(r,e,t)=>r<<32-t|e>>>t,Fn=(r,e,t)=>r<<64-t|e>>>t-32,Un=(r,e,t)=>r>>>t-32|e<<64-t;function ct(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var Uf=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),Kf=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,qf=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),$f=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,Vf=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),zf=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var Eg=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Bt=new Uint32Array(64),nc=class extends Bn{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,t,n,o,s,i,a,c]}set(e,t,n,o,s,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let f=0;f<16;f++,t+=4)Bt[f]=e.getUint32(t,!1);for(let f=16;f<64;f++){let d=Bt[f-15],h=Bt[f-2],p=Je(d,7)^Je(d,18)^d>>>3,y=Je(h,17)^Je(h,19)^h>>>10;Bt[f]=y+Bt[f-7]+p+Bt[f-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:l}=this;for(let f=0;f<64;f++){let d=Je(a,6)^Je(a,11)^Je(a,25),h=l+d+Nf(a,c,u)+Eg[f]+Bt[f]|0,y=(Je(n,2)^Je(n,13)^Je(n,22))+Mf(n,o,s)|0;l=u,u=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+y|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(n,o,s,i,a,c,u,l)}roundClean(){bt(Bt)}destroy(){this.set(0,0,0,0,0,0,0,0),bt(this.buffer)}},oc=class extends nc{A=Et[0]|0;B=Et[1]|0;C=Et[2]|0;D=Et[3]|0;E=Et[4]|0;F=Et[5]|0;G=Et[6]|0;H=Et[7]|0;constructor(){super(32)}};var Hf=Ff(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(r=>BigInt(r))),vg=Hf[0],Sg=Hf[1],Ft=new Uint32Array(80),Ut=new Uint32Array(80),sc=class extends Bn{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:u,El:l,Fh:f,Fl:d,Gh:h,Gl:p,Hh:y,Hl:g}=this;return[e,t,n,o,s,i,a,c,u,l,f,d,h,p,y,g]}set(e,t,n,o,s,i,a,c,u,l,f,d,h,p,y,g){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=f|0,this.Fl=d|0,this.Gh=h|0,this.Gl=p|0,this.Hh=y|0,this.Hl=g|0}process(e,t){for(let E=0;E<16;E++,t+=4)Ft[E]=e.getUint32(t),Ut[E]=e.getUint32(t+=4);for(let E=16;E<80;E++){let I=Ft[E-15]|0,O=Ut[E-15]|0,$=Jt(I,O,1)^Jt(I,O,8)^tc(I,O,7),q=er(I,O,1)^er(I,O,8)^rc(I,O,7),S=Ft[E-2]|0,v=Ut[E-2]|0,B=Jt(S,v,19)^Fn(S,v,61)^tc(S,v,6),z=er(S,v,19)^Un(S,v,61)^rc(S,v,6),k=qf(q,z,Ut[E-7],Ut[E-16]),w=$f(k,$,B,Ft[E-7],Ft[E-16]);Ft[E]=w|0,Ut[E]=k|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:l,Eh:f,El:d,Fh:h,Fl:p,Gh:y,Gl:g,Hh:m,Hl:_}=this;for(let E=0;E<80;E++){let I=Jt(f,d,14)^Jt(f,d,18)^Fn(f,d,41),O=er(f,d,14)^er(f,d,18)^Un(f,d,41),$=f&h^~f&y,q=d&p^~d&g,S=Vf(_,O,q,Sg[E],Ut[E]),v=zf(S,m,I,$,vg[E],Ft[E]),B=S|0,z=Jt(n,o,28)^Fn(n,o,34)^Fn(n,o,39),k=er(n,o,28)^Un(n,o,34)^Un(n,o,39),w=n&s^n&a^s&a,x=o&i^o&c^i&c;m=y|0,_=g|0,y=h|0,g=p|0,h=f|0,p=d|0,{h:f,l:d}=ct(u|0,l|0,v|0,B|0),u=a|0,l=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let b=Uf(B,k,x);n=Kf(b,v,z,w),o=b|0}({h:n,l:o}=ct(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=ct(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=ct(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=ct(this.Dh|0,this.Dl|0,u|0,l|0),{h:f,l:d}=ct(this.Eh|0,this.El|0,f|0,d|0),{h,l:p}=ct(this.Fh|0,this.Fl|0,h|0,p|0),{h:y,l:g}=ct(this.Gh|0,this.Gl|0,y|0,g|0),{h:m,l:_}=ct(this.Hh|0,this.Hl|0,m|0,_|0),this.set(n,o,s,i,a,c,u,l,f,d,h,p,y,g,m,_)}roundClean(){bt(Ft,Ut)}destroy(){bt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},ic=class extends sc{Ah=we[0]|0;Al=we[1]|0;Bh=we[2]|0;Bl=we[3]|0;Ch=we[4]|0;Cl=we[5]|0;Dh=we[6]|0;Dl=we[7]|0;Eh=we[8]|0;El=we[9]|0;Fh=we[10]|0;Fl=we[11]|0;Gh=we[12]|0;Gl=we[13]|0;Hh=we[14]|0;Hl=we[15]|0;constructor(){super(64)}};var Br=Ja(()=>new oc,ec(1));var Wf=Ja(()=>new ic,ec(3));var cc=BigInt(0),ac=BigInt(1);function vt(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}" `;throw new Error(t+"expected boolean, got type="+typeof r)}return r}function Gf(r){if(typeof r=="bigint"){if(!ss(r))throw new Error("positive bigint expected, got "+r)}else at(r);return r}function Kn(r){let e=Gf(r).toString(16);return e.length&1?"0"+e:e}function Yf(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?cc:BigInt("0x"+r)}function Fr(r){return Yf(wt(r))}function tr(r){return Yf(wt(as(V(r)).reverse()))}function is(r,e){at(e),r=Gf(r);let t=xt(r.toString(16).padStart(e*2,"0"));if(t.length!==e)throw new Error("number too large");return t}function lc(r,e){return is(r,e).reverse()}function as(r){return Uint8Array.from(r)}var ss=r=>typeof r=="bigint"&&cc<=r;function _g(r,e,t){return ss(r)&&ss(e)&&ss(t)&&e<=r&&r<t}function qn(r,e,t,n){if(!_g(e,t,n))throw new Error("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function uc(r){let e;for(e=0;r>cc;r>>=ac,e+=1);return e}var $n=r=>(ac<<BigInt(r))-ac;function jf(r,e,t){if(at(r,"hashLen"),at(e,"qByteLen"),typeof t!="function")throw new Error("hmacFn must be a function");let n=g=>new Uint8Array(g),o=Uint8Array.of(),s=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(r),u=n(r),l=0,f=()=>{c.fill(1),u.fill(0),l=0},d=(...g)=>t(u,Fe(c,...g)),h=(g=o)=>{u=d(s,g),c=d(),g.length!==0&&(u=d(i,g),c=d())},p=()=>{if(l++>=a)throw new Error("drbg: tried max amount of iterations");let g=0,m=[];for(;g<e;){c=d();let _=c.slice();m.push(_),g+=c.length}return Fe(...m)};return(g,m)=>{f(),h(g);let _;for(;!(_=m(p()));)h();return f(),_}}function Kt(r,e={},t={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function n(s,i,a){let c=r[s];if(a&&c===void 0)return;let u=typeof c;if(u!==i||c===null)throw new Error(`param "${s}" is invalid: expected ${i}, got ${u}`)}let o=(s,i)=>Object.entries(s).forEach(([a,c])=>n(a,c,i));o(e,!1),o(t,!0)}function Ur(r){let e=new WeakMap;return(t,...n)=>{let o=e.get(t);if(o!==void 0)return o;let s=r(t,...n);return e.set(t,s),s}}var De=BigInt(0),he=BigInt(1),rr=BigInt(2),Qf=BigInt(3),Jf=BigInt(4),ed=BigInt(5),Ag=BigInt(7),td=BigInt(8),Ig=BigInt(9),rd=BigInt(16);function de(r,e){let t=r%e;return t>=De?t:e+t}function oe(r,e,t){let n=r;for(;e-- >De;)n*=n,n%=t;return n}function Xf(r,e){if(r===De)throw new Error("invert: expected non-zero number");if(e<=De)throw new Error("invert: expected positive modulus, got "+e);let t=de(r,e),n=e,o=De,s=he,i=he,a=De;for(;t!==De;){let u=n/t,l=n%t,f=o-i*u,d=s-a*u;n=t,t=l,o=i,s=a,i=f,a=d}if(n!==he)throw new Error("invert: does not exist");return de(o,e)}function dc(r,e,t){if(!r.eql(r.sqr(e),t))throw new Error("Cannot find square root")}function nd(r,e){let t=(r.ORDER+he)/Jf,n=r.pow(e,t);return dc(r,n,e),n}function Cg(r,e){let t=(r.ORDER-ed)/td,n=r.mul(e,rr),o=r.pow(n,t),s=r.mul(e,o),i=r.mul(r.mul(s,rr),o),a=r.mul(s,r.sub(i,r.ONE));return dc(r,a,e),a}function Tg(r){let e=Kr(r),t=od(r),n=t(e,e.neg(e.ONE)),o=t(e,n),s=t(e,e.neg(n)),i=(r+Ag)/rd;return(a,c)=>{let u=a.pow(c,i),l=a.mul(u,n),f=a.mul(u,o),d=a.mul(u,s),h=a.eql(a.sqr(l),c),p=a.eql(a.sqr(f),c);u=a.cmov(u,l,h),l=a.cmov(d,f,p);let y=a.eql(a.sqr(l),c),g=a.cmov(u,l,y);return dc(a,g,c),g}}function od(r){if(r<Qf)throw new Error("sqrt is not defined for small field");let e=r-he,t=0;for(;e%rr===De;)e/=rr,t++;let n=rr,o=Kr(r);for(;Zf(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return nd;let s=o.pow(n,e),i=(e+he)/rr;return function(c,u){if(c.is0(u))return u;if(Zf(c,u)!==1)throw new Error("Cannot find square root");let l=t,f=c.mul(c.ONE,s),d=c.pow(u,e),h=c.pow(u,i);for(;!c.eql(d,c.ONE);){if(c.is0(d))return c.ZERO;let p=1,y=c.sqr(d);for(;!c.eql(y,c.ONE);)if(p++,y=c.sqr(y),p===l)throw new Error("Cannot find square root");let g=he<<BigInt(l-p-1),m=c.pow(f,g);l=p,f=c.sqr(m),d=c.mul(d,f),h=c.mul(h,m)}return h}}function Lg(r){return r%Jf===Qf?nd:r%td===ed?Cg:r%rd===Ig?Tg(r):od(r)}var sd=(r,e)=>(de(r,e)&he)===he,Pg=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function hc(r){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=Pg.reduce((n,o)=>(n[o]="function",n),e);return Kt(r,t),r}function Dg(r,e,t){if(t<De)throw new Error("invalid exponent, negatives unsupported");if(t===De)return r.ONE;if(t===he)return e;let n=r.ONE,o=e;for(;t>De;)t&he&&(n=r.mul(n,o)),o=r.sqr(o),t>>=he;return n}function Vn(r,e,t=!1){let n=new Array(e.length).fill(t?r.ZERO:void 0),o=e.reduce((i,a,c)=>r.is0(a)?i:(n[c]=i,r.mul(i,a)),r.ONE),s=r.inv(o);return e.reduceRight((i,a,c)=>r.is0(a)?i:(n[c]=r.mul(i,n[c]),r.mul(i,a)),s),n}function Zf(r,e){let t=(r.ORDER-he)/rr,n=r.pow(e,t),o=r.eql(n,r.ONE),s=r.eql(n,r.ZERO),i=r.eql(n,r.neg(r.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function kg(r,e){e!==void 0&&at(e);let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}var fc=class{ORDER;BITS;BYTES;isLE;ZERO=De;ONE=he;_lengths;_sqrt;_mod;constructor(e,t={}){if(e<=De)throw new Error("invalid field: expected ORDER > 0, got "+e);let n;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(n=t.BITS),typeof t.sqrt=="function"&&(this.sqrt=t.sqrt),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=t.allowedLengths?.slice()),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:o,nByteLength:s}=kg(e,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return de(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return De<=e&&e<this.ORDER}is0(e){return e===De}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&he)===he}neg(e){return de(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return de(e*e,this.ORDER)}add(e,t){return de(e+t,this.ORDER)}sub(e,t){return de(e-t,this.ORDER)}mul(e,t){return de(e*t,this.ORDER)}pow(e,t){return Dg(this,e,t)}div(e,t){return de(e*Xf(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return Xf(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=Lg(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?lc(e,this.BYTES):is(e,this.BYTES)}fromBytes(e,t=!1){V(e);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(!n.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let u=new Uint8Array(o);u.set(e,s?0:u.length-e.length),e=u}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?tr(e):Fr(e);if(a&&(c=de(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Vn(this,e)}cmov(e,t,n){return n?t:e}};function Kr(r,e={}){return new fc(r,e)}function id(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let e=r.toString(2).length;return Math.ceil(e/8)}function pc(r){let e=id(r);return e+Math.ceil(e/2)}function mc(r,e,t=!1){V(r);let n=r.length,o=id(e),s=pc(e);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=t?tr(r):Fr(r),a=de(i,e-he)+he;return t?lc(a,o):is(a,o)}var qr=BigInt(0),nr=BigInt(1);function zn(r,e){let t=e.negate();return r?t:e}function or(r,e){let t=Vn(r.Fp,e.map(n=>n.Z));return e.map((n,o)=>r.fromAffine(n.toAffine(t[o])))}function ud(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function gc(r,e){ud(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1),o=2**r,s=$n(r),i=BigInt(r);return{windows:t,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function ad(r,e,t){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=t,a=Number(r&o),c=r>>i;a>n&&(a-=s,c+=nr);let u=e*n,l=u+Math.abs(a)-1,f=a===0,d=a<0,h=e%2!==0;return{nextN:c,offset:l,isZero:f,isNeg:d,isNegF:h,offsetF:u}}var yc=new WeakMap,fd=new WeakMap;function bc(r){return fd.get(r)||1}function cd(r){if(r!==qr)throw new Error("invalid wNAF")}var $r=class{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let o=e;for(;t>qr;)t&nr&&(n=n.add(o)),o=o.double(),t>>=nr;return n}precomputeWindow(e,t){let{windows:n,windowSize:o}=gc(t,this.bits),s=[],i=e,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let u=1;u<o;u++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=gc(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:u,isZero:l,isNeg:f,isNegF:d,offsetF:h}=ad(n,a,i);n=c,l?s=s.add(zn(d,t[h])):o=o.add(zn(f,t[u]))}return cd(n),{p:o,f:s}}wNAFUnsafe(e,t,n,o=this.ZERO){let s=gc(e,this.bits);for(let i=0;i<s.windows&&n!==qr;i++){let{nextN:a,offset:c,isZero:u,isNeg:l}=ad(n,i,s);if(n=a,!u){let f=t[c];o=o.add(l?f.negate():f)}}return cd(n),o}getPrecomputes(e,t,n){let o=yc.get(t);return o||(o=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(o=n(o)),yc.set(t,o))),o}cached(e,t,n){let o=bc(e);return this.wNAF(o,this.getPrecomputes(o,e,n),t)}unsafe(e,t,n,o){let s=bc(e);return s===1?this._unsafeLadder(e,t,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),t,o)}createCache(e,t){ud(t,this.bits),fd.set(e,t),yc.delete(e)}hasCache(e){return bc(e)!==1}};function dd(r,e,t,n){let o=e,s=r.ZERO,i=r.ZERO;for(;t>qr||n>qr;)t&nr&&(s=s.add(o)),n&nr&&(i=i.add(o)),o=o.double(),t>>=nr,n>>=nr;return{p1:s,p2:i}}function ld(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return hc(e),e}else return Kr(r,{isLE:t})}function cs(r,e,t={},n){if(n===void 0&&(n=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let u=e[c];if(!(typeof u=="bigint"&&u>qr))throw new Error(`CURVE.${c} must be positive bigint`)}let o=ld(e.p,t.Fp,n),s=ld(e.n,t.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}function ls(r,e){return function(n){let o=r(n);return{secretKey:o,publicKey:e(o)}}}var qt=BigInt(0),pe=BigInt(1),wc=BigInt(2),Rg=BigInt(8);function Og(r,e,t,n){let o=r.sqr(t),s=r.sqr(n),i=r.add(r.mul(e.a,o),s),a=r.add(r.ONE,r.mul(e.d,r.mul(o,s)));return r.eql(i,a)}function hd(r,e={}){let t=cs("edwards",r,e,e.FpFnLE),{Fp:n,Fn:o}=t,s=t.CURVE,{h:i}=s;Kt(e,{},{uvRatio:"function"});let a=wc<<BigInt(o.BYTES*8)-pe,c=g=>n.create(g),u=e.uvRatio||((g,m)=>{try{return{isValid:!0,value:n.sqrt(n.div(g,m))}}catch{return{isValid:!1,value:qt}}});if(!Og(n,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function l(g,m,_=!1){let E=_?pe:qt;return qn("coordinate "+g,m,E,a),m}function f(g){if(!(g instanceof p))throw new Error("EdwardsPoint expected")}let d=Ur((g,m)=>{let{X:_,Y:E,Z:I}=g,O=g.is0();m==null&&(m=O?Rg:n.inv(I));let $=c(_*m),q=c(E*m),S=n.mul(I,m);if(O)return{x:qt,y:pe};if(S!==pe)throw new Error("invZ was invalid");return{x:$,y:q}}),h=Ur(g=>{let{a:m,d:_}=s;if(g.is0())throw new Error("bad point: ZERO");let{X:E,Y:I,Z:O,T:$}=g,q=c(E*E),S=c(I*I),v=c(O*O),B=c(v*v),z=c(q*m),k=c(v*c(z+S)),w=c(B+c(_*c(q*S)));if(k!==w)throw new Error("bad point: equation left != right (1)");let x=c(E*I),b=c(O*$);if(x!==b)throw new Error("bad point: equation left != right (2)");return!0});class p{static BASE=new p(s.Gx,s.Gy,pe,c(s.Gx*s.Gy));static ZERO=new p(qt,pe,pe,qt);static Fp=n;static Fn=o;X;Y;Z;T;constructor(m,_,E,I){this.X=l("x",m),this.Y=l("y",_),this.Z=l("z",E,!0),this.T=l("t",I),Object.freeze(this)}static CURVE(){return s}static fromAffine(m){if(m instanceof p)throw new Error("extended point not allowed");let{x:_,y:E}=m||{};return l("x",_),l("y",E),new p(_,E,pe,c(_*E))}static fromBytes(m,_=!1){let E=n.BYTES,{a:I,d:O}=s;m=as(V(m,E,"point")),vt(_,"zip215");let $=as(m),q=m[E-1];$[E-1]=q&-129;let S=tr($),v=_?a:n.ORDER;qn("point.y",S,qt,v);let B=c(S*S),z=c(B-pe),k=c(O*B-I),{isValid:w,value:x}=u(z,k);if(!w)throw new Error("bad point: invalid y coordinate");let b=(x&pe)===pe,A=(q&128)!==0;if(!_&&x===qt&&A)throw new Error("bad point: x=0 and x_0=1");return A!==b&&(x=c(-x)),p.fromAffine({x,y:S})}static fromHex(m,_=!1){return p.fromBytes(xt(m),_)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(m=8,_=!0){return y.createCache(this,m),_||this.multiply(wc),this}assertValidity(){h(this)}equals(m){f(m);let{X:_,Y:E,Z:I}=this,{X:O,Y:$,Z:q}=m,S=c(_*q),v=c(O*I),B=c(E*q),z=c($*I);return S===v&&B===z}is0(){return this.equals(p.ZERO)}negate(){return new p(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:m}=s,{X:_,Y:E,Z:I}=this,O=c(_*_),$=c(E*E),q=c(wc*c(I*I)),S=c(m*O),v=_+E,B=c(c(v*v)-O-$),z=S+$,k=z-q,w=S-$,x=c(B*k),b=c(z*w),A=c(B*w),T=c(k*z);return new p(x,b,T,A)}add(m){f(m);let{a:_,d:E}=s,{X:I,Y:O,Z:$,T:q}=this,{X:S,Y:v,Z:B,T:z}=m,k=c(I*S),w=c(O*v),x=c(q*E*z),b=c($*B),A=c((I+O)*(S+v)-k-w),T=b-x,D=b+x,R=c(w-_*k),P=c(A*T),M=c(D*R),K=c(A*R),ie=c(T*D);return new p(P,M,ie,K)}subtract(m){return this.add(m.negate())}multiply(m){if(!o.isValidNot0(m))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:_,f:E}=y.cached(this,m,I=>or(p,I));return or(p,[_,E])[0]}multiplyUnsafe(m,_=p.ZERO){if(!o.isValid(m))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return m===qt?p.ZERO:this.is0()||m===pe?this:y.unsafe(this,m,E=>or(p,E),_)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return y.unsafe(this,s.n).is0()}toAffine(m){return d(this,m)}clearCofactor(){return i===pe?this:this.multiplyUnsafe(i)}toBytes(){let{x:m,y:_}=this.toAffine(),E=n.toBytes(_);return E[E.length-1]|=m&pe?128:0,E}toHex(){return wt(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let y=new $r(p,o.BITS);return p.BASE.precompute(8),p}function pd(r,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');Kt(t,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=t,{BASE:o,Fp:s,Fn:i}=r,a=t.randomBytes||Mt,c=t.adjustScalarBytes||(S=>S),u=t.domain||((S,v,B)=>{if(vt(B,"phflag"),v.length||B)throw new Error("Contexts/pre-hash are not supported");return S});function l(S){return i.create(tr(S))}function f(S){let v=E.secretKey;V(S,E.secretKey,"secretKey");let B=V(e(S),2*v,"hashedSecretKey"),z=c(B.slice(0,v)),k=B.slice(v,2*v),w=l(z);return{head:z,prefix:k,scalar:w}}function d(S){let{head:v,prefix:B,scalar:z}=f(S),k=o.multiply(z),w=k.toBytes();return{head:v,prefix:B,scalar:z,point:k,pointBytes:w}}function h(S){return d(S).pointBytes}function p(S=Uint8Array.of(),...v){let B=Fe(...v);return l(e(u(B,V(S,void 0,"context"),!!n)))}function y(S,v,B={}){S=V(S,void 0,"message"),n&&(S=n(S));let{prefix:z,scalar:k,pointBytes:w}=d(v),x=p(B.context,z,S),b=o.multiply(x).toBytes(),A=p(B.context,b,w,S),T=i.create(x+A*k);if(!i.isValid(T))throw new Error("sign failed: invalid s");let D=Fe(b,i.toBytes(T));return V(D,E.signature,"result")}let g={zip215:!0};function m(S,v,B,z=g){let{context:k,zip215:w}=z,x=E.signature;S=V(S,x,"signature"),v=V(v,void 0,"message"),B=V(B,E.publicKey,"publicKey"),w!==void 0&&vt(w,"zip215"),n&&(v=n(v));let b=x/2,A=S.subarray(0,b),T=tr(S.subarray(b,x)),D,R,P;try{D=r.fromBytes(B,w),R=r.fromBytes(A,w),P=o.multiplyUnsafe(T)}catch{return!1}if(!w&&D.isSmallOrder())return!1;let M=p(k,R.toBytes(),D.toBytes(),v);return R.add(D.multiplyUnsafe(M)).subtract(P).clearCofactor().is0()}let _=s.BYTES,E={secretKey:_,publicKey:_,signature:2*_,seed:_};function I(S=a(E.seed)){return V(S,E.seed,"seed")}function O(S){return Qt(S)&&S.length===i.BYTES}function $(S,v){try{return!!r.fromBytes(S,v)}catch{return!1}}let q={getExtendedPublicKey:d,randomSecretKey:I,isValidSecretKey:O,isValidPublicKey:$,toMontgomery(S){let{y:v}=r.fromBytes(S),B=E.publicKey,z=B===32;if(!z&&B!==57)throw new Error("only defined for 25519 and 448");let k=z?s.div(pe+v,pe-v):s.div(v-pe,v+pe);return s.toBytes(k)},toMontgomerySecret(S){let v=E.secretKey;V(S,v);let B=e(S.subarray(0,v));return c(B).subarray(0,v)}};return Object.freeze({keygen:ls(I,h),getPublicKey:h,sign:y,verify:m,utils:q,Point:r,lengths:E})}var Ng=BigInt(1),md=BigInt(2);var Mg=BigInt(5),Bg=BigInt(8),xc=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Fg={p:xc,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Bg,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Ug(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=xc,a=r*r%s*r%s,c=oe(a,md,s)*a%s,u=oe(c,Ng,s)*r%s,l=oe(u,Mg,s)*u%s,f=oe(l,e,s)*l%s,d=oe(f,t,s)*f%s,h=oe(d,n,s)*d%s,p=oe(h,o,s)*h%s,y=oe(p,o,s)*h%s,g=oe(y,e,s)*l%s;return{pow_p_5_8:oe(g,md,s)*r%s,b2:a}}function Kg(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var gd=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function qg(r,e){let t=xc,n=de(e*e*e,t),o=de(n*n*e,t),s=Ug(r*o).pow_p_5_8,i=de(r*n*s,t),a=de(e*i*i,t),c=i,u=de(i*gd,t),l=a===r,f=a===de(-r,t),d=a===de(-r*gd,t);return l&&(i=c),(f||d)&&(i=u),sd(i,t)&&(i=de(-i,t)),{isValid:l||f,value:i}}var $g=hd(Fg,{uvRatio:qg});function Vg(r){return pd($g,Wf,Object.assign({adjustScalarBytes:Kg},r))}var Hn=Vg({});var Wn=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},Gn=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},us=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var yd={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new us("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/blob/main/packages/crypto/README.md#web-crypto-api");return e}};var Ue=yd;var fs=32,Yn=64,Ec=32;var Vr,bd=(async()=>{try{return await Ue.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function wd(){let r=Hn.utils.randomSecretKey(),e=Hn.getPublicKey(r);return{privateKey:Yg(r,e),publicKey:e}}async function zg(r,e){let t;r.length===Yn?t=r.subarray(0,32):t=r;let n={crv:"Ed25519",kty:"OKP",x:U(r.subarray(32),"base64url"),d:U(t,"base64url"),ext:!0,key_ops:["sign"]},o=await Ue.get().subtle.importKey("jwk",n,{name:"Ed25519"},!0,["sign"]),s=await Ue.get().subtle.sign({name:"Ed25519"},o,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(s,0,s.byteLength)}function Hg(r,e){let t=r.subarray(0,Ec);return Hn.sign(e instanceof Uint8Array?e:e.subarray(),t)}async function xd(r,e){return Vr==null&&(Vr=await bd),Vr?zg(r,e):Hg(r,e)}async function Wg(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await Ue.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await Ue.get().subtle.verify({name:"Ed25519"},n,e,t instanceof Uint8Array?t:t.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function Gg(r,e,t){return Hn.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function Ed(r,e,t){return Vr==null&&(Vr=await bd),Vr?Wg(r,e,t):Gg(r,e,t)}function Yg(r,e){let t=new Uint8Array(Yn);for(let n=0;n<Ec;n++)t[n]=r[n],t[Ec+n]=e[n];return t}function zr(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var jn=class{type="Ed25519";raw;constructor(e){this.raw=hs(e,fs)}toMultihash(){return Xe.digest(We(this))}toCID(){return fe.createV1(114,this.toMultihash())}toString(){return ee.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Z(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let o=Ed(this.raw,t,e);return zr(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}},ds=class{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=hs(e,Yn),this.publicKey=new jn(t)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Z(this.raw,e.raw)}sign(e,t){t?.signal?.throwIfAborted();let n=xd(this.raw,e);return zr(n)?n.then(o=>(t?.signal?.throwIfAborted(),o)):(t?.signal?.throwIfAborted(),n)}};function vc(r){return r=hs(r,fs),new jn(r)}async function Sd(){let{privateKey:r,publicKey:e}=wd();return new ds(r,e)}function hs(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new C(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var jg=Math.pow(2,7),Xg=Math.pow(2,14),Zg=Math.pow(2,21),Sc=Math.pow(2,28),_c=Math.pow(2,35),Ac=Math.pow(2,42),Ic=Math.pow(2,49),j=128,_e=127;function me(r){if(r<jg)return 1;if(r<Xg)return 2;if(r<Zg)return 3;if(r<Sc)return 4;if(r<_c)return 5;if(r<Ac)return 6;if(r<Ic)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Hr(r,e,t=0){switch(me(r)){case 8:e[t++]=r&255|j,r/=128;case 7:e[t++]=r&255|j,r/=128;case 6:e[t++]=r&255|j,r/=128;case 5:e[t++]=r&255|j,r/=128;case 4:e[t++]=r&255|j,r>>>=7;case 3:e[t++]=r&255|j,r>>>=7;case 2:e[t++]=r&255|j,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function Qg(r,e,t=0){switch(me(r)){case 8:e.set(t++,r&255|j),r/=128;case 7:e.set(t++,r&255|j),r/=128;case 6:e.set(t++,r&255|j),r/=128;case 5:e.set(t++,r&255|j),r/=128;case 4:e.set(t++,r&255|j),r>>>=7;case 3:e.set(t++,r&255|j),r>>>=7;case 2:e.set(t++,r&255|j),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function Cc(r,e){let t=r[e],n=0;if(n+=t&_e,t<j||(t=r[e+1],n+=(t&_e)<<7,t<j)||(t=r[e+2],n+=(t&_e)<<14,t<j)||(t=r[e+3],n+=(t&_e)<<21,t<j)||(t=r[e+4],n+=(t&_e)*Sc,t<j)||(t=r[e+5],n+=(t&_e)*_c,t<j)||(t=r[e+6],n+=(t&_e)*Ac,t<j)||(t=r[e+7],n+=(t&_e)*Ic,t<j))return n;throw new RangeError("Could not decode varint")}function Jg(r,e){let t=r.get(e),n=0;if(n+=t&_e,t<j||(t=r.get(e+1),n+=(t&_e)<<7,t<j)||(t=r.get(e+2),n+=(t&_e)<<14,t<j)||(t=r.get(e+3),n+=(t&_e)<<21,t<j)||(t=r.get(e+4),n+=(t&_e)*Sc,t<j)||(t=r.get(e+5),n+=(t&_e)*_c,t<j)||(t=r.get(e+6),n+=(t&_e)*Ac,t<j)||(t=r.get(e+7),n+=(t&_e)*Ic,t<j))return n;throw new RangeError("Could not decode varint")}function $t(r,e,t=0){return e==null&&(e=Se(me(r))),e instanceof Uint8Array?Hr(r,e,t):Qg(r,e,t)}function sr(r,e=0){return r instanceof Uint8Array?Cc(r,e):Jg(r,e)}var Tc=new Float32Array([-0]),Vt=new Uint8Array(Tc.buffer);function _d(r,e,t){Tc[0]=r,e[t]=Vt[0],e[t+1]=Vt[1],e[t+2]=Vt[2],e[t+3]=Vt[3]}function Ad(r,e){return Vt[0]=r[e],Vt[1]=r[e+1],Vt[2]=r[e+2],Vt[3]=r[e+3],Tc[0]}var Lc=new Float64Array([-0]),Ae=new Uint8Array(Lc.buffer);function Id(r,e,t){Lc[0]=r,e[t]=Ae[0],e[t+1]=Ae[1],e[t+2]=Ae[2],e[t+3]=Ae[3],e[t+4]=Ae[4],e[t+5]=Ae[5],e[t+6]=Ae[6],e[t+7]=Ae[7]}function Cd(r,e){return Ae[0]=r[e],Ae[1]=r[e+1],Ae[2]=r[e+2],Ae[3]=r[e+3],Ae[4]=r[e+4],Ae[5]=r[e+5],Ae[6]=r[e+6],Ae[7]=r[e+7],Lc[0]}var e0=BigInt(Number.MAX_SAFE_INTEGER),t0=BigInt(Number.MIN_SAFE_INTEGER),qe=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return ir;if(e<e0&&e>t0)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>Td&&(o=0n,++n>Td&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return ir;let t=e<0;t&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):ir}},ir=new qe(0,0);ir.toBigInt=function(){return 0n};ir.zzEncode=ir.zzDecode=function(){return this};ir.length=function(){return 1};var Td=4294967296n;function Ld(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function Pd(r,e,t){if(t-e<1)return"";let o,s=[],i=0,a;for(;e<t;)a=r[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function Pc(r,e,t){let n=t,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function et(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function ps(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var Dc=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,et(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw et(this,4);return ps(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw et(this,4);return ps(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw et(this,4);let e=Ad(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw et(this,4);let e=Cd(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw et(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Pd(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw et(this,e);this.pos+=e}else do if(this.pos>=this.len)throw et(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new qe(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw et(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw et(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw et(this,8);let e=ps(this.buf,this.pos+=4),t=ps(this.buf,this.pos+=4);return new qe(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=Cc(this.buf,this.pos);return this.pos+=me(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function Zn(r){return new Dc(r instanceof Uint8Array?r:r.subarray())}function ke(r,e,t){let n=Zn(r);return e.decode(n,void 0,t)}function kc(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return Se(i);o+i>e&&(n=Se(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var ar=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function Rc(){}var Nc=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},r0=kc();function n0(r){return globalThis.Buffer!=null?Se(r):r0(r)}var Jn=class{len;head;tail;states;constructor(){this.len=0,this.head=new ar(Rc,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new ar(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Mc((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(ms,10,qe.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=qe.fromBigInt(e);return this._push(ms,t.length(),t)}uint64Number(e){return this._push(Hr,me(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=qe.fromBigInt(e).zzEncode();return this._push(ms,t.length(),t)}sint64Number(e){let t=qe.fromNumber(e).zzEncode();return this._push(ms,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Oc,1,e?1:0)}fixed32(e){return this._push(Qn,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=qe.fromBigInt(e);return this._push(Qn,4,t.lo)._push(Qn,4,t.hi)}fixed64Number(e){let t=qe.fromNumber(e);return this._push(Qn,4,t.lo)._push(Qn,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(_d,4,e)}double(e){return this._push(Id,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(Oc,1,0):this.uint32(t)._push(s0,t,e)}string(e){let t=Ld(e);return t!==0?this.uint32(t)._push(Pc,t,e):this._push(Oc,1,0)}fork(){return this.states=new Nc(this),this.head=this.tail=new ar(Rc,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new ar(Rc,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=n0(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function Oc(r,e,t){e[t]=r&255}function o0(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var Mc=class extends ar{next;constructor(e,t){super(o0,e,t),this.next=void 0}};function ms(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function Qn(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function s0(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(Jn.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(i0,e,r),this},Jn.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(a0,e,r),this});function i0(r,e,t){e.set(r,t)}function a0(r,e,t){r.length<40?Pc(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(L(r),t)}function Bc(){return new Jn}function Re(r,e){let t=Bc();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}function*Oe(r,e,t){let n=Zn(r);yield*e.stream(n,void 0,"$",t)}var gs={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function ys(r,e,t,n,o){return{name:r,type:e,encode:t,decode:n,stream:o}}function Fc(r){function e(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let t=function(i,a){let c=e(i);a.int32(c)},n=function(i){let a=i.int32();return e(a)},o=function*(i){let a=i.int32();yield e(a)};return ys("enum",gs.VARINT,t,n,o)}function Ne(r,e,t){return ys("message",gs.LENGTH_DELIMITED,r,e,t)}var Ge=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},eo=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var se;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(se||(se={}));var Uc;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(Uc||(Uc={}));(function(r){r.codec=()=>Fc(Uc)})(se||(se={}));var lt;(function(r){let e;r.codec=()=>(e==null&&(e=Ne((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),se.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.Type=se.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.Type`,value:se.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return Re(s,r.codec())}r.encode=t;function n(s,i){return ke(s,r.codec(),i)}r.decode=n;function o(s,i){return Oe(s,r.codec(),i)}r.stream=o})(lt||(lt={}));var Kc;(function(r){let e;r.codec=()=>(e==null&&(e=Ne((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),se.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.Type=se.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.Type`,value:se.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return Re(s,r.codec())}r.encode=t;function n(s,i){return ke(s,r.codec(),i)}r.decode=n;function o(s,i){return Oe(s,r.codec(),i)}r.stream=o})(Kc||(Kc={}));function Wr(r){if(isNaN(r)||r<=0)throw new C("random bytes length must be a Number bigger than 0");return Mt(r)}var ro={};Be(ro,{MAX_RSA_KEY_SIZE:()=>qc,generateRSAKeyPair:()=>Xc,jwkToJWKKeyPair:()=>Md,jwkToPkcs1:()=>f0,jwkToPkix:()=>Hc,jwkToRSAPrivateKey:()=>jc,pkcs1MessageToJwk:()=>Vc,pkcs1MessageToRSAPrivateKey:()=>Wc,pkcs1ToJwk:()=>u0,pkcs1ToRSAPrivateKey:()=>Nd,pkixMessageToJwk:()=>zc,pkixMessageToRSAPublicKey:()=>Yc,pkixToJwk:()=>d0,pkixToRSAPublicKey:()=>Gc});var Gr=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=ro.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return fe.createV1(114,this._multihash)}toString(){return ee.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Z(this.raw,e.raw)}verify(e,t,n){return Od(this.jwk,t,e,n)}},to=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=ro.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Z(this.raw,e.raw)}sign(e,t){return Rd(this.jwk,e,t)}};var qc=8192,$c=18,c0=1062,l0=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function u0(r){let e=gt(r);return Vc(e)}function Vc(r){return{n:U(r[1],"base64url"),e:U(r[2],"base64url"),d:U(r[3],"base64url"),p:U(r[4],"base64url"),q:U(r[5],"base64url"),dp:U(r[6],"base64url"),dq:U(r[7],"base64url"),qi:U(r[8],"base64url"),kty:"RSA"}}function f0(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new C("JWK was missing components");return Qe([Pe(Uint8Array.from([0])),Pe(L(r.n,"base64url")),Pe(L(r.e,"base64url")),Pe(L(r.d,"base64url")),Pe(L(r.p,"base64url")),Pe(L(r.q,"base64url")),Pe(L(r.dp,"base64url")),Pe(L(r.dq,"base64url")),Pe(L(r.qi,"base64url"))]).subarray()}function d0(r){let e=gt(r,{offset:0});return zc(e)}function zc(r){let e=gt(r[1],{offset:0});return{kty:"RSA",n:U(e[0],"base64url"),e:U(e[1],"base64url")}}function Hc(r){if(r.n==null||r.e==null)throw new C("JWK was missing components");return Qe([l0,Mn(Qe([Pe(L(r.n,"base64url")),Pe(L(r.e,"base64url"))]))]).subarray()}function Nd(r){let e=gt(r);return Wc(e)}function Wc(r){let e=Vc(r);return jc(e)}function Gc(r,e){if(r.byteLength>=c0)throw new Tr("Key size is too large");let t=gt(r,{offset:0});return Yc(t,r,e)}function Yc(r,e,t){let n=zc(r);if(t==null){let o=Br(lt.encode({Type:se.RSA,Data:e}));t=it($c,o)}return new Gr(n,t)}function jc(r){if(Fd(r)>qc)throw new C("Key size is too large");let e=Md(r),t=Br(lt.encode({Type:se.RSA,Data:Hc(e.publicKey)})),n=it($c,t);return new to(e.privateKey,new Gr(e.publicKey,n))}async function Xc(r){if(r>qc)throw new C("Key size is too large");let e=await Bd(r),t=Br(lt.encode({Type:se.RSA,Data:Hc(e.publicKey)})),n=it($c,t);return new to(e.privateKey,new Gr(e.publicKey,n))}function Md(r){if(r==null)throw new C("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function Bd(r,e){let t=await Ue.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);e?.signal?.throwIfAborted();let n=await h0(t,e);return{privateKey:n[0],publicKey:n[1]}}async function Rd(r,e,t){let n=await Ue.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let o=await Ue.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,e instanceof Uint8Array?e:e.subarray());return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function Od(r,e,t,n){let o=await Ue.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let s=await Ue.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,e,t instanceof Uint8Array?t:t.subarray());return n?.signal?.throwIfAborted(),s}async function h0(r,e){if(r.privateKey==null||r.publicKey==null)throw new C("Private and public key are required");let t=await Promise.all([Ue.get().subtle.exportKey("jwk",r.privateKey),Ue.get().subtle.exportKey("jwk",r.publicKey)]);return e?.signal?.throwIfAborted(),t}function Fd(r){if(r.kty!=="RSA")throw new C("invalid key type");if(r.n==null)throw new C("invalid key modulus");return L(r.n,"base64url").length*8}var bs=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if(rs(e),V(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(t.length>n?e.create().update(t).digest():t);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),bt(o)}update(e){return Mr(this),this.iHash.update(e),this}digestInto(e){Mr(this),V(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Zc=(r,e,t)=>new bs(r,e).update(t).digest();Zc.create=(r,e)=>new bs(r,e);var Ud=(r,e)=>(r+(r>=0?e:-e)/Kd)/e;function p0(r,e,t){let[[n,o],[s,i]]=e,a=Ud(i*r,t),c=Ud(-o*r,t),u=r-a*n-c*s,l=-a*o-c*i,f=u<St,d=l<St;f&&(u=-u),d&&(l=-l);let h=$n(Math.ceil(uc(t)/2))+Yr;if(u<St||u>=h||l<St||l>=h)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:f,k1:u,k2neg:d,k2:l}}function Jc(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function Qc(r,e){let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return vt(t.lowS,"lowS"),vt(t.prehash,"prehash"),t.format!==void 0&&Jc(t.format),t}var el=class extends Error{constructor(e=""){super(e)}},zt={Err:el,_tlv:{encode:(r,e)=>{let{Err:t}=zt;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,o=Kn(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let s=n>127?Kn(o.length/2|128):"";return Kn(r)+s+o+e},decode(r,e){let{Err:t}=zt,n=0;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let o=e[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let u=e.subarray(n,n+c);if(u.length!==c)throw new t("tlv.decode: length bytes not complete");if(u[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let l of u)i=i<<8|l;if(n+=c,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(r){let{Err:e}=zt;if(r<St)throw new e("integer: negative integers are not allowed");let t=Kn(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(r){let{Err:e}=zt;if(r[0]&128)throw new e("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Fr(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=zt,o=V(r,void 0,"signature"),{v:s,l:i}=n.decode(48,o);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:u,l}=n.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(u)}},hexFromSig(r){let{_tlv:e,_int:t}=zt,n=e.encode(2,t.encode(r.r)),o=e.encode(2,t.encode(r.s)),s=n+o;return e.encode(48,s)}},St=BigInt(0),Yr=BigInt(1),Kd=BigInt(2),ws=BigInt(3),m0=BigInt(4);function qd(r,e={}){let t=cs("weierstrass",r,e),{Fp:n,Fn:o}=t,s=t.CURVE,{h:i,n:a}=s;Kt(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c}=e;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let u=Vd(n,o);function l(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(k,w,x){let{x:b,y:A}=w.toAffine(),T=n.toBytes(b);if(vt(x,"isCompressed"),x){l();let D=!n.isOdd(A);return Fe($d(D),T)}else return Fe(Uint8Array.of(4),T,n.toBytes(A))}function d(k){V(k,void 0,"Point");let{publicKey:w,publicKeyUncompressed:x}=u,b=k.length,A=k[0],T=k.subarray(1);if(b===w&&(A===2||A===3)){let D=n.fromBytes(T);if(!n.isValid(D))throw new Error("bad point: is not on curve, wrong x");let R=y(D),P;try{P=n.sqrt(R)}catch(ie){let ne=ie instanceof Error?": "+ie.message:"";throw new Error("bad point: is not on curve, sqrt error"+ne)}l();let M=n.isOdd(P);return(A&1)===1!==M&&(P=n.neg(P)),{x:D,y:P}}else if(b===x&&A===4){let D=n.BYTES,R=n.fromBytes(T.subarray(0,D)),P=n.fromBytes(T.subarray(D,D*2));if(!g(R,P))throw new Error("bad point: is not on curve");return{x:R,y:P}}else throw new Error(`bad point: got length ${b}, expected compressed=${w} or uncompressed=${x}`)}let h=e.toBytes||f,p=e.fromBytes||d;function y(k){let w=n.sqr(k),x=n.mul(w,k);return n.add(n.add(x,n.mul(k,s.a)),s.b)}function g(k,w){let x=n.sqr(w),b=y(k);return n.eql(x,b)}if(!g(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let m=n.mul(n.pow(s.a,ws),m0),_=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(m,_)))throw new Error("bad curve params: a or b");function E(k,w,x=!1){if(!n.isValid(w)||x&&n.is0(w))throw new Error(`bad point coordinate ${k}`);return w}function I(k){if(!(k instanceof v))throw new Error("Weierstrass Point expected")}function O(k){if(!c||!c.basises)throw new Error("no endo");return p0(k,c.basises,o.ORDER)}let $=Ur((k,w)=>{let{X:x,Y:b,Z:A}=k;if(n.eql(A,n.ONE))return{x,y:b};let T=k.is0();w==null&&(w=T?n.ONE:n.inv(A));let D=n.mul(x,w),R=n.mul(b,w),P=n.mul(A,w);if(T)return{x:n.ZERO,y:n.ZERO};if(!n.eql(P,n.ONE))throw new Error("invZ was invalid");return{x:D,y:R}}),q=Ur(k=>{if(k.is0()){if(e.allowInfinityPoint&&!n.is0(k.Y))return;throw new Error("bad point: ZERO")}let{x:w,y:x}=k.toAffine();if(!n.isValid(w)||!n.isValid(x))throw new Error("bad point: x or y not field elements");if(!g(w,x))throw new Error("bad point: equation left != right");if(!k.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function S(k,w,x,b,A){return x=new v(n.mul(x.X,k),x.Y,x.Z),w=zn(b,w),x=zn(A,x),w.add(x)}class v{static BASE=new v(s.Gx,s.Gy,n.ONE);static ZERO=new v(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(w,x,b){this.X=E("x",w),this.Y=E("y",x,!0),this.Z=E("z",b),Object.freeze(this)}static CURVE(){return s}static fromAffine(w){let{x,y:b}=w||{};if(!w||!n.isValid(x)||!n.isValid(b))throw new Error("invalid affine point");if(w instanceof v)throw new Error("projective point not allowed");return n.is0(x)&&n.is0(b)?v.ZERO:new v(x,b,n.ONE)}static fromBytes(w){let x=v.fromAffine(p(V(w,void 0,"point")));return x.assertValidity(),x}static fromHex(w){return v.fromBytes(xt(w))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(w=8,x=!0){return z.createCache(this,w),x||this.multiply(ws),this}assertValidity(){q(this)}hasEvenY(){let{y:w}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(w)}equals(w){I(w);let{X:x,Y:b,Z:A}=this,{X:T,Y:D,Z:R}=w,P=n.eql(n.mul(x,R),n.mul(T,A)),M=n.eql(n.mul(b,R),n.mul(D,A));return P&&M}negate(){return new v(this.X,n.neg(this.Y),this.Z)}double(){let{a:w,b:x}=s,b=n.mul(x,ws),{X:A,Y:T,Z:D}=this,R=n.ZERO,P=n.ZERO,M=n.ZERO,K=n.mul(A,A),ie=n.mul(T,T),ne=n.mul(D,D),G=n.mul(A,T);return G=n.add(G,G),M=n.mul(A,D),M=n.add(M,M),R=n.mul(w,M),P=n.mul(b,ne),P=n.add(R,P),R=n.sub(ie,P),P=n.add(ie,P),P=n.mul(R,P),R=n.mul(G,R),M=n.mul(b,M),ne=n.mul(w,ne),G=n.sub(K,ne),G=n.mul(w,G),G=n.add(G,M),M=n.add(K,K),K=n.add(M,K),K=n.add(K,ne),K=n.mul(K,G),P=n.add(P,K),ne=n.mul(T,D),ne=n.add(ne,ne),K=n.mul(ne,G),R=n.sub(R,K),M=n.mul(ne,ie),M=n.add(M,M),M=n.add(M,M),new v(R,P,M)}add(w){I(w);let{X:x,Y:b,Z:A}=this,{X:T,Y:D,Z:R}=w,P=n.ZERO,M=n.ZERO,K=n.ZERO,ie=s.a,ne=n.mul(s.b,ws),G=n.mul(x,T),ae=n.mul(b,D),be=n.mul(A,R),st=n.add(x,b),ce=n.add(T,D);st=n.mul(st,ce),ce=n.add(G,ae),st=n.sub(st,ce),ce=n.add(x,A);let ve=n.add(T,R);return ce=n.mul(ce,ve),ve=n.add(G,be),ce=n.sub(ce,ve),ve=n.add(b,A),P=n.add(D,R),ve=n.mul(ve,P),P=n.add(ae,be),ve=n.sub(ve,P),K=n.mul(ie,ce),P=n.mul(ne,be),K=n.add(P,K),P=n.sub(ae,K),K=n.add(ae,K),M=n.mul(P,K),ae=n.add(G,G),ae=n.add(ae,G),be=n.mul(ie,be),ce=n.mul(ne,ce),ae=n.add(ae,be),be=n.sub(G,be),be=n.mul(ie,be),ce=n.add(ce,be),G=n.mul(ae,ce),M=n.add(M,G),G=n.mul(ve,ce),P=n.mul(st,P),P=n.sub(P,G),G=n.mul(st,ae),K=n.mul(ve,K),K=n.add(K,G),new v(P,M,K)}subtract(w){return this.add(w.negate())}is0(){return this.equals(v.ZERO)}multiply(w){let{endo:x}=e;if(!o.isValidNot0(w))throw new Error("invalid scalar: out of range");let b,A,T=D=>z.cached(this,D,R=>or(v,R));if(x){let{k1neg:D,k1:R,k2neg:P,k2:M}=O(w),{p:K,f:ie}=T(R),{p:ne,f:G}=T(M);A=ie.add(G),b=S(x.beta,K,ne,D,P)}else{let{p:D,f:R}=T(w);b=D,A=R}return or(v,[b,A])[0]}multiplyUnsafe(w){let{endo:x}=e,b=this;if(!o.isValid(w))throw new Error("invalid scalar: out of range");if(w===St||b.is0())return v.ZERO;if(w===Yr)return b;if(z.hasCache(this))return this.multiply(w);if(x){let{k1neg:A,k1:T,k2neg:D,k2:R}=O(w),{p1:P,p2:M}=dd(v,b,T,R);return S(x.beta,P,M,A,D)}else return z.unsafe(b,w)}toAffine(w){return $(this,w)}isTorsionFree(){let{isTorsionFree:w}=e;return i===Yr?!0:w?w(v,this):z.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:w}=e;return i===Yr?this:w?w(v,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(w=!0){return vt(w,"isCompressed"),this.assertValidity(),h(v,this,w)}toHex(w=!0){return wt(this.toBytes(w))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let B=o.BITS,z=new $r(v,e.endo?Math.ceil(B/2):B);return v.BASE.precompute(8),v}function $d(r){return Uint8Array.of(r?2:3)}function Vd(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function g0(r,e={}){let{Fn:t}=r,n=e.randomBytes||Mt,o=Object.assign(Vd(r.Fp,t),{seed:pc(t.ORDER)});function s(h){try{let p=t.fromBytes(h);return t.isValidNot0(p)}catch{return!1}}function i(h,p){let{publicKey:y,publicKeyUncompressed:g}=o;try{let m=h.length;return p===!0&&m!==y||p===!1&&m!==g?!1:!!r.fromBytes(h)}catch{return!1}}function a(h=n(o.seed)){return mc(V(h,o.seed,"seed"),t.ORDER)}function c(h,p=!0){return r.BASE.multiply(t.fromBytes(h)).toBytes(p)}function u(h){let{secretKey:p,publicKey:y,publicKeyUncompressed:g}=o;if(!Qt(h)||"_lengths"in t&&t._lengths||p===y)return;let m=V(h,void 0,"key").length;return m===y||m===g}function l(h,p,y=!0){if(u(h)===!0)throw new Error("first arg must be private key");if(u(p)===!1)throw new Error("second arg must be public key");let g=t.fromBytes(h);return r.fromBytes(p).multiply(g).toBytes(y)}let f={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},d=ls(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:l,keygen:d,Point:r,utils:f,lengths:o})}function zd(r,e,t={}){rs(e),Kt(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let n=t.randomBytes||Mt,o=t.hmac||((x,b)=>Zc(e,x,b)),{Fp:s,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:u,getPublicKey:l,getSharedSecret:f,utils:d,lengths:h}=g0(r,t),p={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},y=a*Kd<s.ORDER;function g(x){let b=a>>Yr;return x>b}function m(x,b){if(!i.isValidNot0(b))throw new Error(`invalid signature ${x}: out of range 1..Point.Fn.ORDER`);return b}function _(){if(y)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function E(x,b){Jc(b);let A=h.signature,T=b==="compact"?A:b==="recovered"?A+1:void 0;return V(x,T)}class I{r;s;recovery;constructor(b,A,T){if(this.r=m("r",b),this.s=m("s",A),T!=null){if(_(),![0,1,2,3].includes(T))throw new Error("invalid recovery id");this.recovery=T}Object.freeze(this)}static fromBytes(b,A=p.format){E(b,A);let T;if(A==="der"){let{r:M,s:K}=zt.toSig(V(b));return new I(M,K)}A==="recovered"&&(T=b[0],A="compact",b=b.subarray(1));let D=h.signature/2,R=b.subarray(0,D),P=b.subarray(D,D*2);return new I(i.fromBytes(R),i.fromBytes(P),T)}static fromHex(b,A){return this.fromBytes(xt(b),A)}assertRecovery(){let{recovery:b}=this;if(b==null)throw new Error("invalid recovery id: must be present");return b}addRecoveryBit(b){return new I(this.r,this.s,b)}recoverPublicKey(b){let{r:A,s:T}=this,D=this.assertRecovery(),R=D===2||D===3?A+a:A;if(!s.isValid(R))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let P=s.toBytes(R),M=r.fromBytes(Fe($d((D&1)===0),P)),K=i.inv(R),ie=$(V(b,void 0,"msgHash")),ne=i.create(-ie*K),G=i.create(T*K),ae=r.BASE.multiplyUnsafe(ne).add(M.multiplyUnsafe(G));if(ae.is0())throw new Error("invalid recovery: point at infinify");return ae.assertValidity(),ae}hasHighS(){return g(this.s)}toBytes(b=p.format){if(Jc(b),b==="der")return xt(zt.hexFromSig(this));let{r:A,s:T}=this,D=i.toBytes(A),R=i.toBytes(T);return b==="recovered"?(_(),Fe(Uint8Array.of(this.assertRecovery()),D,R)):Fe(D,R)}toHex(b){return wt(this.toBytes(b))}}let O=t.bits2int||function(b){if(b.length>8192)throw new Error("input is too large");let A=Fr(b),T=b.length*8-c;return T>0?A>>BigInt(T):A},$=t.bits2int_modN||function(b){return i.create(O(b))},q=$n(c);function S(x){return qn("num < 2^"+c,x,St,q),i.toBytes(x)}function v(x,b){return V(x,void 0,"message"),b?V(e(x),void 0,"prehashed message"):x}function B(x,b,A){let{lowS:T,prehash:D,extraEntropy:R}=Qc(A,p);x=v(x,D);let P=$(x),M=i.fromBytes(b);if(!i.isValidNot0(M))throw new Error("invalid private key");let K=[S(M),S(P)];if(R!=null&&R!==!1){let ae=R===!0?n(h.secretKey):R;K.push(V(ae,void 0,"extraEntropy"))}let ie=Fe(...K),ne=P;function G(ae){let be=O(ae);if(!i.isValidNot0(be))return;let st=i.inv(be),ce=r.BASE.multiply(be).toAffine(),ve=i.create(ce.x);if(ve===St)return;let Uo=i.create(st*i.create(ne+ve*M));if(Uo===St)return;let Wu=(ce.x===ve?0:2)|Number(ce.y&Yr),Gu=Uo;return T&&g(Uo)&&(Gu=i.neg(Uo),Wu^=1),new I(ve,Gu,y?void 0:Wu)}return{seed:ie,k2sig:G}}function z(x,b,A={}){let{seed:T,k2sig:D}=B(x,b,A);return jf(e.outputLen,i.BYTES,o)(T,D).toBytes(A.format)}function k(x,b,A,T={}){let{lowS:D,prehash:R,format:P}=Qc(T,p);if(A=V(A,void 0,"publicKey"),b=v(b,R),!Qt(x)){let M=x instanceof I?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+M)}E(x,P);try{let M=I.fromBytes(x,P),K=r.fromBytes(A);if(D&&M.hasHighS())return!1;let{r:ie,s:ne}=M,G=$(b),ae=i.inv(ne),be=i.create(G*ae),st=i.create(ie*ae),ce=r.BASE.multiplyUnsafe(be).add(K.multiplyUnsafe(st));return ce.is0()?!1:i.create(ce.x)===ie}catch{return!1}}function w(x,b,A={}){let{prehash:T}=Qc(A,p);return b=v(b,T),I.fromBytes(x,"recovered").recoverPublicKey(b).toBytes()}return Object.freeze({keygen:u,getPublicKey:l,getSharedSecret:f,utils:d,lengths:h,Point:r,sign:z,verify:k,recoverPublicKey:w,Signature:I,hash:e})}var rl={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},y0={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Hd=BigInt(2);function b0(r){let e=rl.p,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=r*r*r%e,l=u*u*r%e,f=oe(l,t,e)*l%e,d=oe(f,t,e)*l%e,h=oe(d,Hd,e)*u%e,p=oe(h,o,e)*h%e,y=oe(p,s,e)*p%e,g=oe(y,a,e)*y%e,m=oe(g,c,e)*g%e,_=oe(m,a,e)*y%e,E=oe(_,t,e)*l%e,I=oe(E,i,e)*p%e,O=oe(I,n,e)*u%e,$=oe(O,Hd,e);if(!tl.eql(tl.sqr($),r))throw new Error("Cannot find square root");return $}var tl=Kr(rl.p,{sqrt:b0}),w0=qd(rl,{Fp:tl,endo:y0}),tt=zd(w0,Br);function Wd(r,e,t){let n=Nr.digest(e instanceof Uint8Array?e:e.subarray());if(zr(n))return n.then(({digest:o})=>(t?.signal?.throwIfAborted(),tt.sign(o,r,{prehash:!1,format:"der"}))).catch(o=>{throw o.name==="AbortError"?o:new Wn(String(o))});try{return tt.sign(n.digest,r,{prehash:!1,format:"der"})}catch(o){throw new Wn(String(o))}}function Gd(r,e,t,n){let o=Nr.digest(t instanceof Uint8Array?t:t.subarray());if(zr(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),tt.verify(e,s,r,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new Gn(String(s))});try{return n?.signal?.throwIfAborted(),tt.verify(e,o.digest,r,{prehash:!1,format:"der"})}catch(s){throw new Gn(String(s))}}var no=class{type="secp256k1";raw;_key;constructor(e){this._key=Xd(e),this.raw=Yd(this._key)}toMultihash(){return Xe.digest(We(this))}toCID(){return fe.createV1(114,this.toMultihash())}toString(){return ee.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Z(this.raw,e.raw)}verify(e,t,n){return Gd(this._key,t,e,n)}},xs=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=jd(e),this.publicKey=new no(t??Zd(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Z(this.raw,e.raw)}sign(e,t){return Wd(this.raw,e,t)}};function nl(r){return new no(r)}async function Qd(){let r=x0();return new xs(r)}function Yd(r){return tt.Point.fromBytes(r).toBytes()}function jd(r){try{return tt.getPublicKey(r,!0),r}catch(e){throw new An(String(e))}}function Xd(r){try{return tt.Point.fromBytes(r),r}catch(e){throw new Tr(String(e))}}function Zd(r){try{return tt.getPublicKey(r,!0)}catch(e){throw new An(String(e))}}function x0(){return tt.utils.randomSecretKey()}async function Jd(r,e){if(r==="Ed25519")return Sd();if(r==="secp256k1")return Qd();if(r==="RSA")return Xc(E0(e));if(r==="ECDSA")return Df(v0(e));throw new kt}function jr(r,e){let{Type:t,Data:n}=lt.decode(r),o=n??new Uint8Array;switch(t){case se.RSA:return Gc(o,e);case se.Ed25519:return vc(o);case se.secp256k1:return nl(o);case se.ECDSA:return Qa(o);default:throw new kt}}function eh(r){let{Type:e,Data:t}=lt.decode(r.digest),n=t??new Uint8Array;switch(e){case se.Ed25519:return vc(n);case se.secp256k1:return nl(n);case se.ECDSA:return Qa(n);default:throw new kt}}function We(r){return lt.encode({Type:se[r.type],Data:r.raw})}function E0(r){return r==null?2048:parseInt(r,10)}function v0(r){if(r==="P-256"||r==null)return"P-256";if(r==="P-384")return"P-384";if(r==="P-521")return"P-521";throw new C("Unsupported curve, should be P-256, P-384 or P-521")}var th=Symbol.for("nodejs.util.inspect.custom"),S0=114,oo=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[jo]=!0;toString(){return this.string==null&&(this.string=ee.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return fe.createV1(S0,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return Z(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return Z(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[th](){return`PeerId(${this.toString()})`}},so=class extends oo{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},io=class extends oo{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},ao=class extends oo{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},_0=2336,co=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Xe.digest(L(this.url))}[th](){return`PeerId(${this.url})`}[jo]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return fe.createV1(_0,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=U(e)),e.toString()===this.toString())}};var A0=114,rh=2336;function ut(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=mt(ee.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return lo(fe.parse(r));if(e==null)throw new C('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=mt(e.decode(r))}return Xr(t)}function ol(r){if(r.type==="Ed25519")return new io({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new ao({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new so({multihash:r.toCID().multihash,publicKey:r});throw new kt}function nh(r){return ol(r.publicKey)}function Xr(r){if(C0(r))return new so({multihash:r});if(I0(r))try{let e=eh(r);if(e.type==="Ed25519")return new io({multihash:r,publicKey:e});if(e.type==="secp256k1")return new ao({multihash:r,publicKey:e})}catch{let t=U(r.digest);return new co(new URL(t))}throw new $o("Supplied PeerID Multihash is invalid")}function lo(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==A0&&r.code!==rh)throw new qo("Supplied PeerID CID is invalid");if(r.code===rh){let e=U(r.multihash.digest);return new co(new URL(e))}return Xr(r.multihash)}function I0(r){return r.code===Xe.code}function C0(r){return r.code===Nr.code}async function oh(r){if(r.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new C("Private network is enforced, but no protector was provided");return r}function T0(r,e){if(typeof r=="string")return L0(r);if(typeof r=="number")return k0(r,e);throw Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(r)}`)}var Es=T0;function L0(r){if(typeof r!="string"||r.length===0||r.length>100)throw Error(`Value provided to ms.parse() must be a string with length between 1 and 99. value=${JSON.stringify(r)}`);let e=/^(?<value>-?\d*\.?\d+) *(?<unit>milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)?$/i.exec(r);if(!e?.groups)return NaN;let{value:t,unit:n="ms"}=e.groups,o=parseFloat(t),s=n.toLowerCase();switch(s){case"years":case"year":case"yrs":case"yr":case"y":return o*315576e5;case"months":case"month":case"mo":return o*26298e5;case"weeks":case"week":case"w":return o*6048e5;case"days":case"day":case"d":return o*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return o*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return o*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return o*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return o;default:throw Error(`Unknown unit "${s}" provided to ms.parse(). value=${JSON.stringify(r)}`)}}function P0(r){let e=Math.abs(r);return e>=315576e5?`${Math.round(r/315576e5)}y`:e>=26298e5?`${Math.round(r/26298e5)}mo`:e>=6048e5?`${Math.round(r/6048e5)}w`:e>=864e5?`${Math.round(r/864e5)}d`:e>=36e5?`${Math.round(r/36e5)}h`:e>=6e4?`${Math.round(r/6e4)}m`:e>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function D0(r){let e=Math.abs(r);return e>=315576e5?cr(r,e,315576e5,"year"):e>=26298e5?cr(r,e,26298e5,"month"):e>=6048e5?cr(r,e,6048e5,"week"):e>=864e5?cr(r,e,864e5,"day"):e>=36e5?cr(r,e,36e5,"hour"):e>=6e4?cr(r,e,6e4,"minute"):e>=1e3?cr(r,e,1e3,"second"):`${r} ms`}function k0(r,e){if(typeof r!="number"||!Number.isFinite(r))throw Error("Value provided to ms.format() must be of type number.");return e?.long?D0(r):P0(r)}function cr(r,e,t,n){let o=e>=t*1.5;return`${Math.round(r/t)} ${n}${o?"s":""}`}function sl(r){t.debug=t,t.default=t,t.coerce=c,t.disable=s,t.enable=o,t.enabled=i,t.humanize=Es,t.destroy=u,Object.keys(r).forEach(l=>{t[l]=r[l]}),t.names=[],t.skips=[],t.formatters={};function e(l){let f=0;for(let d=0;d<l.length;d++)f=(f<<5)-f+l.charCodeAt(d),f|=0;return t.colors[Math.abs(f)%t.colors.length]}t.selectColor=e;function t(l,f){let d,h=null,p,y;function g(...m){if(!g.enabled)return;let _=g,E=Number(new Date),I=E-(d||E);_.diff=I,_.prev=d,_.curr=E,d=E,m[0]=t.coerce(m[0]),typeof m[0]!="string"&&m.unshift("%O");let O=0;m[0]=m[0].replace(/%([a-zA-Z%])/g,(q,S)=>{if(q==="%%")return"%";O++;let v=t.formatters[S];if(typeof v=="function"){let B=m[O];q=v.call(_,B),m.splice(O,1),O--}return q}),t.formatArgs.call(_,m),f?.onLog!=null&&f.onLog(...m),(_.log||t.log).apply(_,m)}return g.namespace=l,g.useColors=t.useColors(),g.color=t.selectColor(l),g.extend=n,g.destroy=t.destroy,Object.defineProperty(g,"enabled",{enumerable:!0,configurable:!1,get:()=>h!==null?h:(p!==t.namespaces&&(p=t.namespaces,y=t.enabled(l)),y),set:m=>{h=m}}),typeof t.init=="function"&&t.init(g),g}function n(l,f){let d=t(this.namespace+(typeof f>"u"?":":f)+l);return d.log=this.log,d}function o(l){t.save(l),t.namespaces=l,t.names=[],t.skips=[];let f,d=(typeof l=="string"?l:"").split(/[\s,]+/),h=d.length;for(f=0;f<h;f++)d[f]&&(l=d[f].replace(/\*/g,".*?"),l[0]==="-"?t.skips.push(new RegExp("^"+l.substr(1)+"$")):t.names.push(new RegExp("^"+l+"$")))}function s(){let l=[...t.names.map(a),...t.skips.map(a).map(f=>"-"+f)].join(",");return t.enable(""),l}function i(l){if(l[l.length-1]==="*")return!0;let f,d;for(f=0,d=t.skips.length;f<d;f++)if(t.skips[f].test(l))return!1;for(f=0,d=t.names.length;f<d;f++)if(t.names[f].test(l))return!0;return!1}function a(l){return l.toString().substring(2,l.toString().length-2).replace(/\.\*\?$/,"*")}function c(l){return l instanceof Error?l.stack??l.message:l}function u(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.setupFormatters(t.formatters),t.enable(t.load()),t}var vs=U0(),R0=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function O0(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/(edge|trident)\/(\d+)/)!=null?!1:typeof document<"u"&&document.documentElement?.style?.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/firefox\/(\d+)/)!=null&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/applewebkit\/(\d+)/)}function N0(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Es(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(t++,o==="%c"&&(n=t))}),r.splice(n,0,e)}var M0=console.debug??console.log??(()=>{});function B0(r){try{r?vs?.setItem("debug",r):vs?.removeItem("debug")}catch{}}function F0(){let r;try{r=vs?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function U0(){try{return localStorage}catch{}}function K0(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var sh=sl({formatArgs:N0,save:B0,load:F0,useColors:O0,setupFormatters:K0,colors:R0,storage:vs,log:M0});var Ke=sh;Ke.formatters.b=r=>r==null?"undefined":ee.baseEncode(r);Ke.formatters.t=r=>r==null?"undefined":He.baseEncode(r);Ke.formatters.m=r=>r==null?"undefined":Ua.baseEncode(r);Ke.formatters.p=r=>r==null?"undefined":r.toString();Ke.formatters.c=r=>r==null?"undefined":r.toString();Ke.formatters.k=r=>r==null?"undefined":r.toString();Ke.formatters.a=r=>r==null?"undefined":r.toString();function ih(r,e=""){let t=ah(r.message),n=ah(r.stack);return t!=null&&n!=null?n.includes(t)?`${n.split(`
|
|
3
3
|
`).join(`
|
|
4
4
|
${e}`)}`:`${t}
|
|
5
5
|
${e}${n.split(`
|
|
6
6
|
`).join(`
|
|
7
7
|
${e}`)}`:n!=null?`${n.split(`
|
|
8
8
|
`).join(`
|
|
9
|
-
${e}`)}`:t!=null?`${t}`:`${r.toString()}`}function
|
|
10
|
-
${e}${r.errors.map(n=>`${
|
|
9
|
+
${e}`)}`:t!=null?`${t}`:`${r.toString()}`}function q0(r){return r instanceof AggregateError||r?.name==="AggregateError"&&Array.isArray(r.errors)}function ch(r,e=""){if(q0(r)){let t=ih(r,e);return r.errors.length>0?(e=`${e} `,t+=`
|
|
10
|
+
${e}${r.errors.map(n=>`${ch(n,`${e}`)}`).join(`
|
|
11
11
|
${e}`)}`):t+=`
|
|
12
|
-
${e}[Error list was empty]`,t.trim()}return Hd(r,e)}Ke.formatters.e=r=>r==null?"undefined":Gd(r);function C0(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function ys(r){return{forComponent(e){return Yd(e,r)}}}function Yd(r,e){let t=C0(`${r}:trace`);return Ke.enabled(`${r}:trace`)&&Ke.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=Ke(`${r}:trace`,e)),Object.assign(Ke(r,e),{error:Ke(`${r}:error`,e),trace:t,newScope:n=>Yd(`${r}:${n}`,e)})}function Wd(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}function ir(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}function bs(r){let e=pt(J.decode(`z${r}`));return Yr(e)}var Ye=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),{key:t,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return ir(this.map.entries(),e=>[e[1].key,e[1].value])}forEach(e){this.map.forEach((t,n)=>{e(t.value,t.key,this)})}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),{key:e,value:t})}keys(){return ir(this.map.values(),e=>e.key)}values(){return ir(this.map.values(),e=>e.value)}get size(){return this.map.size}};var ar=class r{set;constructor(e){if(this.set=new Set,e!=null)for(let t of e)this.set.add(t.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return ir(this.set.entries(),e=>{let t=bs(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=bs(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return ir(this.set.values(),e=>bs(e))}intersection(e){let t=new r;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new r;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new r;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};var Qc={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Xd={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},jd=new globalThis.TextEncoder;function I0(r,e){let t=Qc[e],n=Xd[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function T0(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Qc[e],o=Xd[e],s=r;for(;s.length>0;){let i=jd.encodeInto(s,t);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(t[a]),o=BigInt.asUintN(e,o*n)}return o}function Jc(r,{size:e=32,utf8Buffer:t}={}){if(!Qc[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(t)return T0(r,e,t);r=jd.encode(r)}return I0(r,e)}var ro={hash:r=>Number(Jc(r,{size:32})),hashV:(r,e)=>L0(ro.hash(r,e))};function L0(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),L(e,"base16")}var el=64,rt=class{fp;h;seed;constructor(e,t,n,o=2){if(o>el)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),i=le(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?Z(this.fp,e.fp):!1}};function cr(r,e){return Math.floor(Math.random()*(e-r))+r}var lr=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof rt))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof rt))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(this.contents[t]==null)return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof rt))throw new TypeError("Invalid Fingerprint");let t=cr(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof rt))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var P0=500,no=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??ro,this.seed=e.seed??cr(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=L(e));let t=new rt(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new lr(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new lr(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let s=[n,o],i=s[cr(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new lr(this.bucketSize));for(let a=0;a<P0;a++){let c=this.buckets[i].swap(t);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new lr(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=L(e));let t=new rt(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let s=(n^t.hash())%this.filterSize;return this.buckets[s]?.has(t)??!1}remove(e){typeof e=="string"&&(e=L(e));let t=new rt(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let s=(n^t.hash())%this.filterSize,i=this.buckets[s]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},D0={1:.5,2:.84,4:.95,8:.98};function k0(r=.001){return r>.002?2:r>1e-5?4:8}function Zd(r,e=.001){let t=k0(e),n=D0[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),el);return{filterSize:o,bucketSize:t,fingerprintSize:s}}var ws=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??ro,this.seed=e.seed??cr(0,Math.pow(2,10)),this.filterSeries=[new no({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=L(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new no({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=L(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=L(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function oo(r,e=.001,t){return new ws({...Zd(r,e),...t??{}})}function H(r){let e=r.getComponents(),t={},n=0;if(e[n]?.name==="ip6zone"&&(t.zone=`${e[n].value}`,n++),e[n].name==="ip4"||e[n].name==="ip6"||e[n].name==="dns"||e[n].name==="dns4"||e[n].name==="dns6"?(t.type=e[n].name,t.host=e[n].value,n++):e[n].name==="dnsaddr"&&(t.type=e[n].name,t.host=`_dnsaddr.${e[n].value}`,n++),(e[n]?.name==="tcp"||e[n]?.name==="udp")&&(t.protocol=e[n].name==="tcp"?"tcp":"udp",t.port=parseInt(`${e[n].value}`),n++),e[n]?.name==="ipcidr"&&(t.type==="ip4"?t.cidr=parseInt(`${e[n].value}`):t.type==="ip6"&&(t.cidr=`${e[n].value}`),n++),t.type==null||t.host==null)throw new I(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e[n]?.name==="tls"&&e[n+1]?.name==="sni"&&(t.sni=e[n+1].value,n+=2),t}var xs=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let u=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let d=Number.parseInt(f,e);if(!Number.isNaN(d))return d});if(u===void 0)break;if(s*=e,s+=u,s>l||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Qd=45,R0=15,Xr=new xs;function Es(r){if(!(r.length>R0))return Xr.new(r).parseWith(()=>Xr.readIPv4Addr())}function vs(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Qd))return Xr.new(r).parseWith(()=>Xr.readIPv6Addr())}function jr(r,e=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>Qd)return;let t=Xr.new(r).parseWith(()=>Xr.readIPAddr());if(t)return e&&t.length===4?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,t[0],t[1],t[2],t[3]]):t}function Jd(r,e,t){let n=0;for(let o of r)if(!(n<e)){if(n>t)break;if(o!==255)return!1;n++}return!0}function eh(r,e,t,n){let o=0;for(let s of r)if(!(o<t)){if(o>n)break;if(s!==e[o])return!1;o++}return!0}function tl(r){switch(r.length){case ur:return r.join(".");case fr:{let e=[];for(let t=0;t<r.length;t++)t%2===0&&e.push(r[t].toString(16).padStart(2,"0")+r[t+1].toString(16).padStart(2,"0"));return e.join(":")}default:throw new Error("Invalid ip length")}}function th(r){let e=0;for(let[t,n]of r.entries()){if(n===255){e+=8;continue}for(;(n&128)!=0;)e++,n=n<<1;if((n&128)!=0)return-1;for(let o=t+1;o<r.length;o++)if(r[o]!=0)return-1;break}return e}function rh(r){let e="0x";for(let t of r)e+=(t>>4).toString(16)+(t&15).toString(16);return e}var ur=4,fr=16,uS=parseInt("0xFFFF",16),O0=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function so(r,e){e.length===fr&&r.length===ur&&Jd(e,0,11)&&(e=e.slice(12)),e.length===ur&&r.length===fr&&eh(r,O0,0,11)&&(r=r.slice(12));let t=r.length;if(t!=e.length)throw new Error("Failed to mask ip");let n=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=r[o]&e[o];return n}function nh(r,e){if(typeof e=="string"&&(e=jr(e)),e==null)throw new Error("Invalid ip");if(e.length!==r.network.length)return!1;for(let t=0;t<e.length;t++)if((r.network[t]&r.mask[t])!==(e[t]&r.mask[t]))return!1;return!0}function rl(r){let[e,t]=r.split("/");if(!e||!t)throw new Error("Failed to parse given CIDR: "+r);let n=ur,o=Es(e);if(o==null&&(n=fr,o=vs(e),o==null))throw new Error("Failed to parse given CIDR: "+r);let s=parseInt(t,10);if(Number.isNaN(s)||String(s).length!==t.length||s<0||s>n*8)throw new Error("Failed to parse given CIDR: "+r);let i=nl(s,8*n);return{network:so(o,i),mask:i}}function nl(r,e){if(e!==8*ur&&e!==8*fr)throw new Error("Invalid CIDR mask");if(r<0||r>e)throw new Error("Invalid CIDR mask");let t=e/8,n=new Uint8Array(t);for(let o=0;o<t;o++){if(r>=8){n[o]=255,r-=8;continue}n[o]=255-(255>>r),r=0}return n}var Zr=class{constructor(e,t){if(t==null)({network:this.network,mask:this.mask}=rl(e));else{let n=jr(e);if(n==null)throw new Error("Failed to parse network");t=String(t);let o=parseInt(t,10);if(Number.isNaN(o)||String(o).length!==t.length||o<0||o>n.length*8){let s=jr(t);if(s==null)throw new Error("Failed to parse mask");this.mask=s}else this.mask=nl(o,8*n.length);this.network=so(n,this.mask)}}contains(e){return nh({network:this.network,mask:this.mask},e)}toString(){let e=th(this.mask),t=e!==-1?String(e):rh(this.mask);return tl(this.network)+"/"+t}};function oh(r){try{let e=H(r);switch(e.type){case"ip4":return e.host.startsWith("169.254.");case"ip6":return e.host.toLowerCase().startsWith("fe80");default:return!1}}catch{return!1}}function sh(r){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^::1$/.test(r)}function io(r){try{let e=H(r);switch(e.type){case"ip4":case"ip6":return sh(e.host);default:return!1}}catch{return!1}}function xe(r){try{return H(r),!0}catch{return!1}}function nt(r){return!!Es(r)}function Ss(r){return!!vs(r)}var ah=fa(ih(),1),N0=["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"],M0=N0.map(r=>new ah.Netmask(r));function ol(r){for(let e of M0)if(e.contains(r))return!0;return!1}function B0(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function F0(r){let e=r.split(":");if(e.length<2)return!1;let t=e[e.length-1].padStart(4,"0"),n=e[e.length-2].padStart(4,"0"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return ol(o)}function U0(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function K0(r){let e=r.split(":"),t=e[e.length-1];return ol(t)}function q0(r){return/^::$/.test(r)||/^::1$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^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(r)||/^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(r)||/^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(r)||/^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(r)||/^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(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}function Qr(r){if(nt(r))return ol(r);if(B0(r))return F0(r);if(U0(r))return K0(r);if(Ss(r))return q0(r)}function St(r){try{let e=H(r);switch(e.type){case"ip4":case"ip6":return Qr(e.host)??!1;default:return e.host==="localhost"}}catch{return!1}}function ge(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var _s=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},Jr=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new _s(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new _s(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var sl=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function en(r={}){return $0(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function $0(r,e){e=e??{};let t=e.onEnd,n=new Jr,o,s,i,a=ge(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((m,g)=>{s=_=>{s=null,n.push(_);try{m(r(n))}catch(E){g(E)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=ge()})}},l=m=>s!=null?s(m):(n.push(m),o),u=m=>(n=new Jr,s!=null?s({error:m}):(n.push({error:m}),o)),f=m=>{if(i)return o;if(e?.objectMode!==!0&&m?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:m})},d=m=>i?o:(i=!0,m!=null?u(m):l({done:!0})),h=()=>(n=new Jr,d(),{done:!0}),p=m=>(d(m),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:p,push:f,end:d,get readableLength(){return n.size},onEmpty:async m=>{let g=m?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let _,E;g!=null&&(_=new Promise((C,O)=>{E=()=>{O(new sl)},g.addEventListener("abort",E)}));try{await Promise.race([a.promise,_])}finally{E!=null&&g!=null&&g?.removeEventListener("abort",E)}}},t==null)return o;let y=o;return o={[Symbol.asyncIterator](){return this},next(){return y.next()},throw(m){return y.throw(m),t!=null&&(t(m),t=void 0),{done:!0}},return(){return y.return(),t!=null&&(t(),t=void 0),{done:!0}},push:f,end(m){return y.end(m),t!=null&&(t(m),t=void 0),o},get readableLength(){return y.readableLength},onEmpty:m=>y.onEmpty(m)},o}var il=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},ch=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function co(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e,a,c,u=new Promise((f,d)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(i?.aborted){d(ch(i));return}if(i&&(c=()=>{d(ch(i))},i.addEventListener("abort",c,{once:!0})),r.then(f,d),t===Number.POSITIVE_INFINITY)return;let h=new il;a=s.setTimeout.call(void 0,()=>{if(n){try{f(n())}catch(p){d(p)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?f():o instanceof Error?d(o):(h.message=o??`Promise timed out after ${t} milliseconds`,d(h))},t)}).finally(()=>{u.clear(),c&&i&&i.removeEventListener("abort",c)});return u.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},u}var V0=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function z0(r,e,t){let n,o=new Promise((s,i)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:l,removeListener:u}=V0(r),f=async(...h)=>{let p=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(p))return}catch(y){n(),i(y);return}c.push(p),t.count===c.length&&(n(),s(c))},d=(...h)=>{n(),i(t.rejectionMultiArgs?h:h[0])};n=()=>{for(let h of a)u(h,f);for(let h of t.rejectionEvents)a.includes(h)||u(h,d)};for(let h of a)l(h,f);for(let h of t.rejectionEvents)a.includes(h)||l(h,d);t.signal&&t.signal.addEventListener("abort",()=>{d(t.signal.reason)},{once:!0}),t.resolveImmediately&&s(c)});if(o.cancel=n,typeof t.timeout=="number"){let s=co(o,{milliseconds:t.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function ot(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=z0(r,e,t),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function lo(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var As=class extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(e="Rate limit exceeded",t){super(e),this.name="RateLimitError",this.remainingPoints=t.remainingPoints,this.msBeforeNext=t.msBeforeNext,this.consumedPoints=t.consumedPoints,this.isFirstInDuration=t.isFirstInDuration}},Cs=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}},dr=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"};function H0(r){return r.reason}async function $e(r,e,t){if(e==null)return r;let n=t?.translateError??H0;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let o;try{return await Promise.race([r,new Promise((s,i)=>{o=()=>{i(n(e))},e.addEventListener("abort",o)})])}finally{o!=null&&e.removeEventListener("abort",o)}}var Is=class{deferred;signal;constructor(e){this.signal=e,this.deferred=ge(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Xe)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function W0(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Ts=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=W0(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Xe),this.cleanup())}async join(e={}){let t=new Is(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await $e(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var tn=class extends Le{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=lo(this.emitEmpty.bind(this),1),this.emitIdle=lo(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Cs;let n=new Ts(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(t).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Xe)}),this.clear()}async onEmpty(e){this.size!==0&&await ot(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await ot(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await ot(this,"idle",e)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=en({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new Xe("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};function _t(r){let e=new globalThis.AbortController;function t(){let s=r.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();e.abort(s);for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}for(let s of r){if(s?.aborted===!0){t();break}s?.addEventListener!=null&&s.addEventListener("abort",t)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}var rn=class{movingAverage;variance;deviation;forecast;timeSpan;previousTime;constructor(e){this.timeSpan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timeSpan)}push(e,t=Date.now()){if(this.previousTime!=null){let n=this.alpha(t,this.previousTime),o=e-this.movingAverage,s=n*o;this.movingAverage=n*e+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+o*s),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*o}else this.movingAverage=e;this.previousTime=t}};var G0=1.2,Y0=2,X0=5e3,j0=6e4,Z0=5e3,Ls=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){let t=e.interval??Z0;this.success=new rn(t),this.failure=new rn(t),this.next=new rn(t),this.failureMultiplier=e.failureMultiplier??Y0,this.timeoutMultiplier=e.timeoutMultiplier??G0,this.minTimeout=e.minTimeout??X0,this.maxTimeout=e.maxTimeout??j0,e.metricName!=null&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){let t=Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier));t<this.minTimeout&&(t=this.minTimeout),t>this.maxTimeout&&(t=this.maxTimeout);let n=AbortSignal.timeout(t),o=_t([e.signal,n]);return o.start=Date.now(),o.timeout=t,o}cleanUp(e){e.clear();let t=Date.now()-e.start;e.aborted?(this.failure.push(t),this.next.push(t*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:t})):(this.success.push(t),this.next.push(t),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:t}))}};var Ee=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},At=class extends Error{static name="ValidationError";name="ValidationError"},Ps=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Ds=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function cl(r){return e=>U(e,r)}function ll(r){return e=>L(e,r)}function nn(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function hr(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function lh(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=L(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=hr(n);return Ze([t,o],t.length+o.length)}function uh(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=He.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=hr(n);return Ze([t,o],t.length+o.length)}function ul(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=U(e,"base32"),o=nn(t);return`${n}:${o}`}var fl=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let o=parseInt(t,10);if(isNaN(o)||o<0||o>255)throw new Ee("Invalid byte value in IP address");e[n]=o}),e},fh=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=nt(t[n]),i;s&&(i=fl(t[n]),t[n]=U(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,U(i.subarray(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let s=parseInt(t[n],16);if(isNaN(s)||s<0||s>65535)throw new Ee("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},dh=function(r){if(r.byteLength!==4)throw new Ee("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},hh=function(r){if(r.byteLength!==16)throw new Ee("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],s=r[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new Ee(`Invalid IPv6 address "${t}"`)}};function ph(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Ee(`Invalid IPv6 address "${r}"`)}}var al=Object.values(An).map(r=>r.decoder),Q0=(function(){let r=al[0].or(al[1]);return al.slice(2).forEach(e=>r=r.or(e)),r})();function mh(r){return Q0.decode(r)}function gh(r){return e=>r.encoder.encode(e)}function J0(r){if(parseInt(r).toString()!==r)throw new At("Value must be an integer")}function ey(r){if(r<0)throw new At("Value must be a positive integer, or zero")}function ty(r){return e=>{if(e>r)throw new At(`Value must be smaller than or equal to ${r}`)}}function ry(...r){return e=>{for(let t of r)t(e)}}var uo=ry(J0,ey,ty(65535));var ye=-1,dl=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(typeof e=="string"?t=this.protocolsByName.get(e):t=this.protocolsByCode.get(e),t==null)throw new Ds(`Protocol ${e} was unknown`);return t}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(t=>{this.protocolsByName.set(t,e)})}removeProtocol(e){let t=this.protocolsByCode.get(e);t!=null&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},Ct=new dl,yy=[{code:4,name:"ip4",size:32,valueToBytes:fl,bytesToValue:dh,validate:r=>{if(!nt(r))throw new At(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:hr,bytesToValue:nn,validate:uo},{code:273,name:"udp",size:16,valueToBytes:hr,bytesToValue:nn,validate:uo},{code:33,name:"dccp",size:16,valueToBytes:hr,bytesToValue:nn,validate:uo},{code:41,name:"ip6",size:128,valueToBytes:fh,bytesToValue:hh,stringToValue:ph,validate:r=>{if(!Ss(r))throw new At(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:ye},{code:43,name:"ipcidr",size:8,bytesToValue:cl("base10"),valueToBytes:ll("base10")},{code:53,name:"dns",size:ye},{code:54,name:"dns4",size:ye},{code:55,name:"dns6",size:ye},{code:56,name:"dnsaddr",size:ye},{code:132,name:"sctp",size:16,valueToBytes:hr,bytesToValue:nn,validate:uo},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:ye,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:ye,bytesToValue:cl("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?ll("base58btc")(r):ue.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:ul,valueToBytes:lh},{code:445,name:"onion3",size:296,bytesToValue:ul,valueToBytes:uh},{code:446,name:"garlic64",size:ye},{code:447,name:"garlic32",size:ye},{code:448,name:"tls"},{code:449,name:"sni",size:ye},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:ye,bytesToValue:gh(ka),valueToBytes:mh},{code:480,name:"http"},{code:481,name:"http-path",size:ye,stringToValue:r=>`/${decodeURIComponent(r)}`,valueToString:r=>encodeURIComponent(r.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:ye}];yy.forEach(r=>{Ct.addProtocol(r)});function yh(r){let e=[],t=0;for(;t<r.length;){let n=rr(r,t),o=Ct.getProtocol(n),s=me(n),i=by(o,r,t+s),a=0;i>0&&o.size===ye&&(a=me(i));let c=s+a+i,l={code:n,name:o.name,bytes:r.subarray(t,t+c)};if(i>0){let u=t+s+a,f=r.subarray(u,u+i);l.value=o.bytesToValue?.(f)??U(f)}e.push(l),t+=c}return e}function bh(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=Ct.getProtocol(n.code),s=me(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??L(n.value),a=i.byteLength,o.size===ye&&(c=me(a)));let l=new Uint8Array(s+c+a),u=0;Vr(n.code,l,u),u+=s,i!=null&&(o.size===ye&&(Vr(a,l,u),u+=c),l.set(i,u)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return Ze(t,e)}function wh(r){if(r.charAt(0)!=="/")throw new Ee('String multiaddr must start with "/"');let e=[],t="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(t==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=Ct.getProtocol(o);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",t="protocol";continue}else if(a)throw new Ee(`Component ${o} was missing value`);t="value"}else if(t==="value"){let l={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new Ee(`Component ${o} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new Ee("Incomplete multiaddr");return e}function xh(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=Ct.getProtocol(e.code);if(t==null)throw new Ee(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function by(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:rr(e,t)}var wy=Symbol.for("nodejs.util.inspect.custom"),Cl=Symbol.for("@multiformats/multiaddr");function xy(r){if(r==null&&(r="/"),zt(r))return r.getComponents();if(r instanceof Uint8Array)return yh(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),wh(r);if(Array.isArray(r))return r;throw new Ee("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Ms=class r{[Cl]=!0;#e;#r;#n;constructor(e="/",t={}){this.#e=xy(e),t.validate!==!1&&Ey(this)}get bytes(){return this.#n==null&&(this.#n=bh(this.#e)),this.#n}toString(){return this.#r==null&&(this.#r=xh(this.#e)),this.#r}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new Ps(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,o),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}equals(e){return Z(this.bytes,e.bytes)}[wy](){return`Multiaddr(${this.toString()})`}};function Ey(r){r.getComponents().forEach(e=>{let t=Ct.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function zt(r){return!!r?.[Cl]}function X(r){return new Ms(r)}var Il=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=ge(),this.haveNext=ge()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=ge(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=ge(),await $e(this.readNext.promise,t?.signal,t)}};function Eh(){return new Il}function vy(r){return r[Symbol.asyncIterator]!=null}async function Sy(r,e,t){try{await Promise.all(r.map(async n=>{for await(let o of n)await e.push(o,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*_y(r){let e=new AbortController,t=Eh();Sy(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*Ay(r){for(let e of r)yield*e}function Cy(...r){let e=[];for(let t of r)vy(t)||e.push(t);return e.length===r.length?Ay(e):_y(r)}var un=Cy;var Iy=4194304,Bs=class extends Error{static name="UnwrappedError";name="UnwrappedError"},Ll=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Pl=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Dl=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Ty(r){return typeof r?.closeRead=="function"}function Ly(r){return typeof r?.close=="function"}function Tl(r){return Ty(r)?r.remoteWriteStatus!=="writable"&&r.readBufferLength===0:Ly(r)?r.status!=="open":!1}function Py(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function kl(r,e){let t=e?.maxBufferSize??Iy,n=new Q,o,s=!1;if(!Py(r))throw new I("Argument should be a Stream or a Multiaddr");let i=u=>{if(n.append(u.data),n.byteLength>t){let f=n.byteLength;n.consume(n.byteLength),o?.reject(new Error(`Read buffer overflow - ${f} > ${t}`))}o?.resolve()};r.addEventListener("message",i);let a=u=>{u.error!=null?o?.reject(u.error):o?.resolve()};r.addEventListener("close",a);let c=()=>{o?.resolve()};r.addEventListener("remoteCloseWrite",c);let l={readBuffer:n,async read(u){if(s===!0)throw new Bs("Stream was unwrapped");if(Tl(r)){if(n.byteLength===0&&u?.bytes==null)return null;if(u?.bytes!=null&&n.byteLength<u.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,u.bytes),new dr(`Unexpected EOF - stream closed after reading ${n.byteLength}/${u.bytes} bytes`)}let f=u?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=f){o.resolve();break}if(await $e(o.promise,u?.signal),Tl(r)){if(n.byteLength===0&&u?.bytes==null)return null;break}o=Promise.withResolvers()}let d=u?.bytes??n.byteLength;if(n.byteLength<d){if(Tl(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,d),new dr(`Unexpected EOF - stream closed while reading ${n.byteLength}/${d} bytes`);return l.read(u)}let h=n.sublist(0,d);return n.consume(d),h},async write(u,f){if(s===!0)throw new Bs("Stream was unwrapped");r.send(u)||await ot(r,"drain",{signal:f?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,r.removeEventListener("message",i),r.removeEventListener("close",a),r.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.push(n))),r}};return l}function Fs(r,e={}){let t=kl(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=me(e.maxDataLength));let n=e?.lengthDecoder??rr,o=e?.lengthEncoder??Kt;return{async read(i){let a=-1,c=new Q;for(;;){let u=await t.read({...i,bytes:1});if(u==null)break;c.append(u);try{a=n(c)}catch(f){if(f instanceof RangeError)continue;throw f}if(a<0)throw new Ll("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new Dl(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new Pl(`Message length too long - ${a} > ${e.maxDataLength}`);let l=await t.read({...i,bytes:a});if(l==null)throw r.log.error("tried to read %d bytes but the stream closed",a),new dr(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(l.byteLength!==a)throw r.log.error("read %d/%d bytes before the stream closed",l.byteLength,a),new dr(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(i,a){await t.write(new Q(o(i.byteLength),i),a)},async writeV(i,a){let c=new Q(...i.flatMap(l=>[o(l.byteLength),l]));await t.write(c,a)},unwrap(){return t.unwrap()}}}var Us=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},fn=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ks=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},fo=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function qs(r){return r[Symbol.asyncIterator]!=null}function vh(r,e){if(r.byteLength>e)throw new fn("Message length too long")}var Vs=r=>{let e=me(r),t=Se(e);return Kt(r,t),Vs.bytes=e,t};Vs.bytes=0;function zs(r,e){e=e??{};let t=e.lengthEncoder??Vs,n=e?.maxDataLength??4194304;function*o(s){vh(s,n);let i=t(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return qs(r)?(async function*(){for await(let s of r)yield*o(s)})():(function*(){for(let s of r)yield*o(s)})()}zs.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Vs,n=e?.maxDataLength??4194304;return vh(r,n),new Q(t(r.byteLength),r)};var gr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(gr||(gr={}));var Ol=r=>{let e=rr(r);return Ol.bytes=me(e),e};Ol.bytes=0;function Rl(r,e){let t=new Q,n=gr.LENGTH,o=-1,s=e?.lengthDecoder??Ol,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===gr.LENGTH)try{if(o=s(t),o<0)throw new Us("Invalid message length");if(o>a)throw new fn("Message length too long");let l=s.bytes;t.consume(l),e?.onLength!=null&&e.onLength(o),n=gr.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>i)throw new Ks("Message length length too long");break}throw l}if(n===gr.DATA){if(t.byteLength<o)break;let l=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(l),yield l,n=gr.LENGTH}}}return qs(r)?(async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new fo("Unexpected end of input")})():(function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new fo("Unexpected end of input")})()}Rl.fromReader=(r,e)=>{let t=1,n=(async function*(){for(;;)try{let{done:s,value:i}=await r.next(t);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{t=1}})();return Rl(n,{...e??{},onLength:s=>{t=s}})};var Hs=class extends tn{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var Ws=class extends tn{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};var Gs=class{memoryStorage;points;duration;blockDuration;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new Nl}consume(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+t&&(i=this.memoryStorage.set(o,i.consumedPoints,this.blockDuration)),new As("Rate limit exceeded",i);return i}penalty(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,-t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(e,t){let n=t*1e3,o=this.points+1;return this.memoryStorage.set(this.getKey(e),o,t),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:o,isFirstInDuration:!1}}set(e,t,n=0){let o=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,n),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:t,isFirstInDuration:!1}}get(e){let t=this.memoryStorage.get(this.getKey(e));return t!=null&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return e?.customDuration!=null&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.substring(this.keyPrefix.length)}},Nl=class{storage;constructor(){this.storage=new Map}incrby(e,t,n){let o=this.storage.get(e);if(o!=null){let s=o.expiresAt!=null?o.expiresAt.getTime()-new Date().getTime():-1;return o.expiresAt==null||s>0?(o.value+=t,{remainingPoints:0,msBeforeNext:s,consumedPoints:o.value,isFirstInDuration:!1}):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let o=n*1e3,s=this.storage.get(e);s!=null&&clearTimeout(s.timeoutId);let i={value:t,expiresAt:o>0?new Date(Date.now()+o):void 0};return this.storage.set(e,i),o>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(e)},o),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:i.value,isFirstInDuration:!0}}get(e){let t=this.storage.get(e);if(t!=null)return{remainingPoints:0,msBeforeNext:t.expiresAt!=null?t.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){let t=this.storage.get(e);return t!=null?(t.timeoutId!=null&&clearTimeout(t.timeoutId),this.storage.delete(e),!0):!1}};var Ml=class extends Map{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Ce(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Ml({name:e,metrics:t}):n=new Map,n}var Bl=class extends Ye{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Fl(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Bl({name:e,metrics:t}):n=new Ye,n}var ho;(function(r){let e;r.codec=()=>(e==null&&(e=Ne((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.publicKey!=null&&s.publicKey.byteLength>0&&(i.uint32(10),i.bytes(s.publicKey)),s.payloadType!=null&&s.payloadType.byteLength>0&&(i.uint32(18),i.bytes(s.payloadType)),s.payload!=null&&s.payload.byteLength>0&&(i.uint32(26),i.bytes(s.payload)),s.signature!=null&&s.signature.byteLength>0&&(i.uint32(42),i.bytes(s.signature)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={publicKey:le(0),payloadType:le(0),payload:le(0),signature:le(0)},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.publicKey=s.bytes();break}case 2:{c.payloadType=s.bytes();break}case 3:{c.payload=s.bytes();break}case 5:{c.signature=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.publicKey`,value:s.bytes()};break}case 2:{yield{field:`${a}.payloadType`,value:s.bytes()};break}case 3:{yield{field:`${a}.payload`,value:s.bytes()};break}case 5:{yield{field:`${a}.signature`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return Re(s,r.codec())}r.encode=t;function n(s,i){return ke(s,r.codec(),i)}r.decode=n;function o(s,i){return Oe(s,r.codec(),i)}r.stream=o})(ho||(ho={}));var Ys=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var dn=class r{static createFromProtobuf=e=>{let t=ho.decode(e),n=Gr(t.publicKey);return new r({publicKey:n,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t,n)=>{if(t==null)throw new Error("Missing private key");let o=e.domain,s=e.codec,i=e.marshal(),a=Sh(o,s,i),c=await t.sign(a.subarray(),n);return new r({publicKey:t.publicKey,payloadType:s,payload:i,signature:c})};static openAndCertify=async(e,t,n)=>{let o=r.createFromProtobuf(e);if(!await o.validate(t,n))throw new Ys("Envelope signature is not valid for the given domain");return o};publicKey;payloadType;payload;signature;marshaled;constructor(e){let{publicKey:t,payloadType:n,payload:o,signature:s}=e;this.publicKey=t,this.payloadType=n,this.payload=o,this.signature=s}marshal(){return this.marshaled==null&&(this.marshaled=ho.encode({publicKey:We(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return e==null?!1:Z(this.marshal(),e.marshal())}async validate(e,t){let n=Sh(e,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,t)}},Sh=(r,e,t)=>{let n=L(r),o=Kt(n.byteLength),s=Kt(e.length),i=Kt(t.length);return new Q(o,n,s,e,i,t)};var _h="libp2p-peer-record",Ah=Uint8Array.from([3,1]);var po;(function(r){let e;(function(i){let a;i.codec=()=>(a==null&&(a=Ne((f,d,h={})=>{h.lengthDelimited!==!1&&d.fork(),f.multiaddr!=null&&f.multiaddr.byteLength>0&&(d.uint32(10),d.bytes(f.multiaddr)),h.lengthDelimited!==!1&&d.ldelim()},(f,d,h={})=>{let p={multiaddr:le(0)},y=d==null?f.len:f.pos+d;for(;f.pos<y;){let m=f.uint32();switch(m>>>3){case 1:{p.multiaddr=f.bytes();break}default:{f.skipType(m&7);break}}}return p},function*(f,d,h,p={}){let y=d==null?f.len:f.pos+d;for(;f.pos<y;){let m=f.uint32();switch(m>>>3){case 1:{yield{field:`${h}.multiaddr`,value:f.bytes()};break}default:{f.skipType(m&7);break}}}})),a);function c(f){return Re(f,i.codec())}i.encode=c;function l(f,d){return ke(f,i.codec(),d)}i.decode=l;function u(f,d){return Oe(f,i.codec(),d)}i.stream=u})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=Ne((i,a,c={})=>{if(c.lengthDelimited!==!1&&a.fork(),i.peerId!=null&&i.peerId.byteLength>0&&(a.uint32(10),a.bytes(i.peerId)),i.seq!=null&&i.seq!==0n&&(a.uint32(16),a.uint64(i.seq)),i.addresses!=null&&i.addresses.length>0)for(let l of i.addresses)a.uint32(26),r.AddressInfo.codec().encode(l,a);c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let l={peerId:le(0),seq:0n,addresses:[]},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let f=i.uint32();switch(f>>>3){case 1:{l.peerId=i.bytes();break}case 2:{l.seq=i.uint64();break}case 3:{if(c.limits?.addresses!=null&&l.addresses.length===c.limits.addresses)throw new Ge('Decode error - repeated field "addresses" had too many elements');l.addresses.push(r.AddressInfo.codec().decode(i,i.uint32(),{limits:c.limits?.addresses$}));break}default:{i.skipType(f&7);break}}}return l},function*(i,a,c,l={}){let u={addresses:0},f=a==null?i.len:i.pos+a;for(;i.pos<f;){let d=i.uint32();switch(d>>>3){case 1:{yield{field:`${c}.peerId`,value:i.bytes()};break}case 2:{yield{field:`${c}.seq`,value:i.uint64()};break}case 3:{if(l.limits?.addresses!=null&&u.addresses===l.limits.addresses)throw new Ge('Streaming decode error - repeated field "addresses" had too many elements');for(let h of r.AddressInfo.codec().stream(i,i.uint32(),`${c}.addresses[]`,{limits:l.limits?.addresses$}))yield{...h,index:u.addresses};u.addresses++;break}default:{i.skipType(d&7);break}}}})),t);function n(i){return Re(i,r.codec())}r.encode=n;function o(i,a){return ke(i,r.codec(),a)}r.decode=o;function s(i,a){return Oe(i,r.codec(),a)}r.stream=s})(po||(po={}));function Ch(r,e){let t=(n,o)=>n.toString().localeCompare(o.toString());return r.length!==e.length?!1:(e.sort(t),r.sort(t).every((n,o)=>e[o].equals(n)))}var yr=class r{static createFromProtobuf=e=>{let t=po.decode(e),n=Yr(pt(t.peerId)),o=(t.addresses??[]).map(i=>X(i.multiaddr)),s=t.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=_h;static CODEC=Ah;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(e){let{peerId:t,multiaddrs:n,seqNumber:o}=e;this.peerId=t,this.multiaddrs=n??[],this.seqNumber=o??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=po.encode({peerId:this.peerId.toMultihash().bytes,seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))})),this.marshaled}equals(e){return!(!(e instanceof r)||!this.peerId.equals(e.peerId)||this.seqNumber!==e.seqNumber||!Ch(this.multiaddrs,e.multiaddrs))}};function ky(r){return r[Symbol.asyncIterator]!=null}function Ry(r){if(ky(r))return(async()=>{let t=[];for await(let n of r)t.push(n);return t})();let e=[];for(let t of r)e.push(t);return e}var mo=Ry;var Ve=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function Xs(r,e,t,n){let o=new Ve(n?.errorMessage);n?.errorCode!=null&&(o.code=n.errorCode);let s=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(o):new Promise((i,a)=>{function c(){Kl(t,"abort",f),Kl(r,e,l),Kl(r,s,u)}let l=d=>{try{if(n?.filter?.(d)===!1)return}catch(h){c(),a(h);return}c(),i(d)},u=d=>{if(c(),d instanceof Error){a(d);return}a(d.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},f=()=>{c(),a(o)};Ul(t,"abort",f),Ul(r,e,l),Ul(r,s,u)})}function Ul(r,e,t){r!=null&&(Ih(r)?r.addEventListener(e,t):r.addListener(e,t))}function Kl(r,e,t){r!=null&&(Ih(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function Ih(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var js=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var Zs=class{deferred;signal;constructor(e){this.signal=e,this.deferred=Promise.withResolvers(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Ve)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Oy(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Qs=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=Oy(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Ve),this.cleanup())}async join(e={}){let t=new Zs(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await $e(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};function ql(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var go=class extends Le{concurrency;maxSize;queue;pending;sort;autoStart;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.autoStart=e.autoStart??!0,this.sort=e.sort,this.queue=[],this.emitEmpty=ql(this.emitEmpty.bind(this),1),this.emitIdle=ql(this.emitIdle.bind(this),1)}[Symbol.asyncIterator](){return this.toGenerator()}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.safeDispatchEvent("next"),this.autoStart&&this.tryToStartAnother()}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}start(){this.autoStart===!1&&(this.autoStart=!0,this.tryToStartAnother())}pause(){this.autoStart=!1}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new js;let n=new Qs(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.autoStart&&this.tryToStartAnother(),n.join(t).then(o=>(this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Ve)}),this.clear()}async onEmpty(e){this.size!==0&&await Xs(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await Xs(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Xs(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=en({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail.result)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new Ve("Queue aborted"))};this.addEventListener("success",o),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("success",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var Js="lock:worker:request-read",ei="lock:worker:abort-read-request",ti="lock:worker:release-read",ri="lock:master:grant-read",ni="lock:master:error-read",oi="lock:worker:request-write",si="lock:worker:abort-write-request",ii="lock:worker:release-write",ai="lock:master:grant-write",ci="lock:master:error-write",li="lock:worker:finalize",ui="mortice",Th={singleProcess:!1};var $l=(r,e,t,n,o,s,i,a,c)=>l=>{if(l.data==null)return;let u={type:l.data.type,name:l.data.name,identifier:l.data.identifier};u.type===o&&r.safeDispatchEvent(t,{detail:{name:u.name,identifier:u.identifier,handler:async()=>{e.postMessage({type:c,name:u.name,identifier:u.identifier}),await new Promise(f=>{let d=h=>{if(h?.data==null)return;let p={type:h.data.type,name:h.data.name,identifier:h.data.identifier};p.type===a&&p.identifier===u.identifier&&(e.removeEventListener("message",d),f())};e.addEventListener("message",d)})},onError:f=>{e.postMessage({type:i,name:u.name,identifier:u.identifier,error:{message:f.message,name:f.name,stack:f.stack}})}}}),u.type===s&&r.safeDispatchEvent(n,{detail:{name:u.name,identifier:u.identifier}}),u.type===li&&r.safeDispatchEvent("finalizeRequest",{detail:{name:u.name}})};var Lh=(r=10)=>Math.random().toString().substring(2,r+2);var fi=class{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(ui)}readLock(e){return this.sendRequest(Js,ei,ri,ni,ti,e)}writeLock(e){return this.sendRequest(oi,si,ai,ci,ii,e)}finalize(){this.channel.postMessage({type:li,name:this.name}),this.channel.close()}async sendRequest(e,t,n,o,s,i){i?.signal?.throwIfAborted();let a=Lh();return this.channel.postMessage({type:e,identifier:a,name:this.name}),new Promise((c,l)=>{let u=()=>{this.channel.postMessage({type:t,identifier:a,name:this.name})};i?.signal?.addEventListener("abort",u,{once:!0});let f=d=>{if(d.data?.identifier===a&&(d.data?.type===n&&(this.channel.removeEventListener("message",f),i?.signal?.removeEventListener("abort",u),c(()=>{this.channel.postMessage({type:s,identifier:a,name:this.name})})),d.data.type===o)){this.channel.removeEventListener("message",f),i?.signal?.removeEventListener("abort",u);let h=new Error;d.data.error!=null&&(h.message=d.data.error.message,h.name=d.data.error.name,h.stack=d.data.error.stack),l(h)}};this.channel.addEventListener("message",f)})}};var Ph=r=>{if(r=Object.assign({},Th,r),!!globalThis.document||r.singleProcess){let t=new BroadcastChannel(ui),n=new Le;return t.addEventListener("message",$l(n,t,"requestReadLock","abortReadLockRequest",Js,ei,ni,ti,ri)),t.addEventListener("message",$l(n,t,"requestWriteLock","abortWriteLockRequest",oi,si,ci,ii,ai)),n}return new fi(r.name)};var br=new Map,yo;function Dh(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function Ny(r){if(yo==null&&(yo=Ph(r),!Dh(yo))){let e=yo;e.addEventListener("requestReadLock",t=>{let n=t.detail.name,o=t.detail.identifier,s=br.get(n);if(s==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||i.abort()};e.addEventListener("abortReadLockRequest",a),s.readLock({signal:i.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortReadLockRequest",a)})}),e.addEventListener("requestWriteLock",t=>{let n=t.detail.name,o=t.detail.identifier,s=br.get(n);if(s==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||i.abort()};e.addEventListener("abortWriteLockRequest",a),s.writeLock({signal:i.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortWriteLockRequest",a)})}),e.addEventListener("finalizeRequest",t=>{let n=t.detail.name,o=br.get(n);o?.finalize()})}return yo}async function Vl(r,e){let t,n,o=new Promise((i,a)=>{t=i,n=a}),s=()=>{n(new Ve)};return e?.signal?.addEventListener("abort",s,{once:!0}),r.add(async()=>{await new Promise(i=>{t(()=>{e?.signal?.removeEventListener("abort",s),i()})})},{signal:e?.signal}).catch(i=>{n(i)}),o}var kh=(r,e)=>{let t=br.get(r);if(t!=null)return t;let n=Ny(e);if(Dh(n))return t=n,br.set(r,t),t;let o=new go({concurrency:1}),s;return t={async readLock(i){if(s!=null)return Vl(s,i);s=new go({concurrency:e.concurrency,autoStart:!1});let a=s,c=Vl(s,i);return o.add(async()=>{a.start(),await a.onIdle().then(()=>{s===a&&(s=null)})}),c},async writeLock(i){return s=null,Vl(o,i)},finalize:()=>{br.delete(r)},queue:o},br.set(r,t),e.autoFinalize===!0&&o.addEventListener("idle",()=>{t.finalize()},{once:!0}),t};var My={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function zl(r){let e=Object.assign({},My,r);return kh(e.name,e)}var It;(function(r){let e;(function(a){let c;a.codec=()=>(c==null&&(c=Ne((d,h,p={})=>{p.lengthDelimited!==!1&&h.fork(),d.key!=null&&d.key!==""&&(h.uint32(10),h.string(d.key)),d.value!=null&&d.value.byteLength>0&&(h.uint32(18),h.bytes(d.value)),p.lengthDelimited!==!1&&h.ldelim()},(d,h,p={})=>{let y={key:"",value:le(0)},m=h==null?d.len:d.pos+h;for(;d.pos<m;){let g=d.uint32();switch(g>>>3){case 1:{y.key=d.string();break}case 2:{y.value=d.bytes();break}default:{d.skipType(g&7);break}}}return y},function*(d,h,p,y={}){let m=h==null?d.len:d.pos+h;for(;d.pos<m;){let g=d.uint32();switch(g>>>3){case 1:{yield{field:`${p}.key`,value:d.string()};break}case 2:{yield{field:`${p}.value`,value:d.bytes()};break}default:{d.skipType(g&7);break}}}})),c);function l(d){return Re(d,a.codec())}a.encode=l;function u(d,h){return ke(d,a.codec(),h)}a.decode=u;function f(d,h){return Oe(d,a.codec(),h)}a.stream=f})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(a){let c;a.codec=()=>(c==null&&(c=Ne((d,h,p={})=>{p.lengthDelimited!==!1&&h.fork(),d.key!=null&&d.key!==""&&(h.uint32(10),h.string(d.key)),d.value!=null&&(h.uint32(18),wo.codec().encode(d.value,h)),p.lengthDelimited!==!1&&h.ldelim()},(d,h,p={})=>{let y={key:""},m=h==null?d.len:d.pos+h;for(;d.pos<m;){let g=d.uint32();switch(g>>>3){case 1:{y.key=d.string();break}case 2:{y.value=wo.codec().decode(d,d.uint32(),{limits:p.limits?.value});break}default:{d.skipType(g&7);break}}}return y},function*(d,h,p,y={}){let m=h==null?d.len:d.pos+h;for(;d.pos<m;){let g=d.uint32();switch(g>>>3){case 1:{yield{field:`${p}.key`,value:d.string()};break}case 2:{yield*wo.codec().stream(d,d.uint32(),`${p}.value`,{limits:y.limits?.value});break}default:{d.skipType(g&7);break}}}})),c);function l(d){return Re(d,a.codec())}a.encode=l;function u(d,h){return ke(d,a.codec(),h)}a.decode=u;function f(d,h){return Oe(d,a.codec(),h)}a.stream=f})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Ne((a,c,l={})=>{if(l.lengthDelimited!==!1&&c.fork(),a.addresses!=null&&a.addresses.length>0)for(let u of a.addresses)c.uint32(10),bo.codec().encode(u,c);if(a.protocols!=null&&a.protocols.length>0)for(let u of a.protocols)c.uint32(18),c.string(u);if(a.publicKey!=null&&(c.uint32(34),c.bytes(a.publicKey)),a.peerRecordEnvelope!=null&&(c.uint32(42),c.bytes(a.peerRecordEnvelope)),a.metadata!=null&&a.metadata.size>0)for(let[u,f]of a.metadata.entries())c.uint32(50),r.Peer$metadataEntry.codec().encode({key:u,value:f},c);if(a.tags!=null&&a.tags.size>0)for(let[u,f]of a.tags.entries())c.uint32(58),r.Peer$tagsEntry.codec().encode({key:u,value:f},c);a.updated!=null&&(c.uint32(64),c.uint64Number(a.updated)),l.lengthDelimited!==!1&&c.ldelim()},(a,c,l={})=>{let u={addresses:[],protocols:[],metadata:new Map,tags:new Map},f=c==null?a.len:a.pos+c;for(;a.pos<f;){let d=a.uint32();switch(d>>>3){case 1:{if(l.limits?.addresses!=null&&u.addresses.length===l.limits.addresses)throw new Ge('Decode error - repeated field "addresses" had too many elements');u.addresses.push(bo.codec().decode(a,a.uint32(),{limits:l.limits?.addresses$}));break}case 2:{if(l.limits?.protocols!=null&&u.protocols.length===l.limits.protocols)throw new Ge('Decode error - repeated field "protocols" had too many elements');u.protocols.push(a.string());break}case 4:{u.publicKey=a.bytes();break}case 5:{u.peerRecordEnvelope=a.bytes();break}case 6:{if(l.limits?.metadata!=null&&u.metadata.size===l.limits.metadata)throw new Wn('Decode error - map field "metadata" had too many elements');let h=r.Peer$metadataEntry.codec().decode(a,a.uint32(),{limits:{value:l.limits?.metadata$value}});u.metadata.set(h.key,h.value);break}case 7:{if(l.limits?.tags!=null&&u.tags.size===l.limits.tags)throw new Wn('Decode error - map field "tags" had too many elements');let h=r.Peer$tagsEntry.codec().decode(a,a.uint32(),{limits:{value:l.limits?.tags$value}});u.tags.set(h.key,h.value);break}case 8:{u.updated=a.uint64Number();break}default:{a.skipType(d&7);break}}}return u},function*(a,c,l,u={}){let f={addresses:0,protocols:0,metadata:0,tags:0},d=c==null?a.len:a.pos+c;for(;a.pos<d;){let h=a.uint32();switch(h>>>3){case 1:{if(u.limits?.addresses!=null&&f.addresses===u.limits.addresses)throw new Ge('Streaming decode error - repeated field "addresses" had too many elements');for(let p of bo.codec().stream(a,a.uint32(),`${l}.addresses[]`,{limits:u.limits?.addresses$}))yield{...p,index:f.addresses};f.addresses++;break}case 2:{if(u.limits?.protocols!=null&&f.protocols===u.limits.protocols)throw new Ge('Streaming decode error - repeated field "protocols" had too many elements');yield{field:`${l}.protocols[]`,index:f.protocols,value:a.string()},f.protocols++;break}case 4:{yield{field:`${l}.publicKey`,value:a.bytes()};break}case 5:{yield{field:`${l}.peerRecordEnvelope`,value:a.bytes()};break}case 6:{if(u.limits?.metadata!=null&&f.metadata===u.limits.metadata)throw new Ge('Decode error - map field "metadata" had too many elements');yield*r.Peer$metadataEntry.codec().stream(a,a.uint32(),`${l}.metadata{}`,{limits:{value:u.limits?.metadata$value}}),f.metadata++;break}case 7:{if(u.limits?.tags!=null&&f.tags===u.limits.tags)throw new Ge('Decode error - map field "tags" had too many elements');yield*r.Peer$tagsEntry.codec().stream(a,a.uint32(),`${l}.tags{}`,{limits:{value:u.limits?.tags$value}}),f.tags++;break}case 8:{yield{field:`${l}.updated`,value:a.uint64Number()};break}default:{a.skipType(h&7);break}}}})),n);function o(a){return Re(a,r.codec())}r.encode=o;function s(a,c){return ke(a,r.codec(),c)}r.decode=s;function i(a,c){return Oe(a,r.codec(),c)}r.stream=i})(It||(It={}));var bo;(function(r){let e;r.codec=()=>(e==null&&(e=Ne((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.multiaddr!=null&&s.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(s.multiaddr)),s.isCertified!=null&&(i.uint32(16),i.bool(s.isCertified)),s.observed!=null&&(i.uint32(24),i.uint64Number(s.observed)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={multiaddr:le(0)},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.multiaddr=s.bytes();break}case 2:{c.isCertified=s.bool();break}case 3:{c.observed=s.uint64Number();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.multiaddr`,value:s.bytes()};break}case 2:{yield{field:`${a}.isCertified`,value:s.bool()};break}case 3:{yield{field:`${a}.observed`,value:s.uint64Number()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return Re(s,r.codec())}r.encode=t;function n(s,i){return ke(s,r.codec(),i)}r.decode=n;function o(s,i){return Oe(s,r.codec(),i)}r.stream=o})(bo||(bo={}));var wo;(function(r){let e;r.codec=()=>(e==null&&(e=Ne((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.value!=null&&s.value!==0&&(i.uint32(8),i.uint32(s.value)),s.expiry!=null&&(i.uint32(16),i.uint64(s.expiry)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={value:0},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.value=s.uint32();break}case 2:{c.expiry=s.uint64();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.value`,value:s.uint32()};break}case 2:{yield{field:`${a}.expiry`,value:s.uint64()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return Re(s,r.codec())}r.encode=t;function n(s,i){return ke(s,r.codec(),i)}r.decode=n;function o(s,i){return Oe(s,r.codec(),i)}r.stream=o})(wo||(wo={}));function By(r,e){if(r.publicKey!=null||e.publicKey==null)return r;let t;r.type==="RSA"&&(t=r.toMultihash());let n=Gr(e.publicKey,t);return jc(n)}function Rh(r,e,t){let n=It.decode(e);return hn(r,n,t)}function hn(r,e,t){let n=new Map,o=BigInt(Date.now());for(let[s,i]of e.tags.entries())i.expiry!=null&&i.expiry<o||n.set(s,i);return{...e,id:By(r,e),addresses:e.addresses.filter(({observed:s})=>s!=null&&s>Date.now()-t).map(({multiaddr:s,isCertified:i})=>({multiaddr:X(s),isCertified:i??!1})),metadata:e.metadata,peerRecordEnvelope:e.peerRecordEnvelope??void 0,tags:n}}function Oh(r,e){return Fy(r.addresses,e.addresses)&&Uy(r.protocols,e.protocols)&&Ky(r.publicKey,e.publicKey)&&qy(r.peerRecordEnvelope,e.peerRecordEnvelope)&&$y(r.metadata,e.metadata)&&Vy(r.tags,e.tags)}function Fy(r,e){return Mh(r,e,(t,n)=>!(t.isCertified!==n.isCertified||!Z(t.multiaddr,n.multiaddr)))}function Uy(r,e){return Mh(r,e,(t,n)=>t===n)}function Ky(r,e){return Nh(r,e)}function qy(r,e){return Nh(r,e)}function $y(r,e){return Bh(r,e,(t,n)=>Z(t,n))}function Vy(r,e){return Bh(r,e,(t,n)=>t.value===n.value&&t.expiry===n.expiry)}function Nh(r,e){return r==null&&e==null?!0:r!=null&&e!=null?Z(r,e):!1}function Mh(r,e,t){if(r.length!==e.length)return!1;for(let n=0;n<r.length;n++)if(!t(r[n],e[n]))return!1;return!0}function Bh(r,e,t){if(r.size!==e.size)return!1;for(let[n,o]of r.entries()){let s=e.get(n);if(s==null||!t(o,s))return!1}return!0}var Tt="/",Fh=new TextEncoder().encode(Tt),di=Fh[0],wr=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=L(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==di)throw new Error("Invalid key")}toString(e="utf8"){return U(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Tt))}static random(){return new r(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new r(e):typeof e.uint8Array=="function"?new r(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=Fh),this._buf[0]!==di){let e=new Uint8Array(this._buf.byteLength+1);e.fill(di,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===di;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let o=0;o<t.length;o++){if(n.length<o+1)return!1;let s=t[o],i=n[o];if(s<i)return!0;if(s>i)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Tt).slice(1)}type(){return zy(this.baseNamespace())}name(){return Hy(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Tt)||(e+=Tt),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Tt):new r(e.slice(0,-1).join(Tt))}child(e){return this.toString()===Tt?e:e.toString()===Tt?this:new r(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()===this.toString()?!1:e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()===this.toString()?!1:this.toString().startsWith(e.toString())}isTopLevel(){return this.list().length===1}concat(...e){return r.withNamespaces([...this.namespaces(),...Wy(e.map(t=>t.namespaces()))])}};function zy(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function Hy(r){let e=r.split(":");return e[e.length-1]}function Wy(r){return[].concat(...r)}var Hl="/peers/";function xo(r){if(!Dt(r)||r.type==null)throw new I("Invalid PeerId");let e=r.toCID().toString();return new wr(`${Hl}${e}`)}async function Uh(r,e,t,n,o){let s=new Map;for(let i of t){if(i==null)continue;if(i.multiaddr instanceof Uint8Array&&(i.multiaddr=X(i.multiaddr)),!zt(i.multiaddr))throw new I("Multiaddr was invalid");if(!await e(r,i.multiaddr,o))continue;let a=i.isCertified??!1,c=i.multiaddr.toString(),l=s.get(c);l!=null?i.isCertified=l.isCertified||a:s.set(c,{multiaddr:i.multiaddr,isCertified:a})}return[...s.values()].sort((i,a)=>i.multiaddr.toString().localeCompare(a.multiaddr.toString())).map(({isCertified:i,multiaddr:a})=>{let c=a.getComponents().find(l=>l.code===421)?.value;return r.equals(c)&&(a=a.decapsulate(X(`/p2p/${r}`))),{isCertified:i,multiaddr:a.bytes}})}async function pi(r,e,t,n){if(e==null)throw new I("Invalid PeerData");if(e.publicKey!=null&&r.publicKey!=null&&!e.publicKey.equals(r.publicKey))throw new I("publicKey bytes do not match peer id publicKey bytes");let o=n.existingPeer?.peer;if(o!=null&&!r.equals(o.id))throw new I("peer id did not match existing peer id");let s=o?.addresses??[],i=new Set(o?.protocols??[]),a=o?.metadata??new Map,c=o?.tags??new Map,l=o?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(s=[],e.multiaddrs!=null&&s.push(...e.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&s.push(...e.addresses)),e.protocols!=null&&(i=new Set(e.protocols)),e.metadata!=null){let d=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=hi(d,{validate:Kh})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=hi(d,{validate:qh,map:$h})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&s.push(...e.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&s.push(...e.addresses),e.protocols!=null&&(i=new Set([...i,...e.protocols])),e.metadata!=null){let d=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[h,p]of d)p==null?a.delete(h):a.set(h,p);a=hi([...a.entries()],{validate:Kh})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),h=new Map(c);for(let[p,y]of d)y==null?h.delete(p):h.set(p,y);c=hi([...h.entries()],{validate:qh,map:$h})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}let u;o?.id.publicKey!=null?u=We(o.id.publicKey):e.publicKey!=null?u=We(e.publicKey):r.publicKey!=null&&(u=We(r.publicKey));let f={addresses:await Uh(r,n.addressFilter??(async()=>!0),s,n.existingPeer?.peerPB.addresses,n),protocols:[...i.values()].sort((d,h)=>d.localeCompare(h)),metadata:a,tags:c,publicKey:u,peerRecordEnvelope:l};return f.addresses.forEach(d=>{d.observed=n.existingPeer?.peerPB.addresses?.find(h=>Z(h.multiaddr,h.multiaddr))?.observed??Date.now()}),r.type!=="RSA"&&delete f.publicKey,f}function hi(r,e){let t=new Map;for(let[n,o]of r)o!=null&&e.validate(n,o);for(let[n,o]of r.sort(([s],[i])=>s.localeCompare(i)))o!=null&&t.set(n,e.map?.(n,o)??o);return t}function Kh(r,e){if(typeof r!="string")throw new I("Metadata key must be a string");if(!(e instanceof Uint8Array))throw new I("Metadata value must be a Uint8Array")}function qh(r,e){if(typeof r!="string")throw new I("Tag name must be a string");if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new I("Tag value must be an integer");if(e.value<0||e.value>100)throw new I("Tag value must be between 0-100")}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new I("Tag ttl must be an integer");if(e.ttl<0)throw new I("Tag ttl must be between greater than 0")}}function $h(r,e){let t;e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl)));let n={value:e.value??0};return t!=null&&(n.expiry=t),n}function Vh(r){let e=r.toString().split("/")[2],t=ue.parse(e,He);return to(t)}function Wl(r,e,t){let n=Vh(r);return Rh(n,e,t)}function Gy(r,e){return{prefix:Hl,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(Wl(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(Wl(n.key,n.value,e),Wl(o.key,o.value,e)))}}var mi=class{peerId;datastore;locks;addressFilter;log;maxAddressAge;maxPeerAge;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.locks=Fl({name:"libp2p_peer_store_locks",metrics:e.metrics}),this.maxAddressAge=t.maxAddressAge??36e5,this.maxPeerAge=t.maxPeerAge??216e5}getLock(e){let t=this.locks.get(e);return t==null&&(t={refs:0,lock:zl({name:e.toString(),singleProcess:!0})},this.locks.set(e,t)),t.refs++,t}maybeRemoveLock(e,t){t.refs--,t.refs===0&&(t.lock.finalize(),this.locks.delete(e))}async getReadLock(e,t){let n=this.getLock(e);try{let o=await n.lock.readLock(t);return()=>{o(),this.maybeRemoveLock(e,n)}}catch(o){throw this.maybeRemoveLock(e,n),o}}async getWriteLock(e,t){let n=this.getLock(e);try{let o=await n.lock.writeLock(t);return()=>{o(),this.maybeRemoveLock(e,n)}}catch(o){throw this.maybeRemoveLock(e,n),o}}async has(e,t){try{return await this.load(e,t),!0}catch(n){if(n.name!=="NotFoundError")throw n}return!1}async delete(e,t){this.peerId.equals(e)||await this.datastore.delete(xo(e),t)}async load(e,t){let n=xo(e),o=await this.datastore.get(n,t),s=It.decode(o);if(this.#n(e,s))throw await this.datastore.delete(n,t),new Gt;return hn(e,s,this.peerId.equals(e)?1/0:this.maxAddressAge)}async save(e,t,n){let o=await this.#e(e,n),s=await pi(e,t,"patch",{...n,addressFilter:this.addressFilter});return this.#r(e,s,o)}async patch(e,t,n){let o=await this.#e(e,n),s=await pi(e,t,"patch",{...n,addressFilter:this.addressFilter,existingPeer:o});return this.#r(e,s,o)}async merge(e,t,n){let o=await this.#e(e,n),s=await pi(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#r(e,s,o)}async*all(e){for await(let{key:t,value:n}of this.datastore.query(Gy(e??{},this.maxAddressAge),e)){let o=Vh(t);if(o.equals(this.peerId))continue;let s=It.decode(n);if(this.#n(o,s)){await this.datastore.delete(t,e);continue}yield hn(o,s,this.peerId.equals(o)?1/0:this.maxAddressAge)}}async#e(e,t){try{let n=xo(e),o=await this.datastore.get(n,t),s=It.decode(o);if(this.#n(e,s))throw await this.datastore.delete(n,t),new Gt;return{peerPB:s,peer:hn(e,s,this.maxAddressAge)}}catch(n){n.name!=="NotFoundError"&&this.log.error("invalid peer data found in peer store - %e",n)}}async#r(e,t,n,o){t.updated=Date.now();let s=It.encode(t);return await this.datastore.put(xo(e),s,o),{peer:hn(e,t,this.maxAddressAge),previous:n?.peer,updated:n==null||!Oh(t,n.peerPB)}}#n(e,t){if(t.updated==null)return!0;if(this.peerId.equals(e))return!1;let n=t.updated<Date.now()-this.maxPeerAge,o=Date.now()-this.maxAddressAge,s=t.addresses.filter(i=>i.observed!=null&&i.observed>o);return n&&s.length===0}};var Gl=class{store;events;peerId;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.events=e.events,this.peerId=e.peerId,this.store=new mi(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){for await(let n of this.store.all(t))e(n)}async all(e){return mo(this.store.all(e))}async delete(e,t){let n=await this.store.getReadLock(e,t);try{await this.store.delete(e,t)}finally{n()}}async has(e,t){let n=await this.store.getReadLock(e,t);try{return await this.store.has(e,t)}finally{this.log.trace("has release read lock"),n?.()}}async get(e,t){let n=await this.store.getReadLock(e,t);try{return await this.store.load(e,t)}finally{n?.()}}async getInfo(e,t){let n=await this.get(e,t);return{id:n.id,multiaddrs:n.addresses.map(({multiaddr:o})=>o)}}async save(e,t,n){let o=await this.store.getWriteLock(e,n);try{let s=await this.store.save(e,t,n);return this.#e(e,s),s.peer}finally{o?.()}}async patch(e,t,n){let o=await this.store.getWriteLock(e,n);try{let s=await this.store.patch(e,t,n);return this.#e(e,s),s.peer}finally{o?.()}}async merge(e,t,n){let o=await this.store.getWriteLock(e,n);try{let s=await this.store.merge(e,t,n);return this.#e(e,s),s.peer}finally{o?.()}}async consumePeerRecord(e,t,n){let o=Dt(t)?t:Dt(t?.expectedPeer)?t.expectedPeer:void 0,s=Dt(t)||t===void 0?n:t,i=await dn.openAndCertify(e,yr.DOMAIN,s),a=to(i.publicKey.toCID());if(o?.equals(a)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",o,a),!1;let c=yr.createFromProtobuf(i.payload),l;try{l=await this.get(a,s)}catch(u){if(u.name!=="NotFoundError")throw u}if(l?.peerRecordEnvelope!=null){let u=dn.createFromProtobuf(l.peerRecordEnvelope),f=yr.createFromProtobuf(u.payload);if(f.seqNumber>=c.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",f.seqNumber,c.seqNumber),!1}return await this.patch(c.peerId,{peerRecordEnvelope:e,addresses:c.multiaddrs.map(u=>({isCertified:!0,multiaddr:u}))},s),!0}#e(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}};function zh(r,e={}){return new Gl(r,e)}var gi=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(e="Not Found"){super(e)}};function Yy(r){return r[Symbol.asyncIterator]!=null}function Xy(r){if(Yy(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Yl=Xy;function jy(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var Hh=jy;function Zy(r){return r[Symbol.asyncIterator]!=null}function Qy(r,e){let t=0;if(Zy(r))return(async function*(){for await(let c of r)await e(c,t++)&&(yield c)})();let n=Hh(r),{value:o,done:s}=n.next();if(s===!0)return(function*(){})();let i=e(o,t++);if(typeof i.then=="function")return(async function*(){await i&&(yield o);for(let c of n)await e(c,t++)&&(yield c)})();let a=e;return(function*(){i===!0&&(yield o);for(let c of n)a(c,t++)&&(yield c)})()}var xr=Qy;function Jy(r){return r[Symbol.asyncIterator]!=null}function eb(r,e){return Jy(r)?(async function*(){yield*(await mo(r)).sort(e)})():(function*(){yield*mo(r).sort(e)})()}var Xl=eb;function tb(r){return r[Symbol.asyncIterator]!=null}function rb(r,e){return tb(r)?(async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}})():(function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}})()}var jl=rb;var yi=class{put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(let{key:n,value:o}of e)await this.put(n,o,t),yield n}async*getMany(e,t={}){for await(let n of e)yield{key:n,value:await this.get(n,t)}}async*deleteMany(e,t={}){for await(let n of e)await this.delete(n,t),yield n}batch(){let e=[],t=[];return{put(n,o){e.push({key:n,value:o})},delete(n){t.push(n)},commit:async n=>{await Yl(this.putMany(e,n)),e=[],await Yl(this.deleteMany(t,n)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let n=this._all(e,t);if(e.prefix!=null){let o=e.prefix;n=xr(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>xr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>Xl(o,s),n)),e.offset!=null){let o=0,s=e.offset;n=xr(n,()=>o++>=s)}return e.limit!=null&&(n=jl(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let o=e.prefix;n=xr(n,s=>s.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>xr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>Xl(o,s),n)),e.offset!=null){let o=e.offset,s=0;n=xr(n,()=>s++>=o)}return e.limit!=null&&(n=jl(n,e.limit)),n}};var bi=class extends yi{data;constructor(){super(),this.data=new Map}put(e,t,n){return n?.signal?.throwIfAborted(),this.data.set(e.toString(),t),e}get(e,t){t?.signal?.throwIfAborted();let n=this.data.get(e.toString());if(n==null)throw new gi;return n}has(e,t){return t?.signal?.throwIfAborted(),this.data.has(e.toString())}delete(e,t){t?.signal?.throwIfAborted(),this.data.delete(e.toString())}*_all(e,t){t?.signal?.throwIfAborted();for(let[n,o]of this.data.entries())yield{key:new wr(n),value:o},t?.signal?.throwIfAborted()}*_allKeys(e,t){t?.signal?.throwIfAborted();for(let n of this.data.keys())yield new wr(n),t?.signal?.throwIfAborted()}};var ee=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),N=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),Wh=r=>({match:e=>r.match(e)===!1?e:!1}),W=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),Ie=(...r)=>({match:e=>{let t;for(let n of r){let o=n.match(e);o!==!1&&(t==null||o.length<t.length)&&(t=o)}return t??!1}}),j=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e}});function te(...r){function e(o){if(o==null)return!1;let s=o.getComponents();for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function t(o){return e(o)!==!1}function n(o){let s=e(o);return s===!1?!1:s.length===0}return{matchers:r,matches:t,exactMatch:n}}var nb=N(421),Gh=te(nb),xi=N(54),Ei=N(55),vi=N(56),Ql=N(53),_6=te(xi,W(N(421))),A6=te(Ei,W(N(421))),C6=te(vi,W(N(421))),I6=te(Ie(Ql,vi,xi,Ei),W(N(421))),Yh=j(N(4),W(N(43))),Xh=j(W(N(42)),N(41),W(N(43))),Jl=Ie(Yh,Xh),Er=Ie(Jl,Ql,xi,Ei,vi),T6=te(Ie(Jl,j(Ie(Ql,vi,xi,Ei),W(N(421))))),eu=te(Yh),tu=te(Xh),L6=te(Jl),ru=j(Er,N(6)),Eo=j(Er,N(273)),vo=te(j(ru,W(N(421)))),P6=te(Eo),nu=j(Eo,ee(460),W(N(421))),Si=j(Eo,ee(461),W(N(421))),ob=Ie(nu,Si),D6=te(nu),jh=te(Si),Zl=Ie(Er,ru,Eo,nu,Si),Zh=Ie(j(Zl,ee(477),W(N(421)))),vr=te(Zh),Qh=Ie(j(Zl,ee(478),W(N(421))),j(Zl,ee(448),W(N(449)),ee(477),W(N(421)))),So=te(Qh),Jh=j(Eo,ee(280),W(N(466)),W(N(466)),W(N(421))),ou=te(Jh),ep=j(Si,ee(465),W(N(466)),W(N(466)),W(N(421))),su=te(ep),wi=Ie(Zh,Qh,j(ru,W(N(421))),j(ob,W(N(421))),j(Er,W(N(421))),Jh,ep,N(421)),k6=te(wi),sb=j(W(wi),ee(290),Wh(ee(281)),W(N(421))),Sr=te(sb),ib=Ie(j(wi,ee(290),ee(281),W(N(421))),j(wi,ee(281),W(N(421))),j(ee(281),W(N(421)))),iu=te(ib),ab=Ie(j(Er,N(6),ee(480),W(N(421))),j(Er,ee(480),W(N(421)))),R6=te(ab),cb=j(Er,Ie(j(N(6,"443"),ee(480)),j(N(6),ee(443)),j(N(6),ee(448),ee(480)),j(ee(448),ee(480)),ee(448),ee(443)),W(N(421))),O6=te(cb),lb=Ie(j(N(777),W(N(421)))),N6=te(lb),ub=Ie(j(N(400),W(N(421)))),M6=te(ub);var tp=864e13;var _i=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=Ce({name:"libp2p_address_manager_dns_mappings",metrics:e.metrics})}has(e){let t=H(e),n=t.host;(t.type==="ip4"||t.type==="ip6")&&t.sni!=null&&(n=t.sni);for(let o of this.mappings.values())if(o.domain===n)return!0;return!1}add(e,t){t.forEach(n=>{this.log("add DNS mapping %s to %s",n,e);let o=Qr(n)===!0;this.mappings.set(n,{domain:e,verified:o,expires:o?tp-Date.now():0,lastVerified:o?tp-Date.now():void 0})})}remove(e){let t=H(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;let n=!1;for(let[o,s]of this.mappings.entries())s.domain===t.sni&&(this.log("removing %s to %s DNS mapping %e",o,s.domain),this.mappings.delete(o),n=n||s.verified);return n}getAll(e){let t=[];for(let n=0;n<e.length;n++){let o=e[n].multiaddr;if(!xe(o))continue;let s=H(o);for(let[i,a]of this.mappings.entries()){if(s.host!==i)continue;let c=this.maybeAddSNIComponent(o,a.domain);c!=null&&(e.splice(n,1),n--,t.push({multiaddr:c,verified:a.verified,type:"dns-mapping",expires:a.expires,lastVerified:a.lastVerified}))}}return t}maybeAddSNIComponent(e,t){let n=e.getComponents();for(let o=0;o<n.length;o++)if(n[o].code===448&&n[o+1]?.code!==449)return n.splice(o+1,0,{name:"sni",code:449,value:t}),X(n)}confirm(e,t){let n=H(e),o=n.host;(n.type==="ip4"||n.type==="ip6")&&n.sni!=null&&(o=n.sni);let s=!1;for(let[i,a]of this.mappings.entries())a.domain===o&&(this.log("marking %s to %s DNS mapping as verified",i,a.domain),s=a.verified,a.verified=!0,a.expires=Date.now()+t,a.lastVerified=Date.now());return s}unconfirm(e,t){let n=H(e);if(n.type!=="ip4"&&n.type!=="ip6")return!1;let o=n.sni??n.host,s=!1;for(let[i,a]of this.mappings.entries())a.domain===o&&(this.log("removing verification of %s to %s DNS mapping",i,a.domain),s=s||a.verified,a.verified=!1,a.expires=Date.now()+t);return s}};var Ai=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=Ce({name:"libp2p_address_manager_ip_mappings",metrics:e.metrics})}has(e){let t=H(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;for(let n of this.mappings.values())for(let o of n)if(o.externalIp===t.host)return!0;return!1}add(e,t,n,o=t,s="tcp"){let i=`${e}-${t}-${s}`,a=this.mappings.get(i)??[],c={internalIp:e,internalPort:t,externalIp:n,externalPort:o,externalFamily:nt(n)?4:6,protocol:s,verified:!1,expires:0};a.push(c),this.mappings.set(i,a)}remove(e){let t=H(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;let n=!1;for(let[o,s]of this.mappings.entries()){for(let i=0;i<s.length;i++){let a=s[i];a.externalIp===t.host&&a.externalPort===t.port&&a.protocol===t.protocol&&(this.log("removing %s:%s to %s:%s %s IP mapping",a.externalIp,a.externalPort,t.host,t.port,t.protocol),n=n||a.verified,s.splice(i,1),i--)}s.length===0&&this.mappings.delete(o)}return n}getAll(e){let t=[];for(let{multiaddr:n}of e){if(!xe(n))continue;let o=H(n);if(o.type!=="ip4"&&o.type!=="ip6")continue;let s;if(o.protocol==="tcp"?s=`${o.host}-${o.port}-tcp`:o.protocol==="udp"&&(s=`${o.host}-${o.port}-udp`),s==null)continue;let i=this.mappings.get(s);if(i!=null)for(let a of i)t.push({multiaddr:this.maybeOverrideIp(n,a.externalIp,a.externalFamily,a.protocol,a.externalPort),verified:a.verified,type:"ip-mapping",expires:a.expires,lastVerified:a.lastVerified})}return t}maybeOverrideIp(e,t,n,o,s){let i=e.getComponents(),a=i.findIndex(l=>l.code===4||l.code===41),c=i.findIndex(l=>l.name===o);return a>-1&&c>-1?(i[a].value=t,i[a].code=n===4?4:41,i[c].value=`${s}`,X(i)):e}confirm(e,t){if(!xe(e))return!1;let n=H(e),o=!1;for(let s of this.mappings.values())for(let i of s)i.externalIp===n.host&&(this.log("marking %s to %s IP mapping as verified",i.internalIp,i.externalIp),o=i.verified,i.verified=!0,i.expires=Date.now()+t,i.lastVerified=Date.now());return o}unconfirm(e,t){if(!xe(e))return!1;let n=H(e),o=!1;for(let s of this.mappings.values())for(let i=0;i<s.length;i++){let a=s[i];a.externalIp===n.host&&a.externalPort===n.port&&a.protocol===n.protocol&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",a.externalIp,a.externalPort,n.host,n.port,n.protocol),o=o||a.verified,a.verified=!1,a.expires=Date.now()+t)}return o}};var fb={maxObservedAddresses:10},Ci=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Ce({name:"libp2p_address_manager_observed_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??fb.maxObservedAddresses}has(e){return this.addresses.has(e.toString())}removePrefixed(e){for(let t of this.addresses.keys())t.toString().startsWith(e)&&this.addresses.delete(t)}add(e){this.addresses.size!==this.maxObservedAddresses&&(St(e)||oh(e)||(this.log("adding observed address %a",e),this.addresses.set(e.toString(),{verified:!1,expires:0})))}getAll(){return Array.from(this.addresses).map(([e,t])=>({multiaddr:X(e),verified:t.verified,type:"observed",expires:t.expires,lastVerified:t.lastVerified}))}remove(e){let t=this.addresses.get(e.toString())?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(e.toString()),t}confirm(e,t){let n=e.toString(),o=this.addresses.get(n)??{verified:!1,expires:Date.now()+t,lastVerified:Date.now()},s=o.verified;return o.verified=!0,o.expires=Date.now()+t,o.lastVerified=Date.now(),this.log("marking observed address %a as verified",n),this.addresses.set(n,o),s}};var db={maxObservedAddresses:10},Ii=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Ce({name:"libp2p_address_manager_transport_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??db.maxObservedAddresses}get(e,t){if(St(e))return{multiaddr:e,verified:!0,type:"transport",expires:Date.now()+t,lastVerified:Date.now()};let n=this.toKey(e),o=this.addresses.get(n);return o==null&&(o={verified:!xe(e),expires:0},this.addresses.set(n,o)),{multiaddr:e,verified:o.verified,type:"transport",expires:o.expires,lastVerified:o.lastVerified}}has(e){let t=this.toKey(e);return this.addresses.has(t)}remove(e){let t=this.toKey(e),n=this.addresses.get(t)?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(t),n}confirm(e,t){let n=this.toKey(e),o=this.addresses.get(n)??{verified:!1,expires:0,lastVerified:0},s=o.verified;return o.verified=!0,o.expires=Date.now()+t,o.lastVerified=Date.now(),this.addresses.set(n,o),s}unconfirm(e,t){let n=this.toKey(e),o=this.addresses.get(n)??{verified:!1,expires:0},s=o.verified;return o.verified=!1,o.expires=Date.now()+t,this.addresses.set(n,o),s}toKey(e){if(!xe(e))return e.toString();let t=H(e);return`${t.host}-${t.port}-${t.protocol}`}};var rp=6e4,np={maxObservedAddresses:10,addressVerificationTTL:rp*10,addressVerificationRetry:rp*5},hb=r=>r;function au(r,e){let t=r.getComponents().findLast(n=>n.code===421)?.value;return t!=null&&ut(t).equals(e)&&(r=r.decapsulate(X(`/p2p/${e.toString()}`))),r}var Ti=class{log;components;listen;announce;appendAnnounce;announceFilter;observed;dnsMappings;ipMappings;transportAddresses;observedAddressFilter;addressVerificationTTL;addressVerificationRetry;constructor(e,t={}){let{listen:n=[],announce:o=[],appendAnnounce:s=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(i=>i.toString()),this.announce=new Set(o.map(i=>i.toString())),this.appendAnnounce=new Set(s.map(i=>i.toString())),this.observed=new Ci(e,t),this.dnsMappings=new _i(e,t),this.ipMappings=new Ai(e,t),this.transportAddresses=new Ii(e,t),this.announceFilter=t.announceFilter??hb,this.observedAddressFilter=oo(1024),this.addressVerificationTTL=t.addressVerificationTTL??np.addressVerificationTTL,this.addressVerificationRetry=t.addressVerificationRetry??np.addressVerificationRetry,this._updatePeerStoreAddresses=lo(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){let e=this.getAddresses().map(t=>t.getComponents().findLast(n=>n.code===421)?.value===this.components.peerId.toString()?t.decapsulate(`/p2p/${this.components.peerId.toString()}`):t);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(t=>{this.log.error("error updating addresses - %e",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>X(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>X(e))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(e=>X(e))}getObservedAddrs(){return this.observed.getAll().map(e=>e.multiaddr)}addObservedAddr(e){let t=H(e),n;switch(t.type){case"ip4":{n=`${t.host}:${t.port}`;break}case"ip6":{n=`[${t.host}]:${t.port}`;break}default:return}this.observedAddressFilter.has(n)||(this.observedAddressFilter.add(n),e=au(e,this.components.peerId),!this.ipMappings.has(e)&&(this.dnsMappings.has(e)||this.observed.add(e)))}confirmObservedAddr(e,t){e=au(e,this.components.peerId);let n=!0;(t?.type==="transport"||this.transportAddresses.has(e))&&!this.transportAddresses.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="dns-mapping"||this.dnsMappings.has(e))&&!this.dnsMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="ip-mapping"||this.ipMappings.has(e))&&!this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="observed"||this.observed.has(e))&&(this.maybeUpgradeToIPMapping(e)?(this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL),n=!1):!this.observed.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1)),n||this._updatePeerStoreAddresses()}removeObservedAddr(e,t){e=au(e,this.components.peerId);let n=!1;this.observed.has(e)&&!this.observed.remove(e)&&n&&(n=!1),this.transportAddresses.has(e)&&!this.transportAddresses.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.dnsMappings.has(e)&&!this.dnsMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.ipMappings.has(e)&&!this.ipMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),n&&this._updatePeerStoreAddresses()}getAddresses(){let e=new Set,t=this.getAddressesWithMetadata().filter(n=>{if(!n.verified)return!1;let o=n.multiaddr.toString();return e.has(o)?!1:(e.add(o),!0)}).map(n=>n.multiaddr);return this.announceFilter(t.map(n=>{let o=X(n);return o.getComponents().pop()?.value===this.components.peerId.toString()?o:o.encapsulate(`/p2p/${this.components.peerId.toString()}`)}))}getAddressesWithMetadata(){let e=this.getAnnounceAddrs();if(e.length>0)return this.components.transportManager.getListeners().forEach(o=>{o.updateAnnounceAddrs(e)}),e.map(o=>({multiaddr:o,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}));let t=[];t=t.concat(this.components.transportManager.getAddrs().map(o=>this.transportAddresses.get(o,this.addressVerificationTTL)));let n=this.getAppendAnnounceAddrs();return n.length>0&&(this.components.transportManager.getListeners().forEach(o=>{o.updateAnnounceAddrs(n)}),t=t.concat(n.map(o=>({multiaddr:o,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()})))),t=t.concat(this.observed.getAll()),t=t.concat(this.ipMappings.getAll(t)),t=t.concat(this.dnsMappings.getAll(t)),t}addDNSMapping(e,t){this.dnsMappings.add(e,t)}removeDNSMapping(e){this.dnsMappings.remove(X(`/dns/${e}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,n,o=t,s="tcp"){this.ipMappings.add(e,t,n,o,s),this.observed.removePrefixed(`/ip${nt(n)?4:6}/${n}/${s}/${o}`)}removePublicAddressMapping(e,t,n,o=t,s="tcp"){this.ipMappings.remove(X(`/ip${nt(n)?4:6}/${n}/${s}/${o}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){if(this.ipMappings.has(e)||!xe(e))return!1;let t=H(e);if(t.type!=="ip4"||Qr(t.host)===!0)return!1;let n=this.components.transportManager.getListeners(),o=[s=>vr.exactMatch(s)||So.exactMatch(s),s=>vo.exactMatch(s),s=>jh.exactMatch(s)];for(let s of o){if(!s(e))continue;let i=n.filter(l=>l.getAddrs().filter(u=>H(u).type==="ip4"&&s(u)).length>0);if(i.length!==1)continue;let a=i[0].getAddrs().filter(l=>!io(l)).pop();if(a==null)continue;let c=H(a);return c.port==null?!1:(this.observed.remove(e),this.ipMappings.add(c.host,c.port,t.host,t.port,t.protocol),!0)}return!1}};var op;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(op||(op={}));var Li=class extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}},Pi=class extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}},pn=class extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}},_o=class extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}},Di=class extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}},ki=class extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}},Ri=class extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}},Ao=class extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}},Oi=class extends Error{constructor(e="No transport was configured to listen on this address"){super(e),this.name="UnsupportedListenAddressError"}},Ni=class extends Error{constructor(e="Configured listen addresses could not be listened on"){super(e),this.name="UnsupportedListenAddressesError"}},Mi=class extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}},Bi=class extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}},Fi=class extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}},Ht=class extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}},_r=class extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}},Ui=class extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}},Ki=class extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}};var cu=class{components={};_started=!1;constructor(e={}){this.components={};for(let[t,n]of Object.entries(e))this.components[t]=n;this.components.logger==null&&(this.components.logger=ys())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>zo(t)).map(async t=>{await t[e]?.()}))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}},pb=["metrics","connectionProtector","dns"],mb=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function sp(r={}){let e=new cu(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!mb.includes(o)){let i=e.components[o];if(i==null&&!pb.includes(o))throw new Li(`${o} not set`);return i}return Reflect.get(n,o,s)},set(n,o,s){return typeof o=="string"?e.components[o]=s:Reflect.set(n,o,s),!0}})}function ip(r){let e={};for(let t of Object.values(r.components))for(let n of gb(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of yb(t))if(e[n]!==!0)throw new Pi(`Service "${bb(t)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function gb(r){return Array.isArray(r?.[xn])?r[xn]:[]}function yb(r){return Array.isArray(r?.[ga])?r[ga]:[]}function bb(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}function ap(r={}){return r.denyDialMultiaddr==null&&(r.denyDialMultiaddr=e=>vr.matches(e)?!0:St(e)),r}var de=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};function qi(r){if(Dt(r))return{peerId:r,multiaddrs:[]};let e=Array.isArray(r)?r:[r],t;if(e.length>0){let n=e[0].getComponents().findLast(o=>o.code===421)?.value;t=n==null?void 0:ut(n),e.forEach(o=>{if(!zt(o))throw new Lt("Invalid multiaddr");let s=o.getComponents().findLast(i=>i.code===421)?.value;if(s==null){if(t!=null)throw new I("Multiaddrs must all have the same peer id or have no peer id")}else{let i=ut(s);if(t?.equals(i)!==!0)throw new I("Multiaddrs must all have the same peer id or have no peer id")}})}return e=e.filter(n=>!Gh.exactMatch(n)),{peerId:t,multiaddrs:e}}var wb=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function cp(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??wb;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}function Co(r){let e=H(r),t=e.cidr;if(e.type!=="ip4"&&e.type!=="ip6")throw new I(`Multiaddr ${r} was not an IPv4 or IPv6 address`);if(t==null)switch(e.type){case"ip4":{t=32;break}case"ip6":{t=128;break}default:throw new I(`Multiaddr ${r} was not an IPv4 or IPv6 address`)}return new Zr(e.host,t)}function lu(r){return!Sr.exactMatch(r)}function $i(r,e,t){if(r==null||e==null)return;let n=e.filter(s=>s.status==="open").sort((s,i)=>s.direct?-1:i.direct?1:0).find(s=>s.limits==null);if(n==null||n.direct||t==null)return n;if(!t.some(s=>lu(s)))return n}var Vi=class{connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.allow=(t.allow??[]).map(n=>Co(n)),this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),this.maybePruneConnections=this.maybePruneConnections.bind(this)}start(){this.events.addEventListener("connection:open",this.maybePruneConnections)}stop(){this.events.removeEventListener("connection:open",this.maybePruneConnections)}maybePruneConnections(){this._maybePruneConnections().catch(e=>{this.log.error("error while pruning connections - %e",e)})}async _maybePruneConnections(){let e=this.connectionManager.getConnections(),t=e.length,n=this.connectionManager.getMaxConnections();if(this.log("checking max connections limit %d/%d",t,n),t<=n)return;let o=new Ye;for(let c of e){let l=c.remotePeer;if(!o.has(l)){o.set(l,0);try{let u=await this.peerStore.get(l);o.set(l,[...u.tags.values()].reduce((f,d)=>f+d.value,0))}catch(u){u.name!=="NotFoundError"&&this.log.error("error loading peer tags - %e",u)}}}let s=this.sortConnections(e,o),i=Math.max(t-n,0),a=[];for(let c of s)if(this.log("too many connections open - closing a connection to %p",c.remotePeer),this.allow.some(u=>{if(xe(c.remoteAddr)){let f=H(c.remoteAddr);return u.contains(f.host)}return!0})||a.push(c),a.length===i)break;await Promise.all(a.map(async c=>{await cp(c,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:a})}sortConnections(e,t){return e.sort((n,o)=>{let s=n.timeline.open,i=o.timeline.open;return s<i?1:s>i?-1:0}).sort((n,o)=>n.direction==="outbound"&&o.direction==="inbound"?1:n.direction==="inbound"&&o.direction==="outbound"?-1:0).sort((n,o)=>n.streams.length>o.streams.length?1:n.streams.length<o.streams.length?-1:0).sort((n,o)=>{let s=t.get(n.remotePeer)??0,i=t.get(o.remotePeer)??0;return s>i?1:s<i?-1:0})}};var lp="last-dial-failure",up="last-dial-success";var fp=100,zi=50;function xb(r,e){let t=vo.exactMatch(r.multiaddr),n=vo.exactMatch(e.multiaddr);if(t&&!n)return-1;if(!t&&n)return 1;let o=So.exactMatch(r.multiaddr),s=So.exactMatch(e.multiaddr);if(o&&!s)return-1;if(!o&&s)return 1;let i=vr.exactMatch(r.multiaddr),a=vr.exactMatch(e.multiaddr);if(i&&!a)return-1;if(!i&&a)return 1;let c=iu.exactMatch(r.multiaddr),l=iu.exactMatch(e.multiaddr);if(c&&!l)return-1;if(!c&&l)return 1;let u=ou.exactMatch(r.multiaddr),f=ou.exactMatch(e.multiaddr);if(u&&!f)return-1;if(!u&&f)return 1;let d=su.exactMatch(r.multiaddr),h=su.exactMatch(e.multiaddr);return d&&!h?-1:!d&&h?1:0}function Eb(r,e){let t=io(r.multiaddr),n=io(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function vb(r,e){let t=St(r.multiaddr),n=St(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function Sb(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function _b(r,e){let t=Sr.exactMatch(r.multiaddr),n=Sr.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function dp(r){return r.sort(xb).sort(Sb).sort(_b).sort(vb).sort(Eb)}var Hi=class extends AggregateError{static name="DNSQueryFailedError";name="DNSQueryFailedError"};var fu=fa(pp(),1);function du(r,e,t){let n=0,o=r.length;for(;o>0;){let s=Math.trunc(o/2),i=n+s;t(r[i],e)<=0?(n=++i,o-=s+1):o=s}return n}var To=class{#e=[];enqueue(e,t){let{priority:n=0,id:o}=t??{},s={priority:n,id:o,run:e};if(this.size===0||this.#e[this.size-1].priority>=n){this.#e.push(s);return}let i=du(this.#e,s,(a,c)=>c.priority-a.priority);this.#e.splice(i,0,s)}setPriority(e,t){let n=this.#e.findIndex(s=>s.id===e);if(n===-1)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);let[o]=this.#e.splice(n,1);this.enqueue(o.run,{priority:t,id:e})}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this.#e.length}};var Lo=class extends fu.default{#e;#r;#n=0;#h;#m=!1;#b=!1;#c;#C=0;#w=0;#l;#u;#a;#i=[];#s=0;#t;#I;#o=0;#g;#f;#k=1n;#y=new Map;timeout;constructor(e){if(super(),e={carryoverIntervalCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:To,strict:!1,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${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 \`${e.interval?.toString()??""}\` (${typeof e.interval})`);if(e.strict&&e.interval===0)throw new TypeError("The `strict` option requires a non-zero `interval`");if(e.strict&&e.intervalCap===Number.POSITIVE_INFINITY)throw new TypeError("The `strict` option requires a finite `intervalCap`");if(this.#e=e.carryoverIntervalCount??e.carryoverConcurrencyCount??!1,this.#r=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#h=e.intervalCap,this.#c=e.interval,this.#a=e.strict,this.#t=new e.queueClass,this.#I=e.queueClass,this.concurrency=e.concurrency,e.timeout!==void 0&&!(Number.isFinite(e.timeout)&&e.timeout>0))throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${e.timeout}\` (${typeof e.timeout})`);this.timeout=e.timeout,this.#f=e.autoStart===!1,this.#K()}#x(e){for(;this.#s<this.#i.length;){let n=this.#i[this.#s];if(n!==void 0&&e-n>=this.#c)this.#s++;else break}(this.#s>100&&this.#s>this.#i.length/2||this.#s===this.#i.length)&&(this.#i=this.#i.slice(this.#s),this.#s=0)}#R(e){this.#a?this.#i.push(e):this.#n++}#O(){this.#a?this.#i.length>this.#s&&this.#i.pop():this.#n>0&&this.#n--}#E(){return this.#i.length-this.#s}get#N(){return this.#r?!0:this.#a?this.#E()<this.#h:this.#n<this.#h}get#M(){return this.#o<this.#g}#B(){this.#o--,this.#o===0&&this.emit("pendingZero"),this.#_(),this.emit("next")}#F(){this.#u=void 0,this.#P(),this.#L()}#U(e){if(this.#a){if(this.#x(e),this.#E()>=this.#h){let n=this.#i[this.#s],o=this.#c-(e-n);return this.#v(o),!0}return!1}if(this.#l===void 0){let t=this.#C-e;if(t<0){if(this.#w>0){let n=e-this.#w;if(n<this.#c)return this.#v(this.#c-n),!0}this.#n=this.#e?this.#o:0}else return this.#v(t),!0}return!1}#v(e){this.#u===void 0&&(this.#u=setTimeout(()=>{this.#F()},e))}#S(){this.#l&&(clearInterval(this.#l),this.#l=void 0)}#T(){this.#u&&(clearTimeout(this.#u),this.#u=void 0)}#_(){if(this.#t.size===0){if(this.#S(),this.emit("empty"),this.#o===0){if(this.#T(),this.#a&&this.#s>0){let t=Date.now();this.#x(t)}this.emit("idle")}return!1}let e=!1;if(!this.#f){let t=Date.now(),n=!this.#U(t);if(this.#N&&this.#M){let o=this.#t.dequeue();this.#r||(this.#R(t),this.#p()),this.emit("active"),o(),n&&this.#L(),e=!0}}return e}#L(){this.#r||this.#l!==void 0||this.#a||(this.#l=setInterval(()=>{this.#P()},this.#c),this.#C=Date.now()+this.#c)}#P(){this.#a||(this.#n===0&&this.#o===0&&this.#l&&this.#S(),this.#n=this.#e?this.#o:0),this.#A(),this.#p()}#A(){for(;this.#_(););}get concurrency(){return this.#g}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})`);this.#g=e,this.#A()}setPriority(e,t){if(typeof t!="number"||!Number.isFinite(t))throw new TypeError(`Expected \`priority\` to be a finite number, got \`${t}\` (${typeof t})`);this.#t.setPriority(e,t)}async add(e,t={}){return t={timeout:this.timeout,...t,id:t.id??(this.#k++).toString()},new Promise((n,o)=>{let s=Symbol(`task-${t.id}`);this.#t.enqueue(async()=>{this.#o++,this.#y.set(s,{id:t.id,priority:t.priority??0,startTime:Date.now(),timeout:t.timeout});let i;try{try{t.signal?.throwIfAborted()}catch(l){throw this.#q(),this.#y.delete(s),l}this.#w=Date.now();let a=e({signal:t.signal});if(t.timeout&&(a=co(Promise.resolve(a),{milliseconds:t.timeout,message:`Task timed out after ${t.timeout}ms (queue has ${this.#o} running, ${this.#t.size} waiting)`})),t.signal){let{signal:l}=t;a=Promise.race([a,new Promise((u,f)=>{i=()=>{f(l.reason)},l.addEventListener("abort",i,{once:!0})})])}let c=await a;n(c),this.emit("completed",c)}catch(a){o(a),this.emit("error",a)}finally{i&&t.signal?.removeEventListener("abort",i),this.#y.delete(s),queueMicrotask(()=>{this.#B()})}},t),this.emit("add"),this.#_()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#f?(this.#f=!1,this.#A(),this):this}pause(){this.#f=!0}clear(){this.#t=new this.#I,this.#S(),this.#D(),this.emit("empty"),this.#o===0&&(this.#T(),this.emit("idle")),this.emit("next")}async onEmpty(){this.#t.size!==0&&await this.#d("empty")}async onSizeLessThan(e){this.#t.size<e||await this.#d("next",()=>this.#t.size<e)}async onIdle(){this.#o===0&&this.#t.size===0||await this.#d("idle")}async onPendingZero(){this.#o!==0&&await this.#d("pendingZero")}async onRateLimit(){this.isRateLimited||await this.#d("rateLimit")}async onRateLimitCleared(){this.isRateLimited&&await this.#d("rateLimitCleared")}onError(){return new Promise((e,t)=>{let n=o=>{this.off("error",n),t(o)};this.on("error",n)})}async#d(e,t){return new Promise(n=>{let o=()=>{t&&!t()||(this.off(e,o),n())};this.on(e,o)})}get size(){return this.#t.size}sizeBy(e){return this.#t.filter(e).length}get pending(){return this.#o}get isPaused(){return this.#f}#K(){this.#r||(this.on("add",()=>{this.#t.size>0&&this.#p()}),this.on("next",()=>{this.#p()}))}#p(){this.#r||this.#b||(this.#b=!0,queueMicrotask(()=>{this.#b=!1,this.#D()}))}#q(){this.#r||(this.#O(),this.#p())}#D(){let e=this.#m;if(this.#r||this.#t.size===0){e&&(this.#m=!1,this.emit("rateLimitCleared"));return}let t;if(this.#a){let o=Date.now();this.#x(o),t=this.#E()}else t=this.#n;let n=t>=this.#h;n!==e&&(this.#m=n,this.emit(n?"rateLimit":"rateLimitCleared"))}get isRateLimited(){return this.#m}get isSaturated(){return this.#o===this.#g&&this.#t.size>0||this.isRateLimited&&this.#t.size>0}get runningTasks(){return[...this.#y.values()].map(e=>({...e}))}};function Gi(r){let e=[ze.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var hu=60;function Yi(r){return{Status:r.Status??0,TC:r.TC??r.flag_tc??!1,RD:r.RD??r.flag_rd??!1,RA:r.RA??r.flag_ra??!1,AD:r.AD??r.flag_ad??!1,CD:r.CD??r.flag_cd??!1,Question:(r.Question??r.questions??[]).map(e=>({name:e.name,type:ze[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:ze[e.type],TTL:e.TTL??e.ttl??hu,data:e.data instanceof Uint8Array?U(e.data):e.data}))}}var Ib=4;function pu(r,e={}){let t=new Lo({concurrency:e.queryConcurrency??Ib});return async(n,o={})=>{let s=o?.logger?.forComponent("dns:dns-json-over-https"),i=new URLSearchParams;i.set("name",n),Gi(o.types).forEach(c=>{i.append("type",ze[c])}),o.onProgress?.(new de("dns:query",n)),s?.("GET %s",`${r}?${i}`);let a=await t.add(async()=>{let c=await fetch(`${r}?${i}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(s?.("GET %s %d",c.url,c.status),c.status!==200)throw new Error(`Unexpected HTTP status: ${c.status} - ${c.statusText}`);let l=Yi(await c.json());return o.onProgress?.(new de("dns:response",l)),l},{signal:o.signal});if(a==null)throw new Error("No DNS response received");return a}}function mp(){return[pu("https://cloudflare-dns.com/dns-query"),pu("https://dns.google/resolve")]}var bp=fa(yp(),1);var mu=class{lru;constructor(e){this.lru=(0,bp.default)(e)}get(e,t){let n=!0,o=[];for(let s of t){let i=this.getAnswers(e,s);if(i.length===0){n=!1;break}o.push(...i)}if(n)return Yi({answers:o})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,o=this.lru.get(n);if(o!=null){let s=o.filter(i=>i.expires>Date.now()).map(({expires:i,value:a})=>({...a,TTL:Math.round((i-Date.now())/1e3),type:ze[a.type]}));return s.length===0&&this.lru.remove(n),s}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(t.TTL??hu)*1e3,value:t}),this.lru.set(n,o)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function wp(r){return new mu(r)}var Tb=1e3,Xi=class{resolvers;cache;logger;constructor(e){this.resolvers={},this.cache=wp(e.cacheSize??Tb),this.logger=e.logger,Object.entries(e.resolvers??{}).forEach(([t,n])=>{Array.isArray(n)||(n=[n]),t.endsWith(".")||(t=`${t}.`),this.resolvers[t]=n}),this.resolvers["."]==null&&(this.resolvers["."]=mp())}async query(e,t={}){let n=Gi(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new de("dns:cache",o)),o;let s=`${e.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of i){if(t.signal?.aborted===!0)break;try{let l=await c(e,{...t,logger:this.logger,types:n});for(let u of l.Answer)this.cache.add(e,u);return l}catch(l){a.push(l),t.onProgress?.(new de("dns:error",l))}}throw new Hi(a,`DNS lookup of ${e} ${n} failed`)}};var ze;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(ze||(ze={}));function xp(r={}){return new Xi(r)}var gu=class{dns;canResolve(e){return e.getComponents().some(({name:t})=>t==="dnsaddr")}async resolve(e,t){let n=e.getComponents().find(c=>c.name==="dnsaddr")?.value;if(n==null)return[e];let s=await this.getDNS(t).query(`_dnsaddr.${n}`,{signal:t?.signal,types:[ze.TXT]}),i=e.getComponents().find(c=>c.name==="p2p")?.value,a=[];for(let c of s.Answer){let l=c.data.replace(/["']/g,"").trim().split("=")[1];l!=null&&(i!=null&&!l.includes(i)||a.push(X(l)))}return a}getDNS(e){return e.dns!=null?e.dns:(this.dns==null&&(this.dns=xp()),this.dns)}},Ar=new gu;async function yu(r,e,t){let n=t.depth??0;if(n>(t.maxRecursiveDepth??32))throw new Ki("Max recursive depth reached");let o=!1,s=[];for(let i of Object.values(e))if(i.canResolve(r)){o=!0;let a=await i.resolve(r,t);for(let c of a)s.push(...await yu(c,e,{...t,depth:n+1}))}return o===!1&&s.push(r),s}var Po={maxParallelDials:zi,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,resolvers:{dnsaddr:Ar}},ji=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;resolvers;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??Po.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??Po.maxDialQueueLength,this.dialTimeout=t.dialTimeout??Po.dialTimeout,this.connections=t.connections??new Ye,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.resolvers=t.resolvers??Po.resolvers,this.shutDownController=new AbortController,this.shutDownController.signal,this.queue=new Ws({concurrency:t.maxParallelDials??Po.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("failure",n=>{n.detail?.error.name!==Xe.name&&this.log.error("error in dial queue - %e",n.detail.error)})}start(){this.shutDownController=new AbortController,this.shutDownController.signal}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:o}=qi(e);if(n!=null&&t.force!==!0){let i=$i(n,this.connections.get(n),o);if(i!=null)return this.log("already connected to %a",i.remoteAddr),t.onProgress?.(new de("dial-queue:already-connected")),i}let s=this.queue.queue.find(i=>{if(n?.equals(i.options.peerId)===!0)return!0;let a=i.options.multiaddrs;if(a==null)return!1;for(let c of o)if(a.has(c.toString()))return!0;return!1});if(s!=null){this.log("joining existing dial target for %p",n);for(let i of o)s.options.multiaddrs.add(i.toString());return t.onProgress?.(new de("dial-queue:already-in-dial-queue")),s.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new Tr("Dial queue is full");return this.log("creating dial target for %p",n,o.map(i=>i.toString())),t.onProgress?.(new de("dial-queue:add-to-dial-queue")),this.queue.add(async i=>{i.onProgress?.(new de("dial-queue:start-dial"));let a=_t([this.shutDownController.signal,i.signal]);try{return await this.dialPeer(i,a)}finally{a.clear()}},{peerId:n,priority:t.priority??Eu,multiaddrs:new Set(o.map(i=>i.toString())),signal:t.signal??AbortSignal.timeout(this.dialTimeout),onProgress:t.onProgress})}async dialPeer(e,t){let n=e.peerId,o=e.multiaddrs,s=new Set,i=e.multiaddrs.size===0,a=0,c=0,l=[];for(this.log("starting dial to %p",n);i||o.size>0;){c++,i=!1;let u=[],f=new Set(e.multiaddrs);o.clear(),this.log("calculating addrs to dial %p from %s",n,[...f]);let d=await this.calculateMultiaddrs(n,f,{...e,signal:t});for(let h of d){if(s.has(h.multiaddr.toString())){this.log.trace("skipping previously failed multiaddr %a while dialing %p",h.multiaddr,n);continue}u.push(h)}this.log("%s dial to %p with %s",c===1?"starting":"continuing",n,u.map(h=>h.multiaddr.toString())),e?.onProgress?.(new de("dial-queue:calculated-addresses",u));for(let h of u){if(a===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",a,e.peerId),new Tr("Peer had more than maxPeerAddrsToDial");a++;try{let p=await this.components.transportManager.dial(h.multiaddr,{...e,signal:t});this.log("dial to %a succeeded",h.multiaddr);try{await this.components.peerStore.merge(p.remotePeer,{multiaddrs:[p.remoteAddr],metadata:{[up]:L(Date.now().toString())}})}catch(y){this.log.error("could not update last dial failure key for %p - %e",n,y)}return p}catch(p){if(this.log.error("dial failed to %a - %e",h.multiaddr,p),s.add(h.multiaddr.toString()),n!=null)try{await this.components.peerStore.merge(n,{metadata:{[lp]:L(Date.now().toString())}})}catch(y){this.log.error("could not update last dial failure key for %p - %e",n,y)}if(t.aborted)throw new Uo(p.message);l.push(p)}}}throw l.length===1?l[0]:new AggregateError(l,"All multiaddr dials failed")}async calculateMultiaddrs(e,t=new Set,n={}){let o=[...t].map(f=>({multiaddr:X(f),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new Tr("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new Ao("The dial request is blocked by gater.allowDialPeer");if(o.length===0){this.log("loading multiaddrs for %p",e);try{let f=await this.components.peerStore.get(e);o.push(...f.addresses),this.log("loaded multiaddrs for %p",e,o.map(({multiaddr:d})=>d.toString()))}catch(f){if(f.name!=="NotFoundError")throw f}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let f=await this.components.peerRouting.findPeer(e,n);this.log("found multiaddrs for %p in the peer routing",e,o.map(({multiaddr:d})=>d.toString())),o.push(...f.multiaddrs.map(d=>({multiaddr:d,isCertified:!1})))}catch(f){f.name==="NoPeerRoutersError"?this.log("no peer routers configured",e):this.log.error("looking up multiaddrs for %p in the peer routing failed - %e",e,f)}}}let s=(await Promise.all(o.map(async f=>{let d=await yu(f.multiaddr,this.resolvers,{dns:this.components.dns,log:this.log,...n});return d.length===1&&d[0].equals(f.multiaddr)?f:d.map(h=>({multiaddr:h,isCertified:!1}))}))).flat();if(e!=null){let f=`/p2p/${e.toString()}`;s=s.map(d=>d.multiaddr.getComponents().pop()?.name!=="p2p"?{multiaddr:d.multiaddr.encapsulate(f),isCertified:d.isCertified}:d)}let i=s.filter(f=>{if(this.components.transportManager.dialTransportForMultiaddr(f.multiaddr)==null)return!1;let d=f.multiaddr.getComponents().findLast(h=>h.code===421)?.value;return e!=null&&d!=null?e.equals(d):!0}),a=new Map;for(let f of i){let d=f.multiaddr.toString(),h=a.get(d);if(h!=null){h.isCertified=h.isCertified||f.isCertified||!1;continue}a.set(d,f)}let c=[...a.values()];if(c.length===0)throw new Mi("The dial request has no valid addresses");let l=[];for(let f of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(f.multiaddr)||l.push(f);let u=this.addressSorter==null?dp(l):l.sort(this.addressSorter);if(u.length===0)throw new Ao("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",e??"unknown peer",s.map(({multiaddr:f})=>f.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",u.map(({multiaddr:f})=>f.toString())),u}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let n=await this.calculateMultiaddrs(void 0,new Set(e.map(o=>o.toString())),t);return t.runOnLimitedConnection===!1?n.find(o=>!Sr.matches(o.multiaddr))!=null:!0}catch{}return!1}};var Lb=Object.prototype.toString,Pb=r=>Lb.call(r)==="[object Error]",Db=new Set(["network error","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function vu(r){if(!(r&&Pb(r)&&r.name==="TypeError"&&typeof r.message=="string"))return!1;let{message:t,stack:n}=r;return t==="Load failed"?n===void 0||"__sentry_captured__"in r:t.startsWith("error sending request for url")||t==="Failed to fetch"||t.startsWith("Failed to fetch (")&&t.endsWith(")")?!0:Db.has(t)}function kb(r){if(typeof r=="number"){if(r<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(r))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(r!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function Zi(r,e,{min:t=0,allowInfinity:n=!1}={}){if(e!==void 0){if(typeof e!="number"||Number.isNaN(e))throw new TypeError(`Expected \`${r}\` to be a number${n?" or Infinity":""}.`);if(!n&&!Number.isFinite(e))throw new TypeError(`Expected \`${r}\` to be a finite number.`);if(e<t)throw new TypeError(`Expected \`${r}\` to be \u2265 ${t}.`)}}var Su=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}};function Rb(r,e){let t=Math.max(1,r+1),n=e.randomize?Math.random()+1:1,o=Math.round(n*e.minTimeout*e.factor**(t-1));return o=Math.min(o,e.maxTimeout),o}function Ep(r,e){return Number.isFinite(e)?e-(performance.now()-r):e}async function Ob({error:r,attemptNumber:e,retriesConsumed:t,startTime:n,options:o}){let s=r instanceof Error?r:new TypeError(`Non-error was thrown: "${r}". You should only throw errors.`);if(s instanceof Su)throw s.originalError;let i=Number.isFinite(o.retries)?Math.max(0,o.retries-t):o.retries,a=o.maxRetryTime??Number.POSITIVE_INFINITY,c=Object.freeze({error:s,attemptNumber:e,retriesLeft:i,retriesConsumed:t});if(await o.onFailedAttempt(c),Ep(n,a)<=0)throw s;let l=await o.shouldConsumeRetry(c),u=Ep(n,a);if(u<=0||i<=0)throw s;if(s instanceof TypeError&&!vu(s)){if(l)throw s;return o.signal?.throwIfAborted(),!1}if(!await o.shouldRetry(c))throw s;if(!l)return o.signal?.throwIfAborted(),!1;let f=Rb(t,o),d=Math.min(f,u);return o.signal?.throwIfAborted(),d>0&&await new Promise((h,p)=>{let y=()=>{clearTimeout(m),o.signal?.removeEventListener("abort",y),p(o.signal.reason)},m=setTimeout(()=>{o.signal?.removeEventListener("abort",y),h()},d);o.unref&&m.unref?.(),o.signal?.addEventListener("abort",y,{once:!0})}),o.signal?.throwIfAborted(),!0}async function _u(r,e={}){if(e={...e},kb(e.retries),Object.hasOwn(e,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");e.retries??=10,e.factor??=2,e.minTimeout??=1e3,e.maxTimeout??=Number.POSITIVE_INFINITY,e.maxRetryTime??=Number.POSITIVE_INFINITY,e.randomize??=!1,e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,e.shouldConsumeRetry??=()=>!0,Zi("factor",e.factor,{min:0,allowInfinity:!1}),Zi("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),Zi("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),Zi("maxRetryTime",e.maxRetryTime,{min:0,allowInfinity:!0}),e.factor>0||(e.factor=1),e.signal?.throwIfAborted();let t=0,n=0,o=performance.now();for(;!Number.isFinite(e.retries)||n<=e.retries;){t++;try{e.signal?.throwIfAborted();let s=await r(t);return e.signal?.throwIfAborted(),s}catch(s){await Ob({error:s,attemptNumber:t,retriesConsumed:n,startTime:o,options:e})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}var Qi=class{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;events;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.queue=new Hs({concurrency:t.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:e.metrics}),this.started=!1,this.retries=t.retries??5,this.backoffFactor=t.backoffFactor,this.retryInterval=t.retryInterval,this.events=e.events,e.events.addEventListener("peer:disconnect",n=>{this.maybeReconnect(n.detail).catch(o=>{this.log.error("failed to maybe reconnect to %p - %e",n.detail,o)})})}async maybeReconnect(e){if(!this.started)return;let t=await this.peerStore.get(e);vp(t)&&(this.queue.has(e)||this.queue.add(async n=>{await _u(async o=>{if(this.started)try{await this.connectionManager.openConnection(e,{signal:n?.signal})}catch(s){throw this.log("reconnecting to %p attempt %d of %d failed - %e",e,o,this.retries,s),s}},{signal:n?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:e}).catch(async n=>{this.log.error("failed to reconnect to %p - %e",e,n);let o={};[...t.tags.keys()].forEach(s=>{s.startsWith(ma)&&(o[s]=void 0)}),await this.peerStore.merge(e,{tags:o}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:e})}).catch(async n=>{this.log.error("failed to remove keep-alive tag from %p - %e",e,n)}))}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>vp(t)]});await Promise.all(e.map(async t=>{await this.connectionManager.openConnection(t.id).catch(n=>{this.log.error("could not open connection to keepalive peer - %e",n)})}))}).catch(e=>{this.log.error("error reconnect to peers after start - %e",e)})}stop(){this.started=!1,this.queue.abort()}};function vp(r){for(let e of r.tags.keys())if(e.startsWith(ma))return!0;return!1}var Eu=50,Au={maxConnections:fp,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},Ji=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;outboundPendingConnections;maxConnections;dialQueue;reconnectQueue;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;peerId;constructor(e,t={}){if(this.maxConnections=t.maxConnections??Au.maxConnections,this.maxConnections<1)throw new I("Connection Manager maxConnections must be greater than 0");this.connections=new Ye,this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.allow=(t.allow??[]).map(n=>Co(X(n))),this.deny=(t.deny??[]).map(n=>Co(X(n))),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??Au.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new Gs({points:t.inboundConnectionThreshold??Au.inboundConnectionThreshold,duration:1}),this.connectionPruner=new Vi({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{allow:t.allow?.map(n=>X(n))}),this.dialQueue=new ji(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??zi,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??1e4,resolvers:t.resolvers??{dnsaddr:Ar},connections:this.connections}),this.reconnectQueue=new Qi({events:e.events,peerStore:e.peerStore,logger:e.logger,connectionManager:this},{retries:t.reconnectRetries,retryInterval:t.reconnectRetryInterval,backoffFactor:t.reconnectBackoffFactor,maxParallelReconnects:t.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0,"outbound pending":this.outboundPendingConnections};for(let t of this.connections.values())for(let n of t)e[n.direction]++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let t of this.connections.values())for(let n of t)for(let o of n.streams){let s=`${o.direction} ${o.protocol??"unnegotiated"}`;e[s]=(e[s]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let e={};for(let n of this.connections.values())for(let o of n){let s={};for(let i of o.streams){let a=`${i.direction} ${i.protocol??"unnegotiated"}`;s[a]=(s[a]??0)+1}for(let[i,a]of Object.entries(s))e[i]=e[i]??[],e[i].push(a)}let t={};for(let[n,o]of Object.entries(e)){o=o.sort((i,a)=>i-a);let s=Math.floor(o.length*.9);t[n]=o[s]}return t}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await Nu(this.dialQueue,this.reconnectQueue,this.connectionPruner),this.started=!0,this.log("started")}async stop(){this.events.removeEventListener("connection:open",this.onConnect),this.events.removeEventListener("connection:close",this.onDisconnect),await Mu(this.reconnectQueue,this.dialQueue,this.connectionPruner);let e=[];for(let t of this.connections.values())for(let n of t)e.push(Promise.all([ot(n,"close",{signal:AbortSignal.timeout(500)}),n.close({signal:AbortSignal.timeout(500)})]).catch(o=>{n.abort(o)}));this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}getMaxConnections(){return this.maxConnections}setMaxConnections(e){if(e<1)throw new I("Connection Manager maxConnections must be greater than 0");let t=!1;e<this.maxConnections&&(t=!0),this.maxConnections=e,t&&this.connectionPruner.maybePruneConnections()}onConnect(e){this._onConnect(e).catch(t=>{this.log.error("could not connect - %e",t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}if(t.status!=="open")return;let n=t.remotePeer,o=!this.connections.has(n),s=this.connections.get(n)??[];s.push(t),this.connections.set(n,s),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),o&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e,n=t.remotePeer,s=(this.connections.get(n)??[]).filter(i=>i.id!==t.id);this.connections.set(n,s),s.length===0&&(this.log.trace("peer %p disconnected, removing connection map entry",n),this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:n}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let t=[];for(let n of this.connections.values())t=t.concat(n);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.started)throw new dt("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted();let{peerId:n,multiaddrs:o}=qi(e);if(this.peerId.equals(n))throw new Ir("Can not dial self");if(n!=null&&t.force!==!0){this.log("dial %p",n);let c=$i(n,this.getConnections(n),o);if(c!=null)return this.log("had an existing connection to %p as %a",n,c.remoteAddr),t.onProgress?.(new de("dial-queue:already-connected")),c}let s=await this.dialQueue.dial(e,{...t,priority:t.priority??Eu});if(s.status!=="open")throw new Wt("Remote closed connection during opening");let i=this.connections.get(s.remotePeer);i==null&&(i=[],this.connections.set(s.remotePeer,i));let a=!1;for(let c of i)if(c.id===s.id&&(a=!0),t.force!==!0&&c.id!==s.id&&c.remoteAddr.equals(s.remoteAddr))return s.abort(new Lt("Duplicate multiaddr connection")),c;return a||i.push(s),s}finally{this.outboundPendingConnections--}}async openStream(e,t,n={}){return(await this.openConnection(e,n)).newStream(t,n)}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async o=>{try{await Promise.all([ot(o,"close",t),o.close(t)])}catch(s){o.abort(s)}}))}acceptIncomingConnection(e){if(this.deny.some(o=>{if(xe(e.remoteAddr)){let s=H(e.remoteAddr);return o.contains(s.host)}return!1}))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(o=>{if(xe(e.remoteAddr)){let s=H(e.remoteAddr);return o.contains(s.host)}return!0}))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(xe(e.remoteAddr)){let o=H(e.remoteAddr);try{this.inboundConnectionRateLimiter.consume(o.host,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,o.host),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){let e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map(n=>X(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};var Bb=1e4,Fb="1.0.0",Ub="ping",Kb="ipfs",Sp=32,qb=!0,ea=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??Kb}/${Ub}/${Fb}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??Bb,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??qb,this.timeout=new Ls({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[xn]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,this.abortController.signal,this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(e=>{Promise.resolve().then(async()=>{let t=Date.now(),n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal});try{let o=await e.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0}),s=kl(o);t=Date.now(),await Promise.all([s.write(zr(Sp),{signal:n}),s.read({bytes:Sp,signal:n})]),e.rtt=Date.now()-t,await o.close({signal:n})}catch(o){if(o.name!=="UnsupportedProtocolError")throw o;e.rtt=(Date.now()-t)/2}finally{this.timeout.cleanUp(n)}}).catch(t=>{this.log.error("error during heartbeat - %e",t),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),e.abort(t)):this.log("connection ping failed, but not aborting due to abortConnectionOnPingFailure flag")})})},this.pingIntervalMs)}stop(){this.abortController?.abort(),this.heartbeatInterval!=null&&clearInterval(this.heartbeatInterval)}};var ta=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e,this.findProviders=e.metrics?.traceFunction("libp2p.contentRouting.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()}),getAttributesFromYieldedValue:(n,o)=>({...o,providers:[...Array.isArray(o.providers)?o.providers:[],n.id.toString()]})})??this.findProviders,this.provide=e.metrics?.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.cancelReprovide,this.put=e.metrics?.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:([n])=>({key:U(n,"base36")})})??this.put,this.get=e.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([n])=>({key:U(n,"base36")})})??this.get}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(this.routers.length===0)throw new pn("No content routers available");let n=this,o=new ar;for await(let s of un(...n.routers.filter(i=>i.findProviders instanceof Function).map(i=>i.findProviders(e,t))))s!=null&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),!o.has(s.id)&&(o.add(s.id),yield s))}async provide(e,t={}){if(this.routers.length===0)throw new pn("No content routers available");await Promise.all(this.routers.filter(n=>n.provide instanceof Function).map(async n=>{await n.provide(e,t)}))}async cancelReprovide(e,t={}){if(this.routers.length===0)throw new pn("No content routers available");await Promise.all(this.routers.filter(n=>n.cancelReprovide instanceof Function).map(async n=>{await n.cancelReprovide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new dt;await Promise.all(this.routers.filter(o=>o.put instanceof Function).map(async o=>{await o.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new dt;return Promise.any(this.routers.filter(n=>n.get instanceof Function).map(async n=>n.get(e,t)))}};var ra=globalThis.CustomEvent??Event;async function*Cu(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered??!1,o=new EventTarget,s=[],i=ge(),a=ge(),c=!1,l,u=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of r){if(s.length===t&&(i=ge(),await i.promise),u)break;let y={done:!1};s.push(y),p().then(m=>{y.done=!0,y.ok=!0,y.value=m,o.dispatchEvent(new ra("task-complete"))},m=>{y.done=!0,y.err=m,o.dispatchEvent(new ra("task-complete"))})}c=!0,o.dispatchEvent(new ra("task-complete"))}catch(p){l=p,o.dispatchEvent(new ra("task-complete"))}});function f(){return n?s[0]?.done:!!s.find(p=>p.done)}function*d(){for(;s.length>0&&s[0].done;){let p=s[0];if(s.shift(),p.ok)yield p.value;else throw u=!0,i.resolve(),p.err;i.resolve()}}function*h(){for(;f();)for(let p=0;p<s.length;p++)if(s[p].done){let y=s[p];if(s.splice(p,1),p--,y.ok)yield y.value;else throw u=!0,i.resolve(),y.err;i.resolve()}}for(;;){if(f()||(a=ge(),await a.promise),l!=null||(n?yield*d():yield*h(),l!=null))throw l;if(c&&s.length===0)break}}var na=class{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[],this.findPeer=e.metrics?.traceFunction("libp2p.peerRouting.findPeer",this.findPeer.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,peer:n.toString()})})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,key:U(n,"base36")}),getAttributesFromYieldedValue:(n,o)=>({...o,peers:[...Array.isArray(o.peers)?o.peers:[],n.id.toString()]})})??this.getClosestPeers}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(this.routers.length===0)throw new _o("No peer routers available");if(e.toString()===this.peerId.toString())throw new Di("Should not try to find self");let n=this,o=un(...this.routers.filter(s=>s.findPeer instanceof Function).map(s=>(async function*(){try{yield await s.findPeer(e,t)}catch(i){n.log.error("router failed to find peer - %e",i)}})()));for await(let s of o)if(s!=null)return s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),s;throw new Gt}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new _o("No peer routers available");let n=this,o=oo(1024);for await(let s of Cu((async function*(){let i=un(...n.routers.filter(a=>a.getClosestPeers instanceof Function).map(a=>a.getClosestPeers(e,t)));for await(let a of i)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.findPeer(a.id,{...t,useCache:!1})}catch(c){n.log.error("could not find peer multiaddrs - %e",c);return}return a}})()))s!=null&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),!o.has(s.id.toMultihash().bytes)&&(o.add(s.id.toMultihash().bytes),yield s))}};var oa=class extends Le{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,this.shutdownController.signal}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,this.shutdownController.signal}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=_t([this.shutdownController.signal,e?.signal]);try{for(;;)this.needNext?.resolve(),this.needNext=ge(),yield(await ot(this,"walk:peer",{signal:t,rejectionEvents:["walk:error"]})).detail}catch(n){throw n.detail!=null?n.detail:n}finally{t.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,this.walkController.signal;let e=_t([this.walkController.signal,this.shutdownController.signal]);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let o=zr(32),s=Date.now();for await(let i of this.peerRouting.getClosestPeers(o,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",i.id,Date.now()-s,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:i}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await $e(this.needNext.promise,e)),s=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",o,this.walkers,n)}catch(o){this.log.error("random walk errored - %e",o),this.safeDispatchEvent("walk:error",{detail:o})}this.log("no walkers left, ended walk")}).catch(o=>{this.log.error("random walk errored - %e",o)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}};var Iu=32,Tu=64,sa=class{log;topologies;handlers;components;middleware;constructor(e){this.components=e,this.log=e.logger.forComponent("libp2p:registrar"),this.middleware=new Map,this.topologies=new Map,e.metrics?.registerMetricGroup("libp2p_registrar_topologies",{calculate:()=>{let t={};for(let[n,o]of this.topologies)t[n]=o.size;return t}}),this.handlers=Ce({name:"libp2p_registrar_protocol_handlers",metrics:e.metrics}),this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new ki(`No handler registered for protocol ${e}`);return t}getTopologies(e){let t=this.topologies.get(e);return t==null?[]:[...t.values()]}async handle(e,t,n){if(this.handlers.has(e)&&n?.force!==!0)throw new Ri(`Handler already registered for protocol ${e}`);this.handlers.set(e,{handler:t,options:{maxInboundStreams:Iu,maxOutboundStreams:Tu,...n}}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]},n)}async unhandle(e,t){(Array.isArray(e)?e:[e]).forEach(o=>{this.handlers.delete(o)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()},t)}async register(e,t){if(t==null)throw new I("invalid topology");let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,o=this.topologies.get(e);return o==null&&(o=new Map,this.topologies.set(e,o)),o.set(n,t),n}unregister(e){for(let[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(t))}use(e,t){this.middleware.set(e,t)}unuse(e){this.middleware.delete(e)}getMiddleware(e){return this.middleware.get(e)??[]}async _onDisconnect(e){let t=e.detail,n={signal:AbortSignal.timeout(5e3)};try{let o=await this.components.peerStore.get(t,n);for(let s of o.protocols){let i=this.topologies.get(s);i!=null&&await Promise.all([...i.values()].map(async a=>{a.filter!=null&&a.filter.has(t)!==!0||(a.filter?.remove(t),await a.onDisconnect?.(t))}))}}catch(o){if(o.name==="NotFoundError")return;this.log.error("could not inform topologies of disconnecting peer %p - %e",t,o)}}async _onPeerUpdate(e){let{peer:t,previous:n}=e.detail,o=(n?.protocols??[]).filter(s=>!t.protocols.includes(s));try{for(let s of o){let i=this.topologies.get(s);i!=null&&await Promise.all([...i.values()].map(async a=>{a.filter!=null&&a.filter.has(t.id)!==!0||(a.filter?.remove(t.id),await a.onDisconnect?.(t.id))}))}}catch(s){this.log.error("could not inform topologies of updated peer %p - %e",t.id,s)}}async _onPeerIdentify(e){let t=e.detail.protocols,n=e.detail.connection,o=e.detail.peerId;try{for(let s of t){let i=this.topologies.get(s);i!=null&&await Promise.all([...i.values()].map(async a=>{n.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(o)!==!0&&(a.filter?.add(o),await a.onConnect?.(o,n))}))}}catch(s){this.log.error("could not inform topologies of updated peer after identify %p - %e",o,s)}}};var ia=class{log;components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=Ce({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=Ce({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??wn.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new I("Transport must have a valid tag");if(this.transports.has(t))throw new I(`There is already a transport with the tag ${t}`);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){let e=[];for(let[t,n]of this.listeners)for(this.log("closing listeners for %s",t);n.length>0;){let o=n.pop();o!=null&&e.push(o.close())}await Promise.all(e),this.log("all listeners closed");for(let t of this.listeners.keys())this.listeners.set(t,[]);this.started=!1}async dial(e,t){let n=this.dialTransportForMultiaddr(e);if(n==null)throw new Ui(`No transport available for address ${String(e)}`);return t?.onProgress?.(new de("transport-manager:selected-transport",n[Symbol.toStringTag])),n.dial(e,{...t,upgrader:this.components.upgrader})}getAddrs(){let e=[];for(let t of this.listeners.values())for(let n of t)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(let t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(let t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new dt("Not started");if(e==null||e.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let t={errors:new Map,ipv4:{success:0,attempts:0},ipv6:{success:0,attempts:0}};e.forEach(s=>{t.errors.set(s.toString(),new Oi)});let n=[];for(let[s,i]of this.transports.entries()){let a=i.listenFilter(e);for(let c of a){this.log("creating listener for %s on %a",s,c);let l=i.createListener({upgrader:this.components.upgrader}),u=this.listeners.get(s)??[];u==null&&(u=[],this.listeners.set(s,u)),u.push(l),l.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:l})}),l.addEventListener("close",()=>{let f=u.findIndex(d=>d===l);u.splice(f,1),this.components.events.safeDispatchEvent("transport:close",{detail:l})}),eu.matches(c)?t.ipv4.attempts++:tu.matches(c)&&t.ipv6.attempts++,n.push(l.listen(c).then(()=>{t.errors.delete(c.toString()),eu.matches(c)&&t.ipv4.success++,tu.matches(c)&&t.ipv6.success++},f=>{throw this.log.error("transport %s could not listen on address %a - %e",s,c,f),t.errors.set(c.toString(),f),f}))}}let o=await Promise.allSettled(n);if(!(o.length>0&&o.every(s=>s.status==="fulfilled"))){if(this.ipv6Unsupported(t)){this.log("all IPv4 addresses succeed but all IPv6 failed");return}if(this.faultTolerance===wn.NO_FATAL){this.log("failed to listen on any address but fault tolerance allows this");return}throw new Ni(`Some configured addresses failed to be listened on, you may need to remove one or more listen addresses from your configuration or set \`transportManager.faultTolerance\` to NO_FATAL:
|
|
12
|
+
${e}[Error list was empty]`,t.trim()}return ih(r,e)}Ke.formatters.e=r=>r==null?"undefined":ch(r);function $0(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function Ss(r){return{forComponent(e){return lh(e,r)}}}function lh(r,e){let t=$0(`${r}:trace`);return Ke.enabled(`${r}:trace`)&&Ke.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=Ke(`${r}:trace`,e)),Object.assign(Ke(r,e),{error:Ke(`${r}:error`,e),trace:t,newScope:n=>lh(`${r}:${n}`,e)})}function ah(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}function lr(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}function _s(r){let e=mt(ee.decode(`z${r}`));return Xr(e)}var Ye=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),{key:t,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return lr(this.map.entries(),e=>[e[1].key,e[1].value])}forEach(e){this.map.forEach((t,n)=>{e(t.value,t.key,this)})}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),{key:e,value:t})}keys(){return lr(this.map.values(),e=>e.key)}values(){return lr(this.map.values(),e=>e.value)}get size(){return this.map.size}};var ur=class r{set;constructor(e){if(this.set=new Set,e!=null)for(let t of e)this.set.add(t.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return lr(this.set.entries(),e=>{let t=_s(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=_s(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return lr(this.set.values(),e=>_s(e))}intersection(e){let t=new r;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new r;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new r;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};var il={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},uh={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},fh=new globalThis.TextEncoder;function V0(r,e){let t=il[e],n=uh[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function z0(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=il[e],o=uh[e],s=r;for(;s.length>0;){let i=fh.encodeInto(s,t);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(t[a]),o=BigInt.asUintN(e,o*n)}return o}function al(r,{size:e=32,utf8Buffer:t}={}){if(!il[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(t)return z0(r,e,t);r=fh.encode(r)}return V0(r,e)}var uo={hash:r=>Number(al(r,{size:32})),hashV:(r,e)=>H0(uo.hash(r,e))};function H0(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),L(e,"base16")}var cl=64,rt=class{fp;h;seed;constructor(e,t,n,o=2){if(o>cl)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),i=ue(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?Z(this.fp,e.fp):!1}};function fr(r,e){return Math.floor(Math.random()*(e-r))+r}var dr=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof rt))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof rt))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(this.contents[t]==null)return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof rt))throw new TypeError("Invalid Fingerprint");let t=fr(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof rt))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var W0=500,fo=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??uo,this.seed=e.seed??fr(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=L(e));let t=new rt(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new dr(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new dr(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let s=[n,o],i=s[fr(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new dr(this.bucketSize));for(let a=0;a<W0;a++){let c=this.buckets[i].swap(t);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new dr(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=L(e));let t=new rt(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let s=(n^t.hash())%this.filterSize;return this.buckets[s]?.has(t)??!1}remove(e){typeof e=="string"&&(e=L(e));let t=new rt(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let s=(n^t.hash())%this.filterSize,i=this.buckets[s]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},G0={1:.5,2:.84,4:.95,8:.98};function Y0(r=.001){return r>.002?2:r>1e-5?4:8}function dh(r,e=.001){let t=Y0(e),n=G0[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),cl);return{filterSize:o,bucketSize:t,fingerprintSize:s}}var As=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??uo,this.seed=e.seed??fr(0,Math.pow(2,10)),this.filterSeries=[new fo({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=L(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new fo({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=L(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=L(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function ho(r,e=.001,t){return new As({...dh(r,e),...t??{}})}function W(r){let e=r.getComponents(),t={},n=0;if(e[n]?.name==="ip6zone"&&(t.zone=`${e[n].value}`,n++),e[n].name==="ip4"||e[n].name==="ip6"||e[n].name==="dns"||e[n].name==="dns4"||e[n].name==="dns6"?(t.type=e[n].name,t.host=e[n].value,n++):e[n].name==="dnsaddr"&&(t.type=e[n].name,t.host=`_dnsaddr.${e[n].value}`,n++),(e[n]?.name==="tcp"||e[n]?.name==="udp")&&(t.protocol=e[n].name==="tcp"?"tcp":"udp",t.port=parseInt(`${e[n].value}`),n++),e[n]?.name==="ipcidr"&&(t.type==="ip4"?t.cidr=parseInt(`${e[n].value}`):t.type==="ip6"&&(t.cidr=`${e[n].value}`),n++),t.type==null||t.host==null)throw new C(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e[n]?.name==="tls"&&e[n+1]?.name==="sni"&&(t.sni=e[n+1].value,n+=2),t}var Is=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*o)-1;for(;;){let l=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let d=Number.parseInt(f,e);if(!Number.isNaN(d))return d});if(l===void 0)break;if(s*=e,s+=l,s>u||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var hh=45,j0=15,Zr=new Is;function Cs(r){if(!(r.length>j0))return Zr.new(r).parseWith(()=>Zr.readIPv4Addr())}function Ts(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>hh))return Zr.new(r).parseWith(()=>Zr.readIPv6Addr())}function Qr(r,e=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>hh)return;let t=Zr.new(r).parseWith(()=>Zr.readIPAddr());if(t)return e&&t.length===4?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,t[0],t[1],t[2],t[3]]):t}function ph(r,e,t){let n=0;for(let o of r)if(!(n<e)){if(n>t)break;if(o!==255)return!1;n++}return!0}function mh(r,e,t,n){let o=0;for(let s of r)if(!(o<t)){if(o>n)break;if(s!==e[o])return!1;o++}return!0}function ll(r){switch(r.length){case hr:return r.join(".");case pr:{let e=[];for(let t=0;t<r.length;t++)t%2===0&&e.push(r[t].toString(16).padStart(2,"0")+r[t+1].toString(16).padStart(2,"0"));return e.join(":")}default:throw new Error("Invalid ip length")}}function gh(r){let e=0;for(let[t,n]of r.entries()){if(n===255){e+=8;continue}for(;(n&128)!=0;)e++,n=n<<1;if((n&128)!=0)return-1;for(let o=t+1;o<r.length;o++)if(r[o]!=0)return-1;break}return e}function yh(r){let e="0x";for(let t of r)e+=(t>>4).toString(16)+(t&15).toString(16);return e}var hr=4,pr=16,DS=parseInt("0xFFFF",16),X0=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function po(r,e){e.length===pr&&r.length===hr&&ph(e,0,11)&&(e=e.slice(12)),e.length===hr&&r.length===pr&&mh(r,X0,0,11)&&(r=r.slice(12));let t=r.length;if(t!=e.length)throw new Error("Failed to mask ip");let n=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=r[o]&e[o];return n}function bh(r,e){if(typeof e=="string"&&(e=Qr(e)),e==null)throw new Error("Invalid ip");if(e.length!==r.network.length)return!1;for(let t=0;t<e.length;t++)if((r.network[t]&r.mask[t])!==(e[t]&r.mask[t]))return!1;return!0}function ul(r){let[e,t]=r.split("/");if(!e||!t)throw new Error("Failed to parse given CIDR: "+r);let n=hr,o=Cs(e);if(o==null&&(n=pr,o=Ts(e),o==null))throw new Error("Failed to parse given CIDR: "+r);let s=parseInt(t,10);if(Number.isNaN(s)||String(s).length!==t.length||s<0||s>n*8)throw new Error("Failed to parse given CIDR: "+r);let i=fl(s,8*n);return{network:po(o,i),mask:i}}function fl(r,e){if(e!==8*hr&&e!==8*pr)throw new Error("Invalid CIDR mask");if(r<0||r>e)throw new Error("Invalid CIDR mask");let t=e/8,n=new Uint8Array(t);for(let o=0;o<t;o++){if(r>=8){n[o]=255,r-=8;continue}n[o]=255-(255>>r),r=0}return n}var Jr=class{constructor(e,t){if(t==null)({network:this.network,mask:this.mask}=ul(e));else{let n=Qr(e);if(n==null)throw new Error("Failed to parse network");t=String(t);let o=parseInt(t,10);if(Number.isNaN(o)||String(o).length!==t.length||o<0||o>n.length*8){let s=Qr(t);if(s==null)throw new Error("Failed to parse mask");this.mask=s}else this.mask=fl(o,8*n.length);this.network=po(n,this.mask)}}contains(e){return bh({network:this.network,mask:this.mask},e)}toString(){let e=gh(this.mask),t=e!==-1?String(e):yh(this.mask);return ll(this.network)+"/"+t}};function wh(r){try{let e=W(r);switch(e.type){case"ip4":return e.host.startsWith("169.254.");case"ip6":return e.host.toLowerCase().startsWith("fe80");default:return!1}}catch{return!1}}function xh(r){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^::1$/.test(r)}function mo(r){try{let e=W(r);switch(e.type){case"ip4":case"ip6":return xh(e.host);default:return!1}}catch{return!1}}function xe(r){try{return W(r),!0}catch{return!1}}function nt(r){return!!Cs(r)}function Ls(r){return!!Ts(r)}var _h=wa(Sh(),1),ny=["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"],oy=ny.map(r=>new _h.Netmask(r));function bl(r){for(let e of oy)if(e.contains(r))return!0;return!1}function sy(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function iy(r){let e=r.split(":");if(e.length<2)return!1;let t=e[e.length-1].padStart(4,"0"),n=e[e.length-2].padStart(4,"0"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return bl(o)}function ay(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function cy(r){let e=r.split(":"),t=e[e.length-1];return bl(t)}function ly(r){return/^::$/.test(r)||/^::1$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^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(r)||/^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(r)||/^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(r)||/^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(r)||/^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(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}function nn(r){if(nt(r))return bl(r);if(sy(r))return iy(r);if(ay(r))return cy(r);if(Ls(r))return ly(r)}function _t(r){try{let e=W(r);switch(e.type){case"ip4":case"ip6":return nn(e.host)??!1;default:return e.host==="localhost"}}catch{return!1}}function ge(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Ds=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},on=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Ds(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new Ds(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var wl=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function sn(r={}){return uy(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function uy(r,e){e=e??{};let t=e.onEnd,n=new on,o,s,i,a=ge(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((g,m)=>{s=_=>{s=null,n.push(_);try{g(r(n))}catch(E){m(E)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=ge()})}},u=g=>s!=null?s(g):(n.push(g),o),l=g=>(n=new on,s!=null?s({error:g}):(n.push({error:g}),o)),f=g=>{if(i)return o;if(e?.objectMode!==!0&&g?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:g})},d=g=>i?o:(i=!0,g!=null?l(g):u({done:!0})),h=()=>(n=new on,d(),{done:!0}),p=g=>(d(g),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:p,push:f,end:d,get readableLength(){return n.size},onEmpty:async g=>{let m=g?.signal;if(m?.throwIfAborted(),n.isEmpty())return;let _,E;m!=null&&(_=new Promise((I,O)=>{E=()=>{O(new wl)},m.addEventListener("abort",E)}));try{await Promise.race([a.promise,_])}finally{E!=null&&m!=null&&m?.removeEventListener("abort",E)}}},t==null)return o;let y=o;return o={[Symbol.asyncIterator](){return this},next(){return y.next()},throw(g){return y.throw(g),t!=null&&(t(g),t=void 0),{done:!0}},return(){return y.return(),t!=null&&(t(),t=void 0),{done:!0}},push:f,end(g){return y.end(g),t!=null&&(t(g),t=void 0),o},get readableLength(){return y.readableLength},onEmpty:g=>y.onEmpty(g)},o}var xl=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},Ah=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function go(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e,a,c,l=new Promise((f,d)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(i?.aborted){d(Ah(i));return}if(i&&(c=()=>{d(Ah(i))},i.addEventListener("abort",c,{once:!0})),r.then(f,d),t===Number.POSITIVE_INFINITY)return;let h=new xl;a=s.setTimeout.call(void 0,()=>{if(n){try{f(n())}catch(p){d(p)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?f():o instanceof Error?d(o):(h.message=o??`Promise timed out after ${t} milliseconds`,d(h))},t)}).finally(()=>{l.clear(),c&&i&&i.removeEventListener("abort",c)});return l.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},l}var fy=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function dy(r,e,t){let n,o=new Promise((s,i)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:u,removeListener:l}=fy(r),f=async(...h)=>{let p=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(p))return}catch(y){n(),i(y);return}c.push(p),t.count===c.length&&(n(),s(c))},d=(...h)=>{n(),i(t.rejectionMultiArgs?h:h[0])};n=()=>{for(let h of a)l(h,f);for(let h of t.rejectionEvents)a.includes(h)||l(h,d)};for(let h of a)u(h,f);for(let h of t.rejectionEvents)a.includes(h)||u(h,d);t.signal&&t.signal.addEventListener("abort",()=>{d(t.signal.reason)},{once:!0}),t.resolveImmediately&&s(c)});if(o.cancel=n,typeof t.timeout=="number"){let s=go(o,{milliseconds:t.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function ot(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=dy(r,e,t),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function yo(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var ks=class extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(e="Rate limit exceeded",t){super(e),this.name="RateLimitError",this.remainingPoints=t.remainingPoints,this.msBeforeNext=t.msBeforeNext,this.consumedPoints=t.consumedPoints,this.isFirstInDuration=t.isFirstInDuration}},Rs=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}},gr=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"};function hy(r){return r.reason}async function $e(r,e,t){if(e==null)return r;let n=t?.translateError??hy;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let o;try{return await Promise.race([r,new Promise((s,i)=>{o=()=>{i(n(e))},e.addEventListener("abort",o)})])}finally{o!=null&&e.removeEventListener("abort",o)}}var Os=class{deferred;signal;onProgress;constructor(e){this.signal=e?.signal,this.onProgress=e?.onProgress,this.deferred=ge(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new je)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function py(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Ns=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=py(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new je),this.cleanup())}async join(e){let t=new Os(e);return this.recipients.push(t),e?.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await $e(this.fn({...this.options??{},signal:this.controller.signal,onProgress:t=>{this.recipients.forEach(n=>{n.onProgress?.(t)})}}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var an=class extends Le{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=yo(this.emitEmpty.bind(this),1),this.emitIdle=yo(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Rs;let n=new Ns(e,t);this.enqueue(n),this.safeDispatchEvent("add");let o=n.join(t).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s});return this.tryToStartAnother(),o}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new je)}),this.clear()}async onEmpty(e){this.size!==0&&await ot(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await ot(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await ot(this,"idle",e)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=sn({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new je("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};function At(r){let e=new globalThis.AbortController;function t(){let s=r.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();e.abort(s);for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}for(let s of r){if(s?.aborted===!0){t();break}s?.addEventListener!=null&&s.addEventListener("abort",t)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}var cn=class{movingAverage;variance;deviation;forecast;timeSpan;previousTime;constructor(e){this.timeSpan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timeSpan)}push(e,t=Date.now()){if(this.previousTime!=null){let n=this.alpha(t,this.previousTime),o=e-this.movingAverage,s=n*o;this.movingAverage=n*e+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+o*s),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*o}else this.movingAverage=e;this.previousTime=t}};var my=1.2,gy=2,yy=5e3,by=6e4,wy=5e3,Ms=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){let t=e.interval??wy;this.success=new cn(t),this.failure=new cn(t),this.next=new cn(t),this.failureMultiplier=e.failureMultiplier??gy,this.timeoutMultiplier=e.timeoutMultiplier??my,this.minTimeout=e.minTimeout??yy,this.maxTimeout=e.maxTimeout??by,e.metricName!=null&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){let t=Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier));t<this.minTimeout&&(t=this.minTimeout),t>this.maxTimeout&&(t=this.maxTimeout);let n=AbortSignal.timeout(t),o=At([e.signal,n]);return o.start=Date.now(),o.timeout=t,o}cleanUp(e){e.clear();let t=Date.now()-e.start;e.aborted?(this.failure.push(t),this.next.push(t*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:t})):(this.success.push(t),this.next.push(t),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:t}))}};var Ee=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},It=class extends Error{static name="ValidationError";name="ValidationError"},Bs=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Fs=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function vl(r){return e=>U(e,r)}function Sl(r){return e=>L(e,r)}function ln(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function yr(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function Ih(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=L(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=yr(n);return Ze([t,o],t.length+o.length)}function Ch(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=He.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=yr(n);return Ze([t,o],t.length+o.length)}function _l(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=U(e,"base32"),o=ln(t);return`${n}:${o}`}var Al=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let o=parseInt(t,10);if(isNaN(o)||o<0||o>255)throw new Ee("Invalid byte value in IP address");e[n]=o}),e},Th=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=nt(t[n]),i;s&&(i=Al(t[n]),t[n]=U(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,U(i.subarray(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let s=parseInt(t[n],16);if(isNaN(s)||s<0||s>65535)throw new Ee("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},Lh=function(r){if(r.byteLength!==4)throw new Ee("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},Ph=function(r){if(r.byteLength!==16)throw new Ee("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],s=r[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new Ee(`Invalid IPv6 address "${t}"`)}};function Dh(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Ee(`Invalid IPv6 address "${r}"`)}}var El=Object.values(Rn).map(r=>r.decoder),xy=(function(){let r=El[0].or(El[1]);return El.slice(2).forEach(e=>r=r.or(e)),r})();function kh(r){return xy.decode(r)}function Rh(r){return e=>r.encoder.encode(e)}function Ey(r){if(parseInt(r).toString()!==r)throw new It("Value must be an integer")}function vy(r){if(r<0)throw new It("Value must be a positive integer, or zero")}function Sy(r){return e=>{if(e>r)throw new It(`Value must be smaller than or equal to ${r}`)}}function _y(...r){return e=>{for(let t of r)t(e)}}var bo=_y(Ey,vy,Sy(65535));var ye=-1,Il=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(typeof e=="string"?t=this.protocolsByName.get(e):t=this.protocolsByCode.get(e),t==null)throw new Fs(`Protocol ${e} was unknown`);return t}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(t=>{this.protocolsByName.set(t,e)})}removeProtocol(e){let t=this.protocolsByCode.get(e);t!=null&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},Tt=new Il,Fy=[{code:4,name:"ip4",size:32,valueToBytes:Al,bytesToValue:Lh,validate:r=>{if(!nt(r))throw new It(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:yr,bytesToValue:ln,validate:bo},{code:273,name:"udp",size:16,valueToBytes:yr,bytesToValue:ln,validate:bo},{code:33,name:"dccp",size:16,valueToBytes:yr,bytesToValue:ln,validate:bo},{code:41,name:"ip6",size:128,valueToBytes:Th,bytesToValue:Ph,stringToValue:Dh,validate:r=>{if(!Ls(r))throw new It(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:ye},{code:43,name:"ipcidr",size:8,bytesToValue:vl("base10"),valueToBytes:Sl("base10")},{code:53,name:"dns",size:ye},{code:54,name:"dns4",size:ye},{code:55,name:"dns6",size:ye},{code:56,name:"dnsaddr",size:ye},{code:132,name:"sctp",size:16,valueToBytes:yr,bytesToValue:ln,validate:bo},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:ye,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:ye,bytesToValue:vl("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Sl("base58btc")(r):fe.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:_l,valueToBytes:Ih},{code:445,name:"onion3",size:296,bytesToValue:_l,valueToBytes:Ch},{code:446,name:"garlic64",size:ye},{code:447,name:"garlic32",size:ye},{code:448,name:"tls"},{code:449,name:"sni",size:ye},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:ye,bytesToValue:Rh(Ka),valueToBytes:kh},{code:480,name:"http"},{code:481,name:"http-path",size:ye,stringToValue:r=>`/${decodeURIComponent(r)}`,valueToString:r=>encodeURIComponent(r.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:ye}];Fy.forEach(r=>{Tt.addProtocol(r)});function Oh(r){let e=[],t=0;for(;t<r.length;){let n=sr(r,t),o=Tt.getProtocol(n),s=me(n),i=Uy(o,r,t+s),a=0;i>0&&o.size===ye&&(a=me(i));let c=s+a+i,u={code:n,name:o.name,bytes:r.subarray(t,t+c)};if(i>0){let l=t+s+a,f=r.subarray(l,l+i);u.value=o.bytesToValue?.(f)??U(f)}e.push(u),t+=c}return e}function Nh(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=Tt.getProtocol(n.code),s=me(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??L(n.value),a=i.byteLength,o.size===ye&&(c=me(a)));let u=new Uint8Array(s+c+a),l=0;Hr(n.code,u,l),l+=s,i!=null&&(o.size===ye&&(Hr(a,u,l),l+=c),u.set(i,l)),n.bytes=u}t.push(n.bytes),e+=n.bytes.byteLength}return Ze(t,e)}function Mh(r){if(r.charAt(0)!=="/")throw new Ee('String multiaddr must start with "/"');let e=[],t="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(t==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=Tt.getProtocol(o);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",t="protocol";continue}else if(a)throw new Ee(`Component ${o} was missing value`);t="value"}else if(t==="value"){let u={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new Ee(`Component ${o} was missing value`);u.value=c.stringToValue?.(n)??n}e.push(u),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new Ee("Incomplete multiaddr");return e}function Bh(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=Tt.getProtocol(e.code);if(t==null)throw new Ee(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function Uy(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:sr(e,t)}var Ky=Symbol.for("nodejs.util.inspect.custom"),Kl=Symbol.for("@multiformats/multiaddr");function qy(r){if(r==null&&(r="/"),Gt(r))return r.getComponents();if(r instanceof Uint8Array)return Oh(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),Mh(r);if(Array.isArray(r))return r;throw new Ee("Must be a string, Uint8Array, Component[], or another Multiaddr")}var zs=class r{[Kl]=!0;#e;#r;#n;constructor(e="/",t={}){this.#e=qy(e),t.validate!==!1&&$y(this)}get bytes(){return this.#n==null&&(this.#n=Nh(this.#e)),this.#n}toString(){return this.#r==null&&(this.#r=Bh(this.#e)),this.#r}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new Bs(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,o),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}equals(e){return Z(this.bytes,e.bytes)}[Ky](){return`Multiaddr(${this.toString()})`}};function $y(r){r.getComponents().forEach(e=>{let t=Tt.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function Gt(r){return!!r?.[Kl]}function X(r){return new zs(r)}var ql=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=ge(),this.haveNext=ge()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=ge(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=ge(),await $e(this.readNext.promise,t?.signal,t)}};function Fh(){return new ql}function Vy(r){return r[Symbol.asyncIterator]!=null}async function zy(r,e,t){try{await Promise.all(r.map(async n=>{for await(let o of n)await e.push(o,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*Hy(r){let e=new AbortController,t=Fh();zy(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*Wy(r){for(let e of r)yield*e}function Gy(...r){let e=[];for(let t of r)Vy(t)||e.push(t);return e.length===r.length?Wy(e):Hy(r)}var mn=Gy;var Yy=4194304,Hs=class extends Error{static name="UnwrappedError";name="UnwrappedError"},Vl=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},zl=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Hl=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function jy(r){return typeof r?.closeRead=="function"}function Xy(r){return typeof r?.close=="function"}function $l(r){return jy(r)?r.remoteWriteStatus!=="writable"&&r.readBufferLength===0:Xy(r)?r.status!=="open":!1}function Zy(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function Wl(r,e){let t=e?.maxBufferSize??Yy,n=new Q,o,s=!1;if(!Zy(r))throw new C("Argument should be a Stream or a Multiaddr");let i=l=>{if(n.append(l.data),n.byteLength>t){let f=n.byteLength;n.consume(n.byteLength),o?.reject(new Error(`Read buffer overflow - ${f} > ${t}`))}o?.resolve()};r.addEventListener("message",i);let a=l=>{l.error!=null?o?.reject(l.error):o?.resolve()};r.addEventListener("close",a);let c=()=>{o?.resolve()};r.addEventListener("remoteCloseWrite",c);let u={readBuffer:n,async read(l){if(s===!0)throw new Hs("Stream was unwrapped");if($l(r)){if(n.byteLength===0&&l?.bytes==null)return null;if(l?.bytes!=null&&n.byteLength<l.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,l.bytes),new gr(`Unexpected EOF - stream closed after reading ${n.byteLength}/${l.bytes} bytes`)}let f=l?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=f){o.resolve();break}if(await $e(o.promise,l?.signal),$l(r)){if(n.byteLength===0&&l?.bytes==null)return null;break}o=Promise.withResolvers()}let d=l?.bytes??n.byteLength;if(n.byteLength<d){if($l(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,d),new gr(`Unexpected EOF - stream closed while reading ${n.byteLength}/${d} bytes`);return u.read(l)}let h=n.sublist(0,d);return n.consume(d),h},async write(l,f){if(s===!0)throw new Hs("Stream was unwrapped");r.send(l)||await ot(r,"drain",{signal:f?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,r.removeEventListener("message",i),r.removeEventListener("close",a),r.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.push(n))),r}};return u}function Ws(r,e={}){let t=Wl(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=me(e.maxDataLength));let n=e?.lengthDecoder??sr,o=e?.lengthEncoder??$t;return{async read(i){let a=-1,c=new Q;for(;;){let l=await t.read({...i,bytes:1});if(l==null)break;c.append(l);try{a=n(c)}catch(f){if(f instanceof RangeError)continue;throw f}if(a<0)throw new Vl("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new Hl(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new zl(`Message length too long - ${a} > ${e.maxDataLength}`);let u=await t.read({...i,bytes:a});if(u==null)throw r.log.error("tried to read %d bytes but the stream closed",a),new gr(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(u.byteLength!==a)throw r.log.error("read %d/%d bytes before the stream closed",u.byteLength,a),new gr(`Unexpected EOF - read ${u.byteLength}/${a} bytes before the stream closed`);return u},async write(i,a){await t.write(new Q(o(i.byteLength),i),a)},async writeV(i,a){let c=new Q(...i.flatMap(u=>[o(u.byteLength),u]));await t.write(c,a)},unwrap(){return t.unwrap()}}}var Gs=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},gn=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ys=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},wo=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function js(r){return r[Symbol.asyncIterator]!=null}function Uh(r,e){if(r.byteLength>e)throw new gn("Message length too long")}var Zs=r=>{let e=me(r),t=Se(e);return $t(r,t),Zs.bytes=e,t};Zs.bytes=0;function Qs(r,e){e=e??{};let t=e.lengthEncoder??Zs,n=e?.maxDataLength??4194304;function*o(s){Uh(s,n);let i=t(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return js(r)?(async function*(){for await(let s of r)yield*o(s)})():(function*(){for(let s of r)yield*o(s)})()}Qs.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Zs,n=e?.maxDataLength??4194304;return Uh(r,n),new Q(t(r.byteLength),r)};var wr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(wr||(wr={}));var Yl=r=>{let e=sr(r);return Yl.bytes=me(e),e};Yl.bytes=0;function Gl(r,e){let t=new Q,n=wr.LENGTH,o=-1,s=e?.lengthDecoder??Yl,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===wr.LENGTH)try{if(o=s(t),o<0)throw new Gs("Invalid message length");if(o>a)throw new gn("Message length too long");let u=s.bytes;t.consume(u),e?.onLength!=null&&e.onLength(o),n=wr.DATA}catch(u){if(u instanceof RangeError){if(t.byteLength>i)throw new Ys("Message length length too long");break}throw u}if(n===wr.DATA){if(t.byteLength<o)break;let u=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(u),yield u,n=wr.LENGTH}}}return js(r)?(async function*(){for await(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw new wo("Unexpected end of input")})():(function*(){for(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw new wo("Unexpected end of input")})()}Gl.fromReader=(r,e)=>{let t=1,n=(async function*(){for(;;)try{let{done:s,value:i}=await r.next(t);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{t=1}})();return Gl(n,{...e??{},onLength:s=>{t=s}})};var Js=class extends an{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var ei=class extends an{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};var ti=class{memoryStorage;points;duration;blockDuration;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new jl}consume(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+t&&(i=this.memoryStorage.set(o,i.consumedPoints,this.blockDuration)),new ks("Rate limit exceeded",i);return i}penalty(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,-t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(e,t){let n=t*1e3,o=this.points+1;return this.memoryStorage.set(this.getKey(e),o,t),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:o,isFirstInDuration:!1}}set(e,t,n=0){let o=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,n),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:t,isFirstInDuration:!1}}get(e){let t=this.memoryStorage.get(this.getKey(e));return t!=null&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return e?.customDuration!=null&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.substring(this.keyPrefix.length)}},jl=class{storage;constructor(){this.storage=new Map}incrby(e,t,n){let o=this.storage.get(e);if(o!=null){let s=o.expiresAt!=null?o.expiresAt.getTime()-new Date().getTime():-1;return o.expiresAt==null||s>0?(o.value+=t,{remainingPoints:0,msBeforeNext:s,consumedPoints:o.value,isFirstInDuration:!1}):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let o=n*1e3,s=this.storage.get(e);s!=null&&clearTimeout(s.timeoutId);let i={value:t,expiresAt:o>0?new Date(Date.now()+o):void 0};return this.storage.set(e,i),o>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(e)},o),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:i.value,isFirstInDuration:!0}}get(e){let t=this.storage.get(e);if(t!=null)return{remainingPoints:0,msBeforeNext:t.expiresAt!=null?t.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){let t=this.storage.get(e);return t!=null?(t.timeoutId!=null&&clearTimeout(t.timeoutId),this.storage.delete(e),!0):!1}};var Xl=class extends Map{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Ie(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Xl({name:e,metrics:t}):n=new Map,n}var Zl=class extends Ye{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Ql(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Zl({name:e,metrics:t}):n=new Ye,n}var xo;(function(r){let e;r.codec=()=>(e==null&&(e=Ne((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.publicKey!=null&&s.publicKey.byteLength>0&&(i.uint32(10),i.bytes(s.publicKey)),s.payloadType!=null&&s.payloadType.byteLength>0&&(i.uint32(18),i.bytes(s.payloadType)),s.payload!=null&&s.payload.byteLength>0&&(i.uint32(26),i.bytes(s.payload)),s.signature!=null&&s.signature.byteLength>0&&(i.uint32(42),i.bytes(s.signature)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={publicKey:ue(0),payloadType:ue(0),payload:ue(0),signature:ue(0)},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.publicKey=s.bytes();break}case 2:{c.payloadType=s.bytes();break}case 3:{c.payload=s.bytes();break}case 5:{c.signature=s.bytes();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.publicKey`,value:s.bytes()};break}case 2:{yield{field:`${a}.payloadType`,value:s.bytes()};break}case 3:{yield{field:`${a}.payload`,value:s.bytes()};break}case 5:{yield{field:`${a}.signature`,value:s.bytes()};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return Re(s,r.codec())}r.encode=t;function n(s,i){return ke(s,r.codec(),i)}r.decode=n;function o(s,i){return Oe(s,r.codec(),i)}r.stream=o})(xo||(xo={}));var ri=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var yn=class r{static createFromProtobuf=e=>{let t=xo.decode(e),n=jr(t.publicKey);return new r({publicKey:n,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t,n)=>{if(t==null)throw new Error("Missing private key");let o=e.domain,s=e.codec,i=e.marshal(),a=Kh(o,s,i),c=await t.sign(a.subarray(),n);return new r({publicKey:t.publicKey,payloadType:s,payload:i,signature:c})};static openAndCertify=async(e,t,n)=>{let o=r.createFromProtobuf(e);if(!await o.validate(t,n))throw new ri("Envelope signature is not valid for the given domain");return o};publicKey;payloadType;payload;signature;marshaled;constructor(e){let{publicKey:t,payloadType:n,payload:o,signature:s}=e;this.publicKey=t,this.payloadType=n,this.payload=o,this.signature=s}marshal(){return this.marshaled==null&&(this.marshaled=xo.encode({publicKey:We(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return e==null?!1:Z(this.marshal(),e.marshal())}async validate(e,t){let n=Kh(e,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,t)}},Kh=(r,e,t)=>{let n=L(r),o=$t(n.byteLength),s=$t(e.length),i=$t(t.length);return new Q(o,n,s,e,i,t)};var qh="libp2p-peer-record",$h=Uint8Array.from([3,1]);var Eo;(function(r){let e;(function(i){let a;i.codec=()=>(a==null&&(a=Ne((f,d,h={})=>{h.lengthDelimited!==!1&&d.fork(),f.multiaddr!=null&&f.multiaddr.byteLength>0&&(d.uint32(10),d.bytes(f.multiaddr)),h.lengthDelimited!==!1&&d.ldelim()},(f,d,h={})=>{let p={multiaddr:ue(0)},y=d==null?f.len:f.pos+d;for(;f.pos<y;){let g=f.uint32();g>>>3===1?p.multiaddr=f.bytes():f.skipType(g&7)}return p},function*(f,d,h,p={}){let y=d==null?f.len:f.pos+d;for(;f.pos<y;){let g=f.uint32();g>>>3===1?yield{field:`${h}.multiaddr`,value:f.bytes()}:f.skipType(g&7)}})),a);function c(f){return Re(f,i.codec())}i.encode=c;function u(f,d){return ke(f,i.codec(),d)}i.decode=u;function l(f,d){return Oe(f,i.codec(),d)}i.stream=l})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=Ne((i,a,c={})=>{if(c.lengthDelimited!==!1&&a.fork(),i.peerId!=null&&i.peerId.byteLength>0&&(a.uint32(10),a.bytes(i.peerId)),i.seq!=null&&i.seq!==0n&&(a.uint32(16),a.uint64(i.seq)),i.addresses!=null&&i.addresses.length>0)for(let u of i.addresses)a.uint32(26),r.AddressInfo.codec().encode(u,a);c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let u={peerId:ue(0),seq:0n,addresses:[]},l=a==null?i.len:i.pos+a;for(;i.pos<l;){let f=i.uint32();switch(f>>>3){case 1:{u.peerId=i.bytes();break}case 2:{u.seq=i.uint64();break}case 3:{if(c.limits?.addresses!=null&&u.addresses.length===c.limits.addresses)throw new Ge('Decode error - repeated field "addresses" had too many elements');u.addresses.push(r.AddressInfo.codec().decode(i,i.uint32(),{limits:c.limits?.addresses$}));break}default:{i.skipType(f&7);break}}}return u},function*(i,a,c,u={}){let l={addresses:0},f=a==null?i.len:i.pos+a;for(;i.pos<f;){let d=i.uint32();switch(d>>>3){case 1:{yield{field:`${c}.peerId`,value:i.bytes()};break}case 2:{yield{field:`${c}.seq`,value:i.uint64()};break}case 3:{if(u.limits?.addresses!=null&&l.addresses===u.limits.addresses)throw new Ge('Streaming decode error - repeated field "addresses" had too many elements');for(let h of r.AddressInfo.codec().stream(i,i.uint32(),`${c}.addresses[]`,{limits:u.limits?.addresses$}))yield{...h,index:l.addresses};l.addresses++;break}default:{i.skipType(d&7);break}}}})),t);function n(i){return Re(i,r.codec())}r.encode=n;function o(i,a){return ke(i,r.codec(),a)}r.decode=o;function s(i,a){return Oe(i,r.codec(),a)}r.stream=s})(Eo||(Eo={}));function Vh(r,e){let t=(n,o)=>n.toString().localeCompare(o.toString());return r.length!==e.length?!1:(e.sort(t),r.sort(t).every((n,o)=>e[o].equals(n)))}var xr=class r{static createFromProtobuf=e=>{let t=Eo.decode(e),n=Xr(mt(t.peerId)),o=(t.addresses??[]).map(i=>X(i.multiaddr)),s=t.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=qh;static CODEC=$h;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(e){let{peerId:t,multiaddrs:n,seqNumber:o}=e;this.peerId=t,this.multiaddrs=n??[],this.seqNumber=o??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=Eo.encode({peerId:this.peerId.toMultihash().bytes,seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))})),this.marshaled}equals(e){return!(!(e instanceof r)||!this.peerId.equals(e.peerId)||this.seqNumber!==e.seqNumber||!Vh(this.multiaddrs,e.multiaddrs))}};function Jy(r){return r[Symbol.asyncIterator]!=null}function eb(r){if(Jy(r))return(async()=>{let t=[];for await(let n of r)t.push(n);return t})();let e=[];for(let t of r)e.push(t);return e}var vo=eb;var Ve=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function ni(r,e,t,n){let o=new Ve(n?.errorMessage);n?.errorCode!=null&&(o.code=n.errorCode);let s=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(o):new Promise((i,a)=>{function c(){eu(t,"abort",f),eu(r,e,u),eu(r,s,l)}let u=d=>{try{if(n?.filter?.(d)===!1)return}catch(h){c(),a(h);return}c(),i(d)},l=d=>{if(c(),d instanceof Error){a(d);return}a(d.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},f=()=>{c(),a(o)};Jl(t,"abort",f),Jl(r,e,u),Jl(r,s,l)})}function Jl(r,e,t){r!=null&&(zh(r)?r.addEventListener(e,t):r.addListener(e,t))}function eu(r,e,t){r!=null&&(zh(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function zh(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var oi=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var si=class{deferred;signal;constructor(e){this.signal=e,this.deferred=Promise.withResolvers(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Ve)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function tb(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var ii=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=tb(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Ve),this.cleanup())}async join(e={}){let t=new si(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await $e(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};function tu(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var So=class extends Le{concurrency;maxSize;queue;pending;sort;autoStart;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.autoStart=e.autoStart??!0,this.sort=e.sort,this.queue=[],this.emitEmpty=tu(this.emitEmpty.bind(this),1),this.emitIdle=tu(this.emitIdle.bind(this),1)}[Symbol.asyncIterator](){return this.toGenerator()}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.safeDispatchEvent("next"),this.autoStart&&this.tryToStartAnother()}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}start(){this.autoStart===!1&&(this.autoStart=!0,this.tryToStartAnother())}pause(){this.autoStart=!1}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new oi;let n=new ii(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.autoStart&&this.tryToStartAnother(),n.join(t).then(o=>(this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Ve)}),this.clear()}async onEmpty(e){this.size!==0&&await ni(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await ni(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await ni(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=sn({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail.result)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new Ve("Queue aborted"))};this.addEventListener("success",o),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("success",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var ai="lock:worker:request-read",ci="lock:worker:abort-read-request",li="lock:worker:release-read",ui="lock:master:grant-read",fi="lock:master:error-read",di="lock:worker:request-write",hi="lock:worker:abort-write-request",pi="lock:worker:release-write",mi="lock:master:grant-write",gi="lock:master:error-write",yi="lock:worker:finalize",bi="mortice",Hh={singleProcess:!1};var ru=(r,e,t,n,o,s,i,a,c)=>u=>{if(u.data==null)return;let l={type:u.data.type,name:u.data.name,identifier:u.data.identifier};l.type===o&&r.safeDispatchEvent(t,{detail:{name:l.name,identifier:l.identifier,handler:async()=>{e.postMessage({type:c,name:l.name,identifier:l.identifier}),await new Promise(f=>{let d=h=>{if(h?.data==null)return;let p={type:h.data.type,name:h.data.name,identifier:h.data.identifier};p.type===a&&p.identifier===l.identifier&&(e.removeEventListener("message",d),f())};e.addEventListener("message",d)})},onError:f=>{e.postMessage({type:i,name:l.name,identifier:l.identifier,error:{message:f.message,name:f.name,stack:f.stack}})}}}),l.type===s&&r.safeDispatchEvent(n,{detail:{name:l.name,identifier:l.identifier}}),l.type===yi&&r.safeDispatchEvent("finalizeRequest",{detail:{name:l.name}})};var Wh=(r=10)=>Math.random().toString().substring(2,r+2);var wi=class{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(bi)}readLock(e){return this.sendRequest(ai,ci,ui,fi,li,e)}writeLock(e){return this.sendRequest(di,hi,mi,gi,pi,e)}finalize(){this.channel.postMessage({type:yi,name:this.name}),this.channel.close()}async sendRequest(e,t,n,o,s,i){i?.signal?.throwIfAborted();let a=Wh();return this.channel.postMessage({type:e,identifier:a,name:this.name}),new Promise((c,u)=>{let l=()=>{this.channel.postMessage({type:t,identifier:a,name:this.name})};i?.signal?.addEventListener("abort",l,{once:!0});let f=d=>{if(d.data?.identifier===a&&(d.data?.type===n&&(this.channel.removeEventListener("message",f),i?.signal?.removeEventListener("abort",l),c(()=>{this.channel.postMessage({type:s,identifier:a,name:this.name})})),d.data.type===o)){this.channel.removeEventListener("message",f),i?.signal?.removeEventListener("abort",l);let h=new Error;d.data.error!=null&&(h.message=d.data.error.message,h.name=d.data.error.name,h.stack=d.data.error.stack),u(h)}};this.channel.addEventListener("message",f)})}};var Gh=r=>{if(r=Object.assign({},Hh,r),!!globalThis.document||r.singleProcess){let t=new BroadcastChannel(bi),n=new Le;return t.addEventListener("message",ru(n,t,"requestReadLock","abortReadLockRequest",ai,ci,fi,li,ui)),t.addEventListener("message",ru(n,t,"requestWriteLock","abortWriteLockRequest",di,hi,gi,pi,mi)),n}return new wi(r.name)};var Er=new Map,_o;function Yh(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function rb(r){if(_o==null&&(_o=Gh(r),!Yh(_o))){let e=_o;e.addEventListener("requestReadLock",t=>{let n=t.detail.name,o=t.detail.identifier,s=Er.get(n);if(s==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||i.abort()};e.addEventListener("abortReadLockRequest",a),s.readLock({signal:i.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortReadLockRequest",a)})}),e.addEventListener("requestWriteLock",t=>{let n=t.detail.name,o=t.detail.identifier,s=Er.get(n);if(s==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||i.abort()};e.addEventListener("abortWriteLockRequest",a),s.writeLock({signal:i.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortWriteLockRequest",a)})}),e.addEventListener("finalizeRequest",t=>{let n=t.detail.name,o=Er.get(n);o?.finalize()})}return _o}async function nu(r,e){let t,n,o=new Promise((i,a)=>{t=i,n=a}),s=()=>{n(new Ve)};return e?.signal?.addEventListener("abort",s,{once:!0}),r.add(async()=>{await new Promise(i=>{t(()=>{e?.signal?.removeEventListener("abort",s),i()})})},{signal:e?.signal}).catch(i=>{n(i)}),o}var jh=(r,e)=>{let t=Er.get(r);if(t!=null)return t;let n=rb(e);if(Yh(n))return t=n,Er.set(r,t),t;let o=new So({concurrency:1}),s;return t={async readLock(i){if(s!=null)return nu(s,i);s=new So({concurrency:e.concurrency,autoStart:!1});let a=s,c=nu(s,i);return o.add(async()=>{a.start(),await a.onIdle().then(()=>{s===a&&(s=null)})}),c},async writeLock(i){return s=null,nu(o,i)},finalize:()=>{Er.delete(r)},queue:o},Er.set(r,t),e.autoFinalize===!0&&o.addEventListener("idle",()=>{t.finalize()},{once:!0}),t};var nb={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function ou(r){let e=Object.assign({},nb,r);return jh(e.name,e)}var Lt;(function(r){let e;(function(a){let c;a.codec=()=>(c==null&&(c=Ne((d,h,p={})=>{p.lengthDelimited!==!1&&h.fork(),d.key!=null&&d.key!==""&&(h.uint32(10),h.string(d.key)),d.value!=null&&d.value.byteLength>0&&(h.uint32(18),h.bytes(d.value)),p.lengthDelimited!==!1&&h.ldelim()},(d,h,p={})=>{let y={key:"",value:ue(0)},g=h==null?d.len:d.pos+h;for(;d.pos<g;){let m=d.uint32();switch(m>>>3){case 1:{y.key=d.string();break}case 2:{y.value=d.bytes();break}default:{d.skipType(m&7);break}}}return y},function*(d,h,p,y={}){let g=h==null?d.len:d.pos+h;for(;d.pos<g;){let m=d.uint32();switch(m>>>3){case 1:{yield{field:`${p}.key`,value:d.string()};break}case 2:{yield{field:`${p}.value`,value:d.bytes()};break}default:{d.skipType(m&7);break}}}})),c);function u(d){return Re(d,a.codec())}a.encode=u;function l(d,h){return ke(d,a.codec(),h)}a.decode=l;function f(d,h){return Oe(d,a.codec(),h)}a.stream=f})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(a){let c;a.codec=()=>(c==null&&(c=Ne((d,h,p={})=>{p.lengthDelimited!==!1&&h.fork(),d.key!=null&&d.key!==""&&(h.uint32(10),h.string(d.key)),d.value!=null&&(h.uint32(18),Io.codec().encode(d.value,h)),p.lengthDelimited!==!1&&h.ldelim()},(d,h,p={})=>{let y={key:""},g=h==null?d.len:d.pos+h;for(;d.pos<g;){let m=d.uint32();switch(m>>>3){case 1:{y.key=d.string();break}case 2:{y.value=Io.codec().decode(d,d.uint32(),{limits:p.limits?.value});break}default:{d.skipType(m&7);break}}}return y},function*(d,h,p,y={}){let g=h==null?d.len:d.pos+h;for(;d.pos<g;){let m=d.uint32();switch(m>>>3){case 1:{yield{field:`${p}.key`,value:d.string()};break}case 2:{yield*Io.codec().stream(d,d.uint32(),`${p}.value`,{limits:y.limits?.value});break}default:{d.skipType(m&7);break}}}})),c);function u(d){return Re(d,a.codec())}a.encode=u;function l(d,h){return ke(d,a.codec(),h)}a.decode=l;function f(d,h){return Oe(d,a.codec(),h)}a.stream=f})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Ne((a,c,u={})=>{if(u.lengthDelimited!==!1&&c.fork(),a.addresses!=null&&a.addresses.length>0)for(let l of a.addresses)c.uint32(10),Ao.codec().encode(l,c);if(a.protocols!=null&&a.protocols.length>0)for(let l of a.protocols)c.uint32(18),c.string(l);if(a.publicKey!=null&&(c.uint32(34),c.bytes(a.publicKey)),a.peerRecordEnvelope!=null&&(c.uint32(42),c.bytes(a.peerRecordEnvelope)),a.metadata!=null&&a.metadata.size>0)for(let[l,f]of a.metadata.entries())c.uint32(50),r.Peer$metadataEntry.codec().encode({key:l,value:f},c);if(a.tags!=null&&a.tags.size>0)for(let[l,f]of a.tags.entries())c.uint32(58),r.Peer$tagsEntry.codec().encode({key:l,value:f},c);a.updated!=null&&(c.uint32(64),c.uint64Number(a.updated)),u.lengthDelimited!==!1&&c.ldelim()},(a,c,u={})=>{let l={addresses:[],protocols:[],metadata:new Map,tags:new Map},f=c==null?a.len:a.pos+c;for(;a.pos<f;){let d=a.uint32();switch(d>>>3){case 1:{if(u.limits?.addresses!=null&&l.addresses.length===u.limits.addresses)throw new Ge('Decode error - repeated field "addresses" had too many elements');l.addresses.push(Ao.codec().decode(a,a.uint32(),{limits:u.limits?.addresses$}));break}case 2:{if(u.limits?.protocols!=null&&l.protocols.length===u.limits.protocols)throw new Ge('Decode error - repeated field "protocols" had too many elements');l.protocols.push(a.string());break}case 4:{l.publicKey=a.bytes();break}case 5:{l.peerRecordEnvelope=a.bytes();break}case 6:{if(u.limits?.metadata!=null&&l.metadata.size===u.limits.metadata)throw new eo('Decode error - map field "metadata" had too many elements');let h=r.Peer$metadataEntry.codec().decode(a,a.uint32(),{limits:{value:u.limits?.metadata$value}});l.metadata.set(h.key,h.value);break}case 7:{if(u.limits?.tags!=null&&l.tags.size===u.limits.tags)throw new eo('Decode error - map field "tags" had too many elements');let h=r.Peer$tagsEntry.codec().decode(a,a.uint32(),{limits:{value:u.limits?.tags$value}});l.tags.set(h.key,h.value);break}case 8:{l.updated=a.uint64Number();break}default:{a.skipType(d&7);break}}}return l},function*(a,c,u,l={}){let f={addresses:0,protocols:0,metadata:0,tags:0},d=c==null?a.len:a.pos+c;for(;a.pos<d;){let h=a.uint32();switch(h>>>3){case 1:{if(l.limits?.addresses!=null&&f.addresses===l.limits.addresses)throw new Ge('Streaming decode error - repeated field "addresses" had too many elements');for(let p of Ao.codec().stream(a,a.uint32(),`${u}.addresses[]`,{limits:l.limits?.addresses$}))yield{...p,index:f.addresses};f.addresses++;break}case 2:{if(l.limits?.protocols!=null&&f.protocols===l.limits.protocols)throw new Ge('Streaming decode error - repeated field "protocols" had too many elements');yield{field:`${u}.protocols[]`,index:f.protocols,value:a.string()},f.protocols++;break}case 4:{yield{field:`${u}.publicKey`,value:a.bytes()};break}case 5:{yield{field:`${u}.peerRecordEnvelope`,value:a.bytes()};break}case 6:{if(l.limits?.metadata!=null&&f.metadata===l.limits.metadata)throw new Ge('Decode error - map field "metadata" had too many elements');yield*r.Peer$metadataEntry.codec().stream(a,a.uint32(),`${u}.metadata{}`,{limits:{value:l.limits?.metadata$value}}),f.metadata++;break}case 7:{if(l.limits?.tags!=null&&f.tags===l.limits.tags)throw new Ge('Decode error - map field "tags" had too many elements');yield*r.Peer$tagsEntry.codec().stream(a,a.uint32(),`${u}.tags{}`,{limits:{value:l.limits?.tags$value}}),f.tags++;break}case 8:{yield{field:`${u}.updated`,value:a.uint64Number()};break}default:{a.skipType(h&7);break}}}})),n);function o(a){return Re(a,r.codec())}r.encode=o;function s(a,c){return ke(a,r.codec(),c)}r.decode=s;function i(a,c){return Oe(a,r.codec(),c)}r.stream=i})(Lt||(Lt={}));var Ao;(function(r){let e;r.codec=()=>(e==null&&(e=Ne((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.multiaddr!=null&&s.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(s.multiaddr)),s.isCertified!=null&&(i.uint32(16),i.bool(s.isCertified)),s.observed!=null&&(i.uint32(24),i.uint64Number(s.observed)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={multiaddr:ue(0)},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.multiaddr=s.bytes();break}case 2:{c.isCertified=s.bool();break}case 3:{c.observed=s.uint64Number();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.multiaddr`,value:s.bytes()};break}case 2:{yield{field:`${a}.isCertified`,value:s.bool()};break}case 3:{yield{field:`${a}.observed`,value:s.uint64Number()};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return Re(s,r.codec())}r.encode=t;function n(s,i){return ke(s,r.codec(),i)}r.decode=n;function o(s,i){return Oe(s,r.codec(),i)}r.stream=o})(Ao||(Ao={}));var Io;(function(r){let e;r.codec=()=>(e==null&&(e=Ne((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.value!=null&&s.value!==0&&(i.uint32(8),i.uint32(s.value)),s.expiry!=null&&(i.uint32(16),i.uint64(s.expiry)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={value:0},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.value=s.uint32();break}case 2:{c.expiry=s.uint64();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.value`,value:s.uint32()};break}case 2:{yield{field:`${a}.expiry`,value:s.uint64()};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return Re(s,r.codec())}r.encode=t;function n(s,i){return ke(s,r.codec(),i)}r.decode=n;function o(s,i){return Oe(s,r.codec(),i)}r.stream=o})(Io||(Io={}));function ob(r,e){if(r.publicKey!=null||e.publicKey==null)return r;let t;r.type==="RSA"&&(t=r.toMultihash());let n=jr(e.publicKey,t);return ol(n)}function Xh(r,e,t){let n=Lt.decode(e);return bn(r,n,t)}function bn(r,e,t){let n=new Map,o=BigInt(Date.now());for(let[s,i]of e.tags.entries())i.expiry!=null&&i.expiry<o||n.set(s,i);return{...e,id:ob(r,e),addresses:e.addresses.filter(({observed:s})=>s!=null&&s>Date.now()-t).map(({multiaddr:s,isCertified:i})=>({multiaddr:X(s),isCertified:i??!1})),metadata:e.metadata,peerRecordEnvelope:e.peerRecordEnvelope??void 0,tags:n}}function Zh(r,e){return sb(r.addresses,e.addresses)&&ib(r.protocols,e.protocols)&&ab(r.publicKey,e.publicKey)&&cb(r.peerRecordEnvelope,e.peerRecordEnvelope)&&lb(r.metadata,e.metadata)&&ub(r.tags,e.tags)}function sb(r,e){return Jh(r,e,(t,n)=>!(t.isCertified!==n.isCertified||!Z(t.multiaddr,n.multiaddr)))}function ib(r,e){return Jh(r,e,(t,n)=>t===n)}function ab(r,e){return Qh(r,e)}function cb(r,e){return Qh(r,e)}function lb(r,e){return ep(r,e,(t,n)=>Z(t,n))}function ub(r,e){return ep(r,e,(t,n)=>t.value===n.value&&t.expiry===n.expiry)}function Qh(r,e){return r==null&&e==null?!0:r!=null&&e!=null?Z(r,e):!1}function Jh(r,e,t){if(r.length!==e.length)return!1;for(let n=0;n<r.length;n++)if(!t(r[n],e[n]))return!1;return!0}function ep(r,e,t){if(r.size!==e.size)return!1;for(let[n,o]of r.entries()){let s=e.get(n);if(s==null||!t(o,s))return!1}return!0}var Pt="/",tp=new TextEncoder().encode(Pt),xi=tp[0],vr=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=L(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==xi)throw new Error("Invalid key")}toString(e="utf8"){return U(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Pt))}static random(){return new r(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new r(e):typeof e.uint8Array=="function"?new r(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=tp),this._buf[0]!==xi){let e=new Uint8Array(this._buf.byteLength+1);e.fill(xi,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===xi;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let o=0;o<t.length;o++){if(n.length<o+1)return!1;let s=t[o],i=n[o];if(s<i)return!0;if(s>i)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Pt).slice(1)}type(){return fb(this.baseNamespace())}name(){return db(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Pt)||(e+=Pt),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Pt):new r(e.slice(0,-1).join(Pt))}child(e){return this.toString()===Pt?e:e.toString()===Pt?this:new r(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()===this.toString()?!1:e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()===this.toString()?!1:this.toString().startsWith(e.toString())}isTopLevel(){return this.list().length===1}concat(...e){return r.withNamespaces([...this.namespaces(),...hb(e.map(t=>t.namespaces()))])}};function fb(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function db(r){let e=r.split(":");return e[e.length-1]}function hb(r){return[].concat(...r)}var su="/peers/";function Co(r){if(!Rt(r)||r.type==null)throw new C("Invalid PeerId");let e=r.toCID().toString();return new vr(`${su}${e}`)}async function rp(r,e,t,n,o){let s=new Map;for(let i of t){if(i==null)continue;if(i.multiaddr instanceof Uint8Array&&(i.multiaddr=X(i.multiaddr)),!Gt(i.multiaddr))throw new C("Multiaddr was invalid");if(!await e(r,i.multiaddr,o))continue;let a=i.isCertified??!1,c=i.multiaddr.toString(),u=s.get(c);u!=null?i.isCertified=u.isCertified||a:s.set(c,{multiaddr:i.multiaddr,isCertified:a})}return[...s.values()].sort((i,a)=>i.multiaddr.toString().localeCompare(a.multiaddr.toString())).map(({isCertified:i,multiaddr:a})=>{let c=a.getComponents().find(u=>u.code===421)?.value;return r.equals(c)&&(a=a.decapsulate(X(`/p2p/${r}`))),{isCertified:i,multiaddr:a.bytes}})}async function vi(r,e,t,n){if(e==null)throw new C("Invalid PeerData");if(e.publicKey!=null&&r.publicKey!=null&&!e.publicKey.equals(r.publicKey))throw new C("publicKey bytes do not match peer id publicKey bytes");let o=n.existingPeer?.peer;if(o!=null&&!r.equals(o.id))throw new C("peer id did not match existing peer id");let s=o?.addresses??[],i=new Set(o?.protocols??[]),a=o?.metadata??new Map,c=o?.tags??new Map,u=o?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(s=[],e.multiaddrs!=null&&s.push(...e.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&s.push(...e.addresses)),e.protocols!=null&&(i=new Set(e.protocols)),e.metadata!=null){let d=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=Ei(d,{validate:np})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=Ei(d,{validate:op,map:sp})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&s.push(...e.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&s.push(...e.addresses),e.protocols!=null&&(i=new Set([...i,...e.protocols])),e.metadata!=null){let d=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[h,p]of d)p==null?a.delete(h):a.set(h,p);a=Ei([...a.entries()],{validate:np})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),h=new Map(c);for(let[p,y]of d)y==null?h.delete(p):h.set(p,y);c=Ei([...h.entries()],{validate:op,map:sp})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}let l;o?.id.publicKey!=null?l=We(o.id.publicKey):e.publicKey!=null?l=We(e.publicKey):r.publicKey!=null&&(l=We(r.publicKey));let f={addresses:await rp(r,n.addressFilter??(async()=>!0),s,n.existingPeer?.peerPB.addresses,n),protocols:[...i.values()].sort((d,h)=>d.localeCompare(h)),metadata:a,tags:c,publicKey:l,peerRecordEnvelope:u};return f.addresses.forEach(d=>{d.observed=n.existingPeer?.peerPB.addresses?.find(h=>Z(h.multiaddr,h.multiaddr))?.observed??Date.now()}),r.type!=="RSA"&&delete f.publicKey,f}function Ei(r,e){let t=new Map;for(let[n,o]of r)o!=null&&e.validate(n,o);for(let[n,o]of r.sort(([s],[i])=>s.localeCompare(i)))o!=null&&t.set(n,e.map?.(n,o)??o);return t}function np(r,e){if(typeof r!="string")throw new C("Metadata key must be a string");if(!(e instanceof Uint8Array))throw new C("Metadata value must be a Uint8Array")}function op(r,e){if(typeof r!="string")throw new C("Tag name must be a string");if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new C("Tag value must be an integer");if(e.value<0||e.value>100)throw new C("Tag value must be between 0-100")}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new C("Tag ttl must be an integer");if(e.ttl<0)throw new C("Tag ttl must be between greater than 0")}}function sp(r,e){let t;e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl)));let n={value:e.value??0};return t!=null&&(n.expiry=t),n}function ip(r){let e=r.toString().split("/")[2],t=fe.parse(e,He);return lo(t)}function iu(r,e,t){let n=ip(r);return Xh(n,e,t)}function pb(r,e){return{prefix:su,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(iu(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(iu(n.key,n.value,e),iu(o.key,o.value,e)))}}var Si=class{peerId;datastore;locks;addressFilter;log;maxAddressAge;maxPeerAge;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.locks=Ql({name:"libp2p_peer_store_locks",metrics:e.metrics}),this.maxAddressAge=t.maxAddressAge??36e5,this.maxPeerAge=t.maxPeerAge??216e5}getLock(e){let t=this.locks.get(e);return t==null&&(t={refs:0,lock:ou({name:e.toString(),singleProcess:!0})},this.locks.set(e,t)),t.refs++,t}maybeRemoveLock(e,t){t.refs--,t.refs===0&&(t.lock.finalize(),this.locks.delete(e))}async getReadLock(e,t){let n=this.getLock(e);try{let o=await n.lock.readLock(t);return()=>{o(),this.maybeRemoveLock(e,n)}}catch(o){throw this.maybeRemoveLock(e,n),o}}async getWriteLock(e,t){let n=this.getLock(e);try{let o=await n.lock.writeLock(t);return()=>{o(),this.maybeRemoveLock(e,n)}}catch(o){throw this.maybeRemoveLock(e,n),o}}async has(e,t){try{return await this.load(e,t),!0}catch(n){if(n.name!=="NotFoundError")throw n}return!1}async delete(e,t){this.peerId.equals(e)||await this.datastore.delete(Co(e),t)}async load(e,t){let n=Co(e),o=await this.datastore.get(n,t),s=Lt.decode(o);if(this.#n(e,s))throw await this.datastore.delete(n,t),new Xt;return bn(e,s,this.peerId.equals(e)?1/0:this.maxAddressAge)}async save(e,t,n){let o=await this.#e(e,n),s=await vi(e,t,"patch",{...n,addressFilter:this.addressFilter});return this.#r(e,s,o)}async patch(e,t,n){let o=await this.#e(e,n),s=await vi(e,t,"patch",{...n,addressFilter:this.addressFilter,existingPeer:o});return this.#r(e,s,o)}async merge(e,t,n){let o=await this.#e(e,n),s=await vi(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#r(e,s,o)}async*all(e){for await(let{key:t,value:n}of this.datastore.query(pb(e??{},this.maxAddressAge),e)){let o=ip(t);if(o.equals(this.peerId))continue;let s=Lt.decode(n);if(this.#n(o,s)){await this.datastore.delete(t,e);continue}yield bn(o,s,this.peerId.equals(o)?1/0:this.maxAddressAge)}}async#e(e,t){try{let n=Co(e),o=await this.datastore.get(n,t),s=Lt.decode(o);if(this.#n(e,s))throw await this.datastore.delete(n,t),new Xt;return{peerPB:s,peer:bn(e,s,this.maxAddressAge)}}catch(n){n.name!=="NotFoundError"&&this.log.error("invalid peer data found in peer store - %e",n)}}async#r(e,t,n,o){t.updated=Date.now();let s=Lt.encode(t);return await this.datastore.put(Co(e),s,o),{peer:bn(e,t,this.maxAddressAge),previous:n?.peer,updated:n==null||!Zh(t,n.peerPB)}}#n(e,t){if(t.updated==null)return!0;if(this.peerId.equals(e))return!1;let n=t.updated<Date.now()-this.maxPeerAge,o=Date.now()-this.maxAddressAge,s=t.addresses.filter(i=>i.observed!=null&&i.observed>o);return n&&s.length===0}};var au=class{store;events;peerId;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.events=e.events,this.peerId=e.peerId,this.store=new Si(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){for await(let n of this.store.all(t))e(n)}async all(e){return vo(this.store.all(e))}async delete(e,t){let n=await this.store.getReadLock(e,t);try{await this.store.delete(e,t)}finally{n()}}async has(e,t){let n=await this.store.getReadLock(e,t);try{return await this.store.has(e,t)}finally{this.log.trace("has release read lock"),n?.()}}async get(e,t){let n=await this.store.getReadLock(e,t);try{return await this.store.load(e,t)}finally{n?.()}}async getInfo(e,t){let n=await this.get(e,t);return{id:n.id,multiaddrs:n.addresses.map(({multiaddr:o})=>o)}}async save(e,t,n){let o=await this.store.getWriteLock(e,n);try{let s=await this.store.save(e,t,n);return this.#e(e,s),s.peer}finally{o?.()}}async patch(e,t,n){let o=await this.store.getWriteLock(e,n);try{let s=await this.store.patch(e,t,n);return this.#e(e,s),s.peer}finally{o?.()}}async merge(e,t,n){let o=await this.store.getWriteLock(e,n);try{let s=await this.store.merge(e,t,n);return this.#e(e,s),s.peer}finally{o?.()}}async consumePeerRecord(e,t,n){let o=Rt(t)?t:Rt(t?.expectedPeer)?t.expectedPeer:void 0,s=Rt(t)||t===void 0?n:t,i=await yn.openAndCertify(e,xr.DOMAIN,s),a=lo(i.publicKey.toCID());if(o?.equals(a)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",o,a),!1;let c=xr.createFromProtobuf(i.payload),u;try{u=await this.get(a,s)}catch(l){if(l.name!=="NotFoundError")throw l}if(u?.peerRecordEnvelope!=null){let l=yn.createFromProtobuf(u.peerRecordEnvelope),f=xr.createFromProtobuf(l.payload);if(f.seqNumber>=c.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",f.seqNumber,c.seqNumber),!1}return await this.patch(c.peerId,{peerRecordEnvelope:e,addresses:c.multiaddrs.map(l=>({isCertified:!0,multiaddr:l}))},s),!0}#e(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}};function ap(r,e={}){return new au(r,e)}var _i=class r extends Error{static name="NotFoundError";name=r.name;static code="ERR_NOT_FOUND";code=r.code;constructor(e="Not Found"){super(e)}};function mb(r){return r[Symbol.asyncIterator]!=null}function gb(r){if(mb(r))return(async()=>{for await(let e of r);})();for(let e of r);}var cu=gb;function yb(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var cp=yb;function bb(r){return r[Symbol.asyncIterator]!=null}function wb(r,e){let t=0;if(bb(r))return(async function*(){for await(let c of r)await e(c,t++)&&(yield c)})();let n=cp(r),{value:o,done:s}=n.next();if(s===!0)return(function*(){})();let i=e(o,t++);if(typeof i.then=="function")return(async function*(){await i&&(yield o);for(let c of n)await e(c,t++)&&(yield c)})();let a=e;return(function*(){i===!0&&(yield o);for(let c of n)a(c,t++)&&(yield c)})()}var Sr=wb;function xb(r){return r[Symbol.asyncIterator]!=null}function Eb(r,e){return xb(r)?(async function*(){yield*(await vo(r)).sort(e)})():(function*(){yield*vo(r).sort(e)})()}var lu=Eb;function vb(r){return r[Symbol.asyncIterator]!=null}function Sb(r,e){return vb(r)?(async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}})():(function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}})()}var uu=Sb;var Ai=class{put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(let{key:n,value:o}of e)await this.put(n,o,t),yield n}async*getMany(e,t={}){for await(let n of e)yield{key:n,value:await this.get(n,t)}}async*deleteMany(e,t={}){for await(let n of e)await this.delete(n,t),yield n}batch(){let e=[],t=[];return{put(n,o){e.push({key:n,value:o})},delete(n){t.push(n)},commit:async n=>{await cu(this.putMany(e,n)),e=[],await cu(this.deleteMany(t,n)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let n=this._all(e,t);if(e.prefix!=null){let o=e.prefix;n=Sr(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Sr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>lu(o,s),n)),e.offset!=null){let o=0,s=e.offset;n=Sr(n,()=>o++>=s)}return e.limit!=null&&(n=uu(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let o=e.prefix;n=Sr(n,s=>s.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Sr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>lu(o,s),n)),e.offset!=null){let o=e.offset,s=0;n=Sr(n,()=>s++>=o)}return e.limit!=null&&(n=uu(n,e.limit)),n}};var Ii=class extends Ai{data;constructor(){super(),this.data=new Map}put(e,t,n){return n?.signal?.throwIfAborted(),this.data.set(e.toString(),t),e}get(e,t){t?.signal?.throwIfAborted();let n=this.data.get(e.toString());if(n==null)throw new _i;return n}has(e,t){return t?.signal?.throwIfAborted(),this.data.has(e.toString())}delete(e,t){t?.signal?.throwIfAborted(),this.data.delete(e.toString())}*_all(e,t){t?.signal?.throwIfAborted();for(let[n,o]of this.data.entries())yield{key:new vr(n),value:o},t?.signal?.throwIfAborted()}*_allKeys(e,t){t?.signal?.throwIfAborted();for(let n of this.data.keys())yield new vr(n),t?.signal?.throwIfAborted()}};var te=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),N=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),lp=r=>({match:e=>r.match(e)===!1?e:!1}),H=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),Ce=(...r)=>({match:e=>{let t;for(let n of r){let o=n.match(e);o!==!1&&(t==null||o.length<t.length)&&(t=o)}return t??!1}}),Y=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e}});function re(...r){function e(o){if(o==null)return!1;let s=o.getComponents();for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function t(o){return e(o)!==!1}function n(o){let s=e(o);return s===!1?!1:s.length===0}return{matchers:r,matches:t,exactMatch:n}}var _b=N(421),up=re(_b),Ti=N(54),Li=N(55),Pi=N(56),du=N(53),G6=re(Ti,H(N(421))),Y6=re(Li,H(N(421))),j6=re(Pi,H(N(421))),X6=re(Ce(du,Pi,Ti,Li),H(N(421))),fp=Y(N(4),H(N(43))),dp=Y(H(N(42)),N(41),H(N(43))),hu=Ce(fp,dp),wn=Ce(hu,du,Ti,Li,Pi),Z6=re(Ce(hu,Y(Ce(du,Pi,Ti,Li),H(N(421))))),pu=re(fp),mu=re(dp),Q6=re(hu),gu=Y(wn,N(6)),To=Y(wn,N(273)),Lo=re(Y(gu,H(N(421)))),J6=re(To),yu=Y(To,te(460),H(N(421))),Di=Y(To,te(461),H(N(421))),Ab=Ce(yu,Di),eT=re(yu),hp=re(Di),fu=Ce(wn,gu,To,yu,Di),pp=Ce(Y(fu,te(477),H(N(421)))),_r=re(pp),mp=Ce(Y(fu,te(478),H(N(421))),Y(fu,te(448),H(N(449)),te(477),H(N(421)))),Po=re(mp),gp=Y(To,te(280),H(N(466)),H(N(466)),H(N(421))),bu=re(gp),yp=Y(Di,te(465),H(N(466)),H(N(466)),H(N(421))),wu=re(yp),Ci=Ce(pp,mp,Y(gu,H(N(421))),Y(Ab,H(N(421))),Y(wn,H(N(421))),gp,yp,N(421)),tT=re(Ci),Ib=Y(H(Ci),te(290),lp(te(281)),H(N(421))),Ar=re(Ib),Cb=Ce(Y(Ci,te(290),te(281),H(N(421))),Y(Ci,te(281),H(N(421))),Y(te(281),H(N(421)))),xu=re(Cb),Tb=Y(wn,Ce(Y(N(6,"80")),Y(N(6),te(480)),te(480)),H(N(481)),H(N(421))),rT=re(Tb),Lb=Y(wn,Ce(Y(N(6,"443")),Y(N(6,"443"),te(480)),Y(N(6),te(443)),Y(N(6),te(448),te(480)),Y(te(448),te(480)),te(448),te(443)),H(N(481)),H(N(421))),nT=re(Lb),Pb=Ce(Y(N(777),H(N(421)))),oT=re(Pb),Db=Ce(Y(N(400),H(N(421)))),sT=re(Db);var bp=864e13;var ki=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=Ie({name:"libp2p_address_manager_dns_mappings",metrics:e.metrics})}has(e){let t=W(e),n=t.host;(t.type==="ip4"||t.type==="ip6")&&t.sni!=null&&(n=t.sni);for(let o of this.mappings.values())if(o.domain===n)return!0;return!1}add(e,t){t.forEach(n=>{this.log("add DNS mapping %s to %s",n,e);let o=nn(n)===!0;this.mappings.set(n,{domain:e,verified:o,expires:o?bp-Date.now():0,lastVerified:o?bp-Date.now():void 0})})}remove(e){let t=W(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;let n=!1;for(let[o,s]of this.mappings.entries())s.domain===t.sni&&(this.log("removing %s to %s DNS mapping %e",o,s.domain),this.mappings.delete(o),n=n||s.verified);return n}getAll(e){let t=[];for(let n=0;n<e.length;n++){let o=e[n].multiaddr;if(!xe(o))continue;let s=W(o);for(let[i,a]of this.mappings.entries()){if(s.host!==i)continue;let c=this.maybeAddSNIComponent(o,a.domain);c!=null&&(e.splice(n,1),n--,t.push({multiaddr:c,verified:a.verified,type:"dns-mapping",expires:a.expires,lastVerified:a.lastVerified}))}}return t}maybeAddSNIComponent(e,t){let n=e.getComponents();for(let o=0;o<n.length;o++)if(n[o].code===448&&n[o+1]?.code!==449)return n.splice(o+1,0,{name:"sni",code:449,value:t}),X(n)}confirm(e,t){let n=W(e),o=n.host;(n.type==="ip4"||n.type==="ip6")&&n.sni!=null&&(o=n.sni);let s=!1;for(let[i,a]of this.mappings.entries())a.domain===o&&(this.log("marking %s to %s DNS mapping as verified",i,a.domain),s=a.verified,a.verified=!0,a.expires=Date.now()+t,a.lastVerified=Date.now());return s}unconfirm(e,t){let n=W(e);if(n.type!=="ip4"&&n.type!=="ip6")return!1;let o=n.sni??n.host,s=!1;for(let[i,a]of this.mappings.entries())a.domain===o&&(this.log("removing verification of %s to %s DNS mapping",i,a.domain),s=s||a.verified,a.verified=!1,a.expires=Date.now()+t);return s}};var Ri=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=Ie({name:"libp2p_address_manager_ip_mappings",metrics:e.metrics})}has(e){let t=W(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;for(let n of this.mappings.values())for(let o of n)if(o.externalIp===t.host)return!0;return!1}add(e,t,n,o=t,s="tcp"){let i=`${e}-${t}-${s}`,a=this.mappings.get(i)??[],c={internalIp:e,internalPort:t,externalIp:n,externalPort:o,externalFamily:nt(n)?4:6,protocol:s,verified:!1,expires:0};a.push(c),this.mappings.set(i,a)}remove(e){let t=W(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;let n=!1;for(let[o,s]of this.mappings.entries()){for(let i=0;i<s.length;i++){let a=s[i];a.externalIp===t.host&&a.externalPort===t.port&&a.protocol===t.protocol&&(this.log("removing %s:%s to %s:%s %s IP mapping",a.externalIp,a.externalPort,t.host,t.port,t.protocol),n=n||a.verified,s.splice(i,1),i--)}s.length===0&&this.mappings.delete(o)}return n}getAll(e){let t=[];for(let{multiaddr:n}of e){if(!xe(n))continue;let o=W(n);if(o.type!=="ip4"&&o.type!=="ip6")continue;let s;if(o.protocol==="tcp"?s=`${o.host}-${o.port}-tcp`:o.protocol==="udp"&&(s=`${o.host}-${o.port}-udp`),s==null)continue;let i=this.mappings.get(s);if(i!=null)for(let a of i)t.push({multiaddr:this.maybeOverrideIp(n,a.externalIp,a.externalFamily,a.protocol,a.externalPort),verified:a.verified,type:"ip-mapping",expires:a.expires,lastVerified:a.lastVerified})}return t}maybeOverrideIp(e,t,n,o,s){let i=e.getComponents(),a=i.findIndex(u=>u.code===4||u.code===41),c=i.findIndex(u=>u.name===o);return a>-1&&c>-1?(i[a].value=t,i[a].code=n===4?4:41,i[c].value=`${s}`,X(i)):e}confirm(e,t){if(!xe(e))return!1;let n=W(e),o=!1;for(let s of this.mappings.values())for(let i of s)i.externalIp===n.host&&(this.log("marking %s to %s IP mapping as verified",i.internalIp,i.externalIp),o=i.verified,i.verified=!0,i.expires=Date.now()+t,i.lastVerified=Date.now());return o}unconfirm(e,t){if(!xe(e))return!1;let n=W(e),o=!1;for(let s of this.mappings.values())for(let i=0;i<s.length;i++){let a=s[i];a.externalIp===n.host&&a.externalPort===n.port&&a.protocol===n.protocol&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",a.externalIp,a.externalPort,n.host,n.port,n.protocol),o=o||a.verified,a.verified=!1,a.expires=Date.now()+t)}return o}};var kb={maxObservedAddresses:10},Oi=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Ie({name:"libp2p_address_manager_observed_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??kb.maxObservedAddresses}has(e){return this.addresses.has(e.toString())}removePrefixed(e){for(let t of this.addresses.keys())t.toString().startsWith(e)&&this.addresses.delete(t)}add(e){this.addresses.size!==this.maxObservedAddresses&&(_t(e)||wh(e)||(this.log("adding observed address %a",e),this.addresses.set(e.toString(),{verified:!1,expires:0})))}getAll(){return Array.from(this.addresses).map(([e,t])=>({multiaddr:X(e),verified:t.verified,type:"observed",expires:t.expires,lastVerified:t.lastVerified}))}remove(e){let t=this.addresses.get(e.toString())?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(e.toString()),t}confirm(e,t){let n=e.toString(),o=this.addresses.get(n)??{verified:!1,expires:Date.now()+t,lastVerified:Date.now()},s=o.verified;return o.verified=!0,o.expires=Date.now()+t,o.lastVerified=Date.now(),this.log("marking observed address %a as verified",n),this.addresses.set(n,o),s}};var Rb={maxObservedAddresses:10},Ni=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Ie({name:"libp2p_address_manager_transport_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??Rb.maxObservedAddresses}get(e,t){if(_t(e))return{multiaddr:e,verified:!0,type:"transport",expires:Date.now()+t,lastVerified:Date.now()};let n=this.toKey(e),o=this.addresses.get(n);return o==null&&(o={verified:!xe(e),expires:0},this.addresses.set(n,o)),{multiaddr:e,verified:o.verified,type:"transport",expires:o.expires,lastVerified:o.lastVerified}}has(e){let t=this.toKey(e);return this.addresses.has(t)}remove(e){let t=this.toKey(e),n=this.addresses.get(t)?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(t),n}confirm(e,t){let n=this.toKey(e),o=this.addresses.get(n)??{verified:!1,expires:0,lastVerified:0},s=o.verified;return o.verified=!0,o.expires=Date.now()+t,o.lastVerified=Date.now(),this.addresses.set(n,o),s}unconfirm(e,t){let n=this.toKey(e),o=this.addresses.get(n)??{verified:!1,expires:0},s=o.verified;return o.verified=!1,o.expires=Date.now()+t,this.addresses.set(n,o),s}toKey(e){if(!xe(e))return e.toString();let t=W(e);return`${t.host}-${t.port}-${t.protocol}`}};var wp=6e4,xp={maxObservedAddresses:10,addressVerificationTTL:wp*10,addressVerificationRetry:wp*5},Ob=r=>r;function Eu(r,e){let t=r.getComponents().findLast(n=>n.code===421)?.value;return t!=null&&ut(t).equals(e)&&(r=r.decapsulate(X(`/p2p/${e.toString()}`))),r}var Mi=class{log;components;listen;announce;appendAnnounce;announceFilter;observed;dnsMappings;ipMappings;transportAddresses;observedAddressFilter;addressVerificationTTL;addressVerificationRetry;constructor(e,t={}){let{listen:n=[],announce:o=[],appendAnnounce:s=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(i=>i.toString()),this.announce=new Set(o.map(i=>i.toString())),this.appendAnnounce=new Set(s.map(i=>i.toString())),this.observed=new Oi(e,t),this.dnsMappings=new ki(e,t),this.ipMappings=new Ri(e,t),this.transportAddresses=new Ni(e,t),this.announceFilter=t.announceFilter??Ob,this.observedAddressFilter=ho(1024),this.addressVerificationTTL=t.addressVerificationTTL??xp.addressVerificationTTL,this.addressVerificationRetry=t.addressVerificationRetry??xp.addressVerificationRetry,this._updatePeerStoreAddresses=yo(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){let e=this.getAddresses().map(t=>t.getComponents().findLast(n=>n.code===421)?.value===this.components.peerId.toString()?t.decapsulate(`/p2p/${this.components.peerId.toString()}`):t);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(t=>{this.log.error("error updating addresses - %e",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>X(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>X(e))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(e=>X(e))}getObservedAddrs(){return this.observed.getAll().map(e=>e.multiaddr)}addObservedAddr(e){let t=W(e),n;switch(t.type){case"ip4":{n=`${t.host}:${t.port}`;break}case"ip6":{n=`[${t.host}]:${t.port}`;break}default:return}this.observedAddressFilter.has(n)||(this.observedAddressFilter.add(n),e=Eu(e,this.components.peerId),!this.ipMappings.has(e)&&(this.dnsMappings.has(e)||this.observed.add(e)))}confirmObservedAddr(e,t){e=Eu(e,this.components.peerId);let n=!0;(t?.type==="transport"||this.transportAddresses.has(e))&&!this.transportAddresses.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="dns-mapping"||this.dnsMappings.has(e))&&!this.dnsMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="ip-mapping"||this.ipMappings.has(e))&&!this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="observed"||this.observed.has(e))&&(this.maybeUpgradeToIPMapping(e)?(this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL),n=!1):!this.observed.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1)),n||this._updatePeerStoreAddresses()}removeObservedAddr(e,t){e=Eu(e,this.components.peerId);let n=!1;this.observed.has(e)&&!this.observed.remove(e)&&n&&(n=!1),this.transportAddresses.has(e)&&!this.transportAddresses.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.dnsMappings.has(e)&&!this.dnsMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.ipMappings.has(e)&&!this.ipMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),n&&this._updatePeerStoreAddresses()}getAddresses(){let e=new Set,t=this.getAddressesWithMetadata().filter(n=>{if(!n.verified)return!1;let o=n.multiaddr.toString();return e.has(o)?!1:(e.add(o),!0)}).map(n=>n.multiaddr);return this.announceFilter(t.map(n=>{let o=X(n);return o.getComponents().pop()?.value===this.components.peerId.toString()?o:o.encapsulate(`/p2p/${this.components.peerId.toString()}`)}))}getAddressesWithMetadata(){let e=this.getAnnounceAddrs();if(e.length>0)return this.components.transportManager.getListeners().forEach(o=>{o.updateAnnounceAddrs(e)}),e.map(o=>({multiaddr:o,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}));let t=[];t=t.concat(this.components.transportManager.getAddrs().map(o=>this.transportAddresses.get(o,this.addressVerificationTTL)));let n=this.getAppendAnnounceAddrs();return n.length>0&&(this.components.transportManager.getListeners().forEach(o=>{o.updateAnnounceAddrs(n)}),t=t.concat(n.map(o=>({multiaddr:o,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()})))),t=t.concat(this.observed.getAll()),t=t.concat(this.ipMappings.getAll(t)),t=t.concat(this.dnsMappings.getAll(t)),t}addDNSMapping(e,t){this.dnsMappings.add(e,t)}removeDNSMapping(e){this.dnsMappings.remove(X(`/dns/${e}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,n,o=t,s="tcp"){this.ipMappings.add(e,t,n,o,s),this.observed.removePrefixed(`/ip${nt(n)?4:6}/${n}/${s}/${o}`)}removePublicAddressMapping(e,t,n,o=t,s="tcp"){this.ipMappings.remove(X(`/ip${nt(n)?4:6}/${n}/${s}/${o}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){if(this.ipMappings.has(e)||!xe(e))return!1;let t=W(e);if(t.type!=="ip4"||nn(t.host)===!0)return!1;let n=this.components.transportManager.getListeners(),o=[s=>_r.exactMatch(s)||Po.exactMatch(s),s=>Lo.exactMatch(s),s=>hp.exactMatch(s)];for(let s of o){if(!s(e))continue;let i=n.filter(u=>u.getAddrs().filter(l=>W(l).type==="ip4"&&s(l)).length>0);if(i.length!==1)continue;let a=i[0].getAddrs().filter(u=>!mo(u)).pop();if(a==null)continue;let c=W(a);return c.port==null?!1:(this.observed.remove(e),this.ipMappings.add(c.host,c.port,t.host,t.port,t.protocol),!0)}return!1}};var Ep;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(Ep||(Ep={}));var Bi=class extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}},Fi=class extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}},xn=class extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}},Do=class extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}},Ui=class extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}},Ki=class extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}},qi=class extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}},ko=class extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}},$i=class extends Error{constructor(e="No transport was configured to listen on this address"){super(e),this.name="UnsupportedListenAddressError"}},Vi=class extends Error{constructor(e="Configured listen addresses could not be listened on"){super(e),this.name="UnsupportedListenAddressesError"}},zi=class extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}},Hi=class extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}},Wi=class extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}},Yt=class extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}},Ir=class extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}},Gi=class extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}},Yi=class extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}};var vu=class{components={};_started=!1;constructor(e={}){this.components={};for(let[t,n]of Object.entries(e))this.components[t]=n;this.components.logger==null&&(this.components.logger=Ss())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>Xo(t)).map(async t=>{await t[e]?.()}))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}},Nb=["metrics","connectionProtector","dns"],Mb=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function vp(r={}){let e=new vu(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!Mb.includes(o)){let i=e.components[o];if(i==null&&!Nb.includes(o))throw new Bi(`${o} not set`);return i}return Reflect.get(n,o,s)},set(n,o,s){return typeof o=="string"?e.components[o]=s:Reflect.set(n,o,s),!0}})}function Sp(r){let e={};for(let t of Object.values(r.components))for(let n of Bb(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of Fb(t))if(e[n]!==!0)throw new Fi(`Service "${Ub(t)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function Bb(r){return Array.isArray(r?.[Tn])?r[Tn]:[]}function Fb(r){return Array.isArray(r?.[_a])?r[_a]:[]}function Ub(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}function _p(r={}){return r.denyDialMultiaddr==null&&(r.denyDialMultiaddr=e=>_r.matches(e)?!0:_t(e)),r}var J=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};function ji(r){if(Rt(r))return{peerId:r,multiaddrs:[]};let e=Array.isArray(r)?r:[r],t;if(e.length>0){let n=e[0].getComponents().findLast(o=>o.code===421)?.value;t=n==null?void 0:ut(n),e.forEach(o=>{if(!Gt(o))throw new Dt("Invalid multiaddr");let s=o.getComponents().findLast(i=>i.code===421)?.value;if(s==null){if(t!=null)throw new C("Multiaddrs must all have the same peer id or have no peer id")}else{let i=ut(s);if(t?.equals(i)!==!0)throw new C("Multiaddrs must all have the same peer id or have no peer id")}})}return e=e.filter(n=>!up.exactMatch(n)),{peerId:t,multiaddrs:e}}var Kb=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function Ap(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??Kb;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}function Ro(r){let e=W(r),t=e.cidr;if(e.type!=="ip4"&&e.type!=="ip6")throw new C(`Multiaddr ${r} was not an IPv4 or IPv6 address`);if(t==null)switch(e.type){case"ip4":{t=32;break}case"ip6":{t=128;break}default:throw new C(`Multiaddr ${r} was not an IPv4 or IPv6 address`)}return new Jr(e.host,t)}function Su(r){return!Ar.exactMatch(r)}function Xi(r,e,t){if(r==null||e==null)return;let n=e.filter(s=>s.status==="open").sort((s,i)=>s.direct?-1:i.direct?1:0).find(s=>s.limits==null);if(n==null||n.direct||t==null)return n;if(!t.some(s=>Su(s)))return n}var Zi=class{connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.allow=(t.allow??[]).map(n=>Ro(n)),this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),this.maybePruneConnections=this.maybePruneConnections.bind(this)}start(){this.events.addEventListener("connection:open",this.maybePruneConnections)}stop(){this.events.removeEventListener("connection:open",this.maybePruneConnections)}maybePruneConnections(){this._maybePruneConnections().catch(e=>{this.log.error("error while pruning connections - %e",e)})}async _maybePruneConnections(){let e=this.connectionManager.getConnections(),t=e.length,n=this.connectionManager.getMaxConnections();if(this.log("checking max connections limit %d/%d",t,n),t<=n)return;let o=new Ye;for(let c of e){let u=c.remotePeer;if(!o.has(u)){o.set(u,0);try{let l=await this.peerStore.get(u);o.set(u,[...l.tags.values()].reduce((f,d)=>f+d.value,0))}catch(l){l.name!=="NotFoundError"&&this.log.error("error loading peer tags - %e",l)}}}let s=this.sortConnections(e,o),i=Math.max(t-n,0),a=[];for(let c of s)if(this.log("too many connections open - closing a connection to %p",c.remotePeer),this.allow.some(l=>{if(xe(c.remoteAddr)){let f=W(c.remoteAddr);return l.contains(f.host)}return!0})||a.push(c),a.length===i)break;await Promise.all(a.map(async c=>{await Ap(c,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:a})}sortConnections(e,t){return e.sort((n,o)=>{let s=n.timeline.open,i=o.timeline.open;return s<i?1:s>i?-1:0}).sort((n,o)=>n.direction==="outbound"&&o.direction==="inbound"?1:n.direction==="inbound"&&o.direction==="outbound"?-1:0).sort((n,o)=>n.streams.length>o.streams.length?1:n.streams.length<o.streams.length?-1:0).sort((n,o)=>{let s=t.get(n.remotePeer)??0,i=t.get(o.remotePeer)??0;return s>i?1:s<i?-1:0})}};var Ip="last-dial-failure",Cp="last-dial-success";var Tp=100,Qi=50;function qb(r,e){let t=Lo.exactMatch(r.multiaddr),n=Lo.exactMatch(e.multiaddr);if(t&&!n)return-1;if(!t&&n)return 1;let o=Po.exactMatch(r.multiaddr),s=Po.exactMatch(e.multiaddr);if(o&&!s)return-1;if(!o&&s)return 1;let i=_r.exactMatch(r.multiaddr),a=_r.exactMatch(e.multiaddr);if(i&&!a)return-1;if(!i&&a)return 1;let c=xu.exactMatch(r.multiaddr),u=xu.exactMatch(e.multiaddr);if(c&&!u)return-1;if(!c&&u)return 1;let l=bu.exactMatch(r.multiaddr),f=bu.exactMatch(e.multiaddr);if(l&&!f)return-1;if(!l&&f)return 1;let d=wu.exactMatch(r.multiaddr),h=wu.exactMatch(e.multiaddr);return d&&!h?-1:!d&&h?1:0}function $b(r,e){let t=mo(r.multiaddr),n=mo(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function Vb(r,e){let t=_t(r.multiaddr),n=_t(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function zb(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function Hb(r,e){let t=Ar.exactMatch(r.multiaddr),n=Ar.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function Lp(r){return r.sort(qb).sort(zb).sort(Hb).sort(Vb).sort($b)}var Ji=class extends AggregateError{static name="DNSQueryFailedError";name="DNSQueryFailedError"};var Au=wa(Dp(),1);function Iu(r,e,t){let n=0,o=r.length;for(;o>0;){let s=Math.trunc(o/2),i=n+s;t(r[i],e)<=0?(n=++i,o-=s+1):o=s}return n}var En=class{#e=[];enqueue(e,t){let{priority:n=0,id:o}=t??{},s={priority:n,id:o,run:e};if(this.size===0||this.#e[this.size-1].priority>=n){this.#e.push(s);return}let i=Iu(this.#e,s,(a,c)=>c.priority-a.priority);this.#e.splice(i,0,s)}setPriority(e,t){let n=this.#e.findIndex(s=>s.id===e);if(n===-1)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);let[o]=this.#e.splice(n,1);this.enqueue(o.run,{priority:t,id:e})}remove(e){let t=this.#e.findIndex(n=>typeof e=="string"?n.id===e:n.run===e);t!==-1&&this.#e.splice(t,1)}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this.#e.length}};var No=class extends Au.default{#e;#r;#n=0;#h;#m=!1;#w=!1;#c;#C=0;#x=0;#l;#u;#a;#i=[];#s=0;#t;#T;#o=0;#g;#f;#R=1n;#y=new Map;#E=new Set;timeout;constructor(e){if(super(),e={carryoverIntervalCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:En,strict:!1,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${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 \`${e.interval?.toString()??""}\` (${typeof e.interval})`);if(e.strict&&e.interval===0)throw new TypeError("The `strict` option requires a non-zero `interval`");if(e.strict&&e.intervalCap===Number.POSITIVE_INFINITY)throw new TypeError("The `strict` option requires a finite `intervalCap`");if(this.#e=e.carryoverIntervalCount??e.carryoverConcurrencyCount??!1,this.#r=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#h=e.intervalCap,this.#c=e.interval,this.#a=e.strict,this.#t=new e.queueClass,this.#T=e.queueClass,this.concurrency=e.concurrency,e.timeout!==void 0&&!(Number.isFinite(e.timeout)&&e.timeout>0))throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${e.timeout}\` (${typeof e.timeout})`);this.timeout=e.timeout,this.#f=e.autoStart===!1,this.#q()}#v(e){for(;this.#s<this.#i.length;){let n=this.#i[this.#s];if(n!==void 0&&e-n>=this.#c)this.#s++;else break}(this.#s>100&&this.#s>this.#i.length/2||this.#s===this.#i.length)&&(this.#i=this.#i.slice(this.#s),this.#s=0)}#O(e){this.#a?this.#i.push(e):this.#n++}#N(){this.#a?this.#i.length>this.#s&&this.#i.pop():this.#n>0&&this.#n--}#S(){return this.#i.length-this.#s}get#M(){return this.#r?!0:this.#a?this.#S()<this.#h:this.#n<this.#h}get#B(){return this.#o<this.#g}#F(){this.#o--,this.#o===0&&this.emit("pendingZero"),this.#b(),this.emit("next")}#U(){this.#u=void 0,this.#D(),this.#P()}#K(e){if(this.#a){if(this.#v(e),this.#S()>=this.#h){let n=this.#i[this.#s],o=this.#c-(e-n);return this.#_(o),!0}return!1}if(this.#l===void 0){let t=this.#C-e;if(t<0){if(this.#x>0){let n=e-this.#x;if(n<this.#c)return this.#_(this.#c-n),!0}this.#n=this.#e?this.#o:0}else return this.#_(t),!0}return!1}#_(e){this.#u===void 0&&(this.#u=setTimeout(()=>{this.#U()},e))}#A(){this.#l&&(clearInterval(this.#l),this.#l=void 0)}#L(){this.#u&&(clearTimeout(this.#u),this.#u=void 0)}#b(){if(this.#t.size===0){if(this.#A(),this.emit("empty"),this.#o===0){if(this.#L(),this.#a&&this.#s>0){let t=Date.now();this.#v(t)}this.emit("idle")}return!1}let e=!1;if(!this.#f){let t=Date.now(),n=!this.#K(t);if(this.#M&&this.#B){let o=this.#t.dequeue();this.#r||(this.#O(t),this.#p()),this.emit("active"),o(),n&&this.#P(),e=!0}}return e}#P(){this.#r||this.#l!==void 0||this.#a||(this.#l=setInterval(()=>{this.#D()},this.#c),this.#C=Date.now()+this.#c)}#D(){this.#a||(this.#n===0&&this.#o===0&&this.#l&&this.#A(),this.#n=this.#e?this.#o:0),this.#I(),this.#p()}#I(){for(;this.#b(););}get concurrency(){return this.#g}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})`);this.#g=e,this.#I()}setPriority(e,t){if(typeof t!="number"||!Number.isFinite(t))throw new TypeError(`Expected \`priority\` to be a finite number, got \`${t}\` (${typeof t})`);this.#t.setPriority(e,t)}async add(e,t={}){return t={timeout:this.timeout,...t,id:t.id??(this.#R++).toString()},new Promise((n,o)=>{let s=Symbol(`task-${t.id}`),i=()=>{},a=async()=>{i(),this.#o++,this.#y.set(s,{id:t.id,priority:t.priority??0,startTime:Date.now(),timeout:t.timeout});let u;try{try{t.signal?.throwIfAborted()}catch(d){throw this.#$(),this.#y.delete(s),d}this.#x=Date.now();let l=e({signal:t.signal});if(t.timeout&&(l=go(Promise.resolve(l),{milliseconds:t.timeout,message:`Task timed out after ${t.timeout}ms (queue has ${this.#o} running, ${this.#t.size} waiting)`})),t.signal){let{signal:d}=t;l=Promise.race([l,new Promise((h,p)=>{u=()=>{p(d.reason)},d.addEventListener("abort",u,{once:!0})})])}let f=await l;n(f),this.emit("completed",f)}catch(l){o(l),this.emit("error",l)}finally{u&&t.signal?.removeEventListener("abort",u),this.#y.delete(s),queueMicrotask(()=>{this.#F()})}};this.#t.enqueue(a,t);let c=()=>{if(this.#t instanceof En){this.#t.remove(a);return}this.#t.remove?.(t.id)};if(t.signal){let{signal:u}=t,l=()=>{i(),c(),o(u.reason),this.#b(),this.emit("next")};if(i=()=>{u.removeEventListener("abort",l),this.#E.delete(i)},u.aborted){l();return}u.addEventListener("abort",l,{once:!0}),this.#E.add(i)}this.emit("add"),this.#b()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#f?(this.#f=!1,this.#I(),this):this}pause(){this.#f=!0}clear(){for(let e of this.#E)e();this.#t=new this.#T,this.#A(),this.#k(),this.emit("empty"),this.#o===0&&(this.#L(),this.emit("idle")),this.emit("next")}async onEmpty(){this.#t.size!==0&&await this.#d("empty")}async onSizeLessThan(e){this.#t.size<e||await this.#d("next",()=>this.#t.size<e)}async onIdle(){this.#o===0&&this.#t.size===0||await this.#d("idle")}async onPendingZero(){this.#o!==0&&await this.#d("pendingZero")}async onRateLimit(){this.isRateLimited||await this.#d("rateLimit")}async onRateLimitCleared(){this.isRateLimited&&await this.#d("rateLimitCleared")}onError(){return new Promise((e,t)=>{let n=o=>{this.off("error",n),t(o)};this.on("error",n)})}async#d(e,t){return new Promise(n=>{let o=()=>{t&&!t()||(this.off(e,o),n())};this.on(e,o)})}get size(){return this.#t.size}sizeBy(e){return this.#t.filter(e).length}get pending(){return this.#o}get isPaused(){return this.#f}#q(){this.#r||(this.on("add",()=>{this.#t.size>0&&this.#p()}),this.on("next",()=>{this.#p()}))}#p(){this.#r||this.#w||(this.#w=!0,queueMicrotask(()=>{this.#w=!1,this.#k()}))}#$(){this.#r||(this.#N(),this.#p())}#k(){let e=this.#m;if(this.#r||this.#t.size===0){e&&(this.#m=!1,this.emit("rateLimitCleared"));return}let t;if(this.#a){let o=Date.now();this.#v(o),t=this.#S()}else t=this.#n;let n=t>=this.#h;n!==e&&(this.#m=n,this.emit(n?"rateLimit":"rateLimitCleared"))}get isRateLimited(){return this.#m}get isSaturated(){return this.#o===this.#g&&this.#t.size>0||this.isRateLimited&&this.#t.size>0}get runningTasks(){return[...this.#y.values()].map(e=>({...e}))}};function ta(r){let e=[ze.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var Cu=60;function ra(r){return{Status:r.Status??0,TC:r.TC??r.flag_tc??!1,RD:r.RD??r.flag_rd??!1,RA:r.RA??r.flag_ra??!1,AD:r.AD??r.flag_ad??!1,CD:r.CD??r.flag_cd??!1,Question:(r.Question??r.questions??[]).map(e=>({name:e.name,type:ze[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:ze[e.type],TTL:e.TTL??e.ttl??Cu,data:e.data instanceof Uint8Array?U(e.data):e.data}))}}var Yb=4;function Tu(r,e={}){let t=new No({concurrency:e.queryConcurrency??Yb});return async(n,o={})=>{let s=o?.logger?.forComponent("dns:dns-json-over-https"),i=new URLSearchParams;i.set("name",n),ta(o.types).forEach(c=>{i.append("type",ze[c])}),o.onProgress?.(new J("dns:query",n)),s?.("GET %s",`${r}?${i}`);let a=await t.add(async()=>{let c=await fetch(`${r}?${i}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(s?.("GET %s %d",c.url,c.status),c.status!==200)throw new Error(`Unexpected HTTP status: ${c.status} - ${c.statusText}`);let u=ra(await c.json());return o.onProgress?.(new J("dns:response",u)),u},{signal:o.signal});if(a==null)throw new Error("No DNS response received");return a}}function kp(){return[Tu("https://cloudflare-dns.com/dns-query"),Tu("https://dns.google/resolve")]}var Np=wa(Op(),1);var Lu=class{lru;constructor(e){this.lru=(0,Np.default)(e)}get(e,t){let n=!0,o=[];for(let s of t){let i=this.getAnswers(e,s);if(i.length===0){n=!1;break}o.push(...i)}if(n)return ra({answers:o})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,o=this.lru.get(n);if(o!=null){let s=o.filter(i=>i.expires>Date.now()).map(({expires:i,value:a})=>({...a,TTL:Math.round((i-Date.now())/1e3),type:ze[a.type]}));return s.length===0&&this.lru.remove(n),s}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(t.TTL??Cu)*1e3,value:t}),this.lru.set(n,o)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function Mp(r){return new Lu(r)}var jb=1e3,na=class{resolvers;cache;logger;constructor(e){this.resolvers={},this.cache=Mp(e.cacheSize??jb),this.logger=e.logger,Object.entries(e.resolvers??{}).forEach(([t,n])=>{Array.isArray(n)||(n=[n]),t.endsWith(".")||(t=`${t}.`),this.resolvers[t]=n}),this.resolvers["."]==null&&(this.resolvers["."]=kp())}async query(e,t={}){let n=ta(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new J("dns:cache",o)),o;let s=`${e.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of i){if(t.signal?.aborted===!0)break;try{let u=await c(e,{...t,logger:this.logger,types:n});for(let l of u.Answer)this.cache.add(e,l);return u}catch(u){a.push(u),t.onProgress?.(new J("dns:error",u))}}throw new Ji(a,`DNS lookup of ${e} ${n} failed`)}};var ze;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(ze||(ze={}));function Bp(r={}){return new na(r)}var Pu=class{dns;canResolve(e){return e.getComponents().some(({name:t})=>t==="dnsaddr")}async resolve(e,t){let n=e.getComponents().find(c=>c.name==="dnsaddr")?.value;if(n==null)return[e];let s=await this.getDNS(t).query(`_dnsaddr.${n}`,{signal:t?.signal,types:[ze.TXT]}),i=e.getComponents().find(c=>c.name==="p2p")?.value,a=[];for(let c of s.Answer){let u=c.data.replace(/["']/g,"").trim().split("=")[1];u!=null&&(i!=null&&!u.includes(i)||a.push(X(u)))}return a}getDNS(e){return e.dns!=null?e.dns:(this.dns==null&&(this.dns=Bp()),this.dns)}},Cr=new Pu;async function Du(r,e,t){let n=t.depth??0;if(n>(t.maxRecursiveDepth??32))throw new Yi("Max recursive depth reached");let o=!1,s=[];for(let i of Object.values(e))if(i.canResolve(r)){o=!0;let a=await i.resolve(r,t);for(let c of a)s.push(...await Du(c,e,{...t,depth:n+1}))}return o===!1&&s.push(r),s}var Mo={maxParallelDials:Qi,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,resolvers:{dnsaddr:Cr}},oa=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;resolvers;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??Mo.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??Mo.maxDialQueueLength,this.dialTimeout=t.dialTimeout??Mo.dialTimeout,this.connections=t.connections??new Ye,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.resolvers=t.resolvers??Mo.resolvers,this.shutDownController=new AbortController,this.shutDownController.signal,this.queue=new ei({concurrency:t.maxParallelDials??Mo.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("failure",n=>{n.detail?.error.name!==je.name&&this.log.error("error in dial queue - %e",n.detail.error)})}start(){this.shutDownController=new AbortController,this.shutDownController.signal}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:o}=ji(e);if(n!=null&&t.force!==!0){let i=Xi(n,this.connections.get(n),o);if(i!=null)return this.log("already connected to %a",i.remoteAddr),t.onProgress?.(new J("dial-queue:already-connected",i)),i}let s=this.queue.queue.find(i=>{if(n?.equals(i.options.peerId)===!0)return!0;let a=i.options.multiaddrs;if(a==null)return!1;for(let c of o)if(a.has(c.toString()))return!0;return!1});if(s!=null){this.log("joining existing dial target for %p",n);for(let i of o)s.options.multiaddrs.add(i.toString());return t.onProgress?.(new J("dial-queue:already-in-dial-queue")),s.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new Pr("Dial queue is full");return this.log("creating dial target for %p",n,o.map(i=>i.toString())),t.onProgress?.(new J("dial-queue:add-to-dial-queue")),this.queue.add(async i=>{i.onProgress?.(new J("dial-queue:start-dial"));let a=At([this.shutDownController.signal,i.signal]);try{return await this.dialPeer(i,a)}finally{a.clear()}},{peerId:n,priority:t.priority??Nu,multiaddrs:new Set(o.map(i=>i.toString())),signal:t.signal??AbortSignal.timeout(this.dialTimeout),onProgress:t.onProgress})}async dialPeer(e,t){let n=e.peerId,o=e.multiaddrs,s=new Set,i=e.multiaddrs.size===0,a=0,c=0,u=[];for(this.log("starting dial to %p",n);i||o.size>0;){c++,i=!1;let l=[],f=new Set(e.multiaddrs);o.clear(),this.log("calculating addrs to dial %p from %s",n,[...f]);let d=await this.calculateMultiaddrs(n,f,{...e,signal:t});for(let h of d){if(s.has(h.multiaddr.toString())){this.log.trace("skipping previously failed multiaddr %a while dialing %p",h.multiaddr,n);continue}l.push(h)}this.log("%s dial to %p with %s",c===1?"starting":"continuing",n,l.map(h=>h.multiaddr.toString())),e?.onProgress?.(new J("dial-queue:calculated-addresses",l));for(let h of l){if(a===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",a,e.peerId),new Pr("Peer had more than maxPeerAddrsToDial");a++;try{let p=await this.components.transportManager.dial(h.multiaddr,{...e,signal:t});this.log("dial to %a succeeded",h.multiaddr);try{await this.components.peerStore.merge(p.remotePeer,{multiaddrs:[p.remoteAddr],metadata:{[Cp]:L(Date.now().toString())}})}catch(y){this.log.error("could not update last dial failure key for %p - %e",n,y)}return p}catch(p){if(this.log.error("dial failed to %a - %e",h.multiaddr,p),s.add(h.multiaddr.toString()),n!=null)try{await this.components.peerStore.merge(n,{metadata:{[Ip]:L(Date.now().toString())}})}catch(y){this.log.error("could not update last dial failure key for %p - %e",n,y)}if(t.aborted)throw new Ho(p.message);u.push(p)}}}throw u.length===1?u[0]:new AggregateError(u,"All multiaddr dials failed")}async calculateMultiaddrs(e,t=new Set,n={}){let o=[...t].map(f=>({multiaddr:X(f),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new Pr("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new ko("The dial request is blocked by gater.allowDialPeer");if(o.length===0){this.log("loading multiaddrs for %p",e);try{let f=await this.components.peerStore.get(e);o.push(...f.addresses),this.log("loaded multiaddrs for %p",e,o.map(({multiaddr:d})=>d.toString()))}catch(f){if(f.name!=="NotFoundError")throw f}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let f=await this.components.peerRouting.findPeer(e,n);this.log("found multiaddrs for %p in the peer routing",e,o.map(({multiaddr:d})=>d.toString())),o.push(...f.multiaddrs.map(d=>({multiaddr:d,isCertified:!1})))}catch(f){f.name==="NoPeerRoutersError"?this.log("no peer routers configured",e):this.log.error("looking up multiaddrs for %p in the peer routing failed - %e",e,f)}}}let s=(await Promise.all(o.map(async f=>{let d=await Du(f.multiaddr,this.resolvers,{dns:this.components.dns,log:this.log,...n});return d.length===1&&d[0].equals(f.multiaddr)?f:d.map(h=>({multiaddr:h,isCertified:!1}))}))).flat();if(e!=null){let f=`/p2p/${e.toString()}`;s=s.map(d=>d.multiaddr.getComponents().pop()?.name!=="p2p"?{multiaddr:d.multiaddr.encapsulate(f),isCertified:d.isCertified}:d)}let i=s.filter(f=>{if(this.components.transportManager.dialTransportForMultiaddr(f.multiaddr)==null)return!1;let d=f.multiaddr.getComponents().findLast(h=>h.code===421)?.value;return e!=null&&d!=null?e.equals(d):!0}),a=new Map;for(let f of i){let d=f.multiaddr.toString(),h=a.get(d);if(h!=null){h.isCertified=h.isCertified||f.isCertified||!1;continue}a.set(d,f)}let c=[...a.values()];if(c.length===0)throw new zi("The dial request has no valid addresses");let u=[];for(let f of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(f.multiaddr)||u.push(f);let l=this.addressSorter==null?Lp(u):u.sort(this.addressSorter);if(l.length===0)throw new ko("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",e??"unknown peer",s.map(({multiaddr:f})=>f.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",l.map(({multiaddr:f})=>f.toString())),l}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let n=await this.calculateMultiaddrs(void 0,new Set(e.map(o=>o.toString())),t);return t.runOnLimitedConnection===!1?n.find(o=>!Ar.matches(o.multiaddr))!=null:!0}catch{}return!1}};var Xb=Object.prototype.toString,Zb=r=>Xb.call(r)==="[object Error]",Qb=new Set(["network error","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function Mu(r){if(!(r&&Zb(r)&&r.name==="TypeError"&&typeof r.message=="string"))return!1;let{message:t,stack:n}=r;return t==="Load failed"?n===void 0||"__sentry_captured__"in r:t.startsWith("error sending request for url")||t==="Failed to fetch"||t.startsWith("Failed to fetch (")&&t.endsWith(")")?!0:Qb.has(t)}function Jb(r){if(typeof r=="number"){if(r<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(r))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(r!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function sa(r,e,{min:t=0,allowInfinity:n=!1}={}){if(e!==void 0){if(typeof e!="number"||Number.isNaN(e))throw new TypeError(`Expected \`${r}\` to be a number${n?" or Infinity":""}.`);if(!n&&!Number.isFinite(e))throw new TypeError(`Expected \`${r}\` to be a finite number.`);if(e<t)throw new TypeError(`Expected \`${r}\` to be \u2265 ${t}.`)}}function Bu(r,e){if(e!==void 0&&typeof e!="function")throw new TypeError(`Expected \`${r}\` to be a function.`)}var Fu=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}};function ew(r,e){let t=Math.max(1,r+1),n=e.randomize?Math.random()+1:1,o=Math.round(n*e.minTimeout*e.factor**(t-1));return o=Math.min(o,e.maxTimeout),o}function ia(r,e){return Number.isFinite(e)?e-(performance.now()-r):e}async function tw(r,e){r<=0||await new Promise((t,n)=>{let o=()=>{clearTimeout(s),e.signal?.removeEventListener("abort",o),n(e.signal.reason)},s=setTimeout(()=>{e.signal?.removeEventListener("abort",o),t()},r);e.unref&&s.unref?.(),e.signal?.addEventListener("abort",o,{once:!0})})}async function rw({error:r,attemptNumber:e,retriesConsumed:t,startTime:n,options:o}){let s=r instanceof Error?r:new TypeError(`Non-error was thrown: "${r}". You should only throw errors.`);if(s instanceof Fu)throw s.originalError;let i=Number.isFinite(o.retries)?Math.max(0,o.retries-t):o.retries,a=o.maxRetryTime??Number.POSITIVE_INFINITY,c=ew(t,o);if(ia(n,a)<=0){let m=Object.freeze({error:s,attemptNumber:e,retriesLeft:i,retriesConsumed:t,retryDelay:0});throw await o.onFailedAttempt(m),s}let l=Object.freeze({error:s,attemptNumber:e,retriesLeft:i,retriesConsumed:t,retryDelay:i>0?c:0}),f=await o.shouldConsumeRetry(l),d=f&&i>0?c:0,h=Object.freeze({error:s,attemptNumber:e,retriesLeft:i,retriesConsumed:t,retryDelay:d});if(await o.onFailedAttempt(h),ia(n,a)<=0||ia(n,a)<=0||i<=0||s instanceof TypeError&&!Mu(s)||!await o.shouldRetry(h))throw s;let y=ia(n,a);if(y<=0)throw s;if(!f)return o.signal?.throwIfAborted(),!1;let g=Math.min(d,y);return o.signal?.throwIfAborted(),await tw(g,o),o.signal?.throwIfAborted(),!0}async function Uu(r,e={}){if(e={...e},Jb(e.retries),Object.hasOwn(e,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");e.retries??=10,e.factor??=2,e.minTimeout??=1e3,e.maxTimeout??=Number.POSITIVE_INFINITY,e.maxRetryTime??=Number.POSITIVE_INFINITY,e.randomize??=!1,e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,e.shouldConsumeRetry??=()=>!0,Bu("onFailedAttempt",e.onFailedAttempt),Bu("shouldRetry",e.shouldRetry),Bu("shouldConsumeRetry",e.shouldConsumeRetry),sa("factor",e.factor,{min:0,allowInfinity:!1}),sa("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),sa("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),sa("maxRetryTime",e.maxRetryTime,{min:0,allowInfinity:!0}),e.factor>0||(e.factor=1),e.signal?.throwIfAborted();let t=0,n=0,o=performance.now();for(;!Number.isFinite(e.retries)||n<=e.retries;){t++;try{e.signal?.throwIfAborted();let s=await r(t);return e.signal?.throwIfAborted(),s}catch(s){await rw({error:s,attemptNumber:t,retriesConsumed:n,startTime:o,options:e})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}var aa=class{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;events;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.queue=new Js({concurrency:t.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:e.metrics}),this.started=!1,this.retries=t.retries??5,this.backoffFactor=t.backoffFactor,this.retryInterval=t.retryInterval,this.events=e.events,e.events.addEventListener("peer:disconnect",n=>{this.maybeReconnect(n.detail).catch(o=>{this.log.error("failed to maybe reconnect to %p - %e",n.detail,o)})})}async maybeReconnect(e){if(!this.started)return;let t=await this.peerStore.get(e);Fp(t)&&(this.queue.has(e)||this.queue.add(async n=>{await Uu(async o=>{if(this.started)try{await this.connectionManager.openConnection(e,{signal:n?.signal})}catch(s){throw this.log("reconnecting to %p attempt %d of %d failed - %e",e,o,this.retries,s),s}},{signal:n?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:e}).catch(async n=>{this.log.error("failed to reconnect to %p - %e",e,n);let o={};[...t.tags.keys()].forEach(s=>{s.startsWith(Sa)&&(o[s]=void 0)}),await this.peerStore.merge(e,{tags:o}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:e})}).catch(async n=>{this.log.error("failed to remove keep-alive tag from %p - %e",e,n)}))}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>Fp(t)]});await Promise.all(e.map(async t=>{await this.connectionManager.openConnection(t.id).catch(n=>{this.log.error("could not open connection to keepalive peer - %e",n)})}))}).catch(e=>{this.log.error("error reconnect to peers after start - %e",e)})}stop(){this.started=!1,this.queue.abort()}};function Fp(r){for(let e of r.tags.keys())if(e.startsWith(Sa))return!0;return!1}var Nu=50,Ku={maxConnections:Tp,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},ca=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;outboundPendingConnections;maxConnections;dialQueue;reconnectQueue;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;peerId;constructor(e,t={}){if(this.maxConnections=t.maxConnections??Ku.maxConnections,this.maxConnections<1)throw new C("Connection Manager maxConnections must be greater than 0");this.connections=new Ye,this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.allow=(t.allow??[]).map(n=>Ro(X(n))),this.deny=(t.deny??[]).map(n=>Ro(X(n))),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??Ku.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new ti({points:t.inboundConnectionThreshold??Ku.inboundConnectionThreshold,duration:1}),this.connectionPruner=new Zi({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{allow:t.allow?.map(n=>X(n))}),this.dialQueue=new oa(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??Qi,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??1e4,resolvers:t.resolvers??{dnsaddr:Cr},connections:this.connections}),this.reconnectQueue=new aa({events:e.events,peerStore:e.peerStore,logger:e.logger,connectionManager:this},{retries:t.reconnectRetries,retryInterval:t.reconnectRetryInterval,backoffFactor:t.reconnectBackoffFactor,maxParallelReconnects:t.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0,"outbound pending":this.outboundPendingConnections};for(let t of this.connections.values())for(let n of t)e[n.direction]++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let t of this.connections.values())for(let n of t)for(let o of n.streams){let s=`${o.direction} ${o.protocol??"unnegotiated"}`;e[s]=(e[s]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let e={};for(let n of this.connections.values())for(let o of n){let s={};for(let i of o.streams){let a=`${i.direction} ${i.protocol??"unnegotiated"}`;s[a]=(s[a]??0)+1}for(let[i,a]of Object.entries(s))e[i]=e[i]??[],e[i].push(a)}let t={};for(let[n,o]of Object.entries(e)){o=o.sort((i,a)=>i-a);let s=Math.floor(o.length*.9);t[n]=o[s]}return t}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await Xu(this.dialQueue,this.reconnectQueue,this.connectionPruner),this.started=!0,this.log("started")}async stop(){this.events.removeEventListener("connection:open",this.onConnect),this.events.removeEventListener("connection:close",this.onDisconnect),await Zu(this.reconnectQueue,this.dialQueue,this.connectionPruner);let e=[];for(let t of this.connections.values())for(let n of t)e.push(Promise.all([ot(n,"close",{signal:AbortSignal.timeout(500)}),n.close({signal:AbortSignal.timeout(500)})]).catch(o=>{n.abort(o)}));this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}getMaxConnections(){return this.maxConnections}setMaxConnections(e){if(e<1)throw new C("Connection Manager maxConnections must be greater than 0");let t=!1;e<this.maxConnections&&(t=!0),this.maxConnections=e,t&&this.connectionPruner.maybePruneConnections()}onConnect(e){this._onConnect(e).catch(t=>{this.log.error("could not connect - %e",t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}if(t.status!=="open")return;let n=t.remotePeer,o=!this.connections.has(n),s=this.connections.get(n)??[];s.push(t),this.connections.set(n,s),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),o&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e,n=t.remotePeer,s=(this.connections.get(n)??[]).filter(i=>i.id!==t.id);this.connections.set(n,s),s.length===0&&(this.log.trace("peer %p disconnected, removing connection map entry",n),this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:n}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let t=[];for(let n of this.connections.values())t=t.concat(n);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.started)throw new ht("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted(),t?.onProgress?.(new J("connection:open",e));let{peerId:n,multiaddrs:o}=ji(e);if(this.peerId.equals(n))throw new Lr("Can not dial self");if(n!=null&&t.force!==!0){this.log("dial %p",n);let c=Xi(n,this.getConnections(n),o);if(c!=null)return this.log("had an existing connection to %p as %a",n,c.remoteAddr),t.onProgress?.(new J("dial-queue:already-connected")),t.onProgress?.(new J("connection:opened",c)),c}let s=await this.dialQueue.dial(e,{...t,priority:t.priority??Nu});if(s.status!=="open")throw new jt("Remote closed connection during opening");let i=this.connections.get(s.remotePeer);i==null&&(i=[],this.connections.set(s.remotePeer,i));let a=!1;for(let c of i)if(c.id===s.id&&(a=!0),t.force!==!0&&c.id!==s.id&&c.remoteAddr.equals(s.remoteAddr))return s.abort(new Dt("Duplicate multiaddr connection")),c;return a||i.push(s),t.onProgress?.(new J("connection:opened",s)),s}finally{this.outboundPendingConnections--}}async openStream(e,t,n={}){return(await this.openConnection(e,n)).newStream(t,n)}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async o=>{try{await Promise.all([ot(o,"close",t),o.close(t)])}catch(s){o.abort(s)}}))}acceptIncomingConnection(e){if(this.deny.some(o=>{if(xe(e.remoteAddr)){let s=W(e.remoteAddr);return o.contains(s.host)}return!1}))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(o=>{if(xe(e.remoteAddr)){let s=W(e.remoteAddr);return o.contains(s.host)}return!0}))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(xe(e.remoteAddr)){let o=W(e.remoteAddr);try{this.inboundConnectionRateLimiter.consume(o.host,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,o.host),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){let e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map(n=>X(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};var sw=1e4,iw="1.0.0",aw="ping",cw="ipfs",Up=32,lw=!0,la=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??cw}/${aw}/${iw}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??sw,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??lw,this.timeout=new Ms({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[Tn]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,this.abortController.signal,this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(e=>{Promise.resolve().then(async()=>{let t=Date.now(),n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal});try{let o=await e.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0}),s=Wl(o);t=Date.now(),await Promise.all([s.write(Wr(Up),{signal:n}),s.read({bytes:Up,signal:n})]),e.rtt=Date.now()-t,await o.close({signal:n})}catch(o){if(o.name!=="UnsupportedProtocolError")throw o;e.rtt=(Date.now()-t)/2}finally{this.timeout.cleanUp(n)}}).catch(t=>{this.log.error("error during heartbeat - %e",t),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),e.abort(t)):this.log("connection ping failed, but not aborting due to abortConnectionOnPingFailure flag")})})},this.pingIntervalMs)}stop(){this.abortController?.abort(),this.heartbeatInterval!=null&&clearInterval(this.heartbeatInterval)}};var ua=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e,this.findProviders=e.metrics?.traceFunction("libp2p.contentRouting.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()}),getAttributesFromYieldedValue:(n,o)=>({...o,providers:[...Array.isArray(o.providers)?o.providers:[],n.id.toString()]})})??this.findProviders,this.provide=e.metrics?.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.cancelReprovide,this.put=e.metrics?.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:([n])=>({key:U(n,"base36")})})??this.put,this.get=e.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([n])=>({key:U(n,"base36")})})??this.get}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(this.routers.length===0)throw new xn("No content routers available");let n=this,o=new ur;for await(let s of mn(...n.routers.filter(i=>i.findProviders instanceof Function).map(i=>i.findProviders(e,t))))s!=null&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),!o.has(s.id)&&(o.add(s.id),yield s))}async provide(e,t={}){if(this.routers.length===0)throw new xn("No content routers available");await Promise.all(this.routers.filter(n=>n.provide instanceof Function).map(async n=>{await n.provide(e,t)}))}async cancelReprovide(e,t={}){if(this.routers.length===0)throw new xn("No content routers available");await Promise.all(this.routers.filter(n=>n.cancelReprovide instanceof Function).map(async n=>{await n.cancelReprovide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new ht;await Promise.all(this.routers.filter(o=>o.put instanceof Function).map(async o=>{await o.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new ht;return Promise.any(this.routers.filter(n=>n.get instanceof Function).map(async n=>n.get(e,t)))}};var fa=globalThis.CustomEvent??Event;async function*qu(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered??!1,o=new EventTarget,s=[],i=ge(),a=ge(),c=!1,u,l=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of r){if(s.length===t&&(i=ge(),await i.promise),l)break;let y={done:!1};s.push(y),p().then(g=>{y.done=!0,y.ok=!0,y.value=g,o.dispatchEvent(new fa("task-complete"))},g=>{y.done=!0,y.err=g,o.dispatchEvent(new fa("task-complete"))})}c=!0,o.dispatchEvent(new fa("task-complete"))}catch(p){u=p,o.dispatchEvent(new fa("task-complete"))}});function f(){return n?s[0]?.done:!!s.find(p=>p.done)}function*d(){for(;s.length>0&&s[0].done;){let p=s[0];if(s.shift(),p.ok)yield p.value;else throw l=!0,i.resolve(),p.err;i.resolve()}}function*h(){for(;f();)for(let p=0;p<s.length;p++)if(s[p].done){let y=s[p];if(s.splice(p,1),p--,y.ok)yield y.value;else throw l=!0,i.resolve(),y.err;i.resolve()}}for(;;){if(f()||(a=ge(),await a.promise),u!=null||(n?yield*d():yield*h(),u!=null))throw u;if(c&&s.length===0)break}}var da=class{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[],this.findPeer=e.metrics?.traceFunction("libp2p.peerRouting.findPeer",this.findPeer.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,peer:n.toString()})})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,key:U(n,"base36")}),getAttributesFromYieldedValue:(n,o)=>({...o,peers:[...Array.isArray(o.peers)?o.peers:[],n.id.toString()]})})??this.getClosestPeers}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(this.routers.length===0)throw new Do("No peer routers available");if(e.toString()===this.peerId.toString())throw new Ui("Should not try to find self");let n=this,o=mn(...this.routers.filter(s=>s.findPeer instanceof Function).map(s=>(async function*(){try{yield await s.findPeer(e,t)}catch(i){n.log.error("router failed to find peer - %e",i)}})()));for await(let s of o)if(s!=null)return s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),s;throw new Xt}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new Do("No peer routers available");let n=this,o=ho(1024);for await(let s of qu((async function*(){let i=mn(...n.routers.filter(a=>a.getClosestPeers instanceof Function).map(a=>a.getClosestPeers(e,t)));for await(let a of i)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.findPeer(a.id,{...t,useCache:!1})}catch(c){n.log.error("could not find peer multiaddrs - %e",c);return}return a}})()))s!=null&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),!o.has(s.id.toMultihash().bytes)&&(o.add(s.id.toMultihash().bytes),yield s))}};var ha=class extends Le{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,this.shutdownController.signal}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,this.shutdownController.signal}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=At([this.shutdownController.signal,e?.signal]);try{for(;;)this.needNext?.resolve(),this.needNext=ge(),yield(await ot(this,"walk:peer",{signal:t,rejectionEvents:["walk:error"]})).detail}catch(n){throw n.detail!=null?n.detail:n}finally{t.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,this.walkController.signal;let e=At([this.walkController.signal,this.shutdownController.signal]);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let o=Wr(32),s=Date.now();for await(let i of this.peerRouting.getClosestPeers(o,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",i.id,Date.now()-s,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:i}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await $e(this.needNext.promise,e)),s=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",o,this.walkers,n)}catch(o){this.log.error("random walk errored - %e",o),this.safeDispatchEvent("walk:error",{detail:o})}this.log("no walkers left, ended walk")}).catch(o=>{this.log.error("random walk errored - %e",o)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}};var $u=32,Vu=64,pa=class{log;topologies;handlers;components;middleware;constructor(e){this.components=e,this.log=e.logger.forComponent("libp2p:registrar"),this.middleware=new Map,this.topologies=new Map,e.metrics?.registerMetricGroup("libp2p_registrar_topologies",{calculate:()=>{let t={};for(let[n,o]of this.topologies)t[n]=o.size;return t}}),this.handlers=Ie({name:"libp2p_registrar_protocol_handlers",metrics:e.metrics}),this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new Ki(`No handler registered for protocol ${e}`);return t}getTopologies(e){let t=this.topologies.get(e);return t==null?[]:[...t.values()]}async handle(e,t,n){if(this.handlers.has(e)&&n?.force!==!0)throw new qi(`Handler already registered for protocol ${e}`);this.handlers.set(e,{handler:t,options:{maxInboundStreams:$u,maxOutboundStreams:Vu,...n}}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]},n)}async unhandle(e,t){(Array.isArray(e)?e:[e]).forEach(o=>{this.handlers.delete(o)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()},t)}async register(e,t){if(t==null)throw new C("invalid topology");let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,o=this.topologies.get(e);return o==null&&(o=new Map,this.topologies.set(e,o)),o.set(n,t),n}unregister(e){for(let[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(t))}use(e,t){this.middleware.set(e,t)}unuse(e){this.middleware.delete(e)}getMiddleware(e){return this.middleware.get(e)??[]}async _onDisconnect(e){let t=e.detail,n={signal:AbortSignal.timeout(5e3)};try{let o=await this.components.peerStore.get(t,n);for(let s of o.protocols){let i=this.topologies.get(s);i!=null&&await Promise.all([...i.values()].map(async a=>{a.filter!=null&&a.filter.has(t)!==!0||(a.filter?.remove(t),await a.onDisconnect?.(t))}))}}catch(o){if(o.name==="NotFoundError")return;this.log.error("could not inform topologies of disconnecting peer %p - %e",t,o)}}async _onPeerUpdate(e){let{peer:t,previous:n}=e.detail,o=(n?.protocols??[]).filter(s=>!t.protocols.includes(s));try{for(let s of o){let i=this.topologies.get(s);i!=null&&await Promise.all([...i.values()].map(async a=>{a.filter!=null&&a.filter.has(t.id)!==!0||(a.filter?.remove(t.id),await a.onDisconnect?.(t.id))}))}}catch(s){this.log.error("could not inform topologies of updated peer %p - %e",t.id,s)}}async _onPeerIdentify(e){let t=e.detail.protocols,n=e.detail.connection,o=e.detail.peerId;try{for(let s of t){let i=this.topologies.get(s);i!=null&&await Promise.all([...i.values()].map(async a=>{n.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(o)!==!0&&(a.filter?.add(o),await a.onConnect?.(o,n))}))}}catch(s){this.log.error("could not inform topologies of updated peer after identify %p - %e",o,s)}}};var ma=class{log;components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=Ie({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=Ie({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??Cn.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new C("Transport must have a valid tag");if(this.transports.has(t))throw new C(`There is already a transport with the tag ${t}`);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){let e=[];for(let[t,n]of this.listeners)for(this.log("closing listeners for %s",t);n.length>0;){let o=n.pop();o!=null&&e.push(o.close())}await Promise.all(e),this.log("all listeners closed");for(let t of this.listeners.keys())this.listeners.set(t,[]);this.started=!1}async dial(e,t){let n=this.dialTransportForMultiaddr(e);if(n==null)throw new Gi(`No transport available for address ${String(e)}`);return t?.onProgress?.(new J("transport-manager:selected-transport",n[Symbol.toStringTag])),n.dial(e,{...t,upgrader:this.components.upgrader})}getAddrs(){let e=[];for(let t of this.listeners.values())for(let n of t)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(let t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(let t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new ht("Not started");if(e==null||e.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let t={errors:new Map,ipv4:{success:0,attempts:0},ipv6:{success:0,attempts:0}};e.forEach(s=>{t.errors.set(s.toString(),new $i)});let n=[];for(let[s,i]of this.transports.entries()){let a=i.listenFilter(e);for(let c of a){this.log("creating listener for %s on %a",s,c);let u=i.createListener({upgrader:this.components.upgrader}),l=this.listeners.get(s)??[];l==null&&(l=[],this.listeners.set(s,l)),l.push(u),u.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:u})}),u.addEventListener("close",()=>{let f=l.findIndex(d=>d===u);l.splice(f,1),this.components.events.safeDispatchEvent("transport:close",{detail:u})}),pu.matches(c)?t.ipv4.attempts++:mu.matches(c)&&t.ipv6.attempts++,n.push(u.listen(c).then(()=>{t.errors.delete(c.toString()),pu.matches(c)&&t.ipv4.success++,mu.matches(c)&&t.ipv6.success++},f=>{throw this.log.error("transport %s could not listen on address %a - %e",s,c,f),t.errors.set(c.toString(),f),f}))}}let o=await Promise.allSettled(n);if(!(o.length>0&&o.every(s=>s.status==="fulfilled"))){if(this.ipv6Unsupported(t)){this.log("all IPv4 addresses succeed but all IPv6 failed");return}if(this.faultTolerance===Cn.NO_FATAL){this.log("failed to listen on any address but fault tolerance allows this");return}throw new Vi(`Some configured addresses failed to be listened on, you may need to remove one or more listen addresses from your configuration or set \`transportManager.faultTolerance\` to NO_FATAL:
|
|
13
13
|
${[...t.errors.entries()].map(([s,i])=>`
|
|
14
|
-
${s}: ${`${
|
|
14
|
+
${s}: ${`${uw(i)}`.split(`
|
|
15
15
|
`).join(`
|
|
16
16
|
`)}
|
|
17
|
-
`).join("")}`)}}ipv6Unsupported(e){if(e.ipv4.attempts===0||e.ipv6.attempts===0)return!1;let t=e.ipv4.attempts===e.ipv4.success,n=e.ipv6.success===0;return t&&n}async remove(e){let t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);let n=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){let o=t.pop();o!=null&&n.push(o.close())}await Promise.all(n),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}};function
|
|
18
|
-
`);async function
|
|
19
|
-
`),
|
|
20
|
-
`);if(await o.writeV([c,
|
|
21
|
-
`),t);if(n.trace("reading protocol response"),a=await
|
|
22
|
-
`),t),n.trace('responded with "%s" for "%s"',
|
|
23
|
-
`),t),n.trace('responded with "%s" for "%s"',s,s),o.unwrap(),s;if(s==="ls"){let i=new Q(...e.map(a=>
|
|
17
|
+
`).join("")}`)}}ipv6Unsupported(e){if(e.ipv4.attempts===0||e.ipv6.attempts===0)return!1;let t=e.ipv4.attempts===e.ipv4.success,n=e.ipv6.success===0;return t&&n}async remove(e){let t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);let n=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){let o=t.pop();o!=null&&n.push(o.close())}await Promise.all(n),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}};function uw(r){return r.stack!=null&&r.stack.trim()!==""?r.stack:r.message!=null?r.message:r.toString()}var dt="/multistream/1.0.0";var fw=L(`
|
|
18
|
+
`);async function Bo(r,e){let n=(await r.read(e)).subarray();if(n.byteLength===0||n[n.length-1]!==fw[0])throw new zo("Missing newline");return U(n).trimEnd()}async function vn(r,e,t={}){if(e=Array.isArray(e)?[...e]:[e],e.length===0)throw new Error("At least one protocol must be specified");let n=r.log.newScope("mss:select"),o=Ws(r,{...t,maxDataLength:1024});for(let s=0;s<e.length;s++){let i=e[s],a;if(s===0){n.trace('write ["%s", "%s"]',dt,i);let c=L(`${dt}
|
|
19
|
+
`),u=L(`${i}
|
|
20
|
+
`);if(await o.writeV([c,u],t),n.trace("reading multistream-select header"),a=await Bo(o,t),n.trace('read "%s"',a),a!==dt){n.error("did not read multistream-select header from response");break}}else n.trace('write "%s"',i),await o.write(L(`${i}
|
|
21
|
+
`),t);if(n.trace("reading protocol response"),a=await Bo(o,t),n.trace('read "%s"',a),a===i)return n.trace('selected "%s" after negotiation',a),o.unwrap(),i}throw new Vo(`Protocol selection failed - could not negotiate ${e}`)}async function Sn(r,e,t={}){e=Array.isArray(e)?e:[e];let n=r.log.newScope("mss:handle"),o=Ws(r,{...t,maxDataLength:1024,maxLengthLength:2});for(;;){n.trace("reading incoming string");let s=await Bo(o,t);if(n.trace('read "%s"',s),s===dt){n.trace('respond with "%s" for "%s"',dt,s),await o.write(L(`${dt}
|
|
22
|
+
`),t),n.trace('responded with "%s" for "%s"',dt,s);continue}if(e.includes(s))return n.trace('respond with "%s" for "%s"',s,s),await o.write(L(`${s}
|
|
23
|
+
`),t),n.trace('responded with "%s" for "%s"',s,s),o.unwrap(),s;if(s==="ls"){let i=new Q(...e.map(a=>Qs.single(L(`${a}
|
|
24
24
|
`))),L(`
|
|
25
25
|
`));n.trace('respond with "%s" for %s',e,s),await o.write(i,t),n.trace('responded with "%s" for %s',e,s);continue}n.trace('respond with "na" for "%s"',s),await o.write(L(`na
|
|
26
|
-
`),t),n('responded with "na" for "%s"',s)}}var Pu=class extends Le{id;remoteAddr;remotePeer;direction;timeline;direct;multiplexer;encryption;limits;log;maConn;muxer;components;outboundStreamProtocolNegotiationTimeout;inboundStreamProtocolNegotiationTimeout;closeTimeout;constructor(e,t){super(),this.components=e,this.id=t.id,this.remoteAddr=t.maConn.remoteAddr,this.remotePeer=t.remotePeer,this.direction=t.direction??"outbound",this.timeline=t.maConn.timeline,this.encryption=t.cryptoProtocol,this.limits=t.limits,this.maConn=t.maConn,this.log=t.maConn.log,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.closeTimeout=t.closeTimeout??1e3,this.direct=lu(t.maConn.remoteAddr),this.onIncomingStream=this.onIncomingStream.bind(this),this.remoteAddr.getComponents().find(n=>n.code===421)==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),t.muxer!=null&&(this.multiplexer=t.muxer.protocol,this.muxer=t.muxer,this.muxer.addEventListener("stream",this.onIncomingStream)),this.maConn.addEventListener("close",n=>{this.dispatchEvent(new $o(n.local,n.error))})}[Symbol.toStringTag]="Connection";[Ou]=!0;get streams(){return this.muxer?.streams??[]}get status(){return this.maConn.status}newStream=async(e,t={})=>{if(this.muxer==null)throw new Ht("Connection is not multiplexed");if(this.muxer.status!=="open")throw new Wt(`The connection muxer is "${this.muxer.status}" and not "open"`);if(this.maConn.status!=="open")throw new Wt(`The connection is "${this.status}" and not "open"`);if(this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new bn("Cannot open protocol stream on limited connection");Array.isArray(e)||(e=[e]),this.log.trace("starting new stream for protocols %s",e);let n=await this.muxer.createStream({...t,protocol:e.length===1?e[0]:void 0});this.log.trace("started new stream %s for protocols %s",n.id,e);try{if(t.signal==null){n.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",e);let a=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);t={...t,signal:a}}n.protocol===""?(n.log.trace("selecting protocol from protocols %s",e),n.protocol=await mn(n,e,t),n.log("negotiated protocol %s",n.protocol)):n.log("pre-negotiated protocol %s",n.protocol);let o=Wb(n.protocol,this.components.registrar,t),s=Ip(n.protocol,"outbound",this);if(s>o){let a=new qo(`Too many outbound protocol streams for protocol "${n.protocol}" - ${s}/${o}`);throw n.abort(a),a}await this.components.peerStore.merge(this.remotePeer,{protocols:[n.protocol]}),this.components.metrics?.trackProtocolStream(n);let i=this.components.registrar.getMiddleware(n.protocol);return await this.runMiddlewareChain(n,this,i)}catch(o){throw n.status==="open"?n.abort(o):this.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",this.direction==="inbound"?"from":"to",this.remoteAddr,e,o),o}};async onIncomingStream(e){let t=e.detail,n=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);t.log("start protocol negotiation, timing out after %dms",this.inboundStreamProtocolNegotiationTimeout);try{if(t.protocol===""){let l=this.components.registrar.getProtocols();t.log.trace("selecting protocol from protocols %s",l),t.protocol=await gn(t,l,{signal:n}),t.log("negotiated protocol %s",t.protocol)}else t.log("pre-negotiated protocol %s",t.protocol);let o=Hb(t.protocol,this.components.registrar);if(Ip(t.protocol,"inbound",this)>o)throw new Ko(`Too many inbound protocol streams for protocol "${t.protocol}" - limit ${o}`);await this.components.peerStore.merge(this.remotePeer,{protocols:[t.protocol]},{signal:n}),this.components.metrics?.trackProtocolStream(t);let{handler:i,options:a}=this.components.registrar.getHandler(t.protocol);if(this.limits!=null&&a.runOnLimitedConnection!==!0)throw new bn("Cannot open protocol stream on limited connection");let c=this.components.registrar.getMiddleware(t.protocol);c.push(async(l,u,f)=>{await i(l,u),f(l,u)}),await this.runMiddlewareChain(t,this,c)}catch(o){t.abort(o)}}async runMiddlewareChain(e,t,n){for(let o=0;o<n.length;o++){let s=n[o];e.log.trace("running middleware",o,s),await new Promise((i,a)=>{try{let c=s(e,t,(l,u)=>{e=l,t=u,i()});c instanceof Promise&&c.catch(a)}catch(c){a(c)}}),e.log.trace("ran middleware",o,s)}return e}async close(e={}){if(this.log("closing connection to %a",this.remoteAddr),e.signal==null){let t=AbortSignal.timeout(this.closeTimeout);e={...e,signal:t}}await this.muxer?.close(e),await this.maConn.close(e)}abort(e){this.muxer?.abort(e),this.maConn.abort(e)}};function Tp(r,e){return new Pu(r,e)}function Hb(r,e){try{let{options:t}=e.getHandler(r);if(t.maxInboundStreams!=null)return t.maxInboundStreams}catch(t){if(t.name!=="UnhandledProtocolError")throw t}return Iu}function Wb(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.name!=="UnhandledProtocolError")throw n}return t.maxOutboundStreams??Tu}function Ip(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var aa=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;connectionCloseTimeout;constructor(e,t){this.components=e,this.connectionEncrypters=Ce({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),t.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=Ce({name:"libp2p_upgrader_stream_multiplexers",metrics:this.components.metrics}),t.streamMuxers.forEach(n=>{this.streamMuxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.connectionCloseTimeout=t.connectionCloseTimeout??1e3,this.events=e.events,this.metrics={dials:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total"),inboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_inbound_errors_total"),outboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_outbound_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,...t){let n=this.components.connectionGater[e];if(n==null)return;if(await n.apply(this.components.connectionGater,t)===!0)throw new Bi(`The multiaddr connection is blocked by gater.${e}`)}createInboundAbortSignal(e){let t=_t([AbortSignal.timeout(this.inboundUpgradeTimeout),e]);return t}async upgradeInbound(e,t){let n=!1,o=this.createInboundAbortSignal(t.signal);try{if(this.metrics.dials?.increment({inbound:!0}),n=this.components.connectionManager.acceptIncomingConnection(e),!n)throw new Fi("Connection denied");await $e(this.shouldBlockConnection("denyInboundConnection",e),o),await this._performUpgrade(e,"inbound",{...t,signal:o})}catch(s){throw this.metrics.errors?.increment({inbound:!0}),this.metrics.inboundErrors?.increment({[s.name??"Error"]:!0}),s}finally{o.clear(),n&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){try{this.metrics.dials?.increment({outbound:!0});let n=e.remoteAddr.getComponents().findLast(i=>i.code===421)?.value,o;n!=null&&(o=ut(n),await $e(this.shouldBlockConnection("denyOutboundConnection",o,e),t.signal));let s="outbound";return t.initiator===!1&&(s="inbound"),await this._performUpgrade(e,s,t)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),this.metrics.outboundErrors?.increment({[n.name??"Error"]:!0}),n}}async _performUpgrade(e,t,n){let o=e,s,i,a,c,l=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`;if(e.log=e.log.newScope(`${t}:${l}`),this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t),n?.skipProtection!==!0){let f=this.components.connectionProtector;f!=null&&(e.log("protecting the %s connection",t),o=await f.protect(o,n))}try{if(Gb(n)){if(n.remotePeer==null)throw new Lt(`${t} connection that skipped encryption must have a peer id`);c="native",s=n.remotePeer}else{let f=e.remoteAddr.getComponents().findLast(h=>h.code===421)?.value,d;f!=null&&(d=ut(f)),n?.onProgress?.(new de(`upgrader:encrypt-${t}-connection`)),{connection:o,remotePeer:s,protocol:c,streamMuxer:i}=await(t==="inbound"?this._encryptInbound(o,{...n,remotePeer:d}):this._encryptOutbound(o,{...n,remotePeer:d}))}if(s.equals(this.components.peerId)){let f=new Ir("Can not dial self");throw e.abort(f),f}await this.shouldBlockConnection(t==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,e),n?.muxerFactory!=null?i=n.muxerFactory:i==null&&this.streamMuxers.size>0&&(n?.onProgress?.(new de(`upgrader:multiplex-${t}-connection`)),i=await(t==="inbound"?this._multiplexInbound(o,this.streamMuxers,n):this._multiplexOutbound(o,this.streamMuxers,n)))}catch(f){throw e.log.error("failed to upgrade %s connection %s %a - %e",t,t==="inbound"?"from":"to",e.remoteAddr,f),f}i!=null&&(e.log("create muxer %s",i.protocol),a=i.createStreamMuxer(o)),await this.shouldBlockConnection(t==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,e);let u=this._createConnection({id:l,cryptoProtocol:c,direction:t,maConn:e,stream:o,muxer:a,remotePeer:s,limits:n?.limits,closeTimeout:this.connectionCloseTimeout});return u.log("successfully upgraded connection"),u}_createConnection(e){let t=Tp(this.components,{...e,outboundStreamProtocolNegotiationTimeout:this.outboundStreamProtocolNegotiationTimeout,inboundStreamProtocolNegotiationTimeout:this.inboundStreamProtocolNegotiationTimeout});return t.addEventListener("close",()=>{this.events.safeDispatchEvent("connection:close",{detail:t})}),this.events.safeDispatchEvent("connection:open",{detail:t}),t}async _encryptInbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{let o=await gn(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new _r(`no crypto module found for ${o}`);return e.log("encrypting inbound connection using %s",o),{...await s.secureInbound(e,t),protocol:o}}catch(o){throw new _r(o.message)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",n);let o=await mn(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new _r(`no crypto module found for ${o}`);return e.log("encrypting outbound connection using %s",o),{...await s.secureOutbound(e,t),protocol:o}}catch(o){throw new _r(o.message)}}async _multiplexOutbound(e,t,n){let o=Array.from(t.keys());e.log("outbound selecting muxer %s",o);try{e.log.trace("selecting stream muxer from %s",o);let s=await mn(e,o,n),i=t.get(s);if(i==null)throw new Ht(`No muxer configured for protocol "${s}"`);return e.log("selected %s as muxer protocol",s),i}catch(s){throw e.log.error("error multiplexing outbound connection - %e",s),new Ht(String(s))}}async _multiplexInbound(e,t,n){let o=Array.from(t.keys());e.log("inbound handling muxers %s",o);try{e.log.trace("selecting stream muxer from %s",o);let s=await gn(e,o,n),i=t.get(s);if(i==null)throw new Ht(`No muxer configured for protocol "${s}"`);return e.log("selected %s as muxer protocol",s),i}catch(s){throw e.log.error("error multiplexing inbound connection - %e",s),s}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}};function Gb(r){return r.skipEncryption===!0}var ca="3.1.7",la="js-libp2p";function Pp(r,e){return`${r??la}/${e??ca} browser/${globalThis.navigator.userAgent}`}var ko=class extends Le{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new Le,n=t.dispatchEvent.bind(t);t.dispatchEvent=l=>{let u=n(l),f=this.dispatchEvent(new CustomEvent(l.type,{detail:l.detail}));return u||f},this.peerId=e.peerId,this.logger=e.logger??ys(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=e.nodeInfo?.name??la,s=e.nodeInfo?.version??ca,i=this.components=sp({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:o,version:s,userAgent:e.nodeInfo?.userAgent??Pp(o,s)},logger:this.logger,events:t,datastore:e.datastore??new bi,connectionGater:ap(e.connectionGater),dns:e.dns});e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",zh(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),i.events.addEventListener("peer:update",l=>{if(l.detail.previous==null){let u={id:l.detail.peer.id,multiaddrs:l.detail.peer.addresses.map(f=>f.multiaddr)};i.events.safeDispatchEvent("peer:discovery",{detail:u})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new aa(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map((l,u)=>this.configureComponent(`connection-encryption-${u}`,l(this.components))),streamMuxers:(e.streamMuxers??[]).map((l,u)=>this.configureComponent(`stream-muxers-${u}`,l(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:e.connectionManager?.inboundStreamProtocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:e.connectionManager?.outboundStreamProtocolNegotiationTimeout,connectionCloseTimeout:e.connectionManager?.connectionCloseTimeout}),this.configureComponent("transportManager",new ia(this.components,e.transportManager)),this.configureComponent("connectionManager",new Ji(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new ea(this.components,e.connectionMonitor)),this.configureComponent("registrar",new sa(this.components)),this.configureComponent("addressManager",new Ti(this.components,e.addresses));let a=(e.peerRouters??[]).map((l,u)=>this.configureComponent(`peer-router-${u}`,l(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new na(this.components,{routers:a}));let c=(e.contentRouters??[]).map((l,u)=>this.configureComponent(`content-router-${u}`,l(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new ta(this.components,{routers:c})),this.configureComponent("randomWalk",new oa(this.components)),(e.peerDiscovery??[]).forEach((l,u)=>{this.configureComponent(`peer-discovery-${u}`,l(this.components)).addEventListener("peer",d=>{this.#e(d)})}),e.transports?.forEach((l,u)=>{this.components.transportManager.add(this.configureComponent(`transport-${u}`,l(this.components)))}),e.services!=null)for(let l of Object.keys(e.services)){let u=e.services[l],f=u(this.components);if(f==null){this.log.error("service factory %s returned null or undefined instance",l);continue}this.services[l]=f,this.configureComponent(l,f),f[da]!=null&&(this.log("registering service %s for content routing",l),c.push(f[da])),f[pa]!=null&&(this.log("registering service %s for peer routing",l),a.push(f[pa])),f[ha]!=null&&(this.log("registering service %s for peer discovery",l),f[ha].addEventListener?.("peer",d=>{this.#e(d)}))}ip(i)}configureComponent(e,t){return t==null&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started with peer id %p",this.peerId)}catch(e){throw this.log.error("an error occurred starting libp2p - %e",e),this.status="started",await this.stop(),e}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new ar;for(let t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,n={}){if(t==null)throw new I("no protocols were provided to open a stream");if(t=Array.isArray(t)?t:[t],t.length===0)throw new I("no protocols were provided to open a stream");return this.components.connectionManager.openStream(e,t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){zt(e)&&(e=ut(e.getComponents().findLast(n=>n.code===421)?.value??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;try{let i=await this.peerStore.get(e,t);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let n=Ze([L("/pk/"),e.toMultihash().bytes]),o=await this.contentRouting.get(n,t),s=Gr(o);return await this.peerStore.patch(e,{publicKey:s},t),s}async handle(e,t,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async o=>{await this.components.registrar.handle(o,t,n)}))}async unhandle(e,t){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async n=>{await this.components.registrar.unhandle(n,t)}))}async register(e,t,n){return this.components.registrar.register(e,t,n)}unregister(e){this.components.registrar.unregister(e)}use(e,t){this.components.registrar.use(e,Array.isArray(t)?t:[t])}unuse(e){this.components.registrar.unuse(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#e(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error("could not update multiaddrs of discovered peer - %e",n)})}};async function Yb(r={}){r.privateKey??=await Fd("Ed25519");let e=new ko({...await Vd(r),peerId:$d(r.privateKey)});return r.start!==!1&&await e.start(),e}var Xb=["dial","dialProtocol","hangUp","handle","unhandle","getMultiaddrs","getProtocols"];function jb(r){return r==null?!1:r instanceof ko?!0:Xb.every(e=>typeof r[e]=="function")}return Mp(Zb);})();
|
|
26
|
+
`),t),n('responded with "na" for "%s"',s)}}var Hu=class extends Le{id;remoteAddr;remotePeer;direction;timeline;direct;multiplexer;encryption;limits;log;maConn;muxer;components;outboundStreamProtocolNegotiationTimeout;inboundStreamProtocolNegotiationTimeout;closeTimeout;constructor(e,t){super(),this.components=e,this.id=t.id,this.remoteAddr=t.maConn.remoteAddr,this.remotePeer=t.remotePeer,this.direction=t.direction??"outbound",this.timeline=t.maConn.timeline,this.encryption=t.cryptoProtocol,this.limits=t.limits,this.maConn=t.maConn,this.log=t.maConn.log,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.closeTimeout=t.closeTimeout??1e3,this.direct=Su(t.maConn.remoteAddr),this.onIncomingStream=this.onIncomingStream.bind(this),this.remoteAddr.getComponents().find(n=>n.code===421)==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),t.muxer!=null&&(this.multiplexer=t.muxer.protocol,this.muxer=t.muxer,this.muxer.addEventListener("stream",this.onIncomingStream)),this.maConn.addEventListener("close",n=>{this.dispatchEvent(new Yo(n.local,n.error))})}[Symbol.toStringTag]="Connection";[ju]=!0;get streams(){return this.muxer?.streams??[]}get status(){return this.maConn.status}newStream=async(e,t={})=>{if(this.muxer==null)throw new Yt("Connection is not multiplexed");if(this.muxer.status!=="open")throw new jt(`The connection muxer is "${this.muxer.status}" and not "open"`);if(this.maConn.status!=="open")throw new jt(`The connection is "${this.status}" and not "open"`);if(this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new In("Cannot open protocol stream on limited connection");Array.isArray(e)||(e=[e]),t.onProgress?.(new J("connection:open-stream",{connection:this,protocols:e})),this.log.trace("starting new stream for protocols %s",e);let n=await this.muxer.createStream({...t,protocol:e.length===1?e[0]:void 0});this.log.trace("started new stream %s for protocols %s",n.id,e);try{if(t.signal==null){n.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",e);let c=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);t={...t,signal:c}}n.protocol===""?(n.log.trace("selecting protocol from protocols %s",e),n.protocol=await vn(n,e,t),n.log("negotiated protocol %s",n.protocol)):n.log("pre-negotiated protocol %s",n.protocol);let o=pw(n.protocol,this.components.registrar,t),s=Vp(n.protocol,"outbound",this);if(s>o){let c=new Go(`Too many outbound protocol streams for protocol "${n.protocol}" - ${s}/${o}`);throw n.abort(c),c}await this.components.peerStore.merge(this.remotePeer,{protocols:[n.protocol]}),this.components.metrics?.trackProtocolStream(n);let i=this.components.registrar.getMiddleware(n.protocol),a=await this.runMiddlewareChain(n,this,i);return t.onProgress?.(new J("connection:opened-stream",{connection:this,stream:a})),a}catch(o){throw n.status==="open"?n.abort(o):this.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",this.direction==="inbound"?"from":"to",this.remoteAddr,e,o),o}};async onIncomingStream(e){let t=e.detail,n=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);t.log("start protocol negotiation, timing out after %dms",this.inboundStreamProtocolNegotiationTimeout);try{if(t.protocol===""){let u=this.components.registrar.getProtocols();t.log.trace("selecting protocol from protocols %s",u),t.protocol=await Sn(t,u,{signal:n}),t.log("negotiated protocol %s",t.protocol)}else t.log("pre-negotiated protocol %s",t.protocol);let o=hw(t.protocol,this.components.registrar);if(Vp(t.protocol,"inbound",this)>o)throw new Wo(`Too many inbound protocol streams for protocol "${t.protocol}" - limit ${o}`);await this.components.peerStore.merge(this.remotePeer,{protocols:[t.protocol]},{signal:n}),this.components.metrics?.trackProtocolStream(t);let{handler:i,options:a}=this.components.registrar.getHandler(t.protocol);if(this.limits!=null&&a.runOnLimitedConnection!==!0)throw new In("Cannot open protocol stream on limited connection");let c=this.components.registrar.getMiddleware(t.protocol);c.push(async(u,l,f)=>{await i(u,l),f(u,l)}),await this.runMiddlewareChain(t,this,c)}catch(o){t.abort(o)}}async runMiddlewareChain(e,t,n){for(let o=0;o<n.length;o++){let s=n[o];e.log.trace("running middleware",o,s),await new Promise((i,a)=>{try{let c=s(e,t,(u,l)=>{e=u,t=l,i()});c instanceof Promise&&c.catch(a)}catch(c){a(c)}}),e.log.trace("ran middleware",o,s)}return e}async close(e={}){if(this.log("closing connection to %a",this.remoteAddr),e.signal==null){let t=AbortSignal.timeout(this.closeTimeout);e={...e,signal:t}}await this.muxer?.close(e),await this.maConn.close(e)}abort(e){this.muxer?.abort(e),this.maConn.abort(e)}};function zp(r,e){return new Hu(r,e)}function hw(r,e){try{let{options:t}=e.getHandler(r);if(t.maxInboundStreams!=null)return t.maxInboundStreams}catch(t){if(t.name!=="UnhandledProtocolError")throw t}return $u}function pw(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.name!=="UnhandledProtocolError")throw n}return t.maxOutboundStreams??Vu}function Vp(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var ga=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;connectionCloseTimeout;constructor(e,t){this.components=e,this.connectionEncrypters=Ie({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),t.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=Ie({name:"libp2p_upgrader_stream_multiplexers",metrics:this.components.metrics}),t.streamMuxers.forEach(n=>{this.streamMuxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.connectionCloseTimeout=t.connectionCloseTimeout??1e3,this.events=e.events,this.metrics={dials:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total"),inboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_inbound_errors_total"),outboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_outbound_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,...t){let n=this.components.connectionGater[e];if(n==null)return;if(await n.apply(this.components.connectionGater,t)===!0)throw new Hi(`The multiaddr connection is blocked by gater.${e}`)}createInboundAbortSignal(e){let t=At([AbortSignal.timeout(this.inboundUpgradeTimeout),e]);return t}async upgradeInbound(e,t){let n=!1,o=this.createInboundAbortSignal(t.signal);try{if(this.metrics.dials?.increment({inbound:!0}),n=this.components.connectionManager.acceptIncomingConnection(e),!n)throw new Wi("Connection denied");await $e(this.shouldBlockConnection("denyInboundConnection",e),o),await this._performUpgrade(e,"inbound",{...t,signal:o})}catch(s){throw this.metrics.errors?.increment({inbound:!0}),this.metrics.inboundErrors?.increment({[s.name??"Error"]:!0}),s}finally{o.clear(),n&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){try{this.metrics.dials?.increment({outbound:!0});let n=e.remoteAddr.getComponents().findLast(i=>i.code===421)?.value,o;n!=null&&(o=ut(n),await $e(this.shouldBlockConnection("denyOutboundConnection",o,e),t.signal));let s="outbound";return t.initiator===!1&&(s="inbound"),await this._performUpgrade(e,s,t)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),this.metrics.outboundErrors?.increment({[n.name??"Error"]:!0}),n}}async _performUpgrade(e,t,n){let o=e,s,i,a,c,u=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`;if(e.log=e.log.newScope(`${t}:${u}`),this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t),n?.skipProtection!==!0){let f=this.components.connectionProtector;f!=null&&(e.log("protecting the %s connection",t),o=await f.protect(o,n))}try{if(mw(n)){if(n.remotePeer==null)throw new Dt(`${t} connection that skipped encryption must have a peer id`);c="native",s=n.remotePeer}else{let f=e.remoteAddr.getComponents().findLast(h=>h.code===421)?.value,d;f!=null&&(d=ut(f)),n?.onProgress?.(new J(`upgrader:encrypt-${t}-connection`)),{connection:o,remotePeer:s,protocol:c,streamMuxer:i}=await(t==="inbound"?this._encryptInbound(o,{...n,remotePeer:d}):this._encryptOutbound(o,{...n,remotePeer:d}))}if(s.equals(this.components.peerId)){let f=new Lr("Can not dial self");throw e.abort(f),f}await this.shouldBlockConnection(t==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,e),n?.muxerFactory!=null?i=n.muxerFactory:i==null&&this.streamMuxers.size>0&&(n?.onProgress?.(new J(`upgrader:multiplex-${t}-connection`)),i=await(t==="inbound"?this._multiplexInbound(o,this.streamMuxers,n):this._multiplexOutbound(o,this.streamMuxers,n)))}catch(f){throw e.log.error("failed to upgrade %s connection %s %a - %e",t,t==="inbound"?"from":"to",e.remoteAddr,f),f}i!=null&&(e.log("create muxer %s",i.protocol),a=i.createStreamMuxer(o)),await this.shouldBlockConnection(t==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,e);let l=this._createConnection({id:u,cryptoProtocol:c,direction:t,maConn:e,stream:o,muxer:a,remotePeer:s,limits:n?.limits,closeTimeout:this.connectionCloseTimeout});return l.log("successfully upgraded connection"),l}_createConnection(e){let t=zp(this.components,{...e,outboundStreamProtocolNegotiationTimeout:this.outboundStreamProtocolNegotiationTimeout,inboundStreamProtocolNegotiationTimeout:this.inboundStreamProtocolNegotiationTimeout});return t.addEventListener("close",()=>{this.events.safeDispatchEvent("connection:close",{detail:t})}),this.events.safeDispatchEvent("connection:open",{detail:t}),t}async _encryptInbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{let o=await Sn(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new Ir(`no crypto module found for ${o}`);return e.log("encrypting inbound connection using %s",o),{...await s.secureInbound(e,t),protocol:o}}catch(o){throw new Ir(o.message)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",n);let o=await vn(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new Ir(`no crypto module found for ${o}`);return e.log("encrypting outbound connection using %s",o),{...await s.secureOutbound(e,t),protocol:o}}catch(o){throw new Ir(o.message)}}async _multiplexOutbound(e,t,n){let o=Array.from(t.keys());e.log("outbound selecting muxer %s",o);try{e.log.trace("selecting stream muxer from %s",o);let s=await vn(e,o,n),i=t.get(s);if(i==null)throw new Yt(`No muxer configured for protocol "${s}"`);return e.log("selected %s as muxer protocol",s),i}catch(s){throw e.log.error("error multiplexing outbound connection - %e",s),new Yt(String(s))}}async _multiplexInbound(e,t,n){let o=Array.from(t.keys());e.log("inbound handling muxers %s",o);try{e.log.trace("selecting stream muxer from %s",o);let s=await Sn(e,o,n),i=t.get(s);if(i==null)throw new Yt(`No muxer configured for protocol "${s}"`);return e.log("selected %s as muxer protocol",s),i}catch(s){throw e.log.error("error multiplexing inbound connection - %e",s),s}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}};function mw(r){return r.skipEncryption===!0}var ya="3.2.0-b30baa93a",ba="js-libp2p";function Wp(r,e){return`${r??ba}/${e??ya} browser/${globalThis.navigator.userAgent}`}var Fo=class extends Le{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new Le,n=t.dispatchEvent.bind(t);t.dispatchEvent=u=>{let l=n(u),f=this.dispatchEvent(new CustomEvent(u.type,{detail:u.detail}));return l||f},this.peerId=e.peerId,this.logger=e.logger??Ss(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=e.nodeInfo?.name??ba,s=e.nodeInfo?.version??ya,i=this.components=vp({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:o,version:s,userAgent:e.nodeInfo?.userAgent??Wp(o,s)},logger:this.logger,events:t,datastore:e.datastore??new Ii,connectionGater:_p(e.connectionGater),dns:e.dns});e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",ap(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),i.events.addEventListener("peer:update",u=>{if(u.detail.previous==null){let l={id:u.detail.peer.id,multiaddrs:u.detail.peer.addresses.map(f=>f.multiaddr)};i.events.safeDispatchEvent("peer:discovery",{detail:l})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new ga(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map((u,l)=>this.configureComponent(`connection-encryption-${l}`,u(this.components))),streamMuxers:(e.streamMuxers??[]).map((u,l)=>this.configureComponent(`stream-muxers-${l}`,u(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:e.connectionManager?.inboundStreamProtocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:e.connectionManager?.outboundStreamProtocolNegotiationTimeout,connectionCloseTimeout:e.connectionManager?.connectionCloseTimeout}),this.configureComponent("transportManager",new ma(this.components,e.transportManager)),this.configureComponent("connectionManager",new ca(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new la(this.components,e.connectionMonitor)),this.configureComponent("registrar",new pa(this.components)),this.configureComponent("addressManager",new Mi(this.components,e.addresses));let a=(e.peerRouters??[]).map((u,l)=>this.configureComponent(`peer-router-${l}`,u(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new da(this.components,{routers:a}));let c=(e.contentRouters??[]).map((u,l)=>this.configureComponent(`content-router-${l}`,u(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new ua(this.components,{routers:c})),this.configureComponent("randomWalk",new ha(this.components)),(e.peerDiscovery??[]).forEach((u,l)=>{this.configureComponent(`peer-discovery-${l}`,u(this.components)).addEventListener("peer",d=>{this.#e(d)})}),e.transports?.forEach((u,l)=>{this.components.transportManager.add(this.configureComponent(`transport-${l}`,u(this.components)))}),e.services!=null)for(let u of Object.keys(e.services)){let l=e.services[u],f=l(this.components);if(f==null){this.log.error("service factory %s returned null or undefined instance",u);continue}this.services[u]=f,this.configureComponent(u,f),f[xa]!=null&&(this.log("registering service %s for content routing",u),c.push(f[xa])),f[va]!=null&&(this.log("registering service %s for peer routing",u),a.push(f[va])),f[Ea]!=null&&(this.log("registering service %s for peer discovery",u),f[Ea].addEventListener?.("peer",d=>{this.#e(d)}))}Sp(i)}configureComponent(e,t){return t==null&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started with peer id %p",this.peerId)}catch(e){throw this.log.error("an error occurred starting libp2p - %e",e),this.status="started",await this.stop(),e}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new ur;for(let t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,n={}){if(t==null)throw new C("no protocols were provided to open a stream");if(t=Array.isArray(t)?t:[t],t.length===0)throw new C("no protocols were provided to open a stream");return this.components.connectionManager.openStream(e,t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){Gt(e)&&(e=ut(e.getComponents().findLast(n=>n.code===421)?.value??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;try{let i=await this.peerStore.get(e,t);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let n=Ze([L("/pk/"),e.toMultihash().bytes]),o=await this.contentRouting.get(n,t),s=jr(o);return await this.peerStore.patch(e,{publicKey:s},t),s}async handle(e,t,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async o=>{await this.components.registrar.handle(o,t,n)}))}async unhandle(e,t){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async n=>{await this.components.registrar.unhandle(n,t)}))}async register(e,t,n){return this.components.registrar.register(e,t,n)}unregister(e){this.components.registrar.unregister(e)}use(e,t){this.components.registrar.use(e,Array.isArray(t)?t:[t])}unuse(e){this.components.registrar.unuse(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#e(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error("could not update multiaddrs of discovered peer - %e",n)})}};async function gw(r={}){r.privateKey??=await Jd("Ed25519");let e=new Fo({...await oh(r),peerId:nh(r.privateKey)});return r.start!==!1&&await e.start(),e}var yw=["dial","dialProtocol","hangUp","handle","unhandle","getMultiaddrs","getProtocols"];function bw(r){return r==null?!1:r instanceof Fo?!0:yw.every(e=>typeof r[e]=="function")}return Qp(ww);})();
|
|
27
27
|
/*! Bundled license information:
|
|
28
28
|
|
|
29
29
|
@noble/hashes/utils.js:
|