@libp2p/circuit-relay-v2 4.2.9-868b33379 → 4.2.9-b500071e4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.min.js CHANGED
@@ -1,5 +1,5 @@
1
1
  (function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Libp2PCircuitRelayV2 = factory()}(typeof self !== 'undefined' ? self : this, function () {
2
- "use strict";var Libp2PCircuitRelayV2=(()=>{var ns=Object.defineProperty;var jl=Object.getOwnPropertyDescriptor;var Yl=Object.getOwnPropertyNames;var Zl=Object.prototype.hasOwnProperty;var Te=(r,e)=>{for(var t in e)ns(r,t,{get:e[t],enumerable:!0})},Xl=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Yl(e))!Zl.call(r,s)&&s!==t&&ns(r,s,{get:()=>e[s],enumerable:!(n=jl(e,s))||n.enumerable});return r};var Ql=r=>Xl(ns({},"__esModule",{value:!0}),r);var Xp={};Te(Xp,{RELAY_V2_HOP_CODEC:()=>Ke,RELAY_V2_STOP_CODEC:()=>nr,circuitRelayServer:()=>Yp,circuitRelayTransport:()=>Zp});function Jl(r){return typeof r?.handleEvent=="function"}function ef(r){return(r!==!0&&r!==!1&&r?.once)??!1}var Ie=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){let s=ef(n);super.addEventListener(e,i=>{if(s){let a=this.#e.get(i.type);a!=null&&(a=a.filter(({callback:c})=>c!==t),this.#e.set(i.type,a))}Jl(t)?t.handleEvent(i):t(i)},n);let o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:t,once:s})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let s=this.#e.get(e);s!=null&&(s=s.filter(({callback:o})=>o!==t),this.#e.set(e,s))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var st=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var oe=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 In=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}};var yt=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},Fr=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}};var Dn=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Cn=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var Ln=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var Bn=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}},kt=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 Rn=class extends Event{data;constructor(e,t){super("message",t),this.data=e}},cr=class extends Event{error;local;constructor(e,t,n){super("close",n),this.error=t,this.local=e}},On=class extends cr{constructor(e,t){super(!0,e,t)}},Pn=class extends cr{constructor(e,t){super(!1,e,t)}};var os=Symbol.for("@libp2p/peer-id");var Wa="keep-alive";function Ga(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function ja(...r){let e=[];for(let t of r)Ga(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStart!=null&&await t.beforeStart()})),await Promise.all(e.map(async t=>{await t.start()})),await Promise.all(e.map(async t=>{t.afterStart!=null&&await t.afterStart()}))}async function Ya(...r){let e=[];for(let t of r)Ga(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStop!=null&&await t.beforeStop()})),await Promise.all(e.map(async t=>{await t.stop()})),await Promise.all(e.map(async t=>{t.afterStop!=null&&await t.afterStop()}))}var Xa=Symbol.for("@libp2p/transport");var Za;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Za||(Za={}));var Qa=Symbol.for("@libp2p/service-capabilities"),Ja=Symbol.for("@libp2p/service-dependencies");var us={};Te(us,{base58btc:()=>re,base58flickr:()=>uf});var Bm=new Uint8Array(0);function tc(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function Me(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return Mt(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return Mt(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function rc(r){let e=new Uint8Array(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}var ec=4096;function nc(r){let e=r.length;if(e<=ec)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.subarray(n,n+=ec));return t}function tf(r){return r?.buffer instanceof ArrayBuffer}function Mt(r){return tf(r)?r:r.slice()}function rf(r,e,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),s=0;s<n.length;s++)n[s]=255;for(var o=0;o<r.length;o++){var i=r.charAt(o),a=i.charCodeAt(0);if(n[a]!==255)throw new TypeError(i+" is ambiguous");if(n[a]=o,t){var c=i.toLowerCase().charCodeAt(0),u=i.toUpperCase().charCodeAt(0);c!==a&&(n[c]=o),u!==a&&(n[u]=o)}}var l=r.length,f=r.charAt(0),m=Math.log(l)/Math.log(256),d=Math.log(256)/Math.log(l);function x(y){if(y instanceof Uint8Array||(ArrayBuffer.isView(y)?y=new Uint8Array(y.buffer,y.byteOffset,y.byteLength):Array.isArray(y)&&(y=Uint8Array.from(y))),!(y instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(y.length===0)return"";for(var E=0,A=0,B=0,C=y.length;B!==C&&y[B]===0;)B++,E++;for(var U=(C-B)*d+1>>>0,R=new Uint8Array(U);B!==C;){for(var T=y[B],k=0,M=U-1;(T!==0||k<A)&&M!==-1;M--,k++)T+=256*R[M]>>>0,R[M]=T%l>>>0,T=T/l>>>0;if(T!==0)throw new Error("Non-zero carry");A=k,B++}for(var N=U-A;N!==U&&R[N]===0;)N++;for(var p=f.repeat(E);N<U;++N)p+=r.charAt(R[N]);return p}function S(y){if(typeof y!="string")throw new TypeError("Expected String");if(y.length===0)return new Uint8Array;var E=0;if(y[E]!==" "){for(var A=0,B=0;y[E]===f;)A++,E++;for(var C=(y.length-E)*m+1>>>0,U=new Uint8Array(C);y[E];){var R=n[y.charCodeAt(E)];if(R===255)return;for(var T=0,k=C-1;(R!==0||T<B)&&k!==-1;k--,T++)R+=l*U[k]>>>0,U[k]=R%256>>>0,R=R/256>>>0;if(R!==0)throw new Error("Non-zero carry");B=T,E++}if(y[E]!==" "){for(var M=C-B;M!==C&&U[M]===0;)M++;for(var N=new Uint8Array(A+(C-M)),p=A;M!==C;)N[p++]=U[M++];return N}}}function h(y){var E=S(y);if(E)return E;throw new Error(`Non-${e} character`)}return{encode:x,decodeUnsafe:S,decode:h}}var nf=rf,of=nf,sc=of;var ss=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},is=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,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)}},as=class{decoders;constructor(e){this.decoders=e}or(e){return ic(this,e)}decode(e){let t=e[0],n=this.decoders[t];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(r,e){return new as({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var cs=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new ss(e,t,n),this.decoder=new is(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function ur({name:r,prefix:e,encode:t,decode:n}){return new cs(r,e,t,n)}function gt({name:r,prefix:e,alphabet:t,caseInsensitive:n=!1}){let{encode:s,decode:o}=sc(t,r,n);return ur({prefix:e,name:r,encode:s,decode:i=>Me(o(i))})}function sf(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let u=0;u<s;++u){let l=e[r[u]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|l,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function af(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function cf(r,e){let t={};for(let n=0;n<r.length;++n)if(t[r[n]]=n,e){let s=r[n].toLowerCase(),o=r[n].toUpperCase();s!==r[n]&&(t[s]=n),o!==r[n]&&(t[o]=n)}return t}function se({name:r,prefix:e,bitsPerChar:t,alphabet:n,caseInsensitive:s=!1}){let o=cf(n,s);return ur({prefix:e,name:r,encode(i){return af(i,n,t)},decode(i){return sf(i,o,t,r)}})}var re=gt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),uf=gt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ls={};Te(ls,{base32:()=>bt,base32hex:()=>hf,base32hexpad:()=>mf,base32hexpadupper:()=>yf,base32hexupper:()=>pf,base32pad:()=>ff,base32padupper:()=>df,base32upper:()=>lf,base32z:()=>gf});var bt=se({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5,caseInsensitive:!0}),lf=se({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5,caseInsensitive:!0}),ff=se({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5,caseInsensitive:!0}),df=se({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5,caseInsensitive:!0}),hf=se({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5,caseInsensitive:!0}),pf=se({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5,caseInsensitive:!0}),mf=se({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5,caseInsensitive:!0}),yf=se({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5,caseInsensitive:!0}),gf=se({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var fs={};Te(fs,{base36:()=>Kr,base36upper:()=>bf});var Kr=gt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz",caseInsensitive:!0}),bf=gt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",caseInsensitive:!0});var wf=uc,ac=128,xf=127,Ef=~xf,Sf=Math.pow(2,31);function uc(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Sf;)e[t++]=r&255|ac,r/=128;for(;r&Ef;)e[t++]=r&255|ac,r>>>=7;return e[t]=r|0,uc.bytes=t-n+1,e}var vf=ds,_f=128,cc=127;function ds(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw ds.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&cc)<<s:(i&cc)*Math.pow(2,s),s+=7}while(i>=_f);return ds.bytes=o-n,t}var Af=Math.pow(2,7),Tf=Math.pow(2,14),If=Math.pow(2,21),Df=Math.pow(2,28),Cf=Math.pow(2,35),Lf=Math.pow(2,42),Bf=Math.pow(2,49),Rf=Math.pow(2,56),Of=Math.pow(2,63),Pf=function(r){return r<Af?1:r<Tf?2:r<If?3:r<Df?4:r<Cf?5:r<Lf?6:r<Bf?7:r<Rf?8:r<Of?9:10},Nf={encode:wf,decode:vf,encodingLength:Pf},Uf=Nf,qr=Uf;function zr(r,e=0){return[qr.decode(r,e),qr.decode.bytes]}function lr(r,e,t=0){return qr.encode(r,e,t),e}function fr(r){return qr.encodingLength(r)}function Ze(r,e){let t=e.byteLength,n=fr(r),s=n+fr(t),o=new Uint8Array(s+t);return lr(r,o,0),lr(t,o,n),o.set(e,s),new dr(r,t,e,o)}function Xe(r){let e=Me(r),[t,n]=zr(e),[s,o]=zr(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new dr(t,s,i,e)}function lc(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&tc(r.bytes,t.bytes)}}var dr=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=Mt(n),this.bytes=Mt(s)}};function fc(r,e){let{bytes:t,version:n}=r;return n===0?Mf(t,hs(r),e??re.encoder):Ff(t,hs(r),e??bt.encoder)}var dc=new WeakMap;function hs(r){let e=dc.get(r);if(e==null){let t=new Map;return dc.set(r,t),t}return e}var le=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=Mt(s),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:t}=this;if(e!==Vr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Kf)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}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:t}=this.multihash,n=Ze(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;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 t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??hc(n,s,o.bytes))}else if(t[qf]===!0){let{version:n,multihash:s,code:o}=t,i=Xe(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="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(t!==Vr)throw new Error(`Version 0 CID must use dag-pb (code: ${Vr}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=hc(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Vr,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=Me(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new dr(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,m]=zr(e.subarray(t));return t+=m,f},s=n(),o=Vr;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),u=t+c,l=u-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(e,t){let[n,s]=kf(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return hs(o).set(n,e),o}};function kf(r,e){switch(r[0]){case"Q":{let t=e??re;return[re.prefix,t.decode(`${re.prefix}${r}`)]}case re.prefix:{let t=e??re;return[re.prefix,t.decode(r)]}case bt.prefix:{let t=e??bt;return[bt.prefix,t.decode(r)]}case Kr.prefix:{let t=e??Kr;return[Kr.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function Mf(r,e,t){let{prefix:n}=t;if(n!==re.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function Ff(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}var Vr=112,Kf=18;function hc(r,e,t){let n=fr(r),s=n+fr(e),o=new Uint8Array(s+t.byteLength);return lr(r,o,0),lr(e,o,n),o.set(t,s),o}var qf=Symbol.for("@ipld/js-cid/CID");var ps={};Te(ps,{identity:()=>qe});var pc=0,zf="identity",mc=Me;function Vf(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return Ze(pc,mc(r))}var qe={code:pc,name:zf,encode:mc,digest:Vf};function ce(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function Hf(r){return r.buffer instanceof ArrayBuffer}function _e(r){return Hf(r)?r:r.slice()}async function yc(r,e,t,n){let s=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let o=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},s,_e(e),_e(t.subarray()));return n?.signal?.throwIfAborted(),o}function J(r=0){return new Uint8Array(r)}function xe(r=0){return new Uint8Array(r)}function $f(r){return r?.buffer instanceof ArrayBuffer}function ms(r){if($f(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function Qe(r,e){e==null&&(e=r.reduce((s,o)=>s+o.length,0));let t=xe(e),n=0;for(let s of r)t.set(s,n),n+=s.length;return ms(t)}var bc=Symbol.for("@achingbrain/uint8arraylist");function gc(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let s=t+n.byteLength;if(e<s)return{buf:n,index:e-t};t=s}throw new RangeError("index is out of bounds")}function Un(r){return!!r?.[bc]}var ee=class r{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 t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(Un(n)){t+=n.byteLength;for(let s of n.bufs)this.bufs.push(s)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(Un(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=gc(this.bufs,e);return t.buf[t.index]}set(e,t){let n=gc(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(Un(e))for(let n=0;n<e.length;n++)this.set(t+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,t){let{bufs:n,length:s}=this._subList(e,t);return Qe(n,s)}subarray(e,t){let{bufs:n,length:s}=this._subList(e,t);return n.length===1?n[0]:Qe(n,s)}sublist(e,t){let{bufs:n,length:s}=this._subList(e,t),o=new r;return o.length=s,o.bufs=n,o}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],s=0;for(let o=0;o<this.bufs.length;o++){let i=this.bufs[o],a=s,c=a+i.byteLength;if(s=c,e>=c)continue;let u=e>=a&&e<c,l=t>a&&t<=c;if(u&&l){if(e===a&&t===c){n.push(i);break}let f=e-a;n.push(i.subarray(f,f+(t-e)));break}if(u){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(l){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!Un(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(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let s=n.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let o=256,i=new Int32Array(o);for(let f=0;f<o;f++)i[f]=-1;for(let f=0;f<s;f++)i[n[f]]=f;let a=i,c=this.byteLength-n.byteLength,u=n.byteLength-1,l;for(let f=t;f<=c;f+=l){l=0;for(let m=u;m>=0;m--){let d=this.get(f+m);if(n[m]!==d){l=Math.max(1,m-a[d]);break}}if(l===0)return f}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=xe(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let s=J(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,t,n),this.write(s,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let s=J(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,t,n),this.write(s,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let s=J(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,t,n),this.write(s,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=xe(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let s=J(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,t,n),this.write(s,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let s=J(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,t,n),this.write(s,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let s=J(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,t,n),this.write(s,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let s=J(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,t,n),this.write(s,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let s=J(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,t,n),this.write(s,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!ce(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((s,o)=>s+o.byteLength,0)),n.length=t,n}};var ys={};Te(ys,{base10:()=>Wf});var Wf=gt({prefix:"9",name:"base10",alphabet:"0123456789"});var gs={};Te(gs,{base16:()=>Gf,base16upper:()=>jf});var Gf=se({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4,caseInsensitive:!0}),jf=se({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4,caseInsensitive:!0});var bs={};Te(bs,{base2:()=>Yf});var Yf=se({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var ws={};Te(ws,{base256emoji:()=>ed});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}"),Zf=wc.reduce((r,e,t)=>(r[t]=e,r),[]),Xf=wc.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function Qf(r){return r.reduce((e,t)=>(e+=Zf[t],e),"")}function Jf(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let s=Xf[n];if(s==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}var ed=ur({prefix:"\u{1F680}",name:"base256emoji",encode:Qf,decode:Jf});var Es={};Te(Es,{base64:()=>td,base64pad:()=>rd,base64url:()=>xs,base64urlpad:()=>nd});var td=se({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),rd=se({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),xs=se({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),nd=se({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Ss={};Te(Ss,{base8:()=>od});var od=se({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var vs={};Te(vs,{identity:()=>sd});var sd=ur({prefix:"\0",name:"identity",encode:r=>nc(Me(r)),decode:r=>Me(rc(r))});var y0=new TextEncoder,g0=new TextDecoder;var Ts={};Te(Ts,{sha256:()=>hr,sha512:()=>ud});var cd=20;function As({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new _s(r,e,t,n,s)}var _s=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??cd,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.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,t?.truncate):n.then(s=>xc(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function xc(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return Ze(e,r)}function Sc(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var hr=As({name:"sha2-256",code:18,encode:Sc("SHA-256")}),ud=As({name:"sha2-512",code:19,encode:Sc("SHA-512")});var Hr={...vs,...bs,...Ss,...ys,...gs,...ls,...fs,...us,...Es,...ws},C0={...Ts,...ps};function _c(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var vc=_c("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Is=_c("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=xe(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),ld={utf8:vc,"utf-8":vc,hex:Hr.base16,latin1:Is,ascii:Is,binary:Is,...Hr},kn=ld;function F(r,e="utf8"){let t=kn[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function H(r,e="utf8"){let t=kn[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var fd=parseInt("11111",2),Ds=parseInt("10000000",2),dd=parseInt("01111111",2),Ac={0:$r,1:$r,2:hd,3:yd,4:gd,5:md,6:pd,16:$r,22:$r,48:$r};function at(r,e={offset:0}){let t=r[e.offset]&fd;if(e.offset++,Ac[t]!=null)return Ac[t](r,e);throw new Error("No decoder for tag "+t)}function Wr(r,e){let t=0;if((r[e.offset]&Ds)===Ds){let n=r[e.offset]&dd,s="0x";e.offset++;for(let o=0;o<n;o++,e.offset++)s+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(s,16)}else t=r[e.offset],e.offset++;return t}function $r(r,e){Wr(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=at(r,e);if(n===null)break;t.push(n)}return t}function hd(r,e){let t=Wr(r,e),n=e.offset,s=e.offset+t,o=[];for(let i=n;i<s;i++)i===n&&r[i]===0||o.push(r[i]);return e.offset+=t,Uint8Array.from(o)}function pd(r,e){let t=Wr(r,e),n=e.offset+t,s=r[e.offset];e.offset++;let o=0,i=0;s<40?(o=0,i=s):s<80?(o=1,i=s-40):(o=2,i=s-80);let a=`${o}.${i}`,c=[];for(;e.offset<n;){let u=r[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 md(r,e){return e.offset++,null}function yd(r,e){let t=Wr(r,e),n=r[e.offset];e.offset++;let s=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return s}function gd(r,e){let t=Wr(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function bd(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new ee;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function Cs(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=bd(r.byteLength);return new ee(Uint8Array.from([e.byteLength|Ds]),e)}function De(r){let e=new ee,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new ee(Uint8Array.from([2]),Cs(e),e)}function Mn(r){let e=Uint8Array.from([0]),t=new ee(e,r);return new ee(Uint8Array.from([3]),Cs(t),t)}function wt(r,e=48){let t=new ee;for(let n of r)t.append(n);return new ee(Uint8Array.from([e]),Cs(t),t)}var wd=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),xd=Uint8Array.from([6,5,43,129,4,0,34]),Ed=Uint8Array.from([6,5,43,129,4,0,35]),Sd={ext:!0,kty:"EC",crv:"P-256"},vd={ext:!0,kty:"EC",crv:"P-384"},_d={ext:!0,kty:"EC",crv:"P-521"},Ls=32,Bs=48,Rs=66;function Os(r){let e=at(r);return Tc(e)}function Tc(r){let e=r[1][1][0],t=1,n,s;if(e.byteLength===Ls*2+1)return n=H(e.subarray(t,t+Ls),"base64url"),s=H(e.subarray(t+Ls),"base64url"),new pr({...Sd,key_ops:["verify"],x:n,y:s});if(e.byteLength===Bs*2+1)return n=H(e.subarray(t,t+Bs),"base64url"),s=H(e.subarray(t+Bs),"base64url"),new pr({...vd,key_ops:["verify"],x:n,y:s});if(e.byteLength===Rs*2+1)return n=H(e.subarray(t,t+Rs),"base64url"),s=H(e.subarray(t+Rs),"base64url"),new pr({..._d,key_ops:["verify"],x:n,y:s});throw new oe(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function Ic(r){return wt([De(Uint8Array.from([1])),wt([Ad(r.crv)],160),wt([Mn(new ee(Uint8Array.from([4]),F(r.x??"","base64url"),F(r.y??"","base64url")))],161)]).subarray()}function Ad(r){if(r==="P-256")return wd;if(r==="P-384")return xd;if(r==="P-521")return Ed;throw new oe(`Invalid curve ${r}`)}var pr=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 qe.digest(Je(this))}toCID(){return le.createV1(114,this.toMultihash())}toString(){return re.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ce(this.raw,e.raw)}async verify(e,t,n){return yc(this.jwk,t,e,n)}};function Ps(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}function xt(r,e=""){if(typeof r!="number"){let t=e&&`"${e}" `;throw new TypeError(`${t}expected number, got ${typeof r}`)}if(!Number.isSafeInteger(r)||r<0){let t=e&&`"${e}" `;throw new RangeError(`${t}expected integer >= 0, got ${r}`)}}function Pe(r,e,t=""){let n=Ps(r),s=r?.length,o=e!==void 0;if(!n||o&&s!==e){let i=t&&`"${t}" `,a=o?` of length ${e}`:"",c=n?`length=${s}`:`type=${typeof r}`,u=i+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(u):new TypeError(u)}return r}function Fn(r){if(typeof r!="function"||typeof r.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(xt(r.outputLen),xt(r.blockLen),r.outputLen<1)throw new Error('"outputLen" must be >= 1');if(r.blockLen<1)throw new Error('"blockLen" must be >= 1')}function mr(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function Kn(r,e){Pe(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length<t)throw new RangeError('"digestInto() output" expected to be of length >='+t)}function ut(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function qn(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function ze(r,e){return r<<32-e|r>>>e}var Cc=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Td=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function zn(r){if(Pe(r),Cc)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=Td[r[t]];return e}var ct={_0:48,_9:57,A:65,F:70,a:97,f:102};function Dc(r){if(r>=ct._0&&r<=ct._9)return r-ct._0;if(r>=ct.A&&r<=ct.F)return r-(ct.A-10);if(r>=ct.a&&r<=ct.f)return r-(ct.a-10)}function Gr(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);if(Cc)try{return Uint8Array.fromHex(r)}catch(s){throw s instanceof SyntaxError?new RangeError(s.message):s}let e=r.length,t=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let s=0,o=0;s<t;s++,o+=2){let i=Dc(r.charCodeAt(o)),a=Dc(r.charCodeAt(o+1));if(i===void 0||a===void 0){let c=r[o]+r[o+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+o)}n[s]=i*16+a}return n}function Ns(...r){let e=0;for(let n=0;n<r.length;n++){let s=r[n];Pe(s),e+=s.length}let t=new Uint8Array(e);for(let n=0,s=0;n<r.length;n++){let o=r[n];t.set(o,s),s+=o.length}return t}function Us(r,e={}){let t=(s,o)=>r(o).update(s).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.canXOF=n.canXOF,t.create=s=>r(s),Object.assign(t,e),Object.freeze(t)}function Lc(r=32){xt(r,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(r>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${r}`);return e.getRandomValues(new Uint8Array(r))}var ks=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function Bc(r,e,t){return r&e^~r&t}function Rc(r,e,t){return r&e^r&t^e&t}var jr=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,s){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(e),this.view=qn(this.buffer)}update(e){mr(this),Pe(e);let{view:t,buffer:n,blockLen:s}=this,o=e.length;for(let i=0;i<o;){let a=Math.min(s-this.pos,o-i);if(a===s){let c=qn(e);for(;s<=o-i;i+=s)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){mr(this),Kn(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:s,isLE:o}=this,{pos:i}=this;t[i++]=128,ut(this.buffer.subarray(i)),this.padOffset>s-i&&(this.process(n,0),i=0);for(let f=i;f<s;f++)t[f]=0;n.setBigUint64(s-8,BigInt(this.length*8),o),this.process(n,0);let a=qn(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)a.setUint32(4*f,l[f],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:s,finished:o,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=o,e.length=s,e.pos=a,s%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},lt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var ge=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Vn=BigInt(4294967295),Oc=BigInt(32);function Id(r,e=!1){return e?{h:Number(r&Vn),l:Number(r>>Oc&Vn)}:{h:Number(r>>Oc&Vn)|0,l:Number(r&Vn)|0}}function Pc(r,e=!1){let t=r.length,n=new Uint32Array(t),s=new Uint32Array(t);for(let o=0;o<t;o++){let{h:i,l:a}=Id(r[o],e);[n[o],s[o]]=[i,a]}return[n,s]}var Ms=(r,e,t)=>r>>>t,Fs=(r,e,t)=>r<<32-t|e>>>t,Ft=(r,e,t)=>r>>>t|e<<32-t,Kt=(r,e,t)=>r<<32-t|e>>>t,Yr=(r,e,t)=>r<<64-t|e>>>t-32,Zr=(r,e,t)=>r>>>t-32|e<<64-t;function et(r,e,t,n){let s=(e>>>0)+(n>>>0);return{h:r+t+(s/2**32|0)|0,l:s|0}}var Nc=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),Uc=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,kc=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),Mc=(r,e,t,n,s)=>e+t+n+s+(r/2**32|0)|0,Fc=(r,e,t,n,s)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(s>>>0),Kc=(r,e,t,n,s,o)=>e+t+n+s+o+(r/2**32|0)|0;var Cd=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),Ks=class extends jr{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:s,E:o,F:i,G:a,H:c}=this;return[e,t,n,s,o,i,a,c]}set(e,t,n,s,o,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=s|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let f=0;f<16;f++,t+=4)Et[f]=e.getUint32(t,!1);for(let f=16;f<64;f++){let m=Et[f-15],d=Et[f-2],x=ze(m,7)^ze(m,18)^m>>>3,S=ze(d,17)^ze(d,19)^d>>>10;Et[f]=S+Et[f-7]+x+Et[f-16]|0}let{A:n,B:s,C:o,D:i,E:a,F:c,G:u,H:l}=this;for(let f=0;f<64;f++){let m=ze(a,6)^ze(a,11)^ze(a,25),d=l+m+Bc(a,c,u)+Cd[f]+Et[f]|0,S=(ze(n,2)^ze(n,13)^ze(n,22))+Rc(n,s,o)|0;l=u,u=c,c=a,a=i+d|0,i=o,o=s,s=n,n=d+S|0}n=n+this.A|0,s=s+this.B|0,o=o+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,s,o,i,a,c,u,l)}roundClean(){ut(Et)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),ut(this.buffer)}},qs=class extends Ks{A=lt[0]|0;B=lt[1]|0;C=lt[2]|0;D=lt[3]|0;E=lt[4]|0;F=lt[5]|0;G=lt[6]|0;H=lt[7]|0;constructor(){super(32)}};var qc=Pc(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(r=>BigInt(r))),Ld=qc[0],Bd=qc[1],St=new Uint32Array(80),vt=new Uint32Array(80),zs=class extends jr{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:n,Bl:s,Ch:o,Cl:i,Dh:a,Dl:c,Eh:u,El:l,Fh:f,Fl:m,Gh:d,Gl:x,Hh:S,Hl:h}=this;return[e,t,n,s,o,i,a,c,u,l,f,m,d,x,S,h]}set(e,t,n,s,o,i,a,c,u,l,f,m,d,x,S,h){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=s|0,this.Ch=o|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=m|0,this.Gh=d|0,this.Gl=x|0,this.Hh=S|0,this.Hl=h|0}process(e,t){for(let A=0;A<16;A++,t+=4)St[A]=e.getUint32(t),vt[A]=e.getUint32(t+=4);for(let A=16;A<80;A++){let B=St[A-15]|0,C=vt[A-15]|0,U=Ft(B,C,1)^Ft(B,C,8)^Ms(B,C,7),R=Kt(B,C,1)^Kt(B,C,8)^Fs(B,C,7),T=St[A-2]|0,k=vt[A-2]|0,M=Ft(T,k,19)^Yr(T,k,61)^Ms(T,k,6),N=Kt(T,k,19)^Zr(T,k,61)^Fs(T,k,6),p=kc(R,N,vt[A-7],vt[A-16]),g=Mc(p,U,M,St[A-7],St[A-16]);St[A]=g|0,vt[A]=p|0}let{Ah:n,Al:s,Bh:o,Bl:i,Ch:a,Cl:c,Dh:u,Dl:l,Eh:f,El:m,Fh:d,Fl:x,Gh:S,Gl:h,Hh:y,Hl:E}=this;for(let A=0;A<80;A++){let B=Ft(f,m,14)^Ft(f,m,18)^Yr(f,m,41),C=Kt(f,m,14)^Kt(f,m,18)^Zr(f,m,41),U=f&d^~f&S,R=m&x^~m&h,T=Fc(E,C,R,Bd[A],vt[A]),k=Kc(T,y,B,U,Ld[A],St[A]),M=T|0,N=Ft(n,s,28)^Yr(n,s,34)^Yr(n,s,39),p=Kt(n,s,28)^Zr(n,s,34)^Zr(n,s,39),g=n&o^n&a^o&a,v=s&i^s&c^i&c;y=S|0,E=h|0,S=d|0,h=x|0,d=f|0,x=m|0,{h:f,l:m}=et(u|0,l|0,k|0,M|0),u=a|0,l=c|0,a=o|0,c=i|0,o=n|0,i=s|0;let w=Nc(M,p,v);n=Uc(w,k,N,g),s=w|0}({h:n,l:s}=et(this.Ah|0,this.Al|0,n|0,s|0)),{h:o,l:i}=et(this.Bh|0,this.Bl|0,o|0,i|0),{h:a,l:c}=et(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=et(this.Dh|0,this.Dl|0,u|0,l|0),{h:f,l:m}=et(this.Eh|0,this.El|0,f|0,m|0),{h:d,l:x}=et(this.Fh|0,this.Fl|0,d|0,x|0),{h:S,l:h}=et(this.Gh|0,this.Gl|0,S|0,h|0),{h:y,l:E}=et(this.Hh|0,this.Hl|0,y|0,E|0),this.set(n,s,o,i,a,c,u,l,f,m,d,x,S,h,y,E)}roundClean(){ut(St,vt)}destroy(){this.destroyed=!0,ut(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Vs=class extends zs{Ah=ge[0]|0;Al=ge[1]|0;Bh=ge[2]|0;Bl=ge[3]|0;Ch=ge[4]|0;Cl=ge[5]|0;Dh=ge[6]|0;Dl=ge[7]|0;Eh=ge[8]|0;El=ge[9]|0;Fh=ge[10]|0;Fl=ge[11]|0;Gh=ge[12]|0;Gl=ge[13]|0;Hh=ge[14]|0;Hl=ge[15]|0;constructor(){super(64)}};var yr=Us(()=>new qs,ks(1));var Hn=Us(()=>new Vs,ks(3));var $=(r,e,t)=>Pe(r,e,t),$s=xt,gr=zn,de=(...r)=>Ns(...r),br=r=>Gr(r),qt=Ps,Xr=r=>Lc(r),Wn=BigInt(0),Hs=BigInt(1);function Ve(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}" `;throw new TypeError(t+"expected boolean, got type="+typeof r)}return r}function Gn(r){if(typeof r=="bigint"){if(!$n(r))throw new RangeError("positive bigint expected, got "+r)}else $s(r);return r}function He(r,e=""){if(typeof r!="number"){let t=e&&`"${e}" `;throw new TypeError(t+"expected number, got type="+typeof r)}if(!Number.isSafeInteger(r)){let t=e&&`"${e}" `;throw new RangeError(t+"expected safe integer, got "+r)}}function Qr(r){let e=Gn(r).toString(16);return e.length&1?"0"+e:e}function zc(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);return r===""?Wn:BigInt("0x"+r)}function zt(r){return zc(zn(r))}function tt(r){return zc(zn(Jr(Pe(r)).reverse()))}function jn(r,e){if(xt(e),e===0)throw new RangeError("zero length");r=Gn(r);let t=r.toString(16);if(t.length>e*2)throw new RangeError("number too large");return Gr(t.padStart(e*2,"0"))}function Ws(r,e){return jn(r,e).reverse()}function Vc(r,e){if(r=$(r),e=$(e),r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}function Jr(r){return Uint8Array.from($(r))}function Yn(r){if(typeof r!="string")throw new TypeError("ascii string expected, got "+typeof r);return Uint8Array.from(r,(e,t)=>{let n=e.charCodeAt(0);if(e.length!==1||n>127)throw new RangeError(`string contains non-ASCII character "${r[t]}" with code ${n} at position ${t}`);return n})}var $n=r=>typeof r=="bigint"&&Wn<=r;function Rd(r,e,t){return $n(r)&&$n(e)&&$n(t)&&e<=r&&r<t}function wr(r,e,t,n){if(!Rd(e,t,n))throw new RangeError("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function xr(r){if(r<Wn)throw new Error("expected non-negative bigint, got "+r);let e;for(e=0;r>Wn;r>>=Hs,e+=1);return e}var en=r=>(Hs<<BigInt(r))-Hs;function Hc(r,e,t){if(xt(r,"hashLen"),xt(e,"qByteLen"),typeof t!="function")throw new TypeError("hmacFn must be a function");let n=h=>new Uint8Array(h),s=Uint8Array.of(),o=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(r),u=n(r),l=0,f=()=>{c.fill(1),u.fill(0),l=0},m=(...h)=>t(u,de(c,...h)),d=(h=s)=>{u=m(o,h),c=m(),h.length!==0&&(u=m(i,h),c=m())},x=()=>{if(l++>=a)throw new Error("drbg: tried max amount of iterations");let h=0,y=[];for(;h<e;){c=m();let E=c.slice();y.push(E),h+=c.length}return de(...y)};return(h,y)=>{f(),d(h);let E;for(;(E=y(x()))===void 0;)d();return f(),E}}function $e(r,e={},t={}){if(Object.prototype.toString.call(r)!=="[object Object]")throw new TypeError("expected valid options object");function n(o,i,a){if(!a&&i!=="function"&&!Object.hasOwn(r,o))throw new TypeError(`param "${o}" is invalid: expected own property`);let c=r[o];if(a&&c===void 0)return;let u=typeof c;if(u!==i||c===null)throw new TypeError(`param "${o}" is invalid: expected ${i}, got ${u}`)}let s=(o,i)=>Object.entries(o).forEach(([a,c])=>n(a,c,i));s(e,!1),s(t,!0)}var Gs=()=>{throw new Error("not implemented")};var be=BigInt(0),ie=BigInt(1),Vt=BigInt(2),jc=BigInt(3),Yc=BigInt(4),Zc=BigInt(5),Od=BigInt(7),Xc=BigInt(8),Pd=BigInt(9),Qc=BigInt(16);function ue(r,e){if(e<=be)throw new Error("mod: expected positive modulus, got "+e);let t=r%e;return t>=be?t:e+t}function te(r,e,t){if(e<be)throw new Error("pow2: expected non-negative exponent, got "+e);let n=r;for(;e-- >be;)n*=n,n%=t;return n}function $c(r,e){if(r===be)throw new Error("invert: expected non-zero number");if(e<=be)throw new Error("invert: expected positive modulus, got "+e);let t=ue(r,e),n=e,s=be,o=ie,i=ie,a=be;for(;t!==be;){let u=n/t,l=n-t*u,f=s-i*u,m=o-a*u;n=t,t=l,s=i,o=a,i=f,a=m}if(n!==ie)throw new Error("invert: does not exist");return ue(s,e)}function js(r,e,t){let n=r;if(!n.eql(n.sqr(e),t))throw new Error("Cannot find square root")}function Jc(r,e){let t=r,n=(t.ORDER+ie)/Yc,s=t.pow(e,n);return js(t,s,e),s}function Nd(r,e){let t=r,n=(t.ORDER-Zc)/Xc,s=t.mul(e,Vt),o=t.pow(s,n),i=t.mul(e,o),a=t.mul(t.mul(i,Vt),o),c=t.mul(i,t.sub(a,t.ONE));return js(t,c,e),c}function Ud(r){let e=Er(r),t=eu(r),n=t(e,e.neg(e.ONE)),s=t(e,n),o=t(e,e.neg(n)),i=(r+Od)/Qc;return((a,c)=>{let u=a,l=u.pow(c,i),f=u.mul(l,n),m=u.mul(l,s),d=u.mul(l,o),x=u.eql(u.sqr(f),c),S=u.eql(u.sqr(m),c);l=u.cmov(l,f,x),f=u.cmov(d,m,S);let h=u.eql(u.sqr(f),c),y=u.cmov(l,f,h);return js(u,y,c),y})}function eu(r){if(r<jc)throw new Error("sqrt is not defined for small field");let e=r-ie,t=0;for(;e%Vt===be;)e/=Vt,t++;let n=Vt,s=Er(r);for(;Wc(s,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return Jc;let o=s.pow(n,e),i=(e+ie)/Vt;return function(c,u){let l=c;if(l.is0(u))return u;if(Wc(l,u)!==1)throw new Error("Cannot find square root");let f=t,m=l.mul(l.ONE,o),d=l.pow(u,e),x=l.pow(u,i);for(;!l.eql(d,l.ONE);){if(l.is0(d))return l.ZERO;let S=1,h=l.sqr(d);for(;!l.eql(h,l.ONE);)if(S++,h=l.sqr(h),S===f)throw new Error("Cannot find square root");let y=ie<<BigInt(f-S-1),E=l.pow(m,y);f=S,m=l.sqr(E),d=l.mul(d,m),x=l.mul(x,E)}return x}}function kd(r){return r%Yc===jc?Jc:r%Xc===Zc?Nd:r%Qc===Pd?Ud(r):eu(r)}var ft=(r,e)=>(ue(r,e)&ie)===ie,Md=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ys(r){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=Md.reduce((n,s)=>(n[s]="function",n),e);if($e(r,t),He(r.BYTES,"BYTES"),He(r.BITS,"BITS"),r.BYTES<1||r.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(r.ORDER<=ie)throw new Error("invalid field: expected ORDER > 1, got "+r.ORDER);return r}function Fd(r,e,t){let n=r;if(t<be)throw new Error("invalid exponent, negatives unsupported");if(t===be)return n.ONE;if(t===ie)return e;let s=n.ONE,o=e;for(;t>be;)t&ie&&(s=n.mul(s,o)),o=n.sqr(o),t>>=ie;return s}function tn(r,e,t=!1){let n=r,s=new Array(e.length).fill(t?n.ZERO:void 0),o=e.reduce((a,c,u)=>n.is0(c)?a:(s[u]=a,n.mul(a,c)),n.ONE),i=n.inv(o);return e.reduceRight((a,c,u)=>n.is0(c)?a:(s[u]=n.mul(a,s[u]),n.mul(a,c)),i),s}function Wc(r,e){let t=r,n=(t.ORDER-ie)/Vt,s=t.pow(e,n),o=t.eql(s,t.ONE),i=t.eql(s,t.ZERO),a=t.eql(s,t.neg(t.ONE));if(!o&&!i&&!a)throw new Error("invalid Legendre symbol result");return o?1:i?0:-1}function Kd(r,e){if(e!==void 0&&$s(e),r<=be)throw new Error("invalid n length: expected positive n, got "+r);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let t=xr(r);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected bit length (${t}) >= n.length (${e})`);let n=e!==void 0?e:t,s=Math.ceil(n/8);return{nBitLength:n,nByteLength:s}}var Gc=new WeakMap,Zn=class{ORDER;BITS;BYTES;isLE;ZERO=be;ONE=ie;_lengths;_mod;constructor(e,t={}){if(e<=ie)throw new Error("invalid field: expected ORDER > 1, got "+e);let n;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(n=t.BITS),typeof t.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0}),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=Object.freeze(t.allowedLengths.slice())),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:s,nByteLength:o}=Kd(e,n);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=s,this.BYTES=o,Object.freeze(this)}create(e){return ue(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return be<=e&&e<this.ORDER}is0(e){return e===be}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&ie)===ie}neg(e){return ue(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return ue(e*e,this.ORDER)}add(e,t){return ue(e+t,this.ORDER)}sub(e,t){return ue(e-t,this.ORDER)}mul(e,t){return ue(e*t,this.ORDER)}pow(e,t){return Fd(this,e,t)}div(e,t){return ue(e*$c(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return $c(e,this.ORDER)}sqrt(e){let t=Gc.get(this);return t||Gc.set(this,t=kd(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?Ws(e,this.BYTES):jn(e,this.BYTES)}fromBytes(e,t=!1){$(e);let{_lengths:n,BYTES:s,isLE:o,ORDER:i,_mod:a}=this;if(n){if(e.length<1||!n.includes(e.length)||e.length>s)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let u=new Uint8Array(s);u.set(e,o?0:u.length-e.length),e=u}if(e.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+e.length);let c=o?tt(e):zt(e);if(a&&(c=ue(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return tn(this,e)}cmov(e,t,n){return Ve(n,"condition"),n?t:e}};Object.freeze(Zn.prototype);function Er(r,e={}){return new Zn(r,e)}function tu(r){if(typeof r!="bigint")throw new Error("field order must be bigint");if(r<=ie)throw new Error("field order must be greater than 1");let e=xr(r-ie);return Math.ceil(e/8)}function Zs(r){let e=tu(r);return e+Math.ceil(e/2)}function Xs(r,e,t=!1){$(r);let n=r.length,s=tu(e),o=Math.max(Zs(e),16);if(n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);let i=t?tt(r):zt(r),a=ue(i,e-ie)+ie;return t?Ws(a,s):jn(a,s)}var Sr=BigInt(0),Ht=BigInt(1);function rn(r,e){let t=e.negate();return r?t:e}function $t(r,e){let t=tn(r.Fp,e.map(n=>n.Z));return e.map((n,s)=>r.fromAffine(n.toAffine(t[s])))}function su(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function Qs(r,e){su(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1),s=2**r,o=en(r),i=BigInt(r);return{windows:t,windowSize:n,mask:o,maxNumber:s,shiftBy:i}}function ru(r,e,t){let{windowSize:n,mask:s,maxNumber:o,shiftBy:i}=t,a=Number(r&s),c=r>>i;a>n&&(a-=o,c+=Ht);let u=e*n,l=u+Math.abs(a)-1,f=a===0,m=a<0,d=e%2!==0;return{nextN:c,offset:l,isZero:f,isNeg:m,isNegF:d,offsetF:u}}var Js=new WeakMap,iu=new WeakMap;function ei(r){return iu.get(r)||1}function nu(r){if(r!==Sr)throw new Error("invalid wNAF")}var vr=class{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let s=e;for(;t>Sr;)t&Ht&&(n=n.add(s)),s=s.double(),t>>=Ht;return n}precomputeWindow(e,t){let{windows:n,windowSize:s}=Qs(t,this.bits),o=[],i=e,a=i;for(let c=0;c<n;c++){a=i,o.push(a);for(let u=1;u<s;u++)a=a.add(i),o.push(a);i=a.double()}return o}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let s=this.ZERO,o=this.BASE,i=Qs(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:u,isZero:l,isNeg:f,isNegF:m,offsetF:d}=ru(n,a,i);n=c,l?o=o.add(rn(m,t[d])):s=s.add(rn(f,t[u]))}return nu(n),{p:s,f:o}}wNAFUnsafe(e,t,n,s=this.ZERO){let o=Qs(e,this.bits);for(let i=0;i<o.windows&&n!==Sr;i++){let{nextN:a,offset:c,isZero:u,isNeg:l}=ru(n,i,o);if(n=a,!u){let f=t[c];s=s.add(l?f.negate():f)}}return nu(n),s}getPrecomputes(e,t,n){let s=Js.get(t);return s||(s=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(s=n(s)),Js.set(t,s))),s}cached(e,t,n){let s=ei(e);return this.wNAF(s,this.getPrecomputes(s,e,n),t)}unsafe(e,t,n,s){let o=ei(e);return o===1?this._unsafeLadder(e,t,s):this.wNAFUnsafe(o,this.getPrecomputes(o,e,n),t,s)}createCache(e,t){su(t,this.bits),iu.set(e,t),Js.delete(e)}hasCache(e){return ei(e)!==1}};function au(r,e,t,n){let s=e,o=r.ZERO,i=r.ZERO;for(;t>Sr||n>Sr;)t&Ht&&(o=o.add(s)),n&Ht&&(i=i.add(s)),s=s.double(),t>>=Ht,n>>=Ht;return{p1:o,p2:i}}function ou(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Ys(e),e}else return Er(r,{isLE:t})}function Xn(r,e,t={},n){if(n===void 0&&(n=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let u=e[c];if(!(typeof u=="bigint"&&u>Sr))throw new Error(`CURVE.${c} must be positive bigint`)}let s=ou(e.p,t.Fp,n),o=ou(e.n,t.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!s.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:s,Fn:o}}function Qn(r,e){return function(n){let s=r(n);return{secretKey:s,publicKey:e(s)}}}var _t=BigInt(0),me=BigInt(1),ti=BigInt(2),qd=BigInt(8);function zd(r,e,t,n){let s=r.sqr(t),o=r.sqr(n),i=r.add(r.mul(e.a,s),o),a=r.add(r.ONE,r.mul(e.d,r.mul(s,o)));return r.eql(i,a)}function cu(r,e={}){let t=e,n=Xn("edwards",r,t,t.FpFnLE),{Fp:s,Fn:o}=n,i=n.CURVE,{h:a}=i;$e(t,{},{uvRatio:"function"});let c=ti<<BigInt(o.BYTES*8)-me,u=S=>s.create(S),l=t.uvRatio===void 0?(S,h)=>{try{return{isValid:!0,value:s.sqrt(s.div(S,h))}}catch{return{isValid:!1,value:_t}}}:t.uvRatio;if(!zd(s,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function f(S,h,y=!1){let E=y?me:_t;return wr("coordinate "+S,h,E,c),h}function m(S){if(!(S instanceof d))throw new Error("EdwardsPoint expected")}class d{static BASE=new d(i.Gx,i.Gy,me,u(i.Gx*i.Gy));static ZERO=new d(_t,me,me,_t);static Fp=s;static Fn=o;X;Y;Z;T;constructor(h,y,E,A){this.X=f("x",h),this.Y=f("y",y),this.Z=f("z",E,!0),this.T=f("t",A),Object.freeze(this)}static CURVE(){return i}static fromAffine(h){if(h instanceof d)throw new Error("extended point not allowed");let{x:y,y:E}=h||{};return f("x",y),f("y",E),new d(y,E,me,u(y*E))}static fromBytes(h,y=!1){let E=s.BYTES,{a:A,d:B}=i;h=Jr($(h,E,"point")),Ve(y,"zip215");let C=Jr(h),U=h[E-1];C[E-1]=U&-129;let R=tt(C),T=y?c:s.ORDER;wr("point.y",R,_t,T);let k=u(R*R),M=u(k-me),N=u(B*k-A),{isValid:p,value:g}=l(M,N);if(!p)throw new Error("bad point: invalid y coordinate");let v=(g&me)===me,w=(U&128)!==0;if(!y&&g===_t&&w)throw new Error("bad point: x=0 and x_0=1");return w!==v&&(g=u(-g)),d.fromAffine({x:g,y:R})}static fromHex(h,y=!1){return d.fromBytes(br(h),y)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(h=8,y=!0){return x.createCache(this,h),y||this.multiply(ti),this}assertValidity(){let h=this,{a:y,d:E}=i;if(h.is0())throw new Error("bad point: ZERO");let{X:A,Y:B,Z:C,T:U}=h,R=u(A*A),T=u(B*B),k=u(C*C),M=u(k*k),N=u(R*y),p=u(k*u(N+T)),g=u(M+u(E*u(R*T)));if(p!==g)throw new Error("bad point: equation left != right (1)");let v=u(A*B),w=u(C*U);if(v!==w)throw new Error("bad point: equation left != right (2)")}equals(h){m(h);let{X:y,Y:E,Z:A}=this,{X:B,Y:C,Z:U}=h,R=u(y*U),T=u(B*A),k=u(E*U),M=u(C*A);return R===T&&k===M}is0(){return this.equals(d.ZERO)}negate(){return new d(u(-this.X),this.Y,this.Z,u(-this.T))}double(){let{a:h}=i,{X:y,Y:E,Z:A}=this,B=u(y*y),C=u(E*E),U=u(ti*u(A*A)),R=u(h*B),T=y+E,k=u(u(T*T)-B-C),M=R+C,N=M-U,p=R-C,g=u(k*N),v=u(M*p),w=u(k*p),b=u(N*M);return new d(g,v,b,w)}add(h){m(h);let{a:y,d:E}=i,{X:A,Y:B,Z:C,T:U}=this,{X:R,Y:T,Z:k,T:M}=h,N=u(A*R),p=u(B*T),g=u(U*E*M),v=u(C*k),w=u((A+B)*(R+T)-N-p),b=v-g,_=v+g,D=u(p-y*N),I=u(w*b),L=u(_*D),P=u(w*D),V=u(b*_);return new d(I,L,V,P)}subtract(h){return m(h),this.add(h.negate())}multiply(h){if(!o.isValidNot0(h))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:y,f:E}=x.cached(this,h,A=>$t(d,A));return $t(d,[y,E])[0]}multiplyUnsafe(h){if(!o.isValid(h))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return h===_t?d.ZERO:this.is0()||h===me?this:x.unsafe(this,h,y=>$t(d,y))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return x.unsafe(this,i.n).is0()}toAffine(h){let y=this,E=h,{X:A,Y:B,Z:C}=y,U=y.is0();E==null&&(E=U?qd:s.inv(C));let R=u(A*E),T=u(B*E),k=s.mul(C,E);if(U)return{x:_t,y:me};if(k!==me)throw new Error("invZ was invalid");return{x:R,y:T}}clearCofactor(){return a===me?this:this.multiplyUnsafe(a)}toBytes(){let{x:h,y}=this.toAffine(),E=s.toBytes(y);return E[E.length-1]|=h&me?128:0,E}toHex(){return gr(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let x=new vr(d,o.BITS);return o.BITS>=8&&d.BASE.precompute(8),Object.freeze(d.prototype),Object.freeze(d),d}var Jn=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e}static fromBytes(e){Gs()}static fromHex(e){Gs()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return gr(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.ep.precompute(e,t),this}};function uu(r,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');let n=e,s=t;$e(s,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:o}=s,{BASE:i,Fp:a,Fn:c}=r,u=n.outputLen,l=2*a.BYTES;if(u!==void 0&&(He(u,"hash.outputLen"),u!==l))throw new Error(`hash.outputLen must be ${l}, got ${u}`);let f=s.randomBytes===void 0?Xr:s.randomBytes,m=s.adjustScalarBytes===void 0?p=>p:s.adjustScalarBytes,d=s.domain===void 0?(p,g,v)=>{if(Ve(v,"phflag"),g.length||v)throw new Error("Contexts/pre-hash are not supported");return p}:s.domain;function x(p){return c.create(tt(p))}function S(p){let g=R.secretKey;$(p,R.secretKey,"secretKey");let v=$(n(p),2*g,"hashedSecretKey"),w=m(v.slice(0,g)),b=v.slice(g,2*g),_=x(w);return{head:w,prefix:b,scalar:_}}function h(p){let{head:g,prefix:v,scalar:w}=S(p),b=i.multiply(w),_=b.toBytes();return{head:g,prefix:v,scalar:w,point:b,pointBytes:_}}function y(p){return h(p).pointBytes}function E(p=Uint8Array.of(),...g){let v=de(...g);return x(n(d(v,$(p,void 0,"context"),!!o)))}function A(p,g,v={}){p=$(p,void 0,"message"),o&&(p=o(p));let{prefix:w,scalar:b,pointBytes:_}=h(g),D=E(v.context,w,p),I=i.multiply(D).toBytes(),L=E(v.context,I,_,p),P=c.create(D+L*b);if(!c.isValid(P))throw new Error("sign failed: invalid s");let V=de(I,c.toBytes(P));return $(V,R.signature,"result")}let B={zip215:s.zip215};function C(p,g,v,w=B){let{context:b}=w,_=w.zip215===void 0?!!B.zip215:w.zip215,D=R.signature;p=$(p,D,"signature"),g=$(g,void 0,"message"),v=$(v,R.publicKey,"publicKey"),_!==void 0&&Ve(_,"zip215"),o&&(g=o(g));let I=D/2,L=p.subarray(0,I),P=tt(p.subarray(I,D)),V,j,q;try{V=r.fromBytes(v,_),j=r.fromBytes(L,_),q=i.multiplyUnsafe(P)}catch{return!1}if(!_&&V.isSmallOrder())return!1;let fe=E(b,L,v,g);return j.add(V.multiplyUnsafe(fe)).subtract(q).clearCofactor().is0()}let U=a.BYTES,R={secretKey:U,publicKey:U,signature:2*U,seed:U};function T(p){return p=p===void 0?f(R.seed):p,$(p,R.seed,"seed")}function k(p){return qt(p)&&p.length===R.secretKey}function M(p,g){try{return!!r.fromBytes(p,g===void 0?B.zip215:g)}catch{return!1}}let N={getExtendedPublicKey:h,randomSecretKey:T,isValidSecretKey:k,isValidPublicKey:M,toMontgomery(p){let{y:g}=r.fromBytes(p),v=R.publicKey,w=v===32;if(!w&&v!==57)throw new Error("only defined for 25519 and 448");let b=w?a.div(me+g,me-g):a.div(g-me,g+me);return a.toBytes(b)},toMontgomerySecret(p){let g=R.secretKey;$(p,g);let v=n(p.subarray(0,g));return m(v).subarray(0,g)}};return Object.freeze(R),Object.freeze(N),Object.freeze({keygen:Qn(T,y),getPublicKey:y,sign:A,verify:C,utils:N,Point:r,lengths:R})}function nn(r,e){if(He(r),He(e),e<0||e>4)throw new Error("invalid I2OSP length: "+e);if(r<0||r>2**(8*e)-1)throw new Error("invalid I2OSP input: "+r);let t=Array.from({length:e}).fill(0);for(let n=e-1;n>=0;n--)t[n]=r&255,r>>>=8;return new Uint8Array(t)}function Vd(r,e){let t=new Uint8Array(r.length);for(let n=0;n<r.length;n++)t[n]=r[n]^e[n];return t}function Hd(r){if(!qt(r)&&typeof r!="string")throw new Error("DST must be Uint8Array or ascii string");let e=typeof r=="string"?Yn(r):r;if(e.length===0)throw new Error("DST must be non-empty");return e}function ri(r,e,t,n){$(r),He(t),e=Hd(e),e.length>255&&(e=n(de(Yn("H2C-OVERSIZE-DST-"),e)));let{outputLen:s,blockLen:o}=n,i=Math.ceil(t/s);if(t>65535||i>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=de(e,nn(e.length,1)),c=new Uint8Array(o),u=nn(t,2),l=new Array(i),f=n(de(c,r,u,nn(0,1),a));l[0]=n(de(f,nn(1,1),a));for(let d=1;d<i;d++){let x=[Vd(f,l[d-1]),nn(d+1,1),a];l[d]=n(de(...x))}return de(...l).slice(0,t)}var lu="HashToScalar-";var $d=BigInt(0),dt=BigInt(1),fu=BigInt(2);var Wd=BigInt(5),Gd=BigInt(8),_r=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),ii={p:_r,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Gd,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function jd(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),s=BigInt(80),o=_r,a=r*r%o*r%o,c=te(a,fu,o)*a%o,u=te(c,dt,o)*r%o,l=te(u,Wd,o)*u%o,f=te(l,e,o)*l%o,m=te(f,t,o)*f%o,d=te(m,n,o)*m%o,x=te(d,s,o)*d%o,S=te(x,s,o)*d%o,h=te(S,e,o)*l%o;return{pow_p_5_8:te(h,fu,o)*r%o,b2:a}}function Yd(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var ni=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function ai(r,e){let t=_r,n=ue(e*e*e,t),s=ue(n*n*e,t),o=jd(r*s).pow_p_5_8,i=ue(r*n*o,t),a=ue(e*i*i,t),c=i,u=ue(i*ni,t),l=a===r,f=a===ue(-r,t),m=a===ue(-r*ni,t);return l&&(i=c),(f||m)&&(i=u),ft(i,t)&&(i=ue(-i,t)),{isValid:l||f,value:i}}var Tt=cu(ii,{uvRatio:ai}),At=Tt.Fp,pu=Tt.Fn;function Zd(r){return uu(Tt,Hn,Object.assign({adjustScalarBytes:Yd,zip215:!0},r))}var mu=Zd({});var oi=ni,Xd=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Qd=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),Jd=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),eh=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),du=r=>ai(dt,r),th=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),si=r=>At.create(tt(r)&th);function hu(r){let{d:e}=ii,t=_r,n=y=>At.create(y),s=n(oi*r*r),o=n((s+dt)*Jd),i=BigInt(-1),a=n((i-e*s)*n(s+e)),{isValid:c,value:u}=ai(o,a),l=n(u*r);ft(l,t)||(l=n(-l)),c||(u=l),c||(i=s);let f=n(i*(s-dt)*eh-a),m=u*u,d=n((u+u)*a),x=n(f*Xd),S=n(dt-m),h=n(dt+m);return new Tt(n(d*h),n(S*x),n(x*h),n(d*S))}var It=class r extends Jn{static BASE=new r(Tt.BASE);static ZERO=new r(Tt.ZERO);static Fp=At;static Fn=pu;constructor(e){super(e)}static fromAffine(e){return new r(Tt.fromAffine(e))}assertSame(e){if(!(e instanceof r))throw new Error("RistrettoPoint expected")}init(e){return new r(e)}static fromBytes(e){Pe(e,32);let{a:t,d:n}=ii,s=_r,o=B=>At.create(B),i=si(e);if(!Vc(At.toBytes(i),e)||ft(i,s))throw new Error("invalid ristretto255 encoding 1");let a=o(i*i),c=o(dt+t*a),u=o(dt-t*a),l=o(c*c),f=o(u*u),m=o(t*n*l-f),{isValid:d,value:x}=du(o(m*f)),S=o(x*u),h=o(x*S*m),y=o((i+i)*S);ft(y,s)&&(y=o(-y));let E=o(c*h),A=o(y*E);if(!d||ft(A,s)||E===$d)throw new Error("invalid ristretto255 encoding 2");return new r(new Tt(y,E,dt,A))}static fromHex(e){return r.fromBytes(Gr(e))}toBytes(){let{X:e,Y:t,Z:n,T:s}=this.ep,o=_r,i=h=>At.create(h),a=i(i(n+t)*i(n-t)),c=i(e*t),u=i(c*c),{value:l}=du(i(a*u)),f=i(l*a),m=i(l*c),d=i(f*m*s),x;if(ft(s*d,o)){let h=i(t*oi),y=i(e*oi);e=h,t=y,x=i(f*Qd)}else x=m;ft(e*d,o)&&(t=i(-t));let S=i((n-t)*x);return ft(S,o)&&(S=i(-S)),At.toBytes(S)}equals(e){this.assertSame(e);let{X:t,Y:n}=this.ep,{X:s,Y:o}=e.ep,i=u=>At.create(u),a=i(t*o)===i(n*s),c=i(n*o)===i(t*s);return a||c}is0(){return this.equals(r.ZERO)}};Object.freeze(It.BASE);Object.freeze(It.ZERO);Object.freeze(It.prototype);Object.freeze(It);var rh=Object.freeze({Point:It,hashToCurve(r,e){let t=e?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":e.DST,n=ri(r,t,64,Hn);return rh.deriveToCurve(n)},hashToScalar(r,e={DST:lu}){let t=ri(r,e.DST,64,Hn);return pu.create(tt(t))},deriveToCurve(r){Pe(r,64);let e=si(r.subarray(0,32)),t=hu(e),n=si(r.subarray(32,64)),s=hu(n);return new It(t.add(s))}});var on=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},eo=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var Fe={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new eo("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 to=32;var ci,nh=(async()=>{try{return await Fe.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function oh(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await Fe.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await Fe.get().subtle.verify({name:"Ed25519"},n,_e(e),_e(t instanceof Uint8Array?t:t.subarray()))}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function sh(r,e,t){return mu.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function yu(r,e,t){return ci==null&&(ci=await nh),ci?oh(r,e,t):sh(r,e,t)}function ro(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var no=class{type="Ed25519";raw;constructor(e){this.raw=ui(e,to)}toMultihash(){return qe.digest(Je(this))}toCID(){return le.createV1(114,this.toMultihash())}toString(){return re.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ce(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let s=yu(this.raw,t,e);return ro(s)?s.then(o=>(n?.signal?.throwIfAborted(),o)):s}};function li(r){return r=ui(r,to),new no(r)}function ui(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new oe(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var ah=Math.pow(2,7),ch=Math.pow(2,14),uh=Math.pow(2,21),fi=Math.pow(2,28),di=Math.pow(2,35),hi=Math.pow(2,42),pi=Math.pow(2,49),Y=128,Ee=127;function Ce(r){if(r<ah)return 1;if(r<ch)return 2;if(r<uh)return 3;if(r<fi)return 4;if(r<di)return 5;if(r<hi)return 6;if(r<pi)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Ar(r,e,t=0){switch(Ce(r)){case 8:e[t++]=r&255|Y,r/=128;case 7:e[t++]=r&255|Y,r/=128;case 6:e[t++]=r&255|Y,r/=128;case 5:e[t++]=r&255|Y,r/=128;case 4:e[t++]=r&255|Y,r>>>=7;case 3:e[t++]=r&255|Y,r>>>=7;case 2:e[t++]=r&255|Y,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function lh(r,e,t=0){switch(Ce(r)){case 8:e.set(t++,r&255|Y),r/=128;case 7:e.set(t++,r&255|Y),r/=128;case 6:e.set(t++,r&255|Y),r/=128;case 5:e.set(t++,r&255|Y),r/=128;case 4:e.set(t++,r&255|Y),r>>>=7;case 3:e.set(t++,r&255|Y),r>>>=7;case 2:e.set(t++,r&255|Y),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function mi(r,e){let t=r[e],n=0;if(n+=t&Ee,t<Y||(t=r[e+1],n+=(t&Ee)<<7,t<Y)||(t=r[e+2],n+=(t&Ee)<<14,t<Y)||(t=r[e+3],n+=(t&Ee)<<21,t<Y)||(t=r[e+4],n+=(t&Ee)*fi,t<Y)||(t=r[e+5],n+=(t&Ee)*di,t<Y)||(t=r[e+6],n+=(t&Ee)*hi,t<Y)||(t=r[e+7],n+=(t&Ee)*pi,t<Y))return n;throw new RangeError("Could not decode varint")}function fh(r,e){let t=r.get(e),n=0;if(n+=t&Ee,t<Y||(t=r.get(e+1),n+=(t&Ee)<<7,t<Y)||(t=r.get(e+2),n+=(t&Ee)<<14,t<Y)||(t=r.get(e+3),n+=(t&Ee)<<21,t<Y)||(t=r.get(e+4),n+=(t&Ee)*fi,t<Y)||(t=r.get(e+5),n+=(t&Ee)*di,t<Y)||(t=r.get(e+6),n+=(t&Ee)*hi,t<Y)||(t=r.get(e+7),n+=(t&Ee)*pi,t<Y))return n;throw new RangeError("Could not decode varint")}function Tr(r,e,t=0){return e==null&&(e=xe(Ce(r))),e instanceof Uint8Array?Ar(r,e,t):lh(r,e,t)}function sn(r,e=0){return r instanceof Uint8Array?mi(r,e):fh(r,e)}var gi=new Float32Array([-0]),Dt=new Uint8Array(gi.buffer);function bu(r,e,t){gi[0]=r,e[t]=Dt[0],e[t+1]=Dt[1],e[t+2]=Dt[2],e[t+3]=Dt[3]}function wu(r,e){return Dt[0]=r[e],Dt[1]=r[e+1],Dt[2]=r[e+2],Dt[3]=r[e+3],gi[0]}var bi=new Float64Array([-0]),Se=new Uint8Array(bi.buffer);function xu(r,e,t){bi[0]=r,e[t]=Se[0],e[t+1]=Se[1],e[t+2]=Se[2],e[t+3]=Se[3],e[t+4]=Se[4],e[t+5]=Se[5],e[t+6]=Se[6],e[t+7]=Se[7]}function Eu(r,e){return Se[0]=r[e],Se[1]=r[e+1],Se[2]=r[e+2],Se[3]=r[e+3],Se[4]=r[e+4],Se[5]=r[e+5],Se[6]=r[e+6],Se[7]=r[e+7],bi[0]}var dh=BigInt(Number.MAX_SAFE_INTEGER),hh=BigInt(Number.MIN_SAFE_INTEGER),Ne=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+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 t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(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,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return Wt;if(e<dh&&e>hh)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,s=e-(n<<32n);return t&&(n=~n|0n,s=~s|0n,++s>Su&&(s=0n,++n>Su&&(n=0n))),new r(Number(s),Number(n))}static fromNumber(e){if(e===0)return Wt;let t=e<0;t&&(e=-e);let n=e>>>0,s=(e-n)/4294967296>>>0;return t&&(s=~s>>>0,n=~n>>>0,++n>4294967295&&(n=0,++s>4294967295&&(s=0))),new r(n,s)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):Wt}},Wt=new Ne(0,0);Wt.toBigInt=function(){return 0n};Wt.zzEncode=Wt.zzDecode=function(){return this};Wt.length=function(){return 1};var Su=4294967296n;function vu(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function _u(r,e,t){if(t-e<1)return"";let s,o=[],i=0,a;for(;e<t;)a=r[e++],a<128?o[i++]=a:a>191&&a<224?o[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,o[i++]=55296+(a>>10),o[i++]=56320+(a&1023)):o[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((s??(s=[])).push(String.fromCharCode.apply(String,o)),i=0);return s!=null?(i>0&&s.push(String.fromCharCode.apply(String,o.slice(0,i))),s.join("")):String.fromCharCode.apply(String,o.slice(0,i))}function wi(r,e,t){let n=t,s,o;for(let i=0;i<r.length;++i)s=r.charCodeAt(i),s<128?e[t++]=s:s<2048?(e[t++]=s>>6|192,e[t++]=s&63|128):(s&64512)===55296&&((o=r.charCodeAt(i+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++i,e[t++]=s>>18|240,e[t++]=s>>12&63|128,e[t++]=s>>6&63|128,e[t++]=s&63|128):(e[t++]=s>>12|224,e[t++]=s>>6&63|128,e[t++]=s&63|128);return t-n}function We(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function oo(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var xi=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,We(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 We(this,4);return oo(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw We(this,4);return oo(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw We(this,4);let e=wu(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw We(this,4);let e=Eu(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw We(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return _u(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw We(this,e);this.pos+=e}else do if(this.pos>=this.len)throw We(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),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*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;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw We(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw We(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw We(this,8);let e=oo(this.buf,this.pos+=4),t=oo(this.buf,this.pos+=4);return new Ne(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=mi(this.buf,this.pos);return this.pos+=Ce(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 an(r){return new xi(r instanceof Uint8Array?r:r.subarray())}function Le(r,e,t){let n=an(r);return e.decode(n,void 0,t)}function Ei(r){let e=r??8192,t=e>>>1,n,s=e;return function(i){if(i<1||i>t)return xe(i);s+i>e&&(n=xe(e),s=0);let a=n.subarray(s,s+=i);return(s&7)!==0&&(s=(s|7)+1),a}}var Gt=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function Si(){}var _i=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},ph=Ei();function mh(r){return globalThis.Buffer!=null?xe(r):ph(r)}var un=class{len;head;tail;states;constructor(){this.len=0,this.head=new Gt(Si,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new Gt(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Ai((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(so,10,Ne.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Ne.fromBigInt(e);return this._push(so,t.length(),t)}uint64Number(e){return this._push(Ar,Ce(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 t=Ne.fromBigInt(e).zzEncode();return this._push(so,t.length(),t)}sint64Number(e){let t=Ne.fromNumber(e).zzEncode();return this._push(so,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(vi,1,e?1:0)}fixed32(e){return this._push(cn,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Ne.fromBigInt(e);return this._push(cn,4,t.lo)._push(cn,4,t.hi)}fixed64Number(e){let t=Ne.fromNumber(e);return this._push(cn,4,t.lo)._push(cn,4,t.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(bu,4,e)}double(e){return this._push(xu,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(vi,1,0):this.uint32(t)._push(gh,t,e)}string(e){let t=vu(e);return t!==0?this.uint32(t)._push(wi,t,e):this._push(vi,1,0)}fork(){return this.states=new _i(this),this.head=this.tail=new Gt(Si,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 Gt(Si,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=mh(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function vi(r,e,t){e[t]=r&255}function yh(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var Ai=class extends Gt{next;constructor(e,t){super(yh,e,t),this.next=void 0}};function so(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function cn(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function gh(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(un.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(bh,e,r),this},un.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(wh,e,r),this});function bh(r,e,t){e.set(r,t)}function wh(r,e,t){r.length<40?wi(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(F(r),t)}function Ti(){return new un}function Be(r,e){let t=Ti();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}function*Re(r,e,t){let n=an(r);yield*e.stream(n,void 0,"$",t)}var io={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function ao(r,e,t,n,s){return{name:r,type:e,encode:t,decode:n,stream:s}}function jt(r){function e(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let t=function(i,a){let c=e(i);a.int32(c)},n=function(i){let a=i.int32();return e(a)},s=function*(i){let a=i.int32();yield e(a)};return ao("enum",io.VARINT,t,n,s)}function Oe(r,e,t){return ao("message",io.LENGTH_DELIMITED,r,e,t)}var Yt=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var ne;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(ne||(ne={}));var Ii;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(Ii||(Ii={}));(function(r){r.codec=()=>jt(Ii)})(ne||(ne={}));var rt;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.Type!=null&&(i.uint32(8),ne.codec().encode(o.Type,i)),o.Data!=null&&(i.uint32(18),i.bytes(o.Data)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{c.Type=ne.codec().decode(o);break}case 2:{c.Data=o.bytes();break}default:{o.skipType(l&7);break}}}return c},function*(o,i,a,c={}){let u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{yield{field:`${a}.Type`,value:ne.codec().decode(o)};break}case 2:{yield{field:`${a}.Data`,value:o.bytes()};break}default:{o.skipType(l&7);break}}}})),e);function t(o){return Be(o,r.codec())}r.encode=t;function n(o,i){return Le(o,r.codec(),i)}r.decode=n;function s(o,i){return Re(o,r.codec(),i)}r.stream=s})(rt||(rt={}));var Di;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.Type!=null&&(i.uint32(8),ne.codec().encode(o.Type,i)),o.Data!=null&&(i.uint32(18),i.bytes(o.Data)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{c.Type=ne.codec().decode(o);break}case 2:{c.Data=o.bytes();break}default:{o.skipType(l&7);break}}}return c},function*(o,i,a,c={}){let u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{yield{field:`${a}.Type`,value:ne.codec().decode(o)};break}case 2:{yield{field:`${a}.Data`,value:o.bytes()};break}default:{o.skipType(l&7);break}}}})),e);function t(o){return Be(o,r.codec())}r.encode=t;function n(o,i){return Le(o,r.codec(),i)}r.decode=n;function s(o,i){return Re(o,r.codec(),i)}r.stream=s})(Di||(Di={}));var fn={};Te(fn,{MAX_RSA_KEY_SIZE:()=>Ci,generateRSAKeyPair:()=>Lu,jwkToJWKKeyPair:()=>Bu,jwkToPkcs1:()=>vh,jwkToPkix:()=>Oi,jwkToRSAPrivateKey:()=>ki,pkcs1MessageToJwk:()=>Bi,pkcs1MessageToRSAPrivateKey:()=>Pi,pkcs1ToJwk:()=>Sh,pkcs1ToRSAPrivateKey:()=>Cu,pkixMessageToJwk:()=>Ri,pkixMessageToRSAPublicKey:()=>Ui,pkixToJwk:()=>_h,pkixToRSAPublicKey:()=>Ni});var Ir=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=fn.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return le.createV1(114,this._multihash)}toString(){return re.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ce(this.raw,e.raw)}verify(e,t,n){return Du(this.jwk,t,e,n)}},ln=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=fn.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ce(this.raw,e.raw)}sign(e,t){return Iu(this.jwk,e,t)}};var Ci=8192,Li=18,xh=1062,Eh=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function Sh(r){let e=at(r);return Bi(e)}function Bi(r){return{n:H(r[1],"base64url"),e:H(r[2],"base64url"),d:H(r[3],"base64url"),p:H(r[4],"base64url"),q:H(r[5],"base64url"),dp:H(r[6],"base64url"),dq:H(r[7],"base64url"),qi:H(r[8],"base64url"),kty:"RSA"}}function vh(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new oe("JWK was missing components");return wt([De(Uint8Array.from([0])),De(F(r.n,"base64url")),De(F(r.e,"base64url")),De(F(r.d,"base64url")),De(F(r.p,"base64url")),De(F(r.q,"base64url")),De(F(r.dp,"base64url")),De(F(r.dq,"base64url")),De(F(r.qi,"base64url"))]).subarray()}function _h(r){let e=at(r,{offset:0});return Ri(e)}function Ri(r){let e=at(r[1],{offset:0});return{kty:"RSA",n:H(e[0],"base64url"),e:H(e[1],"base64url")}}function Oi(r){if(r.n==null||r.e==null)throw new oe("JWK was missing components");return wt([Eh,Mn(wt([De(F(r.n,"base64url")),De(F(r.e,"base64url"))]))]).subarray()}function Cu(r){let e=at(r);return Pi(e)}function Pi(r){let e=Bi(r);return ki(e)}function Ni(r,e){if(r.byteLength>=xh)throw new ir("Key size is too large");let t=at(r,{offset:0});return Ui(t,r,e)}function Ui(r,e,t){let n=Ri(r);if(t==null){let s=yr(rt.encode({Type:ne.RSA,Data:e}));t=Ze(Li,s)}return new Ir(n,t)}function ki(r){if(Ou(r)>Ci)throw new oe("Key size is too large");let e=Bu(r),t=yr(rt.encode({Type:ne.RSA,Data:Oi(e.publicKey)})),n=Ze(Li,t);return new ln(e.privateKey,new Ir(e.publicKey,n))}async function Lu(r){if(r>Ci)throw new oe("Key size is too large");let e=await Ru(r),t=yr(rt.encode({Type:ne.RSA,Data:Oi(e.publicKey)})),n=Ze(Li,t);return new ln(e.privateKey,new Ir(e.publicKey,n))}function Bu(r){if(r==null)throw new oe("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function Ru(r,e){let t=await Fe.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);e?.signal?.throwIfAborted();let n=await Ah(t,e);return{privateKey:n[0],publicKey:n[1]}}async function Iu(r,e,t){let n=await Fe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let s=await Fe.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,_e(e instanceof Uint8Array?e:e.subarray()));return t?.signal?.throwIfAborted(),new Uint8Array(s,0,s.byteLength)}async function Du(r,e,t,n){let s=await Fe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let o=await Fe.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},s,_e(e),_e(t instanceof Uint8Array?t:t.subarray()));return n?.signal?.throwIfAborted(),o}async function Ah(r,e){if(r.privateKey==null||r.publicKey==null)throw new oe("Private and public key are required");let t=await Promise.all([Fe.get().subtle.exportKey("jwk",r.privateKey),Fe.get().subtle.exportKey("jwk",r.publicKey)]);return e?.signal?.throwIfAborted(),t}function Ou(r){if(r.kty!=="RSA")throw new oe("invalid key type");if(r.n==null)throw new oe("invalid key modulus");return F(r.n,"base64url").length*8}var co=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(Fn(e),Pe(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,s=new Uint8Array(n);s.set(t.length>n?e.create().update(t).digest():t);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=e.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),ut(s)}update(e){return mr(this),this.iHash.update(e),this}digestInto(e){mr(this),Kn(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),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:t,iHash:n,finished:s,destroyed:o,blockLen:i,outputLen:a}=this;return e=e,e.finished=s,e.destroyed=o,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Pu=(()=>{let r=((e,t,n)=>new co(e,t).update(n).digest());return r.create=(e,t)=>new co(e,t),r})();var Nu=(r,e)=>(r+(r>=0?e:-e)/Uu)/e;function Th(r,e,t){wr("scalar",r,nt,t);let[[n,s],[o,i]]=e,a=Nu(i*r,t),c=Nu(-s*r,t),u=r-a*n-c*o,l=-a*s-c*i,f=u<nt,m=l<nt;f&&(u=-u),m&&(l=-l);let d=en(Math.ceil(xr(t)/2))+Ct;if(u<nt||u>=d||l<nt||l>=d)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:f,k1:u,k2neg:m,k2:l}}function Fi(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function Mi(r,e){$e(r);let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return Ve(t.lowS,"lowS"),Ve(t.prehash,"prehash"),t.format!==void 0&&Fi(t.format),t}var Ki=class extends Error{constructor(e=""){super(e)}},Ge={Err:Ki,_tlv:{encode:(r,e)=>{let{Err:t}=Ge;if(He(r,"tag"),r<0||r>255)throw new t("tlv.encode: wrong tag");if(typeof e!="string")throw new TypeError('"data" expected string, got type='+typeof e);if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,s=Qr(n);if(s.length/2&128)throw new t("tlv.encode: long form length too big");let o=n>127?Qr(s.length/2|128):"";return Qr(r)+o+s+e},decode(r,e){let{Err:t}=Ge;e=$(e,void 0,"DER data");let n=0;if(r<0||r>255)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let s=e[n++],o=!!(s&128),i=0;if(!o)i=s;else{let c=s&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let u=e.subarray(n,n+c);if(u.length!==c)throw new t("tlv.decode: length bytes not complete");if(u[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let l of u)i=i<<8|l;if(n+=c,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(r){let{Err:e}=Ge;if(Gn(r),r<nt)throw new e("integer: negative integers are not allowed");let t=Qr(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(r){let{Err:e}=Ge;if(r.length<1)throw new e("invalid signature integer: empty");if(r[0]&128)throw new e("invalid signature integer: negative");if(r.length>1&&r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return zt(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=Ge,s=$(r,void 0,"signature"),{v:o,l:i}=n.decode(48,s);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,o),{v:u,l}=n.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(u)}},hexFromSig(r){let{_tlv:e,_int:t}=Ge,n=e.encode(2,t.encode(r.r)),s=e.encode(2,t.encode(r.s)),o=n+s;return e.encode(48,o)}};Object.freeze(Ge._tlv);Object.freeze(Ge._int);Object.freeze(Ge);var nt=BigInt(0),Ct=BigInt(1),Uu=BigInt(2),uo=BigInt(3),Ih=BigInt(4);function ku(r,e={}){let t=Xn("weierstrass",r,e),n=t.Fp,s=t.Fn,o=t.CURVE,{h:i,n:a}=o;$e(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c,allowInfinityPoint:u}=e;if(c&&(!n.is0(o.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=Fu(n,s);function f(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function m(N,p,g){if(u&&p.is0())return Uint8Array.of(0);let{x:v,y:w}=p.toAffine(),b=n.toBytes(v);if(Ve(g,"isCompressed"),g){f();let _=!n.isOdd(w);return de(Mu(_),b)}else return de(Uint8Array.of(4),b,n.toBytes(w))}function d(N){$(N,void 0,"Point");let{publicKey:p,publicKeyUncompressed:g}=l,v=N.length,w=N[0],b=N.subarray(1);if(u&&v===1&&w===0)return{x:n.ZERO,y:n.ZERO};if(v===p&&(w===2||w===3)){let _=n.fromBytes(b);if(!n.isValid(_))throw new Error("bad point: is not on curve, wrong x");let D=h(_),I;try{I=n.sqrt(D)}catch(V){let j=V instanceof Error?": "+V.message:"";throw new Error("bad point: is not on curve, sqrt error"+j)}f();let L=n.isOdd(I);return(w&1)===1!==L&&(I=n.neg(I)),{x:_,y:I}}else if(v===g&&w===4){let _=n.BYTES,D=n.fromBytes(b.subarray(0,_)),I=n.fromBytes(b.subarray(_,_*2));if(!y(D,I))throw new Error("bad point: is not on curve");return{x:D,y:I}}else throw new Error(`bad point: got length ${v}, expected compressed=${p} or uncompressed=${g}`)}let x=e.toBytes===void 0?m:e.toBytes,S=e.fromBytes===void 0?d:e.fromBytes;function h(N){let p=n.sqr(N),g=n.mul(p,N);return n.add(n.add(g,n.mul(N,o.a)),o.b)}function y(N,p){let g=n.sqr(p),v=h(N);return n.eql(g,v)}if(!y(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let E=n.mul(n.pow(o.a,uo),Ih),A=n.mul(n.sqr(o.b),BigInt(27));if(n.is0(n.add(E,A)))throw new Error("bad curve params: a or b");function B(N,p,g=!1){if(!n.isValid(p)||g&&n.is0(p))throw new Error(`bad point coordinate ${N}`);return p}function C(N){if(!(N instanceof T))throw new Error("Weierstrass Point expected")}function U(N){if(!c||!c.basises)throw new Error("no endo");return Th(N,c.basises,s.ORDER)}function R(N,p,g,v,w){return g=new T(n.mul(g.X,N),g.Y,g.Z),p=rn(v,p),g=rn(w,g),p.add(g)}class T{static BASE=new T(o.Gx,o.Gy,n.ONE);static ZERO=new T(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=s;X;Y;Z;constructor(p,g,v){this.X=B("x",p),this.Y=B("y",g,!0),this.Z=B("z",v),Object.freeze(this)}static CURVE(){return o}static fromAffine(p){let{x:g,y:v}=p||{};if(!p||!n.isValid(g)||!n.isValid(v))throw new Error("invalid affine point");if(p instanceof T)throw new Error("projective point not allowed");return n.is0(g)&&n.is0(v)?T.ZERO:new T(g,v,n.ONE)}static fromBytes(p){let g=T.fromAffine(S($(p,void 0,"point")));return g.assertValidity(),g}static fromHex(p){return T.fromBytes(br(p))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(p=8,g=!0){return M.createCache(this,p),g||this.multiply(uo),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")}let{x:g,y:v}=p.toAffine();if(!n.isValid(g)||!n.isValid(v))throw new Error("bad point: x or y not field elements");if(!y(g,v))throw new Error("bad point: equation left != right");if(!p.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:p}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(p)}equals(p){C(p);let{X:g,Y:v,Z:w}=this,{X:b,Y:_,Z:D}=p,I=n.eql(n.mul(g,D),n.mul(b,w)),L=n.eql(n.mul(v,D),n.mul(_,w));return I&&L}negate(){return new T(this.X,n.neg(this.Y),this.Z)}double(){let{a:p,b:g}=o,v=n.mul(g,uo),{X:w,Y:b,Z:_}=this,D=n.ZERO,I=n.ZERO,L=n.ZERO,P=n.mul(w,w),V=n.mul(b,b),j=n.mul(_,_),q=n.mul(w,b);return q=n.add(q,q),L=n.mul(w,_),L=n.add(L,L),D=n.mul(p,L),I=n.mul(v,j),I=n.add(D,I),D=n.sub(V,I),I=n.add(V,I),I=n.mul(D,I),D=n.mul(q,D),L=n.mul(v,L),j=n.mul(p,j),q=n.sub(P,j),q=n.mul(p,q),q=n.add(q,L),L=n.add(P,P),P=n.add(L,P),P=n.add(P,j),P=n.mul(P,q),I=n.add(I,P),j=n.mul(b,_),j=n.add(j,j),P=n.mul(j,q),D=n.sub(D,P),L=n.mul(j,V),L=n.add(L,L),L=n.add(L,L),new T(D,I,L)}add(p){C(p);let{X:g,Y:v,Z:w}=this,{X:b,Y:_,Z:D}=p,I=n.ZERO,L=n.ZERO,P=n.ZERO,V=o.a,j=n.mul(o.b,uo),q=n.mul(g,b),fe=n.mul(v,_),he=n.mul(w,D),pe=n.add(g,v),ae=n.add(b,_);pe=n.mul(pe,ae),ae=n.add(q,fe),pe=n.sub(pe,ae),ae=n.add(g,w);let Ae=n.add(b,D);return ae=n.mul(ae,Ae),Ae=n.add(q,he),ae=n.sub(ae,Ae),Ae=n.add(v,w),I=n.add(_,D),Ae=n.mul(Ae,I),I=n.add(fe,he),Ae=n.sub(Ae,I),P=n.mul(V,ae),I=n.mul(j,he),P=n.add(I,P),I=n.sub(fe,P),P=n.add(fe,P),L=n.mul(I,P),fe=n.add(q,q),fe=n.add(fe,q),he=n.mul(V,he),ae=n.mul(j,ae),fe=n.add(fe,he),he=n.sub(q,he),he=n.mul(V,he),ae=n.add(ae,he),q=n.mul(fe,ae),L=n.add(L,q),q=n.mul(Ae,ae),I=n.mul(pe,I),I=n.sub(I,q),q=n.mul(pe,fe),P=n.mul(Ae,P),P=n.add(P,q),new T(I,L,P)}subtract(p){return C(p),this.add(p.negate())}is0(){return this.equals(T.ZERO)}multiply(p){let{endo:g}=e;if(!s.isValidNot0(p))throw new RangeError("invalid scalar: out of range");let v,w,b=_=>M.cached(this,_,D=>$t(T,D));if(g){let{k1neg:_,k1:D,k2neg:I,k2:L}=U(p),{p:P,f:V}=b(D),{p:j,f:q}=b(L);w=V.add(q),v=R(g.beta,P,j,_,I)}else{let{p:_,f:D}=b(p);v=_,w=D}return $t(T,[v,w])[0]}multiplyUnsafe(p){let{endo:g}=e,v=this,w=p;if(!s.isValid(w))throw new RangeError("invalid scalar: out of range");if(w===nt||v.is0())return T.ZERO;if(w===Ct)return v;if(M.hasCache(this))return this.multiply(w);if(g){let{k1neg:b,k1:_,k2neg:D,k2:I}=U(w),{p1:L,p2:P}=au(T,v,_,I);return R(g.beta,L,P,b,D)}else return M.unsafe(v,w)}toAffine(p){let g=this,v=p,{X:w,Y:b,Z:_}=g;if(n.eql(_,n.ONE))return{x:w,y:b};let D=g.is0();v==null&&(v=D?n.ONE:n.inv(_));let I=n.mul(w,v),L=n.mul(b,v),P=n.mul(_,v);if(D)return{x:n.ZERO,y:n.ZERO};if(!n.eql(P,n.ONE))throw new Error("invZ was invalid");return{x:I,y:L}}isTorsionFree(){let{isTorsionFree:p}=e;return i===Ct?!0:p?p(T,this):M.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:p}=e;return i===Ct?this:p?p(T,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===Ct?this.is0():this.clearCofactor().is0()}toBytes(p=!0){return Ve(p,"isCompressed"),this.assertValidity(),x(T,this,p)}toHex(p=!0){return gr(this.toBytes(p))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let k=s.BITS,M=new vr(T,e.endo?Math.ceil(k/2):k);return k>=8&&T.BASE.precompute(8),Object.freeze(T.prototype),Object.freeze(T),T}function Mu(r){return Uint8Array.of(r?2:3)}function Fu(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Dh(r,e={}){let{Fn:t}=r,n=e.randomBytes===void 0?Xr:e.randomBytes,s=Object.assign(Fu(r.Fp,t),{seed:Math.max(Zs(t.ORDER),16)});function o(d){try{let x=t.fromBytes(d);return t.isValidNot0(x)}catch{return!1}}function i(d,x){let{publicKey:S,publicKeyUncompressed:h}=s;try{let y=d.length;return x===!0&&y!==S||x===!1&&y!==h?!1:!!r.fromBytes(d)}catch{return!1}}function a(d){return d=d===void 0?n(s.seed):d,Xs($(d,s.seed,"seed"),t.ORDER)}function c(d,x=!0){return r.BASE.multiply(t.fromBytes(d)).toBytes(x)}function u(d){let{secretKey:x,publicKey:S,publicKeyUncompressed:h}=s,y=t._lengths;if(!qt(d))return;let E=$(d,void 0,"key").length,A=E===S||E===h,B=E===x||!!y?.includes(E);if(!(A&&B))return A}function l(d,x,S=!0){if(u(d)===!0)throw new Error("first arg must be private key");if(u(x)===!1)throw new Error("second arg must be public key");let h=t.fromBytes(d);return r.fromBytes(x).multiply(h).toBytes(S)}let f={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a},m=Qn(a,c);return Object.freeze(f),Object.freeze(s),Object.freeze({getPublicKey:c,getSharedSecret:l,keygen:m,Point:r,utils:f,lengths:s})}function Ku(r,e,t={}){let n=e;Fn(n),$e(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let s=t.randomBytes===void 0?Xr:t.randomBytes,o=t.hmac===void 0?(w,b)=>Pu(n,w,b):t.hmac,{Fp:i,Fn:a}=r,{ORDER:c,BITS:u}=a,{keygen:l,getPublicKey:f,getSharedSecret:m,utils:d,lengths:x}=Dh(r,t),S={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},h=c*Uu+Ct<i.ORDER;function y(w){let b=c>>Ct;return w>b}function E(w,b){if(!a.isValidNot0(b))throw new Error(`invalid signature ${w}: out of range 1..Point.Fn.ORDER`);return b}function A(){if(h)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function B(w,b){Fi(b);let _=x.signature,D=b==="compact"?_:b==="recovered"?_+1:void 0;return $(w,D)}class C{r;s;recovery;constructor(b,_,D){if(this.r=E("r",b),this.s=E("s",_),D!=null){if(A(),![0,1,2,3].includes(D))throw new Error("invalid recovery id");this.recovery=D}Object.freeze(this)}static fromBytes(b,_=S.format){B(b,_);let D;if(_==="der"){let{r:V,s:j}=Ge.toSig($(b));return new C(V,j)}_==="recovered"&&(D=b[0],_="compact",b=b.subarray(1));let I=x.signature/2,L=b.subarray(0,I),P=b.subarray(I,I*2);return new C(a.fromBytes(L),a.fromBytes(P),D)}static fromHex(b,_){return this.fromBytes(br(b),_)}assertRecovery(){let{recovery:b}=this;if(b==null)throw new Error("invalid recovery id: must be present");return b}addRecoveryBit(b){return new C(this.r,this.s,b)}recoverPublicKey(b){let{r:_,s:D}=this,I=this.assertRecovery(),L=I===2||I===3?_+c:_;if(!i.isValid(L))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let P=i.toBytes(L),V=r.fromBytes(de(Mu((I&1)===0),P)),j=a.inv(L),q=R($(b,void 0,"msgHash")),fe=a.create(-q*j),he=a.create(D*j),pe=r.BASE.multiplyUnsafe(fe).add(V.multiplyUnsafe(he));if(pe.is0())throw new Error("invalid recovery: point at infinify");return pe.assertValidity(),pe}hasHighS(){return y(this.s)}toBytes(b=S.format){if(Fi(b),b==="der")return br(Ge.hexFromSig(this));let{r:_,s:D}=this,I=a.toBytes(_),L=a.toBytes(D);return b==="recovered"?(A(),de(Uint8Array.of(this.assertRecovery()),I,L)):de(I,L)}toHex(b){return gr(this.toBytes(b))}}Object.freeze(C.prototype),Object.freeze(C);let U=t.bits2int===void 0?function(b){if(b.length>8192)throw new Error("input is too large");let _=zt(b),D=b.length*8-u;return D>0?_>>BigInt(D):_}:t.bits2int,R=t.bits2int_modN===void 0?function(b){return a.create(U(b))}:t.bits2int_modN,T=en(u);function k(w){return wr("num < 2^"+u,w,nt,T),a.toBytes(w)}function M(w,b){return $(w,void 0,"message"),b?$(n(w),void 0,"prehashed message"):w}function N(w,b,_){let{lowS:D,prehash:I,extraEntropy:L}=Mi(_,S);w=M(w,I);let P=R(w),V=a.fromBytes(b);if(!a.isValidNot0(V))throw new Error("invalid private key");let j=[k(V),k(P)];if(L!=null&&L!==!1){let pe=L===!0?s(x.secretKey):L;j.push($(pe,void 0,"extraEntropy"))}let q=de(...j),fe=P;function he(pe){let ae=U(pe);if(!a.isValidNot0(ae))return;let Ae=a.inv(ae),sr=r.BASE.multiply(ae).toAffine(),Mr=a.create(sr.x);if(Mr===nt)return;let Tn=a.create(Ae*a.create(fe+Mr*V));if(Tn===nt)return;let Ha=(sr.x===Mr?0:2)|Number(sr.y&Ct),$a=Tn;return D&&y(Tn)&&($a=a.neg(Tn),Ha^=1),new C(Mr,$a,h?void 0:Ha)}return{seed:q,k2sig:he}}function p(w,b,_={}){let{seed:D,k2sig:I}=N(w,b,_);return Hc(n.outputLen,a.BYTES,o)(D,I).toBytes(_.format)}function g(w,b,_,D={}){let{lowS:I,prehash:L,format:P}=Mi(D,S);if(_=$(_,void 0,"publicKey"),b=M(b,L),!qt(w)){let V=w instanceof C?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+V)}B(w,P);try{let V=C.fromBytes(w,P),j=r.fromBytes(_);if(I&&V.hasHighS())return!1;let{r:q,s:fe}=V,he=R(b),pe=a.inv(fe),ae=a.create(he*pe),Ae=a.create(q*pe),sr=r.BASE.multiplyUnsafe(ae).add(j.multiplyUnsafe(Ae));return sr.is0()?!1:a.create(sr.x)===q}catch{return!1}}function v(w,b,_={}){let{prehash:D}=Mi(_,S);return b=M(b,D),C.fromBytes(w,"recovered").recoverPublicKey(b).toBytes()}return Object.freeze({keygen:l,getPublicKey:f,getSharedSecret:m,utils:d,lengths:x,Point:r,sign:p,verify:g,recoverPublicKey:v,Signature:C,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")},Ch={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var qu=BigInt(2);function Lh(r){let e=zi.p,t=BigInt(3),n=BigInt(6),s=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=r*r*r%e,l=u*u*r%e,f=te(l,t,e)*l%e,m=te(f,t,e)*l%e,d=te(m,qu,e)*u%e,x=te(d,s,e)*d%e,S=te(x,o,e)*x%e,h=te(S,a,e)*S%e,y=te(h,c,e)*h%e,E=te(y,a,e)*S%e,A=te(E,t,e)*l%e,B=te(A,i,e)*x%e,C=te(B,n,e)*u%e,U=te(C,qu,e);if(!qi.eql(qi.sqr(U),r))throw new Error("Cannot find square root");return U}var qi=Er(zi.p,{sqrt:Lh}),Bh=ku(zi,{Fp:qi,endo:Ch}),Dr=Ku(Bh,yr);function zu(r,e,t,n){let s=hr.digest(t instanceof Uint8Array?t:t.subarray());if(ro(s))return s.then(({digest:o})=>(n?.signal?.throwIfAborted(),Dr.verify(e,o,r,{prehash:!1,format:"der"}))).catch(o=>{throw o.name==="AbortError"?o:new on(String(o))});try{return n?.signal?.throwIfAborted(),Dr.verify(e,s.digest,r,{prehash:!1,format:"der"})}catch(o){throw new on(String(o))}}var lo=class{type="secp256k1";raw;_key;constructor(e){this._key=Hu(e),this.raw=Vu(this._key)}toMultihash(){return qe.digest(Je(this))}toCID(){return le.createV1(114,this.toMultihash())}toString(){return re.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ce(this.raw,e.raw)}verify(e,t,n){return zu(this._key,t,e,n)}};function Vi(r){return new lo(r)}function Vu(r){return Dr.Point.fromBytes(r).toBytes()}function Hu(r){try{return Dr.Point.fromBytes(r),r}catch(e){throw new ir(String(e))}}function $u(r,e){let{Type:t,Data:n}=rt.decode(r),s=n??new Uint8Array;switch(t){case ne.RSA:return Ni(s,e);case ne.Ed25519:return li(s);case ne.secp256k1:return Vi(s);case ne.ECDSA:return Os(s);default:throw new ar}}function Wu(r){let{Type:e,Data:t}=rt.decode(r.digest),n=t??new Uint8Array;switch(e){case ne.Ed25519:return li(n);case ne.secp256k1:return Vi(n);case ne.ECDSA:return Os(n);default:throw new ar}}function Je(r){return rt.encode({Type:ne[r.type],Data:r.raw})}var Gu=Symbol.for("nodejs.util.inspect.custom"),Rh=114,dn=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()})`}[os]=!0;toString(){return this.string==null&&(this.string=re.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return le.createV1(Rh,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return ce(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return ce(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Gu](){return`PeerId(${this.toString()})`}},fo=class extends dn{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},ho=class extends dn{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},po=class extends dn{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},Oh=2336,hn=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=qe.digest(F(this.url))}[Gu](){return`PeerId(${this.url})`}[os]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return le.createV1(Oh,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=H(e)),e.toString()===this.toString())}};var Ph=114,ju=2336;function Hi(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=Xe(re.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return Nh(le.parse(r));if(e==null)throw new oe('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=Xe(e.decode(r))}return Cr(t)}function Cr(r){if(kh(r))return new fo({multihash:r});if(Uh(r))try{let e=Wu(r);if(e.type==="Ed25519")return new ho({multihash:r,publicKey:e});if(e.type==="secp256k1")return new po({multihash:r,publicKey:e})}catch{let t=H(r.digest);return new hn(new URL(t))}throw new Cn("Supplied PeerID Multihash is invalid")}function Nh(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==Ph&&r.code!==ju)throw new Dn("Supplied PeerID CID is invalid");if(r.code===ju){let e=H(r.multihash.digest);return new hn(new URL(e))}return Cr(r.multihash)}function Uh(r){return r.code===qe.code}function kh(r){return r.code===hr.code}var pn;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.publicKey!=null&&o.publicKey.byteLength>0&&(i.uint32(10),i.bytes(o.publicKey)),o.payloadType!=null&&o.payloadType.byteLength>0&&(i.uint32(18),i.bytes(o.payloadType)),o.payload!=null&&o.payload.byteLength>0&&(i.uint32(26),i.bytes(o.payload)),o.signature!=null&&o.signature.byteLength>0&&(i.uint32(42),i.bytes(o.signature)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={publicKey:J(0),payloadType:J(0),payload:J(0),signature:J(0)},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{c.publicKey=o.bytes();break}case 2:{c.payloadType=o.bytes();break}case 3:{c.payload=o.bytes();break}case 5:{c.signature=o.bytes();break}default:{o.skipType(l&7);break}}}return c},function*(o,i,a,c={}){let u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{yield{field:`${a}.publicKey`,value:o.bytes()};break}case 2:{yield{field:`${a}.payloadType`,value:o.bytes()};break}case 3:{yield{field:`${a}.payload`,value:o.bytes()};break}case 5:{yield{field:`${a}.signature`,value:o.bytes()};break}default:{o.skipType(l&7);break}}}})),e);function t(o){return Be(o,r.codec())}r.encode=t;function n(o,i){return Le(o,r.codec(),i)}r.decode=n;function s(o,i){return Re(o,r.codec(),i)}r.stream=s})(pn||(pn={}));var mo=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var mn=class r{static createFromProtobuf=e=>{let t=pn.decode(e),n=$u(t.publicKey);return new r({publicKey:n,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t,n)=>{if(t==null)throw new Error("Missing private key");let s=e.domain,o=e.codec,i=e.marshal(),a=Yu(s,o,i),c=await t.sign(a.subarray(),n);return new r({publicKey:t.publicKey,payloadType:o,payload:i,signature:c})};static openAndCertify=async(e,t,n)=>{let s=r.createFromProtobuf(e);if(!await s.validate(t,n))throw new mo("Envelope signature is not valid for the given domain");return s};publicKey;payloadType;payload;signature;marshaled;constructor(e){let{publicKey:t,payloadType:n,payload:s,signature:o}=e;this.publicKey=t,this.payloadType=n,this.payload=s,this.signature=o}marshal(){return this.marshaled==null&&(this.marshaled=pn.encode({publicKey:Je(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return e==null?!1:ce(this.marshal(),e.marshal())}async validate(e,t){let n=Yu(e,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,t)}},Yu=(r,e,t)=>{let n=F(r),s=Tr(n.byteLength),o=Tr(e.length),i=Tr(t.length);return new ee(s,n,o,e,i,t)};var we=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},ht=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 t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}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 t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,s){return this.readAtomically(()=>{let o=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*s)-1;for(;;){let l=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let m=Number.parseInt(f,e);if(!Number.isNaN(m))return m});if(l===void 0)break;if(o*=e,o+=l,o>u||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:o})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let s=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[s]=i[0],t[s+1]=i[1],t[s+2]=i[2],t[s+3]=i[3],[s+4,!0]}let o=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(o===void 0)return[s,!1];t[s]=o>>8,t[s+1]=o&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,s]=e(t);if(n===16)return t;if(s||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let o=new Uint8Array(14),i=16-(n+2),[a]=e(o.subarray(0,i));return t.set(o.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Mh=45,Fh=15,wo=new bo;function Zu(r){if(!(r.length>Fh))return wo.new(r).parseWith(()=>wo.readIPv4Addr())}function Xu(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Mh))return wo.new(r).parseWith(()=>wo.readIPv6Addr())}function xo(r){return!!Zu(r)}function Qu(r){return!!Xu(r)}function Wi(r){return e=>H(e,r)}function Gi(r){return e=>F(e,r)}function Lr(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Zt(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function Ju(r){let e=r.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 t=F(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 s=Zt(n);return Qe([t,s],t.length+s.length)}function el(r){let e=r.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 t=bt.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 s=Zt(n);return Qe([t,s],t.length+s.length)}function ji(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=H(e,"base32"),s=Lr(t);return`${n}:${s}`}var Yi=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let s=parseInt(t,10);if(isNaN(s)||s<0||s>255)throw new we("Invalid byte value in IP address");e[n]=s}),e},tl=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let o=xo(t[n]),i;o&&(i=Yi(t[n]),t[n]=H(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,H(i.subarray(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let o=[n,1];for(n=9-t.length;n>0;n--)o.push("0");t.splice.apply(t,o)}let s=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let o=parseInt(t[n],16);if(isNaN(o)||o<0||o>65535)throw new we("Invalid byte value in IP address");s[e++]=o>>8&255,s[e++]=o&255}return s},rl=function(r){if(r.byteLength!==4)throw new we("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},nl=function(r){if(r.byteLength!==16)throw new we("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let s=r[n],o=r[n+1],i=`${s.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new we(`Invalid IPv6 address "${t}"`)}};function ol(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new we(`Invalid IPv6 address "${r}"`)}}var $i=Object.values(Hr).map(r=>r.decoder),Kh=(function(){let r=$i[0].or($i[1]);return $i.slice(2).forEach(e=>r=r.or(e)),r})();function sl(r){return Kh.decode(r)}function il(r){return e=>r.encoder.encode(e)}function qh(r){if(parseInt(r).toString()!==r)throw new ht("Value must be an integer")}function zh(r){if(r<0)throw new ht("Value must be a positive integer, or zero")}function Vh(r){return e=>{if(e>r)throw new ht(`Value must be smaller than or equal to ${r}`)}}function Hh(...r){return e=>{for(let t of r)t(e)}}var yn=Hh(qh,zh,Vh(65535));var ye=-1,Zi=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(typeof e=="string"?t=this.protocolsByName.get(e):t=this.protocolsByCode.get(e),t==null)throw new go(`Protocol ${e} was unknown`);return t}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(t=>{this.protocolsByName.set(t,e)})}removeProtocol(e){let t=this.protocolsByCode.get(e);t!=null&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},mt=new Zi,op=[{code:4,name:"ip4",size:32,valueToBytes:Yi,bytesToValue:rl,validate:r=>{if(!xo(r))throw new ht(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Zt,bytesToValue:Lr,validate:yn},{code:273,name:"udp",size:16,valueToBytes:Zt,bytesToValue:Lr,validate:yn},{code:33,name:"dccp",size:16,valueToBytes:Zt,bytesToValue:Lr,validate:yn},{code:41,name:"ip6",size:128,valueToBytes:tl,bytesToValue:nl,stringToValue:ol,validate:r=>{if(!Qu(r))throw new ht(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:ye},{code:43,name:"ipcidr",size:8,bytesToValue:Wi("base10"),valueToBytes:Gi("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:Zt,bytesToValue:Lr,validate:yn},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:ye,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:ye,bytesToValue:Wi("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Gi("base58btc")(r):le.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:ji,valueToBytes:Ju},{code:445,name:"onion3",size:296,bytesToValue:ji,valueToBytes:el},{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:il(xs),valueToBytes:sl},{code:480,name:"http"},{code:481,name:"http-path",size:ye,stringToValue:r=>`/${decodeURIComponent(r)}`,valueToString:r=>encodeURIComponent(r.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:ye}];op.forEach(r=>{mt.addProtocol(r)});function al(r){let e=[],t=0;for(;t<r.length;){let n=sn(r,t),s=mt.getProtocol(n),o=Ce(n),i=sp(s,r,t+o),a=0;i>0&&s.size===ye&&(a=Ce(i));let c=o+a+i,u={code:n,name:s.name,bytes:_e(r.subarray(t,t+c))};if(i>0){let l=t+o+a,f=r.subarray(l,l+i);u.value=s.bytesToValue?.(f)??H(f)}e.push(u),t+=c}return e}function cl(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let s=mt.getProtocol(n.code),o=Ce(n.code),i,a=0,c=0;n.value!=null&&(i=s.valueToBytes?.(n.value)??F(n.value),a=i.byteLength,s.size===ye&&(c=Ce(a)));let u=new Uint8Array(o+c+a),l=0;Ar(n.code,u,l),l+=o,i!=null&&(s.size===ye&&(Ar(a,u,l),l+=c),u.set(i,l)),n.bytes=u}t.push(n.bytes),e+=n.bytes.byteLength}return Qe(t,e)}function ul(r){if(r.charAt(0)!=="/")throw new we('String multiaddr must start with "/"');let e=[],t="protocol",n="",s="";for(let o=1;o<r.length;o++){let i=r.charAt(o);i!=="/"&&(t==="protocol"?s+=r.charAt(o):n+=r.charAt(o));let a=o===r.length-1;if(i==="/"||a){let c=mt.getProtocol(s);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",s="",t="protocol";continue}else if(a)throw new we(`Component ${s} was missing value`);t="value"}else if(t==="value"){let u={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new we(`Component ${s} was missing value`);u.value=c.stringToValue?.(n)??n}e.push(u),n="",s="",t="protocol"}}}if(s!==""&&n!=="")throw new we("Incomplete multiaddr");return e}function ll(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=mt.getProtocol(e.code);if(t==null)throw new we(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function sp(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:sn(e,t)}var ip=Symbol.for("nodejs.util.inspect.custom"),ha=Symbol.for("@multiformats/multiaddr");function ap(r){if(r==null&&(r="/"),fl(r))return r.getComponents();if(r instanceof Uint8Array)return al(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),ul(r);if(Array.isArray(r))return r;throw new we("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Ao=class r{[ha]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=ap(e),t.validate!==!1&&cp(this)}get bytes(){return this.#r==null&&(this.#r=cl(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=ll(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),s=n.lastIndexOf(t);if(s<0)throw new yo(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,s),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}equals(e){return ce(this.bytes,e.bytes)}[ip](){return`Multiaddr(${this.toString()})`}};function cp(r){r.getComponents().forEach(e=>{let t=mt.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function fl(r){return!!r?.[ha]}function Ue(r){return new Ao(r)}var pa={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},dl={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},hl=new globalThis.TextEncoder;function up(r,e){let t=pa[e],n=dl[e];for(let s=0;s<r.length;s++)n^=BigInt(r[s]),n=BigInt.asUintN(e,n*t);return n}function lp(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=pa[e],s=dl[e],o=r;for(;o.length>0;){let i=hl.encodeInto(o,t);o=o.slice(i.read);for(let a=0;a<i.written;a++)s^=BigInt(t[a]),s=BigInt.asUintN(e,s*n)}return s}function ma(r,{size:e=32,utf8Buffer:t}={}){if(!pa[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(t)return lp(r,e,t);r=hl.encode(r)}return up(r,e)}var gn={hash:r=>Number(ma(r,{size:32})),hashV:(r,e)=>fp(gn.hash(r,e))};function fp(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),F(e,"base16")}var ya=64,je=class{fp;h;seed;constructor(e,t,n,s=2){if(s>ya)throw new TypeError("Invalid Fingerprint Size");let o=t.hashV(e,n),i=J(s);for(let a=0;a<i.length;a++)i[a]=o[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?ce(this.fp,e.fp):!1}};function Jt(r,e){return Math.floor(Math.random()*(e-r))+r}var er=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof je))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof je))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(this.contents[t]==null)return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof je))throw new TypeError("Invalid Fingerprint");let t=Jt(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof je))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var dp=500,bn=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??gn,this.seed=e.seed??Jt(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=F(e));let t=new je(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new er(this.bucketSize)),this.buckets[s]==null&&(this.buckets[s]=new er(this.bucketSize)),this.buckets[n].add(t)||this.buckets[s].add(t))return this.count++,!0;let o=[n,s],i=o[Jt(0,o.length-1)];this.buckets[i]==null&&(this.buckets[i]=new er(this.bucketSize));for(let a=0;a<dp;a++){let c=this.buckets[i].swap(t);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new er(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=F(e));let t=new je(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=this.buckets[n]?.has(t)??!1;if(s)return s;let o=(n^t.hash())%this.filterSize;return this.buckets[o]?.has(t)??!1}remove(e){typeof e=="string"&&(e=F(e));let t=new je(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=this.buckets[n]?.remove(t)??!1;if(s)return this.count--,s;let o=(n^t.hash())%this.filterSize,i=this.buckets[o]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},hp={1:.5,2:.84,4:.95,8:.98};function pp(r=.001){return r>.002?2:r>1e-5?4:8}function pl(r,e=.001){let t=pp(e),n=hp[t],s=Math.round(r/n),o=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),ya);return{filterSize:s,bucketSize:t,fingerprintSize:o}}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??gn,this.seed=e.seed??Jt(0,Math.pow(2,10)),this.filterSeries=[new bn({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=F(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new bn({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=F(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=F(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function Pr(r,e=.001,t){return new To({...pl(r,e),...t??{}})}var X=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),O=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),ml=r=>({match:e=>r.match(e)===!1?e:!1}),z=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),ve=(...r)=>({match:e=>{let t;for(let n of r){let s=n.match(e);s!==!1&&(t==null||s.length<t.length)&&(t=s)}return t??!1}}),W=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e}});function Q(...r){function e(s){if(s==null)return!1;let o=s.getComponents();for(let i of r){let a=i.match(o);if(a===!1)return!1;o=a}return o}function t(s){return e(s)!==!1}function n(s){let o=e(s);return o===!1?!1:o.length===0}return{matchers:r,matches:t,exactMatch:n}}var mp=O(421),hE=Q(mp),Do=O(54),Co=O(55),Lo=O(56),ba=O(53),pE=Q(Do,z(O(421))),mE=Q(Co,z(O(421))),yE=Q(Lo,z(O(421))),gE=Q(ve(ba,Lo,Do,Co),z(O(421))),yl=W(O(4),z(O(43))),gl=W(z(O(42)),O(41),z(O(43))),wa=ve(yl,gl),Nr=ve(wa,ba,Do,Co,Lo),bE=Q(ve(wa,W(ve(ba,Lo,Do,Co),z(O(421))))),wE=Q(yl),xE=Q(gl),EE=Q(wa),xa=W(Nr,O(6)),wn=W(Nr,O(273)),SE=Q(W(xa,z(O(421)))),vE=Q(wn),Ea=W(wn,X(460),z(O(421))),Bo=W(wn,X(461),z(O(421))),yp=ve(Ea,Bo),_E=Q(Ea),AE=Q(Bo),ga=ve(Nr,xa,wn,Ea,Bo),bl=ve(W(ga,X(477),z(O(421)))),TE=Q(bl),wl=ve(W(ga,X(478),z(O(421))),W(ga,X(448),z(O(449)),X(477),z(O(421)))),IE=Q(wl),xl=W(wn,X(280),z(O(466)),z(O(466)),z(O(421))),DE=Q(xl),El=W(Bo,X(465),z(O(466)),z(O(466)),z(O(421))),CE=Q(El),Io=ve(bl,wl,W(xa,z(O(421))),W(yp,z(O(421))),W(Nr,z(O(421))),xl,El,O(421)),Sl=Q(Io),gp=W(z(Io),X(290),ml(X(281)),z(O(421))),tr=Q(gp),bp=ve(W(Io,X(290),X(281),z(O(421))),W(Io,X(281),z(O(421))),W(X(281),z(O(421)))),LE=Q(bp),wp=W(Nr,ve(W(O(6,"80")),W(O(6),X(480)),X(480)),z(O(481)),z(O(421))),BE=Q(wp),xp=W(Nr,ve(W(O(6,"443")),W(O(6,"443"),X(480)),W(O(6),X(443)),W(O(6),X(448),X(480)),W(X(448),X(480)),X(448),X(443)),z(O(481)),z(O(421))),RE=Q(xp),Ep=ve(W(O(777),z(O(421)))),OE=Q(Ep),Sp=ve(W(O(400),z(O(421)))),PE=Q(Sp);function Ye(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}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}},Ur=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 t=this.head;this.head=t.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 t=this.tail.next;this.tail.next=null,this.tail=t,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,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Lt(r={}){return vp(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function vp(r,e){e=e??{};let t=e.onEnd,n=new Ur,s,o,i,a=Ye(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((h,y)=>{o=E=>{o=null,n.push(E);try{h(r(n))}catch(A){y(A)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Ye()})}},u=h=>o!=null?o(h):(n.push(h),s),l=h=>(n=new Ur,o!=null?o({error:h}):(n.push({error:h}),s)),f=h=>{if(i)return s;if(e?.objectMode!==!0&&h?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:h})},m=h=>i?s:(i=!0,h!=null?l(h):u({done:!0})),d=()=>(n=new Ur,m(),{done:!0}),x=h=>(m(h),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:d,throw:x,push:f,end:m,get readableLength(){return n.size},onEmpty:async h=>{let y=h?.signal;if(y?.throwIfAborted(),n.isEmpty())return;let E,A;y!=null&&(E=new Promise((B,C)=>{A=()=>{C(new Sa)},y.addEventListener("abort",A)}));try{await Promise.race([a.promise,E])}finally{A!=null&&y!=null&&y?.removeEventListener("abort",A)}}},t==null)return s;let S=s;return s={[Symbol.asyncIterator](){return this},next(){return S.next()},throw(h){return S.throw(h),t!=null&&(t(h),t=void 0),{done:!0}},return(){return S.return(),t!=null&&(t(),t=void 0),{done:!0}},push:f,end(h){return S.end(h),t!=null&&(t(h),t=void 0),s},get readableLength(){return S.readableLength},onEmpty:h=>S.onEmpty(h)},s}var va=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},vl=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function _a(r,e){let{milliseconds:t,fallback:n,message:s,customTimers:o={setTimeout,clearTimeout},signal:i}=e,a,c,l=new Promise((f,m)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(i?.aborted){m(vl(i));return}if(i&&(c=()=>{m(vl(i))},i.addEventListener("abort",c,{once:!0})),r.then(f,m),t===Number.POSITIVE_INFINITY)return;let d=new va;a=o.setTimeout.call(void 0,()=>{if(n){try{f(n())}catch(x){m(x)}return}typeof r.cancel=="function"&&r.cancel(),s===!1?f():s instanceof Error?m(s):(d.message=s??`Promise timed out after ${t} milliseconds`,m(d))},t)}).finally(()=>{l.clear(),c&&i&&i.removeEventListener("abort",c)});return l.clear=()=>{o.clearTimeout.call(void 0,a),a=void 0},l}var _p=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function Ap(r,e,t){let n,s=new Promise((o,i)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:u,removeListener:l}=_p(r),f=async(...d)=>{let x=t.multiArgs?d:d[0];if(t.filter)try{if(!await t.filter(x))return}catch(S){n(),i(S);return}c.push(x),t.count===c.length&&(n(),o(c))},m=(...d)=>{n(),i(t.rejectionMultiArgs?d:d[0])};n=()=>{for(let d of a)l(d,f);for(let d of t.rejectionEvents)a.includes(d)||l(d,m)};for(let d of a)u(d,f);for(let d of t.rejectionEvents)a.includes(d)||u(d,m);t.signal&&t.signal.addEventListener("abort",()=>{m(t.signal.reason)},{once:!0}),t.resolveImmediately&&o(c)});if(s.cancel=n,typeof t.timeout=="number"){let o=_a(s,{milliseconds:t.timeout});return o.cancel=()=>{n(),o.clear()},o}return s}function ot(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=Ap(r,e,t),s=n.then(o=>o[0]);return s.cancel=n.cancel,s}function Aa(r,e){let t,n=function(){let s=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(s,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var Oo=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}},rr=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"};var Po=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function Tp(r){return r.reason}async function Bt(r,e,t){if(e==null)return r;let n=t?.translateError??Tp;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let s;try{return await Promise.race([r,new Promise((o,i)=>{s=()=>{i(n(e))},e.addEventListener("abort",s)})])}finally{s!=null&&e.removeEventListener("abort",s)}}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 st)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Ip(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Uo=class{id;fn;options;recipients;status;timeline;controller;dispatchingProgress;constructor(e,t){this.id=Ip(),this.status="queued",this.fn=e,this.options=t,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((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new st),this.cleanup())}async join(e){let t=new No(e);return this.recipients.push(t),e?.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await Bt(this.fn({...this.options??{},signal:this.controller.signal,onProgress:t=>{if(!this.dispatchingProgress){this.dispatchingProgress=!0;try{this.recipients.forEach(n=>{n.onProgress?.(t)})}finally{this.dispatchingProgress=!1}}}}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.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 ko=class extends Ie{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 t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,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,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Oo;let n=new Uo(e,t);this.enqueue(n),this.safeDispatchEvent("add");let s=n.join(t).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{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:o}}),o});return this.tryToStartAnother(),s}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new st)}),this.clear()}async onEmpty(e){this.size!==0&&await ot(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await ot(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await ot(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 t=Lt({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},s=c=>{c.detail!=null&&t.push(c.detail)},o=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new st("Queue aborted"))};this.addEventListener("completed",s),this.addEventListener("failure",o),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",s),this.removeEventListener("failure",o),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var Dp=Math.pow(2,20)*4,Mo=class extends Ie{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;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??Dp,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new ee,this.writeBuffer=new ee,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 t=()=>{this.writableNeedsDrain&&(this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,queueMicrotask(()=>{try{this.processSendQueue()}catch(s){this.log.error("processSendQueue threw - %e",s)}})),this.onDrainPromise?.resolve()};this.addEventListener("drain",t);let n=s=>{this.onDrainPromise?.reject(s.error??new Po)};this.addEventListener("close",n)}get readBufferLength(){return this.readBuffer.byteLength}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),Bt(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let e=Lt(),t=o=>{e.push(o.data)};this.addEventListener("message",t);let n=o=>{e.end(o.error)};this.addEventListener("close",n);let s=()=>{e.end()};this.addEventListener("remoteCloseWrite",s);try{yield*e}finally{this.removeEventListener("message",t),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",s)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new yt(`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();try{this.sendReset(e)}catch(t){this.log("failed to send reset to remote - %e",t)}this.dispatchEvent(new On(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new yt("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 yt("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 yt(`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 yt(`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");let e=new In;this.dispatchEvent(new Pn(e))}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.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.dispatchEvent(new cr))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),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,t=this.writeBuffer.byteLength,n=0;for(;this.writeBuffer.byteLength>0;){let s=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(s===0){e=!1;break}let o=this.writeBuffer.sublist(0,s),i=new ee(o);this.writeBuffer.consume(o.byteLength);let a;try{a=this.sendData(o)}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,t,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),e}finally{this.sendingData=!1}}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 Rn(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.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new Fr(`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 Fr(`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",t=>{this.metrics?.increment({[`${this.metricPrefix}end`]:!0}),t.error!=null?t.local?this.metrics?.increment({[`${this.metricPrefix}abort`]:!0}):this.metrics?.increment({[`${this.metricPrefix}reset`]:!0}):t.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 ot(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 ot(this,"drain",{...e,rejectionEvents:["close"]})),await this.sendClose(e),this.onTransportClosed())}};function Ko(r){let e=new globalThis.AbortController;function t(){let o=r.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();e.abort(o);for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}for(let o of r){if(o?.aborted===!0){t();break}o?.addEventListener!=null&&o.addEventListener("abort",t)}function n(){for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",t)}let s=e.signal;return s.clear=n,s}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,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){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 Bt(this.readNext.promise,t?.signal,t)}};function _l(){return new Ta}function Cp(r){return r[Symbol.asyncIterator]!=null}async function Lp(r,e,t){try{await Promise.all(r.map(async n=>{for await(let s of n)await e.push(s,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*Bp(r){let e=new AbortController,t=_l();Lp(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*Rp(r){for(let e of r)yield*e}function Op(...r){let e=[];for(let t of r)Cp(t)||e.push(t);return e.length===r.length?Rp(e):Bp(r)}var Al=Op;function Tl(r,...e){if(r==null)throw new Error("Empty pipeline");if(Ia(r)){let n=r;r=()=>n.source}else if(Dl(r)||Il(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&Ia(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let n=1;n<t.length-1;n++)Ia(t[n])&&(t[n]=Np(t[n]));return Pp(...t)}var Pp=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},Il=r=>r?.[Symbol.asyncIterator]!=null,Dl=r=>r?.[Symbol.iterator]!=null,Ia=r=>r==null?!1:r.sink!=null&&r.source!=null,Np=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=Lt({objectMode:!0});t.then(()=>{n.end()},i=>{n.end(i)});let s,o=r.source;if(Il(o))s=async function*(){yield*o,n.end()};else if(Dl(o))s=function*(){yield*o,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Al(n,s())}return r.source};var Up=4194304,qo=class extends Error{static name="UnwrappedError";name="UnwrappedError"},Ca=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},La=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ba=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function kp(r){return typeof r?.closeRead=="function"}function Mp(r){return typeof r?.close=="function"}function Da(r){return kp(r)?r.remoteWriteStatus!=="writable"&&r.readBufferLength===0:Mp(r)?r.status!=="open":!1}function Fp(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function Kp(r,e){let t=e?.maxBufferSize??Up,n=new ee,s,o=!1;if(!Fp(r))throw new oe("Argument should be a Stream or a Multiaddr");let i=l=>{if(n.append(l.data),n.byteLength>t){let f=n.byteLength;n.consume(n.byteLength),s?.reject(new Error(`Read buffer overflow - ${f} > ${t}`))}s?.resolve()};r.addEventListener("message",i);let a=l=>{l.error!=null?s?.reject(l.error):s?.resolve()};r.addEventListener("close",a);let c=()=>{s?.resolve()};r.addEventListener("remoteCloseWrite",c);let u={readBuffer:n,async read(l){if(o===!0)throw new qo("Stream was unwrapped");if(Da(r)){if(n.byteLength===0&&l?.bytes==null)return null;if(l?.bytes!=null&&n.byteLength<l.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,l.bytes),new rr(`Unexpected EOF - stream closed after reading ${n.byteLength}/${l.bytes} bytes`)}let f=l?.bytes??1;for(s=Promise.withResolvers();;){if(n.byteLength>=f){s.resolve();break}if(await Bt(s.promise,l?.signal),Da(r)){if(n.byteLength===0&&l?.bytes==null)return null;break}s=Promise.withResolvers()}let m=l?.bytes??n.byteLength;if(n.byteLength<m){if(Da(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,m),new rr(`Unexpected EOF - stream closed while reading ${n.byteLength}/${m} bytes`);return u.read(l)}let d=n.sublist(0,m);return n.consume(m),d},async write(l,f){if(o===!0)throw new qo("Stream was unwrapped");r.send(l)||await ot(r,"drain",{signal:f?.signal,rejectionEvents:["close"]})},unwrap(){return o||(o=!0,r.removeEventListener("message",i),r.removeEventListener("close",a),r.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.unshift(n))),r}};return u}function qp(r,e={}){let t=Kp(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=Ce(e.maxDataLength));let n=e?.lengthDecoder??sn,s=e?.lengthEncoder??Tr;return{async read(i){let a=-1,c=new ee;for(;;){let l=await t.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 Ba(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new La(`Message length too long - ${a} > ${e.maxDataLength}`);let u=await t.read({...i,bytes:a});if(u==null)throw r.log.error("tried to read %d bytes but the stream closed",a),new rr(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(u.byteLength!==a)throw r.log.error("read %d/%d bytes before the stream closed",u.byteLength,a),new rr(`Unexpected EOF - read ${u.byteLength}/${a} bytes before the stream closed`);return u},async write(i,a){await t.write(new ee(s(i.byteLength),i),a)},async writeV(i,a){let c=new ee(...i.flatMap(u=>[s(u.byteLength),u]));await t.write(c,a)},unwrap(){return t.unwrap()}}}function Rt(r,e){let t=qp(r,e),n={read:async(s,o)=>{let i=await t.read(o);return s.decode(i,o)},write:async(s,o,i)=>{await t.write(o.encode(s),i)},writeV:async(s,o,i)=>{await t.writeV(s.map(a=>o.encode(a)),i)},pb:s=>({read:async o=>n.read(s,o),write:async(o,i)=>n.write(o,s,i),writeV:async(o,i)=>n.writeV(o,s,i),unwrap:()=>n}),unwrap:()=>t.unwrap()};return n}function zp(r){return r?.addEventListener!=null}function Vp(r){let e=Lt(),t,n=i=>{e.push(i.data)},s=()=>{e.end(),r.removeEventListener("message",n),r.removeEventListener("close",o),r.removeEventListener("remoteCloseWrite",s)},o=i=>{e.end(i.error),i.error!=null&&t?.reject(i.error),r.removeEventListener("message",n),r.removeEventListener("close",o),r.removeEventListener("remoteCloseWrite",s)};return r.addEventListener("message",n),r.addEventListener("close",o,{once:!0}),r.addEventListener("remoteCloseWrite",s,{once:!0}),{source:e,async sink(i){async function*a(){yield*i}let c=a();for(;;){t=Promise.withResolvers();let{done:u,value:l}=await Promise.race([c.next(),t.promise]);if(r.writeStatus==="closing"||r.writeStatus==="closed"||(l!=null&&(r.send(l)||await Promise.race([ot(r,"drain",{rejectionEvents:["close"]})])),u===!0))break}await r.close()}}}function Cl(...r){let e=r.map(t=>zp(t)?Vp(t):t);return Tl(...e)}var kr=class extends ko{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var Ra=1e3,Ll=60*Ra,Bl=15,Rl=120*Ll,Ol=1,zo=5e3,Pl=100,Oa="circuit-relay-source",xn=`${Wa}-circuit-relay`,Nl=2*Ll,Ul=BigInt(1<<17),Ke="/libp2p/circuit/relay/0.2.0/hop",nr="/libp2p/circuit/relay/0.2.0/stop",kl=30*Ra,F2=30*Ra,En=300,Ml=4096,Fl=.001;var Z;(function(r){let e;(function(a){a.RESERVE="RESERVE",a.CONNECT="CONNECT",a.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(a){a[a.RESERVE=0]="RESERVE",a[a.CONNECT=1]="CONNECT",a[a.STATUS=2]="STATUS"})(t||(t={})),(function(a){a.codec=()=>jt(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Oe((a,c,u={})=>{u.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),r.Type.codec().encode(a.type,c)),a.peer!=null&&(c.uint32(18),Ot.codec().encode(a.peer,c)),a.reservation!=null&&(c.uint32(26),Sn.codec().encode(a.reservation,c)),a.limit!=null&&(c.uint32(34),Pt.codec().encode(a.limit,c)),a.status!=null&&(c.uint32(40),K.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 m=a.uint32();switch(m>>>3){case 1:{l.type=r.Type.codec().decode(a);break}case 2:{l.peer=Ot.codec().decode(a,a.uint32(),{limits:u.limits?.peer});break}case 3:{l.reservation=Sn.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=K.codec().decode(a);break}default:{a.skipType(m&7);break}}}return l},function*(a,c,u,l={}){let f=c==null?a.len:a.pos+c;for(;a.pos<f;){let m=a.uint32();switch(m>>>3){case 1:{yield{field:`${u}.type`,value:r.Type.codec().decode(a)};break}case 2:{yield*Ot.codec().stream(a,a.uint32(),`${u}.peer`,{limits:l.limits?.peer});break}case 3:{yield*Sn.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:K.codec().decode(a)};break}default:{a.skipType(m&7);break}}}})),n);function s(a){return Be(a,r.codec())}r.encode=s;function o(a,c){return Le(a,r.codec(),c)}r.decode=o;function i(a,c){return Re(a,r.codec(),c)}r.stream=i})(Z||(Z={}));var ke;(function(r){let e;(function(a){a.CONNECT="CONNECT",a.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(a){a[a.CONNECT=0]="CONNECT",a[a.STATUS=1]="STATUS"})(t||(t={})),(function(a){a.codec=()=>jt(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Oe((a,c,u={})=>{u.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),r.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),K.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 m=a.uint32();switch(m>>>3){case 1:{l.type=r.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=K.codec().decode(a);break}default:{a.skipType(m&7);break}}}return l},function*(a,c,u,l={}){let f=c==null?a.len:a.pos+c;for(;a.pos<f;){let m=a.uint32();switch(m>>>3){case 1:{yield{field:`${u}.type`,value:r.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:K.codec().decode(a)};break}default:{a.skipType(m&7);break}}}})),n);function s(a){return Be(a,r.codec())}r.encode=s;function o(a,c){return Le(a,r.codec(),c)}r.decode=o;function i(a,c){return Re(a,r.codec(),c)}r.stream=i})(ke||(ke={}));var Ot;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((o,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),o.id!=null&&o.id.byteLength>0&&(i.uint32(10),i.bytes(o.id)),o.addrs!=null&&o.addrs.length>0)for(let c of o.addrs)i.uint32(18),i.bytes(c);a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={id:J(0),addrs:[]},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{c.id=o.bytes();break}case 2:{if(a.limits?.addrs!=null&&c.addrs.length===a.limits.addrs)throw new Yt('Decode error - repeated field "addrs" had too many elements');c.addrs.push(o.bytes());break}default:{o.skipType(l&7);break}}}return c},function*(o,i,a,c={}){let u={addrs:0},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let f=o.uint32();switch(f>>>3){case 1:{yield{field:`${a}.id`,value:o.bytes()};break}case 2:{if(c.limits?.addrs!=null&&u.addrs===c.limits.addrs)throw new Yt('Streaming decode error - repeated field "addrs" had too many elements');yield{field:`${a}.addrs[]`,index:u.addrs,value:o.bytes()},u.addrs++;break}default:{o.skipType(f&7);break}}}})),e);function t(o){return Be(o,r.codec())}r.encode=t;function n(o,i){return Le(o,r.codec(),i)}r.decode=n;function s(o,i){return Re(o,r.codec(),i)}r.stream=s})(Ot||(Ot={}));var Sn;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((o,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),o.expire!=null&&o.expire!==0n&&(i.uint32(8),i.uint64(o.expire)),o.addrs!=null&&o.addrs.length>0)for(let c of o.addrs)i.uint32(18),i.bytes(c);o.voucher!=null&&(i.uint32(26),vn.codec().encode(o.voucher,i)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={expire:0n,addrs:[]},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{c.expire=o.uint64();break}case 2:{if(a.limits?.addrs!=null&&c.addrs.length===a.limits.addrs)throw new Yt('Decode error - repeated field "addrs" had too many elements');c.addrs.push(o.bytes());break}case 3:{c.voucher=vn.codec().decode(o,o.uint32(),{limits:a.limits?.voucher});break}default:{o.skipType(l&7);break}}}return c},function*(o,i,a,c={}){let u={addrs:0},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let f=o.uint32();switch(f>>>3){case 1:{yield{field:`${a}.expire`,value:o.uint64()};break}case 2:{if(c.limits?.addrs!=null&&u.addrs===c.limits.addrs)throw new Yt('Streaming decode error - repeated field "addrs" had too many elements');yield{field:`${a}.addrs[]`,index:u.addrs,value:o.bytes()},u.addrs++;break}case 3:{yield*vn.codec().stream(o,o.uint32(),`${a}.voucher`,{limits:c.limits?.voucher});break}default:{o.skipType(f&7);break}}}})),e);function t(o){return Be(o,r.codec())}r.encode=t;function n(o,i){return Le(o,r.codec(),i)}r.decode=n;function s(o,i){return Re(o,r.codec(),i)}r.stream=s})(Sn||(Sn={}));var Pt;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.duration!=null&&(i.uint32(8),i.uint32(o.duration)),o.data!=null&&(i.uint32(16),i.uint64(o.data)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{c.duration=o.uint32();break}case 2:{c.data=o.uint64();break}default:{o.skipType(l&7);break}}}return c},function*(o,i,a,c={}){let u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{yield{field:`${a}.duration`,value:o.uint32()};break}case 2:{yield{field:`${a}.data`,value:o.uint64()};break}default:{o.skipType(l&7);break}}}})),e);function t(o){return Be(o,r.codec())}r.encode=t;function n(o,i){return Le(o,r.codec(),i)}r.decode=n;function s(o,i){return Re(o,r.codec(),i)}r.stream=s})(Pt||(Pt={}));var K;(function(r){r.UNUSED="UNUSED",r.OK="OK",r.RESERVATION_REFUSED="RESERVATION_REFUSED",r.RESOURCE_LIMIT_EXCEEDED="RESOURCE_LIMIT_EXCEEDED",r.PERMISSION_DENIED="PERMISSION_DENIED",r.CONNECTION_FAILED="CONNECTION_FAILED",r.NO_RESERVATION="NO_RESERVATION",r.MALFORMED_MESSAGE="MALFORMED_MESSAGE",r.UNEXPECTED_MESSAGE="UNEXPECTED_MESSAGE"})(K||(K={}));var Pa;(function(r){r[r.UNUSED=0]="UNUSED",r[r.OK=100]="OK",r[r.RESERVATION_REFUSED=200]="RESERVATION_REFUSED",r[r.RESOURCE_LIMIT_EXCEEDED=201]="RESOURCE_LIMIT_EXCEEDED",r[r.PERMISSION_DENIED=202]="PERMISSION_DENIED",r[r.CONNECTION_FAILED=203]="CONNECTION_FAILED",r[r.NO_RESERVATION=204]="NO_RESERVATION",r[r.MALFORMED_MESSAGE=400]="MALFORMED_MESSAGE",r[r.UNEXPECTED_MESSAGE=401]="UNEXPECTED_MESSAGE"})(Pa||(Pa={}));(function(r){r.codec=()=>jt(Pa)})(K||(K={}));var or;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.relay!=null&&o.relay.byteLength>0&&(i.uint32(10),i.bytes(o.relay)),o.peer!=null&&o.peer.byteLength>0&&(i.uint32(18),i.bytes(o.peer)),o.expiration!=null&&o.expiration!==0n&&(i.uint32(24),i.uint64(o.expiration)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={relay:J(0),peer:J(0),expiration:0n},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{c.relay=o.bytes();break}case 2:{c.peer=o.bytes();break}case 3:{c.expiration=o.uint64();break}default:{o.skipType(l&7);break}}}return c},function*(o,i,a,c={}){let u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{yield{field:`${a}.relay`,value:o.bytes()};break}case 2:{yield{field:`${a}.peer`,value:o.bytes()};break}case 3:{yield{field:`${a}.expiration`,value:o.uint64()};break}default:{o.skipType(l&7);break}}}})),e);function t(o){return Be(o,r.codec())}r.encode=t;function n(o,i){return Le(o,r.codec(),i)}r.decode=n;function s(o,i){return Re(o,r.codec(),i)}r.stream=s})(or||(or={}));var vn;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.publicKey!=null&&o.publicKey.byteLength>0&&(i.uint32(10),i.bytes(o.publicKey)),o.payloadType!=null&&o.payloadType.byteLength>0&&(i.uint32(18),i.bytes(o.payloadType)),o.payload!=null&&(i.uint32(26),or.codec().encode(o.payload,i)),o.signature!=null&&o.signature.byteLength>0&&(i.uint32(42),i.bytes(o.signature)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={publicKey:J(0),payloadType:J(0),signature:J(0)},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{c.publicKey=o.bytes();break}case 2:{c.payloadType=o.bytes();break}case 3:{c.payload=or.codec().decode(o,o.uint32(),{limits:a.limits?.payload});break}case 5:{c.signature=o.bytes();break}default:{o.skipType(l&7);break}}}return c},function*(o,i,a,c={}){let u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{yield{field:`${a}.publicKey`,value:o.bytes()};break}case 2:{yield{field:`${a}.payloadType`,value:o.bytes()};break}case 3:{yield*or.codec().stream(o,o.uint32(),`${a}.payload`,{limits:c.limits?.payload});break}case 5:{yield{field:`${a}.signature`,value:o.bytes()};break}default:{o.skipType(l&7);break}}}})),e);function t(o){return Be(o,r.codec())}r.encode=t;function n(o,i){return Le(o,r.codec(),i)}r.decode=n;function s(o,i){return Re(o,r.codec(),i)}r.stream=s})(vn||(vn={}));var Vo=class extends Error{constructor(e="Transfer limit error"){super(e),this.name="TransferLimitError"}},Ho=class extends Error{constructor(e="Duration limit error"){super(e),this.name="DurationLimitError"}},_n=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 Kl(r,e,t){let n=e.remaining,s=o=>{let i=BigInt(o.data.byteLength);e.remaining-=i,e.remaining<0&&r.abort(new Vo(`data limit of ${n} bytes exceeded`))};r.addEventListener("message",s)}function ql(r,e,t,n,s){function o(l){r.abort(l),e.abort(l)}let i=[t,n.signal];if(n.limit?.duration!=null){s.log("limiting relayed connection duration to %dms",n.limit.duration);let l=AbortSignal.timeout(n.limit.duration);i.push(l)}let a=Ko(i);let c;n.limit?.data!=null&&(c={remaining:n.limit.data});let u=()=>{let l;t.aborted?l=t.reason:l=new Ho(`duration limit of ${n.limit?.duration} ms exceeded`),o(l)};a.addEventListener("abort",u,{once:!0}),c!=null&&(Kl(e,c,s),Kl(r,c,s)),Cl(r,e,r).catch(l=>{o(l)}).finally(()=>{a.clear()})}function Na(r){let e=r*BigInt(1e3),t=new Date().getTime();return Number(e-BigInt(t))}var An=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 t=this;Object.defineProperty(e,"bytes",{get(){return t.bytes}})}if(this.expires!=null){let t=this;Object.defineProperty(e,"seconds",{get(){return Math.round(((t.expires??0)-Date.now())/1e3)}})}return e}},Go=Q(W(Sl.matchers[0],X(290))),jo=Q(X(290));function Yo(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),s=n.value;return n.done===!0||s==null?{done:!0,value:void 0}:{done:!1,value:e(s)}}};return t}var Nt=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),{key:t,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return Yo(this.map.entries(),e=>[e[1].key,e[1].value])}forEach(e){this.map.forEach((t,n)=>{e(t.value,t.key,this)})}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),{key:e,value:t})}keys(){return Yo(this.map.values(),e=>e.key)}values(){return Yo(this.map.values(),e=>e.value)}get size(){return this.map.size}};var Zo=class{filter;constructor(e,t){this.filter=Pr(e,t)}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 Ua(r,e=.001){return new Zo(r,e)}var ka=class extends Nt{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Ma(r){let{name:e,metrics:t}=r,n;return t!=null?n=new ka({name:e,metrics:t}):n=new Nt,n}var Fa=class extends Error{type;code;constructor(e,t,n){super(e??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=t??"ABORT_ERR"}};function zl(r,e){let t=new Fa(e?.errorMessage,e?.errorCode,e?.errorName),n=new AbortController,s=()=>{n.abort(t)},o=AbortSignal.timeout(r);o.addEventListener("abort",s);let i=n.signal;return i.reset=a=>{o?.removeEventListener("abort",s),o=AbortSignal.timeout(a??r),o.addEventListener("abort",()=>{n.abort(t)})},i.clear=()=>{o?.removeEventListener("abort",s),o=void 0},i}var Xo=class{reservations;maxReservations;applyDefaultLimit;reservationTtl;defaultDurationLimit;defaultDataLimit;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:circuit-relay:server:reservation-store"),this.maxReservations=t.maxReservations??Bl,this.applyDefaultLimit=t.applyDefaultLimit!==!1,this.reservationTtl=t.reservationTtl??Rl,this.defaultDurationLimit=t.defaultDurationLimit??Nl,this.defaultDataLimit=t.defaultDataLimit??Ul,this.reservations=Ma({metrics:e.metrics,name:"libp2p_circuit_relay_server_reservations_total"})}reserve(e,t,n){let s=this.reservations.get(e);if(this.reservations.size>=this.maxReservations&&s==null)return{status:K.RESERVATION_REFUSED};let o=new Date(Date.now()+this.reservationTtl),i;return this.applyDefaultLimit&&(i=n??{data:this.defaultDataLimit,duration:this.defaultDurationLimit}),s!=null?(this.log("refreshing reservation for client %p",e),s.signal.reset(this.reservationTtl)):(this.log("creating new reservation for client %p",e),s={addr:t,expiry:o,limit:i,signal:zl(this.reservationTtl)},s.signal.addEventListener("abort",()=>{this.reservations.delete(e)})),this.reservations.set(e,s),{status:K.OK,expire:Math.round(o.getTime()/1e3)}}removeReservation(e){this.reservations.delete(e)}get(e){return this.reservations.get(e)}clear(){this.reservations.clear()}};var Qo=class r{domain="libp2p-relay-rsvp";codec=new Uint8Array([3,2]);relay;peer;expiration;constructor({relay:e,peer:t,expiration:n}){this.relay=e,this.peer=t,this.expiration=n}marshal(){return or.encode({relay:this.relay.toMultihash().bytes,peer:this.peer.toMultihash().bytes,expiration:BigInt(this.expiration)})}equals(e){return!(!(e instanceof r)||!this.peer.equals(e.peer)||!this.relay.equals(e.relay)||this.expiration!==e.expiration)}};var Hp={maxOutboundStopStreams:En},Jo=class extends Ie{components;reservationStore;started;hopTimeout;shutdownController;maxInboundHopStreams;maxOutboundHopStreams;maxOutboundStopStreams;log;constructor(e,t={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:server"),this.components=e,this.started=!1,this.hopTimeout=t?.hopTimeout??kl,this.maxInboundHopStreams=t.maxInboundHopStreams,this.maxOutboundHopStreams=t.maxOutboundHopStreams,this.maxOutboundStopStreams=t.maxOutboundStopStreams??Hp.maxOutboundStopStreams,this.reservationStore=new Xo(e,t.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(Ke,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(Ke),this.started=!1}async onHop(e,t){this.log("received circuit v2 hop protocol stream from %p",t.remotePeer);let n=AbortSignal.timeout(this.hopTimeout);let s={signal:n},o=Rt(e);try{let i=await o.pb(Z).read(s);if(i?.type==null)throw new Error("request was invalid, could not read from stream");this.log("received",i.type),await this.handleHopProtocol({connection:t,stream:o,request:i},s)}catch(i){this.log.error("error while handling hop - %e",i),await o.pb(Z).write({type:Z.Type.STATUS,status:K.MALFORMED_MESSAGE},s),e.abort(i)}}async handleHopProtocol({stream:e,request:t,connection:n},s){switch(this.log("received hop message"),t.type){case Z.Type.RESERVE:await this.handleReserve({stream:e,request:t,connection:n},s);break;case Z.Type.CONNECT:await this.handleConnect({stream:e,request:t,connection:n},s);break;default:this.log.error("invalid hop request type %s via peer %p",t.type,n.remotePeer),await e.pb(Z).write({type:Z.Type.STATUS,status:K.UNEXPECTED_MESSAGE})}}async handleReserve({stream:e,connection:t},n){let s=e.pb(Z);if(this.log("hop reserve request from %p",t.remotePeer),tr.exactMatch(t.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",t.remotePeer),await s.write({type:Z.Type.STATUS,status:K.PERMISSION_DENIED},n);return}if(await this.components.connectionGater.denyInboundRelayReservation?.(t.remotePeer)===!0){this.log.error("reservation for %p denied by connection gater",t.remotePeer),await s.write({type:Z.Type.STATUS,status:K.PERMISSION_DENIED},n);return}let o=this.reservationStore.reserve(t.remotePeer,t.remoteAddr);try{if(o.status!==K.OK){await s.write({type:Z.Type.STATUS,status:o.status},n);return}if(o.expire!=null){let i=o.expire*1e3-Date.now();await this.components.peerStore.merge(t.remotePeer,{tags:{[Oa]:{value:1,ttl:i}}},n)}await s.write({type:Z.Type.STATUS,status:K.OK,reservation:await this.makeReservation(t.remotePeer,BigInt(o.expire??0)),limit:this.reservationStore.get(t.remotePeer)?.limit},n),this.log("sent confirmation response to %s",t.remotePeer),await s.unwrap().unwrap().close(n)}catch(i){this.log.error("failed to send confirmation response to %p - %e",t.remotePeer,i),this.reservationStore.removeReservation(t.remotePeer);try{await this.components.peerStore.merge(t.remotePeer,{tags:{[Oa]:void 0}},n)}catch(a){this.log.error("failed to untag relay source peer %p - %e",t.remotePeer,a)}}}async makeReservation(e,t){let n=[];for(let o of this.components.addressManager.getAddresses())o.toString().includes("/p2p-circuit")||n.push(o.bytes);let s=await mn.seal(new Qo({peer:e,relay:this.components.peerId,expiration:t}),this.components.privateKey);return{addrs:n,expire:t,voucher:{publicKey:Je(s.publicKey),payloadType:s.payloadType,payload:{peer:e.toMultihash().bytes,relay:this.components.peerId.toMultihash().bytes,expiration:t},signature:s.signature}}}async handleConnect({stream:e,request:t,connection:n},s){let o=e.pb(Z);if(tr.matches(n.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",n.remotePeer),await o.write({type:Z.Type.STATUS,status:K.PERMISSION_DENIED},s);return}this.log("hop connect request from %p",n.remotePeer);let i;try{if(t.peer==null)throw this.log.error("no peer info in hop connect request"),new Error("no peer info in request");t.peer.addrs.forEach(Ue),i=Cr(Xe(t.peer.id))}catch(f){this.log.error("invalid hop connect request via peer %p - %e",n.remotePeer,f),await o.write({type:Z.Type.STATUS,status:K.MALFORMED_MESSAGE},s);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,K.NO_RESERVATION),await o.write({type:Z.Type.STATUS,status:K.NO_RESERVATION},s);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 o.write({type:Z.Type.STATUS,status:K.PERMISSION_DENIED},s);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 o.write({type:Z.Type.STATUS,status:K.NO_RESERVATION},s);return}let u=c[0],l=await this.stopHop({connection:u,request:{type:ke.Type.CONNECT,peer:{id:n.remotePeer.toMultihash().bytes,addrs:[]},limit:a?.limit}},s);if(l==null){this.log.error("failed to open stream to destination peer %p",u?.remotePeer),await o.write({type:Z.Type.STATUS,status:K.CONNECTION_FAILED},s);return}await o.write({type:Z.Type.STATUS,status:K.OK,limit:a?.limit},s),this.log("connection from %p to %p established - merging streams",n.remotePeer,i),ql(e.unwrap(),l,this.shutdownController.signal,a,{log:this.log})}async stopHop({connection:e,request:t},n){this.log("starting circuit relay v2 stop request to %s",e.remotePeer);let s=await e.newStream(nr,{maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0,...n}),o=Rt(s),i=o.pb(ke);await i.write(t,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 s.close(n);return}if(a.status===K.OK)return this.log("stop request to %p was successful",e.remotePeer),o.unwrap();this.log("stop request failed with code %d",a.status),await s.close(n)}get reservations(){return this.reservationStore.reservations}};var Ut=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var es=class extends Ie{components;started;running;topologyId;log;discoveryController;filter;queue;constructor(e,t={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:discover-relays"),this.components=e,this.started=!1,this.running=!1,this.filter=t.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(Ke,{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(Ke)],orders:[()=>Math.random()<.5?1:-1,(n,s)=>{let o=Vl(n),i=Vl(s);return o>i?-1:i>o?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 t=this.queue=new kr({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),t.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(s=>s.toString()));continue}t.queued>10&&(this.log.trace("wait for space in queue for %p",n.id),await t.onSizeLessThan(10,{signal:this.discoveryController.signal})),this.log("adding random peer %p to dial queue (length: %d, active %d)",n.id,t.size,t.running),t.add(this.dialPeer,{peerId:n.id,signal:this.discoveryController.signal}).catch(s=>{this.log.error("error opening connection to random peer %p - %e",n.id,s)})}this.log("stop random walk"),await t.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(t=>{this.log.trace("error dialing discovered peer %p - %e",e.detail.id,t)})}async maybeDialPeer(e){if(this.queue==null)return;let t=e.detail.id,n=e.detail.multiaddrs;if(this.queue.has(t)){this.log.trace("random peer %p was already in queue",t);return}if(this.components.connectionManager.getConnections(t)?.length>0){this.log.trace("random peer %p was already connected",t);return}if(!await this.components.connectionManager.isDialable(n)){this.log.trace("random peer %p was not dialable",t);return}this.queue?.add(this.dialPeer,{peerId:e.detail.id,signal:this.discoveryController.signal}).catch(s=>{this.log.error("error opening connection to discovered peer %p - %e",e.detail.id,s)})}async dialPeer({peerId:e,signal:t}){let n=Ko([AbortSignal.timeout(5e3),t]);try{await this.components.connectionManager.openConnection(e,{signal:n})}finally{n.clear()}}};function Vl(r){let e=r.metadata.get("last-dial-success");return e==null?0:new Date(H(e)).getTime()}var qa=class extends Ie{connectionManager;addressManager;reservationStore;listeningAddrs;log;listenTimeout;reservationId;relay;constructor(e,t={}){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=t.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(t=>{this.addressManager.removeObservedAddr(t)}),this.listeningAddrs=[],this.safeDispatchEvent("listening"))};_onAddRelayPeer=e=>{let{details:t}=e.detail;t.type!=="configured"&&t.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(Go.exactMatch(e)){this.log("listen on specific relay server %a",e);let t=AbortSignal.timeout(this.listenTimeout);let n=e.decapsulate("/p2p-circuit"),s=await this.connectionManager.openConnection(n,{signal:t});if(!this.reservationStore.hasReservation(s.remotePeer)){this.log("making reservation on peer %p",s.remotePeer);let o=await this.reservationStore.addRelay(s.remotePeer,"configured");this.addedRelay(o)}}else throw new kt(`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,this.listeningAddrs=e.details.reservation.addrs.map(t=>Ue(t).encapsulate("/p2p-circuit")),this.listeningAddrs.forEach(t=>{this.addressManager.confirmObservedAddr(t,{type:"transport"})}),queueMicrotask(()=>{this.safeDispatchEvent("listening")})}};function Hl(r){return new qa(r)}var $l="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Wl=(r=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)e+=$l[t[r]&63];return e};var $p=60*1e3*10,Wp=60*1e3*5,Gp=30*1e3,ts=class extends Ie{peerId;connectionManager;peerStore;events;reserveQueue;reservations;pendingReservations;maxReservationQueueLength;reservationCompletionTimeout;started;log;relayFilter;constructor(e,t){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=t?.maxReservationQueueLength??Pl,this.reservationCompletionTimeout=t?.reservationCompletionTimeout??zo,this.started=!1,this.relayFilter=Pr(100),this.reserveQueue=new kr({concurrency:t?.reservationConcurrency??Ol,metricName:"libp2p_relay_reservation_queue",metrics:e.metrics}),this.events.addEventListener("connection:close",n=>{[...this.reservations.values()].find(o=>o.connection===n.detail.id)!=null&&this.#t(n.detail.remotePeer).catch(o=>{this.log("could not remove relay %p - %e",n.detail,o)})})}isStarted(){return this.started}start(){this.started=!0}afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>t.tags.has(xn)]});this.log("removing tag from %d old relays",e.length),await Promise.all(e.map(async t=>{await this.peerStore.merge(t.id,{tags:{[xn]:void 0}})})),this.log("redialing %d old relays",e.length),await Promise.all(e.map(async t=>this.addRelay(t.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=Wl();return this.pendingReservations.push(e),this.#r(),e}async addRelay(e,t){if(this.peerId.equals(e))throw this.log.trace("not trying to use self as relay"),new kt("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 kt("The relay was previously invalid");return this.log.trace("try to reserve relay slot with %p",e),this.reserveQueue.add(async()=>{let s=Date.now();try{let o=this.reservations.get(e);if(o!=null){let x=this.connectionManager.getConnections(e),S=!1;if(x.length===0&&this.log("already have relay reservation with %p but we are no longer connected",e),x.map(h=>h.id).includes(o.connection)&&(this.log("already have relay reservation with %p and the original connection is still open",e),S=!0),S&&Na(o.reservation.expire)>$p)return this.log("already have relay reservation with %p but we are still connected and it does not expire soon",e),{relay:e,details:o};await this.#t(e)}if(t==="discovered"&&this.pendingReservations.length===0)throw new _n("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(tr.matches(a.remoteAddr))throw new $o("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-Wp,Gp),Math.pow(2,31)-1),f=setTimeout(()=>{this.log("refresh reservation to relay %p",e),this.addRelay(e,t).catch(async x=>{this.log.error("could not refresh reservation to relay %p - %e",e,x),await this.#t(e)}).catch(x=>{this.log.error("could not remove expired reservation to relay %p - %e",e,x)})},l),m;if(t==="discovered"){let x=this.pendingReservations.pop();if(x==null)throw new _n("Made reservation on relay but did not need any more discovered relays");m={timeout:f,reservation:c,type:t,connection:a.id,id:x}}else m={timeout:f,reservation:c,type:t,connection:a.id};this.reservations.set(e,m),await this.peerStore.merge(e,{tags:{[xn]:{value:1,ttl:u}}}),this.#r();let d={relay:e,details:m};return this.safeDispatchEvent("relay:created-reservation",{detail:d}),d}catch(o){throw t==="discovered"&&o.name==="HadEnoughRelaysError"||this.log.error("could not reserve slot on %p after %dms - %e",e,Date.now()-s,o),(o.name==="DialError"||o.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)}),o}},{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((t,n)=>(n.type===e&&t++,t),0)}cancelReservations(){[...this.reservations.values()].forEach(e=>{clearTimeout(e.timeout)}),this.reservations.clear()}async#e(e,t){t.signal?.throwIfAborted(),this.log("requesting reservation from %p",e.remotePeer);let n=await e.newStream(Ke,t),o=Rt(n).pb(Z);this.log.trace("send RESERVE to %p",e.remotePeer),await o.write({type:Z.Type.RESERVE},t);let i;try{this.log.trace("reading response from %p",e.remotePeer),i=await o.read(t)}catch(c){throw n.abort(c),c}finally{n.status!=="closed"&&await n.close(t)}if(this.log.trace("read response %s",i.status),i.status===K.OK&&i.reservation!=null){let c=new Set;c.add(e.remoteAddr.toString());for(let u of i.reservation.addrs){let l=Ue(u);l.getComponents().find(f=>f.code===421)==null&&(l=l.encapsulate(`/p2p/${e.remotePeer}`)),l=Ue(l.toString().replace(`/p2p/${e.remotePeer}/p2p/${e.remotePeer}`,`/p2p/${e.remotePeer}`)),c.add(l.toString())}return i.reservation.addrs=[...c].map(u=>Ue(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 t=this.reservations.get(e);t!=null&&(this.log("removing relay reservation with %p from local store",e),clearTimeout(t.timeout),this.reservations.delete(e),t.type==="discovered"&&this.pendingReservations.push(t.id),await this.peerStore.merge(e,{tags:{[xn]:void 0}}),this.safeDispatchEvent("relay:removed",{detail:{relay:e,details:t}}),this.#r())}#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=Pr(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",t=>{this.onTransportClosed(t.error)}),this.stream.addEventListener("remoteCloseWrite",t=>{this.onRemoteCloseWrite(),this.close().catch(n=>{this.abort(n)})}),this.stream.addEventListener("message",t=>{e.onDataRead?.(t.data),this.onData(t.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 Va(r){return new za(r)}var jp=r=>{if(r.peer==null)return!1;try{r.peer.addrs.forEach(Ue)}catch{return!1}return!0},Gl={maxInboundStopStreams:En,maxOutboundStopStreams:En,stopTimeout:3e4},rs=class{components;discovery;reservationStore;maxInboundStopStreams;maxOutboundStopStreams;started;log;shutdownController;constructor(e,t={}){this.components=e,this.log=e.logger.forComponent("libp2p:circuit-relay:transport"),this.maxInboundStopStreams=t.maxInboundStopStreams??Gl.maxInboundStopStreams,this.maxOutboundStopStreams=t.maxOutboundStopStreams??Gl.maxOutboundStopStreams,this.shutdownController=new AbortController,this.discovery=new es(e,{filter:t.discoveryFilter??Ua(Ml,Fl)}),this.discovery.addEventListener("relay:discover",n=>{this.reservationStore.addRelay(n.detail,"discovered").catch(s=>{s.name!=="HadEnoughRelaysError"&&s.name!=="RelayQueueFullError"&&this.log.error("could not add discovered relay %p - %e",n.detail,s)})}),this.reservationStore=new ts(e,t),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(nr,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 Ya(this.discovery,this.reservationStore),await this.components.registrar.unhandle(nr),this.started=!1}async dial(e,t){let n=e.toString().split("/p2p-circuit"),s=Ue(n[0]),o=Ue(n[n.length-1]),i=s.getComponents().find(d=>d.code===421)?.value,a=o.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 Bn(`C${d}`)}let c=Hi(i),u=Hi(a),f=this.components.connectionManager.getConnections(c)[0];f==null?(await this.components.peerStore.merge(c,{multiaddrs:[s]}),t.onProgress?.(new Ut("circuit-relay:open-connection")),f=await this.components.connectionManager.openConnection(c,t)):t.onProgress?.(new Ut("circuit-relay:reuse-connection"));let m;try{t.onProgress?.(new Ut("circuit-relay:open-hop-stream")),m=await f.newStream(Ke,t);let d=Rt(m).pb(Z);t.onProgress?.(new Ut("circuit-relay:write-connect-message")),await d.write({type:Z.Type.CONNECT,peer:{id:u.toMultihash().bytes,addrs:[Ue(o).bytes]}},t),t.onProgress?.(new Ut("circuit-relay:read-connect-response"));let x=await d.read(t);if(x.status!==K.OK)throw new Ln(`failed to connect via relay with status ${x?.status?.toString()??"undefined"}`);let S=new An(x.limit),h=Va({stream:d.unwrap().unwrap(),remoteAddr:e,localAddr:s.encapsulate(`/p2p-circuit/p2p/${this.components.peerId.toString()}`),onDataRead:S.onData,onDataWrite:S.onData,log:m.log.newScope("circuit-relay:connection")}),y=await this.components.upgrader.upgradeOutbound(h,{...t,limits:S.getLimits()});return y.log("outbound relayed connection established to %p with limits %o, over connection %s",y.remotePeer,x.limit??"none",f.id),y}catch(d){throw this.log.error("circuit relay dial to destination %p via relay %p failed - %e",u,c,d),m?.abort(d),d}}createListener(e){return Hl({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(t=>Go.exactMatch(t)||jo.exactMatch(t))}dialFilter(e){return e=Array.isArray(e)?e:[e],e.filter(t=>tr.exactMatch(t))}async onStop(e,t){let n=this.components.upgrader.createInboundAbortSignal(this.shutdownController.signal);try{if(!this.reservationStore.hasReservation(t.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([t.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 s=Rt(e).pb(ke),o=await s.read({signal:n});if(this.log("new circuit relay v2 stop stream from %p with type %s",t.remotePeer,o.type),o?.type===void 0){this.log.error("type was missing from circuit v2 stop protocol request from %s",t.remotePeer),await s.write({type:ke.Type.STATUS,status:K.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}if(o.type!==ke.Type.CONNECT){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await s.write({type:ke.Type.STATUS,status:K.UNEXPECTED_MESSAGE},{signal:n}),await e.close({signal:n});return}if(!jp(o)){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await s.write({type:ke.Type.STATUS,status:K.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}let i=Cr(Xe(o.peer.id));if(await this.components.connectionGater.denyInboundRelayedConnection?.(t.remotePeer,i)===!0){this.log.error("connection gater denied inbound relayed connection from %p",t.remotePeer),await s.write({type:ke.Type.STATUS,status:K.PERMISSION_DENIED},{signal:n}),await e.close({signal:n});return}this.log.trace("sending success response to %p",t.remotePeer),await s.write({type:ke.Type.STATUS,status:K.OK},{signal:n});let a=new An(o.limit),c=t.remoteAddr.encapsulate(`/p2p-circuit/p2p/${i.toString()}`),u=this.components.addressManager.getAddresses()[0],l=Va({stream:s.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,o.limit??"none",t.id)}finally{n?.clear()}}};function Yp(r={}){return e=>new Jo(e,r)}function Zp(r={}){return e=>new rs(e,r)}return Ql(Xp);})();
2
+ "use strict";var Libp2PCircuitRelayV2=(()=>{var ns=Object.defineProperty;var jl=Object.getOwnPropertyDescriptor;var Yl=Object.getOwnPropertyNames;var Zl=Object.prototype.hasOwnProperty;var Te=(r,e)=>{for(var t in e)ns(r,t,{get:e[t],enumerable:!0})},Xl=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Yl(e))!Zl.call(r,s)&&s!==t&&ns(r,s,{get:()=>e[s],enumerable:!(n=jl(e,s))||n.enumerable});return r};var Ql=r=>Xl(ns({},"__esModule",{value:!0}),r);var Xp={};Te(Xp,{RELAY_V2_HOP_CODEC:()=>Ke,RELAY_V2_STOP_CODEC:()=>nr,circuitRelayServer:()=>Yp,circuitRelayTransport:()=>Zp});function Jl(r){return typeof r?.handleEvent=="function"}function ef(r){return(r!==!0&&r!==!1&&r?.once)??!1}var Ie=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){let s=ef(n);super.addEventListener(e,i=>{if(s){let a=this.#e.get(i.type);a!=null&&(a=a.filter(({callback:c})=>c!==t),this.#e.set(i.type,a))}Jl(t)?t.handleEvent(i):t(i)},n);let o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:t,once:s})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let s=this.#e.get(e);s!=null&&(s=s.filter(({callback:o})=>o!==t),this.#e.set(e,s))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var st=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var oe=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 In=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}};var yt=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},Fr=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}};var Dn=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Cn=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var Ln=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var Bn=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}},kt=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 Rn=class extends Event{data;constructor(e,t){super("message",t),this.data=e}},cr=class extends Event{error;local;constructor(e,t,n){super("close",n),this.error=t,this.local=e}},On=class extends cr{constructor(e,t){super(!0,e,t)}},Pn=class extends cr{constructor(e,t){super(!1,e,t)}};var os=Symbol.for("@libp2p/peer-id");var Wa="keep-alive";function Ga(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function ja(...r){let e=[];for(let t of r)Ga(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStart!=null&&await t.beforeStart()})),await Promise.all(e.map(async t=>{await t.start()})),await Promise.all(e.map(async t=>{t.afterStart!=null&&await t.afterStart()}))}async function Ya(...r){let e=[];for(let t of r)Ga(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStop!=null&&await t.beforeStop()})),await Promise.all(e.map(async t=>{await t.stop()})),await Promise.all(e.map(async t=>{t.afterStop!=null&&await t.afterStop()}))}var Xa=Symbol.for("@libp2p/transport");var Za;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Za||(Za={}));var Qa=Symbol.for("@libp2p/service-capabilities"),Ja=Symbol.for("@libp2p/service-dependencies");var us={};Te(us,{base58btc:()=>re,base58flickr:()=>uf});var Bm=new Uint8Array(0);function tc(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function Me(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return Mt(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return Mt(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function rc(r){let e=new Uint8Array(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}var ec=4096;function nc(r){let e=r.length;if(e<=ec)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.subarray(n,n+=ec));return t}function tf(r){return r?.buffer instanceof ArrayBuffer}function Mt(r){return tf(r)?r:r.slice()}function rf(r,e,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),s=0;s<n.length;s++)n[s]=255;for(var o=0;o<r.length;o++){var i=r.charAt(o),a=i.charCodeAt(0);if(n[a]!==255)throw new TypeError(i+" is ambiguous");if(n[a]=o,t){var c=i.toLowerCase().charCodeAt(0),u=i.toUpperCase().charCodeAt(0);c!==a&&(n[c]=o),u!==a&&(n[u]=o)}}var l=r.length,f=r.charAt(0),m=Math.log(l)/Math.log(256),d=Math.log(256)/Math.log(l);function x(y){if(y instanceof Uint8Array||(ArrayBuffer.isView(y)?y=new Uint8Array(y.buffer,y.byteOffset,y.byteLength):Array.isArray(y)&&(y=Uint8Array.from(y))),!(y instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(y.length===0)return"";for(var E=0,A=0,B=0,C=y.length;B!==C&&y[B]===0;)B++,E++;for(var U=(C-B)*d+1>>>0,R=new Uint8Array(U);B!==C;){for(var T=y[B],k=0,M=U-1;(T!==0||k<A)&&M!==-1;M--,k++)T+=256*R[M]>>>0,R[M]=T%l>>>0,T=T/l>>>0;if(T!==0)throw new Error("Non-zero carry");A=k,B++}for(var N=U-A;N!==U&&R[N]===0;)N++;for(var p=f.repeat(E);N<U;++N)p+=r.charAt(R[N]);return p}function S(y){if(typeof y!="string")throw new TypeError("Expected String");if(y.length===0)return new Uint8Array;var E=0;if(y[E]!==" "){for(var A=0,B=0;y[E]===f;)A++,E++;for(var C=(y.length-E)*m+1>>>0,U=new Uint8Array(C);y[E];){var R=n[y.charCodeAt(E)];if(R===255)return;for(var T=0,k=C-1;(R!==0||T<B)&&k!==-1;k--,T++)R+=l*U[k]>>>0,U[k]=R%256>>>0,R=R/256>>>0;if(R!==0)throw new Error("Non-zero carry");B=T,E++}if(y[E]!==" "){for(var M=C-B;M!==C&&U[M]===0;)M++;for(var N=new Uint8Array(A+(C-M)),p=A;M!==C;)N[p++]=U[M++];return N}}}function h(y){var E=S(y);if(E)return E;throw new Error(`Non-${e} character`)}return{encode:x,decodeUnsafe:S,decode:h}}var nf=rf,of=nf,sc=of;var ss=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},is=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,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)}},as=class{decoders;constructor(e){this.decoders=e}or(e){return ic(this,e)}decode(e){let t=e[0],n=this.decoders[t];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(r,e){return new as({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var cs=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new ss(e,t,n),this.decoder=new is(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function ur({name:r,prefix:e,encode:t,decode:n}){return new cs(r,e,t,n)}function gt({name:r,prefix:e,alphabet:t,caseInsensitive:n=!1}){let{encode:s,decode:o}=sc(t,r,n);return ur({prefix:e,name:r,encode:s,decode:i=>Me(o(i))})}function sf(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let u=0;u<s;++u){let l=e[r[u]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|l,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function af(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function cf(r,e){let t={};for(let n=0;n<r.length;++n)if(t[r[n]]=n,e){let s=r[n].toLowerCase(),o=r[n].toUpperCase();s!==r[n]&&(t[s]=n),o!==r[n]&&(t[o]=n)}return t}function se({name:r,prefix:e,bitsPerChar:t,alphabet:n,caseInsensitive:s=!1}){let o=cf(n,s);return ur({prefix:e,name:r,encode(i){return af(i,n,t)},decode(i){return sf(i,o,t,r)}})}var re=gt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),uf=gt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ls={};Te(ls,{base32:()=>bt,base32hex:()=>hf,base32hexpad:()=>mf,base32hexpadupper:()=>yf,base32hexupper:()=>pf,base32pad:()=>ff,base32padupper:()=>df,base32upper:()=>lf,base32z:()=>gf});var bt=se({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5,caseInsensitive:!0}),lf=se({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5,caseInsensitive:!0}),ff=se({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5,caseInsensitive:!0}),df=se({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5,caseInsensitive:!0}),hf=se({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5,caseInsensitive:!0}),pf=se({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5,caseInsensitive:!0}),mf=se({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5,caseInsensitive:!0}),yf=se({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5,caseInsensitive:!0}),gf=se({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var fs={};Te(fs,{base36:()=>Kr,base36upper:()=>bf});var Kr=gt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz",caseInsensitive:!0}),bf=gt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",caseInsensitive:!0});var wf=uc,ac=128,xf=127,Ef=~xf,Sf=Math.pow(2,31);function uc(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Sf;)e[t++]=r&255|ac,r/=128;for(;r&Ef;)e[t++]=r&255|ac,r>>>=7;return e[t]=r|0,uc.bytes=t-n+1,e}var vf=ds,_f=128,cc=127;function ds(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw ds.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&cc)<<s:(i&cc)*Math.pow(2,s),s+=7}while(i>=_f);return ds.bytes=o-n,t}var Af=Math.pow(2,7),Tf=Math.pow(2,14),If=Math.pow(2,21),Df=Math.pow(2,28),Cf=Math.pow(2,35),Lf=Math.pow(2,42),Bf=Math.pow(2,49),Rf=Math.pow(2,56),Of=Math.pow(2,63),Pf=function(r){return r<Af?1:r<Tf?2:r<If?3:r<Df?4:r<Cf?5:r<Lf?6:r<Bf?7:r<Rf?8:r<Of?9:10},Nf={encode:wf,decode:vf,encodingLength:Pf},Uf=Nf,qr=Uf;function zr(r,e=0){let t=qr.decode(r,e),n=qr.decode.bytes;if(n>9)throw new RangeError("Invalid varint: too long");if(n>1&&r[e+n-1]===0)throw new RangeError("Invalid varint: not minimally encoded");return[t,n]}function lr(r,e,t=0){return qr.encode(r,e,t),e}function fr(r){return qr.encodingLength(r)}function Ze(r,e){let t=e.byteLength,n=fr(r),s=n+fr(t),o=new Uint8Array(s+t);return lr(r,o,0),lr(t,o,n),o.set(e,s),new dr(r,t,e,o)}function Xe(r){let e=Me(r),[t,n]=zr(e),[s,o]=zr(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new dr(t,s,i,e)}function lc(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&tc(r.bytes,t.bytes)}}var dr=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=Mt(n),this.bytes=Mt(s)}};function fc(r,e){let{bytes:t,version:n}=r;return n===0?Mf(t,hs(r),e??re.encoder):Ff(t,hs(r),e??bt.encoder)}var dc=new WeakMap;function hs(r){let e=dc.get(r);if(e==null){let t=new Map;return dc.set(r,t),t}return e}var le=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=Mt(s),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:t}=this;if(e!==Vr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Kf)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}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:t}=this.multihash,n=Ze(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;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 t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??hc(n,s,o.bytes))}else if(t[qf]===!0){let{version:n,multihash:s,code:o}=t,i=Xe(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="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(t!==Vr)throw new Error(`Version 0 CID must use dag-pb (code: ${Vr}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=hc(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Vr,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=Me(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new dr(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,m]=zr(e.subarray(t));return t+=m,f},s=n(),o=Vr;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),u=t+c,l=u-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(e,t){let[n,s]=kf(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return hs(o).set(n,e),o}};function kf(r,e){switch(r[0]){case"Q":{let t=e??re;return[re.prefix,t.decode(`${re.prefix}${r}`)]}case re.prefix:{let t=e??re;return[re.prefix,t.decode(r)]}case bt.prefix:{let t=e??bt;return[bt.prefix,t.decode(r)]}case Kr.prefix:{let t=e??Kr;return[Kr.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function Mf(r,e,t){let{prefix:n}=t;if(n!==re.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function Ff(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}var Vr=112,Kf=18;function hc(r,e,t){let n=fr(r),s=n+fr(e),o=new Uint8Array(s+t.byteLength);return lr(r,o,0),lr(e,o,n),o.set(t,s),o}var qf=Symbol.for("@ipld/js-cid/CID");var ps={};Te(ps,{identity:()=>qe});var pc=0,zf="identity",mc=Me;function Vf(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return Ze(pc,mc(r))}var qe={code:pc,name:zf,encode:mc,digest:Vf};function ce(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function Hf(r){return r.buffer instanceof ArrayBuffer}function _e(r){return Hf(r)?r:r.slice()}async function yc(r,e,t,n){let s=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let o=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},s,_e(e),_e(t.subarray()));return n?.signal?.throwIfAborted(),o}function J(r=0){return new Uint8Array(r)}function xe(r=0){return new Uint8Array(r)}function $f(r){return r?.buffer instanceof ArrayBuffer}function ms(r){if($f(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function Qe(r,e){e==null&&(e=r.reduce((s,o)=>s+o.length,0));let t=xe(e),n=0;for(let s of r)t.set(s,n),n+=s.length;return ms(t)}var bc=Symbol.for("@achingbrain/uint8arraylist");function gc(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let s=t+n.byteLength;if(e<s)return{buf:n,index:e-t};t=s}throw new RangeError("index is out of bounds")}function Un(r){return!!r?.[bc]}var ee=class r{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 t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(Un(n)){t+=n.byteLength;for(let s of n.bufs)this.bufs.push(s)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(Un(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=gc(this.bufs,e);return t.buf[t.index]}set(e,t){let n=gc(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(Un(e))for(let n=0;n<e.length;n++)this.set(t+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,t){let{bufs:n,length:s}=this._subList(e,t);return Qe(n,s)}subarray(e,t){let{bufs:n,length:s}=this._subList(e,t);return n.length===1?n[0]:Qe(n,s)}sublist(e,t){let{bufs:n,length:s}=this._subList(e,t),o=new r;return o.length=s,o.bufs=n,o}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],s=0;for(let o=0;o<this.bufs.length;o++){let i=this.bufs[o],a=s,c=a+i.byteLength;if(s=c,e>=c)continue;let u=e>=a&&e<c,l=t>a&&t<=c;if(u&&l){if(e===a&&t===c){n.push(i);break}let f=e-a;n.push(i.subarray(f,f+(t-e)));break}if(u){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(l){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!Un(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(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let s=n.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let o=256,i=new Int32Array(o);for(let f=0;f<o;f++)i[f]=-1;for(let f=0;f<s;f++)i[n[f]]=f;let a=i,c=this.byteLength-n.byteLength,u=n.byteLength-1,l;for(let f=t;f<=c;f+=l){l=0;for(let m=u;m>=0;m--){let d=this.get(f+m);if(n[m]!==d){l=Math.max(1,m-a[d]);break}}if(l===0)return f}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=xe(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let s=J(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,t,n),this.write(s,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let s=J(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,t,n),this.write(s,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let s=J(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,t,n),this.write(s,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=xe(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let s=J(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,t,n),this.write(s,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let s=J(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,t,n),this.write(s,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let s=J(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,t,n),this.write(s,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let s=J(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,t,n),this.write(s,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let s=J(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,t,n),this.write(s,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!ce(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((s,o)=>s+o.byteLength,0)),n.length=t,n}};var ys={};Te(ys,{base10:()=>Wf});var Wf=gt({prefix:"9",name:"base10",alphabet:"0123456789"});var gs={};Te(gs,{base16:()=>Gf,base16upper:()=>jf});var Gf=se({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4,caseInsensitive:!0}),jf=se({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4,caseInsensitive:!0});var bs={};Te(bs,{base2:()=>Yf});var Yf=se({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var ws={};Te(ws,{base256emoji:()=>ed});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}"),Zf=wc.reduce((r,e,t)=>(r[t]=e,r),[]),Xf=wc.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function Qf(r){return r.reduce((e,t)=>(e+=Zf[t],e),"")}function Jf(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let s=Xf[n];if(s==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}var ed=ur({prefix:"\u{1F680}",name:"base256emoji",encode:Qf,decode:Jf});var Es={};Te(Es,{base64:()=>td,base64pad:()=>rd,base64url:()=>xs,base64urlpad:()=>nd});var td=se({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),rd=se({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),xs=se({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),nd=se({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Ss={};Te(Ss,{base8:()=>od});var od=se({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var vs={};Te(vs,{identity:()=>sd});var sd=ur({prefix:"\0",name:"identity",encode:r=>nc(Me(r)),decode:r=>Me(rc(r))});var y0=new TextEncoder,g0=new TextDecoder;var Ts={};Te(Ts,{sha256:()=>hr,sha512:()=>ud});var cd=20;function As({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new _s(r,e,t,n,s)}var _s=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??cd,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.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,t?.truncate):n.then(s=>xc(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function xc(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return Ze(e,r)}function Sc(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var hr=As({name:"sha2-256",code:18,encode:Sc("SHA-256")}),ud=As({name:"sha2-512",code:19,encode:Sc("SHA-512")});var Hr={...vs,...bs,...Ss,...ys,...gs,...ls,...fs,...us,...Es,...ws},C0={...Ts,...ps};function _c(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var vc=_c("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Is=_c("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=xe(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),ld={utf8:vc,"utf-8":vc,hex:Hr.base16,latin1:Is,ascii:Is,binary:Is,...Hr},kn=ld;function F(r,e="utf8"){let t=kn[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function H(r,e="utf8"){let t=kn[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var fd=parseInt("11111",2),Ds=parseInt("10000000",2),dd=parseInt("01111111",2),Ac={0:$r,1:$r,2:hd,3:yd,4:gd,5:md,6:pd,16:$r,22:$r,48:$r};function at(r,e={offset:0}){let t=r[e.offset]&fd;if(e.offset++,Ac[t]!=null)return Ac[t](r,e);throw new Error("No decoder for tag "+t)}function Wr(r,e){let t=0;if((r[e.offset]&Ds)===Ds){let n=r[e.offset]&dd,s="0x";e.offset++;for(let o=0;o<n;o++,e.offset++)s+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(s,16)}else t=r[e.offset],e.offset++;return t}function $r(r,e){Wr(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=at(r,e);if(n===null)break;t.push(n)}return t}function hd(r,e){let t=Wr(r,e),n=e.offset,s=e.offset+t,o=[];for(let i=n;i<s;i++)i===n&&r[i]===0||o.push(r[i]);return e.offset+=t,Uint8Array.from(o)}function pd(r,e){let t=Wr(r,e),n=e.offset+t,s=r[e.offset];e.offset++;let o=0,i=0;s<40?(o=0,i=s):s<80?(o=1,i=s-40):(o=2,i=s-80);let a=`${o}.${i}`,c=[];for(;e.offset<n;){let u=r[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 md(r,e){return e.offset++,null}function yd(r,e){let t=Wr(r,e),n=r[e.offset];e.offset++;let s=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return s}function gd(r,e){let t=Wr(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function bd(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new ee;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function Cs(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=bd(r.byteLength);return new ee(Uint8Array.from([e.byteLength|Ds]),e)}function De(r){let e=new ee,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new ee(Uint8Array.from([2]),Cs(e),e)}function Mn(r){let e=Uint8Array.from([0]),t=new ee(e,r);return new ee(Uint8Array.from([3]),Cs(t),t)}function wt(r,e=48){let t=new ee;for(let n of r)t.append(n);return new ee(Uint8Array.from([e]),Cs(t),t)}var wd=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),xd=Uint8Array.from([6,5,43,129,4,0,34]),Ed=Uint8Array.from([6,5,43,129,4,0,35]),Sd={ext:!0,kty:"EC",crv:"P-256"},vd={ext:!0,kty:"EC",crv:"P-384"},_d={ext:!0,kty:"EC",crv:"P-521"},Ls=32,Bs=48,Rs=66;function Os(r){let e=at(r);return Tc(e)}function Tc(r){let e=r[1][1][0],t=1,n,s;if(e.byteLength===Ls*2+1)return n=H(e.subarray(t,t+Ls),"base64url"),s=H(e.subarray(t+Ls),"base64url"),new pr({...Sd,key_ops:["verify"],x:n,y:s});if(e.byteLength===Bs*2+1)return n=H(e.subarray(t,t+Bs),"base64url"),s=H(e.subarray(t+Bs),"base64url"),new pr({...vd,key_ops:["verify"],x:n,y:s});if(e.byteLength===Rs*2+1)return n=H(e.subarray(t,t+Rs),"base64url"),s=H(e.subarray(t+Rs),"base64url"),new pr({..._d,key_ops:["verify"],x:n,y:s});throw new oe(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function Ic(r){return wt([De(Uint8Array.from([1])),wt([Ad(r.crv)],160),wt([Mn(new ee(Uint8Array.from([4]),F(r.x??"","base64url"),F(r.y??"","base64url")))],161)]).subarray()}function Ad(r){if(r==="P-256")return wd;if(r==="P-384")return xd;if(r==="P-521")return Ed;throw new oe(`Invalid curve ${r}`)}var pr=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 qe.digest(Je(this))}toCID(){return le.createV1(114,this.toMultihash())}toString(){return re.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ce(this.raw,e.raw)}async verify(e,t,n){return yc(this.jwk,t,e,n)}};function Ps(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}function xt(r,e=""){if(typeof r!="number"){let t=e&&`"${e}" `;throw new TypeError(`${t}expected number, got ${typeof r}`)}if(!Number.isSafeInteger(r)||r<0){let t=e&&`"${e}" `;throw new RangeError(`${t}expected integer >= 0, got ${r}`)}}function Pe(r,e,t=""){let n=Ps(r),s=r?.length,o=e!==void 0;if(!n||o&&s!==e){let i=t&&`"${t}" `,a=o?` of length ${e}`:"",c=n?`length=${s}`:`type=${typeof r}`,u=i+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(u):new TypeError(u)}return r}function Fn(r){if(typeof r!="function"||typeof r.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(xt(r.outputLen),xt(r.blockLen),r.outputLen<1)throw new Error('"outputLen" must be >= 1');if(r.blockLen<1)throw new Error('"blockLen" must be >= 1')}function mr(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function Kn(r,e){Pe(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length<t)throw new RangeError('"digestInto() output" expected to be of length >='+t)}function ut(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function qn(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function ze(r,e){return r<<32-e|r>>>e}var Cc=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Td=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function zn(r){if(Pe(r),Cc)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=Td[r[t]];return e}var ct={_0:48,_9:57,A:65,F:70,a:97,f:102};function Dc(r){if(r>=ct._0&&r<=ct._9)return r-ct._0;if(r>=ct.A&&r<=ct.F)return r-(ct.A-10);if(r>=ct.a&&r<=ct.f)return r-(ct.a-10)}function Gr(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);if(Cc)try{return Uint8Array.fromHex(r)}catch(s){throw s instanceof SyntaxError?new RangeError(s.message):s}let e=r.length,t=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let s=0,o=0;s<t;s++,o+=2){let i=Dc(r.charCodeAt(o)),a=Dc(r.charCodeAt(o+1));if(i===void 0||a===void 0){let c=r[o]+r[o+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+o)}n[s]=i*16+a}return n}function Ns(...r){let e=0;for(let n=0;n<r.length;n++){let s=r[n];Pe(s),e+=s.length}let t=new Uint8Array(e);for(let n=0,s=0;n<r.length;n++){let o=r[n];t.set(o,s),s+=o.length}return t}function Us(r,e={}){let t=(s,o)=>r(o).update(s).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.canXOF=n.canXOF,t.create=s=>r(s),Object.assign(t,e),Object.freeze(t)}function Lc(r=32){xt(r,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(r>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${r}`);return e.getRandomValues(new Uint8Array(r))}var ks=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function Bc(r,e,t){return r&e^~r&t}function Rc(r,e,t){return r&e^r&t^e&t}var jr=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,s){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(e),this.view=qn(this.buffer)}update(e){mr(this),Pe(e);let{view:t,buffer:n,blockLen:s}=this,o=e.length;for(let i=0;i<o;){let a=Math.min(s-this.pos,o-i);if(a===s){let c=qn(e);for(;s<=o-i;i+=s)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){mr(this),Kn(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:s,isLE:o}=this,{pos:i}=this;t[i++]=128,ut(this.buffer.subarray(i)),this.padOffset>s-i&&(this.process(n,0),i=0);for(let f=i;f<s;f++)t[f]=0;n.setBigUint64(s-8,BigInt(this.length*8),o),this.process(n,0);let a=qn(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)a.setUint32(4*f,l[f],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:s,finished:o,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=o,e.length=s,e.pos=a,s%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},lt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var ge=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Vn=BigInt(4294967295),Oc=BigInt(32);function Id(r,e=!1){return e?{h:Number(r&Vn),l:Number(r>>Oc&Vn)}:{h:Number(r>>Oc&Vn)|0,l:Number(r&Vn)|0}}function Pc(r,e=!1){let t=r.length,n=new Uint32Array(t),s=new Uint32Array(t);for(let o=0;o<t;o++){let{h:i,l:a}=Id(r[o],e);[n[o],s[o]]=[i,a]}return[n,s]}var Ms=(r,e,t)=>r>>>t,Fs=(r,e,t)=>r<<32-t|e>>>t,Ft=(r,e,t)=>r>>>t|e<<32-t,Kt=(r,e,t)=>r<<32-t|e>>>t,Yr=(r,e,t)=>r<<64-t|e>>>t-32,Zr=(r,e,t)=>r>>>t-32|e<<64-t;function et(r,e,t,n){let s=(e>>>0)+(n>>>0);return{h:r+t+(s/2**32|0)|0,l:s|0}}var Nc=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),Uc=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,kc=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),Mc=(r,e,t,n,s)=>e+t+n+s+(r/2**32|0)|0,Fc=(r,e,t,n,s)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(s>>>0),Kc=(r,e,t,n,s,o)=>e+t+n+s+o+(r/2**32|0)|0;var Cd=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),Ks=class extends jr{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:s,E:o,F:i,G:a,H:c}=this;return[e,t,n,s,o,i,a,c]}set(e,t,n,s,o,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=s|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let f=0;f<16;f++,t+=4)Et[f]=e.getUint32(t,!1);for(let f=16;f<64;f++){let m=Et[f-15],d=Et[f-2],x=ze(m,7)^ze(m,18)^m>>>3,S=ze(d,17)^ze(d,19)^d>>>10;Et[f]=S+Et[f-7]+x+Et[f-16]|0}let{A:n,B:s,C:o,D:i,E:a,F:c,G:u,H:l}=this;for(let f=0;f<64;f++){let m=ze(a,6)^ze(a,11)^ze(a,25),d=l+m+Bc(a,c,u)+Cd[f]+Et[f]|0,S=(ze(n,2)^ze(n,13)^ze(n,22))+Rc(n,s,o)|0;l=u,u=c,c=a,a=i+d|0,i=o,o=s,s=n,n=d+S|0}n=n+this.A|0,s=s+this.B|0,o=o+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,s,o,i,a,c,u,l)}roundClean(){ut(Et)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),ut(this.buffer)}},qs=class extends Ks{A=lt[0]|0;B=lt[1]|0;C=lt[2]|0;D=lt[3]|0;E=lt[4]|0;F=lt[5]|0;G=lt[6]|0;H=lt[7]|0;constructor(){super(32)}};var qc=Pc(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(r=>BigInt(r))),Ld=qc[0],Bd=qc[1],St=new Uint32Array(80),vt=new Uint32Array(80),zs=class extends jr{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:n,Bl:s,Ch:o,Cl:i,Dh:a,Dl:c,Eh:u,El:l,Fh:f,Fl:m,Gh:d,Gl:x,Hh:S,Hl:h}=this;return[e,t,n,s,o,i,a,c,u,l,f,m,d,x,S,h]}set(e,t,n,s,o,i,a,c,u,l,f,m,d,x,S,h){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=s|0,this.Ch=o|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=m|0,this.Gh=d|0,this.Gl=x|0,this.Hh=S|0,this.Hl=h|0}process(e,t){for(let A=0;A<16;A++,t+=4)St[A]=e.getUint32(t),vt[A]=e.getUint32(t+=4);for(let A=16;A<80;A++){let B=St[A-15]|0,C=vt[A-15]|0,U=Ft(B,C,1)^Ft(B,C,8)^Ms(B,C,7),R=Kt(B,C,1)^Kt(B,C,8)^Fs(B,C,7),T=St[A-2]|0,k=vt[A-2]|0,M=Ft(T,k,19)^Yr(T,k,61)^Ms(T,k,6),N=Kt(T,k,19)^Zr(T,k,61)^Fs(T,k,6),p=kc(R,N,vt[A-7],vt[A-16]),g=Mc(p,U,M,St[A-7],St[A-16]);St[A]=g|0,vt[A]=p|0}let{Ah:n,Al:s,Bh:o,Bl:i,Ch:a,Cl:c,Dh:u,Dl:l,Eh:f,El:m,Fh:d,Fl:x,Gh:S,Gl:h,Hh:y,Hl:E}=this;for(let A=0;A<80;A++){let B=Ft(f,m,14)^Ft(f,m,18)^Yr(f,m,41),C=Kt(f,m,14)^Kt(f,m,18)^Zr(f,m,41),U=f&d^~f&S,R=m&x^~m&h,T=Fc(E,C,R,Bd[A],vt[A]),k=Kc(T,y,B,U,Ld[A],St[A]),M=T|0,N=Ft(n,s,28)^Yr(n,s,34)^Yr(n,s,39),p=Kt(n,s,28)^Zr(n,s,34)^Zr(n,s,39),g=n&o^n&a^o&a,v=s&i^s&c^i&c;y=S|0,E=h|0,S=d|0,h=x|0,d=f|0,x=m|0,{h:f,l:m}=et(u|0,l|0,k|0,M|0),u=a|0,l=c|0,a=o|0,c=i|0,o=n|0,i=s|0;let w=Nc(M,p,v);n=Uc(w,k,N,g),s=w|0}({h:n,l:s}=et(this.Ah|0,this.Al|0,n|0,s|0)),{h:o,l:i}=et(this.Bh|0,this.Bl|0,o|0,i|0),{h:a,l:c}=et(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=et(this.Dh|0,this.Dl|0,u|0,l|0),{h:f,l:m}=et(this.Eh|0,this.El|0,f|0,m|0),{h:d,l:x}=et(this.Fh|0,this.Fl|0,d|0,x|0),{h:S,l:h}=et(this.Gh|0,this.Gl|0,S|0,h|0),{h:y,l:E}=et(this.Hh|0,this.Hl|0,y|0,E|0),this.set(n,s,o,i,a,c,u,l,f,m,d,x,S,h,y,E)}roundClean(){ut(St,vt)}destroy(){this.destroyed=!0,ut(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Vs=class extends zs{Ah=ge[0]|0;Al=ge[1]|0;Bh=ge[2]|0;Bl=ge[3]|0;Ch=ge[4]|0;Cl=ge[5]|0;Dh=ge[6]|0;Dl=ge[7]|0;Eh=ge[8]|0;El=ge[9]|0;Fh=ge[10]|0;Fl=ge[11]|0;Gh=ge[12]|0;Gl=ge[13]|0;Hh=ge[14]|0;Hl=ge[15]|0;constructor(){super(64)}};var yr=Us(()=>new qs,ks(1));var Hn=Us(()=>new Vs,ks(3));var $=(r,e,t)=>Pe(r,e,t),$s=xt,gr=zn,de=(...r)=>Ns(...r),br=r=>Gr(r),qt=Ps,Xr=r=>Lc(r),Wn=BigInt(0),Hs=BigInt(1);function Ve(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}" `;throw new TypeError(t+"expected boolean, got type="+typeof r)}return r}function Gn(r){if(typeof r=="bigint"){if(!$n(r))throw new RangeError("positive bigint expected, got "+r)}else $s(r);return r}function He(r,e=""){if(typeof r!="number"){let t=e&&`"${e}" `;throw new TypeError(t+"expected number, got type="+typeof r)}if(!Number.isSafeInteger(r)){let t=e&&`"${e}" `;throw new RangeError(t+"expected safe integer, got "+r)}}function Qr(r){let e=Gn(r).toString(16);return e.length&1?"0"+e:e}function zc(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);return r===""?Wn:BigInt("0x"+r)}function zt(r){return zc(zn(r))}function tt(r){return zc(zn(Jr(Pe(r)).reverse()))}function jn(r,e){if(xt(e),e===0)throw new RangeError("zero length");r=Gn(r);let t=r.toString(16);if(t.length>e*2)throw new RangeError("number too large");return Gr(t.padStart(e*2,"0"))}function Ws(r,e){return jn(r,e).reverse()}function Vc(r,e){if(r=$(r),e=$(e),r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}function Jr(r){return Uint8Array.from($(r))}function Yn(r){if(typeof r!="string")throw new TypeError("ascii string expected, got "+typeof r);return Uint8Array.from(r,(e,t)=>{let n=e.charCodeAt(0);if(e.length!==1||n>127)throw new RangeError(`string contains non-ASCII character "${r[t]}" with code ${n} at position ${t}`);return n})}var $n=r=>typeof r=="bigint"&&Wn<=r;function Rd(r,e,t){return $n(r)&&$n(e)&&$n(t)&&e<=r&&r<t}function wr(r,e,t,n){if(!Rd(e,t,n))throw new RangeError("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function xr(r){if(r<Wn)throw new Error("expected non-negative bigint, got "+r);let e;for(e=0;r>Wn;r>>=Hs,e+=1);return e}var en=r=>(Hs<<BigInt(r))-Hs;function Hc(r,e,t){if(xt(r,"hashLen"),xt(e,"qByteLen"),typeof t!="function")throw new TypeError("hmacFn must be a function");let n=h=>new Uint8Array(h),s=Uint8Array.of(),o=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(r),u=n(r),l=0,f=()=>{c.fill(1),u.fill(0),l=0},m=(...h)=>t(u,de(c,...h)),d=(h=s)=>{u=m(o,h),c=m(),h.length!==0&&(u=m(i,h),c=m())},x=()=>{if(l++>=a)throw new Error("drbg: tried max amount of iterations");let h=0,y=[];for(;h<e;){c=m();let E=c.slice();y.push(E),h+=c.length}return de(...y)};return(h,y)=>{f(),d(h);let E;for(;(E=y(x()))===void 0;)d();return f(),E}}function $e(r,e={},t={}){if(Object.prototype.toString.call(r)!=="[object Object]")throw new TypeError("expected valid options object");function n(o,i,a){if(!a&&i!=="function"&&!Object.hasOwn(r,o))throw new TypeError(`param "${o}" is invalid: expected own property`);let c=r[o];if(a&&c===void 0)return;let u=typeof c;if(u!==i||c===null)throw new TypeError(`param "${o}" is invalid: expected ${i}, got ${u}`)}let s=(o,i)=>Object.entries(o).forEach(([a,c])=>n(a,c,i));s(e,!1),s(t,!0)}var Gs=()=>{throw new Error("not implemented")};var be=BigInt(0),ie=BigInt(1),Vt=BigInt(2),jc=BigInt(3),Yc=BigInt(4),Zc=BigInt(5),Od=BigInt(7),Xc=BigInt(8),Pd=BigInt(9),Qc=BigInt(16);function ue(r,e){if(e<=be)throw new Error("mod: expected positive modulus, got "+e);let t=r%e;return t>=be?t:e+t}function te(r,e,t){if(e<be)throw new Error("pow2: expected non-negative exponent, got "+e);let n=r;for(;e-- >be;)n*=n,n%=t;return n}function $c(r,e){if(r===be)throw new Error("invert: expected non-zero number");if(e<=be)throw new Error("invert: expected positive modulus, got "+e);let t=ue(r,e),n=e,s=be,o=ie,i=ie,a=be;for(;t!==be;){let u=n/t,l=n-t*u,f=s-i*u,m=o-a*u;n=t,t=l,s=i,o=a,i=f,a=m}if(n!==ie)throw new Error("invert: does not exist");return ue(s,e)}function js(r,e,t){let n=r;if(!n.eql(n.sqr(e),t))throw new Error("Cannot find square root")}function Jc(r,e){let t=r,n=(t.ORDER+ie)/Yc,s=t.pow(e,n);return js(t,s,e),s}function Nd(r,e){let t=r,n=(t.ORDER-Zc)/Xc,s=t.mul(e,Vt),o=t.pow(s,n),i=t.mul(e,o),a=t.mul(t.mul(i,Vt),o),c=t.mul(i,t.sub(a,t.ONE));return js(t,c,e),c}function Ud(r){let e=Er(r),t=eu(r),n=t(e,e.neg(e.ONE)),s=t(e,n),o=t(e,e.neg(n)),i=(r+Od)/Qc;return((a,c)=>{let u=a,l=u.pow(c,i),f=u.mul(l,n),m=u.mul(l,s),d=u.mul(l,o),x=u.eql(u.sqr(f),c),S=u.eql(u.sqr(m),c);l=u.cmov(l,f,x),f=u.cmov(d,m,S);let h=u.eql(u.sqr(f),c),y=u.cmov(l,f,h);return js(u,y,c),y})}function eu(r){if(r<jc)throw new Error("sqrt is not defined for small field");let e=r-ie,t=0;for(;e%Vt===be;)e/=Vt,t++;let n=Vt,s=Er(r);for(;Wc(s,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return Jc;let o=s.pow(n,e),i=(e+ie)/Vt;return function(c,u){let l=c;if(l.is0(u))return u;if(Wc(l,u)!==1)throw new Error("Cannot find square root");let f=t,m=l.mul(l.ONE,o),d=l.pow(u,e),x=l.pow(u,i);for(;!l.eql(d,l.ONE);){if(l.is0(d))return l.ZERO;let S=1,h=l.sqr(d);for(;!l.eql(h,l.ONE);)if(S++,h=l.sqr(h),S===f)throw new Error("Cannot find square root");let y=ie<<BigInt(f-S-1),E=l.pow(m,y);f=S,m=l.sqr(E),d=l.mul(d,m),x=l.mul(x,E)}return x}}function kd(r){return r%Yc===jc?Jc:r%Xc===Zc?Nd:r%Qc===Pd?Ud(r):eu(r)}var ft=(r,e)=>(ue(r,e)&ie)===ie,Md=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ys(r){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=Md.reduce((n,s)=>(n[s]="function",n),e);if($e(r,t),He(r.BYTES,"BYTES"),He(r.BITS,"BITS"),r.BYTES<1||r.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(r.ORDER<=ie)throw new Error("invalid field: expected ORDER > 1, got "+r.ORDER);return r}function Fd(r,e,t){let n=r;if(t<be)throw new Error("invalid exponent, negatives unsupported");if(t===be)return n.ONE;if(t===ie)return e;let s=n.ONE,o=e;for(;t>be;)t&ie&&(s=n.mul(s,o)),o=n.sqr(o),t>>=ie;return s}function tn(r,e,t=!1){let n=r,s=new Array(e.length).fill(t?n.ZERO:void 0),o=e.reduce((a,c,u)=>n.is0(c)?a:(s[u]=a,n.mul(a,c)),n.ONE),i=n.inv(o);return e.reduceRight((a,c,u)=>n.is0(c)?a:(s[u]=n.mul(a,s[u]),n.mul(a,c)),i),s}function Wc(r,e){let t=r,n=(t.ORDER-ie)/Vt,s=t.pow(e,n),o=t.eql(s,t.ONE),i=t.eql(s,t.ZERO),a=t.eql(s,t.neg(t.ONE));if(!o&&!i&&!a)throw new Error("invalid Legendre symbol result");return o?1:i?0:-1}function Kd(r,e){if(e!==void 0&&$s(e),r<=be)throw new Error("invalid n length: expected positive n, got "+r);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let t=xr(r);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected bit length (${t}) >= n.length (${e})`);let n=e!==void 0?e:t,s=Math.ceil(n/8);return{nBitLength:n,nByteLength:s}}var Gc=new WeakMap,Zn=class{ORDER;BITS;BYTES;isLE;ZERO=be;ONE=ie;_lengths;_mod;constructor(e,t={}){if(e<=ie)throw new Error("invalid field: expected ORDER > 1, got "+e);let n;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(n=t.BITS),typeof t.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0}),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=Object.freeze(t.allowedLengths.slice())),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:s,nByteLength:o}=Kd(e,n);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=s,this.BYTES=o,Object.freeze(this)}create(e){return ue(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return be<=e&&e<this.ORDER}is0(e){return e===be}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&ie)===ie}neg(e){return ue(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return ue(e*e,this.ORDER)}add(e,t){return ue(e+t,this.ORDER)}sub(e,t){return ue(e-t,this.ORDER)}mul(e,t){return ue(e*t,this.ORDER)}pow(e,t){return Fd(this,e,t)}div(e,t){return ue(e*$c(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return $c(e,this.ORDER)}sqrt(e){let t=Gc.get(this);return t||Gc.set(this,t=kd(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?Ws(e,this.BYTES):jn(e,this.BYTES)}fromBytes(e,t=!1){$(e);let{_lengths:n,BYTES:s,isLE:o,ORDER:i,_mod:a}=this;if(n){if(e.length<1||!n.includes(e.length)||e.length>s)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let u=new Uint8Array(s);u.set(e,o?0:u.length-e.length),e=u}if(e.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+e.length);let c=o?tt(e):zt(e);if(a&&(c=ue(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return tn(this,e)}cmov(e,t,n){return Ve(n,"condition"),n?t:e}};Object.freeze(Zn.prototype);function Er(r,e={}){return new Zn(r,e)}function tu(r){if(typeof r!="bigint")throw new Error("field order must be bigint");if(r<=ie)throw new Error("field order must be greater than 1");let e=xr(r-ie);return Math.ceil(e/8)}function Zs(r){let e=tu(r);return e+Math.ceil(e/2)}function Xs(r,e,t=!1){$(r);let n=r.length,s=tu(e),o=Math.max(Zs(e),16);if(n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);let i=t?tt(r):zt(r),a=ue(i,e-ie)+ie;return t?Ws(a,s):jn(a,s)}var Sr=BigInt(0),Ht=BigInt(1);function rn(r,e){let t=e.negate();return r?t:e}function $t(r,e){let t=tn(r.Fp,e.map(n=>n.Z));return e.map((n,s)=>r.fromAffine(n.toAffine(t[s])))}function su(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function Qs(r,e){su(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1),s=2**r,o=en(r),i=BigInt(r);return{windows:t,windowSize:n,mask:o,maxNumber:s,shiftBy:i}}function ru(r,e,t){let{windowSize:n,mask:s,maxNumber:o,shiftBy:i}=t,a=Number(r&s),c=r>>i;a>n&&(a-=o,c+=Ht);let u=e*n,l=u+Math.abs(a)-1,f=a===0,m=a<0,d=e%2!==0;return{nextN:c,offset:l,isZero:f,isNeg:m,isNegF:d,offsetF:u}}var Js=new WeakMap,iu=new WeakMap;function ei(r){return iu.get(r)||1}function nu(r){if(r!==Sr)throw new Error("invalid wNAF")}var vr=class{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let s=e;for(;t>Sr;)t&Ht&&(n=n.add(s)),s=s.double(),t>>=Ht;return n}precomputeWindow(e,t){let{windows:n,windowSize:s}=Qs(t,this.bits),o=[],i=e,a=i;for(let c=0;c<n;c++){a=i,o.push(a);for(let u=1;u<s;u++)a=a.add(i),o.push(a);i=a.double()}return o}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let s=this.ZERO,o=this.BASE,i=Qs(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:u,isZero:l,isNeg:f,isNegF:m,offsetF:d}=ru(n,a,i);n=c,l?o=o.add(rn(m,t[d])):s=s.add(rn(f,t[u]))}return nu(n),{p:s,f:o}}wNAFUnsafe(e,t,n,s=this.ZERO){let o=Qs(e,this.bits);for(let i=0;i<o.windows&&n!==Sr;i++){let{nextN:a,offset:c,isZero:u,isNeg:l}=ru(n,i,o);if(n=a,!u){let f=t[c];s=s.add(l?f.negate():f)}}return nu(n),s}getPrecomputes(e,t,n){let s=Js.get(t);return s||(s=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(s=n(s)),Js.set(t,s))),s}cached(e,t,n){let s=ei(e);return this.wNAF(s,this.getPrecomputes(s,e,n),t)}unsafe(e,t,n,s){let o=ei(e);return o===1?this._unsafeLadder(e,t,s):this.wNAFUnsafe(o,this.getPrecomputes(o,e,n),t,s)}createCache(e,t){su(t,this.bits),iu.set(e,t),Js.delete(e)}hasCache(e){return ei(e)!==1}};function au(r,e,t,n){let s=e,o=r.ZERO,i=r.ZERO;for(;t>Sr||n>Sr;)t&Ht&&(o=o.add(s)),n&Ht&&(i=i.add(s)),s=s.double(),t>>=Ht,n>>=Ht;return{p1:o,p2:i}}function ou(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Ys(e),e}else return Er(r,{isLE:t})}function Xn(r,e,t={},n){if(n===void 0&&(n=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let u=e[c];if(!(typeof u=="bigint"&&u>Sr))throw new Error(`CURVE.${c} must be positive bigint`)}let s=ou(e.p,t.Fp,n),o=ou(e.n,t.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!s.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:s,Fn:o}}function Qn(r,e){return function(n){let s=r(n);return{secretKey:s,publicKey:e(s)}}}var _t=BigInt(0),me=BigInt(1),ti=BigInt(2),qd=BigInt(8);function zd(r,e,t,n){let s=r.sqr(t),o=r.sqr(n),i=r.add(r.mul(e.a,s),o),a=r.add(r.ONE,r.mul(e.d,r.mul(s,o)));return r.eql(i,a)}function cu(r,e={}){let t=e,n=Xn("edwards",r,t,t.FpFnLE),{Fp:s,Fn:o}=n,i=n.CURVE,{h:a}=i;$e(t,{},{uvRatio:"function"});let c=ti<<BigInt(o.BYTES*8)-me,u=S=>s.create(S),l=t.uvRatio===void 0?(S,h)=>{try{return{isValid:!0,value:s.sqrt(s.div(S,h))}}catch{return{isValid:!1,value:_t}}}:t.uvRatio;if(!zd(s,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function f(S,h,y=!1){let E=y?me:_t;return wr("coordinate "+S,h,E,c),h}function m(S){if(!(S instanceof d))throw new Error("EdwardsPoint expected")}class d{static BASE=new d(i.Gx,i.Gy,me,u(i.Gx*i.Gy));static ZERO=new d(_t,me,me,_t);static Fp=s;static Fn=o;X;Y;Z;T;constructor(h,y,E,A){this.X=f("x",h),this.Y=f("y",y),this.Z=f("z",E,!0),this.T=f("t",A),Object.freeze(this)}static CURVE(){return i}static fromAffine(h){if(h instanceof d)throw new Error("extended point not allowed");let{x:y,y:E}=h||{};return f("x",y),f("y",E),new d(y,E,me,u(y*E))}static fromBytes(h,y=!1){let E=s.BYTES,{a:A,d:B}=i;h=Jr($(h,E,"point")),Ve(y,"zip215");let C=Jr(h),U=h[E-1];C[E-1]=U&-129;let R=tt(C),T=y?c:s.ORDER;wr("point.y",R,_t,T);let k=u(R*R),M=u(k-me),N=u(B*k-A),{isValid:p,value:g}=l(M,N);if(!p)throw new Error("bad point: invalid y coordinate");let v=(g&me)===me,w=(U&128)!==0;if(!y&&g===_t&&w)throw new Error("bad point: x=0 and x_0=1");return w!==v&&(g=u(-g)),d.fromAffine({x:g,y:R})}static fromHex(h,y=!1){return d.fromBytes(br(h),y)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(h=8,y=!0){return x.createCache(this,h),y||this.multiply(ti),this}assertValidity(){let h=this,{a:y,d:E}=i;if(h.is0())throw new Error("bad point: ZERO");let{X:A,Y:B,Z:C,T:U}=h,R=u(A*A),T=u(B*B),k=u(C*C),M=u(k*k),N=u(R*y),p=u(k*u(N+T)),g=u(M+u(E*u(R*T)));if(p!==g)throw new Error("bad point: equation left != right (1)");let v=u(A*B),w=u(C*U);if(v!==w)throw new Error("bad point: equation left != right (2)")}equals(h){m(h);let{X:y,Y:E,Z:A}=this,{X:B,Y:C,Z:U}=h,R=u(y*U),T=u(B*A),k=u(E*U),M=u(C*A);return R===T&&k===M}is0(){return this.equals(d.ZERO)}negate(){return new d(u(-this.X),this.Y,this.Z,u(-this.T))}double(){let{a:h}=i,{X:y,Y:E,Z:A}=this,B=u(y*y),C=u(E*E),U=u(ti*u(A*A)),R=u(h*B),T=y+E,k=u(u(T*T)-B-C),M=R+C,N=M-U,p=R-C,g=u(k*N),v=u(M*p),w=u(k*p),b=u(N*M);return new d(g,v,b,w)}add(h){m(h);let{a:y,d:E}=i,{X:A,Y:B,Z:C,T:U}=this,{X:R,Y:T,Z:k,T:M}=h,N=u(A*R),p=u(B*T),g=u(U*E*M),v=u(C*k),w=u((A+B)*(R+T)-N-p),b=v-g,_=v+g,D=u(p-y*N),I=u(w*b),L=u(_*D),P=u(w*D),V=u(b*_);return new d(I,L,V,P)}subtract(h){return m(h),this.add(h.negate())}multiply(h){if(!o.isValidNot0(h))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:y,f:E}=x.cached(this,h,A=>$t(d,A));return $t(d,[y,E])[0]}multiplyUnsafe(h){if(!o.isValid(h))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return h===_t?d.ZERO:this.is0()||h===me?this:x.unsafe(this,h,y=>$t(d,y))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return x.unsafe(this,i.n).is0()}toAffine(h){let y=this,E=h,{X:A,Y:B,Z:C}=y,U=y.is0();E==null&&(E=U?qd:s.inv(C));let R=u(A*E),T=u(B*E),k=s.mul(C,E);if(U)return{x:_t,y:me};if(k!==me)throw new Error("invZ was invalid");return{x:R,y:T}}clearCofactor(){return a===me?this:this.multiplyUnsafe(a)}toBytes(){let{x:h,y}=this.toAffine(),E=s.toBytes(y);return E[E.length-1]|=h&me?128:0,E}toHex(){return gr(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let x=new vr(d,o.BITS);return o.BITS>=8&&d.BASE.precompute(8),Object.freeze(d.prototype),Object.freeze(d),d}var Jn=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e}static fromBytes(e){Gs()}static fromHex(e){Gs()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return gr(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.ep.precompute(e,t),this}};function uu(r,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');let n=e,s=t;$e(s,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:o}=s,{BASE:i,Fp:a,Fn:c}=r,u=n.outputLen,l=2*a.BYTES;if(u!==void 0&&(He(u,"hash.outputLen"),u!==l))throw new Error(`hash.outputLen must be ${l}, got ${u}`);let f=s.randomBytes===void 0?Xr:s.randomBytes,m=s.adjustScalarBytes===void 0?p=>p:s.adjustScalarBytes,d=s.domain===void 0?(p,g,v)=>{if(Ve(v,"phflag"),g.length||v)throw new Error("Contexts/pre-hash are not supported");return p}:s.domain;function x(p){return c.create(tt(p))}function S(p){let g=R.secretKey;$(p,R.secretKey,"secretKey");let v=$(n(p),2*g,"hashedSecretKey"),w=m(v.slice(0,g)),b=v.slice(g,2*g),_=x(w);return{head:w,prefix:b,scalar:_}}function h(p){let{head:g,prefix:v,scalar:w}=S(p),b=i.multiply(w),_=b.toBytes();return{head:g,prefix:v,scalar:w,point:b,pointBytes:_}}function y(p){return h(p).pointBytes}function E(p=Uint8Array.of(),...g){let v=de(...g);return x(n(d(v,$(p,void 0,"context"),!!o)))}function A(p,g,v={}){p=$(p,void 0,"message"),o&&(p=o(p));let{prefix:w,scalar:b,pointBytes:_}=h(g),D=E(v.context,w,p),I=i.multiply(D).toBytes(),L=E(v.context,I,_,p),P=c.create(D+L*b);if(!c.isValid(P))throw new Error("sign failed: invalid s");let V=de(I,c.toBytes(P));return $(V,R.signature,"result")}let B={zip215:s.zip215};function C(p,g,v,w=B){let{context:b}=w,_=w.zip215===void 0?!!B.zip215:w.zip215,D=R.signature;p=$(p,D,"signature"),g=$(g,void 0,"message"),v=$(v,R.publicKey,"publicKey"),_!==void 0&&Ve(_,"zip215"),o&&(g=o(g));let I=D/2,L=p.subarray(0,I),P=tt(p.subarray(I,D)),V,j,q;try{V=r.fromBytes(v,_),j=r.fromBytes(L,_),q=i.multiplyUnsafe(P)}catch{return!1}if(!_&&V.isSmallOrder())return!1;let fe=E(b,L,v,g);return j.add(V.multiplyUnsafe(fe)).subtract(q).clearCofactor().is0()}let U=a.BYTES,R={secretKey:U,publicKey:U,signature:2*U,seed:U};function T(p){return p=p===void 0?f(R.seed):p,$(p,R.seed,"seed")}function k(p){return qt(p)&&p.length===R.secretKey}function M(p,g){try{return!!r.fromBytes(p,g===void 0?B.zip215:g)}catch{return!1}}let N={getExtendedPublicKey:h,randomSecretKey:T,isValidSecretKey:k,isValidPublicKey:M,toMontgomery(p){let{y:g}=r.fromBytes(p),v=R.publicKey,w=v===32;if(!w&&v!==57)throw new Error("only defined for 25519 and 448");let b=w?a.div(me+g,me-g):a.div(g-me,g+me);return a.toBytes(b)},toMontgomerySecret(p){let g=R.secretKey;$(p,g);let v=n(p.subarray(0,g));return m(v).subarray(0,g)}};return Object.freeze(R),Object.freeze(N),Object.freeze({keygen:Qn(T,y),getPublicKey:y,sign:A,verify:C,utils:N,Point:r,lengths:R})}function nn(r,e){if(He(r),He(e),e<0||e>4)throw new Error("invalid I2OSP length: "+e);if(r<0||r>2**(8*e)-1)throw new Error("invalid I2OSP input: "+r);let t=Array.from({length:e}).fill(0);for(let n=e-1;n>=0;n--)t[n]=r&255,r>>>=8;return new Uint8Array(t)}function Vd(r,e){let t=new Uint8Array(r.length);for(let n=0;n<r.length;n++)t[n]=r[n]^e[n];return t}function Hd(r){if(!qt(r)&&typeof r!="string")throw new Error("DST must be Uint8Array or ascii string");let e=typeof r=="string"?Yn(r):r;if(e.length===0)throw new Error("DST must be non-empty");return e}function ri(r,e,t,n){$(r),He(t),e=Hd(e),e.length>255&&(e=n(de(Yn("H2C-OVERSIZE-DST-"),e)));let{outputLen:s,blockLen:o}=n,i=Math.ceil(t/s);if(t>65535||i>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=de(e,nn(e.length,1)),c=new Uint8Array(o),u=nn(t,2),l=new Array(i),f=n(de(c,r,u,nn(0,1),a));l[0]=n(de(f,nn(1,1),a));for(let d=1;d<i;d++){let x=[Vd(f,l[d-1]),nn(d+1,1),a];l[d]=n(de(...x))}return de(...l).slice(0,t)}var lu="HashToScalar-";var $d=BigInt(0),dt=BigInt(1),fu=BigInt(2);var Wd=BigInt(5),Gd=BigInt(8),_r=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),ii={p:_r,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Gd,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function jd(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),s=BigInt(80),o=_r,a=r*r%o*r%o,c=te(a,fu,o)*a%o,u=te(c,dt,o)*r%o,l=te(u,Wd,o)*u%o,f=te(l,e,o)*l%o,m=te(f,t,o)*f%o,d=te(m,n,o)*m%o,x=te(d,s,o)*d%o,S=te(x,s,o)*d%o,h=te(S,e,o)*l%o;return{pow_p_5_8:te(h,fu,o)*r%o,b2:a}}function Yd(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var ni=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function ai(r,e){let t=_r,n=ue(e*e*e,t),s=ue(n*n*e,t),o=jd(r*s).pow_p_5_8,i=ue(r*n*o,t),a=ue(e*i*i,t),c=i,u=ue(i*ni,t),l=a===r,f=a===ue(-r,t),m=a===ue(-r*ni,t);return l&&(i=c),(f||m)&&(i=u),ft(i,t)&&(i=ue(-i,t)),{isValid:l||f,value:i}}var Tt=cu(ii,{uvRatio:ai}),At=Tt.Fp,pu=Tt.Fn;function Zd(r){return uu(Tt,Hn,Object.assign({adjustScalarBytes:Yd,zip215:!0},r))}var mu=Zd({});var oi=ni,Xd=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Qd=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),Jd=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),eh=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),du=r=>ai(dt,r),th=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),si=r=>At.create(tt(r)&th);function hu(r){let{d:e}=ii,t=_r,n=y=>At.create(y),s=n(oi*r*r),o=n((s+dt)*Jd),i=BigInt(-1),a=n((i-e*s)*n(s+e)),{isValid:c,value:u}=ai(o,a),l=n(u*r);ft(l,t)||(l=n(-l)),c||(u=l),c||(i=s);let f=n(i*(s-dt)*eh-a),m=u*u,d=n((u+u)*a),x=n(f*Xd),S=n(dt-m),h=n(dt+m);return new Tt(n(d*h),n(S*x),n(x*h),n(d*S))}var It=class r extends Jn{static BASE=new r(Tt.BASE);static ZERO=new r(Tt.ZERO);static Fp=At;static Fn=pu;constructor(e){super(e)}static fromAffine(e){return new r(Tt.fromAffine(e))}assertSame(e){if(!(e instanceof r))throw new Error("RistrettoPoint expected")}init(e){return new r(e)}static fromBytes(e){Pe(e,32);let{a:t,d:n}=ii,s=_r,o=B=>At.create(B),i=si(e);if(!Vc(At.toBytes(i),e)||ft(i,s))throw new Error("invalid ristretto255 encoding 1");let a=o(i*i),c=o(dt+t*a),u=o(dt-t*a),l=o(c*c),f=o(u*u),m=o(t*n*l-f),{isValid:d,value:x}=du(o(m*f)),S=o(x*u),h=o(x*S*m),y=o((i+i)*S);ft(y,s)&&(y=o(-y));let E=o(c*h),A=o(y*E);if(!d||ft(A,s)||E===$d)throw new Error("invalid ristretto255 encoding 2");return new r(new Tt(y,E,dt,A))}static fromHex(e){return r.fromBytes(Gr(e))}toBytes(){let{X:e,Y:t,Z:n,T:s}=this.ep,o=_r,i=h=>At.create(h),a=i(i(n+t)*i(n-t)),c=i(e*t),u=i(c*c),{value:l}=du(i(a*u)),f=i(l*a),m=i(l*c),d=i(f*m*s),x;if(ft(s*d,o)){let h=i(t*oi),y=i(e*oi);e=h,t=y,x=i(f*Qd)}else x=m;ft(e*d,o)&&(t=i(-t));let S=i((n-t)*x);return ft(S,o)&&(S=i(-S)),At.toBytes(S)}equals(e){this.assertSame(e);let{X:t,Y:n}=this.ep,{X:s,Y:o}=e.ep,i=u=>At.create(u),a=i(t*o)===i(n*s),c=i(n*o)===i(t*s);return a||c}is0(){return this.equals(r.ZERO)}};Object.freeze(It.BASE);Object.freeze(It.ZERO);Object.freeze(It.prototype);Object.freeze(It);var rh=Object.freeze({Point:It,hashToCurve(r,e){let t=e?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":e.DST,n=ri(r,t,64,Hn);return rh.deriveToCurve(n)},hashToScalar(r,e={DST:lu}){let t=ri(r,e.DST,64,Hn);return pu.create(tt(t))},deriveToCurve(r){Pe(r,64);let e=si(r.subarray(0,32)),t=hu(e),n=si(r.subarray(32,64)),s=hu(n);return new It(t.add(s))}});var on=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},eo=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var Fe={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new eo("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 to=32;var ci,nh=(async()=>{try{return await Fe.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function oh(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await Fe.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await Fe.get().subtle.verify({name:"Ed25519"},n,_e(e),_e(t instanceof Uint8Array?t:t.subarray()))}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function sh(r,e,t){return mu.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function yu(r,e,t){return ci==null&&(ci=await nh),ci?oh(r,e,t):sh(r,e,t)}function ro(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var no=class{type="Ed25519";raw;constructor(e){this.raw=ui(e,to)}toMultihash(){return qe.digest(Je(this))}toCID(){return le.createV1(114,this.toMultihash())}toString(){return re.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ce(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let s=yu(this.raw,t,e);return ro(s)?s.then(o=>(n?.signal?.throwIfAborted(),o)):s}};function li(r){return r=ui(r,to),new no(r)}function ui(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new oe(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var ah=Math.pow(2,7),ch=Math.pow(2,14),uh=Math.pow(2,21),fi=Math.pow(2,28),di=Math.pow(2,35),hi=Math.pow(2,42),pi=Math.pow(2,49),Y=128,Ee=127;function Ce(r){if(r<ah)return 1;if(r<ch)return 2;if(r<uh)return 3;if(r<fi)return 4;if(r<di)return 5;if(r<hi)return 6;if(r<pi)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Ar(r,e,t=0){switch(Ce(r)){case 8:e[t++]=r&255|Y,r/=128;case 7:e[t++]=r&255|Y,r/=128;case 6:e[t++]=r&255|Y,r/=128;case 5:e[t++]=r&255|Y,r/=128;case 4:e[t++]=r&255|Y,r>>>=7;case 3:e[t++]=r&255|Y,r>>>=7;case 2:e[t++]=r&255|Y,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function lh(r,e,t=0){switch(Ce(r)){case 8:e.set(t++,r&255|Y),r/=128;case 7:e.set(t++,r&255|Y),r/=128;case 6:e.set(t++,r&255|Y),r/=128;case 5:e.set(t++,r&255|Y),r/=128;case 4:e.set(t++,r&255|Y),r>>>=7;case 3:e.set(t++,r&255|Y),r>>>=7;case 2:e.set(t++,r&255|Y),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function mi(r,e){let t=r[e],n=0;if(n+=t&Ee,t<Y||(t=r[e+1],n+=(t&Ee)<<7,t<Y)||(t=r[e+2],n+=(t&Ee)<<14,t<Y)||(t=r[e+3],n+=(t&Ee)<<21,t<Y)||(t=r[e+4],n+=(t&Ee)*fi,t<Y)||(t=r[e+5],n+=(t&Ee)*di,t<Y)||(t=r[e+6],n+=(t&Ee)*hi,t<Y)||(t=r[e+7],n+=(t&Ee)*pi,t<Y))return n;throw new RangeError("Could not decode varint")}function fh(r,e){let t=r.get(e),n=0;if(n+=t&Ee,t<Y||(t=r.get(e+1),n+=(t&Ee)<<7,t<Y)||(t=r.get(e+2),n+=(t&Ee)<<14,t<Y)||(t=r.get(e+3),n+=(t&Ee)<<21,t<Y)||(t=r.get(e+4),n+=(t&Ee)*fi,t<Y)||(t=r.get(e+5),n+=(t&Ee)*di,t<Y)||(t=r.get(e+6),n+=(t&Ee)*hi,t<Y)||(t=r.get(e+7),n+=(t&Ee)*pi,t<Y))return n;throw new RangeError("Could not decode varint")}function Tr(r,e,t=0){return e==null&&(e=xe(Ce(r))),e instanceof Uint8Array?Ar(r,e,t):lh(r,e,t)}function sn(r,e=0){return r instanceof Uint8Array?mi(r,e):fh(r,e)}var gi=new Float32Array([-0]),Dt=new Uint8Array(gi.buffer);function bu(r,e,t){gi[0]=r,e[t]=Dt[0],e[t+1]=Dt[1],e[t+2]=Dt[2],e[t+3]=Dt[3]}function wu(r,e){return Dt[0]=r[e],Dt[1]=r[e+1],Dt[2]=r[e+2],Dt[3]=r[e+3],gi[0]}var bi=new Float64Array([-0]),Se=new Uint8Array(bi.buffer);function xu(r,e,t){bi[0]=r,e[t]=Se[0],e[t+1]=Se[1],e[t+2]=Se[2],e[t+3]=Se[3],e[t+4]=Se[4],e[t+5]=Se[5],e[t+6]=Se[6],e[t+7]=Se[7]}function Eu(r,e){return Se[0]=r[e],Se[1]=r[e+1],Se[2]=r[e+2],Se[3]=r[e+3],Se[4]=r[e+4],Se[5]=r[e+5],Se[6]=r[e+6],Se[7]=r[e+7],bi[0]}var dh=BigInt(Number.MAX_SAFE_INTEGER),hh=BigInt(Number.MIN_SAFE_INTEGER),Ne=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+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 t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(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,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return Wt;if(e<dh&&e>hh)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,s=e-(n<<32n);return t&&(n=~n|0n,s=~s|0n,++s>Su&&(s=0n,++n>Su&&(n=0n))),new r(Number(s),Number(n))}static fromNumber(e){if(e===0)return Wt;let t=e<0;t&&(e=-e);let n=e>>>0,s=(e-n)/4294967296>>>0;return t&&(s=~s>>>0,n=~n>>>0,++n>4294967295&&(n=0,++s>4294967295&&(s=0))),new r(n,s)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):Wt}},Wt=new Ne(0,0);Wt.toBigInt=function(){return 0n};Wt.zzEncode=Wt.zzDecode=function(){return this};Wt.length=function(){return 1};var Su=4294967296n;function vu(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function _u(r,e,t){if(t-e<1)return"";let s,o=[],i=0,a;for(;e<t;)a=r[e++],a<128?o[i++]=a:a>191&&a<224?o[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,o[i++]=55296+(a>>10),o[i++]=56320+(a&1023)):o[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((s??(s=[])).push(String.fromCharCode.apply(String,o)),i=0);return s!=null?(i>0&&s.push(String.fromCharCode.apply(String,o.slice(0,i))),s.join("")):String.fromCharCode.apply(String,o.slice(0,i))}function wi(r,e,t){let n=t,s,o;for(let i=0;i<r.length;++i)s=r.charCodeAt(i),s<128?e[t++]=s:s<2048?(e[t++]=s>>6|192,e[t++]=s&63|128):(s&64512)===55296&&((o=r.charCodeAt(i+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++i,e[t++]=s>>18|240,e[t++]=s>>12&63|128,e[t++]=s>>6&63|128,e[t++]=s&63|128):(e[t++]=s>>12|224,e[t++]=s>>6&63|128,e[t++]=s&63|128);return t-n}function We(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function oo(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var xi=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,We(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 We(this,4);return oo(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw We(this,4);return oo(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw We(this,4);let e=wu(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw We(this,4);let e=Eu(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw We(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return _u(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw We(this,e);this.pos+=e}else do if(this.pos>=this.len)throw We(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),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*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;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw We(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw We(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw We(this,8);let e=oo(this.buf,this.pos+=4),t=oo(this.buf,this.pos+=4);return new Ne(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=mi(this.buf,this.pos);return this.pos+=Ce(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 an(r){return new xi(r instanceof Uint8Array?r:r.subarray())}function Le(r,e,t){let n=an(r);return e.decode(n,void 0,t)}function Ei(r){let e=r??8192,t=e>>>1,n,s=e;return function(i){if(i<1||i>t)return xe(i);s+i>e&&(n=xe(e),s=0);let a=n.subarray(s,s+=i);return(s&7)!==0&&(s=(s|7)+1),a}}var Gt=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function Si(){}var _i=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},ph=Ei();function mh(r){return globalThis.Buffer!=null?xe(r):ph(r)}var un=class{len;head;tail;states;constructor(){this.len=0,this.head=new Gt(Si,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new Gt(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Ai((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(so,10,Ne.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Ne.fromBigInt(e);return this._push(so,t.length(),t)}uint64Number(e){return this._push(Ar,Ce(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 t=Ne.fromBigInt(e).zzEncode();return this._push(so,t.length(),t)}sint64Number(e){let t=Ne.fromNumber(e).zzEncode();return this._push(so,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(vi,1,e?1:0)}fixed32(e){return this._push(cn,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Ne.fromBigInt(e);return this._push(cn,4,t.lo)._push(cn,4,t.hi)}fixed64Number(e){let t=Ne.fromNumber(e);return this._push(cn,4,t.lo)._push(cn,4,t.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(bu,4,e)}double(e){return this._push(xu,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(vi,1,0):this.uint32(t)._push(gh,t,e)}string(e){let t=vu(e);return t!==0?this.uint32(t)._push(wi,t,e):this._push(vi,1,0)}fork(){return this.states=new _i(this),this.head=this.tail=new Gt(Si,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 Gt(Si,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=mh(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function vi(r,e,t){e[t]=r&255}function yh(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var Ai=class extends Gt{next;constructor(e,t){super(yh,e,t),this.next=void 0}};function so(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function cn(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function gh(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(un.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(bh,e,r),this},un.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(wh,e,r),this});function bh(r,e,t){e.set(r,t)}function wh(r,e,t){r.length<40?wi(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(F(r),t)}function Ti(){return new un}function Be(r,e){let t=Ti();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}function*Re(r,e,t){let n=an(r);yield*e.stream(n,void 0,"$",t)}var io={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function ao(r,e,t,n,s){return{name:r,type:e,encode:t,decode:n,stream:s}}function jt(r){function e(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let t=function(i,a){let c=e(i);a.int32(c)},n=function(i){let a=i.int32();return e(a)},s=function*(i){let a=i.int32();yield e(a)};return ao("enum",io.VARINT,t,n,s)}function Oe(r,e,t){return ao("message",io.LENGTH_DELIMITED,r,e,t)}var Yt=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var ne;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(ne||(ne={}));var Ii;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(Ii||(Ii={}));(function(r){r.codec=()=>jt(Ii)})(ne||(ne={}));var rt;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.Type!=null&&(i.uint32(8),ne.codec().encode(o.Type,i)),o.Data!=null&&(i.uint32(18),i.bytes(o.Data)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{c.Type=ne.codec().decode(o);break}case 2:{c.Data=o.bytes();break}default:{o.skipType(l&7);break}}}return c},function*(o,i,a,c={}){let u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{yield{field:`${a}.Type`,value:ne.codec().decode(o)};break}case 2:{yield{field:`${a}.Data`,value:o.bytes()};break}default:{o.skipType(l&7);break}}}})),e);function t(o){return Be(o,r.codec())}r.encode=t;function n(o,i){return Le(o,r.codec(),i)}r.decode=n;function s(o,i){return Re(o,r.codec(),i)}r.stream=s})(rt||(rt={}));var Di;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.Type!=null&&(i.uint32(8),ne.codec().encode(o.Type,i)),o.Data!=null&&(i.uint32(18),i.bytes(o.Data)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{c.Type=ne.codec().decode(o);break}case 2:{c.Data=o.bytes();break}default:{o.skipType(l&7);break}}}return c},function*(o,i,a,c={}){let u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{yield{field:`${a}.Type`,value:ne.codec().decode(o)};break}case 2:{yield{field:`${a}.Data`,value:o.bytes()};break}default:{o.skipType(l&7);break}}}})),e);function t(o){return Be(o,r.codec())}r.encode=t;function n(o,i){return Le(o,r.codec(),i)}r.decode=n;function s(o,i){return Re(o,r.codec(),i)}r.stream=s})(Di||(Di={}));var fn={};Te(fn,{MAX_RSA_KEY_SIZE:()=>Ci,generateRSAKeyPair:()=>Lu,jwkToJWKKeyPair:()=>Bu,jwkToPkcs1:()=>vh,jwkToPkix:()=>Oi,jwkToRSAPrivateKey:()=>ki,pkcs1MessageToJwk:()=>Bi,pkcs1MessageToRSAPrivateKey:()=>Pi,pkcs1ToJwk:()=>Sh,pkcs1ToRSAPrivateKey:()=>Cu,pkixMessageToJwk:()=>Ri,pkixMessageToRSAPublicKey:()=>Ui,pkixToJwk:()=>_h,pkixToRSAPublicKey:()=>Ni});var Ir=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=fn.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return le.createV1(114,this._multihash)}toString(){return re.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ce(this.raw,e.raw)}verify(e,t,n){return Du(this.jwk,t,e,n)}},ln=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=fn.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ce(this.raw,e.raw)}sign(e,t){return Iu(this.jwk,e,t)}};var Ci=8192,Li=18,xh=1062,Eh=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function Sh(r){let e=at(r);return Bi(e)}function Bi(r){return{n:H(r[1],"base64url"),e:H(r[2],"base64url"),d:H(r[3],"base64url"),p:H(r[4],"base64url"),q:H(r[5],"base64url"),dp:H(r[6],"base64url"),dq:H(r[7],"base64url"),qi:H(r[8],"base64url"),kty:"RSA"}}function vh(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new oe("JWK was missing components");return wt([De(Uint8Array.from([0])),De(F(r.n,"base64url")),De(F(r.e,"base64url")),De(F(r.d,"base64url")),De(F(r.p,"base64url")),De(F(r.q,"base64url")),De(F(r.dp,"base64url")),De(F(r.dq,"base64url")),De(F(r.qi,"base64url"))]).subarray()}function _h(r){let e=at(r,{offset:0});return Ri(e)}function Ri(r){let e=at(r[1],{offset:0});return{kty:"RSA",n:H(e[0],"base64url"),e:H(e[1],"base64url")}}function Oi(r){if(r.n==null||r.e==null)throw new oe("JWK was missing components");return wt([Eh,Mn(wt([De(F(r.n,"base64url")),De(F(r.e,"base64url"))]))]).subarray()}function Cu(r){let e=at(r);return Pi(e)}function Pi(r){let e=Bi(r);return ki(e)}function Ni(r,e){if(r.byteLength>=xh)throw new ir("Key size is too large");let t=at(r,{offset:0});return Ui(t,r,e)}function Ui(r,e,t){let n=Ri(r);if(t==null){let s=yr(rt.encode({Type:ne.RSA,Data:e}));t=Ze(Li,s)}return new Ir(n,t)}function ki(r){if(Ou(r)>Ci)throw new oe("Key size is too large");let e=Bu(r),t=yr(rt.encode({Type:ne.RSA,Data:Oi(e.publicKey)})),n=Ze(Li,t);return new ln(e.privateKey,new Ir(e.publicKey,n))}async function Lu(r){if(r>Ci)throw new oe("Key size is too large");let e=await Ru(r),t=yr(rt.encode({Type:ne.RSA,Data:Oi(e.publicKey)})),n=Ze(Li,t);return new ln(e.privateKey,new Ir(e.publicKey,n))}function Bu(r){if(r==null)throw new oe("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function Ru(r,e){let t=await Fe.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);e?.signal?.throwIfAborted();let n=await Ah(t,e);return{privateKey:n[0],publicKey:n[1]}}async function Iu(r,e,t){let n=await Fe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let s=await Fe.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,_e(e instanceof Uint8Array?e:e.subarray()));return t?.signal?.throwIfAborted(),new Uint8Array(s,0,s.byteLength)}async function Du(r,e,t,n){let s=await Fe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let o=await Fe.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},s,_e(e),_e(t instanceof Uint8Array?t:t.subarray()));return n?.signal?.throwIfAborted(),o}async function Ah(r,e){if(r.privateKey==null||r.publicKey==null)throw new oe("Private and public key are required");let t=await Promise.all([Fe.get().subtle.exportKey("jwk",r.privateKey),Fe.get().subtle.exportKey("jwk",r.publicKey)]);return e?.signal?.throwIfAborted(),t}function Ou(r){if(r.kty!=="RSA")throw new oe("invalid key type");if(r.n==null)throw new oe("invalid key modulus");return F(r.n,"base64url").length*8}var co=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(Fn(e),Pe(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,s=new Uint8Array(n);s.set(t.length>n?e.create().update(t).digest():t);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=e.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),ut(s)}update(e){return mr(this),this.iHash.update(e),this}digestInto(e){mr(this),Kn(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),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:t,iHash:n,finished:s,destroyed:o,blockLen:i,outputLen:a}=this;return e=e,e.finished=s,e.destroyed=o,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Pu=(()=>{let r=((e,t,n)=>new co(e,t).update(n).digest());return r.create=(e,t)=>new co(e,t),r})();var Nu=(r,e)=>(r+(r>=0?e:-e)/Uu)/e;function Th(r,e,t){wr("scalar",r,nt,t);let[[n,s],[o,i]]=e,a=Nu(i*r,t),c=Nu(-s*r,t),u=r-a*n-c*o,l=-a*s-c*i,f=u<nt,m=l<nt;f&&(u=-u),m&&(l=-l);let d=en(Math.ceil(xr(t)/2))+Ct;if(u<nt||u>=d||l<nt||l>=d)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:f,k1:u,k2neg:m,k2:l}}function Fi(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function Mi(r,e){$e(r);let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return Ve(t.lowS,"lowS"),Ve(t.prehash,"prehash"),t.format!==void 0&&Fi(t.format),t}var Ki=class extends Error{constructor(e=""){super(e)}},Ge={Err:Ki,_tlv:{encode:(r,e)=>{let{Err:t}=Ge;if(He(r,"tag"),r<0||r>255)throw new t("tlv.encode: wrong tag");if(typeof e!="string")throw new TypeError('"data" expected string, got type='+typeof e);if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,s=Qr(n);if(s.length/2&128)throw new t("tlv.encode: long form length too big");let o=n>127?Qr(s.length/2|128):"";return Qr(r)+o+s+e},decode(r,e){let{Err:t}=Ge;e=$(e,void 0,"DER data");let n=0;if(r<0||r>255)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let s=e[n++],o=!!(s&128),i=0;if(!o)i=s;else{let c=s&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let u=e.subarray(n,n+c);if(u.length!==c)throw new t("tlv.decode: length bytes not complete");if(u[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let l of u)i=i<<8|l;if(n+=c,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(r){let{Err:e}=Ge;if(Gn(r),r<nt)throw new e("integer: negative integers are not allowed");let t=Qr(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(r){let{Err:e}=Ge;if(r.length<1)throw new e("invalid signature integer: empty");if(r[0]&128)throw new e("invalid signature integer: negative");if(r.length>1&&r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return zt(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=Ge,s=$(r,void 0,"signature"),{v:o,l:i}=n.decode(48,s);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,o),{v:u,l}=n.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(u)}},hexFromSig(r){let{_tlv:e,_int:t}=Ge,n=e.encode(2,t.encode(r.r)),s=e.encode(2,t.encode(r.s)),o=n+s;return e.encode(48,o)}};Object.freeze(Ge._tlv);Object.freeze(Ge._int);Object.freeze(Ge);var nt=BigInt(0),Ct=BigInt(1),Uu=BigInt(2),uo=BigInt(3),Ih=BigInt(4);function ku(r,e={}){let t=Xn("weierstrass",r,e),n=t.Fp,s=t.Fn,o=t.CURVE,{h:i,n:a}=o;$e(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c,allowInfinityPoint:u}=e;if(c&&(!n.is0(o.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=Fu(n,s);function f(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function m(N,p,g){if(u&&p.is0())return Uint8Array.of(0);let{x:v,y:w}=p.toAffine(),b=n.toBytes(v);if(Ve(g,"isCompressed"),g){f();let _=!n.isOdd(w);return de(Mu(_),b)}else return de(Uint8Array.of(4),b,n.toBytes(w))}function d(N){$(N,void 0,"Point");let{publicKey:p,publicKeyUncompressed:g}=l,v=N.length,w=N[0],b=N.subarray(1);if(u&&v===1&&w===0)return{x:n.ZERO,y:n.ZERO};if(v===p&&(w===2||w===3)){let _=n.fromBytes(b);if(!n.isValid(_))throw new Error("bad point: is not on curve, wrong x");let D=h(_),I;try{I=n.sqrt(D)}catch(V){let j=V instanceof Error?": "+V.message:"";throw new Error("bad point: is not on curve, sqrt error"+j)}f();let L=n.isOdd(I);return(w&1)===1!==L&&(I=n.neg(I)),{x:_,y:I}}else if(v===g&&w===4){let _=n.BYTES,D=n.fromBytes(b.subarray(0,_)),I=n.fromBytes(b.subarray(_,_*2));if(!y(D,I))throw new Error("bad point: is not on curve");return{x:D,y:I}}else throw new Error(`bad point: got length ${v}, expected compressed=${p} or uncompressed=${g}`)}let x=e.toBytes===void 0?m:e.toBytes,S=e.fromBytes===void 0?d:e.fromBytes;function h(N){let p=n.sqr(N),g=n.mul(p,N);return n.add(n.add(g,n.mul(N,o.a)),o.b)}function y(N,p){let g=n.sqr(p),v=h(N);return n.eql(g,v)}if(!y(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let E=n.mul(n.pow(o.a,uo),Ih),A=n.mul(n.sqr(o.b),BigInt(27));if(n.is0(n.add(E,A)))throw new Error("bad curve params: a or b");function B(N,p,g=!1){if(!n.isValid(p)||g&&n.is0(p))throw new Error(`bad point coordinate ${N}`);return p}function C(N){if(!(N instanceof T))throw new Error("Weierstrass Point expected")}function U(N){if(!c||!c.basises)throw new Error("no endo");return Th(N,c.basises,s.ORDER)}function R(N,p,g,v,w){return g=new T(n.mul(g.X,N),g.Y,g.Z),p=rn(v,p),g=rn(w,g),p.add(g)}class T{static BASE=new T(o.Gx,o.Gy,n.ONE);static ZERO=new T(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=s;X;Y;Z;constructor(p,g,v){this.X=B("x",p),this.Y=B("y",g,!0),this.Z=B("z",v),Object.freeze(this)}static CURVE(){return o}static fromAffine(p){let{x:g,y:v}=p||{};if(!p||!n.isValid(g)||!n.isValid(v))throw new Error("invalid affine point");if(p instanceof T)throw new Error("projective point not allowed");return n.is0(g)&&n.is0(v)?T.ZERO:new T(g,v,n.ONE)}static fromBytes(p){let g=T.fromAffine(S($(p,void 0,"point")));return g.assertValidity(),g}static fromHex(p){return T.fromBytes(br(p))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(p=8,g=!0){return M.createCache(this,p),g||this.multiply(uo),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")}let{x:g,y:v}=p.toAffine();if(!n.isValid(g)||!n.isValid(v))throw new Error("bad point: x or y not field elements");if(!y(g,v))throw new Error("bad point: equation left != right");if(!p.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:p}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(p)}equals(p){C(p);let{X:g,Y:v,Z:w}=this,{X:b,Y:_,Z:D}=p,I=n.eql(n.mul(g,D),n.mul(b,w)),L=n.eql(n.mul(v,D),n.mul(_,w));return I&&L}negate(){return new T(this.X,n.neg(this.Y),this.Z)}double(){let{a:p,b:g}=o,v=n.mul(g,uo),{X:w,Y:b,Z:_}=this,D=n.ZERO,I=n.ZERO,L=n.ZERO,P=n.mul(w,w),V=n.mul(b,b),j=n.mul(_,_),q=n.mul(w,b);return q=n.add(q,q),L=n.mul(w,_),L=n.add(L,L),D=n.mul(p,L),I=n.mul(v,j),I=n.add(D,I),D=n.sub(V,I),I=n.add(V,I),I=n.mul(D,I),D=n.mul(q,D),L=n.mul(v,L),j=n.mul(p,j),q=n.sub(P,j),q=n.mul(p,q),q=n.add(q,L),L=n.add(P,P),P=n.add(L,P),P=n.add(P,j),P=n.mul(P,q),I=n.add(I,P),j=n.mul(b,_),j=n.add(j,j),P=n.mul(j,q),D=n.sub(D,P),L=n.mul(j,V),L=n.add(L,L),L=n.add(L,L),new T(D,I,L)}add(p){C(p);let{X:g,Y:v,Z:w}=this,{X:b,Y:_,Z:D}=p,I=n.ZERO,L=n.ZERO,P=n.ZERO,V=o.a,j=n.mul(o.b,uo),q=n.mul(g,b),fe=n.mul(v,_),he=n.mul(w,D),pe=n.add(g,v),ae=n.add(b,_);pe=n.mul(pe,ae),ae=n.add(q,fe),pe=n.sub(pe,ae),ae=n.add(g,w);let Ae=n.add(b,D);return ae=n.mul(ae,Ae),Ae=n.add(q,he),ae=n.sub(ae,Ae),Ae=n.add(v,w),I=n.add(_,D),Ae=n.mul(Ae,I),I=n.add(fe,he),Ae=n.sub(Ae,I),P=n.mul(V,ae),I=n.mul(j,he),P=n.add(I,P),I=n.sub(fe,P),P=n.add(fe,P),L=n.mul(I,P),fe=n.add(q,q),fe=n.add(fe,q),he=n.mul(V,he),ae=n.mul(j,ae),fe=n.add(fe,he),he=n.sub(q,he),he=n.mul(V,he),ae=n.add(ae,he),q=n.mul(fe,ae),L=n.add(L,q),q=n.mul(Ae,ae),I=n.mul(pe,I),I=n.sub(I,q),q=n.mul(pe,fe),P=n.mul(Ae,P),P=n.add(P,q),new T(I,L,P)}subtract(p){return C(p),this.add(p.negate())}is0(){return this.equals(T.ZERO)}multiply(p){let{endo:g}=e;if(!s.isValidNot0(p))throw new RangeError("invalid scalar: out of range");let v,w,b=_=>M.cached(this,_,D=>$t(T,D));if(g){let{k1neg:_,k1:D,k2neg:I,k2:L}=U(p),{p:P,f:V}=b(D),{p:j,f:q}=b(L);w=V.add(q),v=R(g.beta,P,j,_,I)}else{let{p:_,f:D}=b(p);v=_,w=D}return $t(T,[v,w])[0]}multiplyUnsafe(p){let{endo:g}=e,v=this,w=p;if(!s.isValid(w))throw new RangeError("invalid scalar: out of range");if(w===nt||v.is0())return T.ZERO;if(w===Ct)return v;if(M.hasCache(this))return this.multiply(w);if(g){let{k1neg:b,k1:_,k2neg:D,k2:I}=U(w),{p1:L,p2:P}=au(T,v,_,I);return R(g.beta,L,P,b,D)}else return M.unsafe(v,w)}toAffine(p){let g=this,v=p,{X:w,Y:b,Z:_}=g;if(n.eql(_,n.ONE))return{x:w,y:b};let D=g.is0();v==null&&(v=D?n.ONE:n.inv(_));let I=n.mul(w,v),L=n.mul(b,v),P=n.mul(_,v);if(D)return{x:n.ZERO,y:n.ZERO};if(!n.eql(P,n.ONE))throw new Error("invZ was invalid");return{x:I,y:L}}isTorsionFree(){let{isTorsionFree:p}=e;return i===Ct?!0:p?p(T,this):M.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:p}=e;return i===Ct?this:p?p(T,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===Ct?this.is0():this.clearCofactor().is0()}toBytes(p=!0){return Ve(p,"isCompressed"),this.assertValidity(),x(T,this,p)}toHex(p=!0){return gr(this.toBytes(p))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let k=s.BITS,M=new vr(T,e.endo?Math.ceil(k/2):k);return k>=8&&T.BASE.precompute(8),Object.freeze(T.prototype),Object.freeze(T),T}function Mu(r){return Uint8Array.of(r?2:3)}function Fu(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Dh(r,e={}){let{Fn:t}=r,n=e.randomBytes===void 0?Xr:e.randomBytes,s=Object.assign(Fu(r.Fp,t),{seed:Math.max(Zs(t.ORDER),16)});function o(d){try{let x=t.fromBytes(d);return t.isValidNot0(x)}catch{return!1}}function i(d,x){let{publicKey:S,publicKeyUncompressed:h}=s;try{let y=d.length;return x===!0&&y!==S||x===!1&&y!==h?!1:!!r.fromBytes(d)}catch{return!1}}function a(d){return d=d===void 0?n(s.seed):d,Xs($(d,s.seed,"seed"),t.ORDER)}function c(d,x=!0){return r.BASE.multiply(t.fromBytes(d)).toBytes(x)}function u(d){let{secretKey:x,publicKey:S,publicKeyUncompressed:h}=s,y=t._lengths;if(!qt(d))return;let E=$(d,void 0,"key").length,A=E===S||E===h,B=E===x||!!y?.includes(E);if(!(A&&B))return A}function l(d,x,S=!0){if(u(d)===!0)throw new Error("first arg must be private key");if(u(x)===!1)throw new Error("second arg must be public key");let h=t.fromBytes(d);return r.fromBytes(x).multiply(h).toBytes(S)}let f={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a},m=Qn(a,c);return Object.freeze(f),Object.freeze(s),Object.freeze({getPublicKey:c,getSharedSecret:l,keygen:m,Point:r,utils:f,lengths:s})}function Ku(r,e,t={}){let n=e;Fn(n),$e(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let s=t.randomBytes===void 0?Xr:t.randomBytes,o=t.hmac===void 0?(w,b)=>Pu(n,w,b):t.hmac,{Fp:i,Fn:a}=r,{ORDER:c,BITS:u}=a,{keygen:l,getPublicKey:f,getSharedSecret:m,utils:d,lengths:x}=Dh(r,t),S={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},h=c*Uu+Ct<i.ORDER;function y(w){let b=c>>Ct;return w>b}function E(w,b){if(!a.isValidNot0(b))throw new Error(`invalid signature ${w}: out of range 1..Point.Fn.ORDER`);return b}function A(){if(h)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function B(w,b){Fi(b);let _=x.signature,D=b==="compact"?_:b==="recovered"?_+1:void 0;return $(w,D)}class C{r;s;recovery;constructor(b,_,D){if(this.r=E("r",b),this.s=E("s",_),D!=null){if(A(),![0,1,2,3].includes(D))throw new Error("invalid recovery id");this.recovery=D}Object.freeze(this)}static fromBytes(b,_=S.format){B(b,_);let D;if(_==="der"){let{r:V,s:j}=Ge.toSig($(b));return new C(V,j)}_==="recovered"&&(D=b[0],_="compact",b=b.subarray(1));let I=x.signature/2,L=b.subarray(0,I),P=b.subarray(I,I*2);return new C(a.fromBytes(L),a.fromBytes(P),D)}static fromHex(b,_){return this.fromBytes(br(b),_)}assertRecovery(){let{recovery:b}=this;if(b==null)throw new Error("invalid recovery id: must be present");return b}addRecoveryBit(b){return new C(this.r,this.s,b)}recoverPublicKey(b){let{r:_,s:D}=this,I=this.assertRecovery(),L=I===2||I===3?_+c:_;if(!i.isValid(L))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let P=i.toBytes(L),V=r.fromBytes(de(Mu((I&1)===0),P)),j=a.inv(L),q=R($(b,void 0,"msgHash")),fe=a.create(-q*j),he=a.create(D*j),pe=r.BASE.multiplyUnsafe(fe).add(V.multiplyUnsafe(he));if(pe.is0())throw new Error("invalid recovery: point at infinify");return pe.assertValidity(),pe}hasHighS(){return y(this.s)}toBytes(b=S.format){if(Fi(b),b==="der")return br(Ge.hexFromSig(this));let{r:_,s:D}=this,I=a.toBytes(_),L=a.toBytes(D);return b==="recovered"?(A(),de(Uint8Array.of(this.assertRecovery()),I,L)):de(I,L)}toHex(b){return gr(this.toBytes(b))}}Object.freeze(C.prototype),Object.freeze(C);let U=t.bits2int===void 0?function(b){if(b.length>8192)throw new Error("input is too large");let _=zt(b),D=b.length*8-u;return D>0?_>>BigInt(D):_}:t.bits2int,R=t.bits2int_modN===void 0?function(b){return a.create(U(b))}:t.bits2int_modN,T=en(u);function k(w){return wr("num < 2^"+u,w,nt,T),a.toBytes(w)}function M(w,b){return $(w,void 0,"message"),b?$(n(w),void 0,"prehashed message"):w}function N(w,b,_){let{lowS:D,prehash:I,extraEntropy:L}=Mi(_,S);w=M(w,I);let P=R(w),V=a.fromBytes(b);if(!a.isValidNot0(V))throw new Error("invalid private key");let j=[k(V),k(P)];if(L!=null&&L!==!1){let pe=L===!0?s(x.secretKey):L;j.push($(pe,void 0,"extraEntropy"))}let q=de(...j),fe=P;function he(pe){let ae=U(pe);if(!a.isValidNot0(ae))return;let Ae=a.inv(ae),sr=r.BASE.multiply(ae).toAffine(),Mr=a.create(sr.x);if(Mr===nt)return;let Tn=a.create(Ae*a.create(fe+Mr*V));if(Tn===nt)return;let Ha=(sr.x===Mr?0:2)|Number(sr.y&Ct),$a=Tn;return D&&y(Tn)&&($a=a.neg(Tn),Ha^=1),new C(Mr,$a,h?void 0:Ha)}return{seed:q,k2sig:he}}function p(w,b,_={}){let{seed:D,k2sig:I}=N(w,b,_);return Hc(n.outputLen,a.BYTES,o)(D,I).toBytes(_.format)}function g(w,b,_,D={}){let{lowS:I,prehash:L,format:P}=Mi(D,S);if(_=$(_,void 0,"publicKey"),b=M(b,L),!qt(w)){let V=w instanceof C?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+V)}B(w,P);try{let V=C.fromBytes(w,P),j=r.fromBytes(_);if(I&&V.hasHighS())return!1;let{r:q,s:fe}=V,he=R(b),pe=a.inv(fe),ae=a.create(he*pe),Ae=a.create(q*pe),sr=r.BASE.multiplyUnsafe(ae).add(j.multiplyUnsafe(Ae));return sr.is0()?!1:a.create(sr.x)===q}catch{return!1}}function v(w,b,_={}){let{prehash:D}=Mi(_,S);return b=M(b,D),C.fromBytes(w,"recovered").recoverPublicKey(b).toBytes()}return Object.freeze({keygen:l,getPublicKey:f,getSharedSecret:m,utils:d,lengths:x,Point:r,sign:p,verify:g,recoverPublicKey:v,Signature:C,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")},Ch={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var qu=BigInt(2);function Lh(r){let e=zi.p,t=BigInt(3),n=BigInt(6),s=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=r*r*r%e,l=u*u*r%e,f=te(l,t,e)*l%e,m=te(f,t,e)*l%e,d=te(m,qu,e)*u%e,x=te(d,s,e)*d%e,S=te(x,o,e)*x%e,h=te(S,a,e)*S%e,y=te(h,c,e)*h%e,E=te(y,a,e)*S%e,A=te(E,t,e)*l%e,B=te(A,i,e)*x%e,C=te(B,n,e)*u%e,U=te(C,qu,e);if(!qi.eql(qi.sqr(U),r))throw new Error("Cannot find square root");return U}var qi=Er(zi.p,{sqrt:Lh}),Bh=ku(zi,{Fp:qi,endo:Ch}),Dr=Ku(Bh,yr);function zu(r,e,t,n){let s=hr.digest(t instanceof Uint8Array?t:t.subarray());if(ro(s))return s.then(({digest:o})=>(n?.signal?.throwIfAborted(),Dr.verify(e,o,r,{prehash:!1,format:"der"}))).catch(o=>{throw o.name==="AbortError"?o:new on(String(o))});try{return n?.signal?.throwIfAborted(),Dr.verify(e,s.digest,r,{prehash:!1,format:"der"})}catch(o){throw new on(String(o))}}var lo=class{type="secp256k1";raw;_key;constructor(e){this._key=Hu(e),this.raw=Vu(this._key)}toMultihash(){return qe.digest(Je(this))}toCID(){return le.createV1(114,this.toMultihash())}toString(){return re.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ce(this.raw,e.raw)}verify(e,t,n){return zu(this._key,t,e,n)}};function Vi(r){return new lo(r)}function Vu(r){return Dr.Point.fromBytes(r).toBytes()}function Hu(r){try{return Dr.Point.fromBytes(r),r}catch(e){throw new ir(String(e))}}function $u(r,e){let{Type:t,Data:n}=rt.decode(r),s=n??new Uint8Array;switch(t){case ne.RSA:return Ni(s,e);case ne.Ed25519:return li(s);case ne.secp256k1:return Vi(s);case ne.ECDSA:return Os(s);default:throw new ar}}function Wu(r){let{Type:e,Data:t}=rt.decode(r.digest),n=t??new Uint8Array;switch(e){case ne.Ed25519:return li(n);case ne.secp256k1:return Vi(n);case ne.ECDSA:return Os(n);default:throw new ar}}function Je(r){return rt.encode({Type:ne[r.type],Data:r.raw})}var Gu=Symbol.for("nodejs.util.inspect.custom"),Rh=114,dn=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()})`}[os]=!0;toString(){return this.string==null&&(this.string=re.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return le.createV1(Rh,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return ce(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return ce(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Gu](){return`PeerId(${this.toString()})`}},fo=class extends dn{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},ho=class extends dn{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},po=class extends dn{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},Oh=2336,hn=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=qe.digest(F(this.url))}[Gu](){return`PeerId(${this.url})`}[os]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return le.createV1(Oh,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=H(e)),e.toString()===this.toString())}};var Ph=114,ju=2336;function Hi(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=Xe(re.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return Nh(le.parse(r));if(e==null)throw new oe('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=Xe(e.decode(r))}return Cr(t)}function Cr(r){if(kh(r))return new fo({multihash:r});if(Uh(r))try{let e=Wu(r);if(e.type==="Ed25519")return new ho({multihash:r,publicKey:e});if(e.type==="secp256k1")return new po({multihash:r,publicKey:e})}catch{let t=H(r.digest);return new hn(new URL(t))}throw new Cn("Supplied PeerID Multihash is invalid")}function Nh(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==Ph&&r.code!==ju)throw new Dn("Supplied PeerID CID is invalid");if(r.code===ju){let e=H(r.multihash.digest);return new hn(new URL(e))}return Cr(r.multihash)}function Uh(r){return r.code===qe.code}function kh(r){return r.code===hr.code}var pn;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.publicKey!=null&&o.publicKey.byteLength>0&&(i.uint32(10),i.bytes(o.publicKey)),o.payloadType!=null&&o.payloadType.byteLength>0&&(i.uint32(18),i.bytes(o.payloadType)),o.payload!=null&&o.payload.byteLength>0&&(i.uint32(26),i.bytes(o.payload)),o.signature!=null&&o.signature.byteLength>0&&(i.uint32(42),i.bytes(o.signature)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={publicKey:J(0),payloadType:J(0),payload:J(0),signature:J(0)},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{c.publicKey=o.bytes();break}case 2:{c.payloadType=o.bytes();break}case 3:{c.payload=o.bytes();break}case 5:{c.signature=o.bytes();break}default:{o.skipType(l&7);break}}}return c},function*(o,i,a,c={}){let u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{yield{field:`${a}.publicKey`,value:o.bytes()};break}case 2:{yield{field:`${a}.payloadType`,value:o.bytes()};break}case 3:{yield{field:`${a}.payload`,value:o.bytes()};break}case 5:{yield{field:`${a}.signature`,value:o.bytes()};break}default:{o.skipType(l&7);break}}}})),e);function t(o){return Be(o,r.codec())}r.encode=t;function n(o,i){return Le(o,r.codec(),i)}r.decode=n;function s(o,i){return Re(o,r.codec(),i)}r.stream=s})(pn||(pn={}));var mo=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var mn=class r{static createFromProtobuf=e=>{let t=pn.decode(e),n=$u(t.publicKey);return new r({publicKey:n,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t,n)=>{if(t==null)throw new Error("Missing private key");let s=e.domain,o=e.codec,i=e.marshal(),a=Yu(s,o,i),c=await t.sign(a.subarray(),n);return new r({publicKey:t.publicKey,payloadType:o,payload:i,signature:c})};static openAndCertify=async(e,t,n)=>{let s=r.createFromProtobuf(e);if(!await s.validate(t,n))throw new mo("Envelope signature is not valid for the given domain");return s};publicKey;payloadType;payload;signature;marshaled;constructor(e){let{publicKey:t,payloadType:n,payload:s,signature:o}=e;this.publicKey=t,this.payloadType=n,this.payload=s,this.signature=o}marshal(){return this.marshaled==null&&(this.marshaled=pn.encode({publicKey:Je(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return e==null?!1:ce(this.marshal(),e.marshal())}async validate(e,t){let n=Yu(e,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,t)}},Yu=(r,e,t)=>{let n=F(r),s=Tr(n.byteLength),o=Tr(e.length),i=Tr(t.length);return new ee(s,n,o,e,i,t)};var we=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},ht=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 t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}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 t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,s){return this.readAtomically(()=>{let o=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*s)-1;for(;;){let l=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let m=Number.parseInt(f,e);if(!Number.isNaN(m))return m});if(l===void 0)break;if(o*=e,o+=l,o>u||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:o})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let s=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[s]=i[0],t[s+1]=i[1],t[s+2]=i[2],t[s+3]=i[3],[s+4,!0]}let o=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(o===void 0)return[s,!1];t[s]=o>>8,t[s+1]=o&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,s]=e(t);if(n===16)return t;if(s||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let o=new Uint8Array(14),i=16-(n+2),[a]=e(o.subarray(0,i));return t.set(o.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Mh=45,Fh=15,wo=new bo;function Zu(r){if(!(r.length>Fh))return wo.new(r).parseWith(()=>wo.readIPv4Addr())}function Xu(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Mh))return wo.new(r).parseWith(()=>wo.readIPv6Addr())}function xo(r){return!!Zu(r)}function Qu(r){return!!Xu(r)}function Wi(r){return e=>H(e,r)}function Gi(r){return e=>F(e,r)}function Lr(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Zt(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function Ju(r){let e=r.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 t=F(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 s=Zt(n);return Qe([t,s],t.length+s.length)}function el(r){let e=r.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 t=bt.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 s=Zt(n);return Qe([t,s],t.length+s.length)}function ji(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=H(e,"base32"),s=Lr(t);return`${n}:${s}`}var Yi=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let s=parseInt(t,10);if(isNaN(s)||s<0||s>255)throw new we("Invalid byte value in IP address");e[n]=s}),e},tl=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let o=xo(t[n]),i;o&&(i=Yi(t[n]),t[n]=H(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,H(i.subarray(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let o=[n,1];for(n=9-t.length;n>0;n--)o.push("0");t.splice.apply(t,o)}let s=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let o=parseInt(t[n],16);if(isNaN(o)||o<0||o>65535)throw new we("Invalid byte value in IP address");s[e++]=o>>8&255,s[e++]=o&255}return s},rl=function(r){if(r.byteLength!==4)throw new we("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},nl=function(r){if(r.byteLength!==16)throw new we("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let s=r[n],o=r[n+1],i=`${s.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new we(`Invalid IPv6 address "${t}"`)}};function ol(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new we(`Invalid IPv6 address "${r}"`)}}var $i=Object.values(Hr).map(r=>r.decoder),Kh=(function(){let r=$i[0].or($i[1]);return $i.slice(2).forEach(e=>r=r.or(e)),r})();function sl(r){return Kh.decode(r)}function il(r){return e=>r.encoder.encode(e)}function qh(r){if(parseInt(r).toString()!==r)throw new ht("Value must be an integer")}function zh(r){if(r<0)throw new ht("Value must be a positive integer, or zero")}function Vh(r){return e=>{if(e>r)throw new ht(`Value must be smaller than or equal to ${r}`)}}function Hh(...r){return e=>{for(let t of r)t(e)}}var yn=Hh(qh,zh,Vh(65535));var ye=-1,Zi=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(typeof e=="string"?t=this.protocolsByName.get(e):t=this.protocolsByCode.get(e),t==null)throw new go(`Protocol ${e} was unknown`);return t}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(t=>{this.protocolsByName.set(t,e)})}removeProtocol(e){let t=this.protocolsByCode.get(e);t!=null&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},mt=new Zi,op=[{code:4,name:"ip4",size:32,valueToBytes:Yi,bytesToValue:rl,validate:r=>{if(!xo(r))throw new ht(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Zt,bytesToValue:Lr,validate:yn},{code:273,name:"udp",size:16,valueToBytes:Zt,bytesToValue:Lr,validate:yn},{code:33,name:"dccp",size:16,valueToBytes:Zt,bytesToValue:Lr,validate:yn},{code:41,name:"ip6",size:128,valueToBytes:tl,bytesToValue:nl,stringToValue:ol,validate:r=>{if(!Qu(r))throw new ht(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:ye},{code:43,name:"ipcidr",size:8,bytesToValue:Wi("base10"),valueToBytes:Gi("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:Zt,bytesToValue:Lr,validate:yn},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:ye,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:ye,bytesToValue:Wi("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Gi("base58btc")(r):le.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:ji,valueToBytes:Ju},{code:445,name:"onion3",size:296,bytesToValue:ji,valueToBytes:el},{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:il(xs),valueToBytes:sl},{code:480,name:"http"},{code:481,name:"http-path",size:ye,stringToValue:r=>`/${decodeURIComponent(r)}`,valueToString:r=>encodeURIComponent(r.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:ye}];op.forEach(r=>{mt.addProtocol(r)});function al(r){let e=[],t=0;for(;t<r.length;){let n=sn(r,t),s=mt.getProtocol(n),o=Ce(n),i=sp(s,r,t+o),a=0;i>0&&s.size===ye&&(a=Ce(i));let c=o+a+i,u={code:n,name:s.name,bytes:_e(r.subarray(t,t+c))};if(i>0){let l=t+o+a,f=r.subarray(l,l+i);u.value=s.bytesToValue?.(f)??H(f)}e.push(u),t+=c}return e}function cl(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let s=mt.getProtocol(n.code),o=Ce(n.code),i,a=0,c=0;n.value!=null&&(i=s.valueToBytes?.(n.value)??F(n.value),a=i.byteLength,s.size===ye&&(c=Ce(a)));let u=new Uint8Array(o+c+a),l=0;Ar(n.code,u,l),l+=o,i!=null&&(s.size===ye&&(Ar(a,u,l),l+=c),u.set(i,l)),n.bytes=u}t.push(n.bytes),e+=n.bytes.byteLength}return Qe(t,e)}function ul(r){if(r.charAt(0)!=="/")throw new we('String multiaddr must start with "/"');let e=[],t="protocol",n="",s="";for(let o=1;o<r.length;o++){let i=r.charAt(o);i!=="/"&&(t==="protocol"?s+=r.charAt(o):n+=r.charAt(o));let a=o===r.length-1;if(i==="/"||a){let c=mt.getProtocol(s);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",s="",t="protocol";continue}else if(a)throw new we(`Component ${s} was missing value`);t="value"}else if(t==="value"){let u={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new we(`Component ${s} was missing value`);u.value=c.stringToValue?.(n)??n}e.push(u),n="",s="",t="protocol"}}}if(s!==""&&n!=="")throw new we("Incomplete multiaddr");return e}function ll(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=mt.getProtocol(e.code);if(t==null)throw new we(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function sp(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:sn(e,t)}var ip=Symbol.for("nodejs.util.inspect.custom"),ha=Symbol.for("@multiformats/multiaddr");function ap(r){if(r==null&&(r="/"),fl(r))return r.getComponents();if(r instanceof Uint8Array)return al(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),ul(r);if(Array.isArray(r))return r;throw new we("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Ao=class r{[ha]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=ap(e),t.validate!==!1&&cp(this)}get bytes(){return this.#r==null&&(this.#r=cl(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=ll(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),s=n.lastIndexOf(t);if(s<0)throw new yo(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,s),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}equals(e){return ce(this.bytes,e.bytes)}[ip](){return`Multiaddr(${this.toString()})`}};function cp(r){r.getComponents().forEach(e=>{let t=mt.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function fl(r){return!!r?.[ha]}function Ue(r){return new Ao(r)}var pa={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},dl={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},hl=new globalThis.TextEncoder;function up(r,e){let t=pa[e],n=dl[e];for(let s=0;s<r.length;s++)n^=BigInt(r[s]),n=BigInt.asUintN(e,n*t);return n}function lp(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=pa[e],s=dl[e],o=r;for(;o.length>0;){let i=hl.encodeInto(o,t);o=o.slice(i.read);for(let a=0;a<i.written;a++)s^=BigInt(t[a]),s=BigInt.asUintN(e,s*n)}return s}function ma(r,{size:e=32,utf8Buffer:t}={}){if(!pa[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(t)return lp(r,e,t);r=hl.encode(r)}return up(r,e)}var gn={hash:r=>Number(ma(r,{size:32})),hashV:(r,e)=>fp(gn.hash(r,e))};function fp(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),F(e,"base16")}var ya=64,je=class{fp;h;seed;constructor(e,t,n,s=2){if(s>ya)throw new TypeError("Invalid Fingerprint Size");let o=t.hashV(e,n),i=J(s);for(let a=0;a<i.length;a++)i[a]=o[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?ce(this.fp,e.fp):!1}};function Jt(r,e){return Math.floor(Math.random()*(e-r))+r}var er=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof je))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof je))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(this.contents[t]==null)return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof je))throw new TypeError("Invalid Fingerprint");let t=Jt(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof je))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var dp=500,bn=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??gn,this.seed=e.seed??Jt(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=F(e));let t=new je(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new er(this.bucketSize)),this.buckets[s]==null&&(this.buckets[s]=new er(this.bucketSize)),this.buckets[n].add(t)||this.buckets[s].add(t))return this.count++,!0;let o=[n,s],i=o[Jt(0,o.length-1)];this.buckets[i]==null&&(this.buckets[i]=new er(this.bucketSize));for(let a=0;a<dp;a++){let c=this.buckets[i].swap(t);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new er(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=F(e));let t=new je(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=this.buckets[n]?.has(t)??!1;if(s)return s;let o=(n^t.hash())%this.filterSize;return this.buckets[o]?.has(t)??!1}remove(e){typeof e=="string"&&(e=F(e));let t=new je(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=this.buckets[n]?.remove(t)??!1;if(s)return this.count--,s;let o=(n^t.hash())%this.filterSize,i=this.buckets[o]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},hp={1:.5,2:.84,4:.95,8:.98};function pp(r=.001){return r>.002?2:r>1e-5?4:8}function pl(r,e=.001){let t=pp(e),n=hp[t],s=Math.round(r/n),o=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),ya);return{filterSize:s,bucketSize:t,fingerprintSize:o}}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??gn,this.seed=e.seed??Jt(0,Math.pow(2,10)),this.filterSeries=[new bn({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=F(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new bn({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=F(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=F(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function Pr(r,e=.001,t){return new To({...pl(r,e),...t??{}})}var X=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),O=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),ml=r=>({match:e=>r.match(e)===!1?e:!1}),z=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),ve=(...r)=>({match:e=>{let t;for(let n of r){let s=n.match(e);s!==!1&&(t==null||s.length<t.length)&&(t=s)}return t??!1}}),W=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e}});function Q(...r){function e(s){if(s==null)return!1;let o=s.getComponents();for(let i of r){let a=i.match(o);if(a===!1)return!1;o=a}return o}function t(s){return e(s)!==!1}function n(s){let o=e(s);return o===!1?!1:o.length===0}return{matchers:r,matches:t,exactMatch:n}}var mp=O(421),hE=Q(mp),Do=O(54),Co=O(55),Lo=O(56),ba=O(53),pE=Q(Do,z(O(421))),mE=Q(Co,z(O(421))),yE=Q(Lo,z(O(421))),gE=Q(ve(ba,Lo,Do,Co),z(O(421))),yl=W(O(4),z(O(43))),gl=W(z(O(42)),O(41),z(O(43))),wa=ve(yl,gl),Nr=ve(wa,ba,Do,Co,Lo),bE=Q(ve(wa,W(ve(ba,Lo,Do,Co),z(O(421))))),wE=Q(yl),xE=Q(gl),EE=Q(wa),xa=W(Nr,O(6)),wn=W(Nr,O(273)),SE=Q(W(xa,z(O(421)))),vE=Q(wn),Ea=W(wn,X(460),z(O(421))),Bo=W(wn,X(461),z(O(421))),yp=ve(Ea,Bo),_E=Q(Ea),AE=Q(Bo),ga=ve(Nr,xa,wn,Ea,Bo),bl=ve(W(ga,X(477),z(O(421)))),TE=Q(bl),wl=ve(W(ga,X(478),z(O(421))),W(ga,X(448),z(O(449)),X(477),z(O(421)))),IE=Q(wl),xl=W(wn,X(280),z(O(466)),z(O(466)),z(O(421))),DE=Q(xl),El=W(Bo,X(465),z(O(466)),z(O(466)),z(O(421))),CE=Q(El),Io=ve(bl,wl,W(xa,z(O(421))),W(yp,z(O(421))),W(Nr,z(O(421))),xl,El,O(421)),Sl=Q(Io),gp=W(z(Io),X(290),ml(X(281)),z(O(421))),tr=Q(gp),bp=ve(W(Io,X(290),X(281),z(O(421))),W(Io,X(281),z(O(421))),W(X(281),z(O(421)))),LE=Q(bp),wp=W(Nr,ve(W(O(6,"80")),W(O(6),X(480)),X(480)),z(O(481)),z(O(421))),BE=Q(wp),xp=W(Nr,ve(W(O(6,"443")),W(O(6,"443"),X(480)),W(O(6),X(443)),W(O(6),X(448),X(480)),W(X(448),X(480)),X(448),X(443)),z(O(481)),z(O(421))),RE=Q(xp),Ep=ve(W(O(777),z(O(421)))),OE=Q(Ep),Sp=ve(W(O(400),z(O(421)))),PE=Q(Sp);function Ye(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}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}},Ur=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 t=this.head;this.head=t.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 t=this.tail.next;this.tail.next=null,this.tail=t,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,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Lt(r={}){return vp(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function vp(r,e){e=e??{};let t=e.onEnd,n=new Ur,s,o,i,a=Ye(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((h,y)=>{o=E=>{o=null,n.push(E);try{h(r(n))}catch(A){y(A)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Ye()})}},u=h=>o!=null?o(h):(n.push(h),s),l=h=>(n=new Ur,o!=null?o({error:h}):(n.push({error:h}),s)),f=h=>{if(i)return s;if(e?.objectMode!==!0&&h?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:h})},m=h=>i?s:(i=!0,h!=null?l(h):u({done:!0})),d=()=>(n=new Ur,m(),{done:!0}),x=h=>(m(h),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:d,throw:x,push:f,end:m,get readableLength(){return n.size},onEmpty:async h=>{let y=h?.signal;if(y?.throwIfAborted(),n.isEmpty())return;let E,A;y!=null&&(E=new Promise((B,C)=>{A=()=>{C(new Sa)},y.addEventListener("abort",A)}));try{await Promise.race([a.promise,E])}finally{A!=null&&y!=null&&y?.removeEventListener("abort",A)}}},t==null)return s;let S=s;return s={[Symbol.asyncIterator](){return this},next(){return S.next()},throw(h){return S.throw(h),t!=null&&(t(h),t=void 0),{done:!0}},return(){return S.return(),t!=null&&(t(),t=void 0),{done:!0}},push:f,end(h){return S.end(h),t!=null&&(t(h),t=void 0),s},get readableLength(){return S.readableLength},onEmpty:h=>S.onEmpty(h)},s}var va=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},vl=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function _a(r,e){let{milliseconds:t,fallback:n,message:s,customTimers:o={setTimeout,clearTimeout},signal:i}=e,a,c,l=new Promise((f,m)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(i?.aborted){m(vl(i));return}if(i&&(c=()=>{m(vl(i))},i.addEventListener("abort",c,{once:!0})),r.then(f,m),t===Number.POSITIVE_INFINITY)return;let d=new va;a=o.setTimeout.call(void 0,()=>{if(n){try{f(n())}catch(x){m(x)}return}typeof r.cancel=="function"&&r.cancel(),s===!1?f():s instanceof Error?m(s):(d.message=s??`Promise timed out after ${t} milliseconds`,m(d))},t)}).finally(()=>{l.clear(),c&&i&&i.removeEventListener("abort",c)});return l.clear=()=>{o.clearTimeout.call(void 0,a),a=void 0},l}var _p=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function Ap(r,e,t){let n,s=new Promise((o,i)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:u,removeListener:l}=_p(r),f=async(...d)=>{let x=t.multiArgs?d:d[0];if(t.filter)try{if(!await t.filter(x))return}catch(S){n(),i(S);return}c.push(x),t.count===c.length&&(n(),o(c))},m=(...d)=>{n(),i(t.rejectionMultiArgs?d:d[0])};n=()=>{for(let d of a)l(d,f);for(let d of t.rejectionEvents)a.includes(d)||l(d,m)};for(let d of a)u(d,f);for(let d of t.rejectionEvents)a.includes(d)||u(d,m);t.signal&&t.signal.addEventListener("abort",()=>{m(t.signal.reason)},{once:!0}),t.resolveImmediately&&o(c)});if(s.cancel=n,typeof t.timeout=="number"){let o=_a(s,{milliseconds:t.timeout});return o.cancel=()=>{n(),o.clear()},o}return s}function ot(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=Ap(r,e,t),s=n.then(o=>o[0]);return s.cancel=n.cancel,s}function Aa(r,e){let t,n=function(){let s=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(s,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var Oo=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}},rr=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"};var Po=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function Tp(r){return r.reason}async function Bt(r,e,t){if(e==null)return r;let n=t?.translateError??Tp;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let s;try{return await Promise.race([r,new Promise((o,i)=>{s=()=>{i(n(e))},e.addEventListener("abort",s)})])}finally{s!=null&&e.removeEventListener("abort",s)}}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 st)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Ip(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Uo=class{id;fn;options;recipients;status;timeline;controller;dispatchingProgress;constructor(e,t){this.id=Ip(),this.status="queued",this.fn=e,this.options=t,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((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new st),this.cleanup())}async join(e){let t=new No(e);return this.recipients.push(t),e?.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await Bt(this.fn({...this.options??{},signal:this.controller.signal,onProgress:t=>{if(!this.dispatchingProgress){this.dispatchingProgress=!0;try{this.recipients.forEach(n=>{n.onProgress?.(t)})}finally{this.dispatchingProgress=!1}}}}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.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 ko=class extends Ie{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 t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,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,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Oo;let n=new Uo(e,t);this.enqueue(n),this.safeDispatchEvent("add");let s=n.join(t).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{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:o}}),o});return this.tryToStartAnother(),s}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new st)}),this.clear()}async onEmpty(e){this.size!==0&&await ot(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await ot(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await ot(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 t=Lt({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},s=c=>{c.detail!=null&&t.push(c.detail)},o=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new st("Queue aborted"))};this.addEventListener("completed",s),this.addEventListener("failure",o),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",s),this.removeEventListener("failure",o),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var Dp=Math.pow(2,20)*4,Mo=class extends Ie{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;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??Dp,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new ee,this.writeBuffer=new ee,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 t=()=>{this.writableNeedsDrain&&(this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,queueMicrotask(()=>{try{this.processSendQueue()}catch(s){this.log.error("processSendQueue threw - %e",s)}})),this.onDrainPromise?.resolve()};this.addEventListener("drain",t);let n=s=>{this.onDrainPromise?.reject(s.error??new Po)};this.addEventListener("close",n)}get readBufferLength(){return this.readBuffer.byteLength}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),Bt(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let e=Lt(),t=o=>{e.push(o.data)};this.addEventListener("message",t);let n=o=>{e.end(o.error)};this.addEventListener("close",n);let s=()=>{e.end()};this.addEventListener("remoteCloseWrite",s);try{yield*e}finally{this.removeEventListener("message",t),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",s)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new yt(`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();try{this.sendReset(e)}catch(t){this.log("failed to send reset to remote - %e",t)}this.dispatchEvent(new On(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new yt("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 yt("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 yt(`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 yt(`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");let e=new In;this.dispatchEvent(new Pn(e))}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.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.dispatchEvent(new cr))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),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,t=this.writeBuffer.byteLength,n=0;for(;this.writeBuffer.byteLength>0;){let s=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(s===0){e=!1;break}let o=this.writeBuffer.sublist(0,s),i=new ee(o);this.writeBuffer.consume(o.byteLength);let a;try{a=this.sendData(o)}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,t,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),e}finally{this.sendingData=!1}}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 Rn(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.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new Fr(`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 Fr(`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",t=>{this.metrics?.increment({[`${this.metricPrefix}end`]:!0}),t.error!=null?t.local?this.metrics?.increment({[`${this.metricPrefix}abort`]:!0}):this.metrics?.increment({[`${this.metricPrefix}reset`]:!0}):t.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 ot(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 ot(this,"drain",{...e,rejectionEvents:["close"]})),await this.sendClose(e),this.onTransportClosed())}};function Ko(r){let e=new globalThis.AbortController;function t(){let o=r.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();e.abort(o);for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}for(let o of r){if(o?.aborted===!0){t();break}o?.addEventListener!=null&&o.addEventListener("abort",t)}function n(){for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",t)}let s=e.signal;return s.clear=n,s}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,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){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 Bt(this.readNext.promise,t?.signal,t)}};function _l(){return new Ta}function Cp(r){return r[Symbol.asyncIterator]!=null}async function Lp(r,e,t){try{await Promise.all(r.map(async n=>{for await(let s of n)await e.push(s,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*Bp(r){let e=new AbortController,t=_l();Lp(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*Rp(r){for(let e of r)yield*e}function Op(...r){let e=[];for(let t of r)Cp(t)||e.push(t);return e.length===r.length?Rp(e):Bp(r)}var Al=Op;function Tl(r,...e){if(r==null)throw new Error("Empty pipeline");if(Ia(r)){let n=r;r=()=>n.source}else if(Dl(r)||Il(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&Ia(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let n=1;n<t.length-1;n++)Ia(t[n])&&(t[n]=Np(t[n]));return Pp(...t)}var Pp=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},Il=r=>r?.[Symbol.asyncIterator]!=null,Dl=r=>r?.[Symbol.iterator]!=null,Ia=r=>r==null?!1:r.sink!=null&&r.source!=null,Np=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=Lt({objectMode:!0});t.then(()=>{n.end()},i=>{n.end(i)});let s,o=r.source;if(Il(o))s=async function*(){yield*o,n.end()};else if(Dl(o))s=function*(){yield*o,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Al(n,s())}return r.source};var Up=4194304,qo=class extends Error{static name="UnwrappedError";name="UnwrappedError"},Ca=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},La=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ba=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function kp(r){return typeof r?.closeRead=="function"}function Mp(r){return typeof r?.close=="function"}function Da(r){return kp(r)?r.remoteWriteStatus!=="writable"&&r.readBufferLength===0:Mp(r)?r.status!=="open":!1}function Fp(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function Kp(r,e){let t=e?.maxBufferSize??Up,n=new ee,s,o=!1;if(!Fp(r))throw new oe("Argument should be a Stream or a Multiaddr");let i=l=>{if(n.append(l.data),n.byteLength>t){let f=n.byteLength;n.consume(n.byteLength),s?.reject(new Error(`Read buffer overflow - ${f} > ${t}`))}s?.resolve()};r.addEventListener("message",i);let a=l=>{l.error!=null?s?.reject(l.error):s?.resolve()};r.addEventListener("close",a);let c=()=>{s?.resolve()};r.addEventListener("remoteCloseWrite",c);let u={readBuffer:n,async read(l){if(o===!0)throw new qo("Stream was unwrapped");if(Da(r)){if(n.byteLength===0&&l?.bytes==null)return null;if(l?.bytes!=null&&n.byteLength<l.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,l.bytes),new rr(`Unexpected EOF - stream closed after reading ${n.byteLength}/${l.bytes} bytes`)}let f=l?.bytes??1;for(s=Promise.withResolvers();;){if(n.byteLength>=f){s.resolve();break}if(await Bt(s.promise,l?.signal),Da(r)){if(n.byteLength===0&&l?.bytes==null)return null;break}s=Promise.withResolvers()}let m=l?.bytes??n.byteLength;if(n.byteLength<m){if(Da(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,m),new rr(`Unexpected EOF - stream closed while reading ${n.byteLength}/${m} bytes`);return u.read(l)}let d=n.sublist(0,m);return n.consume(m),d},async write(l,f){if(o===!0)throw new qo("Stream was unwrapped");r.send(l)||await ot(r,"drain",{signal:f?.signal,rejectionEvents:["close"]})},unwrap(){return o||(o=!0,r.removeEventListener("message",i),r.removeEventListener("close",a),r.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.unshift(n))),r}};return u}function qp(r,e={}){let t=Kp(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=Ce(e.maxDataLength));let n=e?.lengthDecoder??sn,s=e?.lengthEncoder??Tr;return{async read(i){let a=-1,c=new ee;for(;;){let l=await t.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 Ba(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new La(`Message length too long - ${a} > ${e.maxDataLength}`);let u=await t.read({...i,bytes:a});if(u==null)throw r.log.error("tried to read %d bytes but the stream closed",a),new rr(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(u.byteLength!==a)throw r.log.error("read %d/%d bytes before the stream closed",u.byteLength,a),new rr(`Unexpected EOF - read ${u.byteLength}/${a} bytes before the stream closed`);return u},async write(i,a){await t.write(new ee(s(i.byteLength),i),a)},async writeV(i,a){let c=new ee(...i.flatMap(u=>[s(u.byteLength),u]));await t.write(c,a)},unwrap(){return t.unwrap()}}}function Rt(r,e){let t=qp(r,e),n={read:async(s,o)=>{let i=await t.read(o);return s.decode(i,o)},write:async(s,o,i)=>{await t.write(o.encode(s),i)},writeV:async(s,o,i)=>{await t.writeV(s.map(a=>o.encode(a)),i)},pb:s=>({read:async o=>n.read(s,o),write:async(o,i)=>n.write(o,s,i),writeV:async(o,i)=>n.writeV(o,s,i),unwrap:()=>n}),unwrap:()=>t.unwrap()};return n}function zp(r){return r?.addEventListener!=null}function Vp(r){let e=Lt(),t,n=i=>{e.push(i.data)},s=()=>{e.end(),r.removeEventListener("message",n),r.removeEventListener("close",o),r.removeEventListener("remoteCloseWrite",s)},o=i=>{e.end(i.error),i.error!=null&&t?.reject(i.error),r.removeEventListener("message",n),r.removeEventListener("close",o),r.removeEventListener("remoteCloseWrite",s)};return r.addEventListener("message",n),r.addEventListener("close",o,{once:!0}),r.addEventListener("remoteCloseWrite",s,{once:!0}),{source:e,async sink(i){async function*a(){yield*i}let c=a();for(;;){t=Promise.withResolvers();let{done:u,value:l}=await Promise.race([c.next(),t.promise]);if(r.writeStatus==="closing"||r.writeStatus==="closed"||(l!=null&&(r.send(l)||await Promise.race([ot(r,"drain",{rejectionEvents:["close"]})])),u===!0))break}await r.close()}}}function Cl(...r){let e=r.map(t=>zp(t)?Vp(t):t);return Tl(...e)}var kr=class extends ko{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var Ra=1e3,Ll=60*Ra,Bl=15,Rl=120*Ll,Ol=1,zo=5e3,Pl=100,Oa="circuit-relay-source",xn=`${Wa}-circuit-relay`,Nl=2*Ll,Ul=BigInt(1<<17),Ke="/libp2p/circuit/relay/0.2.0/hop",nr="/libp2p/circuit/relay/0.2.0/stop",kl=30*Ra,F2=30*Ra,En=300,Ml=4096,Fl=.001;var Z;(function(r){let e;(function(a){a.RESERVE="RESERVE",a.CONNECT="CONNECT",a.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(a){a[a.RESERVE=0]="RESERVE",a[a.CONNECT=1]="CONNECT",a[a.STATUS=2]="STATUS"})(t||(t={})),(function(a){a.codec=()=>jt(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Oe((a,c,u={})=>{u.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),r.Type.codec().encode(a.type,c)),a.peer!=null&&(c.uint32(18),Ot.codec().encode(a.peer,c)),a.reservation!=null&&(c.uint32(26),Sn.codec().encode(a.reservation,c)),a.limit!=null&&(c.uint32(34),Pt.codec().encode(a.limit,c)),a.status!=null&&(c.uint32(40),K.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 m=a.uint32();switch(m>>>3){case 1:{l.type=r.Type.codec().decode(a);break}case 2:{l.peer=Ot.codec().decode(a,a.uint32(),{limits:u.limits?.peer});break}case 3:{l.reservation=Sn.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=K.codec().decode(a);break}default:{a.skipType(m&7);break}}}return l},function*(a,c,u,l={}){let f=c==null?a.len:a.pos+c;for(;a.pos<f;){let m=a.uint32();switch(m>>>3){case 1:{yield{field:`${u}.type`,value:r.Type.codec().decode(a)};break}case 2:{yield*Ot.codec().stream(a,a.uint32(),`${u}.peer`,{limits:l.limits?.peer});break}case 3:{yield*Sn.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:K.codec().decode(a)};break}default:{a.skipType(m&7);break}}}})),n);function s(a){return Be(a,r.codec())}r.encode=s;function o(a,c){return Le(a,r.codec(),c)}r.decode=o;function i(a,c){return Re(a,r.codec(),c)}r.stream=i})(Z||(Z={}));var ke;(function(r){let e;(function(a){a.CONNECT="CONNECT",a.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(a){a[a.CONNECT=0]="CONNECT",a[a.STATUS=1]="STATUS"})(t||(t={})),(function(a){a.codec=()=>jt(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Oe((a,c,u={})=>{u.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),r.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),K.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 m=a.uint32();switch(m>>>3){case 1:{l.type=r.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=K.codec().decode(a);break}default:{a.skipType(m&7);break}}}return l},function*(a,c,u,l={}){let f=c==null?a.len:a.pos+c;for(;a.pos<f;){let m=a.uint32();switch(m>>>3){case 1:{yield{field:`${u}.type`,value:r.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:K.codec().decode(a)};break}default:{a.skipType(m&7);break}}}})),n);function s(a){return Be(a,r.codec())}r.encode=s;function o(a,c){return Le(a,r.codec(),c)}r.decode=o;function i(a,c){return Re(a,r.codec(),c)}r.stream=i})(ke||(ke={}));var Ot;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((o,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),o.id!=null&&o.id.byteLength>0&&(i.uint32(10),i.bytes(o.id)),o.addrs!=null&&o.addrs.length>0)for(let c of o.addrs)i.uint32(18),i.bytes(c);a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={id:J(0),addrs:[]},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{c.id=o.bytes();break}case 2:{if(a.limits?.addrs!=null&&c.addrs.length===a.limits.addrs)throw new Yt('Decode error - repeated field "addrs" had too many elements');c.addrs.push(o.bytes());break}default:{o.skipType(l&7);break}}}return c},function*(o,i,a,c={}){let u={addrs:0},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let f=o.uint32();switch(f>>>3){case 1:{yield{field:`${a}.id`,value:o.bytes()};break}case 2:{if(c.limits?.addrs!=null&&u.addrs===c.limits.addrs)throw new Yt('Streaming decode error - repeated field "addrs" had too many elements');yield{field:`${a}.addrs[]`,index:u.addrs,value:o.bytes()},u.addrs++;break}default:{o.skipType(f&7);break}}}})),e);function t(o){return Be(o,r.codec())}r.encode=t;function n(o,i){return Le(o,r.codec(),i)}r.decode=n;function s(o,i){return Re(o,r.codec(),i)}r.stream=s})(Ot||(Ot={}));var Sn;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((o,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),o.expire!=null&&o.expire!==0n&&(i.uint32(8),i.uint64(o.expire)),o.addrs!=null&&o.addrs.length>0)for(let c of o.addrs)i.uint32(18),i.bytes(c);o.voucher!=null&&(i.uint32(26),vn.codec().encode(o.voucher,i)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={expire:0n,addrs:[]},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{c.expire=o.uint64();break}case 2:{if(a.limits?.addrs!=null&&c.addrs.length===a.limits.addrs)throw new Yt('Decode error - repeated field "addrs" had too many elements');c.addrs.push(o.bytes());break}case 3:{c.voucher=vn.codec().decode(o,o.uint32(),{limits:a.limits?.voucher});break}default:{o.skipType(l&7);break}}}return c},function*(o,i,a,c={}){let u={addrs:0},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let f=o.uint32();switch(f>>>3){case 1:{yield{field:`${a}.expire`,value:o.uint64()};break}case 2:{if(c.limits?.addrs!=null&&u.addrs===c.limits.addrs)throw new Yt('Streaming decode error - repeated field "addrs" had too many elements');yield{field:`${a}.addrs[]`,index:u.addrs,value:o.bytes()},u.addrs++;break}case 3:{yield*vn.codec().stream(o,o.uint32(),`${a}.voucher`,{limits:c.limits?.voucher});break}default:{o.skipType(f&7);break}}}})),e);function t(o){return Be(o,r.codec())}r.encode=t;function n(o,i){return Le(o,r.codec(),i)}r.decode=n;function s(o,i){return Re(o,r.codec(),i)}r.stream=s})(Sn||(Sn={}));var Pt;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.duration!=null&&(i.uint32(8),i.uint32(o.duration)),o.data!=null&&(i.uint32(16),i.uint64(o.data)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{c.duration=o.uint32();break}case 2:{c.data=o.uint64();break}default:{o.skipType(l&7);break}}}return c},function*(o,i,a,c={}){let u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{yield{field:`${a}.duration`,value:o.uint32()};break}case 2:{yield{field:`${a}.data`,value:o.uint64()};break}default:{o.skipType(l&7);break}}}})),e);function t(o){return Be(o,r.codec())}r.encode=t;function n(o,i){return Le(o,r.codec(),i)}r.decode=n;function s(o,i){return Re(o,r.codec(),i)}r.stream=s})(Pt||(Pt={}));var K;(function(r){r.UNUSED="UNUSED",r.OK="OK",r.RESERVATION_REFUSED="RESERVATION_REFUSED",r.RESOURCE_LIMIT_EXCEEDED="RESOURCE_LIMIT_EXCEEDED",r.PERMISSION_DENIED="PERMISSION_DENIED",r.CONNECTION_FAILED="CONNECTION_FAILED",r.NO_RESERVATION="NO_RESERVATION",r.MALFORMED_MESSAGE="MALFORMED_MESSAGE",r.UNEXPECTED_MESSAGE="UNEXPECTED_MESSAGE"})(K||(K={}));var Pa;(function(r){r[r.UNUSED=0]="UNUSED",r[r.OK=100]="OK",r[r.RESERVATION_REFUSED=200]="RESERVATION_REFUSED",r[r.RESOURCE_LIMIT_EXCEEDED=201]="RESOURCE_LIMIT_EXCEEDED",r[r.PERMISSION_DENIED=202]="PERMISSION_DENIED",r[r.CONNECTION_FAILED=203]="CONNECTION_FAILED",r[r.NO_RESERVATION=204]="NO_RESERVATION",r[r.MALFORMED_MESSAGE=400]="MALFORMED_MESSAGE",r[r.UNEXPECTED_MESSAGE=401]="UNEXPECTED_MESSAGE"})(Pa||(Pa={}));(function(r){r.codec=()=>jt(Pa)})(K||(K={}));var or;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.relay!=null&&o.relay.byteLength>0&&(i.uint32(10),i.bytes(o.relay)),o.peer!=null&&o.peer.byteLength>0&&(i.uint32(18),i.bytes(o.peer)),o.expiration!=null&&o.expiration!==0n&&(i.uint32(24),i.uint64(o.expiration)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={relay:J(0),peer:J(0),expiration:0n},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{c.relay=o.bytes();break}case 2:{c.peer=o.bytes();break}case 3:{c.expiration=o.uint64();break}default:{o.skipType(l&7);break}}}return c},function*(o,i,a,c={}){let u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{yield{field:`${a}.relay`,value:o.bytes()};break}case 2:{yield{field:`${a}.peer`,value:o.bytes()};break}case 3:{yield{field:`${a}.expiration`,value:o.uint64()};break}default:{o.skipType(l&7);break}}}})),e);function t(o){return Be(o,r.codec())}r.encode=t;function n(o,i){return Le(o,r.codec(),i)}r.decode=n;function s(o,i){return Re(o,r.codec(),i)}r.stream=s})(or||(or={}));var vn;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.publicKey!=null&&o.publicKey.byteLength>0&&(i.uint32(10),i.bytes(o.publicKey)),o.payloadType!=null&&o.payloadType.byteLength>0&&(i.uint32(18),i.bytes(o.payloadType)),o.payload!=null&&(i.uint32(26),or.codec().encode(o.payload,i)),o.signature!=null&&o.signature.byteLength>0&&(i.uint32(42),i.bytes(o.signature)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={publicKey:J(0),payloadType:J(0),signature:J(0)},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{c.publicKey=o.bytes();break}case 2:{c.payloadType=o.bytes();break}case 3:{c.payload=or.codec().decode(o,o.uint32(),{limits:a.limits?.payload});break}case 5:{c.signature=o.bytes();break}default:{o.skipType(l&7);break}}}return c},function*(o,i,a,c={}){let u=i==null?o.len:o.pos+i;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{yield{field:`${a}.publicKey`,value:o.bytes()};break}case 2:{yield{field:`${a}.payloadType`,value:o.bytes()};break}case 3:{yield*or.codec().stream(o,o.uint32(),`${a}.payload`,{limits:c.limits?.payload});break}case 5:{yield{field:`${a}.signature`,value:o.bytes()};break}default:{o.skipType(l&7);break}}}})),e);function t(o){return Be(o,r.codec())}r.encode=t;function n(o,i){return Le(o,r.codec(),i)}r.decode=n;function s(o,i){return Re(o,r.codec(),i)}r.stream=s})(vn||(vn={}));var Vo=class extends Error{constructor(e="Transfer limit error"){super(e),this.name="TransferLimitError"}},Ho=class extends Error{constructor(e="Duration limit error"){super(e),this.name="DurationLimitError"}},_n=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 Kl(r,e,t){let n=e.remaining,s=o=>{let i=BigInt(o.data.byteLength);e.remaining-=i,e.remaining<0&&r.abort(new Vo(`data limit of ${n} bytes exceeded`))};r.addEventListener("message",s)}function ql(r,e,t,n,s){function o(l){r.abort(l),e.abort(l)}let i=[t,n.signal];if(n.limit?.duration!=null){s.log("limiting relayed connection duration to %dms",n.limit.duration);let l=AbortSignal.timeout(n.limit.duration);i.push(l)}let a=Ko(i);let c;n.limit?.data!=null&&(c={remaining:n.limit.data});let u=()=>{let l;t.aborted?l=t.reason:l=new Ho(`duration limit of ${n.limit?.duration} ms exceeded`),o(l)};a.addEventListener("abort",u,{once:!0}),c!=null&&(Kl(e,c,s),Kl(r,c,s)),Cl(r,e,r).catch(l=>{o(l)}).finally(()=>{a.clear()})}function Na(r){let e=r*BigInt(1e3),t=new Date().getTime();return Number(e-BigInt(t))}var An=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 t=this;Object.defineProperty(e,"bytes",{get(){return t.bytes}})}if(this.expires!=null){let t=this;Object.defineProperty(e,"seconds",{get(){return Math.round(((t.expires??0)-Date.now())/1e3)}})}return e}},Go=Q(W(Sl.matchers[0],X(290))),jo=Q(X(290));function Yo(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),s=n.value;return n.done===!0||s==null?{done:!0,value:void 0}:{done:!1,value:e(s)}}};return t}var Nt=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),{key:t,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return Yo(this.map.entries(),e=>[e[1].key,e[1].value])}forEach(e){this.map.forEach((t,n)=>{e(t.value,t.key,this)})}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),{key:e,value:t})}keys(){return Yo(this.map.values(),e=>e.key)}values(){return Yo(this.map.values(),e=>e.value)}get size(){return this.map.size}};var Zo=class{filter;constructor(e,t){this.filter=Pr(e,t)}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 Ua(r,e=.001){return new Zo(r,e)}var ka=class extends Nt{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Ma(r){let{name:e,metrics:t}=r,n;return t!=null?n=new ka({name:e,metrics:t}):n=new Nt,n}var Fa=class extends Error{type;code;constructor(e,t,n){super(e??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=t??"ABORT_ERR"}};function zl(r,e){let t=new Fa(e?.errorMessage,e?.errorCode,e?.errorName),n=new AbortController,s=()=>{n.abort(t)},o=AbortSignal.timeout(r);o.addEventListener("abort",s);let i=n.signal;return i.reset=a=>{o?.removeEventListener("abort",s),o=AbortSignal.timeout(a??r),o.addEventListener("abort",()=>{n.abort(t)})},i.clear=()=>{o?.removeEventListener("abort",s),o=void 0},i}var Xo=class{reservations;maxReservations;applyDefaultLimit;reservationTtl;defaultDurationLimit;defaultDataLimit;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:circuit-relay:server:reservation-store"),this.maxReservations=t.maxReservations??Bl,this.applyDefaultLimit=t.applyDefaultLimit!==!1,this.reservationTtl=t.reservationTtl??Rl,this.defaultDurationLimit=t.defaultDurationLimit??Nl,this.defaultDataLimit=t.defaultDataLimit??Ul,this.reservations=Ma({metrics:e.metrics,name:"libp2p_circuit_relay_server_reservations_total"})}reserve(e,t,n){let s=this.reservations.get(e);if(this.reservations.size>=this.maxReservations&&s==null)return{status:K.RESERVATION_REFUSED};let o=new Date(Date.now()+this.reservationTtl),i;return this.applyDefaultLimit&&(i=n??{data:this.defaultDataLimit,duration:this.defaultDurationLimit}),s!=null?(this.log("refreshing reservation for client %p",e),s.signal.reset(this.reservationTtl)):(this.log("creating new reservation for client %p",e),s={addr:t,expiry:o,limit:i,signal:zl(this.reservationTtl)},s.signal.addEventListener("abort",()=>{this.reservations.delete(e)})),this.reservations.set(e,s),{status:K.OK,expire:Math.round(o.getTime()/1e3)}}removeReservation(e){this.reservations.delete(e)}get(e){return this.reservations.get(e)}clear(){this.reservations.clear()}};var Qo=class r{domain="libp2p-relay-rsvp";codec=new Uint8Array([3,2]);relay;peer;expiration;constructor({relay:e,peer:t,expiration:n}){this.relay=e,this.peer=t,this.expiration=n}marshal(){return or.encode({relay:this.relay.toMultihash().bytes,peer:this.peer.toMultihash().bytes,expiration:BigInt(this.expiration)})}equals(e){return!(!(e instanceof r)||!this.peer.equals(e.peer)||!this.relay.equals(e.relay)||this.expiration!==e.expiration)}};var Hp={maxOutboundStopStreams:En},Jo=class extends Ie{components;reservationStore;started;hopTimeout;shutdownController;maxInboundHopStreams;maxOutboundHopStreams;maxOutboundStopStreams;log;constructor(e,t={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:server"),this.components=e,this.started=!1,this.hopTimeout=t?.hopTimeout??kl,this.maxInboundHopStreams=t.maxInboundHopStreams,this.maxOutboundHopStreams=t.maxOutboundHopStreams,this.maxOutboundStopStreams=t.maxOutboundStopStreams??Hp.maxOutboundStopStreams,this.reservationStore=new Xo(e,t.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(Ke,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(Ke),this.started=!1}async onHop(e,t){this.log("received circuit v2 hop protocol stream from %p",t.remotePeer);let n=AbortSignal.timeout(this.hopTimeout);let s={signal:n},o=Rt(e);try{let i=await o.pb(Z).read(s);if(i?.type==null)throw new Error("request was invalid, could not read from stream");this.log("received",i.type),await this.handleHopProtocol({connection:t,stream:o,request:i},s)}catch(i){this.log.error("error while handling hop - %e",i),await o.pb(Z).write({type:Z.Type.STATUS,status:K.MALFORMED_MESSAGE},s),e.abort(i)}}async handleHopProtocol({stream:e,request:t,connection:n},s){switch(this.log("received hop message"),t.type){case Z.Type.RESERVE:await this.handleReserve({stream:e,request:t,connection:n},s);break;case Z.Type.CONNECT:await this.handleConnect({stream:e,request:t,connection:n},s);break;default:this.log.error("invalid hop request type %s via peer %p",t.type,n.remotePeer),await e.pb(Z).write({type:Z.Type.STATUS,status:K.UNEXPECTED_MESSAGE})}}async handleReserve({stream:e,connection:t},n){let s=e.pb(Z);if(this.log("hop reserve request from %p",t.remotePeer),tr.exactMatch(t.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",t.remotePeer),await s.write({type:Z.Type.STATUS,status:K.PERMISSION_DENIED},n);return}if(await this.components.connectionGater.denyInboundRelayReservation?.(t.remotePeer)===!0){this.log.error("reservation for %p denied by connection gater",t.remotePeer),await s.write({type:Z.Type.STATUS,status:K.PERMISSION_DENIED},n);return}let o=this.reservationStore.reserve(t.remotePeer,t.remoteAddr);try{if(o.status!==K.OK){await s.write({type:Z.Type.STATUS,status:o.status},n);return}if(o.expire!=null){let i=o.expire*1e3-Date.now();await this.components.peerStore.merge(t.remotePeer,{tags:{[Oa]:{value:1,ttl:i}}},n)}await s.write({type:Z.Type.STATUS,status:K.OK,reservation:await this.makeReservation(t.remotePeer,BigInt(o.expire??0)),limit:this.reservationStore.get(t.remotePeer)?.limit},n),this.log("sent confirmation response to %s",t.remotePeer),await s.unwrap().unwrap().close(n)}catch(i){this.log.error("failed to send confirmation response to %p - %e",t.remotePeer,i),this.reservationStore.removeReservation(t.remotePeer);try{await this.components.peerStore.merge(t.remotePeer,{tags:{[Oa]:void 0}},n)}catch(a){this.log.error("failed to untag relay source peer %p - %e",t.remotePeer,a)}}}async makeReservation(e,t){let n=[];for(let o of this.components.addressManager.getAddresses())o.toString().includes("/p2p-circuit")||n.push(o.bytes);let s=await mn.seal(new Qo({peer:e,relay:this.components.peerId,expiration:t}),this.components.privateKey);return{addrs:n,expire:t,voucher:{publicKey:Je(s.publicKey),payloadType:s.payloadType,payload:{peer:e.toMultihash().bytes,relay:this.components.peerId.toMultihash().bytes,expiration:t},signature:s.signature}}}async handleConnect({stream:e,request:t,connection:n},s){let o=e.pb(Z);if(tr.matches(n.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",n.remotePeer),await o.write({type:Z.Type.STATUS,status:K.PERMISSION_DENIED},s);return}this.log("hop connect request from %p",n.remotePeer);let i;try{if(t.peer==null)throw this.log.error("no peer info in hop connect request"),new Error("no peer info in request");t.peer.addrs.forEach(Ue),i=Cr(Xe(t.peer.id))}catch(f){this.log.error("invalid hop connect request via peer %p - %e",n.remotePeer,f),await o.write({type:Z.Type.STATUS,status:K.MALFORMED_MESSAGE},s);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,K.NO_RESERVATION),await o.write({type:Z.Type.STATUS,status:K.NO_RESERVATION},s);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 o.write({type:Z.Type.STATUS,status:K.PERMISSION_DENIED},s);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 o.write({type:Z.Type.STATUS,status:K.NO_RESERVATION},s);return}let u=c[0],l=await this.stopHop({connection:u,request:{type:ke.Type.CONNECT,peer:{id:n.remotePeer.toMultihash().bytes,addrs:[]},limit:a?.limit}},s);if(l==null){this.log.error("failed to open stream to destination peer %p",u?.remotePeer),await o.write({type:Z.Type.STATUS,status:K.CONNECTION_FAILED},s);return}await o.write({type:Z.Type.STATUS,status:K.OK,limit:a?.limit},s),this.log("connection from %p to %p established - merging streams",n.remotePeer,i),ql(e.unwrap(),l,this.shutdownController.signal,a,{log:this.log})}async stopHop({connection:e,request:t},n){this.log("starting circuit relay v2 stop request to %s",e.remotePeer);let s=await e.newStream(nr,{maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0,...n}),o=Rt(s),i=o.pb(ke);await i.write(t,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 s.close(n);return}if(a.status===K.OK)return this.log("stop request to %p was successful",e.remotePeer),o.unwrap();this.log("stop request failed with code %d",a.status),await s.close(n)}get reservations(){return this.reservationStore.reservations}};var Ut=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var es=class extends Ie{components;started;running;topologyId;log;discoveryController;filter;queue;constructor(e,t={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:discover-relays"),this.components=e,this.started=!1,this.running=!1,this.filter=t.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(Ke,{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(Ke)],orders:[()=>Math.random()<.5?1:-1,(n,s)=>{let o=Vl(n),i=Vl(s);return o>i?-1:i>o?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 t=this.queue=new kr({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),t.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(s=>s.toString()));continue}t.queued>10&&(this.log.trace("wait for space in queue for %p",n.id),await t.onSizeLessThan(10,{signal:this.discoveryController.signal})),this.log("adding random peer %p to dial queue (length: %d, active %d)",n.id,t.size,t.running),t.add(this.dialPeer,{peerId:n.id,signal:this.discoveryController.signal}).catch(s=>{this.log.error("error opening connection to random peer %p - %e",n.id,s)})}this.log("stop random walk"),await t.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(t=>{this.log.trace("error dialing discovered peer %p - %e",e.detail.id,t)})}async maybeDialPeer(e){if(this.queue==null)return;let t=e.detail.id,n=e.detail.multiaddrs;if(this.queue.has(t)){this.log.trace("random peer %p was already in queue",t);return}if(this.components.connectionManager.getConnections(t)?.length>0){this.log.trace("random peer %p was already connected",t);return}if(!await this.components.connectionManager.isDialable(n)){this.log.trace("random peer %p was not dialable",t);return}this.queue?.add(this.dialPeer,{peerId:e.detail.id,signal:this.discoveryController.signal}).catch(s=>{this.log.error("error opening connection to discovered peer %p - %e",e.detail.id,s)})}async dialPeer({peerId:e,signal:t}){let n=Ko([AbortSignal.timeout(5e3),t]);try{await this.components.connectionManager.openConnection(e,{signal:n})}finally{n.clear()}}};function Vl(r){let e=r.metadata.get("last-dial-success");return e==null?0:new Date(H(e)).getTime()}var qa=class extends Ie{connectionManager;addressManager;reservationStore;listeningAddrs;log;listenTimeout;reservationId;relay;constructor(e,t={}){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=t.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(t=>{this.addressManager.removeObservedAddr(t)}),this.listeningAddrs=[],this.safeDispatchEvent("listening"))};_onAddRelayPeer=e=>{let{details:t}=e.detail;if(t.type==="configured"){this.relay?.equals(e.detail.relay)===!0&&this.addedRelay(e.detail);return}t.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(Go.exactMatch(e)){this.log("listen on specific relay server %a",e);let t=AbortSignal.timeout(this.listenTimeout);let n=e.decapsulate("/p2p-circuit"),s=await this.connectionManager.openConnection(n,{signal:t});if(!this.reservationStore.hasReservation(s.remotePeer)){this.log("making reservation on peer %p",s.remotePeer);let o=await this.reservationStore.addRelay(s.remotePeer,"configured");this.addedRelay(o)}}else throw new kt(`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 t=this.listeningAddrs;this.listeningAddrs=e.details.reservation.addrs.map(n=>Ue(n).encapsulate("/p2p-circuit")),this.listeningAddrs.forEach(n=>{this.addressManager.confirmObservedAddr(n,{type:"transport"})}),t.filter(n=>!this.listeningAddrs.some(s=>s.equals(n))).forEach(n=>{this.addressManager.removeObservedAddr(n)}),queueMicrotask(()=>{this.safeDispatchEvent("listening")})}};function Hl(r){return new qa(r)}var $l="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Wl=(r=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)e+=$l[t[r]&63];return e};var $p=60*1e3*10,Wp=60*1e3*5,Gp=30*1e3,ts=class extends Ie{peerId;connectionManager;peerStore;events;reserveQueue;reservations;pendingReservations;maxReservationQueueLength;reservationCompletionTimeout;started;log;relayFilter;constructor(e,t){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=t?.maxReservationQueueLength??Pl,this.reservationCompletionTimeout=t?.reservationCompletionTimeout??zo,this.started=!1,this.relayFilter=Pr(100),this.reserveQueue=new kr({concurrency:t?.reservationConcurrency??Ol,metricName:"libp2p_relay_reservation_queue",metrics:e.metrics}),this.events.addEventListener("connection:close",n=>{[...this.reservations.values()].find(o=>o.connection===n.detail.id)!=null&&this.#t(n.detail.remotePeer).catch(o=>{this.log.error("could not remove relay %p - %e",n.detail.remotePeer,o)})})}isStarted(){return this.started}start(){this.started=!0}afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>t.tags.has(xn)]});this.log("removing tag from %d old relays",e.length),await Promise.all(e.map(async t=>{await this.peerStore.merge(t.id,{tags:{[xn]:void 0}})})),this.log("redialing %d old relays",e.length),await Promise.all(e.map(async t=>this.addRelay(t.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=Wl();return this.pendingReservations.push(e),this.#r(),e}async addRelay(e,t){if(this.peerId.equals(e))throw this.log.trace("not trying to use self as relay"),new kt("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 kt("The relay was previously invalid");return this.log.trace("try to reserve relay slot with %p",e),this.reserveQueue.add(async()=>{let s=Date.now();try{let o=this.reservations.get(e);if(o!=null){let x=this.connectionManager.getConnections(e),S=!1;if(x.length===0&&this.log("already have relay reservation with %p but we are no longer connected",e),x.map(h=>h.id).includes(o.connection)&&(this.log("already have relay reservation with %p and the original connection is still open",e),S=!0),S&&Na(o.reservation.expire)>$p)return this.log("already have relay reservation with %p but we are still connected and it does not expire soon",e),{relay:e,details:o};S||await this.#t(e)}if(t==="discovered"&&o==null&&this.pendingReservations.length===0)throw new _n("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(tr.matches(a.remoteAddr))throw new $o("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-Wp,Gp),Math.pow(2,31)-1),f=setTimeout(()=>{this.log("refresh reservation to relay %p",e),this.addRelay(e,t).catch(async x=>{this.log.error("could not refresh reservation to relay %p - %e",e,x),await this.#t(e)}).catch(x=>{this.log.error("could not remove expired reservation to relay %p - %e",e,x)})},l),m;if(t==="discovered"){let x=this.reservations.get(e),S=x?.type==="discovered"?x.id:this.pendingReservations.pop();if(S==null)throw new _n("Made reservation on relay but did not need any more discovered relays");m={timeout:f,reservation:c,type:t,connection:a.id,id:S}}else m={timeout:f,reservation:c,type:t,connection:a.id};o!=null&&clearTimeout(o.timeout),this.reservations.set(e,m),await this.peerStore.merge(e,{tags:{[xn]:{value:1,ttl:u}}}),this.#r();let d={relay:e,details:m};return this.safeDispatchEvent("relay:created-reservation",{detail:d}),d}catch(o){throw t==="discovered"&&o.name==="HadEnoughRelaysError"||this.log.error("could not reserve slot on %p after %dms - %e",e,Date.now()-s,o),(o.name==="DialError"||o.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)}),o}},{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((t,n)=>(n.type===e&&t++,t),0)}cancelReservations(){[...this.reservations.values()].forEach(e=>{clearTimeout(e.timeout)}),this.reservations.clear()}async#e(e,t){t.signal?.throwIfAborted(),this.log("requesting reservation from %p",e.remotePeer);let n=await e.newStream(Ke,t),o=Rt(n).pb(Z);this.log.trace("send RESERVE to %p",e.remotePeer),await o.write({type:Z.Type.RESERVE},t);let i;try{this.log.trace("reading response from %p",e.remotePeer),i=await o.read(t)}catch(c){throw n.abort(c),c}finally{n.status!=="closed"&&await n.close(t)}if(this.log.trace("read response %s",i.status),i.status===K.OK&&i.reservation!=null){let c=new Set;c.add(e.remoteAddr.toString());for(let u of i.reservation.addrs){let l=Ue(u);l.getComponents().find(f=>f.code===421)==null&&(l=l.encapsulate(`/p2p/${e.remotePeer}`)),l=Ue(l.toString().replace(`/p2p/${e.remotePeer}/p2p/${e.remotePeer}`,`/p2p/${e.remotePeer}`)),c.add(l.toString())}return i.reservation.addrs=[...c].map(u=>Ue(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 t=this.reservations.get(e);t!=null&&(this.log("removing relay reservation with %p from local store",e),clearTimeout(t.timeout),this.reservations.delete(e),t.type==="discovered"&&this.pendingReservations.push(t.id),this.safeDispatchEvent("relay:removed",{detail:{relay:e,details:t}}),this.#r(),await this.peerStore.merge(e,{tags:{[xn]: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=Pr(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",t=>{this.onTransportClosed(t.error)}),this.stream.addEventListener("remoteCloseWrite",t=>{this.onRemoteCloseWrite(),this.close().catch(n=>{this.abort(n)})}),this.stream.addEventListener("message",t=>{e.onDataRead?.(t.data),this.onData(t.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 Va(r){return new za(r)}var jp=r=>{if(r.peer==null)return!1;try{r.peer.addrs.forEach(Ue)}catch{return!1}return!0},Gl={maxInboundStopStreams:En,maxOutboundStopStreams:En,stopTimeout:3e4},rs=class{components;discovery;reservationStore;maxInboundStopStreams;maxOutboundStopStreams;started;log;shutdownController;constructor(e,t={}){this.components=e,this.log=e.logger.forComponent("libp2p:circuit-relay:transport"),this.maxInboundStopStreams=t.maxInboundStopStreams??Gl.maxInboundStopStreams,this.maxOutboundStopStreams=t.maxOutboundStopStreams??Gl.maxOutboundStopStreams,this.shutdownController=new AbortController,this.discovery=new es(e,{filter:t.discoveryFilter??Ua(Ml,Fl)}),this.discovery.addEventListener("relay:discover",n=>{this.reservationStore.addRelay(n.detail,"discovered").catch(s=>{s.name!=="HadEnoughRelaysError"&&s.name!=="RelayQueueFullError"&&this.log.error("could not add discovered relay %p - %e",n.detail,s)})}),this.reservationStore=new ts(e,t),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(nr,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 Ya(this.discovery,this.reservationStore),await this.components.registrar.unhandle(nr),this.started=!1}async dial(e,t){let n=e.toString().split("/p2p-circuit"),s=Ue(n[0]),o=Ue(n[n.length-1]),i=s.getComponents().find(d=>d.code===421)?.value,a=o.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 Bn(`C${d}`)}let c=Hi(i),u=Hi(a),f=this.components.connectionManager.getConnections(c)[0];f==null?(await this.components.peerStore.merge(c,{multiaddrs:[s]}),t.onProgress?.(new Ut("circuit-relay:open-connection")),f=await this.components.connectionManager.openConnection(c,t)):t.onProgress?.(new Ut("circuit-relay:reuse-connection"));let m;try{t.onProgress?.(new Ut("circuit-relay:open-hop-stream")),m=await f.newStream(Ke,t);let d=Rt(m).pb(Z);t.onProgress?.(new Ut("circuit-relay:write-connect-message")),await d.write({type:Z.Type.CONNECT,peer:{id:u.toMultihash().bytes,addrs:[Ue(o).bytes]}},t),t.onProgress?.(new Ut("circuit-relay:read-connect-response"));let x=await d.read(t);if(x.status!==K.OK)throw new Ln(`failed to connect via relay with status ${x?.status?.toString()??"undefined"}`);let S=new An(x.limit),h=Va({stream:d.unwrap().unwrap(),remoteAddr:e,localAddr:s.encapsulate(`/p2p-circuit/p2p/${this.components.peerId.toString()}`),onDataRead:S.onData,onDataWrite:S.onData,log:m.log.newScope("circuit-relay:connection")}),y=await this.components.upgrader.upgradeOutbound(h,{...t,limits:S.getLimits()});return y.log("outbound relayed connection established to %p with limits %o, over connection %s",y.remotePeer,x.limit??"none",f.id),y}catch(d){throw this.log.error("circuit relay dial to destination %p via relay %p failed - %e",u,c,d),m?.abort(d),d}}createListener(e){return Hl({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(t=>Go.exactMatch(t)||jo.exactMatch(t))}dialFilter(e){return e=Array.isArray(e)?e:[e],e.filter(t=>tr.exactMatch(t))}async onStop(e,t){let n=this.components.upgrader.createInboundAbortSignal(this.shutdownController.signal);try{if(!this.reservationStore.hasReservation(t.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([t.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 s=Rt(e).pb(ke),o=await s.read({signal:n});if(this.log("new circuit relay v2 stop stream from %p with type %s",t.remotePeer,o.type),o?.type===void 0){this.log.error("type was missing from circuit v2 stop protocol request from %s",t.remotePeer),await s.write({type:ke.Type.STATUS,status:K.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}if(o.type!==ke.Type.CONNECT){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await s.write({type:ke.Type.STATUS,status:K.UNEXPECTED_MESSAGE},{signal:n}),await e.close({signal:n});return}if(!jp(o)){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await s.write({type:ke.Type.STATUS,status:K.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}let i=Cr(Xe(o.peer.id));if(await this.components.connectionGater.denyInboundRelayedConnection?.(t.remotePeer,i)===!0){this.log.error("connection gater denied inbound relayed connection from %p",t.remotePeer),await s.write({type:ke.Type.STATUS,status:K.PERMISSION_DENIED},{signal:n}),await e.close({signal:n});return}this.log.trace("sending success response to %p",t.remotePeer),await s.write({type:ke.Type.STATUS,status:K.OK},{signal:n});let a=new An(o.limit),c=t.remoteAddr.encapsulate(`/p2p-circuit/p2p/${i.toString()}`),u=this.components.addressManager.getAddresses()[0],l=Va({stream:s.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,o.limit??"none",t.id)}finally{n?.clear()}}};function Yp(r={}){return e=>new Jo(e,r)}function Zp(r={}){return e=>new rs(e,r)}return Ql(Xp);})();
3
3
  /*! Bundled license information:
4
4
 
5
5
  @noble/curves/utils.js: