@libp2p/autonat-v2 2.0.15-90100be0c → 2.0.15-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 +1 -1
- package/dist/index.min.js.map +3 -3
- package/package.json +9 -9
package/dist/index.min.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
(function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Libp2PAutonatV2 = factory()}(typeof self !== 'undefined' ? self : this, function () {
|
|
2
|
-
"use strict";var Libp2PAutonatV2=(()=>{var kc=Object.create;var Nr=Object.defineProperty;var Pc=Object.getOwnPropertyDescriptor;var Oc=Object.getOwnPropertyNames;var Nc=Object.getPrototypeOf,Uc=Object.prototype.hasOwnProperty;var zn=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),bt=(r,t)=>{for(var e in t)Nr(r,e,{get:t[e],enumerable:!0})},js=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Oc(t))!Uc.call(r,o)&&o!==e&&Nr(r,o,{get:()=>t[o],enumerable:!(n=Pc(t,o))||n.enumerable});return r};var Mc=(r,t,e)=>(e=r!=null?kc(Nc(r)):{},js(t||!r||!r.__esModule?Nr(e,"default",{value:r,enumerable:!0}):e,r)),Kc=r=>js(Nr({},"__esModule",{value:!0}),r);var Ss=zn(Ve=>{"use strict";Object.defineProperty(Ve,"__esModule",{value:!0});Ve.Netmask4Impl=void 0;Ve.ip2long=ze;Ve.long2ip=Rt;function Rt(r){let t=(r&-16777216)>>>24,e=(r&255<<16)>>>16,n=(r&65280)>>>8,o=r&255;return[t,e,n,o].join(".")}var gl=48,bl=97,yl=65;function xl(r){let t=0,e=10,n="9",o=0;r.length>1&&r[o]==="0"&&(r[o+1]==="x"||r[o+1]==="X"?(o+=2,e=16):"0"<=r[o+1]&&r[o+1]<="9"&&(o++,e=8,n="7"));let s=o;for(;o<r.length;){if("0"<=r[o]&&r[o]<=n)t=t*e+(r.charCodeAt(o)-gl)>>>0;else if(e===16)if("a"<=r[o]&&r[o]<="f")t=t*e+(10+r.charCodeAt(o)-bl)>>>0;else if("A"<=r[o]&&r[o]<="F")t=t*e+(10+r.charCodeAt(o)-yl)>>>0;else break;else break;if(t>4294967295)throw new Error("too large");o++}if(o===s)throw new Error("empty octet");return[t,o]}function ze(r){let t=[];for(let e=0;e<=3&&r.length!==0;e++){if(e>0){if(r[0]!==".")throw new Error("Invalid IP");r=r.substring(1)}let[n,o]=xl(r);r=r.substring(o),t.push(n)}if(r.length!==0)throw new Error("Invalid IP");switch(t.length){case 1:if(t[0]>4294967295)throw new Error("Invalid IP");return t[0]>>>0;case 2:if(t[0]>255||t[1]>16777215)throw new Error("Invalid IP");return(t[0]<<24|t[1])>>>0;case 3:if(t[0]>255||t[1]>255||t[2]>65535)throw new Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2])>>>0;case 4:if(t[0]>255||t[1]>255||t[2]>255||t[3]>255)throw new Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2]<<8|t[3])>>>0;default:throw new Error("Invalid IP")}}var Es=class r{constructor(t,e){if(typeof t!="string")throw new Error("Missing `net' parameter");let n=e;if(!n){let o=t.split("/",2);t=o[0],n=o[1]}if(n||(n=32),typeof n=="string"&&n.indexOf(".")>-1){try{this.maskLong=ze(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=(ze(t)&this.maskLong)>>>0}catch{throw new Error("Invalid net address: "+t)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+n);this.size=Math.pow(2,32-this.bitmask),this.base=Rt(this.netLong),this.mask=Rt(this.maskLong),this.hostmask=Rt(~this.maskLong),this.first=this.bitmask<=30?Rt(this.netLong+1):this.base,this.last=this.bitmask<=30?Rt(this.netLong+this.size-2):Rt(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?Rt(this.netLong+this.size-1):void 0}contains(t){return typeof t=="string"&&(t.indexOf("/")>0||t.split(".").length!==4)&&(t=new r(t)),t instanceof r?this.contains(t.base)&&this.contains(t.broadcast||t.last):(ze(t)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0}next(t=1){return new r(Rt(this.netLong+this.size*t),this.mask)}forEach(t){let e=ze(this.first),n=ze(this.last),o=0;for(;e<=n;)t(Rt(e),e,o),o++,e++}toString(){return this.base+"/"+this.bitmask}};Ve.Netmask4Impl=Es});var rc=zn(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.Netmask6Impl=void 0;He.ip6bigint=_s;He.bigint2ip6=xe;var wl=Ss(),vs=(1n<<128n)-1n;function _s(r){let t=r.indexOf("%");t!==-1&&(r=r.substring(0,t));let e=r.lastIndexOf(":");if(e!==-1&&r.indexOf(".",e)!==-1){let n=r.substring(e+1),o=(0,wl.ip2long)(n),s=r.substring(0,e+1)+"0:0";return ec(s)&~0xffffffffn|BigInt(o)}return ec(r)}function ec(r){let t=r.indexOf("::"),e;if(t!==-1){let o=r.substring(0,t),s=r.substring(t+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");e=[...i,...Array(c).fill("0"),...a]}else e=r.split(":");if(e.length!==8)throw new Error("Invalid IPv6: expected 8 groups, got "+e.length);let n=0n;for(let o=0;o<8;o++){let s=e[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 xe(r){if(r<0n||r>vs)throw new Error("Invalid IPv6 address value");let t=[];for(let i=0;i<8;i++)t.unshift(Number(r&0xffffn)),r>>=16n;let e=-1,n=0,o=-1,s=0;for(let i=0;i<8;i++)t[i]===0?o===-1?(o=i,s=1):s++:(s>n&&s>=2&&(e=o,n=s),o=-1,s=0);if(s>n&&s>=2&&(e=o,n=s),e!==-1&&e+n===8&&e>0)return t.slice(0,e).map(a=>a.toString(16)).join(":")+"::";if(e===0)return"::"+t.slice(n).map(a=>a.toString(16)).join(":");if(e>0){let i=t.slice(0,e).map(c=>c.toString(16)),a=t.slice(e+n).map(c=>c.toString(16));return i.join(":")+"::"+a.join(":")}else return t.map(i=>i.toString(16)).join(":")}var Is=class r{constructor(t,e){if(typeof t!="string")throw new Error("Missing `net' parameter");let n=e;if(n==null){let o=t.indexOf("/");o!==-1?(n=parseInt(t.substring(o+1),10),t=t.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=vs>>BigInt(128-this.bitmask)<<BigInt(128-this.bitmask);try{this.netBigint=_s(t)&this.maskBigint}catch{throw new Error("Invalid IPv6 net address: "+t)}this.size=Number(1n<<BigInt(128-this.bitmask)),this.base=xe(this.netBigint),this.mask=xe(this.maskBigint),this.hostmask=xe(~this.maskBigint&vs),this.first=this.base,this.last=xe(this.netBigint+(1n<<BigInt(128-this.bitmask))-1n),this.broadcast=void 0}contains(t){return typeof t=="string"&&t.indexOf("/")>0&&(t=new r(t)),t instanceof r?this.contains(t.base)&&this.contains(t.last):(_s(t)&this.maskBigint)===this.netBigint}next(t=1){let e=1n<<BigInt(128-this.bitmask);return new r(xe(this.netBigint+e*BigInt(t)),this.bitmask)}forEach(t){let e=this.netBigint,n=1n<<BigInt(128-this.bitmask),o=this.netBigint+n-1n,s=0;for(;e<=o;)t(xe(e),Number(e),s),s++,e++}toString(){return this.base+"/"+this.bitmask}};He.Netmask6Impl=Is});var nc=zn(re=>{"use strict";Object.defineProperty(re,"__esModule",{value:!0});re.long2ip=re.ip2long=re.Netmask=void 0;var _n=Ss();Object.defineProperty(re,"ip2long",{enumerable:!0,get:function(){return _n.ip2long}});Object.defineProperty(re,"long2ip",{enumerable:!0,get:function(){return _n.long2ip}});var El=rc(),As=class r{constructor(t,e){if(typeof t!="string")throw new Error("Missing `net' parameter");(t.indexOf("/")!==-1?t.substring(0,t.indexOf("/")):t).indexOf(":")!==-1?this._impl=new El.Netmask6Impl(t,e):this._impl=new _n.Netmask4Impl(t,e),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 _n.Netmask4Impl?(this.maskLong=this._impl.maskLong,this.netLong=this._impl.netLong):(this.maskLong=0,this.netLong=0)}contains(t){return typeof t=="string"&&(t.indexOf("/")>0?t=new r(t):t.indexOf(":")===-1&&t.split(".").length!==4&&(t=new r(t))),t instanceof r?this.contains(t.base)&&this.contains(t.broadcast||t.last):this._impl.contains(t)}next(t=1){let e=this._impl.next(t);return new r(e.base,e.bitmask)}forEach(t){this._impl.forEach(t)}toString(){return this._impl.toString()}};re.Netmask=As});var Md={};bt(Md,{autoNATv2:()=>Ud});var Pt=class extends Error{static name="AbortError";constructor(t="The operation was aborted"){super(t),this.name="AbortError"}};var ft=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},Ur=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}};var Mr=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}};var wt=class extends Error{static name="ProtocolError";constructor(t="Protocol error"){super(t),this.name="ProtocolError"}};var Qe=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var Vn=Symbol.for("@libp2p/peer-id");function Xs(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function Ws(...r){let t=[];for(let e of r)Xs(e)&&t.push(e);await Promise.all(t.map(async e=>{e.beforeStart!=null&&await e.beforeStart()})),await Promise.all(t.map(async e=>{await e.start()})),await Promise.all(t.map(async e=>{e.afterStart!=null&&await e.afterStart()}))}async function Qs(...r){let t=[];for(let e of r)Xs(e)&&t.push(e);await Promise.all(t.map(async e=>{e.beforeStop!=null&&await e.beforeStop()})),await Promise.all(t.map(async e=>{await e.stop()})),await Promise.all(t.map(async e=>{e.afterStop!=null&&await e.afterStop()}))}var Kr=class extends EventTarget{#t=new Map;constructor(){super()}listenerCount(t){let e=this.#t.get(t);return e==null?0:e.length}addEventListener(t,e,n){super.addEventListener(t,e,n);let o=this.#t.get(t);o==null&&(o=[],this.#t.set(t,o)),o.push({callback:e,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(t,e,n){super.removeEventListener(t.toString(),e??null,n);let o=this.#t.get(t);o!=null&&(o=o.filter(({callback:s})=>s!==e),this.#t.set(t,o))}dispatchEvent(t){let e=super.dispatchEvent(t),n=this.#t.get(t.type);return n==null||(n=n.filter(({once:o})=>!o),this.#t.set(t.type,n)),e}safeDispatchEvent(t,e={}){return this.dispatchEvent(new CustomEvent(t,e))}};var qr=Symbol.for("@libp2p/service-capabilities"),Fr=Symbol.for("@libp2p/service-dependencies");var Yn={};bt(Yn,{base58btc:()=>j,base58flickr:()=>Gc});var mh=new Uint8Array(0);function Js(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function Ot(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 ti(r){return new TextEncoder().encode(r)}function ei(r){return new TextDecoder().decode(r)}function qc(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(e[i]!==255)throw new TypeError(s+" is ambiguous");e[i]=o}var a=r.length,c=r.charAt(0),u=Math.log(a)/Math.log(256),f=Math.log(256)/Math.log(a);function l(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var v=0,x=0,b=0,I=h.length;b!==I&&h[b]===0;)b++,v++;for(var w=(I-b)*f+1>>>0,A=new Uint8Array(w);b!==I;){for(var k=h[b],U=0,M=w-1;(k!==0||U<x)&&M!==-1;M--,U++)k+=256*A[M]>>>0,A[M]=k%a>>>0,k=k/a>>>0;if(k!==0)throw new Error("Non-zero carry");x=U,b++}for(var S=w-x;S!==w&&A[S]===0;)S++;for(var E=c.repeat(v);S<w;++S)E+=r.charAt(A[S]);return E}function d(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var v=0;if(h[v]!==" "){for(var x=0,b=0;h[v]===c;)x++,v++;for(var I=(h.length-v)*u+1>>>0,w=new Uint8Array(I);h[v];){var A=e[h.charCodeAt(v)];if(A===255)return;for(var k=0,U=I-1;(A!==0||k<b)&&U!==-1;U--,k++)A+=a*w[U]>>>0,w[U]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");b=k,v++}if(h[v]!==" "){for(var M=I-b;M!==I&&w[M]===0;)M++;for(var S=new Uint8Array(x+(I-M)),E=x;M!==I;)S[E++]=w[M++];return S}}}function y(h){var v=d(h);if(v)return v;throw new Error(`Non-${t} character`)}return{encode:l,decodeUnsafe:d,decode:y}}var Fc=qc,zc=Fc,ni=zc;var Hn=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},$n=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){this.name=t,this.prefix=e;let o=e.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return oi(this,t)}},Gn=class{decoders;constructor(t){this.decoders=t}or(t){return oi(this,t)}decode(t){let e=t[0],n=this.decoders[e];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function oi(r,t){return new Gn({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var Zn=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,o){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=o,this.encoder=new Hn(t,e,n),this.decoder=new $n(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Se({name:r,prefix:t,encode:e,decode:n}){return new Zn(r,t,e,n)}function Gt({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=ni(e,r);return Se({prefix:t,name:r,encode:n,decode:s=>Ot(o(s))})}function Vc(r,t,e,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*e/8|0),i=0,a=0,c=0;for(let u=0;u<o;++u){let f=t[r[u]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<e|f,i+=e,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=e||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function Hc(r,t,e){let n=t[t.length-1]==="=",o=(1<<e)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>e;)i-=e,s+=t[o&a>>i];if(i!==0&&(s+=t[o&a<<e-i]),n)for(;(s.length*e&7)!==0;)s+="=";return s}function $c(r){let t={};for(let e=0;e<r.length;++e)t[r[e]]=e;return t}function Y({name:r,prefix:t,bitsPerChar:e,alphabet:n}){let o=$c(n);return Se({prefix:t,name:r,encode(s){return Hc(s,n,e)},decode(s){return Vc(s,o,e,r)}})}var j=Gt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Gc=Gt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var jn={};bt(jn,{base32:()=>Zt,base32hex:()=>Xc,base32hexpad:()=>Qc,base32hexpadupper:()=>Jc,base32hexupper:()=>Wc,base32pad:()=>Yc,base32padupper:()=>jc,base32upper:()=>Zc,base32z:()=>tu});var Zt=Y({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Zc=Y({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Yc=Y({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),jc=Y({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Xc=Y({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Wc=Y({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Qc=Y({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Jc=Y({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),tu=Y({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Xn={};bt(Xn,{base36:()=>Je,base36upper:()=>eu});var Je=Gt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),eu=Gt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var ru=ai,si=128,nu=127,ou=~nu,su=Math.pow(2,31);function ai(r,t,e){t=t||[],e=e||0;for(var n=e;r>=su;)t[e++]=r&255|si,r/=128;for(;r&ou;)t[e++]=r&255|si,r>>>=7;return t[e]=r|0,ai.bytes=e-n+1,t}var iu=Wn,au=128,ii=127;function Wn(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw Wn.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&ii)<<o:(i&ii)*Math.pow(2,o),o+=7}while(i>=au);return Wn.bytes=s-n,e}var cu=Math.pow(2,7),uu=Math.pow(2,14),fu=Math.pow(2,21),lu=Math.pow(2,28),du=Math.pow(2,35),hu=Math.pow(2,42),pu=Math.pow(2,49),mu=Math.pow(2,56),gu=Math.pow(2,63),bu=function(r){return r<cu?1:r<uu?2:r<fu?3:r<lu?4:r<du?5:r<hu?6:r<pu?7:r<mu?8:r<gu?9:10},yu={encode:ru,decode:iu,encodingLength:bu},xu=yu,tr=xu;function er(r,t=0){return[tr.decode(r,t),tr.decode.bytes]}function ve(r,t,e=0){return tr.encode(r,t,e),t}function _e(r){return tr.encodingLength(r)}function Ae(r,t){let e=t.byteLength,n=_e(r),o=n+_e(e),s=new Uint8Array(o+e);return ve(r,s,0),ve(e,s,n),s.set(t,o),new Ie(r,e,t,s)}function rr(r){let t=Ot(r),[e,n]=er(t),[o,s]=er(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Ie(e,o,i,t)}function ci(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&Js(r.bytes,e.bytes)}}var Ie=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};function ui(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return Eu(e,Qn(r),t??j.encoder);default:return Su(e,Qn(r),t??Zt.encoder)}}var fi=new WeakMap;function Qn(r){let t=fi.get(r);if(t==null){let e=new Map;return fi.set(r,e),e}return t}var at=class r{code;version;multihash;bytes;"/";constructor(t,e,n,o){this.code=e,this.version=t,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:t,multihash:e}=this;if(t!==nr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==vu)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}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:t,digest:e}=this.multihash,n=Ae(t,e);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(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&ci(t.multihash,n.multihash)}toString(t){return ui(this,t)}toJSON(){return{"/":ui(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:o,multihash:s,bytes:i}=e;return new r(n,o,s,i??li(n,o,s.bytes))}else if(e[_u]===!0){let{version:n,multihash:o,code:s}=e,i=rr(o);return r.create(n,s,i)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==nr)throw new Error(`Version 0 CID must use dag-pb (code: ${nr}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=li(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,nr,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,o=Ot(t.subarray(n,n+e.multihashSize));if(o.byteLength!==e.multihashSize)throw new Error("Incorrect length");let s=o.subarray(e.multihashSize-e.digestSize),i=new Ie(e.multihashCode,e.digestSize,s,o);return[e.version===0?r.createV0(i):r.createV1(e.codec,i),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[l,d]=er(t.subarray(e));return e+=d,l},o=n(),s=nr;if(o===18?(o=0,e=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=e,a=n(),c=n(),u=e+c,f=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:f,size:u}}static parse(t,e){let[n,o]=wu(t,e),s=r.decode(o);if(s.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Qn(s).set(n,t),s}};function wu(r,t){switch(r[0]){case"Q":{let e=t??j;return[j.prefix,e.decode(`${j.prefix}${r}`)]}case j.prefix:{let e=t??j;return[j.prefix,e.decode(r)]}case Zt.prefix:{let e=t??Zt;return[Zt.prefix,e.decode(r)]}case Je.prefix:{let e=t??Je;return[Je.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function Eu(r,t,e){let{prefix:n}=e;if(n!==j.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let o=t.get(n);if(o==null){let s=e.encode(r).slice(1);return t.set(n,s),s}else return o}function Su(r,t,e){let{prefix:n}=e,o=t.get(n);if(o==null){let s=e.encode(r);return t.set(n,s),s}else return o}var nr=112,vu=18;function li(r,t,e){let n=_e(r),o=n+_e(t),s=new Uint8Array(o+e.byteLength);return ve(r,s,0),ve(t,s,n),s.set(e,o),s}var _u=Symbol.for("@ipld/js-cid/CID");var Jn={};bt(Jn,{identity:()=>It});var di=0,Iu="identity",hi=Ot;function Au(r,t){if(t?.truncate!=null&&t.truncate!==r.byteLength){if(t.truncate<0||t.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t.truncate)}return Ae(di,hi(r))}var It={code:di,name:Iu,encode:hi,digest:Au};function lt(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function yt(r=0){return new Uint8Array(r)}function pt(r=0){return new Uint8Array(r)}function Nt(r,t){t==null&&(t=r.reduce((o,s)=>o+s.length,0));let e=pt(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}var mi=Symbol.for("@achingbrain/uint8arraylist");function pi(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let o=e+n.byteLength;if(t<o)return{buf:n,index:t-e};e=o}throw new RangeError("index is out of bounds")}function Vr(r){return!!r?.[mi]}var Q=class r{bufs;length;[mi]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let n of t)if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.push(n);else if(Vr(n))e+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let n of t.reverse())if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.unshift(n);else if(Vr(n))e+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=pi(this.bufs,t);return e.buf[e.index]}set(t,e){let n=pi(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else if(Vr(t))for(let n=0;n<t.length;n++)this.set(e+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:n,length:o}=this._subList(t,e);return Nt(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:Nt(n,o)}sublist(t,e){let{bufs:n,length:o}=this._subList(t,e),s=new r;return s.length=o,s.bufs=[...n],s}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===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,t>=c)continue;let u=t>=a&&t<c,f=e>a&&e<=c;if(u&&f){if(t===a&&e===c){n.push(i);break}let l=t-a;n.push(i.subarray(l,l+(e-t)));break}if(u){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(f){if(e===c){n.push(i);break}n.push(i.subarray(0,e-a));break}n.push(i)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!Vr(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;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 l=0;l<s;l++)i[l]=-1;for(let l=0;l<o;l++)i[n[l]]=l;let a=i,c=this.byteLength-n.byteLength,u=n.byteLength-1,f;for(let l=e;l<=c;l+=f){f=0;for(let d=u;d>=0;d--){let y=this.get(l+d);if(n[d]!==y){f=Math.max(1,d-a[y]);break}}if(f===0)return l}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=pt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let o=yt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,e,n),this.write(o,t)}getInt32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){let o=yt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,e,n),this.write(o,t)}getBigInt64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){let o=yt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,e,n),this.write(o,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let n=pt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let o=yt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,e,n),this.write(o,t)}getUint32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){let o=yt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,e,n),this.write(o,t)}getBigUint64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){let o=yt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,e,n),this.write(o,t)}getFloat32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){let o=yt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,e,n),this.write(o,t)}getFloat64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){let o=yt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,e,n),this.write(o,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!lt(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((o,s)=>o+s.byteLength,0)),n.length=e,n}};var to={};bt(to,{base10:()=>Bu});var Bu=Gt({prefix:"9",name:"base10",alphabet:"0123456789"});var eo={};bt(eo,{base16:()=>Du,base16upper:()=>Lu});var Du=Y({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Lu=Y({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var ro={};bt(ro,{base2:()=>Cu});var Cu=Y({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var no={};bt(no,{base256emoji:()=>Ou});var gi=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}"),Tu=gi.reduce((r,t,e)=>(r[e]=t,r),[]),Ru=gi.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function ku(r){return r.reduce((t,e)=>(t+=Tu[e],t),"")}function Pu(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=Ru[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var Ou=Se({prefix:"\u{1F680}",name:"base256emoji",encode:ku,decode:Pu});var so={};bt(so,{base64:()=>Nu,base64pad:()=>Uu,base64url:()=>oo,base64urlpad:()=>Mu});var Nu=Y({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Uu=Y({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),oo=Y({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Mu=Y({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var io={};bt(io,{base8:()=>Ku});var Ku=Y({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var ao={};bt(ao,{identity:()=>qu});var qu=Se({prefix:"\0",name:"identity",encode:r=>ei(r),decode:r=>ti(r)});var Qh=new TextEncoder,Jh=new TextDecoder;var fo={};bt(fo,{sha256:()=>or,sha512:()=>Hu});var Vu=20;function uo({name:r,code:t,encode:e,minDigestLength:n,maxDigestLength:o}){return new co(r,t,e,n,o)}var co=class{name;code;encode;minDigestLength;maxDigestLength;constructor(t,e,n,o,s){this.name=t,this.code=e,this.encode=n,this.minDigestLength=o??Vu,this.maxDigestLength=s}digest(t,e){if(e?.truncate!=null){if(e.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&e.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(t instanceof Uint8Array){let n=this.encode(t);return n instanceof Uint8Array?bi(n,this.code,e?.truncate):n.then(o=>bi(o,this.code,e?.truncate))}else throw Error("Unknown type, must be binary type")}};function bi(r,t,e){if(e!=null&&e!==r.byteLength){if(e>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e)}return Ae(t,r)}function xi(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var or=uo({name:"sha2-256",code:18,encode:xi("SHA-256")}),Hu=uo({name:"sha2-512",code:19,encode:xi("SHA-512")});var sr={...ao,...ro,...io,...to,...eo,...jn,...Xn,...Yn,...so,...no},l0={...fo,...Jn};function Ei(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var wi=Ei("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),lo=Ei("ascii","a",r=>{let t="a";for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return t},r=>{r=r.substring(1);let t=pt(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),$u={utf8:wi,"utf-8":wi,hex:sr.base16,latin1:lo,ascii:lo,binary:lo,...sr},Hr=$u;function H(r,t="utf8"){let e=Hr[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function W(r,t="utf8"){let e=Hr[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var Gu=parseInt("11111",2),ho=parseInt("10000000",2),Zu=parseInt("01111111",2),Si={0:ir,1:ir,2:Yu,3:Wu,4:Qu,5:Xu,6:ju,16:ir,22:ir,48:ir};function po(r,t={offset:0}){let e=r[t.offset]&Gu;if(t.offset++,Si[e]!=null)return Si[e](r,t);throw new Error("No decoder for tag "+e)}function ar(r,t){let e=0;if((r[t.offset]&ho)===ho){let n=r[t.offset]&Zu,o="0x";t.offset++;for(let s=0;s<n;s++,t.offset++)o+=r[t.offset].toString(16).padStart(2,"0");e=parseInt(o,16)}else e=r[t.offset],t.offset++;return e}function ir(r,t){ar(r,t);let e=[];for(;!(t.offset>=r.byteLength);){let n=po(r,t);if(n===null)break;e.push(n)}return e}function Yu(r,t){let e=ar(r,t),n=t.offset,o=t.offset+e,s=[];for(let i=n;i<o;i++)i===n&&r[i]===0||s.push(r[i]);return t.offset+=e,Uint8Array.from(s)}function ju(r,t){let e=ar(r,t),n=t.offset+e,o=r[t.offset];t.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(;t.offset<n;){let u=r[t.offset];if(t.offset++,c.push(u&127),u<128){c.reverse();let f=0;for(let l=0;l<c.length;l++)f+=c[l]<<l*7;a+=`.${f}`,c=[]}}return a}function Xu(r,t){return t.offset++,null}function Wu(r,t){let e=ar(r,t),n=r[t.offset];t.offset++;let o=r.subarray(t.offset,t.offset+e-1);if(t.offset+=e,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function Qu(r,t){let e=ar(r,t),n=r.subarray(t.offset,t.offset+e);return t.offset+=e,n}function Ju(r){let t=r.toString(16);t.length%2===1&&(t="0"+t);let e=new Q;for(let n=0;n<t.length;n+=2)e.append(Uint8Array.from([parseInt(`${t[n]}${t[n+1]}`,16)]));return e}function mo(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let t=Ju(r.byteLength);return new Q(Uint8Array.from([t.byteLength|ho]),t)}function vi(r){let t=new Q,e=128;return(r.subarray()[0]&e)===e&&t.append(Uint8Array.from([0])),t.append(r),new Q(Uint8Array.from([2]),mo(t),t)}function _i(r){let t=Uint8Array.from([0]),e=new Q(t,r);return new Q(Uint8Array.from([3]),mo(e),e)}function $r(r,t=48){let e=new Q;for(let n of r)e.append(n);return new Q(Uint8Array.from([t]),mo(e),e)}async function Ii(r,t,e,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,t,e.subarray());return n?.signal?.throwIfAborted(),s}var tf=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),ef=Uint8Array.from([6,5,43,129,4,0,34]),rf=Uint8Array.from([6,5,43,129,4,0,35]),nf={ext:!0,kty:"EC",crv:"P-256"},of={ext:!0,kty:"EC",crv:"P-384"},sf={ext:!0,kty:"EC",crv:"P-521"},go=32,bo=48,yo=66;function Ai(r){let t=po(r);return Bi(t)}function Bi(r){let t=r[1][1][0],e=1,n,o;if(t.byteLength===go*2+1)return n=W(t.subarray(e,e+go),"base64url"),o=W(t.subarray(e+go),"base64url"),new Be({...nf,key_ops:["verify"],x:n,y:o});if(t.byteLength===bo*2+1)return n=W(t.subarray(e,e+bo),"base64url"),o=W(t.subarray(e+bo),"base64url"),new Be({...of,key_ops:["verify"],x:n,y:o});if(t.byteLength===yo*2+1)return n=W(t.subarray(e,e+yo),"base64url"),o=W(t.subarray(e+yo),"base64url"),new Be({...sf,key_ops:["verify"],x:n,y:o});throw new ft(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function Di(r){return $r([vi(Uint8Array.from([1])),$r([af(r.crv)],160),$r([_i(new Q(Uint8Array.from([4]),H(r.x??"","base64url"),H(r.y??"","base64url")))],161)]).subarray()}function af(r){if(r==="P-256")return tf;if(r==="P-384")return ef;if(r==="P-521")return rf;throw new ft(`Invalid curve ${r}`)}var Be=class{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=Di(this.jwk)),this._raw}toMultihash(){return It.digest(De(this))}toCID(){return at.createV1(114,this.toMultihash())}toString(){return j.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:lt(this.raw,t.raw)}async verify(t,e,n){return Ii(this.jwk,e,t,n)}};function se(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Ct(r,t=""){if(!Number.isSafeInteger(r)||r<0){let e=t&&`"${t}" `;throw new Error(`${e}expected integer >= 0, got ${r}`)}}function N(r,t,e=""){let n=se(r),o=r?.length,s=t!==void 0;if(!n||s&&o!==t){let i=e&&`"${e}" `,a=s?` of length ${t}`:"",c=n?`length=${o}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function Gr(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");Ct(r.outputLen),Ct(r.blockLen)}function Le(r,t=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(t&&r.finished)throw new Error("Hash#digest() has already been called")}function Ci(r,t){N(r,void 0,"digestInto() output");let e=t.outputLen;if(r.length<e)throw new Error('"digestInto() output" expected to be of length >='+e)}function Mt(...r){for(let t=0;t<r.length;t++)r[t].fill(0)}function Zr(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function At(r,t){return r<<32-t|r>>>t}var Ti=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",cf=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function Kt(r){if(N(r),Ti)return r.toHex();let t="";for(let e=0;e<r.length;e++)t+=cf[r[e]];return t}var Ut={_0:48,_9:57,A:65,F:70,a:97,f:102};function Li(r){if(r>=Ut._0&&r<=Ut._9)return r-Ut._0;if(r>=Ut.A&&r<=Ut.F)return r-(Ut.A-10);if(r>=Ut.a&&r<=Ut.f)return r-(Ut.a-10)}function qt(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(Ti)return Uint8Array.fromHex(r);let t=r.length,e=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(e);for(let o=0,s=0;o<e;o++,s+=2){let i=Li(r.charCodeAt(s)),a=Li(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 mt(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];N(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let s=r[n];e.set(s,o),o+=s.length}return e}function xo(r,t={}){let e=(o,s)=>r(s).update(o).digest(),n=r(void 0);return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=o=>r(o),Object.assign(e,t),Object.freeze(e)}function Ce(r=32){let t=typeof globalThis=="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return t.getRandomValues(new Uint8Array(r))}var wo=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function Ri(r,t,e){return r&t^~r&e}function ki(r,t,e){return r&t^r&e^t&e}var cr=class{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(t,e,n,o){this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(t),this.view=Zr(this.buffer)}update(t){Le(this),N(t);let{view:e,buffer:n,blockLen:o}=this,s=t.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=Zr(t);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(t.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){Le(this),Ci(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;e[i++]=128,Mt(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let l=i;l<o;l++)e[l]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=Zr(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let u=c/4,f=this.get();if(u>f.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<u;l++)a.setUint32(4*l,f[l],s)}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){t||=new this.constructor,t.set(...this.get());let{blockLen:e,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return t.destroyed=i,t.finished=s,t.length=o,t.pos=a,o%e&&t.buffer.set(n),t}clone(){return this._cloneInto()}},Ft=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var nt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Yr=BigInt(4294967295),Pi=BigInt(32);function uf(r,t=!1){return t?{h:Number(r&Yr),l:Number(r>>Pi&Yr)}:{h:Number(r>>Pi&Yr)|0,l:Number(r&Yr)|0}}function Oi(r,t=!1){let e=r.length,n=new Uint32Array(e),o=new Uint32Array(e);for(let s=0;s<e;s++){let{h:i,l:a}=uf(r[s],t);[n[s],o[s]]=[i,a]}return[n,o]}var Eo=(r,t,e)=>r>>>e,So=(r,t,e)=>r<<32-e|t>>>e,ie=(r,t,e)=>r>>>e|t<<32-e,ae=(r,t,e)=>r<<32-e|t>>>e,ur=(r,t,e)=>r<<64-e|t>>>e-32,fr=(r,t,e)=>r>>>e-32|t<<64-e;function Tt(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var Ni=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),Ui=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,Mi=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),Ki=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,qi=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),Fi=(r,t,e,n,o,s)=>t+e+n+o+s+(r/2**32|0)|0;var lf=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]),Yt=new Uint32Array(64),vo=class extends cr{constructor(t){super(64,t,8,!1)}get(){let{A:t,B:e,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[t,e,n,o,s,i,a,c]}set(t,e,n,o,s,i,a,c){this.A=t|0,this.B=e|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(t,e){for(let l=0;l<16;l++,e+=4)Yt[l]=t.getUint32(e,!1);for(let l=16;l<64;l++){let d=Yt[l-15],y=Yt[l-2],h=At(d,7)^At(d,18)^d>>>3,v=At(y,17)^At(y,19)^y>>>10;Yt[l]=v+Yt[l-7]+h+Yt[l-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:f}=this;for(let l=0;l<64;l++){let d=At(a,6)^At(a,11)^At(a,25),y=f+d+Ri(a,c,u)+lf[l]+Yt[l]|0,v=(At(n,2)^At(n,13)^At(n,22))+ki(n,o,s)|0;f=u,u=c,c=a,a=i+y|0,i=s,s=o,o=n,n=y+v|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,f=f+this.H|0,this.set(n,o,s,i,a,c,u,f)}roundClean(){Mt(Yt)}destroy(){this.set(0,0,0,0,0,0,0,0),Mt(this.buffer)}},_o=class extends vo{A=Ft[0]|0;B=Ft[1]|0;C=Ft[2]|0;D=Ft[3]|0;E=Ft[4]|0;F=Ft[5]|0;G=Ft[6]|0;H=Ft[7]|0;constructor(){super(32)}};var zi=Oi(["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))),df=zi[0],hf=zi[1],jt=new Uint32Array(80),Xt=new Uint32Array(80),Io=class extends cr{constructor(t){super(128,t,16,!1)}get(){let{Ah:t,Al:e,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:u,El:f,Fh:l,Fl:d,Gh:y,Gl:h,Hh:v,Hl:x}=this;return[t,e,n,o,s,i,a,c,u,f,l,d,y,h,v,x]}set(t,e,n,o,s,i,a,c,u,f,l,d,y,h,v,x){this.Ah=t|0,this.Al=e|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=f|0,this.Fh=l|0,this.Fl=d|0,this.Gh=y|0,this.Gl=h|0,this.Hh=v|0,this.Hl=x|0}process(t,e){for(let w=0;w<16;w++,e+=4)jt[w]=t.getUint32(e),Xt[w]=t.getUint32(e+=4);for(let w=16;w<80;w++){let A=jt[w-15]|0,k=Xt[w-15]|0,U=ie(A,k,1)^ie(A,k,8)^Eo(A,k,7),M=ae(A,k,1)^ae(A,k,8)^So(A,k,7),S=jt[w-2]|0,E=Xt[w-2]|0,P=ie(S,E,19)^ur(S,E,61)^Eo(S,E,6),K=ae(S,E,19)^fr(S,E,61)^So(S,E,6),C=Mi(M,K,Xt[w-7],Xt[w-16]),m=Ki(C,U,P,jt[w-7],jt[w-16]);jt[w]=m|0,Xt[w]=C|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:f,Eh:l,El:d,Fh:y,Fl:h,Gh:v,Gl:x,Hh:b,Hl:I}=this;for(let w=0;w<80;w++){let A=ie(l,d,14)^ie(l,d,18)^ur(l,d,41),k=ae(l,d,14)^ae(l,d,18)^fr(l,d,41),U=l&y^~l&v,M=d&h^~d&x,S=qi(I,k,M,hf[w],Xt[w]),E=Fi(S,b,A,U,df[w],jt[w]),P=S|0,K=ie(n,o,28)^ur(n,o,34)^ur(n,o,39),C=ae(n,o,28)^fr(n,o,34)^fr(n,o,39),m=n&s^n&a^s&a,g=o&i^o&c^i&c;b=v|0,I=x|0,v=y|0,x=h|0,y=l|0,h=d|0,{h:l,l:d}=Tt(u|0,f|0,E|0,P|0),u=a|0,f=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let p=Ni(P,C,g);n=Ui(p,E,K,m),o=p|0}({h:n,l:o}=Tt(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=Tt(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=Tt(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:f}=Tt(this.Dh|0,this.Dl|0,u|0,f|0),{h:l,l:d}=Tt(this.Eh|0,this.El|0,l|0,d|0),{h:y,l:h}=Tt(this.Fh|0,this.Fl|0,y|0,h|0),{h:v,l:x}=Tt(this.Gh|0,this.Gl|0,v|0,x|0),{h:b,l:I}=Tt(this.Hh|0,this.Hl|0,b|0,I|0),this.set(n,o,s,i,a,c,u,f,l,d,y,h,v,x,b,I)}roundClean(){Mt(jt,Xt)}destroy(){Mt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Ao=class extends Io{Ah=nt[0]|0;Al=nt[1]|0;Bh=nt[2]|0;Bl=nt[3]|0;Ch=nt[4]|0;Cl=nt[5]|0;Dh=nt[6]|0;Dl=nt[7]|0;Eh=nt[8]|0;El=nt[9]|0;Fh=nt[10]|0;Fl=nt[11]|0;Gh=nt[12]|0;Gl=nt[13]|0;Hh=nt[14]|0;Hl=nt[15]|0;constructor(){super(64)}};var Vi=xo(()=>new _o,wo(1));var Hi=xo(()=>new Ao,wo(3));var Do=BigInt(0),Bo=BigInt(1);function zt(r,t=""){if(typeof r!="boolean"){let e=t&&`"${t}" `;throw new Error(e+"expected boolean, got type="+typeof r)}return r}function $i(r){if(typeof r=="bigint"){if(!jr(r))throw new Error("positive bigint expected, got "+r)}else Ct(r);return r}function lr(r){let t=$i(r).toString(16);return t.length&1?"0"+t:t}function Gi(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?Do:BigInt("0x"+r)}function Te(r){return Gi(Kt(r))}function ce(r){return Gi(Kt(Wr(N(r)).reverse()))}function Xr(r,t){Ct(t),r=$i(r);let e=qt(r.toString(16).padStart(t*2,"0"));if(e.length!==t)throw new Error("number too large");return e}function Lo(r,t){return Xr(r,t).reverse()}function Wr(r){return Uint8Array.from(r)}var jr=r=>typeof r=="bigint"&&Do<=r;function pf(r,t,e){return jr(r)&&jr(t)&&jr(e)&&t<=r&&r<e}function dr(r,t,e,n){if(!pf(t,e,n))throw new Error("expected valid "+r+": "+e+" <= n < "+n+", got "+t)}function Co(r){let t;for(t=0;r>Do;r>>=Bo,t+=1);return t}var hr=r=>(Bo<<BigInt(r))-Bo;function Zi(r,t,e){if(Ct(r,"hashLen"),Ct(t,"qByteLen"),typeof e!="function")throw new Error("hmacFn must be a function");let n=x=>new Uint8Array(x),o=Uint8Array.of(),s=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(r),u=n(r),f=0,l=()=>{c.fill(1),u.fill(0),f=0},d=(...x)=>e(u,mt(c,...x)),y=(x=o)=>{u=d(s,x),c=d(),x.length!==0&&(u=d(i,x),c=d())},h=()=>{if(f++>=a)throw new Error("drbg: tried max amount of iterations");let x=0,b=[];for(;x<t;){c=d();let I=c.slice();b.push(I),x+=c.length}return mt(...b)};return(x,b)=>{l(),y(x);let I;for(;!(I=b(h()));)y();return l(),I}}function Wt(r,t={},e={}){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(t,!1),o(e,!0)}function Re(r){let t=new WeakMap;return(e,...n)=>{let o=t.get(e);if(o!==void 0)return o;let s=r(e,...n);return t.set(e,s),s}}var dt=BigInt(0),J=BigInt(1),ue=BigInt(2),Xi=BigInt(3),Wi=BigInt(4),Qi=BigInt(5),mf=BigInt(7),Ji=BigInt(8),gf=BigInt(9),ta=BigInt(16);function X(r,t){let e=r%t;return e>=dt?e:t+e}function V(r,t,e){let n=r;for(;t-- >dt;)n*=n,n%=e;return n}function Yi(r,t){if(r===dt)throw new Error("invert: expected non-zero number");if(t<=dt)throw new Error("invert: expected positive modulus, got "+t);let e=X(r,t),n=t,o=dt,s=J,i=J,a=dt;for(;e!==dt;){let u=n/e,f=n%e,l=o-i*u,d=s-a*u;n=e,e=f,o=i,s=a,i=l,a=d}if(n!==J)throw new Error("invert: does not exist");return X(o,t)}function Ro(r,t,e){if(!r.eql(r.sqr(t),e))throw new Error("Cannot find square root")}function ea(r,t){let e=(r.ORDER+J)/Wi,n=r.pow(t,e);return Ro(r,n,t),n}function bf(r,t){let e=(r.ORDER-Qi)/Ji,n=r.mul(t,ue),o=r.pow(n,e),s=r.mul(t,o),i=r.mul(r.mul(s,ue),o),a=r.mul(s,r.sub(i,r.ONE));return Ro(r,a,t),a}function yf(r){let t=ke(r),e=ra(r),n=e(t,t.neg(t.ONE)),o=e(t,n),s=e(t,t.neg(n)),i=(r+mf)/ta;return(a,c)=>{let u=a.pow(c,i),f=a.mul(u,n),l=a.mul(u,o),d=a.mul(u,s),y=a.eql(a.sqr(f),c),h=a.eql(a.sqr(l),c);u=a.cmov(u,f,y),f=a.cmov(d,l,h);let v=a.eql(a.sqr(f),c),x=a.cmov(u,f,v);return Ro(a,x,c),x}}function ra(r){if(r<Xi)throw new Error("sqrt is not defined for small field");let t=r-J,e=0;for(;t%ue===dt;)t/=ue,e++;let n=ue,o=ke(r);for(;ji(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(e===1)return ea;let s=o.pow(n,t),i=(t+J)/ue;return function(c,u){if(c.is0(u))return u;if(ji(c,u)!==1)throw new Error("Cannot find square root");let f=e,l=c.mul(c.ONE,s),d=c.pow(u,t),y=c.pow(u,i);for(;!c.eql(d,c.ONE);){if(c.is0(d))return c.ZERO;let h=1,v=c.sqr(d);for(;!c.eql(v,c.ONE);)if(h++,v=c.sqr(v),h===f)throw new Error("Cannot find square root");let x=J<<BigInt(f-h-1),b=c.pow(l,x);f=h,l=c.sqr(b),d=c.mul(d,l),y=c.mul(y,b)}return y}}function xf(r){return r%Wi===Xi?ea:r%Ji===Qi?bf:r%ta===gf?yf(r):ra(r)}var na=(r,t)=>(X(r,t)&J)===J,wf=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function ko(r){let t={ORDER:"bigint",BYTES:"number",BITS:"number"},e=wf.reduce((n,o)=>(n[o]="function",n),t);return Wt(r,e),r}function Ef(r,t,e){if(e<dt)throw new Error("invalid exponent, negatives unsupported");if(e===dt)return r.ONE;if(e===J)return t;let n=r.ONE,o=t;for(;e>dt;)e&J&&(n=r.mul(n,o)),o=r.sqr(o),e>>=J;return n}function pr(r,t,e=!1){let n=new Array(t.length).fill(e?r.ZERO:void 0),o=t.reduce((i,a,c)=>r.is0(a)?i:(n[c]=i,r.mul(i,a)),r.ONE),s=r.inv(o);return t.reduceRight((i,a,c)=>r.is0(a)?i:(n[c]=r.mul(i,n[c]),r.mul(i,a)),s),n}function ji(r,t){let e=(r.ORDER-J)/ue,n=r.pow(t,e),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 Sf(r,t){t!==void 0&&Ct(t);let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}var To=class{ORDER;BITS;BYTES;isLE;ZERO=dt;ONE=J;_lengths;_sqrt;_mod;constructor(t,e={}){if(t<=dt)throw new Error("invalid field: expected ORDER > 0, got "+t);let n;this.isLE=!1,e!=null&&typeof e=="object"&&(typeof e.BITS=="number"&&(n=e.BITS),typeof e.sqrt=="function"&&(this.sqrt=e.sqrt),typeof e.isLE=="boolean"&&(this.isLE=e.isLE),e.allowedLengths&&(this._lengths=e.allowedLengths?.slice()),typeof e.modFromBytes=="boolean"&&(this._mod=e.modFromBytes));let{nBitLength:o,nByteLength:s}=Sf(t,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=t,this.BITS=o,this.BYTES=s,this._sqrt=void 0,Object.preventExtensions(this)}create(t){return X(t,this.ORDER)}isValid(t){if(typeof t!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof t);return dt<=t&&t<this.ORDER}is0(t){return t===dt}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}isOdd(t){return(t&J)===J}neg(t){return X(-t,this.ORDER)}eql(t,e){return t===e}sqr(t){return X(t*t,this.ORDER)}add(t,e){return X(t+e,this.ORDER)}sub(t,e){return X(t-e,this.ORDER)}mul(t,e){return X(t*e,this.ORDER)}pow(t,e){return Ef(this,t,e)}div(t,e){return X(t*Yi(e,this.ORDER),this.ORDER)}sqrN(t){return t*t}addN(t,e){return t+e}subN(t,e){return t-e}mulN(t,e){return t*e}inv(t){return Yi(t,this.ORDER)}sqrt(t){return this._sqrt||(this._sqrt=xf(this.ORDER)),this._sqrt(this,t)}toBytes(t){return this.isLE?Lo(t,this.BYTES):Xr(t,this.BYTES)}fromBytes(t,e=!1){N(t);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(!n.includes(t.length)||t.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+t.length);let u=new Uint8Array(o);u.set(t,s?0:u.length-t.length),t=u}if(t.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+t.length);let c=s?ce(t):Te(t);if(a&&(c=X(c,i)),!e&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(t){return pr(this,t)}cmov(t,e,n){return n?e:t}};function ke(r,t={}){return new To(r,t)}function oa(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let t=r.toString(2).length;return Math.ceil(t/8)}function Po(r){let t=oa(r);return t+Math.ceil(t/2)}function Oo(r,t,e=!1){N(r);let n=r.length,o=oa(t),s=Po(t);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=e?ce(r):Te(r),a=X(i,t-J)+J;return e?Lo(a,o):Xr(a,o)}var Pe=BigInt(0),fe=BigInt(1);function mr(r,t){let e=t.negate();return r?e:t}function le(r,t){let e=pr(r.Fp,t.map(n=>n.Z));return t.map((n,o)=>r.fromAffine(n.toAffine(e[o])))}function ca(r,t){if(!Number.isSafeInteger(r)||r<=0||r>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+r)}function No(r,t){ca(r,t);let e=Math.ceil(t/r)+1,n=2**(r-1),o=2**r,s=hr(r),i=BigInt(r);return{windows:e,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function sa(r,t,e){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=e,a=Number(r&o),c=r>>i;a>n&&(a-=s,c+=fe);let u=t*n,f=u+Math.abs(a)-1,l=a===0,d=a<0,y=t%2!==0;return{nextN:c,offset:f,isZero:l,isNeg:d,isNegF:y,offsetF:u}}var Uo=new WeakMap,ua=new WeakMap;function Mo(r){return ua.get(r)||1}function ia(r){if(r!==Pe)throw new Error("invalid wNAF")}var Oe=class{BASE;ZERO;Fn;bits;constructor(t,e){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=e}_unsafeLadder(t,e,n=this.ZERO){let o=t;for(;e>Pe;)e&fe&&(n=n.add(o)),o=o.double(),e>>=fe;return n}precomputeWindow(t,e){let{windows:n,windowSize:o}=No(e,this.bits),s=[],i=t,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(t,e,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=No(t,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:u,isZero:f,isNeg:l,isNegF:d,offsetF:y}=sa(n,a,i);n=c,f?s=s.add(mr(d,e[y])):o=o.add(mr(l,e[u]))}return ia(n),{p:o,f:s}}wNAFUnsafe(t,e,n,o=this.ZERO){let s=No(t,this.bits);for(let i=0;i<s.windows&&n!==Pe;i++){let{nextN:a,offset:c,isZero:u,isNeg:f}=sa(n,i,s);if(n=a,!u){let l=e[c];o=o.add(f?l.negate():l)}}return ia(n),o}getPrecomputes(t,e,n){let o=Uo.get(e);return o||(o=this.precomputeWindow(e,t),t!==1&&(typeof n=="function"&&(o=n(o)),Uo.set(e,o))),o}cached(t,e,n){let o=Mo(t);return this.wNAF(o,this.getPrecomputes(o,t,n),e)}unsafe(t,e,n,o){let s=Mo(t);return s===1?this._unsafeLadder(t,e,o):this.wNAFUnsafe(s,this.getPrecomputes(s,t,n),e,o)}createCache(t,e){ca(e,this.bits),ua.set(t,e),Uo.delete(t)}hasCache(t){return Mo(t)!==1}};function fa(r,t,e,n){let o=t,s=r.ZERO,i=r.ZERO;for(;e>Pe||n>Pe;)e&fe&&(s=s.add(o)),n&fe&&(i=i.add(o)),o=o.double(),e>>=fe,n>>=fe;return{p1:s,p2:i}}function aa(r,t,e){if(t){if(t.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return ko(t),t}else return ke(r,{isLE:e})}function Qr(r,t,e={},n){if(n===void 0&&(n=r==="edwards"),!t||typeof t!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let u=t[c];if(!(typeof u=="bigint"&&u>Pe))throw new Error(`CURVE.${c} must be positive bigint`)}let o=aa(t.p,e.Fp,n),s=aa(t.n,e.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(t[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:s}}function Jr(r,t){return function(n){let o=r(n);return{secretKey:o,publicKey:t(o)}}}var Qt=BigInt(0),tt=BigInt(1),Ko=BigInt(2),vf=BigInt(8);function _f(r,t,e,n){let o=r.sqr(e),s=r.sqr(n),i=r.add(r.mul(t.a,o),s),a=r.add(r.ONE,r.mul(t.d,r.mul(o,s)));return r.eql(i,a)}function la(r,t={}){let e=Qr("edwards",r,t,t.FpFnLE),{Fp:n,Fn:o}=e,s=e.CURVE,{h:i}=s;Wt(t,{},{uvRatio:"function"});let a=Ko<<BigInt(o.BYTES*8)-tt,c=x=>n.create(x),u=t.uvRatio||((x,b)=>{try{return{isValid:!0,value:n.sqrt(n.div(x,b))}}catch{return{isValid:!1,value:Qt}}});if(!_f(n,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function f(x,b,I=!1){let w=I?tt:Qt;return dr("coordinate "+x,b,w,a),b}function l(x){if(!(x instanceof h))throw new Error("EdwardsPoint expected")}let d=Re((x,b)=>{let{X:I,Y:w,Z:A}=x,k=x.is0();b==null&&(b=k?vf:n.inv(A));let U=c(I*b),M=c(w*b),S=n.mul(A,b);if(k)return{x:Qt,y:tt};if(S!==tt)throw new Error("invZ was invalid");return{x:U,y:M}}),y=Re(x=>{let{a:b,d:I}=s;if(x.is0())throw new Error("bad point: ZERO");let{X:w,Y:A,Z:k,T:U}=x,M=c(w*w),S=c(A*A),E=c(k*k),P=c(E*E),K=c(M*b),C=c(E*c(K+S)),m=c(P+c(I*c(M*S)));if(C!==m)throw new Error("bad point: equation left != right (1)");let g=c(w*A),p=c(k*U);if(g!==p)throw new Error("bad point: equation left != right (2)");return!0});class h{static BASE=new h(s.Gx,s.Gy,tt,c(s.Gx*s.Gy));static ZERO=new h(Qt,tt,tt,Qt);static Fp=n;static Fn=o;X;Y;Z;T;constructor(b,I,w,A){this.X=f("x",b),this.Y=f("y",I),this.Z=f("z",w,!0),this.T=f("t",A),Object.freeze(this)}static CURVE(){return s}static fromAffine(b){if(b instanceof h)throw new Error("extended point not allowed");let{x:I,y:w}=b||{};return f("x",I),f("y",w),new h(I,w,tt,c(I*w))}static fromBytes(b,I=!1){let w=n.BYTES,{a:A,d:k}=s;b=Wr(N(b,w,"point")),zt(I,"zip215");let U=Wr(b),M=b[w-1];U[w-1]=M&-129;let S=ce(U),E=I?a:n.ORDER;dr("point.y",S,Qt,E);let P=c(S*S),K=c(P-tt),C=c(k*P-A),{isValid:m,value:g}=u(K,C);if(!m)throw new Error("bad point: invalid y coordinate");let p=(g&tt)===tt,_=(M&128)!==0;if(!I&&g===Qt&&_)throw new Error("bad point: x=0 and x_0=1");return _!==p&&(g=c(-g)),h.fromAffine({x:g,y:S})}static fromHex(b,I=!1){return h.fromBytes(qt(b),I)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(b=8,I=!0){return v.createCache(this,b),I||this.multiply(Ko),this}assertValidity(){y(this)}equals(b){l(b);let{X:I,Y:w,Z:A}=this,{X:k,Y:U,Z:M}=b,S=c(I*M),E=c(k*A),P=c(w*M),K=c(U*A);return S===E&&P===K}is0(){return this.equals(h.ZERO)}negate(){return new h(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:b}=s,{X:I,Y:w,Z:A}=this,k=c(I*I),U=c(w*w),M=c(Ko*c(A*A)),S=c(b*k),E=I+w,P=c(c(E*E)-k-U),K=S+U,C=K-M,m=S-U,g=c(P*C),p=c(K*m),_=c(P*m),B=c(C*K);return new h(g,p,B,_)}add(b){l(b);let{a:I,d:w}=s,{X:A,Y:k,Z:U,T:M}=this,{X:S,Y:E,Z:P,T:K}=b,C=c(A*S),m=c(k*E),g=c(M*w*K),p=c(U*P),_=c((A+k)*(S+E)-C-m),B=p-g,L=p+g,T=c(m-I*C),D=c(_*B),R=c(L*T),O=c(_*T),$=c(B*L);return new h(D,R,$,O)}subtract(b){return this.add(b.negate())}multiply(b){if(!o.isValidNot0(b))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:I,f:w}=v.cached(this,b,A=>le(h,A));return le(h,[I,w])[0]}multiplyUnsafe(b,I=h.ZERO){if(!o.isValid(b))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return b===Qt?h.ZERO:this.is0()||b===tt?this:v.unsafe(this,b,w=>le(h,w),I)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return v.unsafe(this,s.n).is0()}toAffine(b){return d(this,b)}clearCofactor(){return i===tt?this:this.multiplyUnsafe(i)}toBytes(){let{x:b,y:I}=this.toAffine(),w=n.toBytes(I);return w[w.length-1]|=b&tt?128:0,w}toHex(){return Kt(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let v=new Oe(h,o.BITS);return h.BASE.precompute(8),h}function da(r,t,e={}){if(typeof t!="function")throw new Error('"hash" function param is required');Wt(e,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=e,{BASE:o,Fp:s,Fn:i}=r,a=e.randomBytes||Ce,c=e.adjustScalarBytes||(S=>S),u=e.domain||((S,E,P)=>{if(zt(P,"phflag"),E.length||P)throw new Error("Contexts/pre-hash are not supported");return S});function f(S){return i.create(ce(S))}function l(S){let E=w.secretKey;N(S,w.secretKey,"secretKey");let P=N(t(S),2*E,"hashedSecretKey"),K=c(P.slice(0,E)),C=P.slice(E,2*E),m=f(K);return{head:K,prefix:C,scalar:m}}function d(S){let{head:E,prefix:P,scalar:K}=l(S),C=o.multiply(K),m=C.toBytes();return{head:E,prefix:P,scalar:K,point:C,pointBytes:m}}function y(S){return d(S).pointBytes}function h(S=Uint8Array.of(),...E){let P=mt(...E);return f(t(u(P,N(S,void 0,"context"),!!n)))}function v(S,E,P={}){S=N(S,void 0,"message"),n&&(S=n(S));let{prefix:K,scalar:C,pointBytes:m}=d(E),g=h(P.context,K,S),p=o.multiply(g).toBytes(),_=h(P.context,p,m,S),B=i.create(g+_*C);if(!i.isValid(B))throw new Error("sign failed: invalid s");let L=mt(p,i.toBytes(B));return N(L,w.signature,"result")}let x={zip215:!0};function b(S,E,P,K=x){let{context:C,zip215:m}=K,g=w.signature;S=N(S,g,"signature"),E=N(E,void 0,"message"),P=N(P,w.publicKey,"publicKey"),m!==void 0&&zt(m,"zip215"),n&&(E=n(E));let p=g/2,_=S.subarray(0,p),B=ce(S.subarray(p,g)),L,T,D;try{L=r.fromBytes(P,m),T=r.fromBytes(_,m),D=o.multiplyUnsafe(B)}catch{return!1}if(!m&&L.isSmallOrder())return!1;let R=h(C,T.toBytes(),L.toBytes(),E);return T.add(L.multiplyUnsafe(R)).subtract(D).clearCofactor().is0()}let I=s.BYTES,w={secretKey:I,publicKey:I,signature:2*I,seed:I};function A(S=a(w.seed)){return N(S,w.seed,"seed")}function k(S){return se(S)&&S.length===i.BYTES}function U(S,E){try{return!!r.fromBytes(S,E)}catch{return!1}}let M={getExtendedPublicKey:d,randomSecretKey:A,isValidSecretKey:k,isValidPublicKey:U,toMontgomery(S){let{y:E}=r.fromBytes(S),P=w.publicKey,K=P===32;if(!K&&P!==57)throw new Error("only defined for 25519 and 448");let C=K?s.div(tt+E,tt-E):s.div(E-tt,E+tt);return s.toBytes(C)},toMontgomerySecret(S){let E=w.secretKey;N(S,E);let P=t(S.subarray(0,E));return c(P).subarray(0,E)}};return Object.freeze({keygen:Jr(A,y),getPublicKey:y,sign:v,verify:b,utils:M,Point:r,lengths:w})}var If=BigInt(1),ha=BigInt(2);var Af=BigInt(5),Bf=BigInt(8),qo=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Df={p:qo,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Bf,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Lf(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),s=qo,a=r*r%s*r%s,c=V(a,ha,s)*a%s,u=V(c,If,s)*r%s,f=V(u,Af,s)*u%s,l=V(f,t,s)*f%s,d=V(l,e,s)*l%s,y=V(d,n,s)*d%s,h=V(y,o,s)*y%s,v=V(h,o,s)*y%s,x=V(v,t,s)*f%s;return{pow_p_5_8:V(x,ha,s)*r%s,b2:a}}function Cf(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var pa=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Tf(r,t){let e=qo,n=X(t*t*t,e),o=X(n*n*t,e),s=Lf(r*o).pow_p_5_8,i=X(r*n*s,e),a=X(t*i*i,e),c=i,u=X(i*pa,e),f=a===r,l=a===X(-r,e),d=a===X(-r*pa,e);return f&&(i=c),(l||d)&&(i=u),na(i,e)&&(i=X(-i,e)),{isValid:f||l,value:i}}var Rf=la(Df,{uvRatio:Tf});function kf(r){return da(Rf,Hi,Object.assign({adjustScalarBytes:Cf},r))}var ma=kf({});var gr=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},tn=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var ga={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new tn("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 t}};var en=ga;var rn=32;var Fo,Pf=(async()=>{try{return await en.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function Of(r,t,e){if(r.buffer instanceof ArrayBuffer){let n=await en.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await en.get().subtle.verify({name:"Ed25519"},n,t,e instanceof Uint8Array?e:e.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function Nf(r,t,e){return ma.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}async function ba(r,t,e){return Fo==null&&(Fo=await Pf),Fo?Of(r,t,e):Nf(r,t,e)}function nn(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var on=class{type="Ed25519";raw;constructor(t){this.raw=zo(t,rn)}toMultihash(){return It.digest(De(this))}toCID(){return at.createV1(114,this.toMultihash())}toString(){return j.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:lt(this.raw,t.raw)}verify(t,e,n){n?.signal?.throwIfAborted();let o=ba(this.raw,e,t);return nn(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function xa(r){return r=zo(r,rn),new on(r)}function zo(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new ft(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}var Mf=Math.pow(2,7),Kf=Math.pow(2,14),qf=Math.pow(2,21),Vo=Math.pow(2,28),Ho=Math.pow(2,35),$o=Math.pow(2,42),Go=Math.pow(2,49),F=128,ct=127;function gt(r){if(r<Mf)return 1;if(r<Kf)return 2;if(r<qf)return 3;if(r<Vo)return 4;if(r<Ho)return 5;if(r<$o)return 6;if(r<Go)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Ne(r,t,e=0){switch(gt(r)){case 8:t[e++]=r&255|F,r/=128;case 7:t[e++]=r&255|F,r/=128;case 6:t[e++]=r&255|F,r/=128;case 5:t[e++]=r&255|F,r/=128;case 4:t[e++]=r&255|F,r>>>=7;case 3:t[e++]=r&255|F,r>>>=7;case 2:t[e++]=r&255|F,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function Ff(r,t,e=0){switch(gt(r)){case 8:t.set(e++,r&255|F),r/=128;case 7:t.set(e++,r&255|F),r/=128;case 6:t.set(e++,r&255|F),r/=128;case 5:t.set(e++,r&255|F),r/=128;case 4:t.set(e++,r&255|F),r>>>=7;case 3:t.set(e++,r&255|F),r>>>=7;case 2:t.set(e++,r&255|F),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function Zo(r,t){let e=r[t],n=0;if(n+=e&ct,e<F||(e=r[t+1],n+=(e&ct)<<7,e<F)||(e=r[t+2],n+=(e&ct)<<14,e<F)||(e=r[t+3],n+=(e&ct)<<21,e<F)||(e=r[t+4],n+=(e&ct)*Vo,e<F)||(e=r[t+5],n+=(e&ct)*Ho,e<F)||(e=r[t+6],n+=(e&ct)*$o,e<F)||(e=r[t+7],n+=(e&ct)*Go,e<F))return n;throw new RangeError("Could not decode varint")}function zf(r,t){let e=r.get(t),n=0;if(n+=e&ct,e<F||(e=r.get(t+1),n+=(e&ct)<<7,e<F)||(e=r.get(t+2),n+=(e&ct)<<14,e<F)||(e=r.get(t+3),n+=(e&ct)<<21,e<F)||(e=r.get(t+4),n+=(e&ct)*Vo,e<F)||(e=r.get(t+5),n+=(e&ct)*Ho,e<F)||(e=r.get(t+6),n+=(e&ct)*$o,e<F)||(e=r.get(t+7),n+=(e&ct)*Go,e<F))return n;throw new RangeError("Could not decode varint")}function wa(r,t,e=0){return t==null&&(t=pt(gt(r))),t instanceof Uint8Array?Ne(r,t,e):Ff(r,t,e)}function br(r,t=0){return r instanceof Uint8Array?Zo(r,t):zf(r,t)}var Yo=new Float32Array([-0]),Jt=new Uint8Array(Yo.buffer);function Sa(r,t,e){Yo[0]=r,t[e]=Jt[0],t[e+1]=Jt[1],t[e+2]=Jt[2],t[e+3]=Jt[3]}function va(r,t){return Jt[0]=r[t],Jt[1]=r[t+1],Jt[2]=r[t+2],Jt[3]=r[t+3],Yo[0]}var jo=new Float64Array([-0]),ut=new Uint8Array(jo.buffer);function _a(r,t,e){jo[0]=r,t[e]=ut[0],t[e+1]=ut[1],t[e+2]=ut[2],t[e+3]=ut[3],t[e+4]=ut[4],t[e+5]=ut[5],t[e+6]=ut[6],t[e+7]=ut[7]}function Ia(r,t){return ut[0]=r[t],ut[1]=r[t+1],ut[2]=r[t+2],ut[3]=r[t+3],ut[4]=r[t+4],ut[5]=r[t+5],ut[6]=r[t+6],ut[7]=r[t+7],jo[0]}var Vf=BigInt(Number.MAX_SAFE_INTEGER),Hf=BigInt(Number.MIN_SAFE_INTEGER),xt=class r{lo;hi;constructor(t,e){this.lo=t|0,this.hi=e|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(e+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(BigInt(e)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?e===0?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return de;if(t<Vf&&t>Hf)return this.fromNumber(Number(t));let e=t<0n;e&&(t=-t);let n=t>>32n,o=t-(n<<32n);return e&&(n=~n|0n,o=~o|0n,++o>Aa&&(o=0n,++n>Aa&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return de;let e=t<0;e&&(t=-t);let n=t>>>0,o=(t-n)/4294967296>>>0;return e&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(t){return typeof t=="number"?r.fromNumber(t):typeof t=="bigint"?r.fromBigInt(t):typeof t=="string"?r.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new r(t.low>>>0,t.high>>>0):de}},de=new xt(0,0);de.toBigInt=function(){return 0n};de.zzEncode=de.zzDecode=function(){return this};de.length=function(){return 1};var Aa=4294967296n;function Ba(r){let t=0,e=0;for(let n=0;n<r.length;++n)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:(e&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function Da(r,t,e){if(e-t<1)return"";let o,s=[],i=0,a;for(;t<e;)a=r[t++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[t++]&63:a>239&&a<365?(a=((a&7)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[t++]&63)<<6|r[t++]&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 Xo(r,t,e){let n=e,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?t[e++]=o:o<2048?(t[e++]=o>>6|192,t[e++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,t[e++]=o>>18|240,t[e++]=o>>12&63|128,t[e++]=o>>6&63|128,t[e++]=o&63|128):(t[e++]=o>>12|224,t[e++]=o>>6&63|128,t[e++]=o&63|128);return e-n}function Bt(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function sn(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var Wo=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,Bt(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Bt(this,4);return sn(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Bt(this,4);return sn(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Bt(this,4);let t=va(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw Bt(this,4);let t=Ia(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw Bt(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return Da(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw Bt(this,t);this.pos+=t}else do if(this.pos>=this.len)throw Bt(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new xt(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw Bt(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw Bt(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Bt(this,8);let t=sn(this.buf,this.pos+=4),e=sn(this.buf,this.pos+=4);return new xt(t,e)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=Zo(this.buf,this.pos);return this.pos+=gt(t),t}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 yr(r){return new Wo(r instanceof Uint8Array?r:r.subarray())}function Et(r,t,e){let n=yr(r);return t.decode(n,void 0,e)}function Qo(r){let t=r??8192,e=t>>>1,n,o=t;return function(i){if(i<1||i>e)return pt(i);o+i>t&&(n=pt(t),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var he=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function Jo(){}var es=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},$f=Qo();function Gf(r){return globalThis.Buffer!=null?pt(r):$f(r)}var wr=class{len;head;tail;states;constructor(){this.len=0,this.head=new he(Jo,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new he(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new rs((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(an,10,xt.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=xt.fromBigInt(t);return this._push(an,e.length(),e)}uint64Number(t){return this._push(Ne,gt(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let e=xt.fromBigInt(t).zzEncode();return this._push(an,e.length(),e)}sint64Number(t){let e=xt.fromNumber(t).zzEncode();return this._push(an,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(ts,1,t?1:0)}fixed32(t){return this._push(xr,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=xt.fromBigInt(t);return this._push(xr,4,e.lo)._push(xr,4,e.hi)}fixed64Number(t){let e=xt.fromNumber(t);return this._push(xr,4,e.lo)._push(xr,4,e.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(Sa,4,t)}double(t){return this._push(_a,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(ts,1,0):this.uint32(e)._push(Yf,e,t)}string(t){let e=Ba(t);return e!==0?this.uint32(e)._push(Xo,e,t):this._push(ts,1,0)}fork(){return this.states=new es(this),this.head=this.tail=new he(Jo,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 he(Jo,0,0),this.len=0),this}ldelim(){let t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=e,this.len+=n),this}finish(){let t=this.head.next,e=Gf(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function ts(r,t,e){t[e]=r&255}function Zf(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var rs=class extends he{next;constructor(t,e){super(Zf,t,e),this.next=void 0}};function an(r,t,e){for(;r.hi!==0;)t[e++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)t[e++]=r.lo&127|128,r.lo=r.lo>>>7;t[e++]=r.lo}function xr(r,t,e){t[e]=r&255,t[e+1]=r>>>8&255,t[e+2]=r>>>16&255,t[e+3]=r>>>24}function Yf(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(wr.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(jf,t,r),this},wr.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(Xf,t,r),this});function jf(r,t,e){t.set(r,e)}function Xf(r,t,e){r.length<40?Xo(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(H(r),e)}function ns(){return new wr}function St(r,t){let e=ns();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}function*vt(r,t,e){let n=yr(r);yield*t.stream(n,void 0,"$",e)}var cn={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function un(r,t,e,n,o){return{name:r,type:t,encode:e,decode:n,stream:o}}function pe(r){function t(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let e=function(i,a){let c=t(i);a.int32(c)},n=function(i){let a=i.int32();return t(a)},o=function*(i){let a=i.int32();yield t(a)};return un("enum",cn.VARINT,e,n,o)}function _t(r,t,e){return un("message",cn.LENGTH_DELIMITED,r,t,e)}var Er=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var ht;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(ht||(ht={}));var os;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(os||(os={}));(function(r){r.codec=()=>pe(os)})(ht||(ht={}));var Sr;(function(r){let t;r.codec=()=>(t==null&&(t=_t((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),ht.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 f=s.uint32();switch(f>>>3){case 1:{c.Type=ht.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(f&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{yield{field:`${a}.Type`,value:ht.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(f&7);break}}}})),t);function e(s){return St(s,r.codec())}r.encode=e;function n(s,i){return Et(s,r.codec(),i)}r.decode=n;function o(s,i){return vt(s,r.codec(),i)}r.stream=o})(Sr||(Sr={}));var ss;(function(r){let t;r.codec=()=>(t==null&&(t=_t((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),ht.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 f=s.uint32();switch(f>>>3){case 1:{c.Type=ht.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(f&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{yield{field:`${a}.Type`,value:ht.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(f&7);break}}}})),t);function e(s){return St(s,r.codec())}r.encode=e;function n(s,i){return Et(s,r.codec(),i)}r.decode=n;function o(s,i){return vt(s,r.codec(),i)}r.stream=o})(ss||(ss={}));var fn=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(t,e){if(Gr(t),N(e,void 0,"key"),this.iHash=t.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(e.length>n?t.create().update(e).digest():e);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=t.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),Mt(o)}update(t){return Le(this),this.iHash.update(t),this}digestInto(t){Le(this),N(t,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||=Object.create(Object.getPrototypeOf(this),{});let{oHash:e,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return t=t,t.finished=o,t.destroyed=s,t.blockLen=i,t.outputLen=a,t.oHash=e._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},is=(r,t,e)=>new fn(r,t).update(e).digest();is.create=(r,t)=>new fn(r,t);var Ca=(r,t)=>(r+(r>=0?t:-t)/Ta)/t;function Qf(r,t,e){let[[n,o],[s,i]]=t,a=Ca(i*r,e),c=Ca(-o*r,e),u=r-a*n-c*s,f=-a*o-c*i,l=u<Vt,d=f<Vt;l&&(u=-u),d&&(f=-f);let y=hr(Math.ceil(Co(e)/2))+Ue;if(u<Vt||u>=y||f<Vt||f>=y)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:l,k1:u,k2neg:d,k2:f}}function cs(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function as(r,t){let e={};for(let n of Object.keys(t))e[n]=r[n]===void 0?t[n]:r[n];return zt(e.lowS,"lowS"),zt(e.prehash,"prehash"),e.format!==void 0&&cs(e.format),e}var us=class extends Error{constructor(t=""){super(t)}},te={Err:us,_tlv:{encode:(r,t)=>{let{Err:e}=te;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length&1)throw new e("tlv.encode: unpadded data");let n=t.length/2,o=lr(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let s=n>127?lr(o.length/2|128):"";return lr(r)+s+o+t},decode(r,t){let{Err:e}=te,n=0;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length<2||t[n++]!==r)throw new e("tlv.decode: wrong tlv");let o=t[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new e("tlv.decode(long): indefinite length not supported");if(c>4)throw new e("tlv.decode(long): byte length is too big");let u=t.subarray(n,n+c);if(u.length!==c)throw new e("tlv.decode: length bytes not complete");if(u[0]===0)throw new e("tlv.decode(long): zero leftmost byte");for(let f of u)i=i<<8|f;if(n+=c,i<128)throw new e("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new e("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(r){let{Err:t}=te;if(r<Vt)throw new t("integer: negative integers are not allowed");let e=lr(r);if(Number.parseInt(e[0],16)&8&&(e="00"+e),e.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return e},decode(r){let{Err:t}=te;if(r[0]&128)throw new t("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return Te(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=te,o=N(r,void 0,"signature"),{v:s,l:i}=n.decode(48,o);if(i.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:u,l:f}=n.decode(2,c);if(f.length)throw new t("invalid signature: left bytes after parsing");return{r:e.decode(a),s:e.decode(u)}},hexFromSig(r){let{_tlv:t,_int:e}=te,n=t.encode(2,e.encode(r.r)),o=t.encode(2,e.encode(r.s)),s=n+o;return t.encode(48,s)}},Vt=BigInt(0),Ue=BigInt(1),Ta=BigInt(2),ln=BigInt(3),Jf=BigInt(4);function Ra(r,t={}){let e=Qr("weierstrass",r,t),{Fp:n,Fn:o}=e,s=e.CURVE,{h:i,n:a}=s;Wt(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c}=t;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=Pa(n,o);function f(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function l(C,m,g){let{x:p,y:_}=m.toAffine(),B=n.toBytes(p);if(zt(g,"isCompressed"),g){f();let L=!n.isOdd(_);return mt(ka(L),B)}else return mt(Uint8Array.of(4),B,n.toBytes(_))}function d(C){N(C,void 0,"Point");let{publicKey:m,publicKeyUncompressed:g}=u,p=C.length,_=C[0],B=C.subarray(1);if(p===m&&(_===2||_===3)){let L=n.fromBytes(B);if(!n.isValid(L))throw new Error("bad point: is not on curve, wrong x");let T=v(L),D;try{D=n.sqrt(T)}catch($){let z=$ instanceof Error?": "+$.message:"";throw new Error("bad point: is not on curve, sqrt error"+z)}f();let R=n.isOdd(D);return(_&1)===1!==R&&(D=n.neg(D)),{x:L,y:D}}else if(p===g&&_===4){let L=n.BYTES,T=n.fromBytes(B.subarray(0,L)),D=n.fromBytes(B.subarray(L,L*2));if(!x(T,D))throw new Error("bad point: is not on curve");return{x:T,y:D}}else throw new Error(`bad point: got length ${p}, expected compressed=${m} or uncompressed=${g}`)}let y=t.toBytes||l,h=t.fromBytes||d;function v(C){let m=n.sqr(C),g=n.mul(m,C);return n.add(n.add(g,n.mul(C,s.a)),s.b)}function x(C,m){let g=n.sqr(m),p=v(C);return n.eql(g,p)}if(!x(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let b=n.mul(n.pow(s.a,ln),Jf),I=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(b,I)))throw new Error("bad curve params: a or b");function w(C,m,g=!1){if(!n.isValid(m)||g&&n.is0(m))throw new Error(`bad point coordinate ${C}`);return m}function A(C){if(!(C instanceof E))throw new Error("Weierstrass Point expected")}function k(C){if(!c||!c.basises)throw new Error("no endo");return Qf(C,c.basises,o.ORDER)}let U=Re((C,m)=>{let{X:g,Y:p,Z:_}=C;if(n.eql(_,n.ONE))return{x:g,y:p};let B=C.is0();m==null&&(m=B?n.ONE:n.inv(_));let L=n.mul(g,m),T=n.mul(p,m),D=n.mul(_,m);if(B)return{x:n.ZERO,y:n.ZERO};if(!n.eql(D,n.ONE))throw new Error("invZ was invalid");return{x:L,y:T}}),M=Re(C=>{if(C.is0()){if(t.allowInfinityPoint&&!n.is0(C.Y))return;throw new Error("bad point: ZERO")}let{x:m,y:g}=C.toAffine();if(!n.isValid(m)||!n.isValid(g))throw new Error("bad point: x or y not field elements");if(!x(m,g))throw new Error("bad point: equation left != right");if(!C.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function S(C,m,g,p,_){return g=new E(n.mul(g.X,C),g.Y,g.Z),m=mr(p,m),g=mr(_,g),m.add(g)}class E{static BASE=new E(s.Gx,s.Gy,n.ONE);static ZERO=new E(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(m,g,p){this.X=w("x",m),this.Y=w("y",g,!0),this.Z=w("z",p),Object.freeze(this)}static CURVE(){return s}static fromAffine(m){let{x:g,y:p}=m||{};if(!m||!n.isValid(g)||!n.isValid(p))throw new Error("invalid affine point");if(m instanceof E)throw new Error("projective point not allowed");return n.is0(g)&&n.is0(p)?E.ZERO:new E(g,p,n.ONE)}static fromBytes(m){let g=E.fromAffine(h(N(m,void 0,"point")));return g.assertValidity(),g}static fromHex(m){return E.fromBytes(qt(m))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(m=8,g=!0){return K.createCache(this,m),g||this.multiply(ln),this}assertValidity(){M(this)}hasEvenY(){let{y:m}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(m)}equals(m){A(m);let{X:g,Y:p,Z:_}=this,{X:B,Y:L,Z:T}=m,D=n.eql(n.mul(g,T),n.mul(B,_)),R=n.eql(n.mul(p,T),n.mul(L,_));return D&&R}negate(){return new E(this.X,n.neg(this.Y),this.Z)}double(){let{a:m,b:g}=s,p=n.mul(g,ln),{X:_,Y:B,Z:L}=this,T=n.ZERO,D=n.ZERO,R=n.ZERO,O=n.mul(_,_),$=n.mul(B,B),z=n.mul(L,L),q=n.mul(_,B);return q=n.add(q,q),R=n.mul(_,L),R=n.add(R,R),T=n.mul(m,R),D=n.mul(p,z),D=n.add(T,D),T=n.sub($,D),D=n.add($,D),D=n.mul(T,D),T=n.mul(q,T),R=n.mul(p,R),z=n.mul(m,z),q=n.sub(O,z),q=n.mul(m,q),q=n.add(q,R),R=n.add(O,O),O=n.add(R,O),O=n.add(O,z),O=n.mul(O,q),D=n.add(D,O),z=n.mul(B,L),z=n.add(z,z),O=n.mul(z,q),T=n.sub(T,O),R=n.mul(z,$),R=n.add(R,R),R=n.add(R,R),new E(T,D,R)}add(m){A(m);let{X:g,Y:p,Z:_}=this,{X:B,Y:L,Z:T}=m,D=n.ZERO,R=n.ZERO,O=n.ZERO,$=s.a,z=n.mul(s.b,ln),q=n.mul(g,B),G=n.mul(p,L),rt=n.mul(_,T),Lt=n.add(g,p),Z=n.add(B,L);Lt=n.mul(Lt,Z),Z=n.add(q,G),Lt=n.sub(Lt,Z),Z=n.add(g,_);let it=n.add(B,T);return Z=n.mul(Z,it),it=n.add(q,rt),Z=n.sub(Z,it),it=n.add(p,_),D=n.add(L,T),it=n.mul(it,D),D=n.add(G,rt),it=n.sub(it,D),O=n.mul($,Z),D=n.mul(z,rt),O=n.add(D,O),D=n.sub(G,O),O=n.add(G,O),R=n.mul(D,O),G=n.add(q,q),G=n.add(G,q),rt=n.mul($,rt),Z=n.mul(z,Z),G=n.add(G,rt),rt=n.sub(q,rt),rt=n.mul($,rt),Z=n.add(Z,rt),q=n.mul(G,Z),R=n.add(R,q),q=n.mul(it,Z),D=n.mul(Lt,D),D=n.sub(D,q),q=n.mul(Lt,G),O=n.mul(it,O),O=n.add(O,q),new E(D,R,O)}subtract(m){return this.add(m.negate())}is0(){return this.equals(E.ZERO)}multiply(m){let{endo:g}=t;if(!o.isValidNot0(m))throw new Error("invalid scalar: out of range");let p,_,B=L=>K.cached(this,L,T=>le(E,T));if(g){let{k1neg:L,k1:T,k2neg:D,k2:R}=k(m),{p:O,f:$}=B(T),{p:z,f:q}=B(R);_=$.add(q),p=S(g.beta,O,z,L,D)}else{let{p:L,f:T}=B(m);p=L,_=T}return le(E,[p,_])[0]}multiplyUnsafe(m){let{endo:g}=t,p=this;if(!o.isValid(m))throw new Error("invalid scalar: out of range");if(m===Vt||p.is0())return E.ZERO;if(m===Ue)return p;if(K.hasCache(this))return this.multiply(m);if(g){let{k1neg:_,k1:B,k2neg:L,k2:T}=k(m),{p1:D,p2:R}=fa(E,p,B,T);return S(g.beta,D,R,_,L)}else return K.unsafe(p,m)}toAffine(m){return U(this,m)}isTorsionFree(){let{isTorsionFree:m}=t;return i===Ue?!0:m?m(E,this):K.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:m}=t;return i===Ue?this:m?m(E,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(m=!0){return zt(m,"isCompressed"),this.assertValidity(),y(E,this,m)}toHex(m=!0){return Kt(this.toBytes(m))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let P=o.BITS,K=new Oe(E,t.endo?Math.ceil(P/2):P);return E.BASE.precompute(8),E}function ka(r){return Uint8Array.of(r?2:3)}function Pa(r,t){return{secretKey:t.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function tl(r,t={}){let{Fn:e}=r,n=t.randomBytes||Ce,o=Object.assign(Pa(r.Fp,e),{seed:Po(e.ORDER)});function s(y){try{let h=e.fromBytes(y);return e.isValidNot0(h)}catch{return!1}}function i(y,h){let{publicKey:v,publicKeyUncompressed:x}=o;try{let b=y.length;return h===!0&&b!==v||h===!1&&b!==x?!1:!!r.fromBytes(y)}catch{return!1}}function a(y=n(o.seed)){return Oo(N(y,o.seed,"seed"),e.ORDER)}function c(y,h=!0){return r.BASE.multiply(e.fromBytes(y)).toBytes(h)}function u(y){let{secretKey:h,publicKey:v,publicKeyUncompressed:x}=o;if(!se(y)||"_lengths"in e&&e._lengths||h===v)return;let b=N(y,void 0,"key").length;return b===v||b===x}function f(y,h,v=!0){if(u(y)===!0)throw new Error("first arg must be private key");if(u(h)===!1)throw new Error("second arg must be public key");let x=e.fromBytes(y);return r.fromBytes(h).multiply(x).toBytes(v)}let l={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},d=Jr(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:f,keygen:d,Point:r,utils:l,lengths:o})}function Oa(r,t,e={}){Gr(t),Wt(e,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),e=Object.assign({},e);let n=e.randomBytes||Ce,o=e.hmac||((g,p)=>is(t,g,p)),{Fp:s,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:u,getPublicKey:f,getSharedSecret:l,utils:d,lengths:y}=tl(r,e),h={prehash:!0,lowS:typeof e.lowS=="boolean"?e.lowS:!0,format:"compact",extraEntropy:!1},v=a*Ta<s.ORDER;function x(g){let p=a>>Ue;return g>p}function b(g,p){if(!i.isValidNot0(p))throw new Error(`invalid signature ${g}: out of range 1..Point.Fn.ORDER`);return p}function I(){if(v)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function w(g,p){cs(p);let _=y.signature,B=p==="compact"?_:p==="recovered"?_+1:void 0;return N(g,B)}class A{r;s;recovery;constructor(p,_,B){if(this.r=b("r",p),this.s=b("s",_),B!=null){if(I(),![0,1,2,3].includes(B))throw new Error("invalid recovery id");this.recovery=B}Object.freeze(this)}static fromBytes(p,_=h.format){w(p,_);let B;if(_==="der"){let{r:R,s:O}=te.toSig(N(p));return new A(R,O)}_==="recovered"&&(B=p[0],_="compact",p=p.subarray(1));let L=y.signature/2,T=p.subarray(0,L),D=p.subarray(L,L*2);return new A(i.fromBytes(T),i.fromBytes(D),B)}static fromHex(p,_){return this.fromBytes(qt(p),_)}assertRecovery(){let{recovery:p}=this;if(p==null)throw new Error("invalid recovery id: must be present");return p}addRecoveryBit(p){return new A(this.r,this.s,p)}recoverPublicKey(p){let{r:_,s:B}=this,L=this.assertRecovery(),T=L===2||L===3?_+a:_;if(!s.isValid(T))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let D=s.toBytes(T),R=r.fromBytes(mt(ka((L&1)===0),D)),O=i.inv(T),$=U(N(p,void 0,"msgHash")),z=i.create(-$*O),q=i.create(B*O),G=r.BASE.multiplyUnsafe(z).add(R.multiplyUnsafe(q));if(G.is0())throw new Error("invalid recovery: point at infinify");return G.assertValidity(),G}hasHighS(){return x(this.s)}toBytes(p=h.format){if(cs(p),p==="der")return qt(te.hexFromSig(this));let{r:_,s:B}=this,L=i.toBytes(_),T=i.toBytes(B);return p==="recovered"?(I(),mt(Uint8Array.of(this.assertRecovery()),L,T)):mt(L,T)}toHex(p){return Kt(this.toBytes(p))}}let k=e.bits2int||function(p){if(p.length>8192)throw new Error("input is too large");let _=Te(p),B=p.length*8-c;return B>0?_>>BigInt(B):_},U=e.bits2int_modN||function(p){return i.create(k(p))},M=hr(c);function S(g){return dr("num < 2^"+c,g,Vt,M),i.toBytes(g)}function E(g,p){return N(g,void 0,"message"),p?N(t(g),void 0,"prehashed message"):g}function P(g,p,_){let{lowS:B,prehash:L,extraEntropy:T}=as(_,h);g=E(g,L);let D=U(g),R=i.fromBytes(p);if(!i.isValidNot0(R))throw new Error("invalid private key");let O=[S(R),S(D)];if(T!=null&&T!==!1){let G=T===!0?n(y.secretKey):T;O.push(N(G,void 0,"extraEntropy"))}let $=mt(...O),z=D;function q(G){let rt=k(G);if(!i.isValidNot0(rt))return;let Lt=i.inv(rt),Z=r.BASE.multiply(rt).toAffine(),it=i.create(Z.x);if(it===Vt)return;let Or=i.create(Lt*i.create(z+it*R));if(Or===Vt)return;let Zs=(Z.x===it?0:2)|Number(Z.y&Ue),Ys=Or;return B&&x(Or)&&(Ys=i.neg(Or),Zs^=1),new A(it,Ys,v?void 0:Zs)}return{seed:$,k2sig:q}}function K(g,p,_={}){let{seed:B,k2sig:L}=P(g,p,_);return Zi(t.outputLen,i.BYTES,o)(B,L).toBytes(_.format)}function C(g,p,_,B={}){let{lowS:L,prehash:T,format:D}=as(B,h);if(_=N(_,void 0,"publicKey"),p=E(p,T),!se(g)){let R=g instanceof A?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+R)}w(g,D);try{let R=A.fromBytes(g,D),O=r.fromBytes(_);if(L&&R.hasHighS())return!1;let{r:$,s:z}=R,q=U(p),G=i.inv(z),rt=i.create(q*G),Lt=i.create($*G),Z=r.BASE.multiplyUnsafe(rt).add(O.multiplyUnsafe(Lt));return Z.is0()?!1:i.create(Z.x)===$}catch{return!1}}function m(g,p,_={}){let{prehash:B}=as(_,h);return p=E(p,B),A.fromBytes(g,"recovered").recoverPublicKey(p).toBytes()}return Object.freeze({keygen:u,getPublicKey:f,getSharedSecret:l,utils:d,lengths:y,Point:r,sign:K,verify:C,recoverPublicKey:m,Signature:A,hash:t})}var ls={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},el={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Na=BigInt(2);function rl(r){let t=ls.p,e=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=r*r*r%t,f=u*u*r%t,l=V(f,e,t)*f%t,d=V(l,e,t)*f%t,y=V(d,Na,t)*u%t,h=V(y,o,t)*y%t,v=V(h,s,t)*h%t,x=V(v,a,t)*v%t,b=V(x,c,t)*x%t,I=V(b,a,t)*v%t,w=V(I,e,t)*f%t,A=V(w,i,t)*h%t,k=V(A,n,t)*u%t,U=V(k,Na,t);if(!fs.eql(fs.sqr(U),r))throw new Error("Cannot find square root");return U}var fs=ke(ls.p,{sqrt:rl}),nl=Ra(ls,{Fp:fs,endo:el}),Me=Oa(nl,Vi);function Ua(r,t,e,n){let o=or.digest(e instanceof Uint8Array?e:e.subarray());if(nn(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),Me.verify(t,s,r,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new gr(String(s))});try{return n?.signal?.throwIfAborted(),Me.verify(t,o.digest,r,{prehash:!1,format:"der"})}catch(s){throw new gr(String(s))}}var dn=class{type="secp256k1";raw;_key;constructor(t){this._key=Ka(t),this.raw=Ma(this._key)}toMultihash(){return It.digest(De(this))}toCID(){return at.createV1(114,this.toMultihash())}toString(){return j.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:lt(this.raw,t.raw)}verify(t,e,n){return Ua(this._key,e,t,n)}};function qa(r){return new dn(r)}function Ma(r){return Me.Point.fromBytes(r).toBytes()}function Ka(r){try{return Me.Point.fromBytes(r),r}catch(t){throw new Ur(String(t))}}function Fa(r){let{Type:t,Data:e}=Sr.decode(r.digest),n=e??new Uint8Array;switch(t){case ht.Ed25519:return xa(n);case ht.secp256k1:return qa(n);case ht.ECDSA:return Ai(n);default:throw new Qe}}function De(r){return Sr.encode({Type:ht[r.type],Data:r.raw})}var za=Symbol.for("nodejs.util.inspect.custom"),ol=114,vr=class{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Vn]=!0;toString(){return this.string==null&&(this.string=j.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return at.createV1(ol,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return lt(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return lt(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[za](){return`PeerId(${this.toString()})`}},hn=class extends vr{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},pn=class extends vr{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},mn=class extends vr{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},sl=2336,gn=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=It.digest(H(this.url))}[za](){return`PeerId(${this.url})`}[Vn]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return at.createV1(sl,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=W(t)),t.toString()===this.toString())}};function Va(r){if(al(r))return new hn({multihash:r});if(il(r))try{let t=Fa(r);if(t.type==="Ed25519")return new pn({multihash:r,publicKey:t});if(t.type==="secp256k1")return new mn({multihash:r,publicKey:t})}catch{let e=W(r.digest);return new gn(new URL(e))}throw new Mr("Supplied PeerID Multihash is invalid")}function il(r){return r.code===It.code}function al(r){return r.code===or.code}function ds(r,t){let e={[Symbol.iterator]:()=>e,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:t(o)}}};return e}function bn(r){let t=rr(j.decode(`z${r}`));return Va(t)}var yn=class r{set;constructor(t){if(this.set=new Set,t!=null)for(let e of t)this.set.add(e.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(t){this.set.add(t.toString())}clear(){this.set.clear()}delete(t){this.set.delete(t.toString())}entries(){return ds(this.set.entries(),t=>{let e=bn(t[0]);return[e,e]})}forEach(t){this.set.forEach(e=>{let n=bn(e);t(n,n,this)})}has(t){return this.set.has(t.toString())}values(){return ds(this.set.values(),t=>bn(t))}intersection(t){let e=new r;for(let n of t)this.has(n)&&e.add(n);return e}difference(t){let e=new r;for(let n of this)t.has(n)||e.add(n);return e}union(t){let e=new r;for(let n of t)e.add(n);for(let n of this)e.add(n);return e}};function hs(){return new yn}var ps={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Ha={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},$a=new globalThis.TextEncoder;function cl(r,t){let e=ps[t],n=Ha[t];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(t,n*e);return n}function ul(r,t,e){if(e.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=ps[t],o=Ha[t],s=r;for(;s.length>0;){let i=$a.encodeInto(s,e);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(e[a]),o=BigInt.asUintN(t,o*n)}return o}function ms(r,{size:t=32,utf8Buffer:e}={}){if(!ps[t])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(e)return ul(r,t,e);r=$a.encode(r)}return cl(r,t)}var _r={hash:r=>Number(ms(r,{size:32})),hashV:(r,t)=>fl(_r.hash(r,t))};function fl(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),H(t,"base16")}var gs=64,Dt=class{fp;h;seed;constructor(t,e,n,o=2){if(o>gs)throw new TypeError("Invalid Fingerprint Size");let s=e.hashV(t,n),i=yt(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=e,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(t){return t?.fp instanceof Uint8Array?lt(this.fp,t.fp):!1}};function me(r,t){return Math.floor(Math.random()*(t-r))+r}var ge=class{contents;constructor(t){this.contents=new Array(t).fill(null)}has(t){if(!(t instanceof Dt))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof Dt))throw new TypeError("Invalid Fingerprint");for(let e=0;e<this.contents.length;e++)if(this.contents[e]==null)return this.contents[e]=t,!0;return!0}swap(t){if(!(t instanceof Dt))throw new TypeError("Invalid Fingerprint");let e=me(0,this.contents.length-1),n=this.contents[e];return this.contents[e]=t,n}remove(t){if(!(t instanceof Dt))throw new TypeError("Invalid Fingerprint");let e=this.contents.findIndex(n=>t.equals(n));return e>-1?(this.contents[e]=null,!0):!1}};var ll=500,Ir=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(t){this.filterSize=t.filterSize,this.bucketSize=t.bucketSize??4,this.fingerprintSize=t.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=t.hash??_r,this.seed=t.seed??me(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=H(t));let e=new Dt(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=(n^e.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new ge(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new ge(this.bucketSize)),this.buckets[n].add(e)||this.buckets[o].add(e))return this.count++,!0;let s=[n,o],i=s[me(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new ge(this.bucketSize));for(let a=0;a<ll;a++){let c=this.buckets[i].swap(e);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new ge(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(t){typeof t=="string"&&(t=H(t));let e=new Dt(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=this.buckets[n]?.has(e)??!1;if(o)return o;let s=(n^e.hash())%this.filterSize;return this.buckets[s]?.has(e)??!1}remove(t){typeof t=="string"&&(t=H(t));let e=new Dt(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=this.buckets[n]?.remove(e)??!1;if(o)return this.count--,o;let s=(n^e.hash())%this.filterSize,i=this.buckets[s]?.remove(e)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},dl={1:.5,2:.84,4:.95,8:.98};function hl(r=.001){return r>.002?2:r>1e-5?4:8}function Ga(r,t=.001){let e=hl(t),n=dl[e],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),gs);return{filterSize:o,bucketSize:e,fingerprintSize:s}}var xn=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(t){this.bucketSize=t.bucketSize??4,this.filterSize=t.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=t.fingerprintSize??2,this.scale=t.scale??2,this.hash=t.hash??_r,this.seed=t.seed??me(0,Math.pow(2,10)),this.filterSeries=[new Ir({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(t){if(typeof t=="string"&&(t=H(t)),this.has(t))return!0;let e=this.filterSeries.find(n=>n.reliable);if(e==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);e=new Ir({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(e)}return e.add(t)}has(t){typeof t=="string"&&(t=H(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].has(t))return!0;return!1}remove(t){typeof t=="string"&&(t=H(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].remove(t))return!0;return!1}get count(){return this.filterSeries.reduce((t,e)=>t+e.count,0)}};function bs(r,t=.001,e){return new xn({...Ga(r,t),...e??{}})}function ee(r){let t=r.getComponents(),e={},n=0;if(t[n]?.name==="ip6zone"&&(e.zone=`${t[n].value}`,n++),t[n].name==="ip4"||t[n].name==="ip6"||t[n].name==="dns"||t[n].name==="dns4"||t[n].name==="dns6"?(e.type=t[n].name,e.host=t[n].value,n++):t[n].name==="dnsaddr"&&(e.type=t[n].name,e.host=`_dnsaddr.${t[n].value}`,n++),(t[n]?.name==="tcp"||t[n]?.name==="udp")&&(e.protocol=t[n].name==="tcp"?"tcp":"udp",e.port=parseInt(`${t[n].value}`),n++),t[n]?.name==="ipcidr"&&(e.type==="ip4"?e.cidr=parseInt(`${t[n].value}`):e.type==="ip6"&&(e.cidr=`${t[n].value}`),n++),e.type==null||e.host==null)throw new ft(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return t[n]?.name==="tls"&&t[n+1]?.name==="sni"&&(e.sni=t[n+1].value,n+=2),e}var wn=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let e=this.index,n=t();return n===void 0&&(this.index=e),n}parseWith(t){let e=t();if(this.index===this.input.length)return e}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(t){return this.readAtomically(()=>{let e=this.readChar();if(e===t)return e})}readSeparator(t,e,n){return this.readAtomically(()=>{if(!(e>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,e,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 f=this.readAtomically(()=>{let l=this.readChar();if(l===void 0)return;let d=Number.parseInt(l,t);if(!Number.isNaN(d))return d});if(f===void 0)break;if(s*=t,s+=f,s>u||(i+=1,e!==void 0&&i>e))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let e=0;e<t.length;e++){let n=this.readSeparator(".",e,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[e]=n}return t})}readIPv6Addr(){let t=e=>{for(let n=0;n<e.length/2;n++){let o=n*2;if(n<e.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return e[o]=i[0],e[o+1]=i[1],e[o+2]=i[2],e[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];e[o]=s>>8,e[o+1]=s&255}return[e.length,!1]};return this.readAtomically(()=>{let e=new Uint8Array(16),[n,o]=t(e);if(n===16)return e;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=t(s.subarray(0,i));return e.set(s.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Za=45,pl=15,Ke=new wn;function En(r){if(!(r.length>pl))return Ke.new(r).parseWith(()=>Ke.readIPv4Addr())}function Sn(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Za))return Ke.new(r).parseWith(()=>Ke.readIPv6Addr())}function qe(r,t=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>Za)return;let e=Ke.new(r).parseWith(()=>Ke.readIPAddr());if(e)return t&&e.length===4?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,e[0],e[1],e[2],e[3]]):e}function Ya(r,t,e){let n=0;for(let o of r)if(!(n<t)){if(n>e)break;if(o!==255)return!1;n++}return!0}function ja(r,t,e,n){let o=0;for(let s of r)if(!(o<e)){if(o>n)break;if(s!==t[o])return!1;o++}return!0}function ys(r){switch(r.length){case be:return r.join(".");case ye:{let t=[];for(let e=0;e<r.length;e++)e%2===0&&t.push(r[e].toString(16).padStart(2,"0")+r[e+1].toString(16).padStart(2,"0"));return t.join(":")}default:throw new Error("Invalid ip length")}}function Xa(r){let t=0;for(let[e,n]of r.entries()){if(n===255){t+=8;continue}for(;(n&128)!=0;)t++,n=n<<1;if((n&128)!=0)return-1;for(let o=e+1;o<r.length;o++)if(r[o]!=0)return-1;break}return t}function Wa(r){let t="0x";for(let e of r)t+=(e>>4).toString(16)+(e&15).toString(16);return t}var be=4,ye=16,xb=parseInt("0xFFFF",16),ml=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Ar(r,t){t.length===ye&&r.length===be&&Ya(t,0,11)&&(t=t.slice(12)),t.length===be&&r.length===ye&&ja(r,ml,0,11)&&(r=r.slice(12));let e=r.length;if(e!=t.length)throw new Error("Failed to mask ip");let n=new Uint8Array(e);for(let o=0;o<e;o++)n[o]=r[o]&t[o];return n}function Qa(r,t){if(typeof t=="string"&&(t=qe(t)),t==null)throw new Error("Invalid ip");if(t.length!==r.network.length)return!1;for(let e=0;e<t.length;e++)if((r.network[e]&r.mask[e])!==(t[e]&r.mask[e]))return!1;return!0}function xs(r){let[t,e]=r.split("/");if(!t||!e)throw new Error("Failed to parse given CIDR: "+r);let n=be,o=En(t);if(o==null&&(n=ye,o=Sn(t),o==null))throw new Error("Failed to parse given CIDR: "+r);let s=parseInt(e,10);if(Number.isNaN(s)||String(s).length!==e.length||s<0||s>n*8)throw new Error("Failed to parse given CIDR: "+r);let i=ws(s,8*n);return{network:Ar(o,i),mask:i}}function ws(r,t){if(t!==8*be&&t!==8*ye)throw new Error("Invalid CIDR mask");if(r<0||r>t)throw new Error("Invalid CIDR mask");let e=t/8,n=new Uint8Array(e);for(let o=0;o<e;o++){if(r>=8){n[o]=255,r-=8;continue}n[o]=255-(255>>r),r=0}return n}var Br=class{constructor(t,e){if(e==null)({network:this.network,mask:this.mask}=xs(t));else{let n=qe(t);if(n==null)throw new Error("Failed to parse network");e=String(e);let o=parseInt(e,10);if(Number.isNaN(o)||String(o).length!==e.length||o<0||o>n.length*8){let s=qe(e);if(s==null)throw new Error("Failed to parse mask");this.mask=s}else this.mask=ws(o,8*n.length);this.network=Ar(n,this.mask)}}contains(t){return Qa({network:this.network,mask:this.mask},t)}toString(){let t=Xa(this.mask),e=t!==-1?String(t):Wa(this.mask);return ys(this.network)+"/"+e}};function Ja(r,t){return new Br(r).contains(t)}function tc(r){try{let t=ee(r);switch(t.type){case"ip6":return Ja("2000::/3",t.host);default:return!1}}catch{return!1}}function Fe(r){return!!En(r)}function vn(r){return!!Sn(r)}var oc=Mc(nc(),1),Sl=["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"],vl=Sl.map(r=>new oc.Netmask(r));function Bs(r){for(let t of vl)if(t.contains(r))return!0;return!1}function _l(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function Il(r){let t=r.split(":");if(t.length<2)return!1;let e=t[t.length-1].padStart(4,"0"),n=t[t.length-2].padStart(4,"0"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(e.substring(0,2),16)}.${parseInt(e.substring(2),16)}`;return Bs(o)}function Al(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function Bl(r){let t=r.split(":"),e=t[t.length-1];return Bs(e)}function Dl(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 In(r){if(Fe(r))return Bs(r);if(_l(r))return Il(r);if(Al(r))return Bl(r);if(vn(r))return Dl(r)}function sc(r){try{let t=ee(r);switch(t.type){case"ip4":case"ip6":return In(t.host)??!1;default:return t.host==="localhost"}}catch{return!1}}function $e(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var An=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||(t-1&t)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},Ge=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new An(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){let e=this.head;this.head=e.next=new An(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let e=this.tail.next;this.tail.next=null,this.tail=e,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var Ds=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function Bn(r={}){return Ll(e=>{let n=e.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function Ll(r,t){t=t??{};let e=t.onEnd,n=new Ge,o,s,i,a=$e(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((x,b)=>{s=I=>{s=null,n.push(I);try{x(r(n))}catch(w){b(w)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=$e()})}},u=x=>s!=null?s(x):(n.push(x),o),f=x=>(n=new Ge,s!=null?s({error:x}):(n.push({error:x}),o)),l=x=>{if(i)return o;if(t?.objectMode!==!0&&x?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:x})},d=x=>i?o:(i=!0,x!=null?f(x):u({done:!0})),y=()=>(n=new Ge,d(),{done:!0}),h=x=>(d(x),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:y,throw:h,push:l,end:d,get readableLength(){return n.size},onEmpty:async x=>{let b=x?.signal;if(b?.throwIfAborted(),n.isEmpty())return;let I,w;b!=null&&(I=new Promise((A,k)=>{w=()=>{k(new Ds)},b.addEventListener("abort",w)}));try{await Promise.race([a.promise,I])}finally{w!=null&&b!=null&&b?.removeEventListener("abort",w)}}},e==null)return o;let v=o;return o={[Symbol.asyncIterator](){return this},next(){return v.next()},throw(x){return v.throw(x),e!=null&&(e(x),e=void 0),{done:!0}},return(){return v.return(),e!=null&&(e(),e=void 0),{done:!0}},push:l,end(x){return v.end(x),e!=null&&(e(x),e=void 0),o},get readableLength(){return v.readableLength},onEmpty:x=>v.onEmpty(x)},o}var Ls=class r extends Error{name="TimeoutError";constructor(t,e){super(t,e),Error.captureStackTrace?.(this,r)}},ic=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function Cs(r,t){let{milliseconds:e,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=t,a,c,f=new Promise((l,d)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(i?.aborted){d(ic(i));return}if(i&&(c=()=>{d(ic(i))},i.addEventListener("abort",c,{once:!0})),r.then(l,d),e===Number.POSITIVE_INFINITY)return;let y=new Ls;a=s.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(h){d(h)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?l():o instanceof Error?d(o):(y.message=o??`Promise timed out after ${e} milliseconds`,d(y))},e)}).finally(()=>{f.clear(),c&&i&&i.removeEventListener("abort",c)});return f.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},f}var Cl=r=>{let t=r.addEventListener||r.on||r.addListener,e=r.removeEventListener||r.off||r.removeListener;if(!t||!e)throw new TypeError("Emitter is not compatible");return{addListener:t.bind(r),removeListener:e.bind(r)}};function Tl(r,t,e){let n,o=new Promise((s,i)=>{if(e={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...e},!(e.count>=0&&(e.count===Number.POSITIVE_INFINITY||Number.isInteger(e.count))))throw new TypeError("The `count` option should be at least 0 or more");e.signal?.throwIfAborted();let a=[t].flat(),c=[],{addListener:u,removeListener:f}=Cl(r),l=async(...y)=>{let h=e.multiArgs?y:y[0];if(e.filter)try{if(!await e.filter(h))return}catch(v){n(),i(v);return}c.push(h),e.count===c.length&&(n(),s(c))},d=(...y)=>{n(),i(e.rejectionMultiArgs?y:y[0])};n=()=>{for(let y of a)f(y,l);for(let y of e.rejectionEvents)a.includes(y)||f(y,d)};for(let y of a)u(y,l);for(let y of e.rejectionEvents)a.includes(y)||u(y,d);e.signal&&e.signal.addEventListener("abort",()=>{d(e.signal.reason)},{once:!0}),e.resolveImmediately&&s(c)});if(o.cancel=n,typeof e.timeout=="number"){let s=Cs(o,{milliseconds:e.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function Ze(r,t,e){typeof e=="function"&&(e={filter:e}),e={...e,count:1,resolveImmediately:!1};let n=Tl(r,t,e),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function Dr(r,t){let e,n=function(){let o=function(){e=void 0,r()};clearTimeout(e),e=setTimeout(o,t)};return n.start=()=>{},n.stop=()=>{clearTimeout(e)},n}var Dn=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}},we=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"};function Rl(r){return r.reason}async function Lr(r,t,e){if(t==null)return r;let n=e?.translateError??Rl;if(t.aborted)return r.catch(()=>{}),Promise.reject(n(t));let o;try{return await Promise.race([r,new Promise((s,i)=>{o=()=>{i(n(t))},t.addEventListener("abort",o)})])}finally{o!=null&&t.removeEventListener("abort",o)}}var Ln=class{deferred;signal;constructor(t){this.signal=t,this.deferred=$e(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Pt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function kl(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Cn=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=kl(),this.status="queued",this.fn=t,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(t){this.controller.abort(t)}onAbort(){this.recipients.reduce((e,n)=>e&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Pt),this.cleanup())}async join(t={}){let e=new Ln(t.signal);return this.recipients.push(e),t.signal?.addEventListener("abort",this.onAbort),e.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let t=await Lr(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(e=>{e.deferred.resolve(t)}),this.status="complete"}catch(t){this.recipients.forEach(e=>{e.deferred.reject(t)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(t=>{t.cleanup(),t.signal?.removeEventListener("abort",this.onAbort)})}};var Tn=class extends Kr{concurrency;maxSize;queue;pending;sort;paused;constructor(t={}){super(),this.concurrency=t.concurrency??Number.POSITIVE_INFINITY,this.maxSize=t.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,t.metricName!=null&&t.metrics?.registerMetricGroup(t.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=t.sort,this.queue=[],this.emitEmpty=Dr(this.emitEmpty.bind(this),1),this.emitIdle=Dr(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 t;for(let e of this.queue)if(e.status==="queued"){t=e;break}return t==null?!1:(this.safeDispatchEvent("active"),this.pending++,t.run().finally(()=>{for(let e=0;e<this.queue.length;e++)if(this.queue[e]===t){this.queue.splice(e,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(t){this.queue.push(t),this.sort!=null&&this.queue.sort(this.sort)}async add(t,e){if(e?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Dn;let n=new Cn(t,e);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(e).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(t=>{t.abort(new Pt)}),this.clear()}async onEmpty(t){this.size!==0&&await Ze(this,"empty",t)}async onSizeLessThan(t,e){this.size<t||await Ze(this,"next",{...e,filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await Ze(this,"idle",t)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(t){t?.signal?.throwIfAborted();let e=Bn({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),e.end(c)},o=c=>{c.detail!=null&&e.push(c.detail)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new Pt("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",s),this.addEventListener("idle",i),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),t?.signal?.removeEventListener("abort",a),n()}}};function Cr(r){let t=new globalThis.AbortController;function e(){let s=r.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();t.abort(s);for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",e)}for(let s of r){if(s?.aborted===!0){e();break}s?.addEventListener!=null&&s.addEventListener("abort",e)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",e)}let o=t.signal;return o.clear=n,o}var ot=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Ht=class extends Error{static name="ValidationError";name="ValidationError"},Rn=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},kn=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function Rs(r){return t=>W(t,r)}function ks(r){return t=>H(t,r)}function Ye(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Ee(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(t)}function ac(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==16)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);let e=H(t[0],"base32"),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Ee(n);return Nt([e,o],e.length+o.length)}function cc(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let e=Zt.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Ee(n);return Nt([e,o],e.length+o.length)}function Ps(r){let t=r.subarray(0,r.length-2),e=r.subarray(r.length-2),n=W(t,"base32"),o=Ye(e);return`${n}:${o}`}var Os=function(r){r=r.toString().trim();let t=new Uint8Array(4);return r.split(/\./g).forEach((e,n)=>{let o=parseInt(e,10);if(isNaN(o)||o<0||o>255)throw new ot("Invalid byte value in IP address");t[n]=o}),t},uc=function(r){let t=0;r=r.toString().trim();let e=r.split(":",8),n;for(n=0;n<e.length;n++){let s=Fe(e[n]),i;s&&(i=Os(e[n]),e[n]=W(i.subarray(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,W(i.subarray(2,4),"base16"))}if(e[0]==="")for(;e.length<8;)e.unshift("0");else if(e[e.length-1]==="")for(;e.length<8;)e.push("0");else if(e.length<8){for(n=0;n<e.length&&e[n]!=="";n++);let s=[n,1];for(n=9-e.length;n>0;n--)s.push("0");e.splice.apply(e,s)}let o=new Uint8Array(t+16);for(n=0;n<e.length;n++){e[n]===""&&(e[n]="0");let s=parseInt(e[n],16);if(isNaN(s)||s<0||s>65535)throw new ot("Invalid byte value in IP address");o[t++]=s>>8&255,o[t++]=s&255}return o},fc=function(r){if(r.byteLength!==4)throw new ot("IPv4 address was incorrect length");let t=[];for(let e=0;e<r.byteLength;e++)t.push(r[e]);return t.join(".")},lc=function(r){if(r.byteLength!==16)throw new ot("IPv6 address was incorrect length");let t=[];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")}`;t.push(i)}let e=t.join(":");try{let n=new URL(`http://[${e}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new ot(`Invalid IPv6 address "${e}"`)}};function dc(r){try{let t=new URL(`http://[${r}]`);return t.hostname.substring(1,t.hostname.length-1)}catch{throw new ot(`Invalid IPv6 address "${r}"`)}}var Ts=Object.values(sr).map(r=>r.decoder),Pl=(function(){let r=Ts[0].or(Ts[1]);return Ts.slice(2).forEach(t=>r=r.or(t)),r})();function hc(r){return Pl.decode(r)}function pc(r){return t=>r.encoder.encode(t)}function Ol(r){if(parseInt(r).toString()!==r)throw new Ht("Value must be an integer")}function Nl(r){if(r<0)throw new Ht("Value must be a positive integer, or zero")}function Ul(r){return t=>{if(t>r)throw new Ht(`Value must be smaller than or equal to ${r}`)}}function Ml(...r){return t=>{for(let e of r)e(t)}}var Tr=Ml(Ol,Nl,Ul(65535));var et=-1,Ns=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(t){let e;if(typeof t=="string"?e=this.protocolsByName.get(t):e=this.protocolsByCode.get(t),e==null)throw new kn(`Protocol ${t} was unknown`);return e}addProtocol(t){this.protocolsByCode.set(t.code,t),this.protocolsByName.set(t.name,t),t.aliases?.forEach(e=>{this.protocolsByName.set(e,t)})}removeProtocol(t){let e=this.protocolsByCode.get(t);e!=null&&(this.protocolsByCode.delete(e.code),this.protocolsByName.delete(e.name),e.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},$t=new Ns,vd=[{code:4,name:"ip4",size:32,valueToBytes:Os,bytesToValue:fc,validate:r=>{if(!Fe(r))throw new Ht(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Ee,bytesToValue:Ye,validate:Tr},{code:273,name:"udp",size:16,valueToBytes:Ee,bytesToValue:Ye,validate:Tr},{code:33,name:"dccp",size:16,valueToBytes:Ee,bytesToValue:Ye,validate:Tr},{code:41,name:"ip6",size:128,valueToBytes:uc,bytesToValue:lc,stringToValue:dc,validate:r=>{if(!vn(r))throw new Ht(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:et},{code:43,name:"ipcidr",size:8,bytesToValue:Rs("base10"),valueToBytes:ks("base10")},{code:53,name:"dns",size:et},{code:54,name:"dns4",size:et},{code:55,name:"dns6",size:et},{code:56,name:"dnsaddr",size:et},{code:132,name:"sctp",size:16,valueToBytes:Ee,bytesToValue:Ye,validate:Tr},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:et,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:et,bytesToValue:Rs("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?ks("base58btc")(r):at.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Ps,valueToBytes:ac},{code:445,name:"onion3",size:296,bytesToValue:Ps,valueToBytes:cc},{code:446,name:"garlic64",size:et},{code:447,name:"garlic32",size:et},{code:448,name:"tls"},{code:449,name:"sni",size:et},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:et,bytesToValue:pc(oo),valueToBytes:hc},{code:480,name:"http"},{code:481,name:"http-path",size:et,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:et}];vd.forEach(r=>{$t.addProtocol(r)});function mc(r){let t=[],e=0;for(;e<r.length;){let n=br(r,e),o=$t.getProtocol(n),s=gt(n),i=_d(o,r,e+s),a=0;i>0&&o.size===et&&(a=gt(i));let c=s+a+i,u={code:n,name:o.name,bytes:r.subarray(e,e+c)};if(i>0){let f=e+s+a,l=r.subarray(f,f+i);u.value=o.bytesToValue?.(l)??W(l)}t.push(u),e+=c}return t}function gc(r){let t=0,e=[];for(let n of r){if(n.bytes==null){let o=$t.getProtocol(n.code),s=gt(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??H(n.value),a=i.byteLength,o.size===et&&(c=gt(a)));let u=new Uint8Array(s+c+a),f=0;Ne(n.code,u,f),f+=s,i!=null&&(o.size===et&&(Ne(a,u,f),f+=c),u.set(i,f)),n.bytes=u}e.push(n.bytes),t+=n.bytes.byteLength}return Nt(e,t)}function bc(r){if(r.charAt(0)!=="/")throw new ot('String multiaddr must start with "/"');let t=[],e="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(e==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=$t.getProtocol(o);if(e==="protocol"){if(c.size==null||c.size===0){t.push({code:c.code,name:c.name}),n="",o="",e="protocol";continue}else if(a)throw new ot(`Component ${o} was missing value`);e="value"}else if(e==="value"){let u={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new ot(`Component ${o} was missing value`);u.value=c.stringToValue?.(n)??n}t.push(u),n="",o="",e="protocol"}}}if(o!==""&&n!=="")throw new ot("Incomplete multiaddr");return t}function yc(r){return`/${r.flatMap(t=>{if(t.value==null)return t.name;let e=$t.getProtocol(t.code);if(e==null)throw new ot(`Unknown protocol code ${t.code}`);return[t.name,e.valueToString?.(t.value)??t.value]}).join("/")}`}function _d(r,t,e){return r.size==null||r.size===0?0:r.size>0?r.size/8:br(t,e)}var Id=Symbol.for("nodejs.util.inspect.custom"),Ks=Symbol.for("@multiformats/multiaddr");function Ad(r){if(r==null&&(r="/"),xc(r))return r.getComponents();if(r instanceof Uint8Array)return mc(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),bc(r);if(Array.isArray(r))return r;throw new ot("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Pn=class r{[Ks]=!0;#t;#e;#r;constructor(t="/",e={}){this.#t=Ad(t),e.validate!==!1&&Bd(this)}get bytes(){return this.#r==null&&(this.#r=gc(this.#t)),this.#r}toString(){return this.#e==null&&(this.#e=yc(this.#t)),this.#e}toJSON(){return this.toString()}getComponents(){return[...this.#t.map(t=>({...t}))]}encapsulate(t){let e=new r(t);return new r([...this.#t,...e.getComponents()],{validate:!1})}decapsulate(t){let e=t.toString(),n=this.toString(),o=n.lastIndexOf(e);if(o<0)throw new Rn(`Address ${this.toString()} does not contain subaddress: ${e}`);return new r(n.slice(0,o),{validate:!1})}decapsulateCode(t){let e;for(let n=this.#t.length-1;n>-1;n--)if(this.#t[n].code===t){e=n;break}return new r(this.#t.slice(0,e),{validate:!1})}equals(t){return lt(this.bytes,t.bytes)}[Id](){return`Multiaddr(${this.toString()})`}};function Bd(r){r.getComponents().forEach(t=>{let e=$t.getProtocol(t.code);t.value!=null&&e.validate?.(t.value)})}function xc(r){return!!r?.[Ks]}function wc(r){return new Pn(r)}var Dd=4194304,On=class extends Error{static name="UnwrappedError";name="UnwrappedError"},Fs=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},zs=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Vs=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Ld(r){return typeof r?.closeRead=="function"}function Cd(r){return typeof r?.close=="function"}function qs(r){return Ld(r)?r.remoteWriteStatus!=="writable"&&r.readBufferLength===0:Cd(r)?r.status!=="open":!1}function Td(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function Rd(r,t){let e=t?.maxBufferSize??Dd,n=new Q,o,s=!1;if(!Td(r))throw new ft("Argument should be a Stream or a Multiaddr");let i=f=>{if(n.append(f.data),n.byteLength>e){let l=n.byteLength;n.consume(n.byteLength),o?.reject(new Error(`Read buffer overflow - ${l} > ${e}`))}o?.resolve()};r.addEventListener("message",i);let a=f=>{f.error!=null?o?.reject(f.error):o?.resolve()};r.addEventListener("close",a);let c=()=>{o?.resolve()};r.addEventListener("remoteCloseWrite",c);let u={readBuffer:n,async read(f){if(s===!0)throw new On("Stream was unwrapped");if(qs(r)){if(n.byteLength===0&&f?.bytes==null)return null;if(f?.bytes!=null&&n.byteLength<f.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,f.bytes),new we(`Unexpected EOF - stream closed after reading ${n.byteLength}/${f.bytes} bytes`)}let l=f?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=l){o.resolve();break}if(await Lr(o.promise,f?.signal),qs(r)){if(n.byteLength===0&&f?.bytes==null)return null;break}o=Promise.withResolvers()}let d=f?.bytes??n.byteLength;if(n.byteLength<d){if(qs(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,d),new we(`Unexpected EOF - stream closed while reading ${n.byteLength}/${d} bytes`);return u.read(f)}let y=n.sublist(0,d);return n.consume(d),y},async write(f,l){if(s===!0)throw new On("Stream was unwrapped");r.send(f)||await Ze(r,"drain",{signal:l?.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 kd(r,t={}){let e=Rd(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=gt(t.maxDataLength));let n=t?.lengthDecoder??br,o=t?.lengthEncoder??wa;return{async read(i){let a=-1,c=new Q;for(;;){let f=await e.read({...i,bytes:1});if(f==null)break;c.append(f);try{a=n(c)}catch(l){if(l instanceof RangeError)continue;throw l}if(a<0)throw new Fs("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new Vs(`Message length length too long - ${c.byteLength} > ${t.maxLengthLength}`);if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new zs(`Message length too long - ${a} > ${t.maxDataLength}`);let u=await e.read({...i,bytes:a});if(u==null)throw r.log.error("tried to read %d bytes but the stream closed",a),new we(`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 we(`Unexpected EOF - read ${u.byteLength}/${a} bytes before the stream closed`);return u},async write(i,a){await e.write(new Q(o(i.byteLength),i),a)},async writeV(i,a){let c=new Q(...i.flatMap(u=>[o(u.byteLength),u]));await e.write(c,a)},unwrap(){return e.unwrap()}}}function je(r,t){let e=kd(r,t),n={read:async(o,s)=>{let i=await e.read(s);return o.decode(i)},write:async(o,s,i)=>{await e.write(s.encode(o),i)},writeV:async(o,s,i)=>{await e.writeV(o.map(a=>s.encode(a)),i)},pb:o=>({read:async s=>n.read(o,s),write:async(s,i)=>n.write(s,o,i),writeV:async(s,i)=>n.writeV(s,o,i),unwrap:()=>n}),unwrap:()=>e.unwrap()};return n}var Nn=class extends Tn{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};function Ec(r,t,e){let n,o,s=!1;function i(){let u={signal:o.signal},f;e?.timeout!=null&&(f=Cr([o.signal,AbortSignal.timeout(e.timeout)]),u.signal=f),s=!0,Promise.resolve().then(async()=>{await r(u)}).catch(()=>{}).finally(()=>{f!=null&&(f.aborted?f.clear():f.addEventListener("abort",()=>{f.clear()},{once:!0})),s=!1,!o.signal.aborted&&(n=setTimeout(i,t))})}let a=Dr(i,e?.debounce??100),c=!1;return{setInterval:u=>{t!==u&&(t=u,n!=null&&(clearTimeout(n),n=setTimeout(i,t)))},setTimeout:u=>{e??={},e.timeout=u},run:()=>{s||(clearTimeout(n),a())},start:()=>{c||(c=!0,o=new AbortController,o.signal,e?.runImmediately===!0?queueMicrotask(()=>{i()}):n=setTimeout(i,t))},stop:()=>{clearTimeout(n),o?.abort(),c=!1}}}var Hs=class extends Map{metric;constructor(t){super();let{name:e,metrics:n}=t;this.metric=n.registerMetric(e),this.updateComponentMetric()}set(t,e){return super.set(t,e),this.updateComponentMetric(),this}delete(t){let e=super.delete(t);return this.updateComponentMetric(),e}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Sc(r){let{name:t,metrics:e}=r,n;return e!=null?n=new Hs({name:t,metrics:e}):n=new Map,n}var $s="libp2p",Gs="autonat";var vc="dial-request",_c="dial-back",Ic=200n*1024n,Ac=4096;var Xe;(function(r){let t;r.codec=()=>(t==null&&(t=_t((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s={...s},s.dialDataResponse!=null&&(s.dialDataRequest=void 0,s.dialResponse=void 0,s.dialRequest=void 0),s.dialDataRequest!=null&&(s.dialDataResponse=void 0,s.dialResponse=void 0,s.dialRequest=void 0),s.dialResponse!=null&&(s.dialDataResponse=void 0,s.dialDataRequest=void 0,s.dialRequest=void 0),s.dialRequest!=null&&(s.dialDataResponse=void 0,s.dialDataRequest=void 0,s.dialResponse=void 0),s.dialRequest!=null&&(i.uint32(10),Rr.codec().encode(s.dialRequest,i)),s.dialResponse!=null&&(i.uint32(18),kt.codec().encode(s.dialResponse,i)),s.dialDataRequest!=null&&(i.uint32(26),kr.codec().encode(s.dialDataRequest,i)),s.dialDataResponse!=null&&(i.uint32(34),Pr.codec().encode(s.dialDataResponse,i)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{c.dialRequest=Rr.codec().decode(s,s.uint32(),{limits:a.limits?.dialRequest});break}case 2:{c.dialResponse=kt.codec().decode(s,s.uint32(),{limits:a.limits?.dialResponse});break}case 3:{c.dialDataRequest=kr.codec().decode(s,s.uint32(),{limits:a.limits?.dialDataRequest});break}case 4:{c.dialDataResponse=Pr.codec().decode(s,s.uint32(),{limits:a.limits?.dialDataResponse});break}default:{s.skipType(f&7);break}}}return c.dialDataResponse!=null&&(delete c.dialDataRequest,delete c.dialResponse,delete c.dialRequest),c.dialDataRequest!=null&&(delete c.dialDataResponse,delete c.dialResponse,delete c.dialRequest),c.dialResponse!=null&&(delete c.dialDataResponse,delete c.dialDataRequest,delete c.dialRequest),c.dialRequest!=null&&(delete c.dialDataResponse,delete c.dialDataRequest,delete c.dialResponse),c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{yield*Rr.codec().stream(s,s.uint32(),`${a}.dialRequest`,{limits:c.limits?.dialRequest});break}case 2:{yield*kt.codec().stream(s,s.uint32(),`${a}.dialResponse`,{limits:c.limits?.dialResponse});break}case 3:{yield*kr.codec().stream(s,s.uint32(),`${a}.dialDataRequest`,{limits:c.limits?.dialDataRequest});break}case 4:{yield*Pr.codec().stream(s,s.uint32(),`${a}.dialDataResponse`,{limits:c.limits?.dialDataResponse});break}default:{s.skipType(f&7);break}}}})),t);function e(s){return St(s,r.codec())}r.encode=e;function n(s,i){return Et(s,r.codec(),i)}r.decode=n;function o(s,i){return vt(s,r.codec(),i)}r.stream=o})(Xe||(Xe={}));var Rr;(function(r){let t;r.codec=()=>(t==null&&(t=_t((s,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),s.addrs!=null&&s.addrs.length>0)for(let c of s.addrs)i.uint32(10),i.bytes(c);s.nonce!=null&&s.nonce!==0n&&(i.uint32(17),i.fixed64(s.nonce)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={addrs:[],nonce:0n},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{if(a.limits?.addrs!=null&&c.addrs.length===a.limits.addrs)throw new Er('Decode error - repeated field "addrs" had too many elements');c.addrs.push(s.bytes());break}case 2:{c.nonce=s.fixed64();break}default:{s.skipType(f&7);break}}}return c},function*(s,i,a,c={}){let u={addrs:0},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let l=s.uint32();switch(l>>>3){case 1:{if(c.limits?.addrs!=null&&u.addrs===c.limits.addrs)throw new Er('Streaming decode error - repeated field "addrs" had too many elements');yield{field:`${a}.addrs[]`,index:u.addrs,value:s.bytes()},u.addrs++;break}case 2:{yield{field:`${a}.nonce`,value:s.fixed64()};break}default:{s.skipType(l&7);break}}}})),t);function e(s){return St(s,r.codec())}r.encode=e;function n(s,i){return Et(s,r.codec(),i)}r.decode=n;function o(s,i){return vt(s,r.codec(),i)}r.stream=o})(Rr||(Rr={}));var kr;(function(r){let t;r.codec=()=>(t==null&&(t=_t((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.addrIdx!=null&&s.addrIdx!==0&&(i.uint32(8),i.uint32(s.addrIdx)),s.numBytes!=null&&s.numBytes!==0n&&(i.uint32(16),i.uint64(s.numBytes)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={addrIdx:0,numBytes:0n},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{c.addrIdx=s.uint32();break}case 2:{c.numBytes=s.uint64();break}default:{s.skipType(f&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{yield{field:`${a}.addrIdx`,value:s.uint32()};break}case 2:{yield{field:`${a}.numBytes`,value:s.uint64()};break}default:{s.skipType(f&7);break}}}})),t);function e(s){return St(s,r.codec())}r.encode=e;function n(s,i){return Et(s,r.codec(),i)}r.decode=n;function o(s,i){return vt(s,r.codec(),i)}r.stream=o})(kr||(kr={}));var st;(function(r){r.UNUSED="UNUSED",r.E_DIAL_ERROR="E_DIAL_ERROR",r.E_DIAL_BACK_ERROR="E_DIAL_BACK_ERROR",r.OK="OK"})(st||(st={}));var Un;(function(r){r[r.UNUSED=0]="UNUSED",r[r.E_DIAL_ERROR=100]="E_DIAL_ERROR",r[r.E_DIAL_BACK_ERROR=101]="E_DIAL_BACK_ERROR",r[r.OK=200]="OK"})(Un||(Un={}));(function(r){r.codec=()=>pe(Un)})(st||(st={}));var kt;(function(r){let t;(function(a){a.E_INTERNAL_ERROR="E_INTERNAL_ERROR",a.E_REQUEST_REJECTED="E_REQUEST_REJECTED",a.E_DIAL_REFUSED="E_DIAL_REFUSED",a.OK="OK"})(t=r.ResponseStatus||(r.ResponseStatus={}));let e;(function(a){a[a.E_INTERNAL_ERROR=0]="E_INTERNAL_ERROR",a[a.E_REQUEST_REJECTED=100]="E_REQUEST_REJECTED",a[a.E_DIAL_REFUSED=101]="E_DIAL_REFUSED",a[a.OK=200]="OK"})(e||(e={})),(function(a){a.codec=()=>pe(e)})(t=r.ResponseStatus||(r.ResponseStatus={}));let n;r.codec=()=>(n==null&&(n=_t((a,c,u={})=>{u.lengthDelimited!==!1&&c.fork(),a.status!=null&&e[a.status]!==0&&(c.uint32(8),r.ResponseStatus.codec().encode(a.status,c)),a.addrIdx!=null&&a.addrIdx!==0&&(c.uint32(16),c.uint32(a.addrIdx)),a.dialStatus!=null&&Un[a.dialStatus]!==0&&(c.uint32(24),st.codec().encode(a.dialStatus,c)),u.lengthDelimited!==!1&&c.ldelim()},(a,c,u={})=>{let f={status:t.E_INTERNAL_ERROR,addrIdx:0,dialStatus:st.UNUSED},l=c==null?a.len:a.pos+c;for(;a.pos<l;){let d=a.uint32();switch(d>>>3){case 1:{f.status=r.ResponseStatus.codec().decode(a);break}case 2:{f.addrIdx=a.uint32();break}case 3:{f.dialStatus=st.codec().decode(a);break}default:{a.skipType(d&7);break}}}return f},function*(a,c,u,f={}){let l=c==null?a.len:a.pos+c;for(;a.pos<l;){let d=a.uint32();switch(d>>>3){case 1:{yield{field:`${u}.status`,value:r.ResponseStatus.codec().decode(a)};break}case 2:{yield{field:`${u}.addrIdx`,value:a.uint32()};break}case 3:{yield{field:`${u}.dialStatus`,value:st.codec().decode(a)};break}default:{a.skipType(d&7);break}}}})),n);function o(a){return St(a,r.codec())}r.encode=o;function s(a,c){return Et(a,r.codec(),c)}r.decode=s;function i(a,c){return vt(a,r.codec(),c)}r.stream=i})(kt||(kt={}));var Pr;(function(r){let t;r.codec=()=>(t==null&&(t=_t((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.data!=null&&s.data.byteLength>0&&(i.uint32(10),i.bytes(s.data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={data:yt(0)},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{c.data=s.bytes();break}default:{s.skipType(f&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{yield{field:`${a}.data`,value:s.bytes()};break}default:{s.skipType(f&7);break}}}})),t);function e(s){return St(s,r.codec())}r.encode=e;function n(s,i){return Et(s,r.codec(),i)}r.decode=n;function o(s,i){return vt(s,r.codec(),i)}r.stream=o})(Pr||(Pr={}));var We;(function(r){let t;r.codec=()=>(t==null&&(t=_t((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.nonce!=null&&s.nonce!==0n&&(i.uint32(9),i.fixed64(s.nonce)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={nonce:0n},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{c.nonce=s.fixed64();break}default:{s.skipType(f&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{yield{field:`${a}.nonce`,value:s.fixed64()};break}default:{s.skipType(f&7);break}}}})),t);function e(s){return St(s,r.codec())}r.encode=e;function n(s,i){return Et(s,r.codec(),i)}r.decode=n;function o(s,i){return vt(s,r.codec(),i)}r.stream=o})(We||(We={}));var ne;(function(r){let t;(function(a){a.OK="OK"})(t=r.DialBackStatus||(r.DialBackStatus={}));let e;(function(a){a[a.OK=0]="OK"})(e||(e={})),(function(a){a.codec=()=>pe(e)})(t=r.DialBackStatus||(r.DialBackStatus={}));let n;r.codec=()=>(n==null&&(n=_t((a,c,u={})=>{u.lengthDelimited!==!1&&c.fork(),a.status!=null&&e[a.status]!==0&&(c.uint32(8),r.DialBackStatus.codec().encode(a.status,c)),u.lengthDelimited!==!1&&c.ldelim()},(a,c,u={})=>{let f={status:t.OK},l=c==null?a.len:a.pos+c;for(;a.pos<l;){let d=a.uint32();switch(d>>>3){case 1:{f.status=r.DialBackStatus.codec().decode(a);break}default:{a.skipType(d&7);break}}}return f},function*(a,c,u,f={}){let l=c==null?a.len:a.pos+c;for(;a.pos<l;){let d=a.uint32();switch(d>>>3){case 1:{yield{field:`${u}.status`,value:r.DialBackStatus.codec().decode(a)};break}default:{a.skipType(d&7);break}}}})),n);function o(a){return St(a,r.codec())}r.encode=o;function s(a,c){return Et(a,r.codec(),c)}r.decode=s;function i(a,c){return vt(a,r.codec(),c)}r.stream=i})(ne||(ne={}));function Mn(r,t){return Math.round(Math.random()*(t-r)+r)}var Od=4,Nd=8,Kn=class{components;dialRequestProtocol;dialBackProtocol;timeout;maxInboundStreams;maxOutboundStreams;maxMessageSize;maxDialDataBytes;dialDataChunkSize;started;log;topologyId;dialResults;findPeers;addressFilter;connectionThreshold;queue;nonces;constructor(t,e){this.components=t,this.log=t.logger.forComponent("libp2p:auto-nat-v2:client"),this.started=!1,this.dialRequestProtocol=e.dialRequestProtocol,this.dialBackProtocol=e.dialBackProtocol,this.timeout=e.timeout??3e4,this.maxInboundStreams=e.maxInboundStreams??2,this.maxOutboundStreams=e.maxOutboundStreams??20,this.connectionThreshold=e.connectionThreshold??80,this.maxMessageSize=e.maxMessageSize??8192,this.dialResults=Sc({name:"libp2p_autonat_v2_dial_results",metrics:t.metrics}),this.findPeers=Ec(this.findRandomPeers.bind(this),6e4),this.addressFilter=bs(1024),this.queue=new Nn({concurrency:3,maxSize:50}),this.maxDialDataBytes=e.maxDialDataBytes??Ic,this.dialDataChunkSize=e.dialDataChunkSize??Ac,this.nonces=new Set}[Symbol.toStringTag]="@libp2p/autonat-v2";[qr]=["@libp2p/autonat"];get[Fr](){return["@libp2p/identify"]}isStarted(){return this.started}async start(){this.started||(this.topologyId=await this.components.registrar.register(this.dialRequestProtocol,{onConnect:(t,e)=>{this.verifyExternalAddresses(e).catch(n=>{this.log.error("could not verify addresses - %e",n)})}}),await this.components.registrar.handle(this.dialBackProtocol,(t,e)=>{this.handleDialBackStream(t,e).catch(n=>{this.log.error("error handling incoming autonat stream - %e",n)})},{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams}),this.findPeers.start(),this.started=!0)}async stop(){await this.components.registrar.unhandle(this.dialRequestProtocol),await this.components.registrar.unhandle(this.dialBackProtocol),this.topologyId!=null&&await this.components.registrar.unhandle(this.topologyId),this.dialResults.clear(),this.findPeers.stop(),this.started=!1}allAddressesAreVerified(){return this.components.addressManager.getAddressesWithMetadata().every(t=>t.expires>Date.now()?!0:t.verified)}async findRandomPeers(t){if(this.allAddressesAreVerified())return;let e=Cr([AbortSignal.timeout(1e4),t?.signal]);try{this.log("starting random walk to find peers to run AutoNAT");for await(let n of this.components.randomWalk.walk({signal:e})){if(!await this.components.connectionManager.isDialable(n.multiaddrs)){this.log.trace("random peer %p was not dialable %s",n.id,n.multiaddrs.map(o=>o.toString()).join(", "));continue}try{this.log.trace("dial random peer %p",n.id),await this.components.connectionManager.openConnection(n.multiaddrs,{signal:e})}catch{}if(this.allAddressesAreVerified()){this.log("stopping random walk, all addresses are verified");return}if(!this.hasConnectionCapacity()){this.log("stopping random walk, too close to max connections");return}}}catch{}}async handleDialBackStream(t,e){let n=AbortSignal.timeout(this.timeout);let o=je(t,{maxDataLength:this.maxMessageSize});try{let s=await o.read(We,{signal:n});if(!this.nonces.has(s.nonce))throw new wt("No matching dial found for nonce value");this.nonces.delete(s.nonce),await o.write({status:ne.DialBackStatus.OK},ne),await t.close({signal:n})}catch(s){this.log.error("error handling incoming dial back stream - %e",s),t.abort(s)}}getUnverifiedMultiaddrs(t,e){let n=this.components.addressManager.getAddressesWithMetadata().sort((s,i)=>s.type==="observed"&&i.type!=="observed"?1:i.type==="observed"&&s.type!=="observed"?-1:0).filter(s=>!(!(s.expires<Date.now())||ee(s.multiaddr).type==="ip6"&&(!e||!tc(s.multiaddr))||sc(s.multiaddr))),o=[];for(let s of n){let i=s.multiaddr.toString(),a=this.dialResults.get(i);if(a!=null&&a.networkSegments.includes(t)){this.log.trace("%a already has a network segment result from %s",a.multiaddr,t);continue}if(a==null){let c=s.expires<Date.now();if(c&&this.addressFilter.remove?.(i),this.addressFilter.has(i))continue;this.addressFilter.add(i),this.log.trace("creating dial result %s %s",c?"to revalidate":"for",i),a={multiaddr:s.multiaddr,success:0,failure:0,networkSegments:[],verifyingPeers:hs(),type:s.type,lastVerified:s.lastVerified},this.dialResults.set(i,a)}o.push(a)}return o}removeOutdatedMultiaddrResults(){let t=new Set(this.components.addressManager.getAddressesWithMetadata().filter(({expires:e})=>e<Date.now()).map(({multiaddr:e})=>e.toString()));for(let e of this.dialResults.keys())t.has(e)||(this.log.trace("remove results for %a",e),this.dialResults.delete(e))}async verifyExternalAddresses(t){if(!this.isStarted())return;this.removeOutdatedMultiaddrResults();let n=(await this.components.peerStore.get(t.remotePeer)).addresses.some(({multiaddr:i})=>ee(i).type==="ip6"),o=this.getNetworkSegment(t.remoteAddr),s=this.getUnverifiedMultiaddrs(o,n);if(s.length!==0){if(!this.hasConnectionCapacity()){s[0]?.lastVerified!=null?(this.log("automatically re-verifying %a because we are too close to the connection limit",s[0].multiaddr),this.confirmAddress(s[0])):this.log("skipping verifying %a because we are too close to the connection limit",s[0]?.multiaddr);return}this.queue.add(async i=>{let a=Cr([i.signal,AbortSignal.timeout(this.timeout)]),c=BigInt(Mn(0,Number.MAX_SAFE_INTEGER));this.nonces.add(c);try{await this.askPeerToVerify(t,o,c,i)}finally{a.clear(),this.nonces.delete(c)}},{peerId:t.remotePeer}).catch(i=>{this.log.error("error from %p verifying addresses - %e",t.remotePeer,i)})}}async askPeerToVerify(t,e,n,o){let s=[...this.dialResults.values()].filter(a=>a.result==null).map(a=>a.multiaddr);if(s.length===0){this.queue.clear();return}this.log.trace("asking %a to verify multiaddrs %s",t.remoteAddr,s);let i=await t.newStream(this.dialRequestProtocol,o);try{let a=je(i).pb(Xe);await a.write({dialRequest:{addrs:s.map(c=>c.bytes),nonce:n}},o);for(let c=0;c<s.length;c++){let u=await a.read(o);if(u.dialDataRequest!=null){if(u.dialDataRequest.numBytes>this.maxDialDataBytes){this.log("too many dial data byte requested by %p - %s/%s",t.remotePeer,u.dialDataRequest.numBytes,this.maxDialDataBytes);continue}this.log("sending %d bytes to %p as anti-amplification attack protection",u.dialDataRequest.numBytes,t.remotePeer);let y=new Uint8Array(this.dialDataChunkSize),h=BigInt(this.dialDataChunkSize);for(let v=0n;v<u.dialDataRequest.numBytes;v+=h)await a.write({dialDataResponse:{data:y}},o);u=await a.read(o)}if(u.dialResponse==null){this.log("invalid autonat response from %p - %j",t.remotePeer,u);return}if(u.dialResponse.status!==kt.ResponseStatus.OK)return;let l=s[u.dialResponse.addrIdx];if(l==null){this.log.trace("peer dialed unknown address");continue}let d=this.dialResults.get(l.toString());if(d==null){this.log.trace("peer reported %a as %s but there is no result object",l,u.dialResponse.status);continue}if(d.networkSegments.includes(e)){this.log.trace("%a results already included network segment %s",l,e);continue}if(d.result!=null){this.log.trace("already resolved result for %a, ignoring response from",l,t.remotePeer);continue}if(d.verifyingPeers.has(t.remotePeer)){this.log.trace("peer %p has already verified %a, ignoring response",t.remotePeer,l);continue}if(d.verifyingPeers.add(t.remotePeer),d.networkSegments.push(e),u.dialResponse.dialStatus===st.OK){if(this.log.trace("%p dialed %a successfully",t.remotePeer,d.multiaddr),d.success++,d.type!=="observed"){this.confirmAddress(d);continue}}else if(u.dialResponse.dialStatus===st.E_DIAL_ERROR)this.log.trace("%p could not dial %a",t.remotePeer,d.multiaddr),d.failure++;else if(u.dialResponse.dialStatus===st.E_DIAL_BACK_ERROR){this.log.trace("%p saw error while dialing %a",t.remotePeer,d.multiaddr);continue}this.log("%a success %d failure %d",d.multiaddr,d.success,d.failure),d.success===Od&&this.confirmAddress(d),d.failure===Nd&&this.unconfirmAddress(d)}}finally{try{await i.close(o)}catch(a){i.abort(a)}}}hasConnectionCapacity(){let e=this.components.connectionManager.getConnections().length,n=this.components.connectionManager.getMaxConnections();return e/n*100<this.connectionThreshold}confirmAddress(t){this.log("%s address %a is externally dialable",t.type,t.multiaddr),this.components.addressManager.confirmObservedAddr(t.multiaddr),this.dialResults.delete(t.multiaddr.toString()),t.result=!0}unconfirmAddress(t){this.log("%s address %a is not externally dialable",t.type,t.multiaddr),this.components.addressManager.removeObservedAddr(t.multiaddr),this.dialResults.delete(t.multiaddr.toString()),t.result=!1}getNetworkSegment(t){let e=ee(t);switch(e.type){case"ip4":return e.host.split(".")[0].padStart(3,"0");case"ip6":return e.host.split(":")[0].padStart(4,"0");default:throw new ft(`Remote address ${t} was not an IPv4 or Ipv6 address`)}}};var qn=class{components;dialRequestProtocol;dialBackProtocol;timeout;maxInboundStreams;maxOutboundStreams;maxMessageSize;started;log;constructor(t,e){this.components=t,this.log=t.logger.forComponent("libp2p:auto-nat-v2:server"),this.started=!1,this.dialRequestProtocol=e.dialRequestProtocol,this.dialBackProtocol=e.dialBackProtocol,this.timeout=e.timeout??3e4,this.maxInboundStreams=e.maxInboundStreams??2,this.maxOutboundStreams=e.maxOutboundStreams??20,this.maxMessageSize=e.maxMessageSize??8192,this.handleDialRequestStream=this.handleDialRequestStream.bind(this)}async start(){this.started||(await this.components.registrar.handle(this.dialRequestProtocol,this.handleDialRequestStream,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams}),this.started=!0)}async stop(){await this.components.registrar.unhandle(this.dialRequestProtocol),this.started=!1}async handleDialRequestStream(t,e){let n=AbortSignal.timeout(this.timeout);let o=je(t,{maxDataLength:this.maxMessageSize}).pb(Xe),s=Tc(e.remoteAddr);if(s==null)throw new wt(`Could not find IP address in connection address "${e.remoteAddr}"`);let{dialRequest:i}=await o.read({signal:n});if(i==null)throw new wt("Did not receive DialRequest message on incoming dial request stream");if(i.addrs.length===0)throw new wt("Did not receive any addresses to dial");for(let a=0;a<i.addrs.length;a++)try{let c=wc(i.addrs[a]);if(!await this.components.connectionManager.isDialable(c,{signal:n})){await o.write({dialResponse:{addrIdx:a,status:kt.ResponseStatus.E_DIAL_REFUSED,dialStatus:st.UNUSED}},{signal:n});continue}let f=Tc(c);if(f==null)throw new wt(`Could not find IP address in requested address "${c}"`);if(In(f))throw new wt(`Requested address had private IP "${c}"`);f!==s&&await this.preventAmplificationAttack(o,a,{signal:n});let l=await this.dialClientBack(c,i.nonce,{signal:n});await o.write({dialResponse:{addrIdx:a,status:kt.ResponseStatus.OK,dialStatus:l}},{signal:n})}catch(c){this.log.error("error handling incoming dialback request - %e",c)}await t.close({signal:n})}async preventAmplificationAttack(t,e,n){let o=Mn(3e4,1e5);await t.write({dialDataRequest:{addrIdx:e,numBytes:BigInt(o)}},n);let s=0;for(;s<o;){let{dialDataResponse:i}=await t.read(n);if(i==null)throw new wt("Did not receive DialDataResponse message on incoming dial request stream");s+=i.data.byteLength}}async dialClientBack(t,e,n){let o;try{o=await this.components.connectionManager.openConnection(t,{force:!0,...n})}catch(s){return this.log.error("failed to open connection to %a - %e",t,s),st.E_DIAL_ERROR}try{let s=await o.newStream(this.dialBackProtocol,n),i=je(s,{maxDataLength:this.maxMessageSize});if(await i.write({nonce:e},We,n),(await i.read(ne,n)).status!==ne.DialBackStatus.OK)throw new wt("DialBackResponse status was not OK");await o.close(n)}catch(s){return this.log.error("could not perform dial back - %e",s),o.abort(s),st.E_DIAL_BACK_ERROR}return st.OK}};function Tc(r){return r.getComponents().filter(t=>t.code===4||t.code===41).map(t=>t.value).pop()}var Fn=class{client;server;constructor(t,e){let n=`/${e.protocolPrefix??$s}/${Gs}/${"2"}/${vc}`,o=`/${e.protocolPrefix??$s}/${Gs}/${"2"}/${_c}`;this.client=new Kn(t,{...e,dialRequestProtocol:n,dialBackProtocol:o}),this.server=new qn(t,{...e,dialRequestProtocol:n,dialBackProtocol:o})}[Symbol.toStringTag]="@libp2p/autonat-v2";[qr]=["@libp2p/autonat"];get[Fr](){return["@libp2p/identify"]}async start(){await Ws(this.client,this.server)}async stop(){await Qs(this.client,this.server)}};function Ud(r={}){return t=>new Fn(t,r)}return Kc(Md);})();
|
|
2
|
+
"use strict";var Libp2PAutonatV2=(()=>{var kc=Object.create;var Nr=Object.defineProperty;var Pc=Object.getOwnPropertyDescriptor;var Oc=Object.getOwnPropertyNames;var Nc=Object.getPrototypeOf,Uc=Object.prototype.hasOwnProperty;var zn=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),bt=(r,t)=>{for(var e in t)Nr(r,e,{get:t[e],enumerable:!0})},js=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Oc(t))!Uc.call(r,o)&&o!==e&&Nr(r,o,{get:()=>t[o],enumerable:!(n=Pc(t,o))||n.enumerable});return r};var Mc=(r,t,e)=>(e=r!=null?kc(Nc(r)):{},js(t||!r||!r.__esModule?Nr(e,"default",{value:r,enumerable:!0}):e,r)),Kc=r=>js(Nr({},"__esModule",{value:!0}),r);var Ss=zn(Ve=>{"use strict";Object.defineProperty(Ve,"__esModule",{value:!0});Ve.Netmask4Impl=void 0;Ve.ip2long=ze;Ve.long2ip=Rt;function Rt(r){let t=(r&-16777216)>>>24,e=(r&255<<16)>>>16,n=(r&65280)>>>8,o=r&255;return[t,e,n,o].join(".")}var gl=48,bl=97,yl=65;function xl(r){let t=0,e=10,n="9",o=0;r.length>1&&r[o]==="0"&&(r[o+1]==="x"||r[o+1]==="X"?(o+=2,e=16):"0"<=r[o+1]&&r[o+1]<="9"&&(o++,e=8,n="7"));let s=o;for(;o<r.length;){if("0"<=r[o]&&r[o]<=n)t=t*e+(r.charCodeAt(o)-gl)>>>0;else if(e===16)if("a"<=r[o]&&r[o]<="f")t=t*e+(10+r.charCodeAt(o)-bl)>>>0;else if("A"<=r[o]&&r[o]<="F")t=t*e+(10+r.charCodeAt(o)-yl)>>>0;else break;else break;if(t>4294967295)throw new Error("too large");o++}if(o===s)throw new Error("empty octet");return[t,o]}function ze(r){let t=[];for(let e=0;e<=3&&r.length!==0;e++){if(e>0){if(r[0]!==".")throw new Error("Invalid IP");r=r.substring(1)}let[n,o]=xl(r);r=r.substring(o),t.push(n)}if(r.length!==0)throw new Error("Invalid IP");switch(t.length){case 1:if(t[0]>4294967295)throw new Error("Invalid IP");return t[0]>>>0;case 2:if(t[0]>255||t[1]>16777215)throw new Error("Invalid IP");return(t[0]<<24|t[1])>>>0;case 3:if(t[0]>255||t[1]>255||t[2]>65535)throw new Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2])>>>0;case 4:if(t[0]>255||t[1]>255||t[2]>255||t[3]>255)throw new Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2]<<8|t[3])>>>0;default:throw new Error("Invalid IP")}}var Es=class r{constructor(t,e){if(typeof t!="string")throw new Error("Missing `net' parameter");let n=e;if(!n){let o=t.split("/",2);t=o[0],n=o[1]}if(n||(n=32),typeof n=="string"&&n.indexOf(".")>-1){try{this.maskLong=ze(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=(ze(t)&this.maskLong)>>>0}catch{throw new Error("Invalid net address: "+t)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+n);this.size=Math.pow(2,32-this.bitmask),this.base=Rt(this.netLong),this.mask=Rt(this.maskLong),this.hostmask=Rt(~this.maskLong),this.first=this.bitmask<=30?Rt(this.netLong+1):this.base,this.last=this.bitmask<=30?Rt(this.netLong+this.size-2):Rt(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?Rt(this.netLong+this.size-1):void 0}contains(t){return typeof t=="string"&&(t.indexOf("/")>0||t.split(".").length!==4)&&(t=new r(t)),t instanceof r?this.contains(t.base)&&this.contains(t.broadcast||t.last):(ze(t)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0}next(t=1){return new r(Rt(this.netLong+this.size*t),this.mask)}forEach(t){let e=ze(this.first),n=ze(this.last),o=0;for(;e<=n;)t(Rt(e),e,o),o++,e++}toString(){return this.base+"/"+this.bitmask}};Ve.Netmask4Impl=Es});var rc=zn(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.Netmask6Impl=void 0;He.ip6bigint=_s;He.bigint2ip6=xe;var wl=Ss(),vs=(1n<<128n)-1n;function _s(r){let t=r.indexOf("%");t!==-1&&(r=r.substring(0,t));let e=r.lastIndexOf(":");if(e!==-1&&r.indexOf(".",e)!==-1){let n=r.substring(e+1),o=(0,wl.ip2long)(n),s=r.substring(0,e+1)+"0:0";return ec(s)&~0xffffffffn|BigInt(o)}return ec(r)}function ec(r){let t=r.indexOf("::"),e;if(t!==-1){let o=r.substring(0,t),s=r.substring(t+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");e=[...i,...Array(c).fill("0"),...a]}else e=r.split(":");if(e.length!==8)throw new Error("Invalid IPv6: expected 8 groups, got "+e.length);let n=0n;for(let o=0;o<8;o++){let s=e[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 xe(r){if(r<0n||r>vs)throw new Error("Invalid IPv6 address value");let t=[];for(let i=0;i<8;i++)t.unshift(Number(r&0xffffn)),r>>=16n;let e=-1,n=0,o=-1,s=0;for(let i=0;i<8;i++)t[i]===0?o===-1?(o=i,s=1):s++:(s>n&&s>=2&&(e=o,n=s),o=-1,s=0);if(s>n&&s>=2&&(e=o,n=s),e!==-1&&e+n===8&&e>0)return t.slice(0,e).map(a=>a.toString(16)).join(":")+"::";if(e===0)return"::"+t.slice(n).map(a=>a.toString(16)).join(":");if(e>0){let i=t.slice(0,e).map(c=>c.toString(16)),a=t.slice(e+n).map(c=>c.toString(16));return i.join(":")+"::"+a.join(":")}else return t.map(i=>i.toString(16)).join(":")}var Is=class r{constructor(t,e){if(typeof t!="string")throw new Error("Missing `net' parameter");let n=e;if(n==null){let o=t.indexOf("/");o!==-1?(n=parseInt(t.substring(o+1),10),t=t.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=vs>>BigInt(128-this.bitmask)<<BigInt(128-this.bitmask);try{this.netBigint=_s(t)&this.maskBigint}catch{throw new Error("Invalid IPv6 net address: "+t)}this.size=Number(1n<<BigInt(128-this.bitmask)),this.base=xe(this.netBigint),this.mask=xe(this.maskBigint),this.hostmask=xe(~this.maskBigint&vs),this.first=this.base,this.last=xe(this.netBigint+(1n<<BigInt(128-this.bitmask))-1n),this.broadcast=void 0}contains(t){return typeof t=="string"&&t.indexOf("/")>0&&(t=new r(t)),t instanceof r?this.contains(t.base)&&this.contains(t.last):(_s(t)&this.maskBigint)===this.netBigint}next(t=1){let e=1n<<BigInt(128-this.bitmask);return new r(xe(this.netBigint+e*BigInt(t)),this.bitmask)}forEach(t){let e=this.netBigint,n=1n<<BigInt(128-this.bitmask),o=this.netBigint+n-1n,s=0;for(;e<=o;)t(xe(e),Number(e),s),s++,e++}toString(){return this.base+"/"+this.bitmask}};He.Netmask6Impl=Is});var nc=zn(re=>{"use strict";Object.defineProperty(re,"__esModule",{value:!0});re.long2ip=re.ip2long=re.Netmask=void 0;var _n=Ss();Object.defineProperty(re,"ip2long",{enumerable:!0,get:function(){return _n.ip2long}});Object.defineProperty(re,"long2ip",{enumerable:!0,get:function(){return _n.long2ip}});var El=rc(),As=class r{constructor(t,e){if(typeof t!="string")throw new Error("Missing `net' parameter");(t.indexOf("/")!==-1?t.substring(0,t.indexOf("/")):t).indexOf(":")!==-1?this._impl=new El.Netmask6Impl(t,e):this._impl=new _n.Netmask4Impl(t,e),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 _n.Netmask4Impl?(this.maskLong=this._impl.maskLong,this.netLong=this._impl.netLong):(this.maskLong=0,this.netLong=0)}contains(t){return typeof t=="string"&&(t.indexOf("/")>0?t=new r(t):t.indexOf(":")===-1&&t.split(".").length!==4&&(t=new r(t))),t instanceof r?this.contains(t.base)&&this.contains(t.broadcast||t.last):this._impl.contains(t)}next(t=1){let e=this._impl.next(t);return new r(e.base,e.bitmask)}forEach(t){this._impl.forEach(t)}toString(){return this._impl.toString()}};re.Netmask=As});var Md={};bt(Md,{autoNATv2:()=>Ud});var Pt=class extends Error{static name="AbortError";constructor(t="The operation was aborted"){super(t),this.name="AbortError"}};var ft=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},Ur=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}};var Mr=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}};var wt=class extends Error{static name="ProtocolError";constructor(t="Protocol error"){super(t),this.name="ProtocolError"}};var Qe=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var Vn=Symbol.for("@libp2p/peer-id");function Xs(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function Ws(...r){let t=[];for(let e of r)Xs(e)&&t.push(e);await Promise.all(t.map(async e=>{e.beforeStart!=null&&await e.beforeStart()})),await Promise.all(t.map(async e=>{await e.start()})),await Promise.all(t.map(async e=>{e.afterStart!=null&&await e.afterStart()}))}async function Qs(...r){let t=[];for(let e of r)Xs(e)&&t.push(e);await Promise.all(t.map(async e=>{e.beforeStop!=null&&await e.beforeStop()})),await Promise.all(t.map(async e=>{await e.stop()})),await Promise.all(t.map(async e=>{e.afterStop!=null&&await e.afterStop()}))}var Kr=class extends EventTarget{#t=new Map;constructor(){super()}listenerCount(t){let e=this.#t.get(t);return e==null?0:e.length}addEventListener(t,e,n){super.addEventListener(t,e,n);let o=this.#t.get(t);o==null&&(o=[],this.#t.set(t,o)),o.push({callback:e,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(t,e,n){super.removeEventListener(t.toString(),e??null,n);let o=this.#t.get(t);o!=null&&(o=o.filter(({callback:s})=>s!==e),this.#t.set(t,o))}dispatchEvent(t){let e=super.dispatchEvent(t),n=this.#t.get(t.type);return n==null||(n=n.filter(({once:o})=>!o),this.#t.set(t.type,n)),e}safeDispatchEvent(t,e={}){return this.dispatchEvent(new CustomEvent(t,e))}};var qr=Symbol.for("@libp2p/service-capabilities"),Fr=Symbol.for("@libp2p/service-dependencies");var Yn={};bt(Yn,{base58btc:()=>j,base58flickr:()=>Gc});var mh=new Uint8Array(0);function Js(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function Ot(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 ti(r){return new TextEncoder().encode(r)}function ei(r){return new TextDecoder().decode(r)}function qc(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(e[i]!==255)throw new TypeError(s+" is ambiguous");e[i]=o}var a=r.length,c=r.charAt(0),u=Math.log(a)/Math.log(256),f=Math.log(256)/Math.log(a);function l(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var v=0,x=0,b=0,I=h.length;b!==I&&h[b]===0;)b++,v++;for(var w=(I-b)*f+1>>>0,A=new Uint8Array(w);b!==I;){for(var k=h[b],U=0,M=w-1;(k!==0||U<x)&&M!==-1;M--,U++)k+=256*A[M]>>>0,A[M]=k%a>>>0,k=k/a>>>0;if(k!==0)throw new Error("Non-zero carry");x=U,b++}for(var S=w-x;S!==w&&A[S]===0;)S++;for(var E=c.repeat(v);S<w;++S)E+=r.charAt(A[S]);return E}function d(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var v=0;if(h[v]!==" "){for(var x=0,b=0;h[v]===c;)x++,v++;for(var I=(h.length-v)*u+1>>>0,w=new Uint8Array(I);h[v];){var A=e[h.charCodeAt(v)];if(A===255)return;for(var k=0,U=I-1;(A!==0||k<b)&&U!==-1;U--,k++)A+=a*w[U]>>>0,w[U]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");b=k,v++}if(h[v]!==" "){for(var M=I-b;M!==I&&w[M]===0;)M++;for(var S=new Uint8Array(x+(I-M)),E=x;M!==I;)S[E++]=w[M++];return S}}}function y(h){var v=d(h);if(v)return v;throw new Error(`Non-${t} character`)}return{encode:l,decodeUnsafe:d,decode:y}}var Fc=qc,zc=Fc,ni=zc;var Hn=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},$n=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){this.name=t,this.prefix=e;let o=e.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return oi(this,t)}},Gn=class{decoders;constructor(t){this.decoders=t}or(t){return oi(this,t)}decode(t){let e=t[0],n=this.decoders[e];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function oi(r,t){return new Gn({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var Zn=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,o){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=o,this.encoder=new Hn(t,e,n),this.decoder=new $n(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Se({name:r,prefix:t,encode:e,decode:n}){return new Zn(r,t,e,n)}function Gt({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=ni(e,r);return Se({prefix:t,name:r,encode:n,decode:s=>Ot(o(s))})}function Vc(r,t,e,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*e/8|0),i=0,a=0,c=0;for(let u=0;u<o;++u){let f=t[r[u]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<e|f,i+=e,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=e||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function Hc(r,t,e){let n=t[t.length-1]==="=",o=(1<<e)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>e;)i-=e,s+=t[o&a>>i];if(i!==0&&(s+=t[o&a<<e-i]),n)for(;(s.length*e&7)!==0;)s+="=";return s}function $c(r){let t={};for(let e=0;e<r.length;++e)t[r[e]]=e;return t}function Y({name:r,prefix:t,bitsPerChar:e,alphabet:n}){let o=$c(n);return Se({prefix:t,name:r,encode(s){return Hc(s,n,e)},decode(s){return Vc(s,o,e,r)}})}var j=Gt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Gc=Gt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var jn={};bt(jn,{base32:()=>Zt,base32hex:()=>Xc,base32hexpad:()=>Qc,base32hexpadupper:()=>Jc,base32hexupper:()=>Wc,base32pad:()=>Yc,base32padupper:()=>jc,base32upper:()=>Zc,base32z:()=>tu});var Zt=Y({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Zc=Y({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Yc=Y({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),jc=Y({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Xc=Y({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Wc=Y({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Qc=Y({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Jc=Y({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),tu=Y({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Xn={};bt(Xn,{base36:()=>Je,base36upper:()=>eu});var Je=Gt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),eu=Gt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var ru=ai,si=128,nu=127,ou=~nu,su=Math.pow(2,31);function ai(r,t,e){t=t||[],e=e||0;for(var n=e;r>=su;)t[e++]=r&255|si,r/=128;for(;r&ou;)t[e++]=r&255|si,r>>>=7;return t[e]=r|0,ai.bytes=e-n+1,t}var iu=Wn,au=128,ii=127;function Wn(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw Wn.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&ii)<<o:(i&ii)*Math.pow(2,o),o+=7}while(i>=au);return Wn.bytes=s-n,e}var cu=Math.pow(2,7),uu=Math.pow(2,14),fu=Math.pow(2,21),lu=Math.pow(2,28),du=Math.pow(2,35),hu=Math.pow(2,42),pu=Math.pow(2,49),mu=Math.pow(2,56),gu=Math.pow(2,63),bu=function(r){return r<cu?1:r<uu?2:r<fu?3:r<lu?4:r<du?5:r<hu?6:r<pu?7:r<mu?8:r<gu?9:10},yu={encode:ru,decode:iu,encodingLength:bu},xu=yu,tr=xu;function er(r,t=0){return[tr.decode(r,t),tr.decode.bytes]}function ve(r,t,e=0){return tr.encode(r,t,e),t}function _e(r){return tr.encodingLength(r)}function Ae(r,t){let e=t.byteLength,n=_e(r),o=n+_e(e),s=new Uint8Array(o+e);return ve(r,s,0),ve(e,s,n),s.set(t,o),new Ie(r,e,t,s)}function rr(r){let t=Ot(r),[e,n]=er(t),[o,s]=er(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Ie(e,o,i,t)}function ci(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&Js(r.bytes,e.bytes)}}var Ie=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};function ui(r,t){let{bytes:e,version:n}=r;return n===0?Eu(e,Qn(r),t??j.encoder):Su(e,Qn(r),t??Zt.encoder)}var fi=new WeakMap;function Qn(r){let t=fi.get(r);if(t==null){let e=new Map;return fi.set(r,e),e}return t}var at=class r{code;version;multihash;bytes;"/";constructor(t,e,n,o){this.code=e,this.version=t,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:t,multihash:e}=this;if(t!==nr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==vu)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}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:t,digest:e}=this.multihash,n=Ae(t,e);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(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&ci(t.multihash,n.multihash)}toString(t){return ui(this,t)}toJSON(){return{"/":ui(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:o,multihash:s,bytes:i}=e;return new r(n,o,s,i??li(n,o,s.bytes))}else if(e[_u]===!0){let{version:n,multihash:o,code:s}=e,i=rr(o);return r.create(n,s,i)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==nr)throw new Error(`Version 0 CID must use dag-pb (code: ${nr}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=li(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,nr,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,o=Ot(t.subarray(n,n+e.multihashSize));if(o.byteLength!==e.multihashSize)throw new Error("Incorrect length");let s=o.subarray(e.multihashSize-e.digestSize),i=new Ie(e.multihashCode,e.digestSize,s,o);return[e.version===0?r.createV0(i):r.createV1(e.codec,i),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[l,d]=er(t.subarray(e));return e+=d,l},o=n(),s=nr;if(o===18?(o=0,e=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=e,a=n(),c=n(),u=e+c,f=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:f,size:u}}static parse(t,e){let[n,o]=wu(t,e),s=r.decode(o);if(s.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Qn(s).set(n,t),s}};function wu(r,t){switch(r[0]){case"Q":{let e=t??j;return[j.prefix,e.decode(`${j.prefix}${r}`)]}case j.prefix:{let e=t??j;return[j.prefix,e.decode(r)]}case Zt.prefix:{let e=t??Zt;return[Zt.prefix,e.decode(r)]}case Je.prefix:{let e=t??Je;return[Je.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function Eu(r,t,e){let{prefix:n}=e;if(n!==j.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let o=t.get(n);if(o==null){let s=e.encode(r).slice(1);return t.set(n,s),s}else return o}function Su(r,t,e){let{prefix:n}=e,o=t.get(n);if(o==null){let s=e.encode(r);return t.set(n,s),s}else return o}var nr=112,vu=18;function li(r,t,e){let n=_e(r),o=n+_e(t),s=new Uint8Array(o+e.byteLength);return ve(r,s,0),ve(t,s,n),s.set(e,o),s}var _u=Symbol.for("@ipld/js-cid/CID");var Jn={};bt(Jn,{identity:()=>It});var di=0,Iu="identity",hi=Ot;function Au(r,t){if(t?.truncate!=null&&t.truncate!==r.byteLength){if(t.truncate<0||t.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t.truncate)}return Ae(di,hi(r))}var It={code:di,name:Iu,encode:hi,digest:Au};function lt(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function yt(r=0){return new Uint8Array(r)}function pt(r=0){return new Uint8Array(r)}function Nt(r,t){t==null&&(t=r.reduce((o,s)=>o+s.length,0));let e=pt(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}var mi=Symbol.for("@achingbrain/uint8arraylist");function pi(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let o=e+n.byteLength;if(t<o)return{buf:n,index:t-e};e=o}throw new RangeError("index is out of bounds")}function Vr(r){return!!r?.[mi]}var Q=class r{bufs;length;[mi]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let n of t)if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.push(n);else if(Vr(n))e+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let n of t.reverse())if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.unshift(n);else if(Vr(n))e+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=pi(this.bufs,t);return e.buf[e.index]}set(t,e){let n=pi(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else if(Vr(t))for(let n=0;n<t.length;n++)this.set(e+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:n,length:o}=this._subList(t,e);return Nt(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:Nt(n,o)}sublist(t,e){let{bufs:n,length:o}=this._subList(t,e),s=new r;return s.length=o,s.bufs=[...n],s}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===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,t>=c)continue;let u=t>=a&&t<c,f=e>a&&e<=c;if(u&&f){if(t===a&&e===c){n.push(i);break}let l=t-a;n.push(i.subarray(l,l+(e-t)));break}if(u){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(f){if(e===c){n.push(i);break}n.push(i.subarray(0,e-a));break}n.push(i)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!Vr(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;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 l=0;l<s;l++)i[l]=-1;for(let l=0;l<o;l++)i[n[l]]=l;let a=i,c=this.byteLength-n.byteLength,u=n.byteLength-1,f;for(let l=e;l<=c;l+=f){f=0;for(let d=u;d>=0;d--){let y=this.get(l+d);if(n[d]!==y){f=Math.max(1,d-a[y]);break}}if(f===0)return l}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=pt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let o=yt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,e,n),this.write(o,t)}getInt32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){let o=yt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,e,n),this.write(o,t)}getBigInt64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){let o=yt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,e,n),this.write(o,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let n=pt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let o=yt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,e,n),this.write(o,t)}getUint32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){let o=yt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,e,n),this.write(o,t)}getBigUint64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){let o=yt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,e,n),this.write(o,t)}getFloat32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){let o=yt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,e,n),this.write(o,t)}getFloat64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){let o=yt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,e,n),this.write(o,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!lt(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((o,s)=>o+s.byteLength,0)),n.length=e,n}};var to={};bt(to,{base10:()=>Bu});var Bu=Gt({prefix:"9",name:"base10",alphabet:"0123456789"});var eo={};bt(eo,{base16:()=>Du,base16upper:()=>Lu});var Du=Y({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Lu=Y({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var ro={};bt(ro,{base2:()=>Cu});var Cu=Y({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var no={};bt(no,{base256emoji:()=>Ou});var gi=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}"),Tu=gi.reduce((r,t,e)=>(r[e]=t,r),[]),Ru=gi.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function ku(r){return r.reduce((t,e)=>(t+=Tu[e],t),"")}function Pu(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=Ru[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var Ou=Se({prefix:"\u{1F680}",name:"base256emoji",encode:ku,decode:Pu});var so={};bt(so,{base64:()=>Nu,base64pad:()=>Uu,base64url:()=>oo,base64urlpad:()=>Mu});var Nu=Y({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Uu=Y({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),oo=Y({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Mu=Y({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var io={};bt(io,{base8:()=>Ku});var Ku=Y({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var ao={};bt(ao,{identity:()=>qu});var qu=Se({prefix:"\0",name:"identity",encode:r=>ei(r),decode:r=>ti(r)});var Qh=new TextEncoder,Jh=new TextDecoder;var fo={};bt(fo,{sha256:()=>or,sha512:()=>Hu});var Vu=20;function uo({name:r,code:t,encode:e,minDigestLength:n,maxDigestLength:o}){return new co(r,t,e,n,o)}var co=class{name;code;encode;minDigestLength;maxDigestLength;constructor(t,e,n,o,s){this.name=t,this.code=e,this.encode=n,this.minDigestLength=o??Vu,this.maxDigestLength=s}digest(t,e){if(e?.truncate!=null){if(e.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&e.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(t instanceof Uint8Array){let n=this.encode(t);return n instanceof Uint8Array?bi(n,this.code,e?.truncate):n.then(o=>bi(o,this.code,e?.truncate))}else throw Error("Unknown type, must be binary type")}};function bi(r,t,e){if(e!=null&&e!==r.byteLength){if(e>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e)}return Ae(t,r)}function xi(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var or=uo({name:"sha2-256",code:18,encode:xi("SHA-256")}),Hu=uo({name:"sha2-512",code:19,encode:xi("SHA-512")});var sr={...ao,...ro,...io,...to,...eo,...jn,...Xn,...Yn,...so,...no},l0={...fo,...Jn};function Ei(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var wi=Ei("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),lo=Ei("ascii","a",r=>{let t="a";for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return t},r=>{r=r.substring(1);let t=pt(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),$u={utf8:wi,"utf-8":wi,hex:sr.base16,latin1:lo,ascii:lo,binary:lo,...sr},Hr=$u;function H(r,t="utf8"){let e=Hr[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function W(r,t="utf8"){let e=Hr[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var Gu=parseInt("11111",2),ho=parseInt("10000000",2),Zu=parseInt("01111111",2),Si={0:ir,1:ir,2:Yu,3:Wu,4:Qu,5:Xu,6:ju,16:ir,22:ir,48:ir};function po(r,t={offset:0}){let e=r[t.offset]&Gu;if(t.offset++,Si[e]!=null)return Si[e](r,t);throw new Error("No decoder for tag "+e)}function ar(r,t){let e=0;if((r[t.offset]&ho)===ho){let n=r[t.offset]&Zu,o="0x";t.offset++;for(let s=0;s<n;s++,t.offset++)o+=r[t.offset].toString(16).padStart(2,"0");e=parseInt(o,16)}else e=r[t.offset],t.offset++;return e}function ir(r,t){ar(r,t);let e=[];for(;!(t.offset>=r.byteLength);){let n=po(r,t);if(n===null)break;e.push(n)}return e}function Yu(r,t){let e=ar(r,t),n=t.offset,o=t.offset+e,s=[];for(let i=n;i<o;i++)i===n&&r[i]===0||s.push(r[i]);return t.offset+=e,Uint8Array.from(s)}function ju(r,t){let e=ar(r,t),n=t.offset+e,o=r[t.offset];t.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(;t.offset<n;){let u=r[t.offset];if(t.offset++,c.push(u&127),u<128){c.reverse();let f=0;for(let l=0;l<c.length;l++)f+=c[l]<<l*7;a+=`.${f}`,c=[]}}return a}function Xu(r,t){return t.offset++,null}function Wu(r,t){let e=ar(r,t),n=r[t.offset];t.offset++;let o=r.subarray(t.offset,t.offset+e-1);if(t.offset+=e,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function Qu(r,t){let e=ar(r,t),n=r.subarray(t.offset,t.offset+e);return t.offset+=e,n}function Ju(r){let t=r.toString(16);t.length%2===1&&(t="0"+t);let e=new Q;for(let n=0;n<t.length;n+=2)e.append(Uint8Array.from([parseInt(`${t[n]}${t[n+1]}`,16)]));return e}function mo(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let t=Ju(r.byteLength);return new Q(Uint8Array.from([t.byteLength|ho]),t)}function vi(r){let t=new Q,e=128;return(r.subarray()[0]&e)===e&&t.append(Uint8Array.from([0])),t.append(r),new Q(Uint8Array.from([2]),mo(t),t)}function _i(r){let t=Uint8Array.from([0]),e=new Q(t,r);return new Q(Uint8Array.from([3]),mo(e),e)}function $r(r,t=48){let e=new Q;for(let n of r)e.append(n);return new Q(Uint8Array.from([t]),mo(e),e)}async function Ii(r,t,e,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,t,e.subarray());return n?.signal?.throwIfAborted(),s}var tf=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),ef=Uint8Array.from([6,5,43,129,4,0,34]),rf=Uint8Array.from([6,5,43,129,4,0,35]),nf={ext:!0,kty:"EC",crv:"P-256"},of={ext:!0,kty:"EC",crv:"P-384"},sf={ext:!0,kty:"EC",crv:"P-521"},go=32,bo=48,yo=66;function Ai(r){let t=po(r);return Bi(t)}function Bi(r){let t=r[1][1][0],e=1,n,o;if(t.byteLength===go*2+1)return n=W(t.subarray(e,e+go),"base64url"),o=W(t.subarray(e+go),"base64url"),new Be({...nf,key_ops:["verify"],x:n,y:o});if(t.byteLength===bo*2+1)return n=W(t.subarray(e,e+bo),"base64url"),o=W(t.subarray(e+bo),"base64url"),new Be({...of,key_ops:["verify"],x:n,y:o});if(t.byteLength===yo*2+1)return n=W(t.subarray(e,e+yo),"base64url"),o=W(t.subarray(e+yo),"base64url"),new Be({...sf,key_ops:["verify"],x:n,y:o});throw new ft(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function Di(r){return $r([vi(Uint8Array.from([1])),$r([af(r.crv)],160),$r([_i(new Q(Uint8Array.from([4]),H(r.x??"","base64url"),H(r.y??"","base64url")))],161)]).subarray()}function af(r){if(r==="P-256")return tf;if(r==="P-384")return ef;if(r==="P-521")return rf;throw new ft(`Invalid curve ${r}`)}var Be=class{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=Di(this.jwk)),this._raw}toMultihash(){return It.digest(De(this))}toCID(){return at.createV1(114,this.toMultihash())}toString(){return j.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:lt(this.raw,t.raw)}async verify(t,e,n){return Ii(this.jwk,e,t,n)}};function se(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Ct(r,t=""){if(!Number.isSafeInteger(r)||r<0){let e=t&&`"${t}" `;throw new Error(`${e}expected integer >= 0, got ${r}`)}}function N(r,t,e=""){let n=se(r),o=r?.length,s=t!==void 0;if(!n||s&&o!==t){let i=e&&`"${e}" `,a=s?` of length ${t}`:"",c=n?`length=${o}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function Gr(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");Ct(r.outputLen),Ct(r.blockLen)}function Le(r,t=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(t&&r.finished)throw new Error("Hash#digest() has already been called")}function Ci(r,t){N(r,void 0,"digestInto() output");let e=t.outputLen;if(r.length<e)throw new Error('"digestInto() output" expected to be of length >='+e)}function Mt(...r){for(let t=0;t<r.length;t++)r[t].fill(0)}function Zr(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function At(r,t){return r<<32-t|r>>>t}var Ti=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",cf=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function Kt(r){if(N(r),Ti)return r.toHex();let t="";for(let e=0;e<r.length;e++)t+=cf[r[e]];return t}var Ut={_0:48,_9:57,A:65,F:70,a:97,f:102};function Li(r){if(r>=Ut._0&&r<=Ut._9)return r-Ut._0;if(r>=Ut.A&&r<=Ut.F)return r-(Ut.A-10);if(r>=Ut.a&&r<=Ut.f)return r-(Ut.a-10)}function qt(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(Ti)return Uint8Array.fromHex(r);let t=r.length,e=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(e);for(let o=0,s=0;o<e;o++,s+=2){let i=Li(r.charCodeAt(s)),a=Li(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 mt(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];N(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let s=r[n];e.set(s,o),o+=s.length}return e}function xo(r,t={}){let e=(o,s)=>r(s).update(o).digest(),n=r(void 0);return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=o=>r(o),Object.assign(e,t),Object.freeze(e)}function Ce(r=32){let t=typeof globalThis=="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return t.getRandomValues(new Uint8Array(r))}var wo=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function Ri(r,t,e){return r&t^~r&e}function ki(r,t,e){return r&t^r&e^t&e}var cr=class{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(t,e,n,o){this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(t),this.view=Zr(this.buffer)}update(t){Le(this),N(t);let{view:e,buffer:n,blockLen:o}=this,s=t.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=Zr(t);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(t.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){Le(this),Ci(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;e[i++]=128,Mt(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let l=i;l<o;l++)e[l]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=Zr(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let u=c/4,f=this.get();if(u>f.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<u;l++)a.setUint32(4*l,f[l],s)}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){t||=new this.constructor,t.set(...this.get());let{blockLen:e,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return t.destroyed=i,t.finished=s,t.length=o,t.pos=a,o%e&&t.buffer.set(n),t}clone(){return this._cloneInto()}},Ft=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var nt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Yr=BigInt(4294967295),Pi=BigInt(32);function uf(r,t=!1){return t?{h:Number(r&Yr),l:Number(r>>Pi&Yr)}:{h:Number(r>>Pi&Yr)|0,l:Number(r&Yr)|0}}function Oi(r,t=!1){let e=r.length,n=new Uint32Array(e),o=new Uint32Array(e);for(let s=0;s<e;s++){let{h:i,l:a}=uf(r[s],t);[n[s],o[s]]=[i,a]}return[n,o]}var Eo=(r,t,e)=>r>>>e,So=(r,t,e)=>r<<32-e|t>>>e,ie=(r,t,e)=>r>>>e|t<<32-e,ae=(r,t,e)=>r<<32-e|t>>>e,ur=(r,t,e)=>r<<64-e|t>>>e-32,fr=(r,t,e)=>r>>>e-32|t<<64-e;function Tt(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var Ni=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),Ui=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,Mi=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),Ki=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,qi=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),Fi=(r,t,e,n,o,s)=>t+e+n+o+s+(r/2**32|0)|0;var lf=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]),Yt=new Uint32Array(64),vo=class extends cr{constructor(t){super(64,t,8,!1)}get(){let{A:t,B:e,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[t,e,n,o,s,i,a,c]}set(t,e,n,o,s,i,a,c){this.A=t|0,this.B=e|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(t,e){for(let l=0;l<16;l++,e+=4)Yt[l]=t.getUint32(e,!1);for(let l=16;l<64;l++){let d=Yt[l-15],y=Yt[l-2],h=At(d,7)^At(d,18)^d>>>3,v=At(y,17)^At(y,19)^y>>>10;Yt[l]=v+Yt[l-7]+h+Yt[l-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:f}=this;for(let l=0;l<64;l++){let d=At(a,6)^At(a,11)^At(a,25),y=f+d+Ri(a,c,u)+lf[l]+Yt[l]|0,v=(At(n,2)^At(n,13)^At(n,22))+ki(n,o,s)|0;f=u,u=c,c=a,a=i+y|0,i=s,s=o,o=n,n=y+v|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,f=f+this.H|0,this.set(n,o,s,i,a,c,u,f)}roundClean(){Mt(Yt)}destroy(){this.set(0,0,0,0,0,0,0,0),Mt(this.buffer)}},_o=class extends vo{A=Ft[0]|0;B=Ft[1]|0;C=Ft[2]|0;D=Ft[3]|0;E=Ft[4]|0;F=Ft[5]|0;G=Ft[6]|0;H=Ft[7]|0;constructor(){super(32)}};var zi=Oi(["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))),df=zi[0],hf=zi[1],jt=new Uint32Array(80),Xt=new Uint32Array(80),Io=class extends cr{constructor(t){super(128,t,16,!1)}get(){let{Ah:t,Al:e,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:u,El:f,Fh:l,Fl:d,Gh:y,Gl:h,Hh:v,Hl:x}=this;return[t,e,n,o,s,i,a,c,u,f,l,d,y,h,v,x]}set(t,e,n,o,s,i,a,c,u,f,l,d,y,h,v,x){this.Ah=t|0,this.Al=e|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=f|0,this.Fh=l|0,this.Fl=d|0,this.Gh=y|0,this.Gl=h|0,this.Hh=v|0,this.Hl=x|0}process(t,e){for(let w=0;w<16;w++,e+=4)jt[w]=t.getUint32(e),Xt[w]=t.getUint32(e+=4);for(let w=16;w<80;w++){let A=jt[w-15]|0,k=Xt[w-15]|0,U=ie(A,k,1)^ie(A,k,8)^Eo(A,k,7),M=ae(A,k,1)^ae(A,k,8)^So(A,k,7),S=jt[w-2]|0,E=Xt[w-2]|0,P=ie(S,E,19)^ur(S,E,61)^Eo(S,E,6),K=ae(S,E,19)^fr(S,E,61)^So(S,E,6),C=Mi(M,K,Xt[w-7],Xt[w-16]),m=Ki(C,U,P,jt[w-7],jt[w-16]);jt[w]=m|0,Xt[w]=C|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:f,Eh:l,El:d,Fh:y,Fl:h,Gh:v,Gl:x,Hh:b,Hl:I}=this;for(let w=0;w<80;w++){let A=ie(l,d,14)^ie(l,d,18)^ur(l,d,41),k=ae(l,d,14)^ae(l,d,18)^fr(l,d,41),U=l&y^~l&v,M=d&h^~d&x,S=qi(I,k,M,hf[w],Xt[w]),E=Fi(S,b,A,U,df[w],jt[w]),P=S|0,K=ie(n,o,28)^ur(n,o,34)^ur(n,o,39),C=ae(n,o,28)^fr(n,o,34)^fr(n,o,39),m=n&s^n&a^s&a,g=o&i^o&c^i&c;b=v|0,I=x|0,v=y|0,x=h|0,y=l|0,h=d|0,{h:l,l:d}=Tt(u|0,f|0,E|0,P|0),u=a|0,f=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let p=Ni(P,C,g);n=Ui(p,E,K,m),o=p|0}({h:n,l:o}=Tt(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=Tt(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=Tt(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:f}=Tt(this.Dh|0,this.Dl|0,u|0,f|0),{h:l,l:d}=Tt(this.Eh|0,this.El|0,l|0,d|0),{h:y,l:h}=Tt(this.Fh|0,this.Fl|0,y|0,h|0),{h:v,l:x}=Tt(this.Gh|0,this.Gl|0,v|0,x|0),{h:b,l:I}=Tt(this.Hh|0,this.Hl|0,b|0,I|0),this.set(n,o,s,i,a,c,u,f,l,d,y,h,v,x,b,I)}roundClean(){Mt(jt,Xt)}destroy(){Mt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Ao=class extends Io{Ah=nt[0]|0;Al=nt[1]|0;Bh=nt[2]|0;Bl=nt[3]|0;Ch=nt[4]|0;Cl=nt[5]|0;Dh=nt[6]|0;Dl=nt[7]|0;Eh=nt[8]|0;El=nt[9]|0;Fh=nt[10]|0;Fl=nt[11]|0;Gh=nt[12]|0;Gl=nt[13]|0;Hh=nt[14]|0;Hl=nt[15]|0;constructor(){super(64)}};var Vi=xo(()=>new _o,wo(1));var Hi=xo(()=>new Ao,wo(3));var Do=BigInt(0),Bo=BigInt(1);function zt(r,t=""){if(typeof r!="boolean"){let e=t&&`"${t}" `;throw new Error(e+"expected boolean, got type="+typeof r)}return r}function $i(r){if(typeof r=="bigint"){if(!jr(r))throw new Error("positive bigint expected, got "+r)}else Ct(r);return r}function lr(r){let t=$i(r).toString(16);return t.length&1?"0"+t:t}function Gi(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?Do:BigInt("0x"+r)}function Te(r){return Gi(Kt(r))}function ce(r){return Gi(Kt(Wr(N(r)).reverse()))}function Xr(r,t){Ct(t),r=$i(r);let e=qt(r.toString(16).padStart(t*2,"0"));if(e.length!==t)throw new Error("number too large");return e}function Lo(r,t){return Xr(r,t).reverse()}function Wr(r){return Uint8Array.from(r)}var jr=r=>typeof r=="bigint"&&Do<=r;function pf(r,t,e){return jr(r)&&jr(t)&&jr(e)&&t<=r&&r<e}function dr(r,t,e,n){if(!pf(t,e,n))throw new Error("expected valid "+r+": "+e+" <= n < "+n+", got "+t)}function Co(r){let t;for(t=0;r>Do;r>>=Bo,t+=1);return t}var hr=r=>(Bo<<BigInt(r))-Bo;function Zi(r,t,e){if(Ct(r,"hashLen"),Ct(t,"qByteLen"),typeof e!="function")throw new Error("hmacFn must be a function");let n=x=>new Uint8Array(x),o=Uint8Array.of(),s=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(r),u=n(r),f=0,l=()=>{c.fill(1),u.fill(0),f=0},d=(...x)=>e(u,mt(c,...x)),y=(x=o)=>{u=d(s,x),c=d(),x.length!==0&&(u=d(i,x),c=d())},h=()=>{if(f++>=a)throw new Error("drbg: tried max amount of iterations");let x=0,b=[];for(;x<t;){c=d();let I=c.slice();b.push(I),x+=c.length}return mt(...b)};return(x,b)=>{l(),y(x);let I;for(;!(I=b(h()));)y();return l(),I}}function Wt(r,t={},e={}){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(t,!1),o(e,!0)}function Re(r){let t=new WeakMap;return(e,...n)=>{let o=t.get(e);if(o!==void 0)return o;let s=r(e,...n);return t.set(e,s),s}}var dt=BigInt(0),J=BigInt(1),ue=BigInt(2),Xi=BigInt(3),Wi=BigInt(4),Qi=BigInt(5),mf=BigInt(7),Ji=BigInt(8),gf=BigInt(9),ta=BigInt(16);function X(r,t){let e=r%t;return e>=dt?e:t+e}function V(r,t,e){let n=r;for(;t-- >dt;)n*=n,n%=e;return n}function Yi(r,t){if(r===dt)throw new Error("invert: expected non-zero number");if(t<=dt)throw new Error("invert: expected positive modulus, got "+t);let e=X(r,t),n=t,o=dt,s=J,i=J,a=dt;for(;e!==dt;){let u=n/e,f=n%e,l=o-i*u,d=s-a*u;n=e,e=f,o=i,s=a,i=l,a=d}if(n!==J)throw new Error("invert: does not exist");return X(o,t)}function Ro(r,t,e){if(!r.eql(r.sqr(t),e))throw new Error("Cannot find square root")}function ea(r,t){let e=(r.ORDER+J)/Wi,n=r.pow(t,e);return Ro(r,n,t),n}function bf(r,t){let e=(r.ORDER-Qi)/Ji,n=r.mul(t,ue),o=r.pow(n,e),s=r.mul(t,o),i=r.mul(r.mul(s,ue),o),a=r.mul(s,r.sub(i,r.ONE));return Ro(r,a,t),a}function yf(r){let t=ke(r),e=ra(r),n=e(t,t.neg(t.ONE)),o=e(t,n),s=e(t,t.neg(n)),i=(r+mf)/ta;return(a,c)=>{let u=a.pow(c,i),f=a.mul(u,n),l=a.mul(u,o),d=a.mul(u,s),y=a.eql(a.sqr(f),c),h=a.eql(a.sqr(l),c);u=a.cmov(u,f,y),f=a.cmov(d,l,h);let v=a.eql(a.sqr(f),c),x=a.cmov(u,f,v);return Ro(a,x,c),x}}function ra(r){if(r<Xi)throw new Error("sqrt is not defined for small field");let t=r-J,e=0;for(;t%ue===dt;)t/=ue,e++;let n=ue,o=ke(r);for(;ji(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(e===1)return ea;let s=o.pow(n,t),i=(t+J)/ue;return function(c,u){if(c.is0(u))return u;if(ji(c,u)!==1)throw new Error("Cannot find square root");let f=e,l=c.mul(c.ONE,s),d=c.pow(u,t),y=c.pow(u,i);for(;!c.eql(d,c.ONE);){if(c.is0(d))return c.ZERO;let h=1,v=c.sqr(d);for(;!c.eql(v,c.ONE);)if(h++,v=c.sqr(v),h===f)throw new Error("Cannot find square root");let x=J<<BigInt(f-h-1),b=c.pow(l,x);f=h,l=c.sqr(b),d=c.mul(d,l),y=c.mul(y,b)}return y}}function xf(r){return r%Wi===Xi?ea:r%Ji===Qi?bf:r%ta===gf?yf(r):ra(r)}var na=(r,t)=>(X(r,t)&J)===J,wf=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function ko(r){let t={ORDER:"bigint",BYTES:"number",BITS:"number"},e=wf.reduce((n,o)=>(n[o]="function",n),t);return Wt(r,e),r}function Ef(r,t,e){if(e<dt)throw new Error("invalid exponent, negatives unsupported");if(e===dt)return r.ONE;if(e===J)return t;let n=r.ONE,o=t;for(;e>dt;)e&J&&(n=r.mul(n,o)),o=r.sqr(o),e>>=J;return n}function pr(r,t,e=!1){let n=new Array(t.length).fill(e?r.ZERO:void 0),o=t.reduce((i,a,c)=>r.is0(a)?i:(n[c]=i,r.mul(i,a)),r.ONE),s=r.inv(o);return t.reduceRight((i,a,c)=>r.is0(a)?i:(n[c]=r.mul(i,n[c]),r.mul(i,a)),s),n}function ji(r,t){let e=(r.ORDER-J)/ue,n=r.pow(t,e),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 Sf(r,t){t!==void 0&&Ct(t);let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}var To=class{ORDER;BITS;BYTES;isLE;ZERO=dt;ONE=J;_lengths;_sqrt;_mod;constructor(t,e={}){if(t<=dt)throw new Error("invalid field: expected ORDER > 0, got "+t);let n;this.isLE=!1,e!=null&&typeof e=="object"&&(typeof e.BITS=="number"&&(n=e.BITS),typeof e.sqrt=="function"&&(this.sqrt=e.sqrt),typeof e.isLE=="boolean"&&(this.isLE=e.isLE),e.allowedLengths&&(this._lengths=e.allowedLengths?.slice()),typeof e.modFromBytes=="boolean"&&(this._mod=e.modFromBytes));let{nBitLength:o,nByteLength:s}=Sf(t,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=t,this.BITS=o,this.BYTES=s,this._sqrt=void 0,Object.preventExtensions(this)}create(t){return X(t,this.ORDER)}isValid(t){if(typeof t!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof t);return dt<=t&&t<this.ORDER}is0(t){return t===dt}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}isOdd(t){return(t&J)===J}neg(t){return X(-t,this.ORDER)}eql(t,e){return t===e}sqr(t){return X(t*t,this.ORDER)}add(t,e){return X(t+e,this.ORDER)}sub(t,e){return X(t-e,this.ORDER)}mul(t,e){return X(t*e,this.ORDER)}pow(t,e){return Ef(this,t,e)}div(t,e){return X(t*Yi(e,this.ORDER),this.ORDER)}sqrN(t){return t*t}addN(t,e){return t+e}subN(t,e){return t-e}mulN(t,e){return t*e}inv(t){return Yi(t,this.ORDER)}sqrt(t){return this._sqrt||(this._sqrt=xf(this.ORDER)),this._sqrt(this,t)}toBytes(t){return this.isLE?Lo(t,this.BYTES):Xr(t,this.BYTES)}fromBytes(t,e=!1){N(t);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(!n.includes(t.length)||t.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+t.length);let u=new Uint8Array(o);u.set(t,s?0:u.length-t.length),t=u}if(t.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+t.length);let c=s?ce(t):Te(t);if(a&&(c=X(c,i)),!e&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(t){return pr(this,t)}cmov(t,e,n){return n?e:t}};function ke(r,t={}){return new To(r,t)}function oa(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let t=r.toString(2).length;return Math.ceil(t/8)}function Po(r){let t=oa(r);return t+Math.ceil(t/2)}function Oo(r,t,e=!1){N(r);let n=r.length,o=oa(t),s=Po(t);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=e?ce(r):Te(r),a=X(i,t-J)+J;return e?Lo(a,o):Xr(a,o)}var Pe=BigInt(0),fe=BigInt(1);function mr(r,t){let e=t.negate();return r?e:t}function le(r,t){let e=pr(r.Fp,t.map(n=>n.Z));return t.map((n,o)=>r.fromAffine(n.toAffine(e[o])))}function ca(r,t){if(!Number.isSafeInteger(r)||r<=0||r>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+r)}function No(r,t){ca(r,t);let e=Math.ceil(t/r)+1,n=2**(r-1),o=2**r,s=hr(r),i=BigInt(r);return{windows:e,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function sa(r,t,e){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=e,a=Number(r&o),c=r>>i;a>n&&(a-=s,c+=fe);let u=t*n,f=u+Math.abs(a)-1,l=a===0,d=a<0,y=t%2!==0;return{nextN:c,offset:f,isZero:l,isNeg:d,isNegF:y,offsetF:u}}var Uo=new WeakMap,ua=new WeakMap;function Mo(r){return ua.get(r)||1}function ia(r){if(r!==Pe)throw new Error("invalid wNAF")}var Oe=class{BASE;ZERO;Fn;bits;constructor(t,e){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=e}_unsafeLadder(t,e,n=this.ZERO){let o=t;for(;e>Pe;)e&fe&&(n=n.add(o)),o=o.double(),e>>=fe;return n}precomputeWindow(t,e){let{windows:n,windowSize:o}=No(e,this.bits),s=[],i=t,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(t,e,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=No(t,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:u,isZero:f,isNeg:l,isNegF:d,offsetF:y}=sa(n,a,i);n=c,f?s=s.add(mr(d,e[y])):o=o.add(mr(l,e[u]))}return ia(n),{p:o,f:s}}wNAFUnsafe(t,e,n,o=this.ZERO){let s=No(t,this.bits);for(let i=0;i<s.windows&&n!==Pe;i++){let{nextN:a,offset:c,isZero:u,isNeg:f}=sa(n,i,s);if(n=a,!u){let l=e[c];o=o.add(f?l.negate():l)}}return ia(n),o}getPrecomputes(t,e,n){let o=Uo.get(e);return o||(o=this.precomputeWindow(e,t),t!==1&&(typeof n=="function"&&(o=n(o)),Uo.set(e,o))),o}cached(t,e,n){let o=Mo(t);return this.wNAF(o,this.getPrecomputes(o,t,n),e)}unsafe(t,e,n,o){let s=Mo(t);return s===1?this._unsafeLadder(t,e,o):this.wNAFUnsafe(s,this.getPrecomputes(s,t,n),e,o)}createCache(t,e){ca(e,this.bits),ua.set(t,e),Uo.delete(t)}hasCache(t){return Mo(t)!==1}};function fa(r,t,e,n){let o=t,s=r.ZERO,i=r.ZERO;for(;e>Pe||n>Pe;)e&fe&&(s=s.add(o)),n&fe&&(i=i.add(o)),o=o.double(),e>>=fe,n>>=fe;return{p1:s,p2:i}}function aa(r,t,e){if(t){if(t.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return ko(t),t}else return ke(r,{isLE:e})}function Qr(r,t,e={},n){if(n===void 0&&(n=r==="edwards"),!t||typeof t!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let u=t[c];if(!(typeof u=="bigint"&&u>Pe))throw new Error(`CURVE.${c} must be positive bigint`)}let o=aa(t.p,e.Fp,n),s=aa(t.n,e.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(t[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:s}}function Jr(r,t){return function(n){let o=r(n);return{secretKey:o,publicKey:t(o)}}}var Qt=BigInt(0),tt=BigInt(1),Ko=BigInt(2),vf=BigInt(8);function _f(r,t,e,n){let o=r.sqr(e),s=r.sqr(n),i=r.add(r.mul(t.a,o),s),a=r.add(r.ONE,r.mul(t.d,r.mul(o,s)));return r.eql(i,a)}function la(r,t={}){let e=Qr("edwards",r,t,t.FpFnLE),{Fp:n,Fn:o}=e,s=e.CURVE,{h:i}=s;Wt(t,{},{uvRatio:"function"});let a=Ko<<BigInt(o.BYTES*8)-tt,c=x=>n.create(x),u=t.uvRatio||((x,b)=>{try{return{isValid:!0,value:n.sqrt(n.div(x,b))}}catch{return{isValid:!1,value:Qt}}});if(!_f(n,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function f(x,b,I=!1){let w=I?tt:Qt;return dr("coordinate "+x,b,w,a),b}function l(x){if(!(x instanceof h))throw new Error("EdwardsPoint expected")}let d=Re((x,b)=>{let{X:I,Y:w,Z:A}=x,k=x.is0();b==null&&(b=k?vf:n.inv(A));let U=c(I*b),M=c(w*b),S=n.mul(A,b);if(k)return{x:Qt,y:tt};if(S!==tt)throw new Error("invZ was invalid");return{x:U,y:M}}),y=Re(x=>{let{a:b,d:I}=s;if(x.is0())throw new Error("bad point: ZERO");let{X:w,Y:A,Z:k,T:U}=x,M=c(w*w),S=c(A*A),E=c(k*k),P=c(E*E),K=c(M*b),C=c(E*c(K+S)),m=c(P+c(I*c(M*S)));if(C!==m)throw new Error("bad point: equation left != right (1)");let g=c(w*A),p=c(k*U);if(g!==p)throw new Error("bad point: equation left != right (2)");return!0});class h{static BASE=new h(s.Gx,s.Gy,tt,c(s.Gx*s.Gy));static ZERO=new h(Qt,tt,tt,Qt);static Fp=n;static Fn=o;X;Y;Z;T;constructor(b,I,w,A){this.X=f("x",b),this.Y=f("y",I),this.Z=f("z",w,!0),this.T=f("t",A),Object.freeze(this)}static CURVE(){return s}static fromAffine(b){if(b instanceof h)throw new Error("extended point not allowed");let{x:I,y:w}=b||{};return f("x",I),f("y",w),new h(I,w,tt,c(I*w))}static fromBytes(b,I=!1){let w=n.BYTES,{a:A,d:k}=s;b=Wr(N(b,w,"point")),zt(I,"zip215");let U=Wr(b),M=b[w-1];U[w-1]=M&-129;let S=ce(U),E=I?a:n.ORDER;dr("point.y",S,Qt,E);let P=c(S*S),K=c(P-tt),C=c(k*P-A),{isValid:m,value:g}=u(K,C);if(!m)throw new Error("bad point: invalid y coordinate");let p=(g&tt)===tt,_=(M&128)!==0;if(!I&&g===Qt&&_)throw new Error("bad point: x=0 and x_0=1");return _!==p&&(g=c(-g)),h.fromAffine({x:g,y:S})}static fromHex(b,I=!1){return h.fromBytes(qt(b),I)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(b=8,I=!0){return v.createCache(this,b),I||this.multiply(Ko),this}assertValidity(){y(this)}equals(b){l(b);let{X:I,Y:w,Z:A}=this,{X:k,Y:U,Z:M}=b,S=c(I*M),E=c(k*A),P=c(w*M),K=c(U*A);return S===E&&P===K}is0(){return this.equals(h.ZERO)}negate(){return new h(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:b}=s,{X:I,Y:w,Z:A}=this,k=c(I*I),U=c(w*w),M=c(Ko*c(A*A)),S=c(b*k),E=I+w,P=c(c(E*E)-k-U),K=S+U,C=K-M,m=S-U,g=c(P*C),p=c(K*m),_=c(P*m),B=c(C*K);return new h(g,p,B,_)}add(b){l(b);let{a:I,d:w}=s,{X:A,Y:k,Z:U,T:M}=this,{X:S,Y:E,Z:P,T:K}=b,C=c(A*S),m=c(k*E),g=c(M*w*K),p=c(U*P),_=c((A+k)*(S+E)-C-m),B=p-g,L=p+g,T=c(m-I*C),D=c(_*B),R=c(L*T),O=c(_*T),$=c(B*L);return new h(D,R,$,O)}subtract(b){return this.add(b.negate())}multiply(b){if(!o.isValidNot0(b))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:I,f:w}=v.cached(this,b,A=>le(h,A));return le(h,[I,w])[0]}multiplyUnsafe(b,I=h.ZERO){if(!o.isValid(b))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return b===Qt?h.ZERO:this.is0()||b===tt?this:v.unsafe(this,b,w=>le(h,w),I)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return v.unsafe(this,s.n).is0()}toAffine(b){return d(this,b)}clearCofactor(){return i===tt?this:this.multiplyUnsafe(i)}toBytes(){let{x:b,y:I}=this.toAffine(),w=n.toBytes(I);return w[w.length-1]|=b&tt?128:0,w}toHex(){return Kt(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let v=new Oe(h,o.BITS);return h.BASE.precompute(8),h}function da(r,t,e={}){if(typeof t!="function")throw new Error('"hash" function param is required');Wt(e,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=e,{BASE:o,Fp:s,Fn:i}=r,a=e.randomBytes||Ce,c=e.adjustScalarBytes||(S=>S),u=e.domain||((S,E,P)=>{if(zt(P,"phflag"),E.length||P)throw new Error("Contexts/pre-hash are not supported");return S});function f(S){return i.create(ce(S))}function l(S){let E=w.secretKey;N(S,w.secretKey,"secretKey");let P=N(t(S),2*E,"hashedSecretKey"),K=c(P.slice(0,E)),C=P.slice(E,2*E),m=f(K);return{head:K,prefix:C,scalar:m}}function d(S){let{head:E,prefix:P,scalar:K}=l(S),C=o.multiply(K),m=C.toBytes();return{head:E,prefix:P,scalar:K,point:C,pointBytes:m}}function y(S){return d(S).pointBytes}function h(S=Uint8Array.of(),...E){let P=mt(...E);return f(t(u(P,N(S,void 0,"context"),!!n)))}function v(S,E,P={}){S=N(S,void 0,"message"),n&&(S=n(S));let{prefix:K,scalar:C,pointBytes:m}=d(E),g=h(P.context,K,S),p=o.multiply(g).toBytes(),_=h(P.context,p,m,S),B=i.create(g+_*C);if(!i.isValid(B))throw new Error("sign failed: invalid s");let L=mt(p,i.toBytes(B));return N(L,w.signature,"result")}let x={zip215:!0};function b(S,E,P,K=x){let{context:C,zip215:m}=K,g=w.signature;S=N(S,g,"signature"),E=N(E,void 0,"message"),P=N(P,w.publicKey,"publicKey"),m!==void 0&&zt(m,"zip215"),n&&(E=n(E));let p=g/2,_=S.subarray(0,p),B=ce(S.subarray(p,g)),L,T,D;try{L=r.fromBytes(P,m),T=r.fromBytes(_,m),D=o.multiplyUnsafe(B)}catch{return!1}if(!m&&L.isSmallOrder())return!1;let R=h(C,T.toBytes(),L.toBytes(),E);return T.add(L.multiplyUnsafe(R)).subtract(D).clearCofactor().is0()}let I=s.BYTES,w={secretKey:I,publicKey:I,signature:2*I,seed:I};function A(S=a(w.seed)){return N(S,w.seed,"seed")}function k(S){return se(S)&&S.length===i.BYTES}function U(S,E){try{return!!r.fromBytes(S,E)}catch{return!1}}let M={getExtendedPublicKey:d,randomSecretKey:A,isValidSecretKey:k,isValidPublicKey:U,toMontgomery(S){let{y:E}=r.fromBytes(S),P=w.publicKey,K=P===32;if(!K&&P!==57)throw new Error("only defined for 25519 and 448");let C=K?s.div(tt+E,tt-E):s.div(E-tt,E+tt);return s.toBytes(C)},toMontgomerySecret(S){let E=w.secretKey;N(S,E);let P=t(S.subarray(0,E));return c(P).subarray(0,E)}};return Object.freeze({keygen:Jr(A,y),getPublicKey:y,sign:v,verify:b,utils:M,Point:r,lengths:w})}var If=BigInt(1),ha=BigInt(2);var Af=BigInt(5),Bf=BigInt(8),qo=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Df={p:qo,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Bf,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Lf(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),s=qo,a=r*r%s*r%s,c=V(a,ha,s)*a%s,u=V(c,If,s)*r%s,f=V(u,Af,s)*u%s,l=V(f,t,s)*f%s,d=V(l,e,s)*l%s,y=V(d,n,s)*d%s,h=V(y,o,s)*y%s,v=V(h,o,s)*y%s,x=V(v,t,s)*f%s;return{pow_p_5_8:V(x,ha,s)*r%s,b2:a}}function Cf(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var pa=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Tf(r,t){let e=qo,n=X(t*t*t,e),o=X(n*n*t,e),s=Lf(r*o).pow_p_5_8,i=X(r*n*s,e),a=X(t*i*i,e),c=i,u=X(i*pa,e),f=a===r,l=a===X(-r,e),d=a===X(-r*pa,e);return f&&(i=c),(l||d)&&(i=u),na(i,e)&&(i=X(-i,e)),{isValid:f||l,value:i}}var Rf=la(Df,{uvRatio:Tf});function kf(r){return da(Rf,Hi,Object.assign({adjustScalarBytes:Cf},r))}var ma=kf({});var gr=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},tn=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var ga={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new tn("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 t}};var en=ga;var rn=32;var Fo,Pf=(async()=>{try{return await en.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function Of(r,t,e){if(r.buffer instanceof ArrayBuffer){let n=await en.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await en.get().subtle.verify({name:"Ed25519"},n,t,e instanceof Uint8Array?e:e.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function Nf(r,t,e){return ma.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}async function ba(r,t,e){return Fo==null&&(Fo=await Pf),Fo?Of(r,t,e):Nf(r,t,e)}function nn(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var on=class{type="Ed25519";raw;constructor(t){this.raw=zo(t,rn)}toMultihash(){return It.digest(De(this))}toCID(){return at.createV1(114,this.toMultihash())}toString(){return j.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:lt(this.raw,t.raw)}verify(t,e,n){n?.signal?.throwIfAborted();let o=ba(this.raw,e,t);return nn(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function xa(r){return r=zo(r,rn),new on(r)}function zo(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new ft(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}var Mf=Math.pow(2,7),Kf=Math.pow(2,14),qf=Math.pow(2,21),Vo=Math.pow(2,28),Ho=Math.pow(2,35),$o=Math.pow(2,42),Go=Math.pow(2,49),F=128,ct=127;function gt(r){if(r<Mf)return 1;if(r<Kf)return 2;if(r<qf)return 3;if(r<Vo)return 4;if(r<Ho)return 5;if(r<$o)return 6;if(r<Go)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Ne(r,t,e=0){switch(gt(r)){case 8:t[e++]=r&255|F,r/=128;case 7:t[e++]=r&255|F,r/=128;case 6:t[e++]=r&255|F,r/=128;case 5:t[e++]=r&255|F,r/=128;case 4:t[e++]=r&255|F,r>>>=7;case 3:t[e++]=r&255|F,r>>>=7;case 2:t[e++]=r&255|F,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function Ff(r,t,e=0){switch(gt(r)){case 8:t.set(e++,r&255|F),r/=128;case 7:t.set(e++,r&255|F),r/=128;case 6:t.set(e++,r&255|F),r/=128;case 5:t.set(e++,r&255|F),r/=128;case 4:t.set(e++,r&255|F),r>>>=7;case 3:t.set(e++,r&255|F),r>>>=7;case 2:t.set(e++,r&255|F),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function Zo(r,t){let e=r[t],n=0;if(n+=e&ct,e<F||(e=r[t+1],n+=(e&ct)<<7,e<F)||(e=r[t+2],n+=(e&ct)<<14,e<F)||(e=r[t+3],n+=(e&ct)<<21,e<F)||(e=r[t+4],n+=(e&ct)*Vo,e<F)||(e=r[t+5],n+=(e&ct)*Ho,e<F)||(e=r[t+6],n+=(e&ct)*$o,e<F)||(e=r[t+7],n+=(e&ct)*Go,e<F))return n;throw new RangeError("Could not decode varint")}function zf(r,t){let e=r.get(t),n=0;if(n+=e&ct,e<F||(e=r.get(t+1),n+=(e&ct)<<7,e<F)||(e=r.get(t+2),n+=(e&ct)<<14,e<F)||(e=r.get(t+3),n+=(e&ct)<<21,e<F)||(e=r.get(t+4),n+=(e&ct)*Vo,e<F)||(e=r.get(t+5),n+=(e&ct)*Ho,e<F)||(e=r.get(t+6),n+=(e&ct)*$o,e<F)||(e=r.get(t+7),n+=(e&ct)*Go,e<F))return n;throw new RangeError("Could not decode varint")}function wa(r,t,e=0){return t==null&&(t=pt(gt(r))),t instanceof Uint8Array?Ne(r,t,e):Ff(r,t,e)}function br(r,t=0){return r instanceof Uint8Array?Zo(r,t):zf(r,t)}var Yo=new Float32Array([-0]),Jt=new Uint8Array(Yo.buffer);function Sa(r,t,e){Yo[0]=r,t[e]=Jt[0],t[e+1]=Jt[1],t[e+2]=Jt[2],t[e+3]=Jt[3]}function va(r,t){return Jt[0]=r[t],Jt[1]=r[t+1],Jt[2]=r[t+2],Jt[3]=r[t+3],Yo[0]}var jo=new Float64Array([-0]),ut=new Uint8Array(jo.buffer);function _a(r,t,e){jo[0]=r,t[e]=ut[0],t[e+1]=ut[1],t[e+2]=ut[2],t[e+3]=ut[3],t[e+4]=ut[4],t[e+5]=ut[5],t[e+6]=ut[6],t[e+7]=ut[7]}function Ia(r,t){return ut[0]=r[t],ut[1]=r[t+1],ut[2]=r[t+2],ut[3]=r[t+3],ut[4]=r[t+4],ut[5]=r[t+5],ut[6]=r[t+6],ut[7]=r[t+7],jo[0]}var Vf=BigInt(Number.MAX_SAFE_INTEGER),Hf=BigInt(Number.MIN_SAFE_INTEGER),xt=class r{lo;hi;constructor(t,e){this.lo=t|0,this.hi=e|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(e+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(BigInt(e)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?e===0?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return de;if(t<Vf&&t>Hf)return this.fromNumber(Number(t));let e=t<0n;e&&(t=-t);let n=t>>32n,o=t-(n<<32n);return e&&(n=~n|0n,o=~o|0n,++o>Aa&&(o=0n,++n>Aa&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return de;let e=t<0;e&&(t=-t);let n=t>>>0,o=(t-n)/4294967296>>>0;return e&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(t){return typeof t=="number"?r.fromNumber(t):typeof t=="bigint"?r.fromBigInt(t):typeof t=="string"?r.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new r(t.low>>>0,t.high>>>0):de}},de=new xt(0,0);de.toBigInt=function(){return 0n};de.zzEncode=de.zzDecode=function(){return this};de.length=function(){return 1};var Aa=4294967296n;function Ba(r){let t=0,e=0;for(let n=0;n<r.length;++n)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:(e&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function Da(r,t,e){if(e-t<1)return"";let o,s=[],i=0,a;for(;t<e;)a=r[t++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[t++]&63:a>239&&a<365?(a=((a&7)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[t++]&63)<<6|r[t++]&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 Xo(r,t,e){let n=e,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?t[e++]=o:o<2048?(t[e++]=o>>6|192,t[e++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,t[e++]=o>>18|240,t[e++]=o>>12&63|128,t[e++]=o>>6&63|128,t[e++]=o&63|128):(t[e++]=o>>12|224,t[e++]=o>>6&63|128,t[e++]=o&63|128);return e-n}function Bt(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function sn(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var Wo=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,Bt(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Bt(this,4);return sn(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Bt(this,4);return sn(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Bt(this,4);let t=va(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw Bt(this,4);let t=Ia(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw Bt(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return Da(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw Bt(this,t);this.pos+=t}else do if(this.pos>=this.len)throw Bt(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new xt(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw Bt(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw Bt(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Bt(this,8);let t=sn(this.buf,this.pos+=4),e=sn(this.buf,this.pos+=4);return new xt(t,e)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=Zo(this.buf,this.pos);return this.pos+=gt(t),t}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 yr(r){return new Wo(r instanceof Uint8Array?r:r.subarray())}function Et(r,t,e){let n=yr(r);return t.decode(n,void 0,e)}function Qo(r){let t=r??8192,e=t>>>1,n,o=t;return function(i){if(i<1||i>e)return pt(i);o+i>t&&(n=pt(t),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var he=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function Jo(){}var es=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},$f=Qo();function Gf(r){return globalThis.Buffer!=null?pt(r):$f(r)}var wr=class{len;head;tail;states;constructor(){this.len=0,this.head=new he(Jo,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new he(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new rs((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(an,10,xt.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=xt.fromBigInt(t);return this._push(an,e.length(),e)}uint64Number(t){return this._push(Ne,gt(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let e=xt.fromBigInt(t).zzEncode();return this._push(an,e.length(),e)}sint64Number(t){let e=xt.fromNumber(t).zzEncode();return this._push(an,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(ts,1,t?1:0)}fixed32(t){return this._push(xr,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=xt.fromBigInt(t);return this._push(xr,4,e.lo)._push(xr,4,e.hi)}fixed64Number(t){let e=xt.fromNumber(t);return this._push(xr,4,e.lo)._push(xr,4,e.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(Sa,4,t)}double(t){return this._push(_a,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(ts,1,0):this.uint32(e)._push(Yf,e,t)}string(t){let e=Ba(t);return e!==0?this.uint32(e)._push(Xo,e,t):this._push(ts,1,0)}fork(){return this.states=new es(this),this.head=this.tail=new he(Jo,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 he(Jo,0,0),this.len=0),this}ldelim(){let t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=e,this.len+=n),this}finish(){let t=this.head.next,e=Gf(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function ts(r,t,e){t[e]=r&255}function Zf(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var rs=class extends he{next;constructor(t,e){super(Zf,t,e),this.next=void 0}};function an(r,t,e){for(;r.hi!==0;)t[e++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)t[e++]=r.lo&127|128,r.lo=r.lo>>>7;t[e++]=r.lo}function xr(r,t,e){t[e]=r&255,t[e+1]=r>>>8&255,t[e+2]=r>>>16&255,t[e+3]=r>>>24}function Yf(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(wr.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(jf,t,r),this},wr.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(Xf,t,r),this});function jf(r,t,e){t.set(r,e)}function Xf(r,t,e){r.length<40?Xo(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(H(r),e)}function ns(){return new wr}function St(r,t){let e=ns();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}function*vt(r,t,e){let n=yr(r);yield*t.stream(n,void 0,"$",e)}var cn={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function un(r,t,e,n,o){return{name:r,type:t,encode:e,decode:n,stream:o}}function pe(r){function t(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let e=function(i,a){let c=t(i);a.int32(c)},n=function(i){let a=i.int32();return t(a)},o=function*(i){let a=i.int32();yield t(a)};return un("enum",cn.VARINT,e,n,o)}function _t(r,t,e){return un("message",cn.LENGTH_DELIMITED,r,t,e)}var Er=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var ht;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(ht||(ht={}));var os;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(os||(os={}));(function(r){r.codec=()=>pe(os)})(ht||(ht={}));var Sr;(function(r){let t;r.codec=()=>(t==null&&(t=_t((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),ht.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 f=s.uint32();switch(f>>>3){case 1:{c.Type=ht.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(f&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{yield{field:`${a}.Type`,value:ht.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(f&7);break}}}})),t);function e(s){return St(s,r.codec())}r.encode=e;function n(s,i){return Et(s,r.codec(),i)}r.decode=n;function o(s,i){return vt(s,r.codec(),i)}r.stream=o})(Sr||(Sr={}));var ss;(function(r){let t;r.codec=()=>(t==null&&(t=_t((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),ht.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 f=s.uint32();switch(f>>>3){case 1:{c.Type=ht.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(f&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{yield{field:`${a}.Type`,value:ht.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(f&7);break}}}})),t);function e(s){return St(s,r.codec())}r.encode=e;function n(s,i){return Et(s,r.codec(),i)}r.decode=n;function o(s,i){return vt(s,r.codec(),i)}r.stream=o})(ss||(ss={}));var fn=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(t,e){if(Gr(t),N(e,void 0,"key"),this.iHash=t.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(e.length>n?t.create().update(e).digest():e);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=t.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),Mt(o)}update(t){return Le(this),this.iHash.update(t),this}digestInto(t){Le(this),N(t,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||=Object.create(Object.getPrototypeOf(this),{});let{oHash:e,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return t=t,t.finished=o,t.destroyed=s,t.blockLen=i,t.outputLen=a,t.oHash=e._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},is=(r,t,e)=>new fn(r,t).update(e).digest();is.create=(r,t)=>new fn(r,t);var Ca=(r,t)=>(r+(r>=0?t:-t)/Ta)/t;function Qf(r,t,e){let[[n,o],[s,i]]=t,a=Ca(i*r,e),c=Ca(-o*r,e),u=r-a*n-c*s,f=-a*o-c*i,l=u<Vt,d=f<Vt;l&&(u=-u),d&&(f=-f);let y=hr(Math.ceil(Co(e)/2))+Ue;if(u<Vt||u>=y||f<Vt||f>=y)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:l,k1:u,k2neg:d,k2:f}}function cs(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function as(r,t){let e={};for(let n of Object.keys(t))e[n]=r[n]===void 0?t[n]:r[n];return zt(e.lowS,"lowS"),zt(e.prehash,"prehash"),e.format!==void 0&&cs(e.format),e}var us=class extends Error{constructor(t=""){super(t)}},te={Err:us,_tlv:{encode:(r,t)=>{let{Err:e}=te;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length&1)throw new e("tlv.encode: unpadded data");let n=t.length/2,o=lr(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let s=n>127?lr(o.length/2|128):"";return lr(r)+s+o+t},decode(r,t){let{Err:e}=te,n=0;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length<2||t[n++]!==r)throw new e("tlv.decode: wrong tlv");let o=t[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new e("tlv.decode(long): indefinite length not supported");if(c>4)throw new e("tlv.decode(long): byte length is too big");let u=t.subarray(n,n+c);if(u.length!==c)throw new e("tlv.decode: length bytes not complete");if(u[0]===0)throw new e("tlv.decode(long): zero leftmost byte");for(let f of u)i=i<<8|f;if(n+=c,i<128)throw new e("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new e("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(r){let{Err:t}=te;if(r<Vt)throw new t("integer: negative integers are not allowed");let e=lr(r);if(Number.parseInt(e[0],16)&8&&(e="00"+e),e.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return e},decode(r){let{Err:t}=te;if(r[0]&128)throw new t("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return Te(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=te,o=N(r,void 0,"signature"),{v:s,l:i}=n.decode(48,o);if(i.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:u,l:f}=n.decode(2,c);if(f.length)throw new t("invalid signature: left bytes after parsing");return{r:e.decode(a),s:e.decode(u)}},hexFromSig(r){let{_tlv:t,_int:e}=te,n=t.encode(2,e.encode(r.r)),o=t.encode(2,e.encode(r.s)),s=n+o;return t.encode(48,s)}},Vt=BigInt(0),Ue=BigInt(1),Ta=BigInt(2),ln=BigInt(3),Jf=BigInt(4);function Ra(r,t={}){let e=Qr("weierstrass",r,t),{Fp:n,Fn:o}=e,s=e.CURVE,{h:i,n:a}=s;Wt(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c}=t;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=Pa(n,o);function f(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function l(C,m,g){let{x:p,y:_}=m.toAffine(),B=n.toBytes(p);if(zt(g,"isCompressed"),g){f();let L=!n.isOdd(_);return mt(ka(L),B)}else return mt(Uint8Array.of(4),B,n.toBytes(_))}function d(C){N(C,void 0,"Point");let{publicKey:m,publicKeyUncompressed:g}=u,p=C.length,_=C[0],B=C.subarray(1);if(p===m&&(_===2||_===3)){let L=n.fromBytes(B);if(!n.isValid(L))throw new Error("bad point: is not on curve, wrong x");let T=v(L),D;try{D=n.sqrt(T)}catch($){let z=$ instanceof Error?": "+$.message:"";throw new Error("bad point: is not on curve, sqrt error"+z)}f();let R=n.isOdd(D);return(_&1)===1!==R&&(D=n.neg(D)),{x:L,y:D}}else if(p===g&&_===4){let L=n.BYTES,T=n.fromBytes(B.subarray(0,L)),D=n.fromBytes(B.subarray(L,L*2));if(!x(T,D))throw new Error("bad point: is not on curve");return{x:T,y:D}}else throw new Error(`bad point: got length ${p}, expected compressed=${m} or uncompressed=${g}`)}let y=t.toBytes||l,h=t.fromBytes||d;function v(C){let m=n.sqr(C),g=n.mul(m,C);return n.add(n.add(g,n.mul(C,s.a)),s.b)}function x(C,m){let g=n.sqr(m),p=v(C);return n.eql(g,p)}if(!x(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let b=n.mul(n.pow(s.a,ln),Jf),I=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(b,I)))throw new Error("bad curve params: a or b");function w(C,m,g=!1){if(!n.isValid(m)||g&&n.is0(m))throw new Error(`bad point coordinate ${C}`);return m}function A(C){if(!(C instanceof E))throw new Error("Weierstrass Point expected")}function k(C){if(!c||!c.basises)throw new Error("no endo");return Qf(C,c.basises,o.ORDER)}let U=Re((C,m)=>{let{X:g,Y:p,Z:_}=C;if(n.eql(_,n.ONE))return{x:g,y:p};let B=C.is0();m==null&&(m=B?n.ONE:n.inv(_));let L=n.mul(g,m),T=n.mul(p,m),D=n.mul(_,m);if(B)return{x:n.ZERO,y:n.ZERO};if(!n.eql(D,n.ONE))throw new Error("invZ was invalid");return{x:L,y:T}}),M=Re(C=>{if(C.is0()){if(t.allowInfinityPoint&&!n.is0(C.Y))return;throw new Error("bad point: ZERO")}let{x:m,y:g}=C.toAffine();if(!n.isValid(m)||!n.isValid(g))throw new Error("bad point: x or y not field elements");if(!x(m,g))throw new Error("bad point: equation left != right");if(!C.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function S(C,m,g,p,_){return g=new E(n.mul(g.X,C),g.Y,g.Z),m=mr(p,m),g=mr(_,g),m.add(g)}class E{static BASE=new E(s.Gx,s.Gy,n.ONE);static ZERO=new E(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(m,g,p){this.X=w("x",m),this.Y=w("y",g,!0),this.Z=w("z",p),Object.freeze(this)}static CURVE(){return s}static fromAffine(m){let{x:g,y:p}=m||{};if(!m||!n.isValid(g)||!n.isValid(p))throw new Error("invalid affine point");if(m instanceof E)throw new Error("projective point not allowed");return n.is0(g)&&n.is0(p)?E.ZERO:new E(g,p,n.ONE)}static fromBytes(m){let g=E.fromAffine(h(N(m,void 0,"point")));return g.assertValidity(),g}static fromHex(m){return E.fromBytes(qt(m))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(m=8,g=!0){return K.createCache(this,m),g||this.multiply(ln),this}assertValidity(){M(this)}hasEvenY(){let{y:m}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(m)}equals(m){A(m);let{X:g,Y:p,Z:_}=this,{X:B,Y:L,Z:T}=m,D=n.eql(n.mul(g,T),n.mul(B,_)),R=n.eql(n.mul(p,T),n.mul(L,_));return D&&R}negate(){return new E(this.X,n.neg(this.Y),this.Z)}double(){let{a:m,b:g}=s,p=n.mul(g,ln),{X:_,Y:B,Z:L}=this,T=n.ZERO,D=n.ZERO,R=n.ZERO,O=n.mul(_,_),$=n.mul(B,B),z=n.mul(L,L),q=n.mul(_,B);return q=n.add(q,q),R=n.mul(_,L),R=n.add(R,R),T=n.mul(m,R),D=n.mul(p,z),D=n.add(T,D),T=n.sub($,D),D=n.add($,D),D=n.mul(T,D),T=n.mul(q,T),R=n.mul(p,R),z=n.mul(m,z),q=n.sub(O,z),q=n.mul(m,q),q=n.add(q,R),R=n.add(O,O),O=n.add(R,O),O=n.add(O,z),O=n.mul(O,q),D=n.add(D,O),z=n.mul(B,L),z=n.add(z,z),O=n.mul(z,q),T=n.sub(T,O),R=n.mul(z,$),R=n.add(R,R),R=n.add(R,R),new E(T,D,R)}add(m){A(m);let{X:g,Y:p,Z:_}=this,{X:B,Y:L,Z:T}=m,D=n.ZERO,R=n.ZERO,O=n.ZERO,$=s.a,z=n.mul(s.b,ln),q=n.mul(g,B),G=n.mul(p,L),rt=n.mul(_,T),Lt=n.add(g,p),Z=n.add(B,L);Lt=n.mul(Lt,Z),Z=n.add(q,G),Lt=n.sub(Lt,Z),Z=n.add(g,_);let it=n.add(B,T);return Z=n.mul(Z,it),it=n.add(q,rt),Z=n.sub(Z,it),it=n.add(p,_),D=n.add(L,T),it=n.mul(it,D),D=n.add(G,rt),it=n.sub(it,D),O=n.mul($,Z),D=n.mul(z,rt),O=n.add(D,O),D=n.sub(G,O),O=n.add(G,O),R=n.mul(D,O),G=n.add(q,q),G=n.add(G,q),rt=n.mul($,rt),Z=n.mul(z,Z),G=n.add(G,rt),rt=n.sub(q,rt),rt=n.mul($,rt),Z=n.add(Z,rt),q=n.mul(G,Z),R=n.add(R,q),q=n.mul(it,Z),D=n.mul(Lt,D),D=n.sub(D,q),q=n.mul(Lt,G),O=n.mul(it,O),O=n.add(O,q),new E(D,R,O)}subtract(m){return this.add(m.negate())}is0(){return this.equals(E.ZERO)}multiply(m){let{endo:g}=t;if(!o.isValidNot0(m))throw new Error("invalid scalar: out of range");let p,_,B=L=>K.cached(this,L,T=>le(E,T));if(g){let{k1neg:L,k1:T,k2neg:D,k2:R}=k(m),{p:O,f:$}=B(T),{p:z,f:q}=B(R);_=$.add(q),p=S(g.beta,O,z,L,D)}else{let{p:L,f:T}=B(m);p=L,_=T}return le(E,[p,_])[0]}multiplyUnsafe(m){let{endo:g}=t,p=this;if(!o.isValid(m))throw new Error("invalid scalar: out of range");if(m===Vt||p.is0())return E.ZERO;if(m===Ue)return p;if(K.hasCache(this))return this.multiply(m);if(g){let{k1neg:_,k1:B,k2neg:L,k2:T}=k(m),{p1:D,p2:R}=fa(E,p,B,T);return S(g.beta,D,R,_,L)}else return K.unsafe(p,m)}toAffine(m){return U(this,m)}isTorsionFree(){let{isTorsionFree:m}=t;return i===Ue?!0:m?m(E,this):K.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:m}=t;return i===Ue?this:m?m(E,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(m=!0){return zt(m,"isCompressed"),this.assertValidity(),y(E,this,m)}toHex(m=!0){return Kt(this.toBytes(m))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let P=o.BITS,K=new Oe(E,t.endo?Math.ceil(P/2):P);return E.BASE.precompute(8),E}function ka(r){return Uint8Array.of(r?2:3)}function Pa(r,t){return{secretKey:t.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function tl(r,t={}){let{Fn:e}=r,n=t.randomBytes||Ce,o=Object.assign(Pa(r.Fp,e),{seed:Po(e.ORDER)});function s(y){try{let h=e.fromBytes(y);return e.isValidNot0(h)}catch{return!1}}function i(y,h){let{publicKey:v,publicKeyUncompressed:x}=o;try{let b=y.length;return h===!0&&b!==v||h===!1&&b!==x?!1:!!r.fromBytes(y)}catch{return!1}}function a(y=n(o.seed)){return Oo(N(y,o.seed,"seed"),e.ORDER)}function c(y,h=!0){return r.BASE.multiply(e.fromBytes(y)).toBytes(h)}function u(y){let{secretKey:h,publicKey:v,publicKeyUncompressed:x}=o;if(!se(y)||"_lengths"in e&&e._lengths||h===v)return;let b=N(y,void 0,"key").length;return b===v||b===x}function f(y,h,v=!0){if(u(y)===!0)throw new Error("first arg must be private key");if(u(h)===!1)throw new Error("second arg must be public key");let x=e.fromBytes(y);return r.fromBytes(h).multiply(x).toBytes(v)}let l={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},d=Jr(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:f,keygen:d,Point:r,utils:l,lengths:o})}function Oa(r,t,e={}){Gr(t),Wt(e,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),e=Object.assign({},e);let n=e.randomBytes||Ce,o=e.hmac||((g,p)=>is(t,g,p)),{Fp:s,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:u,getPublicKey:f,getSharedSecret:l,utils:d,lengths:y}=tl(r,e),h={prehash:!0,lowS:typeof e.lowS=="boolean"?e.lowS:!0,format:"compact",extraEntropy:!1},v=a*Ta<s.ORDER;function x(g){let p=a>>Ue;return g>p}function b(g,p){if(!i.isValidNot0(p))throw new Error(`invalid signature ${g}: out of range 1..Point.Fn.ORDER`);return p}function I(){if(v)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function w(g,p){cs(p);let _=y.signature,B=p==="compact"?_:p==="recovered"?_+1:void 0;return N(g,B)}class A{r;s;recovery;constructor(p,_,B){if(this.r=b("r",p),this.s=b("s",_),B!=null){if(I(),![0,1,2,3].includes(B))throw new Error("invalid recovery id");this.recovery=B}Object.freeze(this)}static fromBytes(p,_=h.format){w(p,_);let B;if(_==="der"){let{r:R,s:O}=te.toSig(N(p));return new A(R,O)}_==="recovered"&&(B=p[0],_="compact",p=p.subarray(1));let L=y.signature/2,T=p.subarray(0,L),D=p.subarray(L,L*2);return new A(i.fromBytes(T),i.fromBytes(D),B)}static fromHex(p,_){return this.fromBytes(qt(p),_)}assertRecovery(){let{recovery:p}=this;if(p==null)throw new Error("invalid recovery id: must be present");return p}addRecoveryBit(p){return new A(this.r,this.s,p)}recoverPublicKey(p){let{r:_,s:B}=this,L=this.assertRecovery(),T=L===2||L===3?_+a:_;if(!s.isValid(T))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let D=s.toBytes(T),R=r.fromBytes(mt(ka((L&1)===0),D)),O=i.inv(T),$=U(N(p,void 0,"msgHash")),z=i.create(-$*O),q=i.create(B*O),G=r.BASE.multiplyUnsafe(z).add(R.multiplyUnsafe(q));if(G.is0())throw new Error("invalid recovery: point at infinify");return G.assertValidity(),G}hasHighS(){return x(this.s)}toBytes(p=h.format){if(cs(p),p==="der")return qt(te.hexFromSig(this));let{r:_,s:B}=this,L=i.toBytes(_),T=i.toBytes(B);return p==="recovered"?(I(),mt(Uint8Array.of(this.assertRecovery()),L,T)):mt(L,T)}toHex(p){return Kt(this.toBytes(p))}}let k=e.bits2int||function(p){if(p.length>8192)throw new Error("input is too large");let _=Te(p),B=p.length*8-c;return B>0?_>>BigInt(B):_},U=e.bits2int_modN||function(p){return i.create(k(p))},M=hr(c);function S(g){return dr("num < 2^"+c,g,Vt,M),i.toBytes(g)}function E(g,p){return N(g,void 0,"message"),p?N(t(g),void 0,"prehashed message"):g}function P(g,p,_){let{lowS:B,prehash:L,extraEntropy:T}=as(_,h);g=E(g,L);let D=U(g),R=i.fromBytes(p);if(!i.isValidNot0(R))throw new Error("invalid private key");let O=[S(R),S(D)];if(T!=null&&T!==!1){let G=T===!0?n(y.secretKey):T;O.push(N(G,void 0,"extraEntropy"))}let $=mt(...O),z=D;function q(G){let rt=k(G);if(!i.isValidNot0(rt))return;let Lt=i.inv(rt),Z=r.BASE.multiply(rt).toAffine(),it=i.create(Z.x);if(it===Vt)return;let Or=i.create(Lt*i.create(z+it*R));if(Or===Vt)return;let Zs=(Z.x===it?0:2)|Number(Z.y&Ue),Ys=Or;return B&&x(Or)&&(Ys=i.neg(Or),Zs^=1),new A(it,Ys,v?void 0:Zs)}return{seed:$,k2sig:q}}function K(g,p,_={}){let{seed:B,k2sig:L}=P(g,p,_);return Zi(t.outputLen,i.BYTES,o)(B,L).toBytes(_.format)}function C(g,p,_,B={}){let{lowS:L,prehash:T,format:D}=as(B,h);if(_=N(_,void 0,"publicKey"),p=E(p,T),!se(g)){let R=g instanceof A?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+R)}w(g,D);try{let R=A.fromBytes(g,D),O=r.fromBytes(_);if(L&&R.hasHighS())return!1;let{r:$,s:z}=R,q=U(p),G=i.inv(z),rt=i.create(q*G),Lt=i.create($*G),Z=r.BASE.multiplyUnsafe(rt).add(O.multiplyUnsafe(Lt));return Z.is0()?!1:i.create(Z.x)===$}catch{return!1}}function m(g,p,_={}){let{prehash:B}=as(_,h);return p=E(p,B),A.fromBytes(g,"recovered").recoverPublicKey(p).toBytes()}return Object.freeze({keygen:u,getPublicKey:f,getSharedSecret:l,utils:d,lengths:y,Point:r,sign:K,verify:C,recoverPublicKey:m,Signature:A,hash:t})}var ls={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},el={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Na=BigInt(2);function rl(r){let t=ls.p,e=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=r*r*r%t,f=u*u*r%t,l=V(f,e,t)*f%t,d=V(l,e,t)*f%t,y=V(d,Na,t)*u%t,h=V(y,o,t)*y%t,v=V(h,s,t)*h%t,x=V(v,a,t)*v%t,b=V(x,c,t)*x%t,I=V(b,a,t)*v%t,w=V(I,e,t)*f%t,A=V(w,i,t)*h%t,k=V(A,n,t)*u%t,U=V(k,Na,t);if(!fs.eql(fs.sqr(U),r))throw new Error("Cannot find square root");return U}var fs=ke(ls.p,{sqrt:rl}),nl=Ra(ls,{Fp:fs,endo:el}),Me=Oa(nl,Vi);function Ua(r,t,e,n){let o=or.digest(e instanceof Uint8Array?e:e.subarray());if(nn(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),Me.verify(t,s,r,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new gr(String(s))});try{return n?.signal?.throwIfAborted(),Me.verify(t,o.digest,r,{prehash:!1,format:"der"})}catch(s){throw new gr(String(s))}}var dn=class{type="secp256k1";raw;_key;constructor(t){this._key=Ka(t),this.raw=Ma(this._key)}toMultihash(){return It.digest(De(this))}toCID(){return at.createV1(114,this.toMultihash())}toString(){return j.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:lt(this.raw,t.raw)}verify(t,e,n){return Ua(this._key,e,t,n)}};function qa(r){return new dn(r)}function Ma(r){return Me.Point.fromBytes(r).toBytes()}function Ka(r){try{return Me.Point.fromBytes(r),r}catch(t){throw new Ur(String(t))}}function Fa(r){let{Type:t,Data:e}=Sr.decode(r.digest),n=e??new Uint8Array;switch(t){case ht.Ed25519:return xa(n);case ht.secp256k1:return qa(n);case ht.ECDSA:return Ai(n);default:throw new Qe}}function De(r){return Sr.encode({Type:ht[r.type],Data:r.raw})}var za=Symbol.for("nodejs.util.inspect.custom"),ol=114,vr=class{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Vn]=!0;toString(){return this.string==null&&(this.string=j.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return at.createV1(ol,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return lt(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return lt(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[za](){return`PeerId(${this.toString()})`}},hn=class extends vr{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},pn=class extends vr{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},mn=class extends vr{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},sl=2336,gn=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=It.digest(H(this.url))}[za](){return`PeerId(${this.url})`}[Vn]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return at.createV1(sl,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=W(t)),t.toString()===this.toString())}};function Va(r){if(al(r))return new hn({multihash:r});if(il(r))try{let t=Fa(r);if(t.type==="Ed25519")return new pn({multihash:r,publicKey:t});if(t.type==="secp256k1")return new mn({multihash:r,publicKey:t})}catch{let e=W(r.digest);return new gn(new URL(e))}throw new Mr("Supplied PeerID Multihash is invalid")}function il(r){return r.code===It.code}function al(r){return r.code===or.code}function ds(r,t){let e={[Symbol.iterator]:()=>e,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:t(o)}}};return e}function bn(r){let t=rr(j.decode(`z${r}`));return Va(t)}var yn=class r{set;constructor(t){if(this.set=new Set,t!=null)for(let e of t)this.set.add(e.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(t){this.set.add(t.toString())}clear(){this.set.clear()}delete(t){this.set.delete(t.toString())}entries(){return ds(this.set.entries(),t=>{let e=bn(t[0]);return[e,e]})}forEach(t){this.set.forEach(e=>{let n=bn(e);t(n,n,this)})}has(t){return this.set.has(t.toString())}values(){return ds(this.set.values(),t=>bn(t))}intersection(t){let e=new r;for(let n of t)this.has(n)&&e.add(n);return e}difference(t){let e=new r;for(let n of this)t.has(n)||e.add(n);return e}union(t){let e=new r;for(let n of t)e.add(n);for(let n of this)e.add(n);return e}};function hs(){return new yn}var ps={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Ha={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},$a=new globalThis.TextEncoder;function cl(r,t){let e=ps[t],n=Ha[t];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(t,n*e);return n}function ul(r,t,e){if(e.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=ps[t],o=Ha[t],s=r;for(;s.length>0;){let i=$a.encodeInto(s,e);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(e[a]),o=BigInt.asUintN(t,o*n)}return o}function ms(r,{size:t=32,utf8Buffer:e}={}){if(!ps[t])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(e)return ul(r,t,e);r=$a.encode(r)}return cl(r,t)}var _r={hash:r=>Number(ms(r,{size:32})),hashV:(r,t)=>fl(_r.hash(r,t))};function fl(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),H(t,"base16")}var gs=64,Dt=class{fp;h;seed;constructor(t,e,n,o=2){if(o>gs)throw new TypeError("Invalid Fingerprint Size");let s=e.hashV(t,n),i=yt(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=e,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(t){return t?.fp instanceof Uint8Array?lt(this.fp,t.fp):!1}};function me(r,t){return Math.floor(Math.random()*(t-r))+r}var ge=class{contents;constructor(t){this.contents=new Array(t).fill(null)}has(t){if(!(t instanceof Dt))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof Dt))throw new TypeError("Invalid Fingerprint");for(let e=0;e<this.contents.length;e++)if(this.contents[e]==null)return this.contents[e]=t,!0;return!0}swap(t){if(!(t instanceof Dt))throw new TypeError("Invalid Fingerprint");let e=me(0,this.contents.length-1),n=this.contents[e];return this.contents[e]=t,n}remove(t){if(!(t instanceof Dt))throw new TypeError("Invalid Fingerprint");let e=this.contents.findIndex(n=>t.equals(n));return e>-1?(this.contents[e]=null,!0):!1}};var ll=500,Ir=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(t){this.filterSize=t.filterSize,this.bucketSize=t.bucketSize??4,this.fingerprintSize=t.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=t.hash??_r,this.seed=t.seed??me(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=H(t));let e=new Dt(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=(n^e.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new ge(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new ge(this.bucketSize)),this.buckets[n].add(e)||this.buckets[o].add(e))return this.count++,!0;let s=[n,o],i=s[me(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new ge(this.bucketSize));for(let a=0;a<ll;a++){let c=this.buckets[i].swap(e);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new ge(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(t){typeof t=="string"&&(t=H(t));let e=new Dt(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=this.buckets[n]?.has(e)??!1;if(o)return o;let s=(n^e.hash())%this.filterSize;return this.buckets[s]?.has(e)??!1}remove(t){typeof t=="string"&&(t=H(t));let e=new Dt(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=this.buckets[n]?.remove(e)??!1;if(o)return this.count--,o;let s=(n^e.hash())%this.filterSize,i=this.buckets[s]?.remove(e)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},dl={1:.5,2:.84,4:.95,8:.98};function hl(r=.001){return r>.002?2:r>1e-5?4:8}function Ga(r,t=.001){let e=hl(t),n=dl[e],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),gs);return{filterSize:o,bucketSize:e,fingerprintSize:s}}var xn=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(t){this.bucketSize=t.bucketSize??4,this.filterSize=t.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=t.fingerprintSize??2,this.scale=t.scale??2,this.hash=t.hash??_r,this.seed=t.seed??me(0,Math.pow(2,10)),this.filterSeries=[new Ir({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(t){if(typeof t=="string"&&(t=H(t)),this.has(t))return!0;let e=this.filterSeries.find(n=>n.reliable);if(e==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);e=new Ir({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(e)}return e.add(t)}has(t){typeof t=="string"&&(t=H(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].has(t))return!0;return!1}remove(t){typeof t=="string"&&(t=H(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].remove(t))return!0;return!1}get count(){return this.filterSeries.reduce((t,e)=>t+e.count,0)}};function bs(r,t=.001,e){return new xn({...Ga(r,t),...e??{}})}function ee(r){let t=r.getComponents(),e={},n=0;if(t[n]?.name==="ip6zone"&&(e.zone=`${t[n].value}`,n++),t[n].name==="ip4"||t[n].name==="ip6"||t[n].name==="dns"||t[n].name==="dns4"||t[n].name==="dns6"?(e.type=t[n].name,e.host=t[n].value,n++):t[n].name==="dnsaddr"&&(e.type=t[n].name,e.host=`_dnsaddr.${t[n].value}`,n++),(t[n]?.name==="tcp"||t[n]?.name==="udp")&&(e.protocol=t[n].name==="tcp"?"tcp":"udp",e.port=parseInt(`${t[n].value}`),n++),t[n]?.name==="ipcidr"&&(e.type==="ip4"?e.cidr=parseInt(`${t[n].value}`):e.type==="ip6"&&(e.cidr=`${t[n].value}`),n++),e.type==null||e.host==null)throw new ft(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return t[n]?.name==="tls"&&t[n+1]?.name==="sni"&&(e.sni=t[n+1].value,n+=2),e}var wn=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let e=this.index,n=t();return n===void 0&&(this.index=e),n}parseWith(t){let e=t();if(this.index===this.input.length)return e}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(t){return this.readAtomically(()=>{let e=this.readChar();if(e===t)return e})}readSeparator(t,e,n){return this.readAtomically(()=>{if(!(e>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,e,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 f=this.readAtomically(()=>{let l=this.readChar();if(l===void 0)return;let d=Number.parseInt(l,t);if(!Number.isNaN(d))return d});if(f===void 0)break;if(s*=t,s+=f,s>u||(i+=1,e!==void 0&&i>e))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let e=0;e<t.length;e++){let n=this.readSeparator(".",e,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[e]=n}return t})}readIPv6Addr(){let t=e=>{for(let n=0;n<e.length/2;n++){let o=n*2;if(n<e.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return e[o]=i[0],e[o+1]=i[1],e[o+2]=i[2],e[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];e[o]=s>>8,e[o+1]=s&255}return[e.length,!1]};return this.readAtomically(()=>{let e=new Uint8Array(16),[n,o]=t(e);if(n===16)return e;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=t(s.subarray(0,i));return e.set(s.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Za=45,pl=15,Ke=new wn;function En(r){if(!(r.length>pl))return Ke.new(r).parseWith(()=>Ke.readIPv4Addr())}function Sn(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Za))return Ke.new(r).parseWith(()=>Ke.readIPv6Addr())}function qe(r,t=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>Za)return;let e=Ke.new(r).parseWith(()=>Ke.readIPAddr());if(e)return t&&e.length===4?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,e[0],e[1],e[2],e[3]]):e}function Ya(r,t,e){let n=0;for(let o of r)if(!(n<t)){if(n>e)break;if(o!==255)return!1;n++}return!0}function ja(r,t,e,n){let o=0;for(let s of r)if(!(o<e)){if(o>n)break;if(s!==t[o])return!1;o++}return!0}function ys(r){switch(r.length){case be:return r.join(".");case ye:{let t=[];for(let e=0;e<r.length;e++)e%2===0&&t.push(r[e].toString(16).padStart(2,"0")+r[e+1].toString(16).padStart(2,"0"));return t.join(":")}default:throw new Error("Invalid ip length")}}function Xa(r){let t=0;for(let[e,n]of r.entries()){if(n===255){t+=8;continue}for(;(n&128)!=0;)t++,n=n<<1;if((n&128)!=0)return-1;for(let o=e+1;o<r.length;o++)if(r[o]!=0)return-1;break}return t}function Wa(r){let t="0x";for(let e of r)t+=(e>>4).toString(16)+(e&15).toString(16);return t}var be=4,ye=16,xb=parseInt("0xFFFF",16),ml=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Ar(r,t){t.length===ye&&r.length===be&&Ya(t,0,11)&&(t=t.slice(12)),t.length===be&&r.length===ye&&ja(r,ml,0,11)&&(r=r.slice(12));let e=r.length;if(e!=t.length)throw new Error("Failed to mask ip");let n=new Uint8Array(e);for(let o=0;o<e;o++)n[o]=r[o]&t[o];return n}function Qa(r,t){if(typeof t=="string"&&(t=qe(t)),t==null)throw new Error("Invalid ip");if(t.length!==r.network.length)return!1;for(let e=0;e<t.length;e++)if((r.network[e]&r.mask[e])!==(t[e]&r.mask[e]))return!1;return!0}function xs(r){let[t,e]=r.split("/");if(!t||!e)throw new Error("Failed to parse given CIDR: "+r);let n=be,o=En(t);if(o==null&&(n=ye,o=Sn(t),o==null))throw new Error("Failed to parse given CIDR: "+r);let s=parseInt(e,10);if(Number.isNaN(s)||String(s).length!==e.length||s<0||s>n*8)throw new Error("Failed to parse given CIDR: "+r);let i=ws(s,8*n);return{network:Ar(o,i),mask:i}}function ws(r,t){if(t!==8*be&&t!==8*ye)throw new Error("Invalid CIDR mask");if(r<0||r>t)throw new Error("Invalid CIDR mask");let e=t/8,n=new Uint8Array(e);for(let o=0;o<e;o++){if(r>=8){n[o]=255,r-=8;continue}n[o]=255-(255>>r),r=0}return n}var Br=class{constructor(t,e){if(e==null)({network:this.network,mask:this.mask}=xs(t));else{let n=qe(t);if(n==null)throw new Error("Failed to parse network");e=String(e);let o=parseInt(e,10);if(Number.isNaN(o)||String(o).length!==e.length||o<0||o>n.length*8){let s=qe(e);if(s==null)throw new Error("Failed to parse mask");this.mask=s}else this.mask=ws(o,8*n.length);this.network=Ar(n,this.mask)}}contains(t){return Qa({network:this.network,mask:this.mask},t)}toString(){let t=Xa(this.mask),e=t!==-1?String(t):Wa(this.mask);return ys(this.network)+"/"+e}};function Ja(r,t){return new Br(r).contains(t)}function tc(r){try{let t=ee(r);return t.type==="ip6"?Ja("2000::/3",t.host):!1}catch{return!1}}function Fe(r){return!!En(r)}function vn(r){return!!Sn(r)}var oc=Mc(nc(),1),Sl=["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"],vl=Sl.map(r=>new oc.Netmask(r));function Bs(r){for(let t of vl)if(t.contains(r))return!0;return!1}function _l(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function Il(r){let t=r.split(":");if(t.length<2)return!1;let e=t[t.length-1].padStart(4,"0"),n=t[t.length-2].padStart(4,"0"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(e.substring(0,2),16)}.${parseInt(e.substring(2),16)}`;return Bs(o)}function Al(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function Bl(r){let t=r.split(":"),e=t[t.length-1];return Bs(e)}function Dl(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 In(r){if(Fe(r))return Bs(r);if(_l(r))return Il(r);if(Al(r))return Bl(r);if(vn(r))return Dl(r)}function sc(r){try{let t=ee(r);switch(t.type){case"ip4":case"ip6":return In(t.host)??!1;default:return t.host==="localhost"}}catch{return!1}}function $e(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var An=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||(t-1&t)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},Ge=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new An(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){let e=this.head;this.head=e.next=new An(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let e=this.tail.next;this.tail.next=null,this.tail=e,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var Ds=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function Bn(r={}){return Ll(e=>{let n=e.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function Ll(r,t){t=t??{};let e=t.onEnd,n=new Ge,o,s,i,a=$e(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((x,b)=>{s=I=>{s=null,n.push(I);try{x(r(n))}catch(w){b(w)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=$e()})}},u=x=>s!=null?s(x):(n.push(x),o),f=x=>(n=new Ge,s!=null?s({error:x}):(n.push({error:x}),o)),l=x=>{if(i)return o;if(t?.objectMode!==!0&&x?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:x})},d=x=>i?o:(i=!0,x!=null?f(x):u({done:!0})),y=()=>(n=new Ge,d(),{done:!0}),h=x=>(d(x),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:y,throw:h,push:l,end:d,get readableLength(){return n.size},onEmpty:async x=>{let b=x?.signal;if(b?.throwIfAborted(),n.isEmpty())return;let I,w;b!=null&&(I=new Promise((A,k)=>{w=()=>{k(new Ds)},b.addEventListener("abort",w)}));try{await Promise.race([a.promise,I])}finally{w!=null&&b!=null&&b?.removeEventListener("abort",w)}}},e==null)return o;let v=o;return o={[Symbol.asyncIterator](){return this},next(){return v.next()},throw(x){return v.throw(x),e!=null&&(e(x),e=void 0),{done:!0}},return(){return v.return(),e!=null&&(e(),e=void 0),{done:!0}},push:l,end(x){return v.end(x),e!=null&&(e(x),e=void 0),o},get readableLength(){return v.readableLength},onEmpty:x=>v.onEmpty(x)},o}var Ls=class r extends Error{name="TimeoutError";constructor(t,e){super(t,e),Error.captureStackTrace?.(this,r)}},ic=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function Cs(r,t){let{milliseconds:e,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=t,a,c,f=new Promise((l,d)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(i?.aborted){d(ic(i));return}if(i&&(c=()=>{d(ic(i))},i.addEventListener("abort",c,{once:!0})),r.then(l,d),e===Number.POSITIVE_INFINITY)return;let y=new Ls;a=s.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(h){d(h)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?l():o instanceof Error?d(o):(y.message=o??`Promise timed out after ${e} milliseconds`,d(y))},e)}).finally(()=>{f.clear(),c&&i&&i.removeEventListener("abort",c)});return f.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},f}var Cl=r=>{let t=r.addEventListener||r.on||r.addListener,e=r.removeEventListener||r.off||r.removeListener;if(!t||!e)throw new TypeError("Emitter is not compatible");return{addListener:t.bind(r),removeListener:e.bind(r)}};function Tl(r,t,e){let n,o=new Promise((s,i)=>{if(e={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...e},!(e.count>=0&&(e.count===Number.POSITIVE_INFINITY||Number.isInteger(e.count))))throw new TypeError("The `count` option should be at least 0 or more");e.signal?.throwIfAborted();let a=[t].flat(),c=[],{addListener:u,removeListener:f}=Cl(r),l=async(...y)=>{let h=e.multiArgs?y:y[0];if(e.filter)try{if(!await e.filter(h))return}catch(v){n(),i(v);return}c.push(h),e.count===c.length&&(n(),s(c))},d=(...y)=>{n(),i(e.rejectionMultiArgs?y:y[0])};n=()=>{for(let y of a)f(y,l);for(let y of e.rejectionEvents)a.includes(y)||f(y,d)};for(let y of a)u(y,l);for(let y of e.rejectionEvents)a.includes(y)||u(y,d);e.signal&&e.signal.addEventListener("abort",()=>{d(e.signal.reason)},{once:!0}),e.resolveImmediately&&s(c)});if(o.cancel=n,typeof e.timeout=="number"){let s=Cs(o,{milliseconds:e.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function Ze(r,t,e){typeof e=="function"&&(e={filter:e}),e={...e,count:1,resolveImmediately:!1};let n=Tl(r,t,e),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function Dr(r,t){let e,n=function(){let o=function(){e=void 0,r()};clearTimeout(e),e=setTimeout(o,t)};return n.start=()=>{},n.stop=()=>{clearTimeout(e)},n}var Dn=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}},we=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"};function Rl(r){return r.reason}async function Lr(r,t,e){if(t==null)return r;let n=e?.translateError??Rl;if(t.aborted)return r.catch(()=>{}),Promise.reject(n(t));let o;try{return await Promise.race([r,new Promise((s,i)=>{o=()=>{i(n(t))},t.addEventListener("abort",o)})])}finally{o!=null&&t.removeEventListener("abort",o)}}var Ln=class{deferred;signal;onProgress;constructor(t){this.signal=t?.signal,this.onProgress=t?.onProgress,this.deferred=$e(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Pt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function kl(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Cn=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=kl(),this.status="queued",this.fn=t,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(t){this.controller.abort(t)}onAbort(){this.recipients.reduce((e,n)=>e&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Pt),this.cleanup())}async join(t){let e=new Ln(t);return this.recipients.push(e),t?.signal?.addEventListener("abort",this.onAbort),e.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let t=await Lr(this.fn({...this.options??{},signal:this.controller.signal,onProgress:e=>{this.recipients.forEach(n=>{n.onProgress?.(e)})}}),this.controller.signal);this.recipients.forEach(e=>{e.deferred.resolve(t)}),this.status="complete"}catch(t){this.recipients.forEach(e=>{e.deferred.reject(t)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(t=>{t.cleanup(),t.signal?.removeEventListener("abort",this.onAbort)})}};var Tn=class extends Kr{concurrency;maxSize;queue;pending;sort;paused;constructor(t={}){super(),this.concurrency=t.concurrency??Number.POSITIVE_INFINITY,this.maxSize=t.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,t.metricName!=null&&t.metrics?.registerMetricGroup(t.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=t.sort,this.queue=[],this.emitEmpty=Dr(this.emitEmpty.bind(this),1),this.emitIdle=Dr(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 t;for(let e of this.queue)if(e.status==="queued"){t=e;break}return t==null?!1:(this.safeDispatchEvent("active"),this.pending++,t.run().finally(()=>{for(let e=0;e<this.queue.length;e++)if(this.queue[e]===t){this.queue.splice(e,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(t){this.queue.push(t),this.sort!=null&&this.queue.sort(this.sort)}async add(t,e){if(e?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Dn;let n=new Cn(t,e);this.enqueue(n),this.safeDispatchEvent("add");let o=n.join(e).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(t=>{t.abort(new Pt)}),this.clear()}async onEmpty(t){this.size!==0&&await Ze(this,"empty",t)}async onSizeLessThan(t,e){this.size<t||await Ze(this,"next",{...e,filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await Ze(this,"idle",t)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(t){t?.signal?.throwIfAborted();let e=Bn({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),e.end(c)},o=c=>{c.detail!=null&&e.push(c.detail)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new Pt("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",s),this.addEventListener("idle",i),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),t?.signal?.removeEventListener("abort",a),n()}}};function Cr(r){let t=new globalThis.AbortController;function e(){let s=r.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();t.abort(s);for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",e)}for(let s of r){if(s?.aborted===!0){e();break}s?.addEventListener!=null&&s.addEventListener("abort",e)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",e)}let o=t.signal;return o.clear=n,o}var ot=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Ht=class extends Error{static name="ValidationError";name="ValidationError"},Rn=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},kn=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function Rs(r){return t=>W(t,r)}function ks(r){return t=>H(t,r)}function Ye(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Ee(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(t)}function ac(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==16)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);let e=H(t[0],"base32"),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Ee(n);return Nt([e,o],e.length+o.length)}function cc(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let e=Zt.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Ee(n);return Nt([e,o],e.length+o.length)}function Ps(r){let t=r.subarray(0,r.length-2),e=r.subarray(r.length-2),n=W(t,"base32"),o=Ye(e);return`${n}:${o}`}var Os=function(r){r=r.toString().trim();let t=new Uint8Array(4);return r.split(/\./g).forEach((e,n)=>{let o=parseInt(e,10);if(isNaN(o)||o<0||o>255)throw new ot("Invalid byte value in IP address");t[n]=o}),t},uc=function(r){let t=0;r=r.toString().trim();let e=r.split(":",8),n;for(n=0;n<e.length;n++){let s=Fe(e[n]),i;s&&(i=Os(e[n]),e[n]=W(i.subarray(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,W(i.subarray(2,4),"base16"))}if(e[0]==="")for(;e.length<8;)e.unshift("0");else if(e[e.length-1]==="")for(;e.length<8;)e.push("0");else if(e.length<8){for(n=0;n<e.length&&e[n]!=="";n++);let s=[n,1];for(n=9-e.length;n>0;n--)s.push("0");e.splice.apply(e,s)}let o=new Uint8Array(t+16);for(n=0;n<e.length;n++){e[n]===""&&(e[n]="0");let s=parseInt(e[n],16);if(isNaN(s)||s<0||s>65535)throw new ot("Invalid byte value in IP address");o[t++]=s>>8&255,o[t++]=s&255}return o},fc=function(r){if(r.byteLength!==4)throw new ot("IPv4 address was incorrect length");let t=[];for(let e=0;e<r.byteLength;e++)t.push(r[e]);return t.join(".")},lc=function(r){if(r.byteLength!==16)throw new ot("IPv6 address was incorrect length");let t=[];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")}`;t.push(i)}let e=t.join(":");try{let n=new URL(`http://[${e}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new ot(`Invalid IPv6 address "${e}"`)}};function dc(r){try{let t=new URL(`http://[${r}]`);return t.hostname.substring(1,t.hostname.length-1)}catch{throw new ot(`Invalid IPv6 address "${r}"`)}}var Ts=Object.values(sr).map(r=>r.decoder),Pl=(function(){let r=Ts[0].or(Ts[1]);return Ts.slice(2).forEach(t=>r=r.or(t)),r})();function hc(r){return Pl.decode(r)}function pc(r){return t=>r.encoder.encode(t)}function Ol(r){if(parseInt(r).toString()!==r)throw new Ht("Value must be an integer")}function Nl(r){if(r<0)throw new Ht("Value must be a positive integer, or zero")}function Ul(r){return t=>{if(t>r)throw new Ht(`Value must be smaller than or equal to ${r}`)}}function Ml(...r){return t=>{for(let e of r)e(t)}}var Tr=Ml(Ol,Nl,Ul(65535));var et=-1,Ns=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(t){let e;if(typeof t=="string"?e=this.protocolsByName.get(t):e=this.protocolsByCode.get(t),e==null)throw new kn(`Protocol ${t} was unknown`);return e}addProtocol(t){this.protocolsByCode.set(t.code,t),this.protocolsByName.set(t.name,t),t.aliases?.forEach(e=>{this.protocolsByName.set(e,t)})}removeProtocol(t){let e=this.protocolsByCode.get(t);e!=null&&(this.protocolsByCode.delete(e.code),this.protocolsByName.delete(e.name),e.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},$t=new Ns,vd=[{code:4,name:"ip4",size:32,valueToBytes:Os,bytesToValue:fc,validate:r=>{if(!Fe(r))throw new Ht(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Ee,bytesToValue:Ye,validate:Tr},{code:273,name:"udp",size:16,valueToBytes:Ee,bytesToValue:Ye,validate:Tr},{code:33,name:"dccp",size:16,valueToBytes:Ee,bytesToValue:Ye,validate:Tr},{code:41,name:"ip6",size:128,valueToBytes:uc,bytesToValue:lc,stringToValue:dc,validate:r=>{if(!vn(r))throw new Ht(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:et},{code:43,name:"ipcidr",size:8,bytesToValue:Rs("base10"),valueToBytes:ks("base10")},{code:53,name:"dns",size:et},{code:54,name:"dns4",size:et},{code:55,name:"dns6",size:et},{code:56,name:"dnsaddr",size:et},{code:132,name:"sctp",size:16,valueToBytes:Ee,bytesToValue:Ye,validate:Tr},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:et,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:et,bytesToValue:Rs("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?ks("base58btc")(r):at.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Ps,valueToBytes:ac},{code:445,name:"onion3",size:296,bytesToValue:Ps,valueToBytes:cc},{code:446,name:"garlic64",size:et},{code:447,name:"garlic32",size:et},{code:448,name:"tls"},{code:449,name:"sni",size:et},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:et,bytesToValue:pc(oo),valueToBytes:hc},{code:480,name:"http"},{code:481,name:"http-path",size:et,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:et}];vd.forEach(r=>{$t.addProtocol(r)});function mc(r){let t=[],e=0;for(;e<r.length;){let n=br(r,e),o=$t.getProtocol(n),s=gt(n),i=_d(o,r,e+s),a=0;i>0&&o.size===et&&(a=gt(i));let c=s+a+i,u={code:n,name:o.name,bytes:r.subarray(e,e+c)};if(i>0){let f=e+s+a,l=r.subarray(f,f+i);u.value=o.bytesToValue?.(l)??W(l)}t.push(u),e+=c}return t}function gc(r){let t=0,e=[];for(let n of r){if(n.bytes==null){let o=$t.getProtocol(n.code),s=gt(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??H(n.value),a=i.byteLength,o.size===et&&(c=gt(a)));let u=new Uint8Array(s+c+a),f=0;Ne(n.code,u,f),f+=s,i!=null&&(o.size===et&&(Ne(a,u,f),f+=c),u.set(i,f)),n.bytes=u}e.push(n.bytes),t+=n.bytes.byteLength}return Nt(e,t)}function bc(r){if(r.charAt(0)!=="/")throw new ot('String multiaddr must start with "/"');let t=[],e="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(e==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=$t.getProtocol(o);if(e==="protocol"){if(c.size==null||c.size===0){t.push({code:c.code,name:c.name}),n="",o="",e="protocol";continue}else if(a)throw new ot(`Component ${o} was missing value`);e="value"}else if(e==="value"){let u={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new ot(`Component ${o} was missing value`);u.value=c.stringToValue?.(n)??n}t.push(u),n="",o="",e="protocol"}}}if(o!==""&&n!=="")throw new ot("Incomplete multiaddr");return t}function yc(r){return`/${r.flatMap(t=>{if(t.value==null)return t.name;let e=$t.getProtocol(t.code);if(e==null)throw new ot(`Unknown protocol code ${t.code}`);return[t.name,e.valueToString?.(t.value)??t.value]}).join("/")}`}function _d(r,t,e){return r.size==null||r.size===0?0:r.size>0?r.size/8:br(t,e)}var Id=Symbol.for("nodejs.util.inspect.custom"),Ks=Symbol.for("@multiformats/multiaddr");function Ad(r){if(r==null&&(r="/"),xc(r))return r.getComponents();if(r instanceof Uint8Array)return mc(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),bc(r);if(Array.isArray(r))return r;throw new ot("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Pn=class r{[Ks]=!0;#t;#e;#r;constructor(t="/",e={}){this.#t=Ad(t),e.validate!==!1&&Bd(this)}get bytes(){return this.#r==null&&(this.#r=gc(this.#t)),this.#r}toString(){return this.#e==null&&(this.#e=yc(this.#t)),this.#e}toJSON(){return this.toString()}getComponents(){return[...this.#t.map(t=>({...t}))]}encapsulate(t){let e=new r(t);return new r([...this.#t,...e.getComponents()],{validate:!1})}decapsulate(t){let e=t.toString(),n=this.toString(),o=n.lastIndexOf(e);if(o<0)throw new Rn(`Address ${this.toString()} does not contain subaddress: ${e}`);return new r(n.slice(0,o),{validate:!1})}decapsulateCode(t){let e;for(let n=this.#t.length-1;n>-1;n--)if(this.#t[n].code===t){e=n;break}return new r(this.#t.slice(0,e),{validate:!1})}equals(t){return lt(this.bytes,t.bytes)}[Id](){return`Multiaddr(${this.toString()})`}};function Bd(r){r.getComponents().forEach(t=>{let e=$t.getProtocol(t.code);t.value!=null&&e.validate?.(t.value)})}function xc(r){return!!r?.[Ks]}function wc(r){return new Pn(r)}var Dd=4194304,On=class extends Error{static name="UnwrappedError";name="UnwrappedError"},Fs=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},zs=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Vs=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Ld(r){return typeof r?.closeRead=="function"}function Cd(r){return typeof r?.close=="function"}function qs(r){return Ld(r)?r.remoteWriteStatus!=="writable"&&r.readBufferLength===0:Cd(r)?r.status!=="open":!1}function Td(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function Rd(r,t){let e=t?.maxBufferSize??Dd,n=new Q,o,s=!1;if(!Td(r))throw new ft("Argument should be a Stream or a Multiaddr");let i=f=>{if(n.append(f.data),n.byteLength>e){let l=n.byteLength;n.consume(n.byteLength),o?.reject(new Error(`Read buffer overflow - ${l} > ${e}`))}o?.resolve()};r.addEventListener("message",i);let a=f=>{f.error!=null?o?.reject(f.error):o?.resolve()};r.addEventListener("close",a);let c=()=>{o?.resolve()};r.addEventListener("remoteCloseWrite",c);let u={readBuffer:n,async read(f){if(s===!0)throw new On("Stream was unwrapped");if(qs(r)){if(n.byteLength===0&&f?.bytes==null)return null;if(f?.bytes!=null&&n.byteLength<f.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,f.bytes),new we(`Unexpected EOF - stream closed after reading ${n.byteLength}/${f.bytes} bytes`)}let l=f?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=l){o.resolve();break}if(await Lr(o.promise,f?.signal),qs(r)){if(n.byteLength===0&&f?.bytes==null)return null;break}o=Promise.withResolvers()}let d=f?.bytes??n.byteLength;if(n.byteLength<d){if(qs(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,d),new we(`Unexpected EOF - stream closed while reading ${n.byteLength}/${d} bytes`);return u.read(f)}let y=n.sublist(0,d);return n.consume(d),y},async write(f,l){if(s===!0)throw new On("Stream was unwrapped");r.send(f)||await Ze(r,"drain",{signal:l?.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 kd(r,t={}){let e=Rd(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=gt(t.maxDataLength));let n=t?.lengthDecoder??br,o=t?.lengthEncoder??wa;return{async read(i){let a=-1,c=new Q;for(;;){let f=await e.read({...i,bytes:1});if(f==null)break;c.append(f);try{a=n(c)}catch(l){if(l instanceof RangeError)continue;throw l}if(a<0)throw new Fs("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new Vs(`Message length length too long - ${c.byteLength} > ${t.maxLengthLength}`);if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new zs(`Message length too long - ${a} > ${t.maxDataLength}`);let u=await e.read({...i,bytes:a});if(u==null)throw r.log.error("tried to read %d bytes but the stream closed",a),new we(`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 we(`Unexpected EOF - read ${u.byteLength}/${a} bytes before the stream closed`);return u},async write(i,a){await e.write(new Q(o(i.byteLength),i),a)},async writeV(i,a){let c=new Q(...i.flatMap(u=>[o(u.byteLength),u]));await e.write(c,a)},unwrap(){return e.unwrap()}}}function je(r,t){let e=kd(r,t),n={read:async(o,s)=>{let i=await e.read(s);return o.decode(i)},write:async(o,s,i)=>{await e.write(s.encode(o),i)},writeV:async(o,s,i)=>{await e.writeV(o.map(a=>s.encode(a)),i)},pb:o=>({read:async s=>n.read(o,s),write:async(s,i)=>n.write(s,o,i),writeV:async(s,i)=>n.writeV(s,o,i),unwrap:()=>n}),unwrap:()=>e.unwrap()};return n}var Nn=class extends Tn{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};function Ec(r,t,e){let n,o,s=!1;function i(){let u={signal:o.signal},f;e?.timeout!=null&&(f=Cr([o.signal,AbortSignal.timeout(e.timeout)]),u.signal=f),s=!0,Promise.resolve().then(async()=>{await r(u)}).catch(()=>{}).finally(()=>{f!=null&&(f.aborted?f.clear():f.addEventListener("abort",()=>{f.clear()},{once:!0})),s=!1,!o.signal.aborted&&(n=setTimeout(i,t))})}let a=Dr(i,e?.debounce??100),c=!1;return{setInterval:u=>{t!==u&&(t=u,n!=null&&(clearTimeout(n),n=setTimeout(i,t)))},setTimeout:u=>{e??={},e.timeout=u},run:()=>{s||(clearTimeout(n),a())},start:()=>{c||(c=!0,o=new AbortController,o.signal,e?.runImmediately===!0?queueMicrotask(()=>{i()}):n=setTimeout(i,t))},stop:()=>{clearTimeout(n),o?.abort(),c=!1}}}var Hs=class extends Map{metric;constructor(t){super();let{name:e,metrics:n}=t;this.metric=n.registerMetric(e),this.updateComponentMetric()}set(t,e){return super.set(t,e),this.updateComponentMetric(),this}delete(t){let e=super.delete(t);return this.updateComponentMetric(),e}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Sc(r){let{name:t,metrics:e}=r,n;return e!=null?n=new Hs({name:t,metrics:e}):n=new Map,n}var $s="libp2p",Gs="autonat";var vc="dial-request",_c="dial-back",Ic=200n*1024n,Ac=4096;var Xe;(function(r){let t;r.codec=()=>(t==null&&(t=_t((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s={...s},s.dialDataResponse!=null&&(s.dialDataRequest=void 0,s.dialResponse=void 0,s.dialRequest=void 0),s.dialDataRequest!=null&&(s.dialDataResponse=void 0,s.dialResponse=void 0,s.dialRequest=void 0),s.dialResponse!=null&&(s.dialDataResponse=void 0,s.dialDataRequest=void 0,s.dialRequest=void 0),s.dialRequest!=null&&(s.dialDataResponse=void 0,s.dialDataRequest=void 0,s.dialResponse=void 0),s.dialRequest!=null&&(i.uint32(10),Rr.codec().encode(s.dialRequest,i)),s.dialResponse!=null&&(i.uint32(18),kt.codec().encode(s.dialResponse,i)),s.dialDataRequest!=null&&(i.uint32(26),kr.codec().encode(s.dialDataRequest,i)),s.dialDataResponse!=null&&(i.uint32(34),Pr.codec().encode(s.dialDataResponse,i)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{c.dialRequest=Rr.codec().decode(s,s.uint32(),{limits:a.limits?.dialRequest});break}case 2:{c.dialResponse=kt.codec().decode(s,s.uint32(),{limits:a.limits?.dialResponse});break}case 3:{c.dialDataRequest=kr.codec().decode(s,s.uint32(),{limits:a.limits?.dialDataRequest});break}case 4:{c.dialDataResponse=Pr.codec().decode(s,s.uint32(),{limits:a.limits?.dialDataResponse});break}default:{s.skipType(f&7);break}}}return c.dialDataResponse!=null&&(delete c.dialDataRequest,delete c.dialResponse,delete c.dialRequest),c.dialDataRequest!=null&&(delete c.dialDataResponse,delete c.dialResponse,delete c.dialRequest),c.dialResponse!=null&&(delete c.dialDataResponse,delete c.dialDataRequest,delete c.dialRequest),c.dialRequest!=null&&(delete c.dialDataResponse,delete c.dialDataRequest,delete c.dialResponse),c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{yield*Rr.codec().stream(s,s.uint32(),`${a}.dialRequest`,{limits:c.limits?.dialRequest});break}case 2:{yield*kt.codec().stream(s,s.uint32(),`${a}.dialResponse`,{limits:c.limits?.dialResponse});break}case 3:{yield*kr.codec().stream(s,s.uint32(),`${a}.dialDataRequest`,{limits:c.limits?.dialDataRequest});break}case 4:{yield*Pr.codec().stream(s,s.uint32(),`${a}.dialDataResponse`,{limits:c.limits?.dialDataResponse});break}default:{s.skipType(f&7);break}}}})),t);function e(s){return St(s,r.codec())}r.encode=e;function n(s,i){return Et(s,r.codec(),i)}r.decode=n;function o(s,i){return vt(s,r.codec(),i)}r.stream=o})(Xe||(Xe={}));var Rr;(function(r){let t;r.codec=()=>(t==null&&(t=_t((s,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),s.addrs!=null&&s.addrs.length>0)for(let c of s.addrs)i.uint32(10),i.bytes(c);s.nonce!=null&&s.nonce!==0n&&(i.uint32(17),i.fixed64(s.nonce)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={addrs:[],nonce:0n},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{if(a.limits?.addrs!=null&&c.addrs.length===a.limits.addrs)throw new Er('Decode error - repeated field "addrs" had too many elements');c.addrs.push(s.bytes());break}case 2:{c.nonce=s.fixed64();break}default:{s.skipType(f&7);break}}}return c},function*(s,i,a,c={}){let u={addrs:0},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let l=s.uint32();switch(l>>>3){case 1:{if(c.limits?.addrs!=null&&u.addrs===c.limits.addrs)throw new Er('Streaming decode error - repeated field "addrs" had too many elements');yield{field:`${a}.addrs[]`,index:u.addrs,value:s.bytes()},u.addrs++;break}case 2:{yield{field:`${a}.nonce`,value:s.fixed64()};break}default:{s.skipType(l&7);break}}}})),t);function e(s){return St(s,r.codec())}r.encode=e;function n(s,i){return Et(s,r.codec(),i)}r.decode=n;function o(s,i){return vt(s,r.codec(),i)}r.stream=o})(Rr||(Rr={}));var kr;(function(r){let t;r.codec=()=>(t==null&&(t=_t((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.addrIdx!=null&&s.addrIdx!==0&&(i.uint32(8),i.uint32(s.addrIdx)),s.numBytes!=null&&s.numBytes!==0n&&(i.uint32(16),i.uint64(s.numBytes)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={addrIdx:0,numBytes:0n},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{c.addrIdx=s.uint32();break}case 2:{c.numBytes=s.uint64();break}default:{s.skipType(f&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{yield{field:`${a}.addrIdx`,value:s.uint32()};break}case 2:{yield{field:`${a}.numBytes`,value:s.uint64()};break}default:{s.skipType(f&7);break}}}})),t);function e(s){return St(s,r.codec())}r.encode=e;function n(s,i){return Et(s,r.codec(),i)}r.decode=n;function o(s,i){return vt(s,r.codec(),i)}r.stream=o})(kr||(kr={}));var st;(function(r){r.UNUSED="UNUSED",r.E_DIAL_ERROR="E_DIAL_ERROR",r.E_DIAL_BACK_ERROR="E_DIAL_BACK_ERROR",r.OK="OK"})(st||(st={}));var Un;(function(r){r[r.UNUSED=0]="UNUSED",r[r.E_DIAL_ERROR=100]="E_DIAL_ERROR",r[r.E_DIAL_BACK_ERROR=101]="E_DIAL_BACK_ERROR",r[r.OK=200]="OK"})(Un||(Un={}));(function(r){r.codec=()=>pe(Un)})(st||(st={}));var kt;(function(r){let t;(function(a){a.E_INTERNAL_ERROR="E_INTERNAL_ERROR",a.E_REQUEST_REJECTED="E_REQUEST_REJECTED",a.E_DIAL_REFUSED="E_DIAL_REFUSED",a.OK="OK"})(t=r.ResponseStatus||(r.ResponseStatus={}));let e;(function(a){a[a.E_INTERNAL_ERROR=0]="E_INTERNAL_ERROR",a[a.E_REQUEST_REJECTED=100]="E_REQUEST_REJECTED",a[a.E_DIAL_REFUSED=101]="E_DIAL_REFUSED",a[a.OK=200]="OK"})(e||(e={})),(function(a){a.codec=()=>pe(e)})(t=r.ResponseStatus||(r.ResponseStatus={}));let n;r.codec=()=>(n==null&&(n=_t((a,c,u={})=>{u.lengthDelimited!==!1&&c.fork(),a.status!=null&&e[a.status]!==0&&(c.uint32(8),r.ResponseStatus.codec().encode(a.status,c)),a.addrIdx!=null&&a.addrIdx!==0&&(c.uint32(16),c.uint32(a.addrIdx)),a.dialStatus!=null&&Un[a.dialStatus]!==0&&(c.uint32(24),st.codec().encode(a.dialStatus,c)),u.lengthDelimited!==!1&&c.ldelim()},(a,c,u={})=>{let f={status:t.E_INTERNAL_ERROR,addrIdx:0,dialStatus:st.UNUSED},l=c==null?a.len:a.pos+c;for(;a.pos<l;){let d=a.uint32();switch(d>>>3){case 1:{f.status=r.ResponseStatus.codec().decode(a);break}case 2:{f.addrIdx=a.uint32();break}case 3:{f.dialStatus=st.codec().decode(a);break}default:{a.skipType(d&7);break}}}return f},function*(a,c,u,f={}){let l=c==null?a.len:a.pos+c;for(;a.pos<l;){let d=a.uint32();switch(d>>>3){case 1:{yield{field:`${u}.status`,value:r.ResponseStatus.codec().decode(a)};break}case 2:{yield{field:`${u}.addrIdx`,value:a.uint32()};break}case 3:{yield{field:`${u}.dialStatus`,value:st.codec().decode(a)};break}default:{a.skipType(d&7);break}}}})),n);function o(a){return St(a,r.codec())}r.encode=o;function s(a,c){return Et(a,r.codec(),c)}r.decode=s;function i(a,c){return vt(a,r.codec(),c)}r.stream=i})(kt||(kt={}));var Pr;(function(r){let t;r.codec=()=>(t==null&&(t=_t((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.data!=null&&s.data.byteLength>0&&(i.uint32(10),i.bytes(s.data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={data:yt(0)},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();f>>>3===1?c.data=s.bytes():s.skipType(f&7)}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();f>>>3===1?yield{field:`${a}.data`,value:s.bytes()}:s.skipType(f&7)}})),t);function e(s){return St(s,r.codec())}r.encode=e;function n(s,i){return Et(s,r.codec(),i)}r.decode=n;function o(s,i){return vt(s,r.codec(),i)}r.stream=o})(Pr||(Pr={}));var We;(function(r){let t;r.codec=()=>(t==null&&(t=_t((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.nonce!=null&&s.nonce!==0n&&(i.uint32(9),i.fixed64(s.nonce)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={nonce:0n},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();f>>>3===1?c.nonce=s.fixed64():s.skipType(f&7)}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();f>>>3===1?yield{field:`${a}.nonce`,value:s.fixed64()}:s.skipType(f&7)}})),t);function e(s){return St(s,r.codec())}r.encode=e;function n(s,i){return Et(s,r.codec(),i)}r.decode=n;function o(s,i){return vt(s,r.codec(),i)}r.stream=o})(We||(We={}));var ne;(function(r){let t;(function(a){a.OK="OK"})(t=r.DialBackStatus||(r.DialBackStatus={}));let e;(function(a){a[a.OK=0]="OK"})(e||(e={})),(function(a){a.codec=()=>pe(e)})(t=r.DialBackStatus||(r.DialBackStatus={}));let n;r.codec=()=>(n==null&&(n=_t((a,c,u={})=>{u.lengthDelimited!==!1&&c.fork(),a.status!=null&&e[a.status]!==0&&(c.uint32(8),r.DialBackStatus.codec().encode(a.status,c)),u.lengthDelimited!==!1&&c.ldelim()},(a,c,u={})=>{let f={status:t.OK},l=c==null?a.len:a.pos+c;for(;a.pos<l;){let d=a.uint32();d>>>3===1?f.status=r.DialBackStatus.codec().decode(a):a.skipType(d&7)}return f},function*(a,c,u,f={}){let l=c==null?a.len:a.pos+c;for(;a.pos<l;){let d=a.uint32();d>>>3===1?yield{field:`${u}.status`,value:r.DialBackStatus.codec().decode(a)}:a.skipType(d&7)}})),n);function o(a){return St(a,r.codec())}r.encode=o;function s(a,c){return Et(a,r.codec(),c)}r.decode=s;function i(a,c){return vt(a,r.codec(),c)}r.stream=i})(ne||(ne={}));function Mn(r,t){return Math.round(Math.random()*(t-r)+r)}var Od=4,Nd=8,Kn=class{components;dialRequestProtocol;dialBackProtocol;timeout;maxInboundStreams;maxOutboundStreams;maxMessageSize;maxDialDataBytes;dialDataChunkSize;started;log;topologyId;dialResults;findPeers;addressFilter;connectionThreshold;queue;nonces;constructor(t,e){this.components=t,this.log=t.logger.forComponent("libp2p:auto-nat-v2:client"),this.started=!1,this.dialRequestProtocol=e.dialRequestProtocol,this.dialBackProtocol=e.dialBackProtocol,this.timeout=e.timeout??3e4,this.maxInboundStreams=e.maxInboundStreams??2,this.maxOutboundStreams=e.maxOutboundStreams??20,this.connectionThreshold=e.connectionThreshold??80,this.maxMessageSize=e.maxMessageSize??8192,this.dialResults=Sc({name:"libp2p_autonat_v2_dial_results",metrics:t.metrics}),this.findPeers=Ec(this.findRandomPeers.bind(this),6e4),this.addressFilter=bs(1024),this.queue=new Nn({concurrency:3,maxSize:50}),this.maxDialDataBytes=e.maxDialDataBytes??Ic,this.dialDataChunkSize=e.dialDataChunkSize??Ac,this.nonces=new Set}[Symbol.toStringTag]="@libp2p/autonat-v2";[qr]=["@libp2p/autonat"];get[Fr](){return["@libp2p/identify"]}isStarted(){return this.started}async start(){this.started||(this.topologyId=await this.components.registrar.register(this.dialRequestProtocol,{onConnect:(t,e)=>{this.verifyExternalAddresses(e).catch(n=>{this.log.error("could not verify addresses - %e",n)})}}),await this.components.registrar.handle(this.dialBackProtocol,(t,e)=>{this.handleDialBackStream(t,e).catch(n=>{this.log.error("error handling incoming autonat stream - %e",n)})},{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams}),this.findPeers.start(),this.started=!0)}async stop(){await this.components.registrar.unhandle(this.dialRequestProtocol),await this.components.registrar.unhandle(this.dialBackProtocol),this.topologyId!=null&&await this.components.registrar.unhandle(this.topologyId),this.dialResults.clear(),this.findPeers.stop(),this.started=!1}allAddressesAreVerified(){return this.components.addressManager.getAddressesWithMetadata().every(t=>t.expires>Date.now()?!0:t.verified)}async findRandomPeers(t){if(this.allAddressesAreVerified())return;let e=Cr([AbortSignal.timeout(1e4),t?.signal]);try{this.log("starting random walk to find peers to run AutoNAT");for await(let n of this.components.randomWalk.walk({signal:e})){if(!await this.components.connectionManager.isDialable(n.multiaddrs)){this.log.trace("random peer %p was not dialable %s",n.id,n.multiaddrs.map(o=>o.toString()).join(", "));continue}try{this.log.trace("dial random peer %p",n.id),await this.components.connectionManager.openConnection(n.multiaddrs,{signal:e})}catch{}if(this.allAddressesAreVerified()){this.log("stopping random walk, all addresses are verified");return}if(!this.hasConnectionCapacity()){this.log("stopping random walk, too close to max connections");return}}}catch{}}async handleDialBackStream(t,e){let n=AbortSignal.timeout(this.timeout);let o=je(t,{maxDataLength:this.maxMessageSize});try{let s=await o.read(We,{signal:n});if(!this.nonces.has(s.nonce))throw new wt("No matching dial found for nonce value");this.nonces.delete(s.nonce),await o.write({status:ne.DialBackStatus.OK},ne),await t.close({signal:n})}catch(s){this.log.error("error handling incoming dial back stream - %e",s),t.abort(s)}}getUnverifiedMultiaddrs(t,e){let n=this.components.addressManager.getAddressesWithMetadata().sort((s,i)=>s.type==="observed"&&i.type!=="observed"?1:i.type==="observed"&&s.type!=="observed"?-1:0).filter(s=>!(!(s.expires<Date.now())||ee(s.multiaddr).type==="ip6"&&(!e||!tc(s.multiaddr))||sc(s.multiaddr))),o=[];for(let s of n){let i=s.multiaddr.toString(),a=this.dialResults.get(i);if(a!=null&&a.networkSegments.includes(t)){this.log.trace("%a already has a network segment result from %s",a.multiaddr,t);continue}if(a==null){let c=s.expires<Date.now();if(c&&this.addressFilter.remove?.(i),this.addressFilter.has(i))continue;this.addressFilter.add(i),this.log.trace("creating dial result %s %s",c?"to revalidate":"for",i),a={multiaddr:s.multiaddr,success:0,failure:0,networkSegments:[],verifyingPeers:hs(),type:s.type,lastVerified:s.lastVerified},this.dialResults.set(i,a)}o.push(a)}return o}removeOutdatedMultiaddrResults(){let t=new Set(this.components.addressManager.getAddressesWithMetadata().filter(({expires:e})=>e<Date.now()).map(({multiaddr:e})=>e.toString()));for(let e of this.dialResults.keys())t.has(e)||(this.log.trace("remove results for %a",e),this.dialResults.delete(e))}async verifyExternalAddresses(t){if(!this.isStarted())return;this.removeOutdatedMultiaddrResults();let n=(await this.components.peerStore.get(t.remotePeer)).addresses.some(({multiaddr:i})=>ee(i).type==="ip6"),o=this.getNetworkSegment(t.remoteAddr),s=this.getUnverifiedMultiaddrs(o,n);if(s.length!==0){if(!this.hasConnectionCapacity()){s[0]?.lastVerified!=null?(this.log("automatically re-verifying %a because we are too close to the connection limit",s[0].multiaddr),this.confirmAddress(s[0])):this.log("skipping verifying %a because we are too close to the connection limit",s[0]?.multiaddr);return}this.queue.add(async i=>{let a=Cr([i.signal,AbortSignal.timeout(this.timeout)]),c=BigInt(Mn(0,Number.MAX_SAFE_INTEGER));this.nonces.add(c);try{await this.askPeerToVerify(t,o,c,i)}finally{a.clear(),this.nonces.delete(c)}},{peerId:t.remotePeer}).catch(i=>{this.log.error("error from %p verifying addresses - %e",t.remotePeer,i)})}}async askPeerToVerify(t,e,n,o){let s=[...this.dialResults.values()].filter(a=>a.result==null).map(a=>a.multiaddr);if(s.length===0){this.queue.clear();return}this.log.trace("asking %a to verify multiaddrs %s",t.remoteAddr,s);let i=await t.newStream(this.dialRequestProtocol,o);try{let a=je(i).pb(Xe);await a.write({dialRequest:{addrs:s.map(c=>c.bytes),nonce:n}},o);for(let c=0;c<s.length;c++){let u=await a.read(o);if(u.dialDataRequest!=null){if(u.dialDataRequest.numBytes>this.maxDialDataBytes){this.log("too many dial data byte requested by %p - %s/%s",t.remotePeer,u.dialDataRequest.numBytes,this.maxDialDataBytes);continue}this.log("sending %d bytes to %p as anti-amplification attack protection",u.dialDataRequest.numBytes,t.remotePeer);let y=new Uint8Array(this.dialDataChunkSize),h=BigInt(this.dialDataChunkSize);for(let v=0n;v<u.dialDataRequest.numBytes;v+=h)await a.write({dialDataResponse:{data:y}},o);u=await a.read(o)}if(u.dialResponse==null){this.log("invalid autonat response from %p - %j",t.remotePeer,u);return}if(u.dialResponse.status!==kt.ResponseStatus.OK)return;let l=s[u.dialResponse.addrIdx];if(l==null){this.log.trace("peer dialed unknown address");continue}let d=this.dialResults.get(l.toString());if(d==null){this.log.trace("peer reported %a as %s but there is no result object",l,u.dialResponse.status);continue}if(d.networkSegments.includes(e)){this.log.trace("%a results already included network segment %s",l,e);continue}if(d.result!=null){this.log.trace("already resolved result for %a, ignoring response from",l,t.remotePeer);continue}if(d.verifyingPeers.has(t.remotePeer)){this.log.trace("peer %p has already verified %a, ignoring response",t.remotePeer,l);continue}if(d.verifyingPeers.add(t.remotePeer),d.networkSegments.push(e),u.dialResponse.dialStatus===st.OK){if(this.log.trace("%p dialed %a successfully",t.remotePeer,d.multiaddr),d.success++,d.type!=="observed"){this.confirmAddress(d);continue}}else if(u.dialResponse.dialStatus===st.E_DIAL_ERROR)this.log.trace("%p could not dial %a",t.remotePeer,d.multiaddr),d.failure++;else if(u.dialResponse.dialStatus===st.E_DIAL_BACK_ERROR){this.log.trace("%p saw error while dialing %a",t.remotePeer,d.multiaddr);continue}this.log("%a success %d failure %d",d.multiaddr,d.success,d.failure),d.success===Od&&this.confirmAddress(d),d.failure===Nd&&this.unconfirmAddress(d)}}finally{try{await i.close(o)}catch(a){i.abort(a)}}}hasConnectionCapacity(){let e=this.components.connectionManager.getConnections().length,n=this.components.connectionManager.getMaxConnections();return e/n*100<this.connectionThreshold}confirmAddress(t){this.log("%s address %a is externally dialable",t.type,t.multiaddr),this.components.addressManager.confirmObservedAddr(t.multiaddr),this.dialResults.delete(t.multiaddr.toString()),t.result=!0}unconfirmAddress(t){this.log("%s address %a is not externally dialable",t.type,t.multiaddr),this.components.addressManager.removeObservedAddr(t.multiaddr),this.dialResults.delete(t.multiaddr.toString()),t.result=!1}getNetworkSegment(t){let e=ee(t);switch(e.type){case"ip4":return e.host.split(".")[0].padStart(3,"0");case"ip6":return e.host.split(":")[0].padStart(4,"0");default:throw new ft(`Remote address ${t} was not an IPv4 or Ipv6 address`)}}};var qn=class{components;dialRequestProtocol;dialBackProtocol;timeout;maxInboundStreams;maxOutboundStreams;maxMessageSize;started;log;constructor(t,e){this.components=t,this.log=t.logger.forComponent("libp2p:auto-nat-v2:server"),this.started=!1,this.dialRequestProtocol=e.dialRequestProtocol,this.dialBackProtocol=e.dialBackProtocol,this.timeout=e.timeout??3e4,this.maxInboundStreams=e.maxInboundStreams??2,this.maxOutboundStreams=e.maxOutboundStreams??20,this.maxMessageSize=e.maxMessageSize??8192,this.handleDialRequestStream=this.handleDialRequestStream.bind(this)}async start(){this.started||(await this.components.registrar.handle(this.dialRequestProtocol,this.handleDialRequestStream,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams}),this.started=!0)}async stop(){await this.components.registrar.unhandle(this.dialRequestProtocol),this.started=!1}async handleDialRequestStream(t,e){let n=AbortSignal.timeout(this.timeout);let o=je(t,{maxDataLength:this.maxMessageSize}).pb(Xe),s=Tc(e.remoteAddr);if(s==null)throw new wt(`Could not find IP address in connection address "${e.remoteAddr}"`);let{dialRequest:i}=await o.read({signal:n});if(i==null)throw new wt("Did not receive DialRequest message on incoming dial request stream");if(i.addrs.length===0)throw new wt("Did not receive any addresses to dial");for(let a=0;a<i.addrs.length;a++)try{let c=wc(i.addrs[a]);if(!await this.components.connectionManager.isDialable(c,{signal:n})){await o.write({dialResponse:{addrIdx:a,status:kt.ResponseStatus.E_DIAL_REFUSED,dialStatus:st.UNUSED}},{signal:n});continue}let f=Tc(c);if(f==null)throw new wt(`Could not find IP address in requested address "${c}"`);if(In(f))throw new wt(`Requested address had private IP "${c}"`);f!==s&&await this.preventAmplificationAttack(o,a,{signal:n});let l=await this.dialClientBack(c,i.nonce,{signal:n});await o.write({dialResponse:{addrIdx:a,status:kt.ResponseStatus.OK,dialStatus:l}},{signal:n})}catch(c){this.log.error("error handling incoming dialback request - %e",c)}await t.close({signal:n})}async preventAmplificationAttack(t,e,n){let o=Mn(3e4,1e5);await t.write({dialDataRequest:{addrIdx:e,numBytes:BigInt(o)}},n);let s=0;for(;s<o;){let{dialDataResponse:i}=await t.read(n);if(i==null)throw new wt("Did not receive DialDataResponse message on incoming dial request stream");s+=i.data.byteLength}}async dialClientBack(t,e,n){let o;try{o=await this.components.connectionManager.openConnection(t,{force:!0,...n})}catch(s){return this.log.error("failed to open connection to %a - %e",t,s),st.E_DIAL_ERROR}try{let s=await o.newStream(this.dialBackProtocol,n),i=je(s,{maxDataLength:this.maxMessageSize});if(await i.write({nonce:e},We,n),(await i.read(ne,n)).status!==ne.DialBackStatus.OK)throw new wt("DialBackResponse status was not OK");await o.close(n)}catch(s){return this.log.error("could not perform dial back - %e",s),o.abort(s),st.E_DIAL_BACK_ERROR}return st.OK}};function Tc(r){return r.getComponents().filter(t=>t.code===4||t.code===41).map(t=>t.value).pop()}var Fn=class{client;server;constructor(t,e){let n=`/${e.protocolPrefix??$s}/${Gs}/${"2"}/${vc}`,o=`/${e.protocolPrefix??$s}/${Gs}/${"2"}/${_c}`;this.client=new Kn(t,{...e,dialRequestProtocol:n,dialBackProtocol:o}),this.server=new qn(t,{...e,dialRequestProtocol:n,dialBackProtocol:o})}[Symbol.toStringTag]="@libp2p/autonat-v2";[qr]=["@libp2p/autonat"];get[Fr](){return["@libp2p/identify"]}async start(){await Ws(this.client,this.server)}async stop(){await Qs(this.client,this.server)}};function Ud(r={}){return t=>new Fn(t,r)}return Kc(Md);})();
|
|
3
3
|
/*! Bundled license information:
|
|
4
4
|
|
|
5
5
|
@noble/hashes/utils.js:
|