@libp2p/autonat-v2 1.0.0-cb1c14e62 → 1.0.0-cf9aab5c8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.min.js CHANGED
@@ -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 zc=Object.create;var Hr=Object.defineProperty;var Hc=Object.getOwnPropertyDescriptor;var Vc=Object.getOwnPropertyNames;var Gc=Object.getPrototypeOf,$c=Object.prototype.hasOwnProperty;var Zc=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),mt=(r,t)=>{for(var e in t)Hr(r,e,{get:t[e],enumerable:!0})},ri=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Vc(t))!$c.call(r,o)&&o!==e&&Hr(r,o,{get:()=>t[o],enumerable:!(n=Hc(t,o))||n.enumerable});return r};var Xc=(r,t,e)=>(e=r!=null?zc(Gc(r)):{},ri(t||!r||!r.__esModule?Hr(e,"default",{value:r,enumerable:!0}):e,r)),jc=r=>ri(Hr({},"__esModule",{value:!0}),r);var Ec=Zc(qr=>{(function(){var r,t,e,n,o,s,i,a;a=function(c){var u,d,l,f;return u=(c&255<<24)>>>24,d=(c&255<<16)>>>16,l=(c&65280)>>>8,f=c&255,[u,d,l,f].join(".")},i=function(c){var u,d,l,f,h,m;for(u=[],l=f=0;f<=3&&c.length!==0;l=++f){if(l>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}m=t(c),h=m[0],d=m[1],c=c.substring(d),u.push(h)}if(c.length!==0)throw new Error("Invalid IP");switch(u.length){case 1:if(u[0]>4294967295)throw new Error("Invalid IP");return u[0]>>>0;case 2:if(u[0]>255||u[1]>16777215)throw new Error("Invalid IP");return(u[0]<<24|u[1])>>>0;case 3:if(u[0]>255||u[1]>255||u[2]>65535)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2])>>>0;case 4:if(u[0]>255||u[1]>255||u[2]>255||u[3]>255)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2]<<8|u[3])>>>0;default:throw new Error("Invalid IP")}},e=function(c){return c.charCodeAt(0)},n=e("0"),s=e("a"),o=e("A"),t=function(c){var u,d,l,f,h;for(f=0,u=10,d="9",l=0,c.length>1&&c[l]==="0"&&(c[l+1]==="x"||c[l+1]==="X"?(l+=2,u=16):"0"<=c[l+1]&&c[l+1]<="9"&&(l++,u=8,d="7")),h=l;l<c.length;){if("0"<=c[l]&&c[l]<=d)f=f*u+(e(c[l])-n)>>>0;else if(u===16)if("a"<=c[l]&&c[l]<="f")f=f*u+(10+e(c[l])-s)>>>0;else if("A"<=c[l]&&c[l]<="F")f=f*u+(10+e(c[l])-o)>>>0;else break;else break;if(f>4294967295)throw new Error("too large");l++}if(l===h)throw new Error("empty octet");return[f,l]},r=function(){function c(u,d){var l,f,h,m;if(typeof u!="string")throw new Error("Missing `net' parameter");if(d||(m=u.split("/",2),u=m[0],d=m[1]),d||(d=32),typeof d=="string"&&d.indexOf(".")>-1){try{this.maskLong=i(d)}catch(x){throw l=x,new Error("Invalid mask: "+d)}for(f=h=32;h>=0;f=--h)if(this.maskLong===4294967295<<32-f>>>0){this.bitmask=f;break}}else if(d||d===0)this.bitmask=parseInt(d,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(i(u)&this.maskLong)>>>0}catch(x){throw l=x,new Error("Invalid net address: "+u)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+d);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(u){return typeof u=="string"&&(u.indexOf("/")>0||u.split(".").length!==4)&&(u=new c(u)),u instanceof c?this.contains(u.base)&&this.contains(u.broadcast||u.last):(i(u)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(u){return u==null&&(u=1),new c(a(this.netLong+this.size*u),this.mask)},c.prototype.forEach=function(u){var d,l,f;for(f=i(this.first),l=i(this.last),d=0;f<=l;)u(a(f),f,d),d++,f++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),qr.ip2long=i,qr.long2ip=a,qr.Netmask=r}).call(qr)});var Ud={};mt(Ud,{autoNATv2:()=>Nd});var no=Symbol.for("@libp2p/peer-id");var kt=class extends Error{static name="AbortError";constructor(t="The operation was aborted"){super(t),this.name="AbortError"}};var Nt=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},Vr=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}};var Gr=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}};var St=class extends Error{static name="ProtocolError";constructor(t="Protocol error"){super(t),this.name="ProtocolError"}};var ar=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var $r=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))}};function ni(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function oi(...r){let t=[];for(let e of r)ni(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 si(...r){let t=[];for(let e of r)ni(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 Zr=Symbol.for("@libp2p/service-capabilities"),Xr=Symbol.for("@libp2p/service-dependencies");var co={};mt(co,{base58btc:()=>Z,base58flickr:()=>ru});var fh=new Uint8Array(0);function ii(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 Ut(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 ai(r){return new TextEncoder().encode(r)}function ci(r){return new TextDecoder().decode(r)}function Yc(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),d=Math.log(256)/Math.log(a);function l(m){if(m instanceof Uint8Array||(ArrayBuffer.isView(m)?m=new Uint8Array(m.buffer,m.byteOffset,m.byteLength):Array.isArray(m)&&(m=Uint8Array.from(m))),!(m instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(m.length===0)return"";for(var x=0,p=0,S=0,I=m.length;S!==I&&m[S]===0;)S++,x++;for(var _=(I-S)*d+1>>>0,T=new Uint8Array(_);S!==I;){for(var P=m[S],B=0,N=_-1;(P!==0||B<p)&&N!==-1;N--,B++)P+=256*T[N]>>>0,T[N]=P%a>>>0,P=P/a>>>0;if(P!==0)throw new Error("Non-zero carry");p=B,S++}for(var U=_-p;U!==_&&T[U]===0;)U++;for(var C=c.repeat(x);U<_;++U)C+=r.charAt(T[U]);return C}function f(m){if(typeof m!="string")throw new TypeError("Expected String");if(m.length===0)return new Uint8Array;var x=0;if(m[x]!==" "){for(var p=0,S=0;m[x]===c;)p++,x++;for(var I=(m.length-x)*u+1>>>0,_=new Uint8Array(I);m[x];){var T=e[m.charCodeAt(x)];if(T===255)return;for(var P=0,B=I-1;(T!==0||P<S)&&B!==-1;B--,P++)T+=a*_[B]>>>0,_[B]=T%256>>>0,T=T/256>>>0;if(T!==0)throw new Error("Non-zero carry");S=P,x++}if(m[x]!==" "){for(var N=I-S;N!==I&&_[N]===0;)N++;for(var U=new Uint8Array(p+(I-N)),C=p;N!==I;)U[C++]=_[N++];return U}}}function h(m){var x=f(m);if(x)return x;throw new Error(`Non-${t} character`)}return{encode:l,decodeUnsafe:f,decode:h}}var Wc=Yc,Qc=Wc,fi=Qc;var oo=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")}},so=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 li(this,t)}},io=class{decoders;constructor(t){this.decoders=t}or(t){return li(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 li(r,t){return new io({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var ao=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 oo(t,e,n),this.decoder=new so(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Re({name:r,prefix:t,encode:e,decode:n}){return new ao(r,t,e,n)}function te({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=fi(e,r);return Re({prefix:t,name:r,encode:n,decode:s=>Ut(o(s))})}function Jc(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 d=t[r[u]];if(d===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<e|d,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 tu(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 eu(r){let t={};for(let e=0;e<r.length;++e)t[r[e]]=e;return t}function X({name:r,prefix:t,bitsPerChar:e,alphabet:n}){let o=eu(n);return Re({prefix:t,name:r,encode(s){return tu(s,n,e)},decode(s){return Jc(s,o,e,r)}})}var Z=te({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),ru=te({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var uo={};mt(uo,{base32:()=>ee,base32hex:()=>iu,base32hexpad:()=>cu,base32hexpadupper:()=>uu,base32hexupper:()=>au,base32pad:()=>ou,base32padupper:()=>su,base32upper:()=>nu,base32z:()=>fu});var ee=X({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),nu=X({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ou=X({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),su=X({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),iu=X({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),au=X({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),cu=X({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),uu=X({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),fu=X({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var fo={};mt(fo,{base36:()=>cr,base36upper:()=>lu});var cr=te({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),lu=te({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var du=pi,di=128,hu=127,pu=~hu,mu=Math.pow(2,31);function pi(r,t,e){t=t||[],e=e||0;for(var n=e;r>=mu;)t[e++]=r&255|di,r/=128;for(;r&pu;)t[e++]=r&255|di,r>>>=7;return t[e]=r|0,pi.bytes=e-n+1,t}var gu=lo,yu=128,hi=127;function lo(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw lo.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&hi)<<o:(i&hi)*Math.pow(2,o),o+=7}while(i>=yu);return lo.bytes=s-n,e}var bu=Math.pow(2,7),xu=Math.pow(2,14),wu=Math.pow(2,21),Eu=Math.pow(2,28),Su=Math.pow(2,35),_u=Math.pow(2,42),vu=Math.pow(2,49),Au=Math.pow(2,56),Iu=Math.pow(2,63),Bu=function(r){return r<bu?1:r<xu?2:r<wu?3:r<Eu?4:r<Su?5:r<_u?6:r<vu?7:r<Au?8:r<Iu?9:10},Du={encode:du,decode:gu,encodingLength:Bu},Tu=Du,ur=Tu;function fr(r,t=0){return[ur.decode(r,t),ur.decode.bytes]}function Pe(r,t,e=0){return ur.encode(r,t,e),t}function Oe(r){return ur.encodingLength(r)}function he(r,t){let e=t.byteLength,n=Oe(r),o=n+Oe(e),s=new Uint8Array(o+e);return Pe(r,s,0),Pe(e,s,n),s.set(t,o),new ke(r,e,t,s)}function lr(r){let t=Ut(r),[e,n]=fr(t),[o,s]=fr(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new ke(e,o,i,t)}function mi(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&ii(r.bytes,e.bytes)}}var ke=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};function gi(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return Lu(e,ho(r),t??Z.encoder);default:return Ru(e,ho(r),t??ee.encoder)}}var yi=new WeakMap;function ho(r){let t=yi.get(r);if(t==null){let e=new Map;return yi.set(r,e),e}return t}var tt=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!==dr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==Pu)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=he(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&&mi(t.multihash,n.multihash)}toString(t){return gi(this,t)}toJSON(){return{"/":gi(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??bi(n,o,s.bytes))}else if(e[Ou]===!0){let{version:n,multihash:o,code:s}=e,i=lr(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!==dr)throw new Error(`Version 0 CID must use dag-pb (code: ${dr}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=bi(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,dr,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=Ut(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 ke(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,f]=fr(t.subarray(e));return e+=f,l},o=n(),s=dr;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,d=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:d,size:u}}static parse(t,e){let[n,o]=Cu(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 ho(s).set(n,t),s}};function Cu(r,t){switch(r[0]){case"Q":{let e=t??Z;return[Z.prefix,e.decode(`${Z.prefix}${r}`)]}case Z.prefix:{let e=t??Z;return[Z.prefix,e.decode(r)]}case ee.prefix:{let e=t??ee;return[ee.prefix,e.decode(r)]}case cr.prefix:{let e=t??cr;return[cr.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 Lu(r,t,e){let{prefix:n}=e;if(n!==Z.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 Ru(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 dr=112,Pu=18;function bi(r,t,e){let n=Oe(r),o=n+Oe(t),s=new Uint8Array(o+e.byteLength);return Pe(r,s,0),Pe(t,s,n),s.set(e,o),s}var Ou=Symbol.for("@ipld/js-cid/CID");var po={};mt(po,{identity:()=>Bt});var xi=0,ku="identity",wi=Ut;function Nu(r){return he(xi,wi(r))}var Bt={code:xi,name:ku,encode:wi,digest:Nu};function ct(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 gt(r=0){return new Uint8Array(r)}function ft(r=0){return new Uint8Array(r)}function Mt(r,t){t==null&&(t=r.reduce((o,s)=>o+s.length,0));let e=ft(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}var Si=Symbol.for("@achingbrain/uint8arraylist");function Ei(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 Yr(r){return!!r?.[Si]}var Q=class r{bufs;length;[Si]=!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(Yr(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(Yr(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=Ei(this.bufs,t);return e.buf[e.index]}set(t,e){let n=Ei(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(Yr(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 Mt(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:Mt(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,d=e>a&&e<=c;if(u&&d){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(d){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(!Yr(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,d;for(let l=e;l<=c;l+=d){d=0;for(let f=u;f>=0;f--){let h=this.get(l+f);if(n[f]!==h){d=Math.max(1,f-a[h]);break}}if(d===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=ft(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=gt(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=gt(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=gt(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=ft(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=gt(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=gt(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=gt(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=gt(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=gt(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(!ct(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 mo={};mt(mo,{base10:()=>Uu});var Uu=te({prefix:"9",name:"base10",alphabet:"0123456789"});var go={};mt(go,{base16:()=>Mu,base16upper:()=>Ku});var Mu=X({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Ku=X({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var yo={};mt(yo,{base2:()=>qu});var qu=X({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var bo={};mt(bo,{base256emoji:()=>Gu});var _i=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}"),Fu=_i.reduce((r,t,e)=>(r[e]=t,r),[]),zu=_i.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function Hu(r){return r.reduce((t,e)=>(t+=Fu[e],t),"")}function Vu(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=zu[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var Gu=Re({prefix:"\u{1F680}",name:"base256emoji",encode:Hu,decode:Vu});var wo={};mt(wo,{base64:()=>$u,base64pad:()=>Zu,base64url:()=>xo,base64urlpad:()=>Xu});var $u=X({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Zu=X({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),xo=X({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Xu=X({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Eo={};mt(Eo,{base8:()=>ju});var ju=X({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var So={};mt(So,{identity:()=>Yu});var Yu=Re({prefix:"\0",name:"identity",encode:r=>ci(r),decode:r=>ai(r)});var Zh=new TextEncoder,Xh=new TextDecoder;var Ao={};mt(Ao,{sha256:()=>hr,sha512:()=>Ju});function vo({name:r,code:t,encode:e}){return new _o(r,t,e)}var _o=class{name;code;encode;constructor(t,e,n){this.name=t,this.code=e,this.encode=n}digest(t){if(t instanceof Uint8Array){let e=this.encode(t);return e instanceof Uint8Array?he(this.code,e):e.then(n=>he(this.code,n))}else throw Error("Unknown type, must be binary type")}};function Ai(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var hr=vo({name:"sha2-256",code:18,encode:Ai("SHA-256")}),Ju=vo({name:"sha2-512",code:19,encode:Ai("SHA-512")});var pr={...So,...yo,...Eo,...mo,...go,...uo,...fo,...co,...wo,...bo},ip={...Ao,...po};function Bi(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var Ii=Bi("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Io=Bi("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=ft(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),tf={utf8:Ii,"utf-8":Ii,hex:pr.base16,latin1:Io,ascii:Io,binary:Io,...pr},Wr=tf;function H(r,t="utf8"){let e=Wr[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function G(r,t="utf8"){let e=Wr[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var ef=parseInt("11111",2),Bo=parseInt("10000000",2),rf=parseInt("01111111",2),Di={0:mr,1:mr,2:nf,3:af,4:cf,5:sf,6:of,16:mr,22:mr,48:mr};function Do(r,t={offset:0}){let e=r[t.offset]&ef;if(t.offset++,Di[e]!=null)return Di[e](r,t);throw new Error("No decoder for tag "+e)}function gr(r,t){let e=0;if((r[t.offset]&Bo)===Bo){let n=r[t.offset]&rf,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 mr(r,t){gr(r,t);let e=[];for(;!(t.offset>=r.byteLength);){let n=Do(r,t);if(n===null)break;e.push(n)}return e}function nf(r,t){let e=gr(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 of(r,t){let e=gr(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 d=0;for(let l=0;l<c.length;l++)d+=c[l]<<l*7;a+=`.${d}`,c=[]}}return a}function sf(r,t){return t.offset++,null}function af(r,t){let e=gr(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 cf(r,t){let e=gr(r,t),n=r.subarray(t.offset,t.offset+e);return t.offset+=e,n}function uf(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 To(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let t=uf(r.byteLength);return new Q(Uint8Array.from([t.byteLength|Bo]),t)}function Ti(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]),To(t),t)}function Ci(r){let t=Uint8Array.from([0]),e=new Q(t,r);return new Q(Uint8Array.from([3]),To(e),e)}function Qr(r,t=48){let e=new Q;for(let n of r)e.append(n);return new Q(Uint8Array.from([t]),To(e),e)}async function Li(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 ff=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),lf=Uint8Array.from([6,5,43,129,4,0,34]),df=Uint8Array.from([6,5,43,129,4,0,35]),hf={ext:!0,kty:"EC",crv:"P-256"},pf={ext:!0,kty:"EC",crv:"P-384"},mf={ext:!0,kty:"EC",crv:"P-521"},Co=32,Lo=48,Ro=66;function Ri(r){let t=Do(r);return Pi(t)}function Pi(r){let t=r[1][1][0],e=1,n,o;if(t.byteLength===Co*2+1)return n=G(t.subarray(e,e+Co),"base64url"),o=G(t.subarray(e+Co),"base64url"),new Ne({...hf,key_ops:["verify"],x:n,y:o});if(t.byteLength===Lo*2+1)return n=G(t.subarray(e,e+Lo),"base64url"),o=G(t.subarray(e+Lo),"base64url"),new Ne({...pf,key_ops:["verify"],x:n,y:o});if(t.byteLength===Ro*2+1)return n=G(t.subarray(e,e+Ro),"base64url"),o=G(t.subarray(e+Ro),"base64url"),new Ne({...mf,key_ops:["verify"],x:n,y:o});throw new Nt(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function Oi(r){return Qr([Ti(Uint8Array.from([1])),Qr([gf(r.crv)],160),Qr([Ci(new Q(Uint8Array.from([4]),H(r.x??"","base64url"),H(r.y??"","base64url")))],161)]).subarray()}function gf(r){if(r==="P-256")return ff;if(r==="P-384")return lf;if(r==="P-521")return df;throw new Nt(`Invalid curve ${r}`)}var Ne=class{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=Oi(this.jwk)),this._raw}toMultihash(){return Bt.digest(Ue(this))}toCID(){return tt.createV1(114,this.toMultihash())}toString(){return Z.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:ct(this.raw,t.raw)}async verify(t,e,n){return Li(this.jwk,e,t,n)}};var me=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function ge(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function yr(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function j(r,...t){if(!ge(r))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(r.length))throw new Error("Uint8Array expected of length "+t+", got length="+r.length)}function Jr(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");yr(r.outputLen),yr(r.blockLen)}function Ke(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 Ni(r,t){j(r);let e=t.outputLen;if(r.length<e)throw new Error("digestInto() expects output buffer of length at least "+e)}function qt(...r){for(let t=0;t<r.length;t++)r[t].fill(0)}function tn(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Dt(r,t){return r<<32-t|r>>>t}var Ui=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",yf=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function _t(r){if(j(r),Ui)return r.toHex();let t="";for(let e=0;e<r.length;e++)t+=yf[r[e]];return t}var Kt={_0:48,_9:57,A:65,F:70,a:97,f:102};function ki(r){if(r>=Kt._0&&r<=Kt._9)return r-Kt._0;if(r>=Kt.A&&r<=Kt.F)return r-(Kt.A-10);if(r>=Kt.a&&r<=Kt.f)return r-(Kt.a-10)}function ye(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(Ui)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=ki(r.charCodeAt(s)),a=ki(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 Po(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function br(r){return typeof r=="string"&&(r=Po(r)),j(r),r}function lt(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];j(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}var Me=class{};function Oo(r){let t=n=>r().update(br(n)).digest(),e=r();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>r(),t}function xr(r=32){if(me&&typeof me.getRandomValues=="function")return me.getRandomValues(new Uint8Array(r));if(me&&typeof me.randomBytes=="function")return Uint8Array.from(me.randomBytes(r));throw new Error("crypto.getRandomValues must be defined")}function bf(r,t,e,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(t,e,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(e>>o&s),a=Number(e&s),c=n?4:0,u=n?0:4;r.setUint32(t+c,i,n),r.setUint32(t+u,a,n)}function Mi(r,t,e){return r&t^~r&e}function Ki(r,t,e){return r&t^r&e^t&e}var wr=class extends Me{constructor(t,e,n,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(t),this.view=tn(this.buffer)}update(t){Ke(this),t=br(t),j(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=tn(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){Ke(this),Ni(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;e[i++]=128,qt(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let l=i;l<o;l++)e[l]=0;bf(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=tn(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,d=this.get();if(u>d.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<u;l++)a.setUint32(4*l,d[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||(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 en=BigInt(4294967295),qi=BigInt(32);function xf(r,t=!1){return t?{h:Number(r&en),l:Number(r>>qi&en)}:{h:Number(r>>qi&en)|0,l:Number(r&en)|0}}function Fi(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}=xf(r[s],t);[n[s],o[s]]=[i,a]}return[n,o]}var ko=(r,t,e)=>r>>>e,No=(r,t,e)=>r<<32-e|t>>>e,be=(r,t,e)=>r>>>e|t<<32-e,xe=(r,t,e)=>r<<32-e|t>>>e,Er=(r,t,e)=>r<<64-e|t>>>e-32,Sr=(r,t,e)=>r>>>e-32|t<<64-e;function Pt(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var zi=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),Hi=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,Vi=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),Gi=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,$i=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),Zi=(r,t,e,n,o,s)=>t+e+n+o+s+(r/2**32|0)|0;var Ef=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]),re=new Uint32Array(64),Uo=class extends wr{constructor(t=32){super(64,t,8,!1),this.A=Ft[0]|0,this.B=Ft[1]|0,this.C=Ft[2]|0,this.D=Ft[3]|0,this.E=Ft[4]|0,this.F=Ft[5]|0,this.G=Ft[6]|0,this.H=Ft[7]|0}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)re[l]=t.getUint32(e,!1);for(let l=16;l<64;l++){let f=re[l-15],h=re[l-2],m=Dt(f,7)^Dt(f,18)^f>>>3,x=Dt(h,17)^Dt(h,19)^h>>>10;re[l]=x+re[l-7]+m+re[l-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:d}=this;for(let l=0;l<64;l++){let f=Dt(a,6)^Dt(a,11)^Dt(a,25),h=d+f+Mi(a,c,u)+Ef[l]+re[l]|0,x=(Dt(n,2)^Dt(n,13)^Dt(n,22))+Ki(n,o,s)|0;d=u,u=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+x|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,d=d+this.H|0,this.set(n,o,s,i,a,c,u,d)}roundClean(){qt(re)}destroy(){this.set(0,0,0,0,0,0,0,0),qt(this.buffer)}};var Xi=Fi(["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))),Sf=Xi[0],_f=Xi[1],ne=new Uint32Array(80),oe=new Uint32Array(80),Mo=class extends wr{constructor(t=64){super(128,t,16,!1),this.Ah=nt[0]|0,this.Al=nt[1]|0,this.Bh=nt[2]|0,this.Bl=nt[3]|0,this.Ch=nt[4]|0,this.Cl=nt[5]|0,this.Dh=nt[6]|0,this.Dl=nt[7]|0,this.Eh=nt[8]|0,this.El=nt[9]|0,this.Fh=nt[10]|0,this.Fl=nt[11]|0,this.Gh=nt[12]|0,this.Gl=nt[13]|0,this.Hh=nt[14]|0,this.Hl=nt[15]|0}get(){let{Ah:t,Al:e,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:u,El:d,Fh:l,Fl:f,Gh:h,Gl:m,Hh:x,Hl:p}=this;return[t,e,n,o,s,i,a,c,u,d,l,f,h,m,x,p]}set(t,e,n,o,s,i,a,c,u,d,l,f,h,m,x,p){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=d|0,this.Fh=l|0,this.Fl=f|0,this.Gh=h|0,this.Gl=m|0,this.Hh=x|0,this.Hl=p|0}process(t,e){for(let _=0;_<16;_++,e+=4)ne[_]=t.getUint32(e),oe[_]=t.getUint32(e+=4);for(let _=16;_<80;_++){let T=ne[_-15]|0,P=oe[_-15]|0,B=be(T,P,1)^be(T,P,8)^ko(T,P,7),N=xe(T,P,1)^xe(T,P,8)^No(T,P,7),U=ne[_-2]|0,C=oe[_-2]|0,y=be(U,C,19)^Er(U,C,61)^ko(U,C,6),g=xe(U,C,19)^Sr(U,C,61)^No(U,C,6),E=Vi(N,g,oe[_-7],oe[_-16]),v=Gi(E,B,y,ne[_-7],ne[_-16]);ne[_]=v|0,oe[_]=E|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:d,Eh:l,El:f,Fh:h,Fl:m,Gh:x,Gl:p,Hh:S,Hl:I}=this;for(let _=0;_<80;_++){let T=be(l,f,14)^be(l,f,18)^Er(l,f,41),P=xe(l,f,14)^xe(l,f,18)^Sr(l,f,41),B=l&h^~l&x,N=f&m^~f&p,U=$i(I,P,N,_f[_],oe[_]),C=Zi(U,S,T,B,Sf[_],ne[_]),y=U|0,g=be(n,o,28)^Er(n,o,34)^Er(n,o,39),E=xe(n,o,28)^Sr(n,o,34)^Sr(n,o,39),v=n&s^n&a^s&a,L=o&i^o&c^i&c;S=x|0,I=p|0,x=h|0,p=m|0,h=l|0,m=f|0,{h:l,l:f}=Pt(u|0,d|0,C|0,y|0),u=a|0,d=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let R=zi(y,E,L);n=Hi(R,C,g,v),o=R|0}({h:n,l:o}=Pt(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=Pt(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=Pt(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:d}=Pt(this.Dh|0,this.Dl|0,u|0,d|0),{h:l,l:f}=Pt(this.Eh|0,this.El|0,l|0,f|0),{h,l:m}=Pt(this.Fh|0,this.Fl|0,h|0,m|0),{h:x,l:p}=Pt(this.Gh|0,this.Gl|0,x|0,p|0),{h:S,l:I}=Pt(this.Hh|0,this.Hl|0,S|0,I|0),this.set(n,o,s,i,a,c,u,d,l,f,h,m,x,p,S,I)}roundClean(){qt(ne,oe)}destroy(){qt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var ji=Oo(()=>new Uo);var Yi=Oo(()=>new Mo);var Fo=BigInt(0),qo=BigInt(1);function zt(r,t){if(typeof t!="boolean")throw new Error(r+" boolean expected, got "+t)}function _r(r){let t=r.toString(16);return t.length&1?"0"+t:t}function Wi(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?Fo:BigInt("0x"+r)}function qe(r){return Wi(_t(r))}function Ht(r){return j(r),Wi(_t(Uint8Array.from(r).reverse()))}function rn(r,t){return ye(r.toString(16).padStart(t*2,"0"))}function Vt(r,t){return rn(r,t).reverse()}function F(r,t,e){let n;if(typeof t=="string")try{n=ye(t)}catch(s){throw new Error(r+" must be hex string or Uint8Array, cause: "+s)}else if(ge(t))n=Uint8Array.from(t);else throw new Error(r+" must be hex string or Uint8Array");let o=n.length;if(typeof e=="number"&&o!==e)throw new Error(r+" of length "+e+" expected, got "+o);return n}function Qi(r,t){if(r.length!==t.length)return!1;let e=0;for(let n=0;n<r.length;n++)e|=r[n]^t[n];return e===0}var Ko=r=>typeof r=="bigint"&&Fo<=r;function Ji(r,t,e){return Ko(r)&&Ko(t)&&Ko(e)&&t<=r&&r<e}function se(r,t,e,n){if(!Ji(t,e,n))throw new Error("expected valid "+r+": "+e+" <= n < "+n+", got "+t)}function nn(r){let t;for(t=0;r>Fo;r>>=qo,t+=1);return t}var ie=r=>(qo<<BigInt(r))-qo;function ta(r,t,e){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof e!="function")throw new Error("hmacFn must be a function");let n=h=>new Uint8Array(h),o=h=>Uint8Array.of(h),s=n(r),i=n(r),a=0,c=()=>{s.fill(1),i.fill(0),a=0},u=(...h)=>e(i,s,...h),d=(h=n(0))=>{i=u(o(0),h),s=u(),h.length!==0&&(i=u(o(1),h),s=u())},l=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let h=0,m=[];for(;h<t;){s=u();let x=s.slice();m.push(x),h+=s.length}return lt(...m)};return(h,m)=>{c(),d(h);let x;for(;!(x=m(l()));)d();return c(),x}}function ae(r,t,e={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function n(o,s,i){let a=r[o];if(i&&a===void 0)return;let c=typeof a;if(c!==s||a===null)throw new Error(`param "${o}" is invalid: expected ${s}, got ${c}`)}Object.entries(t).forEach(([o,s])=>n(o,s,!1)),Object.entries(e).forEach(([o,s])=>n(o,s,!0))}function Fe(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 ut=BigInt(0),et=BigInt(1),we=BigInt(2),na=BigInt(3),oa=BigInt(4),sa=BigInt(5),vf=BigInt(7),ia=BigInt(8),Af=BigInt(9),aa=BigInt(16);function Y(r,t){let e=r%t;return e>=ut?e:t+e}function $(r,t,e){let n=r;for(;t-- >ut;)n*=n,n%=e;return n}function ea(r,t){if(r===ut)throw new Error("invert: expected non-zero number");if(t<=ut)throw new Error("invert: expected positive modulus, got "+t);let e=Y(r,t),n=t,o=ut,s=et,i=et,a=ut;for(;e!==ut;){let u=n/e,d=n%e,l=o-i*u,f=s-a*u;n=e,e=d,o=i,s=a,i=l,a=f}if(n!==et)throw new Error("invert: does not exist");return Y(o,t)}function zo(r,t,e){if(!r.eql(r.sqr(t),e))throw new Error("Cannot find square root")}function ca(r,t){let e=(r.ORDER+et)/oa,n=r.pow(t,e);return zo(r,n,t),n}function If(r,t){let e=(r.ORDER-sa)/ia,n=r.mul(t,we),o=r.pow(n,e),s=r.mul(t,o),i=r.mul(r.mul(s,we),o),a=r.mul(s,r.sub(i,r.ONE));return zo(r,a,t),a}function Bf(r){let t=yt(r),e=ua(r),n=e(t,t.neg(t.ONE)),o=e(t,n),s=e(t,t.neg(n)),i=(r+vf)/aa;return(a,c)=>{let u=a.pow(c,i),d=a.mul(u,n),l=a.mul(u,o),f=a.mul(u,s),h=a.eql(a.sqr(d),c),m=a.eql(a.sqr(l),c);u=a.cmov(u,d,h),d=a.cmov(f,l,m);let x=a.eql(a.sqr(d),c),p=a.cmov(u,d,x);return zo(a,p,c),p}}function ua(r){if(r<na)throw new Error("sqrt is not defined for small field");let t=r-et,e=0;for(;t%we===ut;)t/=we,e++;let n=we,o=yt(r);for(;ra(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(e===1)return ca;let s=o.pow(n,t),i=(t+et)/we;return function(c,u){if(c.is0(u))return u;if(ra(c,u)!==1)throw new Error("Cannot find square root");let d=e,l=c.mul(c.ONE,s),f=c.pow(u,t),h=c.pow(u,i);for(;!c.eql(f,c.ONE);){if(c.is0(f))return c.ZERO;let m=1,x=c.sqr(f);for(;!c.eql(x,c.ONE);)if(m++,x=c.sqr(x),m===d)throw new Error("Cannot find square root");let p=et<<BigInt(d-m-1),S=c.pow(l,p);d=m,l=c.sqr(S),f=c.mul(f,l),h=c.mul(h,S)}return h}}function Df(r){return r%oa===na?ca:r%ia===sa?If:r%aa===Af?Bf(r):ua(r)}var Gt=(r,t)=>(Y(r,t)&et)===et,Tf=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ho(r){let t={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},e=Tf.reduce((n,o)=>(n[o]="function",n),t);return ae(r,e),r}function Cf(r,t,e){if(e<ut)throw new Error("invalid exponent, negatives unsupported");if(e===ut)return r.ONE;if(e===et)return t;let n=r.ONE,o=t;for(;e>ut;)e&et&&(n=r.mul(n,o)),o=r.sqr(o),e>>=et;return n}function vr(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 ra(r,t){let e=(r.ORDER-et)/we,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 fa(r,t){t!==void 0&&yr(t);let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}function yt(r,t,e=!1,n={}){if(r<=ut)throw new Error("invalid field: expected ORDER > 0, got "+r);let o,s,i=!1,a;if(typeof t=="object"&&t!=null){if(n.sqrt||e)throw new Error("cannot specify opts in two arguments");let f=t;f.BITS&&(o=f.BITS),f.sqrt&&(s=f.sqrt),typeof f.isLE=="boolean"&&(e=f.isLE),typeof f.modOnDecode=="boolean"&&(i=f.modOnDecode),a=f.allowedLengths}else typeof t=="number"&&(o=t),n.sqrt&&(s=n.sqrt);let{nBitLength:c,nByteLength:u}=fa(r,o);if(u>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let d,l=Object.freeze({ORDER:r,isLE:e,BITS:c,BYTES:u,MASK:ie(c),ZERO:ut,ONE:et,allowedLengths:a,create:f=>Y(f,r),isValid:f=>{if(typeof f!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof f);return ut<=f&&f<r},is0:f=>f===ut,isValidNot0:f=>!l.is0(f)&&l.isValid(f),isOdd:f=>(f&et)===et,neg:f=>Y(-f,r),eql:(f,h)=>f===h,sqr:f=>Y(f*f,r),add:(f,h)=>Y(f+h,r),sub:(f,h)=>Y(f-h,r),mul:(f,h)=>Y(f*h,r),pow:(f,h)=>Cf(l,f,h),div:(f,h)=>Y(f*ea(h,r),r),sqrN:f=>f*f,addN:(f,h)=>f+h,subN:(f,h)=>f-h,mulN:(f,h)=>f*h,inv:f=>ea(f,r),sqrt:s||(f=>(d||(d=Df(r)),d(l,f))),toBytes:f=>e?Vt(f,u):rn(f,u),fromBytes:(f,h=!0)=>{if(a){if(!a.includes(f.length)||f.length>u)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+f.length);let x=new Uint8Array(u);x.set(f,e?0:x.length-f.length),f=x}if(f.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+f.length);let m=e?Ht(f):qe(f);if(i&&(m=Y(m,r)),!h&&!l.isValid(m))throw new Error("invalid field element: outside of range 0..ORDER");return m},invertBatch:f=>vr(l,f),cmov:(f,h,m)=>m?h:f});return Object.freeze(l)}function la(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 Vo(r){let t=la(r);return t+Math.ceil(t/2)}function Go(r,t,e=!1){let n=r.length,o=la(t),s=Vo(t);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=e?Ht(r):qe(r),a=Y(i,t-et)+et;return e?Vt(a,o):rn(a,o)}var ze=BigInt(0),Ee=BigInt(1);function Ar(r,t){let e=t.negate();return r?e:t}function $t(r,t){let e=vr(r.Fp,t.map(n=>n.Z));return t.map((n,o)=>r.fromAffine(n.toAffine(e[o])))}function ma(r,t){if(!Number.isSafeInteger(r)||r<=0||r>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+r)}function $o(r,t){ma(r,t);let e=Math.ceil(t/r)+1,n=2**(r-1),o=2**r,s=ie(r),i=BigInt(r);return{windows:e,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function da(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+=Ee);let u=t*n,d=u+Math.abs(a)-1,l=a===0,f=a<0,h=t%2!==0;return{nextN:c,offset:d,isZero:l,isNeg:f,isNegF:h,offsetF:u}}function Lf(r,t){if(!Array.isArray(r))throw new Error("array expected");r.forEach((e,n)=>{if(!(e instanceof t))throw new Error("invalid point at index "+n)})}function Rf(r,t){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((e,n)=>{if(!t.isValid(e))throw new Error("invalid scalar at index "+n)})}var Zo=new WeakMap,ga=new WeakMap;function Xo(r){return ga.get(r)||1}function ha(r){if(r!==ze)throw new Error("invalid wNAF")}var He=class{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>ze;)e&Ee&&(n=n.add(o)),o=o.double(),e>>=Ee;return n}precomputeWindow(t,e){let{windows:n,windowSize:o}=$o(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=$o(t,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:u,isZero:d,isNeg:l,isNegF:f,offsetF:h}=da(n,a,i);n=c,d?s=s.add(Ar(f,e[h])):o=o.add(Ar(l,e[u]))}return ha(n),{p:o,f:s}}wNAFUnsafe(t,e,n,o=this.ZERO){let s=$o(t,this.bits);for(let i=0;i<s.windows&&n!==ze;i++){let{nextN:a,offset:c,isZero:u,isNeg:d}=da(n,i,s);if(n=a,!u){let l=e[c];o=o.add(d?l.negate():l)}}return ha(n),o}getPrecomputes(t,e,n){let o=Zo.get(e);return o||(o=this.precomputeWindow(e,t),t!==1&&(typeof n=="function"&&(o=n(o)),Zo.set(e,o))),o}cached(t,e,n){let o=Xo(t);return this.wNAF(o,this.getPrecomputes(o,t,n),e)}unsafe(t,e,n,o){let s=Xo(t);return s===1?this._unsafeLadder(t,e,o):this.wNAFUnsafe(s,this.getPrecomputes(s,t,n),e,o)}createCache(t,e){ma(e,this.bits),ga.set(t,e),Zo.delete(t)}hasCache(t){return Xo(t)!==1}};function ya(r,t,e,n){let o=t,s=r.ZERO,i=r.ZERO;for(;e>ze||n>ze;)e&Ee&&(s=s.add(o)),n&Ee&&(i=i.add(o)),o=o.double(),e>>=Ee,n>>=Ee;return{p1:s,p2:i}}function Ve(r,t,e,n){Lf(e,r),Rf(n,t);let o=e.length,s=n.length;if(o!==s)throw new Error("arrays of points and scalars must have equal length");let i=r.ZERO,a=nn(BigInt(o)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let u=ie(c),d=new Array(Number(u)+1).fill(i),l=Math.floor((t.BITS-1)/c)*c,f=i;for(let h=l;h>=0;h-=c){d.fill(i);for(let x=0;x<s;x++){let p=n[x],S=Number(p>>BigInt(h)&u);d[S]=d[S].add(e[x])}let m=i;for(let x=d.length-1,p=i;x>0;x--)p=p.add(d[x]),m=m.add(p);if(f=f.add(m),h!==0)for(let x=0;x<c;x++)f=f.double()}return f}function pa(r,t){if(t){if(t.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Ho(t),t}else return yt(r)}function on(r,t,e={}){if(!t||typeof t!="object")throw new Error(`expected valid ${r} CURVE object`);for(let a of["p","n","h"]){let c=t[a];if(!(typeof c=="bigint"&&c>ze))throw new Error(`CURVE.${a} must be positive bigint`)}let n=pa(t.p,e.Fp),o=pa(t.n,e.Fn),i=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let a of i)if(!n.isValid(t[a]))throw new Error(`CURVE.${a} must be valid field element of CURVE.Fp`);return{Fp:n,Fn:o}}var Ot=BigInt(0),J=BigInt(1),jo=BigInt(2),Pf=BigInt(8);function Of(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 kf(r,t={}){let{Fp:e,Fn:n}=on("edwards",r,t),{h:o,n:s}=r;ae(t,{},{uvRatio:"function"});let i=jo<<BigInt(n.BYTES*8)-J,a=x=>e.create(x),c=t.uvRatio||((x,p)=>{try{return{isValid:!0,value:e.sqrt(e.div(x,p))}}catch{return{isValid:!1,value:Ot}}});if(!Of(e,r,r.Gx,r.Gy))throw new Error("bad curve params: generator point");function u(x,p,S=!1){let I=S?J:Ot;return se("coordinate "+x,p,I,i),p}function d(x){if(!(x instanceof h))throw new Error("ExtendedPoint expected")}let l=Fe((x,p)=>{let{X:S,Y:I,Z:_}=x,T=x.is0();p==null&&(p=T?Pf:e.inv(_));let P=a(S*p),B=a(I*p),N=e.mul(_,p);if(T)return{x:Ot,y:J};if(N!==J)throw new Error("invZ was invalid");return{x:P,y:B}}),f=Fe(x=>{let{a:p,d:S}=r;if(x.is0())throw new Error("bad point: ZERO");let{X:I,Y:_,Z:T,T:P}=x,B=a(I*I),N=a(_*_),U=a(T*T),C=a(U*U),y=a(B*p),g=a(U*a(y+N)),E=a(C+a(S*a(B*N)));if(g!==E)throw new Error("bad point: equation left != right (1)");let v=a(I*_),L=a(T*P);if(v!==L)throw new Error("bad point: equation left != right (2)");return!0});class h{constructor(p,S,I,_){this.X=u("x",p),this.Y=u("y",S),this.Z=u("z",I,!0),this.T=u("t",_),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(p){return $t(h,p)}static msm(p,S){return Ve(h,n,p,S)}_setWindowSize(p){this.precompute(p)}static fromAffine(p){if(p instanceof h)throw new Error("extended point not allowed");let{x:S,y:I}=p||{};return u("x",S),u("y",I),new h(S,I,J,a(S*I))}precompute(p=8,S=!0){return m.createCache(this,p),S||this.multiply(jo),this}assertValidity(){f(this)}equals(p){d(p);let{X:S,Y:I,Z:_}=this,{X:T,Y:P,Z:B}=p,N=a(S*B),U=a(T*_),C=a(I*B),y=a(P*_);return N===U&&C===y}is0(){return this.equals(h.ZERO)}negate(){return new h(a(-this.X),this.Y,this.Z,a(-this.T))}double(){let{a:p}=r,{X:S,Y:I,Z:_}=this,T=a(S*S),P=a(I*I),B=a(jo*a(_*_)),N=a(p*T),U=S+I,C=a(a(U*U)-T-P),y=N+P,g=y-B,E=N-P,v=a(C*g),L=a(y*E),R=a(C*E),w=a(g*y);return new h(v,L,w,R)}add(p){d(p);let{a:S,d:I}=r,{X:_,Y:T,Z:P,T:B}=this,{X:N,Y:U,Z:C,T:y}=p,g=a(_*N),E=a(T*U),v=a(B*I*y),L=a(P*C),R=a((_+T)*(N+U)-g-E),w=L-v,b=L+v,A=a(E-S*g),D=a(R*w),O=a(b*A),k=a(R*A),M=a(w*b);return new h(D,O,M,k)}subtract(p){return this.add(p.negate())}multiply(p){let S=p;se("scalar",S,J,s);let{p:I,f:_}=m.cached(this,S,T=>$t(h,T));return $t(h,[I,_])[0]}multiplyUnsafe(p,S=h.ZERO){let I=p;return se("scalar",I,Ot,s),I===Ot?h.ZERO:this.is0()||I===J?this:m.unsafe(this,I,_=>$t(h,_),S)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}isTorsionFree(){return m.unsafe(this,s).is0()}toAffine(p){return l(this,p)}clearCofactor(){return o===J?this:this.multiplyUnsafe(o)}static fromBytes(p,S=!1){return j(p),h.fromHex(p,S)}static fromHex(p,S=!1){let{d:I,a:_}=r,T=e.BYTES;p=F("pointHex",p,T),zt("zip215",S);let P=p.slice(),B=p[T-1];P[T-1]=B&-129;let N=Ht(P),U=S?i:e.ORDER;se("pointHex.y",N,Ot,U);let C=a(N*N),y=a(C-J),g=a(I*C-_),{isValid:E,value:v}=c(y,g);if(!E)throw new Error("Point.fromHex: invalid y coordinate");let L=(v&J)===J,R=(B&128)!==0;if(!S&&v===Ot&&R)throw new Error("Point.fromHex: x=0 and x_0=1");return R!==L&&(v=a(-v)),h.fromAffine({x:v,y:N})}toBytes(){let{x:p,y:S}=this.toAffine(),I=Vt(S,e.BYTES);return I[I.length-1]|=p&J?128:0,I}toRawBytes(){return this.toBytes()}toHex(){return _t(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}h.BASE=new h(r.Gx,r.Gy,J,a(r.Gx*r.Gy)),h.ZERO=new h(Ot,J,J,Ot),h.Fp=e,h.Fn=n;let m=new He(h,n.BYTES*8);return h}var sn=class{constructor(t){this.ep=t}static fromBytes(t){throw new Error("fromBytes must be implemented by subclass")}static fromHex(t){throw new Error("fromHex must be implemented by subclass")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(t){return this.ep.toAffine(t)}toRawBytes(){return this.toBytes()}toHex(){return _t(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(t){return this.assertSame(t),this.init(this.ep.add(t.ep))}subtract(t){return this.assertSame(t),this.init(this.ep.subtract(t.ep))}multiply(t){return this.init(this.ep.multiply(t))}multiplyUnsafe(t){return this.init(this.ep.multiplyUnsafe(t))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(t,e){return this.init(this.ep.precompute(t,e))}};function Nf(r,t,e){if(typeof t!="function")throw new Error('"hash" function param is required');ae(e,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=e,{BASE:o,Fp:s,Fn:i}=r,a=i.ORDER,c=e.randomBytes||xr,u=e.adjustScalarBytes||(g=>g),d=e.domain||((g,E,v)=>{if(zt("phflag",v),E.length||v)throw new Error("Contexts/pre-hash are not supported");return g});function l(g){return i.create(g)}function f(g){return l(Ht(g))}function h(g){let E=s.BYTES;g=F("private key",g,E);let v=F("hashed private key",t(g),2*E),L=u(v.slice(0,E)),R=v.slice(E,2*E),w=f(L);return{head:L,prefix:R,scalar:w}}function m(g){let{head:E,prefix:v,scalar:L}=h(g),R=o.multiply(L),w=R.toBytes();return{head:E,prefix:v,scalar:L,point:R,pointBytes:w}}function x(g){return m(g).pointBytes}function p(g=Uint8Array.of(),...E){let v=lt(...E);return f(t(d(v,F("context",g),!!n)))}function S(g,E,v={}){g=F("message",g),n&&(g=n(g));let{prefix:L,scalar:R,pointBytes:w}=m(E),b=p(v.context,L,g),A=o.multiply(b).toBytes(),D=p(v.context,A,w,g),O=l(b+D*R);se("signature.s",O,Ot,a);let k=s.BYTES,M=lt(A,Vt(O,k));return F("result",M,k*2)}let I={zip215:!0};function _(g,E,v,L=I){let{context:R,zip215:w}=L,b=s.BYTES;g=F("signature",g,2*b),E=F("message",E),v=F("publicKey",v,b),w!==void 0&&zt("zip215",w),n&&(E=n(E));let A=Ht(g.slice(b,2*b)),D,O,k;try{D=r.fromHex(v,w),O=r.fromHex(g.slice(0,b),w),k=o.multiplyUnsafe(A)}catch{return!1}if(!w&&D.isSmallOrder())return!1;let M=p(R,O.toBytes(),D.toBytes(),E);return O.add(D.multiplyUnsafe(M)).subtract(k).clearCofactor().is0()}o.precompute(8);let T=s.BYTES,P={secret:T,public:T,signature:2*T,seed:T};function B(g=c(P.seed)){return g}let N={getExtendedPublicKey:m,randomSecretKey:B,isValidSecretKey:C,isValidPublicKey:y,randomPrivateKey:B,toMontgomery(g){let{y:E}=r.fromBytes(g),v=T===32;if(!v&&T!==57)throw new Error("only defined for 25519 and 448");let L=v?s.div(J+E,J-E):s.div(E-J,E+J);return s.toBytes(L)},toMontgomeryPriv(g){j(g,T);let E=t(g.subarray(0,T));return u(E).subarray(0,T)},precompute(g=8,E=r.BASE){return E.precompute(g,!1)}};function U(g){let E=N.randomSecretKey(g);return{secretKey:E,publicKey:x(E)}}function C(g){try{return!!i.fromBytes(g,!1)}catch{return!1}}function y(g,E){try{return!!r.fromBytes(g,E)}catch{return!1}}return Object.freeze({keygen:U,getPublicKey:x,sign:S,verify:_,utils:N,Point:r,info:{type:"edwards",lengths:P}})}function Uf(r){let t={a:r.a,d:r.d,p:r.Fp.ORDER,n:r.n,h:r.h,Gx:r.Gx,Gy:r.Gy},e=r.Fp,n=yt(t.n,r.nBitLength,!0),o={Fp:e,Fn:n,uvRatio:r.uvRatio},s={randomBytes:r.randomBytes,adjustScalarBytes:r.adjustScalarBytes,domain:r.domain,prehash:r.prehash,mapToCurve:r.mapToCurve};return{CURVE:t,curveOpts:o,hash:r.hash,eddsaOpts:s}}function Mf(r,t){return Object.assign({},t,{ExtendedPoint:t.Point,CURVE:r})}function ba(r){let{CURVE:t,curveOpts:e,hash:n,eddsaOpts:o}=Uf(r),s=kf(t,e),i=Nf(s,n,o);return Mf(r,i)}var Kf=BigInt(0),Zt=BigInt(1),xa=BigInt(2),p0=BigInt(3),qf=BigInt(5),Ff=BigInt(8),Ir={p:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Ff,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function zf(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),s=Ir.p,a=r*r%s*r%s,c=$(a,xa,s)*a%s,u=$(c,Zt,s)*r%s,d=$(u,qf,s)*u%s,l=$(d,t,s)*d%s,f=$(l,e,s)*l%s,h=$(f,n,s)*f%s,m=$(h,o,s)*h%s,x=$(m,o,s)*h%s,p=$(x,t,s)*d%s;return{pow_p_5_8:$(p,xa,s)*r%s,b2:a}}function Hf(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var Yo=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Jo(r,t){let e=Ir.p,n=Y(t*t*t,e),o=Y(n*n*t,e),s=zf(r*o).pow_p_5_8,i=Y(r*n*s,e),a=Y(t*i*i,e),c=i,u=Y(i*Yo,e),d=a===r,l=a===Y(-r,e),f=a===Y(-r*Yo,e);return d&&(i=c),(l||f)&&(i=u),Gt(i,e)&&(i=Y(-i,e)),{isValid:d||l,value:i}}var Se=yt(Ir.p,{isLE:!0}),Vf=yt(Ir.n,{isLE:!0}),Gf={...Ir,Fp:Se,hash:Yi,adjustScalarBytes:Hf,uvRatio:Jo},bt=ba(Gf);var Wo=Yo,$f=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Zf=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),Xf=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),jf=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),wa=r=>Jo(Zt,r),Yf=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Qo=r=>bt.CURVE.Fp.create(Ht(r)&Yf);function Ea(r){let{d:t}=bt.CURVE,e=bt.CURVE.Fp.ORDER,n=bt.CURVE.Fp.create,o=n(Wo*r*r),s=n((o+Zt)*Xf),i=BigInt(-1),a=n((i-t*o)*n(o+t)),{isValid:c,value:u}=Jo(s,a),d=n(u*r);Gt(d,e)||(d=n(-d)),c||(u=d),c||(i=o);let l=n(i*(o-Zt)*jf-a),f=u*u,h=n((u+u)*a),m=n(l*$f),x=n(Zt-f),p=n(Zt+f);return new bt.Point(n(h*p),n(x*m),n(m*p),n(h*x))}function Wf(r){j(r,64);let t=Qo(r.subarray(0,32)),e=Ea(t),n=Qo(r.subarray(32,64)),o=Ea(n);return new Xt(e.add(o))}var Xt=class r extends sn{constructor(t){super(t)}static fromAffine(t){return new r(bt.Point.fromAffine(t))}assertSame(t){if(!(t instanceof r))throw new Error("RistrettoPoint expected")}init(t){return new r(t)}static hashToCurve(t){return Wf(F("ristrettoHash",t,64))}static fromBytes(t){j(t,32);let{a:e,d:n}=bt.CURVE,o=Se.ORDER,s=Se.create,i=Qo(t);if(!Qi(Vt(i,32),t)||Gt(i,o))throw new Error("invalid ristretto255 encoding 1");let a=s(i*i),c=s(Zt+e*a),u=s(Zt-e*a),d=s(c*c),l=s(u*u),f=s(e*n*d-l),{isValid:h,value:m}=wa(s(f*l)),x=s(m*u),p=s(m*x*f),S=s((i+i)*x);Gt(S,o)&&(S=s(-S));let I=s(c*p),_=s(S*I);if(!h||Gt(_,o)||I===Kf)throw new Error("invalid ristretto255 encoding 2");return new r(new bt.Point(S,I,Zt,_))}static fromHex(t){return r.fromBytes(F("ristrettoHex",t,32))}static msm(t,e){return Ve(r,bt.Point.Fn,t,e)}toBytes(){let{X:t,Y:e,Z:n,T:o}=this.ep,s=Se.ORDER,i=Se.create,a=i(i(n+e)*i(n-e)),c=i(t*e),u=i(c*c),{value:d}=wa(i(a*u)),l=i(d*a),f=i(d*c),h=i(l*f*o),m;if(Gt(o*h,s)){let p=i(e*Wo),S=i(t*Wo);t=p,e=S,m=i(l*Zf)}else m=f;Gt(t*h,s)&&(e=i(-e));let x=i((n-e)*m);return Gt(x,s)&&(x=i(-x)),Vt(x,32)}equals(t){this.assertSame(t);let{X:e,Y:n}=this.ep,{X:o,Y:s}=t.ep,i=Se.create,a=i(e*s)===i(n*o),c=i(n*s)===i(e*o);return a||c}is0(){return this.equals(r.ZERO)}};Xt.BASE=new Xt(bt.Point.BASE);Xt.ZERO=new Xt(bt.Point.ZERO);Xt.Fp=Se;Xt.Fn=Vf;var Br=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},an=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var Sa={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new an("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 cn=Sa;var un=32;var ts,Qf=(async()=>{try{return await cn.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function Jf(r,t,e){if(r.buffer instanceof ArrayBuffer){let n=await cn.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await cn.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 tl(r,t,e){return bt.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}async function _a(r,t,e){return ts==null&&(ts=await Qf),ts?Jf(r,t,e):tl(r,t,e)}function fn(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var ln=class{type="Ed25519";raw;constructor(t){this.raw=es(t,un)}toMultihash(){return Bt.digest(Ue(this))}toCID(){return tt.createV1(114,this.toMultihash())}toString(){return Z.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:ct(this.raw,t.raw)}verify(t,e,n){n?.signal?.throwIfAborted();let o=_a(this.raw,e,t);return fn(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function Aa(r){return r=es(r,un),new ln(r)}function es(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new Nt(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}var rl=Math.pow(2,7),nl=Math.pow(2,14),ol=Math.pow(2,21),rs=Math.pow(2,28),ns=Math.pow(2,35),os=Math.pow(2,42),ss=Math.pow(2,49),K=128,st=127;function dt(r){if(r<rl)return 1;if(r<nl)return 2;if(r<ol)return 3;if(r<rs)return 4;if(r<ns)return 5;if(r<os)return 6;if(r<ss)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Ge(r,t,e=0){switch(dt(r)){case 8:t[e++]=r&255|K,r/=128;case 7:t[e++]=r&255|K,r/=128;case 6:t[e++]=r&255|K,r/=128;case 5:t[e++]=r&255|K,r/=128;case 4:t[e++]=r&255|K,r>>>=7;case 3:t[e++]=r&255|K,r>>>=7;case 2:t[e++]=r&255|K,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function sl(r,t,e=0){switch(dt(r)){case 8:t.set(e++,r&255|K),r/=128;case 7:t.set(e++,r&255|K),r/=128;case 6:t.set(e++,r&255|K),r/=128;case 5:t.set(e++,r&255|K),r/=128;case 4:t.set(e++,r&255|K),r>>>=7;case 3:t.set(e++,r&255|K),r>>>=7;case 2:t.set(e++,r&255|K),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function is(r,t){let e=r[t],n=0;if(n+=e&st,e<K||(e=r[t+1],n+=(e&st)<<7,e<K)||(e=r[t+2],n+=(e&st)<<14,e<K)||(e=r[t+3],n+=(e&st)<<21,e<K)||(e=r[t+4],n+=(e&st)*rs,e<K)||(e=r[t+5],n+=(e&st)*ns,e<K)||(e=r[t+6],n+=(e&st)*os,e<K)||(e=r[t+7],n+=(e&st)*ss,e<K))return n;throw new RangeError("Could not decode varint")}function il(r,t){let e=r.get(t),n=0;if(n+=e&st,e<K||(e=r.get(t+1),n+=(e&st)<<7,e<K)||(e=r.get(t+2),n+=(e&st)<<14,e<K)||(e=r.get(t+3),n+=(e&st)<<21,e<K)||(e=r.get(t+4),n+=(e&st)*rs,e<K)||(e=r.get(t+5),n+=(e&st)*ns,e<K)||(e=r.get(t+6),n+=(e&st)*os,e<K)||(e=r.get(t+7),n+=(e&st)*ss,e<K))return n;throw new RangeError("Could not decode varint")}function Ia(r,t,e=0){return t==null&&(t=ft(dt(r))),t instanceof Uint8Array?Ge(r,t,e):sl(r,t,e)}function Dr(r,t=0){return r instanceof Uint8Array?is(r,t):il(r,t)}var as=new Float32Array([-0]),ce=new Uint8Array(as.buffer);function Da(r,t,e){as[0]=r,t[e]=ce[0],t[e+1]=ce[1],t[e+2]=ce[2],t[e+3]=ce[3]}function Ta(r,t){return ce[0]=r[t],ce[1]=r[t+1],ce[2]=r[t+2],ce[3]=r[t+3],as[0]}var cs=new Float64Array([-0]),it=new Uint8Array(cs.buffer);function Ca(r,t,e){cs[0]=r,t[e]=it[0],t[e+1]=it[1],t[e+2]=it[2],t[e+3]=it[3],t[e+4]=it[4],t[e+5]=it[5],t[e+6]=it[6],t[e+7]=it[7]}function La(r,t){return it[0]=r[t],it[1]=r[t+1],it[2]=r[t+2],it[3]=r[t+3],it[4]=r[t+4],it[5]=r[t+5],it[6]=r[t+6],it[7]=r[t+7],cs[0]}var al=BigInt(Number.MAX_SAFE_INTEGER),cl=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 _e;if(t<al&&t>cl)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>Ra&&(o=0n,++n>Ra&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return _e;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):_e}},_e=new xt(0,0);_e.toBigInt=function(){return 0n};_e.zzEncode=_e.zzDecode=function(){return this};_e.length=function(){return 1};var Ra=4294967296n;function Pa(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 Oa(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 us(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 Tt(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function dn(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var fs=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,Tt(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 Tt(this,4);return dn(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Tt(this,4);return dn(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Tt(this,4);let t=Ta(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw Tt(this,4);let t=La(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 Tt(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return Oa(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw Tt(this,t);this.pos+=t}else do if(this.pos>=this.len)throw Tt(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 Tt(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 Tt(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 Tt(this,8);let t=dn(this.buf,this.pos+=4),e=dn(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=is(this.buf,this.pos);return this.pos+=dt(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 ls(r){return new fs(r instanceof Uint8Array?r:r.subarray())}function vt(r,t,e){let n=ls(r);return t.decode(n,void 0,e)}function ds(r){let t=r??8192,e=t>>>1,n,o=t;return function(i){if(i<1||i>e)return ft(i);o+i>t&&(n=ft(t),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var ve=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function hs(){}var ms=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},ul=ds();function fl(r){return globalThis.Buffer!=null?ft(r):ul(r)}var Cr=class{len;head;tail;states;constructor(){this.len=0,this.head=new ve(hs,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new ve(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new gs((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(hn,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(hn,e.length(),e)}uint64Number(t){return this._push(Ge,dt(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(hn,e.length(),e)}sint64Number(t){let e=xt.fromNumber(t).zzEncode();return this._push(hn,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(ps,1,t?1:0)}fixed32(t){return this._push(Tr,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=xt.fromBigInt(t);return this._push(Tr,4,e.lo)._push(Tr,4,e.hi)}fixed64Number(t){let e=xt.fromNumber(t);return this._push(Tr,4,e.lo)._push(Tr,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(Da,4,t)}double(t){return this._push(Ca,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(ps,1,0):this.uint32(e)._push(dl,e,t)}string(t){let e=Pa(t);return e!==0?this.uint32(e)._push(us,e,t):this._push(ps,1,0)}fork(){return this.states=new ms(this),this.head=this.tail=new ve(hs,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 ve(hs,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=fl(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function ps(r,t,e){t[e]=r&255}function ll(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var gs=class extends ve{next;constructor(t,e){super(ll,t,e),this.next=void 0}};function hn(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 Tr(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 dl(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(Cr.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(hl,t,r),this},Cr.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(pl,t,r),this});function hl(r,t,e){t.set(r,e)}function pl(r,t,e){r.length<40?us(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(H(r),e)}function ys(){return new Cr}function At(r,t){let e=ys();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var $e;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})($e||($e={}));function pn(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function Ae(r){function t(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let e=function(s,i){let a=t(s);i.int32(a)},n=function(s){let i=s.int32();return t(i)};return pn("enum",$e.VARINT,e,n)}function It(r,t){return pn("message",$e.LENGTH_DELIMITED,r,t)}var mn=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var wt;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(wt||(wt={}));var bs;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(bs||(bs={}));(function(r){r.codec=()=>Ae(bs)})(wt||(wt={}));var Lr;(function(r){let t;r.codec=()=>(t==null&&(t=It((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),wt.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.Type=wt.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>At(e,r.codec()),r.decode=(e,n)=>vt(e,r.codec(),n)})(Lr||(Lr={}));var xs;(function(r){let t;r.codec=()=>(t==null&&(t=It((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),wt.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.Type=wt.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>At(e,r.codec()),r.decode=(e,n)=>vt(e,r.codec(),n)})(xs||(xs={}));var gn=class extends Me{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,Jr(t);let n=br(e);if(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 o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?t.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=t.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),qt(s)}update(t){return Ke(this),this.iHash.update(t),this}digestInto(t){Ke(this),j(t,this.outputLen),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||(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()}},ws=(r,t,e)=>new gn(r,t).update(e).digest();ws.create=(r,t)=>new gn(r,t);var Na=(r,t)=>(r+(r>=0?t:-t)/Ma)/t;function gl(r,t,e){let[[n,o],[s,i]]=t,a=Na(i*r,e),c=Na(-o*r,e),u=r-a*n-c*s,d=-a*o-c*i,l=u<Yt,f=d<Yt;l&&(u=-u),f&&(d=-d);let h=ie(Math.ceil(nn(e)/2))+Xe;if(u<Yt||u>=h||d<Yt||d>=h)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:l,k1:u,k2neg:f,k2:d}}function Ua(r){r.lowS!==void 0&&zt("lowS",r.lowS),r.prehash!==void 0&&zt("prehash",r.prehash)}var Es=class extends Error{constructor(t=""){super(t)}},jt={Err:Es,_tlv:{encode:(r,t)=>{let{Err:e}=jt;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=_r(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let s=n>127?_r(o.length/2|128):"";return _r(r)+s+o+t},decode(r,t){let{Err:e}=jt,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 d of u)i=i<<8|d;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}=jt;if(r<Yt)throw new t("integer: negative integers are not allowed");let e=_r(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}=jt;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 qe(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=jt,o=F("signature",r),{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:d}=n.decode(2,c);if(d.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}=jt,n=t.encode(2,e.encode(r.r)),o=t.encode(2,e.encode(r.s)),s=n+o;return t.encode(48,s)}},Yt=BigInt(0),Xe=BigInt(1),Ma=BigInt(2),yn=BigInt(3),yl=BigInt(4);function bl(r,t,e){function n(o){let s=r.sqr(o),i=r.mul(s,o);return r.add(r.add(i,r.mul(o,t)),e)}return n}function Ze(r,t){let{BYTES:e}=r,n;if(typeof t=="bigint")n=t;else{let o=F("private key",t);try{n=r.fromBytes(o)}catch{throw new Error(`invalid private key: expected ui8a of size ${e}, got ${typeof t}`)}}if(!r.isValidNot0(n))throw new Error("invalid private key: out of range [1..N-1]");return n}function xl(r,t={}){let{Fp:e,Fn:n}=on("weierstrass",r,t),{h:o,n:s}=r;ae(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:i}=t;if(i&&(!e.is0(r.a)||typeof i.beta!="bigint"||!Array.isArray(i.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');function a(){if(!e.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function c(C,y,g){let{x:E,y:v}=y.toAffine(),L=e.toBytes(E);if(zt("isCompressed",g),g){a();let R=!e.isOdd(v);return lt(Ka(R),L)}else return lt(Uint8Array.of(4),L,e.toBytes(v))}function u(C){j(C);let y=e.BYTES,g=y+1,E=2*y+1,v=C.length,L=C[0],R=C.subarray(1);if(v===g&&(L===2||L===3)){let w=e.fromBytes(R);if(!e.isValid(w))throw new Error("bad point: is not on curve, wrong x");let b=f(w),A;try{A=e.sqrt(b)}catch(k){let M=k instanceof Error?": "+k.message:"";throw new Error("bad point: is not on curve, sqrt error"+M)}a();let D=e.isOdd(A);return(L&1)===1!==D&&(A=e.neg(A)),{x:w,y:A}}else if(v===E&&L===4){let w=e.fromBytes(R.subarray(y*0,y*1)),b=e.fromBytes(R.subarray(y*1,y*2));if(!h(w,b))throw new Error("bad point: is not on curve");return{x:w,y:b}}else throw new Error(`bad point: got length ${v}, expected compressed=${g} or uncompressed=${E}`)}let d=t.toBytes||c,l=t.fromBytes||u,f=bl(e,r.a,r.b);function h(C,y){let g=e.sqr(y),E=f(C);return e.eql(g,E)}if(!h(r.Gx,r.Gy))throw new Error("bad curve params: generator point");let m=e.mul(e.pow(r.a,yn),yl),x=e.mul(e.sqr(r.b),BigInt(27));if(e.is0(e.add(m,x)))throw new Error("bad curve params: a or b");function p(C,y,g=!1){if(!e.isValid(y)||g&&e.is0(y))throw new Error(`bad point coordinate ${C}`);return y}function S(C){if(!(C instanceof B))throw new Error("ProjectivePoint expected")}function I(C){if(!i||!i.basises)throw new Error("no endo");return gl(C,i.basises,n.ORDER)}let _=Fe((C,y)=>{let{X:g,Y:E,Z:v}=C;if(e.eql(v,e.ONE))return{x:g,y:E};let L=C.is0();y==null&&(y=L?e.ONE:e.inv(v));let R=e.mul(g,y),w=e.mul(E,y),b=e.mul(v,y);if(L)return{x:e.ZERO,y:e.ZERO};if(!e.eql(b,e.ONE))throw new Error("invZ was invalid");return{x:R,y:w}}),T=Fe(C=>{if(C.is0()){if(t.allowInfinityPoint&&!e.is0(C.Y))return;throw new Error("bad point: ZERO")}let{x:y,y:g}=C.toAffine();if(!e.isValid(y)||!e.isValid(g))throw new Error("bad point: x or y not field elements");if(!h(y,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 P(C,y,g,E,v){return g=new B(e.mul(g.X,C),g.Y,g.Z),y=Ar(E,y),g=Ar(v,g),y.add(g)}class B{constructor(y,g,E){this.X=p("x",y),this.Y=p("y",g,!0),this.Z=p("z",E),Object.freeze(this)}static fromAffine(y){let{x:g,y:E}=y||{};if(!y||!e.isValid(g)||!e.isValid(E))throw new Error("invalid affine point");if(y instanceof B)throw new Error("projective point not allowed");return e.is0(g)&&e.is0(E)?B.ZERO:new B(g,E,e.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}static normalizeZ(y){return $t(B,y)}static fromBytes(y){return j(y),B.fromHex(y)}static fromHex(y){let g=B.fromAffine(l(F("pointHex",y)));return g.assertValidity(),g}static fromPrivateKey(y){return B.BASE.multiply(Ze(n,y))}static msm(y,g){return Ve(B,n,y,g)}_setWindowSize(y){this.precompute(y)}precompute(y=8,g=!0){return U.createCache(this,y),g||this.multiply(yn),this}assertValidity(){T(this)}hasEvenY(){let{y}=this.toAffine();if(!e.isOdd)throw new Error("Field doesn't support isOdd");return!e.isOdd(y)}equals(y){S(y);let{X:g,Y:E,Z:v}=this,{X:L,Y:R,Z:w}=y,b=e.eql(e.mul(g,w),e.mul(L,v)),A=e.eql(e.mul(E,w),e.mul(R,v));return b&&A}negate(){return new B(this.X,e.neg(this.Y),this.Z)}double(){let{a:y,b:g}=r,E=e.mul(g,yn),{X:v,Y:L,Z:R}=this,w=e.ZERO,b=e.ZERO,A=e.ZERO,D=e.mul(v,v),O=e.mul(L,L),k=e.mul(R,R),M=e.mul(v,L);return M=e.add(M,M),A=e.mul(v,R),A=e.add(A,A),w=e.mul(y,A),b=e.mul(E,k),b=e.add(w,b),w=e.sub(O,b),b=e.add(O,b),b=e.mul(w,b),w=e.mul(M,w),A=e.mul(E,A),k=e.mul(y,k),M=e.sub(D,k),M=e.mul(y,M),M=e.add(M,A),A=e.add(D,D),D=e.add(A,D),D=e.add(D,k),D=e.mul(D,M),b=e.add(b,D),k=e.mul(L,R),k=e.add(k,k),D=e.mul(k,M),w=e.sub(w,D),A=e.mul(k,O),A=e.add(A,A),A=e.add(A,A),new B(w,b,A)}add(y){S(y);let{X:g,Y:E,Z:v}=this,{X:L,Y:R,Z:w}=y,b=e.ZERO,A=e.ZERO,D=e.ZERO,O=r.a,k=e.mul(r.b,yn),M=e.mul(g,L),V=e.mul(E,R),z=e.mul(v,w),ht=e.add(g,E),q=e.add(L,R);ht=e.mul(ht,q),q=e.add(M,V),ht=e.sub(ht,q),q=e.add(g,v);let W=e.add(L,w);return q=e.mul(q,W),W=e.add(M,z),q=e.sub(q,W),W=e.add(E,v),b=e.add(R,w),W=e.mul(W,b),b=e.add(V,z),W=e.sub(W,b),D=e.mul(O,q),b=e.mul(k,z),D=e.add(b,D),b=e.sub(V,D),D=e.add(V,D),A=e.mul(b,D),V=e.add(M,M),V=e.add(V,M),z=e.mul(O,z),q=e.mul(k,q),V=e.add(V,z),z=e.sub(M,z),z=e.mul(O,z),q=e.add(q,z),M=e.mul(V,q),A=e.add(A,M),M=e.mul(W,q),b=e.mul(ht,b),b=e.sub(b,M),M=e.mul(ht,V),D=e.mul(W,D),D=e.add(D,M),new B(b,A,D)}subtract(y){return this.add(y.negate())}is0(){return this.equals(B.ZERO)}multiply(y){let{endo:g}=t;if(!n.isValidNot0(y))throw new Error("invalid scalar: out of range");let E,v,L=R=>U.cached(this,R,w=>$t(B,w));if(g){let{k1neg:R,k1:w,k2neg:b,k2:A}=I(y),{p:D,f:O}=L(w),{p:k,f:M}=L(A);v=O.add(M),E=P(g.beta,D,k,R,b)}else{let{p:R,f:w}=L(y);E=R,v=w}return $t(B,[E,v])[0]}multiplyUnsafe(y){let{endo:g}=t,E=this;if(!n.isValid(y))throw new Error("invalid scalar: out of range");if(y===Yt||E.is0())return B.ZERO;if(y===Xe)return E;if(U.hasCache(this))return this.multiply(y);if(g){let{k1neg:v,k1:L,k2neg:R,k2:w}=I(y),{p1:b,p2:A}=ya(B,E,L,w);return P(g.beta,b,A,v,R)}else return U.unsafe(E,y)}multiplyAndAddUnsafe(y,g,E){let v=this.multiplyUnsafe(g).add(y.multiplyUnsafe(E));return v.is0()?void 0:v}toAffine(y){return _(this,y)}isTorsionFree(){let{isTorsionFree:y}=t;return o===Xe?!0:y?y(B,this):U.unsafe(this,s).is0()}clearCofactor(){let{clearCofactor:y}=t;return o===Xe?this:y?y(B,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(y=!0){return zt("isCompressed",y),this.assertValidity(),d(B,this,y)}toRawBytes(y=!0){return this.toBytes(y)}toHex(y=!0){return _t(this.toBytes(y))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}B.BASE=new B(r.Gx,r.Gy,e.ONE),B.ZERO=new B(e.ZERO,e.ONE,e.ZERO),B.Fp=e,B.Fn=n;let N=n.BITS,U=new He(B,t.endo?Math.ceil(N/2):N);return B}function Ka(r){return Uint8Array.of(r?2:3)}function wl(r,t,e={}){Jr(t),ae(e,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let n=e.randomBytes||xr,o=e.hmac||((w,...b)=>ws(t,w,lt(...b))),{Fp:s,Fn:i}=r,{ORDER:a,BITS:c}=i,u=Vo(a),d={secret:i.BYTES,public:1+s.BYTES,publicUncompressed:1+2*s.BYTES,signature:2*i.BYTES,seed:u};function l(w){let b=a>>Xe;return w>b}function f(w){return l(w)?i.neg(w):w}function h(w,b){if(!i.isValidNot0(b))throw new Error(`invalid signature ${w}: out of range 1..CURVE.n`)}class m{constructor(b,A,D){h("r",b),h("s",A),this.r=b,this.s=A,D!=null&&(this.recovery=D),Object.freeze(this)}static fromBytes(b,A="compact"){if(A==="compact"){let D=i.BYTES;j(b,D*2);let O=b.subarray(0,D),k=b.subarray(D,D*2);return new m(i.fromBytes(O),i.fromBytes(k))}if(A==="der"){j(b);let{r:D,s:O}=jt.toSig(b);return new m(D,O)}throw new Error("invalid format")}static fromHex(b,A){return this.fromBytes(ye(b),A)}addRecoveryBit(b){return new m(this.r,this.s,b)}recoverPublicKey(b){let A=s.ORDER,{r:D,s:O,recovery:k}=this;if(k==null||![0,1,2,3].includes(k))throw new Error("recovery id invalid");if(a*Ma<A&&k>1)throw new Error("recovery id is ambiguous for h>1 curve");let V=k===2||k===3?D+a:D;if(!s.isValid(V))throw new Error("recovery id 2 or 3 invalid");let z=s.toBytes(V),ht=r.fromHex(lt(Ka((k&1)===0),z)),q=i.inv(V),W=N(F("msgHash",b)),pt=i.create(-W*q),Jt=i.create(O*q),le=r.BASE.multiplyUnsafe(pt).add(ht.multiplyUnsafe(Jt));if(le.is0())throw new Error("point at infinify");return le.assertValidity(),le}hasHighS(){return l(this.s)}normalizeS(){return this.hasHighS()?new m(this.r,i.neg(this.s),this.recovery):this}toBytes(b="compact"){if(b==="compact")return lt(i.toBytes(this.r),i.toBytes(this.s));if(b==="der")return ye(jt.hexFromSig(this));throw new Error("invalid format")}toHex(b){return _t(this.toBytes(b))}assertValidity(){}static fromCompact(b){return m.fromBytes(F("sig",b),"compact")}static fromDER(b){return m.fromBytes(F("sig",b),"der")}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return _t(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return _t(this.toBytes("compact"))}}function x(w){try{return!!Ze(i,w)}catch{return!1}}function p(w,b){try{let A=w.length;return b===!0&&A!==d.public||b===!1&&A!==d.publicUncompressed?!1:!!r.fromBytes(w)}catch{return!1}}function S(w=n(u)){return Go(w,a)}let I={isValidSecretKey:x,isValidPublicKey:p,randomSecretKey:S,isValidPrivateKey:x,randomPrivateKey:S,normPrivateKeyToScalar:w=>Ze(i,w),precompute(w=8,b=r.BASE){return b.precompute(w,!1)}};function _(w,b=!0){return r.BASE.multiply(Ze(i,w)).toBytes(b)}function T(w){if(typeof w=="bigint")return!1;if(w instanceof r)return!0;if(i.allowedLengths||d.secret===d.public)return;let b=F("key",w).length;return b===d.public||b===d.publicUncompressed}function P(w,b,A=!0){if(T(w)===!0)throw new Error("first arg must be private key");if(T(b)===!1)throw new Error("second arg must be public key");let D=Ze(i,w);return r.fromHex(b).multiply(D).toBytes(A)}let B=e.bits2int||function(w){if(w.length>8192)throw new Error("input is too large");let b=qe(w),A=w.length*8-c;return A>0?b>>BigInt(A):b},N=e.bits2int_modN||function(w){return i.create(B(w))},U=ie(c);function C(w){return se("num < 2^"+c,w,Yt,U),i.toBytes(w)}function y(w,b,A=g){if(["recovered","canonical"].some(pt=>pt in A))throw new Error("sign() legacy options not supported");let{lowS:D,prehash:O,extraEntropy:k}=A;D==null&&(D=!0),w=F("msgHash",w),Ua(A),O&&(w=F("prehashed msgHash",t(w)));let M=N(w),V=Ze(i,b),z=[C(V),C(M)];if(k!=null&&k!==!1){let pt=k===!0?n(d.secret):k;z.push(F("extraEntropy",pt))}let ht=lt(...z),q=M;function W(pt){let Jt=B(pt);if(!i.isValidNot0(Jt))return;let le=i.inv(Jt),sr=r.BASE.multiply(Jt).toAffine(),de=i.create(sr.x);if(de===Yt)return;let ir=i.create(le*i.create(q+de*V));if(ir===Yt)return;let ti=(sr.x===de?0:2)|Number(sr.y&Xe),ei=ir;return D&&l(ir)&&(ei=f(ir),ti^=1),new m(de,ei,ti)}return{seed:ht,k2sig:W}}let g={lowS:e.lowS,prehash:!1},E={lowS:e.lowS,prehash:!1};function v(w,b,A=g){let{seed:D,k2sig:O}=y(w,b,A);return ta(t.outputLen,i.BYTES,o)(D,O)}r.BASE.precompute(8);function L(w,b,A,D=E){let O=w;b=F("msgHash",b),A=F("publicKey",A),Ua(D);let{lowS:k,prehash:M,format:V}=D;if("strict"in D)throw new Error("options.strict was renamed to lowS");let z,ht;if(V===void 0){let q=typeof O=="string"||ge(O),W=!q&&O!==null&&typeof O=="object"&&typeof O.r=="bigint"&&typeof O.s=="bigint";if(!q&&!W)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(W)z=new m(O.r,O.s);else if(q){try{z=m.fromDER(O)}catch(pt){if(!(pt instanceof jt.Err))throw pt}if(!z)try{z=m.fromCompact(O)}catch{return!1}}}else if(V==="compact"||V==="der"){if(typeof O!="string"&&!ge(O))throw new Error('"der" / "compact" format expects Uint8Array signature');z=m.fromBytes(F("sig",O),V)}else if(V==="js"){if(!(O instanceof m))throw new Error('"js" format expects Signature instance');z=O}else throw new Error('format must be "compact", "der" or "js"');if(!z)return!1;try{if(ht=r.fromHex(A),k&&z.hasHighS())return!1;M&&(b=t(b));let{r:q,s:W}=z,pt=N(b),Jt=i.inv(W),le=i.create(pt*Jt),sr=i.create(q*Jt),de=r.BASE.multiplyUnsafe(le).add(ht.multiplyUnsafe(sr));return de.is0()?!1:i.create(de.x)===q}catch{return!1}}function R(w){let b=I.randomSecretKey(w);return{secretKey:b,publicKey:_(b)}}return Object.freeze({keygen:R,getPublicKey:_,sign:v,verify:L,getSharedSecret:P,utils:I,Point:r,Signature:m,info:{type:"weierstrass",lengths:d,publicKeyHasPrefix:!0}})}function El(r){let t={a:r.a,b:r.b,p:r.Fp.ORDER,n:r.n,h:r.h,Gx:r.Gx,Gy:r.Gy},e=r.Fp,n=r.allowedPrivateKeyLengths?Array.from(new Set(r.allowedPrivateKeyLengths.map(i=>Math.ceil(i/2)))):void 0,o=yt(t.n,{BITS:r.nBitLength,allowedLengths:n,modOnDecode:r.wrapPrivateKey}),s={Fp:e,Fn:o,allowInfinityPoint:r.allowInfinityPoint,endo:r.endo,isTorsionFree:r.isTorsionFree,clearCofactor:r.clearCofactor,fromBytes:r.fromBytes,toBytes:r.toBytes};return{CURVE:t,curveOpts:s}}function Sl(r){let{CURVE:t,curveOpts:e}=El(r),n={hmac:r.hmac,randomBytes:r.randomBytes,lowS:r.lowS,bits2int:r.bits2int,bits2int_modN:r.bits2int_modN};return{CURVE:t,curveOpts:e,hash:r.hash,ecdsaOpts:n}}function _l(r,t){return Object.assign({},t,{ProjectivePoint:t.Point,CURVE:r})}function qa(r){let{CURVE:t,curveOpts:e,hash:n,ecdsaOpts:o}=Sl(r),s=xl(t,e),i=wl(s,n,o);return _l(r,i)}function Fa(r,t){let e=n=>qa({...r,hash:n});return{...e(t),create:e}}var _s={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},vl={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var za=BigInt(2);function Al(r){let t=_s.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,d=u*u*r%t,l=$(d,e,t)*d%t,f=$(l,e,t)*d%t,h=$(f,za,t)*u%t,m=$(h,o,t)*h%t,x=$(m,s,t)*m%t,p=$(x,a,t)*x%t,S=$(p,c,t)*p%t,I=$(S,a,t)*x%t,_=$(I,e,t)*d%t,T=$(_,i,t)*m%t,P=$(T,n,t)*u%t,B=$(P,za,t);if(!Ss.eql(Ss.sqr(B),r))throw new Error("Cannot find square root");return B}var Ss=yt(_s.p,void 0,void 0,{sqrt:Al}),je=Fa({..._s,Fp:Ss,lowS:!0,endo:vl},ji);function Ha(r,t,e,n){let o=hr.digest(e instanceof Uint8Array?e:e.subarray());if(fn(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),je.verify(t,s,r))).catch(s=>{throw s.name==="AbortError"?s:new Br(String(s))});try{return n?.signal?.throwIfAborted(),je.verify(t,o.digest,r)}catch(s){throw new Br(String(s))}}var bn=class{type="secp256k1";raw;_key;constructor(t){this._key=Ga(t),this.raw=Va(this._key)}toMultihash(){return Bt.digest(Ue(this))}toCID(){return tt.createV1(114,this.toMultihash())}toString(){return Z.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:ct(this.raw,t.raw)}verify(t,e,n){return Ha(this._key,e,t,n)}};function $a(r){return new bn(r)}function Va(r){return je.ProjectivePoint.fromHex(r).toRawBytes(!0)}function Ga(r){try{return je.ProjectivePoint.fromHex(r),r}catch(t){throw new Vr(String(t))}}function Za(r){let{Type:t,Data:e}=Lr.decode(r.digest),n=e??new Uint8Array;switch(t){case wt.Ed25519:return Aa(n);case wt.secp256k1:return $a(n);case wt.ECDSA:return Ri(n);default:throw new ar}}function Ue(r){return Lr.encode({Type:wt[r.type],Data:r.raw})}var Xa=Symbol.for("nodejs.util.inspect.custom"),Il=114,Rr=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()})`}[no]=!0;toString(){return this.string==null&&(this.string=Z.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return tt.createV1(Il,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return ct(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return ct(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[Xa](){return`PeerId(${this.toString()})`}},xn=class extends Rr{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},wn=class extends Rr{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},En=class extends Rr{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},Bl=2336,Sn=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=Bt.digest(H(this.url))}[Xa](){return`PeerId(${this.url})`}[no]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return tt.createV1(Bl,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=G(t)),t.toString()===this.toString())}};function ja(r){if(Tl(r))return new xn({multihash:r});if(Dl(r))try{let t=Za(r);if(t.type==="Ed25519")return new wn({multihash:r,publicKey:t});if(t.type==="secp256k1")return new En({multihash:r,publicKey:t})}catch{let e=G(r.digest);return new Sn(new URL(e))}throw new Gr("Supplied PeerID Multihash is invalid")}function Dl(r){return r.code===Bt.code}function Tl(r){return r.code===hr.code}function vs(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 _n(r){let t=lr(Z.decode(`z${r}`));return ja(t)}var vn=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 vs(this.set.entries(),t=>{let e=_n(t[0]);return[e,e]})}forEach(t){this.set.forEach(e=>{let n=_n(e);t(n,n,this)})}has(t){return this.set.has(t.toString())}values(){return vs(this.set.values(),t=>_n(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 As(){return new vn}var Is={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Ya={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Wa=new globalThis.TextEncoder;function Cl(r,t){let e=Is[t],n=Ya[t];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(t,n*e);return n}function Ll(r,t,e){if(e.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Is[t],o=Ya[t],s=r;for(;s.length>0;){let i=Wa.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 Bs(r,{size:t=32,utf8Buffer:e}={}){if(!Is[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 Ll(r,t,e);r=Wa.encode(r)}return Cl(r,t)}var Pr={hash:r=>Number(Bs(r,{size:32})),hashV:(r,t)=>Rl(Pr.hash(r,t))};function Rl(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),H(t,"base16")}var Ds=64,Ct=class{fp;h;seed;constructor(t,e,n,o=2){if(o>Ds)throw new TypeError("Invalid Fingerprint Size");let s=e.hashV(t,n),i=gt(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?ct(this.fp,t.fp):!1}};function Ie(r,t){return Math.floor(Math.random()*(t-r))+r}var Be=class{contents;constructor(t){this.contents=new Array(t).fill(null)}has(t){if(!(t instanceof Ct))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof Ct))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 Ct))throw new TypeError("Invalid Fingerprint");let e=Ie(0,this.contents.length-1),n=this.contents[e];return this.contents[e]=t,n}remove(t){if(!(t instanceof Ct))throw new TypeError("Invalid Fingerprint");let e=this.contents.findIndex(n=>t.equals(n));return e>-1?(this.contents[e]=null,!0):!1}};var Pl=500,Or=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??Pr,this.seed=t.seed??Ie(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=H(t));let e=new Ct(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 Be(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new Be(this.bucketSize)),this.buckets[n].add(e)||this.buckets[o].add(e))return this.count++,!0;let s=[n,o],i=s[Ie(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new Be(this.bucketSize));for(let a=0;a<Pl;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 Be(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(t){typeof t=="string"&&(t=H(t));let e=new Ct(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 Ct(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}},Ol={1:.5,2:.84,4:.95,8:.98};function kl(r=.001){return r>.002?2:r>1e-5?4:8}function Qa(r,t=.001){let e=kl(t),n=Ol[e],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),Ds);return{filterSize:o,bucketSize:e,fingerprintSize:s}}var An=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??Pr,this.seed=t.seed??Ie(0,Math.pow(2,10)),this.filterSeries=[new Or({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 Or({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 Ts(r,t=.001,e){return new An({...Qa(r,t),...e??{}})}var In=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 d=this.readAtomically(()=>{let l=this.readChar();if(l===void 0)return;let f=Number.parseInt(l,t);if(!Number.isNaN(f))return f});if(d===void 0)break;if(s*=t,s+=d,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 Ja=45,Nl=15,Ye=new In;function Bn(r){if(!(r.length>Nl))return Ye.new(r).parseWith(()=>Ye.readIPv4Addr())}function Dn(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Ja))return Ye.new(r).parseWith(()=>Ye.readIPv6Addr())}function We(r,t=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>Ja)return;let e=Ye.new(r).parseWith(()=>Ye.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 tc(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 ec(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 Cs(r){switch(r.length){case De:return r.join(".");case Te:{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 rc(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 nc(r){let t="0x";for(let e of r)t+=(e>>4).toString(16)+(e&15).toString(16);return t}var De=4,Te=16,xy=parseInt("0xFFFF",16),Ul=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function kr(r,t){t.length===Te&&r.length===De&&tc(t,0,11)&&(t=t.slice(12)),t.length===De&&r.length===Te&&ec(r,Ul,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 oc(r,t){if(typeof t=="string"&&(t=We(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 Ls(r){let[t,e]=r.split("/");if(!t||!e)throw new Error("Failed to parse given CIDR: "+r);let n=De,o=Bn(t);if(o==null&&(n=Te,o=Dn(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=Rs(s,8*n);return{network:kr(o,i),mask:i}}function Rs(r,t){if(t!==8*De&&t!==8*Te)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 Qe=class{constructor(t,e){if(e==null)({network:this.network,mask:this.mask}=Ls(t));else{let n=We(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=We(e);if(s==null)throw new Error("Failed to parse mask");this.mask=s}else this.mask=Rs(o,8*n.length);this.network=kr(n,this.mask)}}contains(t){return oc({network:this.network,mask:this.mask},t)}toString(){let t=rc(this.mask),e=t!==-1?String(t):nc(this.mask);return Cs(this.network)+"/"+e}};function sc(r,t){return new Qe(r).contains(t)}var ot=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Wt=class extends Error{static name="ValidationError";name="ValidationError"},Nr=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Tn=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function Je(r){return!!Bn(r)}function Cn(r){return!!Dn(r)}function Os(r){return t=>G(t,r)}function ks(r){return t=>H(t,r)}function tr(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Ce(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(t)}function ic(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=Ce(n);return Mt([e,o],e.length+o.length)}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!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let e=ee.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=Ce(n);return Mt([e,o],e.length+o.length)}function Ns(r){let t=r.subarray(0,r.length-2),e=r.subarray(r.length-2),n=G(t,"base32"),o=tr(e);return`${n}:${o}`}var Us=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},cc=function(r){let t=0;r=r.toString().trim();let e=r.split(":",8),n;for(n=0;n<e.length;n++){let s=Je(e[n]),i;s&&(i=Us(e[n]),e[n]=G(i.subarray(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,G(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},uc=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(".")},fc=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 lc(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 Ps=Object.values(pr).map(r=>r.decoder),Ml=function(){let r=Ps[0].or(Ps[1]);return Ps.slice(2).forEach(t=>r=r.or(t)),r}();function dc(r){return Ml.decode(r)}function hc(r){return t=>r.encoder.encode(t)}function Kl(r){if(parseInt(r).toString()!==r)throw new Wt("Value must be an integer")}function ql(r){if(r<0)throw new Wt("Value must be a positive integer, or zero")}function Fl(r){return t=>{if(t>r)throw new Wt(`Value must be smaller than or equal to ${r}`)}}function zl(...r){return t=>{for(let e of r)e(t)}}var Ur=zl(Kl,ql,Fl(65535));var rt=-1,Ms=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 Tn(`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)}))}},Et=new Ms,bd=[{code:4,name:"ip4",size:32,valueToBytes:Us,bytesToValue:uc,validate:r=>{if(!Je(r))throw new Wt(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Ce,bytesToValue:tr,validate:Ur},{code:273,name:"udp",size:16,valueToBytes:Ce,bytesToValue:tr,validate:Ur},{code:33,name:"dccp",size:16,valueToBytes:Ce,bytesToValue:tr,validate:Ur},{code:41,name:"ip6",size:128,valueToBytes:cc,bytesToValue:fc,stringToValue:lc,validate:r=>{if(!Cn(r))throw new Wt(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:rt},{code:43,name:"ipcidr",size:8,bytesToValue:Os("base10"),valueToBytes:ks("base10")},{code:53,name:"dns",size:rt,resolvable:!0},{code:54,name:"dns4",size:rt,resolvable:!0},{code:55,name:"dns6",size:rt,resolvable:!0},{code:56,name:"dnsaddr",size:rt,resolvable:!0},{code:132,name:"sctp",size:16,valueToBytes:Ce,bytesToValue:tr,validate:Ur},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:rt,path:!0,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:rt,bytesToValue:Os("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?ks("base58btc")(r):tt.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Ns,valueToBytes:ic},{code:445,name:"onion3",size:296,bytesToValue:Ns,valueToBytes:ac},{code:446,name:"garlic64",size:rt},{code:447,name:"garlic32",size:rt},{code:448,name:"tls"},{code:449,name:"sni",size:rt},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:rt,bytesToValue:hc(xo),valueToBytes:dc},{code:480,name:"http"},{code:481,name:"http-path",size:rt,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:rt}];bd.forEach(r=>{Et.addProtocol(r)});function pc(r){let t=[],e=0;for(;e<r.length;){let n=Dr(r,e),o=Et.getProtocol(n),s=dt(n),i=xd(o,r,e+s),a=0;i>0&&o.size===rt&&(a=dt(i));let c=s+a+i,u={code:n,name:o.name,bytes:r.subarray(e,e+c)};if(i>0){let d=e+s+a,l=r.subarray(d,d+i);u.value=o.bytesToValue?.(l)??G(l)}t.push(u),e+=c}return t}function mc(r){let t=0,e=[];for(let n of r){if(n.bytes==null){let o=Et.getProtocol(n.code),s=dt(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??H(n.value),a=i.byteLength,o.size===rt&&(c=dt(a)));let u=new Uint8Array(s+c+a),d=0;Ge(n.code,u,d),d+=s,i!=null&&(o.size===rt&&(Ge(a,u,d),d+=c),u.set(i,d)),n.bytes=u}e.push(n.bytes),t+=n.bytes.byteLength}return Mt(e,t)}function gc(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=Et.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=Et.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 xd(r,t,e){return r.size==null||r.size===0?0:r.size>0?r.size/8:Dr(t,e)}var wd=Symbol.for("nodejs.util.inspect.custom"),Gs=Symbol.for("@multiformats/multiaddr"),Ed=[53,54,55,56],Vs=class extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}};function Sd(r){if(r==null&&(r="/"),xc(r))return r.getComponents();if(r instanceof Uint8Array)return pc(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),gc(r);if(Array.isArray(r))return r;throw new ot("Must be a string, Uint8Array, Component[], or another Multiaddr")}var On=class r{[Gs]=!0;#t;#e;#r;constructor(t="/",e={}){this.#t=Sd(t),e.validate!==!1&&_d(this)}get bytes(){return this.#r==null&&(this.#r=mc(this.#t)),this.#r}toString(){return this.#e==null&&(this.#e=yc(this.#t)),this.#e}toJSON(){return this.toString()}toOptions(){let t,e,n,o,s="";for(let{code:a,name:c,value:u}of this.#t)a===42&&(s=`%${u??""}`),Ed.includes(a)&&(e="tcp",o=443,n=`${u??""}${s}`,t=a===55?6:4),(a===6||a===273)&&(e=c==="tcp"?"tcp":"udp",o=parseInt(u??"")),(a===4||a===41)&&(e="tcp",n=`${u??""}${s}`,t=a===41?6:4);if(t==null||e==null||n==null||o==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:t,host:n,transport:e,port:o}}getComponents(){return[...this.#t]}protos(){return this.#t.map(({code:t,value:e})=>{let n=Et.getProtocol(t);return{code:t,size:n.size??0,name:n.name,resolvable:!!n.resolvable,path:!!n.path}})}protoCodes(){return this.#t.map(({code:t})=>t)}protoNames(){return this.#t.map(({name:t})=>t)}tuples(){return this.#t.map(({code:t,value:e})=>{if(e==null)return[t];let n=Et.getProtocol(t),o=[t];return e!=null&&o.push(n.valueToBytes?.(e)??H(e)),o})}stringTuples(){return this.#t.map(({code:t,value:e})=>e==null?[t]:[t,e])}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 Nr(`Address ${this.toString()} does not contain subaddress: ${t.toString()}`);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})}getPeerId(){try{let t=[];this.#t.forEach(({code:n,value:o})=>{n===421&&t.push([n,o]),n===290&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?G(Z.decode(`z${n}`),"base58btc"):G(tt.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){for(let t of this.#t)if(Et.getProtocol(t.code).path)return t.value??null;return null}equals(t){return ct(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(s=>s.resolvable);if(e==null)return[this];let n=bc.get(e.name);if(n==null)throw new Vs(`no available resolver for ${e.name}`);return(await n(this,t)).map(s=>Kr(s))}nodeAddress(){let t=this.toOptions();if(t.transport!=="tcp"&&t.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${t.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:t.family,address:t.host,port:t.port}}isThinWaistAddress(){return!(this.#t.length!==2||this.#t[0].code!==4&&this.#t[0].code!==41||this.#t[1].code!==6&&this.#t[1].code!==273)}[wd](){return`Multiaddr(${this.toString()})`}};function _d(r){r.getComponents().forEach(t=>{let e=Et.getProtocol(t.code);t.value!=null&&e.validate?.(t.value)})}var bc=new Map;function xc(r){return!!r?.[Gs]}function Kr(r){return new On(r)}function wc(r){try{for(let{code:t,value:e}of r.getComponents())if(e!=null&&t===41)return sc("2000::/3",e)}catch{}return!1}var Sc=Xc(Ec(),1),vd=["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"],Ad=vd.map(r=>new Sc.Netmask(r));function $s(r){for(let t of Ad)if(t.contains(r))return!0;return!1}function Id(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function Bd(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 $s(o)}function Dd(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function Td(r){let t=r.split(":"),e=t[t.length-1];return $s(e)}function Cd(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 kn(r){if(Je(r))return $s(r);if(Id(r))return Bd(r);if(Dd(r))return Td(r);if(Cn(r))return Cd(r)}function _c(r){try{for(let{code:t}of r.getComponents())if(t!==42)return t===4||t===41}catch{}return!1}function vc(r){try{if(!_c(r))return!1;let[[,t]]=r.stringTuples();return t==null?!1:kn(t)??!1}catch{}return!0}function Rt(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var Nn=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}},er=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new Nn(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 Nn(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 Zs=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function Ac(r={}){return Ld(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 Ld(r,t){t=t??{};let e=t.onEnd,n=new er,o,s,i,a=Rt(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((p,S)=>{s=I=>{s=null,n.push(I);try{p(r(n))}catch(_){S(_)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Rt()})}},u=p=>s!=null?s(p):(n.push(p),o),d=p=>(n=new er,s!=null?s({error:p}):(n.push({error:p}),o)),l=p=>{if(i)return o;if(t?.objectMode!==!0&&p?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:p})},f=p=>i?o:(i=!0,p!=null?d(p):u({done:!0})),h=()=>(n=new er,f(),{done:!0}),m=p=>(f(p),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:m,push:l,end:f,get readableLength(){return n.size},onEmpty:async p=>{let S=p?.signal;if(S?.throwIfAborted(),n.isEmpty())return;let I,_;S!=null&&(I=new Promise((T,P)=>{_=()=>{P(new Zs)},S.addEventListener("abort",_)}));try{await Promise.race([a.promise,I])}finally{_!=null&&S!=null&&S?.removeEventListener("abort",_)}}},e==null)return o;let x=o;return o={[Symbol.asyncIterator](){return this},next(){return x.next()},throw(p){return x.throw(p),e!=null&&(e(p),e=void 0),{done:!0}},return(){return x.return(),e!=null&&(e(),e=void 0),{done:!0}},push:l,end(p){return x.end(p),e!=null&&(e(p),e=void 0),o},get readableLength(){return x.readableLength},onEmpty:p=>x.onEmpty(p)},o}var Un=class extends Error{static name="AbortError";name="AbortError";constructor(t="The operation was aborted",...e){super(t,...e)}};async function Mn(r,t,e,n){let o=new Un(n?.errorMessage);n?.errorCode!=null&&(o.code=n.errorCode);let s=n?.errorEvent??"error";return e?.aborted===!0?Promise.reject(o):new Promise((i,a)=>{function c(){js(e,"abort",l),js(r,t,u),js(r,s,d)}let u=f=>{try{if(n?.filter?.(f)===!1)return}catch(h){c(),a(h);return}c(),i(f)},d=f=>{if(c(),f instanceof Error){a(f);return}a(f.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},l=()=>{c(),a(o)};Xs(e,"abort",l),Xs(r,t,u),Xs(r,s,d)})}function Xs(r,t,e){r!=null&&(Ic(r)?r.addEventListener(t,e):r.addListener(t,e))}function js(r,t,e){r!=null&&(Ic(r)?r.removeEventListener(t,e):r.removeListener(t,e))}function Ic(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}function Fr(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 Kn=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};var qn=class extends Error{type;code;constructor(t,e,n){super(t??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=e??"ABORT_ERR"}};async function Le(r,t,e){if(t==null)return r;if(t.aborted)return r.catch(()=>{}),Promise.reject(new qn(e?.errorMessage,e?.errorCode,e?.errorName));let n,o=new qn(e?.errorMessage,e?.errorCode,e?.errorName);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},t.addEventListener("abort",n)})])}finally{n!=null&&t.removeEventListener("abort",n)}}var Fn=class{deferred;signal;constructor(t){this.signal=t,this.deferred=Rt(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new kt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Rd(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var zn=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=Rd(),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 kt),this.cleanup())}async join(t={}){let e=new Fn(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 Le(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 Hn=class extends $r{concurrency;maxSize;queue;pending;sort;constructor(t={}){super(),this.concurrency=t.concurrency??Number.POSITIVE_INFINITY,this.maxSize=t.maxSize??Number.POSITIVE_INFINITY,this.pending=0,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=Fr(this.emitEmpty.bind(this),1),this.emitIdle=Fr(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let 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 Kn;let n=new zn(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 kt)}),this.clear()}async onEmpty(t){this.size!==0&&await Mn(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await Mn(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await Mn(this,"idle",t?.signal)}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=Ac({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 kt("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()}}};var Vn=class extends Hn{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};function zr(r){let t=new globalThis.AbortController;function e(){t.abort();for(let s of r)s?.removeEventListener!=null&&s.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}function Bc(r,t,e){let n,o,s=!1;function i(){let u={signal:o.signal};if(e?.timeout!=null){let d=zr([o.signal,AbortSignal.timeout(e.timeout)]);u.signal=d}s=!0,Promise.resolve().then(async()=>{await r(u)}).catch(()=>{}).finally(()=>{s=!1,!o.signal.aborted&&(n=setTimeout(i,t))})}let a=Fr(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 Ys=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 Dc(r){let{name:t,metrics:e}=r,n;return e!=null?n=new Ys({name:t,metrics:e}):n=new Map,n}var Ws=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=Rt(),this.haveNext=Rt()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let t=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=Rt(),t}async throw(t){return this.ended=!0,this.error=t,t!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(t)),{done:!0,value:void 0}}async return(){let t={done:!0,value:void 0};return this.ended=!0,this.nextResult=t,this.haveNext.resolve(),t}async push(t,e){await this._push(t,e)}async end(t,e){t!=null?await this.throw(t):await this._push(void 0,e)}async _push(t,e){if(t!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;t!=null?this.nextResult={done:!1,value:t}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=Rt(),await Le(this.readNext.promise,e?.signal,e)}};function Tc(){return new Ws}var Gn=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Cc(r,t){let e=Tc();r.sink(e).catch(async i=>{await e.end(i)}),r.sink=async i=>{for await(let a of i)await e.push(a);await e.end()};let n=r.source;r.source[Symbol.iterator]!=null?n=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(n=r.source[Symbol.asyncIterator]());let o=new Q;return{read:async i=>{if(i?.signal?.throwIfAborted(),i?.bytes==null){let{done:c,value:u}=await Le(n.next(),i?.signal);return c===!0?null:u}for(;o.byteLength<i.bytes;){let{value:c,done:u}=await Le(n.next(),i?.signal);if(u===!0)throw new Gn("unexpected end of input");o.append(c)}let a=o.sublist(0,i.bytes);return o.consume(i.bytes),a},write:async(i,a)=>{a?.signal?.throwIfAborted(),i instanceof Uint8Array?await e.push(i,a):await e.push(i.subarray(),a)},unwrap:()=>{if(o.byteLength>0){let i=r.source;r.source=async function*(){t?.yieldBytes===!1?yield o:yield*o,yield*i}()}return r}}}var $n=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Zn=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Xn=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Lc(r,t={}){let e=Cc(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=dt(t.maxDataLength));let n=t?.lengthDecoder??Dr,o=t?.lengthEncoder??Ia;return{read:async i=>{let a=-1,c=new Q;for(;;){c.append(await e.read({...i,bytes:1}));try{a=n(c)}catch(u){if(u instanceof RangeError)continue;throw u}if(a<0)throw new $n("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new Xn("message length length too long");if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new Zn("message length too long");return e.read({...i,bytes:a})},write:async(i,a)=>{await e.write(new Q(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new Q(...i.flatMap(u=>[o(u.byteLength),u]));await e.write(c,a)},unwrap:()=>e.unwrap()}}function rr(r,t){let e=Lc(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 Qs="libp2p",Js="autonat";var Rc="dial-request",Pc="dial-back",Oc=200n*1024n,kc=4096;var nr;(function(r){let t;r.codec=()=>(t==null&&(t=It((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e={...e},e.dialDataResponse!=null&&(e.dialDataRequest=void 0,e.dialResponse=void 0,e.dialRequest=void 0),e.dialDataRequest!=null&&(e.dialDataResponse=void 0,e.dialResponse=void 0,e.dialRequest=void 0),e.dialResponse!=null&&(e.dialDataResponse=void 0,e.dialDataRequest=void 0,e.dialRequest=void 0),e.dialRequest!=null&&(e.dialDataResponse=void 0,e.dialDataRequest=void 0,e.dialResponse=void 0),e.dialRequest!=null&&(n.uint32(10),jn.codec().encode(e.dialRequest,n)),e.dialResponse!=null&&(n.uint32(18),Qt.codec().encode(e.dialResponse,n)),e.dialDataRequest!=null&&(n.uint32(26),Yn.codec().encode(e.dialDataRequest,n)),e.dialDataResponse!=null&&(n.uint32(34),Qn.codec().encode(e.dialDataResponse,n)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.dialRequest=jn.codec().decode(e,e.uint32(),{limits:o.limits?.dialRequest});break}case 2:{s.dialResponse=Qt.codec().decode(e,e.uint32(),{limits:o.limits?.dialResponse});break}case 3:{s.dialDataRequest=Yn.codec().decode(e,e.uint32(),{limits:o.limits?.dialDataRequest});break}case 4:{s.dialDataResponse=Qn.codec().decode(e,e.uint32(),{limits:o.limits?.dialDataResponse});break}default:{e.skipType(a&7);break}}}return s.dialDataResponse!=null&&(delete s.dialDataRequest,delete s.dialResponse,delete s.dialRequest),s.dialDataRequest!=null&&(delete s.dialDataResponse,delete s.dialResponse,delete s.dialRequest),s.dialResponse!=null&&(delete s.dialDataResponse,delete s.dialDataRequest,delete s.dialRequest),s.dialRequest!=null&&(delete s.dialDataResponse,delete s.dialDataRequest,delete s.dialResponse),s})),t),r.encode=e=>At(e,r.codec()),r.decode=(e,n)=>vt(e,r.codec(),n)})(nr||(nr={}));var jn;(function(r){let t;r.codec=()=>(t==null&&(t=It((e,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),e.addrs!=null)for(let s of e.addrs)n.uint32(10),n.bytes(s);e.nonce!=null&&e.nonce!==0n&&(n.uint32(17),n.fixed64(e.nonce)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={addrs:[],nonce:0n},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{if(o.limits?.addrs!=null&&s.addrs.length===o.limits.addrs)throw new mn('Decode error - map field "addrs" had too many elements');s.addrs.push(e.bytes());break}case 2:{s.nonce=e.fixed64();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>At(e,r.codec()),r.decode=(e,n)=>vt(e,r.codec(),n)})(jn||(jn={}));var Yn;(function(r){let t;r.codec=()=>(t==null&&(t=It((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.addrIdx!=null&&e.addrIdx!==0&&(n.uint32(8),n.uint32(e.addrIdx)),e.numBytes!=null&&e.numBytes!==0n&&(n.uint32(16),n.uint64(e.numBytes)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={addrIdx:0,numBytes:0n},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.addrIdx=e.uint32();break}case 2:{s.numBytes=e.uint64();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>At(e,r.codec()),r.decode=(e,n)=>vt(e,r.codec(),n)})(Yn||(Yn={}));var at;(function(r){r.UNUSED="UNUSED",r.E_DIAL_ERROR="E_DIAL_ERROR",r.E_DIAL_BACK_ERROR="E_DIAL_BACK_ERROR",r.OK="OK"})(at||(at={}));var Wn;(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"})(Wn||(Wn={}));(function(r){r.codec=()=>Ae(Wn)})(at||(at={}));var Qt;(function(r){let t;(function(o){o.E_INTERNAL_ERROR="E_INTERNAL_ERROR",o.E_REQUEST_REJECTED="E_REQUEST_REJECTED",o.E_DIAL_REFUSED="E_DIAL_REFUSED",o.OK="OK"})(t=r.ResponseStatus||(r.ResponseStatus={}));let e;(function(o){o[o.E_INTERNAL_ERROR=0]="E_INTERNAL_ERROR",o[o.E_REQUEST_REJECTED=100]="E_REQUEST_REJECTED",o[o.E_DIAL_REFUSED=101]="E_DIAL_REFUSED",o[o.OK=200]="OK"})(e||(e={})),function(o){o.codec=()=>Ae(e)}(t=r.ResponseStatus||(r.ResponseStatus={}));let n;r.codec=()=>(n==null&&(n=It((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.status!=null&&e[o.status]!==0&&(s.uint32(8),r.ResponseStatus.codec().encode(o.status,s)),o.addrIdx!=null&&o.addrIdx!==0&&(s.uint32(16),s.uint32(o.addrIdx)),o.dialStatus!=null&&Wn[o.dialStatus]!==0&&(s.uint32(24),at.codec().encode(o.dialStatus,s)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={status:t.E_INTERNAL_ERROR,addrIdx:0,dialStatus:at.UNUSED},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let u=o.uint32();switch(u>>>3){case 1:{a.status=r.ResponseStatus.codec().decode(o);break}case 2:{a.addrIdx=o.uint32();break}case 3:{a.dialStatus=at.codec().decode(o);break}default:{o.skipType(u&7);break}}}return a})),n),r.encode=o=>At(o,r.codec()),r.decode=(o,s)=>vt(o,r.codec(),s)})(Qt||(Qt={}));var Qn;(function(r){let t;r.codec=()=>(t==null&&(t=It((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.data!=null&&e.data.byteLength>0&&(n.uint32(10),n.bytes(e.data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={data:gt(0)},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>At(e,r.codec()),r.decode=(e,n)=>vt(e,r.codec(),n)})(Qn||(Qn={}));var or;(function(r){let t;r.codec=()=>(t==null&&(t=It((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.nonce!=null&&e.nonce!==0n&&(n.uint32(9),n.fixed64(e.nonce)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={nonce:0n},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.nonce=e.fixed64();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>At(e,r.codec()),r.decode=(e,n)=>vt(e,r.codec(),n)})(or||(or={}));var fe;(function(r){let t;(function(o){o.OK="OK"})(t=r.DialBackStatus||(r.DialBackStatus={}));let e;(function(o){o[o.OK=0]="OK"})(e||(e={})),function(o){o.codec=()=>Ae(e)}(t=r.DialBackStatus||(r.DialBackStatus={}));let n;r.codec=()=>(n==null&&(n=It((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.status!=null&&e[o.status]!==0&&(s.uint32(8),r.DialBackStatus.codec().encode(o.status,s)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={status:t.OK},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let u=o.uint32();switch(u>>>3){case 1:{a.status=r.DialBackStatus.codec().decode(o);break}default:{o.skipType(u&7);break}}}return a})),n),r.encode=o=>At(o,r.codec()),r.decode=(o,s)=>vt(o,r.codec(),s)})(fe||(fe={}));function Jn(r,t){return Math.round(Math.random()*(t-r)+r)}var Od=4,kd=8,to=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=Dc({name:"libp2p_autonat_v2_dial_results",metrics:t.metrics}),this.findPeers=Bc(this.findRandomPeers.bind(this),6e4),this.addressFilter=Ts(1024),this.queue=new Vn({concurrency:3,maxSize:50}),this.maxDialDataBytes=e.maxDialDataBytes??Oc,this.dialDataChunkSize=e.dialDataChunkSize??kc,this.nonces=new Set}[Symbol.toStringTag]="@libp2p/autonat-v2";[Zr]=["@libp2p/autonat"];get[Xr](){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=>{this.handleDialBackStream(t).catch(e=>{this.log.error("error handling incoming autonat stream - %e",e)})},{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=zr([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){let e=AbortSignal.timeout(this.timeout);let n=rr(t.stream,{maxDataLength:this.maxMessageSize});try{let o=await n.read(or,{signal:e});if(!this.nonces.has(o.nonce))throw new St("No matching dial found for nonce value");this.nonces.delete(o.nonce),await n.write({status:fe.DialBackStatus.OK},fe),await t.stream.close({signal:e})}catch(o){this.log.error("error handling incoming dial back stream - %e",o),t.stream.abort(o)}}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())||s.multiaddr.toOptions().family===6&&(!e||!wc(s.multiaddr))||vc(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:As(),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})=>i.toOptions().family===6),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=zr([i.signal,AbortSignal.timeout(this.timeout)]),c=BigInt(Jn(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 %p to verify multiaddrs %s",t.remotePeer,s);let i=await t.newStream(this.dialRequestProtocol,o);try{let a=rr(i).pb(nr);for(await a.write({dialRequest:{addrs:s.map(c=>c.bytes),nonce:n}},o);;){let c=await a.read(o);if(c.dialDataRequest!=null){if(c.dialDataRequest.numBytes>this.maxDialDataBytes){this.log("too many dial data byte requested by %p - %s/%s",t.remotePeer,c.dialDataRequest.numBytes,this.maxDialDataBytes);continue}this.log("sending %d bytes to %p as anti-amplification attack protection",c.dialDataRequest.numBytes,t.remotePeer);let f=new Uint8Array(this.dialDataChunkSize),h=BigInt(this.dialDataChunkSize);for(let m=0n;m<c.dialDataRequest.numBytes;m+=h)await a.write({dialDataResponse:{data:f}},o);c=await a.read(o)}if(c.dialResponse==null){this.log("invalid autonat response from %p - %j",t.remotePeer,c);return}if(c.dialResponse.status!==Qt.ResponseStatus.OK)return;let d=s[c.dialResponse.addrIdx];if(d==null){this.log.trace("peer dialed unknown address");continue}let l=this.dialResults.get(d.toString());if(l==null){this.log.trace("peer reported %a as %s but there is no result object",d,c.dialResponse.status);continue}if(l.networkSegments.includes(e)){this.log.trace("%a results already included network segment %s",d,e);continue}if(l.result!=null){this.log.trace("already resolved result for %a, ignoring response from",d,t.remotePeer);continue}if(l.verifyingPeers.has(t.remotePeer)){this.log.trace("peer %p has already verified %a, ignoring response",t.remotePeer,d);continue}if(l.verifyingPeers.add(t.remotePeer),l.networkSegments.push(e),c.dialResponse.dialStatus===at.OK){if(this.log.trace("%p dialed %a successfully",t.remotePeer,l.multiaddr),l.success++,l.type!=="observed"){this.confirmAddress(l);continue}}else if(c.dialResponse.dialStatus===at.E_DIAL_ERROR)this.log.trace("%p could not dial %a",t.remotePeer,l.multiaddr),l.failure++;else if(c.dialResponse.dialStatus===at.E_DIAL_BACK_ERROR){this.log.trace("%p saw error while dialing %a",t.remotePeer,l.multiaddr);continue}this.log("%a success %d failure %d",l.multiaddr,l.success,l.failure),l.success===Od&&this.confirmAddress(l),l.failure===kd&&this.unconfirmAddress(l)}}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=t.toOptions();return e.family===4?e.host.split(".")[0].padStart(3,"0"):e.host.split(":")[0].padStart(4,"0")}};var eo=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}async start(){this.started||(await this.components.registrar.handle(this.dialRequestProtocol,t=>{this.handleDialRequestStream(t).catch(e=>{this.log.error("error handling incoming autonat stream - %e",e)})},{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams}),this.started=!0)}async stop(){await this.components.registrar.unhandle(this.dialRequestProtocol),this.started=!1}async handleDialRequestStream(t){let e=AbortSignal.timeout(this.timeout);let n=rr(t.stream,{maxDataLength:this.maxMessageSize}).pb(nr);try{let o=qc(t.connection.remoteAddr);if(o==null)throw new St(`Could not find IP address in connection address "${t.connection.remoteAddr}"`);let{dialRequest:s}=await n.read({signal:e});if(s==null)throw new St("Did not receive DialRequest message on incoming dial request stream");if(s.addrs.length===0)throw new St("Did not receive any addresses to dial");for(let i=0;i<s.addrs.length;i++)try{let a=Kr(s.addrs[i]);if(!await this.components.connectionManager.isDialable(a,{signal:e})){await n.write({dialResponse:{addrIdx:i,status:Qt.ResponseStatus.E_DIAL_REFUSED,dialStatus:at.UNUSED}},{signal:e});continue}let u=qc(a);if(u==null)throw new St(`Could not find IP address in requested address "${a}"`);if(kn(u))throw new St(`Requested address had private IP "${a}"`);u!==o&&await this.preventAmplificationAttack(n,i,{signal:e});let d=await this.dialClientBack(a,s.nonce,{signal:e});await n.write({dialResponse:{addrIdx:i,status:Qt.ResponseStatus.OK,dialStatus:d}},{signal:e})}catch(a){this.log.error("could not parse multiaddr - %e",a)}await t.stream.close({signal:e})}catch(o){this.log.error("error handling incoming autonat stream - %e",o),t.stream.abort(o)}}async preventAmplificationAttack(t,e,n){let o=Jn(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 St("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",s,t),at.E_DIAL_ERROR}try{let s=await o.newStream(this.dialBackProtocol,n),i=rr(s,{maxDataLength:this.maxMessageSize});if(await i.write({nonce:e},or,n),(await i.read(fe)).status!==fe.DialBackStatus.OK)throw new St("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),at.E_DIAL_BACK_ERROR}return at.OK}};function qc(r){return r.getComponents().filter(t=>t.code===4||t.code===41).map(t=>t.value).pop()}var ro=class{client;server;constructor(t,e){let n=`/${e.protocolPrefix??Qs}/${Js}/${"2"}/${Rc}`,o=`/${e.protocolPrefix??Qs}/${Js}/${"2"}/${Pc}`;this.client=new to(t,{...e,dialRequestProtocol:n,dialBackProtocol:o}),this.server=new eo(t,{...e,dialRequestProtocol:n,dialBackProtocol:o})}[Symbol.toStringTag]="@libp2p/autonat-v2";[Zr]=["@libp2p/autonat"];get[Xr](){return["@libp2p/identify"]}async start(){await oi(this.client,this.server)}async stop(){await si(this.client,this.server)}};function Nd(r={}){return t=>new ro(t,r)}return jc(Ud);})();
2
+ "use strict";var Libp2PAutonatV2=(()=>{var Gc=Object.create;var zr=Object.defineProperty;var Zc=Object.getOwnPropertyDescriptor;var Xc=Object.getOwnPropertyNames;var jc=Object.getPrototypeOf,Wc=Object.prototype.hasOwnProperty;var Yc=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),yt=(r,t)=>{for(var e in t)zr(r,e,{get:t[e],enumerable:!0})},ai=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Xc(t))!Wc.call(r,o)&&o!==e&&zr(r,o,{get:()=>t[o],enumerable:!(n=Zc(t,o))||n.enumerable});return r};var Qc=(r,t,e)=>(e=r!=null?Gc(jc(r)):{},ai(t||!r||!r.__esModule?zr(e,"default",{value:r,enumerable:!0}):e,r)),Jc=r=>ai(zr({},"__esModule",{value:!0}),r);var Ac=Yc(Mr=>{(function(){var r,t,e,n,o,s,i,a;a=function(c){var u,d,l,f;return u=(c&255<<24)>>>24,d=(c&255<<16)>>>16,l=(c&65280)>>>8,f=c&255,[u,d,l,f].join(".")},i=function(c){var u,d,l,f,p,h;for(u=[],l=f=0;f<=3&&c.length!==0;l=++f){if(l>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}h=t(c),p=h[0],d=h[1],c=c.substring(d),u.push(p)}if(c.length!==0)throw new Error("Invalid IP");switch(u.length){case 1:if(u[0]>4294967295)throw new Error("Invalid IP");return u[0]>>>0;case 2:if(u[0]>255||u[1]>16777215)throw new Error("Invalid IP");return(u[0]<<24|u[1])>>>0;case 3:if(u[0]>255||u[1]>255||u[2]>65535)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2])>>>0;case 4:if(u[0]>255||u[1]>255||u[2]>255||u[3]>255)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2]<<8|u[3])>>>0;default:throw new Error("Invalid IP")}},e=function(c){return c.charCodeAt(0)},n=e("0"),s=e("a"),o=e("A"),t=function(c){var u,d,l,f,p;for(f=0,u=10,d="9",l=0,c.length>1&&c[l]==="0"&&(c[l+1]==="x"||c[l+1]==="X"?(l+=2,u=16):"0"<=c[l+1]&&c[l+1]<="9"&&(l++,u=8,d="7")),p=l;l<c.length;){if("0"<=c[l]&&c[l]<=d)f=f*u+(e(c[l])-n)>>>0;else if(u===16)if("a"<=c[l]&&c[l]<="f")f=f*u+(10+e(c[l])-s)>>>0;else if("A"<=c[l]&&c[l]<="F")f=f*u+(10+e(c[l])-o)>>>0;else break;else break;if(f>4294967295)throw new Error("too large");l++}if(l===p)throw new Error("empty octet");return[f,l]},r=function(){function c(u,d){var l,f,p,h;if(typeof u!="string")throw new Error("Missing `net' parameter");if(d||(h=u.split("/",2),u=h[0],d=h[1]),d||(d=32),typeof d=="string"&&d.indexOf(".")>-1){try{this.maskLong=i(d)}catch(E){throw l=E,new Error("Invalid mask: "+d)}for(f=p=32;p>=0;f=--p)if(this.maskLong===4294967295<<32-f>>>0){this.bitmask=f;break}}else if(d||d===0)this.bitmask=parseInt(d,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(i(u)&this.maskLong)>>>0}catch(E){throw l=E,new Error("Invalid net address: "+u)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+d);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(u){return typeof u=="string"&&(u.indexOf("/")>0||u.split(".").length!==4)&&(u=new c(u)),u instanceof c?this.contains(u.base)&&this.contains(u.broadcast||u.last):(i(u)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(u){return u==null&&(u=1),new c(a(this.netLong+this.size*u),this.mask)},c.prototype.forEach=function(u){var d,l,f;for(f=i(this.first),l=i(this.last),d=0;f<=l;)u(a(f),f,d),d++,f++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),Mr.ip2long=i,Mr.long2ip=a,Mr.Netmask=r}).call(Mr)});var qd={};yt(qd,{autoNATv2:()=>Fd});var no=Symbol.for("@libp2p/peer-id");var Nt=class extends Error{static name="AbortError";constructor(t="The operation was aborted"){super(t),this.name="AbortError"}};var Ut=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},Vr=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}};var Hr=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}};var vt=class extends Error{static name="ProtocolError";constructor(t="Protocol error"){super(t),this.name="ProtocolError"}};var sr=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var $r=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))}};function ci(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function ui(...r){let t=[];for(let e of r)ci(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 fi(...r){let t=[];for(let e of r)ci(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 Gr=Symbol.for("@libp2p/service-capabilities"),Zr=Symbol.for("@libp2p/service-dependencies");var co={};yt(co,{base58btc:()=>G,base58flickr:()=>iu});var ph=new Uint8Array(0);function li(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 Mt(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 di(r){return new TextEncoder().encode(r)}function hi(r){return new TextDecoder().decode(r)}function tu(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),d=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 E=0,_=0,y=0,v=h.length;y!==v&&h[y]===0;)y++,E++;for(var x=(v-y)*d+1>>>0,D=new Uint8Array(x);y!==v;){for(var L=h[y],M=0,U=x-1;(L!==0||M<_)&&U!==-1;U--,M++)L+=256*D[U]>>>0,D[U]=L%a>>>0,L=L/a>>>0;if(L!==0)throw new Error("Non-zero carry");_=M,y++}for(var O=x-_;O!==x&&D[O]===0;)O++;for(var w=c.repeat(E);O<x;++O)w+=r.charAt(D[O]);return w}function f(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var E=0;if(h[E]!==" "){for(var _=0,y=0;h[E]===c;)_++,E++;for(var v=(h.length-E)*u+1>>>0,x=new Uint8Array(v);h[E];){var D=e[h.charCodeAt(E)];if(D===255)return;for(var L=0,M=v-1;(D!==0||L<y)&&M!==-1;M--,L++)D+=a*x[M]>>>0,x[M]=D%256>>>0,D=D/256>>>0;if(D!==0)throw new Error("Non-zero carry");y=L,E++}if(h[E]!==" "){for(var U=v-y;U!==v&&x[U]===0;)U++;for(var O=new Uint8Array(_+(v-U)),w=_;U!==v;)O[w++]=x[U++];return O}}}function p(h){var E=f(h);if(E)return E;throw new Error(`Non-${t} character`)}return{encode:l,decodeUnsafe:f,decode:p}}var eu=tu,ru=eu,mi=ru;var oo=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")}},so=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 gi(this,t)}},io=class{decoders;constructor(t){this.decoders=t}or(t){return gi(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 gi(r,t){return new io({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var ao=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 oo(t,e,n),this.decoder=new so(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Te({name:r,prefix:t,encode:e,decode:n}){return new ao(r,t,e,n)}function ee({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=mi(e,r);return Te({prefix:t,name:r,encode:n,decode:s=>Mt(o(s))})}function nu(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 d=t[r[u]];if(d===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<e|d,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 ou(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 su(r){let t={};for(let e=0;e<r.length;++e)t[r[e]]=e;return t}function W({name:r,prefix:t,bitsPerChar:e,alphabet:n}){let o=su(n);return Te({prefix:t,name:r,encode(s){return ou(s,n,e)},decode(s){return nu(s,o,e,r)}})}var G=ee({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),iu=ee({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var uo={};yt(uo,{base32:()=>re,base32hex:()=>fu,base32hexpad:()=>du,base32hexpadupper:()=>hu,base32hexupper:()=>lu,base32pad:()=>cu,base32padupper:()=>uu,base32upper:()=>au,base32z:()=>pu});var re=W({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),au=W({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),cu=W({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),uu=W({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),fu=W({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),lu=W({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),du=W({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),hu=W({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),pu=W({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var fo={};yt(fo,{base36:()=>ir,base36upper:()=>mu});var ir=ee({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),mu=ee({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var gu=xi,yi=128,yu=127,bu=~yu,xu=Math.pow(2,31);function xi(r,t,e){t=t||[],e=e||0;for(var n=e;r>=xu;)t[e++]=r&255|yi,r/=128;for(;r&bu;)t[e++]=r&255|yi,r>>>=7;return t[e]=r|0,xi.bytes=e-n+1,t}var wu=lo,Eu=128,bi=127;function lo(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw lo.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&bi)<<o:(i&bi)*Math.pow(2,o),o+=7}while(i>=Eu);return lo.bytes=s-n,e}var _u=Math.pow(2,7),Su=Math.pow(2,14),vu=Math.pow(2,21),Au=Math.pow(2,28),Iu=Math.pow(2,35),Bu=Math.pow(2,42),Du=Math.pow(2,49),Cu=Math.pow(2,56),Tu=Math.pow(2,63),Ru=function(r){return r<_u?1:r<Su?2:r<vu?3:r<Au?4:r<Iu?5:r<Bu?6:r<Du?7:r<Cu?8:r<Tu?9:10},Lu={encode:gu,decode:wu,encodingLength:Ru},Pu=Lu,ar=Pu;function cr(r,t=0){return[ar.decode(r,t),ar.decode.bytes]}function Re(r,t,e=0){return ar.encode(r,t,e),t}function Le(r){return ar.encodingLength(r)}function he(r,t){let e=t.byteLength,n=Le(r),o=n+Le(e),s=new Uint8Array(o+e);return Re(r,s,0),Re(e,s,n),s.set(t,o),new Pe(r,e,t,s)}function ur(r){let t=Mt(r),[e,n]=cr(t),[o,s]=cr(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Pe(e,o,i,t)}function wi(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&li(r.bytes,e.bytes)}}var Pe=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};function Ei(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return ku(e,ho(r),t??G.encoder);default:return Nu(e,ho(r),t??re.encoder)}}var _i=new WeakMap;function ho(r){let t=_i.get(r);if(t==null){let e=new Map;return _i.set(r,e),e}return t}var tt=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!==fr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==Uu)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=he(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&&wi(t.multihash,n.multihash)}toString(t){return Ei(this,t)}toJSON(){return{"/":Ei(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??Si(n,o,s.bytes))}else if(e[Mu]===!0){let{version:n,multihash:o,code:s}=e,i=ur(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!==fr)throw new Error(`Version 0 CID must use dag-pb (code: ${fr}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=Si(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,fr,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=Mt(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 Pe(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,f]=cr(t.subarray(e));return e+=f,l},o=n(),s=fr;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,d=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:d,size:u}}static parse(t,e){let[n,o]=Ou(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 ho(s).set(n,t),s}};function Ou(r,t){switch(r[0]){case"Q":{let e=t??G;return[G.prefix,e.decode(`${G.prefix}${r}`)]}case G.prefix:{let e=t??G;return[G.prefix,e.decode(r)]}case re.prefix:{let e=t??re;return[re.prefix,e.decode(r)]}case ir.prefix:{let e=t??ir;return[ir.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 ku(r,t,e){let{prefix:n}=e;if(n!==G.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 Nu(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 fr=112,Uu=18;function Si(r,t,e){let n=Le(r),o=n+Le(t),s=new Uint8Array(o+e.byteLength);return Re(r,s,0),Re(t,s,n),s.set(e,o),s}var Mu=Symbol.for("@ipld/js-cid/CID");var po={};yt(po,{identity:()=>Ct});var vi=0,Ku="identity",Ai=Mt;function Fu(r){return he(vi,Ai(r))}var Ct={code:vi,name:Ku,encode:Ai,digest:Fu};function ft(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 bt(r=0){return new Uint8Array(r)}function pt(r=0){return new Uint8Array(r)}function Kt(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 Bi=Symbol.for("@achingbrain/uint8arraylist");function Ii(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 jr(r){return!!r?.[Bi]}var J=class r{bufs;length;[Bi]=!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(jr(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(jr(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=Ii(this.bufs,t);return e.buf[e.index]}set(t,e){let n=Ii(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(jr(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 Kt(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:Kt(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,d=e>a&&e<=c;if(u&&d){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(d){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(!jr(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,d;for(let l=e;l<=c;l+=d){d=0;for(let f=u;f>=0;f--){let p=this.get(l+f);if(n[f]!==p){d=Math.max(1,f-a[p]);break}}if(d===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=bt(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=bt(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=bt(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=bt(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=bt(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=bt(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=bt(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=bt(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(!ft(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 mo={};yt(mo,{base10:()=>qu});var qu=ee({prefix:"9",name:"base10",alphabet:"0123456789"});var go={};yt(go,{base16:()=>zu,base16upper:()=>Vu});var zu=W({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Vu=W({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var yo={};yt(yo,{base2:()=>Hu});var Hu=W({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var bo={};yt(bo,{base256emoji:()=>ju});var Di=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}"),$u=Di.reduce((r,t,e)=>(r[e]=t,r),[]),Gu=Di.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function Zu(r){return r.reduce((t,e)=>(t+=$u[e],t),"")}function Xu(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=Gu[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var ju=Te({prefix:"\u{1F680}",name:"base256emoji",encode:Zu,decode:Xu});var wo={};yt(wo,{base64:()=>Wu,base64pad:()=>Yu,base64url:()=>xo,base64urlpad:()=>Qu});var Wu=W({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Yu=W({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),xo=W({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Qu=W({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Eo={};yt(Eo,{base8:()=>Ju});var Ju=W({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var _o={};yt(_o,{identity:()=>tf});var tf=Te({prefix:"\0",name:"identity",encode:r=>hi(r),decode:r=>di(r)});var Yh=new TextEncoder,Qh=new TextDecoder;var Ao={};yt(Ao,{sha256:()=>lr,sha512:()=>nf});function vo({name:r,code:t,encode:e}){return new So(r,t,e)}var So=class{name;code;encode;constructor(t,e,n){this.name=t,this.code=e,this.encode=n}digest(t){if(t instanceof Uint8Array){let e=this.encode(t);return e instanceof Uint8Array?he(this.code,e):e.then(n=>he(this.code,n))}else throw Error("Unknown type, must be binary type")}};function Ti(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var lr=vo({name:"sha2-256",code:18,encode:Ti("SHA-256")}),nf=vo({name:"sha2-512",code:19,encode:Ti("SHA-512")});var dr={..._o,...yo,...Eo,...mo,...go,...uo,...fo,...co,...wo,...bo},fp={...Ao,...po};function Li(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var Ri=Li("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Io=Li("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}),of={utf8:Ri,"utf-8":Ri,hex:dr.base16,latin1:Io,ascii:Io,binary:Io,...dr},Wr=of;function V(r,t="utf8"){let e=Wr[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function H(r,t="utf8"){let e=Wr[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var sf=parseInt("11111",2),Bo=parseInt("10000000",2),af=parseInt("01111111",2),Pi={0:hr,1:hr,2:cf,3:lf,4:df,5:ff,6:uf,16:hr,22:hr,48:hr};function Do(r,t={offset:0}){let e=r[t.offset]&sf;if(t.offset++,Pi[e]!=null)return Pi[e](r,t);throw new Error("No decoder for tag "+e)}function pr(r,t){let e=0;if((r[t.offset]&Bo)===Bo){let n=r[t.offset]&af,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 hr(r,t){pr(r,t);let e=[];for(;!(t.offset>=r.byteLength);){let n=Do(r,t);if(n===null)break;e.push(n)}return e}function cf(r,t){let e=pr(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 uf(r,t){let e=pr(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 d=0;for(let l=0;l<c.length;l++)d+=c[l]<<l*7;a+=`.${d}`,c=[]}}return a}function ff(r,t){return t.offset++,null}function lf(r,t){let e=pr(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 df(r,t){let e=pr(r,t),n=r.subarray(t.offset,t.offset+e);return t.offset+=e,n}function hf(r){let t=r.toString(16);t.length%2===1&&(t="0"+t);let e=new J;for(let n=0;n<t.length;n+=2)e.append(Uint8Array.from([parseInt(`${t[n]}${t[n+1]}`,16)]));return e}function Co(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let t=hf(r.byteLength);return new J(Uint8Array.from([t.byteLength|Bo]),t)}function Oi(r){let t=new J,e=128;return(r.subarray()[0]&e)===e&&t.append(Uint8Array.from([0])),t.append(r),new J(Uint8Array.from([2]),Co(t),t)}function ki(r){let t=Uint8Array.from([0]),e=new J(t,r);return new J(Uint8Array.from([3]),Co(e),e)}function Yr(r,t=48){let e=new J;for(let n of r)e.append(n);return new J(Uint8Array.from([t]),Co(e),e)}async function Ni(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 pf=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),mf=Uint8Array.from([6,5,43,129,4,0,34]),gf=Uint8Array.from([6,5,43,129,4,0,35]),yf={ext:!0,kty:"EC",crv:"P-256"},bf={ext:!0,kty:"EC",crv:"P-384"},xf={ext:!0,kty:"EC",crv:"P-521"},To=32,Ro=48,Lo=66;function Ui(r){let t=Do(r);return Mi(t)}function Mi(r){let t=r[1][1][0],e=1,n,o;if(t.byteLength===To*2+1)return n=H(t.subarray(e,e+To),"base64url"),o=H(t.subarray(e+To),"base64url"),new Oe({...yf,key_ops:["verify"],x:n,y:o});if(t.byteLength===Ro*2+1)return n=H(t.subarray(e,e+Ro),"base64url"),o=H(t.subarray(e+Ro),"base64url"),new Oe({...bf,key_ops:["verify"],x:n,y:o});if(t.byteLength===Lo*2+1)return n=H(t.subarray(e,e+Lo),"base64url"),o=H(t.subarray(e+Lo),"base64url"),new Oe({...xf,key_ops:["verify"],x:n,y:o});throw new Ut(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function Ki(r){return Yr([Oi(Uint8Array.from([1])),Yr([wf(r.crv)],160),Yr([ki(new J(Uint8Array.from([4]),V(r.x??"","base64url"),V(r.y??"","base64url")))],161)]).subarray()}function wf(r){if(r==="P-256")return pf;if(r==="P-384")return mf;if(r==="P-521")return gf;throw new Ut(`Invalid curve ${r}`)}var Oe=class{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=Ki(this.jwk)),this._raw}toMultihash(){return Ct.digest(ke(this))}toCID(){return tt.createV1(114,this.toMultihash())}toString(){return G.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:ft(this.raw,t.raw)}async verify(t,e,n){return Ni(this.jwk,e,t,n)}};var me=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function qt(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function mr(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function mt(r,...t){if(!qt(r))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(r.length))throw new Error("Uint8Array expected of length "+t+", got length="+r.length)}function Qr(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");mr(r.outputLen),mr(r.blockLen)}function Ue(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 qi(r,t){mt(r);let e=t.outputLen;if(r.length<e)throw new Error("digestInto() expects output buffer of length at least "+e)}function zt(...r){for(let t=0;t<r.length;t++)r[t].fill(0)}function Jr(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Tt(r,t){return r<<32-t|r>>>t}var zi=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Ef=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function At(r){if(mt(r),zi)return r.toHex();let t="";for(let e=0;e<r.length;e++)t+=Ef[r[e]];return t}var Ft={_0:48,_9:57,A:65,F:70,a:97,f:102};function Fi(r){if(r>=Ft._0&&r<=Ft._9)return r-Ft._0;if(r>=Ft.A&&r<=Ft.F)return r-(Ft.A-10);if(r>=Ft.a&&r<=Ft.f)return r-(Ft.a-10)}function ge(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(zi)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=Fi(r.charCodeAt(s)),a=Fi(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 Po(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function gr(r){return typeof r=="string"&&(r=Po(r)),mt(r),r}function lt(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];mt(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}var Ne=class{};function Oo(r){let t=n=>r().update(gr(n)).digest(),e=r();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>r(),t}function Me(r=32){if(me&&typeof me.getRandomValues=="function")return me.getRandomValues(new Uint8Array(r));if(me&&typeof me.randomBytes=="function")return Uint8Array.from(me.randomBytes(r));throw new Error("crypto.getRandomValues must be defined")}function _f(r,t,e,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(t,e,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(e>>o&s),a=Number(e&s),c=n?4:0,u=n?0:4;r.setUint32(t+c,i,n),r.setUint32(t+u,a,n)}function Vi(r,t,e){return r&t^~r&e}function Hi(r,t,e){return r&t^r&e^t&e}var yr=class extends Ne{constructor(t,e,n,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(t),this.view=Jr(this.buffer)}update(t){Ue(this),t=gr(t),mt(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=Jr(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){Ue(this),qi(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;e[i++]=128,zt(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let l=i;l<o;l++)e[l]=0;_f(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=Jr(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,d=this.get();if(u>d.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<u;l++)a.setUint32(4*l,d[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||(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()}},Vt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var ot=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var tn=BigInt(4294967295),$i=BigInt(32);function Sf(r,t=!1){return t?{h:Number(r&tn),l:Number(r>>$i&tn)}:{h:Number(r>>$i&tn)|0,l:Number(r&tn)|0}}function Gi(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}=Sf(r[s],t);[n[s],o[s]]=[i,a]}return[n,o]}var ko=(r,t,e)=>r>>>e,No=(r,t,e)=>r<<32-e|t>>>e,ye=(r,t,e)=>r>>>e|t<<32-e,be=(r,t,e)=>r<<32-e|t>>>e,br=(r,t,e)=>r<<64-e|t>>>e-32,xr=(r,t,e)=>r>>>e-32|t<<64-e;function kt(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var Zi=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),Xi=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,ji=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),Wi=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,Yi=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),Qi=(r,t,e,n,o,s)=>t+e+n+o+s+(r/2**32|0)|0;var Af=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]),ne=new Uint32Array(64),Uo=class extends yr{constructor(t=32){super(64,t,8,!1),this.A=Vt[0]|0,this.B=Vt[1]|0,this.C=Vt[2]|0,this.D=Vt[3]|0,this.E=Vt[4]|0,this.F=Vt[5]|0,this.G=Vt[6]|0,this.H=Vt[7]|0}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)ne[l]=t.getUint32(e,!1);for(let l=16;l<64;l++){let f=ne[l-15],p=ne[l-2],h=Tt(f,7)^Tt(f,18)^f>>>3,E=Tt(p,17)^Tt(p,19)^p>>>10;ne[l]=E+ne[l-7]+h+ne[l-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:d}=this;for(let l=0;l<64;l++){let f=Tt(a,6)^Tt(a,11)^Tt(a,25),p=d+f+Vi(a,c,u)+Af[l]+ne[l]|0,E=(Tt(n,2)^Tt(n,13)^Tt(n,22))+Hi(n,o,s)|0;d=u,u=c,c=a,a=i+p|0,i=s,s=o,o=n,n=p+E|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,d=d+this.H|0,this.set(n,o,s,i,a,c,u,d)}roundClean(){zt(ne)}destroy(){this.set(0,0,0,0,0,0,0,0),zt(this.buffer)}};var Ji=Gi(["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))),If=Ji[0],Bf=Ji[1],oe=new Uint32Array(80),se=new Uint32Array(80),Mo=class extends yr{constructor(t=64){super(128,t,16,!1),this.Ah=ot[0]|0,this.Al=ot[1]|0,this.Bh=ot[2]|0,this.Bl=ot[3]|0,this.Ch=ot[4]|0,this.Cl=ot[5]|0,this.Dh=ot[6]|0,this.Dl=ot[7]|0,this.Eh=ot[8]|0,this.El=ot[9]|0,this.Fh=ot[10]|0,this.Fl=ot[11]|0,this.Gh=ot[12]|0,this.Gl=ot[13]|0,this.Hh=ot[14]|0,this.Hl=ot[15]|0}get(){let{Ah:t,Al:e,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:u,El:d,Fh:l,Fl:f,Gh:p,Gl:h,Hh:E,Hl:_}=this;return[t,e,n,o,s,i,a,c,u,d,l,f,p,h,E,_]}set(t,e,n,o,s,i,a,c,u,d,l,f,p,h,E,_){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=d|0,this.Fh=l|0,this.Fl=f|0,this.Gh=p|0,this.Gl=h|0,this.Hh=E|0,this.Hl=_|0}process(t,e){for(let x=0;x<16;x++,e+=4)oe[x]=t.getUint32(e),se[x]=t.getUint32(e+=4);for(let x=16;x<80;x++){let D=oe[x-15]|0,L=se[x-15]|0,M=ye(D,L,1)^ye(D,L,8)^ko(D,L,7),U=be(D,L,1)^be(D,L,8)^No(D,L,7),O=oe[x-2]|0,w=se[x-2]|0,C=ye(O,w,19)^br(O,w,61)^ko(O,w,6),k=be(O,w,19)^xr(O,w,61)^No(O,w,6),T=ji(U,k,se[x-7],se[x-16]),b=Wi(T,M,C,oe[x-7],oe[x-16]);oe[x]=b|0,se[x]=T|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:d,Eh:l,El:f,Fh:p,Fl:h,Gh:E,Gl:_,Hh:y,Hl:v}=this;for(let x=0;x<80;x++){let D=ye(l,f,14)^ye(l,f,18)^br(l,f,41),L=be(l,f,14)^be(l,f,18)^xr(l,f,41),M=l&p^~l&E,U=f&h^~f&_,O=Yi(v,L,U,Bf[x],se[x]),w=Qi(O,y,D,M,If[x],oe[x]),C=O|0,k=ye(n,o,28)^br(n,o,34)^br(n,o,39),T=be(n,o,28)^xr(n,o,34)^xr(n,o,39),b=n&s^n&a^s&a,m=o&i^o&c^i&c;y=E|0,v=_|0,E=p|0,_=h|0,p=l|0,h=f|0,{h:l,l:f}=kt(u|0,d|0,w|0,C|0),u=a|0,d=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let g=Zi(C,T,m);n=Xi(g,w,k,b),o=g|0}({h:n,l:o}=kt(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=kt(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=kt(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:d}=kt(this.Dh|0,this.Dl|0,u|0,d|0),{h:l,l:f}=kt(this.Eh|0,this.El|0,l|0,f|0),{h:p,l:h}=kt(this.Fh|0,this.Fl|0,p|0,h|0),{h:E,l:_}=kt(this.Gh|0,this.Gl|0,E|0,_|0),{h:y,l:v}=kt(this.Hh|0,this.Hl|0,y|0,v|0),this.set(n,o,s,i,a,c,u,d,l,f,p,h,E,_,y,v)}roundClean(){zt(oe,se)}destroy(){zt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var ta=Oo(()=>new Uo);var ea=Oo(()=>new Mo);var qo=BigInt(0),Fo=BigInt(1);function Ht(r,t=""){if(typeof r!="boolean"){let e=t&&`"${t}"`;throw new Error(e+"expected boolean, got type="+typeof r)}return r}function xt(r,t,e=""){let n=qt(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 wr(r){let t=r.toString(16);return t.length&1?"0"+t:t}function ra(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?qo:BigInt("0x"+r)}function Ke(r){return ra(At(r))}function $t(r){return mt(r),ra(At(Uint8Array.from(r).reverse()))}function en(r,t){return ge(r.toString(16).padStart(t*2,"0"))}function zo(r,t){return en(r,t).reverse()}function q(r,t,e){let n;if(typeof t=="string")try{n=ge(t)}catch(s){throw new Error(r+" must be hex string or Uint8Array, cause: "+s)}else if(qt(t))n=Uint8Array.from(t);else throw new Error(r+" must be hex string or Uint8Array");let o=n.length;if(typeof e=="number"&&o!==e)throw new Error(r+" of length "+e+" expected, got "+o);return n}function na(r,t){if(r.length!==t.length)return!1;let e=0;for(let n=0;n<r.length;n++)e|=r[n]^t[n];return e===0}function Vo(r){return Uint8Array.from(r)}var Ko=r=>typeof r=="bigint"&&qo<=r;function oa(r,t,e){return Ko(r)&&Ko(t)&&Ko(e)&&t<=r&&r<e}function Er(r,t,e,n){if(!oa(t,e,n))throw new Error("expected valid "+r+": "+e+" <= n < "+n+", got "+t)}function rn(r){let t;for(t=0;r>qo;r>>=Fo,t+=1);return t}var ie=r=>(Fo<<BigInt(r))-Fo;function sa(r,t,e){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof e!="function")throw new Error("hmacFn must be a function");let n=p=>new Uint8Array(p),o=p=>Uint8Array.of(p),s=n(r),i=n(r),a=0,c=()=>{s.fill(1),i.fill(0),a=0},u=(...p)=>e(i,s,...p),d=(p=n(0))=>{i=u(o(0),p),s=u(),p.length!==0&&(i=u(o(1),p),s=u())},l=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let p=0,h=[];for(;p<t;){s=u();let E=s.slice();h.push(E),p+=s.length}return lt(...h)};return(p,h)=>{c(),d(p);let E;for(;!(E=h(l()));)d();return c(),E}}function ae(r,t,e={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function n(o,s,i){let a=r[o];if(i&&a===void 0)return;let c=typeof a;if(c!==s||a===null)throw new Error(`param "${o}" is invalid: expected ${s}, got ${c}`)}Object.entries(t).forEach(([o,s])=>n(o,s,!1)),Object.entries(e).forEach(([o,s])=>n(o,s,!0))}var Ho=()=>{throw new Error("not implemented")};function Fe(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),et=BigInt(1),xe=BigInt(2),ca=BigInt(3),ua=BigInt(4),fa=BigInt(5),Df=BigInt(7),la=BigInt(8),Cf=BigInt(9),da=BigInt(16);function Y(r,t){let e=r%t;return e>=dt?e:t+e}function $(r,t,e){let n=r;for(;t-- >dt;)n*=n,n%=e;return n}function ia(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=Y(r,t),n=t,o=dt,s=et,i=et,a=dt;for(;e!==dt;){let u=n/e,d=n%e,l=o-i*u,f=s-a*u;n=e,e=d,o=i,s=a,i=l,a=f}if(n!==et)throw new Error("invert: does not exist");return Y(o,t)}function $o(r,t,e){if(!r.eql(r.sqr(t),e))throw new Error("Cannot find square root")}function ha(r,t){let e=(r.ORDER+et)/ua,n=r.pow(t,e);return $o(r,n,t),n}function Tf(r,t){let e=(r.ORDER-fa)/la,n=r.mul(t,xe),o=r.pow(n,e),s=r.mul(t,o),i=r.mul(r.mul(s,xe),o),a=r.mul(s,r.sub(i,r.ONE));return $o(r,a,t),a}function Rf(r){let t=wt(r),e=pa(r),n=e(t,t.neg(t.ONE)),o=e(t,n),s=e(t,t.neg(n)),i=(r+Df)/da;return(a,c)=>{let u=a.pow(c,i),d=a.mul(u,n),l=a.mul(u,o),f=a.mul(u,s),p=a.eql(a.sqr(d),c),h=a.eql(a.sqr(l),c);u=a.cmov(u,d,p),d=a.cmov(f,l,h);let E=a.eql(a.sqr(d),c),_=a.cmov(u,d,E);return $o(a,_,c),_}}function pa(r){if(r<ca)throw new Error("sqrt is not defined for small field");let t=r-et,e=0;for(;t%xe===dt;)t/=xe,e++;let n=xe,o=wt(r);for(;aa(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(e===1)return ha;let s=o.pow(n,t),i=(t+et)/xe;return function(c,u){if(c.is0(u))return u;if(aa(c,u)!==1)throw new Error("Cannot find square root");let d=e,l=c.mul(c.ONE,s),f=c.pow(u,t),p=c.pow(u,i);for(;!c.eql(f,c.ONE);){if(c.is0(f))return c.ZERO;let h=1,E=c.sqr(f);for(;!c.eql(E,c.ONE);)if(h++,E=c.sqr(E),h===d)throw new Error("Cannot find square root");let _=et<<BigInt(d-h-1),y=c.pow(l,_);d=h,l=c.sqr(y),f=c.mul(f,l),p=c.mul(p,y)}return p}}function Lf(r){return r%ua===ca?ha:r%la===fa?Tf:r%da===Cf?Rf(r):pa(r)}var Gt=(r,t)=>(Y(r,t)&et)===et,Pf=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Go(r){let t={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},e=Pf.reduce((n,o)=>(n[o]="function",n),t);return ae(r,e),r}function Of(r,t,e){if(e<dt)throw new Error("invalid exponent, negatives unsupported");if(e===dt)return r.ONE;if(e===et)return t;let n=r.ONE,o=t;for(;e>dt;)e&et&&(n=r.mul(n,o)),o=r.sqr(o),e>>=et;return n}function _r(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 aa(r,t){let e=(r.ORDER-et)/xe,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 nn(r,t){t!==void 0&&mr(t);let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}function wt(r,t,e=!1,n={}){if(r<=dt)throw new Error("invalid field: expected ORDER > 0, got "+r);let o,s,i=!1,a;if(typeof t=="object"&&t!=null){if(n.sqrt||e)throw new Error("cannot specify opts in two arguments");let f=t;f.BITS&&(o=f.BITS),f.sqrt&&(s=f.sqrt),typeof f.isLE=="boolean"&&(e=f.isLE),typeof f.modFromBytes=="boolean"&&(i=f.modFromBytes),a=f.allowedLengths}else typeof t=="number"&&(o=t),n.sqrt&&(s=n.sqrt);let{nBitLength:c,nByteLength:u}=nn(r,o);if(u>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let d,l=Object.freeze({ORDER:r,isLE:e,BITS:c,BYTES:u,MASK:ie(c),ZERO:dt,ONE:et,allowedLengths:a,create:f=>Y(f,r),isValid:f=>{if(typeof f!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof f);return dt<=f&&f<r},is0:f=>f===dt,isValidNot0:f=>!l.is0(f)&&l.isValid(f),isOdd:f=>(f&et)===et,neg:f=>Y(-f,r),eql:(f,p)=>f===p,sqr:f=>Y(f*f,r),add:(f,p)=>Y(f+p,r),sub:(f,p)=>Y(f-p,r),mul:(f,p)=>Y(f*p,r),pow:(f,p)=>Of(l,f,p),div:(f,p)=>Y(f*ia(p,r),r),sqrN:f=>f*f,addN:(f,p)=>f+p,subN:(f,p)=>f-p,mulN:(f,p)=>f*p,inv:f=>ia(f,r),sqrt:s||(f=>(d||(d=Lf(r)),d(l,f))),toBytes:f=>e?zo(f,u):en(f,u),fromBytes:(f,p=!0)=>{if(a){if(!a.includes(f.length)||f.length>u)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+f.length);let E=new Uint8Array(u);E.set(f,e?0:E.length-f.length),f=E}if(f.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+f.length);let h=e?$t(f):Ke(f);if(i&&(h=Y(h,r)),!p&&!l.isValid(h))throw new Error("invalid field element: outside of range 0..ORDER");return h},invertBatch:f=>_r(l,f),cmov:(f,p,h)=>h?p:f});return Object.freeze(l)}function ma(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 Zo(r){let t=ma(r);return t+Math.ceil(t/2)}function Xo(r,t,e=!1){let n=r.length,o=ma(t),s=Zo(t);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=e?$t(r):Ke(r),a=Y(i,t-et)+et;return e?zo(a,o):en(a,o)}var qe=BigInt(0),we=BigInt(1);function Sr(r,t){let e=t.negate();return r?e:t}function Zt(r,t){let e=_r(r.Fp,t.map(n=>n.Z));return t.map((n,o)=>r.fromAffine(n.toAffine(e[o])))}function xa(r,t){if(!Number.isSafeInteger(r)||r<=0||r>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+r)}function jo(r,t){xa(r,t);let e=Math.ceil(t/r)+1,n=2**(r-1),o=2**r,s=ie(r),i=BigInt(r);return{windows:e,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function ga(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+=we);let u=t*n,d=u+Math.abs(a)-1,l=a===0,f=a<0,p=t%2!==0;return{nextN:c,offset:d,isZero:l,isNeg:f,isNegF:p,offsetF:u}}function kf(r,t){if(!Array.isArray(r))throw new Error("array expected");r.forEach((e,n)=>{if(!(e instanceof t))throw new Error("invalid point at index "+n)})}function Nf(r,t){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((e,n)=>{if(!t.isValid(e))throw new Error("invalid scalar at index "+n)})}var Wo=new WeakMap,wa=new WeakMap;function Yo(r){return wa.get(r)||1}function ya(r){if(r!==qe)throw new Error("invalid wNAF")}var ze=class{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>qe;)e&we&&(n=n.add(o)),o=o.double(),e>>=we;return n}precomputeWindow(t,e){let{windows:n,windowSize:o}=jo(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=jo(t,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:u,isZero:d,isNeg:l,isNegF:f,offsetF:p}=ga(n,a,i);n=c,d?s=s.add(Sr(f,e[p])):o=o.add(Sr(l,e[u]))}return ya(n),{p:o,f:s}}wNAFUnsafe(t,e,n,o=this.ZERO){let s=jo(t,this.bits);for(let i=0;i<s.windows&&n!==qe;i++){let{nextN:a,offset:c,isZero:u,isNeg:d}=ga(n,i,s);if(n=a,!u){let l=e[c];o=o.add(d?l.negate():l)}}return ya(n),o}getPrecomputes(t,e,n){let o=Wo.get(e);return o||(o=this.precomputeWindow(e,t),t!==1&&(typeof n=="function"&&(o=n(o)),Wo.set(e,o))),o}cached(t,e,n){let o=Yo(t);return this.wNAF(o,this.getPrecomputes(o,t,n),e)}unsafe(t,e,n,o){let s=Yo(t);return s===1?this._unsafeLadder(t,e,o):this.wNAFUnsafe(s,this.getPrecomputes(s,t,n),e,o)}createCache(t,e){xa(e,this.bits),wa.set(t,e),Wo.delete(t)}hasCache(t){return Yo(t)!==1}};function Ea(r,t,e,n){let o=t,s=r.ZERO,i=r.ZERO;for(;e>qe||n>qe;)e&we&&(s=s.add(o)),n&we&&(i=i.add(o)),o=o.double(),e>>=we,n>>=we;return{p1:s,p2:i}}function Ve(r,t,e,n){kf(e,r),Nf(n,t);let o=e.length,s=n.length;if(o!==s)throw new Error("arrays of points and scalars must have equal length");let i=r.ZERO,a=rn(BigInt(o)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let u=ie(c),d=new Array(Number(u)+1).fill(i),l=Math.floor((t.BITS-1)/c)*c,f=i;for(let p=l;p>=0;p-=c){d.fill(i);for(let E=0;E<s;E++){let _=n[E],y=Number(_>>BigInt(p)&u);d[y]=d[y].add(e[E])}let h=i;for(let E=d.length-1,_=i;E>0;E--)_=_.add(d[E]),h=h.add(_);if(f=f.add(h),p!==0)for(let E=0;E<c;E++)f=f.double()}return f}function ba(r,t,e){if(t){if(t.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Go(t),t}else return wt(r,{isLE:e})}function on(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>qe))throw new Error(`CURVE.${c} must be positive bigint`)}let o=ba(t.p,e.Fp,n),s=ba(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}}var ce=BigInt(0),rt=BigInt(1),Qo=BigInt(2),Uf=BigInt(8);function Mf(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 Kf(r,t={}){let e=on("edwards",r,t,t.FpFnLE),{Fp:n,Fn:o}=e,s=e.CURVE,{h:i}=s;ae(t,{},{uvRatio:"function"});let a=Qo<<BigInt(o.BYTES*8)-rt,c=_=>n.create(_),u=t.uvRatio||((_,y)=>{try{return{isValid:!0,value:n.sqrt(n.div(_,y))}}catch{return{isValid:!1,value:ce}}});if(!Mf(n,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function d(_,y,v=!1){let x=v?rt:ce;return Er("coordinate "+_,y,x,a),y}function l(_){if(!(_ instanceof h))throw new Error("ExtendedPoint expected")}let f=Fe((_,y)=>{let{X:v,Y:x,Z:D}=_,L=_.is0();y==null&&(y=L?Uf:n.inv(D));let M=c(v*y),U=c(x*y),O=n.mul(D,y);if(L)return{x:ce,y:rt};if(O!==rt)throw new Error("invZ was invalid");return{x:M,y:U}}),p=Fe(_=>{let{a:y,d:v}=s;if(_.is0())throw new Error("bad point: ZERO");let{X:x,Y:D,Z:L,T:M}=_,U=c(x*x),O=c(D*D),w=c(L*L),C=c(w*w),k=c(U*y),T=c(w*c(k+O)),b=c(C+c(v*c(U*O)));if(T!==b)throw new Error("bad point: equation left != right (1)");let m=c(x*D),g=c(L*M);if(m!==g)throw new Error("bad point: equation left != right (2)");return!0});class h{constructor(y,v,x,D){this.X=d("x",y),this.Y=d("y",v),this.Z=d("z",x,!0),this.T=d("t",D),Object.freeze(this)}static CURVE(){return s}static fromAffine(y){if(y instanceof h)throw new Error("extended point not allowed");let{x:v,y:x}=y||{};return d("x",v),d("y",x),new h(v,x,rt,c(v*x))}static fromBytes(y,v=!1){let x=n.BYTES,{a:D,d:L}=s;y=Vo(xt(y,x,"point")),Ht(v,"zip215");let M=Vo(y),U=y[x-1];M[x-1]=U&-129;let O=$t(M),w=v?a:n.ORDER;Er("point.y",O,ce,w);let C=c(O*O),k=c(C-rt),T=c(L*C-D),{isValid:b,value:m}=u(k,T);if(!b)throw new Error("bad point: invalid y coordinate");let g=(m&rt)===rt,S=(U&128)!==0;if(!v&&m===ce&&S)throw new Error("bad point: x=0 and x_0=1");return S!==g&&(m=c(-m)),h.fromAffine({x:m,y:O})}static fromHex(y,v=!1){return h.fromBytes(q("point",y),v)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=8,v=!0){return E.createCache(this,y),v||this.multiply(Qo),this}assertValidity(){p(this)}equals(y){l(y);let{X:v,Y:x,Z:D}=this,{X:L,Y:M,Z:U}=y,O=c(v*U),w=c(L*D),C=c(x*U),k=c(M*D);return O===w&&C===k}is0(){return this.equals(h.ZERO)}negate(){return new h(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:y}=s,{X:v,Y:x,Z:D}=this,L=c(v*v),M=c(x*x),U=c(Qo*c(D*D)),O=c(y*L),w=v+x,C=c(c(w*w)-L-M),k=O+M,T=k-U,b=O-M,m=c(C*T),g=c(k*b),S=c(C*b),A=c(T*k);return new h(m,g,A,S)}add(y){l(y);let{a:v,d:x}=s,{X:D,Y:L,Z:M,T:U}=this,{X:O,Y:w,Z:C,T:k}=y,T=c(D*O),b=c(L*w),m=c(U*x*k),g=c(M*C),S=c((D+L)*(O+w)-T-b),A=g-m,R=g+m,I=c(b-v*T),B=c(S*A),P=c(R*I),N=c(S*I),Z=c(A*R);return new h(B,P,Z,N)}subtract(y){return this.add(y.negate())}multiply(y){if(!o.isValidNot0(y))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:v,f:x}=E.cached(this,y,D=>Zt(h,D));return Zt(h,[v,x])[0]}multiplyUnsafe(y,v=h.ZERO){if(!o.isValid(y))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return y===ce?h.ZERO:this.is0()||y===rt?this:E.unsafe(this,y,x=>Zt(h,x),v)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return E.unsafe(this,s.n).is0()}toAffine(y){return f(this,y)}clearCofactor(){return i===rt?this:this.multiplyUnsafe(i)}toBytes(){let{x:y,y:v}=this.toAffine(),x=n.toBytes(v);return x[x.length-1]|=y&rt?128:0,x}toHex(){return At(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(y){return Zt(h,y)}static msm(y,v){return Ve(h,o,y,v)}_setWindowSize(y){this.precompute(y)}toRawBytes(){return this.toBytes()}}h.BASE=new h(s.Gx,s.Gy,rt,c(s.Gx*s.Gy)),h.ZERO=new h(ce,rt,rt,ce),h.Fp=n,h.Fn=o;let E=new ze(h,o.BITS);return h.BASE.precompute(8),h}var sn=class{constructor(t){this.ep=t}static fromBytes(t){Ho()}static fromHex(t){Ho()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(t){return this.ep.toAffine(t)}toHex(){return At(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(t){return this.assertSame(t),this.init(this.ep.add(t.ep))}subtract(t){return this.assertSame(t),this.init(this.ep.subtract(t.ep))}multiply(t){return this.init(this.ep.multiply(t))}multiplyUnsafe(t){return this.init(this.ep.multiplyUnsafe(t))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(t,e){return this.init(this.ep.precompute(t,e))}toRawBytes(){return this.toBytes()}};function Ff(r,t,e={}){if(typeof t!="function")throw new Error('"hash" function param is required');ae(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||Me,c=e.adjustScalarBytes||(w=>w),u=e.domain||((w,C,k)=>{if(Ht(k,"phflag"),C.length||k)throw new Error("Contexts/pre-hash are not supported");return w});function d(w){return i.create($t(w))}function l(w){let C=x.secretKey;w=q("private key",w,C);let k=q("hashed private key",t(w),2*C),T=c(k.slice(0,C)),b=k.slice(C,2*C),m=d(T);return{head:T,prefix:b,scalar:m}}function f(w){let{head:C,prefix:k,scalar:T}=l(w),b=o.multiply(T),m=b.toBytes();return{head:C,prefix:k,scalar:T,point:b,pointBytes:m}}function p(w){return f(w).pointBytes}function h(w=Uint8Array.of(),...C){let k=lt(...C);return d(t(u(k,q("context",w),!!n)))}function E(w,C,k={}){w=q("message",w),n&&(w=n(w));let{prefix:T,scalar:b,pointBytes:m}=f(C),g=h(k.context,T,w),S=o.multiply(g).toBytes(),A=h(k.context,S,m,w),R=i.create(g+A*b);if(!i.isValid(R))throw new Error("sign failed: invalid s");let I=lt(S,i.toBytes(R));return xt(I,x.signature,"result")}let _={zip215:!0};function y(w,C,k,T=_){let{context:b,zip215:m}=T,g=x.signature;w=q("signature",w,g),C=q("message",C),k=q("publicKey",k,x.publicKey),m!==void 0&&Ht(m,"zip215"),n&&(C=n(C));let S=g/2,A=w.subarray(0,S),R=$t(w.subarray(S,g)),I,B,P;try{I=r.fromBytes(k,m),B=r.fromBytes(A,m),P=o.multiplyUnsafe(R)}catch{return!1}if(!m&&I.isSmallOrder())return!1;let N=h(b,B.toBytes(),I.toBytes(),C);return B.add(I.multiplyUnsafe(N)).subtract(P).clearCofactor().is0()}let v=s.BYTES,x={secretKey:v,publicKey:v,signature:2*v,seed:v};function D(w=a(x.seed)){return xt(w,x.seed,"seed")}function L(w){let C=O.randomSecretKey(w);return{secretKey:C,publicKey:p(C)}}function M(w){return qt(w)&&w.length===i.BYTES}function U(w,C){try{return!!r.fromBytes(w,C)}catch{return!1}}let O={getExtendedPublicKey:f,randomSecretKey:D,isValidSecretKey:M,isValidPublicKey:U,toMontgomery(w){let{y:C}=r.fromBytes(w),k=x.publicKey,T=k===32;if(!T&&k!==57)throw new Error("only defined for 25519 and 448");let b=T?s.div(rt+C,rt-C):s.div(C-rt,C+rt);return s.toBytes(b)},toMontgomeryPriv(w){let C=x.secretKey;xt(w,C);let k=t(w.subarray(0,C));return c(k).subarray(0,C)},randomPrivateKey:D,precompute(w=8,C=r.BASE){return C.precompute(w,!1)}};return Object.freeze({keygen:L,getPublicKey:p,sign:E,verify:y,utils:O,Point:r,lengths:x})}function qf(r){let t={a:r.a,d:r.d,p:r.Fp.ORDER,n:r.n,h:r.h,Gx:r.Gx,Gy:r.Gy},e=r.Fp,n=wt(t.n,r.nBitLength,!0),o={Fp:e,Fn:n,uvRatio:r.uvRatio},s={randomBytes:r.randomBytes,adjustScalarBytes:r.adjustScalarBytes,domain:r.domain,prehash:r.prehash,mapToCurve:r.mapToCurve};return{CURVE:t,curveOpts:o,hash:r.hash,eddsaOpts:s}}function zf(r,t){let e=t.Point;return Object.assign({},t,{ExtendedPoint:e,CURVE:r,nBitLength:e.Fn.BITS,nByteLength:e.Fn.BYTES})}function _a(r){let{CURVE:t,curveOpts:e,hash:n,eddsaOpts:o}=qf(r),s=Kf(t,e),i=Ff(s,n,o);return zf(r,i)}var Vf=BigInt(0),Xt=BigInt(1),Sa=BigInt(2),b0=BigInt(3),Hf=BigInt(5),$f=BigInt(8),He=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),vr={p:He,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:$f,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Gf(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),s=He,a=r*r%s*r%s,c=$(a,Sa,s)*a%s,u=$(c,Xt,s)*r%s,d=$(u,Hf,s)*u%s,l=$(d,t,s)*d%s,f=$(l,e,s)*l%s,p=$(f,n,s)*f%s,h=$(p,o,s)*p%s,E=$(h,o,s)*p%s,_=$(E,t,s)*d%s;return{pow_p_5_8:$(_,Sa,s)*r%s,b2:a}}function Zf(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var Jo=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function rs(r,t){let e=He,n=Y(t*t*t,e),o=Y(n*n*t,e),s=Gf(r*o).pow_p_5_8,i=Y(r*n*s,e),a=Y(t*i*i,e),c=i,u=Y(i*Jo,e),d=a===r,l=a===Y(-r,e),f=a===Y(-r*Jo,e);return d&&(i=c),(l||f)&&(i=u),Gt(i,e)&&(i=Y(-i,e)),{isValid:d||l,value:i}}var ue=wt(vr.p,{isLE:!0}),Xf=wt(vr.n,{isLE:!0}),jf={...vr,Fp:ue,hash:ea,adjustScalarBytes:Zf,uvRatio:rs},jt=_a(jf);var ts=Jo,Wf=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Yf=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),Qf=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),Jf=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),va=r=>rs(Xt,r),tl=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),es=r=>jt.Point.Fp.create($t(r)&tl);function Aa(r){let{d:t}=vr,e=He,n=y=>ue.create(y),o=n(ts*r*r),s=n((o+Xt)*Qf),i=BigInt(-1),a=n((i-t*o)*n(o+t)),{isValid:c,value:u}=rs(s,a),d=n(u*r);Gt(d,e)||(d=n(-d)),c||(u=d),c||(i=o);let l=n(i*(o-Xt)*Jf-a),f=u*u,p=n((u+u)*a),h=n(l*Wf),E=n(Xt-f),_=n(Xt+f);return new jt.Point(n(p*_),n(E*h),n(h*_),n(p*E))}function el(r){mt(r,64);let t=es(r.subarray(0,32)),e=Aa(t),n=es(r.subarray(32,64)),o=Aa(n);return new Wt(e.add(o))}var Wt=class r extends sn{constructor(t){super(t)}static fromAffine(t){return new r(jt.Point.fromAffine(t))}assertSame(t){if(!(t instanceof r))throw new Error("RistrettoPoint expected")}init(t){return new r(t)}static hashToCurve(t){return el(q("ristrettoHash",t,64))}static fromBytes(t){mt(t,32);let{a:e,d:n}=vr,o=He,s=D=>ue.create(D),i=es(t);if(!na(ue.toBytes(i),t)||Gt(i,o))throw new Error("invalid ristretto255 encoding 1");let a=s(i*i),c=s(Xt+e*a),u=s(Xt-e*a),d=s(c*c),l=s(u*u),f=s(e*n*d-l),{isValid:p,value:h}=va(s(f*l)),E=s(h*u),_=s(h*E*f),y=s((i+i)*E);Gt(y,o)&&(y=s(-y));let v=s(c*_),x=s(y*v);if(!p||Gt(x,o)||v===Vf)throw new Error("invalid ristretto255 encoding 2");return new r(new jt.Point(y,v,Xt,x))}static fromHex(t){return r.fromBytes(q("ristrettoHex",t,32))}static msm(t,e){return Ve(r,jt.Point.Fn,t,e)}toBytes(){let{X:t,Y:e,Z:n,T:o}=this.ep,s=He,i=_=>ue.create(_),a=i(i(n+e)*i(n-e)),c=i(t*e),u=i(c*c),{value:d}=va(i(a*u)),l=i(d*a),f=i(d*c),p=i(l*f*o),h;if(Gt(o*p,s)){let _=i(e*ts),y=i(t*ts);t=_,e=y,h=i(l*Yf)}else h=f;Gt(t*p,s)&&(e=i(-e));let E=i((n-e)*h);return Gt(E,s)&&(E=i(-E)),ue.toBytes(E)}equals(t){this.assertSame(t);let{X:e,Y:n}=this.ep,{X:o,Y:s}=t.ep,i=u=>ue.create(u),a=i(e*s)===i(n*o),c=i(n*s)===i(e*o);return a||c}is0(){return this.equals(r.ZERO)}};Wt.BASE=new Wt(jt.Point.BASE);Wt.ZERO=new Wt(jt.Point.ZERO);Wt.Fp=ue;Wt.Fn=Xf;var Ar=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},an=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var Ia={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new an("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 cn=Ia;var un=32;var ns,rl=(async()=>{try{return await cn.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function nl(r,t,e){if(r.buffer instanceof ArrayBuffer){let n=await cn.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await cn.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 ol(r,t,e){return jt.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}async function Ba(r,t,e){return ns==null&&(ns=await rl),ns?nl(r,t,e):ol(r,t,e)}function fn(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var ln=class{type="Ed25519";raw;constructor(t){this.raw=os(t,un)}toMultihash(){return Ct.digest(ke(this))}toCID(){return tt.createV1(114,this.toMultihash())}toString(){return G.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:ft(this.raw,t.raw)}verify(t,e,n){n?.signal?.throwIfAborted();let o=Ba(this.raw,e,t);return fn(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function Ca(r){return r=os(r,un),new ln(r)}function os(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new Ut(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}var il=Math.pow(2,7),al=Math.pow(2,14),cl=Math.pow(2,21),ss=Math.pow(2,28),is=Math.pow(2,35),as=Math.pow(2,42),cs=Math.pow(2,49),F=128,at=127;function gt(r){if(r<il)return 1;if(r<al)return 2;if(r<cl)return 3;if(r<ss)return 4;if(r<is)return 5;if(r<as)return 6;if(r<cs)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function $e(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 ul(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 us(r,t){let e=r[t],n=0;if(n+=e&at,e<F||(e=r[t+1],n+=(e&at)<<7,e<F)||(e=r[t+2],n+=(e&at)<<14,e<F)||(e=r[t+3],n+=(e&at)<<21,e<F)||(e=r[t+4],n+=(e&at)*ss,e<F)||(e=r[t+5],n+=(e&at)*is,e<F)||(e=r[t+6],n+=(e&at)*as,e<F)||(e=r[t+7],n+=(e&at)*cs,e<F))return n;throw new RangeError("Could not decode varint")}function fl(r,t){let e=r.get(t),n=0;if(n+=e&at,e<F||(e=r.get(t+1),n+=(e&at)<<7,e<F)||(e=r.get(t+2),n+=(e&at)<<14,e<F)||(e=r.get(t+3),n+=(e&at)<<21,e<F)||(e=r.get(t+4),n+=(e&at)*ss,e<F)||(e=r.get(t+5),n+=(e&at)*is,e<F)||(e=r.get(t+6),n+=(e&at)*as,e<F)||(e=r.get(t+7),n+=(e&at)*cs,e<F))return n;throw new RangeError("Could not decode varint")}function Ta(r,t,e=0){return t==null&&(t=pt(gt(r))),t instanceof Uint8Array?$e(r,t,e):ul(r,t,e)}function Ir(r,t=0){return r instanceof Uint8Array?us(r,t):fl(r,t)}var fs=new Float32Array([-0]),fe=new Uint8Array(fs.buffer);function La(r,t,e){fs[0]=r,t[e]=fe[0],t[e+1]=fe[1],t[e+2]=fe[2],t[e+3]=fe[3]}function Pa(r,t){return fe[0]=r[t],fe[1]=r[t+1],fe[2]=r[t+2],fe[3]=r[t+3],fs[0]}var ls=new Float64Array([-0]),ct=new Uint8Array(ls.buffer);function Oa(r,t,e){ls[0]=r,t[e]=ct[0],t[e+1]=ct[1],t[e+2]=ct[2],t[e+3]=ct[3],t[e+4]=ct[4],t[e+5]=ct[5],t[e+6]=ct[6],t[e+7]=ct[7]}function ka(r,t){return ct[0]=r[t],ct[1]=r[t+1],ct[2]=r[t+2],ct[3]=r[t+3],ct[4]=r[t+4],ct[5]=r[t+5],ct[6]=r[t+6],ct[7]=r[t+7],ls[0]}var ll=BigInt(Number.MAX_SAFE_INTEGER),dl=BigInt(Number.MIN_SAFE_INTEGER),Et=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 Ee;if(t<ll&&t>dl)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>Na&&(o=0n,++n>Na&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return Ee;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):Ee}},Ee=new Et(0,0);Ee.toBigInt=function(){return 0n};Ee.zzEncode=Ee.zzDecode=function(){return this};Ee.length=function(){return 1};var Na=4294967296n;function Ua(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 Ma(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 ds(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 Rt(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function dn(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var hs=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,Rt(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 Rt(this,4);return dn(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Rt(this,4);return dn(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Rt(this,4);let t=Pa(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw Rt(this,4);let t=ka(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 Rt(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return Ma(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw Rt(this,t);this.pos+=t}else do if(this.pos>=this.len)throw Rt(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 Et(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 Rt(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 Rt(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 Rt(this,8);let t=dn(this.buf,this.pos+=4),e=dn(this.buf,this.pos+=4);return new Et(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=us(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 ps(r){return new hs(r instanceof Uint8Array?r:r.subarray())}function It(r,t,e){let n=ps(r);return t.decode(n,void 0,e)}function ms(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 _e=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function gs(){}var bs=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},hl=ms();function pl(r){return globalThis.Buffer!=null?pt(r):hl(r)}var Dr=class{len;head;tail;states;constructor(){this.len=0,this.head=new _e(gs,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new _e(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new xs((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(hn,10,Et.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=Et.fromBigInt(t);return this._push(hn,e.length(),e)}uint64Number(t){return this._push($e,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=Et.fromBigInt(t).zzEncode();return this._push(hn,e.length(),e)}sint64Number(t){let e=Et.fromNumber(t).zzEncode();return this._push(hn,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(ys,1,t?1:0)}fixed32(t){return this._push(Br,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=Et.fromBigInt(t);return this._push(Br,4,e.lo)._push(Br,4,e.hi)}fixed64Number(t){let e=Et.fromNumber(t);return this._push(Br,4,e.lo)._push(Br,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(La,4,t)}double(t){return this._push(Oa,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(ys,1,0):this.uint32(e)._push(gl,e,t)}string(t){let e=Ua(t);return e!==0?this.uint32(e)._push(ds,e,t):this._push(ys,1,0)}fork(){return this.states=new bs(this),this.head=this.tail=new _e(gs,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 _e(gs,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=pl(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function ys(r,t,e){t[e]=r&255}function ml(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var xs=class extends _e{next;constructor(t,e){super(ml,t,e),this.next=void 0}};function hn(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 Br(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 gl(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(Dr.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(yl,t,r),this},Dr.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(bl,t,r),this});function yl(r,t,e){t.set(r,e)}function bl(r,t,e){r.length<40?ds(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(V(r),e)}function ws(){return new Dr}function Bt(r,t){let e=ws();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var Ge;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(Ge||(Ge={}));function pn(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function Se(r){function t(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let e=function(s,i){let a=t(s);i.int32(a)},n=function(s){let i=s.int32();return t(i)};return pn("enum",Ge.VARINT,e,n)}function Dt(r,t){return pn("message",Ge.LENGTH_DELIMITED,r,t)}var mn=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var _t;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(_t||(_t={}));var Es;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(Es||(Es={}));(function(r){r.codec=()=>Se(Es)})(_t||(_t={}));var Cr;(function(r){let t;r.codec=()=>(t==null&&(t=Dt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),_t.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.Type=_t.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Bt(e,r.codec()),r.decode=(e,n)=>It(e,r.codec(),n)})(Cr||(Cr={}));var _s;(function(r){let t;r.codec=()=>(t==null&&(t=Dt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),_t.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.Type=_t.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Bt(e,r.codec()),r.decode=(e,n)=>It(e,r.codec(),n)})(_s||(_s={}));var gn=class extends Ne{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,Qr(t);let n=gr(e);if(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 o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?t.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=t.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),zt(s)}update(t){return Ue(this),this.iHash.update(t),this}digestInto(t){Ue(this),mt(t,this.outputLen),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||(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()}},Ss=(r,t,e)=>new gn(r,t).update(e).digest();Ss.create=(r,t)=>new gn(r,t);var Fa=(r,t)=>(r+(r>=0?t:-t)/qa)/t;function wl(r,t,e){let[[n,o],[s,i]]=t,a=Fa(i*r,e),c=Fa(-o*r,e),u=r-a*n-c*s,d=-a*o-c*i,l=u<Qt,f=d<Qt;l&&(u=-u),f&&(d=-d);let p=ie(Math.ceil(rn(e)/2))+Xe;if(u<Qt||u>=p||d<Qt||d>=p)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:l,k1:u,k2neg:f,k2:d}}function As(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function vs(r,t){let e={};for(let n of Object.keys(t))e[n]=r[n]===void 0?t[n]:r[n];return Ht(e.lowS,"lowS"),Ht(e.prehash,"prehash"),e.format!==void 0&&As(e.format),e}var Is=class extends Error{constructor(t=""){super(t)}},Yt={Err:Is,_tlv:{encode:(r,t)=>{let{Err:e}=Yt;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=wr(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let s=n>127?wr(o.length/2|128):"";return wr(r)+s+o+t},decode(r,t){let{Err:e}=Yt,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 d of u)i=i<<8|d;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}=Yt;if(r<Qt)throw new t("integer: negative integers are not allowed");let e=wr(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}=Yt;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 Ke(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=Yt,o=q("signature",r),{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:d}=n.decode(2,c);if(d.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}=Yt,n=t.encode(2,e.encode(r.r)),o=t.encode(2,e.encode(r.s)),s=n+o;return t.encode(48,s)}},Qt=BigInt(0),Xe=BigInt(1),qa=BigInt(2),yn=BigInt(3),El=BigInt(4);function Ze(r,t){let{BYTES:e}=r,n;if(typeof t=="bigint")n=t;else{let o=q("private key",t);try{n=r.fromBytes(o)}catch{throw new Error(`invalid private key: expected ui8a of size ${e}, got ${typeof t}`)}}if(!r.isValidNot0(n))throw new Error("invalid private key: out of range [1..N-1]");return n}function _l(r,t={}){let e=on("weierstrass",r,t),{Fp:n,Fn:o}=e,s=e.CURVE,{h:i,n:a}=s;ae(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});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=Va(n,o);function d(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function l(T,b,m){let{x:g,y:S}=b.toAffine(),A=n.toBytes(g);if(Ht(m,"isCompressed"),m){d();let R=!n.isOdd(S);return lt(za(R),A)}else return lt(Uint8Array.of(4),A,n.toBytes(S))}function f(T){xt(T,void 0,"Point");let{publicKey:b,publicKeyUncompressed:m}=u,g=T.length,S=T[0],A=T.subarray(1);if(g===b&&(S===2||S===3)){let R=n.fromBytes(A);if(!n.isValid(R))throw new Error("bad point: is not on curve, wrong x");let I=E(R),B;try{B=n.sqrt(I)}catch(Z){let z=Z instanceof Error?": "+Z.message:"";throw new Error("bad point: is not on curve, sqrt error"+z)}d();let P=n.isOdd(B);return(S&1)===1!==P&&(B=n.neg(B)),{x:R,y:B}}else if(g===m&&S===4){let R=n.BYTES,I=n.fromBytes(A.subarray(0,R)),B=n.fromBytes(A.subarray(R,R*2));if(!_(I,B))throw new Error("bad point: is not on curve");return{x:I,y:B}}else throw new Error(`bad point: got length ${g}, expected compressed=${b} or uncompressed=${m}`)}let p=t.toBytes||l,h=t.fromBytes||f;function E(T){let b=n.sqr(T),m=n.mul(b,T);return n.add(n.add(m,n.mul(T,s.a)),s.b)}function _(T,b){let m=n.sqr(b),g=E(T);return n.eql(m,g)}if(!_(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let y=n.mul(n.pow(s.a,yn),El),v=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(y,v)))throw new Error("bad curve params: a or b");function x(T,b,m=!1){if(!n.isValid(b)||m&&n.is0(b))throw new Error(`bad point coordinate ${T}`);return b}function D(T){if(!(T instanceof w))throw new Error("ProjectivePoint expected")}function L(T){if(!c||!c.basises)throw new Error("no endo");return wl(T,c.basises,o.ORDER)}let M=Fe((T,b)=>{let{X:m,Y:g,Z:S}=T;if(n.eql(S,n.ONE))return{x:m,y:g};let A=T.is0();b==null&&(b=A?n.ONE:n.inv(S));let R=n.mul(m,b),I=n.mul(g,b),B=n.mul(S,b);if(A)return{x:n.ZERO,y:n.ZERO};if(!n.eql(B,n.ONE))throw new Error("invZ was invalid");return{x:R,y:I}}),U=Fe(T=>{if(T.is0()){if(t.allowInfinityPoint&&!n.is0(T.Y))return;throw new Error("bad point: ZERO")}let{x:b,y:m}=T.toAffine();if(!n.isValid(b)||!n.isValid(m))throw new Error("bad point: x or y not field elements");if(!_(b,m))throw new Error("bad point: equation left != right");if(!T.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function O(T,b,m,g,S){return m=new w(n.mul(m.X,T),m.Y,m.Z),b=Sr(g,b),m=Sr(S,m),b.add(m)}class w{constructor(b,m,g){this.X=x("x",b),this.Y=x("y",m,!0),this.Z=x("z",g),Object.freeze(this)}static CURVE(){return s}static fromAffine(b){let{x:m,y:g}=b||{};if(!b||!n.isValid(m)||!n.isValid(g))throw new Error("invalid affine point");if(b instanceof w)throw new Error("projective point not allowed");return n.is0(m)&&n.is0(g)?w.ZERO:new w(m,g,n.ONE)}static fromBytes(b){let m=w.fromAffine(h(xt(b,void 0,"point")));return m.assertValidity(),m}static fromHex(b){return w.fromBytes(q("pointHex",b))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(b=8,m=!0){return k.createCache(this,b),m||this.multiply(yn),this}assertValidity(){U(this)}hasEvenY(){let{y:b}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(b)}equals(b){D(b);let{X:m,Y:g,Z:S}=this,{X:A,Y:R,Z:I}=b,B=n.eql(n.mul(m,I),n.mul(A,S)),P=n.eql(n.mul(g,I),n.mul(R,S));return B&&P}negate(){return new w(this.X,n.neg(this.Y),this.Z)}double(){let{a:b,b:m}=s,g=n.mul(m,yn),{X:S,Y:A,Z:R}=this,I=n.ZERO,B=n.ZERO,P=n.ZERO,N=n.mul(S,S),Z=n.mul(A,A),z=n.mul(R,R),K=n.mul(S,A);return K=n.add(K,K),P=n.mul(S,R),P=n.add(P,P),I=n.mul(b,P),B=n.mul(g,z),B=n.add(I,B),I=n.sub(Z,B),B=n.add(Z,B),B=n.mul(I,B),I=n.mul(K,I),P=n.mul(g,P),z=n.mul(b,z),K=n.sub(N,z),K=n.mul(b,K),K=n.add(K,P),P=n.add(N,N),N=n.add(P,N),N=n.add(N,z),N=n.mul(N,K),B=n.add(B,N),z=n.mul(A,R),z=n.add(z,z),N=n.mul(z,K),I=n.sub(I,N),P=n.mul(z,Z),P=n.add(P,P),P=n.add(P,P),new w(I,B,P)}add(b){D(b);let{X:m,Y:g,Z:S}=this,{X:A,Y:R,Z:I}=b,B=n.ZERO,P=n.ZERO,N=n.ZERO,Z=s.a,z=n.mul(s.b,yn),K=n.mul(m,A),X=n.mul(g,R),Q=n.mul(S,I),ht=n.add(m,g),j=n.add(A,R);ht=n.mul(ht,j),j=n.add(K,X),ht=n.sub(ht,j),j=n.add(m,S);let it=n.add(A,I);return j=n.mul(j,it),it=n.add(K,Q),j=n.sub(j,it),it=n.add(g,S),B=n.add(R,I),it=n.mul(it,B),B=n.add(X,Q),it=n.sub(it,B),N=n.mul(Z,j),B=n.mul(z,Q),N=n.add(B,N),B=n.sub(X,N),N=n.add(X,N),P=n.mul(B,N),X=n.add(K,K),X=n.add(X,K),Q=n.mul(Z,Q),j=n.mul(z,j),X=n.add(X,Q),Q=n.sub(K,Q),Q=n.mul(Z,Q),j=n.add(j,Q),K=n.mul(X,j),P=n.add(P,K),K=n.mul(it,j),B=n.mul(ht,B),B=n.sub(B,K),K=n.mul(ht,X),N=n.mul(it,N),N=n.add(N,K),new w(B,P,N)}subtract(b){return this.add(b.negate())}is0(){return this.equals(w.ZERO)}multiply(b){let{endo:m}=t;if(!o.isValidNot0(b))throw new Error("invalid scalar: out of range");let g,S,A=R=>k.cached(this,R,I=>Zt(w,I));if(m){let{k1neg:R,k1:I,k2neg:B,k2:P}=L(b),{p:N,f:Z}=A(I),{p:z,f:K}=A(P);S=Z.add(K),g=O(m.beta,N,z,R,B)}else{let{p:R,f:I}=A(b);g=R,S=I}return Zt(w,[g,S])[0]}multiplyUnsafe(b){let{endo:m}=t,g=this;if(!o.isValid(b))throw new Error("invalid scalar: out of range");if(b===Qt||g.is0())return w.ZERO;if(b===Xe)return g;if(k.hasCache(this))return this.multiply(b);if(m){let{k1neg:S,k1:A,k2neg:R,k2:I}=L(b),{p1:B,p2:P}=Ea(w,g,A,I);return O(m.beta,B,P,S,R)}else return k.unsafe(g,b)}multiplyAndAddUnsafe(b,m,g){let S=this.multiplyUnsafe(m).add(b.multiplyUnsafe(g));return S.is0()?void 0:S}toAffine(b){return M(this,b)}isTorsionFree(){let{isTorsionFree:b}=t;return i===Xe?!0:b?b(w,this):k.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:b}=t;return i===Xe?this:b?b(w,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(b=!0){return Ht(b,"isCompressed"),this.assertValidity(),p(w,this,b)}toHex(b=!0){return At(this.toBytes(b))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(b=!0){return this.toBytes(b)}_setWindowSize(b){this.precompute(b)}static normalizeZ(b){return Zt(w,b)}static msm(b,m){return Ve(w,o,b,m)}static fromPrivateKey(b){return w.BASE.multiply(Ze(o,b))}}w.BASE=new w(s.Gx,s.Gy,n.ONE),w.ZERO=new w(n.ZERO,n.ONE,n.ZERO),w.Fp=n,w.Fn=o;let C=o.BITS,k=new ze(w,t.endo?Math.ceil(C/2):C);return w.BASE.precompute(8),w}function za(r){return Uint8Array.of(r?2:3)}function Va(r,t){return{secretKey:t.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function Sl(r,t={}){let{Fn:e}=r,n=t.randomBytes||Me,o=Object.assign(Va(r.Fp,e),{seed:Zo(e.ORDER)});function s(p){try{return!!Ze(e,p)}catch{return!1}}function i(p,h){let{publicKey:E,publicKeyUncompressed:_}=o;try{let y=p.length;return h===!0&&y!==E||h===!1&&y!==_?!1:!!r.fromBytes(p)}catch{return!1}}function a(p=n(o.seed)){return Xo(xt(p,o.seed,"seed"),e.ORDER)}function c(p,h=!0){return r.BASE.multiply(Ze(e,p)).toBytes(h)}function u(p){let h=a(p);return{secretKey:h,publicKey:c(h)}}function d(p){if(typeof p=="bigint")return!1;if(p instanceof r)return!0;let{secretKey:h,publicKey:E,publicKeyUncompressed:_}=o;if(e.allowedLengths||h===E)return;let y=q("key",p).length;return y===E||y===_}function l(p,h,E=!0){if(d(p)===!0)throw new Error("first arg must be private key");if(d(h)===!1)throw new Error("second arg must be public key");let _=Ze(e,p);return r.fromHex(h).multiply(_).toBytes(E)}return Object.freeze({getPublicKey:c,getSharedSecret:l,keygen:u,Point:r,utils:{isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a,isValidPrivateKey:s,randomPrivateKey:a,normPrivateKeyToScalar:p=>Ze(e,p),precompute(p=8,h=r.BASE){return h.precompute(p,!1)}},lengths:o})}function vl(r,t,e={}){Qr(t),ae(e,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let n=e.randomBytes||Me,o=e.hmac||((m,...g)=>Ss(t,m,lt(...g))),{Fp:s,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:u,getPublicKey:d,getSharedSecret:l,utils:f,lengths:p}=Sl(r,e),h={prehash:!1,lowS:typeof e.lowS=="boolean"?e.lowS:!1,format:void 0,extraEntropy:!1},E="compact";function _(m){let g=a>>Xe;return m>g}function y(m,g){if(!i.isValidNot0(g))throw new Error(`invalid signature ${m}: out of range 1..Point.Fn.ORDER`);return g}function v(m,g){As(g);let S=p.signature,A=g==="compact"?S:g==="recovered"?S+1:void 0;return xt(m,A,`${g} signature`)}class x{constructor(g,S,A){this.r=y("r",g),this.s=y("s",S),A!=null&&(this.recovery=A),Object.freeze(this)}static fromBytes(g,S=E){v(g,S);let A;if(S==="der"){let{r:P,s:N}=Yt.toSig(xt(g));return new x(P,N)}S==="recovered"&&(A=g[0],S="compact",g=g.subarray(1));let R=i.BYTES,I=g.subarray(0,R),B=g.subarray(R,R*2);return new x(i.fromBytes(I),i.fromBytes(B),A)}static fromHex(g,S){return this.fromBytes(ge(g),S)}addRecoveryBit(g){return new x(this.r,this.s,g)}recoverPublicKey(g){let S=s.ORDER,{r:A,s:R,recovery:I}=this;if(I==null||![0,1,2,3].includes(I))throw new Error("recovery id invalid");if(a*qa<S&&I>1)throw new Error("recovery id is ambiguous for h>1 curve");let P=I===2||I===3?A+a:A;if(!s.isValid(P))throw new Error("recovery id 2 or 3 invalid");let N=s.toBytes(P),Z=r.fromBytes(lt(za((I&1)===0),N)),z=i.inv(P),K=L(q("msgHash",g)),X=i.create(-K*z),Q=i.create(R*z),ht=r.BASE.multiplyUnsafe(X).add(Z.multiplyUnsafe(Q));if(ht.is0())throw new Error("point at infinify");return ht.assertValidity(),ht}hasHighS(){return _(this.s)}toBytes(g=E){if(As(g),g==="der")return ge(Yt.hexFromSig(this));let S=i.toBytes(this.r),A=i.toBytes(this.s);if(g==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return lt(Uint8Array.of(this.recovery),S,A)}return lt(S,A)}toHex(g){return At(this.toBytes(g))}assertValidity(){}static fromCompact(g){return x.fromBytes(q("sig",g),"compact")}static fromDER(g){return x.fromBytes(q("sig",g),"der")}normalizeS(){return this.hasHighS()?new x(this.r,i.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return At(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return At(this.toBytes("compact"))}}let D=e.bits2int||function(g){if(g.length>8192)throw new Error("input is too large");let S=Ke(g),A=g.length*8-c;return A>0?S>>BigInt(A):S},L=e.bits2int_modN||function(g){return i.create(D(g))},M=ie(c);function U(m){return Er("num < 2^"+c,m,Qt,M),i.toBytes(m)}function O(m,g){return xt(m,void 0,"message"),g?xt(t(m),void 0,"prehashed message"):m}function w(m,g,S){if(["recovered","canonical"].some(X=>X in S))throw new Error("sign() legacy options not supported");let{lowS:A,prehash:R,extraEntropy:I}=vs(S,h);m=O(m,R);let B=L(m),P=Ze(i,g),N=[U(P),U(B)];if(I!=null&&I!==!1){let X=I===!0?n(p.secretKey):I;N.push(q("extraEntropy",X))}let Z=lt(...N),z=B;function K(X){let Q=D(X);if(!i.isValidNot0(Q))return;let ht=i.inv(Q),j=r.BASE.multiply(Q).toAffine(),it=i.create(j.x);if(it===Qt)return;let qr=i.create(ht*i.create(z+it*P));if(qr===Qt)return;let si=(j.x===it?0:2)|Number(j.y&Xe),ii=qr;return A&&_(qr)&&(ii=i.neg(qr),si^=1),new x(it,ii,si)}return{seed:Z,k2sig:K}}function C(m,g,S={}){m=q("message",m);let{seed:A,k2sig:R}=w(m,g,S);return sa(t.outputLen,i.BYTES,o)(A,R)}function k(m){let g,S=typeof m=="string"||qt(m),A=!S&&m!==null&&typeof m=="object"&&typeof m.r=="bigint"&&typeof m.s=="bigint";if(!S&&!A)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(A)g=new x(m.r,m.s);else if(S){try{g=x.fromBytes(q("sig",m),"der")}catch(R){if(!(R instanceof Yt.Err))throw R}if(!g)try{g=x.fromBytes(q("sig",m),"compact")}catch{return!1}}return g||!1}function T(m,g,S,A={}){let{lowS:R,prehash:I,format:B}=vs(A,h);if(S=q("publicKey",S),g=O(q("message",g),I),"strict"in A)throw new Error("options.strict was renamed to lowS");let P=B===void 0?k(m):x.fromBytes(q("sig",m),B);if(P===!1)return!1;try{let N=r.fromBytes(S);if(R&&P.hasHighS())return!1;let{r:Z,s:z}=P,K=L(g),X=i.inv(z),Q=i.create(K*X),ht=i.create(Z*X),j=r.BASE.multiplyUnsafe(Q).add(N.multiplyUnsafe(ht));return j.is0()?!1:i.create(j.x)===Z}catch{return!1}}function b(m,g,S={}){let{prehash:A}=vs(S,h);return g=O(g,A),x.fromBytes(m,"recovered").recoverPublicKey(g).toBytes()}return Object.freeze({keygen:u,getPublicKey:d,getSharedSecret:l,utils:f,lengths:p,Point:r,sign:C,verify:T,recoverPublicKey:b,Signature:x,hash:t})}function Al(r){let t={a:r.a,b:r.b,p:r.Fp.ORDER,n:r.n,h:r.h,Gx:r.Gx,Gy:r.Gy},e=r.Fp,n=r.allowedPrivateKeyLengths?Array.from(new Set(r.allowedPrivateKeyLengths.map(i=>Math.ceil(i/2)))):void 0,o=wt(t.n,{BITS:r.nBitLength,allowedLengths:n,modFromBytes:r.wrapPrivateKey}),s={Fp:e,Fn:o,allowInfinityPoint:r.allowInfinityPoint,endo:r.endo,isTorsionFree:r.isTorsionFree,clearCofactor:r.clearCofactor,fromBytes:r.fromBytes,toBytes:r.toBytes};return{CURVE:t,curveOpts:s}}function Il(r){let{CURVE:t,curveOpts:e}=Al(r),n={hmac:r.hmac,randomBytes:r.randomBytes,lowS:r.lowS,bits2int:r.bits2int,bits2int_modN:r.bits2int_modN};return{CURVE:t,curveOpts:e,hash:r.hash,ecdsaOpts:n}}function Bl(r,t){let e=t.Point;return Object.assign({},t,{ProjectivePoint:e,CURVE:Object.assign({},r,nn(e.Fn.ORDER,e.Fn.BITS))})}function Ha(r){let{CURVE:t,curveOpts:e,hash:n,ecdsaOpts:o}=Il(r),s=_l(t,e),i=vl(s,n,o);return Bl(r,i)}function $a(r,t){let e=n=>Ha({...r,hash:n});return{...e(t),create:e}}var Ds={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Dl={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Ga=BigInt(2);function Cl(r){let t=Ds.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,d=u*u*r%t,l=$(d,e,t)*d%t,f=$(l,e,t)*d%t,p=$(f,Ga,t)*u%t,h=$(p,o,t)*p%t,E=$(h,s,t)*h%t,_=$(E,a,t)*E%t,y=$(_,c,t)*_%t,v=$(y,a,t)*E%t,x=$(v,e,t)*d%t,D=$(x,i,t)*h%t,L=$(D,n,t)*u%t,M=$(L,Ga,t);if(!Bs.eql(Bs.sqr(M),r))throw new Error("Cannot find square root");return M}var Bs=wt(Ds.p,{sqrt:Cl}),je=$a({...Ds,Fp:Bs,lowS:!0,endo:Dl},ta);function Za(r,t,e,n){let o=lr.digest(e instanceof Uint8Array?e:e.subarray());if(fn(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),je.verify(t,s,r))).catch(s=>{throw s.name==="AbortError"?s:new Ar(String(s))});try{return n?.signal?.throwIfAborted(),je.verify(t,o.digest,r)}catch(s){throw new Ar(String(s))}}var bn=class{type="secp256k1";raw;_key;constructor(t){this._key=ja(t),this.raw=Xa(this._key)}toMultihash(){return Ct.digest(ke(this))}toCID(){return tt.createV1(114,this.toMultihash())}toString(){return G.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:ft(this.raw,t.raw)}verify(t,e,n){return Za(this._key,e,t,n)}};function Wa(r){return new bn(r)}function Xa(r){return je.ProjectivePoint.fromHex(r).toRawBytes(!0)}function ja(r){try{return je.ProjectivePoint.fromHex(r),r}catch(t){throw new Vr(String(t))}}function Ya(r){let{Type:t,Data:e}=Cr.decode(r.digest),n=e??new Uint8Array;switch(t){case _t.Ed25519:return Ca(n);case _t.secp256k1:return Wa(n);case _t.ECDSA:return Ui(n);default:throw new sr}}function ke(r){return Cr.encode({Type:_t[r.type],Data:r.raw})}var Qa=Symbol.for("nodejs.util.inspect.custom"),Tl=114,Tr=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()})`}[no]=!0;toString(){return this.string==null&&(this.string=G.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return tt.createV1(Tl,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return ft(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return ft(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[Qa](){return`PeerId(${this.toString()})`}},xn=class extends Tr{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},wn=class extends Tr{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},En=class extends Tr{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},Rl=2336,_n=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=Ct.digest(V(this.url))}[Qa](){return`PeerId(${this.url})`}[no]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return tt.createV1(Rl,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=H(t)),t.toString()===this.toString())}};function Ja(r){if(Pl(r))return new xn({multihash:r});if(Ll(r))try{let t=Ya(r);if(t.type==="Ed25519")return new wn({multihash:r,publicKey:t});if(t.type==="secp256k1")return new En({multihash:r,publicKey:t})}catch{let e=H(r.digest);return new _n(new URL(e))}throw new Hr("Supplied PeerID Multihash is invalid")}function Ll(r){return r.code===Ct.code}function Pl(r){return r.code===lr.code}function Cs(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 Sn(r){let t=ur(G.decode(`z${r}`));return Ja(t)}var vn=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 Cs(this.set.entries(),t=>{let e=Sn(t[0]);return[e,e]})}forEach(t){this.set.forEach(e=>{let n=Sn(e);t(n,n,this)})}has(t){return this.set.has(t.toString())}values(){return Cs(this.set.values(),t=>Sn(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 Ts(){return new vn}var Rs={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},tc={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},ec=new globalThis.TextEncoder;function Ol(r,t){let e=Rs[t],n=tc[t];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(t,n*e);return n}function kl(r,t,e){if(e.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Rs[t],o=tc[t],s=r;for(;s.length>0;){let i=ec.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 Ls(r,{size:t=32,utf8Buffer:e}={}){if(!Rs[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 kl(r,t,e);r=ec.encode(r)}return Ol(r,t)}var Rr={hash:r=>Number(Ls(r,{size:32})),hashV:(r,t)=>Nl(Rr.hash(r,t))};function Nl(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),V(t,"base16")}var Ps=64,Lt=class{fp;h;seed;constructor(t,e,n,o=2){if(o>Ps)throw new TypeError("Invalid Fingerprint Size");let s=e.hashV(t,n),i=bt(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?ft(this.fp,t.fp):!1}};function ve(r,t){return Math.floor(Math.random()*(t-r))+r}var Ae=class{contents;constructor(t){this.contents=new Array(t).fill(null)}has(t){if(!(t instanceof Lt))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof Lt))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 Lt))throw new TypeError("Invalid Fingerprint");let e=ve(0,this.contents.length-1),n=this.contents[e];return this.contents[e]=t,n}remove(t){if(!(t instanceof Lt))throw new TypeError("Invalid Fingerprint");let e=this.contents.findIndex(n=>t.equals(n));return e>-1?(this.contents[e]=null,!0):!1}};var Ul=500,Lr=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??Rr,this.seed=t.seed??ve(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=V(t));let e=new Lt(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 Ae(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new Ae(this.bucketSize)),this.buckets[n].add(e)||this.buckets[o].add(e))return this.count++,!0;let s=[n,o],i=s[ve(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new Ae(this.bucketSize));for(let a=0;a<Ul;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 Ae(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(t){typeof t=="string"&&(t=V(t));let e=new Lt(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=V(t));let e=new Lt(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}},Ml={1:.5,2:.84,4:.95,8:.98};function Kl(r=.001){return r>.002?2:r>1e-5?4:8}function rc(r,t=.001){let e=Kl(t),n=Ml[e],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),Ps);return{filterSize:o,bucketSize:e,fingerprintSize:s}}var An=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??Rr,this.seed=t.seed??ve(0,Math.pow(2,10)),this.filterSeries=[new Lr({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(t){if(typeof t=="string"&&(t=V(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 Lr({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=V(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=V(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 Os(r,t=.001,e){return new An({...rc(r,t),...e??{}})}var In=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 d=this.readAtomically(()=>{let l=this.readChar();if(l===void 0)return;let f=Number.parseInt(l,t);if(!Number.isNaN(f))return f});if(d===void 0)break;if(s*=t,s+=d,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 nc=45,Fl=15,We=new In;function Bn(r){if(!(r.length>Fl))return We.new(r).parseWith(()=>We.readIPv4Addr())}function Dn(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>nc))return We.new(r).parseWith(()=>We.readIPv6Addr())}function Ye(r,t=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>nc)return;let e=We.new(r).parseWith(()=>We.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 oc(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 sc(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 ks(r){switch(r.length){case Ie:return r.join(".");case Be:{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 ic(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 ac(r){let t="0x";for(let e of r)t+=(e>>4).toString(16)+(e&15).toString(16);return t}var Ie=4,Be=16,Sy=parseInt("0xFFFF",16),ql=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Pr(r,t){t.length===Be&&r.length===Ie&&oc(t,0,11)&&(t=t.slice(12)),t.length===Ie&&r.length===Be&&sc(r,ql,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 cc(r,t){if(typeof t=="string"&&(t=Ye(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 Ns(r){let[t,e]=r.split("/");if(!t||!e)throw new Error("Failed to parse given CIDR: "+r);let n=Ie,o=Bn(t);if(o==null&&(n=Be,o=Dn(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=Us(s,8*n);return{network:Pr(o,i),mask:i}}function Us(r,t){if(t!==8*Ie&&t!==8*Be)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 Qe=class{constructor(t,e){if(e==null)({network:this.network,mask:this.mask}=Ns(t));else{let n=Ye(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=Ye(e);if(s==null)throw new Error("Failed to parse mask");this.mask=s}else this.mask=Us(o,8*n.length);this.network=Pr(n,this.mask)}}contains(t){return cc({network:this.network,mask:this.mask},t)}toString(){let t=ic(this.mask),e=t!==-1?String(t):ac(this.mask);return ks(this.network)+"/"+e}};function uc(r,t){return new Qe(r).contains(t)}var st=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Jt=class extends Error{static name="ValidationError";name="ValidationError"},Or=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Cn=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function Je(r){return!!Bn(r)}function Tn(r){return!!Dn(r)}function Ks(r){return t=>H(t,r)}function Fs(r){return t=>V(t,r)}function tr(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function De(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(t)}function fc(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=V(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=De(n);return Kt([e,o],e.length+o.length)}function lc(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=re.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=De(n);return Kt([e,o],e.length+o.length)}function qs(r){let t=r.subarray(0,r.length-2),e=r.subarray(r.length-2),n=H(t,"base32"),o=tr(e);return`${n}:${o}`}var zs=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 st("Invalid byte value in IP address");t[n]=o}),t},dc=function(r){let t=0;r=r.toString().trim();let e=r.split(":",8),n;for(n=0;n<e.length;n++){let s=Je(e[n]),i;s&&(i=zs(e[n]),e[n]=H(i.subarray(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,H(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 st("Invalid byte value in IP address");o[t++]=s>>8&255,o[t++]=s&255}return o},hc=function(r){if(r.byteLength!==4)throw new st("IPv4 address was incorrect length");let t=[];for(let e=0;e<r.byteLength;e++)t.push(r[e]);return t.join(".")},pc=function(r){if(r.byteLength!==16)throw new st("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 st(`Invalid IPv6 address "${e}"`)}};function mc(r){try{let t=new URL(`http://[${r}]`);return t.hostname.substring(1,t.hostname.length-1)}catch{throw new st(`Invalid IPv6 address "${r}"`)}}var Ms=Object.values(dr).map(r=>r.decoder),zl=function(){let r=Ms[0].or(Ms[1]);return Ms.slice(2).forEach(t=>r=r.or(t)),r}();function gc(r){return zl.decode(r)}function yc(r){return t=>r.encoder.encode(t)}function Vl(r){if(parseInt(r).toString()!==r)throw new Jt("Value must be an integer")}function Hl(r){if(r<0)throw new Jt("Value must be a positive integer, or zero")}function $l(r){return t=>{if(t>r)throw new Jt(`Value must be smaller than or equal to ${r}`)}}function Gl(...r){return t=>{for(let e of r)e(t)}}var kr=Gl(Vl,Hl,$l(65535));var nt=-1,Vs=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 Cn(`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)}))}},St=new Vs,_d=[{code:4,name:"ip4",size:32,valueToBytes:zs,bytesToValue:hc,validate:r=>{if(!Je(r))throw new Jt(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:De,bytesToValue:tr,validate:kr},{code:273,name:"udp",size:16,valueToBytes:De,bytesToValue:tr,validate:kr},{code:33,name:"dccp",size:16,valueToBytes:De,bytesToValue:tr,validate:kr},{code:41,name:"ip6",size:128,valueToBytes:dc,bytesToValue:pc,stringToValue:mc,validate:r=>{if(!Tn(r))throw new Jt(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:nt},{code:43,name:"ipcidr",size:8,bytesToValue:Ks("base10"),valueToBytes:Fs("base10")},{code:53,name:"dns",size:nt,resolvable:!0},{code:54,name:"dns4",size:nt,resolvable:!0},{code:55,name:"dns6",size:nt,resolvable:!0},{code:56,name:"dnsaddr",size:nt,resolvable:!0},{code:132,name:"sctp",size:16,valueToBytes:De,bytesToValue:tr,validate:kr},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:nt,path:!0,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:nt,bytesToValue:Ks("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Fs("base58btc")(r):tt.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:qs,valueToBytes:fc},{code:445,name:"onion3",size:296,bytesToValue:qs,valueToBytes:lc},{code:446,name:"garlic64",size:nt},{code:447,name:"garlic32",size:nt},{code:448,name:"tls"},{code:449,name:"sni",size:nt},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:nt,bytesToValue:yc(xo),valueToBytes:gc},{code:480,name:"http"},{code:481,name:"http-path",size:nt,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:nt}];_d.forEach(r=>{St.addProtocol(r)});function bc(r){let t=[],e=0;for(;e<r.length;){let n=Ir(r,e),o=St.getProtocol(n),s=gt(n),i=Sd(o,r,e+s),a=0;i>0&&o.size===nt&&(a=gt(i));let c=s+a+i,u={code:n,name:o.name,bytes:r.subarray(e,e+c)};if(i>0){let d=e+s+a,l=r.subarray(d,d+i);u.value=o.bytesToValue?.(l)??H(l)}t.push(u),e+=c}return t}function xc(r){let t=0,e=[];for(let n of r){if(n.bytes==null){let o=St.getProtocol(n.code),s=gt(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??V(n.value),a=i.byteLength,o.size===nt&&(c=gt(a)));let u=new Uint8Array(s+c+a),d=0;$e(n.code,u,d),d+=s,i!=null&&(o.size===nt&&($e(a,u,d),d+=c),u.set(i,d)),n.bytes=u}e.push(n.bytes),t+=n.bytes.byteLength}return Kt(e,t)}function wc(r){if(r.charAt(0)!=="/")throw new st('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=St.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 st(`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 st(`Component ${o} was missing value`);u.value=c.stringToValue?.(n)??n}t.push(u),n="",o="",e="protocol"}}}if(o!==""&&n!=="")throw new st("Incomplete multiaddr");return t}function Ec(r){return`/${r.flatMap(t=>{if(t.value==null)return t.name;let e=St.getProtocol(t.code);if(e==null)throw new st(`Unknown protocol code ${t.code}`);return[t.name,e.valueToString?.(t.value)??t.value]}).join("/")}`}function Sd(r,t,e){return r.size==null||r.size===0?0:r.size>0?r.size/8:Ir(t,e)}var vd=Symbol.for("nodejs.util.inspect.custom"),Ws=Symbol.for("@multiformats/multiaddr"),Ad=[53,54,55,56],js=class extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}};function Id(r){if(r==null&&(r="/"),Sc(r))return r.getComponents();if(r instanceof Uint8Array)return bc(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),wc(r);if(Array.isArray(r))return r;throw new st("Must be a string, Uint8Array, Component[], or another Multiaddr")}var On=class r{[Ws]=!0;#t;#e;#r;constructor(t="/",e={}){this.#t=Id(t),e.validate!==!1&&Bd(this)}get bytes(){return this.#r==null&&(this.#r=xc(this.#t)),this.#r}toString(){return this.#e==null&&(this.#e=Ec(this.#t)),this.#e}toJSON(){return this.toString()}toOptions(){let t,e,n,o,s="";for(let{code:a,name:c,value:u}of this.#t)a===42&&(s=`%${u??""}`),Ad.includes(a)&&(e="tcp",o=443,n=`${u??""}${s}`,t=a===55?6:4),(a===6||a===273)&&(e=c==="tcp"?"tcp":"udp",o=parseInt(u??"")),(a===4||a===41)&&(e="tcp",n=`${u??""}${s}`,t=a===41?6:4);if(t==null||e==null||n==null||o==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:t,host:n,transport:e,port:o}}getComponents(){return[...this.#t]}protos(){return this.#t.map(({code:t,value:e})=>{let n=St.getProtocol(t);return{code:t,size:n.size??0,name:n.name,resolvable:!!n.resolvable,path:!!n.path}})}protoCodes(){return this.#t.map(({code:t})=>t)}protoNames(){return this.#t.map(({name:t})=>t)}tuples(){return this.#t.map(({code:t,value:e})=>{if(e==null)return[t];let n=St.getProtocol(t),o=[t];return e!=null&&o.push(n.valueToBytes?.(e)??V(e)),o})}stringTuples(){return this.#t.map(({code:t,value:e})=>e==null?[t]:[t,e])}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 Or(`Address ${this.toString()} does not contain subaddress: ${t.toString()}`);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})}getPeerId(){try{let t=[];this.#t.forEach(({code:n,value:o})=>{n===421&&t.push([n,o]),n===290&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?H(G.decode(`z${n}`),"base58btc"):H(tt.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){for(let t of this.#t)if(St.getProtocol(t.code).path)return t.value??null;return null}equals(t){return ft(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(s=>s.resolvable);if(e==null)return[this];let n=_c.get(e.name);if(n==null)throw new js(`no available resolver for ${e.name}`);return(await n(this,t)).map(s=>Ur(s))}nodeAddress(){let t=this.toOptions();if(t.transport!=="tcp"&&t.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${t.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:t.family,address:t.host,port:t.port}}isThinWaistAddress(){return!(this.#t.length!==2||this.#t[0].code!==4&&this.#t[0].code!==41||this.#t[1].code!==6&&this.#t[1].code!==273)}[vd](){return`Multiaddr(${this.toString()})`}};function Bd(r){r.getComponents().forEach(t=>{let e=St.getProtocol(t.code);t.value!=null&&e.validate?.(t.value)})}var _c=new Map;function Sc(r){return!!r?.[Ws]}function Ur(r){return new On(r)}function vc(r){try{for(let{code:t,value:e}of r.getComponents())if(e!=null&&t===41)return uc("2000::/3",e)}catch{}return!1}var Ic=Qc(Ac(),1),Dd=["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"],Cd=Dd.map(r=>new Ic.Netmask(r));function Ys(r){for(let t of Cd)if(t.contains(r))return!0;return!1}function Td(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function Rd(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 Ys(o)}function Ld(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function Pd(r){let t=r.split(":"),e=t[t.length-1];return Ys(e)}function Od(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 kn(r){if(Je(r))return Ys(r);if(Td(r))return Rd(r);if(Ld(r))return Pd(r);if(Tn(r))return Od(r)}function Bc(r){try{for(let{code:t}of r.getComponents())if(t!==42)return t===4||t===41}catch{}return!1}function Dc(r){try{if(!Bc(r))return!1;let[[,t]]=r.stringTuples();return t==null?!1:kn(t)??!1}catch{}return!0}function Ot(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var Nn=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}},er=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new Nn(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 Nn(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 Qs=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function Cc(r={}){return kd(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 kd(r,t){t=t??{};let e=t.onEnd,n=new er,o,s,i,a=Ot(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((_,y)=>{s=v=>{s=null,n.push(v);try{_(r(n))}catch(x){y(x)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Ot()})}},u=_=>s!=null?s(_):(n.push(_),o),d=_=>(n=new er,s!=null?s({error:_}):(n.push({error:_}),o)),l=_=>{if(i)return o;if(t?.objectMode!==!0&&_?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:_})},f=_=>i?o:(i=!0,_!=null?d(_):u({done:!0})),p=()=>(n=new er,f(),{done:!0}),h=_=>(f(_),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:p,throw:h,push:l,end:f,get readableLength(){return n.size},onEmpty:async _=>{let y=_?.signal;if(y?.throwIfAborted(),n.isEmpty())return;let v,x;y!=null&&(v=new Promise((D,L)=>{x=()=>{L(new Qs)},y.addEventListener("abort",x)}));try{await Promise.race([a.promise,v])}finally{x!=null&&y!=null&&y?.removeEventListener("abort",x)}}},e==null)return o;let E=o;return o={[Symbol.asyncIterator](){return this},next(){return E.next()},throw(_){return E.throw(_),e!=null&&(e(_),e=void 0),{done:!0}},return(){return E.return(),e!=null&&(e(),e=void 0),{done:!0}},push:l,end(_){return E.end(_),e!=null&&(e(_),e=void 0),o},get readableLength(){return E.readableLength},onEmpty:_=>E.onEmpty(_)},o}var Un=class extends Error{static name="AbortError";name="AbortError";constructor(t="The operation was aborted",...e){super(t,...e)}};async function Mn(r,t,e,n){let o=new Un(n?.errorMessage);n?.errorCode!=null&&(o.code=n.errorCode);let s=n?.errorEvent??"error";return e?.aborted===!0?Promise.reject(o):new Promise((i,a)=>{function c(){ti(e,"abort",l),ti(r,t,u),ti(r,s,d)}let u=f=>{try{if(n?.filter?.(f)===!1)return}catch(p){c(),a(p);return}c(),i(f)},d=f=>{if(c(),f instanceof Error){a(f);return}a(f.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},l=()=>{c(),a(o)};Js(e,"abort",l),Js(r,t,u),Js(r,s,d)})}function Js(r,t,e){r!=null&&(Tc(r)?r.addEventListener(t,e):r.addListener(t,e))}function ti(r,t,e){r!=null&&(Tc(r)?r.removeEventListener(t,e):r.removeListener(t,e))}function Tc(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}function Kr(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 Kn=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};var Fn=class extends Error{type;code;constructor(t,e,n){super(t??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=e??"ABORT_ERR"}};async function Ce(r,t,e){if(t==null)return r;if(t.aborted)return r.catch(()=>{}),Promise.reject(new Fn(e?.errorMessage,e?.errorCode,e?.errorName));let n,o=new Fn(e?.errorMessage,e?.errorCode,e?.errorName);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},t.addEventListener("abort",n)})])}finally{n!=null&&t.removeEventListener("abort",n)}}var qn=class{deferred;signal;constructor(t){this.signal=t,this.deferred=Ot(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Nt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Nd(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var zn=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=Nd(),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 Nt),this.cleanup())}async join(t={}){let e=new qn(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 Ce(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 Vn=class extends $r{concurrency;maxSize;queue;pending;sort;constructor(t={}){super(),this.concurrency=t.concurrency??Number.POSITIVE_INFINITY,this.maxSize=t.maxSize??Number.POSITIVE_INFINITY,this.pending=0,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=Kr(this.emitEmpty.bind(this),1),this.emitIdle=Kr(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let 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 Kn;let n=new zn(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 Nt)}),this.clear()}async onEmpty(t){this.size!==0&&await Mn(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await Mn(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await Mn(this,"idle",t?.signal)}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=Cc({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 Nt("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()}}};var Hn=class extends Vn{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};function Fr(r){let t=new globalThis.AbortController;function e(){t.abort();for(let s of r)s?.removeEventListener!=null&&s.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}function Rc(r,t,e){let n,o,s=!1;function i(){let u={signal:o.signal};if(e?.timeout!=null){let d=Fr([o.signal,AbortSignal.timeout(e.timeout)]);u.signal=d}s=!0,Promise.resolve().then(async()=>{await r(u)}).catch(()=>{}).finally(()=>{s=!1,!o.signal.aborted&&(n=setTimeout(i,t))})}let a=Kr(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 ei=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 Lc(r){let{name:t,metrics:e}=r,n;return e!=null?n=new ei({name:t,metrics:e}):n=new Map,n}var ri=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=Ot(),this.haveNext=Ot()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let t=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=Ot(),t}async throw(t){return this.ended=!0,this.error=t,t!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(t)),{done:!0,value:void 0}}async return(){let t={done:!0,value:void 0};return this.ended=!0,this.nextResult=t,this.haveNext.resolve(),t}async push(t,e){await this._push(t,e)}async end(t,e){t!=null?await this.throw(t):await this._push(void 0,e)}async _push(t,e){if(t!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;t!=null?this.nextResult={done:!1,value:t}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=Ot(),await Ce(this.readNext.promise,e?.signal,e)}};function Pc(){return new ri}var $n=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Oc(r,t){let e=Pc();r.sink(e).catch(async i=>{await e.end(i)}),r.sink=async i=>{for await(let a of i)await e.push(a);await e.end()};let n=r.source;r.source[Symbol.iterator]!=null?n=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(n=r.source[Symbol.asyncIterator]());let o=new J;return{read:async i=>{if(i?.signal?.throwIfAborted(),i?.bytes==null){let{done:c,value:u}=await Ce(n.next(),i?.signal);return c===!0?null:u}for(;o.byteLength<i.bytes;){let{value:c,done:u}=await Ce(n.next(),i?.signal);if(u===!0)throw new $n("unexpected end of input");o.append(c)}let a=o.sublist(0,i.bytes);return o.consume(i.bytes),a},write:async(i,a)=>{a?.signal?.throwIfAborted(),i instanceof Uint8Array?await e.push(i,a):await e.push(i.subarray(),a)},unwrap:()=>{if(o.byteLength>0){let i=r.source;r.source=async function*(){t?.yieldBytes===!1?yield o:yield*o,yield*i}()}return r}}}var Gn=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Zn=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Xn=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function kc(r,t={}){let e=Oc(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=gt(t.maxDataLength));let n=t?.lengthDecoder??Ir,o=t?.lengthEncoder??Ta;return{read:async i=>{let a=-1,c=new J;for(;;){c.append(await e.read({...i,bytes:1}));try{a=n(c)}catch(u){if(u instanceof RangeError)continue;throw u}if(a<0)throw new Gn("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new Xn("message length length too long");if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new Zn("message length too long");return e.read({...i,bytes:a})},write:async(i,a)=>{await e.write(new J(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new J(...i.flatMap(u=>[o(u.byteLength),u]));await e.write(c,a)},unwrap:()=>e.unwrap()}}function rr(r,t){let e=kc(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 ni="libp2p",oi="autonat";var Nc="dial-request",Uc="dial-back",Mc=200n*1024n,Kc=4096;var nr;(function(r){let t;r.codec=()=>(t==null&&(t=Dt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e={...e},e.dialDataResponse!=null&&(e.dialDataRequest=void 0,e.dialResponse=void 0,e.dialRequest=void 0),e.dialDataRequest!=null&&(e.dialDataResponse=void 0,e.dialResponse=void 0,e.dialRequest=void 0),e.dialResponse!=null&&(e.dialDataResponse=void 0,e.dialDataRequest=void 0,e.dialRequest=void 0),e.dialRequest!=null&&(e.dialDataResponse=void 0,e.dialDataRequest=void 0,e.dialResponse=void 0),e.dialRequest!=null&&(n.uint32(10),jn.codec().encode(e.dialRequest,n)),e.dialResponse!=null&&(n.uint32(18),te.codec().encode(e.dialResponse,n)),e.dialDataRequest!=null&&(n.uint32(26),Wn.codec().encode(e.dialDataRequest,n)),e.dialDataResponse!=null&&(n.uint32(34),Qn.codec().encode(e.dialDataResponse,n)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.dialRequest=jn.codec().decode(e,e.uint32(),{limits:o.limits?.dialRequest});break}case 2:{s.dialResponse=te.codec().decode(e,e.uint32(),{limits:o.limits?.dialResponse});break}case 3:{s.dialDataRequest=Wn.codec().decode(e,e.uint32(),{limits:o.limits?.dialDataRequest});break}case 4:{s.dialDataResponse=Qn.codec().decode(e,e.uint32(),{limits:o.limits?.dialDataResponse});break}default:{e.skipType(a&7);break}}}return s.dialDataResponse!=null&&(delete s.dialDataRequest,delete s.dialResponse,delete s.dialRequest),s.dialDataRequest!=null&&(delete s.dialDataResponse,delete s.dialResponse,delete s.dialRequest),s.dialResponse!=null&&(delete s.dialDataResponse,delete s.dialDataRequest,delete s.dialRequest),s.dialRequest!=null&&(delete s.dialDataResponse,delete s.dialDataRequest,delete s.dialResponse),s})),t),r.encode=e=>Bt(e,r.codec()),r.decode=(e,n)=>It(e,r.codec(),n)})(nr||(nr={}));var jn;(function(r){let t;r.codec=()=>(t==null&&(t=Dt((e,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),e.addrs!=null)for(let s of e.addrs)n.uint32(10),n.bytes(s);e.nonce!=null&&e.nonce!==0n&&(n.uint32(17),n.fixed64(e.nonce)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={addrs:[],nonce:0n},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{if(o.limits?.addrs!=null&&s.addrs.length===o.limits.addrs)throw new mn('Decode error - map field "addrs" had too many elements');s.addrs.push(e.bytes());break}case 2:{s.nonce=e.fixed64();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Bt(e,r.codec()),r.decode=(e,n)=>It(e,r.codec(),n)})(jn||(jn={}));var Wn;(function(r){let t;r.codec=()=>(t==null&&(t=Dt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.addrIdx!=null&&e.addrIdx!==0&&(n.uint32(8),n.uint32(e.addrIdx)),e.numBytes!=null&&e.numBytes!==0n&&(n.uint32(16),n.uint64(e.numBytes)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={addrIdx:0,numBytes:0n},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.addrIdx=e.uint32();break}case 2:{s.numBytes=e.uint64();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Bt(e,r.codec()),r.decode=(e,n)=>It(e,r.codec(),n)})(Wn||(Wn={}));var ut;(function(r){r.UNUSED="UNUSED",r.E_DIAL_ERROR="E_DIAL_ERROR",r.E_DIAL_BACK_ERROR="E_DIAL_BACK_ERROR",r.OK="OK"})(ut||(ut={}));var Yn;(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"})(Yn||(Yn={}));(function(r){r.codec=()=>Se(Yn)})(ut||(ut={}));var te;(function(r){let t;(function(o){o.E_INTERNAL_ERROR="E_INTERNAL_ERROR",o.E_REQUEST_REJECTED="E_REQUEST_REJECTED",o.E_DIAL_REFUSED="E_DIAL_REFUSED",o.OK="OK"})(t=r.ResponseStatus||(r.ResponseStatus={}));let e;(function(o){o[o.E_INTERNAL_ERROR=0]="E_INTERNAL_ERROR",o[o.E_REQUEST_REJECTED=100]="E_REQUEST_REJECTED",o[o.E_DIAL_REFUSED=101]="E_DIAL_REFUSED",o[o.OK=200]="OK"})(e||(e={})),function(o){o.codec=()=>Se(e)}(t=r.ResponseStatus||(r.ResponseStatus={}));let n;r.codec=()=>(n==null&&(n=Dt((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.status!=null&&e[o.status]!==0&&(s.uint32(8),r.ResponseStatus.codec().encode(o.status,s)),o.addrIdx!=null&&o.addrIdx!==0&&(s.uint32(16),s.uint32(o.addrIdx)),o.dialStatus!=null&&Yn[o.dialStatus]!==0&&(s.uint32(24),ut.codec().encode(o.dialStatus,s)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={status:t.E_INTERNAL_ERROR,addrIdx:0,dialStatus:ut.UNUSED},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let u=o.uint32();switch(u>>>3){case 1:{a.status=r.ResponseStatus.codec().decode(o);break}case 2:{a.addrIdx=o.uint32();break}case 3:{a.dialStatus=ut.codec().decode(o);break}default:{o.skipType(u&7);break}}}return a})),n),r.encode=o=>Bt(o,r.codec()),r.decode=(o,s)=>It(o,r.codec(),s)})(te||(te={}));var Qn;(function(r){let t;r.codec=()=>(t==null&&(t=Dt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.data!=null&&e.data.byteLength>0&&(n.uint32(10),n.bytes(e.data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={data:bt(0)},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Bt(e,r.codec()),r.decode=(e,n)=>It(e,r.codec(),n)})(Qn||(Qn={}));var or;(function(r){let t;r.codec=()=>(t==null&&(t=Dt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.nonce!=null&&e.nonce!==0n&&(n.uint32(9),n.fixed64(e.nonce)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={nonce:0n},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.nonce=e.fixed64();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Bt(e,r.codec()),r.decode=(e,n)=>It(e,r.codec(),n)})(or||(or={}));var de;(function(r){let t;(function(o){o.OK="OK"})(t=r.DialBackStatus||(r.DialBackStatus={}));let e;(function(o){o[o.OK=0]="OK"})(e||(e={})),function(o){o.codec=()=>Se(e)}(t=r.DialBackStatus||(r.DialBackStatus={}));let n;r.codec=()=>(n==null&&(n=Dt((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.status!=null&&e[o.status]!==0&&(s.uint32(8),r.DialBackStatus.codec().encode(o.status,s)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={status:t.OK},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let u=o.uint32();switch(u>>>3){case 1:{a.status=r.DialBackStatus.codec().decode(o);break}default:{o.skipType(u&7);break}}}return a})),n),r.encode=o=>Bt(o,r.codec()),r.decode=(o,s)=>It(o,r.codec(),s)})(de||(de={}));function Jn(r,t){return Math.round(Math.random()*(t-r)+r)}var Md=4,Kd=8,to=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=Lc({name:"libp2p_autonat_v2_dial_results",metrics:t.metrics}),this.findPeers=Rc(this.findRandomPeers.bind(this),6e4),this.addressFilter=Os(1024),this.queue=new Hn({concurrency:3,maxSize:50}),this.maxDialDataBytes=e.maxDialDataBytes??Mc,this.dialDataChunkSize=e.dialDataChunkSize??Kc,this.nonces=new Set}[Symbol.toStringTag]="@libp2p/autonat-v2";[Gr]=["@libp2p/autonat"];get[Zr](){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=>{this.handleDialBackStream(t).catch(e=>{this.log.error("error handling incoming autonat stream - %e",e)})},{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=Fr([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){let e=AbortSignal.timeout(this.timeout);let n=rr(t.stream,{maxDataLength:this.maxMessageSize});try{let o=await n.read(or,{signal:e});if(!this.nonces.has(o.nonce))throw new vt("No matching dial found for nonce value");this.nonces.delete(o.nonce),await n.write({status:de.DialBackStatus.OK},de),await t.stream.close({signal:e})}catch(o){this.log.error("error handling incoming dial back stream - %e",o),t.stream.abort(o)}}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())||s.multiaddr.toOptions().family===6&&(!e||!vc(s.multiaddr))||Dc(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:Ts(),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})=>i.toOptions().family===6),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=Fr([i.signal,AbortSignal.timeout(this.timeout)]),c=BigInt(Jn(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 %p to verify multiaddrs %s",t.remotePeer,s);let i=await t.newStream(this.dialRequestProtocol,o);try{let a=rr(i).pb(nr);for(await a.write({dialRequest:{addrs:s.map(c=>c.bytes),nonce:n}},o);;){let c=await a.read(o);if(c.dialDataRequest!=null){if(c.dialDataRequest.numBytes>this.maxDialDataBytes){this.log("too many dial data byte requested by %p - %s/%s",t.remotePeer,c.dialDataRequest.numBytes,this.maxDialDataBytes);continue}this.log("sending %d bytes to %p as anti-amplification attack protection",c.dialDataRequest.numBytes,t.remotePeer);let f=new Uint8Array(this.dialDataChunkSize),p=BigInt(this.dialDataChunkSize);for(let h=0n;h<c.dialDataRequest.numBytes;h+=p)await a.write({dialDataResponse:{data:f}},o);c=await a.read(o)}if(c.dialResponse==null){this.log("invalid autonat response from %p - %j",t.remotePeer,c);return}if(c.dialResponse.status!==te.ResponseStatus.OK)return;let d=s[c.dialResponse.addrIdx];if(d==null){this.log.trace("peer dialed unknown address");continue}let l=this.dialResults.get(d.toString());if(l==null){this.log.trace("peer reported %a as %s but there is no result object",d,c.dialResponse.status);continue}if(l.networkSegments.includes(e)){this.log.trace("%a results already included network segment %s",d,e);continue}if(l.result!=null){this.log.trace("already resolved result for %a, ignoring response from",d,t.remotePeer);continue}if(l.verifyingPeers.has(t.remotePeer)){this.log.trace("peer %p has already verified %a, ignoring response",t.remotePeer,d);continue}if(l.verifyingPeers.add(t.remotePeer),l.networkSegments.push(e),c.dialResponse.dialStatus===ut.OK){if(this.log.trace("%p dialed %a successfully",t.remotePeer,l.multiaddr),l.success++,l.type!=="observed"){this.confirmAddress(l);continue}}else if(c.dialResponse.dialStatus===ut.E_DIAL_ERROR)this.log.trace("%p could not dial %a",t.remotePeer,l.multiaddr),l.failure++;else if(c.dialResponse.dialStatus===ut.E_DIAL_BACK_ERROR){this.log.trace("%p saw error while dialing %a",t.remotePeer,l.multiaddr);continue}this.log("%a success %d failure %d",l.multiaddr,l.success,l.failure),l.success===Md&&this.confirmAddress(l),l.failure===Kd&&this.unconfirmAddress(l)}}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=t.toOptions();return e.family===4?e.host.split(".")[0].padStart(3,"0"):e.host.split(":")[0].padStart(4,"0")}};var eo=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}async start(){this.started||(await this.components.registrar.handle(this.dialRequestProtocol,t=>{this.handleDialRequestStream(t).catch(e=>{this.log.error("error handling incoming autonat stream - %e",e)})},{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams}),this.started=!0)}async stop(){await this.components.registrar.unhandle(this.dialRequestProtocol),this.started=!1}async handleDialRequestStream(t){let e=AbortSignal.timeout(this.timeout);let n=rr(t.stream,{maxDataLength:this.maxMessageSize}).pb(nr);try{let o=Hc(t.connection.remoteAddr);if(o==null)throw new vt(`Could not find IP address in connection address "${t.connection.remoteAddr}"`);let{dialRequest:s}=await n.read({signal:e});if(s==null)throw new vt("Did not receive DialRequest message on incoming dial request stream");if(s.addrs.length===0)throw new vt("Did not receive any addresses to dial");for(let i=0;i<s.addrs.length;i++)try{let a=Ur(s.addrs[i]);if(!await this.components.connectionManager.isDialable(a,{signal:e})){await n.write({dialResponse:{addrIdx:i,status:te.ResponseStatus.E_DIAL_REFUSED,dialStatus:ut.UNUSED}},{signal:e});continue}let u=Hc(a);if(u==null)throw new vt(`Could not find IP address in requested address "${a}"`);if(kn(u))throw new vt(`Requested address had private IP "${a}"`);u!==o&&await this.preventAmplificationAttack(n,i,{signal:e});let d=await this.dialClientBack(a,s.nonce,{signal:e});await n.write({dialResponse:{addrIdx:i,status:te.ResponseStatus.OK,dialStatus:d}},{signal:e})}catch(a){this.log.error("could not parse multiaddr - %e",a)}await t.stream.close({signal:e})}catch(o){this.log.error("error handling incoming autonat stream - %e",o),t.stream.abort(o)}}async preventAmplificationAttack(t,e,n){let o=Jn(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 vt("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",s,t),ut.E_DIAL_ERROR}try{let s=await o.newStream(this.dialBackProtocol,n),i=rr(s,{maxDataLength:this.maxMessageSize});if(await i.write({nonce:e},or,n),(await i.read(de)).status!==de.DialBackStatus.OK)throw new vt("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),ut.E_DIAL_BACK_ERROR}return ut.OK}};function Hc(r){return r.getComponents().filter(t=>t.code===4||t.code===41).map(t=>t.value).pop()}var ro=class{client;server;constructor(t,e){let n=`/${e.protocolPrefix??ni}/${oi}/${"2"}/${Nc}`,o=`/${e.protocolPrefix??ni}/${oi}/${"2"}/${Uc}`;this.client=new to(t,{...e,dialRequestProtocol:n,dialBackProtocol:o}),this.server=new eo(t,{...e,dialRequestProtocol:n,dialBackProtocol:o})}[Symbol.toStringTag]="@libp2p/autonat-v2";[Gr]=["@libp2p/autonat"];get[Zr](){return["@libp2p/identify"]}async start(){await ui(this.client,this.server)}async stop(){await fi(this.client,this.server)}};function Fd(r={}){return t=>new ro(t,r)}return Jc(qd);})();
3
3
  /*! Bundled license information:
4
4
 
5
5
  @noble/hashes/esm/utils.js: