@libp2p/circuit-relay-v2 4.0.0-049bfa0fa → 4.0.0-55b7e5fea

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,18 +1,17 @@
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 Yo=Object.defineProperty;var Nl=Object.getOwnPropertyDescriptor;var Ul=Object.getOwnPropertyNames;var Ml=Object.prototype.hasOwnProperty;var Ae=(r,e)=>{for(var t in e)Yo(r,t,{get:e[t],enumerable:!0})},kl=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ul(e))!Ml.call(r,o)&&o!==t&&Yo(r,o,{get:()=>e[o],enumerable:!(n=Nl(e,o))||n.enumerable});return r};var Kl=r=>kl(Yo({},"__esModule",{value:!0}),r);var Hp={};Ae(Hp,{RELAY_V2_HOP_CODEC:()=>Ve,RELAY_V2_STOP_CODEC:()=>er,circuitRelayServer:()=>qp,circuitRelayTransport:()=>Vp});var Te=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){super.addEventListener(e,t,n);let o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==t),this.#e.set(e,o))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:o})=>!o),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var Je=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var ie=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},tr=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var Sn=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}};var Ot=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},Mr=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}};var vn=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},_n=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var An=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var Tn=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}},Nt=class extends Error{static name="ListenError";constructor(e="Listen error"){super(e),this.name="ListenError"}};var rr=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var In=class extends Event{data;constructor(e,t){super("message",t),this.data=e}},nr=class extends Event{error;local;constructor(e,t,n){super("close",n),this.error=t,this.local=e}},Cn=class extends nr{constructor(e,t){super(!0,e,t)}},Dn=class extends nr{constructor(e,t){super(!1,e,t)}};var Xo=Symbol.for("@libp2p/peer-id");var Na="keep-alive";function Ua(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function Ma(...r){let e=[];for(let t of r)Ua(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 ka(...r){let e=[];for(let t of r)Ua(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 qa=Symbol.for("@libp2p/transport");var Ka;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Ka||(Ka={}));var Va=Symbol.for("@libp2p/service-capabilities"),Ha=Symbol.for("@libp2p/service-dependencies");var ts={};Ae(ts,{base58btc:()=>te,base58flickr:()=>$l});var Sm=new Uint8Array(0);function Fa(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 et(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function za(r){return new TextEncoder().encode(r)}function Ga(r){return new TextDecoder().decode(r)}function ql(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function h(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var x=0,S=0,g=0,_=p.length;g!==_&&p[g]===0;)g++,x++;for(var w=(_-g)*l+1>>>0,C=new Uint8Array(w);g!==_;){for(var P=p[g],q=0,K=w-1;(P!==0||q<S)&&K!==-1;K--,q++)P+=256*C[K]>>>0,C[K]=P%a>>>0,P=P/a>>>0;if(P!==0)throw new Error("Non-zero carry");S=q,g++}for(var N=w-S;N!==w&&C[N]===0;)N++;for(var E=c.repeat(x);N<w;++N)E+=r.charAt(C[N]);return E}function f(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var x=0;if(p[x]!==" "){for(var S=0,g=0;p[x]===c;)S++,x++;for(var _=(p.length-x)*u+1>>>0,w=new Uint8Array(_);p[x];){var C=t[p.charCodeAt(x)];if(C===255)return;for(var P=0,q=_-1;(C!==0||P<g)&&q!==-1;q--,P++)C+=a*w[q]>>>0,w[q]=C%256>>>0,C=C/256>>>0;if(C!==0)throw new Error("Non-zero carry");g=P,x++}if(p[x]!==" "){for(var K=_-g;K!==_&&w[K]===0;)K++;for(var N=new Uint8Array(S+(_-K)),E=S;K!==_;)N[E++]=w[K++];return N}}}function d(p){var x=f(p);if(x)return x;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:f,decode:d}}var Vl=ql,Hl=Vl,Wa=Hl;var jo=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")}},Qo=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Za(this,e)}},Jo=class{decoders;constructor(e){this.decoders=e}or(e){return Za(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 Za(r,e){return new Jo({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var es=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new jo(e,t,n),this.decoder=new Qo(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function or({name:r,prefix:e,encode:t,decode:n}){return new es(r,e,t,n)}function wt({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=Wa(t,r);return or({prefix:e,name:r,encode:n,decode:s=>et(o(s))})}function Fl(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let u=0;u<o;++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,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function zl(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function Gl(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function ae({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=Gl(n);return or({prefix:e,name:r,encode(s){return zl(s,n,t)},decode(s){return Fl(s,o,t,r)}})}var te=wt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),$l=wt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var rs={};Ae(rs,{base32:()=>xt,base32hex:()=>Xl,base32hexpad:()=>Ql,base32hexpadupper:()=>Jl,base32hexupper:()=>jl,base32pad:()=>Zl,base32padupper:()=>Yl,base32upper:()=>Wl,base32z:()=>ef});var xt=ae({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Wl=ae({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Zl=ae({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Yl=ae({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Xl=ae({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),jl=ae({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Ql=ae({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Jl=ae({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),ef=ae({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var ns={};Ae(ns,{base36:()=>kr,base36upper:()=>tf});var kr=wt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),tf=wt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var rf=ja,Ya=128,nf=127,of=~nf,sf=Math.pow(2,31);function ja(r,e,t){e=e||[],t=t||0;for(var n=t;r>=sf;)e[t++]=r&255|Ya,r/=128;for(;r&of;)e[t++]=r&255|Ya,r>>>=7;return e[t]=r|0,ja.bytes=t-n+1,e}var af=os,cf=128,Xa=127;function os(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw os.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&Xa)<<o:(i&Xa)*Math.pow(2,o),o+=7}while(i>=cf);return os.bytes=s-n,t}var uf=Math.pow(2,7),lf=Math.pow(2,14),ff=Math.pow(2,21),hf=Math.pow(2,28),df=Math.pow(2,35),pf=Math.pow(2,42),mf=Math.pow(2,49),yf=Math.pow(2,56),gf=Math.pow(2,63),bf=function(r){return r<uf?1:r<lf?2:r<ff?3:r<hf?4:r<df?5:r<pf?6:r<mf?7:r<yf?8:r<gf?9:10},wf={encode:rf,decode:af,encodingLength:bf},xf=wf,Kr=xf;function qr(r,e=0){return[Kr.decode(r,e),Kr.decode.bytes]}function sr(r,e,t=0){return Kr.encode(r,e,t),e}function ir(r){return Kr.encodingLength(r)}function We(r,e){let t=e.byteLength,n=ir(r),o=n+ir(t),s=new Uint8Array(o+t);return sr(r,s,0),sr(t,s,n),s.set(e,o),new ar(r,t,e,s)}function Ze(r){let e=et(r),[t,n]=qr(e),[o,s]=qr(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new ar(t,o,i,e)}function Qa(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Fa(r.bytes,t.bytes)}}var ar=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};function Ja(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return Sf(t,ss(r),e??te.encoder);default:return vf(t,ss(r),e??xt.encoder)}}var ec=new WeakMap;function ss(r){let e=ec.get(r);if(e==null){let t=new Map;return ec.set(r,t),t}return e}var le=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Vr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==_f)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=We(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&&Qa(e.multihash,n.multihash)}toString(e){return Ja(this,e)}toJSON(){return{"/":Ja(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:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??tc(n,o,s.bytes))}else if(t[Af]===!0){let{version:n,multihash:o,code:s}=t,i=Ze(o);return r.create(n,s,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 o=tc(e,t,n.bytes);return new r(e,t,n,o)}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,o=et(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new ar(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[h,f]=qr(e.subarray(t));return t+=f,h},o=n(),s=Vr;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),u=t+c,l=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(e,t){let[n,o]=Ef(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return ss(s).set(n,e),s}};function Ef(r,e){switch(r[0]){case"Q":{let t=e??te;return[te.prefix,t.decode(`${te.prefix}${r}`)]}case te.prefix:{let t=e??te;return[te.prefix,t.decode(r)]}case xt.prefix:{let t=e??xt;return[xt.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 Sf(r,e,t){let{prefix:n}=t;if(n!==te.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function vf(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var Vr=112,_f=18;function tc(r,e,t){let n=ir(r),o=n+ir(e),s=new Uint8Array(o+t.byteLength);return sr(r,s,0),sr(e,s,n),s.set(t,o),s}var Af=Symbol.for("@ipld/js-cid/CID");var is={};Ae(is,{identity:()=>He});var rc=0,Tf="identity",nc=et;function If(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 We(rc,nc(r))}var He={code:rc,name:Tf,encode:nc,digest:If};function fe(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 re(r=0){return new Uint8Array(r)}function Ie(r=0){return new Uint8Array(r)}function rt(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=Ie(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}var sc=Symbol.for("@achingbrain/uint8arraylist");function oc(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function Bn(r){return!!r?.[sc]}var J=class r{bufs;length;[sc]=!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(Bn(n))t+=n.byteLength,this.bufs.push(...n.bufs);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(Bn(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=oc(this.bufs,e);return t.buf[t.index]}set(e,t){let n=oc(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(Bn(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:o}=this._subList(e,t);return rt(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:rt(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=[...n],s}_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=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let u=e>=a&&e<c,l=t>a&&t<=c;if(u&&l){if(e===a&&t===c){n.push(i);break}let h=e-a;n.push(i.subarray(h,h+(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(!Bn(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(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 o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let h=0;h<s;h++)i[h]=-1;for(let h=0;h<o;h++)i[n[h]]=h;let a=i,c=this.byteLength-n.byteLength,u=n.byteLength-1,l;for(let h=t;h<=c;h+=l){l=0;for(let f=u;f>=0;f--){let d=this.get(h+f);if(n[f]!==d){l=Math.max(1,f-a[d]);break}}if(l===0)return h}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=Ie(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 o=re(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,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 o=re(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,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 o=re(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,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=Ie(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 o=re(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,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 o=re(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,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 o=re(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,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 o=re(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,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 o=re(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,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(!fe(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((o,s)=>o+s.byteLength,0)),n.length=t,n}};var as={};Ae(as,{base10:()=>Cf});var Cf=wt({prefix:"9",name:"base10",alphabet:"0123456789"});var cs={};Ae(cs,{base16:()=>Df,base16upper:()=>Lf});var Df=ae({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Lf=ae({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var us={};Ae(us,{base2:()=>Bf});var Bf=ae({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var ls={};Ae(ls,{base256emoji:()=>Uf});var ic=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}"),Rf=ic.reduce((r,e,t)=>(r[t]=e,r),[]),Pf=ic.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function Of(r){return r.reduce((e,t)=>(e+=Rf[t],e),"")}function Nf(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=Pf[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var Uf=or({prefix:"\u{1F680}",name:"base256emoji",encode:Of,decode:Nf});var hs={};Ae(hs,{base64:()=>Mf,base64pad:()=>kf,base64url:()=>fs,base64urlpad:()=>Kf});var Mf=ae({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),kf=ae({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),fs=ae({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Kf=ae({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ds={};Ae(ds,{base8:()=>qf});var qf=ae({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var ps={};Ae(ps,{identity:()=>Vf});var Vf=or({prefix:"\0",name:"identity",encode:r=>Ga(r),decode:r=>za(r)});var s0=new TextEncoder,i0=new TextDecoder;var gs={};Ae(gs,{sha256:()=>cr,sha512:()=>Gf});var zf=20;function ys({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new ms(r,e,t,n,o)}var ms=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??zf,this.maxDigestLength=s}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?ac(n,this.code,t?.truncate):n.then(o=>ac(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function ac(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 We(e,r)}function uc(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var cr=ys({name:"sha2-256",code:18,encode:uc("SHA-256")}),Gf=ys({name:"sha2-512",code:19,encode:uc("SHA-512")});var Hr={...ps,...us,...ds,...as,...cs,...rs,...ns,...ts,...hs,...ls},b0={...gs,...is};function fc(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var lc=fc("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),bs=fc("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=Ie(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),$f={utf8:lc,"utf-8":lc,hex:Hr.base16,latin1:bs,ascii:bs,binary:bs,...Hr},Rn=$f;function k(r,e="utf8"){let t=Rn[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function z(r,e="utf8"){let t=Rn[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var Wf=parseInt("11111",2),ws=parseInt("10000000",2),Zf=parseInt("01111111",2),hc={0:Fr,1:Fr,2:Yf,3:Qf,4:Jf,5:jf,6:Xf,16:Fr,22:Fr,48:Fr};function nt(r,e={offset:0}){let t=r[e.offset]&Wf;if(e.offset++,hc[t]!=null)return hc[t](r,e);throw new Error("No decoder for tag "+t)}function zr(r,e){let t=0;if((r[e.offset]&ws)===ws){let n=r[e.offset]&Zf,o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++)o+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(o,16)}else t=r[e.offset],e.offset++;return t}function Fr(r,e){zr(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=nt(r,e);if(n===null)break;t.push(n)}return t}function Yf(r,e){let t=zr(r,e),n=e.offset,o=e.offset+t,s=[];for(let i=n;i<o;i++)i===n&&r[i]===0||s.push(r[i]);return e.offset+=t,Uint8Array.from(s)}function Xf(r,e){let t=zr(r,e),n=e.offset+t,o=r[e.offset];e.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,c=[];for(;e.offset<n;){let u=r[e.offset];if(e.offset++,c.push(u&127),u<128){c.reverse();let l=0;for(let h=0;h<c.length;h++)l+=c[h]<<h*7;a+=`.${l}`,c=[]}}return a}function jf(r,e){return e.offset++,null}function Qf(r,e){let t=zr(r,e),n=r[e.offset];e.offset++;let o=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 o}function Jf(r,e){let t=zr(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function eh(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new J;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function xs(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=eh(r.byteLength);return new J(Uint8Array.from([e.byteLength|ws]),e)}function Ce(r){let e=new J,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new J(Uint8Array.from([2]),xs(e),e)}function Pn(r){let e=Uint8Array.from([0]),t=new J(e,r);return new J(Uint8Array.from([3]),xs(t),t)}function Et(r,e=48){let t=new J;for(let n of r)t.append(n);return new J(Uint8Array.from([e]),xs(t),t)}async function dc(r,e,t,n){let o=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,e,t.subarray());return n?.signal?.throwIfAborted(),s}var th=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),rh=Uint8Array.from([6,5,43,129,4,0,34]),nh=Uint8Array.from([6,5,43,129,4,0,35]),oh={ext:!0,kty:"EC",crv:"P-256"},sh={ext:!0,kty:"EC",crv:"P-384"},ih={ext:!0,kty:"EC",crv:"P-521"},Es=32,Ss=48,vs=66;function _s(r){let e=nt(r);return pc(e)}function pc(r){let e=r[1][1][0],t=1,n,o;if(e.byteLength===Es*2+1)return n=z(e.subarray(t,t+Es),"base64url"),o=z(e.subarray(t+Es),"base64url"),new ur({...oh,key_ops:["verify"],x:n,y:o});if(e.byteLength===Ss*2+1)return n=z(e.subarray(t,t+Ss),"base64url"),o=z(e.subarray(t+Ss),"base64url"),new ur({...sh,key_ops:["verify"],x:n,y:o});if(e.byteLength===vs*2+1)return n=z(e.subarray(t,t+vs),"base64url"),o=z(e.subarray(t+vs),"base64url"),new ur({...ih,key_ops:["verify"],x:n,y:o});throw new ie(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function mc(r){return Et([Ce(Uint8Array.from([1])),Et([ah(r.crv)],160),Et([Pn(new J(Uint8Array.from([4]),k(r.x??"","base64url"),k(r.y??"","base64url")))],161)]).subarray()}function ah(r){if(r==="P-256")return th;if(r==="P-384")return rh;if(r==="P-521")return nh;throw new ie(`Invalid curve ${r}`)}var ur=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=mc(this.jwk)),this._raw}toMultihash(){return He.digest(Ye(this))}toCID(){return le.createV1(114,this.toMultihash())}toString(){return te.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:fe(this.raw,e.raw)}async verify(e,t,n){return dc(this.jwk,t,e,n)}};var Ut=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function st(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Gr(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function De(r,...e){if(!st(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error("Uint8Array expected of length "+e+", got length="+r.length)}function On(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Gr(r.outputLen),Gr(r.blockLen)}function fr(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 gc(r,e){De(r);let t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function it(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function Nn(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Fe(r,e){return r<<32-e|r>>>e}var bc=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",ch=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Ke(r){if(De(r),bc)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=ch[r[t]];return e}var ot={_0:48,_9:57,A:65,F:70,a:97,f:102};function yc(r){if(r>=ot._0&&r<=ot._9)return r-ot._0;if(r>=ot.A&&r<=ot.F)return r-(ot.A-10);if(r>=ot.a&&r<=ot.f)return r-(ot.a-10)}function Mt(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(bc)return Uint8Array.fromHex(r);let e=r.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let o=0,s=0;o<t;o++,s+=2){let i=yc(r.charCodeAt(s)),a=yc(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function As(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function $r(r){return typeof r=="string"&&(r=As(r)),De(r),r}function Se(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];De(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let s=r[n];t.set(s,o),o+=s.length}return t}var lr=class{};function Ts(r){let e=n=>r().update($r(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function hr(r=32){if(Ut&&typeof Ut.getRandomValues=="function")return Ut.getRandomValues(new Uint8Array(r));if(Ut&&typeof Ut.randomBytes=="function")return Uint8Array.from(Ut.randomBytes(r));throw new Error("crypto.getRandomValues must be defined")}function uh(r,e,t,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(t>>o&s),a=Number(t&s),c=n?4:0,u=n?0:4;r.setUint32(e+c,i,n),r.setUint32(e+u,a,n)}function wc(r,e,t){return r&e^~r&t}function xc(r,e,t){return r&e^r&t^e&t}var Wr=class extends lr{constructor(e,t,n,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=Nn(this.buffer)}update(e){fr(this),e=$r(e),De(e);let{view:t,buffer:n,blockLen:o}=this,s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=Nn(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){fr(this),gc(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,it(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let h=i;h<o;h++)t[h]=0;uh(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=Nn(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should 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 h=0;h<u;h++)a.setUint32(4*h,l[h],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},at=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var ye=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Un=BigInt(4294967295),Ec=BigInt(32);function lh(r,e=!1){return e?{h:Number(r&Un),l:Number(r>>Ec&Un)}:{h:Number(r>>Ec&Un)|0,l:Number(r&Un)|0}}function Sc(r,e=!1){let t=r.length,n=new Uint32Array(t),o=new Uint32Array(t);for(let s=0;s<t;s++){let{h:i,l:a}=lh(r[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var Is=(r,e,t)=>r>>>t,Cs=(r,e,t)=>r<<32-t|e>>>t,kt=(r,e,t)=>r>>>t|e<<32-t,Kt=(r,e,t)=>r<<32-t|e>>>t,Zr=(r,e,t)=>r<<64-t|e>>>t-32,Yr=(r,e,t)=>r>>>t-32|e<<64-t;function Xe(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var vc=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),_c=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,Ac=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),Tc=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,Ic=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),Cc=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var hh=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]),St=new Uint32Array(64),Mn=class extends Wr{constructor(e=32){super(64,e,8,!1),this.A=at[0]|0,this.B=at[1]|0,this.C=at[2]|0,this.D=at[3]|0,this.E=at[4]|0,this.F=at[5]|0,this.G=at[6]|0,this.H=at[7]|0}get(){let{A:e,B:t,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,t,n,o,s,i,a,c]}set(e,t,n,o,s,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let h=0;h<16;h++,t+=4)St[h]=e.getUint32(t,!1);for(let h=16;h<64;h++){let f=St[h-15],d=St[h-2],p=Fe(f,7)^Fe(f,18)^f>>>3,x=Fe(d,17)^Fe(d,19)^d>>>10;St[h]=x+St[h-7]+p+St[h-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:l}=this;for(let h=0;h<64;h++){let f=Fe(a,6)^Fe(a,11)^Fe(a,25),d=l+f+wc(a,c,u)+hh[h]+St[h]|0,x=(Fe(n,2)^Fe(n,13)^Fe(n,22))+xc(n,o,s)|0;l=u,u=c,c=a,a=i+d|0,i=s,s=o,o=n,n=d+x|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(n,o,s,i,a,c,u,l)}roundClean(){it(St)}destroy(){this.set(0,0,0,0,0,0,0,0),it(this.buffer)}};var Dc=Sc(["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))),dh=Dc[0],ph=Dc[1],vt=new Uint32Array(80),_t=new Uint32Array(80),Ds=class extends Wr{constructor(e=64){super(128,e,16,!1),this.Ah=ye[0]|0,this.Al=ye[1]|0,this.Bh=ye[2]|0,this.Bl=ye[3]|0,this.Ch=ye[4]|0,this.Cl=ye[5]|0,this.Dh=ye[6]|0,this.Dl=ye[7]|0,this.Eh=ye[8]|0,this.El=ye[9]|0,this.Fh=ye[10]|0,this.Fl=ye[11]|0,this.Gh=ye[12]|0,this.Gl=ye[13]|0,this.Hh=ye[14]|0,this.Hl=ye[15]|0}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:u,El:l,Fh:h,Fl:f,Gh:d,Gl:p,Hh:x,Hl:S}=this;return[e,t,n,o,s,i,a,c,u,l,h,f,d,p,x,S]}set(e,t,n,o,s,i,a,c,u,l,h,f,d,p,x,S){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=h|0,this.Fl=f|0,this.Gh=d|0,this.Gl=p|0,this.Hh=x|0,this.Hl=S|0}process(e,t){for(let w=0;w<16;w++,t+=4)vt[w]=e.getUint32(t),_t[w]=e.getUint32(t+=4);for(let w=16;w<80;w++){let C=vt[w-15]|0,P=_t[w-15]|0,q=kt(C,P,1)^kt(C,P,8)^Is(C,P,7),K=Kt(C,P,1)^Kt(C,P,8)^Cs(C,P,7),N=vt[w-2]|0,E=_t[w-2]|0,D=kt(N,E,19)^Zr(N,E,61)^Is(N,E,6),U=Kt(N,E,19)^Yr(N,E,61)^Cs(N,E,6),L=Ac(K,U,_t[w-7],_t[w-16]),b=Tc(L,q,D,vt[w-7],vt[w-16]);vt[w]=b|0,_t[w]=L|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:l,Eh:h,El:f,Fh:d,Fl:p,Gh:x,Gl:S,Hh:g,Hl:_}=this;for(let w=0;w<80;w++){let C=kt(h,f,14)^kt(h,f,18)^Zr(h,f,41),P=Kt(h,f,14)^Kt(h,f,18)^Yr(h,f,41),q=h&d^~h&x,K=f&p^~f&S,N=Ic(_,P,K,ph[w],_t[w]),E=Cc(N,g,C,q,dh[w],vt[w]),D=N|0,U=kt(n,o,28)^Zr(n,o,34)^Zr(n,o,39),L=Kt(n,o,28)^Yr(n,o,34)^Yr(n,o,39),b=n&s^n&a^s&a,m=o&i^o&c^i&c;g=x|0,_=S|0,x=d|0,S=p|0,d=h|0,p=f|0,{h,l:f}=Xe(u|0,l|0,E|0,D|0),u=a|0,l=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let y=vc(D,L,m);n=_c(y,E,U,b),o=y|0}({h:n,l:o}=Xe(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=Xe(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=Xe(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=Xe(this.Dh|0,this.Dl|0,u|0,l|0),{h,l:f}=Xe(this.Eh|0,this.El|0,h|0,f|0),{h:d,l:p}=Xe(this.Fh|0,this.Fl|0,d|0,p|0),{h:x,l:S}=Xe(this.Gh|0,this.Gl|0,x|0,S|0),{h:g,l:_}=Xe(this.Hh|0,this.Hl|0,g|0,_|0),this.set(n,o,s,i,a,c,u,l,h,f,d,p,x,S,g,_)}roundClean(){it(vt,_t)}destroy(){it(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var kn=Ts(()=>new Mn);var Lc=Ts(()=>new Ds);var Rs=BigInt(0),Bs=BigInt(1);function ct(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}"`;throw new Error(t+"expected boolean, got type="+typeof r)}return r}function Oe(r,e,t=""){let n=st(r),o=r?.length,s=e!==void 0;if(!n||s&&o!==e){let i=t&&`"${t}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function Xr(r){let e=r.toString(16);return e.length&1?"0"+e:e}function Bc(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?Rs:BigInt("0x"+r)}function dr(r){return Bc(Ke(r))}function ut(r){return De(r),Bc(Ke(Uint8Array.from(r).reverse()))}function Kn(r,e){return Mt(r.toString(16).padStart(e*2,"0"))}function Ps(r,e){return Kn(r,e).reverse()}function Y(r,e,t){let n;if(typeof e=="string")try{n=Mt(e)}catch(s){throw new Error(r+" must be hex string or Uint8Array, cause: "+s)}else if(st(e))n=Uint8Array.from(e);else throw new Error(r+" must be hex string or Uint8Array");let o=n.length;if(typeof t=="number"&&o!==t)throw new Error(r+" of length "+t+" expected, got "+o);return n}function Rc(r,e){if(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 Os(r){return Uint8Array.from(r)}var Ls=r=>typeof r=="bigint"&&Rs<=r;function Pc(r,e,t){return Ls(r)&&Ls(e)&&Ls(t)&&e<=r&&r<t}function jr(r,e,t,n){if(!Pc(e,t,n))throw new Error("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function qn(r){let e;for(e=0;r>Rs;r>>=Bs,e+=1);return e}var At=r=>(Bs<<BigInt(r))-Bs;function Oc(r,e,t){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let n=d=>new Uint8Array(d),o=d=>Uint8Array.of(d),s=n(r),i=n(r),a=0,c=()=>{s.fill(1),i.fill(0),a=0},u=(...d)=>t(i,s,...d),l=(d=n(0))=>{i=u(o(0),d),s=u(),d.length!==0&&(i=u(o(1),d),s=u())},h=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let d=0,p=[];for(;d<e;){s=u();let x=s.slice();p.push(x),d+=s.length}return Se(...p)};return(d,p)=>{c(),l(d);let x;for(;!(x=p(h()));)l();return c(),x}}function Tt(r,e,t={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function n(o,s,i){let a=r[o];if(i&&a===void 0)return;let c=typeof a;if(c!==s||a===null)throw new Error(`param "${o}" is invalid: expected ${s}, got ${c}`)}Object.entries(e).forEach(([o,s])=>n(o,s,!1)),Object.entries(t).forEach(([o,s])=>n(o,s,!0))}var Ns=()=>{throw new Error("not implemented")};function pr(r){let e=new WeakMap;return(t,...n)=>{let o=e.get(t);if(o!==void 0)return o;let s=r(t,...n);return e.set(t,s),s}}var ve=BigInt(0),de=BigInt(1),qt=BigInt(2),Mc=BigInt(3),kc=BigInt(4),Kc=BigInt(5),mh=BigInt(7),qc=BigInt(8),yh=BigInt(9),Vc=BigInt(16);function ce(r,e){let t=r%e;return t>=ve?t:e+t}function ee(r,e,t){let n=r;for(;e-- >ve;)n*=n,n%=t;return n}function Nc(r,e){if(r===ve)throw new Error("invert: expected non-zero number");if(e<=ve)throw new Error("invert: expected positive modulus, got "+e);let t=ce(r,e),n=e,o=ve,s=de,i=de,a=ve;for(;t!==ve;){let u=n/t,l=n%t,h=o-i*u,f=s-a*u;n=t,t=l,o=i,s=a,i=h,a=f}if(n!==de)throw new Error("invert: does not exist");return ce(o,e)}function Us(r,e,t){if(!r.eql(r.sqr(e),t))throw new Error("Cannot find square root")}function Hc(r,e){let t=(r.ORDER+de)/kc,n=r.pow(e,t);return Us(r,n,e),n}function gh(r,e){let t=(r.ORDER-Kc)/qc,n=r.mul(e,qt),o=r.pow(n,t),s=r.mul(e,o),i=r.mul(r.mul(s,qt),o),a=r.mul(s,r.sub(i,r.ONE));return Us(r,a,e),a}function bh(r){let e=Ne(r),t=Fc(r),n=t(e,e.neg(e.ONE)),o=t(e,n),s=t(e,e.neg(n)),i=(r+mh)/Vc;return(a,c)=>{let u=a.pow(c,i),l=a.mul(u,n),h=a.mul(u,o),f=a.mul(u,s),d=a.eql(a.sqr(l),c),p=a.eql(a.sqr(h),c);u=a.cmov(u,l,d),l=a.cmov(f,h,p);let x=a.eql(a.sqr(l),c),S=a.cmov(u,l,x);return Us(a,S,c),S}}function Fc(r){if(r<Mc)throw new Error("sqrt is not defined for small field");let e=r-de,t=0;for(;e%qt===ve;)e/=qt,t++;let n=qt,o=Ne(r);for(;Uc(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return Hc;let s=o.pow(n,e),i=(e+de)/qt;return function(c,u){if(c.is0(u))return u;if(Uc(c,u)!==1)throw new Error("Cannot find square root");let l=t,h=c.mul(c.ONE,s),f=c.pow(u,e),d=c.pow(u,i);for(;!c.eql(f,c.ONE);){if(c.is0(f))return c.ZERO;let p=1,x=c.sqr(f);for(;!c.eql(x,c.ONE);)if(p++,x=c.sqr(x),p===l)throw new Error("Cannot find square root");let S=de<<BigInt(l-p-1),g=c.pow(h,S);l=p,h=c.sqr(g),f=c.mul(f,h),d=c.mul(d,g)}return d}}function wh(r){return r%kc===Mc?Hc:r%qc===Kc?gh:r%Vc===yh?bh(r):Fc(r)}var lt=(r,e)=>(ce(r,e)&de)===de,xh=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ms(r){let e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},t=xh.reduce((n,o)=>(n[o]="function",n),e);return Tt(r,t),r}function Eh(r,e,t){if(t<ve)throw new Error("invalid exponent, negatives unsupported");if(t===ve)return r.ONE;if(t===de)return e;let n=r.ONE,o=e;for(;t>ve;)t&de&&(n=r.mul(n,o)),o=r.sqr(o),t>>=de;return n}function Qr(r,e,t=!1){let n=new Array(e.length).fill(t?r.ZERO:void 0),o=e.reduce((i,a,c)=>r.is0(a)?i:(n[c]=i,r.mul(i,a)),r.ONE),s=r.inv(o);return e.reduceRight((i,a,c)=>r.is0(a)?i:(n[c]=r.mul(i,n[c]),r.mul(i,a)),s),n}function Uc(r,e){let t=(r.ORDER-de)/qt,n=r.pow(e,t),o=r.eql(n,r.ONE),s=r.eql(n,r.ZERO),i=r.eql(n,r.neg(r.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function Vn(r,e){e!==void 0&&Gr(e);let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function Ne(r,e,t=!1,n={}){if(r<=ve)throw new Error("invalid field: expected ORDER > 0, got "+r);let o,s,i=!1,a;if(typeof e=="object"&&e!=null){if(n.sqrt||t)throw new Error("cannot specify opts in two arguments");let f=e;f.BITS&&(o=f.BITS),f.sqrt&&(s=f.sqrt),typeof f.isLE=="boolean"&&(t=f.isLE),typeof f.modFromBytes=="boolean"&&(i=f.modFromBytes),a=f.allowedLengths}else typeof e=="number"&&(o=e),n.sqrt&&(s=n.sqrt);let{nBitLength:c,nByteLength:u}=Vn(r,o);if(u>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let l,h=Object.freeze({ORDER:r,isLE:t,BITS:c,BYTES:u,MASK:At(c),ZERO:ve,ONE:de,allowedLengths:a,create:f=>ce(f,r),isValid:f=>{if(typeof f!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof f);return ve<=f&&f<r},is0:f=>f===ve,isValidNot0:f=>!h.is0(f)&&h.isValid(f),isOdd:f=>(f&de)===de,neg:f=>ce(-f,r),eql:(f,d)=>f===d,sqr:f=>ce(f*f,r),add:(f,d)=>ce(f+d,r),sub:(f,d)=>ce(f-d,r),mul:(f,d)=>ce(f*d,r),pow:(f,d)=>Eh(h,f,d),div:(f,d)=>ce(f*Nc(d,r),r),sqrN:f=>f*f,addN:(f,d)=>f+d,subN:(f,d)=>f-d,mulN:(f,d)=>f*d,inv:f=>Nc(f,r),sqrt:s||(f=>(l||(l=wh(r)),l(h,f))),toBytes:f=>t?Ps(f,u):Kn(f,u),fromBytes:(f,d=!0)=>{if(a){if(!a.includes(f.length)||f.length>u)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+f.length);let x=new Uint8Array(u);x.set(f,t?0:x.length-f.length),f=x}if(f.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+f.length);let p=t?ut(f):dr(f);if(i&&(p=ce(p,r)),!d&&!h.isValid(p))throw new Error("invalid field element: outside of range 0..ORDER");return p},invertBatch:f=>Qr(h,f),cmov:(f,d,p)=>p?d:f});return Object.freeze(h)}function zc(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let e=r.toString(2).length;return Math.ceil(e/8)}function ks(r){let e=zc(r);return e+Math.ceil(e/2)}function Ks(r,e,t=!1){let n=r.length,o=zc(e),s=ks(e);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=t?ut(r):dr(r),a=ce(i,e-de)+de;return t?Ps(a,o):Kn(a,o)}var mr=BigInt(0),Vt=BigInt(1);function Jr(r,e){let t=e.negate();return r?t:e}function ft(r,e){let t=Qr(r.Fp,e.map(n=>n.Z));return e.map((n,o)=>r.fromAffine(n.toAffine(t[o])))}function Zc(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){Zc(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1),o=2**r,s=At(r),i=BigInt(r);return{windows:t,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function Gc(r,e,t){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=t,a=Number(r&o),c=r>>i;a>n&&(a-=s,c+=Vt);let u=e*n,l=u+Math.abs(a)-1,h=a===0,f=a<0,d=e%2!==0;return{nextN:c,offset:l,isZero:h,isNeg:f,isNegF:d,offsetF:u}}function Sh(r,e){if(!Array.isArray(r))throw new Error("array expected");r.forEach((t,n)=>{if(!(t instanceof e))throw new Error("invalid point at index "+n)})}function vh(r,e){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((t,n)=>{if(!e.isValid(t))throw new Error("invalid scalar at index "+n)})}var Vs=new WeakMap,Yc=new WeakMap;function Hs(r){return Yc.get(r)||1}function $c(r){if(r!==mr)throw new Error("invalid wNAF")}var yr=class{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 o=e;for(;t>mr;)t&Vt&&(n=n.add(o)),o=o.double(),t>>=Vt;return n}precomputeWindow(e,t){let{windows:n,windowSize:o}=qs(t,this.bits),s=[],i=e,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let u=1;u<o;u++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=qs(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:u,isZero:l,isNeg:h,isNegF:f,offsetF:d}=Gc(n,a,i);n=c,l?s=s.add(Jr(f,t[d])):o=o.add(Jr(h,t[u]))}return $c(n),{p:o,f:s}}wNAFUnsafe(e,t,n,o=this.ZERO){let s=qs(e,this.bits);for(let i=0;i<s.windows&&n!==mr;i++){let{nextN:a,offset:c,isZero:u,isNeg:l}=Gc(n,i,s);if(n=a,!u){let h=t[c];o=o.add(l?h.negate():h)}}return $c(n),o}getPrecomputes(e,t,n){let o=Vs.get(t);return o||(o=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(o=n(o)),Vs.set(t,o))),o}cached(e,t,n){let o=Hs(e);return this.wNAF(o,this.getPrecomputes(o,e,n),t)}unsafe(e,t,n,o){let s=Hs(e);return s===1?this._unsafeLadder(e,t,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),t,o)}createCache(e,t){Zc(t,this.bits),Yc.set(e,t),Vs.delete(e)}hasCache(e){return Hs(e)!==1}};function Xc(r,e,t,n){let o=e,s=r.ZERO,i=r.ZERO;for(;t>mr||n>mr;)t&Vt&&(s=s.add(o)),n&Vt&&(i=i.add(o)),o=o.double(),t>>=Vt,n>>=Vt;return{p1:s,p2:i}}function gr(r,e,t,n){Sh(t,r),vh(n,e);let o=t.length,s=n.length;if(o!==s)throw new Error("arrays of points and scalars must have equal length");let i=r.ZERO,a=qn(BigInt(o)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let u=At(c),l=new Array(Number(u)+1).fill(i),h=Math.floor((e.BITS-1)/c)*c,f=i;for(let d=h;d>=0;d-=c){l.fill(i);for(let x=0;x<s;x++){let S=n[x],g=Number(S>>BigInt(d)&u);l[g]=l[g].add(t[x])}let p=i;for(let x=l.length-1,S=i;x>0;x--)S=S.add(l[x]),p=p.add(S);if(f=f.add(p),d!==0)for(let x=0;x<c;x++)f=f.double()}return f}function Wc(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Ms(e),e}else return Ne(r,{isLE:t})}function Hn(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>mr))throw new Error(`CURVE.${c} must be positive bigint`)}let o=Wc(e.p,t.Fp,n),s=Wc(e.n,t.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}var It=BigInt(0),pe=BigInt(1),Fs=BigInt(2),_h=BigInt(8);function Ah(r,e,t,n){let o=r.sqr(t),s=r.sqr(n),i=r.add(r.mul(e.a,o),s),a=r.add(r.ONE,r.mul(e.d,r.mul(o,s)));return r.eql(i,a)}function Th(r,e={}){let t=Hn("edwards",r,e,e.FpFnLE),{Fp:n,Fn:o}=t,s=t.CURVE,{h:i}=s;Tt(e,{},{uvRatio:"function"});let a=Fs<<BigInt(o.BYTES*8)-pe,c=S=>n.create(S),u=e.uvRatio||((S,g)=>{try{return{isValid:!0,value:n.sqrt(n.div(S,g))}}catch{return{isValid:!1,value:It}}});if(!Ah(n,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function l(S,g,_=!1){let w=_?pe:It;return jr("coordinate "+S,g,w,a),g}function h(S){if(!(S instanceof p))throw new Error("ExtendedPoint expected")}let f=pr((S,g)=>{let{X:_,Y:w,Z:C}=S,P=S.is0();g==null&&(g=P?_h:n.inv(C));let q=c(_*g),K=c(w*g),N=n.mul(C,g);if(P)return{x:It,y:pe};if(N!==pe)throw new Error("invZ was invalid");return{x:q,y:K}}),d=pr(S=>{let{a:g,d:_}=s;if(S.is0())throw new Error("bad point: ZERO");let{X:w,Y:C,Z:P,T:q}=S,K=c(w*w),N=c(C*C),E=c(P*P),D=c(E*E),U=c(K*g),L=c(E*c(U+N)),b=c(D+c(_*c(K*N)));if(L!==b)throw new Error("bad point: equation left != right (1)");let m=c(w*C),y=c(P*q);if(m!==y)throw new Error("bad point: equation left != right (2)");return!0});class p{constructor(g,_,w,C){this.X=l("x",g),this.Y=l("y",_),this.Z=l("z",w,!0),this.T=l("t",C),Object.freeze(this)}static CURVE(){return s}static fromAffine(g){if(g instanceof p)throw new Error("extended point not allowed");let{x:_,y:w}=g||{};return l("x",_),l("y",w),new p(_,w,pe,c(_*w))}static fromBytes(g,_=!1){let w=n.BYTES,{a:C,d:P}=s;g=Os(Oe(g,w,"point")),ct(_,"zip215");let q=Os(g),K=g[w-1];q[w-1]=K&-129;let N=ut(q),E=_?a:n.ORDER;jr("point.y",N,It,E);let D=c(N*N),U=c(D-pe),L=c(P*D-C),{isValid:b,value:m}=u(U,L);if(!b)throw new Error("bad point: invalid y coordinate");let y=(m&pe)===pe,v=(K&128)!==0;if(!_&&m===It&&v)throw new Error("bad point: x=0 and x_0=1");return v!==y&&(m=c(-m)),p.fromAffine({x:m,y:N})}static fromHex(g,_=!1){return p.fromBytes(Y("point",g),_)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,_=!0){return x.createCache(this,g),_||this.multiply(Fs),this}assertValidity(){d(this)}equals(g){h(g);let{X:_,Y:w,Z:C}=this,{X:P,Y:q,Z:K}=g,N=c(_*K),E=c(P*C),D=c(w*K),U=c(q*C);return N===E&&D===U}is0(){return this.equals(p.ZERO)}negate(){return new p(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:g}=s,{X:_,Y:w,Z:C}=this,P=c(_*_),q=c(w*w),K=c(Fs*c(C*C)),N=c(g*P),E=_+w,D=c(c(E*E)-P-q),U=N+q,L=U-K,b=N-q,m=c(D*L),y=c(U*b),v=c(D*b),A=c(L*U);return new p(m,y,A,v)}add(g){h(g);let{a:_,d:w}=s,{X:C,Y:P,Z:q,T:K}=this,{X:N,Y:E,Z:D,T:U}=g,L=c(C*N),b=c(P*E),m=c(K*w*U),y=c(q*D),v=c((C+P)*(N+E)-L-b),A=y-m,B=y+m,T=c(b-_*L),I=c(v*A),O=c(B*T),M=c(v*T),ne=c(A*B);return new p(I,O,ne,M)}subtract(g){return this.add(g.negate())}multiply(g){if(!o.isValidNot0(g))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:_,f:w}=x.cached(this,g,C=>ft(p,C));return ft(p,[_,w])[0]}multiplyUnsafe(g,_=p.ZERO){if(!o.isValid(g))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return g===It?p.ZERO:this.is0()||g===pe?this:x.unsafe(this,g,w=>ft(p,w),_)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return x.unsafe(this,s.n).is0()}toAffine(g){return f(this,g)}clearCofactor(){return i===pe?this:this.multiplyUnsafe(i)}toBytes(){let{x:g,y:_}=this.toAffine(),w=n.toBytes(_);return w[w.length-1]|=g&pe?128:0,w}toHex(){return Ke(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(g){return ft(p,g)}static msm(g,_){return gr(p,o,g,_)}_setWindowSize(g){this.precompute(g)}toRawBytes(){return this.toBytes()}}p.BASE=new p(s.Gx,s.Gy,pe,c(s.Gx*s.Gy)),p.ZERO=new p(It,pe,pe,It),p.Fp=n,p.Fn=o;let x=new yr(p,o.BITS);return p.BASE.precompute(8),p}var Fn=class{constructor(e){this.ep=e}static fromBytes(e){Ns()}static fromHex(e){Ns()}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 Ke(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.init(this.ep.precompute(e,t))}toRawBytes(){return this.toBytes()}};function Ih(r,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');Tt(t,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=t,{BASE:o,Fp:s,Fn:i}=r,a=t.randomBytes||hr,c=t.adjustScalarBytes||(E=>E),u=t.domain||((E,D,U)=>{if(ct(U,"phflag"),D.length||U)throw new Error("Contexts/pre-hash are not supported");return E});function l(E){return i.create(ut(E))}function h(E){let D=w.secretKey;E=Y("private key",E,D);let U=Y("hashed private key",e(E),2*D),L=c(U.slice(0,D)),b=U.slice(D,2*D),m=l(L);return{head:L,prefix:b,scalar:m}}function f(E){let{head:D,prefix:U,scalar:L}=h(E),b=o.multiply(L),m=b.toBytes();return{head:D,prefix:U,scalar:L,point:b,pointBytes:m}}function d(E){return f(E).pointBytes}function p(E=Uint8Array.of(),...D){let U=Se(...D);return l(e(u(U,Y("context",E),!!n)))}function x(E,D,U={}){E=Y("message",E),n&&(E=n(E));let{prefix:L,scalar:b,pointBytes:m}=f(D),y=p(U.context,L,E),v=o.multiply(y).toBytes(),A=p(U.context,v,m,E),B=i.create(y+A*b);if(!i.isValid(B))throw new Error("sign failed: invalid s");let T=Se(v,i.toBytes(B));return Oe(T,w.signature,"result")}let S={zip215:!0};function g(E,D,U,L=S){let{context:b,zip215:m}=L,y=w.signature;E=Y("signature",E,y),D=Y("message",D),U=Y("publicKey",U,w.publicKey),m!==void 0&&ct(m,"zip215"),n&&(D=n(D));let v=y/2,A=E.subarray(0,v),B=ut(E.subarray(v,y)),T,I,O;try{T=r.fromBytes(U,m),I=r.fromBytes(A,m),O=o.multiplyUnsafe(B)}catch{return!1}if(!m&&T.isSmallOrder())return!1;let M=p(b,I.toBytes(),T.toBytes(),D);return I.add(T.multiplyUnsafe(M)).subtract(O).clearCofactor().is0()}let _=s.BYTES,w={secretKey:_,publicKey:_,signature:2*_,seed:_};function C(E=a(w.seed)){return Oe(E,w.seed,"seed")}function P(E){let D=N.randomSecretKey(E);return{secretKey:D,publicKey:d(D)}}function q(E){return st(E)&&E.length===i.BYTES}function K(E,D){try{return!!r.fromBytes(E,D)}catch{return!1}}let N={getExtendedPublicKey:f,randomSecretKey:C,isValidSecretKey:q,isValidPublicKey:K,toMontgomery(E){let{y:D}=r.fromBytes(E),U=w.publicKey,L=U===32;if(!L&&U!==57)throw new Error("only defined for 25519 and 448");let b=L?s.div(pe+D,pe-D):s.div(D-pe,D+pe);return s.toBytes(b)},toMontgomerySecret(E){let D=w.secretKey;Oe(E,D);let U=e(E.subarray(0,D));return c(U).subarray(0,D)},randomPrivateKey:C,precompute(E=8,D=r.BASE){return D.precompute(E,!1)}};return Object.freeze({keygen:P,getPublicKey:d,sign:x,verify:g,utils:N,Point:r,lengths:w})}function Ch(r){let e={a:r.a,d:r.d,p:r.Fp.ORDER,n:r.n,h:r.h,Gx:r.Gx,Gy:r.Gy},t=r.Fp,n=Ne(e.n,r.nBitLength,!0),o={Fp:t,Fn:n,uvRatio:r.uvRatio},s={randomBytes:r.randomBytes,adjustScalarBytes:r.adjustScalarBytes,domain:r.domain,prehash:r.prehash,mapToCurve:r.mapToCurve};return{CURVE:e,curveOpts:o,hash:r.hash,eddsaOpts:s}}function Dh(r,e){let t=e.Point;return Object.assign({},e,{ExtendedPoint:t,CURVE:r,nBitLength:t.Fn.BITS,nByteLength:t.Fn.BYTES})}function jc(r){let{CURVE:e,curveOpts:t,hash:n,eddsaOpts:o}=Ch(r),s=Th(e,t),i=Ih(s,n,o);return Dh(r,i)}var Lh=BigInt(0),ht=BigInt(1),Qc=BigInt(2),Ty=BigInt(3),Bh=BigInt(5),Rh=BigInt(8),br=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),en={p:br,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Rh,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Ph(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=br,a=r*r%s*r%s,c=ee(a,Qc,s)*a%s,u=ee(c,ht,s)*r%s,l=ee(u,Bh,s)*u%s,h=ee(l,e,s)*l%s,f=ee(h,t,s)*h%s,d=ee(f,n,s)*f%s,p=ee(d,o,s)*d%s,x=ee(p,o,s)*d%s,S=ee(x,e,s)*l%s;return{pow_p_5_8:ee(S,Qc,s)*r%s,b2:a}}function Oh(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var zs=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Ws(r,e){let t=br,n=ce(e*e*e,t),o=ce(n*n*e,t),s=Ph(r*o).pow_p_5_8,i=ce(r*n*s,t),a=ce(e*i*i,t),c=i,u=ce(i*zs,t),l=a===r,h=a===ce(-r,t),f=a===ce(-r*zs,t);return l&&(i=c),(h||f)&&(i=u),lt(i,t)&&(i=ce(-i,t)),{isValid:l||h,value:i}}var Ct=Ne(en.p,{isLE:!0}),Nh=Ne(en.n,{isLE:!0}),Uh={...en,Fp:Ct,hash:Lc,adjustScalarBytes:Oh,uvRatio:Ws},dt=jc(Uh);var Gs=zs,Mh=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),kh=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),Kh=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),qh=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),Jc=r=>Ws(ht,r),Vh=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),$s=r=>dt.Point.Fp.create(ut(r)&Vh);function eu(r){let{d:e}=en,t=br,n=g=>Ct.create(g),o=n(Gs*r*r),s=n((o+ht)*Kh),i=BigInt(-1),a=n((i-e*o)*n(o+e)),{isValid:c,value:u}=Ws(s,a),l=n(u*r);lt(l,t)||(l=n(-l)),c||(u=l),c||(i=o);let h=n(i*(o-ht)*qh-a),f=u*u,d=n((u+u)*a),p=n(h*Mh),x=n(ht-f),S=n(ht+f);return new dt.Point(n(d*S),n(x*p),n(p*S),n(d*x))}function Hh(r){De(r,64);let e=$s(r.subarray(0,32)),t=eu(e),n=$s(r.subarray(32,64)),o=eu(n);return new pt(t.add(o))}var pt=class r extends Fn{constructor(e){super(e)}static fromAffine(e){return new r(dt.Point.fromAffine(e))}assertSame(e){if(!(e instanceof r))throw new Error("RistrettoPoint expected")}init(e){return new r(e)}static hashToCurve(e){return Hh(Y("ristrettoHash",e,64))}static fromBytes(e){De(e,32);let{a:t,d:n}=en,o=br,s=C=>Ct.create(C),i=$s(e);if(!Rc(Ct.toBytes(i),e)||lt(i,o))throw new Error("invalid ristretto255 encoding 1");let a=s(i*i),c=s(ht+t*a),u=s(ht-t*a),l=s(c*c),h=s(u*u),f=s(t*n*l-h),{isValid:d,value:p}=Jc(s(f*h)),x=s(p*u),S=s(p*x*f),g=s((i+i)*x);lt(g,o)&&(g=s(-g));let _=s(c*S),w=s(g*_);if(!d||lt(w,o)||_===Lh)throw new Error("invalid ristretto255 encoding 2");return new r(new dt.Point(g,_,ht,w))}static fromHex(e){return r.fromBytes(Y("ristrettoHex",e,32))}static msm(e,t){return gr(r,dt.Point.Fn,e,t)}toBytes(){let{X:e,Y:t,Z:n,T:o}=this.ep,s=br,i=S=>Ct.create(S),a=i(i(n+t)*i(n-t)),c=i(e*t),u=i(c*c),{value:l}=Jc(i(a*u)),h=i(l*a),f=i(l*c),d=i(h*f*o),p;if(lt(o*d,s)){let S=i(t*Gs),g=i(e*Gs);e=S,t=g,p=i(h*kh)}else p=f;lt(e*d,s)&&(t=i(-t));let x=i((n-t)*p);return lt(x,s)&&(x=i(-x)),Ct.toBytes(x)}equals(e){this.assertSame(e);let{X:t,Y:n}=this.ep,{X:o,Y:s}=e.ep,i=u=>Ct.create(u),a=i(t*s)===i(n*o),c=i(n*s)===i(t*o);return a||c}is0(){return this.equals(r.ZERO)}};pt.BASE=new pt(dt.Point.BASE);pt.ZERO=new pt(dt.Point.ZERO);pt.Fp=Ct;pt.Fn=Nh;var tn=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},zn=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var tu={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new zn("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 qe=tu;var Gn=32;var Zs,Fh=(async()=>{try{return await qe.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function zh(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await qe.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await qe.get().subtle.verify({name:"Ed25519"},n,e,t instanceof Uint8Array?t:t.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function Gh(r,e,t){return dt.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function ru(r,e,t){return Zs==null&&(Zs=await Fh),Zs?zh(r,e,t):Gh(r,e,t)}function $n(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Wn=class{type="Ed25519";raw;constructor(e){this.raw=Ys(e,Gn)}toMultihash(){return He.digest(Ye(this))}toCID(){return le.createV1(114,this.toMultihash())}toString(){return te.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:fe(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let o=ru(this.raw,t,e);return $n(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function Xs(r){return r=Ys(r,Gn),new Wn(r)}function Ys(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new ie(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var Wh=Math.pow(2,7),Zh=Math.pow(2,14),Yh=Math.pow(2,21),js=Math.pow(2,28),Qs=Math.pow(2,35),Js=Math.pow(2,42),ei=Math.pow(2,49),W=128,we=127;function Le(r){if(r<Wh)return 1;if(r<Zh)return 2;if(r<Yh)return 3;if(r<js)return 4;if(r<Qs)return 5;if(r<Js)return 6;if(r<ei)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function wr(r,e,t=0){switch(Le(r)){case 8:e[t++]=r&255|W,r/=128;case 7:e[t++]=r&255|W,r/=128;case 6:e[t++]=r&255|W,r/=128;case 5:e[t++]=r&255|W,r/=128;case 4:e[t++]=r&255|W,r>>>=7;case 3:e[t++]=r&255|W,r>>>=7;case 2:e[t++]=r&255|W,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function Xh(r,e,t=0){switch(Le(r)){case 8:e.set(t++,r&255|W),r/=128;case 7:e.set(t++,r&255|W),r/=128;case 6:e.set(t++,r&255|W),r/=128;case 5:e.set(t++,r&255|W),r/=128;case 4:e.set(t++,r&255|W),r>>>=7;case 3:e.set(t++,r&255|W),r>>>=7;case 2:e.set(t++,r&255|W),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function ti(r,e){let t=r[e],n=0;if(n+=t&we,t<W||(t=r[e+1],n+=(t&we)<<7,t<W)||(t=r[e+2],n+=(t&we)<<14,t<W)||(t=r[e+3],n+=(t&we)<<21,t<W)||(t=r[e+4],n+=(t&we)*js,t<W)||(t=r[e+5],n+=(t&we)*Qs,t<W)||(t=r[e+6],n+=(t&we)*Js,t<W)||(t=r[e+7],n+=(t&we)*ei,t<W))return n;throw new RangeError("Could not decode varint")}function jh(r,e){let t=r.get(e),n=0;if(n+=t&we,t<W||(t=r.get(e+1),n+=(t&we)<<7,t<W)||(t=r.get(e+2),n+=(t&we)<<14,t<W)||(t=r.get(e+3),n+=(t&we)<<21,t<W)||(t=r.get(e+4),n+=(t&we)*js,t<W)||(t=r.get(e+5),n+=(t&we)*Qs,t<W)||(t=r.get(e+6),n+=(t&we)*Js,t<W)||(t=r.get(e+7),n+=(t&we)*ei,t<W))return n;throw new RangeError("Could not decode varint")}function xr(r,e,t=0){return e==null&&(e=Ie(Le(r))),e instanceof Uint8Array?wr(r,e,t):Xh(r,e,t)}function rn(r,e=0){return r instanceof Uint8Array?ti(r,e):jh(r,e)}var ni=new Float32Array([-0]),Dt=new Uint8Array(ni.buffer);function ou(r,e,t){ni[0]=r,e[t]=Dt[0],e[t+1]=Dt[1],e[t+2]=Dt[2],e[t+3]=Dt[3]}function su(r,e){return Dt[0]=r[e],Dt[1]=r[e+1],Dt[2]=r[e+2],Dt[3]=r[e+3],ni[0]}var oi=new Float64Array([-0]),xe=new Uint8Array(oi.buffer);function iu(r,e,t){oi[0]=r,e[t]=xe[0],e[t+1]=xe[1],e[t+2]=xe[2],e[t+3]=xe[3],e[t+4]=xe[4],e[t+5]=xe[5],e[t+6]=xe[6],e[t+7]=xe[7]}function au(r,e){return xe[0]=r[e],xe[1]=r[e+1],xe[2]=r[e+2],xe[3]=r[e+3],xe[4]=r[e+4],xe[5]=r[e+5],xe[6]=r[e+6],xe[7]=r[e+7],oi[0]}var Qh=BigInt(Number.MAX_SAFE_INTEGER),Jh=BigInt(Number.MIN_SAFE_INTEGER),Ue=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 Ht;if(e<Qh&&e>Jh)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>cu&&(o=0n,++n>cu&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return Ht;let t=e<0;t&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}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):Ht}},Ht=new Ue(0,0);Ht.toBigInt=function(){return 0n};Ht.zzEncode=Ht.zzDecode=function(){return this};Ht.length=function(){return 1};var cu=4294967296n;function uu(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 lu(r,e,t){if(t-e<1)return"";let o,s=[],i=0,a;for(;e<t;)a=r[e++],a<128?s[i++]=a:a>191&&a<224?s[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,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function si(r,e,t){let n=t,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function ze(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Zn(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var ii=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,ze(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw ze(this,4);return Zn(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw ze(this,4);return Zn(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw ze(this,4);let e=su(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw ze(this,4);let e=au(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 ze(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return lu(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw ze(this,e);this.pos+=e}else do if(this.pos>=this.len)throw ze(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new Ue(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 ze(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 ze(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 ze(this,8);let e=Zn(this.buf,this.pos+=4),t=Zn(this.buf,this.pos+=4);return new Ue(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=ti(this.buf,this.pos);return this.pos+=Le(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 ai(r){return new ii(r instanceof Uint8Array?r:r.subarray())}function Be(r,e,t){let n=ai(r);return e.decode(n,void 0,t)}function ci(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return Ie(i);o+i>e&&(n=Ie(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var Ft=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function ui(){}var fi=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},ed=ci();function td(r){return globalThis.Buffer!=null?Ie(r):ed(r)}var on=class{len;head;tail;states;constructor(){this.len=0,this.head=new Ft(ui,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new Ft(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new hi((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(Yn,10,Ue.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Ue.fromBigInt(e);return this._push(Yn,t.length(),t)}uint64Number(e){return this._push(wr,Le(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=Ue.fromBigInt(e).zzEncode();return this._push(Yn,t.length(),t)}sint64Number(e){let t=Ue.fromNumber(e).zzEncode();return this._push(Yn,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(li,1,e?1:0)}fixed32(e){return this._push(nn,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Ue.fromBigInt(e);return this._push(nn,4,t.lo)._push(nn,4,t.hi)}fixed64Number(e){let t=Ue.fromNumber(e);return this._push(nn,4,t.lo)._push(nn,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(ou,4,e)}double(e){return this._push(iu,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(li,1,0):this.uint32(t)._push(nd,t,e)}string(e){let t=uu(e);return t!==0?this.uint32(t)._push(si,t,e):this._push(li,1,0)}fork(){return this.states=new fi(this),this.head=this.tail=new Ft(ui,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 Ft(ui,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=td(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function li(r,e,t){e[t]=r&255}function rd(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var hi=class extends Ft{next;constructor(e,t){super(rd,e,t),this.next=void 0}};function Yn(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 nn(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 nd(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(on.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(od,e,r),this},on.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(sd,e,r),this});function od(r,e,t){e.set(r,t)}function sd(r,e,t){r.length<40?si(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(k(r),t)}function di(){return new on}function Re(r,e){let t=di();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var Er;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(Er||(Er={}));function Xn(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function zt(r){function e(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let t=function(s,i){let a=e(s);i.int32(a)},n=function(s){let i=s.int32();return e(i)};return Xn("enum",Er.VARINT,t,n)}function Pe(r,e){return Xn("message",Er.LENGTH_DELIMITED,r,e)}var sn=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var ue;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(ue||(ue={}));var pi;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(pi||(pi={}));(function(r){r.codec=()=>zt(pi)})(ue||(ue={}));var je;(function(r){let e;r.codec=()=>(e==null&&(e=Pe((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),ue.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.Type=ue.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Re(t,r.codec()),r.decode=(t,n)=>Be(t,r.codec(),n)})(je||(je={}));var mi;(function(r){let e;r.codec=()=>(e==null&&(e=Pe((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),ue.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.Type=ue.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Re(t,r.codec()),r.decode=(t,n)=>Be(t,r.codec(),n)})(mi||(mi={}));var cn={};Ae(cn,{MAX_RSA_KEY_SIZE:()=>yi,generateRSAKeyPair:()=>yu,jwkToJWKKeyPair:()=>gu,jwkToPkcs1:()=>ud,jwkToPkix:()=>xi,jwkToRSAPrivateKey:()=>_i,pkcs1MessageToJwk:()=>bi,pkcs1MessageToRSAPrivateKey:()=>Ei,pkcs1ToJwk:()=>cd,pkcs1ToRSAPrivateKey:()=>mu,pkixMessageToJwk:()=>wi,pkixMessageToRSAPublicKey:()=>vi,pkixToJwk:()=>ld,pkixToRSAPublicKey:()=>Si});var jn=kn;var Sr=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=cn.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return le.createV1(114,this._multihash)}toString(){return te.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:fe(this.raw,e.raw)}verify(e,t,n){return pu(this.jwk,t,e,n)}},an=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=cn.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:fe(this.raw,e.raw)}sign(e,t){return du(this.jwk,e,t)}};var yi=8192,gi=18,id=1062,ad=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function cd(r){let e=nt(r);return bi(e)}function bi(r){return{n:z(r[1],"base64url"),e:z(r[2],"base64url"),d:z(r[3],"base64url"),p:z(r[4],"base64url"),q:z(r[5],"base64url"),dp:z(r[6],"base64url"),dq:z(r[7],"base64url"),qi:z(r[8],"base64url"),kty:"RSA"}}function ud(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 ie("JWK was missing components");return Et([Ce(Uint8Array.from([0])),Ce(k(r.n,"base64url")),Ce(k(r.e,"base64url")),Ce(k(r.d,"base64url")),Ce(k(r.p,"base64url")),Ce(k(r.q,"base64url")),Ce(k(r.dp,"base64url")),Ce(k(r.dq,"base64url")),Ce(k(r.qi,"base64url"))]).subarray()}function ld(r){let e=nt(r,{offset:0});return wi(e)}function wi(r){let e=nt(r[1],{offset:0});return{kty:"RSA",n:z(e[0],"base64url"),e:z(e[1],"base64url")}}function xi(r){if(r.n==null||r.e==null)throw new ie("JWK was missing components");return Et([ad,Pn(Et([Ce(k(r.n,"base64url")),Ce(k(r.e,"base64url"))]))]).subarray()}function mu(r){let e=nt(r);return Ei(e)}function Ei(r){let e=bi(r);return _i(e)}function Si(r,e){if(r.byteLength>=id)throw new tr("Key size is too large");let t=nt(r,{offset:0});return vi(t,r,e)}function vi(r,e,t){let n=wi(r);if(t==null){let o=jn(je.encode({Type:ue.RSA,Data:e}));t=We(gi,o)}return new Sr(n,t)}function _i(r){if(wu(r)>yi)throw new ie("Key size is too large");let e=gu(r),t=jn(je.encode({Type:ue.RSA,Data:xi(e.publicKey)})),n=We(gi,t);return new an(e.privateKey,new Sr(e.publicKey,n))}async function yu(r){if(r>yi)throw new ie("Key size is too large");let e=await bu(r),t=jn(je.encode({Type:ue.RSA,Data:xi(e.publicKey)})),n=We(gi,t);return new an(e.privateKey,new Sr(e.publicKey,n))}function gu(r){if(r==null)throw new ie("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function bu(r,e){let t=await qe.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 fd(t,e);return{privateKey:n[0],publicKey:n[1]}}async function du(r,e,t){let n=await qe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let o=await qe.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,e instanceof Uint8Array?e:e.subarray());return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function pu(r,e,t,n){let o=await qe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let s=await qe.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,e,t instanceof Uint8Array?t:t.subarray());return n?.signal?.throwIfAborted(),s}async function fd(r,e){if(r.privateKey==null||r.publicKey==null)throw new ie("Private and public key are required");let t=await Promise.all([qe.get().subtle.exportKey("jwk",r.privateKey),qe.get().subtle.exportKey("jwk",r.publicKey)]);return e?.signal?.throwIfAborted(),t}function wu(r){if(r.kty!=="RSA")throw new ie("invalid key type");if(r.n==null)throw new ie("invalid key modulus");return k(r.n,"base64url").length*8}var Qn=class extends lr{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,On(e);let n=$r(t);if(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 o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?e.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=e.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),it(s)}update(e){return fr(this),this.iHash.update(e),this}digestInto(e){fr(this),De(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:t,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,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()}},Ai=(r,e,t)=>new Qn(r,e).update(t).digest();Ai.create=(r,e)=>new Qn(r,e);var xu=(r,e)=>(r+(r>=0?e:-e)/Eu)/e;function hd(r,e,t){let[[n,o],[s,i]]=e,a=xu(i*r,t),c=xu(-o*r,t),u=r-a*n-c*s,l=-a*o-c*i,h=u<yt,f=l<yt;h&&(u=-u),f&&(l=-l);let d=At(Math.ceil(qn(t)/2))+_r;if(u<yt||u>=d||l<yt||l>=d)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:h,k1:u,k2neg:f,k2:l}}function Ii(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function Ti(r,e){let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return ct(t.lowS,"lowS"),ct(t.prehash,"prehash"),t.format!==void 0&&Ii(t.format),t}var Ci=class extends Error{constructor(e=""){super(e)}},mt={Err:Ci,_tlv:{encode:(r,e)=>{let{Err:t}=mt;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,o=Xr(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let s=n>127?Xr(o.length/2|128):"";return Xr(r)+s+o+e},decode(r,e){let{Err:t}=mt,n=0;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let o=e[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new 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}=mt;if(r<yt)throw new e("integer: negative integers are not allowed");let t=Xr(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}=mt;if(r[0]&128)throw new e("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return dr(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=mt,o=Y("signature",r),{v:s,l:i}=n.decode(48,o);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v: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}=mt,n=e.encode(2,t.encode(r.r)),o=e.encode(2,t.encode(r.s)),s=n+o;return e.encode(48,s)}},yt=BigInt(0),_r=BigInt(1),Eu=BigInt(2),Jn=BigInt(3),dd=BigInt(4);function vr(r,e){let{BYTES:t}=r,n;if(typeof e=="bigint")n=e;else{let o=Y("private key",e);try{n=r.fromBytes(o)}catch{throw new Error(`invalid private key: expected ui8a of size ${t}, got ${typeof e}`)}}if(!r.isValidNot0(n))throw new Error("invalid private key: out of range [1..N-1]");return n}function pd(r,e={}){let t=Hn("weierstrass",r,e),{Fp:n,Fn:o}=t,s=t.CURVE,{h:i,n:a}=s;Tt(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:c}=e;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let u=vu(n,o);function l(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function h(L,b,m){let{x:y,y:v}=b.toAffine(),A=n.toBytes(y);if(ct(m,"isCompressed"),m){l();let B=!n.isOdd(v);return Se(Su(B),A)}else return Se(Uint8Array.of(4),A,n.toBytes(v))}function f(L){Oe(L,void 0,"Point");let{publicKey:b,publicKeyUncompressed:m}=u,y=L.length,v=L[0],A=L.subarray(1);if(y===b&&(v===2||v===3)){let B=n.fromBytes(A);if(!n.isValid(B))throw new Error("bad point: is not on curve, wrong x");let T=x(B),I;try{I=n.sqrt(T)}catch(ne){let Q=ne instanceof Error?": "+ne.message:"";throw new Error("bad point: is not on curve, sqrt error"+Q)}l();let O=n.isOdd(I);return(v&1)===1!==O&&(I=n.neg(I)),{x:B,y:I}}else if(y===m&&v===4){let B=n.BYTES,T=n.fromBytes(A.subarray(0,B)),I=n.fromBytes(A.subarray(B,B*2));if(!S(T,I))throw new Error("bad point: is not on curve");return{x:T,y:I}}else throw new Error(`bad point: got length ${y}, expected compressed=${b} or uncompressed=${m}`)}let d=e.toBytes||h,p=e.fromBytes||f;function x(L){let b=n.sqr(L),m=n.mul(b,L);return n.add(n.add(m,n.mul(L,s.a)),s.b)}function S(L,b){let m=n.sqr(b),y=x(L);return n.eql(m,y)}if(!S(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let g=n.mul(n.pow(s.a,Jn),dd),_=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(g,_)))throw new Error("bad curve params: a or b");function w(L,b,m=!1){if(!n.isValid(b)||m&&n.is0(b))throw new Error(`bad point coordinate ${L}`);return b}function C(L){if(!(L instanceof E))throw new Error("ProjectivePoint expected")}function P(L){if(!c||!c.basises)throw new Error("no endo");return hd(L,c.basises,o.ORDER)}let q=pr((L,b)=>{let{X:m,Y:y,Z:v}=L;if(n.eql(v,n.ONE))return{x:m,y};let A=L.is0();b==null&&(b=A?n.ONE:n.inv(v));let B=n.mul(m,b),T=n.mul(y,b),I=n.mul(v,b);if(A)return{x:n.ZERO,y:n.ZERO};if(!n.eql(I,n.ONE))throw new Error("invZ was invalid");return{x:B,y:T}}),K=pr(L=>{if(L.is0()){if(e.allowInfinityPoint&&!n.is0(L.Y))return;throw new Error("bad point: ZERO")}let{x:b,y:m}=L.toAffine();if(!n.isValid(b)||!n.isValid(m))throw new Error("bad point: x or y not field elements");if(!S(b,m))throw new Error("bad point: equation left != right");if(!L.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function N(L,b,m,y,v){return m=new E(n.mul(m.X,L),m.Y,m.Z),b=Jr(y,b),m=Jr(v,m),b.add(m)}class E{constructor(b,m,y){this.X=w("x",b),this.Y=w("y",m,!0),this.Z=w("z",y),Object.freeze(this)}static CURVE(){return s}static fromAffine(b){let{x:m,y}=b||{};if(!b||!n.isValid(m)||!n.isValid(y))throw new Error("invalid affine point");if(b instanceof E)throw new Error("projective point not allowed");return n.is0(m)&&n.is0(y)?E.ZERO:new E(m,y,n.ONE)}static fromBytes(b){let m=E.fromAffine(p(Oe(b,void 0,"point")));return m.assertValidity(),m}static fromHex(b){return E.fromBytes(Y("pointHex",b))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(b=8,m=!0){return U.createCache(this,b),m||this.multiply(Jn),this}assertValidity(){K(this)}hasEvenY(){let{y:b}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(b)}equals(b){C(b);let{X:m,Y:y,Z:v}=this,{X:A,Y:B,Z:T}=b,I=n.eql(n.mul(m,T),n.mul(A,v)),O=n.eql(n.mul(y,T),n.mul(B,v));return I&&O}negate(){return new E(this.X,n.neg(this.Y),this.Z)}double(){let{a:b,b:m}=s,y=n.mul(m,Jn),{X:v,Y:A,Z:B}=this,T=n.ZERO,I=n.ZERO,O=n.ZERO,M=n.mul(v,v),ne=n.mul(A,A),Q=n.mul(B,B),G=n.mul(v,A);return G=n.add(G,G),O=n.mul(v,B),O=n.add(O,O),T=n.mul(b,O),I=n.mul(y,Q),I=n.add(T,I),T=n.sub(ne,I),I=n.add(ne,I),I=n.mul(T,I),T=n.mul(G,T),O=n.mul(y,O),Q=n.mul(b,Q),G=n.sub(M,Q),G=n.mul(b,G),G=n.add(G,O),O=n.add(M,M),M=n.add(O,M),M=n.add(M,Q),M=n.mul(M,G),I=n.add(I,M),Q=n.mul(A,B),Q=n.add(Q,Q),M=n.mul(Q,G),T=n.sub(T,M),O=n.mul(Q,ne),O=n.add(O,O),O=n.add(O,O),new E(T,I,O)}add(b){C(b);let{X:m,Y:y,Z:v}=this,{X:A,Y:B,Z:T}=b,I=n.ZERO,O=n.ZERO,M=n.ZERO,ne=s.a,Q=n.mul(s.b,Jn),G=n.mul(m,A),oe=n.mul(y,B),he=n.mul(v,T),_e=n.add(m,y),se=n.add(A,B);_e=n.mul(_e,se),se=n.add(G,oe),_e=n.sub(_e,se),se=n.add(m,v);let be=n.add(A,T);return se=n.mul(se,be),be=n.add(G,he),se=n.sub(se,be),be=n.add(y,v),I=n.add(B,T),be=n.mul(be,I),I=n.add(oe,he),be=n.sub(be,I),M=n.mul(ne,se),I=n.mul(Q,he),M=n.add(I,M),I=n.sub(oe,M),M=n.add(oe,M),O=n.mul(I,M),oe=n.add(G,G),oe=n.add(oe,G),he=n.mul(ne,he),se=n.mul(Q,se),oe=n.add(oe,he),he=n.sub(G,he),he=n.mul(ne,he),se=n.add(se,he),G=n.mul(oe,se),O=n.add(O,G),G=n.mul(be,se),I=n.mul(_e,I),I=n.sub(I,G),G=n.mul(_e,oe),M=n.mul(be,M),M=n.add(M,G),new E(I,O,M)}subtract(b){return this.add(b.negate())}is0(){return this.equals(E.ZERO)}multiply(b){let{endo:m}=e;if(!o.isValidNot0(b))throw new Error("invalid scalar: out of range");let y,v,A=B=>U.cached(this,B,T=>ft(E,T));if(m){let{k1neg:B,k1:T,k2neg:I,k2:O}=P(b),{p:M,f:ne}=A(T),{p:Q,f:G}=A(O);v=ne.add(G),y=N(m.beta,M,Q,B,I)}else{let{p:B,f:T}=A(b);y=B,v=T}return ft(E,[y,v])[0]}multiplyUnsafe(b){let{endo:m}=e,y=this;if(!o.isValid(b))throw new Error("invalid scalar: out of range");if(b===yt||y.is0())return E.ZERO;if(b===_r)return y;if(U.hasCache(this))return this.multiply(b);if(m){let{k1neg:v,k1:A,k2neg:B,k2:T}=P(b),{p1:I,p2:O}=Xc(E,y,A,T);return N(m.beta,I,O,v,B)}else return U.unsafe(y,b)}multiplyAndAddUnsafe(b,m,y){let v=this.multiplyUnsafe(m).add(b.multiplyUnsafe(y));return v.is0()?void 0:v}toAffine(b){return q(this,b)}isTorsionFree(){let{isTorsionFree:b}=e;return i===_r?!0:b?b(E,this):U.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:b}=e;return i===_r?this:b?b(E,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(b=!0){return ct(b,"isCompressed"),this.assertValidity(),d(E,this,b)}toHex(b=!0){return Ke(this.toBytes(b))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(b=!0){return this.toBytes(b)}_setWindowSize(b){this.precompute(b)}static normalizeZ(b){return ft(E,b)}static msm(b,m){return gr(E,o,b,m)}static fromPrivateKey(b){return E.BASE.multiply(vr(o,b))}}E.BASE=new E(s.Gx,s.Gy,n.ONE),E.ZERO=new E(n.ZERO,n.ONE,n.ZERO),E.Fp=n,E.Fn=o;let D=o.BITS,U=new yr(E,e.endo?Math.ceil(D/2):D);return E.BASE.precompute(8),E}function Su(r){return Uint8Array.of(r?2:3)}function vu(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function md(r,e={}){let{Fn:t}=r,n=e.randomBytes||hr,o=Object.assign(vu(r.Fp,t),{seed:ks(t.ORDER)});function s(d){try{return!!vr(t,d)}catch{return!1}}function i(d,p){let{publicKey:x,publicKeyUncompressed:S}=o;try{let g=d.length;return p===!0&&g!==x||p===!1&&g!==S?!1:!!r.fromBytes(d)}catch{return!1}}function a(d=n(o.seed)){return Ks(Oe(d,o.seed,"seed"),t.ORDER)}function c(d,p=!0){return r.BASE.multiply(vr(t,d)).toBytes(p)}function u(d){let p=a(d);return{secretKey:p,publicKey:c(p)}}function l(d){if(typeof d=="bigint")return!1;if(d instanceof r)return!0;let{secretKey:p,publicKey:x,publicKeyUncompressed:S}=o;if(t.allowedLengths||p===x)return;let g=Y("key",d).length;return g===x||g===S}function h(d,p,x=!0){if(l(d)===!0)throw new Error("first arg must be private key");if(l(p)===!1)throw new Error("second arg must be public key");let S=vr(t,d);return r.fromHex(p).multiply(S).toBytes(x)}return Object.freeze({getPublicKey:c,getSharedSecret:h,keygen:u,Point:r,utils:{isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a,isValidPrivateKey:s,randomPrivateKey:a,normPrivateKeyToScalar:d=>vr(t,d),precompute(d=8,p=r.BASE){return p.precompute(d,!1)}},lengths:o})}function yd(r,e,t={}){On(e),Tt(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let n=t.randomBytes||hr,o=t.hmac||((m,...y)=>Ai(e,m,Se(...y))),{Fp:s,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:u,getPublicKey:l,getSharedSecret:h,utils:f,lengths:d}=md(r,t),p={prehash:!1,lowS:typeof t.lowS=="boolean"?t.lowS:!1,format:void 0,extraEntropy:!1},x="compact";function S(m){let y=a>>_r;return m>y}function g(m,y){if(!i.isValidNot0(y))throw new Error(`invalid signature ${m}: out of range 1..Point.Fn.ORDER`);return y}function _(m,y){Ii(y);let v=d.signature,A=y==="compact"?v:y==="recovered"?v+1:void 0;return Oe(m,A,`${y} signature`)}class w{constructor(y,v,A){this.r=g("r",y),this.s=g("s",v),A!=null&&(this.recovery=A),Object.freeze(this)}static fromBytes(y,v=x){_(y,v);let A;if(v==="der"){let{r:O,s:M}=mt.toSig(Oe(y));return new w(O,M)}v==="recovered"&&(A=y[0],v="compact",y=y.subarray(1));let B=i.BYTES,T=y.subarray(0,B),I=y.subarray(B,B*2);return new w(i.fromBytes(T),i.fromBytes(I),A)}static fromHex(y,v){return this.fromBytes(Mt(y),v)}addRecoveryBit(y){return new w(this.r,this.s,y)}recoverPublicKey(y){let v=s.ORDER,{r:A,s:B,recovery:T}=this;if(T==null||![0,1,2,3].includes(T))throw new Error("recovery id invalid");if(a*Eu<v&&T>1)throw new Error("recovery id is ambiguous for h>1 curve");let O=T===2||T===3?A+a:A;if(!s.isValid(O))throw new Error("recovery id 2 or 3 invalid");let M=s.toBytes(O),ne=r.fromBytes(Se(Su((T&1)===0),M)),Q=i.inv(O),G=P(Y("msgHash",y)),oe=i.create(-G*Q),he=i.create(B*Q),_e=r.BASE.multiplyUnsafe(oe).add(ne.multiplyUnsafe(he));if(_e.is0())throw new Error("point at infinify");return _e.assertValidity(),_e}hasHighS(){return S(this.s)}toBytes(y=x){if(Ii(y),y==="der")return Mt(mt.hexFromSig(this));let v=i.toBytes(this.r),A=i.toBytes(this.s);if(y==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return Se(Uint8Array.of(this.recovery),v,A)}return Se(v,A)}toHex(y){return Ke(this.toBytes(y))}assertValidity(){}static fromCompact(y){return w.fromBytes(Y("sig",y),"compact")}static fromDER(y){return w.fromBytes(Y("sig",y),"der")}normalizeS(){return this.hasHighS()?new w(this.r,i.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Ke(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Ke(this.toBytes("compact"))}}let C=t.bits2int||function(y){if(y.length>8192)throw new Error("input is too large");let v=dr(y),A=y.length*8-c;return A>0?v>>BigInt(A):v},P=t.bits2int_modN||function(y){return i.create(C(y))},q=At(c);function K(m){return jr("num < 2^"+c,m,yt,q),i.toBytes(m)}function N(m,y){return Oe(m,void 0,"message"),y?Oe(e(m),void 0,"prehashed message"):m}function E(m,y,v){if(["recovered","canonical"].some(oe=>oe in v))throw new Error("sign() legacy options not supported");let{lowS:A,prehash:B,extraEntropy:T}=Ti(v,p);m=N(m,B);let I=P(m),O=vr(i,y),M=[K(O),K(I)];if(T!=null&&T!==!1){let oe=T===!0?n(d.secretKey):T;M.push(Y("extraEntropy",oe))}let ne=Se(...M),Q=I;function G(oe){let he=C(oe);if(!i.isValidNot0(he))return;let _e=i.inv(he),se=r.BASE.multiply(he).toAffine(),be=i.create(se.x);if(be===yt)return;let En=i.create(_e*i.create(Q+be*O));if(En===yt)return;let Pa=(se.x===be?0:2)|Number(se.y&_r),Oa=En;return A&&S(En)&&(Oa=i.neg(En),Pa^=1),new w(be,Oa,Pa)}return{seed:ne,k2sig:G}}function D(m,y,v={}){m=Y("message",m);let{seed:A,k2sig:B}=E(m,y,v);return Oc(e.outputLen,i.BYTES,o)(A,B)}function U(m){let y,v=typeof m=="string"||st(m),A=!v&&m!==null&&typeof m=="object"&&typeof m.r=="bigint"&&typeof m.s=="bigint";if(!v&&!A)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(A)y=new w(m.r,m.s);else if(v){try{y=w.fromBytes(Y("sig",m),"der")}catch(B){if(!(B instanceof mt.Err))throw B}if(!y)try{y=w.fromBytes(Y("sig",m),"compact")}catch{return!1}}return y||!1}function L(m,y,v,A={}){let{lowS:B,prehash:T,format:I}=Ti(A,p);if(v=Y("publicKey",v),y=N(Y("message",y),T),"strict"in A)throw new Error("options.strict was renamed to lowS");let O=I===void 0?U(m):w.fromBytes(Y("sig",m),I);if(O===!1)return!1;try{let M=r.fromBytes(v);if(B&&O.hasHighS())return!1;let{r:ne,s:Q}=O,G=P(y),oe=i.inv(Q),he=i.create(G*oe),_e=i.create(ne*oe),se=r.BASE.multiplyUnsafe(he).add(M.multiplyUnsafe(_e));return se.is0()?!1:i.create(se.x)===ne}catch{return!1}}function b(m,y,v={}){let{prehash:A}=Ti(v,p);return y=N(y,A),w.fromBytes(m,"recovered").recoverPublicKey(y).toBytes()}return Object.freeze({keygen:u,getPublicKey:l,getSharedSecret:h,utils:f,lengths:d,Point:r,sign:D,verify:L,recoverPublicKey:b,Signature:w,hash:e})}function gd(r){let e={a:r.a,b:r.b,p:r.Fp.ORDER,n:r.n,h:r.h,Gx:r.Gx,Gy:r.Gy},t=r.Fp,n=r.allowedPrivateKeyLengths?Array.from(new Set(r.allowedPrivateKeyLengths.map(i=>Math.ceil(i/2)))):void 0,o=Ne(e.n,{BITS:r.nBitLength,allowedLengths:n,modFromBytes:r.wrapPrivateKey}),s={Fp:t,Fn:o,allowInfinityPoint:r.allowInfinityPoint,endo:r.endo,isTorsionFree:r.isTorsionFree,clearCofactor:r.clearCofactor,fromBytes:r.fromBytes,toBytes:r.toBytes};return{CURVE:e,curveOpts:s}}function bd(r){let{CURVE:e,curveOpts:t}=gd(r),n={hmac:r.hmac,randomBytes:r.randomBytes,lowS:r.lowS,bits2int:r.bits2int,bits2int_modN:r.bits2int_modN};return{CURVE:e,curveOpts:t,hash:r.hash,ecdsaOpts:n}}function wd(r,e){let t=e.Point;return Object.assign({},e,{ProjectivePoint:t,CURVE:Object.assign({},r,Vn(t.Fn.ORDER,t.Fn.BITS))})}function _u(r){let{CURVE:e,curveOpts:t,hash:n,ecdsaOpts:o}=bd(r),s=pd(e,t),i=yd(s,n,o);return wd(r,i)}function Au(r,e){let t=n=>_u({...r,hash:n});return{...t(e),create:t}}var Li={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},xd={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Tu=BigInt(2);function Ed(r){let e=Li.p,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=r*r*r%e,l=u*u*r%e,h=ee(l,t,e)*l%e,f=ee(h,t,e)*l%e,d=ee(f,Tu,e)*u%e,p=ee(d,o,e)*d%e,x=ee(p,s,e)*p%e,S=ee(x,a,e)*x%e,g=ee(S,c,e)*S%e,_=ee(g,a,e)*x%e,w=ee(_,t,e)*l%e,C=ee(w,i,e)*p%e,P=ee(C,n,e)*u%e,q=ee(P,Tu,e);if(!Di.eql(Di.sqr(q),r))throw new Error("Cannot find square root");return q}var Di=Ne(Li.p,{sqrt:Ed}),Ar=Au({...Li,Fp:Di,lowS:!0,endo:xd},kn);function Iu(r,e,t,n){let o=cr.digest(t instanceof Uint8Array?t:t.subarray());if($n(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),Ar.verify(e,s,r))).catch(s=>{throw s.name==="AbortError"?s:new tn(String(s))});try{return n?.signal?.throwIfAborted(),Ar.verify(e,o.digest,r)}catch(s){throw new tn(String(s))}}var eo=class{type="secp256k1";raw;_key;constructor(e){this._key=Du(e),this.raw=Cu(this._key)}toMultihash(){return He.digest(Ye(this))}toCID(){return le.createV1(114,this.toMultihash())}toString(){return te.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:fe(this.raw,e.raw)}verify(e,t,n){return Iu(this._key,t,e,n)}};function Bi(r){return new eo(r)}function Cu(r){return Ar.ProjectivePoint.fromHex(r).toRawBytes(!0)}function Du(r){try{return Ar.ProjectivePoint.fromHex(r),r}catch(e){throw new tr(String(e))}}function Lu(r,e){let{Type:t,Data:n}=je.decode(r),o=n??new Uint8Array;switch(t){case ue.RSA:return Si(o,e);case ue.Ed25519:return Xs(o);case ue.secp256k1:return Bi(o);case ue.ECDSA:return _s(o);default:throw new rr}}function Bu(r){let{Type:e,Data:t}=je.decode(r.digest),n=t??new Uint8Array;switch(e){case ue.Ed25519:return Xs(n);case ue.secp256k1:return Bi(n);case ue.ECDSA:return _s(n);default:throw new rr}}function Ye(r){return je.encode({Type:ue[r.type],Data:r.raw})}var Ru=Symbol.for("nodejs.util.inspect.custom"),Sd=114,un=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()})`}[Xo]=!0;toString(){return this.string==null&&(this.string=te.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return le.createV1(Sd,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return fe(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return fe(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Ru](){return`PeerId(${this.toString()})`}},to=class extends un{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},ro=class extends un{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},no=class extends un{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},vd=2336,ln=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=He.digest(k(this.url))}[Ru](){return`PeerId(${this.url})`}[Xo]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return le.createV1(vd,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=z(e)),e.toString()===this.toString())}};var _d=114,Pu=2336;function Ri(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=Ze(te.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return Ad(le.parse(r));if(e==null)throw new ie('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=Ze(e.decode(r))}return Tr(t)}function Tr(r){if(Id(r))return new to({multihash:r});if(Td(r))try{let e=Bu(r);if(e.type==="Ed25519")return new ro({multihash:r,publicKey:e});if(e.type==="secp256k1")return new no({multihash:r,publicKey:e})}catch{let t=z(r.digest);return new ln(new URL(t))}throw new _n("Supplied PeerID Multihash is invalid")}function Ad(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==_d&&r.code!==Pu)throw new vn("Supplied PeerID CID is invalid");if(r.code===Pu){let e=z(r.multihash.digest);return new ln(new URL(e))}return Tr(r.multihash)}function Td(r){return r.code===He.code}function Id(r){return r.code===cr.code}var fn;(function(r){let e;r.codec=()=>(e==null&&(e=Pe((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.publicKey!=null&&t.publicKey.byteLength>0&&(n.uint32(10),n.bytes(t.publicKey)),t.payloadType!=null&&t.payloadType.byteLength>0&&(n.uint32(18),n.bytes(t.payloadType)),t.payload!=null&&t.payload.byteLength>0&&(n.uint32(26),n.bytes(t.payload)),t.signature!=null&&t.signature.byteLength>0&&(n.uint32(42),n.bytes(t.signature)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={publicKey:re(0),payloadType:re(0),payload:re(0),signature:re(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.publicKey=t.bytes();break}case 2:{s.payloadType=t.bytes();break}case 3:{s.payload=t.bytes();break}case 5:{s.signature=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Re(t,r.codec()),r.decode=(t,n)=>Be(t,r.codec(),n)})(fn||(fn={}));var oo=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var hn=class r{static createFromProtobuf=e=>{let t=fn.decode(e),n=Lu(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 o=e.domain,s=e.codec,i=e.marshal(),a=Ou(o,s,i),c=await t.sign(a.subarray(),n);return new r({publicKey:t.publicKey,payloadType:s,payload:i,signature:c})};static openAndCertify=async(e,t,n)=>{let o=r.createFromProtobuf(e);if(!await o.validate(t,n))throw new oo("Envelope signature is not valid for the given domain");return o};publicKey;payloadType;payload;signature;marshaled;constructor(e){let{publicKey:t,payloadType:n,payload:o,signature:s}=e;this.publicKey=t,this.payloadType=n,this.payload=o,this.signature=s}marshal(){return this.marshaled==null&&(this.marshaled=fn.encode({publicKey:Ye(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return e==null?!1:fe(this.marshal(),e.marshal())}async validate(e,t){let n=Ou(e,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,t)}},Ou=(r,e,t)=>{let n=k(r),o=xr(n.byteLength),s=xr(e.length),i=xr(t.length);return new J(o,n,s,e,i,t)};var ge=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},gt=class extends Error{static name="ValidationError";name="ValidationError"},so=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},io=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var ao=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,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*o)-1;for(;;){let l=this.readAtomically(()=>{let h=this.readChar();if(h===void 0)return;let f=Number.parseInt(h,e);if(!Number.isNaN(f))return f});if(l===void 0)break;if(s*=e,s+=l,s>u||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:s})}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 o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Cd=45,Dd=15,co=new ao;function Nu(r){if(!(r.length>Dd))return co.new(r).parseWith(()=>co.readIPv4Addr())}function Uu(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Cd))return co.new(r).parseWith(()=>co.readIPv6Addr())}function uo(r){return!!Nu(r)}function Mu(r){return!!Uu(r)}function Oi(r){return e=>z(e,r)}function Ni(r){return e=>k(e,r)}function Ir(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Gt(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function ku(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=k(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Gt(n);return rt([t,o],t.length+o.length)}function Ku(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=xt.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Gt(n);return rt([t,o],t.length+o.length)}function Ui(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=z(e,"base32"),o=Ir(t);return`${n}:${o}`}var Mi=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let o=parseInt(t,10);if(isNaN(o)||o<0||o>255)throw new ge("Invalid byte value in IP address");e[n]=o}),e},qu=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=uo(t[n]),i;s&&(i=Mi(t[n]),t[n]=z(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,z(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 s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let s=parseInt(t[n],16);if(isNaN(s)||s<0||s>65535)throw new ge("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},Vu=function(r){if(r.byteLength!==4)throw new ge("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},Hu=function(r){if(r.byteLength!==16)throw new ge("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],s=r[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;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 ge(`Invalid IPv6 address "${t}"`)}};function Fu(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new ge(`Invalid IPv6 address "${r}"`)}}var Pi=Object.values(Hr).map(r=>r.decoder),Ld=(function(){let r=Pi[0].or(Pi[1]);return Pi.slice(2).forEach(e=>r=r.or(e)),r})();function zu(r){return Ld.decode(r)}function Gu(r){return e=>r.encoder.encode(e)}function Bd(r){if(parseInt(r).toString()!==r)throw new gt("Value must be an integer")}function Rd(r){if(r<0)throw new gt("Value must be a positive integer, or zero")}function Pd(r){return e=>{if(e>r)throw new gt(`Value must be smaller than or equal to ${r}`)}}function Od(...r){return e=>{for(let t of r)t(e)}}var dn=Od(Bd,Rd,Pd(65535));var me=-1,ki=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 io(`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)}))}},bt=new ki,Yd=[{code:4,name:"ip4",size:32,valueToBytes:Mi,bytesToValue:Vu,validate:r=>{if(!uo(r))throw new gt(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Gt,bytesToValue:Ir,validate:dn},{code:273,name:"udp",size:16,valueToBytes:Gt,bytesToValue:Ir,validate:dn},{code:33,name:"dccp",size:16,valueToBytes:Gt,bytesToValue:Ir,validate:dn},{code:41,name:"ip6",size:128,valueToBytes:qu,bytesToValue:Hu,stringToValue:Fu,validate:r=>{if(!Mu(r))throw new gt(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:me},{code:43,name:"ipcidr",size:8,bytesToValue:Oi("base10"),valueToBytes:Ni("base10")},{code:53,name:"dns",size:me},{code:54,name:"dns4",size:me},{code:55,name:"dns6",size:me},{code:56,name:"dnsaddr",size:me},{code:132,name:"sctp",size:16,valueToBytes:Gt,bytesToValue:Ir,validate:dn},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:me,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:me,bytesToValue:Oi("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Ni("base58btc")(r):le.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Ui,valueToBytes:ku},{code:445,name:"onion3",size:296,bytesToValue:Ui,valueToBytes:Ku},{code:446,name:"garlic64",size:me},{code:447,name:"garlic32",size:me},{code:448,name:"tls"},{code:449,name:"sni",size:me},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:me,bytesToValue:Gu(fs),valueToBytes:zu},{code:480,name:"http"},{code:481,name:"http-path",size:me,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:me}];Yd.forEach(r=>{bt.addProtocol(r)});function $u(r){let e=[],t=0;for(;t<r.length;){let n=rn(r,t),o=bt.getProtocol(n),s=Le(n),i=Xd(o,r,t+s),a=0;i>0&&o.size===me&&(a=Le(i));let c=s+a+i,u={code:n,name:o.name,bytes:r.subarray(t,t+c)};if(i>0){let l=t+s+a,h=r.subarray(l,l+i);u.value=o.bytesToValue?.(h)??z(h)}e.push(u),t+=c}return e}function Wu(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=bt.getProtocol(n.code),s=Le(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??k(n.value),a=i.byteLength,o.size===me&&(c=Le(a)));let u=new Uint8Array(s+c+a),l=0;wr(n.code,u,l),l+=s,i!=null&&(o.size===me&&(wr(a,u,l),l+=c),u.set(i,l)),n.bytes=u}t.push(n.bytes),e+=n.bytes.byteLength}return rt(t,e)}function Zu(r){if(r.charAt(0)!=="/")throw new ge('String multiaddr must start with "/"');let e=[],t="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(t==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=bt.getProtocol(o);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",t="protocol";continue}else if(a)throw new ge(`Component ${o} 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 ge(`Component ${o} was missing value`);u.value=c.stringToValue?.(n)??n}e.push(u),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new ge("Incomplete multiaddr");return e}function Yu(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=bt.getProtocol(e.code);if(t==null)throw new ge(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function Xd(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:rn(e,t)}var jd=Symbol.for("nodejs.util.inspect.custom"),ta=Symbol.for("@multiformats/multiaddr");function Qd(r){if(r==null&&(r="/"),Xu(r))return r.getComponents();if(r instanceof Uint8Array)return $u(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),Zu(r);if(Array.isArray(r))return r;throw new ge("Must be a string, Uint8Array, Component[], or another Multiaddr")}var po=class r{[ta]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=Qd(e),t.validate!==!1&&Jd(this)}get bytes(){return this.#r==null&&(this.#r=Wu(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=Yu(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(),o=n.lastIndexOf(t);if(o<0)throw new so(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,o),{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 fe(this.bytes,e.bytes)}[jd](){return`Multiaddr(${this.toString()})`}};function Jd(r){r.getComponents().forEach(e=>{let t=bt.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function Xu(r){return!!r?.[ta]}function Me(r){return new po(r)}var ra={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},ju={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Qu=new globalThis.TextEncoder;function ep(r,e){let t=ra[e],n=ju[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function tp(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=ra[e],o=ju[e],s=r;for(;s.length>0;){let i=Qu.encodeInto(s,t);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(t[a]),o=BigInt.asUintN(e,o*n)}return o}function na(r,{size:e=32,utf8Buffer:t}={}){if(!ra[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 tp(r,e,t);r=Qu.encode(r)}return ep(r,e)}var pn={hash:r=>Number(na(r,{size:32})),hashV:(r,e)=>rp(pn.hash(r,e))};function rp(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),k(e,"base16")}var oa=64,Ge=class{fp;h;seed;constructor(e,t,n,o=2){if(o>oa)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),i=re(o);for(let a=0;a<i.length;a++)i[a]=s[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?fe(this.fp,e.fp):!1}};function Yt(r,e){return Math.floor(Math.random()*(e-r))+r}var Xt=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof Ge))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof Ge))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 Ge))throw new TypeError("Invalid Fingerprint");let t=Yt(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof Ge))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var np=500,mn=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??pn,this.seed=e.seed??Yt(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=k(e));let t=new Ge(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new Xt(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new Xt(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let s=[n,o],i=s[Yt(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new Xt(this.bucketSize));for(let a=0;a<np;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 Xt(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=k(e));let t=new Ge(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let s=(n^t.hash())%this.filterSize;return this.buckets[s]?.has(t)??!1}remove(e){typeof e=="string"&&(e=k(e));let t=new Ge(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let s=(n^t.hash())%this.filterSize,i=this.buckets[s]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},op={1:.5,2:.84,4:.95,8:.98};function sp(r=.001){return r>.002?2:r>1e-5?4:8}function Ju(r,e=.001){let t=sp(e),n=op[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),oa);return{filterSize:o,bucketSize:t,fingerprintSize:s}}var mo=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??pn,this.seed=e.seed??Yt(0,Math.pow(2,10)),this.filterSeries=[new mn({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=k(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new mn({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=k(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=k(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 Br(r,e=.001,t){return new mo({...Ju(r,e),...t??{}})}function $e(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var yo=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},Rr=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new yo(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 yo(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 ip(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 ip(r,e){e=e??{};let t=e.onEnd,n=new Rr,o,s,i,a=$e(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((S,g)=>{s=_=>{s=null,n.push(_);try{S(r(n))}catch(w){g(w)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=$e()})}},u=S=>s!=null?s(S):(n.push(S),o),l=S=>(n=new Rr,s!=null?s({error:S}):(n.push({error:S}),o)),h=S=>{if(i)return o;if(e?.objectMode!==!0&&S?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:S})},f=S=>i?o:(i=!0,S!=null?l(S):u({done:!0})),d=()=>(n=new Rr,f(),{done:!0}),p=S=>(f(S),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:d,throw:p,push:h,end:f,get readableLength(){return n.size},onEmpty:async S=>{let g=S?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let _,w;g!=null&&(_=new Promise((C,P)=>{w=()=>{P(new sa)},g.addEventListener("abort",w)}));try{await Promise.race([a.promise,_])}finally{w!=null&&g!=null&&g?.removeEventListener("abort",w)}}},t==null)return o;let x=o;return o={[Symbol.asyncIterator](){return this},next(){return x.next()},throw(S){return x.throw(S),t!=null&&(t(S),t=void 0),{done:!0}},return(){return x.return(),t!=null&&(t(),t=void 0),{done:!0}},push:h,end(S){return x.end(S),t!=null&&(t(S),t=void 0),o},get readableLength(){return x.readableLength},onEmpty:S=>x.onEmpty(S)},o}var ia=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},aa=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},el=r=>globalThis.DOMException===void 0?new aa(r):new DOMException(r),tl=r=>{let e=r.reason===void 0?el("This operation was aborted."):r.reason;return e instanceof Error?e:el(e)};function ca(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=e,i,a,u=new Promise((l,h)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:d}=e;d.aborted&&h(tl(d)),a=()=>{h(tl(d))},d.addEventListener("abort",a,{once:!0})}if(t===Number.POSITIVE_INFINITY){r.then(l,h);return}let f=new ia;i=s.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(d){h(d)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?l():o instanceof Error?h(o):(f.message=o??`Promise timed out after ${t} milliseconds`,h(f))},t),(async()=>{try{l(await r)}catch(d){h(d)}})()}).finally(()=>{u.clear(),a&&e.signal&&e.signal.removeEventListener("abort",a)});return u.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},u}var ap=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 cp(r,e,t){let n,o=new Promise((s,i)=>{if(t={rejectionEvents:["error"],multiArgs:!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}=ap(r),h=(...d)=>{let p=t.multiArgs?d:d[0];t.filter&&!t.filter(p)||(c.push(p),t.count===c.length&&(n(),s(c)))},f=d=>{n(),i(d)};n=()=>{for(let d of a)l(d,h);for(let d of t.rejectionEvents)l(d,f)};for(let d of a)u(d,h);for(let d of t.rejectionEvents)u(d,f);t.signal&&t.signal.addEventListener("abort",()=>{f(t.signal.reason)},{once:!0}),t.resolveImmediately&&s(c)});if(o.cancel=n,typeof t.timeout=="number"){let s=ca(o,{milliseconds:t.timeout});return s.cancel=n,s}return o}function Qe(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=cp(r,e,t),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function ua(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var go=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}},jt=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"};function up(r){return r.reason}async function bo(r,e,t){if(e==null)return r;let n=t?.translateError??up;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let o;try{return await Promise.race([r,new Promise((s,i)=>{o=()=>{i(n(e))},e.addEventListener("abort",o)})])}finally{o!=null&&e.removeEventListener("abort",o)}}var wo=class{deferred;signal;constructor(e){this.signal=e,this.deferred=$e(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Je)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function lp(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var xo=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=lp(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,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 Je),this.cleanup())}async join(e={}){let t=new wo(e.signal);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 bo(this.fn({...this.options??{},signal:this.controller.signal}),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 Eo=class extends Te{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=ua(this.emitEmpty.bind(this),1),this.emitIdle=ua(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 go;let n=new xo(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),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 s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Je)}),this.clear()}async onEmpty(e){this.size!==0&&await Qe(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await Qe(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Qe(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)},o=c=>{c.detail!=null&&t.push(c.detail)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new Je("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var fp=Math.pow(2,20)*4,So=class extends Te{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??fp,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new J,this.writeBuffer=new J,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,this.processSendQueue())};this.addEventListener("drain",t)}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let e=Lt(),t=s=>{e.push(s.data)};this.addEventListener("message",t);let n=s=>{e.end(s.error)};this.addEventListener("close",n);let o=()=>{e.end()};this.addEventListener("remoteCloseWrite",o);try{yield*e}finally{this.removeEventListener("message",t),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",o)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new Ot(`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 Cn(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Ot("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 Ot("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 Ot(`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)}}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 Sn;this.dispatchEvent(new Dn(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 nr))}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;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 o=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(o===0){e=!1;break}let s=this.writeBuffer.sublist(0,o),i=new J(s);this.writeBuffer.consume(s.byteLength);let a=this.sendData(s);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 In(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 Mr(`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 Mr(`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 vo=class extends So{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 Qe(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 Qe(this,"drain",{...e,rejectionEvents:["close"]})),await this.sendClose(e),this.onTransportClosed())}};function _o(r){let e=new globalThis.AbortController;function t(){e.abort();for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}for(let s of r){if(s?.aborted===!0){t();break}s?.addEventListener!=null&&s.addEventListener("abort",t)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}var Ao=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"}};async function rl(r,e,t){if(e==null)return r;if(e.aborted)return r.catch(()=>{}),Promise.reject(new Ao(t?.errorMessage,t?.errorCode,t?.errorName));let n,o=new Ao(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var la=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=$e(),this.haveNext=$e()}[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=$e(),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=$e(),await rl(this.readNext.promise,t?.signal,t)}};function nl(){return new la}function hp(r){return r[Symbol.asyncIterator]!=null}async function dp(r,e,t){try{await Promise.all(r.map(async n=>{for await(let o of n)await e.push(o,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*pp(r){let e=new AbortController,t=nl();dp(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*mp(r){for(let e of r)yield*e}function yp(...r){let e=[];for(let t of r)hp(t)||e.push(t);return e.length===r.length?mp(e):pp(r)}var ol=yp;function sl(r,...e){if(r==null)throw new Error("Empty pipeline");if(fa(r)){let n=r;r=()=>n.source}else if(al(r)||il(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&fa(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++)fa(t[n])&&(t[n]=bp(t[n]));return gp(...t)}var gp=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},il=r=>r?.[Symbol.asyncIterator]!=null,al=r=>r?.[Symbol.iterator]!=null,fa=r=>r==null?!1:r.sink!=null&&r.source!=null,bp=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 o,s=r.source;if(il(s))o=async function*(){yield*s,n.end()};else if(al(s))o=function*(){yield*s,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return ol(n,o())}return r.source};var wp=4194304,To=class extends Error{static name="UnwrappedError";name="UnwrappedError"},da=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},pa=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},ma=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function xp(r){return typeof r?.closeRead=="function"}function Ep(r){return typeof r?.close=="function"}function ha(r){return xp(r)?r.readStatus==="closing"||r.readStatus==="closed":Ep(r)?r.status!=="open":!1}function Sp(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function vp(r,e){let t=e?.maxBufferSize??wp,n=new J,o=Promise.withResolvers(),s=!1;if(!Sp(r))throw new ie("Argument should be a Stream or a Multiaddr");let i=l=>{if(n.append(l.data),n.byteLength>t){let h=n.byteLength;n.consume(n.byteLength),o.reject(new Error(`Read buffer overflow - ${h} > ${t}`))}o.resolve()};r.addEventListener("message",i);let a=l=>{l.error!=null?o.reject(l.error):o.resolve()};r.addEventListener("close",a);let c=()=>{o.resolve()};r.addEventListener("remoteCloseWrite",c);let u={readBuffer:n,async read(l){if(s===!0)throw new To("Stream was unwrapped");if(ha(r)){if(l?.bytes==null)return null;if(n.byteLength<l.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,l.bytes),new jt(`Unexpected EOF - stream closed after reading ${n.byteLength}/${l.bytes} bytes`)}let h=l?.bytes??1;for(;;){if(n.byteLength>=h){o.resolve();break}if(await bo(o.promise,l?.signal),ha(r)){if(n.byteLength===0&&l?.bytes==null)return null;break}o=Promise.withResolvers()}let f=l?.bytes??n.byteLength;if(n.byteLength<f){if(ha(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,f),new jt(`Unexpected EOF - stream closed while reading ${n.byteLength}/${f} bytes`);return u.read(l)}let d=n.sublist(0,f);return n.consume(f),d},async write(l,h){if(s===!0)throw new To("Stream was unwrapped");r.send(l)||await Qe(r,"drain",{signal:h?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,r.removeEventListener("message",i),r.removeEventListener("close",a),r.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.push(n))),r}};return u}function _p(r,e={}){let t=vp(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=Le(e.maxDataLength));let n=e?.lengthDecoder??rn,o=e?.lengthEncoder??xr;return{async read(i){let a=-1,c=new J;for(;;){let l=await t.read({...i,bytes:1});if(l==null)break;c.append(l);try{a=n(c)}catch(h){if(h instanceof RangeError)continue;throw h}if(a<0)throw new da("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new ma(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new pa(`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 jt(`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 jt(`Unexpected EOF - read ${u.byteLength}/${a} bytes before the stream closed`);return u},async write(i,a){await t.write(new J(o(i.byteLength),i),a)},async writeV(i,a){let c=new J(...i.flatMap(u=>[o(u.byteLength),u]));await t.write(c,a)},unwrap(){return t.unwrap()}}}function Bt(r,e){let t=_p(r,e),n={read:async(o,s)=>{let i=await t.read(s);return o.decode(i)},write:async(o,s,i)=>{await t.write(s.encode(o),i)},writeV:async(o,s,i)=>{await t.writeV(o.map(a=>s.encode(a)),i)},pb:o=>({read:async s=>n.read(o,s),write:async(s,i)=>n.write(s,o,i),writeV:async(s,i)=>n.writeV(s,o,i),unwrap:()=>n}),unwrap:()=>t.unwrap()};return n}function Ap(r){return r?.addEventListener!=null}function Tp(r){let e=Lt(),t,n=i=>{e.push(i.data)},o=()=>{e.end(),r.removeEventListener("message",n),r.removeEventListener("close",s),r.removeEventListener("remoteCloseWrite",o)},s=i=>{e.end(i.error),i.error!=null&&t?.reject(i.error),r.removeEventListener("message",n),r.removeEventListener("close",s),r.removeEventListener("remoteCloseWrite",o)};return r.addEventListener("message",n),r.addEventListener("close",s,{once:!0}),r.addEventListener("remoteCloseWrite",o,{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([Qe(r,"drain",{rejectionEvents:["close"]})])),u===!0))break}await r.close()}}}function cl(...r){let e=r.map(t=>Ap(t)?Tp(t):t);return sl(...e)}var Pr=class extends Eo{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var X=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),R=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),ul=r=>({match:e=>r.match(e)===!1?e:!1}),H=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),Ee=(...r)=>({match:e=>{let t;for(let n of r){let o=n.match(e);o!==!1&&(t==null||o.length<t.length)&&(t=o)}return t??!1}}),$=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e}});function j(...r){function e(o){if(o==null)return!1;let s=o.getComponents();for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function t(o){return e(o)!==!1}function n(o){let s=e(o);return s===!1?!1:s.length===0}return{matchers:r,matches:t,exactMatch:n}}var Ip=R(421),FE=j(Ip),Co=R(54),Do=R(55),Lo=R(56),ga=R(53),zE=j(Co,H(R(421))),GE=j(Do,H(R(421))),$E=j(Lo,H(R(421))),WE=j(Ee(ga,Lo,Co,Do),H(R(421))),ll=$(R(4),H(R(43))),fl=$(H(R(42)),R(41),H(R(43))),ba=Ee(ll,fl),Qt=Ee(ba,ga,Co,Do,Lo),ZE=j(Ee(ba,$(Ee(ga,Lo,Co,Do),H(R(421))))),YE=j(ll),XE=j(fl),jE=j(ba),wa=$(Qt,R(6)),yn=$(Qt,R(273)),QE=j($(wa,H(R(421)))),JE=j(yn),xa=$(yn,X(460),H(R(421))),Bo=$(yn,X(461),H(R(421))),Cp=Ee(xa,Bo),e2=j(xa),t2=j(Bo),ya=Ee(Qt,wa,yn,xa,Bo),hl=Ee($(ya,X(477),H(R(421)))),r2=j(hl),dl=Ee($(ya,X(478),H(R(421))),$(ya,X(448),H(R(449)),X(477),H(R(421)))),n2=j(dl),pl=$(yn,X(280),H(R(466)),H(R(466)),H(R(421))),o2=j(pl),ml=$(Bo,X(465),H(R(466)),H(R(466)),H(R(421))),s2=j(ml),Io=Ee(hl,dl,$(wa,H(R(421))),$(Cp,H(R(421))),$(Qt,H(R(421))),pl,ml,R(421)),yl=j(Io),Dp=$(H(Io),X(290),ul(X(281)),H(R(421))),Jt=j(Dp),Lp=Ee($(Io,X(290),X(281),H(R(421))),$(Io,X(281),H(R(421))),$(X(281),H(R(421)))),i2=j(Lp),Bp=Ee($(Qt,R(6),X(480),H(R(421))),$(Qt,X(480),H(R(421)))),a2=j(Bp),Rp=$(Qt,Ee($(R(6,"443"),X(480)),$(R(6),X(443)),$(R(6),X(448),X(480)),$(X(448),X(480)),X(448),X(443)),H(R(421))),c2=j(Rp),Pp=Ee($(R(777),H(R(421)))),u2=j(Pp),Op=Ee($(R(400),H(R(421)))),l2=j(Op);var Ea=1e3,gl=60*Ea,bl=15,wl=120*gl,xl=1,Ro=5e3,El=100,Sa="circuit-relay-source",gn=`${Na}-circuit-relay`,Sl=2*gl,vl=BigInt(1<<17),Ve="/libp2p/circuit/relay/0.2.0/hop",er="/libp2p/circuit/relay/0.2.0/stop",_l=30*Ea,d2=30*Ea,bn=300,Al=4096,Tl=.001;var Z;(function(r){let e;(function(o){o.RESERVE="RESERVE",o.CONNECT="CONNECT",o.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(o){o[o.RESERVE=0]="RESERVE",o[o.CONNECT=1]="CONNECT",o[o.STATUS=2]="STATUS"})(t||(t={})),(function(o){o.codec=()=>zt(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Pe((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.type!=null&&(s.uint32(8),r.Type.codec().encode(o.type,s)),o.peer!=null&&(s.uint32(18),Or.codec().encode(o.peer,s)),o.reservation!=null&&(s.uint32(26),Po.codec().encode(o.reservation,s)),o.limit!=null&&(s.uint32(34),Nr.codec().encode(o.limit,s)),o.status!=null&&(s.uint32(40),V.codec().encode(o.status,s)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let u=o.uint32();switch(u>>>3){case 1:{a.type=r.Type.codec().decode(o);break}case 2:{a.peer=Or.codec().decode(o,o.uint32(),{limits:i.limits?.peer});break}case 3:{a.reservation=Po.codec().decode(o,o.uint32(),{limits:i.limits?.reservation});break}case 4:{a.limit=Nr.codec().decode(o,o.uint32(),{limits:i.limits?.limit});break}case 5:{a.status=V.codec().decode(o);break}default:{o.skipType(u&7);break}}}return a})),n),r.encode=o=>Re(o,r.codec()),r.decode=(o,s)=>Be(o,r.codec(),s)})(Z||(Z={}));var ke;(function(r){let e;(function(o){o.CONNECT="CONNECT",o.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(o){o[o.CONNECT=0]="CONNECT",o[o.STATUS=1]="STATUS"})(t||(t={})),(function(o){o.codec=()=>zt(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Pe((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.type!=null&&(s.uint32(8),r.Type.codec().encode(o.type,s)),o.peer!=null&&(s.uint32(18),Or.codec().encode(o.peer,s)),o.limit!=null&&(s.uint32(26),Nr.codec().encode(o.limit,s)),o.status!=null&&(s.uint32(32),V.codec().encode(o.status,s)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let u=o.uint32();switch(u>>>3){case 1:{a.type=r.Type.codec().decode(o);break}case 2:{a.peer=Or.codec().decode(o,o.uint32(),{limits:i.limits?.peer});break}case 3:{a.limit=Nr.codec().decode(o,o.uint32(),{limits:i.limits?.limit});break}case 4:{a.status=V.codec().decode(o);break}default:{o.skipType(u&7);break}}}return a})),n),r.encode=o=>Re(o,r.codec()),r.decode=(o,s)=>Be(o,r.codec(),s)})(ke||(ke={}));var Or;(function(r){let e;r.codec=()=>(e==null&&(e=Pe((t,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),t.id!=null&&t.id.byteLength>0&&(n.uint32(10),n.bytes(t.id)),t.addrs!=null)for(let s of t.addrs)n.uint32(18),n.bytes(s);o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={id:re(0),addrs:[]},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.id=t.bytes();break}case 2:{if(o.limits?.addrs!=null&&s.addrs.length===o.limits.addrs)throw new sn('Decode error - map field "addrs" had too many elements');s.addrs.push(t.bytes());break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Re(t,r.codec()),r.decode=(t,n)=>Be(t,r.codec(),n)})(Or||(Or={}));var Po;(function(r){let e;r.codec=()=>(e==null&&(e=Pe((t,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),t.expire!=null&&t.expire!==0n&&(n.uint32(8),n.uint64(t.expire)),t.addrs!=null)for(let s of t.addrs)n.uint32(18),n.bytes(s);t.voucher!=null&&(n.uint32(26),Oo.codec().encode(t.voucher,n)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={expire:0n,addrs:[]},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.expire=t.uint64();break}case 2:{if(o.limits?.addrs!=null&&s.addrs.length===o.limits.addrs)throw new sn('Decode error - map field "addrs" had too many elements');s.addrs.push(t.bytes());break}case 3:{s.voucher=Oo.codec().decode(t,t.uint32(),{limits:o.limits?.voucher});break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Re(t,r.codec()),r.decode=(t,n)=>Be(t,r.codec(),n)})(Po||(Po={}));var Nr;(function(r){let e;r.codec=()=>(e==null&&(e=Pe((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.duration!=null&&(n.uint32(8),n.uint32(t.duration)),t.data!=null&&(n.uint32(16),n.uint64(t.data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.duration=t.uint32();break}case 2:{s.data=t.uint64();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Re(t,r.codec()),r.decode=(t,n)=>Be(t,r.codec(),n)})(Nr||(Nr={}));var V;(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"})(V||(V={}));var va;(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"})(va||(va={}));(function(r){r.codec=()=>zt(va)})(V||(V={}));var Ur;(function(r){let e;r.codec=()=>(e==null&&(e=Pe((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.relay!=null&&t.relay.byteLength>0&&(n.uint32(10),n.bytes(t.relay)),t.peer!=null&&t.peer.byteLength>0&&(n.uint32(18),n.bytes(t.peer)),t.expiration!=null&&t.expiration!==0n&&(n.uint32(24),n.uint64(t.expiration)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={relay:re(0),peer:re(0),expiration:0n},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.relay=t.bytes();break}case 2:{s.peer=t.bytes();break}case 3:{s.expiration=t.uint64();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Re(t,r.codec()),r.decode=(t,n)=>Be(t,r.codec(),n)})(Ur||(Ur={}));var Oo;(function(r){let e;r.codec=()=>(e==null&&(e=Pe((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.publicKey!=null&&t.publicKey.byteLength>0&&(n.uint32(10),n.bytes(t.publicKey)),t.payloadType!=null&&t.payloadType.byteLength>0&&(n.uint32(18),n.bytes(t.payloadType)),t.payload!=null&&(n.uint32(26),Ur.codec().encode(t.payload,n)),t.signature!=null&&t.signature.byteLength>0&&(n.uint32(42),n.bytes(t.signature)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={publicKey:re(0),payloadType:re(0),signature:re(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.publicKey=t.bytes();break}case 2:{s.payloadType=t.bytes();break}case 3:{s.payload=Ur.codec().decode(t,t.uint32(),{limits:o.limits?.payload});break}case 5:{s.signature=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Re(t,r.codec()),r.decode=(t,n)=>Be(t,r.codec(),n)})(Oo||(Oo={}));var No=class extends Error{constructor(e="Transfer limit error"){super(e),this.name="TransferLimitError"}},Uo=class extends Error{constructor(e="Duration limit error"){super(e),this.name="DurationLimitError"}},wn=class extends Error{static name="HadEnoughRelaysError";name="HadEnoughRelaysError"},Mo=class extends Error{static name="DoubleRelayError";name="DoubleRelayError"},ko=class extends Error{static name="RelayQueueFullError";name="RelayQueueFullError"};function Il(r,e,t){let n=e.remaining,o=s=>{let i=BigInt(s.data.byteLength);e.remaining-=i,e.remaining<0&&r.abort(new No(`data limit of ${n} bytes exceeded`))};r.addEventListener("message",o)}function Cl(r,e,t,n,o){function s(l){r.abort(l),e.abort(l)}let i=[t,n.signal];if(n.limit?.duration!=null){o.log("limiting relayed connection duration to %dms",n.limit.duration);let l=AbortSignal.timeout(n.limit.duration);i.push(l)}let a=_o(i);let c;n.limit?.data!=null&&(c={remaining:n.limit.data});let u=()=>{let l;t.aborted?l=t.reason:l=new Uo(`duration limit of ${n.limit?.duration} ms exceeded`),s(l)};a.addEventListener("abort",u,{once:!0}),c!=null&&(Il(e,c,o),Il(r,c,o)),cl(r,e,r).catch(l=>{s(l)}).finally(()=>{a.clear()})}function _a(r){let e=r*BigInt(1e3),t=new Date().getTime();return Number(e-BigInt(t))}var xn=class{expires;bytes;constructor(e){e?.duration!=null&&e?.duration!==0&&(this.expires=Date.now()+e.duration*1e3),this.bytes=e?.data,this.bytes===0n&&(this.bytes=void 0),this.onData=this.onData.bind(this)}onData(e){this.bytes!=null&&(this.bytes-=BigInt(e.byteLength),this.bytes<0n&&(this.bytes=0n))}getLimits(){if(this.expires==null&&this.bytes==null)return;let e={};if(this.bytes!=null){let 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}},Ko=j($(yl.matchers[0],X(290))),qo=j(X(290));function Vo(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}var Rt=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 Vo(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 Vo(this.map.values(),e=>e.key)}values(){return Vo(this.map.values(),e=>e.value)}get size(){return this.map.size}};var Ho=class{filter;constructor(e,t){this.filter=Br(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 Aa(r,e=.001){return new Ho(r,e)}var Ta=class extends Rt{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 Ia(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Ta({name:e,metrics:t}):n=new Rt,n}var Ca=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 Dl(r,e){let t=new Ca(e?.errorMessage,e?.errorCode,e?.errorName),n=new AbortController,o=()=>{n.abort(t)},s=AbortSignal.timeout(r);s.addEventListener("abort",o);let i=n.signal;return i.reset=a=>{s?.removeEventListener("abort",o),s=AbortSignal.timeout(a??r),s.addEventListener("abort",()=>{n.abort(t)})},i.clear=()=>{s?.removeEventListener("abort",o),s=void 0},i}var Fo=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??wl,this.defaultDurationLimit=t.defaultDurationLimit??Sl,this.defaultDataLimit=t.defaultDataLimit??vl,this.reservations=Ia({metrics:e.metrics,name:"libp2p_circuit_relay_server_reservations_total"})}reserve(e,t,n){let o=this.reservations.get(e);if(this.reservations.size>=this.maxReservations&&o==null)return{status:V.RESERVATION_REFUSED};let s=new Date(Date.now()+this.reservationTtl),i;return this.applyDefaultLimit&&(i=n??{data:this.defaultDataLimit,duration:this.defaultDurationLimit}),o!=null?(this.log("refreshing reservation for client %p",e),o.signal.reset(this.reservationTtl)):(this.log("creating new reservation for client %p",e),o={addr:t,expiry:s,limit:i,signal:Dl(this.reservationTtl)}),this.reservations.set(e,o),o.signal.addEventListener("abort",()=>{this.reservations.delete(e)}),{status:V.OK,expire:Math.round(s.getTime()/1e3)}}removeReservation(e){this.reservations.delete(e)}get(e){return this.reservations.get(e)}clear(){this.reservations.clear()}};var zo=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 Ur.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 Np={maxOutboundStopStreams:bn},Go=class extends Te{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??_l,this.maxInboundHopStreams=t.maxInboundHopStreams,this.maxOutboundHopStreams=t.maxOutboundHopStreams,this.maxOutboundStopStreams=t.maxOutboundStopStreams??Np.maxOutboundStopStreams,this.reservationStore=new Fo(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(Ve,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(Ve),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 o={signal:n},s=Bt(e);try{let i=await s.pb(Z).read(o);if(i?.type==null)throw new Error("request was invalid, could not read from stream");this.log("received",i.type),await this.handleHopProtocol({connection:t,stream:s,request:i},o)}catch(i){this.log.error("error while handling hop",i),await s.pb(Z).write({type:Z.Type.STATUS,status:V.MALFORMED_MESSAGE},o),e.abort(i)}}async handleHopProtocol({stream:e,request:t,connection:n},o){switch(this.log("received hop message"),t.type){case Z.Type.RESERVE:await this.handleReserve({stream:e,request:t,connection:n},o);break;case Z.Type.CONNECT:await this.handleConnect({stream:e,request:t,connection:n},o);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:V.UNEXPECTED_MESSAGE})}}async handleReserve({stream:e,connection:t},n){let o=e.pb(Z);if(this.log("hop reserve request from %p",t.remotePeer),Jt.exactMatch(t.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",t.remotePeer),await o.write({type:Z.Type.STATUS,status:V.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 o.write({type:Z.Type.STATUS,status:V.PERMISSION_DENIED},n);return}let s=this.reservationStore.reserve(t.remotePeer,t.remoteAddr);try{if(s.status!==V.OK){await o.write({type:Z.Type.STATUS,status:s.status},n);return}if(s.expire!=null){let i=s.expire*1e3-Date.now();await this.components.peerStore.merge(t.remotePeer,{tags:{[Sa]:{value:1,ttl:i}}},n)}await o.write({type:Z.Type.STATUS,status:V.OK,reservation:await this.makeReservation(t.remotePeer,BigInt(s.expire??0)),limit:this.reservationStore.get(t.remotePeer)?.limit},n),this.log("sent confirmation response to %s",t.remotePeer),await o.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:{[Sa]: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 s of this.components.addressManager.getAddresses())s.toString().includes("/p2p-circuit")||n.push(s.bytes);let o=await hn.seal(new zo({peer:e,relay:this.components.peerId,expiration:t}),this.components.privateKey);return{addrs:n,expire:t,voucher:{publicKey:Ye(o.publicKey),payloadType:o.payloadType,payload:{peer:e.toMultihash().bytes,relay:this.components.peerId.toMultihash().bytes,expiration:t},signature:o.signature}}}async handleConnect({stream:e,request:t,connection:n},o){let s=e.pb(Z);if(Jt.matches(n.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",n.remotePeer),await s.write({type:Z.Type.STATUS,status:V.PERMISSION_DENIED},o);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(Me),i=Tr(Ze(t.peer.id))}catch(h){this.log.error("invalid hop connect request via peer %p %s",n.remotePeer,h),await s.write({type:Z.Type.STATUS,status:V.MALFORMED_MESSAGE},o);return}let a=this.reservationStore.get(i);if(a==null){this.log.error("hop connect denied for destination peer %p not having a reservation for %p with status %s",i,n.remotePeer,V.NO_RESERVATION),await s.write({type:Z.Type.STATUS,status:V.NO_RESERVATION},o);return}if(await this.components.connectionGater.denyOutboundRelayedConnection?.(n.remotePeer,i)===!0){this.log.error("hop connect for %p to %p denied by connection gater",n.remotePeer,i),await s.write({type:Z.Type.STATUS,status:V.PERMISSION_DENIED},o);return}let c=this.components.connectionManager.getConnections(i);if(c.length===0){this.log("hop connect denied for destination peer %p not having a connection for %p as there is no destination connection",i,n.remotePeer),await s.write({type:Z.Type.STATUS,status:V.NO_RESERVATION},o);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}},o);if(l==null){this.log.error("failed to open stream to destination peer %p",u?.remotePeer),await s.write({type:Z.Type.STATUS,status:V.CONNECTION_FAILED},o);return}await s.write({type:Z.Type.STATUS,status:V.OK,limit:a?.limit},o),this.log("connection from %p to %p established - merging streams",n.remotePeer,i),Cl(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 o=await e.newStream(er,{maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0,...n}),s=Bt(o),i=s.pb(ke);await i.write(t,n);let a;try{a=await i.read(n)}catch{this.log.error("error parsing stop message response from %p",e.remotePeer)}if(a==null){this.log.error("could not read response from %p",e.remotePeer),await o.close(n);return}if(a.status===V.OK)return this.log("stop request to %p was successful",e.remotePeer),s.unwrap();this.log("stop request failed with code %d",a.status),await o.close(n)}get reservations(){return this.reservationStore.reservations}};var Pt=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var $o=class extends Te{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(Ve,{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(Ve)],orders:[()=>Math.random()<.5?1:-1,(n,o)=>{let s=Ll(n),i=Ll(o);return s>i?-1:i>s?1:0}]});for(let n of e)this.log.trace("found relay peer %p in peer store",n.id),this.safeDispatchEvent("relay:discover",{detail:n.id});this.log("found %d relay peers in peer store",e.length);let t=this.queue=new Pr({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(o=>o.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(o=>{this.log.error("error opening connection to random peer %p",n.id,o)})}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)}))}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(o=>{this.log.error("error opening connection to discovered peer %p",e.detail.id,o)})}async dialPeer({peerId:e,signal:t}){let n=_o([AbortSignal.timeout(5e3),t]);try{await this.components.connectionManager.openConnection(e,{signal:n})}finally{n.clear()}}};function Ll(r){let e=r.metadata.get("last-dial-success");return e==null?0:new Date(z(e)).getTime()}var La=class extends Te{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??Ro,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(qo.exactMatch(e))this.log("searching for circuit relay servers"),this.reservationId=this.reservationStore.reserveRelay();else if(Ko.exactMatch(e)){this.log("listen on specific relay server %a",e);let t=AbortSignal.timeout(this.listenTimeout);let n=e.decapsulate("/p2p-circuit"),o=await this.connectionManager.openConnection(n,{signal:t});if(!this.reservationStore.hasReservation(o.remotePeer)){this.log("making reservation on peer %p",o.remotePeer);let s=await this.reservationStore.addRelay(o.remotePeer,"configured");this.addedRelay(s)}}else throw new Nt(`Could not listen on p2p-circuit address "${e}"`)}getAddrs(){return[...this.listeningAddrs.values()].flat()}updateAnnounceAddrs(){}async close(){this.reservationStore.cancelReservations(),this.listeningAddrs=[],this.reservationStore.removeEventListener("relay:removed",this._onRemoveRelayPeer),queueMicrotask(()=>{this.safeDispatchEvent("close")})}addedRelay(e){this.log("relay peer added %p",e.relay),this.relay=e.relay,this.listeningAddrs=e.details.reservation.addrs.map(t=>Me(t).encapsulate("/p2p-circuit")),this.listeningAddrs.forEach(t=>{this.addressManager.confirmObservedAddr(t,{type:"transport"})}),queueMicrotask(()=>{this.safeDispatchEvent("listening")})}};function Bl(r){return new La(r)}var Rl="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Pl=(r=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)e+=Rl[t[r]&63];return e};var Up=60*1e3*10,Mp=60*1e3*5,kp=30*1e3,Wo=class extends Te{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 Rt,this.pendingReservations=[],this.maxReservationQueueLength=t?.maxReservationQueueLength??El,this.reservationCompletionTimeout=t?.reservationCompletionTimeout??Ro,this.started=!1,this.relayFilter=Br(100),this.reserveQueue=new Pr({concurrency:t?.reservationConcurrency??xl,metricName:"libp2p_relay_reservation_queue",metrics:e.metrics}),this.events.addEventListener("connection:close",n=>{[...this.reservations.values()].find(s=>s.connection===n.detail.id)!=null&&this.#t(n.detail.remotePeer).catch(s=>{this.log("could not remove relay %p - %e",n.detail,s)})})}isStarted(){return this.started}start(){this.started=!0}afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>t.tags.has(gn)]});this.log("removing tag from %d old relays",e.length),await Promise.all(e.map(async t=>{await this.peerStore.merge(t.id,{tags:{[gn]: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(e)})}stop(){this.reserveQueue.clear(),this.reservations.forEach(({timeout:e})=>{clearTimeout(e)}),this.reservations.clear(),this.started=!1}reserveRelay(){let e=Pl();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 Nt("Cannot use self as relay");if(this.reserveQueue.size>this.maxReservationQueueLength)throw new ko("The reservation queue is full");let n=this.reserveQueue.find(e);if(n!=null)return this.log.trace("potential relay peer %p is already in the reservation queue",e),n.join();if(this.relayFilter.has(e.toMultihash().bytes))throw new Nt("The relay was previously invalid");return this.log.trace("try to reserve relay slot with %p",e),this.reserveQueue.add(async()=>{let o=Date.now();try{let s=this.reservations.get(e);if(s!=null){let p=this.connectionManager.getConnections(e),x=!1;if(p.length===0&&this.log("already have relay reservation with %p but we are no longer connected",e),p.map(S=>S.id).includes(s.connection)&&(this.log("already have relay reservation with %p and the original connection is still open",e),x=!0),x&&_a(s.reservation.expire)>Up)return this.log("already have relay reservation with %p but we are still connected and it does not expire soon",e),{relay:e,details:s};await this.#t(e)}if(t==="discovered"&&this.pendingReservations.length===0)throw new wn("Not making reservation on discovered relay because we do not need any more relays");let i=AbortSignal.timeout(this.reservationCompletionTimeout);let a=await this.connectionManager.openConnection(e,{signal:i});if(Jt.matches(a.remoteAddr))throw new Mo("not creating reservation over relayed connection");let c=await this.#e(a,{signal:i}),u=_a(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-Mp,kp),Math.pow(2,31)-1),h=setTimeout(()=>{this.log("refresh reservation to relay %p",e),this.addRelay(e,t).catch(async p=>{this.log.error("could not refresh reservation to relay %p - %e",e,p),await this.#t(e)}).catch(p=>{this.log.error("could not remove expired reservation to relay %p - %e",e,p)})},l),f;if(t==="discovered"){let p=this.pendingReservations.pop();if(p==null)throw new wn("Made reservation on relay but did not need any more discovered relays");f={timeout:h,reservation:c,type:t,connection:a.id,id:p}}else f={timeout:h,reservation:c,type:t,connection:a.id};this.reservations.set(e,f),await this.peerStore.merge(e,{tags:{[gn]:{value:1,ttl:u}}}),this.#r();let d={relay:e,details:f};return this.safeDispatchEvent("relay:created-reservation",{detail:d}),d}catch(s){throw t==="discovered"&&s.name==="HadEnoughRelaysError"||this.log.error("could not reserve slot on %p after %dms - %e",e,Date.now()-o,s),(s.name==="DialError"||s.name==="UnsupportedProtocolError")&&this.relayFilter.add(e.toMultihash().bytes),this.#t(e).catch(i=>{this.log.error("could not remove reservation on %p after reserving slot failed - %e",e,i)}),s}},{peerId:e})}hasReservation(e){return this.reservations.has(e)}getReservation(e){return this.reservations.get(e)?.reservation}reservationCount(e){return e==null?this.reservations.size:[...this.reservations.values()].reduce((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(Ve,t),s=Bt(n).pb(Z);this.log.trace("send RESERVE to %p",e.remotePeer),await s.write({type:Z.Type.RESERVE},t);let i;try{this.log.trace("reading response from %p",e.remotePeer),i=await s.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===V.OK&&i.reservation!=null){let c=new Set;c.add(e.remoteAddr.toString());for(let u of i.reservation.addrs){let l=Me(u);l.getComponents().find(h=>h.code===421)==null&&(l=l.encapsulate(`/p2p/${e.remotePeer}`)),l=Me(l.toString().replace(`/p2p/${e.remotePeer}/p2p/${e.remotePeer}`,`/p2p/${e.remotePeer}`)),c.add(l.toString())}return i.reservation.addrs=[...c].map(u=>Me(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:{[gn]: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=Br(100),this.log("not discovered enough relays %d/%d",this.reservations.size,this.pendingReservations.length),this.safeDispatchEvent("relay:not-enough-relays")}};var Ba=class extends vo{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 Ra(r){return new Ba(r)}var Kp=r=>{if(r.peer==null)return!1;try{r.peer.addrs.forEach(Me)}catch{return!1}return!0},Ol={maxInboundStopStreams:bn,maxOutboundStopStreams:bn,stopTimeout:3e4},Zo=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??Ol.maxInboundStopStreams,this.maxOutboundStopStreams=t.maxOutboundStopStreams??Ol.maxOutboundStopStreams,this.shutdownController=new AbortController,this.discovery=new $o(e,{filter:t.discoveryFilter??Aa(Al,Tl)}),this.discovery.addEventListener("relay:discover",n=>{this.reservationStore.addRelay(n.detail,"discovered").catch(o=>{o.name!=="HadEnoughRelaysError"&&o.name!=="RelayQueueFullError"&&this.log.error("could not add discovered relay %p",n.detail,o)})}),this.reservationStore=new Wo(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";[Va]=["@libp2p/transport","@libp2p/circuit-relay-v2-transport"];get[Ha](){return this.discovery!=null?["@libp2p/identify"]:[]}[qa]=!0;isStarted(){return this.started}async start(){this.shutdownController=new AbortController,this.shutdownController.signal,await this.components.registrar.handle(er,this.onStop,{maxInboundStreams:this.maxInboundStopStreams,maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0}),await Ma(this.discovery,this.reservationStore),this.started=!0}async stop(){this.shutdownController.abort(),await ka(this.discovery,this.reservationStore),await this.components.registrar.unhandle(er),this.started=!1}async dial(e,t){let n=e.toString().split("/p2p-circuit"),o=Me(n[0]),s=Me(n[n.length-1]),i=o.getComponents().find(d=>d.code===421)?.value,a=s.getComponents().find(d=>d.code===421)?.value;if(i==null||a==null){let d=`ircuit relay dial to ${e.toString()} failed as address did not have both relay and destination PeerIDs`;throw this.log.error(`c${d}`),new Tn(`C${d}`)}let c=Ri(i),u=Ri(a),h=this.components.connectionManager.getConnections(c)[0];h==null?(await this.components.peerStore.merge(c,{multiaddrs:[o]}),t.onProgress?.(new Pt("circuit-relay:open-connection")),h=await this.components.connectionManager.openConnection(c,t)):t.onProgress?.(new Pt("circuit-relay:reuse-connection"));let f;try{t.onProgress?.(new Pt("circuit-relay:open-hop-stream")),f=await h.newStream(Ve,t);let d=Bt(f).pb(Z);t.onProgress?.(new Pt("circuit-relay:write-connect-message")),await d.write({type:Z.Type.CONNECT,peer:{id:u.toMultihash().bytes,addrs:[Me(s).bytes]}},t),t.onProgress?.(new Pt("circuit-relay:read-connect-response"));let p=await d.read(t);if(p.status!==V.OK)throw new An(`failed to connect via relay with status ${p?.status?.toString()??"undefined"}`);let x=new xn(p.limit),S=Ra({stream:d.unwrap().unwrap(),remoteAddr:e,localAddr:o.encapsulate(`/p2p-circuit/p2p/${this.components.peerId.toString()}`),onDataRead:x.onData,onDataWrite:x.onData,log:f.log.newScope("circuit-relay:connection")}),g=await this.components.upgrader.upgradeOutbound(S,{...t,limits:x.getLimits()});return g.log("outbound relayed connection established to %p with limits %o, over connection %s",g.remotePeer,p.limit??"none",h.id),g}catch(d){throw this.log.error("circuit relay dial to destination %p via relay %p failed",u,c,d),f?.abort(d),d}}createListener(e){return Bl({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=>Ko.exactMatch(t)||qo.exactMatch(t))}dialFilter(e){return e=Array.isArray(e)?e:[e],e.filter(t=>Jt.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(h){this.log.error("failed to listen on a relay peer we were dialed via but did not have a reservation on",h)}let o=Bt(e).pb(ke),s=await o.read({signal:n});if(this.log("new circuit relay v2 stop stream from %p with type %s",t.remotePeer,s.type),s?.type===void 0){this.log.error("type was missing from circuit v2 stop protocol request from %s",t.remotePeer),await o.write({type:ke.Type.STATUS,status:V.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}if(s.type!==ke.Type.CONNECT){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await o.write({type:ke.Type.STATUS,status:V.UNEXPECTED_MESSAGE},{signal:n}),await e.close({signal:n});return}if(!Kp(s)){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await o.write({type:ke.Type.STATUS,status:V.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}let i=Tr(Ze(s.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 o.write({type:ke.Type.STATUS,status:V.PERMISSION_DENIED},{signal:n}),await e.close({signal:n});return}this.log.trace("sending success response to %p",t.remotePeer),await o.write({type:ke.Type.STATUS,status:V.OK},{signal:n});let a=new xn(s.limit),c=t.remoteAddr.encapsulate(`/p2p-circuit/p2p/${i.toString()}`),u=this.components.addressManager.getAddresses()[0],l=Ra({stream:o.unwrap().unwrap(),remoteAddr:c,localAddr:u,onDataRead:a.onData,onDataWrite:a.onData,log:e.log.newScope("circuit-relay:connection")});await this.components.upgrader.upgradeInbound(l,{limits:a.getLimits(),signal:n}),l.log("inbound relayed connection established to %p with limits %o, over connection %s",i,s.limit??"none",t.id)}finally{n?.clear()}}};function qp(r={}){return e=>new Go(e,r)}function Vp(r={}){return e=>new Zo(e,r)}return Kl(Hp);})();
2
+ "use strict";var Libp2PCircuitRelayV2=(()=>{var Oo=Object.defineProperty;var xl=Object.getOwnPropertyDescriptor;var wl=Object.getOwnPropertyNames;var El=Object.prototype.hasOwnProperty;var ve=(r,e)=>{for(var t in e)Oo(r,t,{get:e[t],enumerable:!0})},Sl=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of wl(e))!El.call(r,o)&&o!==t&&Oo(r,o,{get:()=>e[o],enumerable:!(n=xl(e,o))||n.enumerable});return r};var vl=r=>Sl(Oo({},"__esModule",{value:!0}),r);var dp={};ve(dp,{RELAY_V2_HOP_CODEC:()=>Ue,RELAY_V2_STOP_CODEC:()=>$t,circuitRelayServer:()=>fp,circuitRelayTransport:()=>hp});var _e=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){super.addEventListener(e,t,n);let o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==t),this.#e.set(e,o))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:o})=>!o),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var Xe=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var ie=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Gt=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var un=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}};var _t=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},Tr=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}};var ln=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},fn=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var hn=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var dn=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}},At=class extends Error{static name="ListenError";constructor(e="Listen error"){super(e),this.name="ListenError"}};var Wt=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var pn=class extends Event{data;constructor(e,t){super("message",t),this.data=e}},Zt=class extends Event{error;local;constructor(e,t,n){super("close",n),this.error=t,this.local=e}},mn=class extends Zt{constructor(e,t){super(!0,e,t)}},yn=class extends Zt{constructor(e,t){super(!1,e,t)}};var Po=Symbol.for("@libp2p/peer-id");var ba="keep-alive";function xa(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function wa(...r){let e=[];for(let t of r)xa(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 Ea(...r){let e=[];for(let t of r)xa(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 va=Symbol.for("@libp2p/transport");var Sa;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Sa||(Sa={}));var _a=Symbol.for("@libp2p/service-capabilities"),Aa=Symbol.for("@libp2p/service-dependencies");var Ko={};ve(Ko,{base58btc:()=>te,base58flickr:()=>Ll});var Wp=new Uint8Array(0);function Ta(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 je(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function Ia(r){return new TextEncoder().encode(r)}function Da(r){return new TextDecoder().decode(r)}function _l(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function f(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var v=0,x=0,y=0,A=h.length;y!==A&&h[y]===0;)y++,v++;for(var w=(A-y)*l+1>>>0,T=new Uint8Array(w);y!==A;){for(var P=h[y],k=0,q=w-1;(P!==0||k<x)&&q!==-1;q--,k++)P+=256*T[q]>>>0,T[q]=P%a>>>0,P=P/a>>>0;if(P!==0)throw new Error("Non-zero carry");x=k,y++}for(var S=w-x;S!==w&&T[S]===0;)S++;for(var E=c.repeat(v);S<w;++S)E+=r.charAt(T[S]);return E}function m(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var v=0;if(h[v]!==" "){for(var x=0,y=0;h[v]===c;)x++,v++;for(var A=(h.length-v)*u+1>>>0,w=new Uint8Array(A);h[v];){var T=t[h.charCodeAt(v)];if(T===255)return;for(var P=0,k=A-1;(T!==0||P<y)&&k!==-1;k--,P++)T+=a*w[k]>>>0,w[k]=T%256>>>0,T=T/256>>>0;if(T!==0)throw new Error("Non-zero carry");y=P,v++}if(h[v]!==" "){for(var q=A-y;q!==A&&w[q]===0;)q++;for(var S=new Uint8Array(x+(A-q)),E=x;q!==A;)S[E++]=w[q++];return S}}}function d(h){var v=m(h);if(v)return v;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:m,decode:d}}var Al=_l,Tl=Al,La=Tl;var No=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")}},Uo=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Ra(this,e)}},Mo=class{decoders;constructor(e){this.decoders=e}or(e){return Ra(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 Ra(r,e){return new Mo({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var ko=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new No(e,t,n),this.decoder=new Uo(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Yt({name:r,prefix:e,encode:t,decode:n}){return new ko(r,e,t,n)}function lt({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=La(t,r);return Yt({prefix:e,name:r,encode:n,decode:s=>je(o(s))})}function Il(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let u=0;u<o;++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,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function Dl(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function Cl(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function ae({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=Cl(n);return Yt({prefix:e,name:r,encode(s){return Dl(s,n,t)},decode(s){return Il(s,o,t,r)}})}var te=lt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Ll=lt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var qo={};ve(qo,{base32:()=>ft,base32hex:()=>Pl,base32hexpad:()=>Ul,base32hexpadupper:()=>Ml,base32hexupper:()=>Nl,base32pad:()=>Bl,base32padupper:()=>Ol,base32upper:()=>Rl,base32z:()=>kl});var ft=ae({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Rl=ae({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Bl=ae({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Ol=ae({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Pl=ae({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Nl=ae({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Ul=ae({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Ml=ae({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),kl=ae({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Vo={};ve(Vo,{base36:()=>Ir,base36upper:()=>Kl});var Ir=lt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Kl=lt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var ql=Pa,Ba=128,Vl=127,Hl=~Vl,Fl=Math.pow(2,31);function Pa(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Fl;)e[t++]=r&255|Ba,r/=128;for(;r&Hl;)e[t++]=r&255|Ba,r>>>=7;return e[t]=r|0,Pa.bytes=t-n+1,e}var zl=Ho,$l=128,Oa=127;function Ho(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw Ho.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&Oa)<<o:(i&Oa)*Math.pow(2,o),o+=7}while(i>=$l);return Ho.bytes=s-n,t}var Gl=Math.pow(2,7),Wl=Math.pow(2,14),Zl=Math.pow(2,21),Yl=Math.pow(2,28),Xl=Math.pow(2,35),jl=Math.pow(2,42),Ql=Math.pow(2,49),Jl=Math.pow(2,56),ef=Math.pow(2,63),tf=function(r){return r<Gl?1:r<Wl?2:r<Zl?3:r<Yl?4:r<Xl?5:r<jl?6:r<Ql?7:r<Jl?8:r<ef?9:10},rf={encode:ql,decode:zl,encodingLength:tf},nf=rf,Dr=nf;function Cr(r,e=0){return[Dr.decode(r,e),Dr.decode.bytes]}function Xt(r,e,t=0){return Dr.encode(r,e,t),e}function jt(r){return Dr.encodingLength(r)}function Fe(r,e){let t=e.byteLength,n=jt(r),o=n+jt(t),s=new Uint8Array(o+t);return Xt(r,s,0),Xt(t,s,n),s.set(e,o),new Qt(r,t,e,s)}function ze(r){let e=je(r),[t,n]=Cr(e),[o,s]=Cr(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Qt(t,o,i,e)}function Na(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Ta(r.bytes,t.bytes)}}var Qt=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};function Ua(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return sf(t,Fo(r),e??te.encoder);default:return af(t,Fo(r),e??ft.encoder)}}var Ma=new WeakMap;function Fo(r){let e=Ma.get(r);if(e==null){let t=new Map;return Ma.set(r,t),t}return e}var le=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Lr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==cf)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=Fe(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&&Na(e.multihash,n.multihash)}toString(e){return Ua(this,e)}toJSON(){return{"/":Ua(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:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??ka(n,o,s.bytes))}else if(t[uf]===!0){let{version:n,multihash:o,code:s}=t,i=ze(o);return r.create(n,s,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!==Lr)throw new Error(`Version 0 CID must use dag-pb (code: ${Lr}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=ka(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Lr,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,o=je(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new Qt(t.multihashCode,t.digestSize,s,o);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]=Cr(e.subarray(t));return t+=m,f},o=n(),s=Lr;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),u=t+c,l=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(e,t){let[n,o]=of(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Fo(s).set(n,e),s}};function of(r,e){switch(r[0]){case"Q":{let t=e??te;return[te.prefix,t.decode(`${te.prefix}${r}`)]}case te.prefix:{let t=e??te;return[te.prefix,t.decode(r)]}case ft.prefix:{let t=e??ft;return[ft.prefix,t.decode(r)]}case Ir.prefix:{let t=e??Ir;return[Ir.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 sf(r,e,t){let{prefix:n}=t;if(n!==te.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function af(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var Lr=112,cf=18;function ka(r,e,t){let n=jt(r),o=n+jt(e),s=new Uint8Array(o+t.byteLength);return Xt(r,s,0),Xt(e,s,n),s.set(t,o),s}var uf=Symbol.for("@ipld/js-cid/CID");var zo={};ve(zo,{identity:()=>Me});var Ka=0,lf="identity",qa=je;function ff(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 Fe(Ka,qa(r))}var Me={code:Ka,name:lf,encode:qa,digest:ff};function fe(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 re(r=0){return new Uint8Array(r)}function Ae(r=0){return new Uint8Array(r)}function Je(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=Ae(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}var Ha=Symbol.for("@achingbrain/uint8arraylist");function Va(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function bn(r){return!!r?.[Ha]}var J=class r{bufs;length;[Ha]=!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(bn(n))t+=n.byteLength,this.bufs.push(...n.bufs);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(bn(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=Va(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Va(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(bn(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:o}=this._subList(e,t);return Je(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:Je(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=[...n],s}_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=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let u=e>=a&&e<c,l=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(!bn(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(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 o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let f=0;f<s;f++)i[f]=-1;for(let f=0;f<o;f++)i[n[f]]=f;let a=i,c=this.byteLength-n.byteLength,u=n.byteLength-1,l;for(let f=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=Ae(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 o=re(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,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 o=re(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,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 o=re(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,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=Ae(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 o=re(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,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 o=re(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,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 o=re(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,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 o=re(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,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 o=re(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,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(!fe(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((o,s)=>o+s.byteLength,0)),n.length=t,n}};var $o={};ve($o,{base10:()=>hf});var hf=lt({prefix:"9",name:"base10",alphabet:"0123456789"});var Go={};ve(Go,{base16:()=>df,base16upper:()=>pf});var df=ae({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),pf=ae({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Wo={};ve(Wo,{base2:()=>mf});var mf=ae({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Zo={};ve(Zo,{base256emoji:()=>wf});var Fa=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}"),yf=Fa.reduce((r,e,t)=>(r[t]=e,r),[]),gf=Fa.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function bf(r){return r.reduce((e,t)=>(e+=yf[t],e),"")}function xf(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=gf[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var wf=Yt({prefix:"\u{1F680}",name:"base256emoji",encode:bf,decode:xf});var Xo={};ve(Xo,{base64:()=>Ef,base64pad:()=>Sf,base64url:()=>Yo,base64urlpad:()=>vf});var Ef=ae({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Sf=ae({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Yo=ae({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),vf=ae({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var jo={};ve(jo,{base8:()=>_f});var _f=ae({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Qo={};ve(Qo,{identity:()=>Af});var Af=Yt({prefix:"\0",name:"identity",encode:r=>Da(r),decode:r=>Ia(r)});var Lm=new TextEncoder,Rm=new TextDecoder;var ts={};ve(ts,{sha256:()=>Jt,sha512:()=>Cf});var Df=20;function es({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new Jo(r,e,t,n,o)}var Jo=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??Df,this.maxDigestLength=s}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?za(n,this.code,t?.truncate):n.then(o=>za(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function za(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 Fe(e,r)}function Ga(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Jt=es({name:"sha2-256",code:18,encode:Ga("SHA-256")}),Cf=es({name:"sha2-512",code:19,encode:Ga("SHA-512")});var Rr={...Qo,...Wo,...jo,...$o,...Go,...qo,...Vo,...Ko,...Xo,...Zo},Fm={...ts,...zo};function Za(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Wa=Za("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),rs=Za("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=Ae(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),Lf={utf8:Wa,"utf-8":Wa,hex:Rr.base16,latin1:rs,ascii:rs,binary:rs,...Rr},xn=Lf;function K(r,e="utf8"){let t=xn[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function $(r,e="utf8"){let t=xn[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var Rf=parseInt("11111",2),ns=parseInt("10000000",2),Bf=parseInt("01111111",2),Ya={0:Br,1:Br,2:Of,3:Uf,4:Mf,5:Nf,6:Pf,16:Br,22:Br,48:Br};function et(r,e={offset:0}){let t=r[e.offset]&Rf;if(e.offset++,Ya[t]!=null)return Ya[t](r,e);throw new Error("No decoder for tag "+t)}function Or(r,e){let t=0;if((r[e.offset]&ns)===ns){let n=r[e.offset]&Bf,o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++)o+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(o,16)}else t=r[e.offset],e.offset++;return t}function Br(r,e){Or(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=et(r,e);if(n===null)break;t.push(n)}return t}function Of(r,e){let t=Or(r,e),n=e.offset,o=e.offset+t,s=[];for(let i=n;i<o;i++)i===n&&r[i]===0||s.push(r[i]);return e.offset+=t,Uint8Array.from(s)}function Pf(r,e){let t=Or(r,e),n=e.offset+t,o=r[e.offset];e.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,c=[];for(;e.offset<n;){let u=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 Nf(r,e){return e.offset++,null}function Uf(r,e){let t=Or(r,e),n=r[e.offset];e.offset++;let o=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 o}function Mf(r,e){let t=Or(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function kf(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new J;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function os(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=kf(r.byteLength);return new J(Uint8Array.from([e.byteLength|ns]),e)}function Te(r){let e=new J,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new J(Uint8Array.from([2]),os(e),e)}function wn(r){let e=Uint8Array.from([0]),t=new J(e,r);return new J(Uint8Array.from([3]),os(t),t)}function ht(r,e=48){let t=new J;for(let n of r)t.append(n);return new J(Uint8Array.from([e]),os(t),t)}async function Xa(r,e,t,n){let o=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,e,t.subarray());return n?.signal?.throwIfAborted(),s}var Kf=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),qf=Uint8Array.from([6,5,43,129,4,0,34]),Vf=Uint8Array.from([6,5,43,129,4,0,35]),Hf={ext:!0,kty:"EC",crv:"P-256"},Ff={ext:!0,kty:"EC",crv:"P-384"},zf={ext:!0,kty:"EC",crv:"P-521"},ss=32,is=48,as=66;function cs(r){let e=et(r);return ja(e)}function ja(r){let e=r[1][1][0],t=1,n,o;if(e.byteLength===ss*2+1)return n=$(e.subarray(t,t+ss),"base64url"),o=$(e.subarray(t+ss),"base64url"),new er({...Hf,key_ops:["verify"],x:n,y:o});if(e.byteLength===is*2+1)return n=$(e.subarray(t,t+is),"base64url"),o=$(e.subarray(t+is),"base64url"),new er({...Ff,key_ops:["verify"],x:n,y:o});if(e.byteLength===as*2+1)return n=$(e.subarray(t,t+as),"base64url"),o=$(e.subarray(t+as),"base64url"),new er({...zf,key_ops:["verify"],x:n,y:o});throw new ie(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function Qa(r){return ht([Te(Uint8Array.from([1])),ht([$f(r.crv)],160),ht([wn(new J(Uint8Array.from([4]),K(r.x??"","base64url"),K(r.y??"","base64url")))],161)]).subarray()}function $f(r){if(r==="P-256")return Kf;if(r==="P-384")return qf;if(r==="P-521")return Vf;throw new ie(`Invalid curve ${r}`)}var er=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=Qa(this.jwk)),this._raw}toMultihash(){return Me.digest($e(this))}toCID(){return le.createV1(114,this.toMultihash())}toString(){return te.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:fe(this.raw,e.raw)}async verify(e,t,n){return Xa(this.jwk,t,e,n)}};function Tt(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Ge(r,e=""){if(!Number.isSafeInteger(r)||r<0){let t=e&&`"${e}" `;throw new Error(`${t}expected integer >= 0, got ${r}`)}}function M(r,e,t=""){let n=Tt(r),o=r?.length,s=e!==void 0;if(!n||s&&o!==e){let i=t&&`"${t}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function En(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");Ge(r.outputLen),Ge(r.blockLen)}function tr(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 ec(r,e){M(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length<t)throw new Error('"digestInto() output" expected to be of length >='+t)}function rt(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function Sn(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function ke(r,e){return r<<32-e|r>>>e}var tc=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Gf=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function nt(r){if(M(r),tc)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=Gf[r[t]];return e}var tt={_0:48,_9:57,A:65,F:70,a:97,f:102};function Ja(r){if(r>=tt._0&&r<=tt._9)return r-tt._0;if(r>=tt.A&&r<=tt.F)return r-(tt.A-10);if(r>=tt.a&&r<=tt.f)return r-(tt.a-10)}function ot(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(tc)return Uint8Array.fromHex(r);let e=r.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let o=0,s=0;o<t;o++,s+=2){let i=Ja(r.charCodeAt(s)),a=Ja(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function Ie(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];M(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let s=r[n];t.set(s,o),o+=s.length}return t}function us(r,e={}){let t=(o,s)=>r(s).update(o).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=o=>r(o),Object.assign(t,e),Object.freeze(t)}function rr(r=32){let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(r))}var ls=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function rc(r,e,t){return r&e^~r&t}function nc(r,e,t){return r&e^r&t^e&t}var Pr=class{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,o){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=Sn(this.buffer)}update(e){tr(this),M(e);let{view:t,buffer:n,blockLen:o}=this,s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=Sn(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){tr(this),ec(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,rt(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let f=i;f<o;f++)t[f]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=Sn(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],s)}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:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},st=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var ye=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 Wf(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 sc(r,e=!1){let t=r.length,n=new Uint32Array(t),o=new Uint32Array(t);for(let s=0;s<t;s++){let{h:i,l:a}=Wf(r[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var fs=(r,e,t)=>r>>>t,hs=(r,e,t)=>r<<32-t|e>>>t,It=(r,e,t)=>r>>>t|e<<32-t,Dt=(r,e,t)=>r<<32-t|e>>>t,Nr=(r,e,t)=>r<<64-t|e>>>t-32,Ur=(r,e,t)=>r>>>t-32|e<<64-t;function We(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var ic=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),ac=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,cc=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),uc=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,lc=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),fc=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var Yf=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]),dt=new Uint32Array(64),ds=class extends Pr{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,t,n,o,s,i,a,c]}set(e,t,n,o,s,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let f=0;f<16;f++,t+=4)dt[f]=e.getUint32(t,!1);for(let f=16;f<64;f++){let m=dt[f-15],d=dt[f-2],h=ke(m,7)^ke(m,18)^m>>>3,v=ke(d,17)^ke(d,19)^d>>>10;dt[f]=v+dt[f-7]+h+dt[f-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:l}=this;for(let f=0;f<64;f++){let m=ke(a,6)^ke(a,11)^ke(a,25),d=l+m+rc(a,c,u)+Yf[f]+dt[f]|0,v=(ke(n,2)^ke(n,13)^ke(n,22))+nc(n,o,s)|0;l=u,u=c,c=a,a=i+d|0,i=s,s=o,o=n,n=d+v|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(n,o,s,i,a,c,u,l)}roundClean(){rt(dt)}destroy(){this.set(0,0,0,0,0,0,0,0),rt(this.buffer)}},ps=class extends ds{A=st[0]|0;B=st[1]|0;C=st[2]|0;D=st[3]|0;E=st[4]|0;F=st[5]|0;G=st[6]|0;H=st[7]|0;constructor(){super(32)}};var hc=sc(["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))),Xf=hc[0],jf=hc[1],pt=new Uint32Array(80),mt=new Uint32Array(80),ms=class extends Pr{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:u,El:l,Fh:f,Fl:m,Gh:d,Gl:h,Hh:v,Hl:x}=this;return[e,t,n,o,s,i,a,c,u,l,f,m,d,h,v,x]}set(e,t,n,o,s,i,a,c,u,l,f,m,d,h,v,x){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=f|0,this.Fl=m|0,this.Gh=d|0,this.Gl=h|0,this.Hh=v|0,this.Hl=x|0}process(e,t){for(let w=0;w<16;w++,t+=4)pt[w]=e.getUint32(t),mt[w]=e.getUint32(t+=4);for(let w=16;w<80;w++){let T=pt[w-15]|0,P=mt[w-15]|0,k=It(T,P,1)^It(T,P,8)^fs(T,P,7),q=Dt(T,P,1)^Dt(T,P,8)^hs(T,P,7),S=pt[w-2]|0,E=mt[w-2]|0,N=It(S,E,19)^Nr(S,E,61)^fs(S,E,6),V=Dt(S,E,19)^Ur(S,E,61)^hs(S,E,6),L=cc(q,V,mt[w-7],mt[w-16]),g=uc(L,k,N,pt[w-7],pt[w-16]);pt[w]=g|0,mt[w]=L|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:l,Eh:f,El:m,Fh:d,Fl:h,Gh:v,Gl:x,Hh:y,Hl:A}=this;for(let w=0;w<80;w++){let T=It(f,m,14)^It(f,m,18)^Nr(f,m,41),P=Dt(f,m,14)^Dt(f,m,18)^Ur(f,m,41),k=f&d^~f&v,q=m&h^~m&x,S=lc(A,P,q,jf[w],mt[w]),E=fc(S,y,T,k,Xf[w],pt[w]),N=S|0,V=It(n,o,28)^Nr(n,o,34)^Nr(n,o,39),L=Dt(n,o,28)^Ur(n,o,34)^Ur(n,o,39),g=n&s^n&a^s&a,b=o&i^o&c^i&c;y=v|0,A=x|0,v=d|0,x=h|0,d=f|0,h=m|0,{h:f,l:m}=We(u|0,l|0,E|0,N|0),u=a|0,l=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let p=ic(N,L,b);n=ac(p,E,V,g),o=p|0}({h:n,l:o}=We(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=We(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=We(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=We(this.Dh|0,this.Dl|0,u|0,l|0),{h:f,l:m}=We(this.Eh|0,this.El|0,f|0,m|0),{h:d,l:h}=We(this.Fh|0,this.Fl|0,d|0,h|0),{h:v,l:x}=We(this.Gh|0,this.Gl|0,v|0,x|0),{h:y,l:A}=We(this.Hh|0,this.Hl|0,y|0,A|0),this.set(n,o,s,i,a,c,u,l,f,m,d,h,v,x,y,A)}roundClean(){rt(pt,mt)}destroy(){rt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},ys=class extends ms{Ah=ye[0]|0;Al=ye[1]|0;Bh=ye[2]|0;Bl=ye[3]|0;Ch=ye[4]|0;Cl=ye[5]|0;Dh=ye[6]|0;Dl=ye[7]|0;Eh=ye[8]|0;El=ye[9]|0;Fh=ye[10]|0;Fl=ye[11]|0;Gh=ye[12]|0;Gl=ye[13]|0;Hh=ye[14]|0;Hl=ye[15]|0;constructor(){super(64)}};var nr=us(()=>new ps,ls(1));var dc=us(()=>new ys,ls(3));var bs=BigInt(0),gs=BigInt(1);function it(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}" `;throw new Error(t+"expected boolean, got type="+typeof r)}return r}function pc(r){if(typeof r=="bigint"){if(!_n(r))throw new Error("positive bigint expected, got "+r)}else Ge(r);return r}function Mr(r){let e=pc(r).toString(16);return e.length&1?"0"+e:e}function mc(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?bs:BigInt("0x"+r)}function or(r){return mc(nt(r))}function Ct(r){return mc(nt(Tn(M(r)).reverse()))}function An(r,e){Ge(e),r=pc(r);let t=ot(r.toString(16).padStart(e*2,"0"));if(t.length!==e)throw new Error("number too large");return t}function xs(r,e){return An(r,e).reverse()}function Tn(r){return Uint8Array.from(r)}var _n=r=>typeof r=="bigint"&&bs<=r;function Qf(r,e,t){return _n(r)&&_n(e)&&_n(t)&&e<=r&&r<t}function kr(r,e,t,n){if(!Qf(e,t,n))throw new Error("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function ws(r){let e;for(e=0;r>bs;r>>=gs,e+=1);return e}var Kr=r=>(gs<<BigInt(r))-gs;function yc(r,e,t){if(Ge(r,"hashLen"),Ge(e,"qByteLen"),typeof t!="function")throw new Error("hmacFn must be a function");let n=x=>new Uint8Array(x),o=Uint8Array.of(),s=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=(...x)=>t(u,Ie(c,...x)),d=(x=o)=>{u=m(s,x),c=m(),x.length!==0&&(u=m(i,x),c=m())},h=()=>{if(l++>=a)throw new Error("drbg: tried max amount of iterations");let x=0,y=[];for(;x<e;){c=m();let A=c.slice();y.push(A),x+=c.length}return Ie(...y)};return(x,y)=>{f(),d(x);let A;for(;!(A=y(h()));)d();return f(),A}}function yt(r,e={},t={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function n(s,i,a){let c=r[s];if(a&&c===void 0)return;let u=typeof c;if(u!==i||c===null)throw new Error(`param "${s}" is invalid: expected ${i}, got ${u}`)}let o=(s,i)=>Object.entries(s).forEach(([a,c])=>n(a,c,i));o(e,!1),o(t,!0)}function sr(r){let e=new WeakMap;return(t,...n)=>{let o=e.get(t);if(o!==void 0)return o;let s=r(t,...n);return e.set(t,s),s}}var Se=BigInt(0),he=BigInt(1),Lt=BigInt(2),xc=BigInt(3),wc=BigInt(4),Ec=BigInt(5),Jf=BigInt(7),Sc=BigInt(8),eh=BigInt(9),vc=BigInt(16);function ce(r,e){let t=r%e;return t>=Se?t:e+t}function ee(r,e,t){let n=r;for(;e-- >Se;)n*=n,n%=t;return n}function gc(r,e){if(r===Se)throw new Error("invert: expected non-zero number");if(e<=Se)throw new Error("invert: expected positive modulus, got "+e);let t=ce(r,e),n=e,o=Se,s=he,i=he,a=Se;for(;t!==Se;){let u=n/t,l=n%t,f=o-i*u,m=s-a*u;n=t,t=l,o=i,s=a,i=f,a=m}if(n!==he)throw new Error("invert: does not exist");return ce(o,e)}function Ss(r,e,t){if(!r.eql(r.sqr(e),t))throw new Error("Cannot find square root")}function _c(r,e){let t=(r.ORDER+he)/wc,n=r.pow(e,t);return Ss(r,n,e),n}function th(r,e){let t=(r.ORDER-Ec)/Sc,n=r.mul(e,Lt),o=r.pow(n,t),s=r.mul(e,o),i=r.mul(r.mul(s,Lt),o),a=r.mul(s,r.sub(i,r.ONE));return Ss(r,a,e),a}function rh(r){let e=ir(r),t=Ac(r),n=t(e,e.neg(e.ONE)),o=t(e,n),s=t(e,e.neg(n)),i=(r+Jf)/vc;return(a,c)=>{let u=a.pow(c,i),l=a.mul(u,n),f=a.mul(u,o),m=a.mul(u,s),d=a.eql(a.sqr(l),c),h=a.eql(a.sqr(f),c);u=a.cmov(u,l,d),l=a.cmov(m,f,h);let v=a.eql(a.sqr(l),c),x=a.cmov(u,l,v);return Ss(a,x,c),x}}function Ac(r){if(r<xc)throw new Error("sqrt is not defined for small field");let e=r-he,t=0;for(;e%Lt===Se;)e/=Lt,t++;let n=Lt,o=ir(r);for(;bc(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return _c;let s=o.pow(n,e),i=(e+he)/Lt;return function(c,u){if(c.is0(u))return u;if(bc(c,u)!==1)throw new Error("Cannot find square root");let l=t,f=c.mul(c.ONE,s),m=c.pow(u,e),d=c.pow(u,i);for(;!c.eql(m,c.ONE);){if(c.is0(m))return c.ZERO;let h=1,v=c.sqr(m);for(;!c.eql(v,c.ONE);)if(h++,v=c.sqr(v),h===l)throw new Error("Cannot find square root");let x=he<<BigInt(l-h-1),y=c.pow(f,x);l=h,f=c.sqr(y),m=c.mul(m,f),d=c.mul(d,y)}return d}}function nh(r){return r%wc===xc?_c:r%Sc===Ec?th:r%vc===eh?rh(r):Ac(r)}var Tc=(r,e)=>(ce(r,e)&he)===he,oh=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function vs(r){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=oh.reduce((n,o)=>(n[o]="function",n),e);return yt(r,t),r}function sh(r,e,t){if(t<Se)throw new Error("invalid exponent, negatives unsupported");if(t===Se)return r.ONE;if(t===he)return e;let n=r.ONE,o=e;for(;t>Se;)t&he&&(n=r.mul(n,o)),o=r.sqr(o),t>>=he;return n}function qr(r,e,t=!1){let n=new Array(e.length).fill(t?r.ZERO:void 0),o=e.reduce((i,a,c)=>r.is0(a)?i:(n[c]=i,r.mul(i,a)),r.ONE),s=r.inv(o);return e.reduceRight((i,a,c)=>r.is0(a)?i:(n[c]=r.mul(i,n[c]),r.mul(i,a)),s),n}function bc(r,e){let t=(r.ORDER-he)/Lt,n=r.pow(e,t),o=r.eql(n,r.ONE),s=r.eql(n,r.ZERO),i=r.eql(n,r.neg(r.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function ih(r,e){e!==void 0&&Ge(e);let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}var Es=class{ORDER;BITS;BYTES;isLE;ZERO=Se;ONE=he;_lengths;_sqrt;_mod;constructor(e,t={}){if(e<=Se)throw new Error("invalid field: expected ORDER > 0, got "+e);let n;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(n=t.BITS),typeof t.sqrt=="function"&&(this.sqrt=t.sqrt),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=t.allowedLengths?.slice()),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:o,nByteLength:s}=ih(e,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return ce(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return Se<=e&&e<this.ORDER}is0(e){return e===Se}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&he)===he}neg(e){return ce(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return ce(e*e,this.ORDER)}add(e,t){return ce(e+t,this.ORDER)}sub(e,t){return ce(e-t,this.ORDER)}mul(e,t){return ce(e*t,this.ORDER)}pow(e,t){return sh(this,e,t)}div(e,t){return ce(e*gc(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 gc(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=nh(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?xs(e,this.BYTES):An(e,this.BYTES)}fromBytes(e,t=!1){M(e);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(!n.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let u=new Uint8Array(o);u.set(e,s?0:u.length-e.length),e=u}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?Ct(e):or(e);if(a&&(c=ce(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return qr(this,e)}cmov(e,t,n){return n?t:e}};function ir(r,e={}){return new Es(r,e)}function Ic(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let e=r.toString(2).length;return Math.ceil(e/8)}function _s(r){let e=Ic(r);return e+Math.ceil(e/2)}function As(r,e,t=!1){M(r);let n=r.length,o=Ic(e),s=_s(e);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=t?Ct(r):or(r),a=ce(i,e-he)+he;return t?xs(a,o):An(a,o)}var ar=BigInt(0),Rt=BigInt(1);function Vr(r,e){let t=e.negate();return r?t:e}function Bt(r,e){let t=qr(r.Fp,e.map(n=>n.Z));return e.map((n,o)=>r.fromAffine(n.toAffine(t[o])))}function Rc(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function Ts(r,e){Rc(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1),o=2**r,s=Kr(r),i=BigInt(r);return{windows:t,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function Dc(r,e,t){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=t,a=Number(r&o),c=r>>i;a>n&&(a-=s,c+=Rt);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 Is=new WeakMap,Bc=new WeakMap;function Ds(r){return Bc.get(r)||1}function Cc(r){if(r!==ar)throw new Error("invalid wNAF")}var cr=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 o=e;for(;t>ar;)t&Rt&&(n=n.add(o)),o=o.double(),t>>=Rt;return n}precomputeWindow(e,t){let{windows:n,windowSize:o}=Ts(t,this.bits),s=[],i=e,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let u=1;u<o;u++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=Ts(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:u,isZero:l,isNeg:f,isNegF:m,offsetF:d}=Dc(n,a,i);n=c,l?s=s.add(Vr(m,t[d])):o=o.add(Vr(f,t[u]))}return Cc(n),{p:o,f:s}}wNAFUnsafe(e,t,n,o=this.ZERO){let s=Ts(e,this.bits);for(let i=0;i<s.windows&&n!==ar;i++){let{nextN:a,offset:c,isZero:u,isNeg:l}=Dc(n,i,s);if(n=a,!u){let f=t[c];o=o.add(l?f.negate():f)}}return Cc(n),o}getPrecomputes(e,t,n){let o=Is.get(t);return o||(o=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(o=n(o)),Is.set(t,o))),o}cached(e,t,n){let o=Ds(e);return this.wNAF(o,this.getPrecomputes(o,e,n),t)}unsafe(e,t,n,o){let s=Ds(e);return s===1?this._unsafeLadder(e,t,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),t,o)}createCache(e,t){Rc(t,this.bits),Bc.set(e,t),Is.delete(e)}hasCache(e){return Ds(e)!==1}};function Oc(r,e,t,n){let o=e,s=r.ZERO,i=r.ZERO;for(;t>ar||n>ar;)t&Rt&&(s=s.add(o)),n&Rt&&(i=i.add(o)),o=o.double(),t>>=Rt,n>>=Rt;return{p1:s,p2:i}}function Lc(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return vs(e),e}else return ir(r,{isLE:t})}function In(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>ar))throw new Error(`CURVE.${c} must be positive bigint`)}let o=Lc(e.p,t.Fp,n),s=Lc(e.n,t.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}function Dn(r,e){return function(n){let o=r(n);return{secretKey:o,publicKey:e(o)}}}var gt=BigInt(0),de=BigInt(1),Cs=BigInt(2),ah=BigInt(8);function ch(r,e,t,n){let o=r.sqr(t),s=r.sqr(n),i=r.add(r.mul(e.a,o),s),a=r.add(r.ONE,r.mul(e.d,r.mul(o,s)));return r.eql(i,a)}function Pc(r,e={}){let t=In("edwards",r,e,e.FpFnLE),{Fp:n,Fn:o}=t,s=t.CURVE,{h:i}=s;yt(e,{},{uvRatio:"function"});let a=Cs<<BigInt(o.BYTES*8)-de,c=x=>n.create(x),u=e.uvRatio||((x,y)=>{try{return{isValid:!0,value:n.sqrt(n.div(x,y))}}catch{return{isValid:!1,value:gt}}});if(!ch(n,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function l(x,y,A=!1){let w=A?de:gt;return kr("coordinate "+x,y,w,a),y}function f(x){if(!(x instanceof h))throw new Error("EdwardsPoint expected")}let m=sr((x,y)=>{let{X:A,Y:w,Z:T}=x,P=x.is0();y==null&&(y=P?ah:n.inv(T));let k=c(A*y),q=c(w*y),S=n.mul(T,y);if(P)return{x:gt,y:de};if(S!==de)throw new Error("invZ was invalid");return{x:k,y:q}}),d=sr(x=>{let{a:y,d:A}=s;if(x.is0())throw new Error("bad point: ZERO");let{X:w,Y:T,Z:P,T:k}=x,q=c(w*w),S=c(T*T),E=c(P*P),N=c(E*E),V=c(q*y),L=c(E*c(V+S)),g=c(N+c(A*c(q*S)));if(L!==g)throw new Error("bad point: equation left != right (1)");let b=c(w*T),p=c(P*k);if(b!==p)throw new Error("bad point: equation left != right (2)");return!0});class h{static BASE=new h(s.Gx,s.Gy,de,c(s.Gx*s.Gy));static ZERO=new h(gt,de,de,gt);static Fp=n;static Fn=o;X;Y;Z;T;constructor(y,A,w,T){this.X=l("x",y),this.Y=l("y",A),this.Z=l("z",w,!0),this.T=l("t",T),Object.freeze(this)}static CURVE(){return s}static fromAffine(y){if(y instanceof h)throw new Error("extended point not allowed");let{x:A,y:w}=y||{};return l("x",A),l("y",w),new h(A,w,de,c(A*w))}static fromBytes(y,A=!1){let w=n.BYTES,{a:T,d:P}=s;y=Tn(M(y,w,"point")),it(A,"zip215");let k=Tn(y),q=y[w-1];k[w-1]=q&-129;let S=Ct(k),E=A?a:n.ORDER;kr("point.y",S,gt,E);let N=c(S*S),V=c(N-de),L=c(P*N-T),{isValid:g,value:b}=u(V,L);if(!g)throw new Error("bad point: invalid y coordinate");let p=(b&de)===de,_=(q&128)!==0;if(!A&&b===gt&&_)throw new Error("bad point: x=0 and x_0=1");return _!==p&&(b=c(-b)),h.fromAffine({x:b,y:S})}static fromHex(y,A=!1){return h.fromBytes(ot(y),A)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=8,A=!0){return v.createCache(this,y),A||this.multiply(Cs),this}assertValidity(){d(this)}equals(y){f(y);let{X:A,Y:w,Z:T}=this,{X:P,Y:k,Z:q}=y,S=c(A*q),E=c(P*T),N=c(w*q),V=c(k*T);return S===E&&N===V}is0(){return this.equals(h.ZERO)}negate(){return new h(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:y}=s,{X:A,Y:w,Z:T}=this,P=c(A*A),k=c(w*w),q=c(Cs*c(T*T)),S=c(y*P),E=A+w,N=c(c(E*E)-P-k),V=S+k,L=V-q,g=S-k,b=c(N*L),p=c(V*g),_=c(N*g),I=c(L*V);return new h(b,p,I,_)}add(y){f(y);let{a:A,d:w}=s,{X:T,Y:P,Z:k,T:q}=this,{X:S,Y:E,Z:N,T:V}=y,L=c(T*S),g=c(P*E),b=c(q*w*V),p=c(k*N),_=c((T+P)*(S+E)-L-g),I=p-b,C=p+b,R=c(g-A*L),D=c(_*I),O=c(C*R),U=c(_*R),ne=c(I*C);return new h(D,O,ne,U)}subtract(y){return this.add(y.negate())}multiply(y){if(!o.isValidNot0(y))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:A,f:w}=v.cached(this,y,T=>Bt(h,T));return Bt(h,[A,w])[0]}multiplyUnsafe(y,A=h.ZERO){if(!o.isValid(y))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return y===gt?h.ZERO:this.is0()||y===de?this:v.unsafe(this,y,w=>Bt(h,w),A)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return v.unsafe(this,s.n).is0()}toAffine(y){return m(this,y)}clearCofactor(){return i===de?this:this.multiplyUnsafe(i)}toBytes(){let{x:y,y:A}=this.toAffine(),w=n.toBytes(A);return w[w.length-1]|=y&de?128:0,w}toHex(){return nt(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let v=new cr(h,o.BITS);return h.BASE.precompute(8),h}function Nc(r,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');yt(t,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=t,{BASE:o,Fp:s,Fn:i}=r,a=t.randomBytes||rr,c=t.adjustScalarBytes||(S=>S),u=t.domain||((S,E,N)=>{if(it(N,"phflag"),E.length||N)throw new Error("Contexts/pre-hash are not supported");return S});function l(S){return i.create(Ct(S))}function f(S){let E=w.secretKey;M(S,w.secretKey,"secretKey");let N=M(e(S),2*E,"hashedSecretKey"),V=c(N.slice(0,E)),L=N.slice(E,2*E),g=l(V);return{head:V,prefix:L,scalar:g}}function m(S){let{head:E,prefix:N,scalar:V}=f(S),L=o.multiply(V),g=L.toBytes();return{head:E,prefix:N,scalar:V,point:L,pointBytes:g}}function d(S){return m(S).pointBytes}function h(S=Uint8Array.of(),...E){let N=Ie(...E);return l(e(u(N,M(S,void 0,"context"),!!n)))}function v(S,E,N={}){S=M(S,void 0,"message"),n&&(S=n(S));let{prefix:V,scalar:L,pointBytes:g}=m(E),b=h(N.context,V,S),p=o.multiply(b).toBytes(),_=h(N.context,p,g,S),I=i.create(b+_*L);if(!i.isValid(I))throw new Error("sign failed: invalid s");let C=Ie(p,i.toBytes(I));return M(C,w.signature,"result")}let x={zip215:!0};function y(S,E,N,V=x){let{context:L,zip215:g}=V,b=w.signature;S=M(S,b,"signature"),E=M(E,void 0,"message"),N=M(N,w.publicKey,"publicKey"),g!==void 0&&it(g,"zip215"),n&&(E=n(E));let p=b/2,_=S.subarray(0,p),I=Ct(S.subarray(p,b)),C,R,D;try{C=r.fromBytes(N,g),R=r.fromBytes(_,g),D=o.multiplyUnsafe(I)}catch{return!1}if(!g&&C.isSmallOrder())return!1;let O=h(L,R.toBytes(),C.toBytes(),E);return R.add(C.multiplyUnsafe(O)).subtract(D).clearCofactor().is0()}let A=s.BYTES,w={secretKey:A,publicKey:A,signature:2*A,seed:A};function T(S=a(w.seed)){return M(S,w.seed,"seed")}function P(S){return Tt(S)&&S.length===i.BYTES}function k(S,E){try{return!!r.fromBytes(S,E)}catch{return!1}}let q={getExtendedPublicKey:m,randomSecretKey:T,isValidSecretKey:P,isValidPublicKey:k,toMontgomery(S){let{y:E}=r.fromBytes(S),N=w.publicKey,V=N===32;if(!V&&N!==57)throw new Error("only defined for 25519 and 448");let L=V?s.div(de+E,de-E):s.div(E-de,E+de);return s.toBytes(L)},toMontgomerySecret(S){let E=w.secretKey;M(S,E);let N=e(S.subarray(0,E));return c(N).subarray(0,E)}};return Object.freeze({keygen:Dn(T,d),getPublicKey:d,sign:v,verify:y,utils:q,Point:r,lengths:w})}var uh=BigInt(1),Uc=BigInt(2);var lh=BigInt(5),fh=BigInt(8),Ls=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),hh={p:Ls,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:fh,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function dh(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=Ls,a=r*r%s*r%s,c=ee(a,Uc,s)*a%s,u=ee(c,uh,s)*r%s,l=ee(u,lh,s)*u%s,f=ee(l,e,s)*l%s,m=ee(f,t,s)*f%s,d=ee(m,n,s)*m%s,h=ee(d,o,s)*d%s,v=ee(h,o,s)*d%s,x=ee(v,e,s)*l%s;return{pow_p_5_8:ee(x,Uc,s)*r%s,b2:a}}function ph(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var Mc=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function mh(r,e){let t=Ls,n=ce(e*e*e,t),o=ce(n*n*e,t),s=dh(r*o).pow_p_5_8,i=ce(r*n*s,t),a=ce(e*i*i,t),c=i,u=ce(i*Mc,t),l=a===r,f=a===ce(-r,t),m=a===ce(-r*Mc,t);return l&&(i=c),(f||m)&&(i=u),Tc(i,t)&&(i=ce(-i,t)),{isValid:l||f,value:i}}var yh=Pc(hh,{uvRatio:mh});function gh(r){return Nc(yh,dc,Object.assign({adjustScalarBytes:ph},r))}var kc=gh({});var Hr=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},Cn=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var Kc={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new Cn("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 Ne=Kc;var Ln=32;var Rs,bh=(async()=>{try{return await Ne.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function xh(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await Ne.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await Ne.get().subtle.verify({name:"Ed25519"},n,e,t instanceof Uint8Array?t:t.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function wh(r,e,t){return kc.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function qc(r,e,t){return Rs==null&&(Rs=await bh),Rs?xh(r,e,t):wh(r,e,t)}function Rn(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Bn=class{type="Ed25519";raw;constructor(e){this.raw=Bs(e,Ln)}toMultihash(){return Me.digest($e(this))}toCID(){return le.createV1(114,this.toMultihash())}toString(){return te.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:fe(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let o=qc(this.raw,t,e);return Rn(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function Os(r){return r=Bs(r,Ln),new Bn(r)}function Bs(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new ie(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var Sh=Math.pow(2,7),vh=Math.pow(2,14),_h=Math.pow(2,21),Ps=Math.pow(2,28),Ns=Math.pow(2,35),Us=Math.pow(2,42),Ms=Math.pow(2,49),Z=128,xe=127;function De(r){if(r<Sh)return 1;if(r<vh)return 2;if(r<_h)return 3;if(r<Ps)return 4;if(r<Ns)return 5;if(r<Us)return 6;if(r<Ms)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function ur(r,e,t=0){switch(De(r)){case 8:e[t++]=r&255|Z,r/=128;case 7:e[t++]=r&255|Z,r/=128;case 6:e[t++]=r&255|Z,r/=128;case 5:e[t++]=r&255|Z,r/=128;case 4:e[t++]=r&255|Z,r>>>=7;case 3:e[t++]=r&255|Z,r>>>=7;case 2:e[t++]=r&255|Z,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function Ah(r,e,t=0){switch(De(r)){case 8:e.set(t++,r&255|Z),r/=128;case 7:e.set(t++,r&255|Z),r/=128;case 6:e.set(t++,r&255|Z),r/=128;case 5:e.set(t++,r&255|Z),r/=128;case 4:e.set(t++,r&255|Z),r>>>=7;case 3:e.set(t++,r&255|Z),r>>>=7;case 2:e.set(t++,r&255|Z),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function ks(r,e){let t=r[e],n=0;if(n+=t&xe,t<Z||(t=r[e+1],n+=(t&xe)<<7,t<Z)||(t=r[e+2],n+=(t&xe)<<14,t<Z)||(t=r[e+3],n+=(t&xe)<<21,t<Z)||(t=r[e+4],n+=(t&xe)*Ps,t<Z)||(t=r[e+5],n+=(t&xe)*Ns,t<Z)||(t=r[e+6],n+=(t&xe)*Us,t<Z)||(t=r[e+7],n+=(t&xe)*Ms,t<Z))return n;throw new RangeError("Could not decode varint")}function Th(r,e){let t=r.get(e),n=0;if(n+=t&xe,t<Z||(t=r.get(e+1),n+=(t&xe)<<7,t<Z)||(t=r.get(e+2),n+=(t&xe)<<14,t<Z)||(t=r.get(e+3),n+=(t&xe)<<21,t<Z)||(t=r.get(e+4),n+=(t&xe)*Ps,t<Z)||(t=r.get(e+5),n+=(t&xe)*Ns,t<Z)||(t=r.get(e+6),n+=(t&xe)*Us,t<Z)||(t=r.get(e+7),n+=(t&xe)*Ms,t<Z))return n;throw new RangeError("Could not decode varint")}function lr(r,e,t=0){return e==null&&(e=Ae(De(r))),e instanceof Uint8Array?ur(r,e,t):Ah(r,e,t)}function Fr(r,e=0){return r instanceof Uint8Array?ks(r,e):Th(r,e)}var qs=new Float32Array([-0]),bt=new Uint8Array(qs.buffer);function Hc(r,e,t){qs[0]=r,e[t]=bt[0],e[t+1]=bt[1],e[t+2]=bt[2],e[t+3]=bt[3]}function Fc(r,e){return bt[0]=r[e],bt[1]=r[e+1],bt[2]=r[e+2],bt[3]=r[e+3],qs[0]}var Vs=new Float64Array([-0]),we=new Uint8Array(Vs.buffer);function zc(r,e,t){Vs[0]=r,e[t]=we[0],e[t+1]=we[1],e[t+2]=we[2],e[t+3]=we[3],e[t+4]=we[4],e[t+5]=we[5],e[t+6]=we[6],e[t+7]=we[7]}function $c(r,e){return we[0]=r[e],we[1]=r[e+1],we[2]=r[e+2],we[3]=r[e+3],we[4]=r[e+4],we[5]=r[e+5],we[6]=r[e+6],we[7]=r[e+7],Vs[0]}var Ih=BigInt(Number.MAX_SAFE_INTEGER),Dh=BigInt(Number.MIN_SAFE_INTEGER),Be=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 Ot;if(e<Ih&&e>Dh)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>Gc&&(o=0n,++n>Gc&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return Ot;let t=e<0;t&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}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):Ot}},Ot=new Be(0,0);Ot.toBigInt=function(){return 0n};Ot.zzEncode=Ot.zzDecode=function(){return this};Ot.length=function(){return 1};var Gc=4294967296n;function Wc(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 Zc(r,e,t){if(t-e<1)return"";let o,s=[],i=0,a;for(;e<t;)a=r[e++],a<128?s[i++]=a:a>191&&a<224?s[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,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function Hs(r,e,t){let n=t,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function Ke(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function On(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var Fs=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=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,Ke(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 Ke(this,4);return On(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Ke(this,4);return On(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Ke(this,4);let e=Fc(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Ke(this,4);let e=$c(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 Ke(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Zc(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Ke(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Ke(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 Be(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 Ke(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 Ke(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 Ke(this,8);let e=On(this.buf,this.pos+=4),t=On(this.buf,this.pos+=4);return new Be(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=ks(this.buf,this.pos);return this.pos+=De(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 zs(r){return new Fs(r instanceof Uint8Array?r:r.subarray())}function Ce(r,e,t){let n=zs(r);return e.decode(n,void 0,t)}function $s(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return Ae(i);o+i>e&&(n=Ae(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var Pt=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function Gs(){}var Zs=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},Ch=$s();function Lh(r){return globalThis.Buffer!=null?Ae(r):Ch(r)}var $r=class{len;head;tail;states;constructor(){this.len=0,this.head=new Pt(Gs,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new Pt(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Ys((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(Pn,10,Be.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Be.fromBigInt(e);return this._push(Pn,t.length(),t)}uint64Number(e){return this._push(ur,De(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=Be.fromBigInt(e).zzEncode();return this._push(Pn,t.length(),t)}sint64Number(e){let t=Be.fromNumber(e).zzEncode();return this._push(Pn,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Ws,1,e?1:0)}fixed32(e){return this._push(zr,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Be.fromBigInt(e);return this._push(zr,4,t.lo)._push(zr,4,t.hi)}fixed64Number(e){let t=Be.fromNumber(e);return this._push(zr,4,t.lo)._push(zr,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(Hc,4,e)}double(e){return this._push(zc,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(Ws,1,0):this.uint32(t)._push(Bh,t,e)}string(e){let t=Wc(e);return t!==0?this.uint32(t)._push(Hs,t,e):this._push(Ws,1,0)}fork(){return this.states=new Zs(this),this.head=this.tail=new Pt(Gs,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Pt(Gs,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=Lh(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function Ws(r,e,t){e[t]=r&255}function Rh(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var Ys=class extends Pt{next;constructor(e,t){super(Rh,e,t),this.next=void 0}};function Pn(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 zr(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 Bh(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&($r.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(Oh,e,r),this},$r.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(Ph,e,r),this});function Oh(r,e,t){e.set(r,t)}function Ph(r,e,t){r.length<40?Hs(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(K(r),t)}function Xs(){return new $r}function Le(r,e){let t=Xs();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var fr;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(fr||(fr={}));function Nn(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function Nt(r){function e(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let t=function(s,i){let a=e(s);i.int32(a)},n=function(s){let i=s.int32();return e(i)};return Nn("enum",fr.VARINT,t,n)}function Re(r,e){return Nn("message",fr.LENGTH_DELIMITED,r,e)}var Gr=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var ue;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(ue||(ue={}));var js;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(js||(js={}));(function(r){r.codec=()=>Nt(js)})(ue||(ue={}));var Ze;(function(r){let e;r.codec=()=>(e==null&&(e=Re((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),ue.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.Type=ue.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Le(t,r.codec()),r.decode=(t,n)=>Ce(t,r.codec(),n)})(Ze||(Ze={}));var Qs;(function(r){let e;r.codec=()=>(e==null&&(e=Re((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),ue.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.Type=ue.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Le(t,r.codec()),r.decode=(t,n)=>Ce(t,r.codec(),n)})(Qs||(Qs={}));var Zr={};ve(Zr,{MAX_RSA_KEY_SIZE:()=>Js,generateRSAKeyPair:()=>eu,jwkToJWKKeyPair:()=>tu,jwkToPkcs1:()=>kh,jwkToPkix:()=>ni,jwkToRSAPrivateKey:()=>ai,pkcs1MessageToJwk:()=>ti,pkcs1MessageToRSAPrivateKey:()=>oi,pkcs1ToJwk:()=>Mh,pkcs1ToRSAPrivateKey:()=>Jc,pkixMessageToJwk:()=>ri,pkixMessageToRSAPublicKey:()=>ii,pkixToJwk:()=>Kh,pkixToRSAPublicKey:()=>si});var hr=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=Zr.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return le.createV1(114,this._multihash)}toString(){return te.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:fe(this.raw,e.raw)}verify(e,t,n){return Qc(this.jwk,t,e,n)}},Wr=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=Zr.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:fe(this.raw,e.raw)}sign(e,t){return jc(this.jwk,e,t)}};var Js=8192,ei=18,Nh=1062,Uh=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function Mh(r){let e=et(r);return ti(e)}function ti(r){return{n:$(r[1],"base64url"),e:$(r[2],"base64url"),d:$(r[3],"base64url"),p:$(r[4],"base64url"),q:$(r[5],"base64url"),dp:$(r[6],"base64url"),dq:$(r[7],"base64url"),qi:$(r[8],"base64url"),kty:"RSA"}}function kh(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 ie("JWK was missing components");return ht([Te(Uint8Array.from([0])),Te(K(r.n,"base64url")),Te(K(r.e,"base64url")),Te(K(r.d,"base64url")),Te(K(r.p,"base64url")),Te(K(r.q,"base64url")),Te(K(r.dp,"base64url")),Te(K(r.dq,"base64url")),Te(K(r.qi,"base64url"))]).subarray()}function Kh(r){let e=et(r,{offset:0});return ri(e)}function ri(r){let e=et(r[1],{offset:0});return{kty:"RSA",n:$(e[0],"base64url"),e:$(e[1],"base64url")}}function ni(r){if(r.n==null||r.e==null)throw new ie("JWK was missing components");return ht([Uh,wn(ht([Te(K(r.n,"base64url")),Te(K(r.e,"base64url"))]))]).subarray()}function Jc(r){let e=et(r);return oi(e)}function oi(r){let e=ti(r);return ai(e)}function si(r,e){if(r.byteLength>=Nh)throw new Gt("Key size is too large");let t=et(r,{offset:0});return ii(t,r,e)}function ii(r,e,t){let n=ri(r);if(t==null){let o=nr(Ze.encode({Type:ue.RSA,Data:e}));t=Fe(ei,o)}return new hr(n,t)}function ai(r){if(nu(r)>Js)throw new ie("Key size is too large");let e=tu(r),t=nr(Ze.encode({Type:ue.RSA,Data:ni(e.publicKey)})),n=Fe(ei,t);return new Wr(e.privateKey,new hr(e.publicKey,n))}async function eu(r){if(r>Js)throw new ie("Key size is too large");let e=await ru(r),t=nr(Ze.encode({Type:ue.RSA,Data:ni(e.publicKey)})),n=Fe(ei,t);return new Wr(e.privateKey,new hr(e.publicKey,n))}function tu(r){if(r==null)throw new ie("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function ru(r,e){let t=await Ne.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 qh(t,e);return{privateKey:n[0],publicKey:n[1]}}async function jc(r,e,t){let n=await Ne.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let o=await Ne.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,e instanceof Uint8Array?e:e.subarray());return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function Qc(r,e,t,n){let o=await Ne.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let s=await Ne.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,e,t instanceof Uint8Array?t:t.subarray());return n?.signal?.throwIfAborted(),s}async function qh(r,e){if(r.privateKey==null||r.publicKey==null)throw new ie("Private and public key are required");let t=await Promise.all([Ne.get().subtle.exportKey("jwk",r.privateKey),Ne.get().subtle.exportKey("jwk",r.publicKey)]);return e?.signal?.throwIfAborted(),t}function nu(r){if(r.kty!=="RSA")throw new ie("invalid key type");if(r.n==null)throw new ie("invalid key modulus");return K(r.n,"base64url").length*8}var Un=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if(En(e),M(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,o=new Uint8Array(n);o.set(t.length>n?e.create().update(t).digest():t);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),rt(o)}update(e){return tr(this),this.iHash.update(e),this}digestInto(e){tr(this),M(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),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:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,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()}},ci=(r,e,t)=>new Un(r,e).update(t).digest();ci.create=(r,e)=>new Un(r,e);var ou=(r,e)=>(r+(r>=0?e:-e)/su)/e;function Vh(r,e,t){let[[n,o],[s,i]]=e,a=ou(i*r,t),c=ou(-o*r,t),u=r-a*n-c*s,l=-a*o-c*i,f=u<at,m=l<at;f&&(u=-u),m&&(l=-l);let d=Kr(Math.ceil(ws(t)/2))+dr;if(u<at||u>=d||l<at||l>=d)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:f,k1:u,k2neg:m,k2:l}}function li(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function ui(r,e){let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return it(t.lowS,"lowS"),it(t.prehash,"prehash"),t.format!==void 0&&li(t.format),t}var fi=class extends Error{constructor(e=""){super(e)}},xt={Err:fi,_tlv:{encode:(r,e)=>{let{Err:t}=xt;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,o=Mr(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let s=n>127?Mr(o.length/2|128):"";return Mr(r)+s+o+e},decode(r,e){let{Err:t}=xt,n=0;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let o=e[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new 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}=xt;if(r<at)throw new e("integer: negative integers are not allowed");let t=Mr(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}=xt;if(r[0]&128)throw new e("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return or(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=xt,o=M(r,void 0,"signature"),{v:s,l:i}=n.decode(48,o);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v: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}=xt,n=e.encode(2,t.encode(r.r)),o=e.encode(2,t.encode(r.s)),s=n+o;return e.encode(48,s)}},at=BigInt(0),dr=BigInt(1),su=BigInt(2),Mn=BigInt(3),Hh=BigInt(4);function iu(r,e={}){let t=In("weierstrass",r,e),{Fp:n,Fn:o}=t,s=t.CURVE,{h:i,n:a}=s;yt(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c}=e;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let u=cu(n,o);function l(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(L,g,b){let{x:p,y:_}=g.toAffine(),I=n.toBytes(p);if(it(b,"isCompressed"),b){l();let C=!n.isOdd(_);return Ie(au(C),I)}else return Ie(Uint8Array.of(4),I,n.toBytes(_))}function m(L){M(L,void 0,"Point");let{publicKey:g,publicKeyUncompressed:b}=u,p=L.length,_=L[0],I=L.subarray(1);if(p===g&&(_===2||_===3)){let C=n.fromBytes(I);if(!n.isValid(C))throw new Error("bad point: is not on curve, wrong x");let R=v(C),D;try{D=n.sqrt(R)}catch(ne){let Q=ne instanceof Error?": "+ne.message:"";throw new Error("bad point: is not on curve, sqrt error"+Q)}l();let O=n.isOdd(D);return(_&1)===1!==O&&(D=n.neg(D)),{x:C,y:D}}else if(p===b&&_===4){let C=n.BYTES,R=n.fromBytes(I.subarray(0,C)),D=n.fromBytes(I.subarray(C,C*2));if(!x(R,D))throw new Error("bad point: is not on curve");return{x:R,y:D}}else throw new Error(`bad point: got length ${p}, expected compressed=${g} or uncompressed=${b}`)}let d=e.toBytes||f,h=e.fromBytes||m;function v(L){let g=n.sqr(L),b=n.mul(g,L);return n.add(n.add(b,n.mul(L,s.a)),s.b)}function x(L,g){let b=n.sqr(g),p=v(L);return n.eql(b,p)}if(!x(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let y=n.mul(n.pow(s.a,Mn),Hh),A=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(y,A)))throw new Error("bad curve params: a or b");function w(L,g,b=!1){if(!n.isValid(g)||b&&n.is0(g))throw new Error(`bad point coordinate ${L}`);return g}function T(L){if(!(L instanceof E))throw new Error("Weierstrass Point expected")}function P(L){if(!c||!c.basises)throw new Error("no endo");return Vh(L,c.basises,o.ORDER)}let k=sr((L,g)=>{let{X:b,Y:p,Z:_}=L;if(n.eql(_,n.ONE))return{x:b,y:p};let I=L.is0();g==null&&(g=I?n.ONE:n.inv(_));let C=n.mul(b,g),R=n.mul(p,g),D=n.mul(_,g);if(I)return{x:n.ZERO,y:n.ZERO};if(!n.eql(D,n.ONE))throw new Error("invZ was invalid");return{x:C,y:R}}),q=sr(L=>{if(L.is0()){if(e.allowInfinityPoint&&!n.is0(L.Y))return;throw new Error("bad point: ZERO")}let{x:g,y:b}=L.toAffine();if(!n.isValid(g)||!n.isValid(b))throw new Error("bad point: x or y not field elements");if(!x(g,b))throw new Error("bad point: equation left != right");if(!L.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function S(L,g,b,p,_){return b=new E(n.mul(b.X,L),b.Y,b.Z),g=Vr(p,g),b=Vr(_,b),g.add(b)}class E{static BASE=new E(s.Gx,s.Gy,n.ONE);static ZERO=new E(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(g,b,p){this.X=w("x",g),this.Y=w("y",b,!0),this.Z=w("z",p),Object.freeze(this)}static CURVE(){return s}static fromAffine(g){let{x:b,y:p}=g||{};if(!g||!n.isValid(b)||!n.isValid(p))throw new Error("invalid affine point");if(g instanceof E)throw new Error("projective point not allowed");return n.is0(b)&&n.is0(p)?E.ZERO:new E(b,p,n.ONE)}static fromBytes(g){let b=E.fromAffine(h(M(g,void 0,"point")));return b.assertValidity(),b}static fromHex(g){return E.fromBytes(ot(g))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,b=!0){return V.createCache(this,g),b||this.multiply(Mn),this}assertValidity(){q(this)}hasEvenY(){let{y:g}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(g)}equals(g){T(g);let{X:b,Y:p,Z:_}=this,{X:I,Y:C,Z:R}=g,D=n.eql(n.mul(b,R),n.mul(I,_)),O=n.eql(n.mul(p,R),n.mul(C,_));return D&&O}negate(){return new E(this.X,n.neg(this.Y),this.Z)}double(){let{a:g,b}=s,p=n.mul(b,Mn),{X:_,Y:I,Z:C}=this,R=n.ZERO,D=n.ZERO,O=n.ZERO,U=n.mul(_,_),ne=n.mul(I,I),Q=n.mul(C,C),G=n.mul(_,I);return G=n.add(G,G),O=n.mul(_,C),O=n.add(O,O),R=n.mul(g,O),D=n.mul(p,Q),D=n.add(R,D),R=n.sub(ne,D),D=n.add(ne,D),D=n.mul(R,D),R=n.mul(G,R),O=n.mul(p,O),Q=n.mul(g,Q),G=n.sub(U,Q),G=n.mul(g,G),G=n.add(G,O),O=n.add(U,U),U=n.add(O,U),U=n.add(U,Q),U=n.mul(U,G),D=n.add(D,U),Q=n.mul(I,C),Q=n.add(Q,Q),U=n.mul(Q,G),R=n.sub(R,U),O=n.mul(Q,ne),O=n.add(O,O),O=n.add(O,O),new E(R,D,O)}add(g){T(g);let{X:b,Y:p,Z:_}=this,{X:I,Y:C,Z:R}=g,D=n.ZERO,O=n.ZERO,U=n.ZERO,ne=s.a,Q=n.mul(s.b,Mn),G=n.mul(b,I),oe=n.mul(p,C),me=n.mul(_,R),He=n.add(b,p),se=n.add(I,C);He=n.mul(He,se),se=n.add(G,oe),He=n.sub(He,se),se=n.add(b,_);let be=n.add(I,R);return se=n.mul(se,be),be=n.add(G,me),se=n.sub(se,be),be=n.add(p,_),D=n.add(C,R),be=n.mul(be,D),D=n.add(oe,me),be=n.sub(be,D),U=n.mul(ne,se),D=n.mul(Q,me),U=n.add(D,U),D=n.sub(oe,U),U=n.add(oe,U),O=n.mul(D,U),oe=n.add(G,G),oe=n.add(oe,G),me=n.mul(ne,me),se=n.mul(Q,se),oe=n.add(oe,me),me=n.sub(G,me),me=n.mul(ne,me),se=n.add(se,me),G=n.mul(oe,se),O=n.add(O,G),G=n.mul(be,se),D=n.mul(He,D),D=n.sub(D,G),G=n.mul(He,oe),U=n.mul(be,U),U=n.add(U,G),new E(D,O,U)}subtract(g){return this.add(g.negate())}is0(){return this.equals(E.ZERO)}multiply(g){let{endo:b}=e;if(!o.isValidNot0(g))throw new Error("invalid scalar: out of range");let p,_,I=C=>V.cached(this,C,R=>Bt(E,R));if(b){let{k1neg:C,k1:R,k2neg:D,k2:O}=P(g),{p:U,f:ne}=I(R),{p:Q,f:G}=I(O);_=ne.add(G),p=S(b.beta,U,Q,C,D)}else{let{p:C,f:R}=I(g);p=C,_=R}return Bt(E,[p,_])[0]}multiplyUnsafe(g){let{endo:b}=e,p=this;if(!o.isValid(g))throw new Error("invalid scalar: out of range");if(g===at||p.is0())return E.ZERO;if(g===dr)return p;if(V.hasCache(this))return this.multiply(g);if(b){let{k1neg:_,k1:I,k2neg:C,k2:R}=P(g),{p1:D,p2:O}=Oc(E,p,I,R);return S(b.beta,D,O,_,C)}else return V.unsafe(p,g)}toAffine(g){return k(this,g)}isTorsionFree(){let{isTorsionFree:g}=e;return i===dr?!0:g?g(E,this):V.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:g}=e;return i===dr?this:g?g(E,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(g=!0){return it(g,"isCompressed"),this.assertValidity(),d(E,this,g)}toHex(g=!0){return nt(this.toBytes(g))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let N=o.BITS,V=new cr(E,e.endo?Math.ceil(N/2):N);return E.BASE.precompute(8),E}function au(r){return Uint8Array.of(r?2:3)}function cu(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Fh(r,e={}){let{Fn:t}=r,n=e.randomBytes||rr,o=Object.assign(cu(r.Fp,t),{seed:_s(t.ORDER)});function s(d){try{let h=t.fromBytes(d);return t.isValidNot0(h)}catch{return!1}}function i(d,h){let{publicKey:v,publicKeyUncompressed:x}=o;try{let y=d.length;return h===!0&&y!==v||h===!1&&y!==x?!1:!!r.fromBytes(d)}catch{return!1}}function a(d=n(o.seed)){return As(M(d,o.seed,"seed"),t.ORDER)}function c(d,h=!0){return r.BASE.multiply(t.fromBytes(d)).toBytes(h)}function u(d){let{secretKey:h,publicKey:v,publicKeyUncompressed:x}=o;if(!Tt(d)||"_lengths"in t&&t._lengths||h===v)return;let y=M(d,void 0,"key").length;return y===v||y===x}function l(d,h,v=!0){if(u(d)===!0)throw new Error("first arg must be private key");if(u(h)===!1)throw new Error("second arg must be public key");let x=t.fromBytes(d);return r.fromBytes(h).multiply(x).toBytes(v)}let f={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},m=Dn(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:l,keygen:m,Point:r,utils:f,lengths:o})}function uu(r,e,t={}){En(e),yt(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let n=t.randomBytes||rr,o=t.hmac||((b,p)=>ci(e,b,p)),{Fp:s,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:u,getPublicKey:l,getSharedSecret:f,utils:m,lengths:d}=Fh(r,t),h={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},v=a*su<s.ORDER;function x(b){let p=a>>dr;return b>p}function y(b,p){if(!i.isValidNot0(p))throw new Error(`invalid signature ${b}: out of range 1..Point.Fn.ORDER`);return p}function A(){if(v)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function w(b,p){li(p);let _=d.signature,I=p==="compact"?_:p==="recovered"?_+1:void 0;return M(b,I)}class T{r;s;recovery;constructor(p,_,I){if(this.r=y("r",p),this.s=y("s",_),I!=null){if(A(),![0,1,2,3].includes(I))throw new Error("invalid recovery id");this.recovery=I}Object.freeze(this)}static fromBytes(p,_=h.format){w(p,_);let I;if(_==="der"){let{r:O,s:U}=xt.toSig(M(p));return new T(O,U)}_==="recovered"&&(I=p[0],_="compact",p=p.subarray(1));let C=d.signature/2,R=p.subarray(0,C),D=p.subarray(C,C*2);return new T(i.fromBytes(R),i.fromBytes(D),I)}static fromHex(p,_){return this.fromBytes(ot(p),_)}assertRecovery(){let{recovery:p}=this;if(p==null)throw new Error("invalid recovery id: must be present");return p}addRecoveryBit(p){return new T(this.r,this.s,p)}recoverPublicKey(p){let{r:_,s:I}=this,C=this.assertRecovery(),R=C===2||C===3?_+a:_;if(!s.isValid(R))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let D=s.toBytes(R),O=r.fromBytes(Ie(au((C&1)===0),D)),U=i.inv(R),ne=k(M(p,void 0,"msgHash")),Q=i.create(-ne*U),G=i.create(I*U),oe=r.BASE.multiplyUnsafe(Q).add(O.multiplyUnsafe(G));if(oe.is0())throw new Error("invalid recovery: point at infinify");return oe.assertValidity(),oe}hasHighS(){return x(this.s)}toBytes(p=h.format){if(li(p),p==="der")return ot(xt.hexFromSig(this));let{r:_,s:I}=this,C=i.toBytes(_),R=i.toBytes(I);return p==="recovered"?(A(),Ie(Uint8Array.of(this.assertRecovery()),C,R)):Ie(C,R)}toHex(p){return nt(this.toBytes(p))}}let P=t.bits2int||function(p){if(p.length>8192)throw new Error("input is too large");let _=or(p),I=p.length*8-c;return I>0?_>>BigInt(I):_},k=t.bits2int_modN||function(p){return i.create(P(p))},q=Kr(c);function S(b){return kr("num < 2^"+c,b,at,q),i.toBytes(b)}function E(b,p){return M(b,void 0,"message"),p?M(e(b),void 0,"prehashed message"):b}function N(b,p,_){let{lowS:I,prehash:C,extraEntropy:R}=ui(_,h);b=E(b,C);let D=k(b),O=i.fromBytes(p);if(!i.isValidNot0(O))throw new Error("invalid private key");let U=[S(O),S(D)];if(R!=null&&R!==!1){let oe=R===!0?n(d.secretKey):R;U.push(M(oe,void 0,"extraEntropy"))}let ne=Ie(...U),Q=D;function G(oe){let me=P(oe);if(!i.isValidNot0(me))return;let He=i.inv(me),se=r.BASE.multiply(me).toAffine(),be=i.create(se.x);if(be===at)return;let cn=i.create(He*i.create(Q+be*O));if(cn===at)return;let ya=(se.x===be?0:2)|Number(se.y&dr),ga=cn;return I&&x(cn)&&(ga=i.neg(cn),ya^=1),new T(be,ga,v?void 0:ya)}return{seed:ne,k2sig:G}}function V(b,p,_={}){let{seed:I,k2sig:C}=N(b,p,_);return yc(e.outputLen,i.BYTES,o)(I,C).toBytes(_.format)}function L(b,p,_,I={}){let{lowS:C,prehash:R,format:D}=ui(I,h);if(_=M(_,void 0,"publicKey"),p=E(p,R),!Tt(b)){let O=b instanceof T?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+O)}w(b,D);try{let O=T.fromBytes(b,D),U=r.fromBytes(_);if(C&&O.hasHighS())return!1;let{r:ne,s:Q}=O,G=k(p),oe=i.inv(Q),me=i.create(G*oe),He=i.create(ne*oe),se=r.BASE.multiplyUnsafe(me).add(U.multiplyUnsafe(He));return se.is0()?!1:i.create(se.x)===ne}catch{return!1}}function g(b,p,_={}){let{prehash:I}=ui(_,h);return p=E(p,I),T.fromBytes(b,"recovered").recoverPublicKey(p).toBytes()}return Object.freeze({keygen:u,getPublicKey:l,getSharedSecret:f,utils:m,lengths:d,Point:r,sign:V,verify:L,recoverPublicKey:g,Signature:T,hash:e})}var di={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},zh={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var lu=BigInt(2);function $h(r){let e=di.p,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=r*r*r%e,l=u*u*r%e,f=ee(l,t,e)*l%e,m=ee(f,t,e)*l%e,d=ee(m,lu,e)*u%e,h=ee(d,o,e)*d%e,v=ee(h,s,e)*h%e,x=ee(v,a,e)*v%e,y=ee(x,c,e)*x%e,A=ee(y,a,e)*v%e,w=ee(A,t,e)*l%e,T=ee(w,i,e)*h%e,P=ee(T,n,e)*u%e,k=ee(P,lu,e);if(!hi.eql(hi.sqr(k),r))throw new Error("Cannot find square root");return k}var hi=ir(di.p,{sqrt:$h}),Gh=iu(di,{Fp:hi,endo:zh}),pr=uu(Gh,nr);function fu(r,e,t,n){let o=Jt.digest(t instanceof Uint8Array?t:t.subarray());if(Rn(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),pr.verify(e,s,r,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new Hr(String(s))});try{return n?.signal?.throwIfAborted(),pr.verify(e,o.digest,r,{prehash:!1,format:"der"})}catch(s){throw new Hr(String(s))}}var kn=class{type="secp256k1";raw;_key;constructor(e){this._key=du(e),this.raw=hu(this._key)}toMultihash(){return Me.digest($e(this))}toCID(){return le.createV1(114,this.toMultihash())}toString(){return te.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:fe(this.raw,e.raw)}verify(e,t,n){return fu(this._key,t,e,n)}};function pi(r){return new kn(r)}function hu(r){return pr.Point.fromBytes(r).toBytes()}function du(r){try{return pr.Point.fromBytes(r),r}catch(e){throw new Gt(String(e))}}function pu(r,e){let{Type:t,Data:n}=Ze.decode(r),o=n??new Uint8Array;switch(t){case ue.RSA:return si(o,e);case ue.Ed25519:return Os(o);case ue.secp256k1:return pi(o);case ue.ECDSA:return cs(o);default:throw new Wt}}function mu(r){let{Type:e,Data:t}=Ze.decode(r.digest),n=t??new Uint8Array;switch(e){case ue.Ed25519:return Os(n);case ue.secp256k1:return pi(n);case ue.ECDSA:return cs(n);default:throw new Wt}}function $e(r){return Ze.encode({Type:ue[r.type],Data:r.raw})}var yu=Symbol.for("nodejs.util.inspect.custom"),Wh=114,Yr=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()})`}[Po]=!0;toString(){return this.string==null&&(this.string=te.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return le.createV1(Wh,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return fe(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return fe(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[yu](){return`PeerId(${this.toString()})`}},Kn=class extends Yr{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},qn=class extends Yr{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},Vn=class extends Yr{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},Zh=2336,Xr=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Me.digest(K(this.url))}[yu](){return`PeerId(${this.url})`}[Po]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return le.createV1(Zh,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=$(e)),e.toString()===this.toString())}};var Yh=114,gu=2336;function mi(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=ze(te.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return Xh(le.parse(r));if(e==null)throw new ie('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=ze(e.decode(r))}return mr(t)}function mr(r){if(Qh(r))return new Kn({multihash:r});if(jh(r))try{let e=mu(r);if(e.type==="Ed25519")return new qn({multihash:r,publicKey:e});if(e.type==="secp256k1")return new Vn({multihash:r,publicKey:e})}catch{let t=$(r.digest);return new Xr(new URL(t))}throw new fn("Supplied PeerID Multihash is invalid")}function Xh(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==Yh&&r.code!==gu)throw new ln("Supplied PeerID CID is invalid");if(r.code===gu){let e=$(r.multihash.digest);return new Xr(new URL(e))}return mr(r.multihash)}function jh(r){return r.code===Me.code}function Qh(r){return r.code===Jt.code}var jr;(function(r){let e;r.codec=()=>(e==null&&(e=Re((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.publicKey!=null&&t.publicKey.byteLength>0&&(n.uint32(10),n.bytes(t.publicKey)),t.payloadType!=null&&t.payloadType.byteLength>0&&(n.uint32(18),n.bytes(t.payloadType)),t.payload!=null&&t.payload.byteLength>0&&(n.uint32(26),n.bytes(t.payload)),t.signature!=null&&t.signature.byteLength>0&&(n.uint32(42),n.bytes(t.signature)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={publicKey:re(0),payloadType:re(0),payload:re(0),signature:re(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.publicKey=t.bytes();break}case 2:{s.payloadType=t.bytes();break}case 3:{s.payload=t.bytes();break}case 5:{s.signature=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Le(t,r.codec()),r.decode=(t,n)=>Ce(t,r.codec(),n)})(jr||(jr={}));var Hn=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var Qr=class r{static createFromProtobuf=e=>{let t=jr.decode(e),n=pu(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 o=e.domain,s=e.codec,i=e.marshal(),a=bu(o,s,i),c=await t.sign(a.subarray(),n);return new r({publicKey:t.publicKey,payloadType:s,payload:i,signature:c})};static openAndCertify=async(e,t,n)=>{let o=r.createFromProtobuf(e);if(!await o.validate(t,n))throw new Hn("Envelope signature is not valid for the given domain");return o};publicKey;payloadType;payload;signature;marshaled;constructor(e){let{publicKey:t,payloadType:n,payload:o,signature:s}=e;this.publicKey=t,this.payloadType=n,this.payload=o,this.signature=s}marshal(){return this.marshaled==null&&(this.marshaled=jr.encode({publicKey:$e(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return e==null?!1:fe(this.marshal(),e.marshal())}async validate(e,t){let n=bu(e,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,t)}},bu=(r,e,t)=>{let n=K(r),o=lr(n.byteLength),s=lr(e.length),i=lr(t.length);return new J(o,n,s,e,i,t)};var ge=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},ct=class extends Error{static name="ValidationError";name="ValidationError"},Fn=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},zn=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var $n=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,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*o)-1;for(;;){let l=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let m=Number.parseInt(f,e);if(!Number.isNaN(m))return m});if(l===void 0)break;if(s*=e,s+=l,s>u||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:s})}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 o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Jh=45,ed=15,Gn=new $n;function xu(r){if(!(r.length>ed))return Gn.new(r).parseWith(()=>Gn.readIPv4Addr())}function wu(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Jh))return Gn.new(r).parseWith(()=>Gn.readIPv6Addr())}function Wn(r){return!!xu(r)}function Eu(r){return!!wu(r)}function gi(r){return e=>$(e,r)}function bi(r){return e=>K(e,r)}function yr(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Ut(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function Su(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=K(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Ut(n);return Je([t,o],t.length+o.length)}function vu(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=ft.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Ut(n);return Je([t,o],t.length+o.length)}function xi(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=$(e,"base32"),o=yr(t);return`${n}:${o}`}var wi=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let o=parseInt(t,10);if(isNaN(o)||o<0||o>255)throw new ge("Invalid byte value in IP address");e[n]=o}),e},_u=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=Wn(t[n]),i;s&&(i=wi(t[n]),t[n]=$(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,$(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 s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let s=parseInt(t[n],16);if(isNaN(s)||s<0||s>65535)throw new ge("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},Au=function(r){if(r.byteLength!==4)throw new ge("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},Tu=function(r){if(r.byteLength!==16)throw new ge("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],s=r[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;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 ge(`Invalid IPv6 address "${t}"`)}};function Iu(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new ge(`Invalid IPv6 address "${r}"`)}}var yi=Object.values(Rr).map(r=>r.decoder),td=(function(){let r=yi[0].or(yi[1]);return yi.slice(2).forEach(e=>r=r.or(e)),r})();function Du(r){return td.decode(r)}function Cu(r){return e=>r.encoder.encode(e)}function rd(r){if(parseInt(r).toString()!==r)throw new ct("Value must be an integer")}function nd(r){if(r<0)throw new ct("Value must be a positive integer, or zero")}function od(r){return e=>{if(e>r)throw new ct(`Value must be smaller than or equal to ${r}`)}}function sd(...r){return e=>{for(let t of r)t(e)}}var Jr=sd(rd,nd,od(65535));var pe=-1,Ei=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 zn(`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)}))}},ut=new Ei,wd=[{code:4,name:"ip4",size:32,valueToBytes:wi,bytesToValue:Au,validate:r=>{if(!Wn(r))throw new ct(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Ut,bytesToValue:yr,validate:Jr},{code:273,name:"udp",size:16,valueToBytes:Ut,bytesToValue:yr,validate:Jr},{code:33,name:"dccp",size:16,valueToBytes:Ut,bytesToValue:yr,validate:Jr},{code:41,name:"ip6",size:128,valueToBytes:_u,bytesToValue:Tu,stringToValue:Iu,validate:r=>{if(!Eu(r))throw new ct(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:pe},{code:43,name:"ipcidr",size:8,bytesToValue:gi("base10"),valueToBytes:bi("base10")},{code:53,name:"dns",size:pe},{code:54,name:"dns4",size:pe},{code:55,name:"dns6",size:pe},{code:56,name:"dnsaddr",size:pe},{code:132,name:"sctp",size:16,valueToBytes:Ut,bytesToValue:yr,validate:Jr},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:pe,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:pe,bytesToValue:gi("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?bi("base58btc")(r):le.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:xi,valueToBytes:Su},{code:445,name:"onion3",size:296,bytesToValue:xi,valueToBytes:vu},{code:446,name:"garlic64",size:pe},{code:447,name:"garlic32",size:pe},{code:448,name:"tls"},{code:449,name:"sni",size:pe},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:pe,bytesToValue:Cu(Yo),valueToBytes:Du},{code:480,name:"http"},{code:481,name:"http-path",size:pe,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:pe}];wd.forEach(r=>{ut.addProtocol(r)});function Lu(r){let e=[],t=0;for(;t<r.length;){let n=Fr(r,t),o=ut.getProtocol(n),s=De(n),i=Ed(o,r,t+s),a=0;i>0&&o.size===pe&&(a=De(i));let c=s+a+i,u={code:n,name:o.name,bytes:r.subarray(t,t+c)};if(i>0){let l=t+s+a,f=r.subarray(l,l+i);u.value=o.bytesToValue?.(f)??$(f)}e.push(u),t+=c}return e}function Ru(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=ut.getProtocol(n.code),s=De(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??K(n.value),a=i.byteLength,o.size===pe&&(c=De(a)));let u=new Uint8Array(s+c+a),l=0;ur(n.code,u,l),l+=s,i!=null&&(o.size===pe&&(ur(a,u,l),l+=c),u.set(i,l)),n.bytes=u}t.push(n.bytes),e+=n.bytes.byteLength}return Je(t,e)}function Bu(r){if(r.charAt(0)!=="/")throw new ge('String multiaddr must start with "/"');let e=[],t="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(t==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=ut.getProtocol(o);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",t="protocol";continue}else if(a)throw new ge(`Component ${o} 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 ge(`Component ${o} was missing value`);u.value=c.stringToValue?.(n)??n}e.push(u),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new ge("Incomplete multiaddr");return e}function Ou(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=ut.getProtocol(e.code);if(t==null)throw new ge(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function Ed(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:Fr(e,t)}var Sd=Symbol.for("nodejs.util.inspect.custom"),ki=Symbol.for("@multiformats/multiaddr");function vd(r){if(r==null&&(r="/"),Pu(r))return r.getComponents();if(r instanceof Uint8Array)return Lu(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),Bu(r);if(Array.isArray(r))return r;throw new ge("Must be a string, Uint8Array, Component[], or another Multiaddr")}var jn=class r{[ki]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=vd(e),t.validate!==!1&&_d(this)}get bytes(){return this.#r==null&&(this.#r=Ru(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=Ou(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(),o=n.lastIndexOf(t);if(o<0)throw new Fn(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,o),{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 fe(this.bytes,e.bytes)}[Sd](){return`Multiaddr(${this.toString()})`}};function _d(r){r.getComponents().forEach(e=>{let t=ut.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function Pu(r){return!!r?.[ki]}function Oe(r){return new jn(r)}var Ki={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Nu={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Uu=new globalThis.TextEncoder;function Ad(r,e){let t=Ki[e],n=Nu[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function Td(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Ki[e],o=Nu[e],s=r;for(;s.length>0;){let i=Uu.encodeInto(s,t);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(t[a]),o=BigInt.asUintN(e,o*n)}return o}function qi(r,{size:e=32,utf8Buffer:t}={}){if(!Ki[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 Td(r,e,t);r=Uu.encode(r)}return Ad(r,e)}var en={hash:r=>Number(qi(r,{size:32})),hashV:(r,e)=>Id(en.hash(r,e))};function Id(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),K(e,"base16")}var Vi=64,qe=class{fp;h;seed;constructor(e,t,n,o=2){if(o>Vi)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),i=re(o);for(let a=0;a<i.length;a++)i[a]=s[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?fe(this.fp,e.fp):!1}};function qt(r,e){return Math.floor(Math.random()*(e-r))+r}var Vt=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof qe))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof qe))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 qe))throw new TypeError("Invalid Fingerprint");let t=qt(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof qe))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var Dd=500,tn=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??en,this.seed=e.seed??qt(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=K(e));let t=new qe(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new Vt(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new Vt(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let s=[n,o],i=s[qt(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new Vt(this.bucketSize));for(let a=0;a<Dd;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 Vt(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=K(e));let t=new qe(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let s=(n^t.hash())%this.filterSize;return this.buckets[s]?.has(t)??!1}remove(e){typeof e=="string"&&(e=K(e));let t=new qe(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let s=(n^t.hash())%this.filterSize,i=this.buckets[s]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},Cd={1:.5,2:.84,4:.95,8:.98};function Ld(r=.001){return r>.002?2:r>1e-5?4:8}function Mu(r,e=.001){let t=Ld(e),n=Cd[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),Vi);return{filterSize:o,bucketSize:t,fingerprintSize:s}}var Qn=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??en,this.seed=e.seed??qt(0,Math.pow(2,10)),this.filterSeries=[new tn({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=K(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new tn({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=K(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=K(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 wr(r,e=.001,t){return new Qn({...Mu(r,e),...t??{}})}function Ve(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Jn=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}},Er=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Jn(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 Jn(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 Hi=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function wt(r={}){return Rd(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 Rd(r,e){e=e??{};let t=e.onEnd,n=new Er,o,s,i,a=Ve(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((x,y)=>{s=A=>{s=null,n.push(A);try{x(r(n))}catch(w){y(w)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Ve()})}},u=x=>s!=null?s(x):(n.push(x),o),l=x=>(n=new Er,s!=null?s({error:x}):(n.push({error:x}),o)),f=x=>{if(i)return o;if(e?.objectMode!==!0&&x?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:x})},m=x=>i?o:(i=!0,x!=null?l(x):u({done:!0})),d=()=>(n=new Er,m(),{done:!0}),h=x=>(m(x),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:d,throw:h,push:f,end:m,get readableLength(){return n.size},onEmpty:async x=>{let y=x?.signal;if(y?.throwIfAborted(),n.isEmpty())return;let A,w;y!=null&&(A=new Promise((T,P)=>{w=()=>{P(new Hi)},y.addEventListener("abort",w)}));try{await Promise.race([a.promise,A])}finally{w!=null&&y!=null&&y?.removeEventListener("abort",w)}}},t==null)return o;let v=o;return o={[Symbol.asyncIterator](){return this},next(){return v.next()},throw(x){return v.throw(x),t!=null&&(t(x),t=void 0),{done:!0}},return(){return v.return(),t!=null&&(t(),t=void 0),{done:!0}},push:f,end(x){return v.end(x),t!=null&&(t(x),t=void 0),o},get readableLength(){return v.readableLength},onEmpty:x=>v.onEmpty(x)},o}var Fi=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},zi=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},ku=r=>globalThis.DOMException===void 0?new zi(r):new DOMException(r),Ku=r=>{let e=r.reason===void 0?ku("This operation was aborted."):r.reason;return e instanceof Error?e:ku(e)};function $i(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=e,i,a,u=new Promise((l,f)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:d}=e;d.aborted&&f(Ku(d)),a=()=>{f(Ku(d))},d.addEventListener("abort",a,{once:!0})}if(t===Number.POSITIVE_INFINITY){r.then(l,f);return}let m=new Fi;i=s.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(d){f(d)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?l():o instanceof Error?f(o):(m.message=o??`Promise timed out after ${t} milliseconds`,f(m))},t),(async()=>{try{l(await r)}catch(d){f(d)}})()}).finally(()=>{u.clear(),a&&e.signal&&e.signal.removeEventListener("abort",a)});return u.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},u}var Bd=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 Od(r,e,t){let n,o=new Promise((s,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}=Bd(r),f=async(...d)=>{let h=t.multiArgs?d:d[0];if(t.filter)try{if(!await t.filter(h))return}catch(v){n(),i(v);return}c.push(h),t.count===c.length&&(n(),s(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&&s(c)});if(o.cancel=n,typeof t.timeout=="number"){let s=$i(o,{milliseconds:t.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function Ye(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=Od(r,e,t),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function Gi(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var eo=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}},Ht=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"};function Pd(r){return r.reason}async function to(r,e,t){if(e==null)return r;let n=t?.translateError??Pd;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let o;try{return await Promise.race([r,new Promise((s,i)=>{o=()=>{i(n(e))},e.addEventListener("abort",o)})])}finally{o!=null&&e.removeEventListener("abort",o)}}var ro=class{deferred;signal;constructor(e){this.signal=e,this.deferred=Ve(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Xe)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Nd(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var no=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=Nd(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,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 Xe),this.cleanup())}async join(e={}){let t=new ro(e.signal);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 to(this.fn({...this.options??{},signal:this.controller.signal}),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 oo=class extends _e{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=Gi(this.emitEmpty.bind(this),1),this.emitIdle=Gi(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 eo;let n=new no(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),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 s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Xe)}),this.clear()}async onEmpty(e){this.size!==0&&await Ye(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await Ye(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Ye(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=wt({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new Xe("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var Ud=Math.pow(2,20)*4,so=class extends _e{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??Ud,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new J,this.writeBuffer=new J,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,this.processSendQueue())};this.addEventListener("drain",t)}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let e=wt(),t=s=>{e.push(s.data)};this.addEventListener("message",t);let n=s=>{e.end(s.error)};this.addEventListener("close",n);let o=()=>{e.end()};this.addEventListener("remoteCloseWrite",o);try{yield*e}finally{this.removeEventListener("message",t),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",o)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new _t(`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 mn(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new _t("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 _t("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 _t(`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)}}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 un;this.dispatchEvent(new yn(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 Zt))}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;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 o=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(o===0){e=!1;break}let s=this.writeBuffer.sublist(0,o),i=new J(s);this.writeBuffer.consume(s.byteLength);let a=this.sendData(s);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 pn(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 Tr(`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 Tr(`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 io=class extends so{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 Ye(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 Ye(this,"drain",{...e,rejectionEvents:["close"]})),await this.sendClose(e),this.onTransportClosed())}};function ao(r){let e=new globalThis.AbortController;function t(){e.abort();for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}for(let s of r){if(s?.aborted===!0){t();break}s?.addEventListener!=null&&s.addEventListener("abort",t)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}var co=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"}};async function qu(r,e,t){if(e==null)return r;if(e.aborted)return r.catch(()=>{}),Promise.reject(new co(t?.errorMessage,t?.errorCode,t?.errorName));let n,o=new co(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var Wi=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=Ve(),this.haveNext=Ve()}[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=Ve(),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=Ve(),await qu(this.readNext.promise,t?.signal,t)}};function Vu(){return new Wi}function Md(r){return r[Symbol.asyncIterator]!=null}async function kd(r,e,t){try{await Promise.all(r.map(async n=>{for await(let o of n)await e.push(o,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*Kd(r){let e=new AbortController,t=Vu();kd(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*qd(r){for(let e of r)yield*e}function Vd(...r){let e=[];for(let t of r)Md(t)||e.push(t);return e.length===r.length?qd(e):Kd(r)}var Hu=Vd;function Fu(r,...e){if(r==null)throw new Error("Empty pipeline");if(Zi(r)){let n=r;r=()=>n.source}else if($u(r)||zu(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&Zi(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++)Zi(t[n])&&(t[n]=Fd(t[n]));return Hd(...t)}var Hd=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},zu=r=>r?.[Symbol.asyncIterator]!=null,$u=r=>r?.[Symbol.iterator]!=null,Zi=r=>r==null?!1:r.sink!=null&&r.source!=null,Fd=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=wt({objectMode:!0});t.then(()=>{n.end()},i=>{n.end(i)});let o,s=r.source;if(zu(s))o=async function*(){yield*s,n.end()};else if($u(s))o=function*(){yield*s,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Hu(n,o())}return r.source};var zd=4194304,uo=class extends Error{static name="UnwrappedError";name="UnwrappedError"},Xi=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},ji=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Qi=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function $d(r){return typeof r?.closeRead=="function"}function Gd(r){return typeof r?.close=="function"}function Yi(r){return $d(r)?r.readStatus==="closing"||r.readStatus==="closed":Gd(r)?r.status!=="open":!1}function Wd(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function Zd(r,e){let t=e?.maxBufferSize??zd,n=new J,o,s=!1;if(!Wd(r))throw new ie("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),o?.reject(new Error(`Read buffer overflow - ${f} > ${t}`))}o?.resolve()};r.addEventListener("message",i);let a=l=>{l.error!=null?o?.reject(l.error):o?.resolve()};r.addEventListener("close",a);let c=()=>{o?.resolve()};r.addEventListener("remoteCloseWrite",c);let u={readBuffer:n,async read(l){if(s===!0)throw new uo("Stream was unwrapped");if(Yi(r)){if(l?.bytes==null)return null;if(n.byteLength<l.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,l.bytes),new Ht(`Unexpected EOF - stream closed after reading ${n.byteLength}/${l.bytes} bytes`)}let f=l?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=f){o.resolve();break}if(await to(o.promise,l?.signal),Yi(r)){if(n.byteLength===0&&l?.bytes==null)return null;break}o=Promise.withResolvers()}let m=l?.bytes??n.byteLength;if(n.byteLength<m){if(Yi(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,m),new Ht(`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(s===!0)throw new uo("Stream was unwrapped");r.send(l)||await Ye(r,"drain",{signal:f?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,r.removeEventListener("message",i),r.removeEventListener("close",a),r.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.push(n))),r}};return u}function Yd(r,e={}){let t=Zd(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=De(e.maxDataLength));let n=e?.lengthDecoder??Fr,o=e?.lengthEncoder??lr;return{async read(i){let a=-1,c=new J;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 Xi("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new Qi(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new ji(`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 Ht(`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 Ht(`Unexpected EOF - read ${u.byteLength}/${a} bytes before the stream closed`);return u},async write(i,a){await t.write(new J(o(i.byteLength),i),a)},async writeV(i,a){let c=new J(...i.flatMap(u=>[o(u.byteLength),u]));await t.write(c,a)},unwrap(){return t.unwrap()}}}function Et(r,e){let t=Yd(r,e),n={read:async(o,s)=>{let i=await t.read(s);return o.decode(i)},write:async(o,s,i)=>{await t.write(s.encode(o),i)},writeV:async(o,s,i)=>{await t.writeV(o.map(a=>s.encode(a)),i)},pb:o=>({read:async s=>n.read(o,s),write:async(s,i)=>n.write(s,o,i),writeV:async(s,i)=>n.writeV(s,o,i),unwrap:()=>n}),unwrap:()=>t.unwrap()};return n}function Xd(r){return r?.addEventListener!=null}function jd(r){let e=wt(),t,n=i=>{e.push(i.data)},o=()=>{e.end(),r.removeEventListener("message",n),r.removeEventListener("close",s),r.removeEventListener("remoteCloseWrite",o)},s=i=>{e.end(i.error),i.error!=null&&t?.reject(i.error),r.removeEventListener("message",n),r.removeEventListener("close",s),r.removeEventListener("remoteCloseWrite",o)};return r.addEventListener("message",n),r.addEventListener("close",s,{once:!0}),r.addEventListener("remoteCloseWrite",o,{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([Ye(r,"drain",{rejectionEvents:["close"]})])),u===!0))break}await r.close()}}}function Gu(...r){let e=r.map(t=>Xd(t)?jd(t):t);return Fu(...e)}var Sr=class extends oo{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var X=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),B=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),Wu=r=>({match:e=>r.match(e)===!1?e:!1}),F=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),Ee=(...r)=>({match:e=>{let t;for(let n of r){let o=n.match(e);o!==!1&&(t==null||o.length<t.length)&&(t=o)}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 j(...r){function e(o){if(o==null)return!1;let s=o.getComponents();for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function t(o){return e(o)!==!1}function n(o){let s=e(o);return s===!1?!1:s.length===0}return{matchers:r,matches:t,exactMatch:n}}var Qd=B(421),rE=j(Qd),fo=B(54),ho=B(55),po=B(56),ea=B(53),nE=j(fo,F(B(421))),oE=j(ho,F(B(421))),sE=j(po,F(B(421))),iE=j(Ee(ea,po,fo,ho),F(B(421))),Zu=W(B(4),F(B(43))),Yu=W(F(B(42)),B(41),F(B(43))),ta=Ee(Zu,Yu),Ft=Ee(ta,ea,fo,ho,po),aE=j(Ee(ta,W(Ee(ea,po,fo,ho),F(B(421))))),cE=j(Zu),uE=j(Yu),lE=j(ta),ra=W(Ft,B(6)),rn=W(Ft,B(273)),fE=j(W(ra,F(B(421)))),hE=j(rn),na=W(rn,X(460),F(B(421))),mo=W(rn,X(461),F(B(421))),Jd=Ee(na,mo),dE=j(na),pE=j(mo),Ji=Ee(Ft,ra,rn,na,mo),Xu=Ee(W(Ji,X(477),F(B(421)))),mE=j(Xu),ju=Ee(W(Ji,X(478),F(B(421))),W(Ji,X(448),F(B(449)),X(477),F(B(421)))),yE=j(ju),Qu=W(rn,X(280),F(B(466)),F(B(466)),F(B(421))),gE=j(Qu),Ju=W(mo,X(465),F(B(466)),F(B(466)),F(B(421))),bE=j(Ju),lo=Ee(Xu,ju,W(ra,F(B(421))),W(Jd,F(B(421))),W(Ft,F(B(421))),Qu,Ju,B(421)),el=j(lo),ep=W(F(lo),X(290),Wu(X(281)),F(B(421))),zt=j(ep),tp=Ee(W(lo,X(290),X(281),F(B(421))),W(lo,X(281),F(B(421))),W(X(281),F(B(421)))),xE=j(tp),rp=Ee(W(Ft,B(6),X(480),F(B(421))),W(Ft,X(480),F(B(421)))),wE=j(rp),np=W(Ft,Ee(W(B(6,"443"),X(480)),W(B(6),X(443)),W(B(6),X(448),X(480)),W(X(448),X(480)),X(448),X(443)),F(B(421))),EE=j(np),op=Ee(W(B(777),F(B(421)))),SE=j(op),sp=Ee(W(B(400),F(B(421)))),vE=j(sp);var oa=1e3,tl=60*oa,rl=15,nl=120*tl,ol=1,yo=5e3,sl=100,sa="circuit-relay-source",nn=`${ba}-circuit-relay`,il=2*tl,al=BigInt(1<<17),Ue="/libp2p/circuit/relay/0.2.0/hop",$t="/libp2p/circuit/relay/0.2.0/stop",cl=30*oa,TE=30*oa,on=300,ul=4096,ll=.001;var Y;(function(r){let e;(function(o){o.RESERVE="RESERVE",o.CONNECT="CONNECT",o.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(o){o[o.RESERVE=0]="RESERVE",o[o.CONNECT=1]="CONNECT",o[o.STATUS=2]="STATUS"})(t||(t={})),(function(o){o.codec=()=>Nt(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Re((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.type!=null&&(s.uint32(8),r.Type.codec().encode(o.type,s)),o.peer!=null&&(s.uint32(18),vr.codec().encode(o.peer,s)),o.reservation!=null&&(s.uint32(26),go.codec().encode(o.reservation,s)),o.limit!=null&&(s.uint32(34),_r.codec().encode(o.limit,s)),o.status!=null&&(s.uint32(40),H.codec().encode(o.status,s)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let u=o.uint32();switch(u>>>3){case 1:{a.type=r.Type.codec().decode(o);break}case 2:{a.peer=vr.codec().decode(o,o.uint32(),{limits:i.limits?.peer});break}case 3:{a.reservation=go.codec().decode(o,o.uint32(),{limits:i.limits?.reservation});break}case 4:{a.limit=_r.codec().decode(o,o.uint32(),{limits:i.limits?.limit});break}case 5:{a.status=H.codec().decode(o);break}default:{o.skipType(u&7);break}}}return a})),n),r.encode=o=>Le(o,r.codec()),r.decode=(o,s)=>Ce(o,r.codec(),s)})(Y||(Y={}));var Pe;(function(r){let e;(function(o){o.CONNECT="CONNECT",o.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(o){o[o.CONNECT=0]="CONNECT",o[o.STATUS=1]="STATUS"})(t||(t={})),(function(o){o.codec=()=>Nt(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Re((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.type!=null&&(s.uint32(8),r.Type.codec().encode(o.type,s)),o.peer!=null&&(s.uint32(18),vr.codec().encode(o.peer,s)),o.limit!=null&&(s.uint32(26),_r.codec().encode(o.limit,s)),o.status!=null&&(s.uint32(32),H.codec().encode(o.status,s)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let u=o.uint32();switch(u>>>3){case 1:{a.type=r.Type.codec().decode(o);break}case 2:{a.peer=vr.codec().decode(o,o.uint32(),{limits:i.limits?.peer});break}case 3:{a.limit=_r.codec().decode(o,o.uint32(),{limits:i.limits?.limit});break}case 4:{a.status=H.codec().decode(o);break}default:{o.skipType(u&7);break}}}return a})),n),r.encode=o=>Le(o,r.codec()),r.decode=(o,s)=>Ce(o,r.codec(),s)})(Pe||(Pe={}));var vr;(function(r){let e;r.codec=()=>(e==null&&(e=Re((t,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),t.id!=null&&t.id.byteLength>0&&(n.uint32(10),n.bytes(t.id)),t.addrs!=null)for(let s of t.addrs)n.uint32(18),n.bytes(s);o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={id:re(0),addrs:[]},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.id=t.bytes();break}case 2:{if(o.limits?.addrs!=null&&s.addrs.length===o.limits.addrs)throw new Gr('Decode error - map field "addrs" had too many elements');s.addrs.push(t.bytes());break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Le(t,r.codec()),r.decode=(t,n)=>Ce(t,r.codec(),n)})(vr||(vr={}));var go;(function(r){let e;r.codec=()=>(e==null&&(e=Re((t,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),t.expire!=null&&t.expire!==0n&&(n.uint32(8),n.uint64(t.expire)),t.addrs!=null)for(let s of t.addrs)n.uint32(18),n.bytes(s);t.voucher!=null&&(n.uint32(26),bo.codec().encode(t.voucher,n)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={expire:0n,addrs:[]},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.expire=t.uint64();break}case 2:{if(o.limits?.addrs!=null&&s.addrs.length===o.limits.addrs)throw new Gr('Decode error - map field "addrs" had too many elements');s.addrs.push(t.bytes());break}case 3:{s.voucher=bo.codec().decode(t,t.uint32(),{limits:o.limits?.voucher});break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Le(t,r.codec()),r.decode=(t,n)=>Ce(t,r.codec(),n)})(go||(go={}));var _r;(function(r){let e;r.codec=()=>(e==null&&(e=Re((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.duration!=null&&(n.uint32(8),n.uint32(t.duration)),t.data!=null&&(n.uint32(16),n.uint64(t.data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.duration=t.uint32();break}case 2:{s.data=t.uint64();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Le(t,r.codec()),r.decode=(t,n)=>Ce(t,r.codec(),n)})(_r||(_r={}));var H;(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"})(H||(H={}));var ia;(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"})(ia||(ia={}));(function(r){r.codec=()=>Nt(ia)})(H||(H={}));var Ar;(function(r){let e;r.codec=()=>(e==null&&(e=Re((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.relay!=null&&t.relay.byteLength>0&&(n.uint32(10),n.bytes(t.relay)),t.peer!=null&&t.peer.byteLength>0&&(n.uint32(18),n.bytes(t.peer)),t.expiration!=null&&t.expiration!==0n&&(n.uint32(24),n.uint64(t.expiration)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={relay:re(0),peer:re(0),expiration:0n},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.relay=t.bytes();break}case 2:{s.peer=t.bytes();break}case 3:{s.expiration=t.uint64();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Le(t,r.codec()),r.decode=(t,n)=>Ce(t,r.codec(),n)})(Ar||(Ar={}));var bo;(function(r){let e;r.codec=()=>(e==null&&(e=Re((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.publicKey!=null&&t.publicKey.byteLength>0&&(n.uint32(10),n.bytes(t.publicKey)),t.payloadType!=null&&t.payloadType.byteLength>0&&(n.uint32(18),n.bytes(t.payloadType)),t.payload!=null&&(n.uint32(26),Ar.codec().encode(t.payload,n)),t.signature!=null&&t.signature.byteLength>0&&(n.uint32(42),n.bytes(t.signature)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={publicKey:re(0),payloadType:re(0),signature:re(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.publicKey=t.bytes();break}case 2:{s.payloadType=t.bytes();break}case 3:{s.payload=Ar.codec().decode(t,t.uint32(),{limits:o.limits?.payload});break}case 5:{s.signature=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Le(t,r.codec()),r.decode=(t,n)=>Ce(t,r.codec(),n)})(bo||(bo={}));var xo=class extends Error{constructor(e="Transfer limit error"){super(e),this.name="TransferLimitError"}},wo=class extends Error{constructor(e="Duration limit error"){super(e),this.name="DurationLimitError"}},sn=class extends Error{static name="HadEnoughRelaysError";name="HadEnoughRelaysError"},Eo=class extends Error{static name="DoubleRelayError";name="DoubleRelayError"},So=class extends Error{static name="RelayQueueFullError";name="RelayQueueFullError"};function fl(r,e,t){let n=e.remaining,o=s=>{let i=BigInt(s.data.byteLength);e.remaining-=i,e.remaining<0&&r.abort(new xo(`data limit of ${n} bytes exceeded`))};r.addEventListener("message",o)}function hl(r,e,t,n,o){function s(l){r.abort(l),e.abort(l)}let i=[t,n.signal];if(n.limit?.duration!=null){o.log("limiting relayed connection duration to %dms",n.limit.duration);let l=AbortSignal.timeout(n.limit.duration);i.push(l)}let a=ao(i);let c;n.limit?.data!=null&&(c={remaining:n.limit.data});let u=()=>{let l;t.aborted?l=t.reason:l=new wo(`duration limit of ${n.limit?.duration} ms exceeded`),s(l)};a.addEventListener("abort",u,{once:!0}),c!=null&&(fl(e,c,o),fl(r,c,o)),Gu(r,e,r).catch(l=>{s(l)}).finally(()=>{a.clear()})}function aa(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}},vo=j(W(el.matchers[0],X(290))),_o=j(X(290));function Ao(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}var St=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 Ao(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 Ao(this.map.values(),e=>e.key)}values(){return Ao(this.map.values(),e=>e.value)}get size(){return this.map.size}};var To=class{filter;constructor(e,t){this.filter=wr(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 ca(r,e=.001){return new To(r,e)}var ua=class extends St{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 la(r){let{name:e,metrics:t}=r,n;return t!=null?n=new ua({name:e,metrics:t}):n=new St,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 dl(r,e){let t=new fa(e?.errorMessage,e?.errorCode,e?.errorName),n=new AbortController,o=()=>{n.abort(t)},s=AbortSignal.timeout(r);s.addEventListener("abort",o);let i=n.signal;return i.reset=a=>{s?.removeEventListener("abort",o),s=AbortSignal.timeout(a??r),s.addEventListener("abort",()=>{n.abort(t)})},i.clear=()=>{s?.removeEventListener("abort",o),s=void 0},i}var Io=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??rl,this.applyDefaultLimit=t.applyDefaultLimit!==!1,this.reservationTtl=t.reservationTtl??nl,this.defaultDurationLimit=t.defaultDurationLimit??il,this.defaultDataLimit=t.defaultDataLimit??al,this.reservations=la({metrics:e.metrics,name:"libp2p_circuit_relay_server_reservations_total"})}reserve(e,t,n){let o=this.reservations.get(e);if(this.reservations.size>=this.maxReservations&&o==null)return{status:H.RESERVATION_REFUSED};let s=new Date(Date.now()+this.reservationTtl),i;return this.applyDefaultLimit&&(i=n??{data:this.defaultDataLimit,duration:this.defaultDurationLimit}),o!=null?(this.log("refreshing reservation for client %p",e),o.signal.reset(this.reservationTtl)):(this.log("creating new reservation for client %p",e),o={addr:t,expiry:s,limit:i,signal:dl(this.reservationTtl)}),this.reservations.set(e,o),o.signal.addEventListener("abort",()=>{this.reservations.delete(e)}),{status:H.OK,expire:Math.round(s.getTime()/1e3)}}removeReservation(e){this.reservations.delete(e)}get(e){return this.reservations.get(e)}clear(){this.reservations.clear()}};var Do=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 Ar.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 ip={maxOutboundStopStreams:on},Co=class extends _e{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??cl,this.maxInboundHopStreams=t.maxInboundHopStreams,this.maxOutboundHopStreams=t.maxOutboundHopStreams,this.maxOutboundStopStreams=t.maxOutboundStopStreams??ip.maxOutboundStopStreams,this.reservationStore=new Io(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(Ue,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(Ue),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 o={signal:n},s=Et(e);try{let i=await s.pb(Y).read(o);if(i?.type==null)throw new Error("request was invalid, could not read from stream");this.log("received",i.type),await this.handleHopProtocol({connection:t,stream:s,request:i},o)}catch(i){this.log.error("error while handling hop",i),await s.pb(Y).write({type:Y.Type.STATUS,status:H.MALFORMED_MESSAGE},o),e.abort(i)}}async handleHopProtocol({stream:e,request:t,connection:n},o){switch(this.log("received hop message"),t.type){case Y.Type.RESERVE:await this.handleReserve({stream:e,request:t,connection:n},o);break;case Y.Type.CONNECT:await this.handleConnect({stream:e,request:t,connection:n},o);break;default:this.log.error("invalid hop request type %s via peer %p",t.type,n.remotePeer),await e.pb(Y).write({type:Y.Type.STATUS,status:H.UNEXPECTED_MESSAGE})}}async handleReserve({stream:e,connection:t},n){let o=e.pb(Y);if(this.log("hop reserve request from %p",t.remotePeer),zt.exactMatch(t.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",t.remotePeer),await o.write({type:Y.Type.STATUS,status:H.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 o.write({type:Y.Type.STATUS,status:H.PERMISSION_DENIED},n);return}let s=this.reservationStore.reserve(t.remotePeer,t.remoteAddr);try{if(s.status!==H.OK){await o.write({type:Y.Type.STATUS,status:s.status},n);return}if(s.expire!=null){let i=s.expire*1e3-Date.now();await this.components.peerStore.merge(t.remotePeer,{tags:{[sa]:{value:1,ttl:i}}},n)}await o.write({type:Y.Type.STATUS,status:H.OK,reservation:await this.makeReservation(t.remotePeer,BigInt(s.expire??0)),limit:this.reservationStore.get(t.remotePeer)?.limit},n),this.log("sent confirmation response to %s",t.remotePeer),await o.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:{[sa]: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 s of this.components.addressManager.getAddresses())s.toString().includes("/p2p-circuit")||n.push(s.bytes);let o=await Qr.seal(new Do({peer:e,relay:this.components.peerId,expiration:t}),this.components.privateKey);return{addrs:n,expire:t,voucher:{publicKey:$e(o.publicKey),payloadType:o.payloadType,payload:{peer:e.toMultihash().bytes,relay:this.components.peerId.toMultihash().bytes,expiration:t},signature:o.signature}}}async handleConnect({stream:e,request:t,connection:n},o){let s=e.pb(Y);if(zt.matches(n.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",n.remotePeer),await s.write({type:Y.Type.STATUS,status:H.PERMISSION_DENIED},o);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(Oe),i=mr(ze(t.peer.id))}catch(f){this.log.error("invalid hop connect request via peer %p %s",n.remotePeer,f),await s.write({type:Y.Type.STATUS,status:H.MALFORMED_MESSAGE},o);return}let a=this.reservationStore.get(i);if(a==null){this.log.error("hop connect denied for destination peer %p not having a reservation for %p with status %s",i,n.remotePeer,H.NO_RESERVATION),await s.write({type:Y.Type.STATUS,status:H.NO_RESERVATION},o);return}if(await this.components.connectionGater.denyOutboundRelayedConnection?.(n.remotePeer,i)===!0){this.log.error("hop connect for %p to %p denied by connection gater",n.remotePeer,i),await s.write({type:Y.Type.STATUS,status:H.PERMISSION_DENIED},o);return}let c=this.components.connectionManager.getConnections(i);if(c.length===0){this.log("hop connect denied for destination peer %p not having a connection for %p as there is no destination connection",i,n.remotePeer),await s.write({type:Y.Type.STATUS,status:H.NO_RESERVATION},o);return}let u=c[0],l=await this.stopHop({connection:u,request:{type:Pe.Type.CONNECT,peer:{id:n.remotePeer.toMultihash().bytes,addrs:[]},limit:a?.limit}},o);if(l==null){this.log.error("failed to open stream to destination peer %p",u?.remotePeer),await s.write({type:Y.Type.STATUS,status:H.CONNECTION_FAILED},o);return}await s.write({type:Y.Type.STATUS,status:H.OK,limit:a?.limit},o),this.log("connection from %p to %p established - merging streams",n.remotePeer,i),hl(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 o=await e.newStream($t,{maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0,...n}),s=Et(o),i=s.pb(Pe);await i.write(t,n);let a;try{a=await i.read(n)}catch{this.log.error("error parsing stop message response from %p",e.remotePeer)}if(a==null){this.log.error("could not read response from %p",e.remotePeer),await o.close(n);return}if(a.status===H.OK)return this.log("stop request to %p was successful",e.remotePeer),s.unwrap();this.log("stop request failed with code %d",a.status),await o.close(n)}get reservations(){return this.reservationStore.reservations}};var vt=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var Lo=class extends _e{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(Ue,{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(Ue)],orders:[()=>Math.random()<.5?1:-1,(n,o)=>{let s=pl(n),i=pl(o);return s>i?-1:i>s?1:0}]});for(let n of e)this.log.trace("found relay peer %p in peer store",n.id),this.safeDispatchEvent("relay:discover",{detail:n.id});this.log("found %d relay peers in peer store",e.length);let t=this.queue=new Sr({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(o=>o.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(o=>{this.log.error("error opening connection to random peer %p",n.id,o)})}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)}))}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(o=>{this.log.error("error opening connection to discovered peer %p",e.detail.id,o)})}async dialPeer({peerId:e,signal:t}){let n=ao([AbortSignal.timeout(5e3),t]);try{await this.components.connectionManager.openConnection(e,{signal:n})}finally{n.clear()}}};function pl(r){let e=r.metadata.get("last-dial-success");return e==null?0:new Date($(e)).getTime()}var da=class extends _e{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??yo,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(_o.exactMatch(e))this.log("searching for circuit relay servers"),this.reservationId=this.reservationStore.reserveRelay();else if(vo.exactMatch(e)){this.log("listen on specific relay server %a",e);let t=AbortSignal.timeout(this.listenTimeout);let n=e.decapsulate("/p2p-circuit"),o=await this.connectionManager.openConnection(n,{signal:t});if(!this.reservationStore.hasReservation(o.remotePeer)){this.log("making reservation on peer %p",o.remotePeer);let s=await this.reservationStore.addRelay(o.remotePeer,"configured");this.addedRelay(s)}}else throw new At(`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=>Oe(t).encapsulate("/p2p-circuit")),this.listeningAddrs.forEach(t=>{this.addressManager.confirmObservedAddr(t,{type:"transport"})}),queueMicrotask(()=>{this.safeDispatchEvent("listening")})}};function ml(r){return new da(r)}var yl="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var gl=(r=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)e+=yl[t[r]&63];return e};var ap=60*1e3*10,cp=60*1e3*5,up=30*1e3,Ro=class extends _e{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 St,this.pendingReservations=[],this.maxReservationQueueLength=t?.maxReservationQueueLength??sl,this.reservationCompletionTimeout=t?.reservationCompletionTimeout??yo,this.started=!1,this.relayFilter=wr(100),this.reserveQueue=new Sr({concurrency:t?.reservationConcurrency??ol,metricName:"libp2p_relay_reservation_queue",metrics:e.metrics}),this.events.addEventListener("connection:close",n=>{[...this.reservations.values()].find(s=>s.connection===n.detail.id)!=null&&this.#t(n.detail.remotePeer).catch(s=>{this.log("could not remove relay %p - %e",n.detail,s)})})}isStarted(){return this.started}start(){this.started=!0}afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>t.tags.has(nn)]});this.log("removing tag from %d old relays",e.length),await Promise.all(e.map(async t=>{await this.peerStore.merge(t.id,{tags:{[nn]: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(e)})}stop(){this.reserveQueue.clear(),this.reservations.forEach(({timeout:e})=>{clearTimeout(e)}),this.reservations.clear(),this.started=!1}reserveRelay(){let e=gl();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 At("Cannot use self as relay");if(this.reserveQueue.size>this.maxReservationQueueLength)throw new So("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 At("The relay was previously invalid");return this.log.trace("try to reserve relay slot with %p",e),this.reserveQueue.add(async()=>{let o=Date.now();try{let s=this.reservations.get(e);if(s!=null){let h=this.connectionManager.getConnections(e),v=!1;if(h.length===0&&this.log("already have relay reservation with %p but we are no longer connected",e),h.map(x=>x.id).includes(s.connection)&&(this.log("already have relay reservation with %p and the original connection is still open",e),v=!0),v&&aa(s.reservation.expire)>ap)return this.log("already have relay reservation with %p but we are still connected and it does not expire soon",e),{relay:e,details:s};await this.#t(e)}if(t==="discovered"&&this.pendingReservations.length===0)throw new sn("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(zt.matches(a.remoteAddr))throw new Eo("not creating reservation over relayed connection");let c=await this.#e(a,{signal:i}),u=aa(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-cp,up),Math.pow(2,31)-1),f=setTimeout(()=>{this.log("refresh reservation to relay %p",e),this.addRelay(e,t).catch(async h=>{this.log.error("could not refresh reservation to relay %p - %e",e,h),await this.#t(e)}).catch(h=>{this.log.error("could not remove expired reservation to relay %p - %e",e,h)})},l),m;if(t==="discovered"){let h=this.pendingReservations.pop();if(h==null)throw new sn("Made reservation on relay but did not need any more discovered relays");m={timeout:f,reservation:c,type:t,connection:a.id,id:h}}else m={timeout:f,reservation:c,type:t,connection:a.id};this.reservations.set(e,m),await this.peerStore.merge(e,{tags:{[nn]:{value:1,ttl:u}}}),this.#r();let d={relay:e,details:m};return this.safeDispatchEvent("relay:created-reservation",{detail:d}),d}catch(s){throw t==="discovered"&&s.name==="HadEnoughRelaysError"||this.log.error("could not reserve slot on %p after %dms - %e",e,Date.now()-o,s),(s.name==="DialError"||s.name==="UnsupportedProtocolError")&&this.relayFilter.add(e.toMultihash().bytes),this.#t(e).catch(i=>{this.log.error("could not remove reservation on %p after reserving slot failed - %e",e,i)}),s}},{peerId:e})}hasReservation(e){return this.reservations.has(e)}getReservation(e){return this.reservations.get(e)?.reservation}reservationCount(e){return e==null?this.reservations.size:[...this.reservations.values()].reduce((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(Ue,t),s=Et(n).pb(Y);this.log.trace("send RESERVE to %p",e.remotePeer),await s.write({type:Y.Type.RESERVE},t);let i;try{this.log.trace("reading response from %p",e.remotePeer),i=await s.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===H.OK&&i.reservation!=null){let c=new Set;c.add(e.remoteAddr.toString());for(let u of i.reservation.addrs){let l=Oe(u);l.getComponents().find(f=>f.code===421)==null&&(l=l.encapsulate(`/p2p/${e.remotePeer}`)),l=Oe(l.toString().replace(`/p2p/${e.remotePeer}/p2p/${e.remotePeer}`,`/p2p/${e.remotePeer}`)),c.add(l.toString())}return i.reservation.addrs=[...c].map(u=>Oe(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:{[nn]: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=wr(100),this.log("not discovered enough relays %d/%d",this.reservations.size,this.pendingReservations.length),this.safeDispatchEvent("relay:not-enough-relays")}};var pa=class extends io{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 ma(r){return new pa(r)}var lp=r=>{if(r.peer==null)return!1;try{r.peer.addrs.forEach(Oe)}catch{return!1}return!0},bl={maxInboundStopStreams:on,maxOutboundStopStreams:on,stopTimeout:3e4},Bo=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??bl.maxInboundStopStreams,this.maxOutboundStopStreams=t.maxOutboundStopStreams??bl.maxOutboundStopStreams,this.shutdownController=new AbortController,this.discovery=new Lo(e,{filter:t.discoveryFilter??ca(ul,ll)}),this.discovery.addEventListener("relay:discover",n=>{this.reservationStore.addRelay(n.detail,"discovered").catch(o=>{o.name!=="HadEnoughRelaysError"&&o.name!=="RelayQueueFullError"&&this.log.error("could not add discovered relay %p",n.detail,o)})}),this.reservationStore=new Ro(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";[_a]=["@libp2p/transport","@libp2p/circuit-relay-v2-transport"];get[Aa](){return this.discovery!=null?["@libp2p/identify"]:[]}[va]=!0;isStarted(){return this.started}async start(){this.shutdownController=new AbortController,this.shutdownController.signal,await this.components.registrar.handle($t,this.onStop,{maxInboundStreams:this.maxInboundStopStreams,maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0}),await wa(this.discovery,this.reservationStore),this.started=!0}async stop(){this.shutdownController.abort(),await Ea(this.discovery,this.reservationStore),await this.components.registrar.unhandle($t),this.started=!1}async dial(e,t){let n=e.toString().split("/p2p-circuit"),o=Oe(n[0]),s=Oe(n[n.length-1]),i=o.getComponents().find(d=>d.code===421)?.value,a=s.getComponents().find(d=>d.code===421)?.value;if(i==null||a==null){let d=`ircuit relay dial to ${e.toString()} failed as address did not have both relay and destination PeerIDs`;throw this.log.error(`c${d}`),new dn(`C${d}`)}let c=mi(i),u=mi(a),f=this.components.connectionManager.getConnections(c)[0];f==null?(await this.components.peerStore.merge(c,{multiaddrs:[o]}),t.onProgress?.(new vt("circuit-relay:open-connection")),f=await this.components.connectionManager.openConnection(c,t)):t.onProgress?.(new vt("circuit-relay:reuse-connection"));let m;try{t.onProgress?.(new vt("circuit-relay:open-hop-stream")),m=await f.newStream(Ue,t);let d=Et(m).pb(Y);t.onProgress?.(new vt("circuit-relay:write-connect-message")),await d.write({type:Y.Type.CONNECT,peer:{id:u.toMultihash().bytes,addrs:[Oe(s).bytes]}},t),t.onProgress?.(new vt("circuit-relay:read-connect-response"));let h=await d.read(t);if(h.status!==H.OK)throw new hn(`failed to connect via relay with status ${h?.status?.toString()??"undefined"}`);let v=new an(h.limit),x=ma({stream:d.unwrap().unwrap(),remoteAddr:e,localAddr:o.encapsulate(`/p2p-circuit/p2p/${this.components.peerId.toString()}`),onDataRead:v.onData,onDataWrite:v.onData,log:m.log.newScope("circuit-relay:connection")}),y=await this.components.upgrader.upgradeOutbound(x,{...t,limits:v.getLimits()});return y.log("outbound relayed connection established to %p with limits %o, over connection %s",y.remotePeer,h.limit??"none",f.id),y}catch(d){throw this.log.error("circuit relay dial to destination %p via relay %p failed",u,c,d),m?.abort(d),d}}createListener(e){return ml({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=>vo.exactMatch(t)||_o.exactMatch(t))}dialFilter(e){return e=Array.isArray(e)?e:[e],e.filter(t=>zt.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",f)}let o=Et(e).pb(Pe),s=await o.read({signal:n});if(this.log("new circuit relay v2 stop stream from %p with type %s",t.remotePeer,s.type),s?.type===void 0){this.log.error("type was missing from circuit v2 stop protocol request from %s",t.remotePeer),await o.write({type:Pe.Type.STATUS,status:H.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}if(s.type!==Pe.Type.CONNECT){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await o.write({type:Pe.Type.STATUS,status:H.UNEXPECTED_MESSAGE},{signal:n}),await e.close({signal:n});return}if(!lp(s)){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await o.write({type:Pe.Type.STATUS,status:H.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}let i=mr(ze(s.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 o.write({type:Pe.Type.STATUS,status:H.PERMISSION_DENIED},{signal:n}),await e.close({signal:n});return}this.log.trace("sending success response to %p",t.remotePeer),await o.write({type:Pe.Type.STATUS,status:H.OK},{signal:n});let a=new an(s.limit),c=t.remoteAddr.encapsulate(`/p2p-circuit/p2p/${i.toString()}`),u=this.components.addressManager.getAddresses()[0],l=ma({stream:o.unwrap().unwrap(),remoteAddr:c,localAddr:u,onDataRead:a.onData,onDataWrite:a.onData,log:e.log.newScope("circuit-relay:connection")});await this.components.upgrader.upgradeInbound(l,{limits:a.getLimits(),signal:n}),l.log("inbound relayed connection established to %p with limits %o, over connection %s",i,s.limit??"none",t.id)}finally{n?.clear()}}};function fp(r={}){return e=>new Co(e,r)}function hp(r={}){return e=>new Bo(e,r)}return vl(dp);})();
3
3
  /*! Bundled license information:
4
4
 
5
- @noble/hashes/esm/utils.js:
5
+ @noble/hashes/utils.js:
6
6
  (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
7
7
 
8
- @noble/curves/esm/utils.js:
9
- @noble/curves/esm/abstract/modular.js:
10
- @noble/curves/esm/abstract/curve.js:
11
- @noble/curves/esm/abstract/edwards.js:
12
- @noble/curves/esm/ed25519.js:
13
- @noble/curves/esm/abstract/weierstrass.js:
14
- @noble/curves/esm/_shortw_utils.js:
15
- @noble/curves/esm/secp256k1.js:
8
+ @noble/curves/utils.js:
9
+ @noble/curves/abstract/modular.js:
10
+ @noble/curves/abstract/curve.js:
11
+ @noble/curves/abstract/edwards.js:
12
+ @noble/curves/ed25519.js:
13
+ @noble/curves/abstract/weierstrass.js:
14
+ @noble/curves/secp256k1.js:
16
15
  (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
17
16
  */
18
17
  return Libp2PCircuitRelayV2}));