@libp2p/autonat-v2 1.0.1-da78fa851 → 1.0.1-e8398d97e
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.min.js +1 -1
- package/dist/index.min.js.map +3 -3
- package/package.json +8 -8
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 Oc=Object.create;var Kr=Object.defineProperty;var kc=Object.getOwnPropertyDescriptor;var Nc=Object.getOwnPropertyNames;var Uc=Object.getPrototypeOf,Mc=Object.prototype.hasOwnProperty;var Kc=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),bt=(r,t)=>{for(var e in t)Kr(r,e,{get:t[e],enumerable:!0})},Qs=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Nc(t))!Mc.call(r,o)&&o!==e&&Kr(r,o,{get:()=>t[o],enumerable:!(n=kc(t,o))||n.enumerable});return r};var Fc=(r,t,e)=>(e=r!=null?Oc(Uc(r)):{},Qs(t||!r||!r.__esModule?Kr(e,"default",{value:r,enumerable:!0}):e,r)),qc=r=>Qs(Kr({},"__esModule",{value:!0}),r);var nc=Kc(Or=>{(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,p;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)}p=t(c),h=p[0],d=p[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,p;if(typeof u!="string")throw new Error("Missing `net' parameter");if(d||(p=u.split("/",2),u=p[0],d=p[1]),d||(d=32),typeof d=="string"&&d.indexOf(".")>-1){try{this.maskLong=i(d)}catch(w){throw l=w,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(w){throw l=w,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})(),Or.ip2long=i,Or.long2ip=a,Or.Netmask=r}).call(Or)});var Zd={};bt(Zd,{autoNATv2:()=>Gd});var Ot=class extends Error{static name="AbortError";constructor(t="The operation was aborted"){super(t),this.name="AbortError"}};var ft=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},Fr=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}};var qr=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}};var _t=class extends Error{static name="ProtocolError";constructor(t="Protocol error"){super(t),this.name="ProtocolError"}};var or=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var jn=Symbol.for("@libp2p/peer-id");function Js(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function ti(...r){let t=[];for(let e of r)Js(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 ei(...r){let t=[];for(let e of r)Js(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=class extends EventTarget{#t=new Map;constructor(){super()}listenerCount(t){let e=this.#t.get(t);return e==null?0:e.length}addEventListener(t,e,n){super.addEventListener(t,e,n);let o=this.#t.get(t);o==null&&(o=[],this.#t.set(t,o)),o.push({callback:e,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(t,e,n){super.removeEventListener(t.toString(),e??null,n);let o=this.#t.get(t);o!=null&&(o=o.filter(({callback:s})=>s!==e),this.#t.set(t,o))}dispatchEvent(t){let e=super.dispatchEvent(t),n=this.#t.get(t.type);return n==null||(n=n.filter(({once:o})=>!o),this.#t.set(t.type,n)),e}safeDispatchEvent(t,e={}){return this.dispatchEvent(new CustomEvent(t,e))}};var Vr=Symbol.for("@libp2p/service-capabilities"),Hr=Symbol.for("@libp2p/service-dependencies");var Jn={};bt(Jn,{base58btc:()=>Y,base58flickr:()=>jc});var Ah=new Uint8Array(0);function ri(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 kt(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 ni(r){return new TextEncoder().encode(r)}function oi(r){return new TextDecoder().decode(r)}function zc(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(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var w=0,S=0,y=0,_=p.length;y!==_&&p[y]===0;)y++,w++;for(var x=(_-y)*d+1>>>0,D=new Uint8Array(x);y!==_;){for(var R=p[y],M=0,U=x-1;(R!==0||M<S)&&U!==-1;U--,M++)R+=256*D[U]>>>0,D[U]=R%a>>>0,R=R/a>>>0;if(R!==0)throw new Error("Non-zero carry");S=M,y++}for(var O=x-S;O!==x&&D[O]===0;)O++;for(var E=c.repeat(w);O<x;++O)E+=r.charAt(D[O]);return E}function f(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var w=0;if(p[w]!==" "){for(var S=0,y=0;p[w]===c;)S++,w++;for(var _=(p.length-w)*u+1>>>0,x=new Uint8Array(_);p[w];){var D=e[p.charCodeAt(w)];if(D===255)return;for(var R=0,M=_-1;(D!==0||R<y)&&M!==-1;M--,R++)D+=a*x[M]>>>0,x[M]=D%256>>>0,D=D/256>>>0;if(D!==0)throw new Error("Non-zero carry");y=R,w++}if(p[w]!==" "){for(var U=_-y;U!==_&&x[U]===0;)U++;for(var O=new Uint8Array(S+(_-U)),E=S;U!==_;)O[E++]=x[U++];return O}}}function h(p){var w=f(p);if(w)return w;throw new Error(`Non-${t} character`)}return{encode:l,decodeUnsafe:f,decode:h}}var Vc=zc,Hc=Vc,ii=Hc;var Xn=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")}},Yn=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 ai(this,t)}},Wn=class{decoders;constructor(t){this.decoders=t}or(t){return ai(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 ai(r,t){return new Wn({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var Qn=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 Xn(t,e,n),this.decoder=new Yn(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Be({name:r,prefix:t,encode:e,decode:n}){return new Qn(r,t,e,n)}function Jt({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=ii(e,r);return Be({prefix:t,name:r,encode:n,decode:s=>kt(o(s))})}function $c(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 Gc(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 Zc(r){let t={};for(let e=0;e<r.length;++e)t[r[e]]=e;return t}function j({name:r,prefix:t,bitsPerChar:e,alphabet:n}){let o=Zc(n);return Be({prefix:t,name:r,encode(s){return Gc(s,n,e)},decode(s){return $c(s,o,e,r)}})}var Y=Jt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),jc=Jt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var to={};bt(to,{base32:()=>te,base32hex:()=>Qc,base32hexpad:()=>tu,base32hexpadupper:()=>eu,base32hexupper:()=>Jc,base32pad:()=>Yc,base32padupper:()=>Wc,base32upper:()=>Xc,base32z:()=>ru});var te=j({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Xc=j({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Yc=j({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Wc=j({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Qc=j({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Jc=j({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),tu=j({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),eu=j({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),ru=j({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var eo={};bt(eo,{base36:()=>sr,base36upper:()=>nu});var sr=Jt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),nu=Jt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var ou=fi,ci=128,su=127,iu=~su,au=Math.pow(2,31);function fi(r,t,e){t=t||[],e=e||0;for(var n=e;r>=au;)t[e++]=r&255|ci,r/=128;for(;r&iu;)t[e++]=r&255|ci,r>>>=7;return t[e]=r|0,fi.bytes=e-n+1,t}var cu=ro,uu=128,ui=127;function ro(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw ro.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&ui)<<o:(i&ui)*Math.pow(2,o),o+=7}while(i>=uu);return ro.bytes=s-n,e}var fu=Math.pow(2,7),lu=Math.pow(2,14),du=Math.pow(2,21),hu=Math.pow(2,28),pu=Math.pow(2,35),mu=Math.pow(2,42),gu=Math.pow(2,49),yu=Math.pow(2,56),bu=Math.pow(2,63),xu=function(r){return r<fu?1:r<lu?2:r<du?3:r<hu?4:r<pu?5:r<mu?6:r<gu?7:r<yu?8:r<bu?9:10},wu={encode:ou,decode:cu,encodingLength:xu},Eu=wu,ir=Eu;function ar(r,t=0){return[ir.decode(r,t),ir.decode.bytes]}function De(r,t,e=0){return ir.encode(r,t,e),t}function Ce(r){return ir.encodingLength(r)}function Le(r,t){let e=t.byteLength,n=Ce(r),o=n+Ce(e),s=new Uint8Array(o+e);return De(r,s,0),De(e,s,n),s.set(t,o),new Te(r,e,t,s)}function cr(r){let t=kt(r),[e,n]=ar(t),[o,s]=ar(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Te(e,o,i,t)}function li(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&ri(r.bytes,e.bytes)}}var Te=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};function di(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return vu(e,no(r),t??Y.encoder);default:return _u(e,no(r),t??te.encoder)}}var hi=new WeakMap;function no(r){let t=hi.get(r);if(t==null){let e=new Map;return hi.set(r,e),e}return t}var it=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!==ur)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==Au)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=Le(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&&li(t.multihash,n.multihash)}toString(t){return di(this,t)}toJSON(){return{"/":di(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??pi(n,o,s.bytes))}else if(e[Iu]===!0){let{version:n,multihash:o,code:s}=e,i=cr(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!==ur)throw new Error(`Version 0 CID must use dag-pb (code: ${ur}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=pi(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,ur,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=kt(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 Te(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]=ar(t.subarray(e));return e+=f,l},o=n(),s=ur;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]=Su(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 no(s).set(n,t),s}};function Su(r,t){switch(r[0]){case"Q":{let e=t??Y;return[Y.prefix,e.decode(`${Y.prefix}${r}`)]}case Y.prefix:{let e=t??Y;return[Y.prefix,e.decode(r)]}case te.prefix:{let e=t??te;return[te.prefix,e.decode(r)]}case sr.prefix:{let e=t??sr;return[sr.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 vu(r,t,e){let{prefix:n}=e;if(n!==Y.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 _u(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 ur=112,Au=18;function pi(r,t,e){let n=Ce(r),o=n+Ce(t),s=new Uint8Array(o+e.byteLength);return De(r,s,0),De(t,s,n),s.set(e,o),s}var Iu=Symbol.for("@ipld/js-cid/CID");var oo={};bt(oo,{identity:()=>Ct});var mi=0,Bu="identity",gi=kt;function Du(r,t){if(t?.truncate!=null&&t.truncate!==r.byteLength){if(t.truncate<0||t.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t.truncate)}return Le(mi,gi(r))}var Ct={code:mi,name:Bu,encode:gi,digest:Du};function lt(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function xt(r=0){return new Uint8Array(r)}function mt(r=0){return new Uint8Array(r)}function Nt(r,t){t==null&&(t=r.reduce((o,s)=>o+s.length,0));let e=mt(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}var bi=Symbol.for("@achingbrain/uint8arraylist");function yi(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 Gr(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(Gr(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(Gr(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=yi(this.bufs,t);return e.buf[e.index]}set(t,e){let n=yi(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(Gr(t))for(let n=0;n<t.length;n++)this.set(e+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:n,length:o}=this._subList(t,e);return Nt(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:Nt(n,o)}sublist(t,e){let{bufs:n,length:o}=this._subList(t,e),s=new r;return s.length=o,s.bufs=[...n],s}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,t>=c)continue;let u=t>=a&&t<c,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(!Gr(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=mt(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=xt(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=xt(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=xt(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=mt(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=xt(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=xt(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=xt(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=xt(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=xt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,e,n),this.write(o,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!lt(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((o,s)=>o+s.byteLength,0)),n.length=e,n}};var so={};bt(so,{base10:()=>Cu});var Cu=Jt({prefix:"9",name:"base10",alphabet:"0123456789"});var io={};bt(io,{base16:()=>Tu,base16upper:()=>Lu});var Tu=j({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Lu=j({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var ao={};bt(ao,{base2:()=>Ru});var Ru=j({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var co={};bt(co,{base256emoji:()=>Uu});var xi=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}"),Pu=xi.reduce((r,t,e)=>(r[e]=t,r),[]),Ou=xi.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function ku(r){return r.reduce((t,e)=>(t+=Pu[e],t),"")}function Nu(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=Ou[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var Uu=Be({prefix:"\u{1F680}",name:"base256emoji",encode:ku,decode:Nu});var fo={};bt(fo,{base64:()=>Mu,base64pad:()=>Ku,base64url:()=>uo,base64urlpad:()=>Fu});var Mu=j({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Ku=j({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),uo=j({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Fu=j({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var lo={};bt(lo,{base8:()=>qu});var qu=j({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var ho={};bt(ho,{identity:()=>zu});var zu=Be({prefix:"\0",name:"identity",encode:r=>oi(r),decode:r=>ni(r)});var cp=new TextEncoder,up=new TextDecoder;var go={};bt(go,{sha256:()=>fr,sha512:()=>Gu});var $u=20;function mo({name:r,code:t,encode:e,minDigestLength:n,maxDigestLength:o}){return new po(r,t,e,n,o)}var po=class{name;code;encode;minDigestLength;maxDigestLength;constructor(t,e,n,o,s){this.name=t,this.code=e,this.encode=n,this.minDigestLength=o??$u,this.maxDigestLength=s}digest(t,e){if(e?.truncate!=null){if(e.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&e.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(t instanceof Uint8Array){let n=this.encode(t);return n instanceof Uint8Array?wi(n,this.code,e?.truncate):n.then(o=>wi(o,this.code,e?.truncate))}else throw Error("Unknown type, must be binary type")}};function wi(r,t,e){if(e!=null&&e!==r.byteLength){if(e>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e)}return Le(t,r)}function Si(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var fr=mo({name:"sha2-256",code:18,encode:Si("SHA-256")}),Gu=mo({name:"sha2-512",code:19,encode:Si("SHA-512")});var lr={...ho,...ao,...lo,...so,...io,...to,...eo,...Jn,...fo,...co},Ep={...go,...oo};function _i(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var vi=_i("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),yo=_i("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=mt(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),Zu={utf8:vi,"utf-8":vi,hex:lr.base16,latin1:yo,ascii:yo,binary:yo,...lr},Zr=Zu;function H(r,t="utf8"){let e=Zr[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function Q(r,t="utf8"){let e=Zr[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var ju=parseInt("11111",2),bo=parseInt("10000000",2),Xu=parseInt("01111111",2),Ai={0:dr,1:dr,2:Yu,3:Ju,4:tf,5:Qu,6:Wu,16:dr,22:dr,48:dr};function xo(r,t={offset:0}){let e=r[t.offset]&ju;if(t.offset++,Ai[e]!=null)return Ai[e](r,t);throw new Error("No decoder for tag "+e)}function hr(r,t){let e=0;if((r[t.offset]&bo)===bo){let n=r[t.offset]&Xu,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 dr(r,t){hr(r,t);let e=[];for(;!(t.offset>=r.byteLength);){let n=xo(r,t);if(n===null)break;e.push(n)}return e}function Yu(r,t){let e=hr(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 Wu(r,t){let e=hr(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 Qu(r,t){return t.offset++,null}function Ju(r,t){let e=hr(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 tf(r,t){let e=hr(r,t),n=r.subarray(t.offset,t.offset+e);return t.offset+=e,n}function ef(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 wo(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let t=ef(r.byteLength);return new J(Uint8Array.from([t.byteLength|bo]),t)}function Ii(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]),wo(t),t)}function Bi(r){let t=Uint8Array.from([0]),e=new J(t,r);return new J(Uint8Array.from([3]),wo(e),e)}function jr(r,t=48){let e=new J;for(let n of r)e.append(n);return new J(Uint8Array.from([t]),wo(e),e)}async function Di(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 rf=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),nf=Uint8Array.from([6,5,43,129,4,0,34]),of=Uint8Array.from([6,5,43,129,4,0,35]),sf={ext:!0,kty:"EC",crv:"P-256"},af={ext:!0,kty:"EC",crv:"P-384"},cf={ext:!0,kty:"EC",crv:"P-521"},Eo=32,So=48,vo=66;function Ci(r){let t=xo(r);return Ti(t)}function Ti(r){let t=r[1][1][0],e=1,n,o;if(t.byteLength===Eo*2+1)return n=Q(t.subarray(e,e+Eo),"base64url"),o=Q(t.subarray(e+Eo),"base64url"),new Re({...sf,key_ops:["verify"],x:n,y:o});if(t.byteLength===So*2+1)return n=Q(t.subarray(e,e+So),"base64url"),o=Q(t.subarray(e+So),"base64url"),new Re({...af,key_ops:["verify"],x:n,y:o});if(t.byteLength===vo*2+1)return n=Q(t.subarray(e,e+vo),"base64url"),o=Q(t.subarray(e+vo),"base64url"),new Re({...cf,key_ops:["verify"],x:n,y:o});throw new ft(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function Li(r){return jr([Ii(Uint8Array.from([1])),jr([uf(r.crv)],160),jr([Bi(new J(Uint8Array.from([4]),H(r.x??"","base64url"),H(r.y??"","base64url")))],161)]).subarray()}function uf(r){if(r==="P-256")return rf;if(r==="P-384")return nf;if(r==="P-521")return of;throw new ft(`Invalid curve ${r}`)}var Re=class{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=Li(this.jwk)),this._raw}toMultihash(){return Ct.digest(Pe(this))}toCID(){return it.createV1(114,this.toMultihash())}toString(){return Y.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:lt(this.raw,t.raw)}async verify(t,e,n){return Di(this.jwk,e,t,n)}};var de=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Mt(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function pr(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function gt(r,...t){if(!Mt(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 Xr(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");pr(r.outputLen),pr(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 Pi(r,t){gt(r);let e=t.outputLen;if(r.length<e)throw new Error("digestInto() expects output buffer of length at least "+e)}function Kt(...r){for(let t=0;t<r.length;t++)r[t].fill(0)}function Yr(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Tt(r,t){return r<<32-t|r>>>t}var Oi=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",ff=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function At(r){if(gt(r),Oi)return r.toHex();let t="";for(let e=0;e<r.length;e++)t+=ff[r[e]];return t}var Ut={_0:48,_9:57,A:65,F:70,a:97,f:102};function Ri(r){if(r>=Ut._0&&r<=Ut._9)return r-Ut._0;if(r>=Ut.A&&r<=Ut.F)return r-(Ut.A-10);if(r>=Ut.a&&r<=Ut.f)return r-(Ut.a-10)}function he(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(Oi)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=Ri(r.charCodeAt(s)),a=Ri(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 _o(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function mr(r){return typeof r=="string"&&(r=_o(r)),gt(r),r}function dt(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];gt(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 Oe=class{};function Ao(r){let t=n=>r().update(mr(n)).digest(),e=r();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>r(),t}function Ne(r=32){if(de&&typeof de.getRandomValues=="function")return de.getRandomValues(new Uint8Array(r));if(de&&typeof de.randomBytes=="function")return Uint8Array.from(de.randomBytes(r));throw new Error("crypto.getRandomValues must be defined")}function lf(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 ki(r,t,e){return r&t^~r&e}function Ni(r,t,e){return r&t^r&e^t&e}var gr=class extends Oe{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=Yr(this.buffer)}update(t){ke(this),t=mr(t),gt(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=Yr(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),Pi(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;e[i++]=128,Kt(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let l=i;l<o;l++)e[l]=0;lf(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=Yr(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 Wr=BigInt(4294967295),Ui=BigInt(32);function df(r,t=!1){return t?{h:Number(r&Wr),l:Number(r>>Ui&Wr)}:{h:Number(r>>Ui&Wr)|0,l:Number(r&Wr)|0}}function Mi(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}=df(r[s],t);[n[s],o[s]]=[i,a]}return[n,o]}var Io=(r,t,e)=>r>>>e,Bo=(r,t,e)=>r<<32-e|t>>>e,pe=(r,t,e)=>r>>>e|t<<32-e,me=(r,t,e)=>r<<32-e|t>>>e,yr=(r,t,e)=>r<<64-e|t>>>e-32,br=(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 Ki=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),Fi=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,qi=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),zi=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,Vi=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),Hi=(r,t,e,n,o,s)=>t+e+n+o+s+(r/2**32|0)|0;var pf=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]),ee=new Uint32Array(64),Do=class extends gr{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)ee[l]=t.getUint32(e,!1);for(let l=16;l<64;l++){let f=ee[l-15],h=ee[l-2],p=Tt(f,7)^Tt(f,18)^f>>>3,w=Tt(h,17)^Tt(h,19)^h>>>10;ee[l]=w+ee[l-7]+p+ee[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),h=d+f+ki(a,c,u)+pf[l]+ee[l]|0,w=(Tt(n,2)^Tt(n,13)^Tt(n,22))+Ni(n,o,s)|0;d=u,u=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+w|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(){Kt(ee)}destroy(){this.set(0,0,0,0,0,0,0,0),Kt(this.buffer)}};var $i=Mi(["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))),mf=$i[0],gf=$i[1],re=new Uint32Array(80),ne=new Uint32Array(80),Co=class extends gr{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:p,Hh:w,Hl:S}=this;return[t,e,n,o,s,i,a,c,u,d,l,f,h,p,w,S]}set(t,e,n,o,s,i,a,c,u,d,l,f,h,p,w,S){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=p|0,this.Hh=w|0,this.Hl=S|0}process(t,e){for(let x=0;x<16;x++,e+=4)re[x]=t.getUint32(e),ne[x]=t.getUint32(e+=4);for(let x=16;x<80;x++){let D=re[x-15]|0,R=ne[x-15]|0,M=pe(D,R,1)^pe(D,R,8)^Io(D,R,7),U=me(D,R,1)^me(D,R,8)^Bo(D,R,7),O=re[x-2]|0,E=ne[x-2]|0,C=pe(O,E,19)^yr(O,E,61)^Io(O,E,6),k=me(O,E,19)^br(O,E,61)^Bo(O,E,6),T=qi(U,k,ne[x-7],ne[x-16]),b=zi(T,M,C,re[x-7],re[x-16]);re[x]=b|0,ne[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:h,Fl:p,Gh:w,Gl:S,Hh:y,Hl:_}=this;for(let x=0;x<80;x++){let D=pe(l,f,14)^pe(l,f,18)^yr(l,f,41),R=me(l,f,14)^me(l,f,18)^br(l,f,41),M=l&h^~l&w,U=f&p^~f&S,O=Vi(_,R,U,gf[x],ne[x]),E=Hi(O,y,D,M,mf[x],re[x]),C=O|0,k=pe(n,o,28)^yr(n,o,34)^yr(n,o,39),T=me(n,o,28)^br(n,o,34)^br(n,o,39),b=n&s^n&a^s&a,m=o&i^o&c^i&c;y=w|0,_=S|0,w=h|0,S=p|0,h=l|0,p=f|0,{h:l,l:f}=Pt(u|0,d|0,E|0,C|0),u=a|0,d=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let g=Ki(C,T,m);n=Fi(g,E,k,b),o=g|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:p}=Pt(this.Fh|0,this.Fl|0,h|0,p|0),{h:w,l:S}=Pt(this.Gh|0,this.Gl|0,w|0,S|0),{h:y,l:_}=Pt(this.Hh|0,this.Hl|0,y|0,_|0),this.set(n,o,s,i,a,c,u,d,l,f,h,p,w,S,y,_)}roundClean(){Kt(re,ne)}destroy(){Kt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var Gi=Ao(()=>new Do);var Zi=Ao(()=>new Co);var Ro=BigInt(0),Lo=BigInt(1);function qt(r,t=""){if(typeof r!="boolean"){let e=t&&`"${t}"`;throw new Error(e+"expected boolean, got type="+typeof r)}return r}function wt(r,t,e=""){let n=Mt(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 xr(r){let t=r.toString(16);return t.length&1?"0"+t:t}function ji(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?Ro:BigInt("0x"+r)}function Ue(r){return ji(At(r))}function zt(r){return gt(r),ji(At(Uint8Array.from(r).reverse()))}function Qr(r,t){return he(r.toString(16).padStart(t*2,"0"))}function Po(r,t){return Qr(r,t).reverse()}function q(r,t,e){let n;if(typeof t=="string")try{n=he(t)}catch(s){throw new Error(r+" must be hex string or Uint8Array, cause: "+s)}else if(Mt(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 Xi(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 Oo(r){return Uint8Array.from(r)}var To=r=>typeof r=="bigint"&&Ro<=r;function Yi(r,t,e){return To(r)&&To(t)&&To(e)&&t<=r&&r<e}function wr(r,t,e,n){if(!Yi(t,e,n))throw new Error("expected valid "+r+": "+e+" <= n < "+n+", got "+t)}function Jr(r){let t;for(t=0;r>Ro;r>>=Lo,t+=1);return t}var oe=r=>(Lo<<BigInt(r))-Lo;function Wi(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,p=[];for(;h<t;){s=u();let w=s.slice();p.push(w),h+=s.length}return dt(...p)};return(h,p)=>{c(),d(h);let w;for(;!(w=p(l()));)d();return c(),w}}function se(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 ko=()=>{throw new Error("not implemented")};function Me(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 ht=BigInt(0),tt=BigInt(1),ge=BigInt(2),ta=BigInt(3),ea=BigInt(4),ra=BigInt(5),yf=BigInt(7),na=BigInt(8),bf=BigInt(9),oa=BigInt(16);function X(r,t){let e=r%t;return e>=ht?e:t+e}function V(r,t,e){let n=r;for(;t-- >ht;)n*=n,n%=e;return n}function Qi(r,t){if(r===ht)throw new Error("invert: expected non-zero number");if(t<=ht)throw new Error("invert: expected positive modulus, got "+t);let e=X(r,t),n=t,o=ht,s=tt,i=tt,a=ht;for(;e!==ht;){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!==tt)throw new Error("invert: does not exist");return X(o,t)}function No(r,t,e){if(!r.eql(r.sqr(t),e))throw new Error("Cannot find square root")}function sa(r,t){let e=(r.ORDER+tt)/ea,n=r.pow(t,e);return No(r,n,t),n}function xf(r,t){let e=(r.ORDER-ra)/na,n=r.mul(t,ge),o=r.pow(n,e),s=r.mul(t,o),i=r.mul(r.mul(s,ge),o),a=r.mul(s,r.sub(i,r.ONE));return No(r,a,t),a}function wf(r){let t=Et(r),e=ia(r),n=e(t,t.neg(t.ONE)),o=e(t,n),s=e(t,t.neg(n)),i=(r+yf)/oa;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),p=a.eql(a.sqr(l),c);u=a.cmov(u,d,h),d=a.cmov(f,l,p);let w=a.eql(a.sqr(d),c),S=a.cmov(u,d,w);return No(a,S,c),S}}function ia(r){if(r<ta)throw new Error("sqrt is not defined for small field");let t=r-tt,e=0;for(;t%ge===ht;)t/=ge,e++;let n=ge,o=Et(r);for(;Ji(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(e===1)return sa;let s=o.pow(n,t),i=(t+tt)/ge;return function(c,u){if(c.is0(u))return u;if(Ji(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 p=1,w=c.sqr(f);for(;!c.eql(w,c.ONE);)if(p++,w=c.sqr(w),p===d)throw new Error("Cannot find square root");let S=tt<<BigInt(d-p-1),y=c.pow(l,S);d=p,l=c.sqr(y),f=c.mul(f,l),h=c.mul(h,y)}return h}}function Ef(r){return r%ea===ta?sa:r%na===ra?xf:r%oa===bf?wf(r):ia(r)}var Vt=(r,t)=>(X(r,t)&tt)===tt,Sf=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Uo(r){let t={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},e=Sf.reduce((n,o)=>(n[o]="function",n),t);return se(r,e),r}function vf(r,t,e){if(e<ht)throw new Error("invalid exponent, negatives unsupported");if(e===ht)return r.ONE;if(e===tt)return t;let n=r.ONE,o=t;for(;e>ht;)e&tt&&(n=r.mul(n,o)),o=r.sqr(o),e>>=tt;return n}function Er(r,t,e=!1){let n=new Array(t.length).fill(e?r.ZERO:void 0),o=t.reduce((i,a,c)=>r.is0(a)?i:(n[c]=i,r.mul(i,a)),r.ONE),s=r.inv(o);return t.reduceRight((i,a,c)=>r.is0(a)?i:(n[c]=r.mul(i,n[c]),r.mul(i,a)),s),n}function Ji(r,t){let e=(r.ORDER-tt)/ge,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 tn(r,t){t!==void 0&&pr(t);let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}function Et(r,t,e=!1,n={}){if(r<=ht)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}=tn(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:oe(c),ZERO:ht,ONE:tt,allowedLengths:a,create:f=>X(f,r),isValid:f=>{if(typeof f!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof f);return ht<=f&&f<r},is0:f=>f===ht,isValidNot0:f=>!l.is0(f)&&l.isValid(f),isOdd:f=>(f&tt)===tt,neg:f=>X(-f,r),eql:(f,h)=>f===h,sqr:f=>X(f*f,r),add:(f,h)=>X(f+h,r),sub:(f,h)=>X(f-h,r),mul:(f,h)=>X(f*h,r),pow:(f,h)=>vf(l,f,h),div:(f,h)=>X(f*Qi(h,r),r),sqrN:f=>f*f,addN:(f,h)=>f+h,subN:(f,h)=>f-h,mulN:(f,h)=>f*h,inv:f=>Qi(f,r),sqrt:s||(f=>(d||(d=Ef(r)),d(l,f))),toBytes:f=>e?Po(f,u):Qr(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 w=new Uint8Array(u);w.set(f,e?0:w.length-f.length),f=w}if(f.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+f.length);let p=e?zt(f):Ue(f);if(i&&(p=X(p,r)),!h&&!l.isValid(p))throw new Error("invalid field element: outside of range 0..ORDER");return p},invertBatch:f=>Er(l,f),cmov:(f,h,p)=>p?h:f});return Object.freeze(l)}function aa(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 Mo(r){let t=aa(r);return t+Math.ceil(t/2)}function Ko(r,t,e=!1){let n=r.length,o=aa(t),s=Mo(t);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=e?zt(r):Ue(r),a=X(i,t-tt)+tt;return e?Po(a,o):Qr(a,o)}var Ke=BigInt(0),ye=BigInt(1);function Sr(r,t){let e=t.negate();return r?e:t}function Ht(r,t){let e=Er(r.Fp,t.map(n=>n.Z));return t.map((n,o)=>r.fromAffine(n.toAffine(e[o])))}function la(r,t){if(!Number.isSafeInteger(r)||r<=0||r>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+r)}function Fo(r,t){la(r,t);let e=Math.ceil(t/r)+1,n=2**(r-1),o=2**r,s=oe(r),i=BigInt(r);return{windows:e,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function ca(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+=ye);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 _f(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 Af(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 qo=new WeakMap,da=new WeakMap;function zo(r){return da.get(r)||1}function ua(r){if(r!==Ke)throw new Error("invalid wNAF")}var Fe=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>Ke;)e&ye&&(n=n.add(o)),o=o.double(),e>>=ye;return n}precomputeWindow(t,e){let{windows:n,windowSize:o}=Fo(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=Fo(t,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:u,isZero:d,isNeg:l,isNegF:f,offsetF:h}=ca(n,a,i);n=c,d?s=s.add(Sr(f,e[h])):o=o.add(Sr(l,e[u]))}return ua(n),{p:o,f:s}}wNAFUnsafe(t,e,n,o=this.ZERO){let s=Fo(t,this.bits);for(let i=0;i<s.windows&&n!==Ke;i++){let{nextN:a,offset:c,isZero:u,isNeg:d}=ca(n,i,s);if(n=a,!u){let l=e[c];o=o.add(d?l.negate():l)}}return ua(n),o}getPrecomputes(t,e,n){let o=qo.get(e);return o||(o=this.precomputeWindow(e,t),t!==1&&(typeof n=="function"&&(o=n(o)),qo.set(e,o))),o}cached(t,e,n){let o=zo(t);return this.wNAF(o,this.getPrecomputes(o,t,n),e)}unsafe(t,e,n,o){let s=zo(t);return s===1?this._unsafeLadder(t,e,o):this.wNAFUnsafe(s,this.getPrecomputes(s,t,n),e,o)}createCache(t,e){la(e,this.bits),da.set(t,e),qo.delete(t)}hasCache(t){return zo(t)!==1}};function ha(r,t,e,n){let o=t,s=r.ZERO,i=r.ZERO;for(;e>Ke||n>Ke;)e&ye&&(s=s.add(o)),n&ye&&(i=i.add(o)),o=o.double(),e>>=ye,n>>=ye;return{p1:s,p2:i}}function qe(r,t,e,n){_f(e,r),Af(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=Jr(BigInt(o)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let u=oe(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 w=0;w<s;w++){let S=n[w],y=Number(S>>BigInt(h)&u);d[y]=d[y].add(e[w])}let p=i;for(let w=d.length-1,S=i;w>0;w--)S=S.add(d[w]),p=p.add(S);if(f=f.add(p),h!==0)for(let w=0;w<c;w++)f=f.double()}return f}function fa(r,t,e){if(t){if(t.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Uo(t),t}else return Et(r,{isLE:e})}function en(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>Ke))throw new Error(`CURVE.${c} must be positive bigint`)}let o=fa(t.p,e.Fp,n),s=fa(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 ie=BigInt(0),et=BigInt(1),Vo=BigInt(2),If=BigInt(8);function Bf(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 Df(r,t={}){let e=en("edwards",r,t,t.FpFnLE),{Fp:n,Fn:o}=e,s=e.CURVE,{h:i}=s;se(t,{},{uvRatio:"function"});let a=Vo<<BigInt(o.BYTES*8)-et,c=S=>n.create(S),u=t.uvRatio||((S,y)=>{try{return{isValid:!0,value:n.sqrt(n.div(S,y))}}catch{return{isValid:!1,value:ie}}});if(!Bf(n,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function d(S,y,_=!1){let x=_?et:ie;return wr("coordinate "+S,y,x,a),y}function l(S){if(!(S instanceof p))throw new Error("ExtendedPoint expected")}let f=Me((S,y)=>{let{X:_,Y:x,Z:D}=S,R=S.is0();y==null&&(y=R?If:n.inv(D));let M=c(_*y),U=c(x*y),O=n.mul(D,y);if(R)return{x:ie,y:et};if(O!==et)throw new Error("invZ was invalid");return{x:M,y:U}}),h=Me(S=>{let{a:y,d:_}=s;if(S.is0())throw new Error("bad point: ZERO");let{X:x,Y:D,Z:R,T:M}=S,U=c(x*x),O=c(D*D),E=c(R*R),C=c(E*E),k=c(U*y),T=c(E*c(k+O)),b=c(C+c(_*c(U*O)));if(T!==b)throw new Error("bad point: equation left != right (1)");let m=c(x*D),g=c(R*M);if(m!==g)throw new Error("bad point: equation left != right (2)");return!0});class p{constructor(y,_,x,D){this.X=d("x",y),this.Y=d("y",_),this.Z=d("z",x,!0),this.T=d("t",D),Object.freeze(this)}static CURVE(){return s}static fromAffine(y){if(y instanceof p)throw new Error("extended point not allowed");let{x:_,y:x}=y||{};return d("x",_),d("y",x),new p(_,x,et,c(_*x))}static fromBytes(y,_=!1){let x=n.BYTES,{a:D,d:R}=s;y=Oo(wt(y,x,"point")),qt(_,"zip215");let M=Oo(y),U=y[x-1];M[x-1]=U&-129;let O=zt(M),E=_?a:n.ORDER;wr("point.y",O,ie,E);let C=c(O*O),k=c(C-et),T=c(R*C-D),{isValid:b,value:m}=u(k,T);if(!b)throw new Error("bad point: invalid y coordinate");let g=(m&et)===et,v=(U&128)!==0;if(!_&&m===ie&&v)throw new Error("bad point: x=0 and x_0=1");return v!==g&&(m=c(-m)),p.fromAffine({x:m,y:O})}static fromHex(y,_=!1){return p.fromBytes(q("point",y),_)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=8,_=!0){return w.createCache(this,y),_||this.multiply(Vo),this}assertValidity(){h(this)}equals(y){l(y);let{X:_,Y:x,Z:D}=this,{X:R,Y:M,Z:U}=y,O=c(_*U),E=c(R*D),C=c(x*U),k=c(M*D);return O===E&&C===k}is0(){return this.equals(p.ZERO)}negate(){return new p(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:y}=s,{X:_,Y:x,Z:D}=this,R=c(_*_),M=c(x*x),U=c(Vo*c(D*D)),O=c(y*R),E=_+x,C=c(c(E*E)-R-M),k=O+M,T=k-U,b=O-M,m=c(C*T),g=c(k*b),v=c(C*b),A=c(T*k);return new p(m,g,A,v)}add(y){l(y);let{a:_,d:x}=s,{X:D,Y:R,Z:M,T:U}=this,{X:O,Y:E,Z:C,T:k}=y,T=c(D*O),b=c(R*E),m=c(U*x*k),g=c(M*C),v=c((D+R)*(O+E)-T-b),A=g-m,L=g+m,I=c(b-_*T),B=c(v*A),P=c(L*I),N=c(v*I),$=c(A*L);return new p(B,P,$,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:_,f:x}=w.cached(this,y,D=>Ht(p,D));return Ht(p,[_,x])[0]}multiplyUnsafe(y,_=p.ZERO){if(!o.isValid(y))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return y===ie?p.ZERO:this.is0()||y===et?this:w.unsafe(this,y,x=>Ht(p,x),_)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return w.unsafe(this,s.n).is0()}toAffine(y){return f(this,y)}clearCofactor(){return i===et?this:this.multiplyUnsafe(i)}toBytes(){let{x:y,y:_}=this.toAffine(),x=n.toBytes(_);return x[x.length-1]|=y&et?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 Ht(p,y)}static msm(y,_){return qe(p,o,y,_)}_setWindowSize(y){this.precompute(y)}toRawBytes(){return this.toBytes()}}p.BASE=new p(s.Gx,s.Gy,et,c(s.Gx*s.Gy)),p.ZERO=new p(ie,et,et,ie),p.Fp=n,p.Fn=o;let w=new Fe(p,o.BITS);return p.BASE.precompute(8),p}var rn=class{constructor(t){this.ep=t}static fromBytes(t){ko()}static fromHex(t){ko()}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 Cf(r,t,e={}){if(typeof t!="function")throw new Error('"hash" function param is required');se(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||Ne,c=e.adjustScalarBytes||(E=>E),u=e.domain||((E,C,k)=>{if(qt(k,"phflag"),C.length||k)throw new Error("Contexts/pre-hash are not supported");return E});function d(E){return i.create(zt(E))}function l(E){let C=x.secretKey;E=q("private key",E,C);let k=q("hashed private key",t(E),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(E){let{head:C,prefix:k,scalar:T}=l(E),b=o.multiply(T),m=b.toBytes();return{head:C,prefix:k,scalar:T,point:b,pointBytes:m}}function h(E){return f(E).pointBytes}function p(E=Uint8Array.of(),...C){let k=dt(...C);return d(t(u(k,q("context",E),!!n)))}function w(E,C,k={}){E=q("message",E),n&&(E=n(E));let{prefix:T,scalar:b,pointBytes:m}=f(C),g=p(k.context,T,E),v=o.multiply(g).toBytes(),A=p(k.context,v,m,E),L=i.create(g+A*b);if(!i.isValid(L))throw new Error("sign failed: invalid s");let I=dt(v,i.toBytes(L));return wt(I,x.signature,"result")}let S={zip215:!0};function y(E,C,k,T=S){let{context:b,zip215:m}=T,g=x.signature;E=q("signature",E,g),C=q("message",C),k=q("publicKey",k,x.publicKey),m!==void 0&&qt(m,"zip215"),n&&(C=n(C));let v=g/2,A=E.subarray(0,v),L=zt(E.subarray(v,g)),I,B,P;try{I=r.fromBytes(k,m),B=r.fromBytes(A,m),P=o.multiplyUnsafe(L)}catch{return!1}if(!m&&I.isSmallOrder())return!1;let N=p(b,B.toBytes(),I.toBytes(),C);return B.add(I.multiplyUnsafe(N)).subtract(P).clearCofactor().is0()}let _=s.BYTES,x={secretKey:_,publicKey:_,signature:2*_,seed:_};function D(E=a(x.seed)){return wt(E,x.seed,"seed")}function R(E){let C=O.randomSecretKey(E);return{secretKey:C,publicKey:h(C)}}function M(E){return Mt(E)&&E.length===i.BYTES}function U(E,C){try{return!!r.fromBytes(E,C)}catch{return!1}}let O={getExtendedPublicKey:f,randomSecretKey:D,isValidSecretKey:M,isValidPublicKey:U,toMontgomery(E){let{y:C}=r.fromBytes(E),k=x.publicKey,T=k===32;if(!T&&k!==57)throw new Error("only defined for 25519 and 448");let b=T?s.div(et+C,et-C):s.div(C-et,C+et);return s.toBytes(b)},toMontgomerySecret(E){let C=x.secretKey;wt(E,C);let k=t(E.subarray(0,C));return c(k).subarray(0,C)},randomPrivateKey:D,precompute(E=8,C=r.BASE){return C.precompute(E,!1)}};return Object.freeze({keygen:R,getPublicKey:h,sign:w,verify:y,utils:O,Point:r,lengths:x})}function Tf(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=Et(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 Lf(r,t){let e=t.Point;return Object.assign({},t,{ExtendedPoint:e,CURVE:r,nBitLength:e.Fn.BITS,nByteLength:e.Fn.BYTES})}function pa(r){let{CURVE:t,curveOpts:e,hash:n,eddsaOpts:o}=Tf(r),s=Df(t,e),i=Cf(s,n,o);return Lf(r,i)}var Rf=BigInt(0),$t=BigInt(1),ma=BigInt(2),C0=BigInt(3),Pf=BigInt(5),Of=BigInt(8),ze=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),vr={p:ze,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Of,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function kf(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),s=ze,a=r*r%s*r%s,c=V(a,ma,s)*a%s,u=V(c,$t,s)*r%s,d=V(u,Pf,s)*u%s,l=V(d,t,s)*d%s,f=V(l,e,s)*l%s,h=V(f,n,s)*f%s,p=V(h,o,s)*h%s,w=V(p,o,s)*h%s,S=V(w,t,s)*d%s;return{pow_p_5_8:V(S,ma,s)*r%s,b2:a}}function Nf(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var Ho=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Zo(r,t){let e=ze,n=X(t*t*t,e),o=X(n*n*t,e),s=kf(r*o).pow_p_5_8,i=X(r*n*s,e),a=X(t*i*i,e),c=i,u=X(i*Ho,e),d=a===r,l=a===X(-r,e),f=a===X(-r*Ho,e);return d&&(i=c),(l||f)&&(i=u),Vt(i,e)&&(i=X(-i,e)),{isValid:d||l,value:i}}var ae=Et(vr.p,{isLE:!0}),Uf=Et(vr.n,{isLE:!0}),Mf={...vr,Fp:ae,hash:Zi,adjustScalarBytes:Nf,uvRatio:Zo},Gt=pa(Mf);var $o=Ho,Kf=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Ff=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),qf=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),zf=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),ga=r=>Zo($t,r),Vf=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Go=r=>Gt.Point.Fp.create(zt(r)&Vf);function ya(r){let{d:t}=vr,e=ze,n=y=>ae.create(y),o=n($o*r*r),s=n((o+$t)*qf),i=BigInt(-1),a=n((i-t*o)*n(o+t)),{isValid:c,value:u}=Zo(s,a),d=n(u*r);Vt(d,e)||(d=n(-d)),c||(u=d),c||(i=o);let l=n(i*(o-$t)*zf-a),f=u*u,h=n((u+u)*a),p=n(l*Kf),w=n($t-f),S=n($t+f);return new Gt.Point(n(h*S),n(w*p),n(p*S),n(h*w))}function Hf(r){gt(r,64);let t=Go(r.subarray(0,32)),e=ya(t),n=Go(r.subarray(32,64)),o=ya(n);return new Zt(e.add(o))}var Zt=class r extends rn{constructor(t){super(t)}static fromAffine(t){return new r(Gt.Point.fromAffine(t))}assertSame(t){if(!(t instanceof r))throw new Error("RistrettoPoint expected")}init(t){return new r(t)}static hashToCurve(t){return Hf(q("ristrettoHash",t,64))}static fromBytes(t){gt(t,32);let{a:e,d:n}=vr,o=ze,s=D=>ae.create(D),i=Go(t);if(!Xi(ae.toBytes(i),t)||Vt(i,o))throw new Error("invalid ristretto255 encoding 1");let a=s(i*i),c=s($t+e*a),u=s($t-e*a),d=s(c*c),l=s(u*u),f=s(e*n*d-l),{isValid:h,value:p}=ga(s(f*l)),w=s(p*u),S=s(p*w*f),y=s((i+i)*w);Vt(y,o)&&(y=s(-y));let _=s(c*S),x=s(y*_);if(!h||Vt(x,o)||_===Rf)throw new Error("invalid ristretto255 encoding 2");return new r(new Gt.Point(y,_,$t,x))}static fromHex(t){return r.fromBytes(q("ristrettoHex",t,32))}static msm(t,e){return qe(r,Gt.Point.Fn,t,e)}toBytes(){let{X:t,Y:e,Z:n,T:o}=this.ep,s=ze,i=S=>ae.create(S),a=i(i(n+e)*i(n-e)),c=i(t*e),u=i(c*c),{value:d}=ga(i(a*u)),l=i(d*a),f=i(d*c),h=i(l*f*o),p;if(Vt(o*h,s)){let S=i(e*$o),y=i(t*$o);t=S,e=y,p=i(l*Ff)}else p=f;Vt(t*h,s)&&(e=i(-e));let w=i((n-e)*p);return Vt(w,s)&&(w=i(-w)),ae.toBytes(w)}equals(t){this.assertSame(t);let{X:e,Y:n}=this.ep,{X:o,Y:s}=t.ep,i=u=>ae.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)}};Zt.BASE=new Zt(Gt.Point.BASE);Zt.ZERO=new Zt(Gt.Point.ZERO);Zt.Fp=ae;Zt.Fn=Uf;var _r=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},nn=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var ba={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new nn("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 on=ba;var sn=32;var jo,$f=(async()=>{try{return await on.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function Gf(r,t,e){if(r.buffer instanceof ArrayBuffer){let n=await on.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await on.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 Zf(r,t,e){return Gt.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}async function xa(r,t,e){return jo==null&&(jo=await $f),jo?Gf(r,t,e):Zf(r,t,e)}function an(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var cn=class{type="Ed25519";raw;constructor(t){this.raw=Xo(t,sn)}toMultihash(){return Ct.digest(Pe(this))}toCID(){return it.createV1(114,this.toMultihash())}toString(){return Y.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:lt(this.raw,t.raw)}verify(t,e,n){n?.signal?.throwIfAborted();let o=xa(this.raw,e,t);return an(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function Ea(r){return r=Xo(r,sn),new cn(r)}function Xo(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new ft(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}var Xf=Math.pow(2,7),Yf=Math.pow(2,14),Wf=Math.pow(2,21),Yo=Math.pow(2,28),Wo=Math.pow(2,35),Qo=Math.pow(2,42),Jo=Math.pow(2,49),F=128,at=127;function yt(r){if(r<Xf)return 1;if(r<Yf)return 2;if(r<Wf)return 3;if(r<Yo)return 4;if(r<Wo)return 5;if(r<Qo)return 6;if(r<Jo)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Ve(r,t,e=0){switch(yt(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 Qf(r,t,e=0){switch(yt(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 ts(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)*Yo,e<F)||(e=r[t+5],n+=(e&at)*Wo,e<F)||(e=r[t+6],n+=(e&at)*Qo,e<F)||(e=r[t+7],n+=(e&at)*Jo,e<F))return n;throw new RangeError("Could not decode varint")}function Jf(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)*Yo,e<F)||(e=r.get(t+5),n+=(e&at)*Wo,e<F)||(e=r.get(t+6),n+=(e&at)*Qo,e<F)||(e=r.get(t+7),n+=(e&at)*Jo,e<F))return n;throw new RangeError("Could not decode varint")}function Sa(r,t,e=0){return t==null&&(t=mt(yt(r))),t instanceof Uint8Array?Ve(r,t,e):Qf(r,t,e)}function Ar(r,t=0){return r instanceof Uint8Array?ts(r,t):Jf(r,t)}var es=new Float32Array([-0]),ce=new Uint8Array(es.buffer);function _a(r,t,e){es[0]=r,t[e]=ce[0],t[e+1]=ce[1],t[e+2]=ce[2],t[e+3]=ce[3]}function Aa(r,t){return ce[0]=r[t],ce[1]=r[t+1],ce[2]=r[t+2],ce[3]=r[t+3],es[0]}var rs=new Float64Array([-0]),ct=new Uint8Array(rs.buffer);function Ia(r,t,e){rs[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 Ba(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],rs[0]}var tl=BigInt(Number.MAX_SAFE_INTEGER),el=BigInt(Number.MIN_SAFE_INTEGER),St=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 be;if(t<tl&&t>el)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>Da&&(o=0n,++n>Da&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return be;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):be}},be=new St(0,0);be.toBigInt=function(){return 0n};be.zzEncode=be.zzDecode=function(){return this};be.length=function(){return 1};var Da=4294967296n;function Ca(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 Ta(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 ns(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 Lt(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function un(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var os=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,Lt(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 Lt(this,4);return un(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Lt(this,4);return un(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Lt(this,4);let t=Aa(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw Lt(this,4);let t=Ba(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 Lt(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return Ta(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw Lt(this,t);this.pos+=t}else do if(this.pos>=this.len)throw Lt(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 St(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 Lt(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 Lt(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 Lt(this,8);let t=un(this.buf,this.pos+=4),e=un(this.buf,this.pos+=4);return new St(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=ts(this.buf,this.pos);return this.pos+=yt(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 ss(r){return new os(r instanceof Uint8Array?r:r.subarray())}function It(r,t,e){let n=ss(r);return t.decode(n,void 0,e)}function is(r){let t=r??8192,e=t>>>1,n,o=t;return function(i){if(i<1||i>e)return mt(i);o+i>t&&(n=mt(t),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var xe=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function as(){}var us=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},rl=is();function nl(r){return globalThis.Buffer!=null?mt(r):rl(r)}var Br=class{len;head;tail;states;constructor(){this.len=0,this.head=new xe(as,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new xe(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new fs((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(fn,10,St.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=St.fromBigInt(t);return this._push(fn,e.length(),e)}uint64Number(t){return this._push(Ve,yt(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=St.fromBigInt(t).zzEncode();return this._push(fn,e.length(),e)}sint64Number(t){let e=St.fromNumber(t).zzEncode();return this._push(fn,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(cs,1,t?1:0)}fixed32(t){return this._push(Ir,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=St.fromBigInt(t);return this._push(Ir,4,e.lo)._push(Ir,4,e.hi)}fixed64Number(t){let e=St.fromNumber(t);return this._push(Ir,4,e.lo)._push(Ir,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(_a,4,t)}double(t){return this._push(Ia,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(cs,1,0):this.uint32(e)._push(sl,e,t)}string(t){let e=Ca(t);return e!==0?this.uint32(e)._push(ns,e,t):this._push(cs,1,0)}fork(){return this.states=new us(this),this.head=this.tail=new xe(as,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 xe(as,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=nl(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function cs(r,t,e){t[e]=r&255}function ol(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var fs=class extends xe{next;constructor(t,e){super(ol,t,e),this.next=void 0}};function fn(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 Ir(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 sl(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(Br.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(il,t,r),this},Br.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(al,t,r),this});function il(r,t,e){t.set(r,e)}function al(r,t,e){r.length<40?ns(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(H(r),e)}function ls(){return new Br}function Bt(r,t){let e=ls();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var He;(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"})(He||(He={}));function ln(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function we(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 ln("enum",He.VARINT,e,n)}function Dt(r,t){return ln("message",He.LENGTH_DELIMITED,r,t)}var dn=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var vt;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(vt||(vt={}));var ds;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(ds||(ds={}));(function(r){r.codec=()=>we(ds)})(vt||(vt={}));var Dr;(function(r){let t;r.codec=()=>(t==null&&(t=Dt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),vt.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=vt.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)})(Dr||(Dr={}));var hs;(function(r){let t;r.codec=()=>(t==null&&(t=Dt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),vt.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=vt.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)})(hs||(hs={}));var hn=class extends Oe{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,Xr(t);let n=mr(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),Kt(s)}update(t){return ke(this),this.iHash.update(t),this}digestInto(t){ke(this),gt(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()}},ps=(r,t,e)=>new hn(r,t).update(e).digest();ps.create=(r,t)=>new hn(r,t);var Ra=(r,t)=>(r+(r>=0?t:-t)/Pa)/t;function ul(r,t,e){let[[n,o],[s,i]]=t,a=Ra(i*r,e),c=Ra(-o*r,e),u=r-a*n-c*s,d=-a*o-c*i,l=u<Xt,f=d<Xt;l&&(u=-u),f&&(d=-d);let h=oe(Math.ceil(Jr(e)/2))+Ge;if(u<Xt||u>=h||d<Xt||d>=h)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:l,k1:u,k2neg:f,k2:d}}function gs(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function ms(r,t){let e={};for(let n of Object.keys(t))e[n]=r[n]===void 0?t[n]:r[n];return qt(e.lowS,"lowS"),qt(e.prehash,"prehash"),e.format!==void 0&&gs(e.format),e}var ys=class extends Error{constructor(t=""){super(t)}},jt={Err:ys,_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=xr(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let s=n>127?xr(o.length/2|128):"";return xr(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<Xt)throw new t("integer: negative integers are not allowed");let e=xr(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 Ue(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=jt,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}=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)}},Xt=BigInt(0),Ge=BigInt(1),Pa=BigInt(2),pn=BigInt(3),fl=BigInt(4);function $e(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 ll(r,t={}){let e=en("weierstrass",r,t),{Fp:n,Fn:o}=e,s=e.CURVE,{h:i,n:a}=s;se(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=ka(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:v}=b.toAffine(),A=n.toBytes(g);if(qt(m,"isCompressed"),m){d();let L=!n.isOdd(v);return dt(Oa(L),A)}else return dt(Uint8Array.of(4),A,n.toBytes(v))}function f(T){wt(T,void 0,"Point");let{publicKey:b,publicKeyUncompressed:m}=u,g=T.length,v=T[0],A=T.subarray(1);if(g===b&&(v===2||v===3)){let L=n.fromBytes(A);if(!n.isValid(L))throw new Error("bad point: is not on curve, wrong x");let I=w(L),B;try{B=n.sqrt(I)}catch($){let z=$ instanceof Error?": "+$.message:"";throw new Error("bad point: is not on curve, sqrt error"+z)}d();let P=n.isOdd(B);return(v&1)===1!==P&&(B=n.neg(B)),{x:L,y:B}}else if(g===m&&v===4){let L=n.BYTES,I=n.fromBytes(A.subarray(0,L)),B=n.fromBytes(A.subarray(L,L*2));if(!S(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 h=t.toBytes||l,p=t.fromBytes||f;function w(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 S(T,b){let m=n.sqr(b),g=w(T);return n.eql(m,g)}if(!S(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let y=n.mul(n.pow(s.a,pn),fl),_=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(y,_)))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 E))throw new Error("ProjectivePoint expected")}function R(T){if(!c||!c.basises)throw new Error("no endo");return ul(T,c.basises,o.ORDER)}let M=Me((T,b)=>{let{X:m,Y:g,Z:v}=T;if(n.eql(v,n.ONE))return{x:m,y:g};let A=T.is0();b==null&&(b=A?n.ONE:n.inv(v));let L=n.mul(m,b),I=n.mul(g,b),B=n.mul(v,b);if(A)return{x:n.ZERO,y:n.ZERO};if(!n.eql(B,n.ONE))throw new Error("invZ was invalid");return{x:L,y:I}}),U=Me(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(!S(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,v){return m=new E(n.mul(m.X,T),m.Y,m.Z),b=Sr(g,b),m=Sr(v,m),b.add(m)}class E{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 E)throw new Error("projective point not allowed");return n.is0(m)&&n.is0(g)?E.ZERO:new E(m,g,n.ONE)}static fromBytes(b){let m=E.fromAffine(p(wt(b,void 0,"point")));return m.assertValidity(),m}static fromHex(b){return E.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(pn),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:v}=this,{X:A,Y:L,Z:I}=b,B=n.eql(n.mul(m,I),n.mul(A,v)),P=n.eql(n.mul(g,I),n.mul(L,v));return B&&P}negate(){return new E(this.X,n.neg(this.Y),this.Z)}double(){let{a:b,b:m}=s,g=n.mul(m,pn),{X:v,Y:A,Z:L}=this,I=n.ZERO,B=n.ZERO,P=n.ZERO,N=n.mul(v,v),$=n.mul(A,A),z=n.mul(L,L),K=n.mul(v,A);return K=n.add(K,K),P=n.mul(v,L),P=n.add(P,P),I=n.mul(b,P),B=n.mul(g,z),B=n.add(I,B),I=n.sub($,B),B=n.add($,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,L),z=n.add(z,z),N=n.mul(z,K),I=n.sub(I,N),P=n.mul(z,$),P=n.add(P,P),P=n.add(P,P),new E(I,B,P)}add(b){D(b);let{X:m,Y:g,Z:v}=this,{X:A,Y:L,Z:I}=b,B=n.ZERO,P=n.ZERO,N=n.ZERO,$=s.a,z=n.mul(s.b,pn),K=n.mul(m,A),G=n.mul(g,L),W=n.mul(v,I),pt=n.add(m,g),Z=n.add(A,L);pt=n.mul(pt,Z),Z=n.add(K,G),pt=n.sub(pt,Z),Z=n.add(m,v);let st=n.add(A,I);return Z=n.mul(Z,st),st=n.add(K,W),Z=n.sub(Z,st),st=n.add(g,v),B=n.add(L,I),st=n.mul(st,B),B=n.add(G,W),st=n.sub(st,B),N=n.mul($,Z),B=n.mul(z,W),N=n.add(B,N),B=n.sub(G,N),N=n.add(G,N),P=n.mul(B,N),G=n.add(K,K),G=n.add(G,K),W=n.mul($,W),Z=n.mul(z,Z),G=n.add(G,W),W=n.sub(K,W),W=n.mul($,W),Z=n.add(Z,W),K=n.mul(G,Z),P=n.add(P,K),K=n.mul(st,Z),B=n.mul(pt,B),B=n.sub(B,K),K=n.mul(pt,G),N=n.mul(st,N),N=n.add(N,K),new E(B,P,N)}subtract(b){return this.add(b.negate())}is0(){return this.equals(E.ZERO)}multiply(b){let{endo:m}=t;if(!o.isValidNot0(b))throw new Error("invalid scalar: out of range");let g,v,A=L=>k.cached(this,L,I=>Ht(E,I));if(m){let{k1neg:L,k1:I,k2neg:B,k2:P}=R(b),{p:N,f:$}=A(I),{p:z,f:K}=A(P);v=$.add(K),g=O(m.beta,N,z,L,B)}else{let{p:L,f:I}=A(b);g=L,v=I}return Ht(E,[g,v])[0]}multiplyUnsafe(b){let{endo:m}=t,g=this;if(!o.isValid(b))throw new Error("invalid scalar: out of range");if(b===Xt||g.is0())return E.ZERO;if(b===Ge)return g;if(k.hasCache(this))return this.multiply(b);if(m){let{k1neg:v,k1:A,k2neg:L,k2:I}=R(b),{p1:B,p2:P}=ha(E,g,A,I);return O(m.beta,B,P,v,L)}else return k.unsafe(g,b)}multiplyAndAddUnsafe(b,m,g){let v=this.multiplyUnsafe(m).add(b.multiplyUnsafe(g));return v.is0()?void 0:v}toAffine(b){return M(this,b)}isTorsionFree(){let{isTorsionFree:b}=t;return i===Ge?!0:b?b(E,this):k.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:b}=t;return i===Ge?this:b?b(E,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(b=!0){return qt(b,"isCompressed"),this.assertValidity(),h(E,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 Ht(E,b)}static msm(b,m){return qe(E,o,b,m)}static fromPrivateKey(b){return E.BASE.multiply($e(o,b))}}E.BASE=new E(s.Gx,s.Gy,n.ONE),E.ZERO=new E(n.ZERO,n.ONE,n.ZERO),E.Fp=n,E.Fn=o;let C=o.BITS,k=new Fe(E,t.endo?Math.ceil(C/2):C);return E.BASE.precompute(8),E}function Oa(r){return Uint8Array.of(r?2:3)}function ka(r,t){return{secretKey:t.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function dl(r,t={}){let{Fn:e}=r,n=t.randomBytes||Ne,o=Object.assign(ka(r.Fp,e),{seed:Mo(e.ORDER)});function s(h){try{return!!$e(e,h)}catch{return!1}}function i(h,p){let{publicKey:w,publicKeyUncompressed:S}=o;try{let y=h.length;return p===!0&&y!==w||p===!1&&y!==S?!1:!!r.fromBytes(h)}catch{return!1}}function a(h=n(o.seed)){return Ko(wt(h,o.seed,"seed"),e.ORDER)}function c(h,p=!0){return r.BASE.multiply($e(e,h)).toBytes(p)}function u(h){let p=a(h);return{secretKey:p,publicKey:c(p)}}function d(h){if(typeof h=="bigint")return!1;if(h instanceof r)return!0;let{secretKey:p,publicKey:w,publicKeyUncompressed:S}=o;if(e.allowedLengths||p===w)return;let y=q("key",h).length;return y===w||y===S}function l(h,p,w=!0){if(d(h)===!0)throw new Error("first arg must be private key");if(d(p)===!1)throw new Error("second arg must be public key");let S=$e(e,h);return r.fromHex(p).multiply(S).toBytes(w)}return Object.freeze({getPublicKey:c,getSharedSecret:l,keygen:u,Point:r,utils:{isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a,isValidPrivateKey:s,randomPrivateKey:a,normPrivateKeyToScalar:h=>$e(e,h),precompute(h=8,p=r.BASE){return p.precompute(h,!1)}},lengths:o})}function hl(r,t,e={}){Xr(t),se(e,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let n=e.randomBytes||Ne,o=e.hmac||((m,...g)=>ps(t,m,dt(...g))),{Fp:s,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:u,getPublicKey:d,getSharedSecret:l,utils:f,lengths:h}=dl(r,e),p={prehash:!1,lowS:typeof e.lowS=="boolean"?e.lowS:!1,format:void 0,extraEntropy:!1},w="compact";function S(m){let g=a>>Ge;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 _(m,g){gs(g);let v=h.signature,A=g==="compact"?v:g==="recovered"?v+1:void 0;return wt(m,A,`${g} signature`)}class x{constructor(g,v,A){this.r=y("r",g),this.s=y("s",v),A!=null&&(this.recovery=A),Object.freeze(this)}static fromBytes(g,v=w){_(g,v);let A;if(v==="der"){let{r:P,s:N}=jt.toSig(wt(g));return new x(P,N)}v==="recovered"&&(A=g[0],v="compact",g=g.subarray(1));let L=i.BYTES,I=g.subarray(0,L),B=g.subarray(L,L*2);return new x(i.fromBytes(I),i.fromBytes(B),A)}static fromHex(g,v){return this.fromBytes(he(g),v)}addRecoveryBit(g){return new x(this.r,this.s,g)}recoverPublicKey(g){let v=s.ORDER,{r:A,s:L,recovery:I}=this;if(I==null||![0,1,2,3].includes(I))throw new Error("recovery id invalid");if(a*Pa<v&&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),$=r.fromBytes(dt(Oa((I&1)===0),N)),z=i.inv(P),K=R(q("msgHash",g)),G=i.create(-K*z),W=i.create(L*z),pt=r.BASE.multiplyUnsafe(G).add($.multiplyUnsafe(W));if(pt.is0())throw new Error("point at infinify");return pt.assertValidity(),pt}hasHighS(){return S(this.s)}toBytes(g=w){if(gs(g),g==="der")return he(jt.hexFromSig(this));let v=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 dt(Uint8Array.of(this.recovery),v,A)}return dt(v,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 v=Ue(g),A=g.length*8-c;return A>0?v>>BigInt(A):v},R=e.bits2int_modN||function(g){return i.create(D(g))},M=oe(c);function U(m){return wr("num < 2^"+c,m,Xt,M),i.toBytes(m)}function O(m,g){return wt(m,void 0,"message"),g?wt(t(m),void 0,"prehashed message"):m}function E(m,g,v){if(["recovered","canonical"].some(G=>G in v))throw new Error("sign() legacy options not supported");let{lowS:A,prehash:L,extraEntropy:I}=ms(v,p);m=O(m,L);let B=R(m),P=$e(i,g),N=[U(P),U(B)];if(I!=null&&I!==!1){let G=I===!0?n(h.secretKey):I;N.push(q("extraEntropy",G))}let $=dt(...N),z=B;function K(G){let W=D(G);if(!i.isValidNot0(W))return;let pt=i.inv(W),Z=r.BASE.multiply(W).toAffine(),st=i.create(Z.x);if(st===Xt)return;let Mr=i.create(pt*i.create(z+st*P));if(Mr===Xt)return;let Ys=(Z.x===st?0:2)|Number(Z.y&Ge),Ws=Mr;return A&&S(Mr)&&(Ws=i.neg(Mr),Ys^=1),new x(st,Ws,Ys)}return{seed:$,k2sig:K}}function C(m,g,v={}){m=q("message",m);let{seed:A,k2sig:L}=E(m,g,v);return Wi(t.outputLen,i.BYTES,o)(A,L)}function k(m){let g,v=typeof m=="string"||Mt(m),A=!v&&m!==null&&typeof m=="object"&&typeof m.r=="bigint"&&typeof m.s=="bigint";if(!v&&!A)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(A)g=new x(m.r,m.s);else if(v){try{g=x.fromBytes(q("sig",m),"der")}catch(L){if(!(L instanceof jt.Err))throw L}if(!g)try{g=x.fromBytes(q("sig",m),"compact")}catch{return!1}}return g||!1}function T(m,g,v,A={}){let{lowS:L,prehash:I,format:B}=ms(A,p);if(v=q("publicKey",v),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(v);if(L&&P.hasHighS())return!1;let{r:$,s:z}=P,K=R(g),G=i.inv(z),W=i.create(K*G),pt=i.create($*G),Z=r.BASE.multiplyUnsafe(W).add(N.multiplyUnsafe(pt));return Z.is0()?!1:i.create(Z.x)===$}catch{return!1}}function b(m,g,v={}){let{prehash:A}=ms(v,p);return g=O(g,A),x.fromBytes(m,"recovered").recoverPublicKey(g).toBytes()}return Object.freeze({keygen:u,getPublicKey:d,getSharedSecret:l,utils:f,lengths:h,Point:r,sign:C,verify:T,recoverPublicKey:b,Signature:x,hash:t})}function pl(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=Et(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 ml(r){let{CURVE:t,curveOpts:e}=pl(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 gl(r,t){let e=t.Point;return Object.assign({},t,{ProjectivePoint:e,CURVE:Object.assign({},r,tn(e.Fn.ORDER,e.Fn.BITS))})}function Na(r){let{CURVE:t,curveOpts:e,hash:n,ecdsaOpts:o}=ml(r),s=ll(t,e),i=hl(s,n,o);return gl(r,i)}function Ua(r,t){let e=n=>Na({...r,hash:n});return{...e(t),create:e}}var xs={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},yl={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Ma=BigInt(2);function bl(r){let t=xs.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=V(d,e,t)*d%t,f=V(l,e,t)*d%t,h=V(f,Ma,t)*u%t,p=V(h,o,t)*h%t,w=V(p,s,t)*p%t,S=V(w,a,t)*w%t,y=V(S,c,t)*S%t,_=V(y,a,t)*w%t,x=V(_,e,t)*d%t,D=V(x,i,t)*p%t,R=V(D,n,t)*u%t,M=V(R,Ma,t);if(!bs.eql(bs.sqr(M),r))throw new Error("Cannot find square root");return M}var bs=Et(xs.p,{sqrt:bl}),Ze=Ua({...xs,Fp:bs,lowS:!0,endo:yl},Gi);function Ka(r,t,e,n){let o=fr.digest(e instanceof Uint8Array?e:e.subarray());if(an(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),Ze.verify(t,s,r))).catch(s=>{throw s.name==="AbortError"?s:new _r(String(s))});try{return n?.signal?.throwIfAborted(),Ze.verify(t,o.digest,r)}catch(s){throw new _r(String(s))}}var mn=class{type="secp256k1";raw;_key;constructor(t){this._key=qa(t),this.raw=Fa(this._key)}toMultihash(){return Ct.digest(Pe(this))}toCID(){return it.createV1(114,this.toMultihash())}toString(){return Y.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:lt(this.raw,t.raw)}verify(t,e,n){return Ka(this._key,e,t,n)}};function za(r){return new mn(r)}function Fa(r){return Ze.ProjectivePoint.fromHex(r).toRawBytes(!0)}function qa(r){try{return Ze.ProjectivePoint.fromHex(r),r}catch(t){throw new Fr(String(t))}}function Va(r){let{Type:t,Data:e}=Dr.decode(r.digest),n=e??new Uint8Array;switch(t){case vt.Ed25519:return Ea(n);case vt.secp256k1:return za(n);case vt.ECDSA:return Ci(n);default:throw new or}}function Pe(r){return Dr.encode({Type:vt[r.type],Data:r.raw})}var Ha=Symbol.for("nodejs.util.inspect.custom"),xl=114,Cr=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()})`}[jn]=!0;toString(){return this.string==null&&(this.string=Y.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return it.createV1(xl,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return lt(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return lt(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[Ha](){return`PeerId(${this.toString()})`}},gn=class extends Cr{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},yn=class extends Cr{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},bn=class extends Cr{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},wl=2336,xn=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=Ct.digest(H(this.url))}[Ha](){return`PeerId(${this.url})`}[jn]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return it.createV1(wl,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=Q(t)),t.toString()===this.toString())}};function $a(r){if(Sl(r))return new gn({multihash:r});if(El(r))try{let t=Va(r);if(t.type==="Ed25519")return new yn({multihash:r,publicKey:t});if(t.type==="secp256k1")return new bn({multihash:r,publicKey:t})}catch{let e=Q(r.digest);return new xn(new URL(e))}throw new qr("Supplied PeerID Multihash is invalid")}function El(r){return r.code===Ct.code}function Sl(r){return r.code===fr.code}function ws(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 wn(r){let t=cr(Y.decode(`z${r}`));return $a(t)}var En=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 ws(this.set.entries(),t=>{let e=wn(t[0]);return[e,e]})}forEach(t){this.set.forEach(e=>{let n=wn(e);t(n,n,this)})}has(t){return this.set.has(t.toString())}values(){return ws(this.set.values(),t=>wn(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 Es(){return new En}var Ss={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Ga={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Za=new globalThis.TextEncoder;function vl(r,t){let e=Ss[t],n=Ga[t];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(t,n*e);return n}function _l(r,t,e){if(e.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Ss[t],o=Ga[t],s=r;for(;s.length>0;){let i=Za.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 vs(r,{size:t=32,utf8Buffer:e}={}){if(!Ss[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 _l(r,t,e);r=Za.encode(r)}return vl(r,t)}var Tr={hash:r=>Number(vs(r,{size:32})),hashV:(r,t)=>Al(Tr.hash(r,t))};function Al(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),H(t,"base16")}var _s=64,Rt=class{fp;h;seed;constructor(t,e,n,o=2){if(o>_s)throw new TypeError("Invalid Fingerprint Size");let s=e.hashV(t,n),i=xt(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=e,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(t){return t?.fp instanceof Uint8Array?lt(this.fp,t.fp):!1}};function Ee(r,t){return Math.floor(Math.random()*(t-r))+r}var Se=class{contents;constructor(t){this.contents=new Array(t).fill(null)}has(t){if(!(t instanceof Rt))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof Rt))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 Rt))throw new TypeError("Invalid Fingerprint");let e=Ee(0,this.contents.length-1),n=this.contents[e];return this.contents[e]=t,n}remove(t){if(!(t instanceof Rt))throw new TypeError("Invalid Fingerprint");let e=this.contents.findIndex(n=>t.equals(n));return e>-1?(this.contents[e]=null,!0):!1}};var Il=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??Tr,this.seed=t.seed??Ee(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=H(t));let e=new Rt(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 Se(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new Se(this.bucketSize)),this.buckets[n].add(e)||this.buckets[o].add(e))return this.count++,!0;let s=[n,o],i=s[Ee(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new Se(this.bucketSize));for(let a=0;a<Il;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 Se(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(t){typeof t=="string"&&(t=H(t));let e=new Rt(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 Rt(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}},Bl={1:.5,2:.84,4:.95,8:.98};function Dl(r=.001){return r>.002?2:r>1e-5?4:8}function ja(r,t=.001){let e=Dl(t),n=Bl[e],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),_s);return{filterSize:o,bucketSize:e,fingerprintSize:s}}var Sn=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??Tr,this.seed=t.seed??Ee(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=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 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=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 As(r,t=.001,e){return new Sn({...ja(r,t),...e??{}})}function ue(r){let t=r.getComponents(),e={},n=0;if(t[n]?.name==="ip6zone"&&(e.zone=`${t[n].value}`,n++),t[n].name==="ip4"||t[n].name==="ip6"||t[n].name==="dns"||t[n].name==="dns4"||t[n].name==="dns6"?(e.type=t[n].name,e.host=t[n].value,n++):t[n].name==="dnsaddr"&&(e.type=t[n].name,e.host=`_dnsaddr.${t[n].value}`,n++),(t[n]?.name==="tcp"||t[n]?.name==="udp")&&(e.protocol=t[n].name==="tcp"?"tcp":"udp",e.port=parseInt(`${t[n].value}`),n++),t[n]?.name==="ipcidr"&&(e.type==="ip4"?e.cidr=parseInt(`${t[n].value}`):e.type==="ip6"&&(e.cidr=`${t[n].value}`),n++),e.type==null||e.host==null)throw new ft(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return t[n]?.name==="tls"&&t[n+1]?.name==="sni"&&(e.sni=t[n+1].value,n+=2),e}var vn=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 Xa=45,Cl=15,je=new vn;function _n(r){if(!(r.length>Cl))return je.new(r).parseWith(()=>je.readIPv4Addr())}function An(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Xa))return je.new(r).parseWith(()=>je.readIPv6Addr())}function Xe(r,t=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>Xa)return;let e=je.new(r).parseWith(()=>je.readIPAddr());if(e)return t&&e.length===4?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,e[0],e[1],e[2],e[3]]):e}function Ya(r,t,e){let n=0;for(let o of r)if(!(n<t)){if(n>e)break;if(o!==255)return!1;n++}return!0}function Wa(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 Is(r){switch(r.length){case ve:return r.join(".");case _e:{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 Qa(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 Ja(r){let t="0x";for(let e of r)t+=(e>>4).toString(16)+(e&15).toString(16);return t}var ve=4,_e=16,Oy=parseInt("0xFFFF",16),Tl=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Rr(r,t){t.length===_e&&r.length===ve&&Ya(t,0,11)&&(t=t.slice(12)),t.length===ve&&r.length===_e&&Wa(r,Tl,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 tc(r,t){if(typeof t=="string"&&(t=Xe(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 Bs(r){let[t,e]=r.split("/");if(!t||!e)throw new Error("Failed to parse given CIDR: "+r);let n=ve,o=_n(t);if(o==null&&(n=_e,o=An(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=Ds(s,8*n);return{network:Rr(o,i),mask:i}}function Ds(r,t){if(t!==8*ve&&t!==8*_e)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 Pr=class{constructor(t,e){if(e==null)({network:this.network,mask:this.mask}=Bs(t));else{let n=Xe(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=Xe(e);if(s==null)throw new Error("Failed to parse mask");this.mask=s}else this.mask=Ds(o,8*n.length);this.network=Rr(n,this.mask)}}contains(t){return tc({network:this.network,mask:this.mask},t)}toString(){let t=Qa(this.mask),e=t!==-1?String(t):Ja(this.mask);return Is(this.network)+"/"+e}};function ec(r,t){return new Pr(r).contains(t)}function rc(r){try{let t=ue(r);switch(t.type){case"ip6":return ec("2000::/3",t.host);default:return!1}}catch{return!1}}function Ye(r){return!!_n(r)}function In(r){return!!An(r)}var oc=Fc(nc(),1),Ll=["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"],Rl=Ll.map(r=>new oc.Netmask(r));function Cs(r){for(let t of Rl)if(t.contains(r))return!0;return!1}function Pl(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function Ol(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 Cs(o)}function kl(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function Nl(r){let t=r.split(":"),e=t[t.length-1];return Cs(e)}function Ul(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 Bn(r){if(Ye(r))return Cs(r);if(Pl(r))return Ol(r);if(kl(r))return Nl(r);if(In(r))return Ul(r)}function sc(r){try{let t=ue(r);switch(t.type){case"ip4":case"ip6":return Bn(t.host)??!1;default:return t.host==="localhost"}}catch{return!1}}function We(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var Dn=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}},Qe=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new Dn(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 Dn(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 Ts=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function Cn(r={}){return Ml(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 Ml(r,t){t=t??{};let e=t.onEnd,n=new Qe,o,s,i,a=We(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((S,y)=>{s=_=>{s=null,n.push(_);try{S(r(n))}catch(x){y(x)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=We()})}},u=S=>s!=null?s(S):(n.push(S),o),d=S=>(n=new Qe,s!=null?s({error:S}):(n.push({error:S}),o)),l=S=>{if(i)return o;if(t?.objectMode!==!0&&S?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:S})},f=S=>i?o:(i=!0,S!=null?d(S):u({done:!0})),h=()=>(n=new Qe,f(),{done:!0}),p=S=>(f(S),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:p,push:l,end:f,get readableLength(){return n.size},onEmpty:async S=>{let y=S?.signal;if(y?.throwIfAborted(),n.isEmpty())return;let _,x;y!=null&&(_=new Promise((D,R)=>{x=()=>{R(new Ts)},y.addEventListener("abort",x)}));try{await Promise.race([a.promise,_])}finally{x!=null&&y!=null&&y?.removeEventListener("abort",x)}}},e==null)return o;let w=o;return o={[Symbol.asyncIterator](){return this},next(){return w.next()},throw(S){return w.throw(S),e!=null&&(e(S),e=void 0),{done:!0}},return(){return w.return(),e!=null&&(e(),e=void 0),{done:!0}},push:l,end(S){return w.end(S),e!=null&&(e(S),e=void 0),o},get readableLength(){return w.readableLength},onEmpty:S=>w.onEmpty(S)},o}var Ls=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},Rs=class extends Error{constructor(t){super(),this.name="AbortError",this.message=t}},ic=r=>globalThis.DOMException===void 0?new Rs(r):new DOMException(r),ac=r=>{let t=r.reason===void 0?ic("This operation was aborted."):r.reason;return t instanceof Error?t:ic(t)};function Ps(r,t){let{milliseconds:e,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=t,i,a,u=new Promise((d,l)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(t.signal){let{signal:h}=t;h.aborted&&l(ac(h)),a=()=>{l(ac(h))},h.addEventListener("abort",a,{once:!0})}if(e===Number.POSITIVE_INFINITY){r.then(d,l);return}let f=new Ls;i=s.setTimeout.call(void 0,()=>{if(n){try{d(n())}catch(h){l(h)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?d():o instanceof Error?l(o):(f.message=o??`Promise timed out after ${e} milliseconds`,l(f))},e),(async()=>{try{d(await r)}catch(h){l(h)}})()}).finally(()=>{u.clear(),a&&t.signal&&t.signal.removeEventListener("abort",a)});return u.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},u}var Kl=r=>{let t=r.addEventListener||r.on||r.addListener,e=r.removeEventListener||r.off||r.removeListener;if(!t||!e)throw new TypeError("Emitter is not compatible");return{addListener:t.bind(r),removeListener:e.bind(r)}};function Fl(r,t,e){let n,o=new Promise((s,i)=>{if(e={rejectionEvents:["error"],multiArgs:!1,resolveImmediately:!1,...e},!(e.count>=0&&(e.count===Number.POSITIVE_INFINITY||Number.isInteger(e.count))))throw new TypeError("The `count` option should be at least 0 or more");e.signal?.throwIfAborted();let a=[t].flat(),c=[],{addListener:u,removeListener:d}=Kl(r),l=(...h)=>{let p=e.multiArgs?h:h[0];e.filter&&!e.filter(p)||(c.push(p),e.count===c.length&&(n(),s(c)))},f=h=>{n(),i(h)};n=()=>{for(let h of a)d(h,l);for(let h of e.rejectionEvents)d(h,f)};for(let h of a)u(h,l);for(let h of e.rejectionEvents)u(h,f);e.signal&&e.signal.addEventListener("abort",()=>{f(e.signal.reason)},{once:!0}),e.resolveImmediately&&s(c)});if(o.cancel=n,typeof e.timeout=="number"){let s=Ps(o,{milliseconds:e.timeout});return s.cancel=n,s}return o}function Je(r,t,e){typeof e=="function"&&(e={filter:e}),e={...e,count:1,resolveImmediately:!1};let n=Fl(r,t,e),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}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 Tn=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}},Ae=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"};function ql(r){return r.reason}async function Ln(r,t,e){if(t==null)return r;let n=e?.translateError??ql;if(t.aborted)return r.catch(()=>{}),Promise.reject(n(t));let o;try{return await Promise.race([r,new Promise((s,i)=>{o=()=>{i(n(t))},t.addEventListener("abort",o)})])}finally{o!=null&&t.removeEventListener("abort",o)}}var Rn=class{deferred;signal;constructor(t){this.signal=t,this.deferred=We(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Ot)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function zl(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Pn=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=zl(),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 Ot),this.cleanup())}async join(t={}){let e=new Rn(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 Ln(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 On=class extends zr{concurrency;maxSize;queue;pending;sort;paused;constructor(t={}){super(),this.concurrency=t.concurrency??Number.POSITIVE_INFINITY,this.maxSize=t.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,t.metricName!=null&&t.metrics?.registerMetricGroup(t.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=t.sort,this.queue=[],this.emitEmpty=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")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let t;for(let e of this.queue)if(e.status==="queued"){t=e;break}return t==null?!1:(this.safeDispatchEvent("active"),this.pending++,t.run().finally(()=>{for(let e=0;e<this.queue.length;e++)if(this.queue[e]===t){this.queue.splice(e,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(t){this.queue.push(t),this.sort!=null&&this.queue.sort(this.sort)}async add(t,e){if(e?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Tn;let n=new Pn(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 Ot)}),this.clear()}async onEmpty(t){this.size!==0&&await Je(this,"empty",t)}async onSizeLessThan(t,e){this.size<t||await Je(this,"next",{...e,filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await Je(this,"idle",t)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(t){t?.signal?.throwIfAborted();let e=Cn({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 Ot("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",s),this.addEventListener("idle",i),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),t?.signal?.removeEventListener("abort",a),n()}}};function Nr(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}var ot=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Yt=class extends Error{static name="ValidationError";name="ValidationError"},kn=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Nn=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function ks(r){return t=>Q(t,r)}function Ns(r){return t=>H(t,r)}function tr(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Ie(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(t)}function cc(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==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=Ie(n);return Nt([e,o],e.length+o.length)}function uc(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=te.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=Ie(n);return Nt([e,o],e.length+o.length)}function Us(r){let t=r.subarray(0,r.length-2),e=r.subarray(r.length-2),n=Q(t,"base32"),o=tr(e);return`${n}:${o}`}var Ms=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},fc=function(r){let t=0;r=r.toString().trim();let e=r.split(":",8),n;for(n=0;n<e.length;n++){let s=Ye(e[n]),i;s&&(i=Ms(e[n]),e[n]=Q(i.subarray(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,Q(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},lc=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(".")},dc=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 hc(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 Os=Object.values(lr).map(r=>r.decoder),Vl=(function(){let r=Os[0].or(Os[1]);return Os.slice(2).forEach(t=>r=r.or(t)),r})();function pc(r){return Vl.decode(r)}function mc(r){return t=>r.encoder.encode(t)}function Hl(r){if(parseInt(r).toString()!==r)throw new Yt("Value must be an integer")}function $l(r){if(r<0)throw new Yt("Value must be a positive integer, or zero")}function Gl(r){return t=>{if(t>r)throw new Yt(`Value must be smaller than or equal to ${r}`)}}function Zl(...r){return t=>{for(let e of r)e(t)}}var Ur=Zl(Hl,$l,Gl(65535));var rt=-1,Ks=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 Nn(`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)}))}},Wt=new Ks,Rd=[{code:4,name:"ip4",size:32,valueToBytes:Ms,bytesToValue:lc,validate:r=>{if(!Ye(r))throw new Yt(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Ie,bytesToValue:tr,validate:Ur},{code:273,name:"udp",size:16,valueToBytes:Ie,bytesToValue:tr,validate:Ur},{code:33,name:"dccp",size:16,valueToBytes:Ie,bytesToValue:tr,validate:Ur},{code:41,name:"ip6",size:128,valueToBytes:fc,bytesToValue:dc,stringToValue:hc,validate:r=>{if(!In(r))throw new Yt(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:rt},{code:43,name:"ipcidr",size:8,bytesToValue:ks("base10"),valueToBytes:Ns("base10")},{code:53,name:"dns",size:rt},{code:54,name:"dns4",size:rt},{code:55,name:"dns6",size:rt},{code:56,name:"dnsaddr",size:rt},{code:132,name:"sctp",size:16,valueToBytes:Ie,bytesToValue:tr,validate:Ur},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:rt,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:rt,bytesToValue:ks("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Ns("base58btc")(r):it.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Us,valueToBytes:cc},{code:445,name:"onion3",size:296,bytesToValue:Us,valueToBytes:uc},{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:mc(uo),valueToBytes:pc},{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}];Rd.forEach(r=>{Wt.addProtocol(r)});function gc(r){let t=[],e=0;for(;e<r.length;){let n=Ar(r,e),o=Wt.getProtocol(n),s=yt(n),i=Pd(o,r,e+s),a=0;i>0&&o.size===rt&&(a=yt(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)??Q(l)}t.push(u),e+=c}return t}function yc(r){let t=0,e=[];for(let n of r){if(n.bytes==null){let o=Wt.getProtocol(n.code),s=yt(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=yt(a)));let u=new Uint8Array(s+c+a),d=0;Ve(n.code,u,d),d+=s,i!=null&&(o.size===rt&&(Ve(a,u,d),d+=c),u.set(i,d)),n.bytes=u}e.push(n.bytes),t+=n.bytes.byteLength}return Nt(e,t)}function bc(r){if(r.charAt(0)!=="/")throw new ot('String multiaddr must start with "/"');let t=[],e="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(e==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=Wt.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 xc(r){return`/${r.flatMap(t=>{if(t.value==null)return t.name;let e=Wt.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 Pd(r,t,e){return r.size==null||r.size===0?0:r.size>0?r.size/8:Ar(t,e)}var Od=Symbol.for("nodejs.util.inspect.custom"),zs=Symbol.for("@multiformats/multiaddr");function kd(r){if(r==null&&(r="/"),wc(r))return r.getComponents();if(r instanceof Uint8Array)return gc(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),bc(r);if(Array.isArray(r))return r;throw new ot("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Un=class r{[zs]=!0;#t;#e;#r;constructor(t="/",e={}){this.#t=kd(t),e.validate!==!1&&Nd(this)}get bytes(){return this.#r==null&&(this.#r=yc(this.#t)),this.#r}toString(){return this.#e==null&&(this.#e=xc(this.#t)),this.#e}toJSON(){return this.toString()}getComponents(){return[...this.#t.map(t=>({...t}))]}encapsulate(t){let e=new r(t);return new r([...this.#t,...e.getComponents()],{validate:!1})}decapsulate(t){let e=t.toString(),n=this.toString(),o=n.lastIndexOf(e);if(o<0)throw new kn(`Address ${this.toString()} does not contain subaddress: ${e}`);return new r(n.slice(0,o),{validate:!1})}decapsulateCode(t){let e;for(let n=this.#t.length-1;n>-1;n--)if(this.#t[n].code===t){e=n;break}return new r(this.#t.slice(0,e),{validate:!1})}equals(t){return lt(this.bytes,t.bytes)}[Od](){return`Multiaddr(${this.toString()})`}};function Nd(r){r.getComponents().forEach(t=>{let e=Wt.getProtocol(t.code);t.value!=null&&e.validate?.(t.value)})}function wc(r){return!!r?.[zs]}function Ec(r){return new Un(r)}var Ud=4194304,Mn=class extends Error{static name="UnwrappedError";name="UnwrappedError"},Hs=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},$s=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Gs=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Md(r){return typeof r?.closeRead=="function"}function Kd(r){return typeof r?.close=="function"}function Vs(r){return Md(r)?r.readStatus==="closing"||r.readStatus==="closed":Kd(r)?r.status!=="open":!1}function Fd(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function qd(r,t){let e=t?.maxBufferSize??Ud,n=new J,o=Promise.withResolvers(),s=!1;if(!Fd(r))throw new ft("Argument should be a Stream or a Multiaddr");let i=d=>{if(n.append(d.data),n.byteLength>e){let l=n.byteLength;n.consume(n.byteLength),o.reject(new Error(`Read buffer overflow - ${l} > ${e}`))}o.resolve()};r.addEventListener("message",i);let a=d=>{d.error!=null?o.reject(d.error):o.resolve()};r.addEventListener("close",a);let c=()=>{o.resolve()};r.addEventListener("remoteCloseWrite",c);let u={readBuffer:n,async read(d){if(s===!0)throw new Mn("Stream was unwrapped");if(Vs(r)){if(d?.bytes==null)return null;if(n.byteLength<d.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,d.bytes),new Ae(`Unexpected EOF - stream closed after reading ${n.byteLength}/${d.bytes} bytes`)}let l=d?.bytes??1;for(;;){if(n.byteLength>=l){o.resolve();break}if(await Ln(o.promise,d?.signal),Vs(r)){if(n.byteLength===0&&d?.bytes==null)return null;break}o=Promise.withResolvers()}let f=d?.bytes??n.byteLength;if(n.byteLength<f){if(Vs(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,f),new Ae(`Unexpected EOF - stream closed while reading ${n.byteLength}/${f} bytes`);return u.read(d)}let h=n.sublist(0,f);return n.consume(f),h},async write(d,l){if(s===!0)throw new Mn("Stream was unwrapped");r.send(d)||await Je(r,"drain",{signal:l?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,r.removeEventListener("message",i),r.removeEventListener("close",a),r.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.push(n))),r}};return u}function zd(r,t={}){let e=qd(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=yt(t.maxDataLength));let n=t?.lengthDecoder??Ar,o=t?.lengthEncoder??Sa;return{async read(i){let a=-1,c=new J;for(;;){let d=await e.read({...i,bytes:1});if(d==null)break;c.append(d);try{a=n(c)}catch(l){if(l instanceof RangeError)continue;throw l}if(a<0)throw new Hs("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new Gs(`Message length length too long - ${c.byteLength} > ${t.maxLengthLength}`);if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new $s(`Message length too long - ${a} > ${t.maxDataLength}`);let u=await e.read({...i,bytes:a});if(u==null)throw r.log.error("tried to read %d bytes but the stream closed",a),new Ae(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(u.byteLength!==a)throw r.log.error("read %d/%d bytes before the stream closed",u.byteLength,a),new Ae(`Unexpected EOF - read ${u.byteLength}/${a} bytes before the stream closed`);return u},async write(i,a){await e.write(new J(o(i.byteLength),i),a)},async writeV(i,a){let c=new J(...i.flatMap(u=>[o(u.byteLength),u]));await e.write(c,a)},unwrap(){return e.unwrap()}}}function er(r,t){let e=zd(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 Kn=class extends On{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};function Sc(r,t,e){let n,o,s=!1;function i(){let u={signal:o.signal};if(e?.timeout!=null){let d=Nr([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 Zs=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 vc(r){let{name:t,metrics:e}=r,n;return e!=null?n=new Zs({name:t,metrics:e}):n=new Map,n}var js="libp2p",Xs="autonat";var _c="dial-request",Ac="dial-back",Ic=200n*1024n,Bc=4096;var rr;(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),Fn.codec().encode(e.dialRequest,n)),e.dialResponse!=null&&(n.uint32(18),Qt.codec().encode(e.dialResponse,n)),e.dialDataRequest!=null&&(n.uint32(26),qn.codec().encode(e.dialDataRequest,n)),e.dialDataResponse!=null&&(n.uint32(34),Vn.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=Fn.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=qn.codec().decode(e,e.uint32(),{limits:o.limits?.dialDataRequest});break}case 4:{s.dialDataResponse=Vn.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)})(rr||(rr={}));var Fn;(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 dn('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)})(Fn||(Fn={}));var qn;(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)})(qn||(qn={}));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 zn;(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"})(zn||(zn={}));(function(r){r.codec=()=>we(zn)})(ut||(ut={}));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=()=>we(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&&zn[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)})(Qt||(Qt={}));var Vn;(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:xt(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)})(Vn||(Vn={}));var nr;(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)})(nr||(nr={}));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=()=>we(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)})(fe||(fe={}));function Hn(r,t){return Math.round(Math.random()*(t-r)+r)}var Hd=4,$d=8,$n=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=vc({name:"libp2p_autonat_v2_dial_results",metrics:t.metrics}),this.findPeers=Sc(this.findRandomPeers.bind(this),6e4),this.addressFilter=As(1024),this.queue=new Kn({concurrency:3,maxSize:50}),this.maxDialDataBytes=e.maxDialDataBytes??Ic,this.dialDataChunkSize=e.dialDataChunkSize??Bc,this.nonces=new Set}[Symbol.toStringTag]="@libp2p/autonat-v2";[Vr]=["@libp2p/autonat"];get[Hr](){return["@libp2p/identify"]}isStarted(){return this.started}async start(){this.started||(this.topologyId=await this.components.registrar.register(this.dialRequestProtocol,{onConnect:(t,e)=>{this.verifyExternalAddresses(e).catch(n=>{this.log.error("could not verify addresses - %e",n)})}}),await this.components.registrar.handle(this.dialBackProtocol,(t,e)=>{this.handleDialBackStream(t,e).catch(n=>{this.log.error("error handling incoming autonat stream - %e",n)})},{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams}),this.findPeers.start(),this.started=!0)}async stop(){await this.components.registrar.unhandle(this.dialRequestProtocol),await this.components.registrar.unhandle(this.dialBackProtocol),this.topologyId!=null&&await this.components.registrar.unhandle(this.topologyId),this.dialResults.clear(),this.findPeers.stop(),this.started=!1}allAddressesAreVerified(){return this.components.addressManager.getAddressesWithMetadata().every(t=>t.expires>Date.now()?!0:t.verified)}async findRandomPeers(t){if(this.allAddressesAreVerified())return;let e=Nr([AbortSignal.timeout(1e4),t?.signal]);try{this.log("starting random walk to find peers to run AutoNAT");for await(let n of this.components.randomWalk.walk({signal:e})){if(!await this.components.connectionManager.isDialable(n.multiaddrs)){this.log.trace("random peer %p was not dialable %s",n.id,n.multiaddrs.map(o=>o.toString()).join(", "));continue}try{this.log.trace("dial random peer %p",n.id),await this.components.connectionManager.openConnection(n.multiaddrs,{signal:e})}catch{}if(this.allAddressesAreVerified()){this.log("stopping random walk, all addresses are verified");return}if(!this.hasConnectionCapacity()){this.log("stopping random walk, too close to max connections");return}}}catch{}}async handleDialBackStream(t,e){let n=AbortSignal.timeout(this.timeout);let o=er(t,{maxDataLength:this.maxMessageSize});try{let s=await o.read(nr,{signal:n});if(!this.nonces.has(s.nonce))throw new _t("No matching dial found for nonce value");this.nonces.delete(s.nonce),await o.write({status:fe.DialBackStatus.OK},fe),await t.close({signal:n})}catch(s){this.log.error("error handling incoming dial back stream - %e",s),t.abort(s)}}getUnverifiedMultiaddrs(t,e){let n=this.components.addressManager.getAddressesWithMetadata().sort((s,i)=>s.type==="observed"&&i.type!=="observed"?1:i.type==="observed"&&s.type!=="observed"?-1:0).filter(s=>!(!(s.expires<Date.now())||ue(s.multiaddr).type==="ip6"&&(!e||!rc(s.multiaddr))||sc(s.multiaddr))),o=[];for(let s of n){let i=s.multiaddr.toString(),a=this.dialResults.get(i);if(a!=null&&a.networkSegments.includes(t)){this.log.trace("%a already has a network segment result from %s",a.multiaddr,t);continue}if(a==null){let c=s.expires<Date.now();if(c&&this.addressFilter.remove?.(i),this.addressFilter.has(i))continue;this.addressFilter.add(i),this.log.trace("creating dial result %s %s",c?"to revalidate":"for",i),a={multiaddr:s.multiaddr,success:0,failure:0,networkSegments:[],verifyingPeers:Es(),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})=>ue(i).type==="ip6"),o=this.getNetworkSegment(t.remoteAddr),s=this.getUnverifiedMultiaddrs(o,n);if(s.length!==0){if(!this.hasConnectionCapacity()){s[0]?.lastVerified!=null?(this.log("automatically re-verifying %a because we are too close to the connection limit",s[0].multiaddr),this.confirmAddress(s[0])):this.log("skipping verifying %a because we are too close to the connection limit",s[0]?.multiaddr);return}this.queue.add(async i=>{let a=Nr([i.signal,AbortSignal.timeout(this.timeout)]),c=BigInt(Hn(0,Number.MAX_SAFE_INTEGER));this.nonces.add(c);try{await this.askPeerToVerify(t,o,c,i)}finally{a.clear(),this.nonces.delete(c)}},{peerId:t.remotePeer}).catch(i=>{this.log.error("error from %p verifying addresses - %e",t.remotePeer,i)})}}async askPeerToVerify(t,e,n,o){let s=[...this.dialResults.values()].filter(a=>a.result==null).map(a=>a.multiaddr);if(s.length===0){this.queue.clear();return}this.log.trace("asking %a to verify multiaddrs %s",t.remoteAddr,s);let i=await t.newStream(this.dialRequestProtocol,o);try{let a=er(i).pb(rr);await a.write({dialRequest:{addrs:s.map(c=>c.bytes),nonce:n}},o);for(let c=0;c<s.length;c++){let u=await a.read(o);if(u.dialDataRequest!=null){if(u.dialDataRequest.numBytes>this.maxDialDataBytes){this.log("too many dial data byte requested by %p - %s/%s",t.remotePeer,u.dialDataRequest.numBytes,this.maxDialDataBytes);continue}this.log("sending %d bytes to %p as anti-amplification attack protection",u.dialDataRequest.numBytes,t.remotePeer);let h=new Uint8Array(this.dialDataChunkSize),p=BigInt(this.dialDataChunkSize);for(let w=0n;w<u.dialDataRequest.numBytes;w+=p)await a.write({dialDataResponse:{data:h}},o);u=await a.read(o)}if(u.dialResponse==null){this.log("invalid autonat response from %p - %j",t.remotePeer,u);return}if(u.dialResponse.status!==Qt.ResponseStatus.OK)return;let l=s[u.dialResponse.addrIdx];if(l==null){this.log.trace("peer dialed unknown address");continue}let f=this.dialResults.get(l.toString());if(f==null){this.log.trace("peer reported %a as %s but there is no result object",l,u.dialResponse.status);continue}if(f.networkSegments.includes(e)){this.log.trace("%a results already included network segment %s",l,e);continue}if(f.result!=null){this.log.trace("already resolved result for %a, ignoring response from",l,t.remotePeer);continue}if(f.verifyingPeers.has(t.remotePeer)){this.log.trace("peer %p has already verified %a, ignoring response",t.remotePeer,l);continue}if(f.verifyingPeers.add(t.remotePeer),f.networkSegments.push(e),u.dialResponse.dialStatus===ut.OK){if(this.log.trace("%p dialed %a successfully",t.remotePeer,f.multiaddr),f.success++,f.type!=="observed"){this.confirmAddress(f);continue}}else if(u.dialResponse.dialStatus===ut.E_DIAL_ERROR)this.log.trace("%p could not dial %a",t.remotePeer,f.multiaddr),f.failure++;else if(u.dialResponse.dialStatus===ut.E_DIAL_BACK_ERROR){this.log.trace("%p saw error while dialing %a",t.remotePeer,f.multiaddr);continue}this.log("%a success %d failure %d",f.multiaddr,f.success,f.failure),f.success===Hd&&this.confirmAddress(f),f.failure===$d&&this.unconfirmAddress(f)}}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=ue(t);switch(e.type){case"ip4":return e.host.split(".")[0].padStart(3,"0");case"ip6":return e.host.split(":")[0].padStart(4,"0");default:throw new ft(`Remote address ${t} was not an IPv4 or Ipv6 address`)}}};var Gn=class{components;dialRequestProtocol;dialBackProtocol;timeout;maxInboundStreams;maxOutboundStreams;maxMessageSize;started;log;constructor(t,e){this.components=t,this.log=t.logger.forComponent("libp2p:auto-nat-v2:server"),this.started=!1,this.dialRequestProtocol=e.dialRequestProtocol,this.dialBackProtocol=e.dialBackProtocol,this.timeout=e.timeout??3e4,this.maxInboundStreams=e.maxInboundStreams??2,this.maxOutboundStreams=e.maxOutboundStreams??20,this.maxMessageSize=e.maxMessageSize??8192,this.handleDialRequestStream=this.handleDialRequestStream.bind(this)}async start(){this.started||(await this.components.registrar.handle(this.dialRequestProtocol,this.handleDialRequestStream,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams}),this.started=!0)}async stop(){await this.components.registrar.unhandle(this.dialRequestProtocol),this.started=!1}async handleDialRequestStream(t,e){let n=AbortSignal.timeout(this.timeout);let o=er(t,{maxDataLength:this.maxMessageSize}).pb(rr),s=Rc(e.remoteAddr);if(s==null)throw new _t(`Could not find IP address in connection address "${e.remoteAddr}"`);let{dialRequest:i}=await o.read({signal:n});if(i==null)throw new _t("Did not receive DialRequest message on incoming dial request stream");if(i.addrs.length===0)throw new _t("Did not receive any addresses to dial");for(let a=0;a<i.addrs.length;a++)try{let c=Ec(i.addrs[a]);if(!await this.components.connectionManager.isDialable(c,{signal:n})){await o.write({dialResponse:{addrIdx:a,status:Qt.ResponseStatus.E_DIAL_REFUSED,dialStatus:ut.UNUSED}},{signal:n});continue}let d=Rc(c);if(d==null)throw new _t(`Could not find IP address in requested address "${c}"`);if(Bn(d))throw new _t(`Requested address had private IP "${c}"`);d!==s&&await this.preventAmplificationAttack(o,a,{signal:n});let l=await this.dialClientBack(c,i.nonce,{signal:n});await o.write({dialResponse:{addrIdx:a,status:Qt.ResponseStatus.OK,dialStatus:l}},{signal:n})}catch(c){this.log.error("error handling incoming dialback request - %e",c)}await t.close({signal:n})}async preventAmplificationAttack(t,e,n){let o=Hn(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 _t("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=er(s,{maxDataLength:this.maxMessageSize});if(await i.write({nonce:e},nr,n),(await i.read(fe,n)).status!==fe.DialBackStatus.OK)throw new _t("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 Rc(r){return r.getComponents().filter(t=>t.code===4||t.code===41).map(t=>t.value).pop()}var Zn=class{client;server;constructor(t,e){let n=`/${e.protocolPrefix??js}/${Xs}/${"2"}/${_c}`,o=`/${e.protocolPrefix??js}/${Xs}/${"2"}/${Ac}`;this.client=new $n(t,{...e,dialRequestProtocol:n,dialBackProtocol:o}),this.server=new Gn(t,{...e,dialRequestProtocol:n,dialBackProtocol:o})}[Symbol.toStringTag]="@libp2p/autonat-v2";[Vr]=["@libp2p/autonat"];get[Hr](){return["@libp2p/identify"]}async start(){await ti(this.client,this.server)}async stop(){await ei(this.client,this.server)}};function Gd(r={}){return t=>new Zn(t,r)}return qc(Zd);})();
|
|
2
|
+
"use strict";var Libp2PAutonatV2=(()=>{var Oc=Object.create;var Kr=Object.defineProperty;var kc=Object.getOwnPropertyDescriptor;var Nc=Object.getOwnPropertyNames;var Uc=Object.getPrototypeOf,Mc=Object.prototype.hasOwnProperty;var Kc=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),bt=(r,t)=>{for(var e in t)Kr(r,e,{get:t[e],enumerable:!0})},Qs=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Nc(t))!Mc.call(r,o)&&o!==e&&Kr(r,o,{get:()=>t[o],enumerable:!(n=kc(t,o))||n.enumerable});return r};var Fc=(r,t,e)=>(e=r!=null?Oc(Uc(r)):{},Qs(t||!r||!r.__esModule?Kr(e,"default",{value:r,enumerable:!0}):e,r)),qc=r=>Qs(Kr({},"__esModule",{value:!0}),r);var nc=Kc(Or=>{(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,p;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)}p=t(c),h=p[0],d=p[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,p;if(typeof u!="string")throw new Error("Missing `net' parameter");if(d||(p=u.split("/",2),u=p[0],d=p[1]),d||(d=32),typeof d=="string"&&d.indexOf(".")>-1){try{this.maskLong=i(d)}catch(w){throw l=w,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(w){throw l=w,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})(),Or.ip2long=i,Or.long2ip=a,Or.Netmask=r}).call(Or)});var Zd={};bt(Zd,{autoNATv2:()=>Gd});var Ot=class extends Error{static name="AbortError";constructor(t="The operation was aborted"){super(t),this.name="AbortError"}};var ft=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},Fr=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}};var qr=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}};var _t=class extends Error{static name="ProtocolError";constructor(t="Protocol error"){super(t),this.name="ProtocolError"}};var or=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var jn=Symbol.for("@libp2p/peer-id");function Js(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function ti(...r){let t=[];for(let e of r)Js(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 ei(...r){let t=[];for(let e of r)Js(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=class extends EventTarget{#t=new Map;constructor(){super()}listenerCount(t){let e=this.#t.get(t);return e==null?0:e.length}addEventListener(t,e,n){super.addEventListener(t,e,n);let o=this.#t.get(t);o==null&&(o=[],this.#t.set(t,o)),o.push({callback:e,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(t,e,n){super.removeEventListener(t.toString(),e??null,n);let o=this.#t.get(t);o!=null&&(o=o.filter(({callback:s})=>s!==e),this.#t.set(t,o))}dispatchEvent(t){let e=super.dispatchEvent(t),n=this.#t.get(t.type);return n==null||(n=n.filter(({once:o})=>!o),this.#t.set(t.type,n)),e}safeDispatchEvent(t,e={}){return this.dispatchEvent(new CustomEvent(t,e))}};var Vr=Symbol.for("@libp2p/service-capabilities"),Hr=Symbol.for("@libp2p/service-dependencies");var Jn={};bt(Jn,{base58btc:()=>Y,base58flickr:()=>jc});var _h=new Uint8Array(0);function ri(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 kt(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 ni(r){return new TextEncoder().encode(r)}function oi(r){return new TextDecoder().decode(r)}function zc(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(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var w=0,S=0,y=0,_=p.length;y!==_&&p[y]===0;)y++,w++;for(var x=(_-y)*d+1>>>0,D=new Uint8Array(x);y!==_;){for(var R=p[y],M=0,U=x-1;(R!==0||M<S)&&U!==-1;U--,M++)R+=256*D[U]>>>0,D[U]=R%a>>>0,R=R/a>>>0;if(R!==0)throw new Error("Non-zero carry");S=M,y++}for(var O=x-S;O!==x&&D[O]===0;)O++;for(var E=c.repeat(w);O<x;++O)E+=r.charAt(D[O]);return E}function f(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var w=0;if(p[w]!==" "){for(var S=0,y=0;p[w]===c;)S++,w++;for(var _=(p.length-w)*u+1>>>0,x=new Uint8Array(_);p[w];){var D=e[p.charCodeAt(w)];if(D===255)return;for(var R=0,M=_-1;(D!==0||R<y)&&M!==-1;M--,R++)D+=a*x[M]>>>0,x[M]=D%256>>>0,D=D/256>>>0;if(D!==0)throw new Error("Non-zero carry");y=R,w++}if(p[w]!==" "){for(var U=_-y;U!==_&&x[U]===0;)U++;for(var O=new Uint8Array(S+(_-U)),E=S;U!==_;)O[E++]=x[U++];return O}}}function h(p){var w=f(p);if(w)return w;throw new Error(`Non-${t} character`)}return{encode:l,decodeUnsafe:f,decode:h}}var Vc=zc,Hc=Vc,ii=Hc;var Xn=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")}},Yn=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 ai(this,t)}},Wn=class{decoders;constructor(t){this.decoders=t}or(t){return ai(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 ai(r,t){return new Wn({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var Qn=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 Xn(t,e,n),this.decoder=new Yn(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Be({name:r,prefix:t,encode:e,decode:n}){return new Qn(r,t,e,n)}function Jt({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=ii(e,r);return Be({prefix:t,name:r,encode:n,decode:s=>kt(o(s))})}function $c(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 Gc(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 Zc(r){let t={};for(let e=0;e<r.length;++e)t[r[e]]=e;return t}function j({name:r,prefix:t,bitsPerChar:e,alphabet:n}){let o=Zc(n);return Be({prefix:t,name:r,encode(s){return Gc(s,n,e)},decode(s){return $c(s,o,e,r)}})}var Y=Jt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),jc=Jt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var to={};bt(to,{base32:()=>te,base32hex:()=>Qc,base32hexpad:()=>tu,base32hexpadupper:()=>eu,base32hexupper:()=>Jc,base32pad:()=>Yc,base32padupper:()=>Wc,base32upper:()=>Xc,base32z:()=>ru});var te=j({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Xc=j({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Yc=j({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Wc=j({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Qc=j({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Jc=j({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),tu=j({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),eu=j({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),ru=j({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var eo={};bt(eo,{base36:()=>sr,base36upper:()=>nu});var sr=Jt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),nu=Jt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var ou=fi,ci=128,su=127,iu=~su,au=Math.pow(2,31);function fi(r,t,e){t=t||[],e=e||0;for(var n=e;r>=au;)t[e++]=r&255|ci,r/=128;for(;r&iu;)t[e++]=r&255|ci,r>>>=7;return t[e]=r|0,fi.bytes=e-n+1,t}var cu=ro,uu=128,ui=127;function ro(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw ro.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&ui)<<o:(i&ui)*Math.pow(2,o),o+=7}while(i>=uu);return ro.bytes=s-n,e}var fu=Math.pow(2,7),lu=Math.pow(2,14),du=Math.pow(2,21),hu=Math.pow(2,28),pu=Math.pow(2,35),mu=Math.pow(2,42),gu=Math.pow(2,49),yu=Math.pow(2,56),bu=Math.pow(2,63),xu=function(r){return r<fu?1:r<lu?2:r<du?3:r<hu?4:r<pu?5:r<mu?6:r<gu?7:r<yu?8:r<bu?9:10},wu={encode:ou,decode:cu,encodingLength:xu},Eu=wu,ir=Eu;function ar(r,t=0){return[ir.decode(r,t),ir.decode.bytes]}function De(r,t,e=0){return ir.encode(r,t,e),t}function Ce(r){return ir.encodingLength(r)}function Te(r,t){let e=t.byteLength,n=Ce(r),o=n+Ce(e),s=new Uint8Array(o+e);return De(r,s,0),De(e,s,n),s.set(t,o),new Le(r,e,t,s)}function cr(r){let t=kt(r),[e,n]=ar(t),[o,s]=ar(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Le(e,o,i,t)}function li(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&ri(r.bytes,e.bytes)}}var Le=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};function di(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return vu(e,no(r),t??Y.encoder);default:return _u(e,no(r),t??te.encoder)}}var hi=new WeakMap;function no(r){let t=hi.get(r);if(t==null){let e=new Map;return hi.set(r,e),e}return t}var it=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!==ur)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==Au)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=Te(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&&li(t.multihash,n.multihash)}toString(t){return di(this,t)}toJSON(){return{"/":di(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??pi(n,o,s.bytes))}else if(e[Iu]===!0){let{version:n,multihash:o,code:s}=e,i=cr(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!==ur)throw new Error(`Version 0 CID must use dag-pb (code: ${ur}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=pi(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,ur,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=kt(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 Le(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]=ar(t.subarray(e));return e+=f,l},o=n(),s=ur;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]=Su(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 no(s).set(n,t),s}};function Su(r,t){switch(r[0]){case"Q":{let e=t??Y;return[Y.prefix,e.decode(`${Y.prefix}${r}`)]}case Y.prefix:{let e=t??Y;return[Y.prefix,e.decode(r)]}case te.prefix:{let e=t??te;return[te.prefix,e.decode(r)]}case sr.prefix:{let e=t??sr;return[sr.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 vu(r,t,e){let{prefix:n}=e;if(n!==Y.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 _u(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 ur=112,Au=18;function pi(r,t,e){let n=Ce(r),o=n+Ce(t),s=new Uint8Array(o+e.byteLength);return De(r,s,0),De(t,s,n),s.set(e,o),s}var Iu=Symbol.for("@ipld/js-cid/CID");var oo={};bt(oo,{identity:()=>Ct});var mi=0,Bu="identity",gi=kt;function Du(r,t){if(t?.truncate!=null&&t.truncate!==r.byteLength){if(t.truncate<0||t.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t.truncate)}return Te(mi,gi(r))}var Ct={code:mi,name:Bu,encode:gi,digest:Du};function lt(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function xt(r=0){return new Uint8Array(r)}function mt(r=0){return new Uint8Array(r)}function Nt(r,t){t==null&&(t=r.reduce((o,s)=>o+s.length,0));let e=mt(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}var bi=Symbol.for("@achingbrain/uint8arraylist");function yi(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 Gr(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(Gr(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(Gr(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=yi(this.bufs,t);return e.buf[e.index]}set(t,e){let n=yi(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(Gr(t))for(let n=0;n<t.length;n++)this.set(e+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:n,length:o}=this._subList(t,e);return Nt(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:Nt(n,o)}sublist(t,e){let{bufs:n,length:o}=this._subList(t,e),s=new r;return s.length=o,s.bufs=[...n],s}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,t>=c)continue;let u=t>=a&&t<c,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(!Gr(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=mt(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=xt(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=xt(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=xt(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=mt(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=xt(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=xt(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=xt(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=xt(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=xt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,e,n),this.write(o,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!lt(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((o,s)=>o+s.byteLength,0)),n.length=e,n}};var so={};bt(so,{base10:()=>Cu});var Cu=Jt({prefix:"9",name:"base10",alphabet:"0123456789"});var io={};bt(io,{base16:()=>Lu,base16upper:()=>Tu});var Lu=j({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Tu=j({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var ao={};bt(ao,{base2:()=>Ru});var Ru=j({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var co={};bt(co,{base256emoji:()=>Uu});var xi=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}"),Pu=xi.reduce((r,t,e)=>(r[e]=t,r),[]),Ou=xi.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function ku(r){return r.reduce((t,e)=>(t+=Pu[e],t),"")}function Nu(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=Ou[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var Uu=Be({prefix:"\u{1F680}",name:"base256emoji",encode:ku,decode:Nu});var fo={};bt(fo,{base64:()=>Mu,base64pad:()=>Ku,base64url:()=>uo,base64urlpad:()=>Fu});var Mu=j({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Ku=j({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),uo=j({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Fu=j({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var lo={};bt(lo,{base8:()=>qu});var qu=j({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var ho={};bt(ho,{identity:()=>zu});var zu=Be({prefix:"\0",name:"identity",encode:r=>oi(r),decode:r=>ni(r)});var ap=new TextEncoder,cp=new TextDecoder;var go={};bt(go,{sha256:()=>fr,sha512:()=>Gu});var $u=20;function mo({name:r,code:t,encode:e,minDigestLength:n,maxDigestLength:o}){return new po(r,t,e,n,o)}var po=class{name;code;encode;minDigestLength;maxDigestLength;constructor(t,e,n,o,s){this.name=t,this.code=e,this.encode=n,this.minDigestLength=o??$u,this.maxDigestLength=s}digest(t,e){if(e?.truncate!=null){if(e.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&e.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(t instanceof Uint8Array){let n=this.encode(t);return n instanceof Uint8Array?wi(n,this.code,e?.truncate):n.then(o=>wi(o,this.code,e?.truncate))}else throw Error("Unknown type, must be binary type")}};function wi(r,t,e){if(e!=null&&e!==r.byteLength){if(e>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e)}return Te(t,r)}function Si(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var fr=mo({name:"sha2-256",code:18,encode:Si("SHA-256")}),Gu=mo({name:"sha2-512",code:19,encode:Si("SHA-512")});var lr={...ho,...ao,...lo,...so,...io,...to,...eo,...Jn,...fo,...co},wp={...go,...oo};function _i(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var vi=_i("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),yo=_i("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=mt(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),Zu={utf8:vi,"utf-8":vi,hex:lr.base16,latin1:yo,ascii:yo,binary:yo,...lr},Zr=Zu;function H(r,t="utf8"){let e=Zr[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function Q(r,t="utf8"){let e=Zr[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var ju=parseInt("11111",2),bo=parseInt("10000000",2),Xu=parseInt("01111111",2),Ai={0:dr,1:dr,2:Yu,3:Ju,4:tf,5:Qu,6:Wu,16:dr,22:dr,48:dr};function xo(r,t={offset:0}){let e=r[t.offset]&ju;if(t.offset++,Ai[e]!=null)return Ai[e](r,t);throw new Error("No decoder for tag "+e)}function hr(r,t){let e=0;if((r[t.offset]&bo)===bo){let n=r[t.offset]&Xu,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 dr(r,t){hr(r,t);let e=[];for(;!(t.offset>=r.byteLength);){let n=xo(r,t);if(n===null)break;e.push(n)}return e}function Yu(r,t){let e=hr(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 Wu(r,t){let e=hr(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 Qu(r,t){return t.offset++,null}function Ju(r,t){let e=hr(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 tf(r,t){let e=hr(r,t),n=r.subarray(t.offset,t.offset+e);return t.offset+=e,n}function ef(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 wo(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let t=ef(r.byteLength);return new J(Uint8Array.from([t.byteLength|bo]),t)}function Ii(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]),wo(t),t)}function Bi(r){let t=Uint8Array.from([0]),e=new J(t,r);return new J(Uint8Array.from([3]),wo(e),e)}function jr(r,t=48){let e=new J;for(let n of r)e.append(n);return new J(Uint8Array.from([t]),wo(e),e)}async function Di(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 rf=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),nf=Uint8Array.from([6,5,43,129,4,0,34]),of=Uint8Array.from([6,5,43,129,4,0,35]),sf={ext:!0,kty:"EC",crv:"P-256"},af={ext:!0,kty:"EC",crv:"P-384"},cf={ext:!0,kty:"EC",crv:"P-521"},Eo=32,So=48,vo=66;function Ci(r){let t=xo(r);return Li(t)}function Li(r){let t=r[1][1][0],e=1,n,o;if(t.byteLength===Eo*2+1)return n=Q(t.subarray(e,e+Eo),"base64url"),o=Q(t.subarray(e+Eo),"base64url"),new Re({...sf,key_ops:["verify"],x:n,y:o});if(t.byteLength===So*2+1)return n=Q(t.subarray(e,e+So),"base64url"),o=Q(t.subarray(e+So),"base64url"),new Re({...af,key_ops:["verify"],x:n,y:o});if(t.byteLength===vo*2+1)return n=Q(t.subarray(e,e+vo),"base64url"),o=Q(t.subarray(e+vo),"base64url"),new Re({...cf,key_ops:["verify"],x:n,y:o});throw new ft(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function Ti(r){return jr([Ii(Uint8Array.from([1])),jr([uf(r.crv)],160),jr([Bi(new J(Uint8Array.from([4]),H(r.x??"","base64url"),H(r.y??"","base64url")))],161)]).subarray()}function uf(r){if(r==="P-256")return rf;if(r==="P-384")return nf;if(r==="P-521")return of;throw new ft(`Invalid curve ${r}`)}var Re=class{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=Ti(this.jwk)),this._raw}toMultihash(){return Ct.digest(Pe(this))}toCID(){return it.createV1(114,this.toMultihash())}toString(){return Y.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:lt(this.raw,t.raw)}async verify(t,e,n){return Di(this.jwk,e,t,n)}};var de=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Mt(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function pr(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function gt(r,...t){if(!Mt(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 Xr(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");pr(r.outputLen),pr(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 Pi(r,t){gt(r);let e=t.outputLen;if(r.length<e)throw new Error("digestInto() expects output buffer of length at least "+e)}function Kt(...r){for(let t=0;t<r.length;t++)r[t].fill(0)}function Yr(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Lt(r,t){return r<<32-t|r>>>t}var Oi=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",ff=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function At(r){if(gt(r),Oi)return r.toHex();let t="";for(let e=0;e<r.length;e++)t+=ff[r[e]];return t}var Ut={_0:48,_9:57,A:65,F:70,a:97,f:102};function Ri(r){if(r>=Ut._0&&r<=Ut._9)return r-Ut._0;if(r>=Ut.A&&r<=Ut.F)return r-(Ut.A-10);if(r>=Ut.a&&r<=Ut.f)return r-(Ut.a-10)}function he(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(Oi)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=Ri(r.charCodeAt(s)),a=Ri(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 _o(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function mr(r){return typeof r=="string"&&(r=_o(r)),gt(r),r}function dt(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];gt(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 Oe=class{};function Ao(r){let t=n=>r().update(mr(n)).digest(),e=r();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>r(),t}function Ne(r=32){if(de&&typeof de.getRandomValues=="function")return de.getRandomValues(new Uint8Array(r));if(de&&typeof de.randomBytes=="function")return Uint8Array.from(de.randomBytes(r));throw new Error("crypto.getRandomValues must be defined")}function lf(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 ki(r,t,e){return r&t^~r&e}function Ni(r,t,e){return r&t^r&e^t&e}var gr=class extends Oe{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=Yr(this.buffer)}update(t){ke(this),t=mr(t),gt(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=Yr(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),Pi(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;e[i++]=128,Kt(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let l=i;l<o;l++)e[l]=0;lf(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=Yr(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 Wr=BigInt(4294967295),Ui=BigInt(32);function df(r,t=!1){return t?{h:Number(r&Wr),l:Number(r>>Ui&Wr)}:{h:Number(r>>Ui&Wr)|0,l:Number(r&Wr)|0}}function Mi(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}=df(r[s],t);[n[s],o[s]]=[i,a]}return[n,o]}var Io=(r,t,e)=>r>>>e,Bo=(r,t,e)=>r<<32-e|t>>>e,pe=(r,t,e)=>r>>>e|t<<32-e,me=(r,t,e)=>r<<32-e|t>>>e,yr=(r,t,e)=>r<<64-e|t>>>e-32,br=(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 Ki=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),Fi=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,qi=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),zi=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,Vi=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),Hi=(r,t,e,n,o,s)=>t+e+n+o+s+(r/2**32|0)|0;var pf=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]),ee=new Uint32Array(64),Do=class extends gr{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)ee[l]=t.getUint32(e,!1);for(let l=16;l<64;l++){let f=ee[l-15],h=ee[l-2],p=Lt(f,7)^Lt(f,18)^f>>>3,w=Lt(h,17)^Lt(h,19)^h>>>10;ee[l]=w+ee[l-7]+p+ee[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=Lt(a,6)^Lt(a,11)^Lt(a,25),h=d+f+ki(a,c,u)+pf[l]+ee[l]|0,w=(Lt(n,2)^Lt(n,13)^Lt(n,22))+Ni(n,o,s)|0;d=u,u=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+w|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(){Kt(ee)}destroy(){this.set(0,0,0,0,0,0,0,0),Kt(this.buffer)}};var $i=Mi(["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))),mf=$i[0],gf=$i[1],re=new Uint32Array(80),ne=new Uint32Array(80),Co=class extends gr{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:p,Hh:w,Hl:S}=this;return[t,e,n,o,s,i,a,c,u,d,l,f,h,p,w,S]}set(t,e,n,o,s,i,a,c,u,d,l,f,h,p,w,S){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=p|0,this.Hh=w|0,this.Hl=S|0}process(t,e){for(let x=0;x<16;x++,e+=4)re[x]=t.getUint32(e),ne[x]=t.getUint32(e+=4);for(let x=16;x<80;x++){let D=re[x-15]|0,R=ne[x-15]|0,M=pe(D,R,1)^pe(D,R,8)^Io(D,R,7),U=me(D,R,1)^me(D,R,8)^Bo(D,R,7),O=re[x-2]|0,E=ne[x-2]|0,C=pe(O,E,19)^yr(O,E,61)^Io(O,E,6),k=me(O,E,19)^br(O,E,61)^Bo(O,E,6),L=qi(U,k,ne[x-7],ne[x-16]),b=zi(L,M,C,re[x-7],re[x-16]);re[x]=b|0,ne[x]=L|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:p,Gh:w,Gl:S,Hh:y,Hl:_}=this;for(let x=0;x<80;x++){let D=pe(l,f,14)^pe(l,f,18)^yr(l,f,41),R=me(l,f,14)^me(l,f,18)^br(l,f,41),M=l&h^~l&w,U=f&p^~f&S,O=Vi(_,R,U,gf[x],ne[x]),E=Hi(O,y,D,M,mf[x],re[x]),C=O|0,k=pe(n,o,28)^yr(n,o,34)^yr(n,o,39),L=me(n,o,28)^br(n,o,34)^br(n,o,39),b=n&s^n&a^s&a,m=o&i^o&c^i&c;y=w|0,_=S|0,w=h|0,S=p|0,h=l|0,p=f|0,{h:l,l:f}=Pt(u|0,d|0,E|0,C|0),u=a|0,d=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let g=Ki(C,L,m);n=Fi(g,E,k,b),o=g|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:p}=Pt(this.Fh|0,this.Fl|0,h|0,p|0),{h:w,l:S}=Pt(this.Gh|0,this.Gl|0,w|0,S|0),{h:y,l:_}=Pt(this.Hh|0,this.Hl|0,y|0,_|0),this.set(n,o,s,i,a,c,u,d,l,f,h,p,w,S,y,_)}roundClean(){Kt(re,ne)}destroy(){Kt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var Gi=Ao(()=>new Do);var Zi=Ao(()=>new Co);var Ro=BigInt(0),To=BigInt(1);function qt(r,t=""){if(typeof r!="boolean"){let e=t&&`"${t}"`;throw new Error(e+"expected boolean, got type="+typeof r)}return r}function wt(r,t,e=""){let n=Mt(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 xr(r){let t=r.toString(16);return t.length&1?"0"+t:t}function ji(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?Ro:BigInt("0x"+r)}function Ue(r){return ji(At(r))}function zt(r){return gt(r),ji(At(Uint8Array.from(r).reverse()))}function Qr(r,t){return he(r.toString(16).padStart(t*2,"0"))}function Po(r,t){return Qr(r,t).reverse()}function q(r,t,e){let n;if(typeof t=="string")try{n=he(t)}catch(s){throw new Error(r+" must be hex string or Uint8Array, cause: "+s)}else if(Mt(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 Xi(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 Oo(r){return Uint8Array.from(r)}var Lo=r=>typeof r=="bigint"&&Ro<=r;function Yi(r,t,e){return Lo(r)&&Lo(t)&&Lo(e)&&t<=r&&r<e}function wr(r,t,e,n){if(!Yi(t,e,n))throw new Error("expected valid "+r+": "+e+" <= n < "+n+", got "+t)}function Jr(r){let t;for(t=0;r>Ro;r>>=To,t+=1);return t}var oe=r=>(To<<BigInt(r))-To;function Wi(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,p=[];for(;h<t;){s=u();let w=s.slice();p.push(w),h+=s.length}return dt(...p)};return(h,p)=>{c(),d(h);let w;for(;!(w=p(l()));)d();return c(),w}}function se(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 ko=()=>{throw new Error("not implemented")};function Me(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 ht=BigInt(0),tt=BigInt(1),ge=BigInt(2),ta=BigInt(3),ea=BigInt(4),ra=BigInt(5),yf=BigInt(7),na=BigInt(8),bf=BigInt(9),oa=BigInt(16);function X(r,t){let e=r%t;return e>=ht?e:t+e}function V(r,t,e){let n=r;for(;t-- >ht;)n*=n,n%=e;return n}function Qi(r,t){if(r===ht)throw new Error("invert: expected non-zero number");if(t<=ht)throw new Error("invert: expected positive modulus, got "+t);let e=X(r,t),n=t,o=ht,s=tt,i=tt,a=ht;for(;e!==ht;){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!==tt)throw new Error("invert: does not exist");return X(o,t)}function No(r,t,e){if(!r.eql(r.sqr(t),e))throw new Error("Cannot find square root")}function sa(r,t){let e=(r.ORDER+tt)/ea,n=r.pow(t,e);return No(r,n,t),n}function xf(r,t){let e=(r.ORDER-ra)/na,n=r.mul(t,ge),o=r.pow(n,e),s=r.mul(t,o),i=r.mul(r.mul(s,ge),o),a=r.mul(s,r.sub(i,r.ONE));return No(r,a,t),a}function wf(r){let t=Et(r),e=ia(r),n=e(t,t.neg(t.ONE)),o=e(t,n),s=e(t,t.neg(n)),i=(r+yf)/oa;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),p=a.eql(a.sqr(l),c);u=a.cmov(u,d,h),d=a.cmov(f,l,p);let w=a.eql(a.sqr(d),c),S=a.cmov(u,d,w);return No(a,S,c),S}}function ia(r){if(r<ta)throw new Error("sqrt is not defined for small field");let t=r-tt,e=0;for(;t%ge===ht;)t/=ge,e++;let n=ge,o=Et(r);for(;Ji(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(e===1)return sa;let s=o.pow(n,t),i=(t+tt)/ge;return function(c,u){if(c.is0(u))return u;if(Ji(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 p=1,w=c.sqr(f);for(;!c.eql(w,c.ONE);)if(p++,w=c.sqr(w),p===d)throw new Error("Cannot find square root");let S=tt<<BigInt(d-p-1),y=c.pow(l,S);d=p,l=c.sqr(y),f=c.mul(f,l),h=c.mul(h,y)}return h}}function Ef(r){return r%ea===ta?sa:r%na===ra?xf:r%oa===bf?wf(r):ia(r)}var Vt=(r,t)=>(X(r,t)&tt)===tt,Sf=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Uo(r){let t={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},e=Sf.reduce((n,o)=>(n[o]="function",n),t);return se(r,e),r}function vf(r,t,e){if(e<ht)throw new Error("invalid exponent, negatives unsupported");if(e===ht)return r.ONE;if(e===tt)return t;let n=r.ONE,o=t;for(;e>ht;)e&tt&&(n=r.mul(n,o)),o=r.sqr(o),e>>=tt;return n}function Er(r,t,e=!1){let n=new Array(t.length).fill(e?r.ZERO:void 0),o=t.reduce((i,a,c)=>r.is0(a)?i:(n[c]=i,r.mul(i,a)),r.ONE),s=r.inv(o);return t.reduceRight((i,a,c)=>r.is0(a)?i:(n[c]=r.mul(i,n[c]),r.mul(i,a)),s),n}function Ji(r,t){let e=(r.ORDER-tt)/ge,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 tn(r,t){t!==void 0&&pr(t);let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}function Et(r,t,e=!1,n={}){if(r<=ht)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}=tn(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:oe(c),ZERO:ht,ONE:tt,allowedLengths:a,create:f=>X(f,r),isValid:f=>{if(typeof f!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof f);return ht<=f&&f<r},is0:f=>f===ht,isValidNot0:f=>!l.is0(f)&&l.isValid(f),isOdd:f=>(f&tt)===tt,neg:f=>X(-f,r),eql:(f,h)=>f===h,sqr:f=>X(f*f,r),add:(f,h)=>X(f+h,r),sub:(f,h)=>X(f-h,r),mul:(f,h)=>X(f*h,r),pow:(f,h)=>vf(l,f,h),div:(f,h)=>X(f*Qi(h,r),r),sqrN:f=>f*f,addN:(f,h)=>f+h,subN:(f,h)=>f-h,mulN:(f,h)=>f*h,inv:f=>Qi(f,r),sqrt:s||(f=>(d||(d=Ef(r)),d(l,f))),toBytes:f=>e?Po(f,u):Qr(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 w=new Uint8Array(u);w.set(f,e?0:w.length-f.length),f=w}if(f.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+f.length);let p=e?zt(f):Ue(f);if(i&&(p=X(p,r)),!h&&!l.isValid(p))throw new Error("invalid field element: outside of range 0..ORDER");return p},invertBatch:f=>Er(l,f),cmov:(f,h,p)=>p?h:f});return Object.freeze(l)}function aa(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 Mo(r){let t=aa(r);return t+Math.ceil(t/2)}function Ko(r,t,e=!1){let n=r.length,o=aa(t),s=Mo(t);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=e?zt(r):Ue(r),a=X(i,t-tt)+tt;return e?Po(a,o):Qr(a,o)}var Ke=BigInt(0),ye=BigInt(1);function Sr(r,t){let e=t.negate();return r?e:t}function Ht(r,t){let e=Er(r.Fp,t.map(n=>n.Z));return t.map((n,o)=>r.fromAffine(n.toAffine(e[o])))}function la(r,t){if(!Number.isSafeInteger(r)||r<=0||r>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+r)}function Fo(r,t){la(r,t);let e=Math.ceil(t/r)+1,n=2**(r-1),o=2**r,s=oe(r),i=BigInt(r);return{windows:e,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function ca(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+=ye);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 _f(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 Af(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 qo=new WeakMap,da=new WeakMap;function zo(r){return da.get(r)||1}function ua(r){if(r!==Ke)throw new Error("invalid wNAF")}var Fe=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>Ke;)e&ye&&(n=n.add(o)),o=o.double(),e>>=ye;return n}precomputeWindow(t,e){let{windows:n,windowSize:o}=Fo(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=Fo(t,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:u,isZero:d,isNeg:l,isNegF:f,offsetF:h}=ca(n,a,i);n=c,d?s=s.add(Sr(f,e[h])):o=o.add(Sr(l,e[u]))}return ua(n),{p:o,f:s}}wNAFUnsafe(t,e,n,o=this.ZERO){let s=Fo(t,this.bits);for(let i=0;i<s.windows&&n!==Ke;i++){let{nextN:a,offset:c,isZero:u,isNeg:d}=ca(n,i,s);if(n=a,!u){let l=e[c];o=o.add(d?l.negate():l)}}return ua(n),o}getPrecomputes(t,e,n){let o=qo.get(e);return o||(o=this.precomputeWindow(e,t),t!==1&&(typeof n=="function"&&(o=n(o)),qo.set(e,o))),o}cached(t,e,n){let o=zo(t);return this.wNAF(o,this.getPrecomputes(o,t,n),e)}unsafe(t,e,n,o){let s=zo(t);return s===1?this._unsafeLadder(t,e,o):this.wNAFUnsafe(s,this.getPrecomputes(s,t,n),e,o)}createCache(t,e){la(e,this.bits),da.set(t,e),qo.delete(t)}hasCache(t){return zo(t)!==1}};function ha(r,t,e,n){let o=t,s=r.ZERO,i=r.ZERO;for(;e>Ke||n>Ke;)e&ye&&(s=s.add(o)),n&ye&&(i=i.add(o)),o=o.double(),e>>=ye,n>>=ye;return{p1:s,p2:i}}function qe(r,t,e,n){_f(e,r),Af(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=Jr(BigInt(o)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let u=oe(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 w=0;w<s;w++){let S=n[w],y=Number(S>>BigInt(h)&u);d[y]=d[y].add(e[w])}let p=i;for(let w=d.length-1,S=i;w>0;w--)S=S.add(d[w]),p=p.add(S);if(f=f.add(p),h!==0)for(let w=0;w<c;w++)f=f.double()}return f}function fa(r,t,e){if(t){if(t.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Uo(t),t}else return Et(r,{isLE:e})}function en(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>Ke))throw new Error(`CURVE.${c} must be positive bigint`)}let o=fa(t.p,e.Fp,n),s=fa(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 ie=BigInt(0),et=BigInt(1),Vo=BigInt(2),If=BigInt(8);function Bf(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 Df(r,t={}){let e=en("edwards",r,t,t.FpFnLE),{Fp:n,Fn:o}=e,s=e.CURVE,{h:i}=s;se(t,{},{uvRatio:"function"});let a=Vo<<BigInt(o.BYTES*8)-et,c=S=>n.create(S),u=t.uvRatio||((S,y)=>{try{return{isValid:!0,value:n.sqrt(n.div(S,y))}}catch{return{isValid:!1,value:ie}}});if(!Bf(n,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function d(S,y,_=!1){let x=_?et:ie;return wr("coordinate "+S,y,x,a),y}function l(S){if(!(S instanceof p))throw new Error("ExtendedPoint expected")}let f=Me((S,y)=>{let{X:_,Y:x,Z:D}=S,R=S.is0();y==null&&(y=R?If:n.inv(D));let M=c(_*y),U=c(x*y),O=n.mul(D,y);if(R)return{x:ie,y:et};if(O!==et)throw new Error("invZ was invalid");return{x:M,y:U}}),h=Me(S=>{let{a:y,d:_}=s;if(S.is0())throw new Error("bad point: ZERO");let{X:x,Y:D,Z:R,T:M}=S,U=c(x*x),O=c(D*D),E=c(R*R),C=c(E*E),k=c(U*y),L=c(E*c(k+O)),b=c(C+c(_*c(U*O)));if(L!==b)throw new Error("bad point: equation left != right (1)");let m=c(x*D),g=c(R*M);if(m!==g)throw new Error("bad point: equation left != right (2)");return!0});class p{constructor(y,_,x,D){this.X=d("x",y),this.Y=d("y",_),this.Z=d("z",x,!0),this.T=d("t",D),Object.freeze(this)}static CURVE(){return s}static fromAffine(y){if(y instanceof p)throw new Error("extended point not allowed");let{x:_,y:x}=y||{};return d("x",_),d("y",x),new p(_,x,et,c(_*x))}static fromBytes(y,_=!1){let x=n.BYTES,{a:D,d:R}=s;y=Oo(wt(y,x,"point")),qt(_,"zip215");let M=Oo(y),U=y[x-1];M[x-1]=U&-129;let O=zt(M),E=_?a:n.ORDER;wr("point.y",O,ie,E);let C=c(O*O),k=c(C-et),L=c(R*C-D),{isValid:b,value:m}=u(k,L);if(!b)throw new Error("bad point: invalid y coordinate");let g=(m&et)===et,v=(U&128)!==0;if(!_&&m===ie&&v)throw new Error("bad point: x=0 and x_0=1");return v!==g&&(m=c(-m)),p.fromAffine({x:m,y:O})}static fromHex(y,_=!1){return p.fromBytes(q("point",y),_)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=8,_=!0){return w.createCache(this,y),_||this.multiply(Vo),this}assertValidity(){h(this)}equals(y){l(y);let{X:_,Y:x,Z:D}=this,{X:R,Y:M,Z:U}=y,O=c(_*U),E=c(R*D),C=c(x*U),k=c(M*D);return O===E&&C===k}is0(){return this.equals(p.ZERO)}negate(){return new p(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:y}=s,{X:_,Y:x,Z:D}=this,R=c(_*_),M=c(x*x),U=c(Vo*c(D*D)),O=c(y*R),E=_+x,C=c(c(E*E)-R-M),k=O+M,L=k-U,b=O-M,m=c(C*L),g=c(k*b),v=c(C*b),A=c(L*k);return new p(m,g,A,v)}add(y){l(y);let{a:_,d:x}=s,{X:D,Y:R,Z:M,T:U}=this,{X:O,Y:E,Z:C,T:k}=y,L=c(D*O),b=c(R*E),m=c(U*x*k),g=c(M*C),v=c((D+R)*(O+E)-L-b),A=g-m,T=g+m,I=c(b-_*L),B=c(v*A),P=c(T*I),N=c(v*I),$=c(A*T);return new p(B,P,$,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:_,f:x}=w.cached(this,y,D=>Ht(p,D));return Ht(p,[_,x])[0]}multiplyUnsafe(y,_=p.ZERO){if(!o.isValid(y))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return y===ie?p.ZERO:this.is0()||y===et?this:w.unsafe(this,y,x=>Ht(p,x),_)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return w.unsafe(this,s.n).is0()}toAffine(y){return f(this,y)}clearCofactor(){return i===et?this:this.multiplyUnsafe(i)}toBytes(){let{x:y,y:_}=this.toAffine(),x=n.toBytes(_);return x[x.length-1]|=y&et?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 Ht(p,y)}static msm(y,_){return qe(p,o,y,_)}_setWindowSize(y){this.precompute(y)}toRawBytes(){return this.toBytes()}}p.BASE=new p(s.Gx,s.Gy,et,c(s.Gx*s.Gy)),p.ZERO=new p(ie,et,et,ie),p.Fp=n,p.Fn=o;let w=new Fe(p,o.BITS);return p.BASE.precompute(8),p}var rn=class{constructor(t){this.ep=t}static fromBytes(t){ko()}static fromHex(t){ko()}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 Cf(r,t,e={}){if(typeof t!="function")throw new Error('"hash" function param is required');se(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||Ne,c=e.adjustScalarBytes||(E=>E),u=e.domain||((E,C,k)=>{if(qt(k,"phflag"),C.length||k)throw new Error("Contexts/pre-hash are not supported");return E});function d(E){return i.create(zt(E))}function l(E){let C=x.secretKey;E=q("private key",E,C);let k=q("hashed private key",t(E),2*C),L=c(k.slice(0,C)),b=k.slice(C,2*C),m=d(L);return{head:L,prefix:b,scalar:m}}function f(E){let{head:C,prefix:k,scalar:L}=l(E),b=o.multiply(L),m=b.toBytes();return{head:C,prefix:k,scalar:L,point:b,pointBytes:m}}function h(E){return f(E).pointBytes}function p(E=Uint8Array.of(),...C){let k=dt(...C);return d(t(u(k,q("context",E),!!n)))}function w(E,C,k={}){E=q("message",E),n&&(E=n(E));let{prefix:L,scalar:b,pointBytes:m}=f(C),g=p(k.context,L,E),v=o.multiply(g).toBytes(),A=p(k.context,v,m,E),T=i.create(g+A*b);if(!i.isValid(T))throw new Error("sign failed: invalid s");let I=dt(v,i.toBytes(T));return wt(I,x.signature,"result")}let S={zip215:!0};function y(E,C,k,L=S){let{context:b,zip215:m}=L,g=x.signature;E=q("signature",E,g),C=q("message",C),k=q("publicKey",k,x.publicKey),m!==void 0&&qt(m,"zip215"),n&&(C=n(C));let v=g/2,A=E.subarray(0,v),T=zt(E.subarray(v,g)),I,B,P;try{I=r.fromBytes(k,m),B=r.fromBytes(A,m),P=o.multiplyUnsafe(T)}catch{return!1}if(!m&&I.isSmallOrder())return!1;let N=p(b,B.toBytes(),I.toBytes(),C);return B.add(I.multiplyUnsafe(N)).subtract(P).clearCofactor().is0()}let _=s.BYTES,x={secretKey:_,publicKey:_,signature:2*_,seed:_};function D(E=a(x.seed)){return wt(E,x.seed,"seed")}function R(E){let C=O.randomSecretKey(E);return{secretKey:C,publicKey:h(C)}}function M(E){return Mt(E)&&E.length===i.BYTES}function U(E,C){try{return!!r.fromBytes(E,C)}catch{return!1}}let O={getExtendedPublicKey:f,randomSecretKey:D,isValidSecretKey:M,isValidPublicKey:U,toMontgomery(E){let{y:C}=r.fromBytes(E),k=x.publicKey,L=k===32;if(!L&&k!==57)throw new Error("only defined for 25519 and 448");let b=L?s.div(et+C,et-C):s.div(C-et,C+et);return s.toBytes(b)},toMontgomerySecret(E){let C=x.secretKey;wt(E,C);let k=t(E.subarray(0,C));return c(k).subarray(0,C)},randomPrivateKey:D,precompute(E=8,C=r.BASE){return C.precompute(E,!1)}};return Object.freeze({keygen:R,getPublicKey:h,sign:w,verify:y,utils:O,Point:r,lengths:x})}function Lf(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=Et(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 Tf(r,t){let e=t.Point;return Object.assign({},t,{ExtendedPoint:e,CURVE:r,nBitLength:e.Fn.BITS,nByteLength:e.Fn.BYTES})}function pa(r){let{CURVE:t,curveOpts:e,hash:n,eddsaOpts:o}=Lf(r),s=Df(t,e),i=Cf(s,n,o);return Tf(r,i)}var Rf=BigInt(0),$t=BigInt(1),ma=BigInt(2),D0=BigInt(3),Pf=BigInt(5),Of=BigInt(8),ze=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),vr={p:ze,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Of,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function kf(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),s=ze,a=r*r%s*r%s,c=V(a,ma,s)*a%s,u=V(c,$t,s)*r%s,d=V(u,Pf,s)*u%s,l=V(d,t,s)*d%s,f=V(l,e,s)*l%s,h=V(f,n,s)*f%s,p=V(h,o,s)*h%s,w=V(p,o,s)*h%s,S=V(w,t,s)*d%s;return{pow_p_5_8:V(S,ma,s)*r%s,b2:a}}function Nf(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var Ho=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Zo(r,t){let e=ze,n=X(t*t*t,e),o=X(n*n*t,e),s=kf(r*o).pow_p_5_8,i=X(r*n*s,e),a=X(t*i*i,e),c=i,u=X(i*Ho,e),d=a===r,l=a===X(-r,e),f=a===X(-r*Ho,e);return d&&(i=c),(l||f)&&(i=u),Vt(i,e)&&(i=X(-i,e)),{isValid:d||l,value:i}}var ae=Et(vr.p,{isLE:!0}),Uf=Et(vr.n,{isLE:!0}),Mf={...vr,Fp:ae,hash:Zi,adjustScalarBytes:Nf,uvRatio:Zo},Gt=pa(Mf);var $o=Ho,Kf=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Ff=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),qf=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),zf=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),ga=r=>Zo($t,r),Vf=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Go=r=>Gt.Point.Fp.create(zt(r)&Vf);function ya(r){let{d:t}=vr,e=ze,n=y=>ae.create(y),o=n($o*r*r),s=n((o+$t)*qf),i=BigInt(-1),a=n((i-t*o)*n(o+t)),{isValid:c,value:u}=Zo(s,a),d=n(u*r);Vt(d,e)||(d=n(-d)),c||(u=d),c||(i=o);let l=n(i*(o-$t)*zf-a),f=u*u,h=n((u+u)*a),p=n(l*Kf),w=n($t-f),S=n($t+f);return new Gt.Point(n(h*S),n(w*p),n(p*S),n(h*w))}function Hf(r){gt(r,64);let t=Go(r.subarray(0,32)),e=ya(t),n=Go(r.subarray(32,64)),o=ya(n);return new Zt(e.add(o))}var Zt=class r extends rn{constructor(t){super(t)}static fromAffine(t){return new r(Gt.Point.fromAffine(t))}assertSame(t){if(!(t instanceof r))throw new Error("RistrettoPoint expected")}init(t){return new r(t)}static hashToCurve(t){return Hf(q("ristrettoHash",t,64))}static fromBytes(t){gt(t,32);let{a:e,d:n}=vr,o=ze,s=D=>ae.create(D),i=Go(t);if(!Xi(ae.toBytes(i),t)||Vt(i,o))throw new Error("invalid ristretto255 encoding 1");let a=s(i*i),c=s($t+e*a),u=s($t-e*a),d=s(c*c),l=s(u*u),f=s(e*n*d-l),{isValid:h,value:p}=ga(s(f*l)),w=s(p*u),S=s(p*w*f),y=s((i+i)*w);Vt(y,o)&&(y=s(-y));let _=s(c*S),x=s(y*_);if(!h||Vt(x,o)||_===Rf)throw new Error("invalid ristretto255 encoding 2");return new r(new Gt.Point(y,_,$t,x))}static fromHex(t){return r.fromBytes(q("ristrettoHex",t,32))}static msm(t,e){return qe(r,Gt.Point.Fn,t,e)}toBytes(){let{X:t,Y:e,Z:n,T:o}=this.ep,s=ze,i=S=>ae.create(S),a=i(i(n+e)*i(n-e)),c=i(t*e),u=i(c*c),{value:d}=ga(i(a*u)),l=i(d*a),f=i(d*c),h=i(l*f*o),p;if(Vt(o*h,s)){let S=i(e*$o),y=i(t*$o);t=S,e=y,p=i(l*Ff)}else p=f;Vt(t*h,s)&&(e=i(-e));let w=i((n-e)*p);return Vt(w,s)&&(w=i(-w)),ae.toBytes(w)}equals(t){this.assertSame(t);let{X:e,Y:n}=this.ep,{X:o,Y:s}=t.ep,i=u=>ae.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)}};Zt.BASE=new Zt(Gt.Point.BASE);Zt.ZERO=new Zt(Gt.Point.ZERO);Zt.Fp=ae;Zt.Fn=Uf;var _r=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},nn=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var ba={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new nn("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 on=ba;var sn=32;var jo,$f=(async()=>{try{return await on.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function Gf(r,t,e){if(r.buffer instanceof ArrayBuffer){let n=await on.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await on.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 Zf(r,t,e){return Gt.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}async function xa(r,t,e){return jo==null&&(jo=await $f),jo?Gf(r,t,e):Zf(r,t,e)}function an(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var cn=class{type="Ed25519";raw;constructor(t){this.raw=Xo(t,sn)}toMultihash(){return Ct.digest(Pe(this))}toCID(){return it.createV1(114,this.toMultihash())}toString(){return Y.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:lt(this.raw,t.raw)}verify(t,e,n){n?.signal?.throwIfAborted();let o=xa(this.raw,e,t);return an(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function Ea(r){return r=Xo(r,sn),new cn(r)}function Xo(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new ft(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}var Xf=Math.pow(2,7),Yf=Math.pow(2,14),Wf=Math.pow(2,21),Yo=Math.pow(2,28),Wo=Math.pow(2,35),Qo=Math.pow(2,42),Jo=Math.pow(2,49),F=128,at=127;function yt(r){if(r<Xf)return 1;if(r<Yf)return 2;if(r<Wf)return 3;if(r<Yo)return 4;if(r<Wo)return 5;if(r<Qo)return 6;if(r<Jo)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Ve(r,t,e=0){switch(yt(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 Qf(r,t,e=0){switch(yt(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 ts(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)*Yo,e<F)||(e=r[t+5],n+=(e&at)*Wo,e<F)||(e=r[t+6],n+=(e&at)*Qo,e<F)||(e=r[t+7],n+=(e&at)*Jo,e<F))return n;throw new RangeError("Could not decode varint")}function Jf(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)*Yo,e<F)||(e=r.get(t+5),n+=(e&at)*Wo,e<F)||(e=r.get(t+6),n+=(e&at)*Qo,e<F)||(e=r.get(t+7),n+=(e&at)*Jo,e<F))return n;throw new RangeError("Could not decode varint")}function Sa(r,t,e=0){return t==null&&(t=mt(yt(r))),t instanceof Uint8Array?Ve(r,t,e):Qf(r,t,e)}function Ar(r,t=0){return r instanceof Uint8Array?ts(r,t):Jf(r,t)}var es=new Float32Array([-0]),ce=new Uint8Array(es.buffer);function _a(r,t,e){es[0]=r,t[e]=ce[0],t[e+1]=ce[1],t[e+2]=ce[2],t[e+3]=ce[3]}function Aa(r,t){return ce[0]=r[t],ce[1]=r[t+1],ce[2]=r[t+2],ce[3]=r[t+3],es[0]}var rs=new Float64Array([-0]),ct=new Uint8Array(rs.buffer);function Ia(r,t,e){rs[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 Ba(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],rs[0]}var tl=BigInt(Number.MAX_SAFE_INTEGER),el=BigInt(Number.MIN_SAFE_INTEGER),St=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 be;if(t<tl&&t>el)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>Da&&(o=0n,++n>Da&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return be;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):be}},be=new St(0,0);be.toBigInt=function(){return 0n};be.zzEncode=be.zzDecode=function(){return this};be.length=function(){return 1};var Da=4294967296n;function Ca(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 La(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 ns(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 un(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var os=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 un(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Tt(this,4);return un(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Tt(this,4);let t=Aa(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw Tt(this,4);let t=Ba(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 La(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 St(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=un(this.buf,this.pos+=4),e=un(this.buf,this.pos+=4);return new St(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=ts(this.buf,this.pos);return this.pos+=yt(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 ss(r){return new os(r instanceof Uint8Array?r:r.subarray())}function It(r,t,e){let n=ss(r);return t.decode(n,void 0,e)}function is(r){let t=r??8192,e=t>>>1,n,o=t;return function(i){if(i<1||i>e)return mt(i);o+i>t&&(n=mt(t),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var xe=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function as(){}var us=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},rl=is();function nl(r){return globalThis.Buffer!=null?mt(r):rl(r)}var Br=class{len;head;tail;states;constructor(){this.len=0,this.head=new xe(as,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new xe(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new fs((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(fn,10,St.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=St.fromBigInt(t);return this._push(fn,e.length(),e)}uint64Number(t){return this._push(Ve,yt(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=St.fromBigInt(t).zzEncode();return this._push(fn,e.length(),e)}sint64Number(t){let e=St.fromNumber(t).zzEncode();return this._push(fn,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(cs,1,t?1:0)}fixed32(t){return this._push(Ir,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=St.fromBigInt(t);return this._push(Ir,4,e.lo)._push(Ir,4,e.hi)}fixed64Number(t){let e=St.fromNumber(t);return this._push(Ir,4,e.lo)._push(Ir,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(_a,4,t)}double(t){return this._push(Ia,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(cs,1,0):this.uint32(e)._push(sl,e,t)}string(t){let e=Ca(t);return e!==0?this.uint32(e)._push(ns,e,t):this._push(cs,1,0)}fork(){return this.states=new us(this),this.head=this.tail=new xe(as,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 xe(as,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=nl(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function cs(r,t,e){t[e]=r&255}function ol(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var fs=class extends xe{next;constructor(t,e){super(ol,t,e),this.next=void 0}};function fn(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 Ir(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 sl(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(Br.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(il,t,r),this},Br.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(al,t,r),this});function il(r,t,e){t.set(r,e)}function al(r,t,e){r.length<40?ns(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(H(r),e)}function ls(){return new Br}function Bt(r,t){let e=ls();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var He;(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"})(He||(He={}));function ln(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function we(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 ln("enum",He.VARINT,e,n)}function Dt(r,t){return ln("message",He.LENGTH_DELIMITED,r,t)}var dn=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var vt;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(vt||(vt={}));var ds;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(ds||(ds={}));(function(r){r.codec=()=>we(ds)})(vt||(vt={}));var Dr;(function(r){let t;r.codec=()=>(t==null&&(t=Dt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),vt.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=vt.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)})(Dr||(Dr={}));var hs;(function(r){let t;r.codec=()=>(t==null&&(t=Dt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),vt.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=vt.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)})(hs||(hs={}));var hn=class extends Oe{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,Xr(t);let n=mr(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),Kt(s)}update(t){return ke(this),this.iHash.update(t),this}digestInto(t){ke(this),gt(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()}},ps=(r,t,e)=>new hn(r,t).update(e).digest();ps.create=(r,t)=>new hn(r,t);var Ra=(r,t)=>(r+(r>=0?t:-t)/Pa)/t;function ul(r,t,e){let[[n,o],[s,i]]=t,a=Ra(i*r,e),c=Ra(-o*r,e),u=r-a*n-c*s,d=-a*o-c*i,l=u<Xt,f=d<Xt;l&&(u=-u),f&&(d=-d);let h=oe(Math.ceil(Jr(e)/2))+Ge;if(u<Xt||u>=h||d<Xt||d>=h)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:l,k1:u,k2neg:f,k2:d}}function gs(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function ms(r,t){let e={};for(let n of Object.keys(t))e[n]=r[n]===void 0?t[n]:r[n];return qt(e.lowS,"lowS"),qt(e.prehash,"prehash"),e.format!==void 0&&gs(e.format),e}var ys=class extends Error{constructor(t=""){super(t)}},jt={Err:ys,_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=xr(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let s=n>127?xr(o.length/2|128):"";return xr(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<Xt)throw new t("integer: negative integers are not allowed");let e=xr(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 Ue(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=jt,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}=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)}},Xt=BigInt(0),Ge=BigInt(1),Pa=BigInt(2),pn=BigInt(3),fl=BigInt(4);function $e(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 ll(r,t={}){let e=en("weierstrass",r,t),{Fp:n,Fn:o}=e,s=e.CURVE,{h:i,n:a}=s;se(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=ka(n,o);function d(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function l(L,b,m){let{x:g,y:v}=b.toAffine(),A=n.toBytes(g);if(qt(m,"isCompressed"),m){d();let T=!n.isOdd(v);return dt(Oa(T),A)}else return dt(Uint8Array.of(4),A,n.toBytes(v))}function f(L){wt(L,void 0,"Point");let{publicKey:b,publicKeyUncompressed:m}=u,g=L.length,v=L[0],A=L.subarray(1);if(g===b&&(v===2||v===3)){let T=n.fromBytes(A);if(!n.isValid(T))throw new Error("bad point: is not on curve, wrong x");let I=w(T),B;try{B=n.sqrt(I)}catch($){let z=$ instanceof Error?": "+$.message:"";throw new Error("bad point: is not on curve, sqrt error"+z)}d();let P=n.isOdd(B);return(v&1)===1!==P&&(B=n.neg(B)),{x:T,y:B}}else if(g===m&&v===4){let T=n.BYTES,I=n.fromBytes(A.subarray(0,T)),B=n.fromBytes(A.subarray(T,T*2));if(!S(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 h=t.toBytes||l,p=t.fromBytes||f;function w(L){let b=n.sqr(L),m=n.mul(b,L);return n.add(n.add(m,n.mul(L,s.a)),s.b)}function S(L,b){let m=n.sqr(b),g=w(L);return n.eql(m,g)}if(!S(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let y=n.mul(n.pow(s.a,pn),fl),_=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(y,_)))throw new Error("bad curve params: a or b");function x(L,b,m=!1){if(!n.isValid(b)||m&&n.is0(b))throw new Error(`bad point coordinate ${L}`);return b}function D(L){if(!(L instanceof E))throw new Error("ProjectivePoint expected")}function R(L){if(!c||!c.basises)throw new Error("no endo");return ul(L,c.basises,o.ORDER)}let M=Me((L,b)=>{let{X:m,Y:g,Z:v}=L;if(n.eql(v,n.ONE))return{x:m,y:g};let A=L.is0();b==null&&(b=A?n.ONE:n.inv(v));let T=n.mul(m,b),I=n.mul(g,b),B=n.mul(v,b);if(A)return{x:n.ZERO,y:n.ZERO};if(!n.eql(B,n.ONE))throw new Error("invZ was invalid");return{x:T,y:I}}),U=Me(L=>{if(L.is0()){if(t.allowInfinityPoint&&!n.is0(L.Y))return;throw new Error("bad point: ZERO")}let{x:b,y:m}=L.toAffine();if(!n.isValid(b)||!n.isValid(m))throw new Error("bad point: x or y not field elements");if(!S(b,m))throw new Error("bad point: equation left != right");if(!L.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function O(L,b,m,g,v){return m=new E(n.mul(m.X,L),m.Y,m.Z),b=Sr(g,b),m=Sr(v,m),b.add(m)}class E{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 E)throw new Error("projective point not allowed");return n.is0(m)&&n.is0(g)?E.ZERO:new E(m,g,n.ONE)}static fromBytes(b){let m=E.fromAffine(p(wt(b,void 0,"point")));return m.assertValidity(),m}static fromHex(b){return E.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(pn),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:v}=this,{X:A,Y:T,Z:I}=b,B=n.eql(n.mul(m,I),n.mul(A,v)),P=n.eql(n.mul(g,I),n.mul(T,v));return B&&P}negate(){return new E(this.X,n.neg(this.Y),this.Z)}double(){let{a:b,b:m}=s,g=n.mul(m,pn),{X:v,Y:A,Z:T}=this,I=n.ZERO,B=n.ZERO,P=n.ZERO,N=n.mul(v,v),$=n.mul(A,A),z=n.mul(T,T),K=n.mul(v,A);return K=n.add(K,K),P=n.mul(v,T),P=n.add(P,P),I=n.mul(b,P),B=n.mul(g,z),B=n.add(I,B),I=n.sub($,B),B=n.add($,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,T),z=n.add(z,z),N=n.mul(z,K),I=n.sub(I,N),P=n.mul(z,$),P=n.add(P,P),P=n.add(P,P),new E(I,B,P)}add(b){D(b);let{X:m,Y:g,Z:v}=this,{X:A,Y:T,Z:I}=b,B=n.ZERO,P=n.ZERO,N=n.ZERO,$=s.a,z=n.mul(s.b,pn),K=n.mul(m,A),G=n.mul(g,T),W=n.mul(v,I),pt=n.add(m,g),Z=n.add(A,T);pt=n.mul(pt,Z),Z=n.add(K,G),pt=n.sub(pt,Z),Z=n.add(m,v);let st=n.add(A,I);return Z=n.mul(Z,st),st=n.add(K,W),Z=n.sub(Z,st),st=n.add(g,v),B=n.add(T,I),st=n.mul(st,B),B=n.add(G,W),st=n.sub(st,B),N=n.mul($,Z),B=n.mul(z,W),N=n.add(B,N),B=n.sub(G,N),N=n.add(G,N),P=n.mul(B,N),G=n.add(K,K),G=n.add(G,K),W=n.mul($,W),Z=n.mul(z,Z),G=n.add(G,W),W=n.sub(K,W),W=n.mul($,W),Z=n.add(Z,W),K=n.mul(G,Z),P=n.add(P,K),K=n.mul(st,Z),B=n.mul(pt,B),B=n.sub(B,K),K=n.mul(pt,G),N=n.mul(st,N),N=n.add(N,K),new E(B,P,N)}subtract(b){return this.add(b.negate())}is0(){return this.equals(E.ZERO)}multiply(b){let{endo:m}=t;if(!o.isValidNot0(b))throw new Error("invalid scalar: out of range");let g,v,A=T=>k.cached(this,T,I=>Ht(E,I));if(m){let{k1neg:T,k1:I,k2neg:B,k2:P}=R(b),{p:N,f:$}=A(I),{p:z,f:K}=A(P);v=$.add(K),g=O(m.beta,N,z,T,B)}else{let{p:T,f:I}=A(b);g=T,v=I}return Ht(E,[g,v])[0]}multiplyUnsafe(b){let{endo:m}=t,g=this;if(!o.isValid(b))throw new Error("invalid scalar: out of range");if(b===Xt||g.is0())return E.ZERO;if(b===Ge)return g;if(k.hasCache(this))return this.multiply(b);if(m){let{k1neg:v,k1:A,k2neg:T,k2:I}=R(b),{p1:B,p2:P}=ha(E,g,A,I);return O(m.beta,B,P,v,T)}else return k.unsafe(g,b)}multiplyAndAddUnsafe(b,m,g){let v=this.multiplyUnsafe(m).add(b.multiplyUnsafe(g));return v.is0()?void 0:v}toAffine(b){return M(this,b)}isTorsionFree(){let{isTorsionFree:b}=t;return i===Ge?!0:b?b(E,this):k.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:b}=t;return i===Ge?this:b?b(E,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(b=!0){return qt(b,"isCompressed"),this.assertValidity(),h(E,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 Ht(E,b)}static msm(b,m){return qe(E,o,b,m)}static fromPrivateKey(b){return E.BASE.multiply($e(o,b))}}E.BASE=new E(s.Gx,s.Gy,n.ONE),E.ZERO=new E(n.ZERO,n.ONE,n.ZERO),E.Fp=n,E.Fn=o;let C=o.BITS,k=new Fe(E,t.endo?Math.ceil(C/2):C);return E.BASE.precompute(8),E}function Oa(r){return Uint8Array.of(r?2:3)}function ka(r,t){return{secretKey:t.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function dl(r,t={}){let{Fn:e}=r,n=t.randomBytes||Ne,o=Object.assign(ka(r.Fp,e),{seed:Mo(e.ORDER)});function s(h){try{return!!$e(e,h)}catch{return!1}}function i(h,p){let{publicKey:w,publicKeyUncompressed:S}=o;try{let y=h.length;return p===!0&&y!==w||p===!1&&y!==S?!1:!!r.fromBytes(h)}catch{return!1}}function a(h=n(o.seed)){return Ko(wt(h,o.seed,"seed"),e.ORDER)}function c(h,p=!0){return r.BASE.multiply($e(e,h)).toBytes(p)}function u(h){let p=a(h);return{secretKey:p,publicKey:c(p)}}function d(h){if(typeof h=="bigint")return!1;if(h instanceof r)return!0;let{secretKey:p,publicKey:w,publicKeyUncompressed:S}=o;if(e.allowedLengths||p===w)return;let y=q("key",h).length;return y===w||y===S}function l(h,p,w=!0){if(d(h)===!0)throw new Error("first arg must be private key");if(d(p)===!1)throw new Error("second arg must be public key");let S=$e(e,h);return r.fromHex(p).multiply(S).toBytes(w)}return Object.freeze({getPublicKey:c,getSharedSecret:l,keygen:u,Point:r,utils:{isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a,isValidPrivateKey:s,randomPrivateKey:a,normPrivateKeyToScalar:h=>$e(e,h),precompute(h=8,p=r.BASE){return p.precompute(h,!1)}},lengths:o})}function hl(r,t,e={}){Xr(t),se(e,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let n=e.randomBytes||Ne,o=e.hmac||((m,...g)=>ps(t,m,dt(...g))),{Fp:s,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:u,getPublicKey:d,getSharedSecret:l,utils:f,lengths:h}=dl(r,e),p={prehash:!1,lowS:typeof e.lowS=="boolean"?e.lowS:!1,format:void 0,extraEntropy:!1},w="compact";function S(m){let g=a>>Ge;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 _(m,g){gs(g);let v=h.signature,A=g==="compact"?v:g==="recovered"?v+1:void 0;return wt(m,A,`${g} signature`)}class x{constructor(g,v,A){this.r=y("r",g),this.s=y("s",v),A!=null&&(this.recovery=A),Object.freeze(this)}static fromBytes(g,v=w){_(g,v);let A;if(v==="der"){let{r:P,s:N}=jt.toSig(wt(g));return new x(P,N)}v==="recovered"&&(A=g[0],v="compact",g=g.subarray(1));let T=i.BYTES,I=g.subarray(0,T),B=g.subarray(T,T*2);return new x(i.fromBytes(I),i.fromBytes(B),A)}static fromHex(g,v){return this.fromBytes(he(g),v)}addRecoveryBit(g){return new x(this.r,this.s,g)}recoverPublicKey(g){let v=s.ORDER,{r:A,s:T,recovery:I}=this;if(I==null||![0,1,2,3].includes(I))throw new Error("recovery id invalid");if(a*Pa<v&&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),$=r.fromBytes(dt(Oa((I&1)===0),N)),z=i.inv(P),K=R(q("msgHash",g)),G=i.create(-K*z),W=i.create(T*z),pt=r.BASE.multiplyUnsafe(G).add($.multiplyUnsafe(W));if(pt.is0())throw new Error("point at infinify");return pt.assertValidity(),pt}hasHighS(){return S(this.s)}toBytes(g=w){if(gs(g),g==="der")return he(jt.hexFromSig(this));let v=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 dt(Uint8Array.of(this.recovery),v,A)}return dt(v,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 v=Ue(g),A=g.length*8-c;return A>0?v>>BigInt(A):v},R=e.bits2int_modN||function(g){return i.create(D(g))},M=oe(c);function U(m){return wr("num < 2^"+c,m,Xt,M),i.toBytes(m)}function O(m,g){return wt(m,void 0,"message"),g?wt(t(m),void 0,"prehashed message"):m}function E(m,g,v){if(["recovered","canonical"].some(G=>G in v))throw new Error("sign() legacy options not supported");let{lowS:A,prehash:T,extraEntropy:I}=ms(v,p);m=O(m,T);let B=R(m),P=$e(i,g),N=[U(P),U(B)];if(I!=null&&I!==!1){let G=I===!0?n(h.secretKey):I;N.push(q("extraEntropy",G))}let $=dt(...N),z=B;function K(G){let W=D(G);if(!i.isValidNot0(W))return;let pt=i.inv(W),Z=r.BASE.multiply(W).toAffine(),st=i.create(Z.x);if(st===Xt)return;let Mr=i.create(pt*i.create(z+st*P));if(Mr===Xt)return;let Ys=(Z.x===st?0:2)|Number(Z.y&Ge),Ws=Mr;return A&&S(Mr)&&(Ws=i.neg(Mr),Ys^=1),new x(st,Ws,Ys)}return{seed:$,k2sig:K}}function C(m,g,v={}){m=q("message",m);let{seed:A,k2sig:T}=E(m,g,v);return Wi(t.outputLen,i.BYTES,o)(A,T)}function k(m){let g,v=typeof m=="string"||Mt(m),A=!v&&m!==null&&typeof m=="object"&&typeof m.r=="bigint"&&typeof m.s=="bigint";if(!v&&!A)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(A)g=new x(m.r,m.s);else if(v){try{g=x.fromBytes(q("sig",m),"der")}catch(T){if(!(T instanceof jt.Err))throw T}if(!g)try{g=x.fromBytes(q("sig",m),"compact")}catch{return!1}}return g||!1}function L(m,g,v,A={}){let{lowS:T,prehash:I,format:B}=ms(A,p);if(v=q("publicKey",v),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(v);if(T&&P.hasHighS())return!1;let{r:$,s:z}=P,K=R(g),G=i.inv(z),W=i.create(K*G),pt=i.create($*G),Z=r.BASE.multiplyUnsafe(W).add(N.multiplyUnsafe(pt));return Z.is0()?!1:i.create(Z.x)===$}catch{return!1}}function b(m,g,v={}){let{prehash:A}=ms(v,p);return g=O(g,A),x.fromBytes(m,"recovered").recoverPublicKey(g).toBytes()}return Object.freeze({keygen:u,getPublicKey:d,getSharedSecret:l,utils:f,lengths:h,Point:r,sign:C,verify:L,recoverPublicKey:b,Signature:x,hash:t})}function pl(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=Et(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 ml(r){let{CURVE:t,curveOpts:e}=pl(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 gl(r,t){let e=t.Point;return Object.assign({},t,{ProjectivePoint:e,CURVE:Object.assign({},r,tn(e.Fn.ORDER,e.Fn.BITS))})}function Na(r){let{CURVE:t,curveOpts:e,hash:n,ecdsaOpts:o}=ml(r),s=ll(t,e),i=hl(s,n,o);return gl(r,i)}function Ua(r,t){let e=n=>Na({...r,hash:n});return{...e(t),create:e}}var xs={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},yl={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Ma=BigInt(2);function bl(r){let t=xs.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=V(d,e,t)*d%t,f=V(l,e,t)*d%t,h=V(f,Ma,t)*u%t,p=V(h,o,t)*h%t,w=V(p,s,t)*p%t,S=V(w,a,t)*w%t,y=V(S,c,t)*S%t,_=V(y,a,t)*w%t,x=V(_,e,t)*d%t,D=V(x,i,t)*p%t,R=V(D,n,t)*u%t,M=V(R,Ma,t);if(!bs.eql(bs.sqr(M),r))throw new Error("Cannot find square root");return M}var bs=Et(xs.p,{sqrt:bl}),Ze=Ua({...xs,Fp:bs,lowS:!0,endo:yl},Gi);function Ka(r,t,e,n){let o=fr.digest(e instanceof Uint8Array?e:e.subarray());if(an(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),Ze.verify(t,s,r))).catch(s=>{throw s.name==="AbortError"?s:new _r(String(s))});try{return n?.signal?.throwIfAborted(),Ze.verify(t,o.digest,r)}catch(s){throw new _r(String(s))}}var mn=class{type="secp256k1";raw;_key;constructor(t){this._key=qa(t),this.raw=Fa(this._key)}toMultihash(){return Ct.digest(Pe(this))}toCID(){return it.createV1(114,this.toMultihash())}toString(){return Y.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:lt(this.raw,t.raw)}verify(t,e,n){return Ka(this._key,e,t,n)}};function za(r){return new mn(r)}function Fa(r){return Ze.ProjectivePoint.fromHex(r).toRawBytes(!0)}function qa(r){try{return Ze.ProjectivePoint.fromHex(r),r}catch(t){throw new Fr(String(t))}}function Va(r){let{Type:t,Data:e}=Dr.decode(r.digest),n=e??new Uint8Array;switch(t){case vt.Ed25519:return Ea(n);case vt.secp256k1:return za(n);case vt.ECDSA:return Ci(n);default:throw new or}}function Pe(r){return Dr.encode({Type:vt[r.type],Data:r.raw})}var Ha=Symbol.for("nodejs.util.inspect.custom"),xl=114,Cr=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()})`}[jn]=!0;toString(){return this.string==null&&(this.string=Y.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return it.createV1(xl,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return lt(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return lt(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[Ha](){return`PeerId(${this.toString()})`}},gn=class extends Cr{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},yn=class extends Cr{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},bn=class extends Cr{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},wl=2336,xn=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=Ct.digest(H(this.url))}[Ha](){return`PeerId(${this.url})`}[jn]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return it.createV1(wl,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=Q(t)),t.toString()===this.toString())}};function $a(r){if(Sl(r))return new gn({multihash:r});if(El(r))try{let t=Va(r);if(t.type==="Ed25519")return new yn({multihash:r,publicKey:t});if(t.type==="secp256k1")return new bn({multihash:r,publicKey:t})}catch{let e=Q(r.digest);return new xn(new URL(e))}throw new qr("Supplied PeerID Multihash is invalid")}function El(r){return r.code===Ct.code}function Sl(r){return r.code===fr.code}function ws(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 wn(r){let t=cr(Y.decode(`z${r}`));return $a(t)}var En=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 ws(this.set.entries(),t=>{let e=wn(t[0]);return[e,e]})}forEach(t){this.set.forEach(e=>{let n=wn(e);t(n,n,this)})}has(t){return this.set.has(t.toString())}values(){return ws(this.set.values(),t=>wn(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 Es(){return new En}var Ss={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Ga={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Za=new globalThis.TextEncoder;function vl(r,t){let e=Ss[t],n=Ga[t];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(t,n*e);return n}function _l(r,t,e){if(e.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Ss[t],o=Ga[t],s=r;for(;s.length>0;){let i=Za.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 vs(r,{size:t=32,utf8Buffer:e}={}){if(!Ss[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 _l(r,t,e);r=Za.encode(r)}return vl(r,t)}var Lr={hash:r=>Number(vs(r,{size:32})),hashV:(r,t)=>Al(Lr.hash(r,t))};function Al(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),H(t,"base16")}var _s=64,Rt=class{fp;h;seed;constructor(t,e,n,o=2){if(o>_s)throw new TypeError("Invalid Fingerprint Size");let s=e.hashV(t,n),i=xt(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=e,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(t){return t?.fp instanceof Uint8Array?lt(this.fp,t.fp):!1}};function Ee(r,t){return Math.floor(Math.random()*(t-r))+r}var Se=class{contents;constructor(t){this.contents=new Array(t).fill(null)}has(t){if(!(t instanceof Rt))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof Rt))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 Rt))throw new TypeError("Invalid Fingerprint");let e=Ee(0,this.contents.length-1),n=this.contents[e];return this.contents[e]=t,n}remove(t){if(!(t instanceof Rt))throw new TypeError("Invalid Fingerprint");let e=this.contents.findIndex(n=>t.equals(n));return e>-1?(this.contents[e]=null,!0):!1}};var Il=500,Tr=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??Lr,this.seed=t.seed??Ee(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=H(t));let e=new Rt(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 Se(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new Se(this.bucketSize)),this.buckets[n].add(e)||this.buckets[o].add(e))return this.count++,!0;let s=[n,o],i=s[Ee(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new Se(this.bucketSize));for(let a=0;a<Il;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 Se(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(t){typeof t=="string"&&(t=H(t));let e=new Rt(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 Rt(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}},Bl={1:.5,2:.84,4:.95,8:.98};function Dl(r=.001){return r>.002?2:r>1e-5?4:8}function ja(r,t=.001){let e=Dl(t),n=Bl[e],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),_s);return{filterSize:o,bucketSize:e,fingerprintSize:s}}var Sn=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??Lr,this.seed=t.seed??Ee(0,Math.pow(2,10)),this.filterSeries=[new Tr({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 Tr({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 As(r,t=.001,e){return new Sn({...ja(r,t),...e??{}})}function ue(r){let t=r.getComponents(),e={},n=0;if(t[n]?.name==="ip6zone"&&(e.zone=`${t[n].value}`,n++),t[n].name==="ip4"||t[n].name==="ip6"||t[n].name==="dns"||t[n].name==="dns4"||t[n].name==="dns6"?(e.type=t[n].name,e.host=t[n].value,n++):t[n].name==="dnsaddr"&&(e.type=t[n].name,e.host=`_dnsaddr.${t[n].value}`,n++),(t[n]?.name==="tcp"||t[n]?.name==="udp")&&(e.protocol=t[n].name==="tcp"?"tcp":"udp",e.port=parseInt(`${t[n].value}`),n++),t[n]?.name==="ipcidr"&&(e.type==="ip4"?e.cidr=parseInt(`${t[n].value}`):e.type==="ip6"&&(e.cidr=`${t[n].value}`),n++),e.type==null||e.host==null)throw new ft(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return t[n]?.name==="tls"&&t[n+1]?.name==="sni"&&(e.sni=t[n+1].value,n+=2),e}var vn=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 Xa=45,Cl=15,je=new vn;function _n(r){if(!(r.length>Cl))return je.new(r).parseWith(()=>je.readIPv4Addr())}function An(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Xa))return je.new(r).parseWith(()=>je.readIPv6Addr())}function Xe(r,t=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>Xa)return;let e=je.new(r).parseWith(()=>je.readIPAddr());if(e)return t&&e.length===4?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,e[0],e[1],e[2],e[3]]):e}function Ya(r,t,e){let n=0;for(let o of r)if(!(n<t)){if(n>e)break;if(o!==255)return!1;n++}return!0}function Wa(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 Is(r){switch(r.length){case ve:return r.join(".");case _e:{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 Qa(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 Ja(r){let t="0x";for(let e of r)t+=(e>>4).toString(16)+(e&15).toString(16);return t}var ve=4,_e=16,Py=parseInt("0xFFFF",16),Ll=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Rr(r,t){t.length===_e&&r.length===ve&&Ya(t,0,11)&&(t=t.slice(12)),t.length===ve&&r.length===_e&&Wa(r,Ll,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 tc(r,t){if(typeof t=="string"&&(t=Xe(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 Bs(r){let[t,e]=r.split("/");if(!t||!e)throw new Error("Failed to parse given CIDR: "+r);let n=ve,o=_n(t);if(o==null&&(n=_e,o=An(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=Ds(s,8*n);return{network:Rr(o,i),mask:i}}function Ds(r,t){if(t!==8*ve&&t!==8*_e)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 Pr=class{constructor(t,e){if(e==null)({network:this.network,mask:this.mask}=Bs(t));else{let n=Xe(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=Xe(e);if(s==null)throw new Error("Failed to parse mask");this.mask=s}else this.mask=Ds(o,8*n.length);this.network=Rr(n,this.mask)}}contains(t){return tc({network:this.network,mask:this.mask},t)}toString(){let t=Qa(this.mask),e=t!==-1?String(t):Ja(this.mask);return Is(this.network)+"/"+e}};function ec(r,t){return new Pr(r).contains(t)}function rc(r){try{let t=ue(r);switch(t.type){case"ip6":return ec("2000::/3",t.host);default:return!1}}catch{return!1}}function Ye(r){return!!_n(r)}function In(r){return!!An(r)}var oc=Fc(nc(),1),Tl=["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"],Rl=Tl.map(r=>new oc.Netmask(r));function Cs(r){for(let t of Rl)if(t.contains(r))return!0;return!1}function Pl(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function Ol(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 Cs(o)}function kl(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function Nl(r){let t=r.split(":"),e=t[t.length-1];return Cs(e)}function Ul(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 Bn(r){if(Ye(r))return Cs(r);if(Pl(r))return Ol(r);if(kl(r))return Nl(r);if(In(r))return Ul(r)}function sc(r){try{let t=ue(r);switch(t.type){case"ip4":case"ip6":return Bn(t.host)??!1;default:return t.host==="localhost"}}catch{return!1}}function We(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var Dn=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}},Qe=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new Dn(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 Dn(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 Ls=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function Cn(r={}){return Ml(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 Ml(r,t){t=t??{};let e=t.onEnd,n=new Qe,o,s,i,a=We(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((S,y)=>{s=_=>{s=null,n.push(_);try{S(r(n))}catch(x){y(x)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=We()})}},u=S=>s!=null?s(S):(n.push(S),o),d=S=>(n=new Qe,s!=null?s({error:S}):(n.push({error:S}),o)),l=S=>{if(i)return o;if(t?.objectMode!==!0&&S?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:S})},f=S=>i?o:(i=!0,S!=null?d(S):u({done:!0})),h=()=>(n=new Qe,f(),{done:!0}),p=S=>(f(S),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:p,push:l,end:f,get readableLength(){return n.size},onEmpty:async S=>{let y=S?.signal;if(y?.throwIfAborted(),n.isEmpty())return;let _,x;y!=null&&(_=new Promise((D,R)=>{x=()=>{R(new Ls)},y.addEventListener("abort",x)}));try{await Promise.race([a.promise,_])}finally{x!=null&&y!=null&&y?.removeEventListener("abort",x)}}},e==null)return o;let w=o;return o={[Symbol.asyncIterator](){return this},next(){return w.next()},throw(S){return w.throw(S),e!=null&&(e(S),e=void 0),{done:!0}},return(){return w.return(),e!=null&&(e(),e=void 0),{done:!0}},push:l,end(S){return w.end(S),e!=null&&(e(S),e=void 0),o},get readableLength(){return w.readableLength},onEmpty:S=>w.onEmpty(S)},o}var Ts=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},Rs=class extends Error{constructor(t){super(),this.name="AbortError",this.message=t}},ic=r=>globalThis.DOMException===void 0?new Rs(r):new DOMException(r),ac=r=>{let t=r.reason===void 0?ic("This operation was aborted."):r.reason;return t instanceof Error?t:ic(t)};function Ps(r,t){let{milliseconds:e,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=t,i,a,u=new Promise((d,l)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(t.signal){let{signal:h}=t;h.aborted&&l(ac(h)),a=()=>{l(ac(h))},h.addEventListener("abort",a,{once:!0})}if(e===Number.POSITIVE_INFINITY){r.then(d,l);return}let f=new Ts;i=s.setTimeout.call(void 0,()=>{if(n){try{d(n())}catch(h){l(h)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?d():o instanceof Error?l(o):(f.message=o??`Promise timed out after ${e} milliseconds`,l(f))},e),(async()=>{try{d(await r)}catch(h){l(h)}})()}).finally(()=>{u.clear(),a&&t.signal&&t.signal.removeEventListener("abort",a)});return u.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},u}var Kl=r=>{let t=r.addEventListener||r.on||r.addListener,e=r.removeEventListener||r.off||r.removeListener;if(!t||!e)throw new TypeError("Emitter is not compatible");return{addListener:t.bind(r),removeListener:e.bind(r)}};function Fl(r,t,e){let n,o=new Promise((s,i)=>{if(e={rejectionEvents:["error"],multiArgs:!1,resolveImmediately:!1,...e},!(e.count>=0&&(e.count===Number.POSITIVE_INFINITY||Number.isInteger(e.count))))throw new TypeError("The `count` option should be at least 0 or more");e.signal?.throwIfAborted();let a=[t].flat(),c=[],{addListener:u,removeListener:d}=Kl(r),l=(...h)=>{let p=e.multiArgs?h:h[0];e.filter&&!e.filter(p)||(c.push(p),e.count===c.length&&(n(),s(c)))},f=h=>{n(),i(h)};n=()=>{for(let h of a)d(h,l);for(let h of e.rejectionEvents)d(h,f)};for(let h of a)u(h,l);for(let h of e.rejectionEvents)u(h,f);e.signal&&e.signal.addEventListener("abort",()=>{f(e.signal.reason)},{once:!0}),e.resolveImmediately&&s(c)});if(o.cancel=n,typeof e.timeout=="number"){let s=Ps(o,{milliseconds:e.timeout});return s.cancel=n,s}return o}function Je(r,t,e){typeof e=="function"&&(e={filter:e}),e={...e,count:1,resolveImmediately:!1};let n=Fl(r,t,e),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}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 Ln=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}},Ae=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"};function ql(r){return r.reason}async function Tn(r,t,e){if(t==null)return r;let n=e?.translateError??ql;if(t.aborted)return r.catch(()=>{}),Promise.reject(n(t));let o;try{return await Promise.race([r,new Promise((s,i)=>{o=()=>{i(n(t))},t.addEventListener("abort",o)})])}finally{o!=null&&t.removeEventListener("abort",o)}}var Rn=class{deferred;signal;constructor(t){this.signal=t,this.deferred=We(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Ot)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function zl(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Pn=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=zl(),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 Ot),this.cleanup())}async join(t={}){let e=new Rn(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 Tn(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 On=class extends zr{concurrency;maxSize;queue;pending;sort;paused;constructor(t={}){super(),this.concurrency=t.concurrency??Number.POSITIVE_INFINITY,this.maxSize=t.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,t.metricName!=null&&t.metrics?.registerMetricGroup(t.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=t.sort,this.queue=[],this.emitEmpty=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")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let t;for(let e of this.queue)if(e.status==="queued"){t=e;break}return t==null?!1:(this.safeDispatchEvent("active"),this.pending++,t.run().finally(()=>{for(let e=0;e<this.queue.length;e++)if(this.queue[e]===t){this.queue.splice(e,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(t){this.queue.push(t),this.sort!=null&&this.queue.sort(this.sort)}async add(t,e){if(e?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Ln;let n=new Pn(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 Ot)}),this.clear()}async onEmpty(t){this.size!==0&&await Je(this,"empty",t)}async onSizeLessThan(t,e){this.size<t||await Je(this,"next",{...e,filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await Je(this,"idle",t)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(t){t?.signal?.throwIfAborted();let e=Cn({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 Ot("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",s),this.addEventListener("idle",i),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),t?.signal?.removeEventListener("abort",a),n()}}};function Nr(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}var ot=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Yt=class extends Error{static name="ValidationError";name="ValidationError"},kn=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Nn=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function ks(r){return t=>Q(t,r)}function Ns(r){return t=>H(t,r)}function tr(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Ie(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(t)}function cc(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==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=Ie(n);return Nt([e,o],e.length+o.length)}function uc(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=te.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=Ie(n);return Nt([e,o],e.length+o.length)}function Us(r){let t=r.subarray(0,r.length-2),e=r.subarray(r.length-2),n=Q(t,"base32"),o=tr(e);return`${n}:${o}`}var Ms=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},fc=function(r){let t=0;r=r.toString().trim();let e=r.split(":",8),n;for(n=0;n<e.length;n++){let s=Ye(e[n]),i;s&&(i=Ms(e[n]),e[n]=Q(i.subarray(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,Q(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},lc=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(".")},dc=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 hc(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 Os=Object.values(lr).map(r=>r.decoder),Vl=(function(){let r=Os[0].or(Os[1]);return Os.slice(2).forEach(t=>r=r.or(t)),r})();function pc(r){return Vl.decode(r)}function mc(r){return t=>r.encoder.encode(t)}function Hl(r){if(parseInt(r).toString()!==r)throw new Yt("Value must be an integer")}function $l(r){if(r<0)throw new Yt("Value must be a positive integer, or zero")}function Gl(r){return t=>{if(t>r)throw new Yt(`Value must be smaller than or equal to ${r}`)}}function Zl(...r){return t=>{for(let e of r)e(t)}}var Ur=Zl(Hl,$l,Gl(65535));var rt=-1,Ks=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 Nn(`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)}))}},Wt=new Ks,Rd=[{code:4,name:"ip4",size:32,valueToBytes:Ms,bytesToValue:lc,validate:r=>{if(!Ye(r))throw new Yt(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Ie,bytesToValue:tr,validate:Ur},{code:273,name:"udp",size:16,valueToBytes:Ie,bytesToValue:tr,validate:Ur},{code:33,name:"dccp",size:16,valueToBytes:Ie,bytesToValue:tr,validate:Ur},{code:41,name:"ip6",size:128,valueToBytes:fc,bytesToValue:dc,stringToValue:hc,validate:r=>{if(!In(r))throw new Yt(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:rt},{code:43,name:"ipcidr",size:8,bytesToValue:ks("base10"),valueToBytes:Ns("base10")},{code:53,name:"dns",size:rt},{code:54,name:"dns4",size:rt},{code:55,name:"dns6",size:rt},{code:56,name:"dnsaddr",size:rt},{code:132,name:"sctp",size:16,valueToBytes:Ie,bytesToValue:tr,validate:Ur},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:rt,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:rt,bytesToValue:ks("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Ns("base58btc")(r):it.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Us,valueToBytes:cc},{code:445,name:"onion3",size:296,bytesToValue:Us,valueToBytes:uc},{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:mc(uo),valueToBytes:pc},{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}];Rd.forEach(r=>{Wt.addProtocol(r)});function gc(r){let t=[],e=0;for(;e<r.length;){let n=Ar(r,e),o=Wt.getProtocol(n),s=yt(n),i=Pd(o,r,e+s),a=0;i>0&&o.size===rt&&(a=yt(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)??Q(l)}t.push(u),e+=c}return t}function yc(r){let t=0,e=[];for(let n of r){if(n.bytes==null){let o=Wt.getProtocol(n.code),s=yt(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=yt(a)));let u=new Uint8Array(s+c+a),d=0;Ve(n.code,u,d),d+=s,i!=null&&(o.size===rt&&(Ve(a,u,d),d+=c),u.set(i,d)),n.bytes=u}e.push(n.bytes),t+=n.bytes.byteLength}return Nt(e,t)}function bc(r){if(r.charAt(0)!=="/")throw new ot('String multiaddr must start with "/"');let t=[],e="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(e==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=Wt.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 xc(r){return`/${r.flatMap(t=>{if(t.value==null)return t.name;let e=Wt.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 Pd(r,t,e){return r.size==null||r.size===0?0:r.size>0?r.size/8:Ar(t,e)}var Od=Symbol.for("nodejs.util.inspect.custom"),zs=Symbol.for("@multiformats/multiaddr");function kd(r){if(r==null&&(r="/"),wc(r))return r.getComponents();if(r instanceof Uint8Array)return gc(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),bc(r);if(Array.isArray(r))return r;throw new ot("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Un=class r{[zs]=!0;#t;#e;#r;constructor(t="/",e={}){this.#t=kd(t),e.validate!==!1&&Nd(this)}get bytes(){return this.#r==null&&(this.#r=yc(this.#t)),this.#r}toString(){return this.#e==null&&(this.#e=xc(this.#t)),this.#e}toJSON(){return this.toString()}getComponents(){return[...this.#t.map(t=>({...t}))]}encapsulate(t){let e=new r(t);return new r([...this.#t,...e.getComponents()],{validate:!1})}decapsulate(t){let e=t.toString(),n=this.toString(),o=n.lastIndexOf(e);if(o<0)throw new kn(`Address ${this.toString()} does not contain subaddress: ${e}`);return new r(n.slice(0,o),{validate:!1})}decapsulateCode(t){let e;for(let n=this.#t.length-1;n>-1;n--)if(this.#t[n].code===t){e=n;break}return new r(this.#t.slice(0,e),{validate:!1})}equals(t){return lt(this.bytes,t.bytes)}[Od](){return`Multiaddr(${this.toString()})`}};function Nd(r){r.getComponents().forEach(t=>{let e=Wt.getProtocol(t.code);t.value!=null&&e.validate?.(t.value)})}function wc(r){return!!r?.[zs]}function Ec(r){return new Un(r)}var Ud=4194304,Mn=class extends Error{static name="UnwrappedError";name="UnwrappedError"},Hs=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},$s=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Gs=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Md(r){return typeof r?.closeRead=="function"}function Kd(r){return typeof r?.close=="function"}function Vs(r){return Md(r)?r.readStatus==="closing"||r.readStatus==="closed":Kd(r)?r.status!=="open":!1}function Fd(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function qd(r,t){let e=t?.maxBufferSize??Ud,n=new J,o=Promise.withResolvers(),s=!1;if(!Fd(r))throw new ft("Argument should be a Stream or a Multiaddr");let i=d=>{if(n.append(d.data),n.byteLength>e){let l=n.byteLength;n.consume(n.byteLength),o.reject(new Error(`Read buffer overflow - ${l} > ${e}`))}o.resolve()};r.addEventListener("message",i);let a=d=>{d.error!=null?o.reject(d.error):o.resolve()};r.addEventListener("close",a);let c=()=>{o.resolve()};r.addEventListener("remoteCloseWrite",c);let u={readBuffer:n,async read(d){if(s===!0)throw new Mn("Stream was unwrapped");if(Vs(r)){if(d?.bytes==null)return null;if(n.byteLength<d.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,d.bytes),new Ae(`Unexpected EOF - stream closed after reading ${n.byteLength}/${d.bytes} bytes`)}let l=d?.bytes??1;for(;;){if(n.byteLength>=l){o.resolve();break}if(await Tn(o.promise,d?.signal),Vs(r)){if(n.byteLength===0&&d?.bytes==null)return null;break}o=Promise.withResolvers()}let f=d?.bytes??n.byteLength;if(n.byteLength<f){if(Vs(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,f),new Ae(`Unexpected EOF - stream closed while reading ${n.byteLength}/${f} bytes`);return u.read(d)}let h=n.sublist(0,f);return n.consume(f),h},async write(d,l){if(s===!0)throw new Mn("Stream was unwrapped");r.send(d)||await Je(r,"drain",{signal:l?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,r.removeEventListener("message",i),r.removeEventListener("close",a),r.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.push(n))),r}};return u}function zd(r,t={}){let e=qd(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=yt(t.maxDataLength));let n=t?.lengthDecoder??Ar,o=t?.lengthEncoder??Sa;return{async read(i){let a=-1,c=new J;for(;;){let d=await e.read({...i,bytes:1});if(d==null)break;c.append(d);try{a=n(c)}catch(l){if(l instanceof RangeError)continue;throw l}if(a<0)throw new Hs("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new Gs(`Message length length too long - ${c.byteLength} > ${t.maxLengthLength}`);if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new $s(`Message length too long - ${a} > ${t.maxDataLength}`);let u=await e.read({...i,bytes:a});if(u==null)throw r.log.error("tried to read %d bytes but the stream closed",a),new Ae(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(u.byteLength!==a)throw r.log.error("read %d/%d bytes before the stream closed",u.byteLength,a),new Ae(`Unexpected EOF - read ${u.byteLength}/${a} bytes before the stream closed`);return u},async write(i,a){await e.write(new J(o(i.byteLength),i),a)},async writeV(i,a){let c=new J(...i.flatMap(u=>[o(u.byteLength),u]));await e.write(c,a)},unwrap(){return e.unwrap()}}}function er(r,t){let e=zd(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 Kn=class extends On{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};function Sc(r,t,e){let n,o,s=!1;function i(){let u={signal:o.signal};if(e?.timeout!=null){let d=Nr([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 Zs=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 vc(r){let{name:t,metrics:e}=r,n;return e!=null?n=new Zs({name:t,metrics:e}):n=new Map,n}var js="libp2p",Xs="autonat";var _c="dial-request",Ac="dial-back",Ic=200n*1024n,Bc=4096;var rr;(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),Fn.codec().encode(e.dialRequest,n)),e.dialResponse!=null&&(n.uint32(18),Qt.codec().encode(e.dialResponse,n)),e.dialDataRequest!=null&&(n.uint32(26),qn.codec().encode(e.dialDataRequest,n)),e.dialDataResponse!=null&&(n.uint32(34),Vn.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=Fn.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=qn.codec().decode(e,e.uint32(),{limits:o.limits?.dialDataRequest});break}case 4:{s.dialDataResponse=Vn.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)})(rr||(rr={}));var Fn;(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 dn('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)})(Fn||(Fn={}));var qn;(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)})(qn||(qn={}));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 zn;(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"})(zn||(zn={}));(function(r){r.codec=()=>we(zn)})(ut||(ut={}));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=()=>we(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&&zn[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)})(Qt||(Qt={}));var Vn;(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:xt(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)})(Vn||(Vn={}));var nr;(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)})(nr||(nr={}));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=()=>we(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)})(fe||(fe={}));function Hn(r,t){return Math.round(Math.random()*(t-r)+r)}var Hd=4,$d=8,$n=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=vc({name:"libp2p_autonat_v2_dial_results",metrics:t.metrics}),this.findPeers=Sc(this.findRandomPeers.bind(this),6e4),this.addressFilter=As(1024),this.queue=new Kn({concurrency:3,maxSize:50}),this.maxDialDataBytes=e.maxDialDataBytes??Ic,this.dialDataChunkSize=e.dialDataChunkSize??Bc,this.nonces=new Set}[Symbol.toStringTag]="@libp2p/autonat-v2";[Vr]=["@libp2p/autonat"];get[Hr](){return["@libp2p/identify"]}isStarted(){return this.started}async start(){this.started||(this.topologyId=await this.components.registrar.register(this.dialRequestProtocol,{onConnect:(t,e)=>{this.verifyExternalAddresses(e).catch(n=>{this.log.error("could not verify addresses - %e",n)})}}),await this.components.registrar.handle(this.dialBackProtocol,(t,e)=>{this.handleDialBackStream(t,e).catch(n=>{this.log.error("error handling incoming autonat stream - %e",n)})},{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams}),this.findPeers.start(),this.started=!0)}async stop(){await this.components.registrar.unhandle(this.dialRequestProtocol),await this.components.registrar.unhandle(this.dialBackProtocol),this.topologyId!=null&&await this.components.registrar.unhandle(this.topologyId),this.dialResults.clear(),this.findPeers.stop(),this.started=!1}allAddressesAreVerified(){return this.components.addressManager.getAddressesWithMetadata().every(t=>t.expires>Date.now()?!0:t.verified)}async findRandomPeers(t){if(this.allAddressesAreVerified())return;let e=Nr([AbortSignal.timeout(1e4),t?.signal]);try{this.log("starting random walk to find peers to run AutoNAT");for await(let n of this.components.randomWalk.walk({signal:e})){if(!await this.components.connectionManager.isDialable(n.multiaddrs)){this.log.trace("random peer %p was not dialable %s",n.id,n.multiaddrs.map(o=>o.toString()).join(", "));continue}try{this.log.trace("dial random peer %p",n.id),await this.components.connectionManager.openConnection(n.multiaddrs,{signal:e})}catch{}if(this.allAddressesAreVerified()){this.log("stopping random walk, all addresses are verified");return}if(!this.hasConnectionCapacity()){this.log("stopping random walk, too close to max connections");return}}}catch{}}async handleDialBackStream(t,e){let n=AbortSignal.timeout(this.timeout);let o=er(t,{maxDataLength:this.maxMessageSize});try{let s=await o.read(nr,{signal:n});if(!this.nonces.has(s.nonce))throw new _t("No matching dial found for nonce value");this.nonces.delete(s.nonce),await o.write({status:fe.DialBackStatus.OK},fe),await t.close({signal:n})}catch(s){this.log.error("error handling incoming dial back stream - %e",s),t.abort(s)}}getUnverifiedMultiaddrs(t,e){let n=this.components.addressManager.getAddressesWithMetadata().sort((s,i)=>s.type==="observed"&&i.type!=="observed"?1:i.type==="observed"&&s.type!=="observed"?-1:0).filter(s=>!(!(s.expires<Date.now())||ue(s.multiaddr).type==="ip6"&&(!e||!rc(s.multiaddr))||sc(s.multiaddr))),o=[];for(let s of n){let i=s.multiaddr.toString(),a=this.dialResults.get(i);if(a!=null&&a.networkSegments.includes(t)){this.log.trace("%a already has a network segment result from %s",a.multiaddr,t);continue}if(a==null){let c=s.expires<Date.now();if(c&&this.addressFilter.remove?.(i),this.addressFilter.has(i))continue;this.addressFilter.add(i),this.log.trace("creating dial result %s %s",c?"to revalidate":"for",i),a={multiaddr:s.multiaddr,success:0,failure:0,networkSegments:[],verifyingPeers:Es(),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})=>ue(i).type==="ip6"),o=this.getNetworkSegment(t.remoteAddr),s=this.getUnverifiedMultiaddrs(o,n);if(s.length!==0){if(!this.hasConnectionCapacity()){s[0]?.lastVerified!=null?(this.log("automatically re-verifying %a because we are too close to the connection limit",s[0].multiaddr),this.confirmAddress(s[0])):this.log("skipping verifying %a because we are too close to the connection limit",s[0]?.multiaddr);return}this.queue.add(async i=>{let a=Nr([i.signal,AbortSignal.timeout(this.timeout)]),c=BigInt(Hn(0,Number.MAX_SAFE_INTEGER));this.nonces.add(c);try{await this.askPeerToVerify(t,o,c,i)}finally{a.clear(),this.nonces.delete(c)}},{peerId:t.remotePeer}).catch(i=>{this.log.error("error from %p verifying addresses - %e",t.remotePeer,i)})}}async askPeerToVerify(t,e,n,o){let s=[...this.dialResults.values()].filter(a=>a.result==null).map(a=>a.multiaddr);if(s.length===0){this.queue.clear();return}this.log.trace("asking %a to verify multiaddrs %s",t.remoteAddr,s);let i=await t.newStream(this.dialRequestProtocol,o);try{let a=er(i).pb(rr);await a.write({dialRequest:{addrs:s.map(c=>c.bytes),nonce:n}},o);for(let c=0;c<s.length;c++){let u=await a.read(o);if(u.dialDataRequest!=null){if(u.dialDataRequest.numBytes>this.maxDialDataBytes){this.log("too many dial data byte requested by %p - %s/%s",t.remotePeer,u.dialDataRequest.numBytes,this.maxDialDataBytes);continue}this.log("sending %d bytes to %p as anti-amplification attack protection",u.dialDataRequest.numBytes,t.remotePeer);let h=new Uint8Array(this.dialDataChunkSize),p=BigInt(this.dialDataChunkSize);for(let w=0n;w<u.dialDataRequest.numBytes;w+=p)await a.write({dialDataResponse:{data:h}},o);u=await a.read(o)}if(u.dialResponse==null){this.log("invalid autonat response from %p - %j",t.remotePeer,u);return}if(u.dialResponse.status!==Qt.ResponseStatus.OK)return;let l=s[u.dialResponse.addrIdx];if(l==null){this.log.trace("peer dialed unknown address");continue}let f=this.dialResults.get(l.toString());if(f==null){this.log.trace("peer reported %a as %s but there is no result object",l,u.dialResponse.status);continue}if(f.networkSegments.includes(e)){this.log.trace("%a results already included network segment %s",l,e);continue}if(f.result!=null){this.log.trace("already resolved result for %a, ignoring response from",l,t.remotePeer);continue}if(f.verifyingPeers.has(t.remotePeer)){this.log.trace("peer %p has already verified %a, ignoring response",t.remotePeer,l);continue}if(f.verifyingPeers.add(t.remotePeer),f.networkSegments.push(e),u.dialResponse.dialStatus===ut.OK){if(this.log.trace("%p dialed %a successfully",t.remotePeer,f.multiaddr),f.success++,f.type!=="observed"){this.confirmAddress(f);continue}}else if(u.dialResponse.dialStatus===ut.E_DIAL_ERROR)this.log.trace("%p could not dial %a",t.remotePeer,f.multiaddr),f.failure++;else if(u.dialResponse.dialStatus===ut.E_DIAL_BACK_ERROR){this.log.trace("%p saw error while dialing %a",t.remotePeer,f.multiaddr);continue}this.log("%a success %d failure %d",f.multiaddr,f.success,f.failure),f.success===Hd&&this.confirmAddress(f),f.failure===$d&&this.unconfirmAddress(f)}}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=ue(t);switch(e.type){case"ip4":return e.host.split(".")[0].padStart(3,"0");case"ip6":return e.host.split(":")[0].padStart(4,"0");default:throw new ft(`Remote address ${t} was not an IPv4 or Ipv6 address`)}}};var Gn=class{components;dialRequestProtocol;dialBackProtocol;timeout;maxInboundStreams;maxOutboundStreams;maxMessageSize;started;log;constructor(t,e){this.components=t,this.log=t.logger.forComponent("libp2p:auto-nat-v2:server"),this.started=!1,this.dialRequestProtocol=e.dialRequestProtocol,this.dialBackProtocol=e.dialBackProtocol,this.timeout=e.timeout??3e4,this.maxInboundStreams=e.maxInboundStreams??2,this.maxOutboundStreams=e.maxOutboundStreams??20,this.maxMessageSize=e.maxMessageSize??8192,this.handleDialRequestStream=this.handleDialRequestStream.bind(this)}async start(){this.started||(await this.components.registrar.handle(this.dialRequestProtocol,this.handleDialRequestStream,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams}),this.started=!0)}async stop(){await this.components.registrar.unhandle(this.dialRequestProtocol),this.started=!1}async handleDialRequestStream(t,e){let n=AbortSignal.timeout(this.timeout);let o=er(t,{maxDataLength:this.maxMessageSize}).pb(rr),s=Rc(e.remoteAddr);if(s==null)throw new _t(`Could not find IP address in connection address "${e.remoteAddr}"`);let{dialRequest:i}=await o.read({signal:n});if(i==null)throw new _t("Did not receive DialRequest message on incoming dial request stream");if(i.addrs.length===0)throw new _t("Did not receive any addresses to dial");for(let a=0;a<i.addrs.length;a++)try{let c=Ec(i.addrs[a]);if(!await this.components.connectionManager.isDialable(c,{signal:n})){await o.write({dialResponse:{addrIdx:a,status:Qt.ResponseStatus.E_DIAL_REFUSED,dialStatus:ut.UNUSED}},{signal:n});continue}let d=Rc(c);if(d==null)throw new _t(`Could not find IP address in requested address "${c}"`);if(Bn(d))throw new _t(`Requested address had private IP "${c}"`);d!==s&&await this.preventAmplificationAttack(o,a,{signal:n});let l=await this.dialClientBack(c,i.nonce,{signal:n});await o.write({dialResponse:{addrIdx:a,status:Qt.ResponseStatus.OK,dialStatus:l}},{signal:n})}catch(c){this.log.error("error handling incoming dialback request - %e",c)}await t.close({signal:n})}async preventAmplificationAttack(t,e,n){let o=Hn(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 _t("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=er(s,{maxDataLength:this.maxMessageSize});if(await i.write({nonce:e},nr,n),(await i.read(fe,n)).status!==fe.DialBackStatus.OK)throw new _t("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 Rc(r){return r.getComponents().filter(t=>t.code===4||t.code===41).map(t=>t.value).pop()}var Zn=class{client;server;constructor(t,e){let n=`/${e.protocolPrefix??js}/${Xs}/${"2"}/${_c}`,o=`/${e.protocolPrefix??js}/${Xs}/${"2"}/${Ac}`;this.client=new $n(t,{...e,dialRequestProtocol:n,dialBackProtocol:o}),this.server=new Gn(t,{...e,dialRequestProtocol:n,dialBackProtocol:o})}[Symbol.toStringTag]="@libp2p/autonat-v2";[Vr]=["@libp2p/autonat"];get[Hr](){return["@libp2p/identify"]}async start(){await ti(this.client,this.server)}async stop(){await ei(this.client,this.server)}};function Gd(r={}){return t=>new Zn(t,r)}return qc(Zd);})();
|
|
3
3
|
/*! Bundled license information:
|
|
4
4
|
|
|
5
5
|
@noble/hashes/esm/utils.js:
|