@libp2p/circuit-relay-v2 4.2.12 → 4.2.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.min.js +1 -1
- package/dist/index.min.js.map +3 -3
- package/package.json +4 -4
package/dist/index.min.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
(function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Libp2PCircuitRelayV2 = factory()}(typeof self !== 'undefined' ? self : this, function () {
|
|
2
|
-
"use strict";var Libp2PCircuitRelayV2=(()=>{var os=Object.defineProperty;var nf=Object.getOwnPropertyDescriptor;var of=Object.getOwnPropertyNames;var sf=Object.prototype.hasOwnProperty;var Ae=(t,e)=>{for(var r in e)os(t,r,{get:e[r],enumerable:!0})},af=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of of(e))!sf.call(t,o)&&o!==r&&os(t,o,{get:()=>e[o],enumerable:!(n=nf(e,o))||n.enumerable});return t};var cf=t=>af(os({},"__esModule",{value:!0}),t);var pm={};Ae(pm,{RELAY_V2_HOP_CODEC:()=>ze,RELAY_V2_STOP_CODEC:()=>tr,circuitRelayServer:()=>dm,circuitRelayTransport:()=>hm});function uf(t){return typeof t?.handleEvent=="function"}function lf(t){return t===!0||t===!1}function ff(t){return lf(t)?t:t?.capture??!1}function ss(t){let e={capture:ff(t),once:!!t?.once};return t?.passive!=null&&(e.passive=t?.passive),t?.signal!=null&&(e.signal=t?.signal),e}function $a(t,e){return ss(t).capture===ss(e).capture}var Te=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let r=this.#e.get(e);return r==null?0:r.length}addEventListener(e,r,n){let o=ss(n);if(o?.signal?.aborted===!0)return;let s=l=>{o.once&&this.removeEventListener(e,r,o),uf(r)?r.handleEvent(l):r(l)},i=this.#e.get(e);if(i==null&&(i=[],this.#e.set(e,i)),i.some(l=>l.callback!==r?!1:$a(l.options,o)))return;super.addEventListener(e,s,o);let c=()=>{this.removeEventListener(e,r,o)};o.signal?.addEventListener("abort",c),i.push({callback:r,wrapper:s,options:o,onAbort:c})}removeEventListener(e,r,n){let o=this.#e.get(e);if(o==null){super.removeEventListener(e,r??null,n);return}this.#e.set(e,o.filter(s=>s.callback===r&&$a(s.options,n)?(super.removeEventListener(e,s.wrapper,n),s.options?.signal?.removeEventListener("abort",s.onAbort),!1):!0))}safeDispatchEvent(e,r={}){return this.dispatchEvent(new CustomEvent(e,r))}};var ot=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var fe=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},or=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var xn=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}};var pt=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},kr=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}};var En=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Sn=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var vn=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var _n=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}},Nt=class extends Error{static name="ListenError";constructor(e="Listen error"){super(e),this.name="ListenError"}};var sr=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var An=class extends Event{data;constructor(e,r){super("message",r),this.data=e}},ir=class extends Event{error;local;constructor(e,r,n){super("close",n),this.error=r,this.local=e}},Tn=class extends ir{constructor(e,r){super(!0,e,r)}},In=class extends ir{constructor(e,r){super(!1,e,r)}};var is=Symbol.for("@libp2p/peer-id");var Wa="keep-alive";function Ya(t){return t!=null&&typeof t.start=="function"&&typeof t.stop=="function"}async function ja(...t){let e=[];for(let r of t)Ya(r)&&e.push(r);await Promise.all(e.map(async r=>{r.beforeStart!=null&&await r.beforeStart()})),await Promise.all(e.map(async r=>{await r.start()})),await Promise.all(e.map(async r=>{r.afterStart!=null&&await r.afterStart()}))}async function Ga(...t){let e=[];for(let r of t)Ya(r)&&e.push(r);await Promise.all(e.map(async r=>{r.beforeStop!=null&&await r.beforeStop()})),await Promise.all(e.map(async r=>{await r.stop()})),await Promise.all(e.map(async r=>{r.afterStop!=null&&await r.afterStop()}))}var Xa=Symbol.for("@libp2p/transport");var Za;(function(t){t[t.FATAL_ALL=0]="FATAL_ALL",t[t.NO_FATAL=1]="NO_FATAL"})(Za||(Za={}));var Qa=Symbol.for("@libp2p/service-capabilities"),Ja=Symbol.for("@libp2p/service-dependencies");var fs={};Ae(fs,{base58btc:()=>ie,base58flickr:()=>wf});var jm=new Uint8Array(0);function tc(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}function Me(t){if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return kt(t);if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return kt(new Uint8Array(t.buffer,t.byteOffset,t.byteLength));throw new Error("Unknown type, must be binary type")}function rc(t){let e=new Uint8Array(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}var ec=4096;function nc(t){let e=t.length;if(e<=ec)return String.fromCharCode.apply(String,t);let r="",n=0;for(;n<e;)r+=String.fromCharCode.apply(String,t.subarray(n,n+=ec));return r}function df(t){return t?.buffer instanceof ArrayBuffer}function kt(t){return df(t)?t:t.slice()}function hf(t,e,r){if(t.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),o=0;o<n.length;o++)n[o]=255;for(var s=0;s<t.length;s++){var i=t.charAt(s),a=i.charCodeAt(0);if(n[a]!==255)throw new TypeError(i+" is ambiguous");if(n[a]=s,r){var c=i.toLowerCase().charCodeAt(0),l=i.toUpperCase().charCodeAt(0);c!==a&&(n[c]=s),l!==a&&(n[l]=s)}}var u=t.length,f=t.charAt(0),h=Math.log(u)/Math.log(256),d=Math.log(256)/Math.log(u);function E(w){if(w instanceof Uint8Array||(ArrayBuffer.isView(w)?w=new Uint8Array(w.buffer,w.byteOffset,w.byteLength):Array.isArray(w)&&(w=Uint8Array.from(w))),!(w instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(w.length===0)return"";for(var v=0,y=0,A=0,I=w.length;A!==I&&w[A]===0;)A++,v++;for(var F=(I-A)*d+1>>>0,K=new Uint8Array(F);A!==I;){for(var k=w[A],P=0,N=F-1;(k!==0||P<y)&&N!==-1;N--,P++)k+=256*K[N]>>>0,K[N]=k%u>>>0,k=k/u>>>0;if(k!==0)throw new Error("Non-zero carry");y=P,A++}for(var V=F-y;V!==F&&K[V]===0;)V++;for(var L=f.repeat(v);V<F;++V)L+=t.charAt(K[V]);return L}function b(w){if(typeof w!="string")throw new TypeError("Expected String");if(w.length===0)return new Uint8Array;var v=0;if(w[v]!==" "){for(var y=0,A=0;w[v]===f;)y++,v++;for(var I=(w.length-v)*h+1>>>0,F=new Uint8Array(I);w[v];){var K=n[w.charCodeAt(v)];if(K===255)return;for(var k=0,P=I-1;(K!==0||k<A)&&P!==-1;P--,k++)K+=u*F[P]>>>0,F[P]=K%256>>>0,K=K/256>>>0;if(K!==0)throw new Error("Non-zero carry");A=k,v++}if(w[v]!==" "){for(var N=I-A;N!==I&&F[N]===0;)N++;for(var V=new Uint8Array(y+(I-N)),L=y;N!==I;)V[L++]=F[N++];return V}}}function g(w){var v=b(w);if(v)return v;throw new Error(`Non-${e} character`)}return{encode:E,decodeUnsafe:b,decode:g}}var pf=hf,mf=pf,sc=mf;var as=class{name;prefix;baseEncode;constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},cs=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,r,n){this.name=e,this.prefix=r;let o=r.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return ic(this,e)}},us=class{decoders;constructor(e){this.decoders=e}or(e){return ic(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function ic(t,e){return new us({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}var ls=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,r,n,o){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=o,this.encoder=new as(e,r,n),this.decoder=new cs(e,r,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function ar({name:t,prefix:e,encode:r,decode:n}){return new ls(t,e,r,n)}function mt({name:t,prefix:e,alphabet:r,caseInsensitive:n=!1}){let{encode:o,decode:s}=sc(r,t,n);return ar({prefix:e,name:t,encode:o,decode:i=>Me(s(i))})}function yf(t,e,r,n){let o=t.length;for(;t[o-1]==="=";)--o;let s=new Uint8Array(o*r/8|0),i=0,a=0,c=0;for(let l=0;l<o;++l){let u=e[t[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<r|u,i+=r,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=r||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function gf(t,e,r){let n=e[e.length-1]==="=",o=(1<<r)-1,s="",i=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],i+=8;i>r;)i-=r,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<r-i]),n)for(;(s.length*r&7)!==0;)s+="=";return s}function bf(t,e){let r={};for(let n=0;n<t.length;++n)if(r[t[n]]=n,e){let o=t[n].toLowerCase(),s=t[n].toUpperCase();o!==t[n]&&(r[o]=n),s!==t[n]&&(r[s]=n)}return r}function de({name:t,prefix:e,bitsPerChar:r,alphabet:n,caseInsensitive:o=!1}){let s=bf(n,o);return ar({prefix:e,name:t,encode(i){return gf(i,n,r)},decode(i){return yf(i,s,r,t)}})}var ie=mt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),wf=mt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ds={};Ae(ds,{base32:()=>yt,base32hex:()=>vf,base32hexpad:()=>Af,base32hexpadupper:()=>Tf,base32hexupper:()=>_f,base32pad:()=>Ef,base32padupper:()=>Sf,base32upper:()=>xf,base32z:()=>If});var yt=de({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5,caseInsensitive:!0}),xf=de({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5,caseInsensitive:!0}),Ef=de({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5,caseInsensitive:!0}),Sf=de({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5,caseInsensitive:!0}),vf=de({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5,caseInsensitive:!0}),_f=de({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5,caseInsensitive:!0}),Af=de({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5,caseInsensitive:!0}),Tf=de({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5,caseInsensitive:!0}),If=de({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var hs={};Ae(hs,{base36:()=>Ur,base36upper:()=>Df});var Ur=mt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz",caseInsensitive:!0}),Df=mt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",caseInsensitive:!0});var Cf=uc,ac=128,Bf=127,Lf=~Bf,Rf=Math.pow(2,31);function uc(t,e,r){e=e||[],r=r||0;for(var n=r;t>=Rf;)e[r++]=t&255|ac,t/=128;for(;t&Lf;)e[r++]=t&255|ac,t>>>=7;return e[r]=t|0,uc.bytes=r-n+1,e}var Of=ps,Pf=128,cc=127;function ps(t,n){var r=0,n=n||0,o=0,s=n,i,a=t.length;do{if(s>=a)throw ps.bytes=0,new RangeError("Could not decode varint");i=t[s++],r+=o<28?(i&cc)<<o:(i&cc)*Math.pow(2,o),o+=7}while(i>=Pf);return ps.bytes=s-n,r}var Nf=Math.pow(2,7),kf=Math.pow(2,14),Uf=Math.pow(2,21),Mf=Math.pow(2,28),Ff=Math.pow(2,35),Kf=Math.pow(2,42),qf=Math.pow(2,49),zf=Math.pow(2,56),Hf=Math.pow(2,63),Vf=function(t){return t<Nf?1:t<kf?2:t<Uf?3:t<Mf?4:t<Ff?5:t<Kf?6:t<qf?7:t<zf?8:t<Hf?9:10},$f={encode:Cf,decode:Of,encodingLength:Vf},Wf=$f,Mr=Wf;function Fr(t,e=0){let r=Mr.decode(t,e),n=Mr.decode.bytes;if(n>9)throw new RangeError("Invalid varint: too long");if(n>1&&t[e+n-1]===0)throw new RangeError("Invalid varint: not minimally encoded");return[r,n]}function cr(t,e,r=0){return Mr.encode(t,e,r),e}function ur(t){return Mr.encodingLength(t)}function Ze(t,e){let r=e.byteLength,n=ur(t),o=n+ur(r),s=new Uint8Array(o+r);return cr(t,s,0),cr(r,s,n),s.set(e,o),new lr(t,r,e,s)}function Xe(t){let e=Me(t),[r,n]=Fr(e),[o,s]=Fr(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new lr(r,o,i,e)}function lc(t,e){if(t===e)return!0;{let r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&tc(t.bytes,r.bytes)}}var lr=class{code;size;digest;bytes;constructor(e,r,n,o){this.code=e,this.size=r,this.digest=kt(n),this.bytes=kt(o)}};function fc(t,e){let{bytes:r,version:n}=t;return n===0?jf(r,ms(t),e??ie.encoder):Gf(r,ms(t),e??yt.encoder)}var dc=new WeakMap;function ms(t){let e=dc.get(t);if(e==null){let r=new Map;return dc.set(t,r),r}return e}var pe=class t{code;version;multihash;bytes;"/";constructor(e,r,n,o){this.code=r,this.version=e,this.multihash=n,this.bytes=kt(o),this["/"]=this.bytes}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:r}=this;if(e!==Kr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==Zf)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return t.createV0(r)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:r}=this.multihash,n=Ze(e,r);return t.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return t.equals(this,e)}static equals(e,r){let n=r;return n!=null&&e.code===n.code&&e.version===n.version&&lc(e.multihash,n.multihash)}toString(e){return fc(this,e)}toJSON(){return{"/":fc(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let r=e;if(r instanceof t)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){let{version:n,code:o,multihash:s,bytes:i}=r;return new t(n,o,s,i??hc(n,o,s.bytes))}else if(r[Xf]===!0){let{version:n,multihash:o,code:s}=r,i=Xe(o);return t.create(n,s,i)}else return null}static create(e,r,n){if(typeof r!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(r!==Kr)throw new Error(`Version 0 CID must use dag-pb (code: ${Kr}) block encoding`);return new t(e,r,n,n.bytes)}case 1:{let o=hc(e,r,n.bytes);return new t(e,r,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return t.create(0,Kr,e)}static createV1(e,r){return t.create(1,e,r)}static decode(e){let[r,n]=t.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return r}static decodeFirst(e){let r=t.inspectBytes(e),n=r.size-r.multihashSize,o=Me(e.subarray(n,n+r.multihashSize));if(o.byteLength!==r.multihashSize)throw new Error("Incorrect length");let s=o.subarray(r.multihashSize-r.digestSize),i=new lr(r.multihashCode,r.digestSize,s,o);return[r.version===0?t.createV0(i):t.createV1(r.codec,i),e.subarray(r.size)]}static inspectBytes(e){let r=0,n=()=>{let[f,h]=Fr(e.subarray(r));return r+=h,f},o=n(),s=Kr;if(o===18?(o=0,r=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=r,a=n(),c=n(),l=r+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,r){let[n,o]=Yf(e,r),s=t.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return ms(s).set(n,e),s}};function Yf(t,e){switch(t[0]){case"Q":{let r=e??ie;return[ie.prefix,r.decode(`${ie.prefix}${t}`)]}case ie.prefix:{let r=e??ie;return[ie.prefix,r.decode(t)]}case yt.prefix:{let r=e??yt;return[yt.prefix,r.decode(t)]}case Ur.prefix:{let r=e??Ur;return[Ur.prefix,r.decode(t)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}}function jf(t,e,r){let{prefix:n}=r;if(n!==ie.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let o=e.get(n);if(o==null){let s=r.encode(t).slice(1);return e.set(n,s),s}else return o}function Gf(t,e,r){let{prefix:n}=r,o=e.get(n);if(o==null){let s=r.encode(t);return e.set(n,s),s}else return o}var Kr=112,Zf=18;function hc(t,e,r){let n=ur(t),o=n+ur(e),s=new Uint8Array(o+r.byteLength);return cr(t,s,0),cr(e,s,n),s.set(r,o),s}var Xf=Symbol.for("@ipld/js-cid/CID");var ys={};Ae(ys,{identity:()=>He});var pc=0,Qf="identity",mc=Me;function Jf(t,e){if(e?.truncate!=null&&e.truncate!==t.byteLength){if(e.truncate<0||e.truncate>t.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,e.truncate)}return Ze(pc,mc(t))}var He={code:pc,name:Qf,encode:mc,digest:Jf};function he(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}function ed(t){return t.buffer instanceof ArrayBuffer}function _e(t){return ed(t)?t:t.slice()}async function yc(t,e,r,n){let o=await crypto.subtle.importKey("jwk",t,{name:"ECDSA",namedCurve:t.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,_e(e),_e(r.subarray()));return n?.signal?.throwIfAborted(),s}function ne(t=0){return new Uint8Array(t)}function we(t=0){return new Uint8Array(t)}function td(t){return t?.buffer instanceof ArrayBuffer}function gs(t){if(td(t))return t;let e=t.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function Qe(t,e){e==null&&(e=t.reduce((o,s)=>o+s.length,0));let r=we(e),n=0;for(let o of t)r.set(o,n),n+=o.length;return gs(r)}var bc=Symbol.for("@achingbrain/uint8arraylist");function gc(t,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let r=0;for(let n of t){let o=r+n.byteLength;if(e<o)return{buf:n,index:e-r};r=o}throw new RangeError("index is out of bounds")}function Cn(t){return!!t?.[bc]}var oe=class t{bufs;length;[bc]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let r=0;for(let n of e)if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.push(n);else if(Cn(n)){r+=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+=r}prepend(...e){this.prependAll(e)}prependAll(e){let r=0;for(let n of e.reverse())if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.unshift(n);else if(Cn(n))r+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=r}get(e){let r=gc(this.bufs,e);return r.buf[r.index]}set(e,r){let n=gc(this.bufs,e);n.buf[n.index]=r}write(e,r=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(r+n,e[n]);else if(Cn(e))for(let n=0;n<e.length;n++)this.set(r+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,r){let{bufs:n,length:o}=this._subList(e,r);return Qe(n,o)}subarray(e,r){let{bufs:n,length:o}=this._subList(e,r);return n.length===1?n[0]:Qe(n,o)}sublist(e,r){let{bufs:n,length:o}=this._subList(e,r),s=new t;return s.length=o,s.bufs=n,s}_subList(e,r){if(e=e??0,r=r??this.length,e<0&&(e=this.length+e),r<0&&(r=this.length+r),e<0||r>this.length)throw new RangeError("index is out of bounds");if(e===r)return{bufs:[],length:0};if(e===0&&r===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let l=e>=a&&e<c,u=r>a&&r<=c;if(l&&u){if(e===a&&r===c){n.push(i);break}let f=e-a;n.push(i.subarray(f,f+(r-e)));break}if(l){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(u){if(r===c){n.push(i);break}n.push(i.subarray(0,r-a));break}n.push(i)}return{bufs:n,length:r-e}}indexOf(e,r=0){if(!Cn(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(r=Number(r??0),isNaN(r)&&(r=0),r<0&&(r=this.length+r),r<0&&(r=0),e.length===0)return r>this.length?this.length:r;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=r;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(e){let r=this.subarray(e,e+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt8(0)}setInt8(e,r){let n=we(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,r),this.write(n,e)}getInt16(e,r){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,r)}setInt16(e,r,n){let o=ne(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,r,n),this.write(o,e)}getInt32(e,r){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,r)}setInt32(e,r,n){let o=ne(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,r,n),this.write(o,e)}getBigInt64(e,r){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,r)}setBigInt64(e,r,n){let o=ne(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,r,n),this.write(o,e)}getUint8(e){let r=this.subarray(e,e+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint8(0)}setUint8(e,r){let n=we(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,r),this.write(n,e)}getUint16(e,r){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,r)}setUint16(e,r,n){let o=ne(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,r,n),this.write(o,e)}getUint32(e,r){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,r)}setUint32(e,r,n){let o=ne(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,r,n),this.write(o,e)}getBigUint64(e,r){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,r)}setBigUint64(e,r,n){let o=ne(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,r,n),this.write(o,e)}getFloat32(e,r){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,r)}setFloat32(e,r,n){let o=ne(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,r,n),this.write(o,e)}getFloat64(e,r){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,r)}setFloat64(e,r,n){let o=ne(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,r,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof t)||e.bufs.length!==this.bufs.length)return!1;for(let r=0;r<this.bufs.length;r++)if(!he(this.bufs[r],e.bufs[r]))return!1;return!0}static fromUint8Arrays(e,r){let n=new t;return n.bufs=e,r==null&&(r=e.reduce((o,s)=>o+s.byteLength,0)),n.length=r,n}};var bs={};Ae(bs,{base10:()=>rd});var rd=mt({prefix:"9",name:"base10",alphabet:"0123456789"});var ws={};Ae(ws,{base16:()=>nd,base16upper:()=>od});var nd=de({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4,caseInsensitive:!0}),od=de({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4,caseInsensitive:!0});var xs={};Ae(xs,{base2:()=>sd});var sd=de({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Es={};Ae(Es,{base256emoji:()=>ld});var wc=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}"),id=wc.reduce((t,e,r)=>(t[r]=e,t),[]),ad=wc.reduce((t,e,r)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return t[n]=r,t},[]);function cd(t){return t.reduce((e,r)=>(e+=id[r],e),"")}function ud(t){let e=[];for(let r of t){let n=r.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${r}`);let o=ad[n];if(o==null)throw new Error(`Non-base256emoji character: ${r}`);e.push(o)}return new Uint8Array(e)}var ld=ar({prefix:"\u{1F680}",name:"base256emoji",encode:cd,decode:ud});var vs={};Ae(vs,{base64:()=>fd,base64pad:()=>dd,base64url:()=>Ss,base64urlpad:()=>hd});var fd=de({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),dd=de({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ss=de({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),hd=de({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var _s={};Ae(_s,{base8:()=>pd});var pd=de({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var As={};Ae(As,{identity:()=>md});var md=ar({prefix:"\0",name:"identity",encode:t=>nc(Me(t)),decode:t=>Me(rc(t))});var Oy=new TextEncoder,Py=new TextDecoder;var Ds={};Ae(Ds,{sha256:()=>fr,sha512:()=>wd});var bd=20;function Is({name:t,code:e,encode:r,minDigestLength:n,maxDigestLength:o}){return new Ts(t,e,r,n,o)}var Ts=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,r,n,o,s){this.name=e,this.code=r,this.encode=n,this.minDigestLength=o??bd,this.maxDigestLength=s}digest(e,r){if(r?.truncate!=null){if(r.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&r.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?xc(n,this.code,r?.truncate):n.then(o=>xc(o,this.code,r?.truncate))}else throw Error("Unknown type, must be binary type")}};function xc(t,e,r){if(r!=null&&r!==t.byteLength){if(r>t.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,r)}return Ze(e,t)}function Sc(t){return async e=>new Uint8Array(await crypto.subtle.digest(t,e))}var fr=Is({name:"sha2-256",code:18,encode:Sc("SHA-256")}),wd=Is({name:"sha2-512",code:19,encode:Sc("SHA-512")});var qr={...As,...xs,..._s,...bs,...ws,...ds,...hs,...fs,...vs,...Es},Wy={...Ds,...ys};function _c(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var vc=_c("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Cs=_c("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);let e=we(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),xd={utf8:vc,"utf-8":vc,hex:qr.base16,latin1:Cs,ascii:Cs,binary:Cs,...qr},Bn=xd;function q(t,e="utf8"){let r=Bn[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return r.decoder.decode(`${r.prefix}${t}`)}function $(t,e="utf8"){let r=Bn[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return r.encoder.encode(t).substring(1)}var Ed=parseInt("11111",2),Bs=parseInt("10000000",2),Sd=parseInt("01111111",2),Ac={0:zr,1:zr,2:vd,3:Td,4:Id,5:Ad,6:_d,16:zr,22:zr,48:zr};function it(t,e={offset:0}){let r=t[e.offset]&Ed;if(e.offset++,Ac[r]!=null)return Ac[r](t,e);throw new Error("No decoder for tag "+r)}function Hr(t,e){let r=0;if((t[e.offset]&Bs)===Bs){let n=t[e.offset]&Sd,o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++){if(e.offset>=t.byteLength)throw new Error("invalid DER element length");o+=t[e.offset].toString(16).padStart(2,"0")}r=parseInt(o,16)}else r=t[e.offset],e.offset++;if(!Number.isInteger(r)||r<0||r>t.byteLength-e.offset)throw new Error("invalid DER element length");return r}function zr(t,e){Hr(t,e);let r=[];for(;!(e.offset>=t.byteLength);){let n=it(t,e);if(n===null)break;r.push(n)}return r}function vd(t,e){let r=Hr(t,e),n=e.offset,o=e.offset+r,s=[];for(let i=n;i<o;i++)i===n&&t[i]===0||s.push(t[i]);return e.offset+=r,Uint8Array.from(s)}function _d(t,e){let r=Hr(t,e),n=e.offset+r,o=t[e.offset];e.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,c=[];for(;e.offset<n;){let l=t[e.offset];if(e.offset++,c.push(l&127),l<128){c.reverse();let u=0;for(let f=0;f<c.length;f++)u+=c[f]<<f*7;a+=`.${u}`,c=[]}}return a}function Ad(t,e){return e.offset++,null}function Td(t,e){let r=Hr(t,e),n=t[e.offset];e.offset++;let o=t.subarray(e.offset,e.offset+r-1);if(e.offset+=r,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function Id(t,e){let r=Hr(t,e),n=t.subarray(e.offset,e.offset+r);return e.offset+=r,n}function Dd(t){let e=t.toString(16);e.length%2===1&&(e="0"+e);let r=new oe;for(let n=0;n<e.length;n+=2)r.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return r}function Ls(t){if(t.byteLength<128)return Uint8Array.from([t.byteLength]);let e=Dd(t.byteLength);return new oe(Uint8Array.from([e.byteLength|Bs]),e)}function Ie(t){let e=new oe,r=128;return(t.subarray()[0]&r)===r&&e.append(Uint8Array.from([0])),e.append(t),new oe(Uint8Array.from([2]),Ls(e),e)}function Ln(t){let e=Uint8Array.from([0]),r=new oe(e,t);return new oe(Uint8Array.from([3]),Ls(r),r)}function gt(t,e=48){let r=new oe;for(let n of t)r.append(n);return new oe(Uint8Array.from([e]),Ls(r),r)}var Cd=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Bd=Uint8Array.from([6,5,43,129,4,0,34]),Ld=Uint8Array.from([6,5,43,129,4,0,35]),Rd={ext:!0,kty:"EC",crv:"P-256"},Od={ext:!0,kty:"EC",crv:"P-384"},Pd={ext:!0,kty:"EC",crv:"P-521"},Rs=32,Os=48,Ps=66;function Ns(t){let e=it(t);return Tc(e)}function Tc(t){let e=t[1][1][0],r=1,n,o;if(e.byteLength===Rs*2+1)return n=$(e.subarray(r,r+Rs),"base64url"),o=$(e.subarray(r+Rs),"base64url"),new dr({...Rd,key_ops:["verify"],x:n,y:o});if(e.byteLength===Os*2+1)return n=$(e.subarray(r,r+Os),"base64url"),o=$(e.subarray(r+Os),"base64url"),new dr({...Od,key_ops:["verify"],x:n,y:o});if(e.byteLength===Ps*2+1)return n=$(e.subarray(r,r+Ps),"base64url"),o=$(e.subarray(r+Ps),"base64url"),new dr({...Pd,key_ops:["verify"],x:n,y:o});throw new fe(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function Ic(t){return gt([Ie(Uint8Array.from([1])),gt([Nd(t.crv)],160),gt([Ln(new oe(Uint8Array.from([4]),q(t.x??"","base64url"),q(t.y??"","base64url")))],161)]).subarray()}function Nd(t){if(t==="P-256")return Cd;if(t==="P-384")return Bd;if(t==="P-521")return Ld;throw new fe(`Invalid curve ${t}`)}var dr=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=Ic(this.jwk)),this._raw}toMultihash(){return He.digest(Je(this))}toCID(){return pe.createV1(114,this.toMultihash())}toString(){return ie.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:he(this.raw,e.raw)}async verify(e,r,n){return yc(this.jwk,r,e,n)}};var Rn=BigInt(4294967295),Dc=BigInt(32);function kd(t,e=!1){return e?{h:Number(t&Rn),l:Number(t>>Dc&Rn)}:{h:Number(t>>Dc&Rn)|0,l:Number(t&Rn)|0}}function Cc(t,e=!1){let r=t.length,n=new Uint32Array(r),o=new Uint32Array(r);for(let s=0;s<r;s++){let{h:i,l:a}=kd(t[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var Ud=t=>t/2**32|0,Md=t=>t>>>0;function Bc(t,e,r,n){let o=Ud(r),s=Md(r);t.setUint32(e,n?s:o,n),t.setUint32(e+4,n?o:s,n)}var ks=(t,e,r)=>t>>>r,Us=(t,e,r)=>t<<32-r|e>>>r,Ut=(t,e,r)=>t>>>r|e<<32-r,Mt=(t,e,r)=>t<<32-r|e>>>r,Vr=(t,e,r)=>t<<64-r|e>>>r-32,$r=(t,e,r)=>t>>>r-32|e<<64-r;function et(t,e,r,n){let o=(e>>>0)+(n>>>0);return{h:t+r+(o/2**32|0)|0,l:o|0}}var Lc=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),Rc=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,Oc=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),Pc=(t,e,r,n,o)=>e+r+n+o+(t/2**32|0)|0,Nc=(t,e,r,n,o)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(o>>>0),kc=(t,e,r,n,o,s)=>e+r+n+o+s+(t/2**32|0)|0;function On(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}var Ms=t=>t?`"${t}" `:"";function at(t,e=""){if(typeof t!="number")throw new TypeError(Ms(e)+"expected number, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw new RangeError(Ms(e)+"expected integer >= 0, got "+t);return t}function Fe(t,e,r=""){if(On(t)&&(e===void 0||t.length===e))return t;e!==void 0&&at(e,"length");let n=On(t),o=e!==void 0?` of length ${e}`:"",s=n?`length=${t.length}`:`type=${typeof t}`,i=Ms(r)+"expected Uint8Array"+o+", got "+s;throw n?new RangeError(i):new TypeError(i)}function Pn(t){if(typeof t!="function"||typeof t.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(at(t.outputLen),at(t.blockLen),t.outputLen<1||t.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}var Uc=(t,e)=>{if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof t)};function hr(t,e=!0){if(t.destroyed)throw new Error("hash was destroyed");if(e&&t.finished)throw new Error("digest() was already called")}function Nn(t,e){Fe(t,void 0,"output");let r=e.outputLen;if(!(t.length>=r))throw new RangeError('"output" expected length >= '+r)}function Ft(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function kn(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Ve(t,e){return t<<32-e|t>>>e}var Fc=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Kd=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Un(t){if(Fe(t),Fc)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=Kd[t[r]];return e}function Mc(t){return t>=48&&t<=57?t-48:t>=65&&t<=70?t-55:t>=97&&t<=102?t-87:void 0}function Mn(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);if(Fc)try{return Uint8Array.fromHex(t)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}let e=t.length,r=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(r);for(let o=0,s=0;o<r;o++,s+=2){let i=Mc(t.charCodeAt(s)),a=Mc(t.charCodeAt(s+1));if(i===void 0||a===void 0){let c=t[s]+t[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function Fs(...t){let e=0;for(let n=0;n<t.length;n++){let o=t[n];Fe(o),e+=o.length}let r=new Uint8Array(e);for(let n=0,o=0;n<t.length;n++){let s=t[n];r.set(s,o),o+=s.length}return r}function qd(t,e,r="opts"){return Uc(t,"defaults"),e!==void 0&&Uc(e,r),Object.assign(t,e)}function Ks(t,e={}){if(typeof t!="function")throw new TypeError('"hashCons" expected function, got type='+typeof t);e=qd({},e,"info");let r=(o,s)=>t(s).update(o).digest(),n=t(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=o=>t(o),Object.assign(r,e),Object.freeze(r)}function Kc(t=32){at(t,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(t>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${t}`);return e.getRandomValues(new Uint8Array(t))}var qs=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});function qc(t,e,r){return t&e^~t&r}function zc(t,e,r){return t&e^t&r^e&r}var Wr=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,r,n,o){this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=kn(this.buffer)}update(e){hr(this),Fe(e);let{view:r,buffer:n,blockLen:o}=this,s=e.length,i=!1;for(let a=0;a<s;){let c=Math.min(o-this.pos,s-a);if(c===o){let l=kn(e);for(;o<=s-a;a+=o)this.process(l,a);i=!0;continue}n.set(a===0&&c===s?e:e.subarray(a,a+c),this.pos),this.pos+=c,a+=c,this.pos===o&&(this.process(r,0),this.pos=0,i=!0)}return this.length+=e.length,i&&this.roundClean(),this}digestInto(e){hr(this),Nn(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;r[i++]=128,r.fill(0,i),this.padOffset>o-i&&(this.process(n,0),r.fill(0)),Bc(n,o-8,this.length*8,s),this.process(n,0),this.roundClean();let a=e===r?n:kn(e),c=this.outputLen,l=c/4,u=this.get();if(c%4||l>u.length)throw new Error("invalid outputLen");for(let f=0;f<l;f++)a.setUint32(4*f,u[f],s)}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}_cloneIntoMeta(e){let{buffer:r,length:n,finished:o,destroyed:s,pos:i}=this;return e.destroyed=s,e.finished=o,e.length=n,e.pos=i,i&&e.buffer.set(r),e}clone(){return this._cloneInto()}},Hc=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Vc=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var zd=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),bt=new Uint32Array(64),zs=class extends Wr{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,r){super(64,e,8,!1),this.A=r[0]|0,this.B=r[1]|0,this.C=r[2]|0,this.D=r[3]|0,this.E=r[4]|0,this.F=r[5]|0,this.G=r[6]|0,this.H=r[7]|0}get(){let{A:e,B:r,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,r,n,o,s,i,a,c]}set(e,r,n,o,s,i,a,c){this.A=e|0,this.B=r|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}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,r){for(let f=0;f<16;f++,r+=4)bt[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){let h=bt[f-15],d=bt[f-2],E=Ve(h,7)^Ve(h,18)^h>>>3,b=Ve(d,17)^Ve(d,19)^d>>>10;bt[f]=b+bt[f-7]+E+bt[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=Ve(a,6)^Ve(a,11)^Ve(a,25),d=u+h+qc(a,c,l)+zd[f]+bt[f]|0,b=(Ve(n,2)^Ve(n,13)^Ve(n,22))+zc(n,o,s)|0;u=l,l=c,c=a,a=i+d|0,i=s,s=o,o=n,n=d+b|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(){Ft(bt)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Ft(this.buffer)}},Hs=class extends zs{constructor(){super(32,Hc)}};var $c=Cc(["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(t=>BigInt(t))),Hd=$c[0],Vd=$c[1],wt=new Uint32Array(80),xt=new Uint32Array(80),Vs=class extends Wr{Ah=0;Al=0;Bh=0;Bl=0;Ch=0;Cl=0;Dh=0;Dl=0;Eh=0;El=0;Fh=0;Fl=0;Gh=0;Gl=0;Hh=0;Hl=0;constructor(e,r){super(128,e,16,!1),this.Ah=r[0]|0,this.Al=r[1]|0,this.Bh=r[2]|0,this.Bl=r[3]|0,this.Ch=r[4]|0,this.Cl=r[5]|0,this.Dh=r[6]|0,this.Dl=r[7]|0,this.Eh=r[8]|0,this.El=r[9]|0,this.Fh=r[10]|0,this.Fl=r[11]|0,this.Gh=r[12]|0,this.Gl=r[13]|0,this.Hh=r[14]|0,this.Hl=r[15]|0}get(){let{Ah:e,Al:r,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:l,El:u,Fh:f,Fl:h,Gh:d,Gl:E,Hh:b,Hl:g}=this;return[e,r,n,o,s,i,a,c,l,u,f,h,d,E,b,g]}set(e,r,n,o,s,i,a,c,l,u,f,h,d,E,b,g){this.Ah=e|0,this.Al=r|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=E|0,this.Hh=b|0,this.Hl=g|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,r){for(let y=0;y<16;y++,r+=4)wt[y]=e.getUint32(r),xt[y]=e.getUint32(r+=4);for(let y=16;y<80;y++){let A=wt[y-15]|0,I=xt[y-15]|0,F=Ut(A,I,1)^Ut(A,I,8)^ks(A,I,7),K=Mt(A,I,1)^Mt(A,I,8)^Us(A,I,7),k=wt[y-2]|0,P=xt[y-2]|0,N=Ut(k,P,19)^Vr(k,P,61)^ks(k,P,6),V=Mt(k,P,19)^$r(k,P,61)^Us(k,P,6),L=Oc(K,V,xt[y-7],xt[y-16]),re=Pc(L,F,N,wt[y-7],wt[y-16]);wt[y]=re|0,xt[y]=L|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:E,Gh:b,Gl:g,Hh:w,Hl:v}=this;for(let y=0;y<80;y++){let A=Ut(f,h,14)^Ut(f,h,18)^Vr(f,h,41),I=Mt(f,h,14)^Mt(f,h,18)^$r(f,h,41),F=f&d^~f&b,K=h&E^~h&g,k=Nc(v,I,K,Vd[y],xt[y]),P=kc(k,w,A,F,Hd[y],wt[y]),N=k|0,V=Ut(n,o,28)^Vr(n,o,34)^Vr(n,o,39),L=Mt(n,o,28)^$r(n,o,34)^$r(n,o,39),re=n&s^n&a^s&a,B=o&i^o&c^i&c;w=b|0,v=g|0,b=d|0,g=E|0,d=f|0,E=h|0,{h:f,l:h}=et(l|0,u|0,P|0,N|0),l=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let C=Lc(N,L,B);n=Rc(C,P,V,re),o=C|0}({h:n,l:o}=et(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=et(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=et(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=et(this.Dh|0,this.Dl|0,l|0,u|0),{h:f,l:h}=et(this.Eh|0,this.El|0,f|0,h|0),{h:d,l:E}=et(this.Fh|0,this.Fl|0,d|0,E|0),{h:b,l:g}=et(this.Gh|0,this.Gl|0,b|0,g|0),{h:w,l:v}=et(this.Hh|0,this.Hl|0,w|0,v|0),this.set(n,o,s,i,a,c,l,u,f,h,d,E,b,g,w,v)}roundClean(){Ft(wt,xt)}destroy(){this.destroyed=!0,Ft(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},$s=class extends Vs{constructor(){super(64,Vc)}};var pr=Ks(()=>new Hs,qs(1));var Ws=Ks(()=>new $s,qs(3));function Kn(t,e,r=()=>{}){if(!Array.isArray(t))throw new TypeError(`"${e}" expected array, got type=${typeof t}`);for(let n=0;n<t.length;n++)r(t[n],`${e}[${n}]`);return t}var Z=(t,e,r)=>Fe(t,e,r),Ys=at;function Yc(t,e=""){if(typeof t!="string"){let r=e&&`"${e}" `;throw new TypeError(r+"expected string, got type="+typeof t)}return t}function Et(t,e="object"){if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof t}`);return t}function Kt(t,e){if(typeof t!="function")throw new TypeError(`"${e}" is invalid: expected function, got ${typeof t}`);return t}var Yr=Un,Ke=(...t)=>Fs(...t),mr=t=>Mn(t),vt=On,qt=t=>Kc(t),Fn=BigInt(0),Wc=BigInt(1),$d=t=>t?`"${t}" `:"";function De(t,e=""){if(typeof t!="boolean")throw new TypeError($d(e)+"expected boolean, got type="+typeof t);return t}function qn(t){if(typeof t=="bigint"){if(!St(t))throw new RangeError("positive bigint expected, got "+t)}else Ys(t);return t}function _t(t,e=""){if(typeof t!="number"){let r=e&&`"${e}" `;throw new TypeError(r+"expected number, got type="+typeof t)}if(!Number.isSafeInteger(t)){let r=e&&`"${e}" `;throw new RangeError(r+"expected safe integer, got "+t)}}function jr(t){let e=qn(t).toString(16);return e.length&1?"0"+e:e}function jc(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);return t===""?Fn:BigInt("0x"+t)}function tt(t){return jc(Un(t))}function zt(t){return jc(Un(Hn(Fe(t)).reverse()))}function zn(t,e){if(at(e),e===0)throw new Error("zero output length is invalid");t=qn(t);let r=e*2,n=t.toString(16);if(n.length>r)throw new RangeError("number is too large");return Mn(n.padStart(r,"0"))}function js(t,e){return zn(t,e).reverse()}function Hn(t){return Uint8Array.from(Z(t))}function St(t){return typeof t=="bigint"&&Fn<=t}function Gs(t,e,r){return St(t)&&St(e)&&St(r)&&e<=t&&t<r}function yr(t,e,r,n){if(!Gs(e,r,n))throw new RangeError("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function gr(t){if(t<Fn)throw new Error("expected non-negative bigint, got "+t);return t===Fn?0:t.toString(2).length}var Gr=t=>(_t(t,"n"),(Wc<<BigInt(t))-Wc);function Gc(t,e,r){if(at(t,"hashLen"),at(e,"qByteLen"),typeof r!="function")throw new TypeError("hmacFn must be a function");let n=g=>new Uint8Array(g),o=Uint8Array.of(),s=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(t),l=n(t),u=0,f=()=>{c.fill(1),l.fill(0),u=0},h=(...g)=>r(l,Ke(c,...g)),d=(g=o)=>{l=h(s,g),c=h(),g.length!==0&&(l=h(i,g),c=h())},E=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let g=0,w=[];for(;g<e;){c=h();let v=c.slice();w.push(v),g+=c.length}return Ke(...w)};return(g,w)=>{f(),d(g);let v;for(;(v=w(E()))===void 0;)d();return f(),v}}function Ce(t,e={},r={},n="object"){Et(t,n),Et(e,"fields"),Et(r,"optFields");function o(i,a,c){let l=n==="object"?`param "${String(i)}"`:`"${n}.${String(i)}"`,u=t[i];if(!Object.hasOwn(t,i)&&(c?u!==void 0:a!=="function"))throw new TypeError(`${l} is invalid: expected own property`);if(c&&u===void 0)return;let f=typeof u;if(f!==a||u===null)throw new TypeError(`${l} is invalid: expected ${a}, got ${f}`)}let s=(i,a)=>Object.entries(i).forEach(([c,l])=>o(c,l,a));s(e,!1),s(r,!0)}var me=BigInt(0),X=BigInt(1),At=BigInt(2),Qc=BigInt(3),Zs=BigInt(4),Jc=BigInt(5),Wd=BigInt(7),eu=BigInt(8),Yd=BigInt(9),jd=BigInt(15),tu=BigInt(16),Gd=BigInt("0x10000000000000000");function ae(t,e){if(e<=me)throw new Error("mod: expected positive modulus, got "+e);let r=t%e;return r>=me?r:e+r}function ru(t,e,r){if(r<=X)throw new Error("pow: expected modulus > 1, got "+r);if(typeof e!="bigint")throw new TypeError("invalid exponent: expected bigint, got "+typeof e);if(e<me)throw new Error("invalid exponent, negatives unsupported");if(e===me)return X;if(e===X)return t;let n=t%r;if(n<me&&(n+=r),e<Gd){let a=X;for(;e>me;)e&X&&(a=a*n%r),n=n*n%r,e>>=X;return a}let o=[];for(;e>me;)o.push(Number(e&jd)),e>>=Zs;let s=new Array(16);s[0]=X,s[1]=n;for(let a=2;a<16;a++)s[a]=s[a-1]*n%r;let i=s[o[o.length-1]];for(let a=o.length-2;a>=0;a--){i=i*i%r,i=i*i%r,i=i*i%r,i=i*i%r;let c=o[a];c!==0&&(i=i*s[c]%r)}return i}function se(t,e,r){if(r<=X)throw new Error("pow2: expected modulus > 1, got "+r);if(e<me)throw new Error("pow2: expected non-negative exponent, got "+e);let n=t;for(;e-- >me;)n*=n,n%=r;return n}function Zc(t,e){if(t===me)throw new Error("invert: expected non-zero number");if(e<=X)throw new Error("invert: expected modulus > 1, got "+e);let r=ae(t,e),n=e,o=me,s=X;for(;r!==me;){let a=n/r,c=n-r*a,l=o-s*a;n=r,r=c,o=s,s=l}if(n!==X)throw new Error("invert: does not exist");return ae(o,e)}function nu(t,e){if(e<=X)throw new Error("invertCt: expected prime modulus > 1, got "+e);let r=ae(t,e);if(r===me)throw new Error("invertCt: expected non-zero number");let n=ru(r,e-At,e);if(ae(r*n,e)!==X)throw new Error("invertCt: does not exist");return n}function Xs(t,e,r){let n=t;if(!n.eql(n.sqr(e),r))throw new Error("Cannot find square root")}function Qs(t,e){if((t&X)===me)throw new Error(e+": expected odd modulus, got "+t)}function ou(t,e){let r=t,n=(r.ORDER+X)/Zs,o=r.pow(e,n);return Xs(r,o,e),o}function Zd(t,e){let r=t,n=(r.ORDER-Jc)/eu,o=r.mul(e,At),s=r.pow(o,n),i=r.mul(e,s),a=r.mul(r.mul(i,At),s),c=r.mul(i,r.sub(a,r.ONE));return Xs(r,c,e),c}function Xd(t){let e=wr(t),r=su(t),n=r(e,e.neg(e.ONE)),o=r(e,n),s=r(e,e.neg(n)),i=(t+Wd)/tu;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),E=l.eql(l.sqr(f),c),b=l.eql(l.sqr(h),c);u=l.cmov(u,f,E),f=l.cmov(d,h,b);let g=l.eql(l.sqr(f),c),w=l.cmov(u,f,g);return Xs(l,w,c),w})}function su(t){if(t<Qc)throw new Error("sqrt is not defined for small field");Qs(t,"tonelliShanks");let e=t-X,r=0;for(;e%At===me;)e/=At,r++;let n=At,o=wr(t);for(;Zr(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return ou;let s=o.pow(n,e),i=(e+X)/At;return function(c,l){let u=c;if(u.is0(l))return l;if(Zr(u,l)!==1)throw new Error("Cannot find square root");let f=r,h=u.mul(u.ONE,s),d=u.pow(l,e),E=u.pow(l,i);for(;!u.eql(d,u.ONE);){if(u.is0(d))throw new Error("Cannot find square root: probably non-prime P");let b=1,g=u.sqr(d);for(;!u.eql(g,u.ONE);)if(b++,g=u.sqr(g),b===f)throw new Error("Cannot find square root");let w=X<<BigInt(f-b-1),v=u.pow(h,w);f=b,h=u.sqr(v),d=u.mul(d,h),E=u.mul(E,v)}return E}}function Qd(t){return Qs(t,"Fp.sqrt"),t%Zs===Qc?ou:t%eu===Jc?Zd:t%tu===Yd?Xd(t):su(t)}var iu=(t,e)=>(ae(t,e)&X)===X,Jd=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function br(t){if(Et(t,"field"),typeof t.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof t.ORDER);_t(t.BYTES,"BYTES"),_t(t.BITS,"BITS");for(let e of Jd)Kt(t[e],"field."+e);if(t.BYTES<1||t.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(t.ORDER<=X)throw new Error("invalid field: expected ORDER > 1, got "+t.ORDER);return t}function $n(t,e,r=!1){br(t),Kn(e,"nums"),De(r,"passZero");let n=t,o=new Array(e.length).fill(r?n.ZERO:void 0),s=e.reduce((a,c,l)=>n.is0(c)?a:(o[l]=a,n.mul(a,c)),n.ONE),i=n.inv(s);return e.reduceRight((a,c,l)=>n.is0(c)?a:(o[l]=n.mul(a,o[l]),n.mul(a,c)),i),o}function Zr(t,e){br(t);let r=t;Qs(r.ORDER,"FpLegendre");let n=(r.ORDER-X)/At,o=r.pow(e,n),s=r.eql(o,r.ONE),i=r.eql(o,r.ZERO),a=r.eql(o,r.neg(r.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function eh(t,e){if(e!==void 0&&Ys(e),t<=me)throw new Error("invalid n length: expected positive n, got "+t);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let r=gr(t);if(e!==void 0&&e<r)throw new Error(`invalid n length: expected nBitLength (${e}) >= bitLen(n) (${r})`);let n=e!==void 0?e:r,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}var Xc=new WeakMap,Vn=class{ORDER;BITS;BYTES;isLE;ZERO=me;ONE=X;_lengths;_mod;constructor(e,r={}){if(e<=X)throw new Error("invalid field: expected ORDER > 1, got "+e);let n;this.isLE=!1,r!=null&&typeof r=="object"&&(typeof r.BITS=="number"&&(n=r.BITS),typeof r.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:r.sqrt,enumerable:!0}),typeof r.isLE=="boolean"&&(this.isLE=r.isLE),r.allowedLengths&&(this._lengths=Object.freeze(r.allowedLengths.slice())),typeof r.modFromBytes=="boolean"&&(this._mod=r.modFromBytes));let{nBitLength:o,nByteLength:s}=eh(e,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,Object.freeze(this)}create(e){return ae(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return me<=e&&e<this.ORDER}is0(e){return e===me}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&X)===X}neg(e){return ae(-e,this.ORDER)}eql(e,r){return e===r}sqr(e){return ae(e*e,this.ORDER)}add(e,r){return ae(e+r,this.ORDER)}sub(e,r){return ae(e-r,this.ORDER)}mul(e,r){return ae(e*r,this.ORDER)}pow(e,r){return ru(e,r,this.ORDER)}div(e,r){return ae(e*Zc(r,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,r){return e+r}subN(e,r){return e-r}mulN(e,r){return e*r}inv(e){return Zc(e,this.ORDER)}sqrt(e){let r=Xc.get(this);return r||Xc.set(this,r=Qd(this.ORDER)),r(this,e)}toBytes(e){return this.isLE?js(e,this.BYTES):zn(e,this.BYTES)}fromBytes(e,r=!1){Z(e);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(e.length<1||!n.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let l=new Uint8Array(o);l.set(e,s?0:l.length-e.length),e=l}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?zt(e):tt(e);if(a&&(c=ae(c,i)),!r&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return $n(this,e,!0)}cmov(e,r,n){return De(n,"condition"),n?r:e}};function wr(t,e={}){return Object.freeze(Vn.prototype),new Vn(t,e)}function au(t){if(typeof t!="bigint")throw new Error("field order must be bigint");if(t<=X)throw new Error("field order must be greater than 1");let e=gr(t-X);return Math.ceil(e/8)}function Wn(t){let e=au(t);return e+Math.ceil(e/2)}function Yn(t,e,r=!1){Z(t);let n=t.length,o=au(e),s=Math.max(Wn(e),16);if(n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=r?zt(t):tt(t),a=ae(i,e-X)+X;return r?js(a,o):zn(a,o)}var ti=BigInt(0),Xr=BigInt(1),th=BigInt(4),Js=16,cu=128,rh=5,uu=2**31;function Tt(t){let e=t;if(typeof e!="function")throw new TypeError('"Point" expected constructor, got type='+typeof t);Kt(e.fromAffine,"Point.fromAffine"),Kt(e.fromBytes,"Point.fromBytes"),Kt(e.fromHex,"Point.fromHex"),Et(e.BASE,"Point.BASE"),Et(e.ZERO,"Point.ZERO"),br(e.Fp),br(e.Fn)}function jn(t,e){Tt(t),fu(e,t);let r=$n(t.Fp,e.map(n=>n.Z));return e.map((n,o)=>t.fromAffine(n.toAffine(r[o])))}function nh(t,e,r=1){if(!Number.isSafeInteger(t)||t<r||t>e)throw new Error("invalid window size, expected ["+r+".."+e+"], got W="+t)}function oh(t,e){let r=t*(4*e+128);if(r>uu)throw new Error("invalid window size: table would need ~"+Math.ceil(r/2**20)+" MiB, max "+uu/2**20+" MiB")}function ri(t,e){if(t!==void 0){Kt(t,"randomBytes");try{let r=t(e);if(!vt(r)||r.length!==e)return}catch{return}return t}}function fu(t,e){Kn(t,"points"),t.forEach((r,n)=>{if(!(r instanceof e))throw new Error("invalid point at index "+n)})}function sh(t,e,r){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((n,o)=>{if(!(r===void 0?e.isValid(n):St(n)&&n<r))throw new Error("invalid scalar at index "+o)})}var du=new WeakMap;function ei(t){return du.get(t)||1}function ih(t,e){let r=t.double(),n=[t];for(let o=1;o<e;o++)n.push(n[o-1].add(r));return n}function ah(t,e){let r=2**e,n=r/2,o=BigInt(r-1),s=[];for(;t>ti;){let i=0;t&Xr&&(i=Number(t&o),i>=n&&(i-=r),t-=BigInt(i)),s.push(i),t>>=Xr}return s}function ch(t,e,r){let n=2**e,o=n/2,s=BigInt(n-1),i=BigInt(e),a=[];for(let c=0;c<r;c++){let l=Number(t&s);t>>=i,l>o&&(l-=n,t+=Xr),a.push(l)}if(t!==ti)throw new Error("invalid wnaf");return a}function uh(t,e,r){let n=0;for(let s of r)n=Math.max(n,s.length);let o=t;for(let s=n-1;s>=0;s--){s!==n-1&&(o=o.double());for(let i=0;i<r.length;i++){let a=r[i][s];if(a){let c=e[i][Math.abs(a)-1>>1];o=o.add(a<0?c.negate():c)}}}return o}var xr=class{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,r){Tt(e),this.randomBytes=ri(r,Js),this.Point=e,this.BASE=e.BASE,this.ZERO=e.ZERO,this.bits=e.Fn.BITS}buildWnafTable(e,r,n){let o=Math.ceil(n/r)+1,s=2**(r-1),i=[],a=e;for(let c=0;c<o;c++){let l=a;for(let u=0;u<s;u++)i.push(l),l=l.add(a);a=i[i.length-1].double()}return{W:r,bits:n,windows:o,comp:i}}wnafCachedCT(e,r){let{W:n,windows:o,comp:s}=e,i=2**(n-1),a=ch(r,n,o),c=this.ZERO,l=this.BASE;for(let u=0;u<o;u++){let f=a[u],h=u*i,d=Math.abs(f)-1,E=s[h];for(let g=1;g<i;g++)E=g===d?s[h+g]:E;let b=E.negate();f===0?l=l.add(s[h]):c=c.add(f<0?b:E)}return{p:c,f:l}}getWnafPrecomputes(e,r,n,o){let s=this.wnafPrecomputes.get(r),i=s?.find(a=>a.W===e&&a.bits===n);return i||(i=this.buildWnafTable(r,e,n),typeof o=="function"&&(i={...i,comp:o(i.comp)}),s||(s=[],this.wnafPrecomputes.set(r,s)),s.push(i)),i}assertPoint(e){if(!(e instanceof this.Point))throw new TypeError('"point" expected Point instance, got type='+typeof e)}validateMulInput(e,r){if(this.assertPoint(e),!Gs(r,Xr,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(e,r,n,o){let s=ei(e);return s===1?this.fixedWindowCT(e,r,n):this.wnafCachedCT(this.getWnafPrecomputes(s,e,n,o),r)}mulCT(e,r,n){return this.validateMulInput(e,r),this.runCT(e,r,this.bits,n)}mulCTBlinded(e,r,n){if(this.validateMulInput(e,r),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");let o=this.Point.Fn.BITS+cu,s=this.randomBytes(Js);if(!vt(s)||s.length!==Js)throw new Error("randomBytes returned invalid byte array");s[0]=s[0]&63|128;let i=r+tt(s)*this.Point.Fn.ORDER;return this.runCT(e,i,o,n)}fixedWindowCT(e,r,n){let o=rh,s=1<<o,i=Gr(o),a=new Array(s);a[0]=this.ZERO;for(let u=1;u<s;u++)a[u]=a[u-1].add(e);let c=Math.ceil(n/o),l=this.ZERO;for(let u=c-1;u>=0;u--){if(u!==c-1)for(let d=0;d<o;d++)l=l.double();let f=Number(r>>BigInt(u*o)&i),h=a[0];for(let d=1;d<s;d++)h=d===f?a[d]:h;l=l.add(h)}return{p:l,f:l}}shouldBlind(e,r){return this.randomBytes===void 0?!1:r===Xr?!0:e!==this.BASE?!1:(this.baseCanBeBlinded===void 0&&(this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0()),this.baseCanBeBlinded)}mulSecret(e,r,n,o){return this.shouldBlind(e,n)?this.mulCTBlinded(e,r,o):this.mulCT(e,r,o)}mulUnsafe(e,r,n){if(this.assertPoint(e),!St(r))throw new Error("invalid scalar");let o=ei(e);if(o===1||r>=this.Point.Fn.ORDER)return Gn(this.Point,[e],[r],!0);let s=this.getWnafPrecomputes(o,e,this.bits,n);return this.wnafCachedCT(s,r).p}setWindowSize(e,r){this.assertPoint(e),nh(r,this.bits);let n=Math.ceil((this.bits+cu)/r)+1;oh(n*2**(r-1),this.Point.Fp.BYTES),du.set(e,r),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return ei(e)!==1}};function Gn(t,e,r,n=!1){if(Tt(t),fu(e,t),De(n,"allowOversized"),sh(r,t.Fn,n?t.Fn.ORDER**th:void 0),e.length!==r.length)throw new Error("arrays of points and scalars must have equal length");let o=e.map(i=>ih(i,4)),s=r.map(i=>ah(i,4));return uh(t.ZERO,o,s)}function lu(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return br(e),e}else return wr(t,{isLE:r})}function Zn(t,e,r={},n){if(t!=="weierstrass"&&t!=="edwards")throw new Error('expected curve type "weierstrass" or "edwards"');if(n===void 0&&(n=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);Ce(r);for(let c of["p","n","h"]){let l=e[c];if(!(St(l)&&l!==ti))throw new Error(`CURVE.${c} must be positive bigint`)}let o=lu(e.p,r.Fp,n),s=lu(e.n,r.Fn,n),a=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}function Xn(t,e){return function(n){let o=t(n);return{secretKey:o,publicKey:e(o)}}}var Qn=BigInt(0),Jn=BigInt(1),eo=BigInt(2),lh=BigInt(4),hu=BigInt(8);function fh(t,e,r,n){let o=t.sqr(r),s=t.sqr(n),i=t.add(t.mul(e.a,o),s),a=t.add(t.ONE,t.mul(e.d,t.mul(o,s)));return t.eql(i,a)}function pu(t,e={}){Ce(e,{},{},"extraOpts");let r=e,n=Zn("edwards",t,r,r.FpFnLE),{Fp:o,Fn:s}=n,i=n.CURVE,{h:a}=i;if(Zr(o,i.a)!==1)throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(Zr(o,i.d)!==-1)throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");Ce(r,{},{uvRatio:"function",randomBytes:"function"});let c=r.randomBytes===void 0?qt:r.randomBytes,l=eo<<BigInt(o.BYTES*8)-Jn;function u(v){if(!o.isOdd)throw new Error("Field does not have .isOdd()");return o.isOdd(v)}let f=r.uvRatio===void 0?(v,y)=>{try{return{isValid:!0,value:o.sqrt(o.div(v,y))}}catch{return{isValid:!1,value:Qn}}}:r.uvRatio;if(!fh(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");let h=o.eql(i.a,o.neg(o.ONE))?v=>o.neg(v):o.eql(i.a,o.ONE)?v=>v:v=>o.mul(i.a,v);function d(v,y,A=!1){let I=A?Jn:Qn;return yr("coordinate "+v,y,I,l),y}function E(v){if(!(v instanceof b))throw new Error("EdwardsPoint expected")}class b{static BASE=new b(i.Gx,i.Gy,o.ONE,o.mul(i.Gx,i.Gy));static ZERO=new b(o.ZERO,o.ONE,o.ONE,o.ZERO);static Fp=o;static Fn=s;X;Y;Z;T;constructor(y,A,I,F){this.X=d("x",y),this.Y=d("y",A),this.Z=d("z",I,!0),this.T=d("t",F),Object.freeze(this)}static CURVE(){return i}static fromAffine(y){if(y instanceof b)throw new Error("extended point not allowed");let{x:A,y:I}=y||{};return d("x",A),d("y",I),new b(A,I,o.ONE,o.mul(A,I))}static fromBytes(y,A=!1){let I=o.BYTES,{a:F,d:K}=i;y=Hn(Z(y,I,"point")),De(A,"zip215");let k=Hn(y),P=y[I-1];k[I-1]=P&-129;let N=zt(k),V=A?l:o.ORDER;yr("point.y",N,Qn,V);let L=o.sqr(N),re=o.sub(L,o.ONE),B=o.sub(o.mulN(K,L),F),{isValid:C,value:p}=f(re,B);if(!C)throw new Error("bad point: invalid y coordinate");let x=u(p),_=(P&128)!==0;if(!A&&o.is0(p)&&_)throw new Error("bad point: x=0 and x_0=1");return _!==x&&(p=o.neg(p)),b.fromAffine({x:p,y:N})}static fromHex(y,A=!1){return b.fromBytes(mr(y),A)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=6,A=!0){return w.setWindowSize(this,y),A||this.multiply(eo),this}assertValidity(){let y=this,{a:A,d:I}=i;if(y.is0())throw new Error("bad point: ZERO");let{X:F,Y:K,Z:k,T:P}=y,N=o.sqr(F),V=o.sqr(K),L=o.sqr(k),re=o.sqr(L),B=o.mul(N,A),C=o.mul(o.add(B,V),L),p=o.add(re,o.mul(I,o.mul(N,V)));if(!o.eql(C,p))throw new Error("bad point: equation left != right (1)");let x=o.mul(F,K),_=o.mul(k,P);if(!o.eql(x,_))throw new Error("bad point: equation left != right (2)")}equals(y){E(y);let{X:A,Y:I,Z:F}=this,{X:K,Y:k,Z:P}=y,N=o.mul(A,P),V=o.mul(K,F),L=o.mul(I,P),re=o.mul(k,F);return o.eql(N,V)&&o.eql(L,re)}is0(){return this.equals(b.ZERO)}negate(){return new b(o.neg(this.X),this.Y,this.Z,o.neg(this.T))}double(){let{X:y,Y:A,Z:I}=this,F=o.sqr(y),K=o.sqr(A),k=o.mul(o.sqr(I),eo),P=h(F),N=o.addN(y,A),V=o.sub(o.subN(o.sqr(N),F),K),L=o.addN(P,K),re=o.subN(L,k),B=o.subN(P,K),C=o.mul(V,re),p=o.mul(L,B),x=o.mul(V,B),_=o.mul(re,L);return new b(C,p,_,x)}add(y){E(y);let{d:A}=i,{X:I,Y:F,Z:K,T:k}=this,{X:P,Y:N,Z:V,T:L}=y,re=o.mul(I,P),B=o.mul(F,N),C=o.mul(o.mulN(k,A),L),p=o.mul(K,V),x=o.sub(o.subN(o.mulN(o.addN(I,F),o.addN(P,N)),re),B),_=o.subN(p,C),R=o.addN(p,C),S=o.sub(B,h(re)),m=o.mul(x,_),T=o.mul(R,S),D=o.mul(x,S),U=o.mul(_,R);return new b(m,T,U,D)}subtract(y){return E(y),this.add(y.negate())}multiply(y){if(!s.isValidNot0(y))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:A,f:I}=w.mulSecret(this,y,a,g);return g([A,I])[0]}multiplyUnsafe(y){if(!s.isValid(y))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return y===Qn?b.ZERO:this.is0()||y===Jn?this:w.mulUnsafe(this,y,g)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return w.mulUnsafe(this,i.n).is0()}toAffine(y){let A=this,I=y;if(I!=null&&typeof I!="bigint")throw new TypeError('"invertedZ" expected bigint, got type='+typeof I);let{X:F,Y:K,Z:k}=A,P=A.is0();I==null&&(I=P?o.create(hu):o.inv(k));let N=o.mul(F,I),V=o.mul(K,I),L=o.mul(k,I);if(P)return{x:o.ZERO,y:o.ONE};if(!o.eql(L,o.ONE))throw new Error("invZ was invalid");return{x:N,y:V}}clearCofactor(){return a===Jn?this:a===eo?this.double():a===lh?this.double().double():a===hu?this.double().double().double():this.multiplyUnsafe(a)}toBytes(){let{x:y,y:A}=this.toAffine(),I=o.toBytes(A);return I[I.length-1]|=u(y)?128:0,I}toHex(){return Yr(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let g=v=>jn(b,v),w=new xr(b,c);return w.bits>=6&&b.BASE.precompute(6),Object.freeze(b.prototype),Object.freeze(b),b}function mu(t,e,r={}){if(Tt(t),typeof e!="function")throw new Error('"hash" function param is required');let n=e,o=r;Ce(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function",toMontgomery:"function",toMontgomerySecret:"function"});let{prehash:s}=o,{BASE:i,Fp:a,Fn:c}=t,l=n.outputLen,u=2*a.BYTES;if(l!==void 0&&(_t(l,"hash.outputLen"),l!==u))throw new Error(`hash.outputLen must be ${u}, got ${l}`);let f=o.randomBytes===void 0?qt:o.randomBytes,h=o.toMontgomery,d=o.toMontgomerySecret,E=o.adjustScalarBytes===void 0?B=>B:o.adjustScalarBytes,b=o.domain===void 0?(B,C,p)=>{if(De(p,"phflag"),C.length||p)throw new Error("Contexts/pre-hash are not supported");return B}:o.domain;function g(B){return c.create(zt(B))}function w(B){let C=P.secretKey;Z(B,P.secretKey,"secretKey");let p=Z(n(B),2*C,"hashedSecretKey"),x=E(p.slice(0,C)),_=p.slice(C,2*C),R=g(x);return{head:x,prefix:_,scalar:R}}function v(B){let{head:C,prefix:p,scalar:x}=w(B),_=i.multiply(x),R=_.toBytes();return{head:C,prefix:p,scalar:x,point:_,pointBytes:R}}function y(B){return v(B).pointBytes}function A(B=Uint8Array.of(),...C){let p=Ke(...C);return g(n(b(p,Z(B,void 0,"context"),!!s)))}function I(B,C,p={}){Ce(p,{},{},"options"),B=Z(B,void 0,"message"),s&&(B=s(B));let{prefix:x,scalar:_,pointBytes:R}=v(C),S=A(p.context,x,B),m=i.multiply(S).toBytes(),T=A(p.context,m,R,B),D=c.create(S+T*_);if(!c.isValid(D))throw new Error("sign failed: invalid s");let U=Ke(m,c.toBytes(D));return Z(U,P.signature,"result")}let F={zip215:o.zip215};function K(B,C,p,x=F){Ce(x);let{context:_}=x,R=x.zip215===void 0?!!F.zip215:x.zip215,S=P.signature;B=Z(B,S,"signature"),C=Z(C,void 0,"message"),p=Z(p,P.publicKey,"publicKey"),R!==void 0&&De(R,"zip215"),s&&(C=s(C));let m=S/2,T=B.subarray(0,m),D=zt(B.subarray(m,S)),U,M,G;try{U=t.fromBytes(p,R),M=t.fromBytes(T,R),G=i.multiplyUnsafe(D)}catch{return!1}if(!R&&U.isSmallOrder())return!1;let j=A(_,T,p,C);return M.add(U.multiplyUnsafe(j)).subtract(G).clearCofactor().is0()}let k=a.BYTES,P={secretKey:k,publicKey:k,signature:2*k,seed:k};function N(B){return B=B===void 0?f(P.seed):B,Z(B,P.seed,"seed")}function V(B){return vt(B)&&B.length===P.secretKey}function L(B,C){try{return!!t.fromBytes(B,C===void 0?F.zip215:C)}catch{return!1}}let re={getExtendedPublicKey:v,randomSecretKey:N,isValidSecretKey:V,isValidPublicKey:L,toMontgomery(B){if(h===void 0)throw new Error("Montgomery conversion is not supported for this curve");return h(t.fromBytes(B))},toMontgomerySecret(B){if(d===void 0)throw new Error("Montgomery conversion is not supported for this curve");return d(B)}};return Object.freeze(P),Object.freeze(re),Object.freeze({keygen:Xn(N,y),getPublicKey:y,sign:I,verify:K,utils:re,Point:t,lengths:P})}var ni=BigInt(1),yu=BigInt(2);var dh=BigInt(5),hh=BigInt(8),oi=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),ph={p:oi,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:hh,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function mh(t){let e=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),s=oi,a=t*t%s*t%s,c=se(a,yu,s)*a%s,l=se(c,ni,s)*t%s,u=se(l,dh,s)*l%s,f=se(u,e,s)*u%s,h=se(f,r,s)*f%s,d=se(h,n,s)*h%s,E=se(d,o,s)*d%s,b=se(E,o,s)*d%s,g=se(b,e,s)*u%s;return{pow_p_5_8:se(g,yu,s)*t%s,b2:a}}function wu(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}var gu=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function yh(t,e){let r=oi,n=ae(e*e*e,r),o=ae(n*n*e,r),s=mh(t*o).pow_p_5_8,i=ae(t*n*s,r),a=ae(e*i*i,r),c=i,l=ae(i*gu,r),u=a===t,f=a===ae(-t,r),h=a===ae(-t*gu,r);return u&&(i=c),(f||h)&&(i=l),iu(i,r)&&(i=ae(-i,r)),{isValid:u||f,value:i}}var si=pu(ph,{uvRatio:yh}),bu=si.Fp;function gh(t){let{y:e}=t;return bu.toBytes(bu.div(ni+e,ni-e))}function bh(t){let e=si.Fp.BYTES;return Fe(t,e),wu(Ws(t.subarray(0,e))).subarray(0,e)}function wh(t){return mu(si,Ws,Object.assign({adjustScalarBytes:wu,toMontgomery:gh,toMontgomerySecret:bh,zip215:!0},t))}var xu=wh({});var Qr=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},to=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var qe={get(t=globalThis){let e=t.crypto;if(e?.subtle==null)throw new to("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return e}};var ro=32;var ii,xh=(async()=>{try{return await qe.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function Eh(t,e,r){if(t.buffer instanceof ArrayBuffer){let n=await qe.get().subtle.importKey("raw",t.buffer,{name:"Ed25519"},!1,["verify"]);return await qe.get().subtle.verify({name:"Ed25519"},n,_e(e),_e(r instanceof Uint8Array?r:r.subarray()))}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function Sh(t,e,r){return xu.verify(e,r instanceof Uint8Array?r:r.subarray(),t)}async function Eu(t,e,r){return ii==null&&(ii=await xh),ii?Eh(t,e,r):Sh(t,e,r)}function no(t){return t==null?!1:typeof t.then=="function"&&typeof t.catch=="function"&&typeof t.finally=="function"}var oo=class{type="Ed25519";raw;constructor(e){this.raw=ai(e,ro)}toMultihash(){return He.digest(Je(this))}toCID(){return pe.createV1(114,this.toMultihash())}toString(){return ie.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:he(this.raw,e.raw)}verify(e,r,n){n?.signal?.throwIfAborted();let o=Eu(this.raw,r,e);return no(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function ci(t){return t=ai(t,ro),new oo(t)}function ai(t,e){if(t=Uint8Array.from(t??[]),t.length!==e)throw new fe(`Key must be a Uint8Array of length ${e}, got ${t.length}`);return t}var _h=Math.pow(2,7),Ah=Math.pow(2,14),Th=Math.pow(2,21),ui=Math.pow(2,28),li=Math.pow(2,35),fi=Math.pow(2,42),di=Math.pow(2,49),Q=128,xe=127;function Be(t){if(t<_h)return 1;if(t<Ah)return 2;if(t<Th)return 3;if(t<ui)return 4;if(t<li)return 5;if(t<fi)return 6;if(t<di)return 7;if(Number.MAX_SAFE_INTEGER!=null&&t>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Er(t,e,r=0){switch(Be(t)){case 8:e[r++]=t&255|Q,t/=128;case 7:e[r++]=t&255|Q,t/=128;case 6:e[r++]=t&255|Q,t/=128;case 5:e[r++]=t&255|Q,t/=128;case 4:e[r++]=t&255|Q,t>>>=7;case 3:e[r++]=t&255|Q,t>>>=7;case 2:e[r++]=t&255|Q,t>>>=7;case 1:{e[r++]=t&255,t>>>=7;break}default:throw new Error("unreachable")}return e}function Ih(t,e,r=0){switch(Be(t)){case 8:e.set(r++,t&255|Q),t/=128;case 7:e.set(r++,t&255|Q),t/=128;case 6:e.set(r++,t&255|Q),t/=128;case 5:e.set(r++,t&255|Q),t/=128;case 4:e.set(r++,t&255|Q),t>>>=7;case 3:e.set(r++,t&255|Q),t>>>=7;case 2:e.set(r++,t&255|Q),t>>>=7;case 1:{e.set(r++,t&255),t>>>=7;break}default:throw new Error("unreachable")}return e}function hi(t,e){let r=t[e],n=0;if(n+=r&xe,r<Q||(r=t[e+1],n+=(r&xe)<<7,r<Q)||(r=t[e+2],n+=(r&xe)<<14,r<Q)||(r=t[e+3],n+=(r&xe)<<21,r<Q)||(r=t[e+4],n+=(r&xe)*ui,r<Q)||(r=t[e+5],n+=(r&xe)*li,r<Q)||(r=t[e+6],n+=(r&xe)*fi,r<Q)||(r=t[e+7],n+=(r&xe)*di,r<Q))return n;throw new RangeError("Could not decode varint")}function Dh(t,e){let r=t.get(e),n=0;if(n+=r&xe,r<Q||(r=t.get(e+1),n+=(r&xe)<<7,r<Q)||(r=t.get(e+2),n+=(r&xe)<<14,r<Q)||(r=t.get(e+3),n+=(r&xe)<<21,r<Q)||(r=t.get(e+4),n+=(r&xe)*ui,r<Q)||(r=t.get(e+5),n+=(r&xe)*li,r<Q)||(r=t.get(e+6),n+=(r&xe)*fi,r<Q)||(r=t.get(e+7),n+=(r&xe)*di,r<Q))return n;throw new RangeError("Could not decode varint")}function Sr(t,e,r=0){return e==null&&(e=we(Be(t))),e instanceof Uint8Array?Er(t,e,r):Ih(t,e,r)}function Jr(t,e=0){return t instanceof Uint8Array?hi(t,e):Dh(t,e)}var mi=new Float32Array([-0]),It=new Uint8Array(mi.buffer);function vu(t,e,r){mi[0]=t,e[r]=It[0],e[r+1]=It[1],e[r+2]=It[2],e[r+3]=It[3]}function _u(t,e){return It[0]=t[e],It[1]=t[e+1],It[2]=t[e+2],It[3]=t[e+3],mi[0]}var yi=new Float64Array([-0]),Ee=new Uint8Array(yi.buffer);function Au(t,e,r){yi[0]=t,e[r]=Ee[0],e[r+1]=Ee[1],e[r+2]=Ee[2],e[r+3]=Ee[3],e[r+4]=Ee[4],e[r+5]=Ee[5],e[r+6]=Ee[6],e[r+7]=Ee[7]}function Tu(t,e){return Ee[0]=t[e],Ee[1]=t[e+1],Ee[2]=t[e+2],Ee[3]=t[e+3],Ee[4]=t[e+4],Ee[5]=t[e+5],Ee[6]=t[e+6],Ee[7]=t[e+7],yi[0]}var Ch=BigInt(Number.MAX_SAFE_INTEGER),Bh=BigInt(Number.MIN_SAFE_INTEGER),Ne=class t{lo;hi;constructor(e,r){this.lo=e|0,this.hi=r|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let r=~this.lo+1>>>0,n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(r+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let r=~this.lo+1>>>0,n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(BigInt(r)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,r=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?r===0?e<16384?e<128?1:2:e<2097152?3:4:r<16384?r<128?5:6:r<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return Ht;if(e<Ch&&e>Bh)return this.fromNumber(Number(e));let r=e<0n;r&&(e=-e);let n=e>>32n,o=e-(n<<32n);return r&&(n=~n|0n,o=~o|0n,++o>Iu&&(o=0n,++n>Iu&&(n=0n))),new t(Number(o),Number(n))}static fromNumber(e){if(e===0)return Ht;let r=e<0;r&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return r&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new t(n,o)}static from(e){return typeof e=="number"?t.fromNumber(e):typeof e=="bigint"?t.fromBigInt(e):typeof e=="string"?t.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new t(e.low>>>0,e.high>>>0):Ht}},Ht=new Ne(0,0);Ht.toBigInt=function(){return 0n};Ht.zzEncode=Ht.zzDecode=function(){return this};Ht.length=function(){return 1};var Iu=4294967296n;function Du(t){let e=0,r=0;for(let n=0;n<t.length;++n)r=t.charCodeAt(n),r<128?e+=1:r<2048?e+=2:(r&64512)===55296&&(t.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function Cu(t,e,r){if(r-e<1)return"";let o,s=[],i=0,a;for(;e<r;)a=t[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|t[e++]&63:a>239&&a<365?(a=((a&7)<<18|(t[e++]&63)<<12|(t[e++]&63)<<6|t[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(t[e++]&63)<<6|t[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function gi(t,e,r){let n=r,o,s;for(let i=0;i<t.length;++i)o=t.charCodeAt(i),o<128?e[r++]=o:o<2048?(e[r++]=o>>6|192,e[r++]=o&63|128):(o&64512)===55296&&((s=t.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[r++]=o>>18|240,e[r++]=o>>12&63|128,e[r++]=o>>6&63|128,e[r++]=o&63|128):(e[r++]=o>>12|224,e[r++]=o>>6&63|128,e[r++]=o&63|128);return r-n}function $e(t,e){return RangeError(`index out of range: ${t.pos} + ${e??1} > ${t.len}`)}function so(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}var bi=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=_e(e),this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,$e(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw $e(this,4);return so(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw $e(this,4);return so(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw $e(this,4);let e=_u(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw $e(this,4);let e=Tu(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),r=this.pos,n=this.pos+e;if(n>this.len)throw $e(this,e);return this.pos+=e,r===n?new Uint8Array(0):this.buf.subarray(r,n)}string(){let e=this.bytes();return Cu(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw $e(this,e);this.pos+=e}else do if(this.pos>=this.len)throw $e(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new Ne(0,0),r=0;if(this.len-this.pos>4){for(;r<4;++r)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;r=0}else{for(;r<3;++r){if(this.pos>=this.len)throw $e(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<r*7)>>>0,e}if(this.len-this.pos>4){for(;r<5;++r)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;r<5;++r){if(this.pos>=this.len)throw $e(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw $e(this,8);let e=so(this.buf,this.pos+=4),r=so(this.buf,this.pos+=4);return new Ne(e,r)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=hi(this.buf,this.pos);return this.pos+=Be(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function en(t){return new bi(t instanceof Uint8Array?t:t.subarray())}function Le(t,e,r){let n=en(t);return e.decode(n,void 0,r)}function wi(t){let e=t??8192,r=e>>>1,n,o=e;return function(i){if(i<1||i>r)return we(i);o+i>e&&(n=we(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var Vt=class{fn;len;next;val;constructor(e,r,n){this.fn=e,this.len=r,this.next=void 0,this.val=n}};function xi(){}var Si=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},Lh=wi();function Rh(t){return globalThis.Buffer!=null?we(t):Lh(t)}var rn=class{len;head;tail;states;constructor(){this.len=0,this.head=new Vt(xi,0,0),this.tail=this.head,this.states=null}_push(e,r,n){return this.tail=this.tail.next=new Vt(e,r,n),this.len+=r,this}uint32(e){return this.len+=(this.tail=this.tail.next=new vi((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(io,10,Ne.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let r=Ne.fromBigInt(e);return this._push(io,r.length(),r)}uint64Number(e){return this._push(Er,Be(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let r=Ne.fromBigInt(e).zzEncode();return this._push(io,r.length(),r)}sint64Number(e){let r=Ne.fromNumber(e).zzEncode();return this._push(io,r.length(),r)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Ei,1,e?1:0)}fixed32(e){return this._push(tn,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let r=Ne.fromBigInt(e);return this._push(tn,4,r.lo)._push(tn,4,r.hi)}fixed64Number(e){let r=Ne.fromNumber(e);return this._push(tn,4,r.lo)._push(tn,4,r.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(vu,4,e)}double(e){return this._push(Au,8,e)}bytes(e){let r=e.length>>>0;return r===0?this._push(Ei,1,0):this.uint32(r)._push(Ph,r,e)}string(e){let r=Du(e);return r!==0?this.uint32(r)._push(gi,r,e):this._push(Ei,1,0)}fork(){return this.states=new Si(this),this.head=this.tail=new Vt(xi,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 Vt(xi,0,0),this.len=0),this}ldelim(){let e=this.head,r=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=r,this.len+=n),this}finish(){let e=this.head.next,r=Rh(this.len),n=0;for(;e!=null;)e.fn(e.val,r,n),n+=e.len,e=e.next;return r}};function Ei(t,e,r){e[r]=t&255}function Oh(t,e,r){for(;t>127;)e[r++]=t&127|128,t>>>=7;e[r]=t}var vi=class extends Vt{next;constructor(e,r){super(Oh,e,r),this.next=void 0}};function io(t,e,r){for(;t.hi!==0;)e[r++]=t.lo&127|128,t.lo=(t.lo>>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;t.lo>127;)e[r++]=t.lo&127|128,t.lo=t.lo>>>7;e[r++]=t.lo}function tn(t,e,r){e[r]=t&255,e[r+1]=t>>>8&255,e[r+2]=t>>>16&255,e[r+3]=t>>>24}function Ph(t,e,r){e.set(t,r)}globalThis.Buffer!=null&&(rn.prototype.bytes=function(t){let e=t.length>>>0;return this.uint32(e),e>0&&this._push(Nh,e,t),this},rn.prototype.string=function(t){let e=globalThis.Buffer.byteLength(t);return this.uint32(e),e>0&&this._push(kh,e,t),this});function Nh(t,e,r){e.set(t,r)}function kh(t,e,r){t.length<40?gi(t,e,r):e.utf8Write!=null?e.utf8Write(t,r):e.set(q(t),r)}function _i(){return new rn}function Re(t,e){let r=_i();return e.encode(t,r,{lengthDelimited:!1}),r.finish()}function*Oe(t,e,r){let n=en(t);yield*e.stream(n,void 0,"$",r)}var ao={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function co(t,e,r,n,o){return{name:t,type:e,encode:r,decode:n,stream:o}}function $t(t){function e(s){if(t[s.toString()]==null)throw new Error("Invalid enum value");return t[s]}let r=function(i,a){let c=e(i);a.int32(c)},n=function(i){let a=i.int32();return e(a)},o=function*(i){let a=i.int32();yield e(a)};return co("enum",ao.VARINT,r,n,o)}function Pe(t,e,r){return co("message",ao.LENGTH_DELIMITED,t,e,r)}var Wt=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var ce;(function(t){t.RSA="RSA",t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.ECDSA="ECDSA"})(ce||(ce={}));var Ai;(function(t){t[t.RSA=0]="RSA",t[t.Ed25519=1]="Ed25519",t[t.secp256k1=2]="secp256k1",t[t.ECDSA=3]="ECDSA"})(Ai||(Ai={}));(function(t){t.codec=()=>$t(Ai)})(ce||(ce={}));var rt;(function(t){let e;t.codec=()=>(e==null&&(e=Pe((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),ce.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=ce.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:ce.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function r(s){return Re(s,t.codec())}t.encode=r;function n(s,i){return Le(s,t.codec(),i)}t.decode=n;function o(s,i){return Oe(s,t.codec(),i)}t.stream=o})(rt||(rt={}));var Ti;(function(t){let e;t.codec=()=>(e==null&&(e=Pe((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),ce.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=ce.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:ce.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function r(s){return Re(s,t.codec())}t.encode=r;function n(s,i){return Le(s,t.codec(),i)}t.decode=n;function o(s,i){return Oe(s,t.codec(),i)}t.stream=o})(Ti||(Ti={}));var on={};Ae(on,{MAX_RSA_KEY_SIZE:()=>Ii,generateRSAKeyPair:()=>Nu,jwkToJWKKeyPair:()=>ku,jwkToPkcs1:()=>Kh,jwkToPkix:()=>Li,jwkToRSAPrivateKey:()=>Ni,pkcs1MessageToJwk:()=>Ci,pkcs1MessageToRSAPrivateKey:()=>Ri,pkcs1ToJwk:()=>Fh,pkcs1ToRSAPrivateKey:()=>Pu,pkixMessageToJwk:()=>Bi,pkixMessageToRSAPublicKey:()=>Pi,pkixToJwk:()=>qh,pkixToRSAPublicKey:()=>Oi});var vr=class{type="RSA";jwk;_raw;_multihash;constructor(e,r){this.jwk=e,this._multihash=r}get raw(){return this._raw==null&&(this._raw=on.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return pe.createV1(114,this._multihash)}toString(){return ie.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:he(this.raw,e.raw)}verify(e,r,n){return Ou(this.jwk,r,e,n)}},nn=class{type="RSA";jwk;_raw;publicKey;constructor(e,r){this.jwk=e,this.publicKey=r}get raw(){return this._raw==null&&(this._raw=on.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:he(this.raw,e.raw)}sign(e,r){return Ru(this.jwk,e,r)}};var Ii=8192,Di=18,Uh=1062,Mh=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function Fh(t){let e=it(t);return Ci(e)}function Ci(t){return{n:$(t[1],"base64url"),e:$(t[2],"base64url"),d:$(t[3],"base64url"),p:$(t[4],"base64url"),q:$(t[5],"base64url"),dp:$(t[6],"base64url"),dq:$(t[7],"base64url"),qi:$(t[8],"base64url"),kty:"RSA"}}function Kh(t){if(t.n==null||t.e==null||t.d==null||t.p==null||t.q==null||t.dp==null||t.dq==null||t.qi==null)throw new fe("JWK was missing components");return gt([Ie(Uint8Array.from([0])),Ie(q(t.n,"base64url")),Ie(q(t.e,"base64url")),Ie(q(t.d,"base64url")),Ie(q(t.p,"base64url")),Ie(q(t.q,"base64url")),Ie(q(t.dp,"base64url")),Ie(q(t.dq,"base64url")),Ie(q(t.qi,"base64url"))]).subarray()}function qh(t){let e=it(t,{offset:0});return Bi(e)}function Bi(t){let e=it(t[1],{offset:0});return{kty:"RSA",n:$(e[0],"base64url"),e:$(e[1],"base64url")}}function Li(t){if(t.n==null||t.e==null)throw new fe("JWK was missing components");return gt([Mh,Ln(gt([Ie(q(t.n,"base64url")),Ie(q(t.e,"base64url"))]))]).subarray()}function Pu(t){let e=it(t);return Ri(e)}function Ri(t){let e=Ci(t);return Ni(e)}function Oi(t,e){if(t.byteLength>=Uh)throw new or("Key size is too large");let r=it(t,{offset:0});return Pi(r,t,e)}function Pi(t,e,r){let n=Bi(t);if(r==null){let o=pr(rt.encode({Type:ce.RSA,Data:e}));r=Ze(Di,o)}return new vr(n,r)}function Ni(t){if(Mu(t)>Ii)throw new fe("Key size is too large");let e=ku(t),r=pr(rt.encode({Type:ce.RSA,Data:Li(e.publicKey)})),n=Ze(Di,r);return new nn(e.privateKey,new vr(e.publicKey,n))}async function Nu(t){if(t>Ii)throw new fe("Key size is too large");let e=await Uu(t),r=pr(rt.encode({Type:ce.RSA,Data:Li(e.publicKey)})),n=Ze(Di,r);return new nn(e.privateKey,new vr(e.publicKey,n))}function ku(t){if(t==null)throw new fe("Missing key parameter");return{privateKey:t,publicKey:{kty:t.kty,n:t.n,e:t.e}}}async function Uu(t,e){let r=await qe.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:t,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);e?.signal?.throwIfAborted();let n=await zh(r,e);return{privateKey:n[0],publicKey:n[1]}}async function Ru(t,e,r){let n=await qe.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);r?.signal?.throwIfAborted();let o=await qe.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,_e(e instanceof Uint8Array?e:e.subarray()));return r?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function Ou(t,e,r,n){let o=await qe.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let s=await qe.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,_e(e),_e(r instanceof Uint8Array?r:r.subarray()));return n?.signal?.throwIfAborted(),s}async function zh(t,e){if(t.privateKey==null||t.publicKey==null)throw new fe("Private and public key are required");let r=await Promise.all([qe.get().subtle.exportKey("jwk",t.privateKey),qe.get().subtle.exportKey("jwk",t.publicKey)]);return e?.signal?.throwIfAborted(),r}function Mu(t){if(t.kty!=="RSA")throw new fe("invalid key type");if(t.n==null)throw new fe("invalid key modulus");return q(t.n,"base64url").length*8}var uo=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,r){if(Pn(e),Fe(r,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("expected Hash instance");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(r.length>n?e.create().update(r).digest():r);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),Ft(o)}update(e){return hr(this),this.iHash.update(e),this}digestInto(e){hr(this),Nn(e,this),this.finished=!0;let r=e.subarray(0,this.outputLen);this.iHash.digestInto(r),this.oHash.update(r),this.oHash.digestInto(r),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:r,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a,canXOF:c}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.canXOF=c,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Fu=(()=>{let t=((e,r,n)=>new uo(e,r).update(n).digest());return t.create=(e,r)=>new uo(e,r),t})();var Hh=BigInt(0),ki=class extends Error{constructor(e=""){super(e)}},ct={Err:ki,_tlv:{encode:(t,e)=>{let{Err:r}=ct;if(_t(t,"tag"),t<0||t>255)throw new r("tlv.encode: wrong tag");if(Yc(e,"data"),e.length&1)throw new r("tlv.encode: unpadded data");let n=e.length/2,o=jr(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");let s=n>127?jr(o.length/2|128):"";return jr(t)+s+o+e},decode(t,e){let{Err:r}=ct;e=Z(e,void 0,"DER data");let n=0;if(t<0||t>255)throw new r("tlv.decode: wrong tag");if(e.length<2||e[n++]!==t)throw new r("tlv.decode: wrong tlv");let o=e[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let l=e.subarray(n,n+c);if(l.length!==c)throw new r("tlv.decode: length bytes not complete");if(l[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let u of l)i=i<<8|u;if(n+=c,i<128)throw new r("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(t){let{Err:e}=ct;if(qn(t),t<Hh)throw new e("integer: negative integers are not allowed");let r=jr(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){let{Err:e}=ct;if(t.length<1)throw new e("invalid signature integer: empty");if(t[0]&128)throw new e("invalid signature integer: negative");if(t.length>1&&t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return tt(t)}},toSig(t){let{Err:e,_int:r,_tlv:n}=ct,o=Z(t,void 0,"signature"),{v:s,l:i}=n.decode(48,o);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:l,l:u}=n.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(l)}},hexFromSig(t){let{_tlv:e,_int:r}=ct;Ce(t,{r:"bigint",s:"bigint"},{},"sig");let n=e.encode(2,r.encode(t.r)),o=e.encode(2,r.encode(t.s)),s=n+o;return e.encode(48,s)}},Ui=(Object.freeze(ct._tlv),Object.freeze(ct._int),Object.freeze(ct));var Ku=(t,e)=>(t+(t>=0?e:-e)/qu)/e;function Vh(t,e,r){yr("scalar",t,ut,r);let[[n,o],[s,i]]=e,a=Ku(i*t,r),c=Ku(-o*t,r),l=t-a*n-c*s,u=-a*o-c*i,f=l<ut,h=u<ut;f&&(l=-l),h&&(u=-u);let d=Gr(Math.ceil(gr(r)/2))+Yt;if(l<ut||l>=d||u<ut||u>=d)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:f,k1:l,k2neg:h,k2:u}}function Ki(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Mi(t,e){Ce(t);let r={};for(let n of Object.keys(e))r[n]=t[n]===void 0?e[n]:t[n];return De(r.lowS,"lowS"),De(r.prehash,"prehash"),r.format!==void 0&&Ki(r.format),r}var ut=BigInt(0),Yt=BigInt(1),qu=BigInt(2),Fi=BigInt(3),$h=BigInt(4);function zu(t,e={}){let r=Zn("weierstrass",t,e),n=r.Fp,o=r.Fn,s=r.CURVE,{h:i,n:a}=s;Ce(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",randomBytes:"function"});let{endo:c,allowInfinityPoint:l}=e,u=e.randomBytes===void 0?qt:e.randomBytes;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 f=Vu(n,o);function h(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function d(C,p,x){if(l&&p.is0())return Uint8Array.of(0);let{x:_,y:R}=p.toAffine(),S=n.toBytes(_);if(De(x,"isCompressed"),x){h();let m=!n.isOdd(R);return Ke(Hu(m),S)}else return Ke(Uint8Array.of(4),S,n.toBytes(R))}function E(C){Z(C,void 0,"Point");let{publicKey:p,publicKeyUncompressed:x}=f,_=C.length,R=C[0],S=C.subarray(1);if(l&&_===1&&R===0)return{x:n.ZERO,y:n.ZERO};if(_===p&&(R===2||R===3)){let m=n.fromBytes(S);if(!n.isValid(m))throw new Error("bad point: is not on curve, wrong x");let T=y(m),D;try{D=n.sqrt(T)}catch(G){let j=G instanceof Error?": "+G.message:"";throw new Error("bad point: is not on curve, sqrt error"+j)}h();let U=n.isOdd(D);return(R&1)===1!==U&&(D=n.neg(D)),{x:m,y:D}}else if(_===x&&R===4){let m=n.BYTES,T=n.fromBytes(S.subarray(0,m)),D=n.fromBytes(S.subarray(m,m*2));if(!A(T,D))throw new Error("bad point: is not on curve");return{x:T,y:D}}else throw new Error(`bad point: got length ${_}, expected compressed=${p} or uncompressed=${x}`)}let b=e.toBytes===void 0?d:e.toBytes,g=e.fromBytes===void 0?E:e.fromBytes,w=n.mul(s.b,Fi),v=n.is0(s.a)?C=>n.ZERO:C=>n.mul(s.a,C);function y(C){let p=n.sqr(C),x=n.mul(p,C);return n.add(n.add(x,n.mul(C,s.a)),s.b)}function A(C,p){let x=n.sqr(p),_=y(C);return n.eql(x,_)}if(!A(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let I=n.mul(n.pow(s.a,Fi),$h),F=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(I,F)))throw new Error("bad curve params: a or b");function K(C,p,x=!1){if(!n.isValid(p)||x&&n.is0(p))throw new Error(`bad point coordinate ${C}`);return p}function k(C){if(!(C instanceof L))throw new Error("Weierstrass Point expected")}function P(C){if(!c||!c.basises)throw new Error("no endo");return Vh(C,c.basises,o.ORDER)}function N(C,p,x,_){if(!o.isValid(_))throw new RangeError("invalid scalar: out of range");if(c){let{k1neg:R,k1:S,k2neg:m,k2:T}=P(_),D=new L(n.mul(x.X,c.beta),x.Y,x.Z);C.push(R?x.negate():x,m?D.negate():D),p.push(S,T)}else C.push(x),p.push(_)}let V=new WeakSet;class L{static BASE=new L(s.Gx,s.Gy,n.ONE);static ZERO=new L(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(p,x,_){this.X=K("x",p),this.Y=K("y",x,!0),this.Z=K("z",_),Object.freeze(this)}static CURVE(){return s}static fromAffine(p){let{x,y:_}=p||{};if(!p||!n.isValid(x)||!n.isValid(_))throw new Error("invalid affine point");if(p instanceof L)throw new Error("projective point not allowed");return n.is0(x)&&n.is0(_)?L.ZERO:new L(x,_,n.ONE)}static fromBytes(p){let x=L.fromAffine(g(Z(p,void 0,"point")));return x.assertValidity(),x}static fromHex(p){return L.fromBytes(mr(p))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(p=6,x=!0){return B.setWindowSize(this,p),x||this.multiply(Fi),this}assertValidity(){let p=this;if(p.is0()){if(e.allowInfinityPoint&&n.is0(p.X)&&n.eql(p.Y,n.ONE)&&n.is0(p.Z))return;throw new Error("bad point: ZERO")}if(V.has(p))return;let{x,y:_}=p.toAffine();if(!n.isValid(x)||!n.isValid(_))throw new Error("bad point: x or y not field elements");if(!A(x,_))throw new Error("bad point: equation left != right");if(!p.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");V.add(p)}hasEvenY(){let{y:p}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(p)}equals(p){k(p);let{X:x,Y:_,Z:R}=this,{X:S,Y:m,Z:T}=p,D=n.eql(n.mul(x,T),n.mul(S,R)),U=n.eql(n.mul(_,T),n.mul(m,R));return D&&U}negate(){return new L(this.X,n.neg(this.Y),this.Z)}double(){let{X:p,Y:x,Z:_}=this,R=n.ZERO,S=n.ZERO,m=n.ZERO,T=n.mul(p,p),D=n.mul(x,x),U=n.mul(_,_),M=n.mul(p,x);return M=n.add(M,M),m=n.mul(p,_),m=n.add(m,m),R=v(m),S=n.mul(w,U),S=n.add(R,S),R=n.sub(D,S),S=n.add(D,S),S=n.mul(R,S),R=n.mul(M,R),m=n.mul(w,m),U=v(U),M=n.sub(T,U),M=v(M),M=n.add(M,m),m=n.add(T,T),T=n.add(m,T),T=n.add(T,U),T=n.mul(T,M),S=n.add(S,T),U=n.mul(x,_),U=n.add(U,U),T=n.mul(U,M),R=n.sub(R,T),m=n.mul(U,D),m=n.add(m,m),m=n.add(m,m),new L(R,S,m)}add(p){k(p);let{X:x,Y:_,Z:R}=this,{X:S,Y:m,Z:T}=p,D=n.ZERO,U=n.ZERO,M=n.ZERO,G=n.mul(x,S),j=n.mul(_,m),ue=n.mul(R,T),ve=n.add(x,_),le=n.add(S,m);ve=n.mul(ve,le),le=n.add(G,j),ve=n.sub(ve,le),le=n.add(x,R);let be=n.add(S,T);return le=n.mul(le,be),be=n.add(G,ue),le=n.sub(le,be),be=n.add(_,R),D=n.add(m,T),be=n.mul(be,D),D=n.add(j,ue),be=n.sub(be,D),M=v(le),D=n.mul(w,ue),M=n.add(D,M),D=n.sub(j,M),M=n.add(j,M),U=n.mul(D,M),j=n.add(G,G),j=n.add(j,G),ue=v(ue),le=n.mul(w,le),j=n.add(j,ue),ue=n.sub(G,ue),ue=v(ue),le=n.add(le,ue),G=n.mul(j,le),U=n.add(U,G),G=n.mul(be,le),D=n.mul(ve,D),D=n.sub(D,G),G=n.mul(ve,j),M=n.mul(be,M),M=n.add(M,G),new L(D,U,M)}subtract(p){return k(p),this.add(p.negate())}is0(){return this.equals(L.ZERO)}multiply(p){if(!o.isValidNot0(p))throw new RangeError("invalid scalar: out of range");let{p:x,f:_}=B.mulSecret(this,p,i,re);return re([x,_])[0]}multiplyUnsafe(p){let x=this,_=p;if(!o.isValid(_))throw new RangeError("invalid scalar: out of range");if(_===ut||x.is0())return L.ZERO;if(_===Yt)return x;if(B.hasWindowSize(this))return B.mulUnsafe(x,_,re);let R=[],S=[];return N(R,S,x,_),Gn(L,R,S)}mulAddUnsafe(p,x,_){k(x);let R=[],S=[];return N(R,S,this,p),N(R,S,x,_),Gn(L,R,S)}toAffine(p){let x=this,_=p;if(_!=null&&!n.isValid(_))throw new RangeError('"invertedZ" expected valid field element');let{X:R,Y:S,Z:m}=x;if(n.eql(m,n.ONE))return{x:R,y:S};let T=x.is0();_==null&&(_=T?n.ONE:n.inv(m));let D=n.mul(R,_),U=n.mul(S,_),M=n.mul(m,_);if(T)return{x:n.ZERO,y:n.ZERO};if(!n.eql(M,n.ONE))throw new Error("invZ was invalid");return{x:D,y:U}}isTorsionFree(){let{isTorsionFree:p}=e;return i===Yt?!0:p?p(L,this):B.mulUnsafe(this,a).is0()}clearCofactor(){let{clearCofactor:p}=e;return i===Yt?this:p?p(L,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===Yt?this.is0():this.clearCofactor().is0()}toBytes(p=!0){return De(p,"isCompressed"),this.assertValidity(),b(L,this,p)}toHex(p=!0){return Yr(this.toBytes(p))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let re=C=>jn(L,C),B=new xr(L,u);return B.bits>=6&&L.BASE.precompute(6),Object.freeze(L.prototype),Object.freeze(L),L}function Hu(t){return Uint8Array.of(t?2:3)}function Vu(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Wh(t,e={}){Tt(t);let{Fn:r}=t,n=e.randomBytes===void 0?qt:e.randomBytes,o=Object.assign(Vu(t.Fp,r),{seed:Math.max(Wn(r.ORDER),16)});function s(d){try{let E=r.fromBytes(d);return r.isValidNot0(E)}catch{return!1}}function i(d,E){let{publicKey:b,publicKeyUncompressed:g}=o;try{let w=d.length;return E===!0&&w!==b||E===!1&&w!==g?!1:!!t.fromBytes(d)}catch{return!1}}function a(d){return d=d===void 0?n(o.seed):d,Yn(Z(d,o.seed,"seed"),r.ORDER)}function c(d,E=!0){return t.BASE.multiply(r.fromBytes(d)).toBytes(E)}function l(d){let{secretKey:E,publicKey:b,publicKeyUncompressed:g}=o,w=r._lengths;if(!vt(d))return;let v=Z(d,void 0,"key").length,y=v===b||v===g,A=v===E||!!w?.includes(v);if(!(y&&A))return y}function u(d,E,b=!0){if(l(d)===!0)throw new Error("first arg must be private key");if(l(E)===!1)throw new Error("second arg must be public key");let g=r.fromBytes(d);return t.fromBytes(E).multiply(g).toBytes(b)}let f={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},h=Xn(a,c);return Object.freeze(f),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:h,Point:t,utils:f,lengths:o})}function $u(t,e,r={}){Tt(t);let n=e;Pn(n),Ce(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let o=Object.assign({},r),s=o.randomBytes===void 0?qt:o.randomBytes,i=o.hmac===void 0?(S,m)=>Fu(n,S,m):o.hmac,{Fp:a,Fn:c}=t,{ORDER:l,BITS:u}=c,f=Wn(l),h=ri(s,f),{keygen:d,getPublicKey:E,getSharedSecret:b,utils:g,lengths:w}=Wh(t,o),v={prehash:!0,lowS:typeof o.lowS=="boolean"?o.lowS:!0,format:"compact",extraEntropy:!1},y=l*qu+Yt<a.ORDER;function A(S){let m=l>>Yt;return S>m}function I(S,m){if(!c.isValidNot0(m))throw new Error(`invalid signature ${S}: out of range 1..Point.Fn.ORDER`);return m}function F(){if(!a.isOdd)throw new Error("Field doesn't support isOdd")}function K(S,m,T){return F(),(S===T?0:2)|Number(a.isOdd(m))}function k(){if(y)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function P(S,m){Ki(m);let T=w.signature,D=m==="compact"?T:m==="recovered"?T+1:void 0;return Z(S,D)}class N{r;s;recovery;constructor(m,T,D){if(this.r=I("r",m),this.s=I("s",T),D!=null){if(k(),![0,1,2,3].includes(D))throw new Error("invalid recovery id");this.recovery=D}Object.freeze(this)}static fromBytes(m,T=v.format){P(m,T);let D;if(T==="der"){let{r:j,s:ue}=Ui.toSig(Z(m));return new N(j,ue)}T==="recovered"&&(D=m[0],T="compact",m=m.subarray(1));let U=w.signature/2,M=m.subarray(0,U),G=m.subarray(U,U*2);return new N(c.fromBytes(M),c.fromBytes(G),D)}static fromHex(m,T){return this.fromBytes(mr(m),T)}assertRecovery(){let{recovery:m}=this;if(m==null)throw new Error("invalid recovery id: must be present");return m}addRecoveryBit(m){return new N(this.r,this.s,m)}recoverPublicKey(m){let{r:T,s:D}=this,U=this.assertRecovery(),M=U===2||U===3?T+l:T;if(!a.isValid(M))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let G=a.toBytes(M),j=t.fromBytes(Ke(Hu((U&1)===0),G)),ue=c.inv(M),ve=L(Z(m,void 0,"msgHash")),le=c.create(-ve*ue),be=c.create(D*ue),je=t.BASE.mulAddUnsafe(le,j,be);if(je.is0())throw new Error("invalid recovery: point at infinify");return je.assertValidity(),je}hasHighS(){return A(this.s)}toBytes(m=v.format){if(Ki(m),m==="der")return mr(Ui.hexFromSig(this));let{r:T,s:D}=this,U=c.toBytes(T),M=c.toBytes(D);return m==="recovered"?(k(),Ke(Uint8Array.of(this.assertRecovery()),U,M)):Ke(U,M)}toHex(m){return Yr(this.toBytes(m))}}Object.freeze(N.prototype),Object.freeze(N);let V=o.bits2int===void 0?function(m){if(m.length>8192)throw new Error("input is too large");let T=tt(m),D=m.length*8-u;return D>0?T>>BigInt(D):T}:o.bits2int,L=o.bits2int_modN===void 0?function(m){return c.create(V(m))}:o.bits2int_modN,re=Gr(u);function B(S){return yr("num < 2^"+u,S,ut,re),c.toBytes(S)}function C(S,m){return Z(S,void 0,"message"),m?Z(n(S),void 0,"prehashed message"):S}function p(S,m,T){let{lowS:D,prehash:U,extraEntropy:M}=Mi(T,v);S=C(S,U);let G=L(S),j=c.fromBytes(m);if(!c.isValidNot0(j))throw new Error("invalid private key");let ue=[B(j),B(G)];if(M!=null&&M!==!1){let je=M===!0?s(w.secretKey):M;ue.push(Z(je,void 0,"extraEntropy"))}let ve=Ke(...ue),le=G;function be(je){let nr=V(je);if(!c.isValidNot0(nr))return;let Pr=t.BASE.multiply(nr).toAffine(),ht=c.create(Pr.x);if(ht===ut)return;let Ge;if(h!==void 0){let Nr=tt(Yn(h(f),l)),ef=c.inv(c.mul(Nr,nr)),tf=c.mul(Nr,le),rf=c.mul(Nr,j);Ge=c.create(ef*c.create(tf+rf*ht))}else{let Nr=nu(nr,l);Ge=c.create(Nr*c.create(le+ht*j))}if(Ge===ut)return;let ns=K(Pr.x,Pr.y,ht),Va=Ge;return D&&A(Ge)&&(Va=c.neg(Ge),ns^=1),new N(ht,Va,y?void 0:ns)}return{seed:ve,k2sig:be}}function x(S,m,T={}){let{seed:D,k2sig:U}=p(S,m,T);return Gc(n.outputLen,c.BYTES,i)(D,U).toBytes(T.format)}function _(S,m,T,D={}){let{lowS:U,prehash:M,format:G}=Mi(D,v);if(T=Z(T,void 0,"publicKey"),m=C(m,M),!vt(S)){let j=S instanceof N?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+j)}P(S,G);try{let j=N.fromBytes(S,G),ue=t.fromBytes(T);if(U&&j.hasHighS())return!1;let{r:ve,s:le}=j,be=L(m),je=c.inv(le),nr=c.create(be*je),Pr=c.create(ve*je),ht=t.BASE.mulAddUnsafe(nr,ue,Pr);if(ht.is0())return!1;let Ge=ht.toAffine();return!(c.create(Ge.x)!==ve||G==="recovered"&&j.recovery!==K(Ge.x,Ge.y,ve))}catch{return!1}}function R(S,m,T={}){let{prehash:D}=Mi(T,v);return m=C(m,D),N.fromBytes(S,"recovered").recoverPublicKey(m).toBytes()}return Object.freeze({keygen:d,getPublicKey:E,getSharedSecret:b,utils:g,lengths:w,Point:t,sign:x,verify:_,recoverPublicKey:R,Signature:N,hash:n})}var zi={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Yh={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Wu=BigInt(2);function jh(t){let e=zi.p,r=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=t*t*t%e,u=l*l*t%e,f=se(u,r,e)*u%e,h=se(f,r,e)*u%e,d=se(h,Wu,e)*l%e,E=se(d,o,e)*d%e,b=se(E,s,e)*E%e,g=se(b,a,e)*b%e,w=se(g,c,e)*g%e,v=se(w,a,e)*b%e,y=se(v,r,e)*u%e,A=se(y,i,e)*E%e,I=se(A,n,e)*l%e,F=se(I,Wu,e);if(!qi.eql(qi.sqr(F),t))throw new Error("Cannot find square root");return F}var qi=wr(zi.p,{sqrt:jh}),Gh=zu(zi,{Fp:qi,endo:Yh}),_r=$u(Gh,pr);function Yu(t,e,r,n){let o=fr.digest(r instanceof Uint8Array?r:r.subarray());if(no(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),_r.verify(e,s,t,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new Qr(String(s))});try{return n?.signal?.throwIfAborted(),_r.verify(e,o.digest,t,{prehash:!1,format:"der"})}catch(s){throw new Qr(String(s))}}var lo=class{type="secp256k1";raw;_key;constructor(e){this._key=Gu(e),this.raw=ju(this._key)}toMultihash(){return He.digest(Je(this))}toCID(){return pe.createV1(114,this.toMultihash())}toString(){return ie.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:he(this.raw,e.raw)}verify(e,r,n){return Yu(this._key,r,e,n)}};function Hi(t){return new lo(t)}function ju(t){return _r.Point.fromBytes(t).toBytes()}function Gu(t){try{return _r.Point.fromBytes(t),t}catch(e){throw new or(String(e))}}function Zu(t,e){let{Type:r,Data:n}=rt.decode(t),o=n??new Uint8Array;switch(r){case ce.RSA:return Oi(o,e);case ce.Ed25519:return ci(o);case ce.secp256k1:return Hi(o);case ce.ECDSA:return Ns(o);default:throw new sr}}function Xu(t){let{Type:e,Data:r}=rt.decode(t.digest),n=r??new Uint8Array;switch(e){case ce.Ed25519:return ci(n);case ce.secp256k1:return Hi(n);case ce.ECDSA:return Ns(n);default:throw new sr}}function Je(t){return rt.encode({Type:ce[t.type],Data:t.raw})}var Qu=Symbol.for("nodejs.util.inspect.custom"),Zh=114,sn=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[is]=!0;toString(){return this.string==null&&(this.string=ie.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return pe.createV1(Zh,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return he(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return he(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Qu](){return`PeerId(${this.toString()})`}},fo=class extends sn{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},ho=class extends sn{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},po=class extends sn{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},Xh=2336,an=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=He.digest(q(this.url))}[Qu](){return`PeerId(${this.url})`}[is]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return pe.createV1(Xh,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=$(e)),e.toString()===this.toString())}};var Qh=114,Ju=2336;function Vi(t,e){let r;if(t.charAt(0)==="1"||t.charAt(0)==="Q")r=Xe(ie.decode(`z${t}`));else{if(t.startsWith("k51qzi5uqu5")||t.startsWith("kzwfwjn5ji4")||t.startsWith("k2k4r8")||t.startsWith("bafz"))return Jh(pe.parse(t));if(e==null)throw new fe('Please pass a multibase decoder for strings that do not start with "1" or "Q"');r=Xe(e.decode(t))}return Ar(r)}function Ar(t){if(tp(t))return new fo({multihash:t});if(ep(t))try{let e=Xu(t);if(e.type==="Ed25519")return new ho({multihash:t,publicKey:e});if(e.type==="secp256k1")return new po({multihash:t,publicKey:e})}catch{let r=$(t.digest);return new an(new URL(r))}throw new Sn("Supplied PeerID Multihash is invalid")}function Jh(t){if(t?.multihash==null||t.version==null||t.version===1&&t.code!==Qh&&t.code!==Ju)throw new En("Supplied PeerID CID is invalid");if(t.code===Ju){let e=$(t.multihash.digest);return new an(new URL(e))}return Ar(t.multihash)}function ep(t){return t.code===He.code}function tp(t){return t.code===fr.code}var cn;(function(t){let e;t.codec=()=>(e==null&&(e=Pe((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.publicKey!=null&&s.publicKey.byteLength>0&&(i.uint32(10),i.bytes(s.publicKey)),s.payloadType!=null&&s.payloadType.byteLength>0&&(i.uint32(18),i.bytes(s.payloadType)),s.payload!=null&&s.payload.byteLength>0&&(i.uint32(26),i.bytes(s.payload)),s.signature!=null&&s.signature.byteLength>0&&(i.uint32(42),i.bytes(s.signature)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={publicKey:ne(0),payloadType:ne(0),payload:ne(0),signature:ne(0)},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.publicKey=s.bytes();break}case 2:{c.payloadType=s.bytes();break}case 3:{c.payload=s.bytes();break}case 5:{c.signature=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.publicKey`,value:s.bytes()};break}case 2:{yield{field:`${a}.payloadType`,value:s.bytes()};break}case 3:{yield{field:`${a}.payload`,value:s.bytes()};break}case 5:{yield{field:`${a}.signature`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function r(s){return Re(s,t.codec())}t.encode=r;function n(s,i){return Le(s,t.codec(),i)}t.decode=n;function o(s,i){return Oe(s,t.codec(),i)}t.stream=o})(cn||(cn={}));var mo=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var un=class t{static createFromProtobuf=e=>{let r=cn.decode(e),n=Zu(r.publicKey);return new t({publicKey:n,payloadType:r.payloadType,payload:r.payload,signature:r.signature})};static seal=async(e,r,n)=>{if(r==null)throw new Error("Missing private key");let o=e.domain,s=e.codec,i=e.marshal(),a=el(o,s,i),c=await r.sign(a.subarray(),n);return new t({publicKey:r.publicKey,payloadType:s,payload:i,signature:c})};static openAndCertify=async(e,r,n)=>{let o=t.createFromProtobuf(e);if(!await o.validate(r,n))throw new mo("Envelope signature is not valid for the given domain");return o};publicKey;payloadType;payload;signature;marshaled;constructor(e){let{publicKey:r,payloadType:n,payload:o,signature:s}=e;this.publicKey=r,this.payloadType=n,this.payload=o,this.signature=s}marshal(){return this.marshaled==null&&(this.marshaled=cn.encode({publicKey:Je(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return e==null?!1:he(this.marshal(),e.marshal())}async validate(e,r){let n=el(e,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,r)}},el=(t,e,r)=>{let n=q(t),o=Sr(n.byteLength),s=Sr(e.length),i=Sr(r.length);return new oe(o,n,s,e,i,r)};var ge=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},lt=class extends Error{static name="ValidationError";name="ValidationError"},yo=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},go=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var bo=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let r=this.index,n=e();return n===void 0&&(this.index=r),n}parseWith(e){let r=e();if(this.index===this.input.length)return r}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let r=this.readChar();if(r===e)return r})}readSeparator(e,r,n){return this.readAtomically(()=>{if(!(r>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,r,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,e);if(!Number.isNaN(h))return h});if(u===void 0)break;if(s*=e,s+=u,s>l||(i+=1,r!==void 0&&i>r))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let r=0;r<e.length;r++){let n=this.readSeparator(".",r,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[r]=n}return e})}readIPv6Addr(){let e=r=>{for(let n=0;n<r.length/2;n++){let o=n*2;if(n<r.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return r[o]=i[0],r[o+1]=i[1],r[o+2]=i[2],r[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];r[o]=s>>8,r[o+1]=s&255}return[r.length,!1]};return this.readAtomically(()=>{let r=new Uint8Array(16),[n,o]=e(r);if(n===16)return r;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return r.set(s.subarray(0,a),16-a),r})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var rp=45,np=15,wo=new bo;function tl(t){if(!(t.length>np))return wo.new(t).parseWith(()=>wo.readIPv4Addr())}function rl(t){if(t.includes("%")&&(t=t.split("%")[0]),!(t.length>rp))return wo.new(t).parseWith(()=>wo.readIPv6Addr())}function xo(t){return!!tl(t)}function nl(t){return!!rl(t)}function Wi(t){return e=>$(e,t)}function Yi(t){return e=>q(e,t)}function Tr(t){return new DataView(t.buffer).getUint16(t.byteOffset).toString()}function jt(t){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof t=="string"?parseInt(t):t),new Uint8Array(e)}function ol(t){let e=t.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let r=q(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=jt(n);return Qe([r,o],r.length+o.length)}function sl(t){let e=t.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let r=yt.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=jt(n);return Qe([r,o],r.length+o.length)}function ji(t){let e=t.subarray(0,t.length-2),r=t.subarray(t.length-2),n=$(e,"base32"),o=Tr(r);return`${n}:${o}`}var Gi=function(t){t=t.toString().trim();let e=new Uint8Array(4);return t.split(/\./g).forEach((r,n)=>{let o=parseInt(r,10);if(isNaN(o)||o<0||o>255)throw new ge("Invalid byte value in IP address");e[n]=o}),e},il=function(t){let e=0;t=t.toString().trim();let r=t.split(":",8),n;for(n=0;n<r.length;n++){let s=xo(r[n]),i;s&&(i=Gi(r[n]),r[n]=$(i.subarray(0,2),"base16")),i!=null&&++n<8&&r.splice(n,0,$(i.subarray(2,4),"base16"))}if(r[0]==="")for(;r.length<8;)r.unshift("0");else if(r[r.length-1]==="")for(;r.length<8;)r.push("0");else if(r.length<8){for(n=0;n<r.length&&r[n]!=="";n++);let s=[n,1];for(n=9-r.length;n>0;n--)s.push("0");r.splice.apply(r,s)}let o=new Uint8Array(e+16);for(n=0;n<r.length;n++){r[n]===""&&(r[n]="0");let s=parseInt(r[n],16);if(isNaN(s)||s<0||s>65535)throw new ge("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},al=function(t){if(t.byteLength!==4)throw new ge("IPv4 address was incorrect length");let e=[];for(let r=0;r<t.byteLength;r++)e.push(t[r]);return e.join(".")},cl=function(t){if(t.byteLength!==16)throw new ge("IPv6 address was incorrect length");let e=[];for(let n=0;n<t.byteLength;n+=2){let o=t[n],s=t[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;e.push(i)}let r=e.join(":");try{let n=new URL(`http://[${r}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new ge(`Invalid IPv6 address "${r}"`)}};function ul(t){try{let e=new URL(`http://[${t}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new ge(`Invalid IPv6 address "${t}"`)}}var $i=Object.values(qr).map(t=>t.decoder),op=(function(){let t=$i[0].or($i[1]);return $i.slice(2).forEach(e=>t=t.or(e)),t})();function ll(t){return op.decode(t)}function fl(t){return e=>t.encoder.encode(e)}function sp(t){if(parseInt(t).toString()!==t)throw new lt("Value must be an integer")}function ip(t){if(t<0)throw new lt("Value must be a positive integer, or zero")}function ap(t){return e=>{if(e>t)throw new lt(`Value must be smaller than or equal to ${t}`)}}function cp(...t){return e=>{for(let r of t)r(e)}}var ln=cp(sp,ip,ap(65535));var ye=-1,Zi=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let r;if(typeof e=="string"?r=this.protocolsByName.get(e):r=this.protocolsByCode.get(e),r==null)throw new go(`Protocol ${e} was unknown`);return r}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(r=>{this.protocolsByName.set(r,e)})}removeProtocol(e){let r=this.protocolsByCode.get(e);r!=null&&(this.protocolsByCode.delete(r.code),this.protocolsByName.delete(r.name),r.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},dt=new Zi,Sp=[{code:4,name:"ip4",size:32,valueToBytes:Gi,bytesToValue:al,validate:t=>{if(!xo(t))throw new lt(`Invalid IPv4 address "${t}"`)}},{code:6,name:"tcp",size:16,valueToBytes:jt,bytesToValue:Tr,validate:ln},{code:273,name:"udp",size:16,valueToBytes:jt,bytesToValue:Tr,validate:ln},{code:33,name:"dccp",size:16,valueToBytes:jt,bytesToValue:Tr,validate:ln},{code:41,name:"ip6",size:128,valueToBytes:il,bytesToValue:cl,stringToValue:ul,validate:t=>{if(!nl(t))throw new lt(`Invalid IPv6 address "${t}"`)}},{code:42,name:"ip6zone",size:ye},{code:43,name:"ipcidr",size:8,bytesToValue:Wi("base10"),valueToBytes:Yi("base10")},{code:53,name:"dns",size:ye},{code:54,name:"dns4",size:ye},{code:55,name:"dns6",size:ye},{code:56,name:"dnsaddr",size:ye},{code:132,name:"sctp",size:16,valueToBytes:jt,bytesToValue:Tr,validate:ln},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:ye,stringToValue:t=>decodeURIComponent(t),valueToString:t=>encodeURIComponent(t)},{code:421,name:"p2p",aliases:["ipfs"],size:ye,bytesToValue:Wi("base58btc"),valueToBytes:t=>t.startsWith("Q")||t.startsWith("1")?Yi("base58btc")(t):pe.parse(t).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:ji,valueToBytes:ol},{code:445,name:"onion3",size:296,bytesToValue:ji,valueToBytes:sl},{code:446,name:"garlic64",size:ye},{code:447,name:"garlic32",size:ye},{code:448,name:"tls"},{code:449,name:"sni",size:ye},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:ye,bytesToValue:fl(Ss),valueToBytes:ll},{code:480,name:"http"},{code:481,name:"http-path",size:ye,stringToValue:t=>`/${decodeURIComponent(t)}`,valueToString:t=>encodeURIComponent(t.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:ye}];Sp.forEach(t=>{dt.addProtocol(t)});function dl(t){let e=[],r=0;for(;r<t.length;){let n=Jr(t,r),o=dt.getProtocol(n),s=Be(n),i=vp(o,t,r+s),a=0;i>0&&o.size===ye&&(a=Be(i));let c=s+a+i,l={code:n,name:o.name,bytes:_e(t.subarray(r,r+c))};if(i>0){let u=r+s+a,f=t.subarray(u,u+i);l.value=o.bytesToValue?.(f)??$(f)}e.push(l),r+=c}return e}function hl(t){let e=0,r=[];for(let n of t){if(n.bytes==null){let o=dt.getProtocol(n.code),s=Be(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??q(n.value),a=i.byteLength,o.size===ye&&(c=Be(a)));let l=new Uint8Array(s+c+a),u=0;Er(n.code,l,u),u+=s,i!=null&&(o.size===ye&&(Er(a,l,u),u+=c),l.set(i,u)),n.bytes=l}r.push(n.bytes),e+=n.bytes.byteLength}return Qe(r,e)}function pl(t){if(t.charAt(0)!=="/")throw new ge('String multiaddr must start with "/"');let e=[],r="protocol",n="",o="";for(let s=1;s<t.length;s++){let i=t.charAt(s);i!=="/"&&(r==="protocol"?o+=t.charAt(s):n+=t.charAt(s));let a=s===t.length-1;if(i==="/"||a){let c=dt.getProtocol(o);if(r==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",r="protocol";continue}else if(a)throw new ge(`Component ${o} was missing value`);r="value"}else if(r==="value"){let l={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new ge(`Component ${o} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",o="",r="protocol"}}}if(o!==""&&n!=="")throw new ge("Incomplete multiaddr");return e}function ml(t){return`/${t.flatMap(e=>{if(e.value==null)return e.name;let r=dt.getProtocol(e.code);if(r==null)throw new ge(`Unknown protocol code ${e.code}`);return[e.name,r.valueToString?.(e.value)??e.value]}).join("/")}`}function vp(t,e,r){return t.size==null||t.size===0?0:t.size>0?t.size/8:Jr(e,r)}var _p=Symbol.for("nodejs.util.inspect.custom"),ha=Symbol.for("@multiformats/multiaddr");function Ap(t){if(t==null&&(t="/"),yl(t))return t.getComponents();if(t instanceof Uint8Array)return dl(t);if(typeof t=="string")return t=t.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),t===""&&(t="/"),pl(t);if(Array.isArray(t))return t;throw new ge("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Ao=class t{[ha]=!0;#e;#t;#r;constructor(e="/",r={}){this.#e=Ap(e),r.validate!==!1&&Tp(this)}get bytes(){return this.#r==null&&(this.#r=hl(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=ml(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let r=new t(e);return new t([...this.#e,...r.getComponents()],{validate:!1})}decapsulate(e){let r=e.toString(),n=this.toString(),o=n.lastIndexOf(r);if(o<0)throw new yo(`Address ${this.toString()} does not contain subaddress: ${r}`);return new t(n.slice(0,o),{validate:!1})}decapsulateCode(e){let r;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){r=n;break}return new t(this.#e.slice(0,r),{validate:!1})}equals(e){return he(this.bytes,e.bytes)}[_p](){return`Multiaddr(${this.toString()})`}};function Tp(t){t.getComponents().forEach(e=>{let r=dt.getProtocol(e.code);e.value!=null&&r.validate?.(e.value)})}function yl(t){return!!t?.[ha]}function ke(t){return new Ao(t)}var pa={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},gl={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},bl=new globalThis.TextEncoder;function Ip(t,e){let r=pa[e],n=gl[e];for(let o=0;o<t.length;o++)n^=BigInt(t[o]),n=BigInt.asUintN(e,n*r);return n}function Dp(t,e,r){if(r.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=pa[e],o=gl[e],s=t;for(;s.length>0;){let i=bl.encodeInto(s,r);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(r[a]),o=BigInt.asUintN(e,o*n)}return o}function ma(t,{size:e=32,utf8Buffer:r}={}){if(!pa[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof t=="string"){if(r)return Dp(t,e,r);t=bl.encode(t)}return Ip(t,e)}var fn={hash:t=>Number(ma(t,{size:32})),hashV:(t,e)=>Cp(fn.hash(t,e))};function Cp(t){let e=t.toString(16);return e.length%2===1&&(e=`0${e}`),q(e,"base16")}var ya=64,We=class{fp;h;seed;constructor(e,r,n,o=2){if(o>ya)throw new TypeError("Invalid Fingerprint Size");let s=r.hashV(e,n),i=ne(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=r,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?he(this.fp,e.fp):!1}};function Xt(t,e){return Math.floor(Math.random()*(e-t))+t}var Qt=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof We))throw new TypeError("Invalid Fingerprint");return this.contents.some(r=>e.equals(r))}add(e){if(!(e instanceof We))throw new TypeError("Invalid Fingerprint");for(let r=0;r<this.contents.length;r++)if(this.contents[r]==null)return this.contents[r]=e,!0;return!0}swap(e){if(!(e instanceof We))throw new TypeError("Invalid Fingerprint");let r=Xt(0,this.contents.length-1),n=this.contents[r];return this.contents[r]=e,n}remove(e){if(!(e instanceof We))throw new TypeError("Invalid Fingerprint");let r=this.contents.findIndex(n=>e.equals(n));return r>-1?(this.contents[r]=null,!0):!1}};var Bp=500,dn=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??fn,this.seed=e.seed??Xt(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=q(e));let r=new We(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^r.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new Qt(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new Qt(this.bucketSize)),this.buckets[n].add(r)||this.buckets[o].add(r))return this.count++,!0;let s=[n,o],i=s[Xt(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new Qt(this.bucketSize));for(let a=0;a<Bp;a++){let c=this.buckets[i].swap(r);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new Qt(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=q(e));let r=new We(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(r)??!1;if(o)return o;let s=(n^r.hash())%this.filterSize;return this.buckets[s]?.has(r)??!1}remove(e){typeof e=="string"&&(e=q(e));let r=new We(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(r)??!1;if(o)return this.count--,o;let s=(n^r.hash())%this.filterSize,i=this.buckets[s]?.remove(r)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},Lp={1:.5,2:.84,4:.95,8:.98};function Rp(t=.001){return t>.002?2:t>1e-5?4:8}function wl(t,e=.001){let r=Rp(e),n=Lp[r],o=Math.round(t/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*r)),ya);return{filterSize:o,bucketSize:r,fingerprintSize:s}}var To=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??fn,this.seed=e.seed??Xt(0,Math.pow(2,10)),this.filterSeries=[new dn({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=q(e)),this.has(e))return!0;let r=this.filterSeries.find(n=>n.reliable);if(r==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);r=new dn({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(r)}return r.add(e)}has(e){typeof e=="string"&&(e=q(e));for(let r=0;r<this.filterSeries.length;r++)if(this.filterSeries[r].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=q(e));for(let r=0;r<this.filterSeries.length;r++)if(this.filterSeries[r].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,r)=>e+r.count,0)}};function Br(t,e=.001,r){return new To({...wl(t,e),...r??{}})}var ee=t=>({match:e=>{let r=e[0];return r==null||r.code!==t||r.value!=null?!1:e.slice(1)}}),O=(t,e)=>({match:r=>{let n=r[0];return n?.code!==t||n.value==null||e!=null&&n.value!==e?!1:r.slice(1)}}),xl=t=>({match:e=>t.match(e)===!1?e:!1}),H=t=>({match:e=>{let r=t.match(e);return r===!1?e:r}}),Se=(...t)=>({match:e=>{let r;for(let n of t){let o=n.match(e);o!==!1&&(r==null||o.length<r.length)&&(r=o)}return r??!1}}),W=(...t)=>({match:e=>{for(let r of t){let n=r.match(e);if(n===!1)return!1;e=n}return e}});function te(...t){function e(o){if(o==null)return!1;let s=o.getComponents();for(let i of t){let a=i.match(s);if(a===!1)return!1;s=a}return s}function r(o){return e(o)!==!1}function n(o){let s=e(o);return s===!1?!1:s.length===0}return{matchers:t,matches:r,exactMatch:n}}var Op=O(421),BE=te(Op),Do=O(54),Co=O(55),Bo=O(56),ba=O(53),LE=te(Do,H(O(421))),RE=te(Co,H(O(421))),OE=te(Bo,H(O(421))),PE=te(Se(ba,Bo,Do,Co),H(O(421))),El=W(O(4),H(O(43))),Sl=W(H(O(42)),O(41),H(O(43))),wa=Se(El,Sl),Lr=Se(wa,ba,Do,Co,Bo),NE=te(Se(wa,W(Se(ba,Bo,Do,Co),H(O(421))))),kE=te(El),UE=te(Sl),ME=te(wa),xa=W(Lr,O(6)),hn=W(Lr,O(273)),FE=te(W(xa,H(O(421)))),KE=te(hn),Ea=W(hn,ee(460),H(O(421))),Lo=W(hn,ee(461),H(O(421))),Pp=Se(Ea,Lo),qE=te(Ea),zE=te(Lo),ga=Se(Lr,xa,hn,Ea,Lo),vl=Se(W(ga,ee(477),H(O(421)))),HE=te(vl),_l=Se(W(ga,ee(478),H(O(421))),W(ga,ee(448),H(O(449)),ee(477),H(O(421)))),VE=te(_l),Al=W(hn,ee(280),H(O(466)),H(O(466)),H(O(421))),$E=te(Al),Tl=W(Lo,ee(465),H(O(466)),H(O(466)),H(O(421))),WE=te(Tl),Io=Se(vl,_l,W(xa,H(O(421))),W(Pp,H(O(421))),W(Lr,H(O(421))),Al,Tl,O(421)),Il=te(Io),Np=W(H(Io),ee(290),xl(ee(281)),H(O(421))),Jt=te(Np),kp=Se(W(Io,ee(290),ee(281),H(O(421))),W(Io,ee(281),H(O(421))),W(ee(281),H(O(421)))),YE=te(kp),Up=W(Lr,Se(W(O(6,"80")),W(O(6),ee(480)),ee(480)),H(O(481)),H(O(421))),jE=te(Up),Mp=W(Lr,Se(W(O(6,"443")),W(O(6,"443"),ee(480)),W(O(6),ee(443)),W(O(6),ee(448),ee(480)),W(ee(448),ee(480)),ee(448),ee(443)),H(O(481)),H(O(421))),GE=te(Mp),Fp=Se(W(O(777),H(O(421)))),ZE=te(Fp),Kp=Se(W(O(400),H(O(421)))),XE=te(Kp);function Ye(){let t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}var Ro=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},Rr=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Ro(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let r=this.head;this.head=r.next=new Ro(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let r=this.tail.next;this.tail.next=null,this.tail=r,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var Sa=class extends Error{type;code;constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function Dt(t={}){return qp(r=>{let n=r.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},t)}function qp(t,e){e=e??{};let r=e.onEnd,n=new Rr,o,s,i,a=Ye(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((g,w)=>{s=v=>{s=null,n.push(v);try{g(t(n))}catch(y){w(y)}return o}}):t(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Ye()})}},l=g=>s!=null?s(g):(n.push(g),o),u=g=>(n=new Rr,s!=null?s({error:g}):(n.push({error:g}),o)),f=g=>{if(i)return o;if(e?.objectMode!==!0&&g?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:g})},h=g=>i?o:(i=!0,g!=null?u(g):l({done:!0})),d=()=>(n=new Rr,h(),{done:!0}),E=g=>(h(g),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:d,throw:E,push:f,end:h,get readableLength(){return n.size},onEmpty:async g=>{let w=g?.signal;if(w?.throwIfAborted(),n.isEmpty())return;let v,y;w!=null&&(v=new Promise((A,I)=>{y=()=>{I(new Sa)},w.addEventListener("abort",y)}));try{await Promise.race([a.promise,v])}finally{y!=null&&w!=null&&w?.removeEventListener("abort",y)}}},r==null)return o;let b=o;return o={[Symbol.asyncIterator](){return this},next(){return b.next()},throw(g){return b.throw(g),r!=null&&(r(g),r=void 0),{done:!0}},return(){return b.return(),r!=null&&(r(),r=void 0),{done:!0}},push:f,end(g){return b.end(g),r!=null&&(r(g),r=void 0),o},get readableLength(){return b.readableLength},onEmpty:g=>b.onEmpty(g)},o}var va=class t extends Error{name="TimeoutError";constructor(e,r){super(e,r),Error.captureStackTrace?.(this,t)}},Dl=t=>t.reason??new DOMException("This operation was aborted.","AbortError");function _a(t,e){let{milliseconds:r,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e,a,c,u=new Promise((f,h)=>{if(typeof r!="number"||Math.sign(r)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(i?.aborted){h(Dl(i));return}if(i&&(c=()=>{h(Dl(i))},i.addEventListener("abort",c,{once:!0})),t.then(f,h),r===Number.POSITIVE_INFINITY)return;let d=new va;a=s.setTimeout.call(void 0,()=>{if(n){try{f(n())}catch(E){h(E)}return}typeof t.cancel=="function"&&t.cancel(),o===!1?f():o instanceof Error?h(o):(d.message=o??`Promise timed out after ${r} milliseconds`,h(d))},r)}).finally(()=>{u.clear(),c&&i&&i.removeEventListener("abort",c)});return u.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},u}var zp=t=>{let e=t.addEventListener||t.on||t.addListener,r=t.removeEventListener||t.off||t.removeListener;if(!e||!r)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(t),removeListener:r.bind(t)}};function Hp(t,e,r){let n,o=new Promise((s,i)=>{if(r={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...r},!(r.count>=0&&(r.count===Number.POSITIVE_INFINITY||Number.isInteger(r.count))))throw new TypeError("The `count` option should be at least 0 or more");r.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:l,removeListener:u}=zp(t),f=async(...d)=>{let E=r.multiArgs?d:d[0];if(r.filter)try{if(!await r.filter(E))return}catch(b){n(),i(b);return}c.push(E),r.count===c.length&&(n(),s(c))},h=(...d)=>{n(),i(r.rejectionMultiArgs?d:d[0])};n=()=>{for(let d of a)u(d,f);for(let d of r.rejectionEvents)a.includes(d)||u(d,h)};for(let d of a)l(d,f);for(let d of r.rejectionEvents)a.includes(d)||l(d,h);r.signal&&r.signal.addEventListener("abort",()=>{h(r.signal.reason)},{once:!0}),r.resolveImmediately&&s(c)});if(o.cancel=n,typeof r.timeout=="number"){let s=_a(o,{milliseconds:r.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function nt(t,e,r){typeof r=="function"&&(r={filter:r}),r={...r,count:1,resolveImmediately:!1};let n=Hp(t,e,r),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function Aa(t,e){let r,n=function(){let o=function(){r=void 0,t()};clearTimeout(r),r=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(r)},n}var Oo=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}},er=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"};var Po=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function Vp(t){return t.reason}function Ct(t,e,r){if(e==null||t==null)return t;let n=r?.translateError??Vp;if(e.aborted)return t.catch(()=>{}),Promise.reject(n(e));let o;return Promise.race([t,new Promise((s,i)=>{o=()=>{i(n(e))},e.addEventListener("abort",o)})]).finally(()=>{o!=null&&e.removeEventListener("abort",o)})}var No=class{deferred;signal;onProgress;constructor(e){this.signal=e?.signal,this.onProgress=e?.onProgress,this.deferred=Ye(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new ot)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function $p(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var ko=class{id;fn;options;recipients;status;timeline;controller;dispatchingProgress;constructor(e,r){this.id=$p(),this.status="queued",this.fn=e,this.options=r,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.dispatchingProgress=!1,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((r,n)=>r&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new ot),this.cleanup())}async join(e){let r=new No(e);return this.recipients.push(r),e?.signal?.addEventListener("abort",this.onAbort),r.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await Ct(this.fn({...this.options??{},signal:this.controller.signal,onProgress:r=>{if(!this.dispatchingProgress){this.dispatchingProgress=!0;try{this.recipients.forEach(n=>{n.onProgress?.(r)})}finally{this.dispatchingProgress=!1}}}}),this.controller.signal);this.recipients.forEach(r=>{r.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(r=>{r.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var Uo=class extends Te{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=Aa(this.emitEmpty.bind(this),1),this.emitIdle=Aa(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let r of this.queue)if(r.status==="queued"){e=r;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let r=0;r<this.queue.length;r++)if(this.queue[r]===e){this.queue.splice(r,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,r){if(r?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Oo;let n=new ko(e,r);this.enqueue(n),this.safeDispatchEvent("add");let o=n.join(r).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s});return this.tryToStartAnother(),o}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new ot)}),this.clear()}async onEmpty(e){this.size!==0&&await nt(this,"empty",e)}async onSizeLessThan(e,r){this.size<e||await nt(this,"next",{...r,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await nt(this,"idle",e)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let r=Dt({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),r.end(c)},o=c=>{c.detail!=null&&r.push(c.detail)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new ot("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*r}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var Wp=Math.pow(2,20)*4,Mo=class extends Te{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;#e=!1;onDrainPromise;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??Wp,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new oe,this.writeBuffer=new oe,this.readStatus="readable",this.remoteReadStatus="readable",this.writeStatus="writable",this.remoteWriteStatus="writable",this.sendingData=!1,this.writableNeedsDrain=!1,this.timeline={open:Date.now()},this.processSendQueue=this.processSendQueue.bind(this);let r=()=>{this.writableNeedsDrain&&(this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,queueMicrotask(()=>{try{this.processSendQueue()}catch(o){this.log.error("processSendQueue threw - %e",o)}})),this.onDrainPromise?.resolve()};this.addEventListener("drain",r);let n=o=>{this.onDrainPromise?.reject(o.error??new Po)};this.addEventListener("close",n)}get readBufferLength(){return this.readBuffer.byteLength}get readableEnded(){return this.#e}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),Ct(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let e=Dt(),r=s=>{e.push(s.data)};this.addEventListener("message",r);let n=s=>{e.end(s.error)};this.addEventListener("close",n);let o=()=>{e.end()};this.addEventListener("remoteCloseWrite",o);try{yield*e}finally{this.removeEventListener("message",r),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",o)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new pt(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",e.byteLength),this.writeBuffer.append(e),this.processSendQueue()}abort(e){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",e),this.status="aborted",this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle")),this.writeStatus="closed",this.remoteWriteStatus="closed",this.readStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.maybeDispatchEnd();try{this.sendReset(e)}catch(r){this.log.error("failed to send reset to remote - %e",r)}this.dispatchEvent(new Tn(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new pt("Cannot pause a stream that is closing/closed");this.readStatus!=="paused"&&(this.readStatus="paused",this.sendPause())}resume(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new pt("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new pt(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.append(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}unshift(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new pt(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.prepend(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(e){if(e.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(e),this.dispatchReadBuffer()}}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="message"&&this.readBuffer.byteLength>0&&queueMicrotask(()=>{this.dispatchReadBuffer()})}onRemoteReset(){this.log("remote reset"),this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.readBuffer.byteLength===0&&(this.readStatus="closed",this.maybeDispatchEnd()),this.dispatchEvent(new In(new xn))}onTransportClosed(e){this.log("transport closed"),this.readStatus==="readable"&&this.readBuffer.byteLength===0&&(this.log("close readable end after transport closed and read buffer is empty"),this.readStatus="closed"),this.remoteReadStatus!=="closed"&&(this.remoteReadStatus="closed"),this.remoteWriteStatus!=="closed"&&(this.remoteWriteStatus="closed"),this.writeStatus!=="closed"&&(this.writeStatus="closed"),e!=null?this.abort(e):(this.status==="open"||this.status==="closing")&&(this.timeline.close=Date.now(),this.status="closed",this.maybeDispatchEnd(),this.dispatchEvent(new ir))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.maybeDispatchEnd(),this.writeStatus==="closed"&&this.onTransportClosed())}onRemoteCloseRead(){this.log.trace("on remote close read"),this.remoteReadStatus="closed",this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle"))}processSendQueue(){if(this.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(this.writeBuffer.byteLength===0)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;if(this.writeStatus!=="writable"&&this.writeStatus!=="closing")return this.log.trace("not processing send queue as stream is %s",this.writeStatus),!1;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let e=!0,r=this.writeBuffer.byteLength,n=0;for(;this.writeBuffer.byteLength>0;){let o=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(o===0){e=!1;break}let s=this.writeBuffer.sublist(0,o),i=new oe(s);this.writeBuffer.consume(s.byteLength);let a;try{a=this.sendData(s)}catch(c){throw this.writeBuffer.prepend(i),this.abort(c),c}if(e=a.canSendMore,n+=a.sentBytes,a.sentBytes!==i.byteLength&&(i.consume(a.sentBytes),this.writeBuffer.prepend(i)),!e)break}return e||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",n,r,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),e}finally{this.sendingData=!1}}maybeDispatchEnd(){this.#e||this.readBuffer.byteLength>0||this.remoteWriteStatus!=="closed"&&this.readStatus!=="closed"||(this.#e=!0,this.safeDispatchEvent("end"))}dispatchReadBuffer(){try{if(this.listenerCount("message")===0){this.log.trace("not dispatching pause buffer as there are no listeners for the message event");return}if(this.readBuffer.byteLength===0){this.log.trace("not dispatching pause buffer as there is no data to dispatch");return}if(this.readStatus==="paused"){this.log.trace("not dispatching pause buffer we are paused");return}if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("dropping %d bytes because the readable end is %s",this.readBuffer.byteLength,this.readStatus),this.readBuffer.consume(this.readBuffer.byteLength);return}let e=this.readBuffer.sublist();this.readBuffer.consume(e.byteLength),this.dispatchEvent(new An(e))}finally{this.readBuffer.byteLength===0&&this.remoteWriteStatus==="closed"&&(this.log("close readable end after dispatching read buffer and remote writable end is closed"),this.readStatus="closed",this.maybeDispatchEnd()),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new kr(`Read buffer length of ${this.readBuffer.byteLength} exceeded limit of ${this.maxReadBufferLength}, read status is ${this.readStatus}`))}checkWriteBufferLength(){this.maxWriteBufferLength!=null&&this.writeBuffer.byteLength>this.maxWriteBufferLength&&this.abort(new kr(`Write buffer length of ${this.writeBuffer.byteLength} exceeded limit of ${this.maxWriteBufferLength}, write status is ${this.writeStatus}`))}onMuxerNeedsDrain(){this.writableNeedsDrain=!0}onMuxerDrain(){this.safeDispatchEvent("drain")}};var Fo=class extends Mo{remoteAddr;metricPrefix;metrics;constructor(e){super(e),this.metricPrefix=e.metricPrefix??"",this.metrics=e.metrics,this.remoteAddr=e.remoteAddr,this.addEventListener("close",r=>{this.metrics?.increment({[`${this.metricPrefix}end`]:!0}),r.error!=null?r.local?this.metrics?.increment({[`${this.metricPrefix}abort`]:!0}):this.metrics?.increment({[`${this.metricPrefix}reset`]:!0}):r.local?this.metrics?.increment({[`${this.metricPrefix}_local_close`]:!0}):this.metrics?.increment({[`${this.metricPrefix}_remote_close`]:!0})})}async close(e){this.status==="open"&&(this.status="closing",this.writeStatus="closing",this.remoteWriteStatus="closing",this.remoteReadStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await nt(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await nt(this,"drain",{...e,rejectionEvents:["close"]})),await this.sendClose(e),this.onTransportClosed())}};function Ko(t){let e=new globalThis.AbortController;function r(){let s=t.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();e.abort(s);for(let i of t)i?.removeEventListener!=null&&i.removeEventListener("abort",r)}for(let s of t){if(s?.aborted===!0){r();break}s?.addEventListener!=null&&s.addEventListener("abort",r)}function n(){for(let s of t)s?.removeEventListener!=null&&s.removeEventListener("abort",r)}let o=e.signal;return o.clear=n,o}var Ta=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=Ye(),this.haveNext=Ye()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=Ye(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,r){await this._push(e,r)}async end(e,r){e!=null?await this.throw(e):await this._push(void 0,r)}async _push(e,r){if(e!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=Ye(),await Ct(this.readNext.promise,r?.signal,r)}};function Cl(){return new Ta}function Bl(t){return t[Symbol.asyncIterator]!=null}async function Yp(t,e,r){try{await Promise.all(t.map(async n=>{for(;;){let{value:o,done:s}=await n.next();if(s===!0)break;await e.push(o,{signal:r}),r.throwIfAborted()}})),await e.end(void 0,{signal:r})}catch(n){await e.end(n,{signal:r}).catch(()=>{})}}async function*jp(t){let e=new AbortController,r=Cl(),n=t.map(o=>Bl(o)?o[Symbol.asyncIterator]():o[Symbol.iterator]());Yp(n,r,e.signal).catch(()=>{});try{yield*r}finally{e.abort();for(let o of n)try{Promise.resolve(o.return?.()).catch(()=>{})}catch{}}}function*Gp(t){for(let e of t)yield*e}function Zp(...t){let e=[];for(let r of t)Bl(r)||e.push(r);return e.length===t.length?Gp(e):jp(t)}var Ll=Zp;function Rl(t,...e){if(t==null)throw new Error("Empty pipeline");if(Ia(t)){let n=t;t=()=>n.source}else if(Pl(t)||Ol(t)){let n=t;t=()=>n}let r=[t,...e];if(r.length>1&&Ia(r[r.length-1])&&(r[r.length-1]=r[r.length-1].sink),r.length>2)for(let n=1;n<r.length-1;n++)Ia(r[n])&&(r[n]=Qp(r[n]));return Xp(...r)}var Xp=(...t)=>{let e;for(;t.length>0;)e=t.shift()(e);return e},Ol=t=>t?.[Symbol.asyncIterator]!=null,Pl=t=>t?.[Symbol.iterator]!=null,Ia=t=>t==null?!1:t.sink!=null&&t.source!=null,Qp=t=>e=>{let r=t.sink(e);if(r?.then!=null){let n=Dt({objectMode:!0});r.then(()=>{n.end()},i=>{n.end(i)});let o,s=t.source;if(Ol(s))o=async function*(){yield*s,n.end()};else if(Pl(s))o=function*(){yield*s,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Ll(n,o())}return t.source};var Jp=4194304,qo=class extends Error{static name="UnwrappedError";name="UnwrappedError"},Ca=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Ba=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},La=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function em(t){return typeof t?.closeRead=="function"}function tm(t){return typeof t?.close=="function"}function Da(t){return em(t)?t.remoteWriteStatus!=="writable"&&t.readBufferLength===0:tm(t)?t.status!=="open":!1}function rm(t){return t?.addEventListener!=null&&t?.removeEventListener!=null&&t?.send!=null&&t?.push!=null&&t?.log!=null}function nm(t,e){let r=e?.maxBufferSize??Jp,n=new oe,o,s=!1;if(!rm(t))throw new fe("Argument should be a Stream or a Multiaddr");let i=u=>{if(n.append(u.data),n.byteLength>r){let f=n.byteLength;n.consume(n.byteLength),o?.reject(new Error(`Read buffer overflow - ${f} > ${r}`))}o?.resolve()};t.addEventListener("message",i);let a=u=>{u.error!=null?o?.reject(u.error):o?.resolve()};t.addEventListener("close",a);let c=()=>{o?.resolve()};t.addEventListener("remoteCloseWrite",c);let l={readBuffer:n,async read(u){if(s===!0)throw new qo("Stream was unwrapped");if(Da(t)){if(n.byteLength===0&&u?.bytes==null)return null;if(u?.bytes!=null&&n.byteLength<u.bytes)throw t.log.error("closed after reading %d/%d bytes",n.byteLength,u.bytes),new er(`Unexpected EOF - stream closed after reading ${n.byteLength}/${u.bytes} bytes`)}let f=u?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=f){o.resolve();break}if(await Ct(o.promise,u?.signal),Da(t)){if(n.byteLength===0&&u?.bytes==null)return null;break}o=Promise.withResolvers()}let h=u?.bytes??n.byteLength;if(n.byteLength<h){if(Da(t))throw t.log.error("closed while reading %d/%d bytes",n.byteLength,h),new er(`Unexpected EOF - stream closed while reading ${n.byteLength}/${h} bytes`);return l.read(u)}let d=n.sublist(0,h);return n.consume(h),d},async write(u,f){if(s===!0)throw new qo("Stream was unwrapped");t.send(u)||await nt(t,"drain",{signal:f?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,t.removeEventListener("message",i),t.removeEventListener("close",a),t.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(t.log("stream unwrapped with %d unread bytes",n.byteLength),t.unshift(n))),t}};return l}function om(t,e={}){let r=nm(t,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=Be(e.maxDataLength));let n=e?.lengthDecoder??Jr,o=e?.lengthEncoder??Sr;return{async read(i){let a=-1,c=new oe;for(;;){let u=await r.read({...i,bytes:1});if(u==null)break;c.append(u);try{a=n(c)}catch(f){if(f instanceof RangeError)continue;throw f}if(a<0)throw new Ca("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new La(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new Ba(`Message length too long - ${a} > ${e.maxDataLength}`);let l=await r.read({...i,bytes:a});if(l==null)throw t.log.error("tried to read %d bytes but the stream closed",a),new er(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(l.byteLength!==a)throw t.log.error("read %d/%d bytes before the stream closed",l.byteLength,a),new er(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(i,a){await r.write(new oe(o(i.byteLength),i),a)},async writeV(i,a){let c=new oe(...i.flatMap(l=>[o(l.byteLength),l]));await r.write(c,a)},unwrap(){return r.unwrap()}}}function Bt(t,e){let r=om(t,e),n={read:async(o,s)=>{let i=await r.read(s);return o.decode(i,s)},write:async(o,s,i)=>{await r.write(s.encode(o),i)},writeV:async(o,s,i)=>{await r.writeV(o.map(a=>s.encode(a)),i)},pb:o=>({read:async s=>n.read(o,s),write:async(s,i)=>n.write(s,o,i),writeV:async(s,i)=>n.writeV(s,o,i),unwrap:()=>n}),unwrap:()=>r.unwrap()};return n}function sm(t){return t?.addEventListener!=null}function im(t){let e=Dt(),r,n=i=>{e.push(i.data)},o=()=>{e.end(),t.removeEventListener("message",n),t.removeEventListener("close",s),t.removeEventListener("remoteCloseWrite",o)},s=i=>{e.end(i.error),i.error!=null&&r?.reject(i.error),t.removeEventListener("message",n),t.removeEventListener("close",s),t.removeEventListener("remoteCloseWrite",o)};return t.addEventListener("message",n),t.addEventListener("close",s,{once:!0}),t.addEventListener("remoteCloseWrite",o,{once:!0}),{source:e,async sink(i){async function*a(){yield*i}let c=a();for(;;){r=Promise.withResolvers();let{done:l,value:u}=await Promise.race([c.next(),r.promise]);if(t.writeStatus==="closing"||t.writeStatus==="closed"||(u!=null&&(t.send(u)||await Promise.race([nt(t,"drain",{rejectionEvents:["close"]})])),l===!0))break}await t.close()}}}function Nl(...t){let e=t.map(r=>sm(r)?im(r):r);return Rl(...e)}var Or=class extends Uo{has(e){return this.find(e)!=null}find(e){return this.queue.find(r=>e.equals(r.options.peerId))}};var Ra=1e3,kl=60*Ra,Ul=15,Ml=120*kl,Fl=1,zo=5e3,Kl=100,Oa="circuit-relay-source",pn=`${Wa}-circuit-relay`,ql=2*kl,zl=BigInt(1<<17),ze="/libp2p/circuit/relay/0.2.0/hop",tr="/libp2p/circuit/relay/0.2.0/stop",Hl=30*Ra,r1=30*Ra,mn=300,Vl=4096,$l=.001;var J;(function(t){let e;(function(a){a.RESERVE="RESERVE",a.CONNECT="CONNECT",a.STATUS="STATUS"})(e=t.Type||(t.Type={}));let r;(function(a){a[a.RESERVE=0]="RESERVE",a[a.CONNECT=1]="CONNECT",a[a.STATUS=2]="STATUS"})(r||(r={})),(function(a){a.codec=()=>$t(r)})(e=t.Type||(t.Type={}));let n;t.codec=()=>(n==null&&(n=Pe((a,c,l={})=>{l.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),t.Type.codec().encode(a.type,c)),a.peer!=null&&(c.uint32(18),Lt.codec().encode(a.peer,c)),a.reservation!=null&&(c.uint32(26),yn.codec().encode(a.reservation,c)),a.limit!=null&&(c.uint32(34),Rt.codec().encode(a.limit,c)),a.status!=null&&(c.uint32(40),z.codec().encode(a.status,c)),l.lengthDelimited!==!1&&c.ldelim()},(a,c,l={})=>{let u={},f=c==null?a.len:a.pos+c;for(;a.pos<f;){let h=a.uint32();switch(h>>>3){case 1:{u.type=t.Type.codec().decode(a);break}case 2:{u.peer=Lt.codec().decode(a,a.uint32(),{limits:l.limits?.peer});break}case 3:{u.reservation=yn.codec().decode(a,a.uint32(),{limits:l.limits?.reservation});break}case 4:{u.limit=Rt.codec().decode(a,a.uint32(),{limits:l.limits?.limit});break}case 5:{u.status=z.codec().decode(a);break}default:{a.skipType(h&7);break}}}return u},function*(a,c,l,u={}){let f=c==null?a.len:a.pos+c;for(;a.pos<f;){let h=a.uint32();switch(h>>>3){case 1:{yield{field:`${l}.type`,value:t.Type.codec().decode(a)};break}case 2:{yield*Lt.codec().stream(a,a.uint32(),`${l}.peer`,{limits:u.limits?.peer});break}case 3:{yield*yn.codec().stream(a,a.uint32(),`${l}.reservation`,{limits:u.limits?.reservation});break}case 4:{yield*Rt.codec().stream(a,a.uint32(),`${l}.limit`,{limits:u.limits?.limit});break}case 5:{yield{field:`${l}.status`,value:z.codec().decode(a)};break}default:{a.skipType(h&7);break}}}})),n);function o(a){return Re(a,t.codec())}t.encode=o;function s(a,c){return Le(a,t.codec(),c)}t.decode=s;function i(a,c){return Oe(a,t.codec(),c)}t.stream=i})(J||(J={}));var Ue;(function(t){let e;(function(a){a.CONNECT="CONNECT",a.STATUS="STATUS"})(e=t.Type||(t.Type={}));let r;(function(a){a[a.CONNECT=0]="CONNECT",a[a.STATUS=1]="STATUS"})(r||(r={})),(function(a){a.codec=()=>$t(r)})(e=t.Type||(t.Type={}));let n;t.codec=()=>(n==null&&(n=Pe((a,c,l={})=>{l.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),t.Type.codec().encode(a.type,c)),a.peer!=null&&(c.uint32(18),Lt.codec().encode(a.peer,c)),a.limit!=null&&(c.uint32(26),Rt.codec().encode(a.limit,c)),a.status!=null&&(c.uint32(32),z.codec().encode(a.status,c)),l.lengthDelimited!==!1&&c.ldelim()},(a,c,l={})=>{let u={},f=c==null?a.len:a.pos+c;for(;a.pos<f;){let h=a.uint32();switch(h>>>3){case 1:{u.type=t.Type.codec().decode(a);break}case 2:{u.peer=Lt.codec().decode(a,a.uint32(),{limits:l.limits?.peer});break}case 3:{u.limit=Rt.codec().decode(a,a.uint32(),{limits:l.limits?.limit});break}case 4:{u.status=z.codec().decode(a);break}default:{a.skipType(h&7);break}}}return u},function*(a,c,l,u={}){let f=c==null?a.len:a.pos+c;for(;a.pos<f;){let h=a.uint32();switch(h>>>3){case 1:{yield{field:`${l}.type`,value:t.Type.codec().decode(a)};break}case 2:{yield*Lt.codec().stream(a,a.uint32(),`${l}.peer`,{limits:u.limits?.peer});break}case 3:{yield*Rt.codec().stream(a,a.uint32(),`${l}.limit`,{limits:u.limits?.limit});break}case 4:{yield{field:`${l}.status`,value:z.codec().decode(a)};break}default:{a.skipType(h&7);break}}}})),n);function o(a){return Re(a,t.codec())}t.encode=o;function s(a,c){return Le(a,t.codec(),c)}t.decode=s;function i(a,c){return Oe(a,t.codec(),c)}t.stream=i})(Ue||(Ue={}));var Lt;(function(t){let e;t.codec=()=>(e==null&&(e=Pe((s,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),s.id!=null&&s.id.byteLength>0&&(i.uint32(10),i.bytes(s.id)),s.addrs!=null&&s.addrs.length>0)for(let c of s.addrs)i.uint32(18),i.bytes(c);a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={id:ne(0),addrs:[]},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.id=s.bytes();break}case 2:{if(a.limits?.addrs!=null&&c.addrs.length===a.limits.addrs)throw new Wt('Decode error - repeated field "addrs" had too many elements');c.addrs.push(s.bytes());break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l={addrs:0},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{yield{field:`${a}.id`,value:s.bytes()};break}case 2:{if(c.limits?.addrs!=null&&l.addrs===c.limits.addrs)throw new Wt('Streaming decode error - repeated field "addrs" had too many elements');yield{field:`${a}.addrs[]`,index:l.addrs,value:s.bytes()},l.addrs++;break}default:{s.skipType(f&7);break}}}})),e);function r(s){return Re(s,t.codec())}t.encode=r;function n(s,i){return Le(s,t.codec(),i)}t.decode=n;function o(s,i){return Oe(s,t.codec(),i)}t.stream=o})(Lt||(Lt={}));var yn;(function(t){let e;t.codec=()=>(e==null&&(e=Pe((s,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),s.expire!=null&&s.expire!==0n&&(i.uint32(8),i.uint64(s.expire)),s.addrs!=null&&s.addrs.length>0)for(let c of s.addrs)i.uint32(18),i.bytes(c);s.voucher!=null&&(i.uint32(26),gn.codec().encode(s.voucher,i)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={expire:0n,addrs:[]},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.expire=s.uint64();break}case 2:{if(a.limits?.addrs!=null&&c.addrs.length===a.limits.addrs)throw new Wt('Decode error - repeated field "addrs" had too many elements');c.addrs.push(s.bytes());break}case 3:{c.voucher=gn.codec().decode(s,s.uint32(),{limits:a.limits?.voucher});break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l={addrs:0},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{yield{field:`${a}.expire`,value:s.uint64()};break}case 2:{if(c.limits?.addrs!=null&&l.addrs===c.limits.addrs)throw new Wt('Streaming decode error - repeated field "addrs" had too many elements');yield{field:`${a}.addrs[]`,index:l.addrs,value:s.bytes()},l.addrs++;break}case 3:{yield*gn.codec().stream(s,s.uint32(),`${a}.voucher`,{limits:c.limits?.voucher});break}default:{s.skipType(f&7);break}}}})),e);function r(s){return Re(s,t.codec())}t.encode=r;function n(s,i){return Le(s,t.codec(),i)}t.decode=n;function o(s,i){return Oe(s,t.codec(),i)}t.stream=o})(yn||(yn={}));var Rt;(function(t){let e;t.codec=()=>(e==null&&(e=Pe((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.duration!=null&&(i.uint32(8),i.uint32(s.duration)),s.data!=null&&(i.uint32(16),i.uint64(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.duration=s.uint32();break}case 2:{c.data=s.uint64();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.duration`,value:s.uint32()};break}case 2:{yield{field:`${a}.data`,value:s.uint64()};break}default:{s.skipType(u&7);break}}}})),e);function r(s){return Re(s,t.codec())}t.encode=r;function n(s,i){return Le(s,t.codec(),i)}t.decode=n;function o(s,i){return Oe(s,t.codec(),i)}t.stream=o})(Rt||(Rt={}));var z;(function(t){t.UNUSED="UNUSED",t.OK="OK",t.RESERVATION_REFUSED="RESERVATION_REFUSED",t.RESOURCE_LIMIT_EXCEEDED="RESOURCE_LIMIT_EXCEEDED",t.PERMISSION_DENIED="PERMISSION_DENIED",t.CONNECTION_FAILED="CONNECTION_FAILED",t.NO_RESERVATION="NO_RESERVATION",t.MALFORMED_MESSAGE="MALFORMED_MESSAGE",t.UNEXPECTED_MESSAGE="UNEXPECTED_MESSAGE"})(z||(z={}));var Pa;(function(t){t[t.UNUSED=0]="UNUSED",t[t.OK=100]="OK",t[t.RESERVATION_REFUSED=200]="RESERVATION_REFUSED",t[t.RESOURCE_LIMIT_EXCEEDED=201]="RESOURCE_LIMIT_EXCEEDED",t[t.PERMISSION_DENIED=202]="PERMISSION_DENIED",t[t.CONNECTION_FAILED=203]="CONNECTION_FAILED",t[t.NO_RESERVATION=204]="NO_RESERVATION",t[t.MALFORMED_MESSAGE=400]="MALFORMED_MESSAGE",t[t.UNEXPECTED_MESSAGE=401]="UNEXPECTED_MESSAGE"})(Pa||(Pa={}));(function(t){t.codec=()=>$t(Pa)})(z||(z={}));var rr;(function(t){let e;t.codec=()=>(e==null&&(e=Pe((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.relay!=null&&s.relay.byteLength>0&&(i.uint32(10),i.bytes(s.relay)),s.peer!=null&&s.peer.byteLength>0&&(i.uint32(18),i.bytes(s.peer)),s.expiration!=null&&s.expiration!==0n&&(i.uint32(24),i.uint64(s.expiration)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={relay:ne(0),peer:ne(0),expiration:0n},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.relay=s.bytes();break}case 2:{c.peer=s.bytes();break}case 3:{c.expiration=s.uint64();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.relay`,value:s.bytes()};break}case 2:{yield{field:`${a}.peer`,value:s.bytes()};break}case 3:{yield{field:`${a}.expiration`,value:s.uint64()};break}default:{s.skipType(u&7);break}}}})),e);function r(s){return Re(s,t.codec())}t.encode=r;function n(s,i){return Le(s,t.codec(),i)}t.decode=n;function o(s,i){return Oe(s,t.codec(),i)}t.stream=o})(rr||(rr={}));var gn;(function(t){let e;t.codec=()=>(e==null&&(e=Pe((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.publicKey!=null&&s.publicKey.byteLength>0&&(i.uint32(10),i.bytes(s.publicKey)),s.payloadType!=null&&s.payloadType.byteLength>0&&(i.uint32(18),i.bytes(s.payloadType)),s.payload!=null&&(i.uint32(26),rr.codec().encode(s.payload,i)),s.signature!=null&&s.signature.byteLength>0&&(i.uint32(42),i.bytes(s.signature)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={publicKey:ne(0),payloadType:ne(0),signature:ne(0)},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.publicKey=s.bytes();break}case 2:{c.payloadType=s.bytes();break}case 3:{c.payload=rr.codec().decode(s,s.uint32(),{limits:a.limits?.payload});break}case 5:{c.signature=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.publicKey`,value:s.bytes()};break}case 2:{yield{field:`${a}.payloadType`,value:s.bytes()};break}case 3:{yield*rr.codec().stream(s,s.uint32(),`${a}.payload`,{limits:c.limits?.payload});break}case 5:{yield{field:`${a}.signature`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function r(s){return Re(s,t.codec())}t.encode=r;function n(s,i){return Le(s,t.codec(),i)}t.decode=n;function o(s,i){return Oe(s,t.codec(),i)}t.stream=o})(gn||(gn={}));var Ho=class extends Error{constructor(e="Transfer limit error"){super(e),this.name="TransferLimitError"}},Vo=class extends Error{constructor(e="Duration limit error"){super(e),this.name="DurationLimitError"}},bn=class extends Error{static name="HadEnoughRelaysError";name="HadEnoughRelaysError"},$o=class extends Error{static name="DoubleRelayError";name="DoubleRelayError"},Wo=class extends Error{static name="RelayQueueFullError";name="RelayQueueFullError"};function Wl(t,e,r){let n=e.remaining,o=s=>{let i=BigInt(s.data.byteLength);e.remaining-=i,e.remaining<0&&t.abort(new Ho(`data limit of ${n} bytes exceeded`))};t.addEventListener("message",o)}function Yl(t,e,r,n,o){function s(u){t.abort(u),e.abort(u)}let i=[r,n.signal];if(n.limit?.duration!=null){o.log("limiting relayed connection duration to %dms",n.limit.duration);let u=AbortSignal.timeout(n.limit.duration);i.push(u)}let a=Ko(i);let c;n.limit?.data!=null&&(c={remaining:n.limit.data});let l=()=>{let u;r.aborted?u=r.reason:u=new Vo(`duration limit of ${n.limit?.duration} ms exceeded`),s(u)};a.addEventListener("abort",l,{once:!0}),c!=null&&(Wl(e,c,o),Wl(t,c,o)),Nl(t,e,t).catch(u=>{s(u)}).finally(()=>{a.clear()})}function Na(t){let e=t*BigInt(1e3),r=new Date().getTime();return Number(e-BigInt(r))}var wn=class{expires;bytes;constructor(e){e?.duration!=null&&e?.duration!==0&&(this.expires=Date.now()+e.duration*1e3),this.bytes=e?.data,this.bytes===0n&&(this.bytes=void 0),this.onData=this.onData.bind(this)}onData(e){this.bytes!=null&&(this.bytes-=BigInt(e.byteLength),this.bytes<0n&&(this.bytes=0n))}getLimits(){if(this.expires==null&&this.bytes==null)return;let e={};if(this.bytes!=null){let r=this;Object.defineProperty(e,"bytes",{get(){return r.bytes}})}if(this.expires!=null){let r=this;Object.defineProperty(e,"seconds",{get(){return Math.round(((r.expires??0)-Date.now())/1e3)}})}return e}},Yo=te(W(Il.matchers[0],ee(290))),jo=te(ee(290));function Go(t,e){let r={[Symbol.iterator]:()=>r,next:()=>{let n=t.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return r}var Ot=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[r,n]of e.entries())this.map.set(r.toString(),{key:r,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return Go(this.map.entries(),e=>[e[1].key,e[1].value])}forEach(e){this.map.forEach((r,n)=>{e(r.value,r.key,this)})}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,r){this.map.set(e.toString(),{key:e,value:r})}keys(){return Go(this.map.values(),e=>e.key)}values(){return Go(this.map.values(),e=>e.value)}get size(){return this.map.size}};var Zo=class{filter;constructor(e,r){this.filter=Br(e,r)}has(e){return this.filter.has(e.toMultihash().bytes)}add(e){this.filter.add(e.toMultihash().bytes)}remove(e){this.filter.remove?.(e.toMultihash().bytes)}};function ka(t,e=.001){return new Zo(t,e)}var Ua=class extends Ot{metric;constructor(e){super();let{name:r,metrics:n}=e;this.metric=n.registerMetric(r),this.updateComponentMetric()}set(e,r){return super.set(e,r),this.updateComponentMetric(),this}delete(e){let r=super.delete(e);return this.updateComponentMetric(),r}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Ma(t){let{name:e,metrics:r}=t,n;return r!=null?n=new Ua({name:e,metrics:r}):n=new Ot,n}var Fa=class extends Error{type;code;constructor(e,r,n){super(e??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=r??"ABORT_ERR"}};function jl(t,e){let r=new Fa(e?.errorMessage,e?.errorCode,e?.errorName),n=new AbortController,o=()=>{n.abort(r)},s=AbortSignal.timeout(t);s.addEventListener("abort",o);let i=n.signal;return i.reset=a=>{s?.removeEventListener("abort",o),s=AbortSignal.timeout(a??t),s.addEventListener("abort",()=>{n.abort(r)})},i.clear=()=>{s?.removeEventListener("abort",o),s=void 0},i}var Xo=class{reservations;maxReservations;applyDefaultLimit;reservationTtl;defaultDurationLimit;defaultDataLimit;log;constructor(e,r={}){this.log=e.logger.forComponent("libp2p:circuit-relay:server:reservation-store"),this.maxReservations=r.maxReservations??Ul,this.applyDefaultLimit=r.applyDefaultLimit!==!1,this.reservationTtl=r.reservationTtl??Ml,this.defaultDurationLimit=r.defaultDurationLimit??ql,this.defaultDataLimit=r.defaultDataLimit??zl,this.reservations=Ma({metrics:e.metrics,name:"libp2p_circuit_relay_server_reservations_total"})}reserve(e,r,n){let o=this.reservations.get(e);if(this.reservations.size>=this.maxReservations&&o==null)return{status:z.RESERVATION_REFUSED};let s=new Date(Date.now()+this.reservationTtl),i;return this.applyDefaultLimit&&(i=n??{data:this.defaultDataLimit,duration:this.defaultDurationLimit}),o!=null?(this.log("refreshing reservation for client %p",e),o.signal.reset(this.reservationTtl)):(this.log("creating new reservation for client %p",e),o={addr:r,expiry:s,limit:i,signal:jl(this.reservationTtl)},o.signal.addEventListener("abort",()=>{this.reservations.delete(e)})),this.reservations.set(e,o),{status:z.OK,expire:Math.round(s.getTime()/1e3)}}removeReservation(e){this.reservations.delete(e)}get(e){return this.reservations.get(e)}clear(){this.reservations.clear()}};var Qo=class t{domain="libp2p-relay-rsvp";codec=new Uint8Array([3,2]);relay;peer;expiration;constructor({relay:e,peer:r,expiration:n}){this.relay=e,this.peer=r,this.expiration=n}marshal(){return rr.encode({relay:this.relay.toMultihash().bytes,peer:this.peer.toMultihash().bytes,expiration:BigInt(this.expiration)})}equals(e){return!(!(e instanceof t)||!this.peer.equals(e.peer)||!this.relay.equals(e.relay)||this.expiration!==e.expiration)}};var am={maxOutboundStopStreams:mn},Jo=class extends Te{components;reservationStore;started;hopTimeout;shutdownController;maxInboundHopStreams;maxOutboundHopStreams;maxOutboundStopStreams;log;constructor(e,r={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:server"),this.components=e,this.started=!1,this.hopTimeout=r?.hopTimeout??Hl,this.maxInboundHopStreams=r.maxInboundHopStreams,this.maxOutboundHopStreams=r.maxOutboundHopStreams,this.maxOutboundStopStreams=r.maxOutboundStopStreams??am.maxOutboundStopStreams,this.reservationStore=new Xo(e,r.reservations),this.shutdownController=new AbortController,this.shutdownController.signal,this.onHop=this.onHop.bind(this)}[Symbol.toStringTag]="@libp2p/circuit-relay-v2-server";isStarted(){return this.started}async start(){this.started||(await this.components.registrar.handle(ze,this.onHop,{maxInboundStreams:this.maxInboundHopStreams,maxOutboundStreams:this.maxOutboundHopStreams,runOnLimitedConnection:!0}),this.started=!0)}async stop(){this.reservationStore.clear(),this.shutdownController.abort(),await this.components.registrar.unhandle(ze),this.started=!1}async onHop(e,r){this.log("received circuit v2 hop protocol stream from %p",r.remotePeer);let n=AbortSignal.timeout(this.hopTimeout);let o={signal:n},s=Bt(e);try{let i=await s.pb(J).read(o);if(i?.type==null)throw new Error("request was invalid, could not read from stream");this.log("received",i.type),await this.handleHopProtocol({connection:r,stream:s,request:i},o)}catch(i){this.log.error("error while handling hop - %e",i),await s.pb(J).write({type:J.Type.STATUS,status:z.MALFORMED_MESSAGE},o),e.abort(i)}}async handleHopProtocol({stream:e,request:r,connection:n},o){switch(this.log("received hop message"),r.type){case J.Type.RESERVE:await this.handleReserve({stream:e,request:r,connection:n},o);break;case J.Type.CONNECT:await this.handleConnect({stream:e,request:r,connection:n},o);break;default:this.log.error("invalid hop request type %s via peer %p",r.type,n.remotePeer),await e.pb(J).write({type:J.Type.STATUS,status:z.UNEXPECTED_MESSAGE})}}async handleReserve({stream:e,connection:r},n){let o=e.pb(J);if(this.log("hop reserve request from %p",r.remotePeer),Jt.exactMatch(r.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",r.remotePeer),await o.write({type:J.Type.STATUS,status:z.PERMISSION_DENIED},n);return}if(await this.components.connectionGater.denyInboundRelayReservation?.(r.remotePeer)===!0){this.log.error("reservation for %p denied by connection gater",r.remotePeer),await o.write({type:J.Type.STATUS,status:z.PERMISSION_DENIED},n);return}let s=this.reservationStore.reserve(r.remotePeer,r.remoteAddr);try{if(s.status!==z.OK){await o.write({type:J.Type.STATUS,status:s.status},n);return}if(s.expire!=null){let i=s.expire*1e3-Date.now();await this.components.peerStore.merge(r.remotePeer,{tags:{[Oa]:{value:1,ttl:i}}},n)}await o.write({type:J.Type.STATUS,status:z.OK,reservation:await this.makeReservation(r.remotePeer,BigInt(s.expire??0)),limit:this.reservationStore.get(r.remotePeer)?.limit},n),this.log("sent confirmation response to %s",r.remotePeer),await o.unwrap().unwrap().close(n)}catch(i){this.log.error("failed to send confirmation response to %p - %e",r.remotePeer,i),this.reservationStore.removeReservation(r.remotePeer);try{await this.components.peerStore.merge(r.remotePeer,{tags:{[Oa]:void 0}},n)}catch(a){this.log.error("failed to untag relay source peer %p - %e",r.remotePeer,a)}}}async makeReservation(e,r){let n=[];for(let s of this.components.addressManager.getAddresses())s.toString().includes("/p2p-circuit")||n.push(s.bytes);let o=await un.seal(new Qo({peer:e,relay:this.components.peerId,expiration:r}),this.components.privateKey);return{addrs:n,expire:r,voucher:{publicKey:Je(o.publicKey),payloadType:o.payloadType,payload:{peer:e.toMultihash().bytes,relay:this.components.peerId.toMultihash().bytes,expiration:r},signature:o.signature}}}async handleConnect({stream:e,request:r,connection:n},o){let s=e.pb(J);if(Jt.matches(n.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",n.remotePeer),await s.write({type:J.Type.STATUS,status:z.PERMISSION_DENIED},o);return}this.log("hop connect request from %p",n.remotePeer);let i;try{if(r.peer==null)throw this.log.error("no peer info in hop connect request"),new Error("no peer info in request");r.peer.addrs.forEach(ke),i=Ar(Xe(r.peer.id))}catch(f){this.log.error("invalid hop connect request via peer %p - %e",n.remotePeer,f),await s.write({type:J.Type.STATUS,status:z.MALFORMED_MESSAGE},o);return}let a=this.reservationStore.get(i);if(a==null){this.log.error("hop connect denied for destination peer %p not having a reservation for %p with status %s",i,n.remotePeer,z.NO_RESERVATION),await s.write({type:J.Type.STATUS,status:z.NO_RESERVATION},o);return}if(await this.components.connectionGater.denyOutboundRelayedConnection?.(n.remotePeer,i)===!0){this.log.error("hop connect for %p to %p denied by connection gater",n.remotePeer,i),await s.write({type:J.Type.STATUS,status:z.PERMISSION_DENIED},o);return}let c=this.components.connectionManager.getConnections(i);if(c.length===0){this.log("hop connect denied for destination peer %p not having a connection for %p as there is no destination connection",i,n.remotePeer),await s.write({type:J.Type.STATUS,status:z.NO_RESERVATION},o);return}let l=c[0],u=await this.stopHop({connection:l,request:{type:Ue.Type.CONNECT,peer:{id:n.remotePeer.toMultihash().bytes,addrs:[]},limit:a?.limit}},o);if(u==null){this.log.error("failed to open stream to destination peer %p",l?.remotePeer),await s.write({type:J.Type.STATUS,status:z.CONNECTION_FAILED},o);return}await s.write({type:J.Type.STATUS,status:z.OK,limit:a?.limit},o),this.log("connection from %p to %p established - merging streams",n.remotePeer,i),Yl(e.unwrap(),u,this.shutdownController.signal,a,{log:this.log})}async stopHop({connection:e,request:r},n){this.log("starting circuit relay v2 stop request to %s",e.remotePeer);let o=await e.newStream(tr,{maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0,...n}),s=Bt(o),i=s.pb(Ue);await i.write(r,n);let a;try{a=await i.read(n)}catch(c){this.log.error("error parsing stop message response from %p - %e",e.remotePeer,c)}if(a==null){this.log.error("could not read response from %p",e.remotePeer),await o.close(n);return}if(a.status===z.OK)return this.log("stop request to %p was successful",e.remotePeer),s.unwrap();this.log("stop request failed with code %d",a.status),await o.close(n)}get reservations(){return this.reservationStore.reservations}};var Pt=class extends Event{type;detail;constructor(e,r){super(e),this.type=e,this.detail=r}};var es=class extends Te{components;started;running;topologyId;log;discoveryController;filter;queue;constructor(e,r={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:discover-relays"),this.components=e,this.started=!1,this.running=!1,this.filter=r.filter,this.discoveryController=new AbortController,this.discoveryController.signal,this.dialPeer=this.dialPeer.bind(this),this.onPeer=this.onPeer.bind(this)}isStarted(){return this.started}async start(){this.topologyId=await this.components.registrar.register(ze,{filter:this.filter,onConnect:e=>{this.log.trace("discovered relay %p queue (length: %d, active %d)",e,this.queue?.size,this.queue?.running),this.safeDispatchEvent("relay:discover",{detail:e})}}),this.started=!0}stop(){this.topologyId!=null&&this.components.registrar.unregister(this.topologyId),this.running&&this.stopDiscovery(),this.started=!1}startDiscovery(){this.running||(this.log("start discovery"),this.running=!0,this.discoveryController=new AbortController,this.discoveryController.signal,this.components.events.addEventListener("peer:discovery",this.onPeer),Promise.resolve().then(async()=>{this.log("searching peer store for relays");let e=await this.components.peerStore.all({filters:[n=>n.protocols.includes(ze)],orders:[()=>Math.random()<.5?1:-1,(n,o)=>{let s=Gl(n),i=Gl(o);return s>i?-1:i>s?1:0}]});for(let n of e)this.log.trace("found relay peer %p in peer store",n.id),this.safeDispatchEvent("relay:discover",{detail:n.id});this.log("found %d relay peers in peer store",e.length);let r=this.queue=new Or({concurrency:5});this.log("start random walk");for await(let n of this.components.randomWalk.walk({signal:this.discoveryController.signal})){if(this.log.trace("found random peer %p",n.id),r.has(n.id)){this.log.trace("random peer %p was already in queue",n.id);continue}if(this.components.connectionManager.getConnections(n.id)?.length>0){this.log.trace("random peer %p was already connected",n.id);continue}if(!await this.components.connectionManager.isDialable(n.multiaddrs)){this.log.trace("random peer %p was not dialable",n.id,n.multiaddrs.map(o=>o.toString()));continue}r.queued>10&&(this.log.trace("wait for space in queue for %p",n.id),await r.onSizeLessThan(10,{signal:this.discoveryController.signal})),this.log("adding random peer %p to dial queue (length: %d, active %d)",n.id,r.size,r.running),r.add(this.dialPeer,{peerId:n.id,signal:this.discoveryController.signal}).catch(o=>{this.log.error("error opening connection to random peer %p - %e",n.id,o)})}this.log("stop random walk"),await r.onIdle()}).catch(e=>{this.discoveryController.signal.aborted||this.log.error("failed when finding relays on the network - %e",e)}))}stopDiscovery(){this.log("stop discovery"),this.running=!1,this.discoveryController?.abort(),this.queue?.clear(),this.components.events.removeEventListener("peer:discovery",this.onPeer)}onPeer(e){this.log.trace("maybe dialing discovered peer %p",e.detail.id),this.maybeDialPeer(e).catch(r=>{this.log.trace("error dialing discovered peer %p - %e",e.detail.id,r)})}async maybeDialPeer(e){if(this.queue==null)return;let r=e.detail.id,n=e.detail.multiaddrs;if(this.queue.has(r)){this.log.trace("random peer %p was already in queue",r);return}if(this.components.connectionManager.getConnections(r)?.length>0){this.log.trace("random peer %p was already connected",r);return}if(!await this.components.connectionManager.isDialable(n)){this.log.trace("random peer %p was not dialable",r);return}this.queue?.add(this.dialPeer,{peerId:e.detail.id,signal:this.discoveryController.signal}).catch(o=>{this.log.error("error opening connection to discovered peer %p - %e",e.detail.id,o)})}async dialPeer({peerId:e,signal:r}){let n=Ko([AbortSignal.timeout(5e3),r]);try{await this.components.connectionManager.openConnection(e,{signal:n})}finally{n.clear()}}};function Gl(t){let e=t.metadata.get("last-dial-success");return e==null?0:new Date($(e)).getTime()}var qa=class extends Te{connectionManager;addressManager;reservationStore;listeningAddrs;log;listenTimeout;reservationId;relay;constructor(e,r={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:transport:listener"),this.connectionManager=e.connectionManager,this.addressManager=e.addressManager,this.reservationStore=e.reservationStore,this.listeningAddrs=[],this.listenTimeout=r.listenTimeout??zo,this.reservationStore.addEventListener("relay:removed",this._onRemoveRelayPeer),this.reservationStore.addEventListener("relay:created-reservation",this._onAddRelayPeer)}_onRemoveRelayPeer=e=>{this.log("relay removed %p our relay %p",e.detail.relay,this.relay,this.relay?.equals(e.detail.relay)),this.relay?.equals(e.detail.relay)===!0&&(this.log("relay peer removed %p",e.detail.relay),this.listeningAddrs.forEach(r=>{this.addressManager.removeObservedAddr(r)}),this.listeningAddrs=[],this.safeDispatchEvent("listening"))};_onAddRelayPeer=e=>{let{details:r}=e.detail;if(r.type==="configured"){this.relay?.equals(e.detail.relay)===!0&&this.addedRelay(e.detail);return}r.id===this.reservationId&&this.addedRelay(e.detail)};async listen(e){if(jo.exactMatch(e))this.log("searching for circuit relay servers"),this.reservationId=this.reservationStore.reserveRelay();else if(Yo.exactMatch(e)){this.log("listen on specific relay server %a",e);let r=AbortSignal.timeout(this.listenTimeout);let n=e.decapsulate("/p2p-circuit"),o=await this.connectionManager.openConnection(n,{signal:r});if(!this.reservationStore.hasReservation(o.remotePeer)){this.log("making reservation on peer %p",o.remotePeer);let s=await this.reservationStore.addRelay(o.remotePeer,"configured");this.addedRelay(s)}}else throw new Nt(`Could not listen on p2p-circuit address "${e}"`)}getAddrs(){return[...this.listeningAddrs.values()].flat()}updateAnnounceAddrs(){}async close(){this.reservationStore.cancelReservations(),this.listeningAddrs=[],this.reservationStore.removeEventListener("relay:removed",this._onRemoveRelayPeer),queueMicrotask(()=>{this.safeDispatchEvent("close")})}addedRelay(e){this.log("relay peer added %p",e.relay),this.relay=e.relay;let r=this.listeningAddrs;this.listeningAddrs=e.details.reservation.addrs.map(n=>ke(n).encapsulate("/p2p-circuit")),this.listeningAddrs.forEach(n=>{this.addressManager.confirmObservedAddr(n,{type:"transport"})}),r.filter(n=>!this.listeningAddrs.some(o=>o.equals(n))).forEach(n=>{this.addressManager.removeObservedAddr(n)}),queueMicrotask(()=>{this.safeDispatchEvent("listening")})}};function Zl(t){return new qa(t)}var Xl="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Ql=(t=21)=>{let e="",r=crypto.getRandomValues(new Uint8Array(t|=0));for(;t--;)e+=Xl[r[t]&63];return e};var cm=60*1e3*10,um=60*1e3*5,lm=30*1e3,ts=class extends Te{peerId;connectionManager;peerStore;events;reserveQueue;reservations;pendingReservations;maxReservationQueueLength;reservationCompletionTimeout;started;log;relayFilter;constructor(e,r){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:transport:reservation-store"),this.peerId=e.peerId,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.reservations=new Ot,this.pendingReservations=[],this.maxReservationQueueLength=r?.maxReservationQueueLength??Kl,this.reservationCompletionTimeout=r?.reservationCompletionTimeout??zo,this.started=!1,this.relayFilter=Br(100),this.reserveQueue=new Or({concurrency:r?.reservationConcurrency??Fl,metricName:"libp2p_relay_reservation_queue",metrics:e.metrics}),this.events.addEventListener("connection:close",n=>{[...this.reservations.values()].find(s=>s.connection===n.detail.id)!=null&&this.#t(n.detail.remotePeer).catch(s=>{this.log.error("could not remove relay %p - %e",n.detail.remotePeer,s)})})}isStarted(){return this.started}start(){this.started=!0}afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[r=>r.tags.has(pn)]});this.log("removing tag from %d old relays",e.length),await Promise.all(e.map(async r=>{await this.peerStore.merge(r.id,{tags:{[pn]:void 0}})})),this.log("redialing %d old relays",e.length),await Promise.all(e.map(async r=>this.addRelay(r.id,"discovered"))),this.#r()}).catch(e=>{this.log.error("failed to clean up and redial old relays during afterStart - %e",e)})}stop(){this.reserveQueue.clear(),this.reservations.forEach(({timeout:e})=>{clearTimeout(e)}),this.reservations.clear(),this.started=!1}reserveRelay(){let e=Ql();return this.pendingReservations.push(e),this.#r(),e}async addRelay(e,r){if(this.peerId.equals(e))throw this.log.trace("not trying to use self as relay"),new Nt("Cannot use self as relay");if(this.reserveQueue.size>this.maxReservationQueueLength)throw new Wo("The reservation queue is full");let n=this.reserveQueue.find(e);if(n!=null)return this.log.trace("potential relay peer %p is already in the reservation queue",e),n.join();if(this.relayFilter.has(e.toMultihash().bytes))throw new Nt("The relay was previously invalid");return this.log.trace("try to reserve relay slot with %p",e),this.reserveQueue.add(async()=>{let o=Date.now();try{let s=this.reservations.get(e);if(s!=null){let E=this.connectionManager.getConnections(e),b=!1;if(E.length===0&&this.log("already have relay reservation with %p but we are no longer connected",e),E.map(g=>g.id).includes(s.connection)&&(this.log("already have relay reservation with %p and the original connection is still open",e),b=!0),b&&Na(s.reservation.expire)>cm)return this.log("already have relay reservation with %p but we are still connected and it does not expire soon",e),{relay:e,details:s};b||await this.#t(e)}if(r==="discovered"&&s==null&&this.pendingReservations.length===0)throw new bn("Not making reservation on discovered relay because we do not need any more relays");let i=AbortSignal.timeout(this.reservationCompletionTimeout);let a=await this.connectionManager.openConnection(e,{signal:i});if(Jt.matches(a.remoteAddr))throw new $o("not creating reservation over relayed connection");let c=await this.#e(a,{signal:i}),l=Na(c.expire);this.log("created reservation on relay peer %p, expiry date is %s",e,new Date(Date.now()+l).toString());let u=Math.min(Math.max(l-um,lm),Math.pow(2,31)-1),f=setTimeout(()=>{this.log("refresh reservation to relay %p",e),this.addRelay(e,r).catch(async E=>{this.log.error("could not refresh reservation to relay %p - %e",e,E),await this.#t(e)}).catch(E=>{this.log.error("could not remove expired reservation to relay %p - %e",e,E)})},u),h;if(r==="discovered"){let E=this.reservations.get(e),b=E?.type==="discovered"?E.id:this.pendingReservations.pop();if(b==null)throw new bn("Made reservation on relay but did not need any more discovered relays");h={timeout:f,reservation:c,type:r,connection:a.id,id:b}}else h={timeout:f,reservation:c,type:r,connection:a.id};s!=null&&clearTimeout(s.timeout),this.reservations.set(e,h),await this.peerStore.merge(e,{tags:{[pn]:{value:1,ttl:l}}}),this.#r();let d={relay:e,details:h};return this.safeDispatchEvent("relay:created-reservation",{detail:d}),d}catch(s){throw r==="discovered"&&s.name==="HadEnoughRelaysError"||this.log.error("could not reserve slot on %p after %dms - %e",e,Date.now()-o,s),(s.name==="DialError"||s.name==="UnsupportedProtocolError")&&this.relayFilter.add(e.toMultihash().bytes),this.#t(e).catch(i=>{this.log.error("could not remove reservation on %p after reserving slot failed - %e",e,i)}),s}},{peerId:e})}hasReservation(e){return this.reservations.has(e)}getReservation(e){return this.reservations.get(e)?.reservation}reservationCount(e){return e==null?this.reservations.size:[...this.reservations.values()].reduce((r,n)=>(n.type===e&&r++,r),0)}cancelReservations(){[...this.reservations.values()].forEach(e=>{clearTimeout(e.timeout)}),this.reservations.clear()}async#e(e,r){r.signal?.throwIfAborted(),this.log("requesting reservation from %p",e.remotePeer);let n=await e.newStream(ze,r),s=Bt(n).pb(J);this.log.trace("send RESERVE to %p",e.remotePeer),await s.write({type:J.Type.RESERVE},r);let i;try{this.log.trace("reading response from %p",e.remotePeer),i=await s.read(r)}catch(c){throw n.abort(c),c}finally{n.status!=="closed"&&await n.close(r)}if(this.log.trace("read response %s",i.status),i.status===z.OK&&i.reservation!=null){let c=new Set;c.add(e.remoteAddr.toString());for(let l of i.reservation.addrs){let u=ke(l);u.getComponents().find(f=>f.code===421)==null&&(u=u.encapsulate(`/p2p/${e.remotePeer}`)),u=ke(u.toString().replace(`/p2p/${e.remotePeer}/p2p/${e.remotePeer}`,`/p2p/${e.remotePeer}`)),c.add(u.toString())}return i.reservation.addrs=[...c].map(l=>ke(l).bytes),i.reservation}let a=`reservation failed with status ${i.status??"undefined"}`;throw this.log.error(a),new Error(a)}async#t(e){let r=this.reservations.get(e);r!=null&&(this.log("removing relay reservation with %p from local store",e),clearTimeout(r.timeout),this.reservations.delete(e),r.type==="discovered"&&this.pendingReservations.push(r.id),this.safeDispatchEvent("relay:removed",{detail:{relay:e,details:r}}),this.#r(),await this.peerStore.merge(e,{tags:{[pn]:void 0}}))}#r(){if(this.pendingReservations.length===0){this.log.trace("have discovered enough relays"),this.reserveQueue.clear(),this.safeDispatchEvent("relay:found-enough-relays");return}this.relayFilter=Br(100),this.log("not discovered enough relays %d/%d",this.reservations.size,this.pendingReservations.length),this.safeDispatchEvent("relay:not-enough-relays")}};var za=class extends Fo{stream;init;constructor(e){super({...e,direction:e.stream.direction}),this.init=e,this.stream=e.stream,this.stream.addEventListener("close",r=>{this.onTransportClosed(r.error)}),this.stream.addEventListener("remoteCloseWrite",r=>{this.onRemoteCloseWrite(),this.close().catch(n=>{this.abort(n)})}),this.stream.addEventListener("message",r=>{e.onDataRead?.(r.data),this.onData(r.data)}),this.stream.addEventListener("drain",()=>{this.safeDispatchEvent("drain")})}sendData(e){return this.init.onDataWrite?.(e),{sentBytes:e.byteLength,canSendMore:this.stream.send(e)}}async sendClose(e){await this.stream.close(e)}sendReset(){this.stream.abort(new Error("An error occurred"))}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}};function Ha(t){return new za(t)}var fm=t=>{if(t.peer==null)return!1;try{t.peer.addrs.forEach(ke)}catch{return!1}return!0},Jl={maxInboundStopStreams:mn,maxOutboundStopStreams:mn,stopTimeout:3e4},rs=class{components;discovery;reservationStore;maxInboundStopStreams;maxOutboundStopStreams;started;log;shutdownController;constructor(e,r={}){this.components=e,this.log=e.logger.forComponent("libp2p:circuit-relay:transport"),this.maxInboundStopStreams=r.maxInboundStopStreams??Jl.maxInboundStopStreams,this.maxOutboundStopStreams=r.maxOutboundStopStreams??Jl.maxOutboundStopStreams,this.shutdownController=new AbortController,this.discovery=new es(e,{filter:r.discoveryFilter??ka(Vl,$l)}),this.discovery.addEventListener("relay:discover",n=>{this.reservationStore.addRelay(n.detail,"discovered").catch(o=>{o.name!=="HadEnoughRelaysError"&&o.name!=="RelayQueueFullError"&&this.log.error("could not add discovered relay %p - %e",n.detail,o)})}),this.reservationStore=new ts(e,r),this.reservationStore.addEventListener("relay:not-enough-relays",()=>{this.discovery?.startDiscovery()}),this.reservationStore.addEventListener("relay:found-enough-relays",()=>{this.discovery?.stopDiscovery()}),this.started=!1,this.onStop=this.onStop.bind(this)}[Symbol.toStringTag]="@libp2p/circuit-relay-v2-transport";[Qa]=["@libp2p/transport","@libp2p/circuit-relay-v2-transport"];get[Ja](){return this.discovery!=null?["@libp2p/identify"]:[]}[Xa]=!0;isStarted(){return this.started}async start(){this.shutdownController=new AbortController,this.shutdownController.signal,await this.components.registrar.handle(tr,this.onStop,{maxInboundStreams:this.maxInboundStopStreams,maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0}),await ja(this.discovery,this.reservationStore),this.started=!0}async stop(){this.shutdownController.abort(),await Ga(this.discovery,this.reservationStore),await this.components.registrar.unhandle(tr),this.started=!1}async dial(e,r){let n=e.toString().split("/p2p-circuit"),o=ke(n[0]),s=ke(n[n.length-1]),i=o.getComponents().find(d=>d.code===421)?.value,a=s.getComponents().find(d=>d.code===421)?.value;if(i==null||a==null){let d=`ircuit relay dial to ${e.toString()} failed as address did not have both relay and destination PeerIDs`;throw this.log.error(`c${d}`),new _n(`C${d}`)}let c=Vi(i),l=Vi(a),f=this.components.connectionManager.getConnections(c)[0];f==null?(await this.components.peerStore.merge(c,{multiaddrs:[o]}),r.onProgress?.(new Pt("circuit-relay:open-connection")),f=await this.components.connectionManager.openConnection(c,r)):r.onProgress?.(new Pt("circuit-relay:reuse-connection"));let h;try{r.onProgress?.(new Pt("circuit-relay:open-hop-stream")),h=await f.newStream(ze,r);let d=Bt(h).pb(J);r.onProgress?.(new Pt("circuit-relay:write-connect-message")),await d.write({type:J.Type.CONNECT,peer:{id:l.toMultihash().bytes,addrs:[ke(s).bytes]}},r),r.onProgress?.(new Pt("circuit-relay:read-connect-response"));let E=await d.read(r);if(E.status!==z.OK)throw new vn(`failed to connect via relay with status ${E?.status?.toString()??"undefined"}`);let b=new wn(E.limit),g=Ha({stream:d.unwrap().unwrap(),remoteAddr:e,localAddr:o.encapsulate(`/p2p-circuit/p2p/${this.components.peerId.toString()}`),onDataRead:b.onData,onDataWrite:b.onData,log:h.log.newScope("circuit-relay:connection")}),w=await this.components.upgrader.upgradeOutbound(g,{...r,limits:b.getLimits()});return w.log("outbound relayed connection established to %p with limits %o, over connection %s",w.remotePeer,E.limit??"none",f.id),w}catch(d){throw this.log.error("circuit relay dial to destination %p via relay %p failed - %e",l,c,d),h?.abort(d),d}}createListener(e){return Zl({peerId:this.components.peerId,connectionManager:this.components.connectionManager,addressManager:this.components.addressManager,reservationStore:this.reservationStore,logger:this.components.logger})}listenFilter(e){return e=Array.isArray(e)?e:[e],e.filter(r=>Yo.exactMatch(r)||jo.exactMatch(r))}dialFilter(e){return e=Array.isArray(e)?e:[e],e.filter(r=>Jt.exactMatch(r))}async onStop(e,r){let n=this.components.upgrader.createInboundAbortSignal(this.shutdownController.signal);try{if(!this.reservationStore.hasReservation(r.remotePeer))try{this.log("dialed via relay we did not have a reservation on, start listening on that relay address"),await this.components.transportManager.listen([r.remoteAddr.encapsulate("/p2p-circuit")])}catch(f){this.log.error("failed to listen on a relay peer we were dialed via but did not have a reservation on - %e",f)}let o=Bt(e).pb(Ue),s=await o.read({signal:n});if(this.log("new circuit relay v2 stop stream from %p with type %s",r.remotePeer,s.type),s?.type===void 0){this.log.error("type was missing from circuit v2 stop protocol request from %s",r.remotePeer),await o.write({type:Ue.Type.STATUS,status:z.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}if(s.type!==Ue.Type.CONNECT){this.log.error("invalid stop connect request via peer %p",r.remotePeer),await o.write({type:Ue.Type.STATUS,status:z.UNEXPECTED_MESSAGE},{signal:n}),await e.close({signal:n});return}if(!fm(s)){this.log.error("invalid stop connect request via peer %p",r.remotePeer),await o.write({type:Ue.Type.STATUS,status:z.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}let i=Ar(Xe(s.peer.id));if(await this.components.connectionGater.denyInboundRelayedConnection?.(r.remotePeer,i)===!0){this.log.error("connection gater denied inbound relayed connection from %p",r.remotePeer),await o.write({type:Ue.Type.STATUS,status:z.PERMISSION_DENIED},{signal:n}),await e.close({signal:n});return}this.log.trace("sending success response to %p",r.remotePeer),await o.write({type:Ue.Type.STATUS,status:z.OK},{signal:n});let a=new wn(s.limit),c=r.remoteAddr.encapsulate(`/p2p-circuit/p2p/${i.toString()}`),l=this.components.addressManager.getAddresses()[0],u=Ha({stream:o.unwrap().unwrap(),remoteAddr:c,localAddr:l,onDataRead:a.onData,onDataWrite:a.onData,log:e.log.newScope("circuit-relay:connection")});await this.components.upgrader.upgradeInbound(u,{limits:a.getLimits(),signal:n}),u.log("inbound relayed connection established to %p with limits %o, over connection %s",i,s.limit??"none",r.id)}finally{n?.clear()}}};function dm(t={}){return e=>new Jo(e,t)}function hm(t={}){return e=>new rs(e,t)}return cf(pm);})();
|
|
2
|
+
"use strict";var Libp2PCircuitRelayV2=(()=>{var ss=Object.defineProperty;var of=Object.getOwnPropertyDescriptor;var sf=Object.getOwnPropertyNames;var af=Object.prototype.hasOwnProperty;var Ce=(t,e)=>{for(var r in e)ss(t,r,{get:e[r],enumerable:!0})},cf=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of sf(e))!af.call(t,o)&&o!==r&&ss(t,o,{get:()=>e[o],enumerable:!(n=of(e,o))||n.enumerable});return t};var uf=t=>cf(ss({},"__esModule",{value:!0}),t);var ym={};Ce(ym,{RELAY_V2_HOP_CODEC:()=>je,RELAY_V2_STOP_CODEC:()=>or,circuitRelayServer:()=>pm,circuitRelayTransport:()=>mm});function lf(t){return typeof t?.handleEvent=="function"}function ff(t){return t===!0||t===!1}function df(t){return ff(t)?t:t?.capture??!1}function is(t){let e={capture:df(t),once:!!t?.once};return t?.passive!=null&&(e.passive=t?.passive),t?.signal!=null&&(e.signal=t?.signal),e}function $a(t,e){return is(t).capture===is(e).capture}var Be=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let r=this.#e.get(e);return r==null?0:r.length}addEventListener(e,r,n){let o=is(n);if(o?.signal?.aborted===!0)return;let s=u=>{o.once&&this.removeEventListener(e,r,o),lf(r)?r.handleEvent(u):r(u)},i=this.#e.get(e);if(i==null&&(i=[],this.#e.set(e,i)),i.some(u=>u.callback!==r?!1:$a(u.options,o)))return;super.addEventListener(e,s,o);let c=()=>{this.removeEventListener(e,r,o)};o.signal?.addEventListener("abort",c),i.push({callback:r,wrapper:s,options:o,onAbort:c})}removeEventListener(e,r,n){let o=this.#e.get(e);if(o==null){super.removeEventListener(e,r??null,n);return}this.#e.set(e,o.filter(s=>s.callback===r&&$a(s.options,n)?(super.removeEventListener(e,s.wrapper,n),s.options?.signal?.removeEventListener("abort",s.onAbort),!1):!0))}safeDispatchEvent(e,r={}){return this.dispatchEvent(new CustomEvent(e,r))}};var Je=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var pe=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},ir=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var En=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}};var gt=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},Ut=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}};var Sn=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},vn=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var _n=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var An=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}},Mt=class extends Error{static name="ListenError";constructor(e="Listen error"){super(e),this.name="ListenError"}};var ar=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var Tn=class extends Event{data;constructor(e,r){super("message",r),this.data=e}},cr=class extends Event{error;local;constructor(e,r,n){super("close",n),this.error=r,this.local=e}},Dn=class extends cr{constructor(e,r){super(!0,e,r)}},In=class extends cr{constructor(e,r){super(!1,e,r)}};var as=Symbol.for("@libp2p/peer-id");var Wa="keep-alive";function ja(t){return t!=null&&typeof t.start=="function"&&typeof t.stop=="function"}async function Ya(...t){let e=[];for(let r of t)ja(r)&&e.push(r);await Promise.all(e.map(async r=>{r.beforeStart!=null&&await r.beforeStart()})),await Promise.all(e.map(async r=>{await r.start()})),await Promise.all(e.map(async r=>{r.afterStart!=null&&await r.afterStart()}))}async function Ga(...t){let e=[];for(let r of t)ja(r)&&e.push(r);await Promise.all(e.map(async r=>{r.beforeStop!=null&&await r.beforeStop()})),await Promise.all(e.map(async r=>{await r.stop()})),await Promise.all(e.map(async r=>{r.afterStop!=null&&await r.afterStop()}))}var Xa=Symbol.for("@libp2p/transport");var Za;(function(t){t[t.FATAL_ALL=0]="FATAL_ALL",t[t.NO_FATAL=1]="NO_FATAL"})(Za||(Za={}));var Qa=Symbol.for("@libp2p/service-capabilities"),Ja=Symbol.for("@libp2p/service-dependencies");var ds={};Ce(ds,{base58btc:()=>fe,base58flickr:()=>xf});var Zm=new Uint8Array(0);function tc(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}function He(t){if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return Ft(t);if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return Ft(new Uint8Array(t.buffer,t.byteOffset,t.byteLength));throw new Error("Unknown type, must be binary type")}function rc(t){let e=new Uint8Array(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}var ec=4096;function nc(t){let e=t.length;if(e<=ec)return String.fromCharCode.apply(String,t);let r="",n=0;for(;n<e;)r+=String.fromCharCode.apply(String,t.subarray(n,n+=ec));return r}function hf(t){return t?.buffer instanceof ArrayBuffer}function Ft(t){return hf(t)?t:t.slice()}function pf(t,e,r){if(t.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),o=0;o<n.length;o++)n[o]=255;for(var s=0;s<t.length;s++){var i=t.charAt(s),a=i.charCodeAt(0);if(n[a]!==255)throw new TypeError(i+" is ambiguous");if(n[a]=s,r){var c=i.toLowerCase().charCodeAt(0),u=i.toUpperCase().charCodeAt(0);c!==a&&(n[c]=s),u!==a&&(n[u]=s)}}var l=t.length,f=t.charAt(0),p=Math.log(l)/Math.log(256),h=Math.log(256)/Math.log(l);function w(x){if(x instanceof Uint8Array||(ArrayBuffer.isView(x)?x=new Uint8Array(x.buffer,x.byteOffset,x.byteLength):Array.isArray(x)&&(x=Uint8Array.from(x))),!(x instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(x.length===0)return"";for(var v=0,m=0,_=0,A=x.length;_!==A&&x[_]===0;)_++,v++;for(var N=(A-_)*h+1>>>0,M=new Uint8Array(N);_!==A;){for(var k=x[_],B=0,O=N-1;(k!==0||B<m)&&O!==-1;O--,B++)k+=256*M[O]>>>0,M[O]=k%l>>>0,k=k/l>>>0;if(k!==0)throw new Error("Non-zero carry");m=B,_++}for(var $=N-m;$!==N&&M[$]===0;)$++;for(var V=f.repeat(v);$<N;++$)V+=t.charAt(M[$]);return V}function g(x){if(typeof x!="string")throw new TypeError("Expected String");if(x.length===0)return new Uint8Array;var v=0;if(x[v]!==" "){for(var m=0,_=0;x[v]===f;)m++,v++;for(var A=(x.length-v)*p+1>>>0,N=new Uint8Array(A);x[v];){var M=n[x.charCodeAt(v)];if(M===255)return;for(var k=0,B=A-1;(M!==0||k<_)&&B!==-1;B--,k++)M+=l*N[B]>>>0,N[B]=M%256>>>0,M=M/256>>>0;if(M!==0)throw new Error("Non-zero carry");_=k,v++}if(x[v]!==" "){for(var O=A-_;O!==A&&N[O]===0;)O++;for(var $=new Uint8Array(m+(A-O)),V=m;O!==A;)$[V++]=N[O++];return $}}}function b(x){var v=g(x);if(v)return v;throw new Error(`Non-${e} character`)}return{encode:w,decodeUnsafe:g,decode:b}}var mf=pf,yf=mf,sc=yf;var cs=class{name;prefix;baseEncode;constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},us=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,r,n){this.name=e,this.prefix=r;let o=r.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return ic(this,e)}},ls=class{decoders;constructor(e){this.decoders=e}or(e){return ic(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function ic(t,e){return new ls({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}var fs=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,r,n,o){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=o,this.encoder=new cs(e,r,n),this.decoder=new us(e,r,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function ur({name:t,prefix:e,encode:r,decode:n}){return new fs(t,e,r,n)}function bt({name:t,prefix:e,alphabet:r,caseInsensitive:n=!1}){let{encode:o,decode:s}=sc(r,t,n);return ur({prefix:e,name:t,encode:o,decode:i=>He(s(i))})}function gf(t,e,r,n){let o=t.length;for(;t[o-1]==="=";)--o;let s=new Uint8Array(o*r/8|0),i=0,a=0,c=0;for(let u=0;u<o;++u){let l=e[t[u]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<r|l,i+=r,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=r||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function bf(t,e,r){let n=e[e.length-1]==="=",o=(1<<r)-1,s="",i=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],i+=8;i>r;)i-=r,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<r-i]),n)for(;(s.length*r&7)!==0;)s+="=";return s}function wf(t,e){let r={};for(let n=0;n<t.length;++n)if(r[t[n]]=n,e){let o=t[n].toLowerCase(),s=t[n].toUpperCase();o!==t[n]&&(r[o]=n),s!==t[n]&&(r[s]=n)}return r}function me({name:t,prefix:e,bitsPerChar:r,alphabet:n,caseInsensitive:o=!1}){let s=wf(n,o);return ur({prefix:e,name:t,encode(i){return bf(i,n,r)},decode(i){return gf(i,s,r,t)}})}var fe=bt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),xf=bt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var hs={};Ce(hs,{base32:()=>wt,base32hex:()=>_f,base32hexpad:()=>Tf,base32hexpadupper:()=>Df,base32hexupper:()=>Af,base32pad:()=>Sf,base32padupper:()=>vf,base32upper:()=>Ef,base32z:()=>If});var wt=me({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5,caseInsensitive:!0}),Ef=me({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5,caseInsensitive:!0}),Sf=me({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5,caseInsensitive:!0}),vf=me({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5,caseInsensitive:!0}),_f=me({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5,caseInsensitive:!0}),Af=me({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5,caseInsensitive:!0}),Tf=me({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5,caseInsensitive:!0}),Df=me({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5,caseInsensitive:!0}),If=me({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var ps={};Ce(ps,{base36:()=>Ur,base36upper:()=>Cf});var Ur=bt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz",caseInsensitive:!0}),Cf=bt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",caseInsensitive:!0});var Bf=uc,ac=128,Lf=127,Rf=~Lf,Of=Math.pow(2,31);function uc(t,e,r){e=e||[],r=r||0;for(var n=r;t>=Of;)e[r++]=t&255|ac,t/=128;for(;t&Rf;)e[r++]=t&255|ac,t>>>=7;return e[r]=t|0,uc.bytes=r-n+1,e}var Pf=ms,Nf=128,cc=127;function ms(t,n){var r=0,n=n||0,o=0,s=n,i,a=t.length;do{if(s>=a)throw ms.bytes=0,new RangeError("Could not decode varint");i=t[s++],r+=o<28?(i&cc)<<o:(i&cc)*Math.pow(2,o),o+=7}while(i>=Nf);return ms.bytes=s-n,r}var kf=Math.pow(2,7),Uf=Math.pow(2,14),Mf=Math.pow(2,21),Ff=Math.pow(2,28),Kf=Math.pow(2,35),qf=Math.pow(2,42),zf=Math.pow(2,49),Hf=Math.pow(2,56),Vf=Math.pow(2,63),$f=function(t){return t<kf?1:t<Uf?2:t<Mf?3:t<Ff?4:t<Kf?5:t<qf?6:t<zf?7:t<Hf?8:t<Vf?9:10},Wf={encode:Bf,decode:Pf,encodingLength:$f},jf=Wf,Mr=jf;function Fr(t,e=0){let r=Mr.decode(t,e),n=Mr.decode.bytes;if(n>9)throw new RangeError("Invalid varint: too long");if(n>1&&t[e+n-1]===0)throw new RangeError("Invalid varint: not minimally encoded");return[r,n]}function lr(t,e,r=0){return Mr.encode(t,e,r),e}function fr(t){return Mr.encodingLength(t)}function et(t,e){let r=e.byteLength,n=fr(t),o=n+fr(r),s=new Uint8Array(o+r);return lr(t,s,0),lr(r,s,n),s.set(e,o),new dr(t,r,e,s)}function tt(t){let e=He(t),[r,n]=Fr(e),[o,s]=Fr(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new dr(r,o,i,e)}function lc(t,e){if(t===e)return!0;{let r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&tc(t.bytes,r.bytes)}}var dr=class{code;size;digest;bytes;constructor(e,r,n,o){this.code=e,this.size=r,this.digest=Ft(n),this.bytes=Ft(o)}};function fc(t,e){let{bytes:r,version:n}=t;return n===0?Gf(r,ys(t),e??fe.encoder):Zf(r,ys(t),e??wt.encoder)}var dc=new WeakMap;function ys(t){let e=dc.get(t);if(e==null){let r=new Map;return dc.set(t,r),r}return e}var we=class t{code;version;multihash;bytes;"/";constructor(e,r,n,o){this.code=r,this.version=e,this.multihash=n,this.bytes=Ft(o),this["/"]=this.bytes}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:r}=this;if(e!==Kr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==Xf)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return t.createV0(r)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:r}=this.multihash,n=et(e,r);return t.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return t.equals(this,e)}static equals(e,r){let n=r;return n!=null&&e.code===n.code&&e.version===n.version&&lc(e.multihash,n.multihash)}toString(e){return fc(this,e)}toJSON(){return{"/":fc(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let r=e;if(r instanceof t)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){let{version:n,code:o,multihash:s,bytes:i}=r;return new t(n,o,s,i??hc(n,o,s.bytes))}else if(r[Qf]===!0){let{version:n,multihash:o,code:s}=r,i=tt(o);return t.create(n,s,i)}else return null}static create(e,r,n){if(typeof r!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(r!==Kr)throw new Error(`Version 0 CID must use dag-pb (code: ${Kr}) block encoding`);return new t(e,r,n,n.bytes)}case 1:{let o=hc(e,r,n.bytes);return new t(e,r,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return t.create(0,Kr,e)}static createV1(e,r){return t.create(1,e,r)}static decode(e){let[r,n]=t.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return r}static decodeFirst(e){let r=t.inspectBytes(e),n=r.size-r.multihashSize,o=He(e.subarray(n,n+r.multihashSize));if(o.byteLength!==r.multihashSize)throw new Error("Incorrect length");let s=o.subarray(r.multihashSize-r.digestSize),i=new dr(r.multihashCode,r.digestSize,s,o);return[r.version===0?t.createV0(i):t.createV1(r.codec,i),e.subarray(r.size)]}static inspectBytes(e){let r=0,n=()=>{let[f,p]=Fr(e.subarray(r));return r+=p,f},o=n(),s=Kr;if(o===18?(o=0,r=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=r,a=n(),c=n(),u=r+c,l=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(e,r){let[n,o]=Yf(e,r),s=t.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return ys(s).set(n,e),s}};function Yf(t,e){switch(t[0]){case"Q":{let r=e??fe;return[fe.prefix,r.decode(`${fe.prefix}${t}`)]}case fe.prefix:{let r=e??fe;return[fe.prefix,r.decode(t)]}case wt.prefix:{let r=e??wt;return[wt.prefix,r.decode(t)]}case Ur.prefix:{let r=e??Ur;return[Ur.prefix,r.decode(t)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}}function Gf(t,e,r){let{prefix:n}=r;if(n!==fe.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let o=e.get(n);if(o==null){let s=r.encode(t).slice(1);return e.set(n,s),s}else return o}function Zf(t,e,r){let{prefix:n}=r,o=e.get(n);if(o==null){let s=r.encode(t);return e.set(n,s),s}else return o}var Kr=112,Xf=18;function hc(t,e,r){let n=fr(t),o=n+fr(e),s=new Uint8Array(o+r.byteLength);return lr(t,s,0),lr(e,s,n),s.set(r,o),s}var Qf=Symbol.for("@ipld/js-cid/CID");var gs={};Ce(gs,{identity:()=>Ye});var pc=0,Jf="identity",mc=He;function ed(t,e){if(e?.truncate!=null&&e.truncate!==t.byteLength){if(e.truncate<0||e.truncate>t.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,e.truncate)}return et(pc,mc(t))}var Ye={code:pc,name:Jf,encode:mc,digest:ed};function be(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}function td(t){return t.buffer instanceof ArrayBuffer}function Ie(t){return td(t)?t:t.slice()}async function yc(t,e,r,n){let o=await crypto.subtle.importKey("jwk",t,{name:"ECDSA",namedCurve:t.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,Ie(e),Ie(r.subarray()));return n?.signal?.throwIfAborted(),s}function ae(t=0){return new Uint8Array(t)}function _e(t=0){return new Uint8Array(t)}function rd(t){return t?.buffer instanceof ArrayBuffer}function bs(t){if(rd(t))return t;let e=t.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function rt(t,e){e==null&&(e=t.reduce((o,s)=>o+s.length,0));let r=_e(e),n=0;for(let o of t)r.set(o,n),n+=o.length;return bs(r)}var bc=Symbol.for("@achingbrain/uint8arraylist");function gc(t,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let r=0;for(let n of t){let o=r+n.byteLength;if(e<o)return{buf:n,index:e-r};r=o}throw new RangeError("index is out of bounds")}function Bn(t){return!!t?.[bc]}var ce=class t{bufs;length;[bc]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let r=0;for(let n of e)if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.push(n);else if(Bn(n)){r+=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+=r}prepend(...e){this.prependAll(e)}prependAll(e){let r=0;for(let n of e.reverse())if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.unshift(n);else if(Bn(n))r+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=r}get(e){let r=gc(this.bufs,e);return r.buf[r.index]}set(e,r){let n=gc(this.bufs,e);n.buf[n.index]=r}write(e,r=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(r+n,e[n]);else if(Bn(e))for(let n=0;n<e.length;n++)this.set(r+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,r){let{bufs:n,length:o}=this._subList(e,r);return rt(n,o)}subarray(e,r){let{bufs:n,length:o}=this._subList(e,r);return n.length===1?n[0]:rt(n,o)}sublist(e,r){let{bufs:n,length:o}=this._subList(e,r),s=new t;return s.length=o,s.bufs=n,s}_subList(e,r){if(e=e??0,r=r??this.length,e<0&&(e=this.length+e),r<0&&(r=this.length+r),e<0||r>this.length)throw new RangeError("index is out of bounds");if(e===r)return{bufs:[],length:0};if(e===0&&r===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let u=e>=a&&e<c,l=r>a&&r<=c;if(u&&l){if(e===a&&r===c){n.push(i);break}let f=e-a;n.push(i.subarray(f,f+(r-e)));break}if(u){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(l){if(r===c){n.push(i);break}n.push(i.subarray(0,r-a));break}n.push(i)}return{bufs:n,length:r-e}}indexOf(e,r=0){if(!Bn(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(r=Number(r??0),isNaN(r)&&(r=0),r<0&&(r=this.length+r),r<0&&(r=0),e.length===0)return r>this.length?this.length:r;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let f=0;f<s;f++)i[f]=-1;for(let f=0;f<o;f++)i[n[f]]=f;let a=i,c=this.byteLength-n.byteLength,u=n.byteLength-1,l;for(let f=r;f<=c;f+=l){l=0;for(let p=u;p>=0;p--){let h=this.get(f+p);if(n[p]!==h){l=Math.max(1,p-a[h]);break}}if(l===0)return f}return-1}getInt8(e){let r=this.subarray(e,e+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt8(0)}setInt8(e,r){let n=_e(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,r),this.write(n,e)}getInt16(e,r){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,r)}setInt16(e,r,n){let o=ae(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,r,n),this.write(o,e)}getInt32(e,r){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,r)}setInt32(e,r,n){let o=ae(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,r,n),this.write(o,e)}getBigInt64(e,r){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,r)}setBigInt64(e,r,n){let o=ae(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,r,n),this.write(o,e)}getUint8(e){let r=this.subarray(e,e+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint8(0)}setUint8(e,r){let n=_e(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,r),this.write(n,e)}getUint16(e,r){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,r)}setUint16(e,r,n){let o=ae(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,r,n),this.write(o,e)}getUint32(e,r){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,r)}setUint32(e,r,n){let o=ae(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,r,n),this.write(o,e)}getBigUint64(e,r){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,r)}setBigUint64(e,r,n){let o=ae(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,r,n),this.write(o,e)}getFloat32(e,r){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,r)}setFloat32(e,r,n){let o=ae(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,r,n),this.write(o,e)}getFloat64(e,r){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,r)}setFloat64(e,r,n){let o=ae(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,r,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof t)||e.bufs.length!==this.bufs.length)return!1;for(let r=0;r<this.bufs.length;r++)if(!be(this.bufs[r],e.bufs[r]))return!1;return!0}static fromUint8Arrays(e,r){let n=new t;return n.bufs=e,r==null&&(r=e.reduce((o,s)=>o+s.byteLength,0)),n.length=r,n}};var ws={};Ce(ws,{base10:()=>nd});var nd=bt({prefix:"9",name:"base10",alphabet:"0123456789"});var xs={};Ce(xs,{base16:()=>od,base16upper:()=>sd});var od=me({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4,caseInsensitive:!0}),sd=me({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4,caseInsensitive:!0});var Es={};Ce(Es,{base2:()=>id});var id=me({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Ss={};Ce(Ss,{base256emoji:()=>fd});var wc=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}"),ad=wc.reduce((t,e,r)=>(t[r]=e,t),[]),cd=wc.reduce((t,e,r)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return t[n]=r,t},[]);function ud(t){return t.reduce((e,r)=>(e+=ad[r],e),"")}function ld(t){let e=[];for(let r of t){let n=r.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${r}`);let o=cd[n];if(o==null)throw new Error(`Non-base256emoji character: ${r}`);e.push(o)}return new Uint8Array(e)}var fd=ur({prefix:"\u{1F680}",name:"base256emoji",encode:ud,decode:ld});var _s={};Ce(_s,{base64:()=>dd,base64pad:()=>hd,base64url:()=>vs,base64urlpad:()=>pd});var dd=me({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),hd=me({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),vs=me({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),pd=me({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var As={};Ce(As,{base8:()=>md});var md=me({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Ts={};Ce(Ts,{identity:()=>yd});var yd=ur({prefix:"\0",name:"identity",encode:t=>nc(He(t)),decode:t=>He(rc(t))});var Ny=new TextEncoder,ky=new TextDecoder;var Cs={};Ce(Cs,{sha256:()=>hr,sha512:()=>xd});var wd=20;function Is({name:t,code:e,encode:r,minDigestLength:n,maxDigestLength:o}){return new Ds(t,e,r,n,o)}var Ds=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,r,n,o,s){this.name=e,this.code=r,this.encode=n,this.minDigestLength=o??wd,this.maxDigestLength=s}digest(e,r){if(r?.truncate!=null){if(r.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&r.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?xc(n,this.code,r?.truncate):n.then(o=>xc(o,this.code,r?.truncate))}else throw Error("Unknown type, must be binary type")}};function xc(t,e,r){if(r!=null&&r!==t.byteLength){if(r>t.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,r)}return et(e,t)}function Sc(t){return async e=>new Uint8Array(await crypto.subtle.digest(t,e))}var hr=Is({name:"sha2-256",code:18,encode:Sc("SHA-256")}),xd=Is({name:"sha2-512",code:19,encode:Sc("SHA-512")});var qr={...Ts,...Es,...As,...ws,...xs,...hs,...ps,...ds,..._s,...Ss},Yy={...Cs,...gs};function _c(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var vc=_c("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Bs=_c("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);let e=_e(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),Ed={utf8:vc,"utf-8":vc,hex:qr.base16,latin1:Bs,ascii:Bs,binary:Bs,...qr},Ln=Ed;function K(t,e="utf8"){let r=Ln[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return r.decoder.decode(`${r.prefix}${t}`)}function j(t,e="utf8"){let r=Ln[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return r.encoder.encode(t).substring(1)}var Sd=parseInt("11111",2),Ls=parseInt("10000000",2),vd=parseInt("01111111",2),Ac={0:zr,1:zr,2:_d,3:Dd,4:Id,5:Td,6:Ad,16:zr,22:zr,48:zr};function ut(t,e={offset:0}){let r=t[e.offset]&Sd;if(e.offset++,Ac[r]!=null)return Ac[r](t,e);throw new Error("No decoder for tag "+r)}function Hr(t,e){let r=0;if((t[e.offset]&Ls)===Ls){let n=t[e.offset]&vd,o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++){if(e.offset>=t.byteLength)throw new Error("invalid DER element length");o+=t[e.offset].toString(16).padStart(2,"0")}r=parseInt(o,16)}else r=t[e.offset],e.offset++;if(!Number.isInteger(r)||r<0||r>t.byteLength-e.offset)throw new Error("invalid DER element length");return r}function zr(t,e){Hr(t,e);let r=[];for(;!(e.offset>=t.byteLength);){let n=ut(t,e);if(n===null)break;r.push(n)}return r}function _d(t,e){let r=Hr(t,e),n=e.offset,o=e.offset+r,s=[];for(let i=n;i<o;i++)i===n&&t[i]===0||s.push(t[i]);return e.offset+=r,Uint8Array.from(s)}function Ad(t,e){let r=Hr(t,e),n=e.offset+r,o=t[e.offset];e.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,c=[];for(;e.offset<n;){let u=t[e.offset];if(e.offset++,c.push(u&127),u<128){c.reverse();let l=0;for(let f=0;f<c.length;f++)l+=c[f]<<f*7;a+=`.${l}`,c=[]}}return a}function Td(t,e){return e.offset++,null}function Dd(t,e){let r=Hr(t,e),n=t[e.offset];e.offset++;let o=t.subarray(e.offset,e.offset+r-1);if(e.offset+=r,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function Id(t,e){let r=Hr(t,e),n=t.subarray(e.offset,e.offset+r);return e.offset+=r,n}function Cd(t){let e=t.toString(16);e.length%2===1&&(e="0"+e);let r=new ce;for(let n=0;n<e.length;n+=2)r.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return r}function Rs(t){if(t.byteLength<128)return Uint8Array.from([t.byteLength]);let e=Cd(t.byteLength);return new ce(Uint8Array.from([e.byteLength|Ls]),e)}function Le(t){let e=new ce,r=128;return(t.subarray()[0]&r)===r&&e.append(Uint8Array.from([0])),e.append(t),new ce(Uint8Array.from([2]),Rs(e),e)}function Rn(t){let e=Uint8Array.from([0]),r=new ce(e,t);return new ce(Uint8Array.from([3]),Rs(r),r)}function xt(t,e=48){let r=new ce;for(let n of t)r.append(n);return new ce(Uint8Array.from([e]),Rs(r),r)}var Bd=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Ld=Uint8Array.from([6,5,43,129,4,0,34]),Rd=Uint8Array.from([6,5,43,129,4,0,35]),Od={ext:!0,kty:"EC",crv:"P-256"},Pd={ext:!0,kty:"EC",crv:"P-384"},Nd={ext:!0,kty:"EC",crv:"P-521"},Os=32,Ps=48,Ns=66;function ks(t){let e=ut(t);return Tc(e)}function Tc(t){let e=t[1][1][0],r=1,n,o;if(e.byteLength===Os*2+1)return n=j(e.subarray(r,r+Os),"base64url"),o=j(e.subarray(r+Os),"base64url"),new pr({...Od,key_ops:["verify"],x:n,y:o});if(e.byteLength===Ps*2+1)return n=j(e.subarray(r,r+Ps),"base64url"),o=j(e.subarray(r+Ps),"base64url"),new pr({...Pd,key_ops:["verify"],x:n,y:o});if(e.byteLength===Ns*2+1)return n=j(e.subarray(r,r+Ns),"base64url"),o=j(e.subarray(r+Ns),"base64url"),new pr({...Nd,key_ops:["verify"],x:n,y:o});throw new pe(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function Dc(t){return xt([Le(Uint8Array.from([1])),xt([kd(t.crv)],160),xt([Rn(new ce(Uint8Array.from([4]),K(t.x??"","base64url"),K(t.y??"","base64url")))],161)]).subarray()}function kd(t){if(t==="P-256")return Bd;if(t==="P-384")return Ld;if(t==="P-521")return Rd;throw new pe(`Invalid curve ${t}`)}var pr=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=Dc(this.jwk)),this._raw}toMultihash(){return Ye.digest(nt(this))}toCID(){return we.createV1(114,this.toMultihash())}toString(){return fe.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:be(this.raw,e.raw)}async verify(e,r,n){return yc(this.jwk,r,e,n)}};var On=BigInt(4294967295),Ic=BigInt(32);function Ud(t,e=!1){return e?{h:Number(t&On),l:Number(t>>Ic&On)}:{h:Number(t>>Ic&On)|0,l:Number(t&On)|0}}function Cc(t,e=!1){let r=t.length,n=new Uint32Array(r),o=new Uint32Array(r);for(let s=0;s<r;s++){let{h:i,l:a}=Ud(t[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var Md=t=>t/2**32|0,Fd=t=>t>>>0;function Bc(t,e,r,n){let o=Md(r),s=Fd(r);t.setUint32(e,n?s:o,n),t.setUint32(e+4,n?o:s,n)}var Us=(t,e,r)=>t>>>r,Ms=(t,e,r)=>t<<32-r|e>>>r,Kt=(t,e,r)=>t>>>r|e<<32-r,qt=(t,e,r)=>t<<32-r|e>>>r,Vr=(t,e,r)=>t<<64-r|e>>>r-32,$r=(t,e,r)=>t>>>r-32|e<<64-r;function ot(t,e,r,n){let o=(e>>>0)+(n>>>0);return{h:t+r+(o/2**32|0)|0,l:o|0}}var Lc=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),Rc=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,Oc=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),Pc=(t,e,r,n,o)=>e+r+n+o+(t/2**32|0)|0,Nc=(t,e,r,n,o)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(o>>>0),kc=(t,e,r,n,o,s)=>e+r+n+o+s+(t/2**32|0)|0;function Pn(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}var Fs=t=>t?`"${t}" `:"";function lt(t,e=""){if(typeof t!="number")throw new TypeError(Fs(e)+"expected number, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw new RangeError(Fs(e)+"expected integer >= 0, got "+t);return t}function Ve(t,e,r=""){if(Pn(t)&&(e===void 0||t.length===e))return t;e!==void 0&<(e,"length");let n=Pn(t),o=e!==void 0?` of length ${e}`:"",s=n?`length=${t.length}`:`type=${typeof t}`,i=Fs(r)+"expected Uint8Array"+o+", got "+s;throw n?new RangeError(i):new TypeError(i)}function Nn(t){if(typeof t!="function"||typeof t.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(lt(t.outputLen),lt(t.blockLen),t.outputLen<1||t.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}var qd=(t,e)=>{if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof t)},Uc=(t,e)=>{qd(t,e);let r=Object.getPrototypeOf(t);if(r!==Object.prototype&&r!==null)throw new TypeError(`"${e}" expected plain object`);if(Object.hasOwn(t,"__proto__"))throw new TypeError(`"${e}.__proto__" is not allowed`)};function mr(t,e=!0){if(t.destroyed)throw new Error("hash was destroyed");if(e&&t.finished)throw new Error("digest() was already called")}function kn(t,e){Ve(t,void 0,"output");let r=e.outputLen;if(!(t.length>=r))throw new RangeError('"output" expected length >= '+r)}function zt(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Un(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Ge(t,e){return t<<32-e|t>>>e}var Fc=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",zd=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Mn(t){if(Ve(t),Fc)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=zd[t[r]];return e}function Mc(t){return t>=48&&t<=57?t-48:t>=65&&t<=70?t-55:t>=97&&t<=102?t-87:void 0}function Fn(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);if(Fc)try{return Uint8Array.fromHex(t)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}let e=t.length,r=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(r);for(let o=0,s=0;o<r;o++,s+=2){let i=Mc(t.charCodeAt(s)),a=Mc(t.charCodeAt(s+1));if(i===void 0||a===void 0){let c=t[s]+t[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function Ks(...t){let e=0;for(let n=0;n<t.length;n++){let o=t[n];Ve(o),e+=o.length}let r=new Uint8Array(e);for(let n=0,o=0;n<t.length;n++){let s=t[n];r.set(s,o),o+=s.length}return r}function Hd(t,e,r="opts"){return Uc(t,"defaults"),e!==void 0&&Uc(e,r),Object.assign(Object.create(null),t,e)}function qs(t,e={}){if(typeof t!="function")throw new TypeError('"hashCons" expected function, got type='+typeof t);e=Hd({},e,"info");let r=(o,s)=>t(s).update(o).digest(),n=t(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=o=>t(o),Object.assign(r,e),Object.freeze(r)}function Kc(t=32){lt(t,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(t>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${t}`);return e.getRandomValues(new Uint8Array(t))}var zs=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});function qc(t,e,r){return t&e^~t&r}function zc(t,e,r){return t&e^t&r^e&r}var Wr=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,r,n,o){this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=Un(this.buffer)}update(e){mr(this),Ve(e);let{view:r,buffer:n,blockLen:o}=this,s=e.length,i=!1;for(let a=0;a<s;){let c=Math.min(o-this.pos,s-a);if(c===o){let u=Un(e);for(;o<=s-a;a+=o)this.process(u,a);i=!0;continue}n.set(a===0&&c===s?e:e.subarray(a,a+c),this.pos),this.pos+=c,a+=c,this.pos===o&&(this.process(r,0),this.pos=0,i=!0)}return this.length+=e.length,i&&this.roundClean(),this}digestInto(e){mr(this),kn(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;r[i++]=128,r.fill(0,i),this.padOffset>o-i&&(this.process(n,0),r.fill(0)),Bc(n,o-8,this.length*8,s),this.process(n,0),this.roundClean();let a=e===r?n:Un(e),c=this.outputLen,u=c/4,l=this.get();if(c%4||u>l.length)throw new Error("invalid outputLen");for(let f=0;f<u;f++)a.setUint32(4*f,l[f],s)}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}_cloneIntoMeta(e){let{buffer:r,length:n,finished:o,destroyed:s,pos:i}=this;return e.destroyed=s,e.finished=o,e.length=n,e.pos=i,i&&e.buffer.set(r),e}clone(){return this._cloneInto()}},Hc=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Vc=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Vd=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]),Et=new Uint32Array(64),Hs=class extends Wr{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,r){super(64,e,8,!1),this.A=r[0]|0,this.B=r[1]|0,this.C=r[2]|0,this.D=r[3]|0,this.E=r[4]|0,this.F=r[5]|0,this.G=r[6]|0,this.H=r[7]|0}get(){let{A:e,B:r,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,r,n,o,s,i,a,c]}set(e,r,n,o,s,i,a,c){this.A=e|0,this.B=r|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}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,r){for(let f=0;f<16;f++,r+=4)Et[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){let p=Et[f-15],h=Et[f-2],w=Ge(p,7)^Ge(p,18)^p>>>3,g=Ge(h,17)^Ge(h,19)^h>>>10;Et[f]=g+Et[f-7]+w+Et[f-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:l}=this;for(let f=0;f<64;f++){let p=Ge(a,6)^Ge(a,11)^Ge(a,25),h=l+p+qc(a,c,u)+Vd[f]+Et[f]|0,g=(Ge(n,2)^Ge(n,13)^Ge(n,22))+zc(n,o,s)|0;l=u,u=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+g|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(n,o,s,i,a,c,u,l)}roundClean(){zt(Et)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),zt(this.buffer)}},Vs=class extends Hs{constructor(){super(32,Hc)}};var $c=Cc(["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(t=>BigInt(t))),$d=$c[0],Wd=$c[1],St=new Uint32Array(80),vt=new Uint32Array(80),$s=class extends Wr{Ah=0;Al=0;Bh=0;Bl=0;Ch=0;Cl=0;Dh=0;Dl=0;Eh=0;El=0;Fh=0;Fl=0;Gh=0;Gl=0;Hh=0;Hl=0;constructor(e,r){super(128,e,16,!1),this.Ah=r[0]|0,this.Al=r[1]|0,this.Bh=r[2]|0,this.Bl=r[3]|0,this.Ch=r[4]|0,this.Cl=r[5]|0,this.Dh=r[6]|0,this.Dl=r[7]|0,this.Eh=r[8]|0,this.El=r[9]|0,this.Fh=r[10]|0,this.Fl=r[11]|0,this.Gh=r[12]|0,this.Gl=r[13]|0,this.Hh=r[14]|0,this.Hl=r[15]|0}get(){let{Ah:e,Al:r,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:u,El:l,Fh:f,Fl:p,Gh:h,Gl:w,Hh:g,Hl:b}=this;return[e,r,n,o,s,i,a,c,u,l,f,p,h,w,g,b]}set(e,r,n,o,s,i,a,c,u,l,f,p,h,w,g,b){this.Ah=e|0,this.Al=r|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=f|0,this.Fl=p|0,this.Gh=h|0,this.Gl=w|0,this.Hh=g|0,this.Hl=b|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,r){for(let m=0;m<16;m++,r+=4)St[m]=e.getUint32(r),vt[m]=e.getUint32(r+=4);for(let m=16;m<80;m++){let _=St[m-15]|0,A=vt[m-15]|0,N=Kt(_,A,1)^Kt(_,A,8)^Us(_,A,7),M=qt(_,A,1)^qt(_,A,8)^Ms(_,A,7),k=St[m-2]|0,B=vt[m-2]|0,O=Kt(k,B,19)^Vr(k,B,61)^Us(k,B,6),$=qt(k,B,19)^$r(k,B,61)^Ms(k,B,6),V=Oc(M,$,vt[m-7],vt[m-16]),ne=Pc(V,N,O,St[m-7],St[m-16]);St[m]=ne|0,vt[m]=V|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:l,Eh:f,El:p,Fh:h,Fl:w,Gh:g,Gl:b,Hh:x,Hl:v}=this;for(let m=0;m<80;m++){let _=Kt(f,p,14)^Kt(f,p,18)^Vr(f,p,41),A=qt(f,p,14)^qt(f,p,18)^$r(f,p,41),N=f&h^~f&g,M=p&w^~p&b,k=Nc(v,A,M,Wd[m],vt[m]),B=kc(k,x,_,N,$d[m],St[m]),O=k|0,$=Kt(n,o,28)^Vr(n,o,34)^Vr(n,o,39),V=qt(n,o,28)^$r(n,o,34)^$r(n,o,39),ne=n&s^n&a^s&a,D=o&i^o&c^i&c;x=g|0,v=b|0,g=h|0,b=w|0,h=f|0,w=p|0,{h:f,l:p}=ot(u|0,l|0,B|0,O|0),u=a|0,l=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let F=Lc(O,V,D);n=Rc(F,B,$,ne),o=F|0}({h:n,l:o}=ot(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=ot(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=ot(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=ot(this.Dh|0,this.Dl|0,u|0,l|0),{h:f,l:p}=ot(this.Eh|0,this.El|0,f|0,p|0),{h,l:w}=ot(this.Fh|0,this.Fl|0,h|0,w|0),{h:g,l:b}=ot(this.Gh|0,this.Gl|0,g|0,b|0),{h:x,l:v}=ot(this.Hh|0,this.Hl|0,x|0,v|0),this.set(n,o,s,i,a,c,u,l,f,p,h,w,g,b,x,v)}roundClean(){zt(St,vt)}destroy(){this.destroyed=!0,zt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Ws=class extends $s{constructor(){super(64,Vc)}};var yr=qs(()=>new Vs,zs(1));var js=qs(()=>new Ws,zs(3));function qn(t,e,r=()=>{}){if(!Array.isArray(t))throw new TypeError(`"${e}" expected array, got type=${typeof t}`);for(let n=0;n<t.length;n++)r(t[n],`${e}[${n}]`);return t}var X=(t,e,r)=>Ve(t,e,r),Ys=lt;function jc(t,e=""){if(typeof t!="string"){let r=e&&`"${e}" `;throw new TypeError(r+"expected string, got type="+typeof t)}return t}function _t(t,e="object"){if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof t}`);return t}function Ht(t,e){if(typeof t!="function")throw new TypeError(`"${e}" is invalid: expected function, got ${typeof t}`);return t}var jr=Mn,$e=(...t)=>Ks(...t),gr=t=>Fn(t),Tt=Pn,Vt=t=>Kc(t),Kn=BigInt(0),Wc=BigInt(1),jd=t=>t?`"${t}" `:"";function Re(t,e=""){if(typeof t!="boolean")throw new TypeError(jd(e)+"expected boolean, got type="+typeof t);return t}function zn(t){if(typeof t=="bigint"){if(!At(t))throw new RangeError("positive bigint expected, got "+t)}else Ys(t);return t}function ft(t,e=""){if(typeof t!="number"){let r=e&&`"${e}" `;throw new TypeError(r+"expected number, got type="+typeof t)}if(!Number.isSafeInteger(t)){let r=e&&`"${e}" `;throw new RangeError(r+"expected safe integer, got "+t)}}function Yr(t){let e=zn(t).toString(16);return e.length&1?"0"+e:e}function Yc(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);return t===""?Kn:BigInt("0x"+t)}function st(t){return Yc(Mn(t))}function $t(t){return Yc(Mn(Gr(Ve(t)).reverse()))}function Hn(t,e){if(lt(e),e===0)throw new Error("zero output length is invalid");t=zn(t);let r=e*2,n=t.toString(16);if(n.length>r)throw new RangeError("number is too large");return Fn(n.padStart(r,"0"))}function Gs(t,e){return Hn(t,e).reverse()}function Gr(t){return Uint8Array.from(X(t))}function At(t){return typeof t=="bigint"&&Kn<=t}function Zs(t,e,r){return At(t)&&At(e)&&At(r)&&e<=t&&t<r}function br(t,e,r,n){if(!Zs(e,r,n))throw new RangeError("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function wr(t){if(t<Kn)throw new Error("expected non-negative bigint, got "+t);return t===Kn?0:t.toString(2).length}var Zr=t=>(ft(t,"n"),(Wc<<BigInt(t))-Wc);function Gc(t,e,r){if(lt(t,"hashLen"),lt(e,"qByteLen"),typeof r!="function")throw new TypeError("hmacFn must be a function");let n=b=>new Uint8Array(b),o=Uint8Array.of(),s=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(t),u=n(t),l=0,f=()=>{c.fill(1),u.fill(0),l=0},p=(...b)=>r(u,$e(c,...b)),h=(b=o)=>{u=p(s,b),c=p(),b.length!==0&&(u=p(i,b),c=p())},w=()=>{if(l++>=a)throw new Error("drbg: tried max amount of iterations");let b=0,x=[];for(;b<e;){c=p();let v=c.slice();x.push(v),b+=c.length}return $e(...x)};return(b,x)=>{f(),h(b);let v;for(;(v=x(w()))===void 0;)h();return f(),v}}function Oe(t,e={},r={},n="object"){_t(t,n),_t(e,"fields"),_t(r,"optFields");function o(i,a,c){let u=n==="object"?`param "${String(i)}"`:`"${n}.${String(i)}"`,l=t[i];if(!Object.hasOwn(t,i)&&(c?l!==void 0:a!=="function"))throw new TypeError(`${u} is invalid: expected own property`);if(c&&l===void 0)return;let f=typeof l;if(f!==a||l===null)throw new TypeError(`${u} is invalid: expected ${a}, got ${f}`)}let s=(i,a)=>Object.entries(i).forEach(([c,u])=>o(c,u,a));s(e,!1),s(r,!0)}var xe=BigInt(0),Q=BigInt(1),Dt=BigInt(2),Qc=BigInt(3),Xs=BigInt(4),Jc=BigInt(5),Yd=BigInt(7),eu=BigInt(8),Gd=BigInt(9),Zd=BigInt(15),tu=BigInt(16),Xd=BigInt("0x10000000000000000");function de(t,e){if(e<=xe)throw new Error("mod: expected positive modulus, got "+e);let r=t%e;return r>=xe?r:e+r}function ru(t,e,r){if(r<=Q)throw new Error("pow: expected modulus > 1, got "+r);if(typeof e!="bigint")throw new TypeError("invalid exponent: expected bigint, got "+typeof e);if(e<xe)throw new Error("invalid exponent, negatives unsupported");if(e===xe)return Q;if(e===Q)return t;let n=t%r;if(n<xe&&(n+=r),e<Xd){let a=Q;for(;e>xe;)e&Q&&(a=a*n%r),n=n*n%r,e>>=Q;return a}let o=[];for(;e>xe;)o.push(Number(e&Zd)),e>>=Xs;let s=new Array(16);s[0]=Q,s[1]=n;for(let a=2;a<16;a++)s[a]=s[a-1]*n%r;let i=s[o[o.length-1]];for(let a=o.length-2;a>=0;a--){i=i*i%r,i=i*i%r,i=i*i%r,i=i*i%r;let c=o[a];c!==0&&(i=i*s[c]%r)}return i}function ue(t,e,r){if(r<=Q)throw new Error("pow2: expected modulus > 1, got "+r);if(e<xe)throw new Error("pow2: expected non-negative exponent, got "+e);let n=t;for(;e-- >xe;)n*=n,n%=r;return n}function Zc(t,e){if(t===xe)throw new Error("invert: expected non-zero number");if(e<=Q)throw new Error("invert: expected modulus > 1, got "+e);let r=de(t,e),n=e,o=xe,s=Q;for(;r!==xe;){let a=n/r,c=n-r*a,u=o-s*a;n=r,r=c,o=s,s=u}if(n!==Q)throw new Error("invert: does not exist");return de(o,e)}function nu(t,e){if(e<=Q)throw new Error("invertCt: expected prime modulus > 1, got "+e);let r=de(t,e);if(r===xe)throw new Error("invertCt: expected non-zero number");let n=ru(r,e-Dt,e);if(de(r*n,e)!==Q)throw new Error("invertCt: does not exist");return n}function Qs(t,e,r){let n=t;if(!n.eql(n.sqr(e),r))throw new Error("Cannot find square root")}function Js(t,e){if((t&Q)===xe)throw new Error(e+": expected odd modulus, got "+t)}function ou(t,e){let r=t,n=(r.ORDER+Q)/Xs,o=r.pow(e,n);return Qs(r,o,e),o}function Qd(t,e){let r=t,n=(r.ORDER-Jc)/eu,o=r.mul(e,Dt),s=r.pow(o,n),i=r.mul(e,s),a=r.mul(r.mul(i,Dt),s),c=r.mul(i,r.sub(a,r.ONE));return Qs(r,c,e),c}function Jd(t){let e=Er(t),r=su(t),n=r(e,e.neg(e.ONE)),o=r(e,n),s=r(e,e.neg(n)),i=(t+Yd)/tu;return((a,c)=>{let u=a,l=u.pow(c,i),f=u.mul(l,n),p=u.mul(l,o),h=u.mul(l,s),w=u.eql(u.sqr(f),c),g=u.eql(u.sqr(p),c);l=u.cmov(l,f,w),f=u.cmov(h,p,g);let b=u.eql(u.sqr(f),c),x=u.cmov(l,f,b);return Qs(u,x,c),x})}function su(t){if(t<Qc)throw new Error("sqrt is not defined for small field");Js(t,"tonelliShanks");let e=t-Q,r=0;for(;e%Dt===xe;)e/=Dt,r++;let n=Dt,o=Er(t);for(;Xr(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return ou;let s=o.pow(n,e),i=(e+Q)/Dt;return function(c,u){let l=c;if(l.is0(u))return u;if(Xr(l,u)!==1)throw new Error("Cannot find square root");let f=r,p=l.mul(l.ONE,s),h=l.pow(u,e),w=l.pow(u,i);for(;!l.eql(h,l.ONE);){if(l.is0(h))throw new Error("Cannot find square root: probably non-prime P");let g=1,b=l.sqr(h);for(;!l.eql(b,l.ONE);)if(g++,b=l.sqr(b),g===f)throw new Error("Cannot find square root");let x=Q<<BigInt(f-g-1),v=l.pow(p,x);f=g,p=l.sqr(v),h=l.mul(h,p),w=l.mul(w,v)}return w}}function eh(t){return Js(t,"Fp.sqrt"),t%Xs===Qc?ou:t%eu===Jc?Qd:t%tu===Gd?Jd(t):su(t)}var iu=(t,e)=>(de(t,e)&Q)===Q,th=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function xr(t){if(_t(t,"field"),typeof t.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof t.ORDER);ft(t.BYTES,"BYTES"),ft(t.BITS,"BITS");for(let e of th)Ht(t[e],"field."+e);if(t.BYTES<1||t.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(t.ORDER<=Q)throw new Error("invalid field: expected ORDER > 1, got "+t.ORDER);return t}function $n(t,e,r=!1){xr(t),qn(e,"nums"),Re(r,"passZero");let n=t,o=new Array(e.length).fill(r?n.ZERO:void 0),s=e.reduce((a,c,u)=>n.is0(c)?a:(o[u]=a,n.mul(a,c)),n.ONE),i=n.inv(s);return e.reduceRight((a,c,u)=>n.is0(c)?a:(o[u]=n.mul(a,o[u]),n.mul(a,c)),i),o}function Xr(t,e){xr(t);let r=t;Js(r.ORDER,"FpLegendre");let n=(r.ORDER-Q)/Dt,o=r.pow(e,n),s=r.eql(o,r.ONE),i=r.eql(o,r.ZERO),a=r.eql(o,r.neg(r.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function rh(t,e){if(e!==void 0&&Ys(e),t<=xe)throw new Error("invalid n length: expected positive n, got "+t);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let r=wr(t);if(e!==void 0&&e<r)throw new Error(`invalid n length: expected nBitLength (${e}) >= bitLen(n) (${r})`);let n=e!==void 0?e:r,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}var Xc=new WeakMap,Vn=class{ORDER;BITS;BYTES;isLE;ZERO=xe;ONE=Q;_lengths;_mod;constructor(e,r={}){if(e<=Q)throw new Error("invalid field: expected ORDER > 1, got "+e);let n;this.isLE=!1,r!=null&&typeof r=="object"&&(typeof r.BITS=="number"&&(n=r.BITS),typeof r.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:r.sqrt,enumerable:!0}),typeof r.isLE=="boolean"&&(this.isLE=r.isLE),r.allowedLengths&&(this._lengths=Object.freeze(r.allowedLengths.slice())),typeof r.modFromBytes=="boolean"&&(this._mod=r.modFromBytes));let{nBitLength:o,nByteLength:s}=rh(e,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,Object.freeze(this)}create(e){return de(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return xe<=e&&e<this.ORDER}is0(e){return e===xe}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&Q)===Q}neg(e){return de(-e,this.ORDER)}eql(e,r){return e===r}sqr(e){return de(e*e,this.ORDER)}add(e,r){return de(e+r,this.ORDER)}sub(e,r){return de(e-r,this.ORDER)}mul(e,r){return de(e*r,this.ORDER)}pow(e,r){return ru(e,r,this.ORDER)}div(e,r){return de(e*Zc(r,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,r){return e+r}subN(e,r){return e-r}mulN(e,r){return e*r}inv(e){return Zc(e,this.ORDER)}sqrt(e){let r=Xc.get(this);return r||Xc.set(this,r=eh(this.ORDER)),r(this,e)}toBytes(e){return this.isLE?Gs(e,this.BYTES):Hn(e,this.BYTES)}fromBytes(e,r=!1){X(e);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(e.length<1||!n.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let u=new Uint8Array(o);u.set(e,s?0:u.length-e.length),e=u}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?$t(e):st(e);if(a&&(c=de(c,i)),!r&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return $n(this,e,!0)}cmov(e,r,n){return Re(n,"condition"),n?r:e}};function Er(t,e={}){return Object.freeze(Vn.prototype),new Vn(t,e)}function au(t){if(typeof t!="bigint")throw new Error("field order must be bigint");if(t<=Q)throw new Error("field order must be greater than 1");let e=wr(t-Q);return Math.ceil(e/8)}function Wn(t){let e=au(t);return e+Math.ceil(e/2)}function jn(t,e,r=!1){X(t);let n=t.length,o=au(e),s=Math.max(Wn(e),16);if(n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=r?$t(t):st(t),a=de(i,e-Q)+Q;return r?Gs(a,o):Hn(a,o)}var ri=BigInt(0),Qr=BigInt(1),nh=BigInt(4),ei=16,cu=128,oh=5,uu=2**31;function It(t){let e=t;if(typeof e!="function")throw new TypeError('"Point" expected constructor, got type='+typeof t);Ht(e.fromAffine,"Point.fromAffine"),Ht(e.fromBytes,"Point.fromBytes"),Ht(e.fromHex,"Point.fromHex"),_t(e.BASE,"Point.BASE"),_t(e.ZERO,"Point.ZERO"),xr(e.Fp),xr(e.Fn)}function Yn(t,e){It(t),fu(e,t);let r=$n(t.Fp,e.map(n=>n.Z));return e.map((n,o)=>t.fromAffine(n.toAffine(r[o])))}function sh(t,e,r=1){if(!Number.isSafeInteger(t)||t<r||t>e)throw new Error("invalid window size, expected ["+r+".."+e+"], got W="+t)}function ih(t,e){let r=t*(4*e+128);if(r>uu)throw new Error("invalid window size: table would need ~"+Math.ceil(r/2**20)+" MiB, max "+uu/2**20+" MiB")}function ni(t,e){if(t!==void 0){Ht(t,"randomBytes");try{let r=t(e);if(!Tt(r)||r.length!==e)return}catch{return}return t}}function fu(t,e){qn(t,"points"),t.forEach((r,n)=>{if(!(r instanceof e))throw new Error("invalid point at index "+n)})}function ah(t,e,r){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((n,o)=>{if(!(r===void 0?e.isValid(n):At(n)&&n<r))throw new Error("invalid scalar at index "+o)})}var du=new WeakMap;function ti(t){return du.get(t)||1}function ch(t,e){let r=t.double(),n=[t];for(let o=1;o<e;o++)n.push(n[o-1].add(r));return n}function uh(t,e){let r=2**e,n=r/2,o=BigInt(r-1),s=[];for(;t>ri;){let i=0;t&Qr&&(i=Number(t&o),i>=n&&(i-=r),t-=BigInt(i)),s.push(i),t>>=Qr}return s}function lh(t,e,r){let n=2**e,o=n/2,s=BigInt(n-1),i=BigInt(e),a=[];for(let c=0;c<r;c++){let u=Number(t&s);t>>=i,u>o&&(u-=n,t+=Qr),a.push(u)}if(t!==ri)throw new Error("invalid wnaf");return a}function fh(t,e,r){let n=0;for(let s of r)n=Math.max(n,s.length);let o=t;for(let s=n-1;s>=0;s--){s!==n-1&&(o=o.double());for(let i=0;i<r.length;i++){let a=r[i][s];if(a){let c=e[i][Math.abs(a)-1>>1];o=o.add(a<0?c.negate():c)}}}return o}var Sr=class{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,r){It(e),this.randomBytes=ni(r,ei),this.Point=e,this.BASE=e.BASE,this.ZERO=e.ZERO,this.bits=e.Fn.BITS}buildWnafTable(e,r,n){let o=Math.ceil(n/r)+1,s=2**(r-1),i=[],a=e;for(let c=0;c<o;c++){let u=a;for(let l=0;l<s;l++)i.push(u),u=u.add(a);a=i[i.length-1].double()}return{W:r,bits:n,windows:o,comp:i}}wnafCachedCT(e,r){let{W:n,windows:o,comp:s}=e,i=2**(n-1),a=lh(r,n,o),c=this.ZERO,u=this.BASE;for(let l=0;l<o;l++){let f=a[l],p=l*i,h=Math.abs(f)-1,w=s[p];for(let b=1;b<i;b++)w=b===h?s[p+b]:w;let g=w.negate();f===0?u=u.add(s[p]):c=c.add(f<0?g:w)}return{p:c,f:u}}getWnafPrecomputes(e,r,n,o){let s=this.wnafPrecomputes.get(r),i=s?.find(a=>a.W===e&&a.bits===n);return i||(i=this.buildWnafTable(r,e,n),typeof o=="function"&&(i={...i,comp:o(i.comp)}),s||(s=[],this.wnafPrecomputes.set(r,s)),s.push(i)),i}assertPoint(e){if(!(e instanceof this.Point))throw new TypeError('"point" expected Point instance, got type='+typeof e)}validateMulInput(e,r){if(this.assertPoint(e),!Zs(r,Qr,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(e,r,n,o){let s=ti(e);return s===1?this.fixedWindowCT(e,r,n):this.wnafCachedCT(this.getWnafPrecomputes(s,e,n,o),r)}mulCT(e,r,n){return this.validateMulInput(e,r),this.runCT(e,r,this.bits,n)}mulCTBlinded(e,r,n){if(this.validateMulInput(e,r),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");let o=this.Point.Fn.BITS+cu,s=this.randomBytes(ei);if(!Tt(s)||s.length!==ei)throw new Error("randomBytes returned invalid byte array");s[0]=s[0]&63|128;let i=r+st(s)*this.Point.Fn.ORDER;return this.runCT(e,i,o,n)}fixedWindowCT(e,r,n){let o=oh,s=1<<o,i=Zr(o),a=new Array(s);a[0]=this.ZERO;for(let l=1;l<s;l++)a[l]=a[l-1].add(e);let c=Math.ceil(n/o),u=this.ZERO;for(let l=c-1;l>=0;l--){if(l!==c-1)for(let h=0;h<o;h++)u=u.double();let f=Number(r>>BigInt(l*o)&i),p=a[0];for(let h=1;h<s;h++)p=h===f?a[h]:p;u=u.add(p)}return{p:u,f:u}}shouldBlind(e,r){return this.randomBytes===void 0?!1:r===Qr?!0:e!==this.BASE?!1:(this.baseCanBeBlinded===void 0&&(this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0()),this.baseCanBeBlinded)}mulSecret(e,r,n,o){return this.shouldBlind(e,n)?this.mulCTBlinded(e,r,o):this.mulCT(e,r,o)}mulUnsafe(e,r,n){if(this.assertPoint(e),!At(r))throw new Error("invalid scalar");let o=ti(e);if(o===1||r>=this.Point.Fn.ORDER)return Gn(this.Point,[e],[r],!0);let s=this.getWnafPrecomputes(o,e,this.bits,n);return this.wnafCachedCT(s,r).p}setWindowSize(e,r){this.assertPoint(e),sh(r,this.bits);let n=Math.ceil((this.bits+cu)/r)+1;ih(n*2**(r-1),this.Point.Fp.BYTES),du.set(e,r),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return ti(e)!==1}};function Gn(t,e,r,n=!1){if(It(t),fu(e,t),Re(n,"allowOversized"),ah(r,t.Fn,n?t.Fn.ORDER**nh:void 0),e.length!==r.length)throw new Error("arrays of points and scalars must have equal length");let o=e.map(i=>ch(i,4)),s=r.map(i=>uh(i,4));return fh(t.ZERO,o,s)}function lu(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return xr(e),e}else return Er(t,{isLE:r})}function Zn(t,e,r={},n){if(t!=="weierstrass"&&t!=="edwards")throw new Error('expected curve type "weierstrass" or "edwards"');if(n===void 0&&(n=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);Oe(r);for(let c of["p","n","h"]){let u=e[c];if(!(At(u)&&u!==ri))throw new Error(`CURVE.${c} must be positive bigint`)}let o=lu(e.p,r.Fp,n),s=lu(e.n,r.Fn,n),a=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}function Xn(t,e){return function(n){let o=t(n);return{secretKey:o,publicKey:e(o)}}}var Qn=BigInt(0),Jn=BigInt(1),eo=BigInt(2),dh=BigInt(4),hu=BigInt(8);function hh(t,e,r,n){let o=t.sqr(r),s=t.sqr(n),i=t.add(t.mul(e.a,o),s),a=t.add(t.ONE,t.mul(e.d,t.mul(o,s)));return t.eql(i,a)}function pu(t,e={}){Oe(e,{},{},"extraOpts");let r=e,n=Zn("edwards",t,r,r.FpFnLE),{Fp:o,Fn:s}=n,i=n.CURVE,{h:a}=i;if(Xr(o,i.a)!==1)throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(Xr(o,i.d)!==-1)throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");Oe(r,{},{uvRatio:"function",randomBytes:"function"});let c=r.randomBytes===void 0?Vt:r.randomBytes,u=eo<<BigInt(o.BYTES*8)-Jn;function l(v){if(!o.isOdd)throw new Error("Field does not have .isOdd()");return o.isOdd(v)}let f=r.uvRatio===void 0?(v,m)=>{try{return{isValid:!0,value:o.sqrt(o.div(v,m))}}catch{return{isValid:!1,value:Qn}}}:r.uvRatio;if(!hh(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");let p=o.eql(i.a,o.neg(o.ONE))?v=>o.neg(v):o.eql(i.a,o.ONE)?v=>v:v=>o.mul(i.a,v);function h(v,m,_=!1){let A=_?Jn:Qn;return br("coordinate "+v,m,A,u),m}function w(v){if(!(v instanceof g))throw new Error("EdwardsPoint expected")}class g{static BASE=new g(i.Gx,i.Gy,o.ONE,o.mul(i.Gx,i.Gy));static ZERO=new g(o.ZERO,o.ONE,o.ONE,o.ZERO);static Fp=o;static Fn=s;X;Y;Z;T;constructor(m,_,A,N){this.X=h("x",m),this.Y=h("y",_),this.Z=h("z",A,!0),this.T=h("t",N),Object.freeze(this)}static CURVE(){return i}static fromAffine(m){if(m instanceof g)throw new Error("extended point not allowed");let{x:_,y:A}=m||{};return h("x",_),h("y",A),new g(_,A,o.ONE,o.mul(_,A))}static fromBytes(m,_=!1){let A=o.BYTES,{a:N,d:M}=i;m=Gr(X(m,A,"point")),Re(_,"zip215");let k=Gr(m),B=m[A-1];k[A-1]=B&-129;let O=$t(k),$=_?u:o.ORDER;br("point.y",O,Qn,$);let V=o.sqr(O),ne=o.sub(V,o.ONE),D=o.sub(o.mulN(M,V),N),{isValid:F,value:z}=f(ne,D);if(!F)throw new Error("bad point: invalid y coordinate");let R=l(z),oe=(B&128)!==0;if(!_&&o.is0(z)&&oe)throw new Error("bad point: x=0 and x_0=1");return oe!==R&&(z=o.neg(z)),g.fromAffine({x:z,y:O})}static fromHex(m,_=!1){return g.fromBytes(gr(m),_)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(m=6,_=!0){return x.setWindowSize(this,m),_||this.multiply(eo),this}assertValidity(){let m=this,{a:_,d:A}=i;if(m.is0())throw new Error("bad point: ZERO");let{X:N,Y:M,Z:k,T:B}=m,O=o.sqr(N),$=o.sqr(M),V=o.sqr(k),ne=o.sqr(V),D=o.mul(O,_),F=o.mul(o.add(D,$),V),z=o.add(ne,o.mul(A,o.mul(O,$)));if(!o.eql(F,z))throw new Error("bad point: equation left != right (1)");let R=o.mul(N,M),oe=o.mul(k,B);if(!o.eql(R,oe))throw new Error("bad point: equation left != right (2)")}equals(m){w(m);let{X:_,Y:A,Z:N}=this,{X:M,Y:k,Z:B}=m,O=o.mul(_,B),$=o.mul(M,N),V=o.mul(A,B),ne=o.mul(k,N);return o.eql(O,$)&&o.eql(V,ne)}is0(){return this.equals(g.ZERO)}negate(){return new g(o.neg(this.X),this.Y,this.Z,o.neg(this.T))}double(){let{X:m,Y:_,Z:A}=this,N=o.sqr(m),M=o.sqr(_),k=o.mul(o.sqr(A),eo),B=p(N),O=o.addN(m,_),$=o.sub(o.subN(o.sqr(O),N),M),V=o.addN(B,M),ne=o.subN(V,k),D=o.subN(B,M),F=o.mul($,ne),z=o.mul(V,D),R=o.mul($,D),oe=o.mul(ne,V);return new g(F,z,oe,R)}add(m){w(m);let{d:_}=i,{X:A,Y:N,Z:M,T:k}=this,{X:B,Y:O,Z:$,T:V}=m,ne=o.mul(A,B),D=o.mul(N,O),F=o.mul(o.mulN(k,_),V),z=o.mul(M,$),R=o.sub(o.subN(o.mulN(o.addN(A,N),o.addN(B,O)),ne),D),oe=o.subN(z,F),le=o.addN(z,F),S=o.sub(D,p(ne)),d=o.mul(R,oe),y=o.mul(le,S),E=o.mul(R,S),T=o.mul(oe,le);return new g(d,y,T,E)}subtract(m){return w(m),this.add(m.negate())}multiply(m){if(!s.isValidNot0(m))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:_,f:A}=x.mulSecret(this,m,a,b);return b([_,A])[0]}multiplyUnsafe(m){if(!s.isValid(m))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return m===Qn?g.ZERO:this.is0()||m===Jn?this:x.mulUnsafe(this,m,b)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return x.mulUnsafe(this,i.n).is0()}toAffine(m){let _=this,A=m;if(A!=null&&typeof A!="bigint")throw new TypeError('"invertedZ" expected bigint, got type='+typeof A);let{X:N,Y:M,Z:k}=_,B=_.is0();A==null&&(A=B?o.create(hu):o.inv(k));let O=o.mul(N,A),$=o.mul(M,A),V=o.mul(k,A);if(B)return{x:o.ZERO,y:o.ONE};if(!o.eql(V,o.ONE))throw new Error("invZ was invalid");return{x:O,y:$}}clearCofactor(){return a===Jn?this:a===eo?this.double():a===dh?this.double().double():a===hu?this.double().double().double():this.multiplyUnsafe(a)}toBytes(){let{x:m,y:_}=this.toAffine(),A=o.toBytes(_);return A[A.length-1]|=l(m)?128:0,A}toHex(){return jr(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let b=v=>Yn(g,v),x=new Sr(g,c);return x.bits>=6&&g.BASE.precompute(6),Object.freeze(g.prototype),Object.freeze(g),g}function mu(t,e,r={}){if(It(t),typeof e!="function")throw new Error('"hash" function param is required');let n=e,o=r;Oe(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function",toMontgomery:"function",toMontgomerySecret:"function"});let{prehash:s}=o,{BASE:i,Fp:a,Fn:c}=t,u=n.outputLen,l=2*a.BYTES;if(u!==void 0&&(ft(u,"hash.outputLen"),u!==l))throw new Error(`hash.outputLen must be ${l}, got ${u}`);let f=o.randomBytes===void 0?Vt:o.randomBytes,p=o.toMontgomery,h=o.toMontgomerySecret,w=o.adjustScalarBytes===void 0?D=>D:o.adjustScalarBytes,g=o.domain===void 0?(D,F,z)=>{if(Re(z,"phflag"),F.length||z)throw new Error("Contexts/pre-hash are not supported");return D}:o.domain;function b(D){return c.create($t(D))}function x(D){let F=B.secretKey;X(D,B.secretKey,"secretKey");let z=X(n(D),2*F,"hashedSecretKey"),R=w(z.slice(0,F)),oe=z.slice(F,2*F),le=b(R);return{head:R,prefix:oe,scalar:le}}function v(D){let{head:F,prefix:z,scalar:R}=x(D),oe=i.multiply(R),le=oe.toBytes();return{head:F,prefix:z,scalar:R,point:oe,pointBytes:le}}function m(D){return v(D).pointBytes}function _(D=Uint8Array.of(),...F){let z=$e(...F);return b(n(g(z,X(D,void 0,"context"),!!s)))}function A(D,F,z={}){Oe(z,{},{},"options"),D=Gr(X(D,void 0,"message")),s&&(D=s(D));let{prefix:R,scalar:oe,pointBytes:le}=v(F),S=_(z.context,R,D),d=i.multiply(S).toBytes(),y=_(z.context,d,le,D),E=c.create(S+y*oe);if(!c.isValid(E))throw new Error("sign failed: invalid s");let T=$e(d,c.toBytes(E));return X(T,B.signature,"result")}let N={zip215:o.zip215};function M(D,F,z,R=N){Oe(R);let{context:oe}=R,le=R.zip215===void 0?!!N.zip215:R.zip215,S=B.signature;D=X(D,S,"signature"),F=X(F,void 0,"message"),z=X(z,B.publicKey,"publicKey"),le!==void 0&&Re(le,"zip215"),s&&(F=s(F));let d=S/2,y=D.subarray(0,d),E=$t(D.subarray(d,S)),T,I,C;try{T=t.fromBytes(z,le),I=t.fromBytes(y,le),C=i.multiplyUnsafe(E)}catch{return!1}if(!le&&T.isSmallOrder())return!1;let P=_(oe,y,z,F);return I.add(T.multiplyUnsafe(P)).subtract(C).clearCofactor().is0()}let k=a.BYTES,B={secretKey:k,publicKey:k,signature:2*k,seed:k};function O(D){return D=D===void 0?f(B.seed):D,X(D,B.seed,"seed")}function $(D){return Tt(D)&&D.length===B.secretKey}function V(D,F){try{return!!t.fromBytes(D,F===void 0?N.zip215:F)}catch{return!1}}let ne={getExtendedPublicKey:v,randomSecretKey:O,isValidSecretKey:$,isValidPublicKey:V,toMontgomery(D){if(p===void 0)throw new Error("Montgomery conversion is not supported for this curve");return p(t.fromBytes(D))},toMontgomerySecret(D){if(h===void 0)throw new Error("Montgomery conversion is not supported for this curve");return h(D)}};return Object.freeze(B),Object.freeze(ne),Object.freeze({keygen:Xn(O,m),getPublicKey:m,sign:A,verify:M,utils:ne,Point:t,lengths:B})}var oi=BigInt(1),yu=BigInt(2);var ph=BigInt(5),mh=BigInt(8),si=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),yh={p:si,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:mh,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function gh(t){let e=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),s=si,a=t*t%s*t%s,c=ue(a,yu,s)*a%s,u=ue(c,oi,s)*t%s,l=ue(u,ph,s)*u%s,f=ue(l,e,s)*l%s,p=ue(f,r,s)*f%s,h=ue(p,n,s)*p%s,w=ue(h,o,s)*h%s,g=ue(w,o,s)*h%s,b=ue(g,e,s)*l%s;return{pow_p_5_8:ue(b,yu,s)*t%s,b2:a}}function wu(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}var gu=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function bh(t,e){let r=si,n=de(e*e*e,r),o=de(n*n*e,r),s=gh(t*o).pow_p_5_8,i=de(t*n*s,r),a=de(e*i*i,r),c=i,u=de(i*gu,r),l=a===t,f=a===de(-t,r),p=a===de(-t*gu,r);return l&&(i=c),(f||p)&&(i=u),iu(i,r)&&(i=de(-i,r)),{isValid:l||f,value:i}}var ii=pu(yh,{uvRatio:bh}),bu=ii.Fp;function wh(t){let{y:e}=t;return bu.toBytes(bu.div(oi+e,oi-e))}function xh(t){let e=ii.Fp.BYTES;return Ve(t,e),wu(js(t.subarray(0,e))).subarray(0,e)}function Eh(t){return mu(ii,js,Object.assign({adjustScalarBytes:wu,toMontgomery:wh,toMontgomerySecret:xh,zip215:!0},t))}var xu=Eh({});var Jr=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},to=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var We={get(t=globalThis){let e=t.crypto;if(e?.subtle==null)throw new to("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return e}};var ro=32;var ai,Sh=(async()=>{try{return await We.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function vh(t,e,r){if(t.buffer instanceof ArrayBuffer){let n=await We.get().subtle.importKey("raw",t.buffer,{name:"Ed25519"},!1,["verify"]);return await We.get().subtle.verify({name:"Ed25519"},n,Ie(e),Ie(r instanceof Uint8Array?r:r.subarray()))}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function _h(t,e,r){return xu.verify(e,r instanceof Uint8Array?r:r.subarray(),t)}async function Eu(t,e,r){return ai==null&&(ai=await Sh),ai?vh(t,e,r):_h(t,e,r)}function no(t){return t==null?!1:typeof t.then=="function"&&typeof t.catch=="function"&&typeof t.finally=="function"}var oo=class{type="Ed25519";raw;constructor(e){this.raw=ci(e,ro)}toMultihash(){return Ye.digest(nt(this))}toCID(){return we.createV1(114,this.toMultihash())}toString(){return fe.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:be(this.raw,e.raw)}verify(e,r,n){n?.signal?.throwIfAborted();let o=Eu(this.raw,r,e);return no(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function ui(t){return t=ci(t,ro),new oo(t)}function ci(t,e){if(t=Uint8Array.from(t??[]),t.length!==e)throw new pe(`Key must be a Uint8Array of length ${e}, got ${t.length}`);return t}var Th=Math.pow(2,7),Dh=Math.pow(2,14),Ih=Math.pow(2,21),li=Math.pow(2,28),fi=Math.pow(2,35),di=Math.pow(2,42),hi=Math.pow(2,49),J=128,Ae=127;function Pe(t){if(t<Th)return 1;if(t<Dh)return 2;if(t<Ih)return 3;if(t<li)return 4;if(t<fi)return 5;if(t<di)return 6;if(t<hi)return 7;if(Number.MAX_SAFE_INTEGER!=null&&t>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function vr(t,e,r=0){switch(Pe(t)){case 8:e[r++]=t&255|J,t/=128;case 7:e[r++]=t&255|J,t/=128;case 6:e[r++]=t&255|J,t/=128;case 5:e[r++]=t&255|J,t/=128;case 4:e[r++]=t&255|J,t>>>=7;case 3:e[r++]=t&255|J,t>>>=7;case 2:e[r++]=t&255|J,t>>>=7;case 1:{e[r++]=t&255,t>>>=7;break}default:throw new Error("unreachable")}return e}function Ch(t,e,r=0){switch(Pe(t)){case 8:e.set(r++,t&255|J),t/=128;case 7:e.set(r++,t&255|J),t/=128;case 6:e.set(r++,t&255|J),t/=128;case 5:e.set(r++,t&255|J),t/=128;case 4:e.set(r++,t&255|J),t>>>=7;case 3:e.set(r++,t&255|J),t>>>=7;case 2:e.set(r++,t&255|J),t>>>=7;case 1:{e.set(r++,t&255),t>>>=7;break}default:throw new Error("unreachable")}return e}function pi(t,e){let r=t[e],n=0;if(n+=r&Ae,r<J||(r=t[e+1],n+=(r&Ae)<<7,r<J)||(r=t[e+2],n+=(r&Ae)<<14,r<J)||(r=t[e+3],n+=(r&Ae)<<21,r<J)||(r=t[e+4],n+=(r&Ae)*li,r<J)||(r=t[e+5],n+=(r&Ae)*fi,r<J)||(r=t[e+6],n+=(r&Ae)*di,r<J)||(r=t[e+7],n+=(r&Ae)*hi,r<J))return n;throw new RangeError("Could not decode varint")}function Bh(t,e){let r=t.get(e),n=0;if(n+=r&Ae,r<J||(r=t.get(e+1),n+=(r&Ae)<<7,r<J)||(r=t.get(e+2),n+=(r&Ae)<<14,r<J)||(r=t.get(e+3),n+=(r&Ae)<<21,r<J)||(r=t.get(e+4),n+=(r&Ae)*li,r<J)||(r=t.get(e+5),n+=(r&Ae)*fi,r<J)||(r=t.get(e+6),n+=(r&Ae)*di,r<J)||(r=t.get(e+7),n+=(r&Ae)*hi,r<J))return n;throw new RangeError("Could not decode varint")}function _r(t,e,r=0){return e==null&&(e=_e(Pe(t))),e instanceof Uint8Array?vr(t,e,r):Ch(t,e,r)}function en(t,e=0){return t instanceof Uint8Array?pi(t,e):Bh(t,e)}var yi=new Float32Array([-0]),Ct=new Uint8Array(yi.buffer);function vu(t,e,r){yi[0]=t,e[r]=Ct[0],e[r+1]=Ct[1],e[r+2]=Ct[2],e[r+3]=Ct[3]}function _u(t,e){return Ct[0]=t[e],Ct[1]=t[e+1],Ct[2]=t[e+2],Ct[3]=t[e+3],yi[0]}var gi=new Float64Array([-0]),Te=new Uint8Array(gi.buffer);function Au(t,e,r){gi[0]=t,e[r]=Te[0],e[r+1]=Te[1],e[r+2]=Te[2],e[r+3]=Te[3],e[r+4]=Te[4],e[r+5]=Te[5],e[r+6]=Te[6],e[r+7]=Te[7]}function Tu(t,e){return Te[0]=t[e],Te[1]=t[e+1],Te[2]=t[e+2],Te[3]=t[e+3],Te[4]=t[e+4],Te[5]=t[e+5],Te[6]=t[e+6],Te[7]=t[e+7],gi[0]}var Lh=BigInt(Number.MAX_SAFE_INTEGER),Rh=BigInt(Number.MIN_SAFE_INTEGER),Fe=class t{lo;hi;constructor(e,r){this.lo=e|0,this.hi=r|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let r=~this.lo+1>>>0,n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(r+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let r=~this.lo+1>>>0,n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(BigInt(r)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,r=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?r===0?e<16384?e<128?1:2:e<2097152?3:4:r<16384?r<128?5:6:r<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return Wt;if(e<Lh&&e>Rh)return this.fromNumber(Number(e));let r=e<0n;r&&(e=-e);let n=e>>32n,o=e-(n<<32n);return r&&(n=~n|0n,o=~o|0n,++o>Du&&(o=0n,++n>Du&&(n=0n))),new t(Number(o),Number(n))}static fromNumber(e){if(e===0)return Wt;let r=e<0;r&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return r&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new t(n,o)}static from(e){return typeof e=="number"?t.fromNumber(e):typeof e=="bigint"?t.fromBigInt(e):typeof e=="string"?t.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new t(e.low>>>0,e.high>>>0):Wt}},Wt=new Fe(0,0);Wt.toBigInt=function(){return 0n};Wt.zzEncode=Wt.zzDecode=function(){return this};Wt.length=function(){return 1};var Du=4294967296n;function Iu(t){let e=0,r=0;for(let n=0;n<t.length;++n)r=t.charCodeAt(n),r<128?e+=1:r<2048?e+=2:(r&64512)===55296&&(t.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function Cu(t,e,r){if(r-e<1)return"";let o,s=[],i=0,a;for(;e<r;)a=t[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|t[e++]&63:a>239&&a<365?(a=((a&7)<<18|(t[e++]&63)<<12|(t[e++]&63)<<6|t[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(t[e++]&63)<<6|t[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function bi(t,e,r){let n=r,o,s;for(let i=0;i<t.length;++i)o=t.charCodeAt(i),o<128?e[r++]=o:o<2048?(e[r++]=o>>6|192,e[r++]=o&63|128):(o&64512)===55296&&((s=t.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[r++]=o>>18|240,e[r++]=o>>12&63|128,e[r++]=o>>6&63|128,e[r++]=o&63|128):(e[r++]=o>>12|224,e[r++]=o>>6&63|128,e[r++]=o&63|128);return r-n}function Ze(t,e){return RangeError(`index out of range: ${t.pos} + ${e??1} > ${t.len}`)}function so(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}var wi=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=Ie(e),this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,Ze(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Ze(this,4);return so(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Ze(this,4);return so(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Ze(this,4);let e=_u(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Ze(this,4);let e=Tu(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),r=this.pos,n=this.pos+e;if(n>this.len)throw Ze(this,e);return this.pos+=e,r===n?new Uint8Array(0):this.buf.subarray(r,n)}string(){let e=this.bytes();return Cu(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Ze(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Ze(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new Fe(0,0),r=0;if(this.len-this.pos>4){for(;r<4;++r)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;r=0}else{for(;r<3;++r){if(this.pos>=this.len)throw Ze(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<r*7)>>>0,e}if(this.len-this.pos>4){for(;r<5;++r)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;r<5;++r){if(this.pos>=this.len)throw Ze(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Ze(this,8);let e=so(this.buf,this.pos+=4),r=so(this.buf,this.pos+=4);return new Fe(e,r)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=pi(this.buf,this.pos);return this.pos+=Pe(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function tn(t){return new wi(t instanceof Uint8Array?t:t.subarray())}function Ne(t,e,r){let n=tn(t);return e.decode(n,void 0,r)}function xi(t){let e=t??8192,r=e>>>1,n,o=e;return function(i){if(i<1||i>r)return _e(i);o+i>e&&(n=_e(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var jt=class{fn;len;next;val;constructor(e,r,n){this.fn=e,this.len=r,this.next=void 0,this.val=n}};function Ei(){}var vi=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},Oh=xi();function Ph(t){return globalThis.Buffer!=null?_e(t):Oh(t)}var nn=class{len;head;tail;states;constructor(){this.len=0,this.head=new jt(Ei,0,0),this.tail=this.head,this.states=null}_push(e,r,n){return this.tail=this.tail.next=new jt(e,r,n),this.len+=r,this}uint32(e){return this.len+=(this.tail=this.tail.next=new _i((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(io,10,Fe.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let r=Fe.fromBigInt(e);return this._push(io,r.length(),r)}uint64Number(e){return this._push(vr,Pe(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let r=Fe.fromBigInt(e).zzEncode();return this._push(io,r.length(),r)}sint64Number(e){let r=Fe.fromNumber(e).zzEncode();return this._push(io,r.length(),r)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Si,1,e?1:0)}fixed32(e){return this._push(rn,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let r=Fe.fromBigInt(e);return this._push(rn,4,r.lo)._push(rn,4,r.hi)}fixed64Number(e){let r=Fe.fromNumber(e);return this._push(rn,4,r.lo)._push(rn,4,r.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(vu,4,e)}double(e){return this._push(Au,8,e)}bytes(e){let r=e.length>>>0;return r===0?this._push(Si,1,0):this.uint32(r)._push(kh,r,e)}string(e){let r=Iu(e);return r!==0?this.uint32(r)._push(bi,r,e):this._push(Si,1,0)}fork(){return this.states=new vi(this),this.head=this.tail=new jt(Ei,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 jt(Ei,0,0),this.len=0),this}ldelim(){let e=this.head,r=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=r,this.len+=n),this}finish(){let e=this.head.next,r=Ph(this.len),n=0;for(;e!=null;)e.fn(e.val,r,n),n+=e.len,e=e.next;return r}};function Si(t,e,r){e[r]=t&255}function Nh(t,e,r){for(;t>127;)e[r++]=t&127|128,t>>>=7;e[r]=t}var _i=class extends jt{next;constructor(e,r){super(Nh,e,r),this.next=void 0}};function io(t,e,r){for(;t.hi!==0;)e[r++]=t.lo&127|128,t.lo=(t.lo>>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;t.lo>127;)e[r++]=t.lo&127|128,t.lo=t.lo>>>7;e[r++]=t.lo}function rn(t,e,r){e[r]=t&255,e[r+1]=t>>>8&255,e[r+2]=t>>>16&255,e[r+3]=t>>>24}function kh(t,e,r){e.set(t,r)}globalThis.Buffer!=null&&(nn.prototype.bytes=function(t){let e=t.length>>>0;return this.uint32(e),e>0&&this._push(Uh,e,t),this},nn.prototype.string=function(t){let e=globalThis.Buffer.byteLength(t);return this.uint32(e),e>0&&this._push(Mh,e,t),this});function Uh(t,e,r){e.set(t,r)}function Mh(t,e,r){t.length<40?bi(t,e,r):e.utf8Write!=null?e.utf8Write(t,r):e.set(K(t),r)}function Ai(){return new nn}function ke(t,e){let r=Ai();return e.encode(t,r,{lengthDelimited:!1}),r.finish()}function*Ue(t,e,r){let n=tn(t);yield*e.stream(n,void 0,"$",r)}var ao={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function co(t,e,r,n,o){return{name:t,type:e,encode:r,decode:n,stream:o}}function Yt(t){function e(s){if(t[s.toString()]==null)throw new Error("Invalid enum value");return t[s]}let r=function(i,a){let c=e(i);a.int32(c)},n=function(i){let a=i.int32();return e(a)},o=function*(i){let a=i.int32();yield e(a)};return co("enum",ao.VARINT,r,n,o)}function Me(t,e,r){return co("message",ao.LENGTH_DELIMITED,t,e,r)}var Gt=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var he;(function(t){t.RSA="RSA",t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.ECDSA="ECDSA"})(he||(he={}));var Ti;(function(t){t[t.RSA=0]="RSA",t[t.Ed25519=1]="Ed25519",t[t.secp256k1=2]="secp256k1",t[t.ECDSA=3]="ECDSA"})(Ti||(Ti={}));(function(t){t.codec=()=>Yt(Ti)})(he||(he={}));var it;(function(t){let e;t.codec=()=>(e==null&&(e=Me((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),he.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.Type=he.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.Type`,value:he.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(l&7);break}}}})),e);function r(s){return ke(s,t.codec())}t.encode=r;function n(s,i){return Ne(s,t.codec(),i)}t.decode=n;function o(s,i){return Ue(s,t.codec(),i)}t.stream=o})(it||(it={}));var Di;(function(t){let e;t.codec=()=>(e==null&&(e=Me((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),he.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.Type=he.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.Type`,value:he.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(l&7);break}}}})),e);function r(s){return ke(s,t.codec())}t.encode=r;function n(s,i){return Ne(s,t.codec(),i)}t.decode=n;function o(s,i){return Ue(s,t.codec(),i)}t.stream=o})(Di||(Di={}));var sn={};Ce(sn,{MAX_RSA_KEY_SIZE:()=>Ii,generateRSAKeyPair:()=>Nu,jwkToJWKKeyPair:()=>ku,jwkToPkcs1:()=>zh,jwkToPkix:()=>Ri,jwkToRSAPrivateKey:()=>ki,pkcs1MessageToJwk:()=>Bi,pkcs1MessageToRSAPrivateKey:()=>Oi,pkcs1ToJwk:()=>qh,pkcs1ToRSAPrivateKey:()=>Pu,pkixMessageToJwk:()=>Li,pkixMessageToRSAPublicKey:()=>Ni,pkixToJwk:()=>Hh,pkixToRSAPublicKey:()=>Pi});var Ar=class{type="RSA";jwk;_raw;_multihash;constructor(e,r){this.jwk=e,this._multihash=r}get raw(){return this._raw==null&&(this._raw=sn.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return we.createV1(114,this._multihash)}toString(){return fe.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:be(this.raw,e.raw)}verify(e,r,n){return Ou(this.jwk,r,e,n)}},on=class{type="RSA";jwk;_raw;publicKey;constructor(e,r){this.jwk=e,this.publicKey=r}get raw(){return this._raw==null&&(this._raw=sn.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:be(this.raw,e.raw)}sign(e,r){return Ru(this.jwk,e,r)}};var Ii=8192,Ci=18,Fh=1062,Kh=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function qh(t){let e=ut(t);return Bi(e)}function Bi(t){return{n:j(t[1],"base64url"),e:j(t[2],"base64url"),d:j(t[3],"base64url"),p:j(t[4],"base64url"),q:j(t[5],"base64url"),dp:j(t[6],"base64url"),dq:j(t[7],"base64url"),qi:j(t[8],"base64url"),kty:"RSA"}}function zh(t){if(t.n==null||t.e==null||t.d==null||t.p==null||t.q==null||t.dp==null||t.dq==null||t.qi==null)throw new pe("JWK was missing components");return xt([Le(Uint8Array.from([0])),Le(K(t.n,"base64url")),Le(K(t.e,"base64url")),Le(K(t.d,"base64url")),Le(K(t.p,"base64url")),Le(K(t.q,"base64url")),Le(K(t.dp,"base64url")),Le(K(t.dq,"base64url")),Le(K(t.qi,"base64url"))]).subarray()}function Hh(t){let e=ut(t,{offset:0});return Li(e)}function Li(t){let e=ut(t[1],{offset:0});return{kty:"RSA",n:j(e[0],"base64url"),e:j(e[1],"base64url")}}function Ri(t){if(t.n==null||t.e==null)throw new pe("JWK was missing components");return xt([Kh,Rn(xt([Le(K(t.n,"base64url")),Le(K(t.e,"base64url"))]))]).subarray()}function Pu(t){let e=ut(t);return Oi(e)}function Oi(t){let e=Bi(t);return ki(e)}function Pi(t,e){if(t.byteLength>=Fh)throw new ir("Key size is too large");let r=ut(t,{offset:0});return Ni(r,t,e)}function Ni(t,e,r){let n=Li(t);if(r==null){let o=yr(it.encode({Type:he.RSA,Data:e}));r=et(Ci,o)}return new Ar(n,r)}function ki(t){if(Mu(t)>Ii)throw new pe("Key size is too large");let e=ku(t),r=yr(it.encode({Type:he.RSA,Data:Ri(e.publicKey)})),n=et(Ci,r);return new on(e.privateKey,new Ar(e.publicKey,n))}async function Nu(t){if(t>Ii)throw new pe("Key size is too large");let e=await Uu(t),r=yr(it.encode({Type:he.RSA,Data:Ri(e.publicKey)})),n=et(Ci,r);return new on(e.privateKey,new Ar(e.publicKey,n))}function ku(t){if(t==null)throw new pe("Missing key parameter");return{privateKey:t,publicKey:{kty:t.kty,n:t.n,e:t.e}}}async function Uu(t,e){let r=await We.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:t,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);e?.signal?.throwIfAborted();let n=await Vh(r,e);return{privateKey:n[0],publicKey:n[1]}}async function Ru(t,e,r){let n=await We.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);r?.signal?.throwIfAborted();let o=await We.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,Ie(e instanceof Uint8Array?e:e.subarray()));return r?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function Ou(t,e,r,n){let o=await We.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let s=await We.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,Ie(e),Ie(r instanceof Uint8Array?r:r.subarray()));return n?.signal?.throwIfAborted(),s}async function Vh(t,e){if(t.privateKey==null||t.publicKey==null)throw new pe("Private and public key are required");let r=await Promise.all([We.get().subtle.exportKey("jwk",t.privateKey),We.get().subtle.exportKey("jwk",t.publicKey)]);return e?.signal?.throwIfAborted(),r}function Mu(t){if(t.kty!=="RSA")throw new pe("invalid key type");if(t.n==null)throw new pe("invalid key modulus");return K(t.n,"base64url").length*8}var uo=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,r){if(Nn(e),Ve(r,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("expected Hash instance");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(r.length>n?e.create().update(r).digest():r);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),zt(o)}update(e){return mr(this),this.iHash.update(e),this}digestInto(e){mr(this),kn(e,this),this.finished=!0;let r=e.subarray(0,this.outputLen);this.iHash.digestInto(r),this.oHash.update(r),this.oHash.digestInto(r),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:r,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a,canXOF:c}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.canXOF=c,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Fu=(()=>{let t=((e,r,n)=>new uo(e,r).update(n).digest());return t.create=(e,r)=>new uo(e,r),t})();var $h=BigInt(0),Ui=class extends Error{constructor(e=""){super(e)}},dt={Err:Ui,_tlv:{encode:(t,e)=>{let{Err:r}=dt;if(ft(t,"tag"),t<0||t>255)throw new r("tlv.encode: wrong tag");if(jc(e,"data"),e.length&1)throw new r("tlv.encode: unpadded data");let n=e.length/2,o=Yr(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");let s=n>127?Yr(o.length/2|128):"";return Yr(t)+s+o+e},decode(t,e){let{Err:r}=dt;e=X(e,void 0,"DER data");let n=0;if(t<0||t>255)throw new r("tlv.decode: wrong tag");if(e.length<2||e[n++]!==t)throw new r("tlv.decode: wrong tlv");let o=e[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let u=e.subarray(n,n+c);if(u.length!==c)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let l of u)i=i<<8|l;if(n+=c,i<128)throw new r("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(t){let{Err:e}=dt;if(zn(t),t<$h)throw new e("integer: negative integers are not allowed");let r=Yr(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){let{Err:e}=dt;if(t.length<1)throw new e("invalid signature integer: empty");if(t[0]&128)throw new e("invalid signature integer: negative");if(t.length>1&&t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return st(t)}},toSig(t,e){let{Err:r,_int:n,_tlv:o}=dt;if(e!==void 0&&(ft(e,"maxScalarBytes"),e<1))throw new r("invalid signature: maxScalarBytes must be positive");let s=X(t,void 0,"signature"),{v:i,l:a}=o.decode(48,s);if(a.length)throw new r("invalid signature: left bytes after parsing");let{v:c,l:u}=o.decode(2,i),{v:l,l:f}=o.decode(2,u);if(f.length)throw new r("invalid signature: left bytes after parsing");if(e!==void 0&&(c.length>e||l.length>e))throw new r("invalid signature: integer too large");return{r:n.decode(c),s:n.decode(l)}},hexFromSig(t){let{_tlv:e,_int:r}=dt;Oe(t,{r:"bigint",s:"bigint"},{},"sig");let n=e.encode(2,r.encode(t.r)),o=e.encode(2,r.encode(t.s)),s=n+o;return e.encode(48,s)}},lo=(Object.freeze(dt._tlv),Object.freeze(dt._int),Object.freeze(dt));var Ku=(t,e)=>(t+(t>=0?e:-e)/qu)/e;function Wh(t,e,r){br("scalar",t,ht,r);let[[n,o],[s,i]]=e,a=Ku(i*t,r),c=Ku(-o*t,r),u=t-a*n-c*s,l=-a*o-c*i,f=u<ht,p=l<ht;f&&(u=-u),p&&(l=-l);let h=Zr(Math.ceil(wr(r)/2))+Zt;if(u<ht||u>=h||l<ht||l>=h)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:f,k1:u,k2neg:p,k2:l}}function Ki(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Mi(t,e){Oe(t);let r={};for(let n of Object.keys(e))r[n]=t[n]===void 0?e[n]:t[n];return Re(r.lowS,"lowS"),Re(r.prehash,"prehash"),r.format!==void 0&&Ki(r.format),r}var ht=BigInt(0),Zt=BigInt(1),qu=BigInt(2),Fi=BigInt(3),jh=BigInt(4);function zu(t,e={}){let r=Zn("weierstrass",t,e),n=r.Fp,o=r.Fn,s=r.CURVE,{h:i,n:a}=s;Oe(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",randomBytes:"function"});let{endo:c,allowInfinityPoint:u,clearCofactor:l,isTorsionFree:f,fromBytes:p,toBytes:h}=e,w=e.randomBytes===void 0?Vt:e.randomBytes;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 g=c?{beta:c.beta,basises:c.basises.map(S=>[...S])}:void 0,b=Vu(n,o);function x(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function v(S,d,y){if(d.is0()){if(!u)throw new Error("bad point: ZERO");return Uint8Array.of(0)}let{x:E,y:T}=d.toAffine(),I=n.toBytes(E);if(Re(y,"isCompressed"),y){x();let C=!n.isOdd(T);return $e(Hu(C),I)}else return $e(Uint8Array.of(4),I,n.toBytes(T))}function m(S){X(S,void 0,"Point");let{publicKey:d,publicKeyUncompressed:y}=b,E=S.length,T=S[0],I=S.subarray(1);if(u&&E===1&&T===0)return{x:n.ZERO,y:n.ZERO};if(E===d&&(T===2||T===3)){let C=n.fromBytes(I);if(!n.isValid(C))throw new Error("bad point: is not on curve, wrong x");let P=k(C),U;try{U=n.sqrt(P)}catch(ye){let se=ye instanceof Error?": "+ye.message:"";throw new Error("bad point: is not on curve, sqrt error"+se)}x();let Z=n.isOdd(U);return(T&1)===1!==Z&&(U=n.neg(U)),{x:C,y:U}}else if(E===y&&T===4){let C=n.BYTES,P=n.fromBytes(I.subarray(0,C)),U=n.fromBytes(I.subarray(C,C*2));if(!B(P,U))throw new Error("bad point: is not on curve");return{x:P,y:U}}else throw new Error(`bad point: got length ${E}, expected compressed=${d} or uncompressed=${y}`)}let _=h===void 0?v:h,A=p===void 0?m:p,N=n.mul(s.b,Fi),M=n.is0(s.a)?S=>n.ZERO:S=>n.mul(s.a,S);function k(S){let d=n.sqr(S),y=n.mul(d,S);return n.add(n.add(y,n.mul(S,s.a)),s.b)}function B(S,d){let y=n.sqr(d),E=k(S);return n.eql(y,E)}if(!B(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let O=n.mul(n.pow(s.a,Fi),jh),$=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(O,$)))throw new Error("bad curve params: a or b");function V(S,d,y=!1){if(!n.isValid(d)||y&&n.is0(d))throw new Error(`bad point coordinate ${S}`);return typeof d=="object"&&d!==null?n.create(d):d}function ne(S){if(!(S instanceof R))throw new Error("Weierstrass Point expected")}function D(S){if(!g||!g.basises)throw new Error("no endo");return Wh(S,g.basises,o.ORDER)}function F(S,d,y,E){if(!o.isValid(E))throw new RangeError("invalid scalar: out of range");if(g){let{k1neg:T,k1:I,k2neg:C,k2:P}=D(E),U=new R(n.mul(y.X,g.beta),y.Y,y.Z);S.push(T?y.negate():y,C?U.negate():U),d.push(I,P)}else S.push(y),d.push(E)}let z=new WeakSet;class R{static BASE=new R(s.Gx,s.Gy,n.ONE);static ZERO=new R(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(d,y,E){this.X=V("x",d),this.Y=V("y",y,!0),this.Z=V("z",E),Object.freeze(this)}static CURVE(){return s}static fromAffine(d){let{x:y,y:E}=d||{};if(!d||!n.isValid(y)||!n.isValid(E))throw new Error("invalid affine point");if(d instanceof R)throw new Error("projective point not allowed");return n.is0(y)&&n.is0(E)?R.ZERO:new R(y,E,n.ONE)}static fromBytes(d){let y=R.fromAffine(A(X(d,void 0,"point")));return y.assertValidity(),y}static fromHex(d){return R.fromBytes(gr(d))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(d=6,y=!0){return le.setWindowSize(this,d),y||this.multiply(Fi),this}assertValidity(){let d=this;if(d.is0()){if(u&&n.is0(d.X)&&n.eql(d.Y,n.ONE)&&n.is0(d.Z))return;throw new Error("bad point: ZERO")}if(z.has(d))return;let{x:y,y:E}=d.toAffine();if(!n.isValid(y)||!n.isValid(E))throw new Error("bad point: x or y not field elements");if(!B(y,E))throw new Error("bad point: equation left != right");if(!d.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");z.add(d)}hasEvenY(){let{y:d}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(d)}equals(d){ne(d);let{X:y,Y:E,Z:T}=this,{X:I,Y:C,Z:P}=d,U=n.eql(n.mul(y,P),n.mul(I,T)),Z=n.eql(n.mul(E,P),n.mul(C,T));return U&&Z}negate(){return new R(this.X,n.neg(this.Y),this.Z)}double(){let{X:d,Y:y,Z:E}=this,T=n.ZERO,I=n.ZERO,C=n.ZERO,P=n.mul(d,d),U=n.mul(y,y),Z=n.mul(E,E),W=n.mul(d,y);return W=n.add(W,W),C=n.mul(d,E),C=n.add(C,C),T=M(C),I=n.mul(N,Z),I=n.add(T,I),T=n.sub(U,I),I=n.add(U,I),I=n.mul(T,I),T=n.mul(W,T),C=n.mul(N,C),Z=M(Z),W=n.sub(P,Z),W=M(W),W=n.add(W,C),C=n.add(P,P),P=n.add(C,P),P=n.add(P,Z),P=n.mul(P,W),I=n.add(I,P),Z=n.mul(y,E),Z=n.add(Z,Z),P=n.mul(Z,W),T=n.sub(T,P),C=n.mul(Z,U),C=n.add(C,C),C=n.add(C,C),new R(T,I,C)}add(d){ne(d);let{X:y,Y:E,Z:T}=this,{X:I,Y:C,Z:P}=d,U=n.ZERO,Z=n.ZERO,W=n.ZERO,ye=n.mul(y,I),se=n.mul(E,C),Ee=n.mul(T,P),ze=n.add(y,E),ie=n.add(I,C);ze=n.mul(ze,ie),ie=n.add(ye,se),ze=n.sub(ze,ie),ie=n.add(y,T);let ge=n.add(I,P);return ie=n.mul(ie,ge),ge=n.add(ye,Ee),ie=n.sub(ie,ge),ge=n.add(E,T),U=n.add(C,P),ge=n.mul(ge,U),U=n.add(se,Ee),ge=n.sub(ge,U),W=M(ie),U=n.mul(N,Ee),W=n.add(U,W),U=n.sub(se,W),W=n.add(se,W),Z=n.mul(U,W),se=n.add(ye,ye),se=n.add(se,ye),Ee=M(Ee),ie=n.mul(N,ie),se=n.add(se,Ee),Ee=n.sub(ye,Ee),Ee=M(Ee),ie=n.add(ie,Ee),ye=n.mul(se,ie),Z=n.add(Z,ye),ye=n.mul(ge,ie),U=n.mul(ze,U),U=n.sub(U,ye),ye=n.mul(ze,se),W=n.mul(ge,W),W=n.add(W,ye),new R(U,Z,W)}subtract(d){return ne(d),this.add(d.negate())}is0(){return this.equals(R.ZERO)}multiply(d){if(!o.isValidNot0(d))throw new RangeError("invalid scalar: out of range");let{p:y,f:E}=le.mulSecret(this,d,i,oe);return oe([y,E])[0]}multiplyUnsafe(d){let y=this,E=d;if(!o.isValid(E))throw new RangeError("invalid scalar: out of range");if(E===ht||y.is0())return R.ZERO;if(E===Zt)return y;if(le.hasWindowSize(this))return le.mulUnsafe(y,E,oe);let T=[],I=[];return F(T,I,y,E),Gn(R,T,I)}mulAddUnsafe(d,y,E){ne(y);let T=[],I=[];return F(T,I,this,d),F(T,I,y,E),Gn(R,T,I)}toAffine(d){let y=this,E=d;if(E!=null&&!n.isValid(E))throw new RangeError('"invertedZ" expected valid field element');let{X:T,Y:I,Z:C}=y;if(n.eql(C,n.ONE))return{x:T,y:I};let P=y.is0();E==null&&(E=P?n.ONE:n.inv(C));let U=n.mul(T,E),Z=n.mul(I,E),W=n.mul(C,E);if(P)return{x:n.ZERO,y:n.ZERO};if(!n.eql(W,n.ONE))throw new Error("invZ was invalid");return{x:U,y:Z}}isTorsionFree(){return i===Zt?!0:f?f(R,this):le.mulUnsafe(this,a).is0()}clearCofactor(){return i===Zt?this:l?l(R,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===Zt?this.is0():this.clearCofactor().is0()}toBytes(d=!0){return Re(d,"isCompressed"),this.assertValidity(),_(R,this,d)}toHex(d=!0){return jr(this.toBytes(d))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let oe=S=>Yn(R,S),le=new Sr(R,w);return le.bits>=6&&R.BASE.precompute(6),Object.freeze(R.prototype),Object.freeze(R),R}function Hu(t){return Uint8Array.of(t?2:3)}function Vu(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Yh(t,e={}){It(t);let{Fn:r}=t,n=e.randomBytes===void 0?Vt:e.randomBytes,o=Object.assign(Vu(t.Fp,r),{seed:Math.max(Wn(r.ORDER),16)});function s(h){try{let w=r.fromBytes(h);return r.isValidNot0(w)}catch{return!1}}function i(h,w){let{publicKey:g,publicKeyUncompressed:b}=o;try{let x=h.length;return w===!0&&x!==g||w===!1&&x!==b?!1:!t.fromBytes(h).is0()}catch{return!1}}function a(h){return h=h===void 0?n(o.seed):h,jn(X(h,o.seed,"seed"),r.ORDER)}function c(h,w=!0){return t.BASE.multiply(r.fromBytes(h)).toBytes(w)}function u(h){let{secretKey:w,publicKey:g,publicKeyUncompressed:b}=o,x=r._lengths;if(!Tt(h))return;let v=X(h,void 0,"key").length,m=v===g||v===b,_=v===w||!!x?.includes(v);if(!(m&&_))return m}function l(h,w,g=!0){if(u(h)===!0)throw new Error("first arg must be private key");if(u(w)===!1)throw new Error("second arg must be public key");let b=r.fromBytes(h),x=t.fromBytes(w);if(x.is0())throw new Error("invalid public key: point at infinity");return x.multiply(b).toBytes(g)}let f={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},p=Xn(a,c);return Object.freeze(f),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:l,keygen:p,Point:t,utils:f,lengths:o})}function $u(t,e,r={}){It(t);let n=e;Nn(n),Oe(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let o=Object.assign({},r),s=o.randomBytes===void 0?Vt:o.randomBytes,i=o.hmac===void 0?(S,d)=>Fu(n,S,d):o.hmac,{Fp:a,Fn:c}=t,{ORDER:u,BITS:l}=c,f=Wn(u),p=ni(s,f),{keygen:h,getPublicKey:w,getSharedSecret:g,utils:b,lengths:x}=Yh(t,o),v={prehash:!0,lowS:typeof o.lowS=="boolean"?o.lowS:!0,format:"compact",extraEntropy:!1},m=u*qu+Zt<a.ORDER;function _(S){let d=u>>Zt;return S>d}function A(S,d){if(!c.isValidNot0(d))throw new Error(`invalid signature ${S}: out of range 1..Point.Fn.ORDER`);return d}function N(){if(!a.isOdd)throw new Error("Field doesn't support isOdd")}function M(S,d,y){return N(),(S===y?0:2)|Number(a.isOdd(d))}function k(){if(m)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function B(S,d){Ki(d);let y=x.signature,E=d==="compact"?y:d==="recovered"?y+1:void 0;return X(S,E)}class O{r;s;recovery;constructor(d,y,E){if(this.r=A("r",d),this.s=A("s",y),E!=null){if(k(),![0,1,2,3].includes(E))throw new Error("invalid recovery id");this.recovery=E}Object.freeze(this)}static fromBytes(d,y=v.format){B(d,y);let E;if(y==="der"){if(d.length>2*c.BYTES+16)throw new lo.Err("invalid signature: DER signature too long");let{r:P,s:U}=lo.toSig(X(d),c.BYTES+1);return new O(P,U)}y==="recovered"&&(E=d[0],y="compact",d=d.subarray(1));let T=x.signature/2,I=d.subarray(0,T),C=d.subarray(T,T*2);return new O(c.fromBytes(I),c.fromBytes(C),E)}static fromHex(d,y){return this.fromBytes(gr(d),y)}assertRecovery(){let{recovery:d}=this;if(d==null)throw new Error("invalid recovery id: must be present");return d}addRecoveryBit(d){return new O(this.r,this.s,d)}recoverPublicKey(d){let{r:y,s:E}=this,T=this.assertRecovery(),I=T===2||T===3?y+u:y;if(!a.isValid(I))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let C=a.toBytes(I),P=t.fromBytes($e(Hu((T&1)===0),C)),U=c.inv(I),Z=V(X(d,void 0,"msgHash")),W=c.create(-Z*U),ye=c.create(E*U),se=t.BASE.mulAddUnsafe(W,P,ye);if(se.is0())throw new Error("invalid recovery: point at infinify");return se.assertValidity(),se}hasHighS(){return _(this.s)}toBytes(d=v.format){if(Ki(d),d==="der")return gr(lo.hexFromSig(this));let{r:y,s:E}=this,T=c.toBytes(y),I=c.toBytes(E);return d==="recovered"?(k(),$e(Uint8Array.of(this.assertRecovery()),T,I)):$e(T,I)}toHex(d){return jr(this.toBytes(d))}}Object.freeze(O.prototype),Object.freeze(O);let $=o.bits2int===void 0?function(d){if(d.length>8192)throw new Error("input is too large");let y=st(d),E=d.length*8-l;return E>0?y>>BigInt(E):y}:o.bits2int,V=o.bits2int_modN===void 0?function(d){return c.create($(d))}:o.bits2int_modN,ne=Zr(l);function D(S){return br("num < 2^"+l,S,ht,ne),c.toBytes(S)}function F(S,d){return X(S,void 0,"message"),d?X(n(S),void 0,"prehashed message"):S}function z(S,d,y){let{lowS:E,prehash:T,extraEntropy:I}=Mi(y,v);S=F(S,T);let C=V(S),P=c.fromBytes(d);if(!c.isValidNot0(P))throw new Error("invalid private key");let U=[D(P),D(C)];if(I!=null&&I!==!1){let se=I===!0?s(x.secretKey):I;U.push(X(se,void 0,"extraEntropy"))}let Z=$e(...U),W=C;function ye(se){let Ee=$(se);if(!c.isValidNot0(Ee))return;let ze=t.BASE.multiply(Ee).toAffine(),ie=c.create(ze.x);if(ie===ht)return;let ge;if(p!==void 0){let kr=st(jn(p(f),u)),tf=c.inv(c.mul(kr,Ee)),rf=c.mul(kr,W),nf=c.mul(kr,P);ge=c.create(tf*c.create(rf+nf*ie))}else{let kr=nu(Ee,u);ge=c.create(kr*c.create(W+ie*P))}if(ge===ht)return;let os=M(ze.x,ze.y,ie),Va=ge;return E&&_(ge)&&(Va=c.neg(ge),os^=1),new O(ie,Va,m?void 0:os)}return{seed:Z,k2sig:ye}}function R(S,d,y={}){let{seed:E,k2sig:T}=z(S,d,y);return Gc(n.outputLen,c.BYTES,i)(E,T).toBytes(y.format)}function oe(S,d,y,E={}){let{lowS:T,prehash:I,format:C}=Mi(E,v);if(y=X(y,void 0,"publicKey"),d=F(d,I),!Tt(S)){let P=S instanceof O?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+P)}B(S,C);try{let P=O.fromBytes(S,C),U=t.fromBytes(y);if(U.is0()||T&&P.hasHighS())return!1;let{r:Z,s:W}=P,ye=V(d),se=c.inv(W),Ee=c.create(ye*se),ze=c.create(Z*se),ie=t.BASE.mulAddUnsafe(Ee,U,ze);if(ie.is0())return!1;let ge=ie.toAffine();return!(c.create(ge.x)!==Z||C==="recovered"&&P.recovery!==M(ge.x,ge.y,Z))}catch{return!1}}function le(S,d,y={}){let{prehash:E}=Mi(y,v);return d=F(d,E),O.fromBytes(S,"recovered").recoverPublicKey(d).toBytes()}return Object.freeze({keygen:h,getPublicKey:w,getSharedSecret:g,utils:b,lengths:x,Point:t,sign:R,verify:oe,recoverPublicKey:le,Signature:O,hash:n})}var zi={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Gh={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Wu=BigInt(2);function Zh(t){let e=zi.p,r=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=t*t*t%e,l=u*u*t%e,f=ue(l,r,e)*l%e,p=ue(f,r,e)*l%e,h=ue(p,Wu,e)*u%e,w=ue(h,o,e)*h%e,g=ue(w,s,e)*w%e,b=ue(g,a,e)*g%e,x=ue(b,c,e)*b%e,v=ue(x,a,e)*g%e,m=ue(v,r,e)*l%e,_=ue(m,i,e)*w%e,A=ue(_,n,e)*u%e,N=ue(A,Wu,e);if(!qi.eql(qi.sqr(N),t))throw new Error("Cannot find square root");return N}var qi=Er(zi.p,{sqrt:Zh}),Xh=zu(zi,{Fp:qi,endo:Gh}),Tr=$u(Xh,yr);function ju(t,e,r,n){let o=hr.digest(r instanceof Uint8Array?r:r.subarray());if(no(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),Tr.verify(e,s,t,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new Jr(String(s))});try{return n?.signal?.throwIfAborted(),Tr.verify(e,o.digest,t,{prehash:!1,format:"der"})}catch(s){throw new Jr(String(s))}}var fo=class{type="secp256k1";raw;_key;constructor(e){this._key=Gu(e),this.raw=Yu(this._key)}toMultihash(){return Ye.digest(nt(this))}toCID(){return we.createV1(114,this.toMultihash())}toString(){return fe.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:be(this.raw,e.raw)}verify(e,r,n){return ju(this._key,r,e,n)}};function Hi(t){return new fo(t)}function Yu(t){return Tr.Point.fromBytes(t).toBytes()}function Gu(t){try{return Tr.Point.fromBytes(t),t}catch(e){throw new ir(String(e))}}function Zu(t,e){let{Type:r,Data:n}=it.decode(t),o=n??new Uint8Array;switch(r){case he.RSA:return Pi(o,e);case he.Ed25519:return ui(o);case he.secp256k1:return Hi(o);case he.ECDSA:return ks(o);default:throw new ar}}function Xu(t){let{Type:e,Data:r}=it.decode(t.digest),n=r??new Uint8Array;switch(e){case he.Ed25519:return ui(n);case he.secp256k1:return Hi(n);case he.ECDSA:return ks(n);default:throw new ar}}function nt(t){return it.encode({Type:he[t.type],Data:t.raw})}var Qu=Symbol.for("nodejs.util.inspect.custom"),Qh=114,an=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[as]=!0;toString(){return this.string==null&&(this.string=fe.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return we.createV1(Qh,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return be(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return be(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Qu](){return`PeerId(${this.toString()})`}},ho=class extends an{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},po=class extends an{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},mo=class extends an{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},Jh=2336,cn=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Ye.digest(K(this.url))}[Qu](){return`PeerId(${this.url})`}[as]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return we.createV1(Jh,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=j(e)),e.toString()===this.toString())}};var ep=114,Ju=2336;function Vi(t,e){let r;if(t.charAt(0)==="1"||t.charAt(0)==="Q")r=tt(fe.decode(`z${t}`));else{if(t.startsWith("k51qzi5uqu5")||t.startsWith("kzwfwjn5ji4")||t.startsWith("k2k4r8")||t.startsWith("bafz"))return tp(we.parse(t));if(e==null)throw new pe('Please pass a multibase decoder for strings that do not start with "1" or "Q"');r=tt(e.decode(t))}return Dr(r)}function Dr(t){if(np(t))return new ho({multihash:t});if(rp(t))try{let e=Xu(t);if(e.type==="Ed25519")return new po({multihash:t,publicKey:e});if(e.type==="secp256k1")return new mo({multihash:t,publicKey:e})}catch{let r=j(t.digest);return new cn(new URL(r))}throw new vn("Supplied PeerID Multihash is invalid")}function tp(t){if(t?.multihash==null||t.version==null||t.version===1&&t.code!==ep&&t.code!==Ju)throw new Sn("Supplied PeerID CID is invalid");if(t.code===Ju){let e=j(t.multihash.digest);return new cn(new URL(e))}return Dr(t.multihash)}function rp(t){return t.code===Ye.code}function np(t){return t.code===hr.code}var un;(function(t){let e;t.codec=()=>(e==null&&(e=Me((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.publicKey!=null&&s.publicKey.byteLength>0&&(i.uint32(10),i.bytes(s.publicKey)),s.payloadType!=null&&s.payloadType.byteLength>0&&(i.uint32(18),i.bytes(s.payloadType)),s.payload!=null&&s.payload.byteLength>0&&(i.uint32(26),i.bytes(s.payload)),s.signature!=null&&s.signature.byteLength>0&&(i.uint32(42),i.bytes(s.signature)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={publicKey:ae(0),payloadType:ae(0),payload:ae(0),signature:ae(0)},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.publicKey=s.bytes();break}case 2:{c.payloadType=s.bytes();break}case 3:{c.payload=s.bytes();break}case 5:{c.signature=s.bytes();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.publicKey`,value:s.bytes()};break}case 2:{yield{field:`${a}.payloadType`,value:s.bytes()};break}case 3:{yield{field:`${a}.payload`,value:s.bytes()};break}case 5:{yield{field:`${a}.signature`,value:s.bytes()};break}default:{s.skipType(l&7);break}}}})),e);function r(s){return ke(s,t.codec())}t.encode=r;function n(s,i){return Ne(s,t.codec(),i)}t.decode=n;function o(s,i){return Ue(s,t.codec(),i)}t.stream=o})(un||(un={}));var yo=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var ln=class t{static createFromProtobuf=e=>{let r=un.decode(e),n=Zu(r.publicKey);return new t({publicKey:n,payloadType:r.payloadType,payload:r.payload,signature:r.signature})};static seal=async(e,r,n)=>{if(r==null)throw new Error("Missing private key");let o=e.domain,s=e.codec,i=e.marshal(),a=el(o,s,i),c=await r.sign(a.subarray(),n);return new t({publicKey:r.publicKey,payloadType:s,payload:i,signature:c})};static openAndCertify=async(e,r,n)=>{let o=t.createFromProtobuf(e);if(!await o.validate(r,n))throw new yo("Envelope signature is not valid for the given domain");return o};publicKey;payloadType;payload;signature;marshaled;constructor(e){let{publicKey:r,payloadType:n,payload:o,signature:s}=e;this.publicKey=r,this.payloadType=n,this.payload=o,this.signature=s}marshal(){return this.marshaled==null&&(this.marshaled=un.encode({publicKey:nt(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return e==null?!1:be(this.marshal(),e.marshal())}async validate(e,r){let n=el(e,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,r)}},el=(t,e,r)=>{let n=K(t),o=_r(n.byteLength),s=_r(e.length),i=_r(r.length);return new ce(o,n,s,e,i,r)};var ve=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},pt=class extends Error{static name="ValidationError";name="ValidationError"},go=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},bo=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var wo=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let r=this.index,n=e();return n===void 0&&(this.index=r),n}parseWith(e){let r=e();if(this.index===this.input.length)return r}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let r=this.readChar();if(r===e)return r})}readSeparator(e,r,n){return this.readAtomically(()=>{if(!(r>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,r,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*o)-1;for(;;){let l=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let p=Number.parseInt(f,e);if(!Number.isNaN(p))return p});if(l===void 0)break;if(s*=e,s+=l,s>u||(i+=1,r!==void 0&&i>r))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let r=0;r<e.length;r++){let n=this.readSeparator(".",r,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[r]=n}return e})}readIPv6Addr(){let e=r=>{for(let n=0;n<r.length/2;n++){let o=n*2;if(n<r.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return r[o]=i[0],r[o+1]=i[1],r[o+2]=i[2],r[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];r[o]=s>>8,r[o+1]=s&255}return[r.length,!1]};return this.readAtomically(()=>{let r=new Uint8Array(16),[n,o]=e(r);if(n===16)return r;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return r.set(s.subarray(0,a),16-a),r})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var op=45,sp=15,xo=new wo;function tl(t){if(!(t.length>sp))return xo.new(t).parseWith(()=>xo.readIPv4Addr())}function rl(t){if(t.includes("%")&&(t=t.split("%")[0]),!(t.length>op))return xo.new(t).parseWith(()=>xo.readIPv6Addr())}function Eo(t){return!!tl(t)}function nl(t){return!!rl(t)}function Wi(t){return e=>j(e,t)}function ji(t){return e=>K(e,t)}function Ir(t){return new DataView(t.buffer).getUint16(t.byteOffset).toString()}function Xt(t){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof t=="string"?parseInt(t):t),new Uint8Array(e)}function ol(t){let e=t.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let r=K(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Xt(n);return rt([r,o],r.length+o.length)}function sl(t){let e=t.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let r=wt.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Xt(n);return rt([r,o],r.length+o.length)}function Yi(t){let e=t.subarray(0,t.length-2),r=t.subarray(t.length-2),n=j(e,"base32"),o=Ir(r);return`${n}:${o}`}var Gi=function(t){t=t.toString().trim();let e=new Uint8Array(4);return t.split(/\./g).forEach((r,n)=>{let o=parseInt(r,10);if(isNaN(o)||o<0||o>255)throw new ve("Invalid byte value in IP address");e[n]=o}),e},il=function(t){let e=0;t=t.toString().trim();let r=t.split(":",8),n;for(n=0;n<r.length;n++){let s=Eo(r[n]),i;s&&(i=Gi(r[n]),r[n]=j(i.subarray(0,2),"base16")),i!=null&&++n<8&&r.splice(n,0,j(i.subarray(2,4),"base16"))}if(r[0]==="")for(;r.length<8;)r.unshift("0");else if(r[r.length-1]==="")for(;r.length<8;)r.push("0");else if(r.length<8){for(n=0;n<r.length&&r[n]!=="";n++);let s=[n,1];for(n=9-r.length;n>0;n--)s.push("0");r.splice.apply(r,s)}let o=new Uint8Array(e+16);for(n=0;n<r.length;n++){r[n]===""&&(r[n]="0");let s=parseInt(r[n],16);if(isNaN(s)||s<0||s>65535)throw new ve("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},al=function(t){if(t.byteLength!==4)throw new ve("IPv4 address was incorrect length");let e=[];for(let r=0;r<t.byteLength;r++)e.push(t[r]);return e.join(".")},cl=function(t){if(t.byteLength!==16)throw new ve("IPv6 address was incorrect length");let e=[];for(let n=0;n<t.byteLength;n+=2){let o=t[n],s=t[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;e.push(i)}let r=e.join(":");try{let n=new URL(`http://[${r}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new ve(`Invalid IPv6 address "${r}"`)}};function ul(t){try{let e=new URL(`http://[${t}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new ve(`Invalid IPv6 address "${t}"`)}}var $i=Object.values(qr).map(t=>t.decoder),ip=(function(){let t=$i[0].or($i[1]);return $i.slice(2).forEach(e=>t=t.or(e)),t})();function ll(t){return ip.decode(t)}function fl(t){return e=>t.encoder.encode(e)}function ap(t){if(parseInt(t).toString()!==t)throw new pt("Value must be an integer")}function cp(t){if(t<0)throw new pt("Value must be a positive integer, or zero")}function up(t){return e=>{if(e>t)throw new pt(`Value must be smaller than or equal to ${t}`)}}function lp(...t){return e=>{for(let r of t)r(e)}}var fn=lp(ap,cp,up(65535));var Se=-1,Zi=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let r;if(typeof e=="string"?r=this.protocolsByName.get(e):r=this.protocolsByCode.get(e),r==null)throw new bo(`Protocol ${e} was unknown`);return r}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(r=>{this.protocolsByName.set(r,e)})}removeProtocol(e){let r=this.protocolsByCode.get(e);r!=null&&(this.protocolsByCode.delete(r.code),this.protocolsByName.delete(r.name),r.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},yt=new Zi,_p=[{code:4,name:"ip4",size:32,valueToBytes:Gi,bytesToValue:al,validate:t=>{if(!Eo(t))throw new pt(`Invalid IPv4 address "${t}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Xt,bytesToValue:Ir,validate:fn},{code:273,name:"udp",size:16,valueToBytes:Xt,bytesToValue:Ir,validate:fn},{code:33,name:"dccp",size:16,valueToBytes:Xt,bytesToValue:Ir,validate:fn},{code:41,name:"ip6",size:128,valueToBytes:il,bytesToValue:cl,stringToValue:ul,validate:t=>{if(!nl(t))throw new pt(`Invalid IPv6 address "${t}"`)}},{code:42,name:"ip6zone",size:Se},{code:43,name:"ipcidr",size:8,bytesToValue:Wi("base10"),valueToBytes:ji("base10")},{code:53,name:"dns",size:Se},{code:54,name:"dns4",size:Se},{code:55,name:"dns6",size:Se},{code:56,name:"dnsaddr",size:Se},{code:132,name:"sctp",size:16,valueToBytes:Xt,bytesToValue:Ir,validate:fn},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:Se,stringToValue:t=>decodeURIComponent(t),valueToString:t=>encodeURIComponent(t)},{code:421,name:"p2p",aliases:["ipfs"],size:Se,bytesToValue:Wi("base58btc"),valueToBytes:t=>t.startsWith("Q")||t.startsWith("1")?ji("base58btc")(t):we.parse(t).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Yi,valueToBytes:ol},{code:445,name:"onion3",size:296,bytesToValue:Yi,valueToBytes:sl},{code:446,name:"garlic64",size:Se},{code:447,name:"garlic32",size:Se},{code:448,name:"tls"},{code:449,name:"sni",size:Se},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:Se,bytesToValue:fl(vs),valueToBytes:ll},{code:480,name:"http"},{code:481,name:"http-path",size:Se,stringToValue:t=>`/${decodeURIComponent(t)}`,valueToString:t=>encodeURIComponent(t.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:Se}];_p.forEach(t=>{yt.addProtocol(t)});function dl(t){let e=[],r=0;for(;r<t.length;){let n=en(t,r),o=yt.getProtocol(n),s=Pe(n),i=Ap(o,t,r+s),a=0;i>0&&o.size===Se&&(a=Pe(i));let c=s+a+i,u={code:n,name:o.name,bytes:Ie(t.subarray(r,r+c))};if(i>0){let l=r+s+a,f=t.subarray(l,l+i);u.value=o.bytesToValue?.(f)??j(f)}e.push(u),r+=c}return e}function hl(t){let e=0,r=[];for(let n of t){if(n.bytes==null){let o=yt.getProtocol(n.code),s=Pe(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??K(n.value),a=i.byteLength,o.size===Se&&(c=Pe(a)));let u=new Uint8Array(s+c+a),l=0;vr(n.code,u,l),l+=s,i!=null&&(o.size===Se&&(vr(a,u,l),l+=c),u.set(i,l)),n.bytes=u}r.push(n.bytes),e+=n.bytes.byteLength}return rt(r,e)}function pl(t){if(t.charAt(0)!=="/")throw new ve('String multiaddr must start with "/"');let e=[],r="protocol",n="",o="";for(let s=1;s<t.length;s++){let i=t.charAt(s);i!=="/"&&(r==="protocol"?o+=t.charAt(s):n+=t.charAt(s));let a=s===t.length-1;if(i==="/"||a){let c=yt.getProtocol(o);if(r==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",r="protocol";continue}else if(a)throw new ve(`Component ${o} was missing value`);r="value"}else if(r==="value"){let u={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new ve(`Component ${o} was missing value`);u.value=c.stringToValue?.(n)??n}e.push(u),n="",o="",r="protocol"}}}if(o!==""&&n!=="")throw new ve("Incomplete multiaddr");return e}function ml(t){return`/${t.flatMap(e=>{if(e.value==null)return e.name;let r=yt.getProtocol(e.code);if(r==null)throw new ve(`Unknown protocol code ${e.code}`);return[e.name,r.valueToString?.(e.value)??e.value]}).join("/")}`}function Ap(t,e,r){return t.size==null||t.size===0?0:t.size>0?t.size/8:en(e,r)}var Tp=Symbol.for("nodejs.util.inspect.custom"),ha=Symbol.for("@multiformats/multiaddr");function Dp(t){if(t==null&&(t="/"),yl(t))return t.getComponents();if(t instanceof Uint8Array)return dl(t);if(typeof t=="string")return t=t.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),t===""&&(t="/"),pl(t);if(Array.isArray(t))return t;throw new ve("Must be a string, Uint8Array, Component[], or another Multiaddr")}var To=class t{[ha]=!0;#e;#t;#r;constructor(e="/",r={}){this.#e=Dp(e),r.validate!==!1&&Ip(this)}get bytes(){return this.#r==null&&(this.#r=hl(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=ml(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let r=new t(e);return new t([...this.#e,...r.getComponents()],{validate:!1})}decapsulate(e){let r=e.toString(),n=this.toString(),o=n.lastIndexOf(r);if(o<0)throw new go(`Address ${this.toString()} does not contain subaddress: ${r}`);return new t(n.slice(0,o),{validate:!1})}decapsulateCode(e){let r;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){r=n;break}return new t(this.#e.slice(0,r),{validate:!1})}equals(e){return be(this.bytes,e.bytes)}[Tp](){return`Multiaddr(${this.toString()})`}};function Ip(t){t.getComponents().forEach(e=>{let r=yt.getProtocol(e.code);e.value!=null&&r.validate?.(e.value)})}function yl(t){return!!t?.[ha]}function Ke(t){return new To(t)}var pa={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},gl={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},bl=new globalThis.TextEncoder;function Cp(t,e){let r=pa[e],n=gl[e];for(let o=0;o<t.length;o++)n^=BigInt(t[o]),n=BigInt.asUintN(e,n*r);return n}function Bp(t,e,r){if(r.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=pa[e],o=gl[e],s=t;for(;s.length>0;){let i=bl.encodeInto(s,r);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(r[a]),o=BigInt.asUintN(e,o*n)}return o}function ma(t,{size:e=32,utf8Buffer:r}={}){if(!pa[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof t=="string"){if(r)return Bp(t,e,r);t=bl.encode(t)}return Cp(t,e)}var dn={hash:t=>Number(ma(t,{size:32})),hashV:(t,e)=>Lp(dn.hash(t,e))};function Lp(t){let e=t.toString(16);return e.length%2===1&&(e=`0${e}`),K(e,"base16")}var ya=64,Xe=class{fp;h;seed;constructor(e,r,n,o=2){if(o>ya)throw new TypeError("Invalid Fingerprint Size");let s=r.hashV(e,n),i=ae(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=r,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?be(this.fp,e.fp):!1}};function er(t,e){return Math.floor(Math.random()*(e-t))+t}var tr=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof Xe))throw new TypeError("Invalid Fingerprint");return this.contents.some(r=>e.equals(r))}add(e){if(!(e instanceof Xe))throw new TypeError("Invalid Fingerprint");for(let r=0;r<this.contents.length;r++)if(this.contents[r]==null)return this.contents[r]=e,!0;return!0}swap(e){if(!(e instanceof Xe))throw new TypeError("Invalid Fingerprint");let r=er(0,this.contents.length-1),n=this.contents[r];return this.contents[r]=e,n}remove(e){if(!(e instanceof Xe))throw new TypeError("Invalid Fingerprint");let r=this.contents.findIndex(n=>e.equals(n));return r>-1?(this.contents[r]=null,!0):!1}};var Rp=500,hn=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??dn,this.seed=e.seed??er(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=K(e));let r=new Xe(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^r.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new tr(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new tr(this.bucketSize)),this.buckets[n].add(r)||this.buckets[o].add(r))return this.count++,!0;let s=[n,o],i=s[er(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new tr(this.bucketSize));for(let a=0;a<Rp;a++){let c=this.buckets[i].swap(r);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new tr(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=K(e));let r=new Xe(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(r)??!1;if(o)return o;let s=(n^r.hash())%this.filterSize;return this.buckets[s]?.has(r)??!1}remove(e){typeof e=="string"&&(e=K(e));let r=new Xe(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(r)??!1;if(o)return this.count--,o;let s=(n^r.hash())%this.filterSize,i=this.buckets[s]?.remove(r)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},Op={1:.5,2:.84,4:.95,8:.98};function Pp(t=.001){return t>.002?2:t>1e-5?4:8}function wl(t,e=.001){let r=Pp(e),n=Op[r],o=Math.round(t/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*r)),ya);return{filterSize:o,bucketSize:r,fingerprintSize:s}}var Do=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??dn,this.seed=e.seed??er(0,Math.pow(2,10)),this.filterSeries=[new hn({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=K(e)),this.has(e))return!0;let r=this.filterSeries.find(n=>n.reliable);if(r==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);r=new hn({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(r)}return r.add(e)}has(e){typeof e=="string"&&(e=K(e));for(let r=0;r<this.filterSeries.length;r++)if(this.filterSeries[r].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=K(e));for(let r=0;r<this.filterSeries.length;r++)if(this.filterSeries[r].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,r)=>e+r.count,0)}};function Rr(t,e=.001,r){return new Do({...wl(t,e),...r??{}})}var te=t=>({match:e=>{let r=e[0];return r==null||r.code!==t||r.value!=null?!1:e.slice(1)}}),L=(t,e)=>({match:r=>{let n=r[0];return n?.code!==t||n.value==null||e!=null&&n.value!==e?!1:r.slice(1)}}),xl=t=>({match:e=>t.match(e)===!1?e:!1}),H=t=>({match:e=>{let r=t.match(e);return r===!1?e:r}}),De=(...t)=>({match:e=>{let r;for(let n of t){let o=n.match(e);o!==!1&&(r==null||o.length<r.length)&&(r=o)}return r??!1}}),Y=(...t)=>({match:e=>{for(let r of t){let n=r.match(e);if(n===!1)return!1;e=n}return e}});function re(...t){function e(o){if(o==null)return!1;let s=o.getComponents();for(let i of t){let a=i.match(s);if(a===!1)return!1;s=a}return s}function r(o){return e(o)!==!1}function n(o){let s=e(o);return s===!1?!1:s.length===0}return{matchers:t,matches:r,exactMatch:n}}var Np=L(421),RE=re(Np),Co=L(54),Bo=L(55),Lo=L(56),ba=L(53),OE=re(Co,H(L(421))),PE=re(Bo,H(L(421))),NE=re(Lo,H(L(421))),kE=re(De(ba,Lo,Co,Bo),H(L(421))),El=Y(L(4),H(L(43))),Sl=Y(H(L(42)),L(41),H(L(43))),wa=De(El,Sl),Or=De(wa,ba,Co,Bo,Lo),UE=re(De(wa,Y(De(ba,Lo,Co,Bo),H(L(421))))),ME=re(El),FE=re(Sl),KE=re(wa),xa=Y(Or,L(6)),pn=Y(Or,L(273)),qE=re(Y(xa,H(L(421)))),zE=re(pn),Ea=Y(pn,te(460),H(L(421))),Ro=Y(pn,te(461),H(L(421))),kp=De(Ea,Ro),HE=re(Ea),VE=re(Ro),ga=De(Or,xa,pn,Ea,Ro),vl=De(Y(ga,te(477),H(L(421)))),$E=re(vl),_l=De(Y(ga,te(478),H(L(421))),Y(ga,te(448),H(L(449)),te(477),H(L(421)))),WE=re(_l),Al=Y(pn,te(280),H(L(466)),H(L(466)),H(L(421))),jE=re(Al),Tl=Y(Ro,te(465),H(L(466)),H(L(466)),H(L(421))),YE=re(Tl),Io=De(vl,_l,Y(xa,H(L(421))),Y(kp,H(L(421))),Y(Or,H(L(421))),Al,Tl,L(421)),Dl=re(Io),Up=Y(H(Io),te(290),xl(te(281)),H(L(421))),rr=re(Up),Mp=De(Y(Io,te(290),te(281),H(L(421))),Y(Io,te(281),H(L(421))),Y(te(281),H(L(421)))),GE=re(Mp),Fp=Y(Or,De(Y(L(6,"80")),Y(L(6),te(480)),te(480)),H(L(481)),H(L(421))),ZE=re(Fp),Kp=Y(Or,De(Y(L(6,"443")),Y(L(6,"443"),te(480)),Y(L(6),te(443)),Y(L(6),te(448),te(480)),Y(te(448),te(480)),te(448),te(443)),H(L(481)),H(L(421))),XE=re(Kp),qp=De(Y(L(777),H(L(421)))),QE=re(qp),zp=De(Y(L(400),H(L(421)))),JE=re(zp);function Qe(){let t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}var Oo=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},Pr=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Oo(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let r=this.head;this.head=r.next=new Oo(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let r=this.tail.next;this.tail.next=null,this.tail=r,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var Sa=class extends Error{type;code;constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function Bt(t={}){return Hp(r=>{let n=r.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},t)}function Hp(t,e){e=e??{};let r=e.onEnd,n=new Pr,o,s,i,a=Qe(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((b,x)=>{s=v=>{s=null,n.push(v);try{b(t(n))}catch(m){x(m)}return o}}):t(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Qe()})}},u=b=>s!=null?s(b):(n.push(b),o),l=b=>(n=new Pr,s!=null?s({error:b}):(n.push({error:b}),o)),f=b=>{if(i)return o;if(e?.objectMode!==!0&&b?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:b})},p=b=>i?o:(i=!0,b!=null?l(b):u({done:!0})),h=()=>(n=new Pr,p(),{done:!0}),w=b=>(p(b),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:w,push:f,end:p,get readableLength(){return n.size},onEmpty:async b=>{let x=b?.signal;if(x?.throwIfAborted(),n.isEmpty())return;let v,m;x!=null&&(v=new Promise((_,A)=>{m=()=>{A(new Sa)},x.addEventListener("abort",m)}));try{await Promise.race([a.promise,v])}finally{m!=null&&x!=null&&x?.removeEventListener("abort",m)}}},r==null)return o;let g=o;return o={[Symbol.asyncIterator](){return this},next(){return g.next()},throw(b){return g.throw(b),r!=null&&(r(b),r=void 0),{done:!0}},return(){return g.return(),r!=null&&(r(),r=void 0),{done:!0}},push:f,end(b){return g.end(b),r!=null&&(r(b),r=void 0),o},get readableLength(){return g.readableLength},onEmpty:b=>g.onEmpty(b)},o}var va=class t extends Error{name="TimeoutError";constructor(e,r){super(e,r),Error.captureStackTrace?.(this,t)}},Il=t=>t.reason??new DOMException("This operation was aborted.","AbortError");function _a(t,e){let{milliseconds:r,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e,a,c,l=new Promise((f,p)=>{if(typeof r!="number"||Math.sign(r)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(i?.aborted){p(Il(i));return}if(i&&(c=()=>{p(Il(i))},i.addEventListener("abort",c,{once:!0})),t.then(f,p),r===Number.POSITIVE_INFINITY)return;let h=new va;a=s.setTimeout.call(void 0,()=>{if(n){try{f(n())}catch(w){p(w)}return}typeof t.cancel=="function"&&t.cancel(),o===!1?f():o instanceof Error?p(o):(h.message=o??`Promise timed out after ${r} milliseconds`,p(h))},r)}).finally(()=>{l.clear(),c&&i&&i.removeEventListener("abort",c)});return l.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},l}var Vp=t=>{let e=t.addEventListener||t.on||t.addListener,r=t.removeEventListener||t.off||t.removeListener;if(!e||!r)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(t),removeListener:r.bind(t)}};function $p(t,e,r){let n,o=new Promise((s,i)=>{if(r={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...r},!(r.count>=0&&(r.count===Number.POSITIVE_INFINITY||Number.isInteger(r.count))))throw new TypeError("The `count` option should be at least 0 or more");r.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:u,removeListener:l}=Vp(t),f=async(...h)=>{let w=r.multiArgs?h:h[0];if(r.filter)try{if(!await r.filter(w))return}catch(g){n(),i(g);return}c.push(w),r.count===c.length&&(n(),s(c))},p=(...h)=>{n(),i(r.rejectionMultiArgs?h:h[0])};n=()=>{for(let h of a)l(h,f);for(let h of r.rejectionEvents)a.includes(h)||l(h,p)};for(let h of a)u(h,f);for(let h of r.rejectionEvents)a.includes(h)||u(h,p);r.signal&&r.signal.addEventListener("abort",()=>{p(r.signal.reason)},{once:!0}),r.resolveImmediately&&s(c)});if(o.cancel=n,typeof r.timeout=="number"){let s=_a(o,{milliseconds:r.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function at(t,e,r){typeof r=="function"&&(r={filter:r}),r={...r,count:1,resolveImmediately:!1};let n=$p(t,e,r),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function Aa(t,e){let r,n=function(){let o=function(){r=void 0,t()};clearTimeout(r),r=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(r)},n}var Po=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}},nr=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"};var No=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function Wp(t){return t.reason}function Lt(t,e,r){if(e==null||t==null)return t;let n=r?.translateError??Wp;if(e.aborted)return t.catch(()=>{}),Promise.reject(n(e));let o;return Promise.race([t,new Promise((s,i)=>{o=()=>{i(n(e))},e.addEventListener("abort",o)})]).finally(()=>{o!=null&&e.removeEventListener("abort",o)})}var ko=class{deferred;signal;onProgress;constructor(e){this.signal=e?.signal,this.onProgress=e?.onProgress,this.deferred=Qe(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Je)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function jp(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Cl=new WeakMap,Uo=class{id;fn;options;recipients;status;timeline;controller;dispatchingProgress;constructor(e,r){this.id=jp(),this.status="queued",this.fn=e,this.options=r,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.dispatchingProgress=!1,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((r,n)=>r&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Je),this.cleanup())}async join(e){let r=new ko(e);return this.recipients.push(r),e?.signal?.addEventListener("abort",this.onAbort),r.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await Lt(this.fn({...this.options??{},signal:this.controller.signal,onProgress:r=>{if(this.recipients.length!==0&&!this.dispatchingProgress){if(typeof r=="object"&&r!==null){let n=Cl.get(r);if(n==null&&(n=new WeakSet,Cl.set(r,n)),n.has(this))return;n.add(this)}this.dispatchingProgress=!0;try{this.recipients.forEach(n=>{n.onProgress?.(r)})}finally{this.dispatchingProgress=!1}}}}),this.controller.signal);this.recipients.forEach(r=>{r.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(r=>{r.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.deferred.reject(e.signal?.reason??new Je),e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)}),this.recipients.splice(0,this.recipients.length)}};var Mo=class extends Be{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=Aa(this.emitEmpty.bind(this),1),this.emitIdle=Aa(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let r of this.queue)if(r.status==="queued"){e=r;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let r=0;r<this.queue.length;r++)if(this.queue[r]===e){this.queue.splice(r,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,r){if(r?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Po;let n=new Uo(e,r);this.enqueue(n),this.safeDispatchEvent("add");let o=n.join(r).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s});return this.tryToStartAnother(),o}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Je)}),this.clear()}async onEmpty(e){this.size!==0&&await at(this,"empty",e)}async onSizeLessThan(e,r){this.size<e||await at(this,"next",{...r,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await at(this,"idle",e)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let r=Bt({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),r.end(c)},o=c=>{c.detail!=null&&r.push(c.detail)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new Je("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*r}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var Yp=Math.pow(2,20)*4,Fo=class extends Be{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;#e=!1;onDrainPromise;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??Yp,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new ce,this.writeBuffer=new ce,this.readStatus="readable",this.remoteReadStatus="readable",this.writeStatus="writable",this.remoteWriteStatus="writable",this.sendingData=!1,this.writableNeedsDrain=!1,this.timeline={open:Date.now()},this.processSendQueue=this.processSendQueue.bind(this);let r=()=>{this.writableNeedsDrain&&(this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,queueMicrotask(()=>{try{this.processSendQueue()}catch(o){this.log.error("processSendQueue threw - %e",o)}})),this.onDrainPromise?.resolve()};this.addEventListener("drain",r);let n=o=>{this.onDrainPromise?.reject(o.error??new No)};this.addEventListener("close",n)}get readBufferLength(){return this.readBuffer.byteLength}get readableEnded(){return this.#e}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),Lt(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let e=Bt(),r=s=>{e.push(s.data)};this.addEventListener("message",r);let n=s=>{e.end(s.error)};this.addEventListener("close",n);let o=()=>{e.end()};this.addEventListener("remoteCloseWrite",o);try{yield*e}finally{this.removeEventListener("message",r),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",o)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new gt(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",e.byteLength),this.writeBuffer.append(e),this.processSendQueue()}abort(e){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",e),this.status="aborted",this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle")),this.writeStatus="closed",this.remoteWriteStatus="closed",this.readStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.maybeDispatchEnd();try{this.sendReset(e)}catch(r){this.log.error("failed to send reset to remote - %e",r)}this.dispatchEvent(new Dn(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new gt("Cannot pause a stream that is closing/closed");this.readStatus!=="paused"&&(this.readStatus="paused",this.sendPause())}resume(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new gt("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new gt(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.append(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}unshift(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new gt(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.prepend(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(e){if(e.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(e),this.dispatchReadBuffer()}}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="message"&&this.readBuffer.byteLength>0&&queueMicrotask(()=>{this.dispatchReadBuffer()})}onRemoteReset(){this.log("remote reset"),this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.readBuffer.byteLength===0&&(this.readStatus="closed",this.maybeDispatchEnd()),this.dispatchEvent(new In(new En))}onTransportClosed(e){this.log("transport closed"),this.readStatus==="readable"&&this.readBuffer.byteLength===0&&(this.log("close readable end after transport closed and read buffer is empty"),this.readStatus="closed"),this.remoteReadStatus!=="closed"&&(this.remoteReadStatus="closed"),this.remoteWriteStatus!=="closed"&&(this.remoteWriteStatus="closed"),this.writeStatus!=="closed"&&(this.writeStatus="closed"),e!=null?this.abort(e):(this.status==="open"||this.status==="closing")&&(this.timeline.close=Date.now(),this.status="closed",this.maybeDispatchEnd(),this.dispatchEvent(new cr))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.maybeDispatchEnd(),this.writeStatus==="closed"&&this.onTransportClosed())}onRemoteCloseRead(){this.log.trace("on remote close read"),this.remoteReadStatus="closed",this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle"))}processSendQueue(){if(this.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(this.writeBuffer.byteLength===0)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;if(this.writeStatus!=="writable"&&this.writeStatus!=="closing")return this.log.trace("not processing send queue as stream is %s",this.writeStatus),!1;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let e=!0,r=this.writeBuffer.byteLength,n=0;for(;this.writeBuffer.byteLength>0;){let o=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(o===0){e=!1;break}let s=this.writeBuffer.sublist(0,o),i=new ce(s);this.writeBuffer.consume(s.byteLength);let a;try{a=this.sendData(s)}catch(c){throw this.writeBuffer.prepend(i),this.abort(c),c}if(e=a.canSendMore,n+=a.sentBytes,a.sentBytes!==i.byteLength&&(i.consume(a.sentBytes),this.writeBuffer.prepend(i)),!e)break}return e||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",n,r,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),e}finally{this.sendingData=!1}}maybeDispatchEnd(){this.#e||this.readBuffer.byteLength>0||this.remoteWriteStatus!=="closed"&&this.readStatus!=="closed"||(this.#e=!0,this.safeDispatchEvent("end"))}dispatchReadBuffer(){try{if(this.listenerCount("message")===0){this.log.trace("not dispatching pause buffer as there are no listeners for the message event");return}if(this.readBuffer.byteLength===0){this.log.trace("not dispatching pause buffer as there is no data to dispatch");return}if(this.readStatus==="paused"){this.log.trace("not dispatching pause buffer we are paused");return}if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("dropping %d bytes because the readable end is %s",this.readBuffer.byteLength,this.readStatus),this.readBuffer.consume(this.readBuffer.byteLength);return}let e=this.readBuffer.sublist();this.readBuffer.consume(e.byteLength),this.dispatchEvent(new Tn(e))}finally{this.readBuffer.byteLength===0&&this.remoteWriteStatus==="closed"&&(this.log("close readable end after dispatching read buffer and remote writable end is closed"),this.readStatus="closed",this.maybeDispatchEnd()),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new Ut(`Read buffer length of ${this.readBuffer.byteLength} exceeded limit of ${this.maxReadBufferLength}, read status is ${this.readStatus}`))}checkWriteBufferLength(){this.maxWriteBufferLength!=null&&this.writeBuffer.byteLength>this.maxWriteBufferLength&&this.abort(new Ut(`Write buffer length of ${this.writeBuffer.byteLength} exceeded limit of ${this.maxWriteBufferLength}, write status is ${this.writeStatus}`))}onMuxerNeedsDrain(){this.writableNeedsDrain=!0}onMuxerDrain(){this.safeDispatchEvent("drain")}};var Ko=class extends Fo{remoteAddr;metricPrefix;metrics;constructor(e){super(e),this.metricPrefix=e.metricPrefix??"",this.metrics=e.metrics,this.remoteAddr=e.remoteAddr,this.addEventListener("close",r=>{this.metrics?.increment({[`${this.metricPrefix}end`]:!0}),r.error!=null?r.local?this.metrics?.increment({[`${this.metricPrefix}abort`]:!0}):this.metrics?.increment({[`${this.metricPrefix}reset`]:!0}):r.local?this.metrics?.increment({[`${this.metricPrefix}_local_close`]:!0}):this.metrics?.increment({[`${this.metricPrefix}_remote_close`]:!0})})}async close(e){this.status==="open"&&(this.status="closing",this.writeStatus="closing",this.remoteWriteStatus="closing",this.remoteReadStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await at(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await at(this,"drain",{...e,rejectionEvents:["close"]})),await this.sendClose(e),this.onTransportClosed())}};function qo(t){let e=new globalThis.AbortController;function r(){let s=t.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();e.abort(s);for(let i of t)i?.removeEventListener!=null&&i.removeEventListener("abort",r)}for(let s of t){if(s?.aborted===!0){r();break}s?.addEventListener!=null&&s.addEventListener("abort",r)}function n(){for(let s of t)s?.removeEventListener!=null&&s.removeEventListener("abort",r)}let o=e.signal;return o.clear=n,o}var Ta=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=Qe(),this.haveNext=Qe()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=Qe(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,r){await this._push(e,r)}async end(e,r){e!=null?await this.throw(e):await this._push(void 0,r)}async _push(e,r){if(e!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=Qe(),await Lt(this.readNext.promise,r?.signal,r)}};function Bl(){return new Ta}function Ll(t){return t[Symbol.asyncIterator]!=null}async function Gp(t,e,r){try{await Promise.all(t.map(async n=>{for(;;){let{value:o,done:s}=await n.next();if(s===!0)break;await e.push(o,{signal:r}),r.throwIfAborted()}})),await e.end(void 0,{signal:r})}catch(n){await e.end(n,{signal:r}).catch(()=>{})}}async function*Zp(t){let e=new AbortController,r=Bl(),n=t.map(o=>Ll(o)?o[Symbol.asyncIterator]():o[Symbol.iterator]());Gp(n,r,e.signal).catch(()=>{});try{yield*r}finally{e.abort();for(let o of n)try{Promise.resolve(o.return?.()).catch(()=>{})}catch{}}}function*Xp(t){for(let e of t)yield*e}function Qp(...t){let e=[];for(let r of t)Ll(r)||e.push(r);return e.length===t.length?Xp(e):Zp(t)}var Rl=Qp;function Ol(t,...e){if(t==null)throw new Error("Empty pipeline");if(Da(t)){let n=t;t=()=>n.source}else if(Nl(t)||Pl(t)){let n=t;t=()=>n}let r=[t,...e];if(r.length>1&&Da(r[r.length-1])&&(r[r.length-1]=r[r.length-1].sink),r.length>2)for(let n=1;n<r.length-1;n++)Da(r[n])&&(r[n]=em(r[n]));return Jp(...r)}var Jp=(...t)=>{let e;for(;t.length>0;)e=t.shift()(e);return e},Pl=t=>t?.[Symbol.asyncIterator]!=null,Nl=t=>t?.[Symbol.iterator]!=null,Da=t=>t==null?!1:t.sink!=null&&t.source!=null,em=t=>e=>{let r=t.sink(e);if(r?.then!=null){let n=Bt({objectMode:!0});r.then(()=>{n.end()},i=>{n.end(i)});let o,s=t.source;if(Pl(s))o=async function*(){yield*s,n.end()};else if(Nl(s))o=function*(){yield*s,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Rl(n,o())}return t.source};var tm=4194304,zo=class extends Error{static name="UnwrappedError";name="UnwrappedError"},Ca=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Ba=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},La=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function rm(t){return typeof t?.closeRead=="function"}function nm(t){return typeof t?.close=="function"}function Ia(t){return rm(t)?t.remoteWriteStatus!=="writable"&&t.readBufferLength===0:nm(t)?t.status!=="open":!1}function om(t){return t?.addEventListener!=null&&t?.removeEventListener!=null&&t?.send!=null&&t?.push!=null&&t?.log!=null}function sm(t,e){let r=e?.maxBufferSize??tm,n=new ce,o,s=!1,i;if(!om(t))throw new pe("Argument should be a Stream or a Multiaddr");let a=f=>{if(i==null){if(n.append(f.data),n.byteLength>r){let p=n.byteLength;n.consume(p);let h=new Ut(`Read buffer overflow - ${p} > ${r}`);i=h,o?.reject(h),queueMicrotask(()=>{t.abort(h)});return}o?.resolve()}};t.addEventListener("message",a);let c=f=>{f.error!=null?o?.reject(f.error):o?.resolve()};t.addEventListener("close",c);let u=()=>{o?.resolve()};t.addEventListener("remoteCloseWrite",u);let l={readBuffer:n,async read(f){if(s===!0)throw new zo("Stream was unwrapped");if(i!=null)throw i;if(Ia(t)){if(n.byteLength===0&&f?.bytes==null)return null;if(f?.bytes!=null&&n.byteLength<f.bytes)throw t.log.error("closed after reading %d/%d bytes",n.byteLength,f.bytes),new nr(`Unexpected EOF - stream closed after reading ${n.byteLength}/${f.bytes} bytes`)}let p=f?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=p){o.resolve();break}if(await Lt(o.promise,f?.signal),Ia(t)){if(n.byteLength===0&&f?.bytes==null)return null;break}o=Promise.withResolvers()}let h=f?.bytes??n.byteLength;if(n.byteLength<h){if(Ia(t))throw t.log.error("closed while reading %d/%d bytes",n.byteLength,h),new nr(`Unexpected EOF - stream closed while reading ${n.byteLength}/${h} bytes`);return l.read(f)}let w=n.sublist(0,h);return n.consume(h),w},async write(f,p){if(s===!0)throw new zo("Stream was unwrapped");t.send(f)||await at(t,"drain",{signal:p?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,t.removeEventListener("message",a),t.removeEventListener("close",c),t.removeEventListener("remoteCloseWrite",u),n.byteLength>0&&(t.log("stream unwrapped with %d unread bytes",n.byteLength),t.unshift(n))),t}};return l}function im(t,e={}){let r=sm(t,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=Pe(e.maxDataLength));let n=e?.lengthDecoder??en,o=e?.lengthEncoder??_r;return{async read(i){let a=-1,c=new ce;for(;;){let l=await r.read({...i,bytes:1});if(l==null)break;c.append(l);try{a=n(c)}catch(f){if(f instanceof RangeError)continue;throw f}if(a<0)throw new Ca("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new La(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new Ba(`Message length too long - ${a} > ${e.maxDataLength}`);let u=await r.read({...i,bytes:a});if(u==null)throw t.log.error("tried to read %d bytes but the stream closed",a),new nr(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(u.byteLength!==a)throw t.log.error("read %d/%d bytes before the stream closed",u.byteLength,a),new nr(`Unexpected EOF - read ${u.byteLength}/${a} bytes before the stream closed`);return u},async write(i,a){await r.write(new ce(o(i.byteLength),i),a)},async writeV(i,a){let c=new ce(...i.flatMap(u=>[o(u.byteLength),u]));await r.write(c,a)},unwrap(){return r.unwrap()}}}function Rt(t,e){let r=im(t,e),n={read:async(o,s)=>{let i=await r.read(s);return o.decode(i,s)},write:async(o,s,i)=>{await r.write(s.encode(o),i)},writeV:async(o,s,i)=>{await r.writeV(o.map(a=>s.encode(a)),i)},pb:o=>({read:async s=>n.read(o,s),write:async(s,i)=>n.write(s,o,i),writeV:async(s,i)=>n.writeV(s,o,i),unwrap:()=>n}),unwrap:()=>r.unwrap()};return n}function am(t){return t?.addEventListener!=null}function cm(t){let e=Bt(),r,n=i=>{e.push(i.data)},o=()=>{e.end(),t.removeEventListener("message",n),t.removeEventListener("close",s),t.removeEventListener("remoteCloseWrite",o)},s=i=>{e.end(i.error),i.error!=null&&r?.reject(i.error),t.removeEventListener("message",n),t.removeEventListener("close",s),t.removeEventListener("remoteCloseWrite",o)};return t.addEventListener("message",n),t.addEventListener("close",s,{once:!0}),t.addEventListener("remoteCloseWrite",o,{once:!0}),{source:e,async sink(i){async function*a(){yield*i}let c=a();for(;;){r=Promise.withResolvers();let{done:u,value:l}=await Promise.race([c.next(),r.promise]);if(t.writeStatus==="closing"||t.writeStatus==="closed"||(l!=null&&(t.send(l)||await Promise.race([at(t,"drain",{rejectionEvents:["close"]})])),u===!0))break}await t.close()}}}function kl(...t){let e=t.map(r=>am(r)?cm(r):r);return Ol(...e)}var Nr=class extends Mo{has(e){return this.find(e)!=null}find(e){return this.queue.find(r=>e.equals(r.options.peerId))}};var Ra=1e3,Ul=60*Ra,Ml=15,Fl=120*Ul,Kl=1,Ho=5e3,ql=100,Oa="circuit-relay-source",mn=`${Wa}-circuit-relay`,zl=2*Ul,Hl=BigInt(1<<17),je="/libp2p/circuit/relay/0.2.0/hop",or="/libp2p/circuit/relay/0.2.0/stop",Vl=30*Ra,o1=30*Ra,yn=300,$l=4096,Wl=.001;var ee;(function(t){let e;(function(a){a.RESERVE="RESERVE",a.CONNECT="CONNECT",a.STATUS="STATUS"})(e=t.Type||(t.Type={}));let r;(function(a){a[a.RESERVE=0]="RESERVE",a[a.CONNECT=1]="CONNECT",a[a.STATUS=2]="STATUS"})(r||(r={})),(function(a){a.codec=()=>Yt(r)})(e=t.Type||(t.Type={}));let n;t.codec=()=>(n==null&&(n=Me((a,c,u={})=>{u.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),t.Type.codec().encode(a.type,c)),a.peer!=null&&(c.uint32(18),Ot.codec().encode(a.peer,c)),a.reservation!=null&&(c.uint32(26),gn.codec().encode(a.reservation,c)),a.limit!=null&&(c.uint32(34),Pt.codec().encode(a.limit,c)),a.status!=null&&(c.uint32(40),q.codec().encode(a.status,c)),u.lengthDelimited!==!1&&c.ldelim()},(a,c,u={})=>{let l={},f=c==null?a.len:a.pos+c;for(;a.pos<f;){let p=a.uint32();switch(p>>>3){case 1:{l.type=t.Type.codec().decode(a);break}case 2:{l.peer=Ot.codec().decode(a,a.uint32(),{limits:u.limits?.peer});break}case 3:{l.reservation=gn.codec().decode(a,a.uint32(),{limits:u.limits?.reservation});break}case 4:{l.limit=Pt.codec().decode(a,a.uint32(),{limits:u.limits?.limit});break}case 5:{l.status=q.codec().decode(a);break}default:{a.skipType(p&7);break}}}return l},function*(a,c,u,l={}){let f=c==null?a.len:a.pos+c;for(;a.pos<f;){let p=a.uint32();switch(p>>>3){case 1:{yield{field:`${u}.type`,value:t.Type.codec().decode(a)};break}case 2:{yield*Ot.codec().stream(a,a.uint32(),`${u}.peer`,{limits:l.limits?.peer});break}case 3:{yield*gn.codec().stream(a,a.uint32(),`${u}.reservation`,{limits:l.limits?.reservation});break}case 4:{yield*Pt.codec().stream(a,a.uint32(),`${u}.limit`,{limits:l.limits?.limit});break}case 5:{yield{field:`${u}.status`,value:q.codec().decode(a)};break}default:{a.skipType(p&7);break}}}})),n);function o(a){return ke(a,t.codec())}t.encode=o;function s(a,c){return Ne(a,t.codec(),c)}t.decode=s;function i(a,c){return Ue(a,t.codec(),c)}t.stream=i})(ee||(ee={}));var qe;(function(t){let e;(function(a){a.CONNECT="CONNECT",a.STATUS="STATUS"})(e=t.Type||(t.Type={}));let r;(function(a){a[a.CONNECT=0]="CONNECT",a[a.STATUS=1]="STATUS"})(r||(r={})),(function(a){a.codec=()=>Yt(r)})(e=t.Type||(t.Type={}));let n;t.codec=()=>(n==null&&(n=Me((a,c,u={})=>{u.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),t.Type.codec().encode(a.type,c)),a.peer!=null&&(c.uint32(18),Ot.codec().encode(a.peer,c)),a.limit!=null&&(c.uint32(26),Pt.codec().encode(a.limit,c)),a.status!=null&&(c.uint32(32),q.codec().encode(a.status,c)),u.lengthDelimited!==!1&&c.ldelim()},(a,c,u={})=>{let l={},f=c==null?a.len:a.pos+c;for(;a.pos<f;){let p=a.uint32();switch(p>>>3){case 1:{l.type=t.Type.codec().decode(a);break}case 2:{l.peer=Ot.codec().decode(a,a.uint32(),{limits:u.limits?.peer});break}case 3:{l.limit=Pt.codec().decode(a,a.uint32(),{limits:u.limits?.limit});break}case 4:{l.status=q.codec().decode(a);break}default:{a.skipType(p&7);break}}}return l},function*(a,c,u,l={}){let f=c==null?a.len:a.pos+c;for(;a.pos<f;){let p=a.uint32();switch(p>>>3){case 1:{yield{field:`${u}.type`,value:t.Type.codec().decode(a)};break}case 2:{yield*Ot.codec().stream(a,a.uint32(),`${u}.peer`,{limits:l.limits?.peer});break}case 3:{yield*Pt.codec().stream(a,a.uint32(),`${u}.limit`,{limits:l.limits?.limit});break}case 4:{yield{field:`${u}.status`,value:q.codec().decode(a)};break}default:{a.skipType(p&7);break}}}})),n);function o(a){return ke(a,t.codec())}t.encode=o;function s(a,c){return Ne(a,t.codec(),c)}t.decode=s;function i(a,c){return Ue(a,t.codec(),c)}t.stream=i})(qe||(qe={}));var Ot;(function(t){let e;t.codec=()=>(e==null&&(e=Me((s,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),s.id!=null&&s.id.byteLength>0&&(i.uint32(10),i.bytes(s.id)),s.addrs!=null&&s.addrs.length>0)for(let c of s.addrs)i.uint32(18),i.bytes(c);a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={id:ae(0),addrs:[]},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.id=s.bytes();break}case 2:{if(a.limits?.addrs!=null&&c.addrs.length===a.limits.addrs)throw new Gt('Decode error - repeated field "addrs" had too many elements');c.addrs.push(s.bytes());break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u={addrs:0},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let f=s.uint32();switch(f>>>3){case 1:{yield{field:`${a}.id`,value:s.bytes()};break}case 2:{if(c.limits?.addrs!=null&&u.addrs===c.limits.addrs)throw new Gt('Streaming decode error - repeated field "addrs" had too many elements');yield{field:`${a}.addrs[]`,index:u.addrs,value:s.bytes()},u.addrs++;break}default:{s.skipType(f&7);break}}}})),e);function r(s){return ke(s,t.codec())}t.encode=r;function n(s,i){return Ne(s,t.codec(),i)}t.decode=n;function o(s,i){return Ue(s,t.codec(),i)}t.stream=o})(Ot||(Ot={}));var gn;(function(t){let e;t.codec=()=>(e==null&&(e=Me((s,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),s.expire!=null&&s.expire!==0n&&(i.uint32(8),i.uint64(s.expire)),s.addrs!=null&&s.addrs.length>0)for(let c of s.addrs)i.uint32(18),i.bytes(c);s.voucher!=null&&(i.uint32(26),bn.codec().encode(s.voucher,i)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={expire:0n,addrs:[]},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.expire=s.uint64();break}case 2:{if(a.limits?.addrs!=null&&c.addrs.length===a.limits.addrs)throw new Gt('Decode error - repeated field "addrs" had too many elements');c.addrs.push(s.bytes());break}case 3:{c.voucher=bn.codec().decode(s,s.uint32(),{limits:a.limits?.voucher});break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u={addrs:0},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let f=s.uint32();switch(f>>>3){case 1:{yield{field:`${a}.expire`,value:s.uint64()};break}case 2:{if(c.limits?.addrs!=null&&u.addrs===c.limits.addrs)throw new Gt('Streaming decode error - repeated field "addrs" had too many elements');yield{field:`${a}.addrs[]`,index:u.addrs,value:s.bytes()},u.addrs++;break}case 3:{yield*bn.codec().stream(s,s.uint32(),`${a}.voucher`,{limits:c.limits?.voucher});break}default:{s.skipType(f&7);break}}}})),e);function r(s){return ke(s,t.codec())}t.encode=r;function n(s,i){return Ne(s,t.codec(),i)}t.decode=n;function o(s,i){return Ue(s,t.codec(),i)}t.stream=o})(gn||(gn={}));var Pt;(function(t){let e;t.codec=()=>(e==null&&(e=Me((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.duration!=null&&(i.uint32(8),i.uint32(s.duration)),s.data!=null&&(i.uint32(16),i.uint64(s.data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.duration=s.uint32();break}case 2:{c.data=s.uint64();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.duration`,value:s.uint32()};break}case 2:{yield{field:`${a}.data`,value:s.uint64()};break}default:{s.skipType(l&7);break}}}})),e);function r(s){return ke(s,t.codec())}t.encode=r;function n(s,i){return Ne(s,t.codec(),i)}t.decode=n;function o(s,i){return Ue(s,t.codec(),i)}t.stream=o})(Pt||(Pt={}));var q;(function(t){t.UNUSED="UNUSED",t.OK="OK",t.RESERVATION_REFUSED="RESERVATION_REFUSED",t.RESOURCE_LIMIT_EXCEEDED="RESOURCE_LIMIT_EXCEEDED",t.PERMISSION_DENIED="PERMISSION_DENIED",t.CONNECTION_FAILED="CONNECTION_FAILED",t.NO_RESERVATION="NO_RESERVATION",t.MALFORMED_MESSAGE="MALFORMED_MESSAGE",t.UNEXPECTED_MESSAGE="UNEXPECTED_MESSAGE"})(q||(q={}));var Pa;(function(t){t[t.UNUSED=0]="UNUSED",t[t.OK=100]="OK",t[t.RESERVATION_REFUSED=200]="RESERVATION_REFUSED",t[t.RESOURCE_LIMIT_EXCEEDED=201]="RESOURCE_LIMIT_EXCEEDED",t[t.PERMISSION_DENIED=202]="PERMISSION_DENIED",t[t.CONNECTION_FAILED=203]="CONNECTION_FAILED",t[t.NO_RESERVATION=204]="NO_RESERVATION",t[t.MALFORMED_MESSAGE=400]="MALFORMED_MESSAGE",t[t.UNEXPECTED_MESSAGE=401]="UNEXPECTED_MESSAGE"})(Pa||(Pa={}));(function(t){t.codec=()=>Yt(Pa)})(q||(q={}));var sr;(function(t){let e;t.codec=()=>(e==null&&(e=Me((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.relay!=null&&s.relay.byteLength>0&&(i.uint32(10),i.bytes(s.relay)),s.peer!=null&&s.peer.byteLength>0&&(i.uint32(18),i.bytes(s.peer)),s.expiration!=null&&s.expiration!==0n&&(i.uint32(24),i.uint64(s.expiration)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={relay:ae(0),peer:ae(0),expiration:0n},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.relay=s.bytes();break}case 2:{c.peer=s.bytes();break}case 3:{c.expiration=s.uint64();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.relay`,value:s.bytes()};break}case 2:{yield{field:`${a}.peer`,value:s.bytes()};break}case 3:{yield{field:`${a}.expiration`,value:s.uint64()};break}default:{s.skipType(l&7);break}}}})),e);function r(s){return ke(s,t.codec())}t.encode=r;function n(s,i){return Ne(s,t.codec(),i)}t.decode=n;function o(s,i){return Ue(s,t.codec(),i)}t.stream=o})(sr||(sr={}));var bn;(function(t){let e;t.codec=()=>(e==null&&(e=Me((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.publicKey!=null&&s.publicKey.byteLength>0&&(i.uint32(10),i.bytes(s.publicKey)),s.payloadType!=null&&s.payloadType.byteLength>0&&(i.uint32(18),i.bytes(s.payloadType)),s.payload!=null&&(i.uint32(26),sr.codec().encode(s.payload,i)),s.signature!=null&&s.signature.byteLength>0&&(i.uint32(42),i.bytes(s.signature)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={publicKey:ae(0),payloadType:ae(0),signature:ae(0)},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.publicKey=s.bytes();break}case 2:{c.payloadType=s.bytes();break}case 3:{c.payload=sr.codec().decode(s,s.uint32(),{limits:a.limits?.payload});break}case 5:{c.signature=s.bytes();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.publicKey`,value:s.bytes()};break}case 2:{yield{field:`${a}.payloadType`,value:s.bytes()};break}case 3:{yield*sr.codec().stream(s,s.uint32(),`${a}.payload`,{limits:c.limits?.payload});break}case 5:{yield{field:`${a}.signature`,value:s.bytes()};break}default:{s.skipType(l&7);break}}}})),e);function r(s){return ke(s,t.codec())}t.encode=r;function n(s,i){return Ne(s,t.codec(),i)}t.decode=n;function o(s,i){return Ue(s,t.codec(),i)}t.stream=o})(bn||(bn={}));var Vo=class extends Error{constructor(e="Transfer limit error"){super(e),this.name="TransferLimitError"}},$o=class extends Error{constructor(e="Duration limit error"){super(e),this.name="DurationLimitError"}},wn=class extends Error{static name="HadEnoughRelaysError";name="HadEnoughRelaysError"},Wo=class extends Error{static name="DoubleRelayError";name="DoubleRelayError"},jo=class extends Error{static name="RelayQueueFullError";name="RelayQueueFullError"};function jl(t,e,r){let n=e.remaining,o=s=>{let i=BigInt(s.data.byteLength);e.remaining-=i,e.remaining<0&&t.abort(new Vo(`data limit of ${n} bytes exceeded`))};t.addEventListener("message",o)}function Yl(t,e,r,n,o){function s(l){t.abort(l),e.abort(l)}let i=[r,n.signal];if(n.limit?.duration!=null){o.log("limiting relayed connection duration to %dms",n.limit.duration);let l=AbortSignal.timeout(n.limit.duration);i.push(l)}let a=qo(i);let c;n.limit?.data!=null&&(c={remaining:n.limit.data});let u=()=>{let l;r.aborted?l=r.reason:l=new $o(`duration limit of ${n.limit?.duration} ms exceeded`),s(l)};a.addEventListener("abort",u,{once:!0}),c!=null&&(jl(e,c,o),jl(t,c,o)),kl(t,e,t).catch(l=>{s(l)}).finally(()=>{a.clear()})}function Na(t){let e=t*BigInt(1e3),r=new Date().getTime();return Number(e-BigInt(r))}var xn=class{expires;bytes;constructor(e){e?.duration!=null&&e?.duration!==0&&(this.expires=Date.now()+e.duration*1e3),this.bytes=e?.data,this.bytes===0n&&(this.bytes=void 0),this.onData=this.onData.bind(this)}onData(e){this.bytes!=null&&(this.bytes-=BigInt(e.byteLength),this.bytes<0n&&(this.bytes=0n))}getLimits(){if(this.expires==null&&this.bytes==null)return;let e={};if(this.bytes!=null){let r=this;Object.defineProperty(e,"bytes",{get(){return r.bytes}})}if(this.expires!=null){let r=this;Object.defineProperty(e,"seconds",{get(){return Math.round(((r.expires??0)-Date.now())/1e3)}})}return e}},Yo=re(Y(Dl.matchers[0],te(290))),Go=re(te(290));function Zo(t,e){let r={[Symbol.iterator]:()=>r,next:()=>{let n=t.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return r}var Nt=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[r,n]of e.entries())this.map.set(r.toString(),{key:r,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return Zo(this.map.entries(),e=>[e[1].key,e[1].value])}forEach(e){this.map.forEach((r,n)=>{e(r.value,r.key,this)})}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,r){this.map.set(e.toString(),{key:e,value:r})}keys(){return Zo(this.map.values(),e=>e.key)}values(){return Zo(this.map.values(),e=>e.value)}get size(){return this.map.size}};var Xo=class{filter;constructor(e,r){this.filter=Rr(e,r)}has(e){return this.filter.has(e.toMultihash().bytes)}add(e){this.filter.add(e.toMultihash().bytes)}remove(e){this.filter.remove?.(e.toMultihash().bytes)}};function ka(t,e=.001){return new Xo(t,e)}var Ua=class extends Nt{metric;constructor(e){super();let{name:r,metrics:n}=e;this.metric=n.registerMetric(r),this.updateComponentMetric()}set(e,r){return super.set(e,r),this.updateComponentMetric(),this}delete(e){let r=super.delete(e);return this.updateComponentMetric(),r}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Ma(t){let{name:e,metrics:r}=t,n;return r!=null?n=new Ua({name:e,metrics:r}):n=new Nt,n}var Fa=class extends Error{type;code;constructor(e,r,n){super(e??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=r??"ABORT_ERR"}};function Gl(t,e){let r=new Fa(e?.errorMessage,e?.errorCode,e?.errorName),n=new AbortController,o=()=>{n.abort(r)},s=AbortSignal.timeout(t);s.addEventListener("abort",o);let i=n.signal;return i.reset=a=>{s?.removeEventListener("abort",o),s=AbortSignal.timeout(a??t),s.addEventListener("abort",()=>{n.abort(r)})},i.clear=()=>{s?.removeEventListener("abort",o),s=void 0},i}var Qo=class{reservations;maxReservations;applyDefaultLimit;reservationTtl;defaultDurationLimit;defaultDataLimit;log;constructor(e,r={}){this.log=e.logger.forComponent("libp2p:circuit-relay:server:reservation-store"),this.maxReservations=r.maxReservations??Ml,this.applyDefaultLimit=r.applyDefaultLimit!==!1,this.reservationTtl=r.reservationTtl??Fl,this.defaultDurationLimit=r.defaultDurationLimit??zl,this.defaultDataLimit=r.defaultDataLimit??Hl,this.reservations=Ma({metrics:e.metrics,name:"libp2p_circuit_relay_server_reservations_total"})}reserve(e,r,n){let o=this.reservations.get(e);if(this.reservations.size>=this.maxReservations&&o==null)return{status:q.RESERVATION_REFUSED};let s=new Date(Date.now()+this.reservationTtl),i;return this.applyDefaultLimit&&(i=n??{data:this.defaultDataLimit,duration:this.defaultDurationLimit}),o!=null?(this.log("refreshing reservation for client %p",e),o.signal.reset(this.reservationTtl)):(this.log("creating new reservation for client %p",e),o={addr:r,expiry:s,limit:i,signal:Gl(this.reservationTtl)},o.signal.addEventListener("abort",()=>{this.reservations.delete(e)})),this.reservations.set(e,o),{status:q.OK,expire:Math.round(s.getTime()/1e3)}}removeReservation(e){this.reservations.delete(e)}get(e){return this.reservations.get(e)}clear(){this.reservations.clear()}};var Jo=class t{domain="libp2p-relay-rsvp";codec=new Uint8Array([3,2]);relay;peer;expiration;constructor({relay:e,peer:r,expiration:n}){this.relay=e,this.peer=r,this.expiration=n}marshal(){return sr.encode({relay:this.relay.toMultihash().bytes,peer:this.peer.toMultihash().bytes,expiration:BigInt(this.expiration)})}equals(e){return!(!(e instanceof t)||!this.peer.equals(e.peer)||!this.relay.equals(e.relay)||this.expiration!==e.expiration)}};var um={maxOutboundStopStreams:yn},es=class extends Be{components;reservationStore;started;hopTimeout;shutdownController;maxInboundHopStreams;maxOutboundHopStreams;maxOutboundStopStreams;log;constructor(e,r={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:server"),this.components=e,this.started=!1,this.hopTimeout=r?.hopTimeout??Vl,this.maxInboundHopStreams=r.maxInboundHopStreams,this.maxOutboundHopStreams=r.maxOutboundHopStreams,this.maxOutboundStopStreams=r.maxOutboundStopStreams??um.maxOutboundStopStreams,this.reservationStore=new Qo(e,r.reservations),this.shutdownController=new AbortController,this.shutdownController.signal,this.onHop=this.onHop.bind(this)}[Symbol.toStringTag]="@libp2p/circuit-relay-v2-server";isStarted(){return this.started}async start(){this.started||(await this.components.registrar.handle(je,this.onHop,{maxInboundStreams:this.maxInboundHopStreams,maxOutboundStreams:this.maxOutboundHopStreams,runOnLimitedConnection:!0}),this.started=!0)}async stop(){this.reservationStore.clear(),this.shutdownController.abort(),await this.components.registrar.unhandle(je),this.started=!1}async onHop(e,r){this.log("received circuit v2 hop protocol stream from %p",r.remotePeer);let n=AbortSignal.timeout(this.hopTimeout);let o={signal:n},s=Rt(e);try{let i=await s.pb(ee).read(o);if(i?.type==null)throw new Error("request was invalid, could not read from stream");this.log("received",i.type),await this.handleHopProtocol({connection:r,stream:s,request:i},o)}catch(i){this.log.error("error while handling hop - %e",i),await s.pb(ee).write({type:ee.Type.STATUS,status:q.MALFORMED_MESSAGE},o),e.abort(i)}}async handleHopProtocol({stream:e,request:r,connection:n},o){switch(this.log("received hop message"),r.type){case ee.Type.RESERVE:await this.handleReserve({stream:e,request:r,connection:n},o);break;case ee.Type.CONNECT:await this.handleConnect({stream:e,request:r,connection:n},o);break;default:this.log.error("invalid hop request type %s via peer %p",r.type,n.remotePeer),await e.pb(ee).write({type:ee.Type.STATUS,status:q.UNEXPECTED_MESSAGE})}}async handleReserve({stream:e,connection:r},n){let o=e.pb(ee);if(this.log("hop reserve request from %p",r.remotePeer),rr.exactMatch(r.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",r.remotePeer),await o.write({type:ee.Type.STATUS,status:q.PERMISSION_DENIED},n);return}if(await this.components.connectionGater.denyInboundRelayReservation?.(r.remotePeer)===!0){this.log.error("reservation for %p denied by connection gater",r.remotePeer),await o.write({type:ee.Type.STATUS,status:q.PERMISSION_DENIED},n);return}let s=this.reservationStore.reserve(r.remotePeer,r.remoteAddr);try{if(s.status!==q.OK){await o.write({type:ee.Type.STATUS,status:s.status},n);return}if(s.expire!=null){let i=s.expire*1e3-Date.now();await this.components.peerStore.merge(r.remotePeer,{tags:{[Oa]:{value:1,ttl:i}}},n)}await o.write({type:ee.Type.STATUS,status:q.OK,reservation:await this.makeReservation(r.remotePeer,BigInt(s.expire??0)),limit:this.reservationStore.get(r.remotePeer)?.limit},n),this.log("sent confirmation response to %s",r.remotePeer),await o.unwrap().unwrap().close(n)}catch(i){this.log.error("failed to send confirmation response to %p - %e",r.remotePeer,i),this.reservationStore.removeReservation(r.remotePeer);try{await this.components.peerStore.merge(r.remotePeer,{tags:{[Oa]:void 0}},n)}catch(a){this.log.error("failed to untag relay source peer %p - %e",r.remotePeer,a)}}}async makeReservation(e,r){let n=[];for(let s of this.components.addressManager.getAddresses())s.toString().includes("/p2p-circuit")||n.push(s.bytes);let o=await ln.seal(new Jo({peer:e,relay:this.components.peerId,expiration:r}),this.components.privateKey);return{addrs:n,expire:r,voucher:{publicKey:nt(o.publicKey),payloadType:o.payloadType,payload:{peer:e.toMultihash().bytes,relay:this.components.peerId.toMultihash().bytes,expiration:r},signature:o.signature}}}async handleConnect({stream:e,request:r,connection:n},o){let s=e.pb(ee);if(rr.matches(n.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",n.remotePeer),await s.write({type:ee.Type.STATUS,status:q.PERMISSION_DENIED},o);return}this.log("hop connect request from %p",n.remotePeer);let i;try{if(r.peer==null)throw this.log.error("no peer info in hop connect request"),new Error("no peer info in request");r.peer.addrs.forEach(Ke),i=Dr(tt(r.peer.id))}catch(f){this.log.error("invalid hop connect request via peer %p - %e",n.remotePeer,f),await s.write({type:ee.Type.STATUS,status:q.MALFORMED_MESSAGE},o);return}let a=this.reservationStore.get(i);if(a==null){this.log.error("hop connect denied for destination peer %p not having a reservation for %p with status %s",i,n.remotePeer,q.NO_RESERVATION),await s.write({type:ee.Type.STATUS,status:q.NO_RESERVATION},o);return}if(await this.components.connectionGater.denyOutboundRelayedConnection?.(n.remotePeer,i)===!0){this.log.error("hop connect for %p to %p denied by connection gater",n.remotePeer,i),await s.write({type:ee.Type.STATUS,status:q.PERMISSION_DENIED},o);return}let c=this.components.connectionManager.getConnections(i);if(c.length===0){this.log("hop connect denied for destination peer %p not having a connection for %p as there is no destination connection",i,n.remotePeer),await s.write({type:ee.Type.STATUS,status:q.NO_RESERVATION},o);return}let u=c[0],l=await this.stopHop({connection:u,request:{type:qe.Type.CONNECT,peer:{id:n.remotePeer.toMultihash().bytes,addrs:[]},limit:a?.limit}},o);if(l==null){this.log.error("failed to open stream to destination peer %p",u?.remotePeer),await s.write({type:ee.Type.STATUS,status:q.CONNECTION_FAILED},o);return}await s.write({type:ee.Type.STATUS,status:q.OK,limit:a?.limit},o),this.log("connection from %p to %p established - merging streams",n.remotePeer,i),Yl(e.unwrap(),l,this.shutdownController.signal,a,{log:this.log})}async stopHop({connection:e,request:r},n){this.log("starting circuit relay v2 stop request to %s",e.remotePeer);let o=await e.newStream(or,{maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0,...n}),s=Rt(o),i=s.pb(qe);await i.write(r,n);let a;try{a=await i.read(n)}catch(c){this.log.error("error parsing stop message response from %p - %e",e.remotePeer,c)}if(a==null){this.log.error("could not read response from %p",e.remotePeer),await o.close(n);return}if(a.status===q.OK)return this.log("stop request to %p was successful",e.remotePeer),s.unwrap();this.log("stop request failed with code %d",a.status),await o.close(n)}get reservations(){return this.reservationStore.reservations}};var kt=class extends Event{type;detail;constructor(e,r){super(e),this.type=e,this.detail=r}};var ts=class extends Be{components;started;running;topologyId;log;discoveryController;filter;queue;constructor(e,r={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:discover-relays"),this.components=e,this.started=!1,this.running=!1,this.filter=r.filter,this.discoveryController=new AbortController,this.discoveryController.signal,this.dialPeer=this.dialPeer.bind(this),this.onPeer=this.onPeer.bind(this)}isStarted(){return this.started}async start(){this.topologyId=await this.components.registrar.register(je,{filter:this.filter,onConnect:e=>{this.log.trace("discovered relay %p queue (length: %d, active %d)",e,this.queue?.size,this.queue?.running),this.safeDispatchEvent("relay:discover",{detail:e})}}),this.started=!0}stop(){this.topologyId!=null&&this.components.registrar.unregister(this.topologyId),this.running&&this.stopDiscovery(),this.started=!1}startDiscovery(){this.running||(this.log("start discovery"),this.running=!0,this.discoveryController=new AbortController,this.discoveryController.signal,this.components.events.addEventListener("peer:discovery",this.onPeer),Promise.resolve().then(async()=>{this.log("searching peer store for relays");let e=await this.components.peerStore.all({filters:[n=>n.protocols.includes(je)],orders:[()=>Math.random()<.5?1:-1,(n,o)=>{let s=Zl(n),i=Zl(o);return s>i?-1:i>s?1:0}]});for(let n of e)this.log.trace("found relay peer %p in peer store",n.id),this.safeDispatchEvent("relay:discover",{detail:n.id});this.log("found %d relay peers in peer store",e.length);let r=this.queue=new Nr({concurrency:5});this.log("start random walk");for await(let n of this.components.randomWalk.walk({signal:this.discoveryController.signal})){if(this.log.trace("found random peer %p",n.id),r.has(n.id)){this.log.trace("random peer %p was already in queue",n.id);continue}if(this.components.connectionManager.getConnections(n.id)?.length>0){this.log.trace("random peer %p was already connected",n.id);continue}if(!await this.components.connectionManager.isDialable(n.multiaddrs)){this.log.trace("random peer %p was not dialable",n.id,n.multiaddrs.map(o=>o.toString()));continue}r.queued>10&&(this.log.trace("wait for space in queue for %p",n.id),await r.onSizeLessThan(10,{signal:this.discoveryController.signal})),this.log("adding random peer %p to dial queue (length: %d, active %d)",n.id,r.size,r.running),r.add(this.dialPeer,{peerId:n.id,signal:this.discoveryController.signal}).catch(o=>{this.log.error("error opening connection to random peer %p - %e",n.id,o)})}this.log("stop random walk"),await r.onIdle()}).catch(e=>{this.discoveryController.signal.aborted||this.log.error("failed when finding relays on the network - %e",e)}))}stopDiscovery(){this.log("stop discovery"),this.running=!1,this.discoveryController?.abort(),this.queue?.clear(),this.components.events.removeEventListener("peer:discovery",this.onPeer)}onPeer(e){this.log.trace("maybe dialing discovered peer %p",e.detail.id),this.maybeDialPeer(e).catch(r=>{this.log.trace("error dialing discovered peer %p - %e",e.detail.id,r)})}async maybeDialPeer(e){if(this.queue==null)return;let r=e.detail.id,n=e.detail.multiaddrs;if(this.queue.has(r)){this.log.trace("random peer %p was already in queue",r);return}if(this.components.connectionManager.getConnections(r)?.length>0){this.log.trace("random peer %p was already connected",r);return}if(!await this.components.connectionManager.isDialable(n)){this.log.trace("random peer %p was not dialable",r);return}this.queue?.add(this.dialPeer,{peerId:e.detail.id,signal:this.discoveryController.signal}).catch(o=>{this.log.error("error opening connection to discovered peer %p - %e",e.detail.id,o)})}async dialPeer({peerId:e,signal:r}){let n=qo([AbortSignal.timeout(5e3),r]);try{await this.components.connectionManager.openConnection(e,{signal:n})}finally{n.clear()}}};function Zl(t){let e=t.metadata.get("last-dial-success");return e==null?0:new Date(j(e)).getTime()}var qa=class extends Be{connectionManager;addressManager;reservationStore;listeningAddrs;log;listenTimeout;reservationId;relay;constructor(e,r={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:transport:listener"),this.connectionManager=e.connectionManager,this.addressManager=e.addressManager,this.reservationStore=e.reservationStore,this.listeningAddrs=[],this.listenTimeout=r.listenTimeout??Ho,this.reservationStore.addEventListener("relay:removed",this._onRemoveRelayPeer),this.reservationStore.addEventListener("relay:created-reservation",this._onAddRelayPeer)}_onRemoveRelayPeer=e=>{this.log("relay removed %p our relay %p",e.detail.relay,this.relay,this.relay?.equals(e.detail.relay)),this.relay?.equals(e.detail.relay)===!0&&(this.log("relay peer removed %p",e.detail.relay),this.listeningAddrs.forEach(r=>{this.addressManager.removeObservedAddr(r)}),this.listeningAddrs=[],this.safeDispatchEvent("listening"))};_onAddRelayPeer=e=>{let{details:r}=e.detail;if(r.type==="configured"){this.relay?.equals(e.detail.relay)===!0&&this.addedRelay(e.detail);return}r.id===this.reservationId&&this.addedRelay(e.detail)};async listen(e){if(Go.exactMatch(e))this.log("searching for circuit relay servers"),this.reservationId=this.reservationStore.reserveRelay();else if(Yo.exactMatch(e)){this.log("listen on specific relay server %a",e);let r=AbortSignal.timeout(this.listenTimeout);let n=e.decapsulate("/p2p-circuit"),o=await this.connectionManager.openConnection(n,{signal:r});if(!this.reservationStore.hasReservation(o.remotePeer)){this.log("making reservation on peer %p",o.remotePeer);let s=await this.reservationStore.addRelay(o.remotePeer,"configured");this.addedRelay(s)}}else throw new Mt(`Could not listen on p2p-circuit address "${e}"`)}getAddrs(){return[...this.listeningAddrs.values()].flat()}updateAnnounceAddrs(){}async close(){this.reservationStore.cancelReservations(),this.listeningAddrs=[],this.reservationStore.removeEventListener("relay:removed",this._onRemoveRelayPeer),queueMicrotask(()=>{this.safeDispatchEvent("close")})}addedRelay(e){this.log("relay peer added %p",e.relay),this.relay=e.relay;let r=this.listeningAddrs;this.listeningAddrs=e.details.reservation.addrs.map(n=>Ke(n).encapsulate("/p2p-circuit")),this.listeningAddrs.forEach(n=>{this.addressManager.confirmObservedAddr(n,{type:"transport"})}),r.filter(n=>!this.listeningAddrs.some(o=>o.equals(n))).forEach(n=>{this.addressManager.removeObservedAddr(n)}),queueMicrotask(()=>{this.safeDispatchEvent("listening")})}};function Xl(t){return new qa(t)}var Ql="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Jl=(t=21)=>{let e="",r=crypto.getRandomValues(new Uint8Array(t|=0));for(;t--;)e+=Ql[r[t]&63];return e};var lm=60*1e3*10,fm=60*1e3*5,dm=30*1e3,rs=class extends Be{peerId;connectionManager;peerStore;events;reserveQueue;reservations;pendingReservations;maxReservationQueueLength;reservationCompletionTimeout;started;log;relayFilter;constructor(e,r){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:transport:reservation-store"),this.peerId=e.peerId,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.reservations=new Nt,this.pendingReservations=[],this.maxReservationQueueLength=r?.maxReservationQueueLength??ql,this.reservationCompletionTimeout=r?.reservationCompletionTimeout??Ho,this.started=!1,this.relayFilter=Rr(100),this.reserveQueue=new Nr({concurrency:r?.reservationConcurrency??Kl,metricName:"libp2p_relay_reservation_queue",metrics:e.metrics}),this.events.addEventListener("connection:close",n=>{[...this.reservations.values()].find(s=>s.connection===n.detail.id)!=null&&this.#t(n.detail.remotePeer).catch(s=>{this.log.error("could not remove relay %p - %e",n.detail.remotePeer,s)})})}isStarted(){return this.started}start(){this.started=!0}afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[r=>r.tags.has(mn)]});this.log("removing tag from %d old relays",e.length),await Promise.all(e.map(async r=>{await this.peerStore.merge(r.id,{tags:{[mn]:void 0}})})),this.log("redialing %d old relays",e.length),await Promise.all(e.map(async r=>this.addRelay(r.id,"discovered"))),this.#r()}).catch(e=>{this.log.error("failed to clean up and redial old relays during afterStart - %e",e)})}stop(){this.reserveQueue.clear(),this.reservations.forEach(({timeout:e})=>{clearTimeout(e)}),this.reservations.clear(),this.started=!1}reserveRelay(){let e=Jl();return this.pendingReservations.push(e),this.#r(),e}async addRelay(e,r){if(this.peerId.equals(e))throw this.log.trace("not trying to use self as relay"),new Mt("Cannot use self as relay");if(this.reserveQueue.size>this.maxReservationQueueLength)throw new jo("The reservation queue is full");let n=this.reserveQueue.find(e);if(n!=null)return this.log.trace("potential relay peer %p is already in the reservation queue",e),n.join();if(this.relayFilter.has(e.toMultihash().bytes))throw new Mt("The relay was previously invalid");return this.log.trace("try to reserve relay slot with %p",e),this.reserveQueue.add(async()=>{let o=Date.now();try{let s=this.reservations.get(e);if(s!=null){let w=this.connectionManager.getConnections(e),g=!1;if(w.length===0&&this.log("already have relay reservation with %p but we are no longer connected",e),w.map(b=>b.id).includes(s.connection)&&(this.log("already have relay reservation with %p and the original connection is still open",e),g=!0),g&&Na(s.reservation.expire)>lm)return this.log("already have relay reservation with %p but we are still connected and it does not expire soon",e),{relay:e,details:s};g||await this.#t(e)}if(r==="discovered"&&s==null&&this.pendingReservations.length===0)throw new wn("Not making reservation on discovered relay because we do not need any more relays");let i=AbortSignal.timeout(this.reservationCompletionTimeout);let a=await this.connectionManager.openConnection(e,{signal:i});if(rr.matches(a.remoteAddr))throw new Wo("not creating reservation over relayed connection");let c=await this.#e(a,{signal:i}),u=Na(c.expire);this.log("created reservation on relay peer %p, expiry date is %s",e,new Date(Date.now()+u).toString());let l=Math.min(Math.max(u-fm,dm),Math.pow(2,31)-1),f=setTimeout(()=>{this.log("refresh reservation to relay %p",e),this.addRelay(e,r).catch(async w=>{this.log.error("could not refresh reservation to relay %p - %e",e,w),await this.#t(e)}).catch(w=>{this.log.error("could not remove expired reservation to relay %p - %e",e,w)})},l),p;if(r==="discovered"){let w=this.reservations.get(e),g=w?.type==="discovered"?w.id:this.pendingReservations.pop();if(g==null)throw new wn("Made reservation on relay but did not need any more discovered relays");p={timeout:f,reservation:c,type:r,connection:a.id,id:g}}else p={timeout:f,reservation:c,type:r,connection:a.id};s!=null&&clearTimeout(s.timeout),this.reservations.set(e,p),await this.peerStore.merge(e,{tags:{[mn]:{value:1,ttl:u}}}),this.#r();let h={relay:e,details:p};return this.safeDispatchEvent("relay:created-reservation",{detail:h}),h}catch(s){throw r==="discovered"&&s.name==="HadEnoughRelaysError"||this.log.error("could not reserve slot on %p after %dms - %e",e,Date.now()-o,s),(s.name==="DialError"||s.name==="UnsupportedProtocolError")&&this.relayFilter.add(e.toMultihash().bytes),this.#t(e).catch(i=>{this.log.error("could not remove reservation on %p after reserving slot failed - %e",e,i)}),s}},{peerId:e})}hasReservation(e){return this.reservations.has(e)}getReservation(e){return this.reservations.get(e)?.reservation}reservationCount(e){return e==null?this.reservations.size:[...this.reservations.values()].reduce((r,n)=>(n.type===e&&r++,r),0)}cancelReservations(){[...this.reservations.values()].forEach(e=>{clearTimeout(e.timeout)}),this.reservations.clear()}async#e(e,r){r.signal?.throwIfAborted(),this.log("requesting reservation from %p",e.remotePeer);let n=await e.newStream(je,r),s=Rt(n).pb(ee);this.log.trace("send RESERVE to %p",e.remotePeer),await s.write({type:ee.Type.RESERVE},r);let i;try{this.log.trace("reading response from %p",e.remotePeer),i=await s.read(r)}catch(c){throw n.abort(c),c}finally{n.status!=="closed"&&await n.close(r)}if(this.log.trace("read response %s",i.status),i.status===q.OK&&i.reservation!=null){let c=new Set;c.add(e.remoteAddr.toString());for(let u of i.reservation.addrs){let l=Ke(u);l.getComponents().find(f=>f.code===421)==null&&(l=l.encapsulate(`/p2p/${e.remotePeer}`)),l=Ke(l.toString().replace(`/p2p/${e.remotePeer}/p2p/${e.remotePeer}`,`/p2p/${e.remotePeer}`)),c.add(l.toString())}return i.reservation.addrs=[...c].map(u=>Ke(u).bytes),i.reservation}let a=`reservation failed with status ${i.status??"undefined"}`;throw this.log.error(a),new Error(a)}async#t(e){let r=this.reservations.get(e);r!=null&&(this.log("removing relay reservation with %p from local store",e),clearTimeout(r.timeout),this.reservations.delete(e),r.type==="discovered"&&this.pendingReservations.push(r.id),this.safeDispatchEvent("relay:removed",{detail:{relay:e,details:r}}),this.#r(),await this.peerStore.merge(e,{tags:{[mn]:void 0}}))}#r(){if(this.pendingReservations.length===0){this.log.trace("have discovered enough relays"),this.reserveQueue.clear(),this.safeDispatchEvent("relay:found-enough-relays");return}this.relayFilter=Rr(100),this.log("not discovered enough relays %d/%d",this.reservations.size,this.pendingReservations.length),this.safeDispatchEvent("relay:not-enough-relays")}};var za=class extends Ko{stream;init;constructor(e){super({...e,direction:e.stream.direction}),this.init=e,this.stream=e.stream,this.stream.addEventListener("close",r=>{this.onTransportClosed(r.error)}),this.stream.addEventListener("remoteCloseWrite",r=>{this.onRemoteCloseWrite(),this.close().catch(n=>{this.abort(n)})}),this.stream.addEventListener("message",r=>{e.onDataRead?.(r.data),this.onData(r.data)}),this.stream.addEventListener("drain",()=>{this.safeDispatchEvent("drain")})}sendData(e){return this.init.onDataWrite?.(e),{sentBytes:e.byteLength,canSendMore:this.stream.send(e)}}async sendClose(e){await this.stream.close(e)}sendReset(){this.stream.abort(new Error("An error occurred"))}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}};function Ha(t){return new za(t)}var hm=t=>{if(t.peer==null)return!1;try{t.peer.addrs.forEach(Ke)}catch{return!1}return!0},ef={maxInboundStopStreams:yn,maxOutboundStopStreams:yn,stopTimeout:3e4},ns=class{components;discovery;reservationStore;maxInboundStopStreams;maxOutboundStopStreams;started;log;shutdownController;constructor(e,r={}){this.components=e,this.log=e.logger.forComponent("libp2p:circuit-relay:transport"),this.maxInboundStopStreams=r.maxInboundStopStreams??ef.maxInboundStopStreams,this.maxOutboundStopStreams=r.maxOutboundStopStreams??ef.maxOutboundStopStreams,this.shutdownController=new AbortController,this.discovery=new ts(e,{filter:r.discoveryFilter??ka($l,Wl)}),this.discovery.addEventListener("relay:discover",n=>{this.reservationStore.addRelay(n.detail,"discovered").catch(o=>{o.name!=="HadEnoughRelaysError"&&o.name!=="RelayQueueFullError"&&this.log.error("could not add discovered relay %p - %e",n.detail,o)})}),this.reservationStore=new rs(e,r),this.reservationStore.addEventListener("relay:not-enough-relays",()=>{this.discovery?.startDiscovery()}),this.reservationStore.addEventListener("relay:found-enough-relays",()=>{this.discovery?.stopDiscovery()}),this.started=!1,this.onStop=this.onStop.bind(this)}[Symbol.toStringTag]="@libp2p/circuit-relay-v2-transport";[Qa]=["@libp2p/transport","@libp2p/circuit-relay-v2-transport"];get[Ja](){return this.discovery!=null?["@libp2p/identify"]:[]}[Xa]=!0;isStarted(){return this.started}async start(){this.shutdownController=new AbortController,this.shutdownController.signal,await this.components.registrar.handle(or,this.onStop,{maxInboundStreams:this.maxInboundStopStreams,maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0}),await Ya(this.discovery,this.reservationStore),this.started=!0}async stop(){this.shutdownController.abort(),await Ga(this.discovery,this.reservationStore),await this.components.registrar.unhandle(or),this.started=!1}async dial(e,r){let n=e.toString().split("/p2p-circuit"),o=Ke(n[0]),s=Ke(n[n.length-1]),i=o.getComponents().find(h=>h.code===421)?.value,a=s.getComponents().find(h=>h.code===421)?.value;if(i==null||a==null){let h=`ircuit relay dial to ${e.toString()} failed as address did not have both relay and destination PeerIDs`;throw this.log.error(`c${h}`),new An(`C${h}`)}let c=Vi(i),u=Vi(a),f=this.components.connectionManager.getConnections(c)[0];f==null?(await this.components.peerStore.merge(c,{multiaddrs:[o]}),r.onProgress?.(new kt("circuit-relay:open-connection")),f=await this.components.connectionManager.openConnection(c,r)):r.onProgress?.(new kt("circuit-relay:reuse-connection"));let p;try{r.onProgress?.(new kt("circuit-relay:open-hop-stream")),p=await f.newStream(je,r);let h=Rt(p).pb(ee);r.onProgress?.(new kt("circuit-relay:write-connect-message")),await h.write({type:ee.Type.CONNECT,peer:{id:u.toMultihash().bytes,addrs:[Ke(s).bytes]}},r),r.onProgress?.(new kt("circuit-relay:read-connect-response"));let w=await h.read(r);if(w.status!==q.OK)throw new _n(`failed to connect via relay with status ${w?.status?.toString()??"undefined"}`);let g=new xn(w.limit),b=Ha({stream:h.unwrap().unwrap(),remoteAddr:e,localAddr:o.encapsulate(`/p2p-circuit/p2p/${this.components.peerId.toString()}`),onDataRead:g.onData,onDataWrite:g.onData,log:p.log.newScope("circuit-relay:connection")}),x=await this.components.upgrader.upgradeOutbound(b,{...r,limits:g.getLimits()});return x.log("outbound relayed connection established to %p with limits %o, over connection %s",x.remotePeer,w.limit??"none",f.id),x}catch(h){throw this.log.error("circuit relay dial to destination %p via relay %p failed - %e",u,c,h),p?.abort(h),h}}createListener(e){return Xl({peerId:this.components.peerId,connectionManager:this.components.connectionManager,addressManager:this.components.addressManager,reservationStore:this.reservationStore,logger:this.components.logger})}listenFilter(e){return e=Array.isArray(e)?e:[e],e.filter(r=>Yo.exactMatch(r)||Go.exactMatch(r))}dialFilter(e){return e=Array.isArray(e)?e:[e],e.filter(r=>rr.exactMatch(r))}async onStop(e,r){let n=this.components.upgrader.createInboundAbortSignal(this.shutdownController.signal);try{if(!this.reservationStore.hasReservation(r.remotePeer))try{this.log("dialed via relay we did not have a reservation on, start listening on that relay address"),await this.components.transportManager.listen([r.remoteAddr.encapsulate("/p2p-circuit")])}catch(f){this.log.error("failed to listen on a relay peer we were dialed via but did not have a reservation on - %e",f)}let o=Rt(e).pb(qe),s=await o.read({signal:n});if(this.log("new circuit relay v2 stop stream from %p with type %s",r.remotePeer,s.type),s?.type===void 0){this.log.error("type was missing from circuit v2 stop protocol request from %s",r.remotePeer),await o.write({type:qe.Type.STATUS,status:q.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}if(s.type!==qe.Type.CONNECT){this.log.error("invalid stop connect request via peer %p",r.remotePeer),await o.write({type:qe.Type.STATUS,status:q.UNEXPECTED_MESSAGE},{signal:n}),await e.close({signal:n});return}if(!hm(s)){this.log.error("invalid stop connect request via peer %p",r.remotePeer),await o.write({type:qe.Type.STATUS,status:q.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}let i=Dr(tt(s.peer.id));if(await this.components.connectionGater.denyInboundRelayedConnection?.(r.remotePeer,i)===!0){this.log.error("connection gater denied inbound relayed connection from %p",r.remotePeer),await o.write({type:qe.Type.STATUS,status:q.PERMISSION_DENIED},{signal:n}),await e.close({signal:n});return}this.log.trace("sending success response to %p",r.remotePeer),await o.write({type:qe.Type.STATUS,status:q.OK},{signal:n});let a=new xn(s.limit),c=r.remoteAddr.encapsulate(`/p2p-circuit/p2p/${i.toString()}`),u=this.components.addressManager.getAddresses()[0],l=Ha({stream:o.unwrap().unwrap(),remoteAddr:c,localAddr:u,onDataRead:a.onData,onDataWrite:a.onData,log:e.log.newScope("circuit-relay:connection")});await this.components.upgrader.upgradeInbound(l,{limits:a.getLimits(),signal:n}),l.log("inbound relayed connection established to %p with limits %o, over connection %s",i,s.limit??"none",r.id)}finally{n?.clear()}}};function pm(t={}){return e=>new es(e,t)}function mm(t={}){return e=>new ns(e,t)}return uf(ym);})();
|
|
3
3
|
/*! Bundled license information:
|
|
4
4
|
|
|
5
5
|
@noble/curves/utils.js:
|