@helia/block-brokers 5.2.3 → 5.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.min.js CHANGED
@@ -1,5 +1,5 @@
1
1
  (function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.HeliaBlockBrokers = factory()}(typeof self !== 'undefined' ? self : this, function () {
2
- "use strict";var HeliaBlockBrokers=(()=>{var Ju=Object.create;var xn=Object.defineProperty;var tf=Object.getOwnPropertyDescriptor;var ef=Object.getOwnPropertyNames;var rf=Object.getPrototypeOf,nf=Object.prototype.hasOwnProperty;var En=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),It=(r,t)=>{for(var e in t)xn(r,e,{get:t[e],enumerable:!0})},qa=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ef(t))!nf.call(r,o)&&o!==e&&xn(r,o,{get:()=>t[o],enumerable:!(n=tf(t,o))||n.enumerable});return r};var Ka=(r,t,e)=>(e=r!=null?Ju(rf(r)):{},qa(t||!r||!r.__esModule?xn(e,"default",{value:r,enumerable:!0}):e,r)),of=r=>qa(xn({},"__esModule",{value:!0}),r);var Hi=En(wr=>{"use strict";Object.defineProperty(wr,"__esModule",{value:!0});wr.Netmask4Impl=void 0;wr.ip2long=yr;wr.long2ip=Jt;function Jt(r){let t=(r&-16777216)>>>24,e=(r&255<<16)>>>16,n=(r&65280)>>>8,o=r&255;return[t,e,n,o].join(".")}var Fd=48,Ud=97,Md=65;function zd(r){let t=0,e=10,n="9",o=0;r.length>1&&r[o]==="0"&&(r[o+1]==="x"||r[o+1]==="X"?(o+=2,e=16):"0"<=r[o+1]&&r[o+1]<="9"&&(o++,e=8,n="7"));let s=o;for(;o<r.length;){if("0"<=r[o]&&r[o]<=n)t=t*e+(r.charCodeAt(o)-Fd)>>>0;else if(e===16)if("a"<=r[o]&&r[o]<="f")t=t*e+(10+r.charCodeAt(o)-Ud)>>>0;else if("A"<=r[o]&&r[o]<="F")t=t*e+(10+r.charCodeAt(o)-Md)>>>0;else break;else break;if(t>4294967295)throw new Error("too large");o++}if(o===s)throw new Error("empty octet");return[t,o]}function yr(r){let t=[];for(let e=0;e<=3&&r.length!==0;e++){if(e>0){if(r[0]!==".")throw new Error("Invalid IP");r=r.substring(1)}let[n,o]=zd(r);r=r.substring(o),t.push(n)}if(r.length!==0)throw new Error("Invalid IP");switch(t.length){case 1:if(t[0]>4294967295)throw new Error("Invalid IP");return t[0]>>>0;case 2:if(t[0]>255||t[1]>16777215)throw new Error("Invalid IP");return(t[0]<<24|t[1])>>>0;case 3:if(t[0]>255||t[1]>255||t[2]>65535)throw new Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2])>>>0;case 4:if(t[0]>255||t[1]>255||t[2]>255||t[3]>255)throw new Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2]<<8|t[3])>>>0;default:throw new Error("Invalid IP")}}var zi=class r{constructor(t,e){if(typeof t!="string")throw new Error("Missing `net' parameter");let n=e;if(!n){let o=t.split("/",2);t=o[0],n=o[1]}if(n||(n=32),typeof n=="string"&&n.indexOf(".")>-1){try{this.maskLong=yr(n)}catch{throw new Error("Invalid mask: "+n)}this.bitmask=NaN;for(let o=32;o>=0;o--)if(this.maskLong===4294967295<<32-o>>>0){this.bitmask=o;break}}else if(n||n===0)this.bitmask=parseInt(n,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(yr(t)&this.maskLong)>>>0}catch{throw new Error("Invalid net address: "+t)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+n);this.size=Math.pow(2,32-this.bitmask),this.base=Jt(this.netLong),this.mask=Jt(this.maskLong),this.hostmask=Jt(~this.maskLong),this.first=this.bitmask<=30?Jt(this.netLong+1):this.base,this.last=this.bitmask<=30?Jt(this.netLong+this.size-2):Jt(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?Jt(this.netLong+this.size-1):void 0}contains(t){return typeof t=="string"&&(t.indexOf("/")>0||t.split(".").length!==4)&&(t=new r(t)),t instanceof r?this.contains(t.base)&&this.contains(t.broadcast||t.last):(yr(t)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0}next(t=1){return new r(Jt(this.netLong+this.size*t),this.mask)}forEach(t){let e=yr(this.first),n=yr(this.last),o=0;for(;e<=n;)t(Jt(e),e,o),o++,e++}toString(){return this.base+"/"+this.bitmask}};wr.Netmask4Impl=zi});var $l=En(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0});xr.Netmask6Impl=void 0;xr.ip6bigint=qi;xr.bigint2ip6=ze;var Hd=Hi(),$i=(1n<<128n)-1n;function qi(r){let t=r.indexOf("%");t!==-1&&(r=r.substring(0,t));let e=r.lastIndexOf(":");if(e!==-1&&r.indexOf(".",e)!==-1){let n=r.substring(e+1),o=(0,Hd.ip2long)(n),s=r.substring(0,e+1)+"0:0";return Hl(s)&~0xffffffffn|BigInt(o)}return Hl(r)}function Hl(r){let t=r.indexOf("::"),e;if(t!==-1){let o=r.substring(0,t),s=r.substring(t+2),i=o===""?[]:o.split(":"),a=s===""?[]:s.split(":"),c=8-i.length-a.length;if(c<0)throw new Error("Invalid IPv6: too many groups");e=[...i,...Array(c).fill("0"),...a]}else e=r.split(":");if(e.length!==8)throw new Error("Invalid IPv6: expected 8 groups, got "+e.length);let n=0n;for(let o=0;o<8;o++){let s=e[o];if(s.length===0||s.length>4)throw new Error('Invalid IPv6: bad group "'+s+'"');let i=parseInt(s,16);if(isNaN(i)||i<0||i>65535)throw new Error('Invalid IPv6: bad group "'+s+'"');n=n<<16n|BigInt(i)}return n}function ze(r){if(r<0n||r>$i)throw new Error("Invalid IPv6 address value");let t=[];for(let i=0;i<8;i++)t.unshift(Number(r&0xffffn)),r>>=16n;let e=-1,n=0,o=-1,s=0;for(let i=0;i<8;i++)t[i]===0?o===-1?(o=i,s=1):s++:(s>n&&s>=2&&(e=o,n=s),o=-1,s=0);if(s>n&&s>=2&&(e=o,n=s),e!==-1&&e+n===8&&e>0)return t.slice(0,e).map(a=>a.toString(16)).join(":")+"::";if(e===0)return"::"+t.slice(n).map(a=>a.toString(16)).join(":");if(e>0){let i=t.slice(0,e).map(c=>c.toString(16)),a=t.slice(e+n).map(c=>c.toString(16));return i.join(":")+"::"+a.join(":")}else return t.map(i=>i.toString(16)).join(":")}var Ki=class r{constructor(t,e){if(typeof t!="string")throw new Error("Missing `net' parameter");let n=e;if(n==null){let o=t.indexOf("/");o!==-1?(n=parseInt(t.substring(o+1),10),t=t.substring(0,o)):n=128}if(isNaN(n)||n<0||n>128)throw new Error("Invalid mask for IPv6: "+n);this.bitmask=n,this.bitmask===0?this.maskBigint=0n:this.maskBigint=$i>>BigInt(128-this.bitmask)<<BigInt(128-this.bitmask);try{this.netBigint=qi(t)&this.maskBigint}catch{throw new Error("Invalid IPv6 net address: "+t)}this.size=Number(1n<<BigInt(128-this.bitmask)),this.base=ze(this.netBigint),this.mask=ze(this.maskBigint),this.hostmask=ze(~this.maskBigint&$i),this.first=this.base,this.last=ze(this.netBigint+(1n<<BigInt(128-this.bitmask))-1n),this.broadcast=void 0}contains(t){return typeof t=="string"&&t.indexOf("/")>0&&(t=new r(t)),t instanceof r?this.contains(t.base)&&this.contains(t.last):(qi(t)&this.maskBigint)===this.netBigint}next(t=1){let e=1n<<BigInt(128-this.bitmask);return new r(ze(this.netBigint+e*BigInt(t)),this.bitmask)}forEach(t){let e=this.netBigint,n=1n<<BigInt(128-this.bitmask),o=this.netBigint+n-1n,s=0;for(;e<=o;)t(ze(e),Number(e),s),s++,e++}toString(){return this.base+"/"+this.bitmask}};xr.Netmask6Impl=Ki});var ql=En(Se=>{"use strict";Object.defineProperty(Se,"__esModule",{value:!0});Se.long2ip=Se.ip2long=Se.Netmask=void 0;var mo=Hi();Object.defineProperty(Se,"ip2long",{enumerable:!0,get:function(){return mo.ip2long}});Object.defineProperty(Se,"long2ip",{enumerable:!0,get:function(){return mo.long2ip}});var $d=$l(),Vi=class r{constructor(t,e){if(typeof t!="string")throw new Error("Missing `net' parameter");(t.indexOf("/")!==-1?t.substring(0,t.indexOf("/")):t).indexOf(":")!==-1?this._impl=new $d.Netmask6Impl(t,e):this._impl=new mo.Netmask4Impl(t,e),this.base=this._impl.base,this.mask=this._impl.mask,this.hostmask=this._impl.hostmask,this.bitmask=this._impl.bitmask,this.size=this._impl.size,this.first=this._impl.first,this.last=this._impl.last,this.broadcast=this._impl.broadcast,this._impl instanceof mo.Netmask4Impl?(this.maskLong=this._impl.maskLong,this.netLong=this._impl.netLong):(this.maskLong=0,this.netLong=0)}contains(t){return typeof t=="string"&&(t.indexOf("/")>0?t=new r(t):t.indexOf(":")===-1&&t.split(".").length!==4&&(t=new r(t))),t instanceof r?this.contains(t.base)&&this.contains(t.broadcast||t.last):this._impl.contains(t)}next(t=1){let e=this._impl.next(t);return new r(e.base,e.bitmask)}forEach(t){this._impl.forEach(t)}toString(){return this._impl.toString()}};Se.Netmask=Vi});var vu=En((V2,Eu)=>{Eu.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var t=0,e=Object.create(null),n=Object.create(null);function o(s,i){e[s]=i,t++,t>=r&&(t=0,n=e,e=Object.create(null))}return{has:function(s){return e[s]!==void 0||n[s]!==void 0},remove:function(s){e[s]!==void 0&&(e[s]=void 0),n[s]!==void 0&&(n[s]=void 0)},get:function(s){var i=e[s];if(i!==void 0)return i;if((i=n[s])!==void 0)return o(s,i),i},set:function(s,i){e[s]!==void 0?e[s]=i:o(s,i)},clear:function(){e=Object.create(null),n=Object.create(null)}}}});var Cm={};It(Cm,{bitswap:()=>Iu,trustlessGateway:()=>Qu});var Pt=class extends Error{static name="AbortError";constructor(t="The operation was aborted"){super(t),this.name="AbortError"}};var Tt=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},vn=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}};var _n=class extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}},Sn=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}},An=class extends Error{static name="UnsupportedProtocolError";constructor(t="Unsupported protocol error"){super(t),this.name="UnsupportedProtocolError"}};var In=class extends Error{static name="TimeoutError";constructor(t="Timed out"){super(t),this.name="TimeoutError"}},Tn=class extends Error{static name="NotStartedError";constructor(t="Not started"){super(t),this.name="NotStartedError"}};var Br=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var kn=Symbol.for("@libp2p/peer-id");function Xe(r){return!!r?.[kn]}function sf(r){return typeof r?.handleEvent=="function"}function af(r){return(r!==!0&&r!==!1&&r?.once)??!1}var Vt=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){let o=af(n);super.addEventListener(t,i=>{if(o){let a=this.#t.get(i.type);a!=null&&(a=a.filter(({callback:c})=>c!==e),this.#t.set(i.type,a))}sf(e)?e.handleEvent(i):e(i)},n);let s=this.#t.get(t);s==null&&(s=[],this.#t.set(t,s)),s.push({callback:e,once:o})}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))}safeDispatchEvent(t,e={}){return this.dispatchEvent(new CustomEvent(t,e))}};function Va(r){let t=new globalThis.AbortController;function e(){let s=r.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();t.abort(s);for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",e)}for(let s of r){if(s?.aborted===!0){e();break}s?.addEventListener!=null&&s.addEventListener("abort",e)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",e)}let o=t.signal;return o.clear=n,o}var V=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var Cr=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},Dn=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var Wa={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new Dn("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 Ln=Wa;var ps={};It(ps,{base58btc:()=>it,base58flickr:()=>pf});var Km=new Uint8Array(0);function ja(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 te(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 Ga(r){return new TextEncoder().encode(r)}function Za(r){return new TextDecoder().decode(r)}function cf(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),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function f(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var E=0,p=0,b=0,v=g.length;b!==v&&g[b]===0;)b++,E++;for(var S=(v-b)*u+1>>>0,B=new Uint8Array(S);b!==v;){for(var D=g[b],R=0,C=S-1;(D!==0||R<p)&&C!==-1;C--,R++)D+=256*B[C]>>>0,B[C]=D%a>>>0,D=D/a>>>0;if(D!==0)throw new Error("Non-zero carry");p=R,b++}for(var T=S-p;T!==S&&B[T]===0;)T++;for(var N=c.repeat(E);T<S;++T)N+=r.charAt(B[T]);return N}function h(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var E=0;if(g[E]!==" "){for(var p=0,b=0;g[E]===c;)p++,E++;for(var v=(g.length-E)*l+1>>>0,S=new Uint8Array(v);g[E];){var B=e[g.charCodeAt(E)];if(B===255)return;for(var D=0,R=v-1;(B!==0||D<b)&&R!==-1;R--,D++)B+=a*S[R]>>>0,S[R]=B%256>>>0,B=B/256>>>0;if(B!==0)throw new Error("Non-zero carry");b=D,E++}if(g[E]!==" "){for(var C=v-b;C!==v&&S[C]===0;)C++;for(var T=new Uint8Array(p+(v-C)),N=p;C!==v;)T[N++]=S[C++];return T}}}function d(g){var E=h(g);if(E)return E;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:h,decode:d}}var lf=cf,uf=lf,Xa=uf;var us=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")}},fs=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 Qa(this,t)}},hs=class{decoders;constructor(t){this.decoders=t}or(t){return Qa(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 Qa(r,t){return new hs({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var ds=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 us(t,e,n),this.decoder=new fs(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Qe({name:r,prefix:t,encode:e,decode:n}){return new ds(r,t,e,n)}function fe({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=Xa(e,r);return Qe({prefix:t,name:r,encode:n,decode:s=>te(o(s))})}function ff(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 l=0;l<o;++l){let u=t[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<e|u,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 hf(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 df(r){let t={};for(let e=0;e<r.length;++e)t[r[e]]=e;return t}function rt({name:r,prefix:t,bitsPerChar:e,alphabet:n}){let o=df(n);return Qe({prefix:t,name:r,encode(s){return hf(s,n,e)},decode(s){return ff(s,o,e,r)}})}var it=fe({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),pf=fe({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ms={};It(ms,{base32:()=>he,base32hex:()=>yf,base32hexpad:()=>xf,base32hexpadupper:()=>Ef,base32hexupper:()=>wf,base32pad:()=>gf,base32padupper:()=>bf,base32upper:()=>mf,base32z:()=>vf});var he=rt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),mf=rt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),gf=rt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),bf=rt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),yf=rt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),wf=rt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),xf=rt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Ef=rt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),vf=rt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var gs={};It(gs,{base36:()=>Pr,base36upper:()=>_f});var Pr=fe({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),_f=fe({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Sf=ec,Ja=128,Af=127,If=~Af,Tf=Math.pow(2,31);function ec(r,t,e){t=t||[],e=e||0;for(var n=e;r>=Tf;)t[e++]=r&255|Ja,r/=128;for(;r&If;)t[e++]=r&255|Ja,r>>>=7;return t[e]=r|0,ec.bytes=e-n+1,t}var kf=bs,Df=128,tc=127;function bs(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw bs.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&tc)<<o:(i&tc)*Math.pow(2,o),o+=7}while(i>=Df);return bs.bytes=s-n,e}var Lf=Math.pow(2,7),Bf=Math.pow(2,14),Cf=Math.pow(2,21),Pf=Math.pow(2,28),Of=Math.pow(2,35),Rf=Math.pow(2,42),Nf=Math.pow(2,49),Ff=Math.pow(2,56),Uf=Math.pow(2,63),Mf=function(r){return r<Lf?1:r<Bf?2:r<Cf?3:r<Pf?4:r<Of?5:r<Rf?6:r<Nf?7:r<Ff?8:r<Uf?9:10},zf={encode:Sf,decode:kf,encodingLength:Mf},Hf=zf,Or=Hf;function Rr(r,t=0){return[Or.decode(r,t),Or.decode.bytes]}function Je(r,t,e=0){return Or.encode(r,t,e),t}function tr(r){return Or.encodingLength(r)}function rr(r,t){let e=t.byteLength,n=tr(r),o=n+tr(e),s=new Uint8Array(o+e);return Je(r,s,0),Je(e,s,n),s.set(t,o),new er(r,e,t,s)}function Cn(r){let t=te(r),[e,n]=Rr(t),[o,s]=Rr(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new er(e,o,i,t)}function rc(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&ja(r.bytes,e.bytes)}}var er=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};function nc(r,t){let{bytes:e,version:n}=r;return n===0?qf(e,ys(r),t??it.encoder):Kf(e,ys(r),t??he.encoder)}var oc=new WeakMap;function ys(r){let t=oc.get(r);if(t==null){let e=new Map;return oc.set(r,e),e}return t}var et=class r{code;version;multihash;bytes;"/";constructor(t,e,n,o){this.code=e,this.version=t,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:t,multihash:e}=this;if(t!==Nr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==Vf)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=rr(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&&rc(t.multihash,n.multihash)}toString(t){return nc(this,t)}toJSON(){return{"/":nc(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??sc(n,o,s.bytes))}else if(e[Wf]===!0){let{version:n,multihash:o,code:s}=e,i=Cn(o);return r.create(n,s,i)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==Nr)throw new Error(`Version 0 CID must use dag-pb (code: ${Nr}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=sc(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,Nr,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,o=te(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 er(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[f,h]=Rr(t.subarray(e));return e+=h,f},o=n(),s=Nr;if(o===18?(o=0,e=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=e,a=n(),c=n(),l=e+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(t,e){let[n,o]=$f(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 ys(s).set(n,t),s}};function $f(r,t){switch(r[0]){case"Q":{let e=t??it;return[it.prefix,e.decode(`${it.prefix}${r}`)]}case it.prefix:{let e=t??it;return[it.prefix,e.decode(r)]}case he.prefix:{let e=t??he;return[he.prefix,e.decode(r)]}case Pr.prefix:{let e=t??Pr;return[Pr.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 qf(r,t,e){let{prefix:n}=e;if(n!==it.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 Kf(r,t,e){let{prefix:n}=e,o=t.get(n);if(o==null){let s=e.encode(r);return t.set(n,s),s}else return o}var Nr=112,Vf=18;function sc(r,t,e){let n=tr(r),o=n+tr(t),s=new Uint8Array(o+e.byteLength);return Je(r,s,0),Je(t,s,n),s.set(e,o),s}var Wf=Symbol.for("@ipld/js-cid/CID");var ws={};It(ws,{identity:()=>kt});var ic=0,jf="identity",ac=te;function Gf(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 rr(ic,ac(r))}var kt={code:ic,name:jf,encode:ac,digest:Gf};function at(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 wt(r=0){return new Uint8Array(r)}function xt(r=0){return new Uint8Array(r)}function Ct(r,t){t==null&&(t=r.reduce((o,s)=>o+s.length,0));let e=xt(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}var lc=Symbol.for("@achingbrain/uint8arraylist");function cc(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 Pn(r){return!!r?.[lc]}var ut=class r{bufs;length;[lc]=!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(Pn(n)){e+=n.byteLength;for(let o of n.bufs)this.bufs.push(o)}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(Pn(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=cc(this.bufs,t);return e.buf[e.index]}set(t,e){let n=cc(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(Pn(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 Ct(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:Ct(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 l=t>=a&&t<c,u=e>a&&e<=c;if(l&&u){if(t===a&&e===c){n.push(i);break}let f=t-a;n.push(i.subarray(f,f+(e-t)));break}if(l){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(u){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(!Pn(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 f=0;f<s;f++)i[f]=-1;for(let f=0;f<o;f++)i[n[f]]=f;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let f=e;f<=c;f+=u){u=0;for(let h=l;h>=0;h--){let d=this.get(f+h);if(n[h]!==d){u=Math.max(1,h-a[d]);break}}if(u===0)return f}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=xt(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=wt(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=wt(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=wt(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=xt(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=wt(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=wt(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=wt(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=wt(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=wt(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(!at(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 xs={};It(xs,{base10:()=>Zf});var Zf=fe({prefix:"9",name:"base10",alphabet:"0123456789"});var Es={};It(Es,{base16:()=>Yf,base16upper:()=>Xf});var Yf=rt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Xf=rt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var vs={};It(vs,{base2:()=>Qf});var Qf=rt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var _s={};It(_s,{base256emoji:()=>nh});var uc=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}"),Jf=uc.reduce((r,t,e)=>(r[e]=t,r),[]),th=uc.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function eh(r){return r.reduce((t,e)=>(t+=Jf[e],t),"")}function rh(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=th[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var nh=Qe({prefix:"\u{1F680}",name:"base256emoji",encode:eh,decode:rh});var As={};It(As,{base64:()=>ee,base64pad:()=>oh,base64url:()=>Ss,base64urlpad:()=>sh});var ee=rt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),oh=rt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ss=rt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),sh=rt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Is={};It(Is,{base8:()=>ih});var ih=rt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Ts={};It(Ts,{identity:()=>ah});var ah=Qe({prefix:"\0",name:"identity",encode:r=>Za(r),decode:r=>Ga(r)});var T0=new TextEncoder,k0=new TextDecoder;var Ls={};It(Ls,{sha256:()=>de,sha512:()=>fh});var uh=20;function Ds({name:r,code:t,encode:e,minDigestLength:n,maxDigestLength:o}){return new ks(r,t,e,n,o)}var ks=class{name;code;encode;minDigestLength;maxDigestLength;constructor(t,e,n,o,s){this.name=t,this.code=e,this.encode=n,this.minDigestLength=o??uh,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?fc(n,this.code,e?.truncate):n.then(o=>fc(o,this.code,e?.truncate))}else throw Error("Unknown type, must be binary type")}};function fc(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 rr(t,r)}function dc(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var de=Ds({name:"sha2-256",code:18,encode:dc("SHA-256")}),fh=Ds({name:"sha2-512",code:19,encode:dc("SHA-512")});var Fr={...Ts,...vs,...Is,...xs,...Es,...ms,...gs,...ps,...As,..._s},z0={...Ls,...ws};function mc(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var pc=mc("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Bs=mc("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=xt(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),hh={utf8:pc,"utf-8":pc,hex:Fr.base16,latin1:Bs,ascii:Bs,binary:Bs,...Fr},On=hh;function Z(r,t="utf8"){let e=On[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function W(r,t="utf8"){let e=On[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var dh=parseInt("11111",2),Cs=parseInt("10000000",2),ph=parseInt("01111111",2),gc={0:Ur,1:Ur,2:mh,3:yh,4:wh,5:bh,6:gh,16:Ur,22:Ur,48:Ur};function Ps(r,t={offset:0}){let e=r[t.offset]&dh;if(t.offset++,gc[e]!=null)return gc[e](r,t);throw new Error("No decoder for tag "+e)}function Mr(r,t){let e=0;if((r[t.offset]&Cs)===Cs){let n=r[t.offset]&ph,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 Ur(r,t){Mr(r,t);let e=[];for(;!(t.offset>=r.byteLength);){let n=Ps(r,t);if(n===null)break;e.push(n)}return e}function mh(r,t){let e=Mr(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 gh(r,t){let e=Mr(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 l=r[t.offset];if(t.offset++,c.push(l&127),l<128){c.reverse();let u=0;for(let f=0;f<c.length;f++)u+=c[f]<<f*7;a+=`.${u}`,c=[]}}return a}function bh(r,t){return t.offset++,null}function yh(r,t){let e=Mr(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 wh(r,t){let e=Mr(r,t),n=r.subarray(t.offset,t.offset+e);return t.offset+=e,n}function xh(r){let t=r.toString(16);t.length%2===1&&(t="0"+t);let e=new ut;for(let n=0;n<t.length;n+=2)e.append(Uint8Array.from([parseInt(`${t[n]}${t[n+1]}`,16)]));return e}function Os(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let t=xh(r.byteLength);return new ut(Uint8Array.from([t.byteLength|Cs]),t)}function bc(r){let t=new ut,e=128;return(r.subarray()[0]&e)===e&&t.append(Uint8Array.from([0])),t.append(r),new ut(Uint8Array.from([2]),Os(t),t)}function yc(r){let t=Uint8Array.from([0]),e=new ut(t,r);return new ut(Uint8Array.from([3]),Os(e),e)}function Rn(r,t=48){let e=new ut;for(let n of r)e.append(n);return new ut(Uint8Array.from([t]),Os(e),e)}async function wc(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 Eh=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),vh=Uint8Array.from([6,5,43,129,4,0,34]),_h=Uint8Array.from([6,5,43,129,4,0,35]),Sh={ext:!0,kty:"EC",crv:"P-256"},Ah={ext:!0,kty:"EC",crv:"P-384"},Ih={ext:!0,kty:"EC",crv:"P-521"},Rs=32,Ns=48,Fs=66;function xc(r){let t=Ps(r);return Ec(t)}function Ec(r){let t=r[1][1][0],e=1,n,o;if(t.byteLength===Rs*2+1)return n=W(t.subarray(e,e+Rs),"base64url"),o=W(t.subarray(e+Rs),"base64url"),new nr({...Sh,key_ops:["verify"],x:n,y:o});if(t.byteLength===Ns*2+1)return n=W(t.subarray(e,e+Ns),"base64url"),o=W(t.subarray(e+Ns),"base64url"),new nr({...Ah,key_ops:["verify"],x:n,y:o});if(t.byteLength===Fs*2+1)return n=W(t.subarray(e,e+Fs),"base64url"),o=W(t.subarray(e+Fs),"base64url"),new nr({...Ih,key_ops:["verify"],x:n,y:o});throw new Tt(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function vc(r){return Rn([bc(Uint8Array.from([1])),Rn([Th(r.crv)],160),Rn([yc(new ut(Uint8Array.from([4]),Z(r.x??"","base64url"),Z(r.y??"","base64url")))],161)]).subarray()}function Th(r){if(r==="P-256")return Eh;if(r==="P-384")return vh;if(r==="P-521")return _h;throw new Tt(`Invalid curve ${r}`)}var nr=class{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=vc(this.jwk)),this._raw}toMultihash(){return kt.digest(or(this))}toCID(){return et.createV1(114,this.toMultihash())}toString(){return it.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:at(this.raw,t.raw)}async verify(t,e,n){return wc(this.jwk,e,t,n)}};function Us(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}function pe(r,t=""){if(typeof r!="number"){let e=t&&`"${t}" `;throw new TypeError(`${e}expected number, got ${typeof r}`)}if(!Number.isSafeInteger(r)||r<0){let e=t&&`"${t}" `;throw new RangeError(`${e}expected integer >= 0, got ${r}`)}}function Dt(r,t,e=""){let n=Us(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}`,l=i+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(l):new TypeError(l)}return r}function Nn(r){if(typeof r!="function"||typeof r.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(pe(r.outputLen),pe(r.blockLen),r.outputLen<1)throw new Error('"outputLen" must be >= 1');if(r.blockLen<1)throw new Error('"blockLen" must be >= 1')}function sr(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 Fn(r,t){Dt(r,void 0,"digestInto() output");let e=t.outputLen;if(r.length<e)throw new RangeError('"digestInto() output" expected to be of length >='+e)}function ne(...r){for(let t=0;t<r.length;t++)r[t].fill(0)}function Un(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Ot(r,t){return r<<32-t|r>>>t}var Sc=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",kh=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function Mn(r){if(Dt(r),Sc)return r.toHex();let t="";for(let e=0;e<r.length;e++)t+=kh[r[e]];return t}var re={_0:48,_9:57,A:65,F:70,a:97,f:102};function _c(r){if(r>=re._0&&r<=re._9)return r-re._0;if(r>=re.A&&r<=re.F)return r-(re.A-10);if(r>=re.a&&r<=re.f)return r-(re.a-10)}function zr(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);if(Sc)try{return Uint8Array.fromHex(r)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}let t=r.length,e=t/2;if(t%2)throw new RangeError("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=_c(r.charCodeAt(s)),a=_c(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function Ms(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];Dt(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let s=r[n];e.set(s,o),o+=s.length}return e}function zs(r,t={}){let e=(o,s)=>r(s).update(o).digest(),n=r(void 0);return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.canXOF=n.canXOF,e.create=o=>r(o),Object.assign(e,t),Object.freeze(e)}function Ac(r=32){pe(r,"bytesLength");let t=typeof globalThis=="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(r>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${r}`);return t.getRandomValues(new Uint8Array(r))}var Hs=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function Ic(r,t,e){return r&t^~r&e}function Tc(r,t,e){return r&t^r&e^t&e}var Hr=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(t,e,n,o){this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(t),this.view=Un(this.buffer)}update(t){sr(this),Dt(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=Un(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){sr(this),Fn(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;e[i++]=128,ne(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let f=i;f<o;f++)e[f]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=Un(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<l;f++)a.setUint32(4*f,u[f],s)}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){t||=new this.constructor,t.set(...this.get());let{blockLen:e,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return t.destroyed=i,t.finished=s,t.length=o,t.pos=a,o%e&&t.buffer.set(n),t}clone(){return this._cloneInto()}},oe=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var gt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var zn=BigInt(4294967295),kc=BigInt(32);function Dh(r,t=!1){return t?{h:Number(r&zn),l:Number(r>>kc&zn)}:{h:Number(r>>kc&zn)|0,l:Number(r&zn)|0}}function Dc(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}=Dh(r[s],t);[n[s],o[s]]=[i,a]}return[n,o]}var $s=(r,t,e)=>r>>>e,qs=(r,t,e)=>r<<32-e|t>>>e,ke=(r,t,e)=>r>>>e|t<<32-e,De=(r,t,e)=>r<<32-e|t>>>e,$r=(r,t,e)=>r<<64-e|t>>>e-32,qr=(r,t,e)=>r>>>e-32|t<<64-e;function Wt(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var Lc=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),Bc=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,Cc=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),Pc=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,Oc=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),Rc=(r,t,e,n,o,s)=>t+e+n+o+s+(r/2**32|0)|0;var Bh=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]),me=new Uint32Array(64),Ks=class extends Hr{constructor(t){super(64,t,8,!1)}get(){let{A:t,B:e,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[t,e,n,o,s,i,a,c]}set(t,e,n,o,s,i,a,c){this.A=t|0,this.B=e|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,e){for(let f=0;f<16;f++,e+=4)me[f]=t.getUint32(e,!1);for(let f=16;f<64;f++){let h=me[f-15],d=me[f-2],g=Ot(h,7)^Ot(h,18)^h>>>3,E=Ot(d,17)^Ot(d,19)^d>>>10;me[f]=E+me[f-7]+g+me[f-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){let h=Ot(a,6)^Ot(a,11)^Ot(a,25),d=u+h+Ic(a,c,l)+Bh[f]+me[f]|0,E=(Ot(n,2)^Ot(n,13)^Ot(n,22))+Tc(n,o,s)|0;u=l,l=c,c=a,a=i+d|0,i=s,s=o,o=n,n=d+E|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,o,s,i,a,c,l,u)}roundClean(){ne(me)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),ne(this.buffer)}},Vs=class extends Ks{A=oe[0]|0;B=oe[1]|0;C=oe[2]|0;D=oe[3]|0;E=oe[4]|0;F=oe[5]|0;G=oe[6]|0;H=oe[7]|0;constructor(){super(32)}};var Nc=Dc(["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))),Ch=Nc[0],Ph=Nc[1],ge=new Uint32Array(80),be=new Uint32Array(80),Ws=class extends Hr{constructor(t){super(128,t,16,!1)}get(){let{Ah:t,Al:e,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:l,El:u,Fh:f,Fl:h,Gh:d,Gl:g,Hh:E,Hl:p}=this;return[t,e,n,o,s,i,a,c,l,u,f,h,d,g,E,p]}set(t,e,n,o,s,i,a,c,l,u,f,h,d,g,E,p){this.Ah=t|0,this.Al=e|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=f|0,this.Fl=h|0,this.Gh=d|0,this.Gl=g|0,this.Hh=E|0,this.Hl=p|0}process(t,e){for(let S=0;S<16;S++,e+=4)ge[S]=t.getUint32(e),be[S]=t.getUint32(e+=4);for(let S=16;S<80;S++){let B=ge[S-15]|0,D=be[S-15]|0,R=ke(B,D,1)^ke(B,D,8)^$s(B,D,7),C=De(B,D,1)^De(B,D,8)^qs(B,D,7),T=ge[S-2]|0,N=be[S-2]|0,j=ke(T,N,19)^$r(T,N,61)^$s(T,N,6),F=De(T,N,19)^qr(T,N,61)^qs(T,N,6),m=Cc(C,F,be[S-7],be[S-16]),y=Pc(m,R,j,ge[S-7],ge[S-16]);ge[S]=y|0,be[S]=m|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:f,El:h,Fh:d,Fl:g,Gh:E,Gl:p,Hh:b,Hl:v}=this;for(let S=0;S<80;S++){let B=ke(f,h,14)^ke(f,h,18)^$r(f,h,41),D=De(f,h,14)^De(f,h,18)^qr(f,h,41),R=f&d^~f&E,C=h&g^~h&p,T=Oc(v,D,C,Ph[S],be[S]),N=Rc(T,b,B,R,Ch[S],ge[S]),j=T|0,F=ke(n,o,28)^$r(n,o,34)^$r(n,o,39),m=De(n,o,28)^qr(n,o,34)^qr(n,o,39),y=n&s^n&a^s&a,_=o&i^o&c^i&c;b=E|0,v=p|0,E=d|0,p=g|0,d=f|0,g=h|0,{h:f,l:h}=Wt(l|0,u|0,N|0,j|0),l=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let x=Lc(j,m,_);n=Bc(x,N,F,y),o=x|0}({h:n,l:o}=Wt(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=Wt(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=Wt(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=Wt(this.Dh|0,this.Dl|0,l|0,u|0),{h:f,l:h}=Wt(this.Eh|0,this.El|0,f|0,h|0),{h:d,l:g}=Wt(this.Fh|0,this.Fl|0,d|0,g|0),{h:E,l:p}=Wt(this.Gh|0,this.Gl|0,E|0,p|0),{h:b,l:v}=Wt(this.Hh|0,this.Hl|0,b|0,v|0),this.set(n,o,s,i,a,c,l,u,f,h,d,g,E,p,b,v)}roundClean(){ne(ge,be)}destroy(){this.destroyed=!0,ne(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},js=class extends Ws{Ah=gt[0]|0;Al=gt[1]|0;Bh=gt[2]|0;Bl=gt[3]|0;Ch=gt[4]|0;Cl=gt[5]|0;Dh=gt[6]|0;Dl=gt[7]|0;Eh=gt[8]|0;El=gt[9]|0;Fh=gt[10]|0;Fl=gt[11]|0;Gh=gt[12]|0;Gl=gt[13]|0;Hh=gt[14]|0;Hl=gt[15]|0;constructor(){super(64)}};var Fc=zs(()=>new Vs,Hs(1));var Hn=zs(()=>new js,Hs(3));var H=(r,t,e)=>Dt(r,t,e),Zs=pe,ir=Mn,ft=(...r)=>Ms(...r),ar=r=>zr(r),Le=Us,Kr=r=>Ac(r),qn=BigInt(0),Gs=BigInt(1);function Rt(r,t=""){if(typeof r!="boolean"){let e=t&&`"${t}" `;throw new TypeError(e+"expected boolean, got type="+typeof r)}return r}function Kn(r){if(typeof r=="bigint"){if(!$n(r))throw new RangeError("positive bigint expected, got "+r)}else Zs(r);return r}function Nt(r,t=""){if(typeof r!="number"){let e=t&&`"${t}" `;throw new TypeError(e+"expected number, got type="+typeof r)}if(!Number.isSafeInteger(r)){let e=t&&`"${t}" `;throw new RangeError(e+"expected safe integer, got "+r)}}function Vr(r){let t=Kn(r).toString(16);return t.length&1?"0"+t:t}function Uc(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);return r===""?qn:BigInt("0x"+r)}function Be(r){return Uc(Mn(r))}function jt(r){return Uc(Mn(Wr(Dt(r)).reverse()))}function Vn(r,t){if(pe(t),t===0)throw new RangeError("zero length");r=Kn(r);let e=r.toString(16);if(e.length>t*2)throw new RangeError("number too large");return zr(e.padStart(t*2,"0"))}function Ys(r,t){return Vn(r,t).reverse()}function Mc(r,t){if(r=H(r),t=H(t),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 Wr(r){return Uint8Array.from(H(r))}function Wn(r){if(typeof r!="string")throw new TypeError("ascii string expected, got "+typeof r);return Uint8Array.from(r,(t,e)=>{let n=t.charCodeAt(0);if(t.length!==1||n>127)throw new RangeError(`string contains non-ASCII character "${r[e]}" with code ${n} at position ${e}`);return n})}var $n=r=>typeof r=="bigint"&&qn<=r;function Oh(r,t,e){return $n(r)&&$n(t)&&$n(e)&&t<=r&&r<e}function cr(r,t,e,n){if(!Oh(t,e,n))throw new RangeError("expected valid "+r+": "+e+" <= n < "+n+", got "+t)}function lr(r){if(r<qn)throw new Error("expected non-negative bigint, got "+r);let t;for(t=0;r>qn;r>>=Gs,t+=1);return t}var jr=r=>(Gs<<BigInt(r))-Gs;function zc(r,t,e){if(pe(r,"hashLen"),pe(t,"qByteLen"),typeof e!="function")throw new TypeError("hmacFn must be a function");let n=p=>new Uint8Array(p),o=Uint8Array.of(),s=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(r),l=n(r),u=0,f=()=>{c.fill(1),l.fill(0),u=0},h=(...p)=>e(l,ft(c,...p)),d=(p=o)=>{l=h(s,p),c=h(),p.length!==0&&(l=h(i,p),c=h())},g=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let p=0,b=[];for(;p<t;){c=h();let v=c.slice();b.push(v),p+=c.length}return ft(...b)};return(p,b)=>{f(),d(p);let v;for(;(v=b(g()))===void 0;)d();return f(),v}}function Ft(r,t={},e={}){if(Object.prototype.toString.call(r)!=="[object Object]")throw new TypeError("expected valid options object");function n(s,i,a){if(!a&&i!=="function"&&!Object.hasOwn(r,s))throw new TypeError(`param "${s}" is invalid: expected own property`);let c=r[s];if(a&&c===void 0)return;let l=typeof c;if(l!==i||c===null)throw new TypeError(`param "${s}" is invalid: expected ${i}, got ${l}`)}let o=(s,i)=>Object.entries(s).forEach(([a,c])=>n(a,c,i));o(t,!1),o(e,!0)}var Xs=()=>{throw new Error("not implemented")};var bt=BigInt(0),nt=BigInt(1),Ce=BigInt(2),Kc=BigInt(3),Vc=BigInt(4),Wc=BigInt(5),Rh=BigInt(7),jc=BigInt(8),Nh=BigInt(9),Gc=BigInt(16);function st(r,t){if(t<=bt)throw new Error("mod: expected positive modulus, got "+t);let e=r%t;return e>=bt?e:t+e}function Q(r,t,e){if(t<bt)throw new Error("pow2: expected non-negative exponent, got "+t);let n=r;for(;t-- >bt;)n*=n,n%=e;return n}function Hc(r,t){if(r===bt)throw new Error("invert: expected non-zero number");if(t<=bt)throw new Error("invert: expected positive modulus, got "+t);let e=st(r,t),n=t,o=bt,s=nt,i=nt,a=bt;for(;e!==bt;){let l=n/e,u=n-e*l,f=o-i*l,h=s-a*l;n=e,e=u,o=i,s=a,i=f,a=h}if(n!==nt)throw new Error("invert: does not exist");return st(o,t)}function Qs(r,t,e){let n=r;if(!n.eql(n.sqr(t),e))throw new Error("Cannot find square root")}function Zc(r,t){let e=r,n=(e.ORDER+nt)/Vc,o=e.pow(t,n);return Qs(e,o,t),o}function Fh(r,t){let e=r,n=(e.ORDER-Wc)/jc,o=e.mul(t,Ce),s=e.pow(o,n),i=e.mul(t,s),a=e.mul(e.mul(i,Ce),s),c=e.mul(i,e.sub(a,e.ONE));return Qs(e,c,t),c}function Uh(r){let t=ur(r),e=Yc(r),n=e(t,t.neg(t.ONE)),o=e(t,n),s=e(t,t.neg(n)),i=(r+Rh)/Gc;return((a,c)=>{let l=a,u=l.pow(c,i),f=l.mul(u,n),h=l.mul(u,o),d=l.mul(u,s),g=l.eql(l.sqr(f),c),E=l.eql(l.sqr(h),c);u=l.cmov(u,f,g),f=l.cmov(d,h,E);let p=l.eql(l.sqr(f),c),b=l.cmov(u,f,p);return Qs(l,b,c),b})}function Yc(r){if(r<Kc)throw new Error("sqrt is not defined for small field");let t=r-nt,e=0;for(;t%Ce===bt;)t/=Ce,e++;let n=Ce,o=ur(r);for(;$c(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(e===1)return Zc;let s=o.pow(n,t),i=(t+nt)/Ce;return function(c,l){let u=c;if(u.is0(l))return l;if($c(u,l)!==1)throw new Error("Cannot find square root");let f=e,h=u.mul(u.ONE,s),d=u.pow(l,t),g=u.pow(l,i);for(;!u.eql(d,u.ONE);){if(u.is0(d))return u.ZERO;let E=1,p=u.sqr(d);for(;!u.eql(p,u.ONE);)if(E++,p=u.sqr(p),E===f)throw new Error("Cannot find square root");let b=nt<<BigInt(f-E-1),v=u.pow(h,b);f=E,h=u.sqr(v),d=u.mul(d,h),g=u.mul(g,v)}return g}}function Mh(r){return r%Vc===Kc?Zc:r%jc===Wc?Fh:r%Gc===Nh?Uh(r):Yc(r)}var se=(r,t)=>(st(r,t)&nt)===nt,zh=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Js(r){let t={ORDER:"bigint",BYTES:"number",BITS:"number"},e=zh.reduce((n,o)=>(n[o]="function",n),t);if(Ft(r,e),Nt(r.BYTES,"BYTES"),Nt(r.BITS,"BITS"),r.BYTES<1||r.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(r.ORDER<=nt)throw new Error("invalid field: expected ORDER > 1, got "+r.ORDER);return r}function Hh(r,t,e){let n=r;if(e<bt)throw new Error("invalid exponent, negatives unsupported");if(e===bt)return n.ONE;if(e===nt)return t;let o=n.ONE,s=t;for(;e>bt;)e&nt&&(o=n.mul(o,s)),s=n.sqr(s),e>>=nt;return o}function Gr(r,t,e=!1){let n=r,o=new Array(t.length).fill(e?n.ZERO:void 0),s=t.reduce((a,c,l)=>n.is0(c)?a:(o[l]=a,n.mul(a,c)),n.ONE),i=n.inv(s);return t.reduceRight((a,c,l)=>n.is0(c)?a:(o[l]=n.mul(a,o[l]),n.mul(a,c)),i),o}function $c(r,t){let e=r,n=(e.ORDER-nt)/Ce,o=e.pow(t,n),s=e.eql(o,e.ONE),i=e.eql(o,e.ZERO),a=e.eql(o,e.neg(e.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function $h(r,t){if(t!==void 0&&Zs(t),r<=bt)throw new Error("invalid n length: expected positive n, got "+r);if(t!==void 0&&t<1)throw new Error("invalid n length: expected positive bit length, got "+t);let e=lr(r);if(t!==void 0&&t<e)throw new Error(`invalid n length: expected bit length (${e}) >= n.length (${t})`);let n=t!==void 0?t:e,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}var qc=new WeakMap,jn=class{ORDER;BITS;BYTES;isLE;ZERO=bt;ONE=nt;_lengths;_mod;constructor(t,e={}){if(t<=nt)throw new Error("invalid field: expected ORDER > 1, got "+t);let n;this.isLE=!1,e!=null&&typeof e=="object"&&(typeof e.BITS=="number"&&(n=e.BITS),typeof e.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:e.sqrt,enumerable:!0}),typeof e.isLE=="boolean"&&(this.isLE=e.isLE),e.allowedLengths&&(this._lengths=Object.freeze(e.allowedLengths.slice())),typeof e.modFromBytes=="boolean"&&(this._mod=e.modFromBytes));let{nBitLength:o,nByteLength:s}=$h(t,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=t,this.BITS=o,this.BYTES=s,Object.freeze(this)}create(t){return st(t,this.ORDER)}isValid(t){if(typeof t!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof t);return bt<=t&&t<this.ORDER}is0(t){return t===bt}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}isOdd(t){return(t&nt)===nt}neg(t){return st(-t,this.ORDER)}eql(t,e){return t===e}sqr(t){return st(t*t,this.ORDER)}add(t,e){return st(t+e,this.ORDER)}sub(t,e){return st(t-e,this.ORDER)}mul(t,e){return st(t*e,this.ORDER)}pow(t,e){return Hh(this,t,e)}div(t,e){return st(t*Hc(e,this.ORDER),this.ORDER)}sqrN(t){return t*t}addN(t,e){return t+e}subN(t,e){return t-e}mulN(t,e){return t*e}inv(t){return Hc(t,this.ORDER)}sqrt(t){let e=qc.get(this);return e||qc.set(this,e=Mh(this.ORDER)),e(this,t)}toBytes(t){return this.isLE?Ys(t,this.BYTES):Vn(t,this.BYTES)}fromBytes(t,e=!1){H(t);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(t.length<1||!n.includes(t.length)||t.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+t.length);let l=new Uint8Array(o);l.set(t,s?0:l.length-t.length),t=l}if(t.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+t.length);let c=s?jt(t):Be(t);if(a&&(c=st(c,i)),!e&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(t){return Gr(this,t)}cmov(t,e,n){return Rt(n,"condition"),n?e:t}};Object.freeze(jn.prototype);function ur(r,t={}){return new jn(r,t)}function Xc(r){if(typeof r!="bigint")throw new Error("field order must be bigint");if(r<=nt)throw new Error("field order must be greater than 1");let t=lr(r-nt);return Math.ceil(t/8)}function ti(r){let t=Xc(r);return t+Math.ceil(t/2)}function ei(r,t,e=!1){H(r);let n=r.length,o=Xc(t),s=Math.max(ti(t),16);if(n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=e?jt(r):Be(r),a=st(i,t-nt)+nt;return e?Ys(a,o):Vn(a,o)}var fr=BigInt(0),Pe=BigInt(1);function Zr(r,t){let e=t.negate();return r?e:t}function Oe(r,t){let e=Gr(r.Fp,t.map(n=>n.Z));return t.map((n,o)=>r.fromAffine(n.toAffine(e[o])))}function el(r,t){if(!Number.isSafeInteger(r)||r<=0||r>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+r)}function ri(r,t){el(r,t);let e=Math.ceil(t/r)+1,n=2**(r-1),o=2**r,s=jr(r),i=BigInt(r);return{windows:e,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function Qc(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+=Pe);let l=t*n,u=l+Math.abs(a)-1,f=a===0,h=a<0,d=t%2!==0;return{nextN:c,offset:u,isZero:f,isNeg:h,isNegF:d,offsetF:l}}var ni=new WeakMap,rl=new WeakMap;function oi(r){return rl.get(r)||1}function Jc(r){if(r!==fr)throw new Error("invalid wNAF")}var hr=class{BASE;ZERO;Fn;bits;constructor(t,e){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=e}_unsafeLadder(t,e,n=this.ZERO){let o=t;for(;e>fr;)e&Pe&&(n=n.add(o)),o=o.double(),e>>=Pe;return n}precomputeWindow(t,e){let{windows:n,windowSize:o}=ri(e,this.bits),s=[],i=t,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let l=1;l<o;l++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(t,e,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=ri(t,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:f,isNegF:h,offsetF:d}=Qc(n,a,i);n=c,u?s=s.add(Zr(h,e[d])):o=o.add(Zr(f,e[l]))}return Jc(n),{p:o,f:s}}wNAFUnsafe(t,e,n,o=this.ZERO){let s=ri(t,this.bits);for(let i=0;i<s.windows&&n!==fr;i++){let{nextN:a,offset:c,isZero:l,isNeg:u}=Qc(n,i,s);if(n=a,!l){let f=e[c];o=o.add(u?f.negate():f)}}return Jc(n),o}getPrecomputes(t,e,n){let o=ni.get(e);return o||(o=this.precomputeWindow(e,t),t!==1&&(typeof n=="function"&&(o=n(o)),ni.set(e,o))),o}cached(t,e,n){let o=oi(t);return this.wNAF(o,this.getPrecomputes(o,t,n),e)}unsafe(t,e,n,o){let s=oi(t);return s===1?this._unsafeLadder(t,e,o):this.wNAFUnsafe(s,this.getPrecomputes(s,t,n),e,o)}createCache(t,e){el(e,this.bits),rl.set(t,e),ni.delete(t)}hasCache(t){return oi(t)!==1}};function nl(r,t,e,n){let o=t,s=r.ZERO,i=r.ZERO;for(;e>fr||n>fr;)e&Pe&&(s=s.add(o)),n&Pe&&(i=i.add(o)),o=o.double(),e>>=Pe,n>>=Pe;return{p1:s,p2:i}}function tl(r,t,e){if(t){if(t.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Js(t),t}else return ur(r,{isLE:e})}function Gn(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 l=t[c];if(!(typeof l=="bigint"&&l>fr))throw new Error(`CURVE.${c} must be positive bigint`)}let o=tl(t.p,e.Fp,n),s=tl(t.n,e.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(t[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:s}}function Zn(r,t){return function(n){let o=r(n);return{secretKey:o,publicKey:t(o)}}}var ye=BigInt(0),pt=BigInt(1),si=BigInt(2),qh=BigInt(8);function Kh(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 ol(r,t={}){let e=t,n=Gn("edwards",r,e,e.FpFnLE),{Fp:o,Fn:s}=n,i=n.CURVE,{h:a}=i;Ft(e,{},{uvRatio:"function"});let c=si<<BigInt(s.BYTES*8)-pt,l=E=>o.create(E),u=e.uvRatio===void 0?(E,p)=>{try{return{isValid:!0,value:o.sqrt(o.div(E,p))}}catch{return{isValid:!1,value:ye}}}:e.uvRatio;if(!Kh(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function f(E,p,b=!1){let v=b?pt:ye;return cr("coordinate "+E,p,v,c),p}function h(E){if(!(E instanceof d))throw new Error("EdwardsPoint expected")}class d{static BASE=new d(i.Gx,i.Gy,pt,l(i.Gx*i.Gy));static ZERO=new d(ye,pt,pt,ye);static Fp=o;static Fn=s;X;Y;Z;T;constructor(p,b,v,S){this.X=f("x",p),this.Y=f("y",b),this.Z=f("z",v,!0),this.T=f("t",S),Object.freeze(this)}static CURVE(){return i}static fromAffine(p){if(p instanceof d)throw new Error("extended point not allowed");let{x:b,y:v}=p||{};return f("x",b),f("y",v),new d(b,v,pt,l(b*v))}static fromBytes(p,b=!1){let v=o.BYTES,{a:S,d:B}=i;p=Wr(H(p,v,"point")),Rt(b,"zip215");let D=Wr(p),R=p[v-1];D[v-1]=R&-129;let C=jt(D),T=b?c:o.ORDER;cr("point.y",C,ye,T);let N=l(C*C),j=l(N-pt),F=l(B*N-S),{isValid:m,value:y}=u(j,F);if(!m)throw new Error("bad point: invalid y coordinate");let _=(y&pt)===pt,x=(R&128)!==0;if(!b&&y===ye&&x)throw new Error("bad point: x=0 and x_0=1");return x!==_&&(y=l(-y)),d.fromAffine({x:y,y:C})}static fromHex(p,b=!1){return d.fromBytes(ar(p),b)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(p=8,b=!0){return g.createCache(this,p),b||this.multiply(si),this}assertValidity(){let p=this,{a:b,d:v}=i;if(p.is0())throw new Error("bad point: ZERO");let{X:S,Y:B,Z:D,T:R}=p,C=l(S*S),T=l(B*B),N=l(D*D),j=l(N*N),F=l(C*b),m=l(N*l(F+T)),y=l(j+l(v*l(C*T)));if(m!==y)throw new Error("bad point: equation left != right (1)");let _=l(S*B),x=l(D*R);if(_!==x)throw new Error("bad point: equation left != right (2)")}equals(p){h(p);let{X:b,Y:v,Z:S}=this,{X:B,Y:D,Z:R}=p,C=l(b*R),T=l(B*S),N=l(v*R),j=l(D*S);return C===T&&N===j}is0(){return this.equals(d.ZERO)}negate(){return new d(l(-this.X),this.Y,this.Z,l(-this.T))}double(){let{a:p}=i,{X:b,Y:v,Z:S}=this,B=l(b*b),D=l(v*v),R=l(si*l(S*S)),C=l(p*B),T=b+v,N=l(l(T*T)-B-D),j=C+D,F=j-R,m=C-D,y=l(N*F),_=l(j*m),x=l(N*m),w=l(F*j);return new d(y,_,w,x)}add(p){h(p);let{a:b,d:v}=i,{X:S,Y:B,Z:D,T:R}=this,{X:C,Y:T,Z:N,T:j}=p,F=l(S*C),m=l(B*T),y=l(R*v*j),_=l(D*N),x=l((S+B)*(C+T)-F-m),w=_-y,A=_+y,k=l(m-b*F),I=l(x*w),L=l(A*k),O=l(x*k),z=l(w*A);return new d(I,L,z,O)}subtract(p){return h(p),this.add(p.negate())}multiply(p){if(!s.isValidNot0(p))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:b,f:v}=g.cached(this,p,S=>Oe(d,S));return Oe(d,[b,v])[0]}multiplyUnsafe(p){if(!s.isValid(p))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return p===ye?d.ZERO:this.is0()||p===pt?this:g.unsafe(this,p,b=>Oe(d,b))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return g.unsafe(this,i.n).is0()}toAffine(p){let b=this,v=p,{X:S,Y:B,Z:D}=b,R=b.is0();v==null&&(v=R?qh:o.inv(D));let C=l(S*v),T=l(B*v),N=o.mul(D,v);if(R)return{x:ye,y:pt};if(N!==pt)throw new Error("invZ was invalid");return{x:C,y:T}}clearCofactor(){return a===pt?this:this.multiplyUnsafe(a)}toBytes(){let{x:p,y:b}=this.toAffine(),v=o.toBytes(b);return v[v.length-1]|=p&pt?128:0,v}toHex(){return ir(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let g=new hr(d,s.BITS);return s.BITS>=8&&d.BASE.precompute(8),Object.freeze(d.prototype),Object.freeze(d),d}var Yn=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(t){this.ep=t}static fromBytes(t){Xs()}static fromHex(t){Xs()}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 ir(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.ep.precompute(t,e),this}};function sl(r,t,e={}){if(typeof t!="function")throw new Error('"hash" function param is required');let n=t,o=e;Ft(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:s}=o,{BASE:i,Fp:a,Fn:c}=r,l=n.outputLen,u=2*a.BYTES;if(l!==void 0&&(Nt(l,"hash.outputLen"),l!==u))throw new Error(`hash.outputLen must be ${u}, got ${l}`);let f=o.randomBytes===void 0?Kr:o.randomBytes,h=o.adjustScalarBytes===void 0?m=>m:o.adjustScalarBytes,d=o.domain===void 0?(m,y,_)=>{if(Rt(_,"phflag"),y.length||_)throw new Error("Contexts/pre-hash are not supported");return m}:o.domain;function g(m){return c.create(jt(m))}function E(m){let y=C.secretKey;H(m,C.secretKey,"secretKey");let _=H(n(m),2*y,"hashedSecretKey"),x=h(_.slice(0,y)),w=_.slice(y,2*y),A=g(x);return{head:x,prefix:w,scalar:A}}function p(m){let{head:y,prefix:_,scalar:x}=E(m),w=i.multiply(x),A=w.toBytes();return{head:y,prefix:_,scalar:x,point:w,pointBytes:A}}function b(m){return p(m).pointBytes}function v(m=Uint8Array.of(),...y){let _=ft(...y);return g(n(d(_,H(m,void 0,"context"),!!s)))}function S(m,y,_={}){m=H(m,void 0,"message"),s&&(m=s(m));let{prefix:x,scalar:w,pointBytes:A}=p(y),k=v(_.context,x,m),I=i.multiply(k).toBytes(),L=v(_.context,I,A,m),O=c.create(k+L*w);if(!c.isValid(O))throw new Error("sign failed: invalid s");let z=ft(I,c.toBytes(O));return H(z,C.signature,"result")}let B={zip215:o.zip215};function D(m,y,_,x=B){let{context:w}=x,A=x.zip215===void 0?!!B.zip215:x.zip215,k=C.signature;m=H(m,k,"signature"),y=H(y,void 0,"message"),_=H(_,C.publicKey,"publicKey"),A!==void 0&&Rt(A,"zip215"),s&&(y=s(y));let I=k/2,L=m.subarray(0,I),O=jt(m.subarray(I,k)),z,q,U;try{z=r.fromBytes(_,A),q=r.fromBytes(L,A),U=i.multiplyUnsafe(O)}catch{return!1}if(!A&&z.isSmallOrder())return!1;let lt=v(w,L,_,y);return q.add(z.multiplyUnsafe(lt)).subtract(U).clearCofactor().is0()}let R=a.BYTES,C={secretKey:R,publicKey:R,signature:2*R,seed:R};function T(m){return m=m===void 0?f(C.seed):m,H(m,C.seed,"seed")}function N(m){return Le(m)&&m.length===C.secretKey}function j(m,y){try{return!!r.fromBytes(m,y===void 0?B.zip215:y)}catch{return!1}}let F={getExtendedPublicKey:p,randomSecretKey:T,isValidSecretKey:N,isValidPublicKey:j,toMontgomery(m){let{y}=r.fromBytes(m),_=C.publicKey,x=_===32;if(!x&&_!==57)throw new Error("only defined for 25519 and 448");let w=x?a.div(pt+y,pt-y):a.div(y-pt,y+pt);return a.toBytes(w)},toMontgomerySecret(m){let y=C.secretKey;H(m,y);let _=n(m.subarray(0,y));return h(_).subarray(0,y)}};return Object.freeze(C),Object.freeze(F),Object.freeze({keygen:Zn(T,b),getPublicKey:b,sign:S,verify:D,utils:F,Point:r,lengths:C})}function Yr(r,t){if(Nt(r),Nt(t),t<0||t>4)throw new Error("invalid I2OSP length: "+t);if(r<0||r>2**(8*t)-1)throw new Error("invalid I2OSP input: "+r);let e=Array.from({length:t}).fill(0);for(let n=t-1;n>=0;n--)e[n]=r&255,r>>>=8;return new Uint8Array(e)}function Vh(r,t){let e=new Uint8Array(r.length);for(let n=0;n<r.length;n++)e[n]=r[n]^t[n];return e}function Wh(r){if(!Le(r)&&typeof r!="string")throw new Error("DST must be Uint8Array or ascii string");let t=typeof r=="string"?Wn(r):r;if(t.length===0)throw new Error("DST must be non-empty");return t}function ii(r,t,e,n){H(r),Nt(e),t=Wh(t),t.length>255&&(t=n(ft(Wn("H2C-OVERSIZE-DST-"),t)));let{outputLen:o,blockLen:s}=n,i=Math.ceil(e/o);if(e>65535||i>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=ft(t,Yr(t.length,1)),c=new Uint8Array(s),l=Yr(e,2),u=new Array(i),f=n(ft(c,r,l,Yr(0,1),a));u[0]=n(ft(f,Yr(1,1),a));for(let d=1;d<i;d++){let g=[Vh(f,u[d-1]),Yr(d+1,1),a];u[d]=n(ft(...g))}return ft(...u).slice(0,e)}var il="HashToScalar-";var jh=BigInt(0),ie=BigInt(1),al=BigInt(2);var Gh=BigInt(5),Zh=BigInt(8),dr=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),ui={p:dr,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Zh,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Yh(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),s=dr,a=r*r%s*r%s,c=Q(a,al,s)*a%s,l=Q(c,ie,s)*r%s,u=Q(l,Gh,s)*l%s,f=Q(u,t,s)*u%s,h=Q(f,e,s)*f%s,d=Q(h,n,s)*h%s,g=Q(d,o,s)*d%s,E=Q(g,o,s)*d%s,p=Q(E,t,s)*u%s;return{pow_p_5_8:Q(p,al,s)*r%s,b2:a}}function Xh(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var ai=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function fi(r,t){let e=dr,n=st(t*t*t,e),o=st(n*n*t,e),s=Yh(r*o).pow_p_5_8,i=st(r*n*s,e),a=st(t*i*i,e),c=i,l=st(i*ai,e),u=a===r,f=a===st(-r,e),h=a===st(-r*ai,e);return u&&(i=c),(f||h)&&(i=l),se(i,e)&&(i=st(-i,e)),{isValid:u||f,value:i}}var xe=ol(ui,{uvRatio:fi}),we=xe.Fp,ul=xe.Fn;function Qh(r){return sl(xe,Hn,Object.assign({adjustScalarBytes:Xh,zip215:!0},r))}var fl=Qh({});var ci=ai,Jh=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),td=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),ed=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),rd=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),cl=r=>fi(ie,r),nd=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),li=r=>we.create(jt(r)&nd);function ll(r){let{d:t}=ui,e=dr,n=b=>we.create(b),o=n(ci*r*r),s=n((o+ie)*ed),i=BigInt(-1),a=n((i-t*o)*n(o+t)),{isValid:c,value:l}=fi(s,a),u=n(l*r);se(u,e)||(u=n(-u)),c||(l=u),c||(i=o);let f=n(i*(o-ie)*rd-a),h=l*l,d=n((l+l)*a),g=n(f*Jh),E=n(ie-h),p=n(ie+h);return new xe(n(d*p),n(E*g),n(g*p),n(d*E))}var Ee=class r extends Yn{static BASE=new r(xe.BASE);static ZERO=new r(xe.ZERO);static Fp=we;static Fn=ul;constructor(t){super(t)}static fromAffine(t){return new r(xe.fromAffine(t))}assertSame(t){if(!(t instanceof r))throw new Error("RistrettoPoint expected")}init(t){return new r(t)}static fromBytes(t){Dt(t,32);let{a:e,d:n}=ui,o=dr,s=B=>we.create(B),i=li(t);if(!Mc(we.toBytes(i),t)||se(i,o))throw new Error("invalid ristretto255 encoding 1");let a=s(i*i),c=s(ie+e*a),l=s(ie-e*a),u=s(c*c),f=s(l*l),h=s(e*n*u-f),{isValid:d,value:g}=cl(s(h*f)),E=s(g*l),p=s(g*E*h),b=s((i+i)*E);se(b,o)&&(b=s(-b));let v=s(c*p),S=s(b*v);if(!d||se(S,o)||v===jh)throw new Error("invalid ristretto255 encoding 2");return new r(new xe(b,v,ie,S))}static fromHex(t){return r.fromBytes(zr(t))}toBytes(){let{X:t,Y:e,Z:n,T:o}=this.ep,s=dr,i=p=>we.create(p),a=i(i(n+e)*i(n-e)),c=i(t*e),l=i(c*c),{value:u}=cl(i(a*l)),f=i(u*a),h=i(u*c),d=i(f*h*o),g;if(se(o*d,s)){let p=i(e*ci),b=i(t*ci);t=p,e=b,g=i(f*td)}else g=h;se(t*d,s)&&(e=i(-e));let E=i((n-e)*g);return se(E,s)&&(E=i(-E)),we.toBytes(E)}equals(t){this.assertSame(t);let{X:e,Y:n}=this.ep,{X:o,Y:s}=t.ep,i=l=>we.create(l),a=i(e*s)===i(n*o),c=i(n*s)===i(e*o);return a||c}is0(){return this.equals(r.ZERO)}};Object.freeze(Ee.BASE);Object.freeze(Ee.ZERO);Object.freeze(Ee.prototype);Object.freeze(Ee);var od=Object.freeze({Point:Ee,hashToCurve(r,t){let e=t?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":t.DST,n=ii(r,e,64,Hn);return od.deriveToCurve(n)},hashToScalar(r,t={DST:il}){let e=ii(r,t.DST,64,Hn);return ul.create(jt(e))},deriveToCurve(r){Dt(r,64);let t=li(r.subarray(0,32)),e=ll(t),n=li(r.subarray(32,64)),o=ll(n);return new Ee(e.add(o))}});var Xn=32;var hi,sd=(async()=>{try{return await Ln.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function id(r,t,e){if(r.buffer instanceof ArrayBuffer){let n=await Ln.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await Ln.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 ad(r,t,e){return fl.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}async function hl(r,t,e){return hi==null&&(hi=await sd),hi?id(r,t,e):ad(r,t,e)}function Qn(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Jn=class{type="Ed25519";raw;constructor(t){this.raw=di(t,Xn)}toMultihash(){return kt.digest(or(this))}toCID(){return et.createV1(114,this.toMultihash())}toString(){return it.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:at(this.raw,t.raw)}verify(t,e,n){n?.signal?.throwIfAborted();let o=hl(this.raw,e,t);return Qn(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function pl(r){return r=di(r,Xn),new Jn(r)}function di(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new Tt(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}var ld=Math.pow(2,7),ud=Math.pow(2,14),fd=Math.pow(2,21),pi=Math.pow(2,28),mi=Math.pow(2,35),gi=Math.pow(2,42),bi=Math.pow(2,49),K=128,Et=127;function J(r){if(r<ld)return 1;if(r<ud)return 2;if(r<fd)return 3;if(r<pi)return 4;if(r<mi)return 5;if(r<gi)return 6;if(r<bi)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function pr(r,t,e=0){switch(J(r)){case 8:t[e++]=r&255|K,r/=128;case 7:t[e++]=r&255|K,r/=128;case 6:t[e++]=r&255|K,r/=128;case 5:t[e++]=r&255|K,r/=128;case 4:t[e++]=r&255|K,r>>>=7;case 3:t[e++]=r&255|K,r>>>=7;case 2:t[e++]=r&255|K,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function hd(r,t,e=0){switch(J(r)){case 8:t.set(e++,r&255|K),r/=128;case 7:t.set(e++,r&255|K),r/=128;case 6:t.set(e++,r&255|K),r/=128;case 5:t.set(e++,r&255|K),r/=128;case 4:t.set(e++,r&255|K),r>>>=7;case 3:t.set(e++,r&255|K),r>>>=7;case 2:t.set(e++,r&255|K),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function yi(r,t){let e=r[t],n=0;if(n+=e&Et,e<K||(e=r[t+1],n+=(e&Et)<<7,e<K)||(e=r[t+2],n+=(e&Et)<<14,e<K)||(e=r[t+3],n+=(e&Et)<<21,e<K)||(e=r[t+4],n+=(e&Et)*pi,e<K)||(e=r[t+5],n+=(e&Et)*mi,e<K)||(e=r[t+6],n+=(e&Et)*gi,e<K)||(e=r[t+7],n+=(e&Et)*bi,e<K))return n;throw new RangeError("Could not decode varint")}function dd(r,t){let e=r.get(t),n=0;if(n+=e&Et,e<K||(e=r.get(t+1),n+=(e&Et)<<7,e<K)||(e=r.get(t+2),n+=(e&Et)<<14,e<K)||(e=r.get(t+3),n+=(e&Et)<<21,e<K)||(e=r.get(t+4),n+=(e&Et)*pi,e<K)||(e=r.get(t+5),n+=(e&Et)*mi,e<K)||(e=r.get(t+6),n+=(e&Et)*gi,e<K)||(e=r.get(t+7),n+=(e&Et)*bi,e<K))return n;throw new RangeError("Could not decode varint")}function to(r,t,e=0){return t==null&&(t=xt(J(r))),t instanceof Uint8Array?pr(r,t,e):hd(r,t,e)}function Re(r,t=0){return r instanceof Uint8Array?yi(r,t):dd(r,t)}var xi=new Float32Array([-0]),ve=new Uint8Array(xi.buffer);function ml(r,t,e){xi[0]=r,t[e]=ve[0],t[e+1]=ve[1],t[e+2]=ve[2],t[e+3]=ve[3]}function gl(r,t){return ve[0]=r[t],ve[1]=r[t+1],ve[2]=r[t+2],ve[3]=r[t+3],xi[0]}var Ei=new Float64Array([-0]),vt=new Uint8Array(Ei.buffer);function bl(r,t,e){Ei[0]=r,t[e]=vt[0],t[e+1]=vt[1],t[e+2]=vt[2],t[e+3]=vt[3],t[e+4]=vt[4],t[e+5]=vt[5],t[e+6]=vt[6],t[e+7]=vt[7]}function yl(r,t){return vt[0]=r[t],vt[1]=r[t+1],vt[2]=r[t+2],vt[3]=r[t+3],vt[4]=r[t+4],vt[5]=r[t+5],vt[6]=r[t+6],vt[7]=r[t+7],Ei[0]}var pd=BigInt(Number.MAX_SAFE_INTEGER),md=BigInt(Number.MIN_SAFE_INTEGER),Lt=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 Ne;if(t<pd&&t>md)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>wl&&(o=0n,++n>wl&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return Ne;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):Ne}},Ne=new Lt(0,0);Ne.toBigInt=function(){return 0n};Ne.zzEncode=Ne.zzDecode=function(){return this};Ne.length=function(){return 1};var wl=4294967296n;function xl(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 El(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 vi(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 Ut(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function eo(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var _i=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,Ut(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 Ut(this,4);return eo(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Ut(this,4);return eo(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Ut(this,4);let t=gl(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw Ut(this,4);let t=yl(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 Ut(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return El(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw Ut(this,t);this.pos+=t}else do if(this.pos>=this.len)throw Ut(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 Lt(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 Ut(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 Ut(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 Ut(this,8);let t=eo(this.buf,this.pos+=4),e=eo(this.buf,this.pos+=4);return new Lt(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=yi(this.buf,this.pos);return this.pos+=J(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 Xr(r){return new _i(r instanceof Uint8Array?r:r.subarray())}function Gt(r,t,e){let n=Xr(r);return t.decode(n,void 0,e)}function Si(r){let t=r??8192,e=t>>>1,n,o=t;return function(i){if(i<1||i>e)return xt(i);o+i>t&&(n=xt(t),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var Fe=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function Ai(){}var Ti=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},gd=Si();function bd(r){return globalThis.Buffer!=null?xt(r):gd(r)}var Jr=class{len;head;tail;states;constructor(){this.len=0,this.head=new Fe(Ai,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new Fe(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new ki((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(ro,10,Lt.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=Lt.fromBigInt(t);return this._push(ro,e.length(),e)}uint64Number(t){return this._push(pr,J(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=Lt.fromBigInt(t).zzEncode();return this._push(ro,e.length(),e)}sint64Number(t){let e=Lt.fromNumber(t).zzEncode();return this._push(ro,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(Ii,1,t?1:0)}fixed32(t){return this._push(Qr,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=Lt.fromBigInt(t);return this._push(Qr,4,e.lo)._push(Qr,4,e.hi)}fixed64Number(t){let e=Lt.fromNumber(t);return this._push(Qr,4,e.lo)._push(Qr,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(ml,4,t)}double(t){return this._push(bl,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(Ii,1,0):this.uint32(e)._push(wd,e,t)}string(t){let e=xl(t);return e!==0?this.uint32(e)._push(vi,e,t):this._push(Ii,1,0)}fork(){return this.states=new Ti(this),this.head=this.tail=new Fe(Ai,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 Fe(Ai,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=bd(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function Ii(r,t,e){t[e]=r&255}function yd(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var ki=class extends Fe{next;constructor(t,e){super(yd,t,e),this.next=void 0}};function ro(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 Qr(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 wd(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(Jr.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(xd,t,r),this},Jr.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(Ed,t,r),this});function xd(r,t,e){t.set(r,e)}function Ed(r,t,e){r.length<40?vi(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(Z(r),e)}function Di(){return new Jr}function Zt(r,t){let e=Di();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}function*Yt(r,t,e){let n=Xr(r);yield*t.stream(n,void 0,"$",e)}var no={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function oo(r,t,e,n,o){return{name:r,type:t,encode:e,decode:n,stream:o}}function mr(r){function t(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let e=function(i,a){let c=t(i);a.int32(c)},n=function(i){let a=i.int32();return t(a)},o=function*(i){let a=i.int32();yield t(a)};return oo("enum",no.VARINT,e,n,o)}function Xt(r,t,e){return oo("message",no.LENGTH_DELIMITED,r,t,e)}var ae=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var St;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(St||(St={}));var Li;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(Li||(Li={}));(function(r){r.codec=()=>mr(Li)})(St||(St={}));var tn;(function(r){let t;r.codec=()=>(t==null&&(t=Xt((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),St.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.Type=St.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:St.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),t);function e(s){return Zt(s,r.codec())}r.encode=e;function n(s,i){return Gt(s,r.codec(),i)}r.decode=n;function o(s,i){return Yt(s,r.codec(),i)}r.stream=o})(tn||(tn={}));var Bi;(function(r){let t;r.codec=()=>(t==null&&(t=Xt((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),St.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.Type=St.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:St.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),t);function e(s){return Zt(s,r.codec())}r.encode=e;function n(s,i){return Gt(s,r.codec(),i)}r.decode=n;function o(s,i){return Yt(s,r.codec(),i)}r.stream=o})(Bi||(Bi={}));var so=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(t,e){if(Nn(t),Dt(e,void 0,"key"),this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(e.length>n?t.create().update(e).digest():e);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=t.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),ne(o)}update(t){return sr(this),this.iHash.update(t),this}digestInto(t){sr(this),Fn(t,this),this.finished=!0;let e=t.subarray(0,this.outputLen);this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||=Object.create(Object.getPrototypeOf(this),{});let{oHash:e,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return t=t,t.finished=o,t.destroyed=s,t.blockLen=i,t.outputLen=a,t.oHash=e._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},_l=(()=>{let r=((t,e,n)=>new so(t,e).update(n).digest());return r.create=(t,e)=>new so(t,e),r})();var Sl=(r,t)=>(r+(r>=0?t:-t)/Al)/t;function _d(r,t,e){cr("scalar",r,Qt,e);let[[n,o],[s,i]]=t,a=Sl(i*r,e),c=Sl(-o*r,e),l=r-a*n-c*s,u=-a*o-c*i,f=l<Qt,h=u<Qt;f&&(l=-l),h&&(u=-u);let d=jr(Math.ceil(lr(e)/2))+_e;if(l<Qt||l>=d||u<Qt||u>=d)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:f,k1:l,k2neg:h,k2:u}}function Pi(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function Ci(r,t){Ft(r);let e={};for(let n of Object.keys(t))e[n]=r[n]===void 0?t[n]:r[n];return Rt(e.lowS,"lowS"),Rt(e.prehash,"prehash"),e.format!==void 0&&Pi(e.format),e}var Oi=class extends Error{constructor(t=""){super(t)}},Mt={Err:Oi,_tlv:{encode:(r,t)=>{let{Err:e}=Mt;if(Nt(r,"tag"),r<0||r>255)throw new e("tlv.encode: wrong tag");if(typeof t!="string")throw new TypeError('"data" expected string, got type='+typeof t);if(t.length&1)throw new e("tlv.encode: unpadded data");let n=t.length/2,o=Vr(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let s=n>127?Vr(o.length/2|128):"";return Vr(r)+s+o+t},decode(r,t){let{Err:e}=Mt;t=H(t,void 0,"DER data");let n=0;if(r<0||r>255)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 l=t.subarray(n,n+c);if(l.length!==c)throw new e("tlv.decode: length bytes not complete");if(l[0]===0)throw new e("tlv.decode(long): zero leftmost byte");for(let u of l)i=i<<8|u;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}=Mt;if(Kn(r),r<Qt)throw new t("integer: negative integers are not allowed");let e=Vr(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}=Mt;if(r.length<1)throw new t("invalid signature integer: empty");if(r[0]&128)throw new t("invalid signature integer: negative");if(r.length>1&&r[0]===0&&!(r[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return Be(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=Mt,o=H(r,void 0,"signature"),{v:s,l:i}=n.decode(48,o);if(i.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:l,l:u}=n.decode(2,c);if(u.length)throw new t("invalid signature: left bytes after parsing");return{r:e.decode(a),s:e.decode(l)}},hexFromSig(r){let{_tlv:t,_int:e}=Mt,n=t.encode(2,e.encode(r.r)),o=t.encode(2,e.encode(r.s)),s=n+o;return t.encode(48,s)}};Object.freeze(Mt._tlv);Object.freeze(Mt._int);Object.freeze(Mt);var Qt=BigInt(0),_e=BigInt(1),Al=BigInt(2),io=BigInt(3),Sd=BigInt(4);function Il(r,t={}){let e=Gn("weierstrass",r,t),n=e.Fp,o=e.Fn,s=e.CURVE,{h:i,n:a}=s;Ft(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c,allowInfinityPoint:l}=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=kl(n,o);function f(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function h(F,m,y){if(l&&m.is0())return Uint8Array.of(0);let{x:_,y:x}=m.toAffine(),w=n.toBytes(_);if(Rt(y,"isCompressed"),y){f();let A=!n.isOdd(x);return ft(Tl(A),w)}else return ft(Uint8Array.of(4),w,n.toBytes(x))}function d(F){H(F,void 0,"Point");let{publicKey:m,publicKeyUncompressed:y}=u,_=F.length,x=F[0],w=F.subarray(1);if(l&&_===1&&x===0)return{x:n.ZERO,y:n.ZERO};if(_===m&&(x===2||x===3)){let A=n.fromBytes(w);if(!n.isValid(A))throw new Error("bad point: is not on curve, wrong x");let k=p(A),I;try{I=n.sqrt(k)}catch(z){let q=z instanceof Error?": "+z.message:"";throw new Error("bad point: is not on curve, sqrt error"+q)}f();let L=n.isOdd(I);return(x&1)===1!==L&&(I=n.neg(I)),{x:A,y:I}}else if(_===y&&x===4){let A=n.BYTES,k=n.fromBytes(w.subarray(0,A)),I=n.fromBytes(w.subarray(A,A*2));if(!b(k,I))throw new Error("bad point: is not on curve");return{x:k,y:I}}else throw new Error(`bad point: got length ${_}, expected compressed=${m} or uncompressed=${y}`)}let g=t.toBytes===void 0?h:t.toBytes,E=t.fromBytes===void 0?d:t.fromBytes;function p(F){let m=n.sqr(F),y=n.mul(m,F);return n.add(n.add(y,n.mul(F,s.a)),s.b)}function b(F,m){let y=n.sqr(m),_=p(F);return n.eql(y,_)}if(!b(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let v=n.mul(n.pow(s.a,io),Sd),S=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(v,S)))throw new Error("bad curve params: a or b");function B(F,m,y=!1){if(!n.isValid(m)||y&&n.is0(m))throw new Error(`bad point coordinate ${F}`);return m}function D(F){if(!(F instanceof T))throw new Error("Weierstrass Point expected")}function R(F){if(!c||!c.basises)throw new Error("no endo");return _d(F,c.basises,o.ORDER)}function C(F,m,y,_,x){return y=new T(n.mul(y.X,F),y.Y,y.Z),m=Zr(_,m),y=Zr(x,y),m.add(y)}class T{static BASE=new T(s.Gx,s.Gy,n.ONE);static ZERO=new T(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(m,y,_){this.X=B("x",m),this.Y=B("y",y,!0),this.Z=B("z",_),Object.freeze(this)}static CURVE(){return s}static fromAffine(m){let{x:y,y:_}=m||{};if(!m||!n.isValid(y)||!n.isValid(_))throw new Error("invalid affine point");if(m instanceof T)throw new Error("projective point not allowed");return n.is0(y)&&n.is0(_)?T.ZERO:new T(y,_,n.ONE)}static fromBytes(m){let y=T.fromAffine(E(H(m,void 0,"point")));return y.assertValidity(),y}static fromHex(m){return T.fromBytes(ar(m))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(m=8,y=!0){return j.createCache(this,m),y||this.multiply(io),this}assertValidity(){let m=this;if(m.is0()){if(t.allowInfinityPoint&&n.is0(m.X)&&n.eql(m.Y,n.ONE)&&n.is0(m.Z))return;throw new Error("bad point: ZERO")}let{x:y,y:_}=m.toAffine();if(!n.isValid(y)||!n.isValid(_))throw new Error("bad point: x or y not field elements");if(!b(y,_))throw new Error("bad point: equation left != right");if(!m.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:m}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(m)}equals(m){D(m);let{X:y,Y:_,Z:x}=this,{X:w,Y:A,Z:k}=m,I=n.eql(n.mul(y,k),n.mul(w,x)),L=n.eql(n.mul(_,k),n.mul(A,x));return I&&L}negate(){return new T(this.X,n.neg(this.Y),this.Z)}double(){let{a:m,b:y}=s,_=n.mul(y,io),{X:x,Y:w,Z:A}=this,k=n.ZERO,I=n.ZERO,L=n.ZERO,O=n.mul(x,x),z=n.mul(w,w),q=n.mul(A,A),U=n.mul(x,w);return U=n.add(U,U),L=n.mul(x,A),L=n.add(L,L),k=n.mul(m,L),I=n.mul(_,q),I=n.add(k,I),k=n.sub(z,I),I=n.add(z,I),I=n.mul(k,I),k=n.mul(U,k),L=n.mul(_,L),q=n.mul(m,q),U=n.sub(O,q),U=n.mul(m,U),U=n.add(U,L),L=n.add(O,O),O=n.add(L,O),O=n.add(O,q),O=n.mul(O,U),I=n.add(I,O),q=n.mul(w,A),q=n.add(q,q),O=n.mul(q,U),k=n.sub(k,O),L=n.mul(q,z),L=n.add(L,L),L=n.add(L,L),new T(k,I,L)}add(m){D(m);let{X:y,Y:_,Z:x}=this,{X:w,Y:A,Z:k}=m,I=n.ZERO,L=n.ZERO,O=n.ZERO,z=s.a,q=n.mul(s.b,io),U=n.mul(y,w),lt=n.mul(_,A),ht=n.mul(x,k),dt=n.add(y,_),ot=n.add(w,A);dt=n.mul(dt,ot),ot=n.add(U,lt),dt=n.sub(dt,ot),ot=n.add(y,x);let At=n.add(w,k);return ot=n.mul(ot,At),At=n.add(U,ht),ot=n.sub(ot,At),At=n.add(_,x),I=n.add(A,k),At=n.mul(At,I),I=n.add(lt,ht),At=n.sub(At,I),O=n.mul(z,ot),I=n.mul(q,ht),O=n.add(I,O),I=n.sub(lt,O),O=n.add(lt,O),L=n.mul(I,O),lt=n.add(U,U),lt=n.add(lt,U),ht=n.mul(z,ht),ot=n.mul(q,ot),lt=n.add(lt,ht),ht=n.sub(U,ht),ht=n.mul(z,ht),ot=n.add(ot,ht),U=n.mul(lt,ot),L=n.add(L,U),U=n.mul(At,ot),I=n.mul(dt,I),I=n.sub(I,U),U=n.mul(dt,lt),O=n.mul(At,O),O=n.add(O,U),new T(I,L,O)}subtract(m){return D(m),this.add(m.negate())}is0(){return this.equals(T.ZERO)}multiply(m){let{endo:y}=t;if(!o.isValidNot0(m))throw new RangeError("invalid scalar: out of range");let _,x,w=A=>j.cached(this,A,k=>Oe(T,k));if(y){let{k1neg:A,k1:k,k2neg:I,k2:L}=R(m),{p:O,f:z}=w(k),{p:q,f:U}=w(L);x=z.add(U),_=C(y.beta,O,q,A,I)}else{let{p:A,f:k}=w(m);_=A,x=k}return Oe(T,[_,x])[0]}multiplyUnsafe(m){let{endo:y}=t,_=this,x=m;if(!o.isValid(x))throw new RangeError("invalid scalar: out of range");if(x===Qt||_.is0())return T.ZERO;if(x===_e)return _;if(j.hasCache(this))return this.multiply(x);if(y){let{k1neg:w,k1:A,k2neg:k,k2:I}=R(x),{p1:L,p2:O}=nl(T,_,A,I);return C(y.beta,L,O,w,k)}else return j.unsafe(_,x)}toAffine(m){let y=this,_=m,{X:x,Y:w,Z:A}=y;if(n.eql(A,n.ONE))return{x,y:w};let k=y.is0();_==null&&(_=k?n.ONE:n.inv(A));let I=n.mul(x,_),L=n.mul(w,_),O=n.mul(A,_);if(k)return{x:n.ZERO,y:n.ZERO};if(!n.eql(O,n.ONE))throw new Error("invZ was invalid");return{x:I,y:L}}isTorsionFree(){let{isTorsionFree:m}=t;return i===_e?!0:m?m(T,this):j.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:m}=t;return i===_e?this:m?m(T,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===_e?this.is0():this.clearCofactor().is0()}toBytes(m=!0){return Rt(m,"isCompressed"),this.assertValidity(),g(T,this,m)}toHex(m=!0){return ir(this.toBytes(m))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let N=o.BITS,j=new hr(T,t.endo?Math.ceil(N/2):N);return N>=8&&T.BASE.precompute(8),Object.freeze(T.prototype),Object.freeze(T),T}function Tl(r){return Uint8Array.of(r?2:3)}function kl(r,t){return{secretKey:t.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function Ad(r,t={}){let{Fn:e}=r,n=t.randomBytes===void 0?Kr:t.randomBytes,o=Object.assign(kl(r.Fp,e),{seed:Math.max(ti(e.ORDER),16)});function s(d){try{let g=e.fromBytes(d);return e.isValidNot0(g)}catch{return!1}}function i(d,g){let{publicKey:E,publicKeyUncompressed:p}=o;try{let b=d.length;return g===!0&&b!==E||g===!1&&b!==p?!1:!!r.fromBytes(d)}catch{return!1}}function a(d){return d=d===void 0?n(o.seed):d,ei(H(d,o.seed,"seed"),e.ORDER)}function c(d,g=!0){return r.BASE.multiply(e.fromBytes(d)).toBytes(g)}function l(d){let{secretKey:g,publicKey:E,publicKeyUncompressed:p}=o,b=e._lengths;if(!Le(d))return;let v=H(d,void 0,"key").length,S=v===E||v===p,B=v===g||!!b?.includes(v);if(!(S&&B))return S}function u(d,g,E=!0){if(l(d)===!0)throw new Error("first arg must be private key");if(l(g)===!1)throw new Error("second arg must be public key");let p=e.fromBytes(d);return r.fromBytes(g).multiply(p).toBytes(E)}let f={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},h=Zn(a,c);return Object.freeze(f),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:h,Point:r,utils:f,lengths:o})}function Dl(r,t,e={}){let n=t;Nn(n),Ft(e,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),e=Object.assign({},e);let o=e.randomBytes===void 0?Kr:e.randomBytes,s=e.hmac===void 0?(x,w)=>_l(n,x,w):e.hmac,{Fp:i,Fn:a}=r,{ORDER:c,BITS:l}=a,{keygen:u,getPublicKey:f,getSharedSecret:h,utils:d,lengths:g}=Ad(r,e),E={prehash:!0,lowS:typeof e.lowS=="boolean"?e.lowS:!0,format:"compact",extraEntropy:!1},p=c*Al+_e<i.ORDER;function b(x){let w=c>>_e;return x>w}function v(x,w){if(!a.isValidNot0(w))throw new Error(`invalid signature ${x}: out of range 1..Point.Fn.ORDER`);return w}function S(){if(p)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function B(x,w){Pi(w);let A=g.signature,k=w==="compact"?A:w==="recovered"?A+1:void 0;return H(x,k)}class D{r;s;recovery;constructor(w,A,k){if(this.r=v("r",w),this.s=v("s",A),k!=null){if(S(),![0,1,2,3].includes(k))throw new Error("invalid recovery id");this.recovery=k}Object.freeze(this)}static fromBytes(w,A=E.format){B(w,A);let k;if(A==="der"){let{r:z,s:q}=Mt.toSig(H(w));return new D(z,q)}A==="recovered"&&(k=w[0],A="compact",w=w.subarray(1));let I=g.signature/2,L=w.subarray(0,I),O=w.subarray(I,I*2);return new D(a.fromBytes(L),a.fromBytes(O),k)}static fromHex(w,A){return this.fromBytes(ar(w),A)}assertRecovery(){let{recovery:w}=this;if(w==null)throw new Error("invalid recovery id: must be present");return w}addRecoveryBit(w){return new D(this.r,this.s,w)}recoverPublicKey(w){let{r:A,s:k}=this,I=this.assertRecovery(),L=I===2||I===3?A+c:A;if(!i.isValid(L))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let O=i.toBytes(L),z=r.fromBytes(ft(Tl((I&1)===0),O)),q=a.inv(L),U=C(H(w,void 0,"msgHash")),lt=a.create(-U*q),ht=a.create(k*q),dt=r.BASE.multiplyUnsafe(lt).add(z.multiplyUnsafe(ht));if(dt.is0())throw new Error("invalid recovery: point at infinify");return dt.assertValidity(),dt}hasHighS(){return b(this.s)}toBytes(w=E.format){if(Pi(w),w==="der")return ar(Mt.hexFromSig(this));let{r:A,s:k}=this,I=a.toBytes(A),L=a.toBytes(k);return w==="recovered"?(S(),ft(Uint8Array.of(this.assertRecovery()),I,L)):ft(I,L)}toHex(w){return ir(this.toBytes(w))}}Object.freeze(D.prototype),Object.freeze(D);let R=e.bits2int===void 0?function(w){if(w.length>8192)throw new Error("input is too large");let A=Be(w),k=w.length*8-l;return k>0?A>>BigInt(k):A}:e.bits2int,C=e.bits2int_modN===void 0?function(w){return a.create(R(w))}:e.bits2int_modN,T=jr(l);function N(x){return cr("num < 2^"+l,x,Qt,T),a.toBytes(x)}function j(x,w){return H(x,void 0,"message"),w?H(n(x),void 0,"prehashed message"):x}function F(x,w,A){let{lowS:k,prehash:I,extraEntropy:L}=Ci(A,E);x=j(x,I);let O=C(x),z=a.fromBytes(w);if(!a.isValidNot0(z))throw new Error("invalid private key");let q=[N(z),N(O)];if(L!=null&&L!==!1){let dt=L===!0?o(g.secretKey):L;q.push(H(dt,void 0,"extraEntropy"))}let U=ft(...q),lt=O;function ht(dt){let ot=R(dt);if(!a.isValidNot0(ot))return;let At=a.inv(ot),Ye=r.BASE.multiply(ot).toAffine(),Lr=a.create(Ye.x);if(Lr===Qt)return;let wn=a.create(At*a.create(lt+Lr*z));if(wn===Qt)return;let Ha=(Ye.x===Lr?0:2)|Number(Ye.y&_e),$a=wn;return k&&b(wn)&&($a=a.neg(wn),Ha^=1),new D(Lr,$a,p?void 0:Ha)}return{seed:U,k2sig:ht}}function m(x,w,A={}){let{seed:k,k2sig:I}=F(x,w,A);return zc(n.outputLen,a.BYTES,s)(k,I).toBytes(A.format)}function y(x,w,A,k={}){let{lowS:I,prehash:L,format:O}=Ci(k,E);if(A=H(A,void 0,"publicKey"),w=j(w,L),!Le(x)){let z=x instanceof D?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+z)}B(x,O);try{let z=D.fromBytes(x,O),q=r.fromBytes(A);if(I&&z.hasHighS())return!1;let{r:U,s:lt}=z,ht=C(w),dt=a.inv(lt),ot=a.create(ht*dt),At=a.create(U*dt),Ye=r.BASE.multiplyUnsafe(ot).add(q.multiplyUnsafe(At));return Ye.is0()?!1:a.create(Ye.x)===U}catch{return!1}}function _(x,w,A={}){let{prehash:k}=Ci(A,E);return w=j(w,k),D.fromBytes(x,"recovered").recoverPublicKey(w).toBytes()}return Object.freeze({keygen:u,getPublicKey:f,getSharedSecret:h,utils:d,lengths:g,Point:r,sign:m,verify:y,recoverPublicKey:_,Signature:D,hash:n})}var Ni={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Id={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Ll=BigInt(2);function Td(r){let t=Ni.p,e=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%t,u=l*l*r%t,f=Q(u,e,t)*u%t,h=Q(f,e,t)*u%t,d=Q(h,Ll,t)*l%t,g=Q(d,o,t)*d%t,E=Q(g,s,t)*g%t,p=Q(E,a,t)*E%t,b=Q(p,c,t)*p%t,v=Q(b,a,t)*E%t,S=Q(v,e,t)*u%t,B=Q(S,i,t)*g%t,D=Q(B,n,t)*l%t,R=Q(D,Ll,t);if(!Ri.eql(Ri.sqr(R),r))throw new Error("Cannot find square root");return R}var Ri=ur(Ni.p,{sqrt:Td}),kd=Il(Ni,{Fp:Ri,endo:Id}),gr=Dl(kd,Fc);function Bl(r,t,e,n){let o=de.digest(e instanceof Uint8Array?e:e.subarray());if(Qn(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),gr.verify(t,s,r,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new Cr(String(s))});try{return n?.signal?.throwIfAborted(),gr.verify(t,o.digest,r,{prehash:!1,format:"der"})}catch(s){throw new Cr(String(s))}}var ao=class{type="secp256k1";raw;_key;constructor(t){this._key=Pl(t),this.raw=Cl(this._key)}toMultihash(){return kt.digest(or(this))}toCID(){return et.createV1(114,this.toMultihash())}toString(){return it.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:at(this.raw,t.raw)}verify(t,e,n){return Bl(this._key,e,t,n)}};function Ol(r){return new ao(r)}function Cl(r){return gr.Point.fromBytes(r).toBytes()}function Pl(r){try{return gr.Point.fromBytes(r),r}catch(t){throw new vn(String(t))}}function Rl(r){let{Type:t,Data:e}=tn.decode(r.digest),n=e??new Uint8Array;switch(t){case St.Ed25519:return pl(n);case St.secp256k1:return Ol(n);case St.ECDSA:return xc(n);default:throw new Br}}function or(r){return tn.encode({Type:St[r.type],Data:r.raw})}var Fi={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Nl={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Fl=new globalThis.TextEncoder;function Dd(r,t){let e=Fi[t],n=Nl[t];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(t,n*e);return n}function Ld(r,t,e){if(e.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Fi[t],o=Nl[t],s=r;for(;s.length>0;){let i=Fl.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 Ui(r,{size:t=32,utf8Buffer:e}={}){if(!Fi[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 Ld(r,t,e);r=Fl.encode(r)}return Dd(r,t)}var en={hash:r=>Number(Ui(r,{size:32})),hashV:(r,t)=>Bd(en.hash(r,t))};function Bd(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),Z(t,"base16")}var Mi=64,zt=class{fp;h;seed;constructor(t,e,n,o=2){if(o>Mi)throw new TypeError("Invalid Fingerprint Size");let s=e.hashV(t,n),i=wt(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?at(this.fp,t.fp):!1}};function Ue(r,t){return Math.floor(Math.random()*(t-r))+r}var Me=class{contents;constructor(t){this.contents=new Array(t).fill(null)}has(t){if(!(t instanceof zt))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof zt))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 zt))throw new TypeError("Invalid Fingerprint");let e=Ue(0,this.contents.length-1),n=this.contents[e];return this.contents[e]=t,n}remove(t){if(!(t instanceof zt))throw new TypeError("Invalid Fingerprint");let e=this.contents.findIndex(n=>t.equals(n));return e>-1?(this.contents[e]=null,!0):!1}};var Cd=500,rn=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??en,this.seed=t.seed??Ue(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=Z(t));let e=new zt(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 Me(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new Me(this.bucketSize)),this.buckets[n].add(e)||this.buckets[o].add(e))return this.count++,!0;let s=[n,o],i=s[Ue(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new Me(this.bucketSize));for(let a=0;a<Cd;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 Me(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(t){typeof t=="string"&&(t=Z(t));let e=new zt(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=Z(t));let e=new zt(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}},Pd={1:.5,2:.84,4:.95,8:.98};function Od(r=.001){return r>.002?2:r>1e-5?4:8}function Ul(r,t=.001){let e=Od(t),n=Pd[e],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),Mi);return{filterSize:o,bucketSize:e,fingerprintSize:s}}var co=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??en,this.seed=t.seed??Ue(0,Math.pow(2,10)),this.filterSeries=[new rn({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(t){if(typeof t=="string"&&(t=Z(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 rn({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=Z(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=Z(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 lo(r,t=.001,e){return new co({...Ul(r,t),...e??{}})}function uo(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 Tt(`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 fo=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",l=2**(8*o)-1;for(;;){let u=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let h=Number.parseInt(f,t);if(!Number.isNaN(h))return h});if(u===void 0)break;if(s*=t,s+=u,s>l||(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 Rd=45,Nd=15,ho=new fo;function Ml(r){if(!(r.length>Nd))return ho.new(r).parseWith(()=>ho.readIPv4Addr())}function zl(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Rd))return ho.new(r).parseWith(()=>ho.readIPv6Addr())}function br(r){return!!Ml(r)}function po(r){return!!zl(r)}var Kl=Ka(ql(),1),qd=["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"],Kd=qd.map(r=>new Kl.Netmask(r));function Wi(r){for(let t of Kd)if(t.contains(r))return!0;return!1}function Vd(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function Wd(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 Wi(o)}function jd(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function Gd(r){let t=r.split(":"),e=t[t.length-1];return Wi(e)}function Zd(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 Vl(r){if(br(r))return Wi(r);if(Vd(r))return Wd(r);if(jd(r))return Gd(r);if(po(r))return Zd(r)}function Wl(r){try{let t=uo(r);switch(t.type){case"ip4":case"ip6":return Vl(t.host)??!1;default:return t.host==="localhost"}}catch{return!1}}function Ht(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var go=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||(t-1&t)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},Er=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new go(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 go(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 ji=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function bo(r={}){return Yd(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 Yd(r,t){t=t??{};let e=t.onEnd,n=new Er,o,s,i,a=Ht(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((p,b)=>{s=v=>{s=null,n.push(v);try{p(r(n))}catch(S){b(S)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Ht()})}},l=p=>s!=null?s(p):(n.push(p),o),u=p=>(n=new Er,s!=null?s({error:p}):(n.push({error:p}),o)),f=p=>{if(i)return o;if(t?.objectMode!==!0&&p?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:p})},h=p=>i?o:(i=!0,p!=null?u(p):l({done:!0})),d=()=>(n=new Er,h(),{done:!0}),g=p=>(h(p),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:d,throw:g,push:f,end:h,get readableLength(){return n.size},onEmpty:async p=>{let b=p?.signal;if(b?.throwIfAborted(),n.isEmpty())return;let v,S;b!=null&&(v=new Promise((B,D)=>{S=()=>{D(new ji)},b.addEventListener("abort",S)}));try{await Promise.race([a.promise,v])}finally{S!=null&&b!=null&&b?.removeEventListener("abort",S)}}},e==null)return o;let E=o;return o={[Symbol.asyncIterator](){return this},next(){return E.next()},throw(p){return E.throw(p),e!=null&&(e(p),e=void 0),{done:!0}},return(){return E.return(),e!=null&&(e(),e=void 0),{done:!0}},push:f,end(p){return E.end(p),e!=null&&(e(p),e=void 0),o},get readableLength(){return E.readableLength},onEmpty:p=>E.onEmpty(p)},o}var Gi=class r extends Error{name="TimeoutError";constructor(t,e){super(t,e),Error.captureStackTrace?.(this,r)}},jl=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function Zi(r,t){let{milliseconds:e,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=t,a,c,u=new Promise((f,h)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(i?.aborted){h(jl(i));return}if(i&&(c=()=>{h(jl(i))},i.addEventListener("abort",c,{once:!0})),r.then(f,h),e===Number.POSITIVE_INFINITY)return;let d=new Gi;a=s.setTimeout.call(void 0,()=>{if(n){try{f(n())}catch(g){h(g)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?f():o instanceof Error?h(o):(d.message=o??`Promise timed out after ${e} milliseconds`,h(d))},e)}).finally(()=>{u.clear(),c&&i&&i.removeEventListener("abort",c)});return u.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},u}var Xd=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 Qd(r,t,e){let n,o=new Promise((s,i)=>{if(e={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...e},!(e.count>=0&&(e.count===Number.POSITIVE_INFINITY||Number.isInteger(e.count))))throw new TypeError("The `count` option should be at least 0 or more");e.signal?.throwIfAborted();let a=[t].flat(),c=[],{addListener:l,removeListener:u}=Xd(r),f=async(...d)=>{let g=e.multiArgs?d:d[0];if(e.filter)try{if(!await e.filter(g))return}catch(E){n(),i(E);return}c.push(g),e.count===c.length&&(n(),s(c))},h=(...d)=>{n(),i(e.rejectionMultiArgs?d:d[0])};n=()=>{for(let d of a)u(d,f);for(let d of e.rejectionEvents)a.includes(d)||u(d,h)};for(let d of a)l(d,f);for(let d of e.rejectionEvents)a.includes(d)||l(d,h);e.signal&&e.signal.addEventListener("abort",()=>{h(e.signal.reason)},{once:!0}),e.resolveImmediately&&s(c)});if(o.cancel=n,typeof e.timeout=="number"){let s=Zi(o,{milliseconds:e.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function yo(r,t,e){typeof e=="function"&&(e={filter:e}),e={...e,count:1,resolveImmediately:!1};let n=Qd(r,t,e),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function Yi(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 wo=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};function Jd(r){return r.reason}async function xo(r,t,e){if(t==null)return r;let n=e?.translateError??Jd;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 Eo=class{deferred;signal;constructor(t){this.signal=t,this.deferred=Ht(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Pt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function tp(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var vo=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=tp(),this.status="queued",this.fn=t,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(t){this.controller.abort(t)}onAbort(){this.recipients.reduce((e,n)=>e&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Pt),this.cleanup())}async join(t={}){let e=new Eo(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 xo(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 vr=class extends Vt{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=Yi(this.emitEmpty.bind(this),1),this.emitIdle=Yi(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 wo;let n=new vo(t,e);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(e).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(t=>{t.abort(new Pt)}),this.clear()}async onEmpty(t){this.size!==0&&await yo(this,"empty",t)}async onSizeLessThan(t,e){this.size<t||await yo(this,"next",{...e,filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await yo(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=bo({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),e.end(c)},o=c=>{c.detail!=null&&e.push(c.detail)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new Pt("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",s),this.addEventListener("idle",i),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),t?.signal?.removeEventListener("abort",a),n()}}};var yt=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},ce=class extends Error{static name="ValidationError";name="ValidationError"},_o=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},So=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function Qi(r){return t=>W(t,r)}function Ji(r){return t=>Z(t,r)}function _r(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function He(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(t)}function Gl(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=Z(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=He(n);return Ct([e,o],e.length+o.length)}function Zl(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=he.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=He(n);return Ct([e,o],e.length+o.length)}function ta(r){let t=r.subarray(0,r.length-2),e=r.subarray(r.length-2),n=W(t,"base32"),o=_r(e);return`${n}:${o}`}var ea=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 yt("Invalid byte value in IP address");t[n]=o}),t},Yl=function(r){let t=0;r=r.toString().trim();let e=r.split(":",8),n;for(n=0;n<e.length;n++){let s=br(e[n]),i;s&&(i=ea(e[n]),e[n]=W(i.subarray(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,W(i.subarray(2,4),"base16"))}if(e[0]==="")for(;e.length<8;)e.unshift("0");else if(e[e.length-1]==="")for(;e.length<8;)e.push("0");else if(e.length<8){for(n=0;n<e.length&&e[n]!=="";n++);let s=[n,1];for(n=9-e.length;n>0;n--)s.push("0");e.splice.apply(e,s)}let o=new Uint8Array(t+16);for(n=0;n<e.length;n++){e[n]===""&&(e[n]="0");let s=parseInt(e[n],16);if(isNaN(s)||s<0||s>65535)throw new yt("Invalid byte value in IP address");o[t++]=s>>8&255,o[t++]=s&255}return o},Xl=function(r){if(r.byteLength!==4)throw new yt("IPv4 address was incorrect length");let t=[];for(let e=0;e<r.byteLength;e++)t.push(r[e]);return t.join(".")},Ql=function(r){if(r.byteLength!==16)throw new yt("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 yt(`Invalid IPv6 address "${e}"`)}};function Jl(r){try{let t=new URL(`http://[${r}]`);return t.hostname.substring(1,t.hostname.length-1)}catch{throw new yt(`Invalid IPv6 address "${r}"`)}}var Xi=Object.values(Fr).map(r=>r.decoder),ep=(function(){let r=Xi[0].or(Xi[1]);return Xi.slice(2).forEach(t=>r=r.or(t)),r})();function tu(r){return ep.decode(r)}function eu(r){return t=>r.encoder.encode(t)}function rp(r){if(parseInt(r).toString()!==r)throw new ce("Value must be an integer")}function np(r){if(r<0)throw new ce("Value must be a positive integer, or zero")}function op(r){return t=>{if(t>r)throw new ce(`Value must be smaller than or equal to ${r}`)}}function sp(...r){return t=>{for(let e of r)e(t)}}var nn=sp(rp,np,op(65535));var mt=-1,ra=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 So(`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)}))}},le=new ra,wp=[{code:4,name:"ip4",size:32,valueToBytes:ea,bytesToValue:Xl,validate:r=>{if(!br(r))throw new ce(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:He,bytesToValue:_r,validate:nn},{code:273,name:"udp",size:16,valueToBytes:He,bytesToValue:_r,validate:nn},{code:33,name:"dccp",size:16,valueToBytes:He,bytesToValue:_r,validate:nn},{code:41,name:"ip6",size:128,valueToBytes:Yl,bytesToValue:Ql,stringToValue:Jl,validate:r=>{if(!po(r))throw new ce(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:mt},{code:43,name:"ipcidr",size:8,bytesToValue:Qi("base10"),valueToBytes:Ji("base10")},{code:53,name:"dns",size:mt},{code:54,name:"dns4",size:mt},{code:55,name:"dns6",size:mt},{code:56,name:"dnsaddr",size:mt},{code:132,name:"sctp",size:16,valueToBytes:He,bytesToValue:_r,validate:nn},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:mt,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:mt,bytesToValue:Qi("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Ji("base58btc")(r):et.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:ta,valueToBytes:Gl},{code:445,name:"onion3",size:296,bytesToValue:ta,valueToBytes:Zl},{code:446,name:"garlic64",size:mt},{code:447,name:"garlic32",size:mt},{code:448,name:"tls"},{code:449,name:"sni",size:mt},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:mt,bytesToValue:eu(Ss),valueToBytes:tu},{code:480,name:"http"},{code:481,name:"http-path",size:mt,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:mt}];wp.forEach(r=>{le.addProtocol(r)});function ru(r){let t=[],e=0;for(;e<r.length;){let n=Re(r,e),o=le.getProtocol(n),s=J(n),i=xp(o,r,e+s),a=0;i>0&&o.size===mt&&(a=J(i));let c=s+a+i,l={code:n,name:o.name,bytes:r.subarray(e,e+c)};if(i>0){let u=e+s+a,f=r.subarray(u,u+i);l.value=o.bytesToValue?.(f)??W(f)}t.push(l),e+=c}return t}function nu(r){let t=0,e=[];for(let n of r){if(n.bytes==null){let o=le.getProtocol(n.code),s=J(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??Z(n.value),a=i.byteLength,o.size===mt&&(c=J(a)));let l=new Uint8Array(s+c+a),u=0;pr(n.code,l,u),u+=s,i!=null&&(o.size===mt&&(pr(a,l,u),u+=c),l.set(i,u)),n.bytes=l}e.push(n.bytes),t+=n.bytes.byteLength}return Ct(e,t)}function ou(r){if(r.charAt(0)!=="/")throw new yt('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=le.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 yt(`Component ${o} was missing value`);e="value"}else if(e==="value"){let l={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new yt(`Component ${o} was missing value`);l.value=c.stringToValue?.(n)??n}t.push(l),n="",o="",e="protocol"}}}if(o!==""&&n!=="")throw new yt("Incomplete multiaddr");return t}function su(r){return`/${r.flatMap(t=>{if(t.value==null)return t.name;let e=le.getProtocol(t.code);if(e==null)throw new yt(`Unknown protocol code ${t.code}`);return[t.name,e.valueToString?.(t.value)??t.value]}).join("/")}`}function xp(r,t,e){return r.size==null||r.size===0?0:r.size>0?r.size/8:Re(t,e)}var Ep=Symbol.for("nodejs.util.inspect.custom"),pa=Symbol.for("@multiformats/multiaddr");function vp(r){if(r==null&&(r="/"),iu(r))return r.getComponents();if(r instanceof Uint8Array)return ru(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),ou(r);if(Array.isArray(r))return r;throw new yt("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Lo=class r{[pa]=!0;#t;#e;#r;constructor(t="/",e={}){this.#t=vp(t),e.validate!==!1&&_p(this)}get bytes(){return this.#r==null&&(this.#r=nu(this.#t)),this.#r}toString(){return this.#e==null&&(this.#e=su(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 _o(`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 at(this.bytes,t.bytes)}[Ep](){return`Multiaddr(${this.toString()})`}};function _p(r){r.getComponents().forEach(t=>{let e=le.getProtocol(t.code);t.value!=null&&e.validate?.(t.value)})}function iu(r){return!!r?.[pa]}function Bo(r){return new Lo(r)}var Co=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Ir=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Po=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},un=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Oo(r){return r[Symbol.asyncIterator]!=null}function au(r,t){if(r.byteLength>t)throw new Ir("Message length too long")}var No=r=>{let t=J(r),e=xt(t);return to(r,e),No.bytes=t,e};No.bytes=0;function Fo(r,t){t=t??{};let e=t.lengthEncoder??No,n=t?.maxDataLength??4194304;function*o(s){au(s,n);let i=e(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return Oo(r)?(async function*(){for await(let s of r)yield*o(s)})():(function*(){for(let s of r)yield*o(s)})()}Fo.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??No,n=t?.maxDataLength??4194304;return au(r,n),new ut(e(r.byteLength),r)};var qe;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(qe||(qe={}));var ma=r=>{let t=Re(r);return ma.bytes=J(t),t};ma.bytes=0;function fn(r,t){let e=new ut,n=qe.LENGTH,o=-1,s=t?.lengthDecoder??ma,i=t?.maxLengthLength??8,a=t?.maxDataLength??4194304;function*c(){for(;e.byteLength>0;){if(n===qe.LENGTH)try{if(o=s(e),o<0)throw new Co("Invalid message length");if(o>a)throw new Ir("Message length too long");let l=s.bytes;e.consume(l),t?.onLength!=null&&t.onLength(o),n=qe.DATA}catch(l){if(l instanceof RangeError){if(e.byteLength>i)throw new Po("Message length length too long");break}throw l}if(n===qe.DATA){if(e.byteLength<o)break;let l=e.sublist(0,o);e.consume(o),t?.onData!=null&&t.onData(l),yield l,n=qe.LENGTH}}}return Oo(r)?(async function*(){for await(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new un("Unexpected end of input")})():(function*(){for(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new un("Unexpected end of input")})()}fn.fromReader=(r,t)=>{let e=1,n=(async function*(){for(;;)try{let{done:s,value:i}=await r.next(e);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{e=1}})();return fn(n,{...t??{},onLength:s=>{e=s}})};var Uo=class extends vr{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};var ga=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 cu(r){let{name:t,metrics:e}=r,n;return e!=null?n=new ga({name:t,metrics:e}):n=new Map,n}function Ip(r){return r[Symbol.asyncIterator]!=null}function Tp(r){if(Ip(r))return(async()=>{for await(let t of r);})();for(let t of r);}var ba=Tp;function kp(r){let[t,e]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>t.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:t.next(),[e](){return this}}}var lu=kp;function Dp(r){return r[Symbol.asyncIterator]!=null}function Lp(r,t){let e=0;if(Dp(r))return(async function*(){for await(let c of r)yield t(c,e++)})();let n=lu(r),{value:o,done:s}=n.next();if(s===!0)return(function*(){})();let i=t(o,e++);if(typeof i.then=="function")return(async function*(){yield await i;for(let c of n)yield t(c,e++)})();let a=t;return(function*(){yield i;for(let c of n)yield a(c,e++)})()}var uu=Lp;function Bp(r){return r[Symbol.asyncIterator]!=null}function Cp(r,t){return Bp(r)?(async function*(){let e=0;if(!(t<1)){for await(let n of r)if(yield n,e++,e===t)return}})():(function*(){let e=0;if(!(t<1)){for(let n of r)if(yield n,e++,e===t)return}})()}var fu=Cp;var Mo=class extends Error{static name="AbortError";name="AbortError";constructor(t="The operation was aborted",...e){super(t,...e)}};async function Ke(r,t,e,n){let o=new Mo(n?.errorMessage);n?.errorCode!=null&&(o.code=n.errorCode);let s=n?.errorEvent??"error";return e?.aborted===!0?Promise.reject(o):new Promise((i,a)=>{function c(){wa(e,"abort",f),wa(r,t,l),wa(r,s,u)}let l=h=>{try{if(n?.filter?.(h)===!1)return}catch(d){c(),a(d);return}c(),i(h)},u=h=>{if(c(),h instanceof Error){a(h);return}a(h.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},f=()=>{c(),a(o)};ya(e,"abort",f),ya(r,t,l),ya(r,s,u)})}function ya(r,t,e){r!=null&&(hu(r)?r.addEventListener(t,e):r.addListener(t,e))}function wa(r,t,e){r!=null&&(hu(r)?r.removeEventListener(t,e):r.removeListener(t,e))}function hu(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var hn="/ipfs/bitswap/1.2.0";var tt;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(tt||(tt={}));var xa;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(xa||(xa={}));(function(r){r.codec=()=>mr(xa)})(tt||(tt={}));var Ve;(function(r){let t;r.codec=()=>(t==null&&(t=Xt((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.cid!=null&&s.cid.byteLength>0&&(i.uint32(10),i.bytes(s.cid)),s.priority!=null&&s.priority!==0&&(i.uint32(16),i.int32(s.priority)),s.cancel!=null&&(i.uint32(24),i.bool(s.cancel)),s.wantType!=null&&(i.uint32(32),tt.codec().encode(s.wantType,i)),s.sendDontHave!=null&&(i.uint32(40),i.bool(s.sendDontHave)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={cid:wt(0),priority:0},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.cid=s.bytes();break}case 2:{c.priority=s.int32();break}case 3:{c.cancel=s.bool();break}case 4:{c.wantType=tt.codec().decode(s);break}case 5:{c.sendDontHave=s.bool();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.cid`,value:s.bytes()};break}case 2:{yield{field:`${a}.priority`,value:s.int32()};break}case 3:{yield{field:`${a}.cancel`,value:s.bool()};break}case 4:{yield{field:`${a}.wantType`,value:tt.codec().decode(s)};break}case 5:{yield{field:`${a}.sendDontHave`,value:s.bool()};break}default:{s.skipType(u&7);break}}}})),t);function e(s){return Zt(s,r.codec())}r.encode=e;function n(s,i){return Gt(s,r.codec(),i)}r.decode=n;function o(s,i){return Yt(s,r.codec(),i)}r.stream=o})(Ve||(Ve={}));var dn;(function(r){let t;r.codec=()=>(t==null&&(t=Xt((s,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),s.entries!=null&&s.entries.length>0)for(let c of s.entries)i.uint32(10),Ve.codec().encode(c,i);s.full!=null&&(i.uint32(16),i.bool(s.full)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={entries:[]},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{if(a.limits?.entries!=null&&c.entries.length===a.limits.entries)throw new ae('Decode error - repeated field "entries" had too many elements');c.entries.push(Ve.codec().decode(s,s.uint32(),{limits:a.limits?.entries$}));break}case 2:{c.full=s.bool();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l={entries:0},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{if(c.limits?.entries!=null&&l.entries===c.limits.entries)throw new ae('Streaming decode error - repeated field "entries" had too many elements');for(let h of Ve.codec().stream(s,s.uint32(),`${a}.entries[]`,{limits:c.limits?.entries$}))yield{...h,index:l.entries};l.entries++;break}case 2:{yield{field:`${a}.full`,value:s.bool()};break}default:{s.skipType(f&7);break}}}})),t);function e(s){return Zt(s,r.codec())}r.encode=e;function n(s,i){return Gt(s,r.codec(),i)}r.decode=n;function o(s,i){return Yt(s,r.codec(),i)}r.stream=o})(dn||(dn={}));var We;(function(r){let t;r.codec=()=>(t==null&&(t=Xt((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.prefix!=null&&s.prefix.byteLength>0&&(i.uint32(10),i.bytes(s.prefix)),s.data!=null&&s.data.byteLength>0&&(i.uint32(18),i.bytes(s.data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={prefix:wt(0),data:wt(0)},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.prefix=s.bytes();break}case 2:{c.data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.prefix`,value:s.bytes()};break}case 2:{yield{field:`${a}.data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),t);function e(s){return Zt(s,r.codec())}r.encode=e;function n(s,i){return Gt(s,r.codec(),i)}r.decode=n;function o(s,i){return Yt(s,r.codec(),i)}r.stream=o})(We||(We={}));var Bt;(function(r){r.HaveBlock="HaveBlock",r.DoNotHaveBlock="DoNotHaveBlock"})(Bt||(Bt={}));var zo;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DoNotHaveBlock=1]="DoNotHaveBlock"})(zo||(zo={}));(function(r){r.codec=()=>mr(zo)})(Bt||(Bt={}));var je;(function(r){let t;r.codec=()=>(t==null&&(t=Xt((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.cid!=null&&s.cid.byteLength>0&&(i.uint32(10),i.bytes(s.cid)),s.type!=null&&zo[s.type]!==0&&(i.uint32(16),Bt.codec().encode(s.type,i)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={cid:wt(0),type:Bt.HaveBlock},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.cid=s.bytes();break}case 2:{c.type=Bt.codec().decode(s);break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.cid`,value:s.bytes()};break}case 2:{yield{field:`${a}.type`,value:Bt.codec().decode(s)};break}default:{s.skipType(u&7);break}}}})),t);function e(s){return Zt(s,r.codec())}r.encode=e;function n(s,i){return Gt(s,r.codec(),i)}r.decode=n;function o(s,i){return Yt(s,r.codec(),i)}r.stream=o})(je||(je={}));var Ge;(function(r){let t;r.codec=()=>(t==null&&(t=Xt((s,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),s.wantlist!=null&&(i.uint32(10),dn.codec().encode(s.wantlist,i)),s.blocks!=null&&s.blocks.length>0)for(let c of s.blocks)i.uint32(26),We.codec().encode(c,i);if(s.blockPresences!=null&&s.blockPresences.length>0)for(let c of s.blockPresences)i.uint32(34),je.codec().encode(c,i);s.pendingBytes!=null&&s.pendingBytes!==0&&(i.uint32(40),i.int32(s.pendingBytes)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={blocks:[],blockPresences:[],pendingBytes:0},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.wantlist=dn.codec().decode(s,s.uint32(),{limits:a.limits?.wantlist});break}case 3:{if(a.limits?.blocks!=null&&c.blocks.length===a.limits.blocks)throw new ae('Decode error - repeated field "blocks" had too many elements');c.blocks.push(We.codec().decode(s,s.uint32(),{limits:a.limits?.blocks$}));break}case 4:{if(a.limits?.blockPresences!=null&&c.blockPresences.length===a.limits.blockPresences)throw new ae('Decode error - repeated field "blockPresences" had too many elements');c.blockPresences.push(je.codec().decode(s,s.uint32(),{limits:a.limits?.blockPresences$}));break}case 5:{c.pendingBytes=s.int32();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l={blocks:0,blockPresences:0},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{yield*dn.codec().stream(s,s.uint32(),`${a}.wantlist`,{limits:c.limits?.wantlist});break}case 3:{if(c.limits?.blocks!=null&&l.blocks===c.limits.blocks)throw new ae('Streaming decode error - repeated field "blocks" had too many elements');for(let h of We.codec().stream(s,s.uint32(),`${a}.blocks[]`,{limits:c.limits?.blocks$}))yield{...h,index:l.blocks};l.blocks++;break}case 4:{if(c.limits?.blockPresences!=null&&l.blockPresences===c.limits.blockPresences)throw new ae('Streaming decode error - repeated field "blockPresences" had too many elements');for(let h of je.codec().stream(s,s.uint32(),`${a}.blockPresences[]`,{limits:c.limits?.blockPresences$}))yield{...h,index:l.blockPresences};l.blockPresences++;break}case 5:{yield{field:`${a}.pendingBytes`,value:s.int32()};break}default:{s.skipType(f&7);break}}}})),t);function e(s){return Zt(s,r.codec())}r.encode=e;function n(s,i){return Gt(s,r.codec(),i)}r.decode=n;function o(s,i){return Yt(s,r.codec(),i)}r.stream=o})(Ge||(Ge={}));function du(r,t){for(let[e,n]of t.wantlist.entries()){let o=r.wantlist.get(e);o!=null&&(o.priority>n.priority&&(n.priority=o.priority),n.cancel=n.cancel??o.cancel,n.wantType=n.wantType??o.wantType,n.sendDontHave=n.sendDontHave??o.sendDontHave),r.wantlist.set(e,n)}for(let[e,n]of t.blockPresences.entries())r.blockPresences.set(e,n);for(let[e,n]of t.blocks.entries())r.blocks.set(e,n);return t.full&&!r.full&&(r.full=!0),r}var Ho=class extends Error{static name="BlockTooLargeError";constructor(t="Block too large"){super(t),this.name="BlockTooLargeError"}};var Pp=4193648,Op=Pp+16;function*pu(r,t){let e=[...r.wantlist.values()],n=[...r.blockPresences.values()],o=[...r.blocks.values()],s=0,i=0,a=0,c=!1;for(;;){let l={wantlist:{full:r.full??!1,entries:[]},blockPresences:[],blocks:[],pendingBytes:0},u=Ge.encode(l).byteLength,{added:f,hasMore:h,newSize:d}=Ea(o,l.blocks,a,t,u,Rp);a+=f,u=d;let g=h;({added:f,hasMore:h,newSize:d}=Ea(n,l.blockPresences,i,t,u,Np)),i+=f,u=d;let E=h;if({added:f,hasMore:h,newSize:d}=Ea(e,l.wantlist.entries,s,t,u,Fp),s+=f,u=d,c=!g&&!E&&!h,c||(l.wantlist.full=!1),yield Ge.encode(l),c)break}}function Ea(r,t,e,n,o,s){let i=0,a=!1;for(let c=e;c<r.length;c++){let l=r[c],u=s(l);if(u>Op)throw new Ho("Cannot send block as after encoding it is over the max message size");let f=o+u;if(f>n){a=!0;break}t.push(l),i++,o=f}return{hasMore:a,added:i,newSize:o}}function Rp(r){return va(3,We.encode(r))}function Np(r){return va(4,je.encode(r))}function Fp(r){return va(1,Ve.encode(r))}function va(r,t){let e=J(r),n=J(t.byteLength);return e+n+t.byteLength}var $o=class extends Vt{log;libp2p;routing;protocols;running;maxInboundStreams;maxOutboundStreams;messageReceiveTimeout;messageSendTimeout;registrarIds;metrics;sendQueue;runOnLimitedConnections;maxOutgoingMessageSize;maxIncomingMessageSize;constructor(t,e={}){super(),this.log=t.logger.forComponent("helia:bitswap:network"),this.libp2p=t.libp2p,this.routing=t.routing,this.protocols=e.protocols??[hn],this.registrarIds=[],this.running=!1,this._onStream=this._onStream.bind(this),this.maxInboundStreams=e.maxInboundStreams??1024,this.maxOutboundStreams=e.maxOutboundStreams??1024,this.messageReceiveTimeout=e.messageReceiveTimeout??1e4,this.messageSendTimeout=e.messageSendTimeout??1e4,this.runOnLimitedConnections=e.runOnLimitedConnections??!1,this.maxIncomingMessageSize=e.maxIncomingMessageSize??4194304,this.maxOutgoingMessageSize=e.maxOutgoingMessageSize??e.maxIncomingMessageSize??4194304,this.metrics={blocksSent:t.metrics?.registerCounter("helia_bitswap_sent_blocks_total"),dataSent:t.metrics?.registerCounter("helia_bitswap_sent_data_bytes_total")},this.sendQueue=new Uo({concurrency:e.messageSendConcurrency??50,metrics:t.metrics,metricName:"helia_bitswap_message_send_queue"})}async start(){if(this.running)return;this.running=!0,await this.libp2p.handle(this.protocols,this._onStream,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnections});let t={onConnect:e=>{this.safeDispatchEvent("peer:connected",{detail:e})},onDisconnect:e=>{this.safeDispatchEvent("peer:disconnected",{detail:e})}};this.registrarIds=[];for(let e of this.protocols)this.registrarIds.push(await this.libp2p.register(e,t));this.libp2p.getConnections().forEach(e=>{this.safeDispatchEvent("peer:connected",{detail:e.remotePeer})})}async stop(){if(this.running=!1,await this.libp2p.unhandle(this.protocols),this.registrarIds!=null){for(let t of this.registrarIds)this.libp2p.unregister(t);this.registrarIds=[]}}_onStream(t,e){this.running&&Promise.resolve().then(async()=>{this.log("incoming new bitswap %s stream from %p",t.protocol,e.remotePeer);let n=()=>{t.status==="open"?t.abort(new In(`Incoming Bitswap stream timed out after ${this.messageReceiveTimeout}ms`)):this.log("stream aborted with status %s",t.status)},o=AbortSignal.timeout(this.messageReceiveTimeout);o.addEventListener("abort",n),await t.close({signal:o});let s=bo();t.addEventListener("message",i=>{s.push(i.data)}),t.addEventListener("remoteCloseWrite",()=>{s.end()}),t.addEventListener("close",i=>{i.error!=null&&s.end(i.error)});for await(let i of fn(s,{maxDataLength:this.maxIncomingMessageSize}))try{let a=Ge.decode(i);this.log("incoming new bitswap %s message from %p on stream",t.protocol,e.remotePeer,t.id),this.safeDispatchEvent("bitswap:message",{detail:{peer:e.remotePeer,message:a,connection:e}}),o.removeEventListener("abort",n),o=AbortSignal.timeout(this.messageReceiveTimeout),o.addEventListener("abort",n)}catch(a){this.log.error("error reading incoming bitswap message from %p on stream - %e",e.remotePeer,t.id,a),t.abort(a);break}}).catch(n=>{this.log.error("error handling incoming stream from %p - %e",e.remotePeer,n),t.abort(n)})}async*findProviders(t,e){e?.onProgress?.(new V("bitswap:find-providers",t));for await(let n of this.routing.findProviders(t,e)){if(!await this.libp2p.isDialable(n.multiaddrs,{runOnLimitedConnection:this.runOnLimitedConnections})){this.log("skipping peer %p as they are not dialable - %a",n.id,n.multiaddrs);continue}e?.onProgress?.(new V("bitswap:found-provider",{type:"bitswap",cid:t,provider:n,routing:n.routing})),yield n}}async findAndConnect(t,e){e?.providers!=null&&await Promise.all(e.providers.map(async n=>this.connectTo(n).catch(o=>{this.log.error("could not connect to supplied provider - %e",o)}))),await ba(uu(fu(this.findProviders(t,e),e?.maxProviders??3),async n=>this.connectTo(n.id,e))).catch(n=>{this.log.error(n)})}async sendMessage(t,e,n){if(!this.running)throw new Error("network isn't running");let o=this.sendQueue.queue.find(s=>t.equals(s.options.peerId)&&s.status==="queued");if(o!=null){o.options.message=du(o.options.message,e),await o.join(n);return}await this.sendQueue.add(async s=>{let i=s.message;if(i==null)throw new Tt("No message to send");this.log("sendMessage to %p",t),s.onProgress?.(new V("bitswap:send-wantlist",t));let a=await this.libp2p.dialProtocol(t,hn,s);await a.closeRead(s);try{for(let c of pu(i,this.maxOutgoingMessageSize))a.send(Fo.single(c))||await a.onDrain(s);await a.close(s)}catch(c){this.log.error("error sending message to %p - %e",t,c),s?.onProgress?.(new V("bitswap:send-wantlist:error",{peer:t,error:c})),a.abort(c)}this._updateSentStats(i.blocks)},{onProgress:n?.onProgress,peerId:t,signal:n?.signal??AbortSignal.timeout(this.messageSendTimeout),message:e})}async connectTo(t,e){if(!this.running)throw new Tn("Network isn't running");e?.onProgress?.(new V("bitswap:dial",t));let[n]=await Promise.all([this.libp2p.dial(t,e),Ke(this.libp2p,"peer:identify",e?.signal,{filter:o=>{if(!o.detail.peerId.equals(t))return!1;if(o.detail.protocols.includes(hn))return!0;throw new An(`${t} did not support ${hn}`)}})]);return n}_updateSentStats(t){let e=0;for(let n of t.values())e+=n.data.byteLength;this.metrics.dataSent?.increment(e),this.metrics.blocksSent?.increment(t.size)}};var gu=Symbol.for("nodejs.util.inspect.custom"),jp=114,pn=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()})`}[kn]=!0;toString(){return this.string==null&&(this.string=it.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return et.createV1(jp,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return at(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return at(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[gu](){return`PeerId(${this.toString()})`}},qo=class extends pn{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},Ko=class extends pn{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},Vo=class extends pn{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},Gp=2336,mn=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=kt.digest(Z(this.url))}[gu](){return`PeerId(${this.url})`}[kn]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return et.createV1(Gp,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=W(t)),t.toString()===this.toString())}};var Zp=114,bu=2336;function Yp(r){if(Qp(r))return new qo({multihash:r});if(Xp(r))try{let t=Rl(r);if(t.type==="Ed25519")return new Ko({multihash:r,publicKey:t});if(t.type==="secp256k1")return new Vo({multihash:r,publicKey:t})}catch{let e=W(r.digest);return new mn(new URL(e))}throw new Sn("Supplied PeerID Multihash is invalid")}function yu(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==Zp&&r.code!==bu)throw new _n("Supplied PeerID CID is invalid");if(r.code===bu){let t=W(r.multihash.digest);return new mn(new URL(t))}return Yp(r.multihash)}function Xp(r){return r.code===kt.code}function Qp(r){return r.code===de.code}function Wo(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}var gn=class{map;constructor(t){if(this.map=new Map,t!=null)for(let[e,n]of t.entries())this.map.set(e.toString(),{key:e,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(t){return this.map.delete(t.toString())}entries(){return Wo(this.map.entries(),t=>[t[1].key,t[1].value])}forEach(t){this.map.forEach((e,n)=>{t(e.value,e.key,this)})}get(t){return this.map.get(t.toString())?.value}has(t){return this.map.has(t.toString())}set(t,e){this.map.set(t.toString(),{key:t,value:e})}keys(){return Wo(this.map.values(),t=>t.key)}values(){return Wo(this.map.values(),t=>t.value)}get size(){return this.map.size}};var _a=class extends gn{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 bn(r){let{name:t,metrics:e}=r,n;return e!=null?n=new _a({name:t,metrics:e}):n=new gn,n}function Jp(r){return r[Symbol.asyncIterator]!=null}function tm(r){if(Jp(r))return(async()=>{let n=new Uint8Array(0);for await(let o of r)n=Ct([n,o],n.length+o.length);return n})();let t=[],e=0;for(let n of r)t.push(n),e+=n.byteLength;return Ct(t,e)}var wu=tm;var ue=class{full;pendingBytes;wantlist;blocks;blockPresences;constructor(t=!1,e=0){this.full=t,this.wantlist=new Map,this.blocks=new Map,this.blockPresences=new Map,this.pendingBytes=0}addWantlistEntry(t,e){let n=ee.encode(t.multihash.bytes);this.wantlist.set(n,e)}addBlockPresence(t,e){let n=ee.encode(t.multihash.bytes);this.blockPresences.set(n,e)}addBlock(t,e){let n=ee.encode(t.multihash.bytes);this.blocks.set(n,e)}};function em(r){let t=new Uint8Array(r.reduce((n,o)=>n+J(o),0)),e=0;for(let n of r)t=to(n,t,e),e+=J(n);return t}var xu=em;function Sa(r){return xu([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var jo=class{peerId;blockstore;network;wants;exchangeCount;bytesSent;bytesReceived;lastExchange;maxSizeReplaceHasWithBlock;log;doNotResendBlockWindow;maxWantListSize;constructor(t,e){this.peerId=t.peerId,this.blockstore=t.blockstore,this.network=t.network,this.wants=new Map,this.log=t.logger.forComponent(`helia:bitswap:ledger:${t.peerId}`),this.exchangeCount=0,this.bytesSent=0,this.bytesReceived=0,this.maxSizeReplaceHasWithBlock=e.maxSizeReplaceHasWithBlock??1024,this.doNotResendBlockWindow=e.doNotResendBlockWindow??5e3,this.maxWantListSize=e.maxWantListSize??1024}sentBytes(t){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesSent+=t}receivedBytes(t){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesReceived+=t}debtRatio(){return this.bytesSent/(this.bytesReceived+1)}removeExpiredWants(){this.wants.forEach((t,e)=>{t.expires!=null&&t.expires<Date.now()&&this.wants.delete(e)})}addWants(t){if(t==null)return;t.full===!0&&this.wants.forEach((n,o)=>{n.status==="want"&&this.wants.delete(o)});for(let n of t.entries){let o=et.decode(n.cid),s=W(o.multihash.bytes,"base64");if(n.cancel===!0)this.log("peer %p cancelled want of block for %c",this.peerId,o),this.wants.delete(s);else{n.wantType===tt.WantHave?this.log("peer %p wanted block presence for %c",this.peerId,o):this.log("peer %p wanted block for %c",this.peerId,o);let i=this.wants.get(s);if(i!=null){let a=i.status==="sent"||i.status==="sending",c=i.wantType===tt.WantHave&&(n.wantType==null||n.wantType===tt.WantBlock);a&&c&&(i.status="want"),i.priority=n.priority,i.wantType=n.wantType??tt.WantBlock,i.sendDontHave=n.sendDontHave??!1;continue}this.wants.set(s,{cid:o,priority:n.priority,wantType:n.wantType??tt.WantBlock,sendDontHave:n.sendDontHave??!1,status:"want",created:Date.now()})}}let e=[...this.wants.entries()].filter(([n,o])=>o.status==="want");e.length>this.maxWantListSize&&this.truncateWants(e)}truncateWants(t){t=t.sort((n,o)=>n[1].created<o[1].created?-1:o[1].created<n[1].created?1:0).sort((n,o)=>n[1].haveBlock===!1?-1:o[1].haveBlock===!1?1:0).sort((n,o)=>n[1].priority<o[1].priority?-1:o[1].priority<n[1].priority?1:0);let e=t.length-this.maxWantListSize;for(let n=0;n<e;n++)this.wants.delete(t[n][0])}getWants(){return[...this.wants.values()]}hasWant(t){let e=W(t.multihash.bytes,"base64");return this.wants.has(e)}async sendBlocksToPeer(t){let e=new ue,n=new Set;this.removeExpiredWants();let o=[...this.wants.entries()].filter(([s,i])=>i.status==="want");o.forEach(([s,i])=>{i.status="sending"});for(let[s,i]of o)try{let a=await wu(this.blockstore.get(i.cid,t));if(i.status!=="sending")continue;i.wantType===tt.WantHave?a.byteLength<this.maxSizeReplaceHasWithBlock?(this.log("sending have and block for %c",i.cid),n.add(s),e.addBlock(i.cid,{data:a,prefix:Sa(i.cid)})):(this.log("sending have for %c",i.cid),e.addBlockPresence(i.cid,{cid:i.cid.bytes,type:Bt.HaveBlock})):(this.log("sending block for %c",i.cid),n.add(s),e.addBlock(i.cid,{data:a,prefix:Sa(i.cid)})),i.status="sent",i.expires=Date.now()+this.doNotResendBlockWindow}catch(a){if(a.name!=="NotFoundError")throw a;if(i.status="want",i.haveBlock=!1,this.log("do not have block for %c",i.cid),!i.sendDontHave||i.sentDoNotHave===!0)continue;i.sentDoNotHave=!0,e.addBlockPresence(i.cid,{cid:i.cid.bytes,type:Bt.DoNotHaveBlock})}(e.blocks.size>0||e.blockPresences.size>0)&&(this.log("sending message"),await this.network.sendMessage(this.peerId,e,t),this.log("sent message"),this.sentBytes([...e.blocks.values()].reduce((s,i)=>s+i.data.byteLength,0)))}};var Go=class{blockstore;network;ledgerMap;maxSizeReplaceHasWithBlock;doNotResendBlockWindow;maxWantListSize;log;logger;constructor(t,e={}){this.blockstore=t.blockstore,this.network=t.network,this.maxSizeReplaceHasWithBlock=e.maxSizeReplaceHasWithBlock,this.doNotResendBlockWindow=e.doNotResendBlockWindow,this.maxWantListSize=e.maxWantListSize,this.log=t.logger.forComponent("helia:bitswap:peer-want-lists"),this.logger=t.logger,this.ledgerMap=bn({name:"helia_bitswap_ledger_map",metrics:t.metrics}),this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.connection.remotePeer,n.detail.message).catch(o=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.connection.remotePeer,o)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}ledgerForPeer(t){let e=this.ledgerMap.get(t);if(e!=null)return{peer:e.peerId,value:e.debtRatio(),sent:e.bytesSent,received:e.bytesReceived,exchanged:e.exchangeCount}}wantListForPeer(t){let e=this.ledgerMap.get(t);if(e!=null)return e.removeExpiredWants(),e.getWants()}peers(){return Array.from(this.ledgerMap.values()).map(t=>t.peerId)}async receiveMessage(t,e){let n=this.ledgerMap.get(t);n==null&&(n=new jo({peerId:t,blockstore:this.blockstore,network:this.network,logger:this.logger},{maxSizeReplaceHasWithBlock:this.maxSizeReplaceHasWithBlock,doNotResendBlockWindow:this.doNotResendBlockWindow,maxWantListSize:this.maxWantListSize}),this.ledgerMap.set(t,n)),n.receivedBytes(e.blocks?.reduce((o,s)=>o+s.data.byteLength,0)??0),n.removeExpiredWants(),n.addWants(e.wantlist),this.log("send blocks to peer"),await n.sendBlocksToPeer()}async receivedBlock(t,e){let n=[];for(let o of this.ledgerMap.values())o.hasWant(t)&&n.push(o);await Promise.all(n.map(async o=>o.sendBlocksToPeer(e)))}peerDisconnected(t){this.ledgerMap.delete(t)}};var om=Ka(vu(),1);var Tr;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Tr||(Tr={}));var Zo=class extends Error{static name="InsufficientProvidersError";constructor(t="Insufficient providers found"){super(t),this.name="InsufficientProvidersError"}};var Ze=class extends Vt{initialPeerSearchComplete;requests;logName;log;logger;minProviders;maxProviders;providers;evictionFilter;initialProviders;cidPeerFilterSize;constructor(t,e){super(),this.logName=e.name,this.logger=t.logger,this.log=t.logger.forComponent(this.logName),this.requests=new Map,this.minProviders=e.minProviders??1,this.maxProviders=e.maxProviders??5,this.cidPeerFilterSize=e.cidPeerFilterSize??100,this.providers=[],this.evictionFilter=lo(this.maxProviders),this.initialProviders=[...e.providers??[]]}async retrieve(t,e={}){let n=ee.encode(t.multihash.bytes),o=this.requests.get(n);if(o!=null)return this.log("join existing request for %c",t),o.observers++,o.promise;let s=Ht(),i={promise:s.promise,observers:1,queryFilter:lo(this.cidPeerFilterSize)};this.requests.set(n,i);let a=!1;this.initialPeerSearchComplete==null&&(a=!0,this.log=this.logger.forComponent(`${this.logName}:${t}`),this.initialPeerSearchComplete=this.findProviders(t,this.minProviders,e));let c=!1,l=new vr({concurrency:this.maxProviders});l.addEventListener("failure",h=>{this.log.error("error querying provider %s, evicting from session - %e",h.detail.job.options.provider,h.detail.error),this.evict(h.detail.job.options.provider)}),l.addEventListener("success",h=>{c=!0,s.resolve(h.detail.result)}),l.addEventListener("idle",()=>{if(c){this.log.trace("session idle, found block");return}if(e.signal?.aborted===!0){this.log.trace("session idle, signal aborted");return}Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",t);for(let h=0;h<this.minProviders&&this.providers.length!==0;h++){let d=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(d)}await this.findProviders(t,this.minProviders,e),this.log("found new providers re-retrieving %c",t),this.requests.delete(n),s.resolve(await this.retrieve(t,e))}).catch(h=>{this.log.error("could not find new providers for %c - %e",t,h),s.reject(h)})});let u=h=>{let d=this.toFilterKey(h.detail);i.queryFilter.has(d)||(i.queryFilter.add(d),this.emitFoundProviderProgressEvent(t,h.detail,e),l.add(async()=>this.queryProvider(t,h.detail,e),{provider:h.detail}).catch(g=>{e.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",t,g)}))};if(this.addEventListener("provider",u),a)try{await xo(this.initialPeerSearchComplete,e.signal),a&&this.log("found initial session peers for %c",t)}catch(h){throw a&&this.log("failed to find initial session peers for %c - %e",t,h),this.requests.delete(n),i.observers>1&&s.reject(h),h}Promise.all([...this.providers].filter(h=>{let d=this.toFilterKey(h),g=i.queryFilter.has(d);return g||i.queryFilter.add(this.toFilterKey(h)),!g}).map(async h=>l.add(async()=>this.queryProvider(t,h,e),{provider:h}))).catch(h=>{e.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",t,h)});let f=()=>{s.reject(new Pt(e.signal?.reason??"Session aborted")),l.abort()};e.signal?.addEventListener("abort",f);try{return await s.promise}finally{this.removeEventListener("provider",u),e.signal?.removeEventListener("abort",f),l.clear(),this.requests.delete(n)}}evict(t){this.evictionFilter.add(this.toFilterKey(t));let e=this.providers.findIndex(n=>this.equals(n,t));e!==-1&&this.providers.splice(e,1)}isEvicted(t){return this.evictionFilter.has(this.toFilterKey(t))}hasProvider(t){return!!(this.providers.find(e=>this.equals(e,t))!=null||this.isEvicted(t))}async addPeer(t,e){let n=await this.convertToProvider(t,"manually-added",e);n==null||this.hasProvider(n)||(this.providers.push(n),this.safeDispatchEvent("provider",{detail:n}))}async findProviders(t,e,n){let o=Ht(),s=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c - %d initial providers",e,this.maxProviders,t,this.initialProviders.length);let i=this,a=async function*(){for(;i.initialProviders.length>0;){let l=i.initialProviders.pop();if(l==null)continue;let u=await i.convertToProvider(l,"manual",n);u!=null&&(yield u)}},c=async function*(){yield*a(),yield*i.findNewProviders(t,n)};for await(let l of c()){if(this.providers.length===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(l)&&(this.log("found %d providers, %d in session",s,this.providers.length),this.providers.push(l),this.safeDispatchEvent("provider",{detail:l}),s++,this.providers.length===e&&(this.log("session is ready with %d peer(s), new peers present",this.providers.length),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers %d",this.providers.length);break}}if(this.log("found %d new session peers while trying to find %d, %d in session",s,e,this.providers.length),this.providers.length<e)throw new Zo(`Found ${s} of ${e} ${this.name} providers for ${t}, ${this.providers.length} in session after evictions`)}).catch(i=>{this.log.error("error searching routing for potential session peers for %c - %e",t,i),o.reject(i)}),o.promise}};var Aa=class extends Ze{name="bitswap-session";wantList;network;libp2p;constructor(t,e){super(t,{...e,name:"helia:bitswap:session"}),this.wantList=t.wantList,this.network=t.network,this.libp2p=t.libp2p}async queryProvider(t,e,n){this.log("sending WANT-BLOCK for %c to %p",t,e);let o=await this.wantList.wantSessionBlock(t,e.peerId,n);if(this.log("%p %s %c",e,o.has?"has":"does not have",t),o.has){if(o.block!=null)return o.block;throw new Error("Provider has block but did not send it to us")}throw new Error("Provider did not have block")}async*findNewProviders(t,e={}){for await(let n of this.network.findProviders(t,e))yield{peerId:n.id,routing:n.routing,toString:()=>`Bitswap(${n.id})`}}toFilterKey(t){return t.peerId.toMultihash().bytes}equals(t,e){return t.peerId.equals(e.peerId)}async convertToProvider(t,e,n){if(Xe(t))return{peerId:t,routing:e,toString:()=>`Bitswap(${t})`};if(await this.libp2p.isDialable(t)!==!1)try{let o=await this.libp2p.dial(t,n);return{peerId:o.remotePeer,routing:e,toString:()=>`Bitswap(${o.remotePeer})`}}catch{}}emitFoundProviderProgressEvent(t,e,n){n?.onProgress?.(new V("bitswap:found-provider",{type:"bitswap",cid:t,provider:{id:e.peerId,multiaddrs:[],routing:e.routing},routing:e.routing}))}};function _u(r,t){return new Aa(r,t)}var Yo=class{blocksReceived;duplicateBlocksReceived;dataReceived;duplicateDataReceived;constructor(t){this.blocksReceived=t.metrics?.registerMetricGroup("helia_bitswap_received_blocks"),this.duplicateBlocksReceived=t.metrics?.registerMetricGroup("helia_bitswap_duplicate_received_blocks"),this.dataReceived=t.metrics?.registerMetricGroup("helia_bitswap_data_received_bytes"),this.duplicateDataReceived=t.metrics?.registerMetricGroup("helia_bitswap_duplicate_data_received_bytes")}updateBlocksReceived(t=1,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.blocksReceived?.increment(n)}updateDuplicateBlocksReceived(t=1,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.duplicateBlocksReceived?.increment(n)}updateDataReceived(t,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.dataReceived?.increment(n)}updateDuplicateDataReceived(t,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.duplicateDataReceived?.increment(n)}};function cm(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let t=[];for(;r.length>0;){let e=Re(r);t.push(e),r=r.slice(J(e))}return t}var Su=cm;var Xo=class extends Vt{peers;wants;network;log;sendWantlistDebounce;sendMessagesTimeout;getHasher;sendingMessages;constructor(t,e={}){super(),this.peers=bn({name:"helia_bitswap_peers",metrics:t.metrics}),this.wants=cu({name:"helia_bitswap_wantlist",metrics:t.metrics}),this.network=t.network,this.sendWantlistDebounce=e.sendWantlistDebounce??10,this.log=t.logger.forComponent("helia:bitswap:wantlist"),this.getHasher=t.getHasher,this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.connection,n.detail.message).catch(o=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.connection.remotePeer,o)})}),this.network.addEventListener("peer:connected",n=>{this.peerConnected(n.detail).catch(o=>{this.log.error("error processing newly connected bitswap peer %p - %e",n.detail,o)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}async addEntry(t,e){let n=W(t.multihash.bytes,"base64"),o=this.wants.get(n);o==null&&(o={cid:t,priority:e.priority??1,wantType:e.wantType??tt.WantBlock,cancel:!1,sendDontHave:!0,onProgress:[]},this.wants.set(n,o)),e.onProgress!=null&&o.onProgress.push({onProgress:e.onProgress,signal:e.signal}),o.wantType===tt.WantHave&&e.wantType===tt.WantBlock&&(o.wantType=tt.WantBlock),await this.sendMessagesDebounced();try{return e.wantType===tt.WantBlock?(await Ke(this,"block",e?.signal,{filter:a=>at(t.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await Ke(this,"presence",e?.signal,{filter:i=>at(t.multihash.digest,i.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail}finally{e.signal?.aborted===!0&&(this.log("want for %c was aborted, cancelling want",t),o.cancel=!0,await this.sendMessagesDebounced())}}async sendMessagesDebounced(){await this.sendingMessages?.promise,clearTimeout(this.sendMessagesTimeout),this.sendMessagesTimeout=setTimeout(()=>{this.sendMessages().catch(t=>{this.log("error sending messages to peers - %e",t)})},this.sendWantlistDebounce)}async sendMessages(){this.sendingMessages=Ht(),await Promise.all([...this.peers.entries()].map(async([t,e])=>{let n=new Set,o=new ue;for(let[s,i]of this.wants.entries())e.has(s)||i.cancel||(n.add(s),o.addWantlistEntry(i.cid,{cid:i.cid.bytes,priority:i.priority,wantType:i.wantType,cancel:i.cancel,sendDontHave:i.sendDontHave}));if(o.wantlist.size!==0)try{await this.network.sendMessage(t,o,{onProgress:s=>{this.wants.forEach(({onProgress:i})=>{i.forEach(({onProgress:a})=>{a(s)})})}});for(let s of n)e.add(s)}catch(s){this.log.error("error sending full wantlist to new peer - %e",s)}})).catch(t=>{this.log.error("error sending messages - %e",t)});for(let[t,e]of this.wants)if(e.cancel){this.wants.delete(t);for(let n of this.peers.values())n.delete(t)}this.sendingMessages.resolve()}has(t){let e=W(t.multihash.bytes,"base64");return this.wants.has(e)}async wantSessionPresence(t,e,n={}){let o=new ue;return o.addWantlistEntry(t,{cid:t.bytes,sendDontHave:!0,wantType:tt.WantHave,priority:1}),await this.network.sendMessage(e,o,n),(await Ke(this,"presence",n.signal,{filter:i=>e.equals(i.detail.sender)&&at(t.multihash.digest,i.detail.cid.multihash.digest)})).detail}async wantBlock(t,e={}){return this.addEntry(t,{...e,wantType:tt.WantBlock})}async wantSessionBlock(t,e,n={}){let o=new ue;return o.addWantlistEntry(t,{cid:t.bytes,sendDontHave:!0,wantType:tt.WantBlock,priority:1}),await this.network.sendMessage(e,o,n),(await Ke(this,"presence",n.signal,{filter:i=>e.equals(i.detail.sender)&&at(t.multihash.digest,i.detail.cid.multihash.digest)})).detail}async receivedBlock(t,e){let n=W(t.multihash.bytes,"base64"),o=this.wants.get(n);o!=null&&(o.cancel=!0,await this.sendMessagesDebounced())}async receiveMessage(t,e){this.log("received message from %p with %d blocks",t.remotePeer,e.blocks.length);let n=!1;for(let o of e.blocks){if(o.prefix==null||o.data==null)continue;let s=Su(o.prefix),i=s[0],a=s[1],c=s[2],l=s[3],u=c===de.code?de:await this.getHasher(c);if(u==null){this.log.error("unknown hash algorithm",c);continue}let f=u.digest(o.data,{truncate:l});f.then!=null&&(f=await f);let h=et.create(i===0?0:1,a,f);this.log("received block from %p for %c",t.remotePeer,h),this.safeDispatchEvent("block",{detail:{sender:t.remotePeer,cid:h,block:o.data,connection:t}}),this.safeDispatchEvent("presence",{detail:{sender:t.remotePeer,cid:h,has:!0,block:o.data}});let d=W(h.multihash.bytes,"base64"),g=this.wants.get(d);g!=null&&(g.cancel=!0,n=!0)}for(let{cid:o,type:s}of e.blockPresences){let i=et.decode(o);this.log("received %s from %p for %c",s,t.remotePeer,i),this.safeDispatchEvent("presence",{detail:{sender:t.remotePeer,cid:i,has:s===Bt.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(t){let e=new Set,n=new ue(!0);for(let[o,s]of this.wants.entries())s.cancel||(e.add(o),n.addWantlistEntry(s.cid,{cid:s.cid.bytes,priority:1,wantType:tt.WantBlock,cancel:!1,sendDontHave:!1}));if(n.wantlist.size===0){this.peers.set(t,e);return}try{await this.network.sendMessage(t,n,{onProgress:o=>{this.wants.forEach(({onProgress:s})=>{s.forEach(({onProgress:i})=>{i(o)})})}}),this.peers.set(t,e)}catch(o){this.log.error("error sending full wantlist to new peer %p - %e",t,o)}}peerDisconnected(t){this.peers.delete(t)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}};var Qo=class{log;logger;stats;network;blockstore;peerWantLists;wantList;libp2p;constructor(t,e={}){this.logger=t.logger,this.log=t.logger.forComponent("helia:bitswap"),this.blockstore=t.blockstore,this.libp2p=t.libp2p,this.stats=new Yo(t),this.network=new $o(t,e),this.peerWantLists=new Go({...t,network:this.network},e),this.wantList=new Xo({...t,network:this.network},e)}createSession(t={}){return _u({wantList:this.wantList,network:this.network,logger:this.logger,libp2p:this.libp2p},t)}async want(t,e={}){let n=new AbortController,o=Va([n.signal,e.signal]);n.signal,this.network.findAndConnect(t,{...e,signal:o}).catch(s=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c - %e",t,s)});try{let s=await this.wantList.wantBlock(t,{...e,signal:o});return e.onProgress?.(new V("bitswap:block",{cid:t,sender:s.connection.remotePeer})),s.block}finally{n.abort(),o.clear()}}async notify(t,e={}){await Promise.all([this.peerWantLists.receivedBlock(t,e),this.wantList.receivedBlock(t,e)])}getWantlist(){return[...this.wantList.wants.values()].filter(t=>!t.cancel).map(t=>({cid:t.cid,priority:t.priority,wantType:t.wantType}))}getPeerWantlist(t){return this.peerWantLists.wantListForPeer(t)}async start(){this.wantList.start(),await this.network.start()}async stop(){this.wantList.stop(),await this.network.stop()}};var Au=(r,t={})=>new Qo(r,t);var Ia=class{name="bitswap";bitswap;started;constructor(t,e={}){this.bitswap=Au(t,e),this.started=!1}isStarted(){return this.started}async start(){await this.bitswap.start(),this.started=!0}async stop(){await this.bitswap.stop(),this.started=!1}async announce(t,e){await this.bitswap.notify(t,e)}async retrieve(t,e={}){return this.bitswap.want(t,{...e,onProgress:function(o){if(e?.onProgress!=null)if(e.onProgress(o),o.type==="connection:open"){if(!Xe(o.detail))return;e.onProgress(new V("helia:block-broker:connect",{broker:"bitswap",type:"connect",provider:o.detail,cid:t}))}else o.type==="connection:opened"?e.onProgress(new V("helia:block-broker:connected",{broker:"bitswap",type:"connected",provider:o.detail.remotePeer,address:o.detail.remoteAddr,cid:t})):o.type==="bitswap:send-wantlist"?e.onProgress(new V("helia:block-broker:request-block",{broker:"bitswap",type:"request-block",provider:o.detail,cid:t})):o.type==="bitswap:block"&&e.onProgress(new V("helia:block-broker:receive-block",{broker:"bitswap",type:"receive-block",provider:o.detail.sender,cid:t}))}})}createSession(t){let e=this.bitswap.createSession(t);return{name:"bitswap-session",addPeer:async(n,o)=>{await e.addPeer(n,o)},announce:async(n,o)=>{await this.bitswap.notify(n,o)},retrieve:async(n,o)=>e.retrieve(n,o)}}};function Iu(r={}){return t=>new Ia(t,r)}var lm=[6,53,56,54,55];function Tu(r){return Lu("sni",r)?.value}function ku(r){let t=Lu("tcp",r)?.value;return t==null?"":`:${t}`}function Lu(r,t){return t.find(e=>e.name===r)}function Du(r){return r.some(({code:t})=>t===448)}function qt(r,t){let e=Bu[r.name];if(e==null)throw new Error(`Can't interpret protocol ${r.name}`);let n=e(r,t);return r.code===41?`[${n}]`:n}var Bu={ip4:(r,t)=>r.value,ip6:(r,t)=>t.length===0?r.value:`[${r.value}]`,tcp:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`tcp://${qt(e,t)}:${r.value}`},udp:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`udp://${qt(e,t)}:${r.value}`},dnsaddr:(r,t)=>r.value,dns4:(r,t)=>r.value,dns6:(r,t)=>r.value,dns:(r,t)=>r.value,ipfs:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`${qt(e,t)}`},p2p:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`${qt(e,t)}`},http:(r,t)=>{let e=Du(t),n=Tu(t),o=ku(t);if(e&&n!=null)return`https://${n}${o}`;let s=e?"https://":"http://",i=t.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=qt(i,t);return a=a?.replace("tcp://",""),`${s}${a}`},"http-path":(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=qt(e,t),o=decodeURIComponent(r.value??"");return`${n}${o}`},tls:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return qt(e,t)},sni:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return qt(e,t)},https:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=qt(e,t);return n=n?.replace("tcp://",""),`https://${n}`},ws:(r,t)=>{let e=Du(t),n=Tu(t),o=ku(t);if(e&&n!=null)return`wss://${n}${o}`;let s=e?"wss://":"ws://",i=t.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=qt(i,t);return a=a?.replace("tcp://",""),`${s}${a}`},wss:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=qt(e,t);return n=n?.replace("tcp://",""),`wss://${n}`}};function Jo(r,t){let n=Bo(r).getComponents(),o=n.pop();if(o==null)throw new Error("Unexpected end of multiaddr");let s=Bu[o.name];if(s==null)throw new Error(`No interpreter found for ${o.name}`);let i=s(o,n)??"";return t?.assumeHttp!==!1&&lm.includes(o.code)&&(i=i.replace(/^.*:\/\//,""),o.value==="443"?i=`https://${i}`:i=`http://${i}`),(i.startsWith("http://")||i.startsWith("https://")||i.startsWith("ws://")||i.startsWith("wss://"))&&(i=new URL(i).toString(),i.endsWith("/")&&(i=i.substring(0,i.length-1))),i}var Cu="[a-fA-F\\d:]",Ie=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${Cu})|(?<=${Cu})(?=\\s|$))`:"",Kt="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",ct="[a-fA-F\\d]{1,4}",ts=`
2
+ "use strict";var HeliaBlockBrokers=(()=>{var Ju=Object.create;var xn=Object.defineProperty;var tf=Object.getOwnPropertyDescriptor;var ef=Object.getOwnPropertyNames;var rf=Object.getPrototypeOf,nf=Object.prototype.hasOwnProperty;var En=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),It=(r,t)=>{for(var e in t)xn(r,e,{get:t[e],enumerable:!0})},qa=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ef(t))!nf.call(r,o)&&o!==e&&xn(r,o,{get:()=>t[o],enumerable:!(n=tf(t,o))||n.enumerable});return r};var Ka=(r,t,e)=>(e=r!=null?Ju(rf(r)):{},qa(t||!r||!r.__esModule?xn(e,"default",{value:r,enumerable:!0}):e,r)),of=r=>qa(xn({},"__esModule",{value:!0}),r);var Hi=En(wr=>{"use strict";Object.defineProperty(wr,"__esModule",{value:!0});wr.Netmask4Impl=void 0;wr.ip2long=yr;wr.long2ip=Jt;function Jt(r){let t=(r&-16777216)>>>24,e=(r&255<<16)>>>16,n=(r&65280)>>>8,o=r&255;return[t,e,n,o].join(".")}var Fd=48,Ud=97,Md=65;function zd(r){let t=0,e=10,n="9",o=0;r.length>1&&r[o]==="0"&&(r[o+1]==="x"||r[o+1]==="X"?(o+=2,e=16):"0"<=r[o+1]&&r[o+1]<="9"&&(o++,e=8,n="7"));let s=o;for(;o<r.length;){if("0"<=r[o]&&r[o]<=n)t=t*e+(r.charCodeAt(o)-Fd)>>>0;else if(e===16)if("a"<=r[o]&&r[o]<="f")t=t*e+(10+r.charCodeAt(o)-Ud)>>>0;else if("A"<=r[o]&&r[o]<="F")t=t*e+(10+r.charCodeAt(o)-Md)>>>0;else break;else break;if(t>4294967295)throw new Error("too large");o++}if(o===s)throw new Error("empty octet");return[t,o]}function yr(r){let t=[];for(let e=0;e<=3&&r.length!==0;e++){if(e>0){if(r[0]!==".")throw new Error("Invalid IP");r=r.substring(1)}let[n,o]=zd(r);r=r.substring(o),t.push(n)}if(r.length!==0)throw new Error("Invalid IP");switch(t.length){case 1:if(t[0]>4294967295)throw new Error("Invalid IP");return t[0]>>>0;case 2:if(t[0]>255||t[1]>16777215)throw new Error("Invalid IP");return(t[0]<<24|t[1])>>>0;case 3:if(t[0]>255||t[1]>255||t[2]>65535)throw new Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2])>>>0;case 4:if(t[0]>255||t[1]>255||t[2]>255||t[3]>255)throw new Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2]<<8|t[3])>>>0;default:throw new Error("Invalid IP")}}var zi=class r{constructor(t,e){if(typeof t!="string")throw new Error("Missing `net' parameter");let n=e;if(!n){let o=t.split("/",2);t=o[0],n=o[1]}if(n||(n=32),typeof n=="string"&&n.indexOf(".")>-1){try{this.maskLong=yr(n)}catch{throw new Error("Invalid mask: "+n)}this.bitmask=NaN;for(let o=32;o>=0;o--)if(this.maskLong===4294967295<<32-o>>>0){this.bitmask=o;break}}else if(n||n===0)this.bitmask=parseInt(n,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(yr(t)&this.maskLong)>>>0}catch{throw new Error("Invalid net address: "+t)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+n);this.size=Math.pow(2,32-this.bitmask),this.base=Jt(this.netLong),this.mask=Jt(this.maskLong),this.hostmask=Jt(~this.maskLong),this.first=this.bitmask<=30?Jt(this.netLong+1):this.base,this.last=this.bitmask<=30?Jt(this.netLong+this.size-2):Jt(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?Jt(this.netLong+this.size-1):void 0}contains(t){return typeof t=="string"&&(t.indexOf("/")>0||t.split(".").length!==4)&&(t=new r(t)),t instanceof r?this.contains(t.base)&&this.contains(t.broadcast||t.last):(yr(t)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0}next(t=1){return new r(Jt(this.netLong+this.size*t),this.mask)}forEach(t){let e=yr(this.first),n=yr(this.last),o=0;for(;e<=n;)t(Jt(e),e,o),o++,e++}toString(){return this.base+"/"+this.bitmask}};wr.Netmask4Impl=zi});var $l=En(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0});xr.Netmask6Impl=void 0;xr.ip6bigint=qi;xr.bigint2ip6=ze;var Hd=Hi(),$i=(1n<<128n)-1n;function qi(r){let t=r.indexOf("%");t!==-1&&(r=r.substring(0,t));let e=r.lastIndexOf(":");if(e!==-1&&r.indexOf(".",e)!==-1){let n=r.substring(e+1),o=(0,Hd.ip2long)(n),s=r.substring(0,e+1)+"0:0";return Hl(s)&~0xffffffffn|BigInt(o)}return Hl(r)}function Hl(r){let t=r.indexOf("::"),e;if(t!==-1){let o=r.substring(0,t),s=r.substring(t+2),i=o===""?[]:o.split(":"),a=s===""?[]:s.split(":"),c=8-i.length-a.length;if(c<0)throw new Error("Invalid IPv6: too many groups");e=[...i,...Array(c).fill("0"),...a]}else e=r.split(":");if(e.length!==8)throw new Error("Invalid IPv6: expected 8 groups, got "+e.length);let n=0n;for(let o=0;o<8;o++){let s=e[o];if(s.length===0||s.length>4)throw new Error('Invalid IPv6: bad group "'+s+'"');let i=parseInt(s,16);if(isNaN(i)||i<0||i>65535)throw new Error('Invalid IPv6: bad group "'+s+'"');n=n<<16n|BigInt(i)}return n}function ze(r){if(r<0n||r>$i)throw new Error("Invalid IPv6 address value");let t=[];for(let i=0;i<8;i++)t.unshift(Number(r&0xffffn)),r>>=16n;let e=-1,n=0,o=-1,s=0;for(let i=0;i<8;i++)t[i]===0?o===-1?(o=i,s=1):s++:(s>n&&s>=2&&(e=o,n=s),o=-1,s=0);if(s>n&&s>=2&&(e=o,n=s),e!==-1&&e+n===8&&e>0)return t.slice(0,e).map(a=>a.toString(16)).join(":")+"::";if(e===0)return"::"+t.slice(n).map(a=>a.toString(16)).join(":");if(e>0){let i=t.slice(0,e).map(c=>c.toString(16)),a=t.slice(e+n).map(c=>c.toString(16));return i.join(":")+"::"+a.join(":")}else return t.map(i=>i.toString(16)).join(":")}var Ki=class r{constructor(t,e){if(typeof t!="string")throw new Error("Missing `net' parameter");let n=e;if(n==null){let o=t.indexOf("/");o!==-1?(n=parseInt(t.substring(o+1),10),t=t.substring(0,o)):n=128}if(isNaN(n)||n<0||n>128)throw new Error("Invalid mask for IPv6: "+n);this.bitmask=n,this.bitmask===0?this.maskBigint=0n:this.maskBigint=$i>>BigInt(128-this.bitmask)<<BigInt(128-this.bitmask);try{this.netBigint=qi(t)&this.maskBigint}catch{throw new Error("Invalid IPv6 net address: "+t)}this.size=Number(1n<<BigInt(128-this.bitmask)),this.base=ze(this.netBigint),this.mask=ze(this.maskBigint),this.hostmask=ze(~this.maskBigint&$i),this.first=this.base,this.last=ze(this.netBigint+(1n<<BigInt(128-this.bitmask))-1n),this.broadcast=void 0}contains(t){return typeof t=="string"&&t.indexOf("/")>0&&(t=new r(t)),t instanceof r?this.contains(t.base)&&this.contains(t.last):(qi(t)&this.maskBigint)===this.netBigint}next(t=1){let e=1n<<BigInt(128-this.bitmask);return new r(ze(this.netBigint+e*BigInt(t)),this.bitmask)}forEach(t){let e=this.netBigint,n=1n<<BigInt(128-this.bitmask),o=this.netBigint+n-1n,s=0;for(;e<=o;)t(ze(e),Number(e),s),s++,e++}toString(){return this.base+"/"+this.bitmask}};xr.Netmask6Impl=Ki});var ql=En(Se=>{"use strict";Object.defineProperty(Se,"__esModule",{value:!0});Se.long2ip=Se.ip2long=Se.Netmask=void 0;var mo=Hi();Object.defineProperty(Se,"ip2long",{enumerable:!0,get:function(){return mo.ip2long}});Object.defineProperty(Se,"long2ip",{enumerable:!0,get:function(){return mo.long2ip}});var $d=$l(),Vi=class r{constructor(t,e){if(typeof t!="string")throw new Error("Missing `net' parameter");(t.indexOf("/")!==-1?t.substring(0,t.indexOf("/")):t).indexOf(":")!==-1?this._impl=new $d.Netmask6Impl(t,e):this._impl=new mo.Netmask4Impl(t,e),this.base=this._impl.base,this.mask=this._impl.mask,this.hostmask=this._impl.hostmask,this.bitmask=this._impl.bitmask,this.size=this._impl.size,this.first=this._impl.first,this.last=this._impl.last,this.broadcast=this._impl.broadcast,this._impl instanceof mo.Netmask4Impl?(this.maskLong=this._impl.maskLong,this.netLong=this._impl.netLong):(this.maskLong=0,this.netLong=0)}contains(t){return typeof t=="string"&&(t.indexOf("/")>0?t=new r(t):t.indexOf(":")===-1&&t.split(".").length!==4&&(t=new r(t))),t instanceof r?this.contains(t.base)&&this.contains(t.broadcast||t.last):this._impl.contains(t)}next(t=1){let e=this._impl.next(t);return new r(e.base,e.bitmask)}forEach(t){this._impl.forEach(t)}toString(){return this._impl.toString()}};Se.Netmask=Vi});var vu=En((V2,Eu)=>{Eu.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var t=0,e=Object.create(null),n=Object.create(null);function o(s,i){e[s]=i,t++,t>=r&&(t=0,n=e,e=Object.create(null))}return{has:function(s){return e[s]!==void 0||n[s]!==void 0},remove:function(s){e[s]!==void 0&&(e[s]=void 0),n[s]!==void 0&&(n[s]=void 0)},get:function(s){var i=e[s];if(i!==void 0)return i;if((i=n[s])!==void 0)return o(s,i),i},set:function(s,i){e[s]!==void 0?e[s]=i:o(s,i)},clear:function(){e=Object.create(null),n=Object.create(null)}}}});var Cm={};It(Cm,{bitswap:()=>Iu,trustlessGateway:()=>Qu});var Pt=class extends Error{static name="AbortError";constructor(t="The operation was aborted"){super(t),this.name="AbortError"}};var Tt=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},vn=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}};var _n=class extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}},Sn=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}},An=class extends Error{static name="UnsupportedProtocolError";constructor(t="Unsupported protocol error"){super(t),this.name="UnsupportedProtocolError"}};var In=class extends Error{static name="TimeoutError";constructor(t="Timed out"){super(t),this.name="TimeoutError"}},Tn=class extends Error{static name="NotStartedError";constructor(t="Not started"){super(t),this.name="NotStartedError"}};var Br=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var kn=Symbol.for("@libp2p/peer-id");function Xe(r){return!!r?.[kn]}function sf(r){return typeof r?.handleEvent=="function"}function af(r){return(r!==!0&&r!==!1&&r?.once)??!1}var Vt=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){let o=af(n);super.addEventListener(t,i=>{if(o){let a=this.#t.get(i.type);a!=null&&(a=a.filter(({callback:c})=>c!==e),this.#t.set(i.type,a))}sf(e)?e.handleEvent(i):e(i)},n);let s=this.#t.get(t);s==null&&(s=[],this.#t.set(t,s)),s.push({callback:e,once:o})}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))}safeDispatchEvent(t,e={}){return this.dispatchEvent(new CustomEvent(t,e))}};function Va(r){let t=new globalThis.AbortController;function e(){let s=r.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();t.abort(s);for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",e)}for(let s of r){if(s?.aborted===!0){e();break}s?.addEventListener!=null&&s.addEventListener("abort",e)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",e)}let o=t.signal;return o.clear=n,o}var V=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var Cr=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},Dn=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var Wa={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new Dn("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 Ln=Wa;var ps={};It(ps,{base58btc:()=>it,base58flickr:()=>pf});var Km=new Uint8Array(0);function ja(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 te(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 Ga(r){return new TextEncoder().encode(r)}function Za(r){return new TextDecoder().decode(r)}function cf(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),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function f(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var E=0,p=0,b=0,v=g.length;b!==v&&g[b]===0;)b++,E++;for(var S=(v-b)*u+1>>>0,B=new Uint8Array(S);b!==v;){for(var D=g[b],R=0,C=S-1;(D!==0||R<p)&&C!==-1;C--,R++)D+=256*B[C]>>>0,B[C]=D%a>>>0,D=D/a>>>0;if(D!==0)throw new Error("Non-zero carry");p=R,b++}for(var T=S-p;T!==S&&B[T]===0;)T++;for(var N=c.repeat(E);T<S;++T)N+=r.charAt(B[T]);return N}function h(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var E=0;if(g[E]!==" "){for(var p=0,b=0;g[E]===c;)p++,E++;for(var v=(g.length-E)*l+1>>>0,S=new Uint8Array(v);g[E];){var B=e[g.charCodeAt(E)];if(B===255)return;for(var D=0,R=v-1;(B!==0||D<b)&&R!==-1;R--,D++)B+=a*S[R]>>>0,S[R]=B%256>>>0,B=B/256>>>0;if(B!==0)throw new Error("Non-zero carry");b=D,E++}if(g[E]!==" "){for(var C=v-b;C!==v&&S[C]===0;)C++;for(var T=new Uint8Array(p+(v-C)),N=p;C!==v;)T[N++]=S[C++];return T}}}function d(g){var E=h(g);if(E)return E;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:h,decode:d}}var lf=cf,uf=lf,Xa=uf;var us=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")}},fs=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 Qa(this,t)}},hs=class{decoders;constructor(t){this.decoders=t}or(t){return Qa(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 Qa(r,t){return new hs({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var ds=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 us(t,e,n),this.decoder=new fs(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Qe({name:r,prefix:t,encode:e,decode:n}){return new ds(r,t,e,n)}function fe({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=Xa(e,r);return Qe({prefix:t,name:r,encode:n,decode:s=>te(o(s))})}function ff(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 l=0;l<o;++l){let u=t[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<e|u,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 hf(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 df(r){let t={};for(let e=0;e<r.length;++e)t[r[e]]=e;return t}function rt({name:r,prefix:t,bitsPerChar:e,alphabet:n}){let o=df(n);return Qe({prefix:t,name:r,encode(s){return hf(s,n,e)},decode(s){return ff(s,o,e,r)}})}var it=fe({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),pf=fe({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ms={};It(ms,{base32:()=>he,base32hex:()=>yf,base32hexpad:()=>xf,base32hexpadupper:()=>Ef,base32hexupper:()=>wf,base32pad:()=>gf,base32padupper:()=>bf,base32upper:()=>mf,base32z:()=>vf});var he=rt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),mf=rt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),gf=rt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),bf=rt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),yf=rt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),wf=rt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),xf=rt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Ef=rt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),vf=rt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var gs={};It(gs,{base36:()=>Pr,base36upper:()=>_f});var Pr=fe({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),_f=fe({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Sf=ec,Ja=128,Af=127,If=~Af,Tf=Math.pow(2,31);function ec(r,t,e){t=t||[],e=e||0;for(var n=e;r>=Tf;)t[e++]=r&255|Ja,r/=128;for(;r&If;)t[e++]=r&255|Ja,r>>>=7;return t[e]=r|0,ec.bytes=e-n+1,t}var kf=bs,Df=128,tc=127;function bs(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw bs.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&tc)<<o:(i&tc)*Math.pow(2,o),o+=7}while(i>=Df);return bs.bytes=s-n,e}var Lf=Math.pow(2,7),Bf=Math.pow(2,14),Cf=Math.pow(2,21),Pf=Math.pow(2,28),Of=Math.pow(2,35),Rf=Math.pow(2,42),Nf=Math.pow(2,49),Ff=Math.pow(2,56),Uf=Math.pow(2,63),Mf=function(r){return r<Lf?1:r<Bf?2:r<Cf?3:r<Pf?4:r<Of?5:r<Rf?6:r<Nf?7:r<Ff?8:r<Uf?9:10},zf={encode:Sf,decode:kf,encodingLength:Mf},Hf=zf,Or=Hf;function Rr(r,t=0){return[Or.decode(r,t),Or.decode.bytes]}function Je(r,t,e=0){return Or.encode(r,t,e),t}function tr(r){return Or.encodingLength(r)}function rr(r,t){let e=t.byteLength,n=tr(r),o=n+tr(e),s=new Uint8Array(o+e);return Je(r,s,0),Je(e,s,n),s.set(t,o),new er(r,e,t,s)}function Cn(r){let t=te(r),[e,n]=Rr(t),[o,s]=Rr(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new er(e,o,i,t)}function rc(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&ja(r.bytes,e.bytes)}}var er=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};function nc(r,t){let{bytes:e,version:n}=r;return n===0?qf(e,ys(r),t??it.encoder):Kf(e,ys(r),t??he.encoder)}var oc=new WeakMap;function ys(r){let t=oc.get(r);if(t==null){let e=new Map;return oc.set(r,e),e}return t}var et=class r{code;version;multihash;bytes;"/";constructor(t,e,n,o){this.code=e,this.version=t,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:t,multihash:e}=this;if(t!==Nr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==Vf)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=rr(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&&rc(t.multihash,n.multihash)}toString(t){return nc(this,t)}toJSON(){return{"/":nc(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??sc(n,o,s.bytes))}else if(e[Wf]===!0){let{version:n,multihash:o,code:s}=e,i=Cn(o);return r.create(n,s,i)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==Nr)throw new Error(`Version 0 CID must use dag-pb (code: ${Nr}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=sc(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,Nr,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,o=te(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 er(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[f,h]=Rr(t.subarray(e));return e+=h,f},o=n(),s=Nr;if(o===18?(o=0,e=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=e,a=n(),c=n(),l=e+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(t,e){let[n,o]=$f(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 ys(s).set(n,t),s}};function $f(r,t){switch(r[0]){case"Q":{let e=t??it;return[it.prefix,e.decode(`${it.prefix}${r}`)]}case it.prefix:{let e=t??it;return[it.prefix,e.decode(r)]}case he.prefix:{let e=t??he;return[he.prefix,e.decode(r)]}case Pr.prefix:{let e=t??Pr;return[Pr.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 qf(r,t,e){let{prefix:n}=e;if(n!==it.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 Kf(r,t,e){let{prefix:n}=e,o=t.get(n);if(o==null){let s=e.encode(r);return t.set(n,s),s}else return o}var Nr=112,Vf=18;function sc(r,t,e){let n=tr(r),o=n+tr(t),s=new Uint8Array(o+e.byteLength);return Je(r,s,0),Je(t,s,n),s.set(e,o),s}var Wf=Symbol.for("@ipld/js-cid/CID");var ws={};It(ws,{identity:()=>kt});var ic=0,jf="identity",ac=te;function Gf(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 rr(ic,ac(r))}var kt={code:ic,name:jf,encode:ac,digest:Gf};function at(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}async function cc(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}function wt(r=0){return new Uint8Array(r)}function xt(r=0){return new Uint8Array(r)}function Ct(r,t){t==null&&(t=r.reduce((o,s)=>o+s.length,0));let e=xt(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}var uc=Symbol.for("@achingbrain/uint8arraylist");function lc(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 Pn(r){return!!r?.[uc]}var ut=class r{bufs;length;[uc]=!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(Pn(n)){e+=n.byteLength;for(let o of n.bufs)this.bufs.push(o)}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(Pn(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=lc(this.bufs,t);return e.buf[e.index]}set(t,e){let n=lc(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(Pn(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 Ct(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:Ct(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 l=t>=a&&t<c,u=e>a&&e<=c;if(l&&u){if(t===a&&e===c){n.push(i);break}let f=t-a;n.push(i.subarray(f,f+(e-t)));break}if(l){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(u){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(!Pn(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 f=0;f<s;f++)i[f]=-1;for(let f=0;f<o;f++)i[n[f]]=f;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let f=e;f<=c;f+=u){u=0;for(let h=l;h>=0;h--){let d=this.get(f+h);if(n[h]!==d){u=Math.max(1,h-a[d]);break}}if(u===0)return f}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=xt(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=wt(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=wt(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=wt(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=xt(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=wt(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=wt(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=wt(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=wt(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=wt(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(!at(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 xs={};It(xs,{base10:()=>Zf});var Zf=fe({prefix:"9",name:"base10",alphabet:"0123456789"});var Es={};It(Es,{base16:()=>Yf,base16upper:()=>Xf});var Yf=rt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Xf=rt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var vs={};It(vs,{base2:()=>Qf});var Qf=rt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var _s={};It(_s,{base256emoji:()=>nh});var fc=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}"),Jf=fc.reduce((r,t,e)=>(r[e]=t,r),[]),th=fc.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function eh(r){return r.reduce((t,e)=>(t+=Jf[e],t),"")}function rh(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=th[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var nh=Qe({prefix:"\u{1F680}",name:"base256emoji",encode:eh,decode:rh});var As={};It(As,{base64:()=>ee,base64pad:()=>oh,base64url:()=>Ss,base64urlpad:()=>sh});var ee=rt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),oh=rt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ss=rt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),sh=rt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Is={};It(Is,{base8:()=>ih});var ih=rt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Ts={};It(Ts,{identity:()=>ah});var ah=Qe({prefix:"\0",name:"identity",encode:r=>Za(r),decode:r=>Ga(r)});var k0=new TextEncoder,D0=new TextDecoder;var Ls={};It(Ls,{sha256:()=>de,sha512:()=>fh});var uh=20;function Ds({name:r,code:t,encode:e,minDigestLength:n,maxDigestLength:o}){return new ks(r,t,e,n,o)}var ks=class{name;code;encode;minDigestLength;maxDigestLength;constructor(t,e,n,o,s){this.name=t,this.code=e,this.encode=n,this.minDigestLength=o??uh,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?hc(n,this.code,e?.truncate):n.then(o=>hc(o,this.code,e?.truncate))}else throw Error("Unknown type, must be binary type")}};function hc(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 rr(t,r)}function pc(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var de=Ds({name:"sha2-256",code:18,encode:pc("SHA-256")}),fh=Ds({name:"sha2-512",code:19,encode:pc("SHA-512")});var Fr={...Ts,...vs,...Is,...xs,...Es,...ms,...gs,...ps,...As,..._s},H0={...Ls,...ws};function gc(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var mc=gc("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Bs=gc("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=xt(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),hh={utf8:mc,"utf-8":mc,hex:Fr.base16,latin1:Bs,ascii:Bs,binary:Bs,...Fr},On=hh;function Z(r,t="utf8"){let e=On[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function W(r,t="utf8"){let e=On[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var dh=parseInt("11111",2),Cs=parseInt("10000000",2),ph=parseInt("01111111",2),bc={0:Ur,1:Ur,2:mh,3:yh,4:wh,5:bh,6:gh,16:Ur,22:Ur,48:Ur};function Ps(r,t={offset:0}){let e=r[t.offset]&dh;if(t.offset++,bc[e]!=null)return bc[e](r,t);throw new Error("No decoder for tag "+e)}function Mr(r,t){let e=0;if((r[t.offset]&Cs)===Cs){let n=r[t.offset]&ph,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 Ur(r,t){Mr(r,t);let e=[];for(;!(t.offset>=r.byteLength);){let n=Ps(r,t);if(n===null)break;e.push(n)}return e}function mh(r,t){let e=Mr(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 gh(r,t){let e=Mr(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 l=r[t.offset];if(t.offset++,c.push(l&127),l<128){c.reverse();let u=0;for(let f=0;f<c.length;f++)u+=c[f]<<f*7;a+=`.${u}`,c=[]}}return a}function bh(r,t){return t.offset++,null}function yh(r,t){let e=Mr(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 wh(r,t){let e=Mr(r,t),n=r.subarray(t.offset,t.offset+e);return t.offset+=e,n}function xh(r){let t=r.toString(16);t.length%2===1&&(t="0"+t);let e=new ut;for(let n=0;n<t.length;n+=2)e.append(Uint8Array.from([parseInt(`${t[n]}${t[n+1]}`,16)]));return e}function Os(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let t=xh(r.byteLength);return new ut(Uint8Array.from([t.byteLength|Cs]),t)}function yc(r){let t=new ut,e=128;return(r.subarray()[0]&e)===e&&t.append(Uint8Array.from([0])),t.append(r),new ut(Uint8Array.from([2]),Os(t),t)}function wc(r){let t=Uint8Array.from([0]),e=new ut(t,r);return new ut(Uint8Array.from([3]),Os(e),e)}function Rn(r,t=48){let e=new ut;for(let n of r)e.append(n);return new ut(Uint8Array.from([t]),Os(e),e)}var Eh=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),vh=Uint8Array.from([6,5,43,129,4,0,34]),_h=Uint8Array.from([6,5,43,129,4,0,35]),Sh={ext:!0,kty:"EC",crv:"P-256"},Ah={ext:!0,kty:"EC",crv:"P-384"},Ih={ext:!0,kty:"EC",crv:"P-521"},Rs=32,Ns=48,Fs=66;function xc(r){let t=Ps(r);return Ec(t)}function Ec(r){let t=r[1][1][0],e=1,n,o;if(t.byteLength===Rs*2+1)return n=W(t.subarray(e,e+Rs),"base64url"),o=W(t.subarray(e+Rs),"base64url"),new nr({...Sh,key_ops:["verify"],x:n,y:o});if(t.byteLength===Ns*2+1)return n=W(t.subarray(e,e+Ns),"base64url"),o=W(t.subarray(e+Ns),"base64url"),new nr({...Ah,key_ops:["verify"],x:n,y:o});if(t.byteLength===Fs*2+1)return n=W(t.subarray(e,e+Fs),"base64url"),o=W(t.subarray(e+Fs),"base64url"),new nr({...Ih,key_ops:["verify"],x:n,y:o});throw new Tt(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function vc(r){return Rn([yc(Uint8Array.from([1])),Rn([Th(r.crv)],160),Rn([wc(new ut(Uint8Array.from([4]),Z(r.x??"","base64url"),Z(r.y??"","base64url")))],161)]).subarray()}function Th(r){if(r==="P-256")return Eh;if(r==="P-384")return vh;if(r==="P-521")return _h;throw new Tt(`Invalid curve ${r}`)}var nr=class{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=vc(this.jwk)),this._raw}toMultihash(){return kt.digest(or(this))}toCID(){return et.createV1(114,this.toMultihash())}toString(){return it.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:at(this.raw,t.raw)}async verify(t,e,n){return cc(this.jwk,e,t,n)}};function Us(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}function pe(r,t=""){if(typeof r!="number"){let e=t&&`"${t}" `;throw new TypeError(`${e}expected number, got ${typeof r}`)}if(!Number.isSafeInteger(r)||r<0){let e=t&&`"${t}" `;throw new RangeError(`${e}expected integer >= 0, got ${r}`)}}function Dt(r,t,e=""){let n=Us(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}`,l=i+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(l):new TypeError(l)}return r}function Nn(r){if(typeof r!="function"||typeof r.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(pe(r.outputLen),pe(r.blockLen),r.outputLen<1)throw new Error('"outputLen" must be >= 1');if(r.blockLen<1)throw new Error('"blockLen" must be >= 1')}function sr(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 Fn(r,t){Dt(r,void 0,"digestInto() output");let e=t.outputLen;if(r.length<e)throw new RangeError('"digestInto() output" expected to be of length >='+e)}function ne(...r){for(let t=0;t<r.length;t++)r[t].fill(0)}function Un(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Ot(r,t){return r<<32-t|r>>>t}var Sc=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",kh=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function Mn(r){if(Dt(r),Sc)return r.toHex();let t="";for(let e=0;e<r.length;e++)t+=kh[r[e]];return t}var re={_0:48,_9:57,A:65,F:70,a:97,f:102};function _c(r){if(r>=re._0&&r<=re._9)return r-re._0;if(r>=re.A&&r<=re.F)return r-(re.A-10);if(r>=re.a&&r<=re.f)return r-(re.a-10)}function zr(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);if(Sc)try{return Uint8Array.fromHex(r)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}let t=r.length,e=t/2;if(t%2)throw new RangeError("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=_c(r.charCodeAt(s)),a=_c(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function Ms(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];Dt(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let s=r[n];e.set(s,o),o+=s.length}return e}function zs(r,t={}){let e=(o,s)=>r(s).update(o).digest(),n=r(void 0);return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.canXOF=n.canXOF,e.create=o=>r(o),Object.assign(e,t),Object.freeze(e)}function Ac(r=32){pe(r,"bytesLength");let t=typeof globalThis=="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(r>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${r}`);return t.getRandomValues(new Uint8Array(r))}var Hs=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function Ic(r,t,e){return r&t^~r&e}function Tc(r,t,e){return r&t^r&e^t&e}var Hr=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(t,e,n,o){this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(t),this.view=Un(this.buffer)}update(t){sr(this),Dt(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=Un(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){sr(this),Fn(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;e[i++]=128,ne(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let f=i;f<o;f++)e[f]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=Un(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<l;f++)a.setUint32(4*f,u[f],s)}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){t||=new this.constructor,t.set(...this.get());let{blockLen:e,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return t.destroyed=i,t.finished=s,t.length=o,t.pos=a,o%e&&t.buffer.set(n),t}clone(){return this._cloneInto()}},oe=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var gt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var zn=BigInt(4294967295),kc=BigInt(32);function Dh(r,t=!1){return t?{h:Number(r&zn),l:Number(r>>kc&zn)}:{h:Number(r>>kc&zn)|0,l:Number(r&zn)|0}}function Dc(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}=Dh(r[s],t);[n[s],o[s]]=[i,a]}return[n,o]}var $s=(r,t,e)=>r>>>e,qs=(r,t,e)=>r<<32-e|t>>>e,ke=(r,t,e)=>r>>>e|t<<32-e,De=(r,t,e)=>r<<32-e|t>>>e,$r=(r,t,e)=>r<<64-e|t>>>e-32,qr=(r,t,e)=>r>>>e-32|t<<64-e;function Wt(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var Lc=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),Bc=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,Cc=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),Pc=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,Oc=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),Rc=(r,t,e,n,o,s)=>t+e+n+o+s+(r/2**32|0)|0;var Bh=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]),me=new Uint32Array(64),Ks=class extends Hr{constructor(t){super(64,t,8,!1)}get(){let{A:t,B:e,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[t,e,n,o,s,i,a,c]}set(t,e,n,o,s,i,a,c){this.A=t|0,this.B=e|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,e){for(let f=0;f<16;f++,e+=4)me[f]=t.getUint32(e,!1);for(let f=16;f<64;f++){let h=me[f-15],d=me[f-2],g=Ot(h,7)^Ot(h,18)^h>>>3,E=Ot(d,17)^Ot(d,19)^d>>>10;me[f]=E+me[f-7]+g+me[f-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){let h=Ot(a,6)^Ot(a,11)^Ot(a,25),d=u+h+Ic(a,c,l)+Bh[f]+me[f]|0,E=(Ot(n,2)^Ot(n,13)^Ot(n,22))+Tc(n,o,s)|0;u=l,l=c,c=a,a=i+d|0,i=s,s=o,o=n,n=d+E|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,o,s,i,a,c,l,u)}roundClean(){ne(me)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),ne(this.buffer)}},Vs=class extends Ks{A=oe[0]|0;B=oe[1]|0;C=oe[2]|0;D=oe[3]|0;E=oe[4]|0;F=oe[5]|0;G=oe[6]|0;H=oe[7]|0;constructor(){super(32)}};var Nc=Dc(["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))),Ch=Nc[0],Ph=Nc[1],ge=new Uint32Array(80),be=new Uint32Array(80),Ws=class extends Hr{constructor(t){super(128,t,16,!1)}get(){let{Ah:t,Al:e,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:l,El:u,Fh:f,Fl:h,Gh:d,Gl:g,Hh:E,Hl:p}=this;return[t,e,n,o,s,i,a,c,l,u,f,h,d,g,E,p]}set(t,e,n,o,s,i,a,c,l,u,f,h,d,g,E,p){this.Ah=t|0,this.Al=e|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=f|0,this.Fl=h|0,this.Gh=d|0,this.Gl=g|0,this.Hh=E|0,this.Hl=p|0}process(t,e){for(let S=0;S<16;S++,e+=4)ge[S]=t.getUint32(e),be[S]=t.getUint32(e+=4);for(let S=16;S<80;S++){let B=ge[S-15]|0,D=be[S-15]|0,R=ke(B,D,1)^ke(B,D,8)^$s(B,D,7),C=De(B,D,1)^De(B,D,8)^qs(B,D,7),T=ge[S-2]|0,N=be[S-2]|0,j=ke(T,N,19)^$r(T,N,61)^$s(T,N,6),F=De(T,N,19)^qr(T,N,61)^qs(T,N,6),m=Cc(C,F,be[S-7],be[S-16]),y=Pc(m,R,j,ge[S-7],ge[S-16]);ge[S]=y|0,be[S]=m|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:f,El:h,Fh:d,Fl:g,Gh:E,Gl:p,Hh:b,Hl:v}=this;for(let S=0;S<80;S++){let B=ke(f,h,14)^ke(f,h,18)^$r(f,h,41),D=De(f,h,14)^De(f,h,18)^qr(f,h,41),R=f&d^~f&E,C=h&g^~h&p,T=Oc(v,D,C,Ph[S],be[S]),N=Rc(T,b,B,R,Ch[S],ge[S]),j=T|0,F=ke(n,o,28)^$r(n,o,34)^$r(n,o,39),m=De(n,o,28)^qr(n,o,34)^qr(n,o,39),y=n&s^n&a^s&a,_=o&i^o&c^i&c;b=E|0,v=p|0,E=d|0,p=g|0,d=f|0,g=h|0,{h:f,l:h}=Wt(l|0,u|0,N|0,j|0),l=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let x=Lc(j,m,_);n=Bc(x,N,F,y),o=x|0}({h:n,l:o}=Wt(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=Wt(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=Wt(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=Wt(this.Dh|0,this.Dl|0,l|0,u|0),{h:f,l:h}=Wt(this.Eh|0,this.El|0,f|0,h|0),{h:d,l:g}=Wt(this.Fh|0,this.Fl|0,d|0,g|0),{h:E,l:p}=Wt(this.Gh|0,this.Gl|0,E|0,p|0),{h:b,l:v}=Wt(this.Hh|0,this.Hl|0,b|0,v|0),this.set(n,o,s,i,a,c,l,u,f,h,d,g,E,p,b,v)}roundClean(){ne(ge,be)}destroy(){this.destroyed=!0,ne(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},js=class extends Ws{Ah=gt[0]|0;Al=gt[1]|0;Bh=gt[2]|0;Bl=gt[3]|0;Ch=gt[4]|0;Cl=gt[5]|0;Dh=gt[6]|0;Dl=gt[7]|0;Eh=gt[8]|0;El=gt[9]|0;Fh=gt[10]|0;Fl=gt[11]|0;Gh=gt[12]|0;Gl=gt[13]|0;Hh=gt[14]|0;Hl=gt[15]|0;constructor(){super(64)}};var Fc=zs(()=>new Vs,Hs(1));var Hn=zs(()=>new js,Hs(3));var H=(r,t,e)=>Dt(r,t,e),Zs=pe,ir=Mn,ft=(...r)=>Ms(...r),ar=r=>zr(r),Le=Us,Kr=r=>Ac(r),qn=BigInt(0),Gs=BigInt(1);function Rt(r,t=""){if(typeof r!="boolean"){let e=t&&`"${t}" `;throw new TypeError(e+"expected boolean, got type="+typeof r)}return r}function Kn(r){if(typeof r=="bigint"){if(!$n(r))throw new RangeError("positive bigint expected, got "+r)}else Zs(r);return r}function Nt(r,t=""){if(typeof r!="number"){let e=t&&`"${t}" `;throw new TypeError(e+"expected number, got type="+typeof r)}if(!Number.isSafeInteger(r)){let e=t&&`"${t}" `;throw new RangeError(e+"expected safe integer, got "+r)}}function Vr(r){let t=Kn(r).toString(16);return t.length&1?"0"+t:t}function Uc(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);return r===""?qn:BigInt("0x"+r)}function Be(r){return Uc(Mn(r))}function jt(r){return Uc(Mn(Wr(Dt(r)).reverse()))}function Vn(r,t){if(pe(t),t===0)throw new RangeError("zero length");r=Kn(r);let e=r.toString(16);if(e.length>t*2)throw new RangeError("number too large");return zr(e.padStart(t*2,"0"))}function Ys(r,t){return Vn(r,t).reverse()}function Mc(r,t){if(r=H(r),t=H(t),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 Wr(r){return Uint8Array.from(H(r))}function Wn(r){if(typeof r!="string")throw new TypeError("ascii string expected, got "+typeof r);return Uint8Array.from(r,(t,e)=>{let n=t.charCodeAt(0);if(t.length!==1||n>127)throw new RangeError(`string contains non-ASCII character "${r[e]}" with code ${n} at position ${e}`);return n})}var $n=r=>typeof r=="bigint"&&qn<=r;function Oh(r,t,e){return $n(r)&&$n(t)&&$n(e)&&t<=r&&r<e}function cr(r,t,e,n){if(!Oh(t,e,n))throw new RangeError("expected valid "+r+": "+e+" <= n < "+n+", got "+t)}function lr(r){if(r<qn)throw new Error("expected non-negative bigint, got "+r);let t;for(t=0;r>qn;r>>=Gs,t+=1);return t}var jr=r=>(Gs<<BigInt(r))-Gs;function zc(r,t,e){if(pe(r,"hashLen"),pe(t,"qByteLen"),typeof e!="function")throw new TypeError("hmacFn must be a function");let n=p=>new Uint8Array(p),o=Uint8Array.of(),s=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(r),l=n(r),u=0,f=()=>{c.fill(1),l.fill(0),u=0},h=(...p)=>e(l,ft(c,...p)),d=(p=o)=>{l=h(s,p),c=h(),p.length!==0&&(l=h(i,p),c=h())},g=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let p=0,b=[];for(;p<t;){c=h();let v=c.slice();b.push(v),p+=c.length}return ft(...b)};return(p,b)=>{f(),d(p);let v;for(;(v=b(g()))===void 0;)d();return f(),v}}function Ft(r,t={},e={}){if(Object.prototype.toString.call(r)!=="[object Object]")throw new TypeError("expected valid options object");function n(s,i,a){if(!a&&i!=="function"&&!Object.hasOwn(r,s))throw new TypeError(`param "${s}" is invalid: expected own property`);let c=r[s];if(a&&c===void 0)return;let l=typeof c;if(l!==i||c===null)throw new TypeError(`param "${s}" is invalid: expected ${i}, got ${l}`)}let o=(s,i)=>Object.entries(s).forEach(([a,c])=>n(a,c,i));o(t,!1),o(e,!0)}var Xs=()=>{throw new Error("not implemented")};var bt=BigInt(0),nt=BigInt(1),Ce=BigInt(2),Kc=BigInt(3),Vc=BigInt(4),Wc=BigInt(5),Rh=BigInt(7),jc=BigInt(8),Nh=BigInt(9),Gc=BigInt(16);function st(r,t){if(t<=bt)throw new Error("mod: expected positive modulus, got "+t);let e=r%t;return e>=bt?e:t+e}function Q(r,t,e){if(t<bt)throw new Error("pow2: expected non-negative exponent, got "+t);let n=r;for(;t-- >bt;)n*=n,n%=e;return n}function Hc(r,t){if(r===bt)throw new Error("invert: expected non-zero number");if(t<=bt)throw new Error("invert: expected positive modulus, got "+t);let e=st(r,t),n=t,o=bt,s=nt,i=nt,a=bt;for(;e!==bt;){let l=n/e,u=n-e*l,f=o-i*l,h=s-a*l;n=e,e=u,o=i,s=a,i=f,a=h}if(n!==nt)throw new Error("invert: does not exist");return st(o,t)}function Qs(r,t,e){let n=r;if(!n.eql(n.sqr(t),e))throw new Error("Cannot find square root")}function Zc(r,t){let e=r,n=(e.ORDER+nt)/Vc,o=e.pow(t,n);return Qs(e,o,t),o}function Fh(r,t){let e=r,n=(e.ORDER-Wc)/jc,o=e.mul(t,Ce),s=e.pow(o,n),i=e.mul(t,s),a=e.mul(e.mul(i,Ce),s),c=e.mul(i,e.sub(a,e.ONE));return Qs(e,c,t),c}function Uh(r){let t=ur(r),e=Yc(r),n=e(t,t.neg(t.ONE)),o=e(t,n),s=e(t,t.neg(n)),i=(r+Rh)/Gc;return((a,c)=>{let l=a,u=l.pow(c,i),f=l.mul(u,n),h=l.mul(u,o),d=l.mul(u,s),g=l.eql(l.sqr(f),c),E=l.eql(l.sqr(h),c);u=l.cmov(u,f,g),f=l.cmov(d,h,E);let p=l.eql(l.sqr(f),c),b=l.cmov(u,f,p);return Qs(l,b,c),b})}function Yc(r){if(r<Kc)throw new Error("sqrt is not defined for small field");let t=r-nt,e=0;for(;t%Ce===bt;)t/=Ce,e++;let n=Ce,o=ur(r);for(;$c(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(e===1)return Zc;let s=o.pow(n,t),i=(t+nt)/Ce;return function(c,l){let u=c;if(u.is0(l))return l;if($c(u,l)!==1)throw new Error("Cannot find square root");let f=e,h=u.mul(u.ONE,s),d=u.pow(l,t),g=u.pow(l,i);for(;!u.eql(d,u.ONE);){if(u.is0(d))return u.ZERO;let E=1,p=u.sqr(d);for(;!u.eql(p,u.ONE);)if(E++,p=u.sqr(p),E===f)throw new Error("Cannot find square root");let b=nt<<BigInt(f-E-1),v=u.pow(h,b);f=E,h=u.sqr(v),d=u.mul(d,h),g=u.mul(g,v)}return g}}function Mh(r){return r%Vc===Kc?Zc:r%jc===Wc?Fh:r%Gc===Nh?Uh(r):Yc(r)}var se=(r,t)=>(st(r,t)&nt)===nt,zh=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Js(r){let t={ORDER:"bigint",BYTES:"number",BITS:"number"},e=zh.reduce((n,o)=>(n[o]="function",n),t);if(Ft(r,e),Nt(r.BYTES,"BYTES"),Nt(r.BITS,"BITS"),r.BYTES<1||r.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(r.ORDER<=nt)throw new Error("invalid field: expected ORDER > 1, got "+r.ORDER);return r}function Hh(r,t,e){let n=r;if(e<bt)throw new Error("invalid exponent, negatives unsupported");if(e===bt)return n.ONE;if(e===nt)return t;let o=n.ONE,s=t;for(;e>bt;)e&nt&&(o=n.mul(o,s)),s=n.sqr(s),e>>=nt;return o}function Gr(r,t,e=!1){let n=r,o=new Array(t.length).fill(e?n.ZERO:void 0),s=t.reduce((a,c,l)=>n.is0(c)?a:(o[l]=a,n.mul(a,c)),n.ONE),i=n.inv(s);return t.reduceRight((a,c,l)=>n.is0(c)?a:(o[l]=n.mul(a,o[l]),n.mul(a,c)),i),o}function $c(r,t){let e=r,n=(e.ORDER-nt)/Ce,o=e.pow(t,n),s=e.eql(o,e.ONE),i=e.eql(o,e.ZERO),a=e.eql(o,e.neg(e.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function $h(r,t){if(t!==void 0&&Zs(t),r<=bt)throw new Error("invalid n length: expected positive n, got "+r);if(t!==void 0&&t<1)throw new Error("invalid n length: expected positive bit length, got "+t);let e=lr(r);if(t!==void 0&&t<e)throw new Error(`invalid n length: expected bit length (${e}) >= n.length (${t})`);let n=t!==void 0?t:e,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}var qc=new WeakMap,jn=class{ORDER;BITS;BYTES;isLE;ZERO=bt;ONE=nt;_lengths;_mod;constructor(t,e={}){if(t<=nt)throw new Error("invalid field: expected ORDER > 1, got "+t);let n;this.isLE=!1,e!=null&&typeof e=="object"&&(typeof e.BITS=="number"&&(n=e.BITS),typeof e.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:e.sqrt,enumerable:!0}),typeof e.isLE=="boolean"&&(this.isLE=e.isLE),e.allowedLengths&&(this._lengths=Object.freeze(e.allowedLengths.slice())),typeof e.modFromBytes=="boolean"&&(this._mod=e.modFromBytes));let{nBitLength:o,nByteLength:s}=$h(t,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=t,this.BITS=o,this.BYTES=s,Object.freeze(this)}create(t){return st(t,this.ORDER)}isValid(t){if(typeof t!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof t);return bt<=t&&t<this.ORDER}is0(t){return t===bt}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}isOdd(t){return(t&nt)===nt}neg(t){return st(-t,this.ORDER)}eql(t,e){return t===e}sqr(t){return st(t*t,this.ORDER)}add(t,e){return st(t+e,this.ORDER)}sub(t,e){return st(t-e,this.ORDER)}mul(t,e){return st(t*e,this.ORDER)}pow(t,e){return Hh(this,t,e)}div(t,e){return st(t*Hc(e,this.ORDER),this.ORDER)}sqrN(t){return t*t}addN(t,e){return t+e}subN(t,e){return t-e}mulN(t,e){return t*e}inv(t){return Hc(t,this.ORDER)}sqrt(t){let e=qc.get(this);return e||qc.set(this,e=Mh(this.ORDER)),e(this,t)}toBytes(t){return this.isLE?Ys(t,this.BYTES):Vn(t,this.BYTES)}fromBytes(t,e=!1){H(t);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(t.length<1||!n.includes(t.length)||t.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+t.length);let l=new Uint8Array(o);l.set(t,s?0:l.length-t.length),t=l}if(t.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+t.length);let c=s?jt(t):Be(t);if(a&&(c=st(c,i)),!e&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(t){return Gr(this,t)}cmov(t,e,n){return Rt(n,"condition"),n?e:t}};Object.freeze(jn.prototype);function ur(r,t={}){return new jn(r,t)}function Xc(r){if(typeof r!="bigint")throw new Error("field order must be bigint");if(r<=nt)throw new Error("field order must be greater than 1");let t=lr(r-nt);return Math.ceil(t/8)}function ti(r){let t=Xc(r);return t+Math.ceil(t/2)}function ei(r,t,e=!1){H(r);let n=r.length,o=Xc(t),s=Math.max(ti(t),16);if(n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=e?jt(r):Be(r),a=st(i,t-nt)+nt;return e?Ys(a,o):Vn(a,o)}var fr=BigInt(0),Pe=BigInt(1);function Zr(r,t){let e=t.negate();return r?e:t}function Oe(r,t){let e=Gr(r.Fp,t.map(n=>n.Z));return t.map((n,o)=>r.fromAffine(n.toAffine(e[o])))}function el(r,t){if(!Number.isSafeInteger(r)||r<=0||r>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+r)}function ri(r,t){el(r,t);let e=Math.ceil(t/r)+1,n=2**(r-1),o=2**r,s=jr(r),i=BigInt(r);return{windows:e,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function Qc(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+=Pe);let l=t*n,u=l+Math.abs(a)-1,f=a===0,h=a<0,d=t%2!==0;return{nextN:c,offset:u,isZero:f,isNeg:h,isNegF:d,offsetF:l}}var ni=new WeakMap,rl=new WeakMap;function oi(r){return rl.get(r)||1}function Jc(r){if(r!==fr)throw new Error("invalid wNAF")}var hr=class{BASE;ZERO;Fn;bits;constructor(t,e){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=e}_unsafeLadder(t,e,n=this.ZERO){let o=t;for(;e>fr;)e&Pe&&(n=n.add(o)),o=o.double(),e>>=Pe;return n}precomputeWindow(t,e){let{windows:n,windowSize:o}=ri(e,this.bits),s=[],i=t,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let l=1;l<o;l++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(t,e,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=ri(t,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:f,isNegF:h,offsetF:d}=Qc(n,a,i);n=c,u?s=s.add(Zr(h,e[d])):o=o.add(Zr(f,e[l]))}return Jc(n),{p:o,f:s}}wNAFUnsafe(t,e,n,o=this.ZERO){let s=ri(t,this.bits);for(let i=0;i<s.windows&&n!==fr;i++){let{nextN:a,offset:c,isZero:l,isNeg:u}=Qc(n,i,s);if(n=a,!l){let f=e[c];o=o.add(u?f.negate():f)}}return Jc(n),o}getPrecomputes(t,e,n){let o=ni.get(e);return o||(o=this.precomputeWindow(e,t),t!==1&&(typeof n=="function"&&(o=n(o)),ni.set(e,o))),o}cached(t,e,n){let o=oi(t);return this.wNAF(o,this.getPrecomputes(o,t,n),e)}unsafe(t,e,n,o){let s=oi(t);return s===1?this._unsafeLadder(t,e,o):this.wNAFUnsafe(s,this.getPrecomputes(s,t,n),e,o)}createCache(t,e){el(e,this.bits),rl.set(t,e),ni.delete(t)}hasCache(t){return oi(t)!==1}};function nl(r,t,e,n){let o=t,s=r.ZERO,i=r.ZERO;for(;e>fr||n>fr;)e&Pe&&(s=s.add(o)),n&Pe&&(i=i.add(o)),o=o.double(),e>>=Pe,n>>=Pe;return{p1:s,p2:i}}function tl(r,t,e){if(t){if(t.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Js(t),t}else return ur(r,{isLE:e})}function Gn(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 l=t[c];if(!(typeof l=="bigint"&&l>fr))throw new Error(`CURVE.${c} must be positive bigint`)}let o=tl(t.p,e.Fp,n),s=tl(t.n,e.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(t[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:s}}function Zn(r,t){return function(n){let o=r(n);return{secretKey:o,publicKey:t(o)}}}var ye=BigInt(0),pt=BigInt(1),si=BigInt(2),qh=BigInt(8);function Kh(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 ol(r,t={}){let e=t,n=Gn("edwards",r,e,e.FpFnLE),{Fp:o,Fn:s}=n,i=n.CURVE,{h:a}=i;Ft(e,{},{uvRatio:"function"});let c=si<<BigInt(s.BYTES*8)-pt,l=E=>o.create(E),u=e.uvRatio===void 0?(E,p)=>{try{return{isValid:!0,value:o.sqrt(o.div(E,p))}}catch{return{isValid:!1,value:ye}}}:e.uvRatio;if(!Kh(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function f(E,p,b=!1){let v=b?pt:ye;return cr("coordinate "+E,p,v,c),p}function h(E){if(!(E instanceof d))throw new Error("EdwardsPoint expected")}class d{static BASE=new d(i.Gx,i.Gy,pt,l(i.Gx*i.Gy));static ZERO=new d(ye,pt,pt,ye);static Fp=o;static Fn=s;X;Y;Z;T;constructor(p,b,v,S){this.X=f("x",p),this.Y=f("y",b),this.Z=f("z",v,!0),this.T=f("t",S),Object.freeze(this)}static CURVE(){return i}static fromAffine(p){if(p instanceof d)throw new Error("extended point not allowed");let{x:b,y:v}=p||{};return f("x",b),f("y",v),new d(b,v,pt,l(b*v))}static fromBytes(p,b=!1){let v=o.BYTES,{a:S,d:B}=i;p=Wr(H(p,v,"point")),Rt(b,"zip215");let D=Wr(p),R=p[v-1];D[v-1]=R&-129;let C=jt(D),T=b?c:o.ORDER;cr("point.y",C,ye,T);let N=l(C*C),j=l(N-pt),F=l(B*N-S),{isValid:m,value:y}=u(j,F);if(!m)throw new Error("bad point: invalid y coordinate");let _=(y&pt)===pt,x=(R&128)!==0;if(!b&&y===ye&&x)throw new Error("bad point: x=0 and x_0=1");return x!==_&&(y=l(-y)),d.fromAffine({x:y,y:C})}static fromHex(p,b=!1){return d.fromBytes(ar(p),b)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(p=8,b=!0){return g.createCache(this,p),b||this.multiply(si),this}assertValidity(){let p=this,{a:b,d:v}=i;if(p.is0())throw new Error("bad point: ZERO");let{X:S,Y:B,Z:D,T:R}=p,C=l(S*S),T=l(B*B),N=l(D*D),j=l(N*N),F=l(C*b),m=l(N*l(F+T)),y=l(j+l(v*l(C*T)));if(m!==y)throw new Error("bad point: equation left != right (1)");let _=l(S*B),x=l(D*R);if(_!==x)throw new Error("bad point: equation left != right (2)")}equals(p){h(p);let{X:b,Y:v,Z:S}=this,{X:B,Y:D,Z:R}=p,C=l(b*R),T=l(B*S),N=l(v*R),j=l(D*S);return C===T&&N===j}is0(){return this.equals(d.ZERO)}negate(){return new d(l(-this.X),this.Y,this.Z,l(-this.T))}double(){let{a:p}=i,{X:b,Y:v,Z:S}=this,B=l(b*b),D=l(v*v),R=l(si*l(S*S)),C=l(p*B),T=b+v,N=l(l(T*T)-B-D),j=C+D,F=j-R,m=C-D,y=l(N*F),_=l(j*m),x=l(N*m),w=l(F*j);return new d(y,_,w,x)}add(p){h(p);let{a:b,d:v}=i,{X:S,Y:B,Z:D,T:R}=this,{X:C,Y:T,Z:N,T:j}=p,F=l(S*C),m=l(B*T),y=l(R*v*j),_=l(D*N),x=l((S+B)*(C+T)-F-m),w=_-y,A=_+y,k=l(m-b*F),I=l(x*w),L=l(A*k),O=l(x*k),z=l(w*A);return new d(I,L,z,O)}subtract(p){return h(p),this.add(p.negate())}multiply(p){if(!s.isValidNot0(p))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:b,f:v}=g.cached(this,p,S=>Oe(d,S));return Oe(d,[b,v])[0]}multiplyUnsafe(p){if(!s.isValid(p))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return p===ye?d.ZERO:this.is0()||p===pt?this:g.unsafe(this,p,b=>Oe(d,b))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return g.unsafe(this,i.n).is0()}toAffine(p){let b=this,v=p,{X:S,Y:B,Z:D}=b,R=b.is0();v==null&&(v=R?qh:o.inv(D));let C=l(S*v),T=l(B*v),N=o.mul(D,v);if(R)return{x:ye,y:pt};if(N!==pt)throw new Error("invZ was invalid");return{x:C,y:T}}clearCofactor(){return a===pt?this:this.multiplyUnsafe(a)}toBytes(){let{x:p,y:b}=this.toAffine(),v=o.toBytes(b);return v[v.length-1]|=p&pt?128:0,v}toHex(){return ir(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let g=new hr(d,s.BITS);return s.BITS>=8&&d.BASE.precompute(8),Object.freeze(d.prototype),Object.freeze(d),d}var Yn=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(t){this.ep=t}static fromBytes(t){Xs()}static fromHex(t){Xs()}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 ir(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.ep.precompute(t,e),this}};function sl(r,t,e={}){if(typeof t!="function")throw new Error('"hash" function param is required');let n=t,o=e;Ft(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:s}=o,{BASE:i,Fp:a,Fn:c}=r,l=n.outputLen,u=2*a.BYTES;if(l!==void 0&&(Nt(l,"hash.outputLen"),l!==u))throw new Error(`hash.outputLen must be ${u}, got ${l}`);let f=o.randomBytes===void 0?Kr:o.randomBytes,h=o.adjustScalarBytes===void 0?m=>m:o.adjustScalarBytes,d=o.domain===void 0?(m,y,_)=>{if(Rt(_,"phflag"),y.length||_)throw new Error("Contexts/pre-hash are not supported");return m}:o.domain;function g(m){return c.create(jt(m))}function E(m){let y=C.secretKey;H(m,C.secretKey,"secretKey");let _=H(n(m),2*y,"hashedSecretKey"),x=h(_.slice(0,y)),w=_.slice(y,2*y),A=g(x);return{head:x,prefix:w,scalar:A}}function p(m){let{head:y,prefix:_,scalar:x}=E(m),w=i.multiply(x),A=w.toBytes();return{head:y,prefix:_,scalar:x,point:w,pointBytes:A}}function b(m){return p(m).pointBytes}function v(m=Uint8Array.of(),...y){let _=ft(...y);return g(n(d(_,H(m,void 0,"context"),!!s)))}function S(m,y,_={}){m=H(m,void 0,"message"),s&&(m=s(m));let{prefix:x,scalar:w,pointBytes:A}=p(y),k=v(_.context,x,m),I=i.multiply(k).toBytes(),L=v(_.context,I,A,m),O=c.create(k+L*w);if(!c.isValid(O))throw new Error("sign failed: invalid s");let z=ft(I,c.toBytes(O));return H(z,C.signature,"result")}let B={zip215:o.zip215};function D(m,y,_,x=B){let{context:w}=x,A=x.zip215===void 0?!!B.zip215:x.zip215,k=C.signature;m=H(m,k,"signature"),y=H(y,void 0,"message"),_=H(_,C.publicKey,"publicKey"),A!==void 0&&Rt(A,"zip215"),s&&(y=s(y));let I=k/2,L=m.subarray(0,I),O=jt(m.subarray(I,k)),z,q,U;try{z=r.fromBytes(_,A),q=r.fromBytes(L,A),U=i.multiplyUnsafe(O)}catch{return!1}if(!A&&z.isSmallOrder())return!1;let lt=v(w,L,_,y);return q.add(z.multiplyUnsafe(lt)).subtract(U).clearCofactor().is0()}let R=a.BYTES,C={secretKey:R,publicKey:R,signature:2*R,seed:R};function T(m){return m=m===void 0?f(C.seed):m,H(m,C.seed,"seed")}function N(m){return Le(m)&&m.length===C.secretKey}function j(m,y){try{return!!r.fromBytes(m,y===void 0?B.zip215:y)}catch{return!1}}let F={getExtendedPublicKey:p,randomSecretKey:T,isValidSecretKey:N,isValidPublicKey:j,toMontgomery(m){let{y}=r.fromBytes(m),_=C.publicKey,x=_===32;if(!x&&_!==57)throw new Error("only defined for 25519 and 448");let w=x?a.div(pt+y,pt-y):a.div(y-pt,y+pt);return a.toBytes(w)},toMontgomerySecret(m){let y=C.secretKey;H(m,y);let _=n(m.subarray(0,y));return h(_).subarray(0,y)}};return Object.freeze(C),Object.freeze(F),Object.freeze({keygen:Zn(T,b),getPublicKey:b,sign:S,verify:D,utils:F,Point:r,lengths:C})}function Yr(r,t){if(Nt(r),Nt(t),t<0||t>4)throw new Error("invalid I2OSP length: "+t);if(r<0||r>2**(8*t)-1)throw new Error("invalid I2OSP input: "+r);let e=Array.from({length:t}).fill(0);for(let n=t-1;n>=0;n--)e[n]=r&255,r>>>=8;return new Uint8Array(e)}function Vh(r,t){let e=new Uint8Array(r.length);for(let n=0;n<r.length;n++)e[n]=r[n]^t[n];return e}function Wh(r){if(!Le(r)&&typeof r!="string")throw new Error("DST must be Uint8Array or ascii string");let t=typeof r=="string"?Wn(r):r;if(t.length===0)throw new Error("DST must be non-empty");return t}function ii(r,t,e,n){H(r),Nt(e),t=Wh(t),t.length>255&&(t=n(ft(Wn("H2C-OVERSIZE-DST-"),t)));let{outputLen:o,blockLen:s}=n,i=Math.ceil(e/o);if(e>65535||i>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=ft(t,Yr(t.length,1)),c=new Uint8Array(s),l=Yr(e,2),u=new Array(i),f=n(ft(c,r,l,Yr(0,1),a));u[0]=n(ft(f,Yr(1,1),a));for(let d=1;d<i;d++){let g=[Vh(f,u[d-1]),Yr(d+1,1),a];u[d]=n(ft(...g))}return ft(...u).slice(0,e)}var il="HashToScalar-";var jh=BigInt(0),ie=BigInt(1),al=BigInt(2);var Gh=BigInt(5),Zh=BigInt(8),dr=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),ui={p:dr,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Zh,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Yh(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),s=dr,a=r*r%s*r%s,c=Q(a,al,s)*a%s,l=Q(c,ie,s)*r%s,u=Q(l,Gh,s)*l%s,f=Q(u,t,s)*u%s,h=Q(f,e,s)*f%s,d=Q(h,n,s)*h%s,g=Q(d,o,s)*d%s,E=Q(g,o,s)*d%s,p=Q(E,t,s)*u%s;return{pow_p_5_8:Q(p,al,s)*r%s,b2:a}}function Xh(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var ai=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function fi(r,t){let e=dr,n=st(t*t*t,e),o=st(n*n*t,e),s=Yh(r*o).pow_p_5_8,i=st(r*n*s,e),a=st(t*i*i,e),c=i,l=st(i*ai,e),u=a===r,f=a===st(-r,e),h=a===st(-r*ai,e);return u&&(i=c),(f||h)&&(i=l),se(i,e)&&(i=st(-i,e)),{isValid:u||f,value:i}}var xe=ol(ui,{uvRatio:fi}),we=xe.Fp,ul=xe.Fn;function Qh(r){return sl(xe,Hn,Object.assign({adjustScalarBytes:Xh,zip215:!0},r))}var fl=Qh({});var ci=ai,Jh=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),td=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),ed=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),rd=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),cl=r=>fi(ie,r),nd=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),li=r=>we.create(jt(r)&nd);function ll(r){let{d:t}=ui,e=dr,n=b=>we.create(b),o=n(ci*r*r),s=n((o+ie)*ed),i=BigInt(-1),a=n((i-t*o)*n(o+t)),{isValid:c,value:l}=fi(s,a),u=n(l*r);se(u,e)||(u=n(-u)),c||(l=u),c||(i=o);let f=n(i*(o-ie)*rd-a),h=l*l,d=n((l+l)*a),g=n(f*Jh),E=n(ie-h),p=n(ie+h);return new xe(n(d*p),n(E*g),n(g*p),n(d*E))}var Ee=class r extends Yn{static BASE=new r(xe.BASE);static ZERO=new r(xe.ZERO);static Fp=we;static Fn=ul;constructor(t){super(t)}static fromAffine(t){return new r(xe.fromAffine(t))}assertSame(t){if(!(t instanceof r))throw new Error("RistrettoPoint expected")}init(t){return new r(t)}static fromBytes(t){Dt(t,32);let{a:e,d:n}=ui,o=dr,s=B=>we.create(B),i=li(t);if(!Mc(we.toBytes(i),t)||se(i,o))throw new Error("invalid ristretto255 encoding 1");let a=s(i*i),c=s(ie+e*a),l=s(ie-e*a),u=s(c*c),f=s(l*l),h=s(e*n*u-f),{isValid:d,value:g}=cl(s(h*f)),E=s(g*l),p=s(g*E*h),b=s((i+i)*E);se(b,o)&&(b=s(-b));let v=s(c*p),S=s(b*v);if(!d||se(S,o)||v===jh)throw new Error("invalid ristretto255 encoding 2");return new r(new xe(b,v,ie,S))}static fromHex(t){return r.fromBytes(zr(t))}toBytes(){let{X:t,Y:e,Z:n,T:o}=this.ep,s=dr,i=p=>we.create(p),a=i(i(n+e)*i(n-e)),c=i(t*e),l=i(c*c),{value:u}=cl(i(a*l)),f=i(u*a),h=i(u*c),d=i(f*h*o),g;if(se(o*d,s)){let p=i(e*ci),b=i(t*ci);t=p,e=b,g=i(f*td)}else g=h;se(t*d,s)&&(e=i(-e));let E=i((n-e)*g);return se(E,s)&&(E=i(-E)),we.toBytes(E)}equals(t){this.assertSame(t);let{X:e,Y:n}=this.ep,{X:o,Y:s}=t.ep,i=l=>we.create(l),a=i(e*s)===i(n*o),c=i(n*s)===i(e*o);return a||c}is0(){return this.equals(r.ZERO)}};Object.freeze(Ee.BASE);Object.freeze(Ee.ZERO);Object.freeze(Ee.prototype);Object.freeze(Ee);var od=Object.freeze({Point:Ee,hashToCurve(r,t){let e=t?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":t.DST,n=ii(r,e,64,Hn);return od.deriveToCurve(n)},hashToScalar(r,t={DST:il}){let e=ii(r,t.DST,64,Hn);return ul.create(jt(e))},deriveToCurve(r){Dt(r,64);let t=li(r.subarray(0,32)),e=ll(t),n=li(r.subarray(32,64)),o=ll(n);return new Ee(e.add(o))}});var Xn=32;var hi,sd=(async()=>{try{return await Ln.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function id(r,t,e){if(r.buffer instanceof ArrayBuffer){let n=await Ln.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await Ln.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 ad(r,t,e){return fl.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}async function hl(r,t,e){return hi==null&&(hi=await sd),hi?id(r,t,e):ad(r,t,e)}function Qn(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Jn=class{type="Ed25519";raw;constructor(t){this.raw=di(t,Xn)}toMultihash(){return kt.digest(or(this))}toCID(){return et.createV1(114,this.toMultihash())}toString(){return it.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:at(this.raw,t.raw)}verify(t,e,n){n?.signal?.throwIfAborted();let o=hl(this.raw,e,t);return Qn(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function pl(r){return r=di(r,Xn),new Jn(r)}function di(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new Tt(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}var ld=Math.pow(2,7),ud=Math.pow(2,14),fd=Math.pow(2,21),pi=Math.pow(2,28),mi=Math.pow(2,35),gi=Math.pow(2,42),bi=Math.pow(2,49),K=128,Et=127;function J(r){if(r<ld)return 1;if(r<ud)return 2;if(r<fd)return 3;if(r<pi)return 4;if(r<mi)return 5;if(r<gi)return 6;if(r<bi)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function pr(r,t,e=0){switch(J(r)){case 8:t[e++]=r&255|K,r/=128;case 7:t[e++]=r&255|K,r/=128;case 6:t[e++]=r&255|K,r/=128;case 5:t[e++]=r&255|K,r/=128;case 4:t[e++]=r&255|K,r>>>=7;case 3:t[e++]=r&255|K,r>>>=7;case 2:t[e++]=r&255|K,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function hd(r,t,e=0){switch(J(r)){case 8:t.set(e++,r&255|K),r/=128;case 7:t.set(e++,r&255|K),r/=128;case 6:t.set(e++,r&255|K),r/=128;case 5:t.set(e++,r&255|K),r/=128;case 4:t.set(e++,r&255|K),r>>>=7;case 3:t.set(e++,r&255|K),r>>>=7;case 2:t.set(e++,r&255|K),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function yi(r,t){let e=r[t],n=0;if(n+=e&Et,e<K||(e=r[t+1],n+=(e&Et)<<7,e<K)||(e=r[t+2],n+=(e&Et)<<14,e<K)||(e=r[t+3],n+=(e&Et)<<21,e<K)||(e=r[t+4],n+=(e&Et)*pi,e<K)||(e=r[t+5],n+=(e&Et)*mi,e<K)||(e=r[t+6],n+=(e&Et)*gi,e<K)||(e=r[t+7],n+=(e&Et)*bi,e<K))return n;throw new RangeError("Could not decode varint")}function dd(r,t){let e=r.get(t),n=0;if(n+=e&Et,e<K||(e=r.get(t+1),n+=(e&Et)<<7,e<K)||(e=r.get(t+2),n+=(e&Et)<<14,e<K)||(e=r.get(t+3),n+=(e&Et)<<21,e<K)||(e=r.get(t+4),n+=(e&Et)*pi,e<K)||(e=r.get(t+5),n+=(e&Et)*mi,e<K)||(e=r.get(t+6),n+=(e&Et)*gi,e<K)||(e=r.get(t+7),n+=(e&Et)*bi,e<K))return n;throw new RangeError("Could not decode varint")}function to(r,t,e=0){return t==null&&(t=xt(J(r))),t instanceof Uint8Array?pr(r,t,e):hd(r,t,e)}function Re(r,t=0){return r instanceof Uint8Array?yi(r,t):dd(r,t)}var xi=new Float32Array([-0]),ve=new Uint8Array(xi.buffer);function ml(r,t,e){xi[0]=r,t[e]=ve[0],t[e+1]=ve[1],t[e+2]=ve[2],t[e+3]=ve[3]}function gl(r,t){return ve[0]=r[t],ve[1]=r[t+1],ve[2]=r[t+2],ve[3]=r[t+3],xi[0]}var Ei=new Float64Array([-0]),vt=new Uint8Array(Ei.buffer);function bl(r,t,e){Ei[0]=r,t[e]=vt[0],t[e+1]=vt[1],t[e+2]=vt[2],t[e+3]=vt[3],t[e+4]=vt[4],t[e+5]=vt[5],t[e+6]=vt[6],t[e+7]=vt[7]}function yl(r,t){return vt[0]=r[t],vt[1]=r[t+1],vt[2]=r[t+2],vt[3]=r[t+3],vt[4]=r[t+4],vt[5]=r[t+5],vt[6]=r[t+6],vt[7]=r[t+7],Ei[0]}var pd=BigInt(Number.MAX_SAFE_INTEGER),md=BigInt(Number.MIN_SAFE_INTEGER),Lt=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 Ne;if(t<pd&&t>md)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>wl&&(o=0n,++n>wl&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return Ne;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):Ne}},Ne=new Lt(0,0);Ne.toBigInt=function(){return 0n};Ne.zzEncode=Ne.zzDecode=function(){return this};Ne.length=function(){return 1};var wl=4294967296n;function xl(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 El(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 vi(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 Ut(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function eo(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var _i=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,Ut(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 Ut(this,4);return eo(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Ut(this,4);return eo(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Ut(this,4);let t=gl(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw Ut(this,4);let t=yl(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 Ut(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return El(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw Ut(this,t);this.pos+=t}else do if(this.pos>=this.len)throw Ut(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 Lt(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 Ut(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 Ut(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 Ut(this,8);let t=eo(this.buf,this.pos+=4),e=eo(this.buf,this.pos+=4);return new Lt(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=yi(this.buf,this.pos);return this.pos+=J(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 Xr(r){return new _i(r instanceof Uint8Array?r:r.subarray())}function Gt(r,t,e){let n=Xr(r);return t.decode(n,void 0,e)}function Si(r){let t=r??8192,e=t>>>1,n,o=t;return function(i){if(i<1||i>e)return xt(i);o+i>t&&(n=xt(t),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var Fe=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function Ai(){}var Ti=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},gd=Si();function bd(r){return globalThis.Buffer!=null?xt(r):gd(r)}var Jr=class{len;head;tail;states;constructor(){this.len=0,this.head=new Fe(Ai,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new Fe(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new ki((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(ro,10,Lt.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=Lt.fromBigInt(t);return this._push(ro,e.length(),e)}uint64Number(t){return this._push(pr,J(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=Lt.fromBigInt(t).zzEncode();return this._push(ro,e.length(),e)}sint64Number(t){let e=Lt.fromNumber(t).zzEncode();return this._push(ro,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(Ii,1,t?1:0)}fixed32(t){return this._push(Qr,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=Lt.fromBigInt(t);return this._push(Qr,4,e.lo)._push(Qr,4,e.hi)}fixed64Number(t){let e=Lt.fromNumber(t);return this._push(Qr,4,e.lo)._push(Qr,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(ml,4,t)}double(t){return this._push(bl,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(Ii,1,0):this.uint32(e)._push(wd,e,t)}string(t){let e=xl(t);return e!==0?this.uint32(e)._push(vi,e,t):this._push(Ii,1,0)}fork(){return this.states=new Ti(this),this.head=this.tail=new Fe(Ai,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 Fe(Ai,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=bd(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function Ii(r,t,e){t[e]=r&255}function yd(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var ki=class extends Fe{next;constructor(t,e){super(yd,t,e),this.next=void 0}};function ro(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 Qr(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 wd(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(Jr.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(xd,t,r),this},Jr.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(Ed,t,r),this});function xd(r,t,e){t.set(r,e)}function Ed(r,t,e){r.length<40?vi(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(Z(r),e)}function Di(){return new Jr}function Zt(r,t){let e=Di();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}function*Yt(r,t,e){let n=Xr(r);yield*t.stream(n,void 0,"$",e)}var no={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function oo(r,t,e,n,o){return{name:r,type:t,encode:e,decode:n,stream:o}}function mr(r){function t(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let e=function(i,a){let c=t(i);a.int32(c)},n=function(i){let a=i.int32();return t(a)},o=function*(i){let a=i.int32();yield t(a)};return oo("enum",no.VARINT,e,n,o)}function Xt(r,t,e){return oo("message",no.LENGTH_DELIMITED,r,t,e)}var ae=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var St;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(St||(St={}));var Li;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(Li||(Li={}));(function(r){r.codec=()=>mr(Li)})(St||(St={}));var tn;(function(r){let t;r.codec=()=>(t==null&&(t=Xt((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),St.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.Type=St.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:St.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),t);function e(s){return Zt(s,r.codec())}r.encode=e;function n(s,i){return Gt(s,r.codec(),i)}r.decode=n;function o(s,i){return Yt(s,r.codec(),i)}r.stream=o})(tn||(tn={}));var Bi;(function(r){let t;r.codec=()=>(t==null&&(t=Xt((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),St.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.Type=St.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:St.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),t);function e(s){return Zt(s,r.codec())}r.encode=e;function n(s,i){return Gt(s,r.codec(),i)}r.decode=n;function o(s,i){return Yt(s,r.codec(),i)}r.stream=o})(Bi||(Bi={}));var so=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(t,e){if(Nn(t),Dt(e,void 0,"key"),this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(e.length>n?t.create().update(e).digest():e);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=t.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),ne(o)}update(t){return sr(this),this.iHash.update(t),this}digestInto(t){sr(this),Fn(t,this),this.finished=!0;let e=t.subarray(0,this.outputLen);this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||=Object.create(Object.getPrototypeOf(this),{});let{oHash:e,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return t=t,t.finished=o,t.destroyed=s,t.blockLen=i,t.outputLen=a,t.oHash=e._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},_l=(()=>{let r=((t,e,n)=>new so(t,e).update(n).digest());return r.create=(t,e)=>new so(t,e),r})();var Sl=(r,t)=>(r+(r>=0?t:-t)/Al)/t;function _d(r,t,e){cr("scalar",r,Qt,e);let[[n,o],[s,i]]=t,a=Sl(i*r,e),c=Sl(-o*r,e),l=r-a*n-c*s,u=-a*o-c*i,f=l<Qt,h=u<Qt;f&&(l=-l),h&&(u=-u);let d=jr(Math.ceil(lr(e)/2))+_e;if(l<Qt||l>=d||u<Qt||u>=d)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:f,k1:l,k2neg:h,k2:u}}function Pi(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function Ci(r,t){Ft(r);let e={};for(let n of Object.keys(t))e[n]=r[n]===void 0?t[n]:r[n];return Rt(e.lowS,"lowS"),Rt(e.prehash,"prehash"),e.format!==void 0&&Pi(e.format),e}var Oi=class extends Error{constructor(t=""){super(t)}},Mt={Err:Oi,_tlv:{encode:(r,t)=>{let{Err:e}=Mt;if(Nt(r,"tag"),r<0||r>255)throw new e("tlv.encode: wrong tag");if(typeof t!="string")throw new TypeError('"data" expected string, got type='+typeof t);if(t.length&1)throw new e("tlv.encode: unpadded data");let n=t.length/2,o=Vr(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let s=n>127?Vr(o.length/2|128):"";return Vr(r)+s+o+t},decode(r,t){let{Err:e}=Mt;t=H(t,void 0,"DER data");let n=0;if(r<0||r>255)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 l=t.subarray(n,n+c);if(l.length!==c)throw new e("tlv.decode: length bytes not complete");if(l[0]===0)throw new e("tlv.decode(long): zero leftmost byte");for(let u of l)i=i<<8|u;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}=Mt;if(Kn(r),r<Qt)throw new t("integer: negative integers are not allowed");let e=Vr(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}=Mt;if(r.length<1)throw new t("invalid signature integer: empty");if(r[0]&128)throw new t("invalid signature integer: negative");if(r.length>1&&r[0]===0&&!(r[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return Be(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=Mt,o=H(r,void 0,"signature"),{v:s,l:i}=n.decode(48,o);if(i.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:l,l:u}=n.decode(2,c);if(u.length)throw new t("invalid signature: left bytes after parsing");return{r:e.decode(a),s:e.decode(l)}},hexFromSig(r){let{_tlv:t,_int:e}=Mt,n=t.encode(2,e.encode(r.r)),o=t.encode(2,e.encode(r.s)),s=n+o;return t.encode(48,s)}};Object.freeze(Mt._tlv);Object.freeze(Mt._int);Object.freeze(Mt);var Qt=BigInt(0),_e=BigInt(1),Al=BigInt(2),io=BigInt(3),Sd=BigInt(4);function Il(r,t={}){let e=Gn("weierstrass",r,t),n=e.Fp,o=e.Fn,s=e.CURVE,{h:i,n:a}=s;Ft(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c,allowInfinityPoint:l}=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=kl(n,o);function f(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function h(F,m,y){if(l&&m.is0())return Uint8Array.of(0);let{x:_,y:x}=m.toAffine(),w=n.toBytes(_);if(Rt(y,"isCompressed"),y){f();let A=!n.isOdd(x);return ft(Tl(A),w)}else return ft(Uint8Array.of(4),w,n.toBytes(x))}function d(F){H(F,void 0,"Point");let{publicKey:m,publicKeyUncompressed:y}=u,_=F.length,x=F[0],w=F.subarray(1);if(l&&_===1&&x===0)return{x:n.ZERO,y:n.ZERO};if(_===m&&(x===2||x===3)){let A=n.fromBytes(w);if(!n.isValid(A))throw new Error("bad point: is not on curve, wrong x");let k=p(A),I;try{I=n.sqrt(k)}catch(z){let q=z instanceof Error?": "+z.message:"";throw new Error("bad point: is not on curve, sqrt error"+q)}f();let L=n.isOdd(I);return(x&1)===1!==L&&(I=n.neg(I)),{x:A,y:I}}else if(_===y&&x===4){let A=n.BYTES,k=n.fromBytes(w.subarray(0,A)),I=n.fromBytes(w.subarray(A,A*2));if(!b(k,I))throw new Error("bad point: is not on curve");return{x:k,y:I}}else throw new Error(`bad point: got length ${_}, expected compressed=${m} or uncompressed=${y}`)}let g=t.toBytes===void 0?h:t.toBytes,E=t.fromBytes===void 0?d:t.fromBytes;function p(F){let m=n.sqr(F),y=n.mul(m,F);return n.add(n.add(y,n.mul(F,s.a)),s.b)}function b(F,m){let y=n.sqr(m),_=p(F);return n.eql(y,_)}if(!b(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let v=n.mul(n.pow(s.a,io),Sd),S=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(v,S)))throw new Error("bad curve params: a or b");function B(F,m,y=!1){if(!n.isValid(m)||y&&n.is0(m))throw new Error(`bad point coordinate ${F}`);return m}function D(F){if(!(F instanceof T))throw new Error("Weierstrass Point expected")}function R(F){if(!c||!c.basises)throw new Error("no endo");return _d(F,c.basises,o.ORDER)}function C(F,m,y,_,x){return y=new T(n.mul(y.X,F),y.Y,y.Z),m=Zr(_,m),y=Zr(x,y),m.add(y)}class T{static BASE=new T(s.Gx,s.Gy,n.ONE);static ZERO=new T(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(m,y,_){this.X=B("x",m),this.Y=B("y",y,!0),this.Z=B("z",_),Object.freeze(this)}static CURVE(){return s}static fromAffine(m){let{x:y,y:_}=m||{};if(!m||!n.isValid(y)||!n.isValid(_))throw new Error("invalid affine point");if(m instanceof T)throw new Error("projective point not allowed");return n.is0(y)&&n.is0(_)?T.ZERO:new T(y,_,n.ONE)}static fromBytes(m){let y=T.fromAffine(E(H(m,void 0,"point")));return y.assertValidity(),y}static fromHex(m){return T.fromBytes(ar(m))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(m=8,y=!0){return j.createCache(this,m),y||this.multiply(io),this}assertValidity(){let m=this;if(m.is0()){if(t.allowInfinityPoint&&n.is0(m.X)&&n.eql(m.Y,n.ONE)&&n.is0(m.Z))return;throw new Error("bad point: ZERO")}let{x:y,y:_}=m.toAffine();if(!n.isValid(y)||!n.isValid(_))throw new Error("bad point: x or y not field elements");if(!b(y,_))throw new Error("bad point: equation left != right");if(!m.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:m}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(m)}equals(m){D(m);let{X:y,Y:_,Z:x}=this,{X:w,Y:A,Z:k}=m,I=n.eql(n.mul(y,k),n.mul(w,x)),L=n.eql(n.mul(_,k),n.mul(A,x));return I&&L}negate(){return new T(this.X,n.neg(this.Y),this.Z)}double(){let{a:m,b:y}=s,_=n.mul(y,io),{X:x,Y:w,Z:A}=this,k=n.ZERO,I=n.ZERO,L=n.ZERO,O=n.mul(x,x),z=n.mul(w,w),q=n.mul(A,A),U=n.mul(x,w);return U=n.add(U,U),L=n.mul(x,A),L=n.add(L,L),k=n.mul(m,L),I=n.mul(_,q),I=n.add(k,I),k=n.sub(z,I),I=n.add(z,I),I=n.mul(k,I),k=n.mul(U,k),L=n.mul(_,L),q=n.mul(m,q),U=n.sub(O,q),U=n.mul(m,U),U=n.add(U,L),L=n.add(O,O),O=n.add(L,O),O=n.add(O,q),O=n.mul(O,U),I=n.add(I,O),q=n.mul(w,A),q=n.add(q,q),O=n.mul(q,U),k=n.sub(k,O),L=n.mul(q,z),L=n.add(L,L),L=n.add(L,L),new T(k,I,L)}add(m){D(m);let{X:y,Y:_,Z:x}=this,{X:w,Y:A,Z:k}=m,I=n.ZERO,L=n.ZERO,O=n.ZERO,z=s.a,q=n.mul(s.b,io),U=n.mul(y,w),lt=n.mul(_,A),ht=n.mul(x,k),dt=n.add(y,_),ot=n.add(w,A);dt=n.mul(dt,ot),ot=n.add(U,lt),dt=n.sub(dt,ot),ot=n.add(y,x);let At=n.add(w,k);return ot=n.mul(ot,At),At=n.add(U,ht),ot=n.sub(ot,At),At=n.add(_,x),I=n.add(A,k),At=n.mul(At,I),I=n.add(lt,ht),At=n.sub(At,I),O=n.mul(z,ot),I=n.mul(q,ht),O=n.add(I,O),I=n.sub(lt,O),O=n.add(lt,O),L=n.mul(I,O),lt=n.add(U,U),lt=n.add(lt,U),ht=n.mul(z,ht),ot=n.mul(q,ot),lt=n.add(lt,ht),ht=n.sub(U,ht),ht=n.mul(z,ht),ot=n.add(ot,ht),U=n.mul(lt,ot),L=n.add(L,U),U=n.mul(At,ot),I=n.mul(dt,I),I=n.sub(I,U),U=n.mul(dt,lt),O=n.mul(At,O),O=n.add(O,U),new T(I,L,O)}subtract(m){return D(m),this.add(m.negate())}is0(){return this.equals(T.ZERO)}multiply(m){let{endo:y}=t;if(!o.isValidNot0(m))throw new RangeError("invalid scalar: out of range");let _,x,w=A=>j.cached(this,A,k=>Oe(T,k));if(y){let{k1neg:A,k1:k,k2neg:I,k2:L}=R(m),{p:O,f:z}=w(k),{p:q,f:U}=w(L);x=z.add(U),_=C(y.beta,O,q,A,I)}else{let{p:A,f:k}=w(m);_=A,x=k}return Oe(T,[_,x])[0]}multiplyUnsafe(m){let{endo:y}=t,_=this,x=m;if(!o.isValid(x))throw new RangeError("invalid scalar: out of range");if(x===Qt||_.is0())return T.ZERO;if(x===_e)return _;if(j.hasCache(this))return this.multiply(x);if(y){let{k1neg:w,k1:A,k2neg:k,k2:I}=R(x),{p1:L,p2:O}=nl(T,_,A,I);return C(y.beta,L,O,w,k)}else return j.unsafe(_,x)}toAffine(m){let y=this,_=m,{X:x,Y:w,Z:A}=y;if(n.eql(A,n.ONE))return{x,y:w};let k=y.is0();_==null&&(_=k?n.ONE:n.inv(A));let I=n.mul(x,_),L=n.mul(w,_),O=n.mul(A,_);if(k)return{x:n.ZERO,y:n.ZERO};if(!n.eql(O,n.ONE))throw new Error("invZ was invalid");return{x:I,y:L}}isTorsionFree(){let{isTorsionFree:m}=t;return i===_e?!0:m?m(T,this):j.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:m}=t;return i===_e?this:m?m(T,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===_e?this.is0():this.clearCofactor().is0()}toBytes(m=!0){return Rt(m,"isCompressed"),this.assertValidity(),g(T,this,m)}toHex(m=!0){return ir(this.toBytes(m))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let N=o.BITS,j=new hr(T,t.endo?Math.ceil(N/2):N);return N>=8&&T.BASE.precompute(8),Object.freeze(T.prototype),Object.freeze(T),T}function Tl(r){return Uint8Array.of(r?2:3)}function kl(r,t){return{secretKey:t.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function Ad(r,t={}){let{Fn:e}=r,n=t.randomBytes===void 0?Kr:t.randomBytes,o=Object.assign(kl(r.Fp,e),{seed:Math.max(ti(e.ORDER),16)});function s(d){try{let g=e.fromBytes(d);return e.isValidNot0(g)}catch{return!1}}function i(d,g){let{publicKey:E,publicKeyUncompressed:p}=o;try{let b=d.length;return g===!0&&b!==E||g===!1&&b!==p?!1:!!r.fromBytes(d)}catch{return!1}}function a(d){return d=d===void 0?n(o.seed):d,ei(H(d,o.seed,"seed"),e.ORDER)}function c(d,g=!0){return r.BASE.multiply(e.fromBytes(d)).toBytes(g)}function l(d){let{secretKey:g,publicKey:E,publicKeyUncompressed:p}=o,b=e._lengths;if(!Le(d))return;let v=H(d,void 0,"key").length,S=v===E||v===p,B=v===g||!!b?.includes(v);if(!(S&&B))return S}function u(d,g,E=!0){if(l(d)===!0)throw new Error("first arg must be private key");if(l(g)===!1)throw new Error("second arg must be public key");let p=e.fromBytes(d);return r.fromBytes(g).multiply(p).toBytes(E)}let f={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},h=Zn(a,c);return Object.freeze(f),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:h,Point:r,utils:f,lengths:o})}function Dl(r,t,e={}){let n=t;Nn(n),Ft(e,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),e=Object.assign({},e);let o=e.randomBytes===void 0?Kr:e.randomBytes,s=e.hmac===void 0?(x,w)=>_l(n,x,w):e.hmac,{Fp:i,Fn:a}=r,{ORDER:c,BITS:l}=a,{keygen:u,getPublicKey:f,getSharedSecret:h,utils:d,lengths:g}=Ad(r,e),E={prehash:!0,lowS:typeof e.lowS=="boolean"?e.lowS:!0,format:"compact",extraEntropy:!1},p=c*Al+_e<i.ORDER;function b(x){let w=c>>_e;return x>w}function v(x,w){if(!a.isValidNot0(w))throw new Error(`invalid signature ${x}: out of range 1..Point.Fn.ORDER`);return w}function S(){if(p)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function B(x,w){Pi(w);let A=g.signature,k=w==="compact"?A:w==="recovered"?A+1:void 0;return H(x,k)}class D{r;s;recovery;constructor(w,A,k){if(this.r=v("r",w),this.s=v("s",A),k!=null){if(S(),![0,1,2,3].includes(k))throw new Error("invalid recovery id");this.recovery=k}Object.freeze(this)}static fromBytes(w,A=E.format){B(w,A);let k;if(A==="der"){let{r:z,s:q}=Mt.toSig(H(w));return new D(z,q)}A==="recovered"&&(k=w[0],A="compact",w=w.subarray(1));let I=g.signature/2,L=w.subarray(0,I),O=w.subarray(I,I*2);return new D(a.fromBytes(L),a.fromBytes(O),k)}static fromHex(w,A){return this.fromBytes(ar(w),A)}assertRecovery(){let{recovery:w}=this;if(w==null)throw new Error("invalid recovery id: must be present");return w}addRecoveryBit(w){return new D(this.r,this.s,w)}recoverPublicKey(w){let{r:A,s:k}=this,I=this.assertRecovery(),L=I===2||I===3?A+c:A;if(!i.isValid(L))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let O=i.toBytes(L),z=r.fromBytes(ft(Tl((I&1)===0),O)),q=a.inv(L),U=C(H(w,void 0,"msgHash")),lt=a.create(-U*q),ht=a.create(k*q),dt=r.BASE.multiplyUnsafe(lt).add(z.multiplyUnsafe(ht));if(dt.is0())throw new Error("invalid recovery: point at infinify");return dt.assertValidity(),dt}hasHighS(){return b(this.s)}toBytes(w=E.format){if(Pi(w),w==="der")return ar(Mt.hexFromSig(this));let{r:A,s:k}=this,I=a.toBytes(A),L=a.toBytes(k);return w==="recovered"?(S(),ft(Uint8Array.of(this.assertRecovery()),I,L)):ft(I,L)}toHex(w){return ir(this.toBytes(w))}}Object.freeze(D.prototype),Object.freeze(D);let R=e.bits2int===void 0?function(w){if(w.length>8192)throw new Error("input is too large");let A=Be(w),k=w.length*8-l;return k>0?A>>BigInt(k):A}:e.bits2int,C=e.bits2int_modN===void 0?function(w){return a.create(R(w))}:e.bits2int_modN,T=jr(l);function N(x){return cr("num < 2^"+l,x,Qt,T),a.toBytes(x)}function j(x,w){return H(x,void 0,"message"),w?H(n(x),void 0,"prehashed message"):x}function F(x,w,A){let{lowS:k,prehash:I,extraEntropy:L}=Ci(A,E);x=j(x,I);let O=C(x),z=a.fromBytes(w);if(!a.isValidNot0(z))throw new Error("invalid private key");let q=[N(z),N(O)];if(L!=null&&L!==!1){let dt=L===!0?o(g.secretKey):L;q.push(H(dt,void 0,"extraEntropy"))}let U=ft(...q),lt=O;function ht(dt){let ot=R(dt);if(!a.isValidNot0(ot))return;let At=a.inv(ot),Ye=r.BASE.multiply(ot).toAffine(),Lr=a.create(Ye.x);if(Lr===Qt)return;let wn=a.create(At*a.create(lt+Lr*z));if(wn===Qt)return;let Ha=(Ye.x===Lr?0:2)|Number(Ye.y&_e),$a=wn;return k&&b(wn)&&($a=a.neg(wn),Ha^=1),new D(Lr,$a,p?void 0:Ha)}return{seed:U,k2sig:ht}}function m(x,w,A={}){let{seed:k,k2sig:I}=F(x,w,A);return zc(n.outputLen,a.BYTES,s)(k,I).toBytes(A.format)}function y(x,w,A,k={}){let{lowS:I,prehash:L,format:O}=Ci(k,E);if(A=H(A,void 0,"publicKey"),w=j(w,L),!Le(x)){let z=x instanceof D?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+z)}B(x,O);try{let z=D.fromBytes(x,O),q=r.fromBytes(A);if(I&&z.hasHighS())return!1;let{r:U,s:lt}=z,ht=C(w),dt=a.inv(lt),ot=a.create(ht*dt),At=a.create(U*dt),Ye=r.BASE.multiplyUnsafe(ot).add(q.multiplyUnsafe(At));return Ye.is0()?!1:a.create(Ye.x)===U}catch{return!1}}function _(x,w,A={}){let{prehash:k}=Ci(A,E);return w=j(w,k),D.fromBytes(x,"recovered").recoverPublicKey(w).toBytes()}return Object.freeze({keygen:u,getPublicKey:f,getSharedSecret:h,utils:d,lengths:g,Point:r,sign:m,verify:y,recoverPublicKey:_,Signature:D,hash:n})}var Ni={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Id={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Ll=BigInt(2);function Td(r){let t=Ni.p,e=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%t,u=l*l*r%t,f=Q(u,e,t)*u%t,h=Q(f,e,t)*u%t,d=Q(h,Ll,t)*l%t,g=Q(d,o,t)*d%t,E=Q(g,s,t)*g%t,p=Q(E,a,t)*E%t,b=Q(p,c,t)*p%t,v=Q(b,a,t)*E%t,S=Q(v,e,t)*u%t,B=Q(S,i,t)*g%t,D=Q(B,n,t)*l%t,R=Q(D,Ll,t);if(!Ri.eql(Ri.sqr(R),r))throw new Error("Cannot find square root");return R}var Ri=ur(Ni.p,{sqrt:Td}),kd=Il(Ni,{Fp:Ri,endo:Id}),gr=Dl(kd,Fc);function Bl(r,t,e,n){let o=de.digest(e instanceof Uint8Array?e:e.subarray());if(Qn(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),gr.verify(t,s,r,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new Cr(String(s))});try{return n?.signal?.throwIfAborted(),gr.verify(t,o.digest,r,{prehash:!1,format:"der"})}catch(s){throw new Cr(String(s))}}var ao=class{type="secp256k1";raw;_key;constructor(t){this._key=Pl(t),this.raw=Cl(this._key)}toMultihash(){return kt.digest(or(this))}toCID(){return et.createV1(114,this.toMultihash())}toString(){return it.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:at(this.raw,t.raw)}verify(t,e,n){return Bl(this._key,e,t,n)}};function Ol(r){return new ao(r)}function Cl(r){return gr.Point.fromBytes(r).toBytes()}function Pl(r){try{return gr.Point.fromBytes(r),r}catch(t){throw new vn(String(t))}}function Rl(r){let{Type:t,Data:e}=tn.decode(r.digest),n=e??new Uint8Array;switch(t){case St.Ed25519:return pl(n);case St.secp256k1:return Ol(n);case St.ECDSA:return xc(n);default:throw new Br}}function or(r){return tn.encode({Type:St[r.type],Data:r.raw})}var Fi={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Nl={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Fl=new globalThis.TextEncoder;function Dd(r,t){let e=Fi[t],n=Nl[t];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(t,n*e);return n}function Ld(r,t,e){if(e.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Fi[t],o=Nl[t],s=r;for(;s.length>0;){let i=Fl.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 Ui(r,{size:t=32,utf8Buffer:e}={}){if(!Fi[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 Ld(r,t,e);r=Fl.encode(r)}return Dd(r,t)}var en={hash:r=>Number(Ui(r,{size:32})),hashV:(r,t)=>Bd(en.hash(r,t))};function Bd(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),Z(t,"base16")}var Mi=64,zt=class{fp;h;seed;constructor(t,e,n,o=2){if(o>Mi)throw new TypeError("Invalid Fingerprint Size");let s=e.hashV(t,n),i=wt(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?at(this.fp,t.fp):!1}};function Ue(r,t){return Math.floor(Math.random()*(t-r))+r}var Me=class{contents;constructor(t){this.contents=new Array(t).fill(null)}has(t){if(!(t instanceof zt))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof zt))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 zt))throw new TypeError("Invalid Fingerprint");let e=Ue(0,this.contents.length-1),n=this.contents[e];return this.contents[e]=t,n}remove(t){if(!(t instanceof zt))throw new TypeError("Invalid Fingerprint");let e=this.contents.findIndex(n=>t.equals(n));return e>-1?(this.contents[e]=null,!0):!1}};var Cd=500,rn=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??en,this.seed=t.seed??Ue(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=Z(t));let e=new zt(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 Me(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new Me(this.bucketSize)),this.buckets[n].add(e)||this.buckets[o].add(e))return this.count++,!0;let s=[n,o],i=s[Ue(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new Me(this.bucketSize));for(let a=0;a<Cd;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 Me(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(t){typeof t=="string"&&(t=Z(t));let e=new zt(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=Z(t));let e=new zt(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}},Pd={1:.5,2:.84,4:.95,8:.98};function Od(r=.001){return r>.002?2:r>1e-5?4:8}function Ul(r,t=.001){let e=Od(t),n=Pd[e],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),Mi);return{filterSize:o,bucketSize:e,fingerprintSize:s}}var co=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??en,this.seed=t.seed??Ue(0,Math.pow(2,10)),this.filterSeries=[new rn({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(t){if(typeof t=="string"&&(t=Z(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 rn({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=Z(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=Z(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 lo(r,t=.001,e){return new co({...Ul(r,t),...e??{}})}function uo(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 Tt(`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 fo=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",l=2**(8*o)-1;for(;;){let u=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let h=Number.parseInt(f,t);if(!Number.isNaN(h))return h});if(u===void 0)break;if(s*=t,s+=u,s>l||(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 Rd=45,Nd=15,ho=new fo;function Ml(r){if(!(r.length>Nd))return ho.new(r).parseWith(()=>ho.readIPv4Addr())}function zl(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Rd))return ho.new(r).parseWith(()=>ho.readIPv6Addr())}function br(r){return!!Ml(r)}function po(r){return!!zl(r)}var Kl=Ka(ql(),1),qd=["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"],Kd=qd.map(r=>new Kl.Netmask(r));function Wi(r){for(let t of Kd)if(t.contains(r))return!0;return!1}function Vd(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function Wd(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 Wi(o)}function jd(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function Gd(r){let t=r.split(":"),e=t[t.length-1];return Wi(e)}function Zd(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 Vl(r){if(br(r))return Wi(r);if(Vd(r))return Wd(r);if(jd(r))return Gd(r);if(po(r))return Zd(r)}function Wl(r){try{let t=uo(r);switch(t.type){case"ip4":case"ip6":return Vl(t.host)??!1;default:return t.host==="localhost"}}catch{return!1}}function Ht(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var go=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||(t-1&t)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},Er=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new go(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 go(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 ji=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function bo(r={}){return Yd(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 Yd(r,t){t=t??{};let e=t.onEnd,n=new Er,o,s,i,a=Ht(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((p,b)=>{s=v=>{s=null,n.push(v);try{p(r(n))}catch(S){b(S)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Ht()})}},l=p=>s!=null?s(p):(n.push(p),o),u=p=>(n=new Er,s!=null?s({error:p}):(n.push({error:p}),o)),f=p=>{if(i)return o;if(t?.objectMode!==!0&&p?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:p})},h=p=>i?o:(i=!0,p!=null?u(p):l({done:!0})),d=()=>(n=new Er,h(),{done:!0}),g=p=>(h(p),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:d,throw:g,push:f,end:h,get readableLength(){return n.size},onEmpty:async p=>{let b=p?.signal;if(b?.throwIfAborted(),n.isEmpty())return;let v,S;b!=null&&(v=new Promise((B,D)=>{S=()=>{D(new ji)},b.addEventListener("abort",S)}));try{await Promise.race([a.promise,v])}finally{S!=null&&b!=null&&b?.removeEventListener("abort",S)}}},e==null)return o;let E=o;return o={[Symbol.asyncIterator](){return this},next(){return E.next()},throw(p){return E.throw(p),e!=null&&(e(p),e=void 0),{done:!0}},return(){return E.return(),e!=null&&(e(),e=void 0),{done:!0}},push:f,end(p){return E.end(p),e!=null&&(e(p),e=void 0),o},get readableLength(){return E.readableLength},onEmpty:p=>E.onEmpty(p)},o}var Gi=class r extends Error{name="TimeoutError";constructor(t,e){super(t,e),Error.captureStackTrace?.(this,r)}},jl=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function Zi(r,t){let{milliseconds:e,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=t,a,c,u=new Promise((f,h)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(i?.aborted){h(jl(i));return}if(i&&(c=()=>{h(jl(i))},i.addEventListener("abort",c,{once:!0})),r.then(f,h),e===Number.POSITIVE_INFINITY)return;let d=new Gi;a=s.setTimeout.call(void 0,()=>{if(n){try{f(n())}catch(g){h(g)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?f():o instanceof Error?h(o):(d.message=o??`Promise timed out after ${e} milliseconds`,h(d))},e)}).finally(()=>{u.clear(),c&&i&&i.removeEventListener("abort",c)});return u.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},u}var Xd=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 Qd(r,t,e){let n,o=new Promise((s,i)=>{if(e={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...e},!(e.count>=0&&(e.count===Number.POSITIVE_INFINITY||Number.isInteger(e.count))))throw new TypeError("The `count` option should be at least 0 or more");e.signal?.throwIfAborted();let a=[t].flat(),c=[],{addListener:l,removeListener:u}=Xd(r),f=async(...d)=>{let g=e.multiArgs?d:d[0];if(e.filter)try{if(!await e.filter(g))return}catch(E){n(),i(E);return}c.push(g),e.count===c.length&&(n(),s(c))},h=(...d)=>{n(),i(e.rejectionMultiArgs?d:d[0])};n=()=>{for(let d of a)u(d,f);for(let d of e.rejectionEvents)a.includes(d)||u(d,h)};for(let d of a)l(d,f);for(let d of e.rejectionEvents)a.includes(d)||l(d,h);e.signal&&e.signal.addEventListener("abort",()=>{h(e.signal.reason)},{once:!0}),e.resolveImmediately&&s(c)});if(o.cancel=n,typeof e.timeout=="number"){let s=Zi(o,{milliseconds:e.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function yo(r,t,e){typeof e=="function"&&(e={filter:e}),e={...e,count:1,resolveImmediately:!1};let n=Qd(r,t,e),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function Yi(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 wo=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};function Jd(r){return r.reason}async function xo(r,t,e){if(t==null)return r;let n=e?.translateError??Jd;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 Eo=class{deferred;signal;onProgress;constructor(t){this.signal=t?.signal,this.onProgress=t?.onProgress,this.deferred=Ht(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Pt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function tp(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var vo=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=tp(),this.status="queued",this.fn=t,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(t){this.controller.abort(t)}onAbort(){this.recipients.reduce((e,n)=>e&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Pt),this.cleanup())}async join(t){let e=new Eo(t);return this.recipients.push(e),t?.signal?.addEventListener("abort",this.onAbort),e.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let t=await xo(this.fn({...this.options??{},signal:this.controller.signal,onProgress:e=>{this.recipients.forEach(n=>{n.onProgress?.(e)})}}),this.controller.signal);this.recipients.forEach(e=>{e.deferred.resolve(t)}),this.status="complete"}catch(t){this.recipients.forEach(e=>{e.deferred.reject(t)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(t=>{t.cleanup(),t.signal?.removeEventListener("abort",this.onAbort)})}};var vr=class extends Vt{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=Yi(this.emitEmpty.bind(this),1),this.emitIdle=Yi(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 wo;let n=new vo(t,e);this.enqueue(n),this.safeDispatchEvent("add");let o=n.join(e).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s});return this.tryToStartAnother(),o}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(t=>{t.abort(new Pt)}),this.clear()}async onEmpty(t){this.size!==0&&await yo(this,"empty",t)}async onSizeLessThan(t,e){this.size<t||await yo(this,"next",{...e,filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await yo(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=bo({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),e.end(c)},o=c=>{c.detail!=null&&e.push(c.detail)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new Pt("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",s),this.addEventListener("idle",i),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),t?.signal?.removeEventListener("abort",a),n()}}};var yt=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},ce=class extends Error{static name="ValidationError";name="ValidationError"},_o=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},So=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function Qi(r){return t=>W(t,r)}function Ji(r){return t=>Z(t,r)}function _r(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function He(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(t)}function Gl(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=Z(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=He(n);return Ct([e,o],e.length+o.length)}function Zl(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=he.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=He(n);return Ct([e,o],e.length+o.length)}function ta(r){let t=r.subarray(0,r.length-2),e=r.subarray(r.length-2),n=W(t,"base32"),o=_r(e);return`${n}:${o}`}var ea=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 yt("Invalid byte value in IP address");t[n]=o}),t},Yl=function(r){let t=0;r=r.toString().trim();let e=r.split(":",8),n;for(n=0;n<e.length;n++){let s=br(e[n]),i;s&&(i=ea(e[n]),e[n]=W(i.subarray(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,W(i.subarray(2,4),"base16"))}if(e[0]==="")for(;e.length<8;)e.unshift("0");else if(e[e.length-1]==="")for(;e.length<8;)e.push("0");else if(e.length<8){for(n=0;n<e.length&&e[n]!=="";n++);let s=[n,1];for(n=9-e.length;n>0;n--)s.push("0");e.splice.apply(e,s)}let o=new Uint8Array(t+16);for(n=0;n<e.length;n++){e[n]===""&&(e[n]="0");let s=parseInt(e[n],16);if(isNaN(s)||s<0||s>65535)throw new yt("Invalid byte value in IP address");o[t++]=s>>8&255,o[t++]=s&255}return o},Xl=function(r){if(r.byteLength!==4)throw new yt("IPv4 address was incorrect length");let t=[];for(let e=0;e<r.byteLength;e++)t.push(r[e]);return t.join(".")},Ql=function(r){if(r.byteLength!==16)throw new yt("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 yt(`Invalid IPv6 address "${e}"`)}};function Jl(r){try{let t=new URL(`http://[${r}]`);return t.hostname.substring(1,t.hostname.length-1)}catch{throw new yt(`Invalid IPv6 address "${r}"`)}}var Xi=Object.values(Fr).map(r=>r.decoder),ep=(function(){let r=Xi[0].or(Xi[1]);return Xi.slice(2).forEach(t=>r=r.or(t)),r})();function tu(r){return ep.decode(r)}function eu(r){return t=>r.encoder.encode(t)}function rp(r){if(parseInt(r).toString()!==r)throw new ce("Value must be an integer")}function np(r){if(r<0)throw new ce("Value must be a positive integer, or zero")}function op(r){return t=>{if(t>r)throw new ce(`Value must be smaller than or equal to ${r}`)}}function sp(...r){return t=>{for(let e of r)e(t)}}var nn=sp(rp,np,op(65535));var mt=-1,ra=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 So(`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)}))}},le=new ra,wp=[{code:4,name:"ip4",size:32,valueToBytes:ea,bytesToValue:Xl,validate:r=>{if(!br(r))throw new ce(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:He,bytesToValue:_r,validate:nn},{code:273,name:"udp",size:16,valueToBytes:He,bytesToValue:_r,validate:nn},{code:33,name:"dccp",size:16,valueToBytes:He,bytesToValue:_r,validate:nn},{code:41,name:"ip6",size:128,valueToBytes:Yl,bytesToValue:Ql,stringToValue:Jl,validate:r=>{if(!po(r))throw new ce(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:mt},{code:43,name:"ipcidr",size:8,bytesToValue:Qi("base10"),valueToBytes:Ji("base10")},{code:53,name:"dns",size:mt},{code:54,name:"dns4",size:mt},{code:55,name:"dns6",size:mt},{code:56,name:"dnsaddr",size:mt},{code:132,name:"sctp",size:16,valueToBytes:He,bytesToValue:_r,validate:nn},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:mt,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:mt,bytesToValue:Qi("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Ji("base58btc")(r):et.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:ta,valueToBytes:Gl},{code:445,name:"onion3",size:296,bytesToValue:ta,valueToBytes:Zl},{code:446,name:"garlic64",size:mt},{code:447,name:"garlic32",size:mt},{code:448,name:"tls"},{code:449,name:"sni",size:mt},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:mt,bytesToValue:eu(Ss),valueToBytes:tu},{code:480,name:"http"},{code:481,name:"http-path",size:mt,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:mt}];wp.forEach(r=>{le.addProtocol(r)});function ru(r){let t=[],e=0;for(;e<r.length;){let n=Re(r,e),o=le.getProtocol(n),s=J(n),i=xp(o,r,e+s),a=0;i>0&&o.size===mt&&(a=J(i));let c=s+a+i,l={code:n,name:o.name,bytes:r.subarray(e,e+c)};if(i>0){let u=e+s+a,f=r.subarray(u,u+i);l.value=o.bytesToValue?.(f)??W(f)}t.push(l),e+=c}return t}function nu(r){let t=0,e=[];for(let n of r){if(n.bytes==null){let o=le.getProtocol(n.code),s=J(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??Z(n.value),a=i.byteLength,o.size===mt&&(c=J(a)));let l=new Uint8Array(s+c+a),u=0;pr(n.code,l,u),u+=s,i!=null&&(o.size===mt&&(pr(a,l,u),u+=c),l.set(i,u)),n.bytes=l}e.push(n.bytes),t+=n.bytes.byteLength}return Ct(e,t)}function ou(r){if(r.charAt(0)!=="/")throw new yt('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=le.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 yt(`Component ${o} was missing value`);e="value"}else if(e==="value"){let l={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new yt(`Component ${o} was missing value`);l.value=c.stringToValue?.(n)??n}t.push(l),n="",o="",e="protocol"}}}if(o!==""&&n!=="")throw new yt("Incomplete multiaddr");return t}function su(r){return`/${r.flatMap(t=>{if(t.value==null)return t.name;let e=le.getProtocol(t.code);if(e==null)throw new yt(`Unknown protocol code ${t.code}`);return[t.name,e.valueToString?.(t.value)??t.value]}).join("/")}`}function xp(r,t,e){return r.size==null||r.size===0?0:r.size>0?r.size/8:Re(t,e)}var Ep=Symbol.for("nodejs.util.inspect.custom"),pa=Symbol.for("@multiformats/multiaddr");function vp(r){if(r==null&&(r="/"),iu(r))return r.getComponents();if(r instanceof Uint8Array)return ru(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),ou(r);if(Array.isArray(r))return r;throw new yt("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Lo=class r{[pa]=!0;#t;#e;#r;constructor(t="/",e={}){this.#t=vp(t),e.validate!==!1&&_p(this)}get bytes(){return this.#r==null&&(this.#r=nu(this.#t)),this.#r}toString(){return this.#e==null&&(this.#e=su(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 _o(`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 at(this.bytes,t.bytes)}[Ep](){return`Multiaddr(${this.toString()})`}};function _p(r){r.getComponents().forEach(t=>{let e=le.getProtocol(t.code);t.value!=null&&e.validate?.(t.value)})}function iu(r){return!!r?.[pa]}function Bo(r){return new Lo(r)}var Co=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Ir=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Po=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},un=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Oo(r){return r[Symbol.asyncIterator]!=null}function au(r,t){if(r.byteLength>t)throw new Ir("Message length too long")}var No=r=>{let t=J(r),e=xt(t);return to(r,e),No.bytes=t,e};No.bytes=0;function Fo(r,t){t=t??{};let e=t.lengthEncoder??No,n=t?.maxDataLength??4194304;function*o(s){au(s,n);let i=e(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return Oo(r)?(async function*(){for await(let s of r)yield*o(s)})():(function*(){for(let s of r)yield*o(s)})()}Fo.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??No,n=t?.maxDataLength??4194304;return au(r,n),new ut(e(r.byteLength),r)};var qe;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(qe||(qe={}));var ma=r=>{let t=Re(r);return ma.bytes=J(t),t};ma.bytes=0;function fn(r,t){let e=new ut,n=qe.LENGTH,o=-1,s=t?.lengthDecoder??ma,i=t?.maxLengthLength??8,a=t?.maxDataLength??4194304;function*c(){for(;e.byteLength>0;){if(n===qe.LENGTH)try{if(o=s(e),o<0)throw new Co("Invalid message length");if(o>a)throw new Ir("Message length too long");let l=s.bytes;e.consume(l),t?.onLength!=null&&t.onLength(o),n=qe.DATA}catch(l){if(l instanceof RangeError){if(e.byteLength>i)throw new Po("Message length length too long");break}throw l}if(n===qe.DATA){if(e.byteLength<o)break;let l=e.sublist(0,o);e.consume(o),t?.onData!=null&&t.onData(l),yield l,n=qe.LENGTH}}}return Oo(r)?(async function*(){for await(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new un("Unexpected end of input")})():(function*(){for(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new un("Unexpected end of input")})()}fn.fromReader=(r,t)=>{let e=1,n=(async function*(){for(;;)try{let{done:s,value:i}=await r.next(e);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{e=1}})();return fn(n,{...t??{},onLength:s=>{e=s}})};var Uo=class extends vr{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};var ga=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 cu(r){let{name:t,metrics:e}=r,n;return e!=null?n=new ga({name:t,metrics:e}):n=new Map,n}function Ip(r){return r[Symbol.asyncIterator]!=null}function Tp(r){if(Ip(r))return(async()=>{for await(let t of r);})();for(let t of r);}var ba=Tp;function kp(r){let[t,e]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>t.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:t.next(),[e](){return this}}}var lu=kp;function Dp(r){return r[Symbol.asyncIterator]!=null}function Lp(r,t){let e=0;if(Dp(r))return(async function*(){for await(let c of r)yield t(c,e++)})();let n=lu(r),{value:o,done:s}=n.next();if(s===!0)return(function*(){})();let i=t(o,e++);if(typeof i.then=="function")return(async function*(){yield await i;for(let c of n)yield t(c,e++)})();let a=t;return(function*(){yield i;for(let c of n)yield a(c,e++)})()}var uu=Lp;function Bp(r){return r[Symbol.asyncIterator]!=null}function Cp(r,t){return Bp(r)?(async function*(){let e=0;if(!(t<1)){for await(let n of r)if(yield n,e++,e===t)return}})():(function*(){let e=0;if(!(t<1)){for(let n of r)if(yield n,e++,e===t)return}})()}var fu=Cp;var Mo=class extends Error{static name="AbortError";name="AbortError";constructor(t="The operation was aborted",...e){super(t,...e)}};async function Ke(r,t,e,n){let o=new Mo(n?.errorMessage);n?.errorCode!=null&&(o.code=n.errorCode);let s=n?.errorEvent??"error";return e?.aborted===!0?Promise.reject(o):new Promise((i,a)=>{function c(){wa(e,"abort",f),wa(r,t,l),wa(r,s,u)}let l=h=>{try{if(n?.filter?.(h)===!1)return}catch(d){c(),a(d);return}c(),i(h)},u=h=>{if(c(),h instanceof Error){a(h);return}a(h.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},f=()=>{c(),a(o)};ya(e,"abort",f),ya(r,t,l),ya(r,s,u)})}function ya(r,t,e){r!=null&&(hu(r)?r.addEventListener(t,e):r.addListener(t,e))}function wa(r,t,e){r!=null&&(hu(r)?r.removeEventListener(t,e):r.removeListener(t,e))}function hu(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var hn="/ipfs/bitswap/1.2.0";var tt;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(tt||(tt={}));var xa;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(xa||(xa={}));(function(r){r.codec=()=>mr(xa)})(tt||(tt={}));var Ve;(function(r){let t;r.codec=()=>(t==null&&(t=Xt((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.cid!=null&&s.cid.byteLength>0&&(i.uint32(10),i.bytes(s.cid)),s.priority!=null&&s.priority!==0&&(i.uint32(16),i.int32(s.priority)),s.cancel!=null&&(i.uint32(24),i.bool(s.cancel)),s.wantType!=null&&(i.uint32(32),tt.codec().encode(s.wantType,i)),s.sendDontHave!=null&&(i.uint32(40),i.bool(s.sendDontHave)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={cid:wt(0),priority:0},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.cid=s.bytes();break}case 2:{c.priority=s.int32();break}case 3:{c.cancel=s.bool();break}case 4:{c.wantType=tt.codec().decode(s);break}case 5:{c.sendDontHave=s.bool();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.cid`,value:s.bytes()};break}case 2:{yield{field:`${a}.priority`,value:s.int32()};break}case 3:{yield{field:`${a}.cancel`,value:s.bool()};break}case 4:{yield{field:`${a}.wantType`,value:tt.codec().decode(s)};break}case 5:{yield{field:`${a}.sendDontHave`,value:s.bool()};break}default:{s.skipType(u&7);break}}}})),t);function e(s){return Zt(s,r.codec())}r.encode=e;function n(s,i){return Gt(s,r.codec(),i)}r.decode=n;function o(s,i){return Yt(s,r.codec(),i)}r.stream=o})(Ve||(Ve={}));var dn;(function(r){let t;r.codec=()=>(t==null&&(t=Xt((s,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),s.entries!=null&&s.entries.length>0)for(let c of s.entries)i.uint32(10),Ve.codec().encode(c,i);s.full!=null&&(i.uint32(16),i.bool(s.full)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={entries:[]},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{if(a.limits?.entries!=null&&c.entries.length===a.limits.entries)throw new ae('Decode error - repeated field "entries" had too many elements');c.entries.push(Ve.codec().decode(s,s.uint32(),{limits:a.limits?.entries$}));break}case 2:{c.full=s.bool();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l={entries:0},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{if(c.limits?.entries!=null&&l.entries===c.limits.entries)throw new ae('Streaming decode error - repeated field "entries" had too many elements');for(let h of Ve.codec().stream(s,s.uint32(),`${a}.entries[]`,{limits:c.limits?.entries$}))yield{...h,index:l.entries};l.entries++;break}case 2:{yield{field:`${a}.full`,value:s.bool()};break}default:{s.skipType(f&7);break}}}})),t);function e(s){return Zt(s,r.codec())}r.encode=e;function n(s,i){return Gt(s,r.codec(),i)}r.decode=n;function o(s,i){return Yt(s,r.codec(),i)}r.stream=o})(dn||(dn={}));var We;(function(r){let t;r.codec=()=>(t==null&&(t=Xt((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.prefix!=null&&s.prefix.byteLength>0&&(i.uint32(10),i.bytes(s.prefix)),s.data!=null&&s.data.byteLength>0&&(i.uint32(18),i.bytes(s.data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={prefix:wt(0),data:wt(0)},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.prefix=s.bytes();break}case 2:{c.data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.prefix`,value:s.bytes()};break}case 2:{yield{field:`${a}.data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),t);function e(s){return Zt(s,r.codec())}r.encode=e;function n(s,i){return Gt(s,r.codec(),i)}r.decode=n;function o(s,i){return Yt(s,r.codec(),i)}r.stream=o})(We||(We={}));var Bt;(function(r){r.HaveBlock="HaveBlock",r.DoNotHaveBlock="DoNotHaveBlock"})(Bt||(Bt={}));var zo;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DoNotHaveBlock=1]="DoNotHaveBlock"})(zo||(zo={}));(function(r){r.codec=()=>mr(zo)})(Bt||(Bt={}));var je;(function(r){let t;r.codec=()=>(t==null&&(t=Xt((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.cid!=null&&s.cid.byteLength>0&&(i.uint32(10),i.bytes(s.cid)),s.type!=null&&zo[s.type]!==0&&(i.uint32(16),Bt.codec().encode(s.type,i)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={cid:wt(0),type:Bt.HaveBlock},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.cid=s.bytes();break}case 2:{c.type=Bt.codec().decode(s);break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.cid`,value:s.bytes()};break}case 2:{yield{field:`${a}.type`,value:Bt.codec().decode(s)};break}default:{s.skipType(u&7);break}}}})),t);function e(s){return Zt(s,r.codec())}r.encode=e;function n(s,i){return Gt(s,r.codec(),i)}r.decode=n;function o(s,i){return Yt(s,r.codec(),i)}r.stream=o})(je||(je={}));var Ge;(function(r){let t;r.codec=()=>(t==null&&(t=Xt((s,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),s.wantlist!=null&&(i.uint32(10),dn.codec().encode(s.wantlist,i)),s.blocks!=null&&s.blocks.length>0)for(let c of s.blocks)i.uint32(26),We.codec().encode(c,i);if(s.blockPresences!=null&&s.blockPresences.length>0)for(let c of s.blockPresences)i.uint32(34),je.codec().encode(c,i);s.pendingBytes!=null&&s.pendingBytes!==0&&(i.uint32(40),i.int32(s.pendingBytes)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={blocks:[],blockPresences:[],pendingBytes:0},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.wantlist=dn.codec().decode(s,s.uint32(),{limits:a.limits?.wantlist});break}case 3:{if(a.limits?.blocks!=null&&c.blocks.length===a.limits.blocks)throw new ae('Decode error - repeated field "blocks" had too many elements');c.blocks.push(We.codec().decode(s,s.uint32(),{limits:a.limits?.blocks$}));break}case 4:{if(a.limits?.blockPresences!=null&&c.blockPresences.length===a.limits.blockPresences)throw new ae('Decode error - repeated field "blockPresences" had too many elements');c.blockPresences.push(je.codec().decode(s,s.uint32(),{limits:a.limits?.blockPresences$}));break}case 5:{c.pendingBytes=s.int32();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l={blocks:0,blockPresences:0},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{yield*dn.codec().stream(s,s.uint32(),`${a}.wantlist`,{limits:c.limits?.wantlist});break}case 3:{if(c.limits?.blocks!=null&&l.blocks===c.limits.blocks)throw new ae('Streaming decode error - repeated field "blocks" had too many elements');for(let h of We.codec().stream(s,s.uint32(),`${a}.blocks[]`,{limits:c.limits?.blocks$}))yield{...h,index:l.blocks};l.blocks++;break}case 4:{if(c.limits?.blockPresences!=null&&l.blockPresences===c.limits.blockPresences)throw new ae('Streaming decode error - repeated field "blockPresences" had too many elements');for(let h of je.codec().stream(s,s.uint32(),`${a}.blockPresences[]`,{limits:c.limits?.blockPresences$}))yield{...h,index:l.blockPresences};l.blockPresences++;break}case 5:{yield{field:`${a}.pendingBytes`,value:s.int32()};break}default:{s.skipType(f&7);break}}}})),t);function e(s){return Zt(s,r.codec())}r.encode=e;function n(s,i){return Gt(s,r.codec(),i)}r.decode=n;function o(s,i){return Yt(s,r.codec(),i)}r.stream=o})(Ge||(Ge={}));function du(r,t){for(let[e,n]of t.wantlist.entries()){let o=r.wantlist.get(e);o!=null&&(o.priority>n.priority&&(n.priority=o.priority),n.cancel=n.cancel??o.cancel,n.wantType=n.wantType??o.wantType,n.sendDontHave=n.sendDontHave??o.sendDontHave),r.wantlist.set(e,n)}for(let[e,n]of t.blockPresences.entries())r.blockPresences.set(e,n);for(let[e,n]of t.blocks.entries())r.blocks.set(e,n);return t.full&&!r.full&&(r.full=!0),r}var Ho=class extends Error{static name="BlockTooLargeError";constructor(t="Block too large"){super(t),this.name="BlockTooLargeError"}};var Pp=4193648,Op=Pp+16;function*pu(r,t){let e=[...r.wantlist.values()],n=[...r.blockPresences.values()],o=[...r.blocks.values()],s=0,i=0,a=0,c=!1;for(;;){let l={wantlist:{full:r.full??!1,entries:[]},blockPresences:[],blocks:[],pendingBytes:0},u=Ge.encode(l).byteLength,{added:f,hasMore:h,newSize:d}=Ea(o,l.blocks,a,t,u,Rp);a+=f,u=d;let g=h;({added:f,hasMore:h,newSize:d}=Ea(n,l.blockPresences,i,t,u,Np)),i+=f,u=d;let E=h;if({added:f,hasMore:h,newSize:d}=Ea(e,l.wantlist.entries,s,t,u,Fp),s+=f,u=d,c=!g&&!E&&!h,c||(l.wantlist.full=!1),yield Ge.encode(l),c)break}}function Ea(r,t,e,n,o,s){let i=0,a=!1;for(let c=e;c<r.length;c++){let l=r[c],u=s(l);if(u>Op)throw new Ho("Cannot send block as after encoding it is over the max message size");let f=o+u;if(f>n){a=!0;break}t.push(l),i++,o=f}return{hasMore:a,added:i,newSize:o}}function Rp(r){return va(3,We.encode(r))}function Np(r){return va(4,je.encode(r))}function Fp(r){return va(1,Ve.encode(r))}function va(r,t){let e=J(r),n=J(t.byteLength);return e+n+t.byteLength}var $o=class extends Vt{log;libp2p;routing;protocols;running;maxInboundStreams;maxOutboundStreams;messageReceiveTimeout;messageSendTimeout;registrarIds;metrics;sendQueue;runOnLimitedConnections;maxOutgoingMessageSize;maxIncomingMessageSize;constructor(t,e={}){super(),this.log=t.logger.forComponent("helia:bitswap:network"),this.libp2p=t.libp2p,this.routing=t.routing,this.protocols=e.protocols??[hn],this.registrarIds=[],this.running=!1,this._onStream=this._onStream.bind(this),this.maxInboundStreams=e.maxInboundStreams??1024,this.maxOutboundStreams=e.maxOutboundStreams??1024,this.messageReceiveTimeout=e.messageReceiveTimeout??1e4,this.messageSendTimeout=e.messageSendTimeout??1e4,this.runOnLimitedConnections=e.runOnLimitedConnections??!1,this.maxIncomingMessageSize=e.maxIncomingMessageSize??4194304,this.maxOutgoingMessageSize=e.maxOutgoingMessageSize??e.maxIncomingMessageSize??4194304,this.metrics={blocksSent:t.metrics?.registerCounter("helia_bitswap_sent_blocks_total"),dataSent:t.metrics?.registerCounter("helia_bitswap_sent_data_bytes_total")},this.sendQueue=new Uo({concurrency:e.messageSendConcurrency??50,metrics:t.metrics,metricName:"helia_bitswap_message_send_queue"})}async start(){if(this.running)return;this.running=!0,await this.libp2p.handle(this.protocols,this._onStream,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnections});let t={onConnect:e=>{this.safeDispatchEvent("peer:connected",{detail:e})},onDisconnect:e=>{this.safeDispatchEvent("peer:disconnected",{detail:e})}};this.registrarIds=[];for(let e of this.protocols)this.registrarIds.push(await this.libp2p.register(e,t));this.libp2p.getConnections().forEach(e=>{this.safeDispatchEvent("peer:connected",{detail:e.remotePeer})})}async stop(){if(this.running=!1,await this.libp2p.unhandle(this.protocols),this.registrarIds!=null){for(let t of this.registrarIds)this.libp2p.unregister(t);this.registrarIds=[]}}_onStream(t,e){this.running&&Promise.resolve().then(async()=>{this.log("incoming new bitswap %s stream from %p",t.protocol,e.remotePeer);let n=()=>{t.status==="open"?t.abort(new In(`Incoming Bitswap stream timed out after ${this.messageReceiveTimeout}ms`)):this.log("stream aborted with status %s",t.status)},o=AbortSignal.timeout(this.messageReceiveTimeout);o.addEventListener("abort",n),await t.close({signal:o});let s=bo();t.addEventListener("message",i=>{s.push(i.data)}),t.addEventListener("remoteCloseWrite",()=>{s.end()}),t.addEventListener("close",i=>{i.error!=null&&s.end(i.error)});for await(let i of fn(s,{maxDataLength:this.maxIncomingMessageSize}))try{let a=Ge.decode(i);this.log("incoming new bitswap %s message from %p on stream",t.protocol,e.remotePeer,t.id),this.safeDispatchEvent("bitswap:message",{detail:{peer:e.remotePeer,message:a,connection:e}}),o.removeEventListener("abort",n),o=AbortSignal.timeout(this.messageReceiveTimeout),o.addEventListener("abort",n)}catch(a){this.log.error("error reading incoming bitswap message from %p on stream - %e",e.remotePeer,t.id,a),t.abort(a);break}}).catch(n=>{this.log.error("error handling incoming stream from %p - %e",e.remotePeer,n),t.abort(n)})}async*findProviders(t,e){e?.onProgress?.(new V("bitswap:find-providers",t));for await(let n of this.routing.findProviders(t,e)){if(!await this.libp2p.isDialable(n.multiaddrs,{runOnLimitedConnection:this.runOnLimitedConnections})){this.log("skipping peer %p as they are not dialable - %a",n.id,n.multiaddrs);continue}e?.onProgress?.(new V("bitswap:found-provider",{type:"bitswap",cid:t,provider:n,routing:n.routing})),yield n}}async findAndConnect(t,e){e?.providers!=null&&await Promise.all(e.providers.map(async n=>this.connectTo(n).catch(o=>{this.log.error("could not connect to supplied provider - %e",o)}))),await ba(uu(fu(this.findProviders(t,e),e?.maxProviders??3),async n=>this.connectTo(n.id,e))).catch(n=>{this.log.error(n)})}async sendMessage(t,e,n){if(!this.running)throw new Error("network isn't running");let o=this.sendQueue.queue.find(s=>t.equals(s.options.peerId)&&s.status==="queued");if(o!=null){o.options.message=du(o.options.message,e),await o.join(n);return}await this.sendQueue.add(async s=>{let i=s.message;if(i==null)throw new Tt("No message to send");this.log("sendMessage to %p",t),s.onProgress?.(new V("bitswap:send-wantlist",t));let a=await this.libp2p.dialProtocol(t,hn,s);await a.closeRead(s);try{for(let c of pu(i,this.maxOutgoingMessageSize))a.send(Fo.single(c))||await a.onDrain(s);await a.close(s)}catch(c){this.log.error("error sending message to %p - %e",t,c),s?.onProgress?.(new V("bitswap:send-wantlist:error",{peer:t,error:c})),a.abort(c)}this._updateSentStats(i.blocks)},{onProgress:n?.onProgress,peerId:t,signal:n?.signal??AbortSignal.timeout(this.messageSendTimeout),message:e})}async connectTo(t,e){if(!this.running)throw new Tn("Network isn't running");e?.onProgress?.(new V("bitswap:dial",t));let[n]=await Promise.all([this.libp2p.dial(t,e),Ke(this.libp2p,"peer:identify",e?.signal,{filter:o=>{if(!o.detail.peerId.equals(t))return!1;if(o.detail.protocols.includes(hn))return!0;throw new An(`${t} did not support ${hn}`)}})]);return n}_updateSentStats(t){let e=0;for(let n of t.values())e+=n.data.byteLength;this.metrics.dataSent?.increment(e),this.metrics.blocksSent?.increment(t.size)}};var gu=Symbol.for("nodejs.util.inspect.custom"),jp=114,pn=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()})`}[kn]=!0;toString(){return this.string==null&&(this.string=it.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return et.createV1(jp,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return at(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return at(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[gu](){return`PeerId(${this.toString()})`}},qo=class extends pn{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},Ko=class extends pn{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},Vo=class extends pn{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},Gp=2336,mn=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=kt.digest(Z(this.url))}[gu](){return`PeerId(${this.url})`}[kn]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return et.createV1(Gp,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=W(t)),t.toString()===this.toString())}};var Zp=114,bu=2336;function Yp(r){if(Qp(r))return new qo({multihash:r});if(Xp(r))try{let t=Rl(r);if(t.type==="Ed25519")return new Ko({multihash:r,publicKey:t});if(t.type==="secp256k1")return new Vo({multihash:r,publicKey:t})}catch{let e=W(r.digest);return new mn(new URL(e))}throw new Sn("Supplied PeerID Multihash is invalid")}function yu(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==Zp&&r.code!==bu)throw new _n("Supplied PeerID CID is invalid");if(r.code===bu){let t=W(r.multihash.digest);return new mn(new URL(t))}return Yp(r.multihash)}function Xp(r){return r.code===kt.code}function Qp(r){return r.code===de.code}function Wo(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}var gn=class{map;constructor(t){if(this.map=new Map,t!=null)for(let[e,n]of t.entries())this.map.set(e.toString(),{key:e,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(t){return this.map.delete(t.toString())}entries(){return Wo(this.map.entries(),t=>[t[1].key,t[1].value])}forEach(t){this.map.forEach((e,n)=>{t(e.value,e.key,this)})}get(t){return this.map.get(t.toString())?.value}has(t){return this.map.has(t.toString())}set(t,e){this.map.set(t.toString(),{key:t,value:e})}keys(){return Wo(this.map.values(),t=>t.key)}values(){return Wo(this.map.values(),t=>t.value)}get size(){return this.map.size}};var _a=class extends gn{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 bn(r){let{name:t,metrics:e}=r,n;return e!=null?n=new _a({name:t,metrics:e}):n=new gn,n}function Jp(r){return r[Symbol.asyncIterator]!=null}function tm(r){if(Jp(r))return(async()=>{let n=new Uint8Array(0);for await(let o of r)n=Ct([n,o],n.length+o.length);return n})();let t=[],e=0;for(let n of r)t.push(n),e+=n.byteLength;return Ct(t,e)}var wu=tm;var ue=class{full;pendingBytes;wantlist;blocks;blockPresences;constructor(t=!1,e=0){this.full=t,this.wantlist=new Map,this.blocks=new Map,this.blockPresences=new Map,this.pendingBytes=0}addWantlistEntry(t,e){let n=ee.encode(t.multihash.bytes);this.wantlist.set(n,e)}addBlockPresence(t,e){let n=ee.encode(t.multihash.bytes);this.blockPresences.set(n,e)}addBlock(t,e){let n=ee.encode(t.multihash.bytes);this.blocks.set(n,e)}};function em(r){let t=new Uint8Array(r.reduce((n,o)=>n+J(o),0)),e=0;for(let n of r)t=to(n,t,e),e+=J(n);return t}var xu=em;function Sa(r){return xu([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var jo=class{peerId;blockstore;network;wants;exchangeCount;bytesSent;bytesReceived;lastExchange;maxSizeReplaceHasWithBlock;log;doNotResendBlockWindow;maxWantListSize;constructor(t,e){this.peerId=t.peerId,this.blockstore=t.blockstore,this.network=t.network,this.wants=new Map,this.log=t.logger.forComponent(`helia:bitswap:ledger:${t.peerId}`),this.exchangeCount=0,this.bytesSent=0,this.bytesReceived=0,this.maxSizeReplaceHasWithBlock=e.maxSizeReplaceHasWithBlock??1024,this.doNotResendBlockWindow=e.doNotResendBlockWindow??5e3,this.maxWantListSize=e.maxWantListSize??1024}sentBytes(t){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesSent+=t}receivedBytes(t){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesReceived+=t}debtRatio(){return this.bytesSent/(this.bytesReceived+1)}removeExpiredWants(){this.wants.forEach((t,e)=>{t.expires!=null&&t.expires<Date.now()&&this.wants.delete(e)})}addWants(t){if(t==null)return;t.full===!0&&this.wants.forEach((n,o)=>{n.status==="want"&&this.wants.delete(o)});for(let n of t.entries){let o=et.decode(n.cid),s=W(o.multihash.bytes,"base64");if(n.cancel===!0)this.log("peer %p cancelled want of block for %c",this.peerId,o),this.wants.delete(s);else{n.wantType===tt.WantHave?this.log("peer %p wanted block presence for %c",this.peerId,o):this.log("peer %p wanted block for %c",this.peerId,o);let i=this.wants.get(s);if(i!=null){let a=i.status==="sent"||i.status==="sending",c=i.wantType===tt.WantHave&&(n.wantType==null||n.wantType===tt.WantBlock);a&&c&&(i.status="want"),i.priority=n.priority,i.wantType=n.wantType??tt.WantBlock,i.sendDontHave=n.sendDontHave??!1;continue}this.wants.set(s,{cid:o,priority:n.priority,wantType:n.wantType??tt.WantBlock,sendDontHave:n.sendDontHave??!1,status:"want",created:Date.now()})}}let e=[...this.wants.entries()].filter(([n,o])=>o.status==="want");e.length>this.maxWantListSize&&this.truncateWants(e)}truncateWants(t){t=t.sort((n,o)=>n[1].created<o[1].created?-1:o[1].created<n[1].created?1:0).sort((n,o)=>n[1].haveBlock===!1?-1:o[1].haveBlock===!1?1:0).sort((n,o)=>n[1].priority<o[1].priority?-1:o[1].priority<n[1].priority?1:0);let e=t.length-this.maxWantListSize;for(let n=0;n<e;n++)this.wants.delete(t[n][0])}getWants(){return[...this.wants.values()]}hasWant(t){let e=W(t.multihash.bytes,"base64");return this.wants.has(e)}async sendBlocksToPeer(t){let e=new ue,n=new Set;this.removeExpiredWants();let o=[...this.wants.entries()].filter(([s,i])=>i.status==="want");o.forEach(([s,i])=>{i.status="sending"});for(let[s,i]of o)try{let a=await wu(this.blockstore.get(i.cid,t));if(i.status!=="sending")continue;i.wantType===tt.WantHave?a.byteLength<this.maxSizeReplaceHasWithBlock?(this.log("sending have and block for %c",i.cid),n.add(s),e.addBlock(i.cid,{data:a,prefix:Sa(i.cid)})):(this.log("sending have for %c",i.cid),e.addBlockPresence(i.cid,{cid:i.cid.bytes,type:Bt.HaveBlock})):(this.log("sending block for %c",i.cid),n.add(s),e.addBlock(i.cid,{data:a,prefix:Sa(i.cid)})),i.status="sent",i.expires=Date.now()+this.doNotResendBlockWindow}catch(a){if(a.name!=="NotFoundError")throw a;if(i.status="want",i.haveBlock=!1,this.log("do not have block for %c",i.cid),!i.sendDontHave||i.sentDoNotHave===!0)continue;i.sentDoNotHave=!0,e.addBlockPresence(i.cid,{cid:i.cid.bytes,type:Bt.DoNotHaveBlock})}(e.blocks.size>0||e.blockPresences.size>0)&&(this.log("sending message"),await this.network.sendMessage(this.peerId,e,t),this.log("sent message"),this.sentBytes([...e.blocks.values()].reduce((s,i)=>s+i.data.byteLength,0)))}};var Go=class{blockstore;network;ledgerMap;maxSizeReplaceHasWithBlock;doNotResendBlockWindow;maxWantListSize;log;logger;constructor(t,e={}){this.blockstore=t.blockstore,this.network=t.network,this.maxSizeReplaceHasWithBlock=e.maxSizeReplaceHasWithBlock,this.doNotResendBlockWindow=e.doNotResendBlockWindow,this.maxWantListSize=e.maxWantListSize,this.log=t.logger.forComponent("helia:bitswap:peer-want-lists"),this.logger=t.logger,this.ledgerMap=bn({name:"helia_bitswap_ledger_map",metrics:t.metrics}),this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.connection.remotePeer,n.detail.message).catch(o=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.connection.remotePeer,o)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}ledgerForPeer(t){let e=this.ledgerMap.get(t);if(e!=null)return{peer:e.peerId,value:e.debtRatio(),sent:e.bytesSent,received:e.bytesReceived,exchanged:e.exchangeCount}}wantListForPeer(t){let e=this.ledgerMap.get(t);if(e!=null)return e.removeExpiredWants(),e.getWants()}peers(){return Array.from(this.ledgerMap.values()).map(t=>t.peerId)}async receiveMessage(t,e){let n=this.ledgerMap.get(t);n==null&&(n=new jo({peerId:t,blockstore:this.blockstore,network:this.network,logger:this.logger},{maxSizeReplaceHasWithBlock:this.maxSizeReplaceHasWithBlock,doNotResendBlockWindow:this.doNotResendBlockWindow,maxWantListSize:this.maxWantListSize}),this.ledgerMap.set(t,n)),n.receivedBytes(e.blocks?.reduce((o,s)=>o+s.data.byteLength,0)??0),n.removeExpiredWants(),n.addWants(e.wantlist),this.log("send blocks to peer"),await n.sendBlocksToPeer()}async receivedBlock(t,e){let n=[];for(let o of this.ledgerMap.values())o.hasWant(t)&&n.push(o);await Promise.all(n.map(async o=>o.sendBlocksToPeer(e)))}peerDisconnected(t){this.ledgerMap.delete(t)}};var om=Ka(vu(),1);var Tr;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Tr||(Tr={}));var Zo=class extends Error{static name="InsufficientProvidersError";constructor(t="Insufficient providers found"){super(t),this.name="InsufficientProvidersError"}};var Ze=class extends Vt{initialPeerSearchComplete;requests;logName;log;logger;minProviders;maxProviders;providers;evictionFilter;initialProviders;cidPeerFilterSize;constructor(t,e){super(),this.logName=e.name,this.logger=t.logger,this.log=t.logger.forComponent(this.logName),this.requests=new Map,this.minProviders=e.minProviders??1,this.maxProviders=e.maxProviders??5,this.cidPeerFilterSize=e.cidPeerFilterSize??100,this.providers=[],this.evictionFilter=lo(this.maxProviders),this.initialProviders=[...e.providers??[]]}async retrieve(t,e={}){let n=ee.encode(t.multihash.bytes),o=this.requests.get(n);if(o!=null)return this.log("join existing request for %c",t),o.observers++,o.promise;let s=Ht(),i={promise:s.promise,observers:1,queryFilter:lo(this.cidPeerFilterSize)};this.requests.set(n,i);let a=!1;this.initialPeerSearchComplete==null&&(a=!0,this.log=this.logger.forComponent(`${this.logName}:${t}`),this.initialPeerSearchComplete=this.findProviders(t,this.minProviders,e));let c=!1,l=new vr({concurrency:this.maxProviders});l.addEventListener("failure",h=>{this.log.error("error querying provider %s, evicting from session - %e",h.detail.job.options.provider,h.detail.error),this.evict(h.detail.job.options.provider)}),l.addEventListener("success",h=>{c=!0,s.resolve(h.detail.result)}),l.addEventListener("idle",()=>{if(c){this.log.trace("session idle, found block");return}if(e.signal?.aborted===!0){this.log.trace("session idle, signal aborted");return}Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",t);for(let h=0;h<this.minProviders&&this.providers.length!==0;h++){let d=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(d)}await this.findProviders(t,this.minProviders,e),this.log("found new providers re-retrieving %c",t),this.requests.delete(n),s.resolve(await this.retrieve(t,e))}).catch(h=>{this.log.error("could not find new providers for %c - %e",t,h),s.reject(h)})});let u=h=>{let d=this.toFilterKey(h.detail);i.queryFilter.has(d)||(i.queryFilter.add(d),this.emitFoundProviderProgressEvent(t,h.detail,e),l.add(async()=>this.queryProvider(t,h.detail,e),{provider:h.detail}).catch(g=>{e.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",t,g)}))};if(this.addEventListener("provider",u),a)try{await xo(this.initialPeerSearchComplete,e.signal),a&&this.log("found initial session peers for %c",t)}catch(h){throw a&&this.log("failed to find initial session peers for %c - %e",t,h),this.requests.delete(n),i.observers>1&&s.reject(h),h}Promise.all([...this.providers].filter(h=>{let d=this.toFilterKey(h),g=i.queryFilter.has(d);return g||i.queryFilter.add(this.toFilterKey(h)),!g}).map(async h=>l.add(async()=>this.queryProvider(t,h,e),{provider:h}))).catch(h=>{e.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",t,h)});let f=()=>{s.reject(new Pt(e.signal?.reason??"Session aborted")),l.abort()};e.signal?.addEventListener("abort",f);try{return await s.promise}finally{this.removeEventListener("provider",u),e.signal?.removeEventListener("abort",f),l.clear(),this.requests.delete(n)}}evict(t){this.evictionFilter.add(this.toFilterKey(t));let e=this.providers.findIndex(n=>this.equals(n,t));e!==-1&&this.providers.splice(e,1)}isEvicted(t){return this.evictionFilter.has(this.toFilterKey(t))}hasProvider(t){return!!(this.providers.find(e=>this.equals(e,t))!=null||this.isEvicted(t))}async addPeer(t,e){let n=await this.convertToProvider(t,"manually-added",e);n==null||this.hasProvider(n)||(this.providers.push(n),this.safeDispatchEvent("provider",{detail:n}))}async findProviders(t,e,n){let o=Ht(),s=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c - %d initial providers",e,this.maxProviders,t,this.initialProviders.length);let i=this,a=async function*(){for(;i.initialProviders.length>0;){let l=i.initialProviders.pop();if(l==null)continue;let u=await i.convertToProvider(l,"manual",n);u!=null&&(yield u)}},c=async function*(){yield*a(),yield*i.findNewProviders(t,n)};for await(let l of c()){if(this.providers.length===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(l)&&(this.log("found %d providers, %d in session",s,this.providers.length),this.providers.push(l),this.safeDispatchEvent("provider",{detail:l}),s++,this.providers.length===e&&(this.log("session is ready with %d peer(s), new peers present",this.providers.length),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers %d",this.providers.length);break}}if(this.log("found %d new session peers while trying to find %d, %d in session",s,e,this.providers.length),this.providers.length<e)throw new Zo(`Found ${s} of ${e} ${this.name} providers for ${t}, ${this.providers.length} in session after evictions`)}).catch(i=>{this.log.error("error searching routing for potential session peers for %c - %e",t,i),o.reject(i)}),o.promise}};var Aa=class extends Ze{name="bitswap-session";wantList;network;libp2p;constructor(t,e){super(t,{...e,name:"helia:bitswap:session"}),this.wantList=t.wantList,this.network=t.network,this.libp2p=t.libp2p}async queryProvider(t,e,n){this.log("sending WANT-BLOCK for %c to %p",t,e);let o=await this.wantList.wantSessionBlock(t,e.peerId,n);if(this.log("%p %s %c",e,o.has?"has":"does not have",t),o.has){if(o.block!=null)return o.block;throw new Error("Provider has block but did not send it to us")}throw new Error("Provider did not have block")}async*findNewProviders(t,e={}){for await(let n of this.network.findProviders(t,e))yield{peerId:n.id,routing:n.routing,toString:()=>`Bitswap(${n.id})`}}toFilterKey(t){return t.peerId.toMultihash().bytes}equals(t,e){return t.peerId.equals(e.peerId)}async convertToProvider(t,e,n){if(Xe(t))return{peerId:t,routing:e,toString:()=>`Bitswap(${t})`};if(await this.libp2p.isDialable(t)!==!1)try{let o=await this.libp2p.dial(t,n);return{peerId:o.remotePeer,routing:e,toString:()=>`Bitswap(${o.remotePeer})`}}catch{}}emitFoundProviderProgressEvent(t,e,n){n?.onProgress?.(new V("bitswap:found-provider",{type:"bitswap",cid:t,provider:{id:e.peerId,multiaddrs:[],routing:e.routing},routing:e.routing}))}};function _u(r,t){return new Aa(r,t)}var Yo=class{blocksReceived;duplicateBlocksReceived;dataReceived;duplicateDataReceived;constructor(t){this.blocksReceived=t.metrics?.registerMetricGroup("helia_bitswap_received_blocks"),this.duplicateBlocksReceived=t.metrics?.registerMetricGroup("helia_bitswap_duplicate_received_blocks"),this.dataReceived=t.metrics?.registerMetricGroup("helia_bitswap_data_received_bytes"),this.duplicateDataReceived=t.metrics?.registerMetricGroup("helia_bitswap_duplicate_data_received_bytes")}updateBlocksReceived(t=1,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.blocksReceived?.increment(n)}updateDuplicateBlocksReceived(t=1,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.duplicateBlocksReceived?.increment(n)}updateDataReceived(t,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.dataReceived?.increment(n)}updateDuplicateDataReceived(t,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.duplicateDataReceived?.increment(n)}};function cm(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let t=[];for(;r.length>0;){let e=Re(r);t.push(e),r=r.slice(J(e))}return t}var Su=cm;var Xo=class extends Vt{peers;wants;network;log;sendWantlistDebounce;sendMessagesTimeout;getHasher;sendingMessages;constructor(t,e={}){super(),this.peers=bn({name:"helia_bitswap_peers",metrics:t.metrics}),this.wants=cu({name:"helia_bitswap_wantlist",metrics:t.metrics}),this.network=t.network,this.sendWantlistDebounce=e.sendWantlistDebounce??10,this.log=t.logger.forComponent("helia:bitswap:wantlist"),this.getHasher=t.getHasher,this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.connection,n.detail.message).catch(o=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.connection.remotePeer,o)})}),this.network.addEventListener("peer:connected",n=>{this.peerConnected(n.detail).catch(o=>{this.log.error("error processing newly connected bitswap peer %p - %e",n.detail,o)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}async addEntry(t,e){let n=W(t.multihash.bytes,"base64"),o=this.wants.get(n);o==null&&(o={cid:t,priority:e.priority??1,wantType:e.wantType??tt.WantBlock,cancel:!1,sendDontHave:!0,onProgress:[]},this.wants.set(n,o)),e.onProgress!=null&&o.onProgress.push({onProgress:e.onProgress,signal:e.signal}),o.wantType===tt.WantHave&&e.wantType===tt.WantBlock&&(o.wantType=tt.WantBlock),await this.sendMessagesDebounced();try{return e.wantType===tt.WantBlock?(await Ke(this,"block",e?.signal,{filter:a=>at(t.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await Ke(this,"presence",e?.signal,{filter:i=>at(t.multihash.digest,i.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail}finally{e.signal?.aborted===!0&&(this.log("want for %c was aborted, cancelling want",t),o.cancel=!0,await this.sendMessagesDebounced())}}async sendMessagesDebounced(){await this.sendingMessages?.promise,clearTimeout(this.sendMessagesTimeout),this.sendMessagesTimeout=setTimeout(()=>{this.sendMessages().catch(t=>{this.log("error sending messages to peers - %e",t)})},this.sendWantlistDebounce)}async sendMessages(){this.sendingMessages=Ht(),await Promise.all([...this.peers.entries()].map(async([t,e])=>{let n=new Set,o=new ue;for(let[s,i]of this.wants.entries())e.has(s)||i.cancel||(n.add(s),o.addWantlistEntry(i.cid,{cid:i.cid.bytes,priority:i.priority,wantType:i.wantType,cancel:i.cancel,sendDontHave:i.sendDontHave}));if(o.wantlist.size!==0)try{await this.network.sendMessage(t,o,{onProgress:s=>{this.wants.forEach(({onProgress:i})=>{i.forEach(({onProgress:a})=>{a(s)})})}});for(let s of n)e.add(s)}catch(s){this.log.error("error sending full wantlist to new peer - %e",s)}})).catch(t=>{this.log.error("error sending messages - %e",t)});for(let[t,e]of this.wants)if(e.cancel){this.wants.delete(t);for(let n of this.peers.values())n.delete(t)}this.sendingMessages.resolve()}has(t){let e=W(t.multihash.bytes,"base64");return this.wants.has(e)}async wantSessionPresence(t,e,n={}){let o=new ue;return o.addWantlistEntry(t,{cid:t.bytes,sendDontHave:!0,wantType:tt.WantHave,priority:1}),await this.network.sendMessage(e,o,n),(await Ke(this,"presence",n.signal,{filter:i=>e.equals(i.detail.sender)&&at(t.multihash.digest,i.detail.cid.multihash.digest)})).detail}async wantBlock(t,e={}){return this.addEntry(t,{...e,wantType:tt.WantBlock})}async wantSessionBlock(t,e,n={}){let o=new ue;return o.addWantlistEntry(t,{cid:t.bytes,sendDontHave:!0,wantType:tt.WantBlock,priority:1}),await this.network.sendMessage(e,o,n),(await Ke(this,"presence",n.signal,{filter:i=>e.equals(i.detail.sender)&&at(t.multihash.digest,i.detail.cid.multihash.digest)})).detail}async receivedBlock(t,e){let n=W(t.multihash.bytes,"base64"),o=this.wants.get(n);o!=null&&(o.cancel=!0,await this.sendMessagesDebounced())}async receiveMessage(t,e){this.log("received message from %p with %d blocks",t.remotePeer,e.blocks.length);let n=!1;for(let o of e.blocks){if(o.prefix==null||o.data==null)continue;let s=Su(o.prefix),i=s[0],a=s[1],c=s[2],l=s[3],u=c===de.code?de:await this.getHasher(c);if(u==null){this.log.error("unknown hash algorithm",c);continue}let f=u.digest(o.data,{truncate:l});f.then!=null&&(f=await f);let h=et.create(i===0?0:1,a,f);this.log("received block from %p for %c",t.remotePeer,h),this.safeDispatchEvent("block",{detail:{sender:t.remotePeer,cid:h,block:o.data,connection:t}}),this.safeDispatchEvent("presence",{detail:{sender:t.remotePeer,cid:h,has:!0,block:o.data}});let d=W(h.multihash.bytes,"base64"),g=this.wants.get(d);g!=null&&(g.cancel=!0,n=!0)}for(let{cid:o,type:s}of e.blockPresences){let i=et.decode(o);this.log("received %s from %p for %c",s,t.remotePeer,i),this.safeDispatchEvent("presence",{detail:{sender:t.remotePeer,cid:i,has:s===Bt.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(t){let e=new Set,n=new ue(!0);for(let[o,s]of this.wants.entries())s.cancel||(e.add(o),n.addWantlistEntry(s.cid,{cid:s.cid.bytes,priority:1,wantType:tt.WantBlock,cancel:!1,sendDontHave:!1}));if(n.wantlist.size===0){this.peers.set(t,e);return}try{await this.network.sendMessage(t,n,{onProgress:o=>{this.wants.forEach(({onProgress:s})=>{s.forEach(({onProgress:i})=>{i(o)})})}}),this.peers.set(t,e)}catch(o){this.log.error("error sending full wantlist to new peer %p - %e",t,o)}}peerDisconnected(t){this.peers.delete(t)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}};var Qo=class{log;logger;stats;network;blockstore;peerWantLists;wantList;libp2p;constructor(t,e={}){this.logger=t.logger,this.log=t.logger.forComponent("helia:bitswap"),this.blockstore=t.blockstore,this.libp2p=t.libp2p,this.stats=new Yo(t),this.network=new $o(t,e),this.peerWantLists=new Go({...t,network:this.network},e),this.wantList=new Xo({...t,network:this.network},e)}createSession(t={}){return _u({wantList:this.wantList,network:this.network,logger:this.logger,libp2p:this.libp2p},t)}async want(t,e={}){let n=new AbortController,o=Va([n.signal,e.signal]);n.signal,this.network.findAndConnect(t,{...e,signal:o}).catch(s=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c - %e",t,s)});try{let s=await this.wantList.wantBlock(t,{...e,signal:o});return e.onProgress?.(new V("bitswap:block",{cid:t,sender:s.connection.remotePeer})),s.block}finally{n.abort(),o.clear()}}async notify(t,e={}){await Promise.all([this.peerWantLists.receivedBlock(t,e),this.wantList.receivedBlock(t,e)])}getWantlist(){return[...this.wantList.wants.values()].filter(t=>!t.cancel).map(t=>({cid:t.cid,priority:t.priority,wantType:t.wantType}))}getPeerWantlist(t){return this.peerWantLists.wantListForPeer(t)}async start(){this.wantList.start(),await this.network.start()}async stop(){this.wantList.stop(),await this.network.stop()}};var Au=(r,t={})=>new Qo(r,t);var Ia=class{name="bitswap";bitswap;started;constructor(t,e={}){this.bitswap=Au(t,e),this.started=!1}isStarted(){return this.started}async start(){await this.bitswap.start(),this.started=!0}async stop(){await this.bitswap.stop(),this.started=!1}async announce(t,e){await this.bitswap.notify(t,e)}async retrieve(t,e={}){return this.bitswap.want(t,{...e,onProgress:function(o){if(e?.onProgress!=null)if(e.onProgress(o),o.type==="connection:open"){if(!Xe(o.detail))return;e.onProgress(new V("helia:block-broker:connect",{broker:"bitswap",type:"connect",provider:o.detail,cid:t}))}else o.type==="connection:opened"?e.onProgress(new V("helia:block-broker:connected",{broker:"bitswap",type:"connected",provider:o.detail.remotePeer,address:o.detail.remoteAddr,cid:t})):o.type==="bitswap:send-wantlist"?e.onProgress(new V("helia:block-broker:request-block",{broker:"bitswap",type:"request-block",provider:o.detail,cid:t})):o.type==="bitswap:block"&&e.onProgress(new V("helia:block-broker:receive-block",{broker:"bitswap",type:"receive-block",provider:o.detail.sender,cid:t}))}})}createSession(t){let e=this.bitswap.createSession(t);return{name:"bitswap-session",addPeer:async(n,o)=>{await e.addPeer(n,o)},announce:async(n,o)=>{await this.bitswap.notify(n,o)},retrieve:async(n,o)=>e.retrieve(n,o)}}};function Iu(r={}){return t=>new Ia(t,r)}var lm=[6,53,56,54,55];function Tu(r){return Lu("sni",r)?.value}function ku(r){let t=Lu("tcp",r)?.value;return t==null?"":`:${t}`}function Lu(r,t){return t.find(e=>e.name===r)}function Du(r){return r.some(({code:t})=>t===448)}function qt(r,t){let e=Bu[r.name];if(e==null)throw new Error(`Can't interpret protocol ${r.name}`);let n=e(r,t);return r.code===41?`[${n}]`:n}var Bu={ip4:(r,t)=>r.value,ip6:(r,t)=>t.length===0?r.value:`[${r.value}]`,tcp:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`tcp://${qt(e,t)}:${r.value}`},udp:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`udp://${qt(e,t)}:${r.value}`},dnsaddr:(r,t)=>r.value,dns4:(r,t)=>r.value,dns6:(r,t)=>r.value,dns:(r,t)=>r.value,ipfs:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`${qt(e,t)}`},p2p:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`${qt(e,t)}`},http:(r,t)=>{let e=Du(t),n=Tu(t),o=ku(t);if(e&&n!=null)return`https://${n}${o}`;let s=e?"https://":"http://",i=t.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=qt(i,t);return a=a?.replace("tcp://",""),`${s}${a}`},"http-path":(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=qt(e,t),o=decodeURIComponent(r.value??"");return`${n}${o}`},tls:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return qt(e,t)},sni:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return qt(e,t)},https:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=qt(e,t);return n=n?.replace("tcp://",""),`https://${n}`},ws:(r,t)=>{let e=Du(t),n=Tu(t),o=ku(t);if(e&&n!=null)return`wss://${n}${o}`;let s=e?"wss://":"ws://",i=t.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=qt(i,t);return a=a?.replace("tcp://",""),`${s}${a}`},wss:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=qt(e,t);return n=n?.replace("tcp://",""),`wss://${n}`}};function Jo(r,t){let n=Bo(r).getComponents(),o=n.pop();if(o==null)throw new Error("Unexpected end of multiaddr");let s=Bu[o.name];if(s==null)throw new Error(`No interpreter found for ${o.name}`);let i=s(o,n)??"";return t?.assumeHttp!==!1&&lm.includes(o.code)&&(i=i.replace(/^.*:\/\//,""),o.value==="443"?i=`https://${i}`:i=`http://${i}`),(i.startsWith("http://")||i.startsWith("https://")||i.startsWith("ws://")||i.startsWith("wss://"))&&(i=new URL(i).toString(),i.endsWith("/")&&(i=i.substring(0,i.length-1))),i}var Cu="[a-fA-F\\d:]",Ie=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${Cu})|(?<=${Cu})(?=\\s|$))`:"",Kt="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",ct="[a-fA-F\\d]{1,4}",ts=`
3
3
  (?:
4
4
  (?:${ct}:){7}(?:${ct}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8
5
5
  (?:${ct}:){6}(?:${Kt}|:${ct}|:)| // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::1.2.3.4