@libp2p/circuit-relay-v2 4.1.7 → 4.2.0-2151144c3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.min.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
(function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Libp2PCircuitRelayV2 = factory()}(typeof self !== 'undefined' ? self : this, function () {
|
|
2
|
-
"use strict";var Libp2PCircuitRelayV2=(()=>{var No=Object.defineProperty;var gl=Object.getOwnPropertyDescriptor;var bl=Object.getOwnPropertyNames;var wl=Object.prototype.hasOwnProperty;var ve=(r,e)=>{for(var t in e)No(r,t,{get:e[t],enumerable:!0})},xl=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of bl(e))!wl.call(r,s)&&s!==t&&No(r,s,{get:()=>e[s],enumerable:!(n=gl(e,s))||n.enumerable});return r};var El=r=>xl(No({},"__esModule",{value:!0}),r);var fp={};ve(fp,{RELAY_V2_HOP_CODEC:()=>ke,RELAY_V2_STOP_CODEC:()=>Xt,circuitRelayServer:()=>up,circuitRelayTransport:()=>lp});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 s=this.#e.get(e);s==null&&(s=[],this.#e.set(e,s)),s.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let s=this.#e.get(e);s!=null&&(s=s.filter(({callback:o})=>o!==t),this.#e.set(e,s))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:s})=>!s),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 ae=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Qt=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var hn=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}};var ft=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},Dr=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}};var pn=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},mn=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var yn=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var gn=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}},Ct=class extends Error{static name="ListenError";constructor(e="Listen error"){super(e),this.name="ListenError"}};var Jt=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var bn=class extends Event{data;constructor(e,t){super("message",t),this.data=e}},er=class extends Event{error;local;constructor(e,t,n){super("close",n),this.error=t,this.local=e}},wn=class extends er{constructor(e,t){super(!0,e,t)}},xn=class extends er{constructor(e,t){super(!1,e,t)}};var Uo=Symbol.for("@libp2p/peer-id");var ba="keep-alive";function wa(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function xa(...r){let e=[];for(let t of r)wa(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)wa(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 Vo={};ve(Vo,{base58btc:()=>te,base58flickr:()=>Dl});var $p=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 Qe(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 Sl(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 s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function f(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var v=0,w=0,y=0,A=d.length;y!==A&&d[y]===0;)y++,v++;for(var x=(A-y)*u+1>>>0,T=new Uint8Array(x);y!==A;){for(var P=d[y],M=0,V=x-1;(P!==0||M<w)&&V!==-1;V--,M++)P+=256*T[V]>>>0,T[V]=P%a>>>0,P=P/a>>>0;if(P!==0)throw new Error("Non-zero carry");w=M,y++}for(var S=x-w;S!==x&&T[S]===0;)S++;for(var E=c.repeat(v);S<x;++S)E+=r.charAt(T[S]);return E}function h(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var v=0;if(d[v]!==" "){for(var w=0,y=0;d[v]===c;)w++,v++;for(var A=(d.length-v)*l+1>>>0,x=new Uint8Array(A);d[v];){var T=t[d.charCodeAt(v)];if(T===255)return;for(var P=0,M=A-1;(T!==0||P<y)&&M!==-1;M--,P++)T+=a*x[M]>>>0,x[M]=T%256>>>0,T=T/256>>>0;if(T!==0)throw new Error("Non-zero carry");y=P,v++}if(d[v]!==" "){for(var V=A-y;V!==A&&x[V]===0;)V++;for(var S=new Uint8Array(w+(A-V)),E=w;V!==A;)S[E++]=x[V++];return S}}}function p(d){var v=h(d);if(v)return v;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:h,decode:p}}var vl=Sl,_l=vl,La=_l;var ko=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")}},Mo=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Ra(this,e)}},Ko=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 Ko({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var qo=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new ko(e,t,n),this.decoder=new Mo(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function tr({name:r,prefix:e,encode:t,decode:n}){return new qo(r,e,t,n)}function dt({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=La(t,r);return tr({prefix:e,name:r,encode:n,decode:o=>Qe(s(o))})}function Al(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function Tl(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function Il(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function ce({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=Il(n);return tr({prefix:e,name:r,encode(o){return Tl(o,n,t)},decode(o){return Al(o,s,t,r)}})}var te=dt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Dl=dt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Fo={};ve(Fo,{base32:()=>ht,base32hex:()=>Bl,base32hexpad:()=>Pl,base32hexpadupper:()=>Nl,base32hexupper:()=>Ol,base32pad:()=>Ll,base32padupper:()=>Rl,base32upper:()=>Cl,base32z:()=>Ul});var ht=ce({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Cl=ce({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Ll=ce({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Rl=ce({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Bl=ce({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Ol=ce({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Pl=ce({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Nl=ce({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Ul=ce({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Ho={};ve(Ho,{base36:()=>Cr,base36upper:()=>kl});var Cr=dt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),kl=dt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Ml=Pa,Ba=128,Kl=127,ql=~Kl,Vl=Math.pow(2,31);function Pa(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Vl;)e[t++]=r&255|Ba,r/=128;for(;r&ql;)e[t++]=r&255|Ba,r>>>=7;return e[t]=r|0,Pa.bytes=t-n+1,e}var Fl=zo,Hl=128,Oa=127;function zo(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw zo.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&Oa)<<s:(i&Oa)*Math.pow(2,s),s+=7}while(i>=Hl);return zo.bytes=o-n,t}var zl=Math.pow(2,7),$l=Math.pow(2,14),Wl=Math.pow(2,21),Gl=Math.pow(2,28),Yl=Math.pow(2,35),Zl=Math.pow(2,42),Xl=Math.pow(2,49),jl=Math.pow(2,56),Ql=Math.pow(2,63),Jl=function(r){return r<zl?1:r<$l?2:r<Wl?3:r<Gl?4:r<Yl?5:r<Zl?6:r<Xl?7:r<jl?8:r<Ql?9:10},ef={encode:Ml,decode:Fl,encodingLength:Jl},tf=ef,Lr=tf;function Rr(r,e=0){return[Lr.decode(r,e),Lr.decode.bytes]}function rr(r,e,t=0){return Lr.encode(r,e,t),e}function nr(r){return Lr.encodingLength(r)}function ze(r,e){let t=e.byteLength,n=nr(r),s=n+nr(t),o=new Uint8Array(s+t);return rr(r,o,0),rr(t,o,n),o.set(e,s),new or(r,t,e,o)}function $e(r){let e=Qe(r),[t,n]=Rr(e),[s,o]=Rr(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new or(t,s,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 or=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};function Ua(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return nf(t,$o(r),e??te.encoder);default:return of(t,$o(r),e??ht.encoder)}}var ka=new WeakMap;function $o(r){let e=ka.get(r);if(e==null){let t=new Map;return ka.set(r,t),t}return e}var le=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}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!==Br)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==sf)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=ze(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&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:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??Ma(n,s,o.bytes))}else if(t[af]===!0){let{version:n,multihash:s,code:o}=t,i=$e(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Br)throw new Error(`Version 0 CID must use dag-pb (code: ${Br}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=Ma(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Br,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=Qe(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new or(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,h]=Rr(e.subarray(t));return t+=h,f},s=n(),o=Br;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,s]=rf(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return $o(o).set(n,e),o}};function rf(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 ht.prefix:{let t=e??ht;return[ht.prefix,t.decode(r)]}case Cr.prefix:{let t=e??Cr;return[Cr.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 nf(r,e,t){let{prefix:n}=t;if(n!==te.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function of(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}var Br=112,sf=18;function Ma(r,e,t){let n=nr(r),s=n+nr(e),o=new Uint8Array(s+t.byteLength);return rr(r,o,0),rr(e,o,n),o.set(t,s),o}var af=Symbol.for("@ipld/js-cid/CID");var Wo={};ve(Wo,{identity:()=>Me});var Ka=0,cf="identity",qa=Qe;function uf(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return ze(Ka,qa(r))}var Me={code:Ka,name:cf,encode:qa,digest:uf};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 et(r,e){e==null&&(e=r.reduce((s,o)=>s+o.length,0));let t=Ae(e),n=0;for(let s of r)t.set(s,n),n+=s.length;return t}var Fa=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 s=t+n.byteLength;if(e<s)return{buf:n,index:e-t};t=s}throw new RangeError("index is out of bounds")}function Sn(r){return!!r?.[Fa]}var J=class r{bufs;length;[Fa]=!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(Sn(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(Sn(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(Sn(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:s}=this._subList(e,t);return et(n,s)}subarray(e,t){let{bufs:n,length:s}=this._subList(e,t);return n.length===1?n[0]:et(n,s)}sublist(e,t){let{bufs:n,length:s}=this._subList(e,t),o=new r;return o.length=s,o.bufs=[...n],o}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let n=[],s=0;for(let o=0;o<this.bufs.length;o++){let i=this.bufs[o],a=s,c=a+i.byteLength;if(s=c,e>=c)continue;let l=e>=a&&e<c,u=t>a&&t<=c;if(l&&u){if(e===a&&t===c){n.push(i);break}let f=e-a;n.push(i.subarray(f,f+(t-e)));break}if(l){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(u){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(!Sn(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let s=n.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let o=256,i=new Int32Array(o);for(let f=0;f<o;f++)i[f]=-1;for(let f=0;f<s;f++)i[n[f]]=f;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let f=t;f<=c;f+=u){u=0;for(let h=l;h>=0;h--){let p=this.get(f+h);if(n[h]!==p){u=Math.max(1,h-a[p]);break}}if(u===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 s=re(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,t,n),this.write(s,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let s=re(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,t,n),this.write(s,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let s=re(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,t,n),this.write(s,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=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 s=re(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,t,n),this.write(s,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let s=re(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,t,n),this.write(s,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let s=re(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,t,n),this.write(s,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let s=re(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,t,n),this.write(s,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let s=re(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,t,n),this.write(s,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!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((s,o)=>s+o.byteLength,0)),n.length=t,n}};var Go={};ve(Go,{base10:()=>lf});var lf=dt({prefix:"9",name:"base10",alphabet:"0123456789"});var Yo={};ve(Yo,{base16:()=>ff,base16upper:()=>df});var ff=ce({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),df=ce({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Zo={};ve(Zo,{base2:()=>hf});var hf=ce({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Xo={};ve(Xo,{base256emoji:()=>bf});var Ha=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}"),pf=Ha.reduce((r,e,t)=>(r[t]=e,r),[]),mf=Ha.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function yf(r){return r.reduce((e,t)=>(e+=pf[t],e),"")}function gf(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let s=mf[n];if(s==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}var bf=tr({prefix:"\u{1F680}",name:"base256emoji",encode:yf,decode:gf});var Qo={};ve(Qo,{base64:()=>wf,base64pad:()=>xf,base64url:()=>jo,base64urlpad:()=>Ef});var wf=ce({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),xf=ce({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),jo=ce({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Ef=ce({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Jo={};ve(Jo,{base8:()=>Sf});var Sf=ce({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var es={};ve(es,{identity:()=>vf});var vf=tr({prefix:"\0",name:"identity",encode:r=>Da(r),decode:r=>Ia(r)});var Dm=new TextEncoder,Cm=new TextDecoder;var ns={};ve(ns,{sha256:()=>sr,sha512:()=>If});var Tf=20;function rs({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new ts(r,e,t,n,s)}var ts=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??Tf,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?za(n,this.code,t?.truncate):n.then(s=>za(s,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 ze(e,r)}function Wa(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var sr=rs({name:"sha2-256",code:18,encode:Wa("SHA-256")}),If=rs({name:"sha2-512",code:19,encode:Wa("SHA-512")});var Or={...es,...Zo,...Jo,...Go,...Yo,...Fo,...Ho,...Vo,...Qo,...Xo},Vm={...ns,...Wo};function Ya(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Ga=Ya("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),os=Ya("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}),Df={utf8:Ga,"utf-8":Ga,hex:Or.base16,latin1:os,ascii:os,binary:os,...Or},vn=Df;function K(r,e="utf8"){let t=vn[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function $(r,e="utf8"){let t=vn[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var Cf=parseInt("11111",2),ss=parseInt("10000000",2),Lf=parseInt("01111111",2),Za={0:Pr,1:Pr,2:Rf,3:Pf,4:Nf,5:Of,6:Bf,16:Pr,22:Pr,48:Pr};function tt(r,e={offset:0}){let t=r[e.offset]&Cf;if(e.offset++,Za[t]!=null)return Za[t](r,e);throw new Error("No decoder for tag "+t)}function Nr(r,e){let t=0;if((r[e.offset]&ss)===ss){let n=r[e.offset]&Lf,s="0x";e.offset++;for(let o=0;o<n;o++,e.offset++)s+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(s,16)}else t=r[e.offset],e.offset++;return t}function Pr(r,e){Nr(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=tt(r,e);if(n===null)break;t.push(n)}return t}function Rf(r,e){let t=Nr(r,e),n=e.offset,s=e.offset+t,o=[];for(let i=n;i<s;i++)i===n&&r[i]===0||o.push(r[i]);return e.offset+=t,Uint8Array.from(o)}function Bf(r,e){let t=Nr(r,e),n=e.offset+t,s=r[e.offset];e.offset++;let o=0,i=0;s<40?(o=0,i=s):s<80?(o=1,i=s-40):(o=2,i=s-80);let a=`${o}.${i}`,c=[];for(;e.offset<n;){let l=r[e.offset];if(e.offset++,c.push(l&127),l<128){c.reverse();let u=0;for(let f=0;f<c.length;f++)u+=c[f]<<f*7;a+=`.${u}`,c=[]}}return a}function Of(r,e){return e.offset++,null}function Pf(r,e){let t=Nr(r,e),n=r[e.offset];e.offset++;let s=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return s}function Nf(r,e){let t=Nr(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function Uf(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 is(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=Uf(r.byteLength);return new J(Uint8Array.from([e.byteLength|ss]),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]),is(e),e)}function _n(r){let e=Uint8Array.from([0]),t=new J(e,r);return new J(Uint8Array.from([3]),is(t),t)}function pt(r,e=48){let t=new J;for(let n of r)t.append(n);return new J(Uint8Array.from([e]),is(t),t)}async function Xa(r,e,t,n){let s=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let o=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},s,e,t.subarray());return n?.signal?.throwIfAborted(),o}var kf=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Mf=Uint8Array.from([6,5,43,129,4,0,34]),Kf=Uint8Array.from([6,5,43,129,4,0,35]),qf={ext:!0,kty:"EC",crv:"P-256"},Vf={ext:!0,kty:"EC",crv:"P-384"},Ff={ext:!0,kty:"EC",crv:"P-521"},as=32,cs=48,us=66;function ls(r){let e=tt(r);return ja(e)}function ja(r){let e=r[1][1][0],t=1,n,s;if(e.byteLength===as*2+1)return n=$(e.subarray(t,t+as),"base64url"),s=$(e.subarray(t+as),"base64url"),new ir({...qf,key_ops:["verify"],x:n,y:s});if(e.byteLength===cs*2+1)return n=$(e.subarray(t,t+cs),"base64url"),s=$(e.subarray(t+cs),"base64url"),new ir({...Vf,key_ops:["verify"],x:n,y:s});if(e.byteLength===us*2+1)return n=$(e.subarray(t,t+us),"base64url"),s=$(e.subarray(t+us),"base64url"),new ir({...Ff,key_ops:["verify"],x:n,y:s});throw new ae(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function Qa(r){return pt([Te(Uint8Array.from([1])),pt([Hf(r.crv)],160),pt([_n(new J(Uint8Array.from([4]),K(r.x??"","base64url"),K(r.y??"","base64url")))],161)]).subarray()}function Hf(r){if(r==="P-256")return kf;if(r==="P-384")return Mf;if(r==="P-521")return Kf;throw new ae(`Invalid curve ${r}`)}var ir=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(We(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 Lt(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 k(r,e,t=""){let n=Lt(r),s=r?.length,o=e!==void 0;if(!n||o&&s!==e){let i=t&&`"${t}" `,a=o?` of length ${e}`:"",c=n?`length=${s}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function An(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 ar(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){k(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 nt(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function Tn(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",zf=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function ot(r){if(k(r),tc)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=zf[r[t]];return e}var rt={_0:48,_9:57,A:65,F:70,a:97,f:102};function Ja(r){if(r>=rt._0&&r<=rt._9)return r-rt._0;if(r>=rt.A&&r<=rt.F)return r-(rt.A-10);if(r>=rt.a&&r<=rt.f)return r-(rt.a-10)}function st(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 s=0,o=0;s<t;s++,o+=2){let i=Ja(r.charCodeAt(o)),a=Ja(r.charCodeAt(o+1));if(i===void 0||a===void 0){let c=r[o]+r[o+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+o)}n[s]=i*16+a}return n}function Ie(...r){let e=0;for(let n=0;n<r.length;n++){let s=r[n];k(s),e+=s.length}let t=new Uint8Array(e);for(let n=0,s=0;n<r.length;n++){let o=r[n];t.set(o,s),s+=o.length}return t}function fs(r,e={}){let t=(s,o)=>r(o).update(s).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=s=>r(s),Object.assign(t,e),Object.freeze(t)}function cr(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 ds=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 Ur=class{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,s){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(e),this.view=Tn(this.buffer)}update(e){ar(this),k(e);let{view:t,buffer:n,blockLen:s}=this,o=e.length;for(let i=0;i<o;){let a=Math.min(s-this.pos,o-i);if(a===s){let c=Tn(e);for(;s<=o-i;i+=s)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){ar(this),ec(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:s,isLE:o}=this,{pos:i}=this;t[i++]=128,nt(this.buffer.subarray(i)),this.padOffset>s-i&&(this.process(n,0),i=0);for(let f=i;f<s;f++)t[f]=0;n.setBigUint64(s-8,BigInt(this.length*8),o),this.process(n,0);let a=Tn(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<l;f++)a.setUint32(4*f,u[f],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:s,finished:o,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=o,e.length=s,e.pos=a,s%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},it=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 In=BigInt(4294967295),oc=BigInt(32);function $f(r,e=!1){return e?{h:Number(r&In),l:Number(r>>oc&In)}:{h:Number(r>>oc&In)|0,l:Number(r&In)|0}}function sc(r,e=!1){let t=r.length,n=new Uint32Array(t),s=new Uint32Array(t);for(let o=0;o<t;o++){let{h:i,l:a}=$f(r[o],e);[n[o],s[o]]=[i,a]}return[n,s]}var hs=(r,e,t)=>r>>>t,ps=(r,e,t)=>r<<32-t|e>>>t,Rt=(r,e,t)=>r>>>t|e<<32-t,Bt=(r,e,t)=>r<<32-t|e>>>t,kr=(r,e,t)=>r<<64-t|e>>>t-32,Mr=(r,e,t)=>r>>>t-32|e<<64-t;function Ye(r,e,t,n){let s=(e>>>0)+(n>>>0);return{h:r+t+(s/2**32|0)|0,l:s|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,s)=>e+t+n+s+(r/2**32|0)|0,lc=(r,e,t,n,s)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(s>>>0),fc=(r,e,t,n,s,o)=>e+t+n+s+o+(r/2**32|0)|0;var Gf=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]),mt=new Uint32Array(64),ms=class extends Ur{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:s,E:o,F:i,G:a,H:c}=this;return[e,t,n,s,o,i,a,c]}set(e,t,n,s,o,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=s|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let f=0;f<16;f++,t+=4)mt[f]=e.getUint32(t,!1);for(let f=16;f<64;f++){let h=mt[f-15],p=mt[f-2],d=Ke(h,7)^Ke(h,18)^h>>>3,v=Ke(p,17)^Ke(p,19)^p>>>10;mt[f]=v+mt[f-7]+d+mt[f-16]|0}let{A:n,B:s,C:o,D:i,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){let h=Ke(a,6)^Ke(a,11)^Ke(a,25),p=u+h+rc(a,c,l)+Gf[f]+mt[f]|0,v=(Ke(n,2)^Ke(n,13)^Ke(n,22))+nc(n,s,o)|0;u=l,l=c,c=a,a=i+p|0,i=o,o=s,s=n,n=p+v|0}n=n+this.A|0,s=s+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,s,o,i,a,c,l,u)}roundClean(){nt(mt)}destroy(){this.set(0,0,0,0,0,0,0,0),nt(this.buffer)}},ys=class extends ms{A=it[0]|0;B=it[1]|0;C=it[2]|0;D=it[3]|0;E=it[4]|0;F=it[5]|0;G=it[6]|0;H=it[7]|0;constructor(){super(32)}};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))),Yf=dc[0],Zf=dc[1],yt=new Uint32Array(80),gt=new Uint32Array(80),gs=class extends Ur{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:n,Bl:s,Ch:o,Cl:i,Dh:a,Dl:c,Eh:l,El:u,Fh:f,Fl:h,Gh:p,Gl:d,Hh:v,Hl:w}=this;return[e,t,n,s,o,i,a,c,l,u,f,h,p,d,v,w]}set(e,t,n,s,o,i,a,c,l,u,f,h,p,d,v,w){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=s|0,this.Ch=o|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=f|0,this.Fl=h|0,this.Gh=p|0,this.Gl=d|0,this.Hh=v|0,this.Hl=w|0}process(e,t){for(let x=0;x<16;x++,t+=4)yt[x]=e.getUint32(t),gt[x]=e.getUint32(t+=4);for(let x=16;x<80;x++){let T=yt[x-15]|0,P=gt[x-15]|0,M=Rt(T,P,1)^Rt(T,P,8)^hs(T,P,7),V=Bt(T,P,1)^Bt(T,P,8)^ps(T,P,7),S=yt[x-2]|0,E=gt[x-2]|0,N=Rt(S,E,19)^kr(S,E,61)^hs(S,E,6),F=Bt(S,E,19)^Mr(S,E,61)^ps(S,E,6),L=cc(V,F,gt[x-7],gt[x-16]),g=uc(L,M,N,yt[x-7],yt[x-16]);yt[x]=g|0,gt[x]=L|0}let{Ah:n,Al:s,Bh:o,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:f,El:h,Fh:p,Fl:d,Gh:v,Gl:w,Hh:y,Hl:A}=this;for(let x=0;x<80;x++){let T=Rt(f,h,14)^Rt(f,h,18)^kr(f,h,41),P=Bt(f,h,14)^Bt(f,h,18)^Mr(f,h,41),M=f&p^~f&v,V=h&d^~h&w,S=lc(A,P,V,Zf[x],gt[x]),E=fc(S,y,T,M,Yf[x],yt[x]),N=S|0,F=Rt(n,s,28)^kr(n,s,34)^kr(n,s,39),L=Bt(n,s,28)^Mr(n,s,34)^Mr(n,s,39),g=n&o^n&a^o&a,b=s&i^s&c^i&c;y=v|0,A=w|0,v=p|0,w=d|0,p=f|0,d=h|0,{h:f,l:h}=Ye(l|0,u|0,E|0,N|0),l=a|0,u=c|0,a=o|0,c=i|0,o=n|0,i=s|0;let m=ic(N,L,b);n=ac(m,E,F,g),s=m|0}({h:n,l:s}=Ye(this.Ah|0,this.Al|0,n|0,s|0)),{h:o,l:i}=Ye(this.Bh|0,this.Bl|0,o|0,i|0),{h:a,l:c}=Ye(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=Ye(this.Dh|0,this.Dl|0,l|0,u|0),{h:f,l:h}=Ye(this.Eh|0,this.El|0,f|0,h|0),{h:p,l:d}=Ye(this.Fh|0,this.Fl|0,p|0,d|0),{h:v,l:w}=Ye(this.Gh|0,this.Gl|0,v|0,w|0),{h:y,l:A}=Ye(this.Hh|0,this.Hl|0,y|0,A|0),this.set(n,s,o,i,a,c,l,u,f,h,p,d,v,w,y,A)}roundClean(){nt(yt,gt)}destroy(){nt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},bs=class extends gs{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 ur=fs(()=>new ys,ds(1));var hc=fs(()=>new bs,ds(3));var xs=BigInt(0),ws=BigInt(1);function at(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(!Dn(r))throw new Error("positive bigint expected, got "+r)}else Ge(r);return r}function Kr(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===""?xs:BigInt("0x"+r)}function lr(r){return mc(ot(r))}function Ot(r){return mc(ot(Ln(k(r)).reverse()))}function Cn(r,e){Ge(e),r=pc(r);let t=st(r.toString(16).padStart(e*2,"0"));if(t.length!==e)throw new Error("number too large");return t}function Es(r,e){return Cn(r,e).reverse()}function Ln(r){return Uint8Array.from(r)}var Dn=r=>typeof r=="bigint"&&xs<=r;function Xf(r,e,t){return Dn(r)&&Dn(e)&&Dn(t)&&e<=r&&r<t}function qr(r,e,t,n){if(!Xf(e,t,n))throw new Error("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function Ss(r){let e;for(e=0;r>xs;r>>=ws,e+=1);return e}var Vr=r=>(ws<<BigInt(r))-ws;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=w=>new Uint8Array(w),s=Uint8Array.of(),o=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(r),l=n(r),u=0,f=()=>{c.fill(1),l.fill(0),u=0},h=(...w)=>t(l,Ie(c,...w)),p=(w=s)=>{l=h(o,w),c=h(),w.length!==0&&(l=h(i,w),c=h())},d=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let w=0,y=[];for(;w<e;){c=h();let A=c.slice();y.push(A),w+=c.length}return Ie(...y)};return(w,y)=>{f(),p(w);let A;for(;!(A=y(d()));)p();return f(),A}}function bt(r,e={},t={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function n(o,i,a){let c=r[o];if(a&&c===void 0)return;let l=typeof c;if(l!==i||c===null)throw new Error(`param "${o}" is invalid: expected ${i}, got ${l}`)}let s=(o,i)=>Object.entries(o).forEach(([a,c])=>n(a,c,i));s(e,!1),s(t,!0)}function fr(r){let e=new WeakMap;return(t,...n)=>{let s=e.get(t);if(s!==void 0)return s;let o=r(t,...n);return e.set(t,o),o}}var Se=BigInt(0),de=BigInt(1),Pt=BigInt(2),wc=BigInt(3),xc=BigInt(4),Ec=BigInt(5),jf=BigInt(7),Sc=BigInt(8),Qf=BigInt(9),vc=BigInt(16);function ue(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=ue(r,e),n=e,s=Se,o=de,i=de,a=Se;for(;t!==Se;){let l=n/t,u=n%t,f=s-i*l,h=o-a*l;n=t,t=u,s=i,o=a,i=f,a=h}if(n!==de)throw new Error("invert: does not exist");return ue(s,e)}function _s(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+de)/xc,n=r.pow(e,t);return _s(r,n,e),n}function Jf(r,e){let t=(r.ORDER-Ec)/Sc,n=r.mul(e,Pt),s=r.pow(n,t),o=r.mul(e,s),i=r.mul(r.mul(o,Pt),s),a=r.mul(o,r.sub(i,r.ONE));return _s(r,a,e),a}function ed(r){let e=dr(r),t=Ac(r),n=t(e,e.neg(e.ONE)),s=t(e,n),o=t(e,e.neg(n)),i=(r+jf)/vc;return(a,c)=>{let l=a.pow(c,i),u=a.mul(l,n),f=a.mul(l,s),h=a.mul(l,o),p=a.eql(a.sqr(u),c),d=a.eql(a.sqr(f),c);l=a.cmov(l,u,p),u=a.cmov(h,f,d);let v=a.eql(a.sqr(u),c),w=a.cmov(l,u,v);return _s(a,w,c),w}}function Ac(r){if(r<wc)throw new Error("sqrt is not defined for small field");let e=r-de,t=0;for(;e%Pt===Se;)e/=Pt,t++;let n=Pt,s=dr(r);for(;bc(s,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return _c;let o=s.pow(n,e),i=(e+de)/Pt;return function(c,l){if(c.is0(l))return l;if(bc(c,l)!==1)throw new Error("Cannot find square root");let u=t,f=c.mul(c.ONE,o),h=c.pow(l,e),p=c.pow(l,i);for(;!c.eql(h,c.ONE);){if(c.is0(h))return c.ZERO;let d=1,v=c.sqr(h);for(;!c.eql(v,c.ONE);)if(d++,v=c.sqr(v),d===u)throw new Error("Cannot find square root");let w=de<<BigInt(u-d-1),y=c.pow(f,w);u=d,f=c.sqr(y),h=c.mul(h,f),p=c.mul(p,y)}return p}}function td(r){return r%xc===wc?_c:r%Sc===Ec?Jf:r%vc===Qf?ed(r):Ac(r)}var Tc=(r,e)=>(ue(r,e)&de)===de,rd=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function As(r){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=rd.reduce((n,s)=>(n[s]="function",n),e);return bt(r,t),r}function nd(r,e,t){if(t<Se)throw new Error("invalid exponent, negatives unsupported");if(t===Se)return r.ONE;if(t===de)return e;let n=r.ONE,s=e;for(;t>Se;)t&de&&(n=r.mul(n,s)),s=r.sqr(s),t>>=de;return n}function Fr(r,e,t=!1){let n=new Array(e.length).fill(t?r.ZERO:void 0),s=e.reduce((i,a,c)=>r.is0(a)?i:(n[c]=i,r.mul(i,a)),r.ONE),o=r.inv(s);return e.reduceRight((i,a,c)=>r.is0(a)?i:(n[c]=r.mul(i,n[c]),r.mul(i,a)),o),n}function bc(r,e){let t=(r.ORDER-de)/Pt,n=r.pow(e,t),s=r.eql(n,r.ONE),o=r.eql(n,r.ZERO),i=r.eql(n,r.neg(r.ONE));if(!s&&!o&&!i)throw new Error("invalid Legendre symbol result");return s?1:o?0:-1}function od(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 vs=class{ORDER;BITS;BYTES;isLE;ZERO=Se;ONE=de;_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:s,nByteLength:o}=od(e,n);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=s,this.BYTES=o,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return ue(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&de)===de}neg(e){return ue(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return ue(e*e,this.ORDER)}add(e,t){return ue(e+t,this.ORDER)}sub(e,t){return ue(e-t,this.ORDER)}mul(e,t){return ue(e*t,this.ORDER)}pow(e,t){return nd(this,e,t)}div(e,t){return ue(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=td(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?Es(e,this.BYTES):Cn(e,this.BYTES)}fromBytes(e,t=!1){k(e);let{_lengths:n,BYTES:s,isLE:o,ORDER:i,_mod:a}=this;if(n){if(!n.includes(e.length)||e.length>s)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let l=new Uint8Array(s);l.set(e,o?0:l.length-e.length),e=l}if(e.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+e.length);let c=o?Ot(e):lr(e);if(a&&(c=ue(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Fr(this,e)}cmov(e,t,n){return n?t:e}};function dr(r,e={}){return new vs(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 Ts(r){let e=Ic(r);return e+Math.ceil(e/2)}function Is(r,e,t=!1){k(r);let n=r.length,s=Ic(e),o=Ts(e);if(n<16||n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);let i=t?Ot(r):lr(r),a=ue(i,e-de)+de;return t?Es(a,s):Cn(a,s)}var hr=BigInt(0),Nt=BigInt(1);function Hr(r,e){let t=e.negate();return r?t:e}function Ut(r,e){let t=Fr(r.Fp,e.map(n=>n.Z));return e.map((n,s)=>r.fromAffine(n.toAffine(t[s])))}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 Ds(r,e){Rc(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1),s=2**r,o=Vr(r),i=BigInt(r);return{windows:t,windowSize:n,mask:o,maxNumber:s,shiftBy:i}}function Dc(r,e,t){let{windowSize:n,mask:s,maxNumber:o,shiftBy:i}=t,a=Number(r&s),c=r>>i;a>n&&(a-=o,c+=Nt);let l=e*n,u=l+Math.abs(a)-1,f=a===0,h=a<0,p=e%2!==0;return{nextN:c,offset:u,isZero:f,isNeg:h,isNegF:p,offsetF:l}}var Cs=new WeakMap,Bc=new WeakMap;function Ls(r){return Bc.get(r)||1}function Cc(r){if(r!==hr)throw new Error("invalid wNAF")}var pr=class{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let s=e;for(;t>hr;)t&Nt&&(n=n.add(s)),s=s.double(),t>>=Nt;return n}precomputeWindow(e,t){let{windows:n,windowSize:s}=Ds(t,this.bits),o=[],i=e,a=i;for(let c=0;c<n;c++){a=i,o.push(a);for(let l=1;l<s;l++)a=a.add(i),o.push(a);i=a.double()}return o}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let s=this.ZERO,o=this.BASE,i=Ds(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:f,isNegF:h,offsetF:p}=Dc(n,a,i);n=c,u?o=o.add(Hr(h,t[p])):s=s.add(Hr(f,t[l]))}return Cc(n),{p:s,f:o}}wNAFUnsafe(e,t,n,s=this.ZERO){let o=Ds(e,this.bits);for(let i=0;i<o.windows&&n!==hr;i++){let{nextN:a,offset:c,isZero:l,isNeg:u}=Dc(n,i,o);if(n=a,!l){let f=t[c];s=s.add(u?f.negate():f)}}return Cc(n),s}getPrecomputes(e,t,n){let s=Cs.get(t);return s||(s=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(s=n(s)),Cs.set(t,s))),s}cached(e,t,n){let s=Ls(e);return this.wNAF(s,this.getPrecomputes(s,e,n),t)}unsafe(e,t,n,s){let o=Ls(e);return o===1?this._unsafeLadder(e,t,s):this.wNAFUnsafe(o,this.getPrecomputes(o,e,n),t,s)}createCache(e,t){Rc(t,this.bits),Bc.set(e,t),Cs.delete(e)}hasCache(e){return Ls(e)!==1}};function Oc(r,e,t,n){let s=e,o=r.ZERO,i=r.ZERO;for(;t>hr||n>hr;)t&Nt&&(o=o.add(s)),n&Nt&&(i=i.add(s)),s=s.double(),t>>=Nt,n>>=Nt;return{p1:o,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 As(e),e}else return dr(r,{isLE:t})}function Rn(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 l=e[c];if(!(typeof l=="bigint"&&l>hr))throw new Error(`CURVE.${c} must be positive bigint`)}let s=Lc(e.p,t.Fp,n),o=Lc(e.n,t.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!s.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:s,Fn:o}}function Bn(r,e){return function(n){let s=r(n);return{secretKey:s,publicKey:e(s)}}}var wt=BigInt(0),he=BigInt(1),Rs=BigInt(2),sd=BigInt(8);function id(r,e,t,n){let s=r.sqr(t),o=r.sqr(n),i=r.add(r.mul(e.a,s),o),a=r.add(r.ONE,r.mul(e.d,r.mul(s,o)));return r.eql(i,a)}function Pc(r,e={}){let t=Rn("edwards",r,e,e.FpFnLE),{Fp:n,Fn:s}=t,o=t.CURVE,{h:i}=o;bt(e,{},{uvRatio:"function"});let a=Rs<<BigInt(s.BYTES*8)-he,c=w=>n.create(w),l=e.uvRatio||((w,y)=>{try{return{isValid:!0,value:n.sqrt(n.div(w,y))}}catch{return{isValid:!1,value:wt}}});if(!id(n,o,o.Gx,o.Gy))throw new Error("bad curve params: generator point");function u(w,y,A=!1){let x=A?he:wt;return qr("coordinate "+w,y,x,a),y}function f(w){if(!(w instanceof d))throw new Error("EdwardsPoint expected")}let h=fr((w,y)=>{let{X:A,Y:x,Z:T}=w,P=w.is0();y==null&&(y=P?sd:n.inv(T));let M=c(A*y),V=c(x*y),S=n.mul(T,y);if(P)return{x:wt,y:he};if(S!==he)throw new Error("invZ was invalid");return{x:M,y:V}}),p=fr(w=>{let{a:y,d:A}=o;if(w.is0())throw new Error("bad point: ZERO");let{X:x,Y:T,Z:P,T:M}=w,V=c(x*x),S=c(T*T),E=c(P*P),N=c(E*E),F=c(V*y),L=c(E*c(F+S)),g=c(N+c(A*c(V*S)));if(L!==g)throw new Error("bad point: equation left != right (1)");let b=c(x*T),m=c(P*M);if(b!==m)throw new Error("bad point: equation left != right (2)");return!0});class d{static BASE=new d(o.Gx,o.Gy,he,c(o.Gx*o.Gy));static ZERO=new d(wt,he,he,wt);static Fp=n;static Fn=s;X;Y;Z;T;constructor(y,A,x,T){this.X=u("x",y),this.Y=u("y",A),this.Z=u("z",x,!0),this.T=u("t",T),Object.freeze(this)}static CURVE(){return o}static fromAffine(y){if(y instanceof d)throw new Error("extended point not allowed");let{x:A,y:x}=y||{};return u("x",A),u("y",x),new d(A,x,he,c(A*x))}static fromBytes(y,A=!1){let x=n.BYTES,{a:T,d:P}=o;y=Ln(k(y,x,"point")),at(A,"zip215");let M=Ln(y),V=y[x-1];M[x-1]=V&-129;let S=Ot(M),E=A?a:n.ORDER;qr("point.y",S,wt,E);let N=c(S*S),F=c(N-he),L=c(P*N-T),{isValid:g,value:b}=l(F,L);if(!g)throw new Error("bad point: invalid y coordinate");let m=(b&he)===he,_=(V&128)!==0;if(!A&&b===wt&&_)throw new Error("bad point: x=0 and x_0=1");return _!==m&&(b=c(-b)),d.fromAffine({x:b,y:S})}static fromHex(y,A=!1){return d.fromBytes(st(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(Rs),this}assertValidity(){p(this)}equals(y){f(y);let{X:A,Y:x,Z:T}=this,{X:P,Y:M,Z:V}=y,S=c(A*V),E=c(P*T),N=c(x*V),F=c(M*T);return S===E&&N===F}is0(){return this.equals(d.ZERO)}negate(){return new d(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:y}=o,{X:A,Y:x,Z:T}=this,P=c(A*A),M=c(x*x),V=c(Rs*c(T*T)),S=c(y*P),E=A+x,N=c(c(E*E)-P-M),F=S+M,L=F-V,g=S-M,b=c(N*L),m=c(F*g),_=c(N*g),I=c(L*F);return new d(b,m,I,_)}add(y){f(y);let{a:A,d:x}=o,{X:T,Y:P,Z:M,T:V}=this,{X:S,Y:E,Z:N,T:F}=y,L=c(T*S),g=c(P*E),b=c(V*x*F),m=c(M*N),_=c((T+P)*(S+E)-L-g),I=m-b,C=m+b,R=c(g-A*L),D=c(_*I),O=c(C*R),U=c(_*R),oe=c(I*C);return new d(D,O,oe,U)}subtract(y){return this.add(y.negate())}multiply(y){if(!s.isValidNot0(y))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:A,f:x}=v.cached(this,y,T=>Ut(d,T));return Ut(d,[A,x])[0]}multiplyUnsafe(y,A=d.ZERO){if(!s.isValid(y))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return y===wt?d.ZERO:this.is0()||y===he?this:v.unsafe(this,y,x=>Ut(d,x),A)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return v.unsafe(this,o.n).is0()}toAffine(y){return h(this,y)}clearCofactor(){return i===he?this:this.multiplyUnsafe(i)}toBytes(){let{x:y,y:A}=this.toAffine(),x=n.toBytes(A);return x[x.length-1]|=y&he?128:0,x}toHex(){return ot(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let v=new pr(d,s.BITS);return d.BASE.precompute(8),d}function Nc(r,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');bt(t,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=t,{BASE:s,Fp:o,Fn:i}=r,a=t.randomBytes||cr,c=t.adjustScalarBytes||(S=>S),l=t.domain||((S,E,N)=>{if(at(N,"phflag"),E.length||N)throw new Error("Contexts/pre-hash are not supported");return S});function u(S){return i.create(Ot(S))}function f(S){let E=x.secretKey;k(S,x.secretKey,"secretKey");let N=k(e(S),2*E,"hashedSecretKey"),F=c(N.slice(0,E)),L=N.slice(E,2*E),g=u(F);return{head:F,prefix:L,scalar:g}}function h(S){let{head:E,prefix:N,scalar:F}=f(S),L=s.multiply(F),g=L.toBytes();return{head:E,prefix:N,scalar:F,point:L,pointBytes:g}}function p(S){return h(S).pointBytes}function d(S=Uint8Array.of(),...E){let N=Ie(...E);return u(e(l(N,k(S,void 0,"context"),!!n)))}function v(S,E,N={}){S=k(S,void 0,"message"),n&&(S=n(S));let{prefix:F,scalar:L,pointBytes:g}=h(E),b=d(N.context,F,S),m=s.multiply(b).toBytes(),_=d(N.context,m,g,S),I=i.create(b+_*L);if(!i.isValid(I))throw new Error("sign failed: invalid s");let C=Ie(m,i.toBytes(I));return k(C,x.signature,"result")}let w={zip215:!0};function y(S,E,N,F=w){let{context:L,zip215:g}=F,b=x.signature;S=k(S,b,"signature"),E=k(E,void 0,"message"),N=k(N,x.publicKey,"publicKey"),g!==void 0&&at(g,"zip215"),n&&(E=n(E));let m=b/2,_=S.subarray(0,m),I=Ot(S.subarray(m,b)),C,R,D;try{C=r.fromBytes(N,g),R=r.fromBytes(_,g),D=s.multiplyUnsafe(I)}catch{return!1}if(!g&&C.isSmallOrder())return!1;let O=d(L,R.toBytes(),C.toBytes(),E);return R.add(C.multiplyUnsafe(O)).subtract(D).clearCofactor().is0()}let A=o.BYTES,x={secretKey:A,publicKey:A,signature:2*A,seed:A};function T(S=a(x.seed)){return k(S,x.seed,"seed")}function P(S){return Lt(S)&&S.length===i.BYTES}function M(S,E){try{return!!r.fromBytes(S,E)}catch{return!1}}let V={getExtendedPublicKey:h,randomSecretKey:T,isValidSecretKey:P,isValidPublicKey:M,toMontgomery(S){let{y:E}=r.fromBytes(S),N=x.publicKey,F=N===32;if(!F&&N!==57)throw new Error("only defined for 25519 and 448");let L=F?o.div(he+E,he-E):o.div(E-he,E+he);return o.toBytes(L)},toMontgomerySecret(S){let E=x.secretKey;k(S,E);let N=e(S.subarray(0,E));return c(N).subarray(0,E)}};return Object.freeze({keygen:Bn(T,p),getPublicKey:p,sign:v,verify:y,utils:V,Point:r,lengths:x})}var ad=BigInt(1),Uc=BigInt(2);var cd=BigInt(5),ud=BigInt(8),Bs=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),ld={p:Bs,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:ud,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function fd(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),s=BigInt(80),o=Bs,a=r*r%o*r%o,c=ee(a,Uc,o)*a%o,l=ee(c,ad,o)*r%o,u=ee(l,cd,o)*l%o,f=ee(u,e,o)*u%o,h=ee(f,t,o)*f%o,p=ee(h,n,o)*h%o,d=ee(p,s,o)*p%o,v=ee(d,s,o)*p%o,w=ee(v,e,o)*u%o;return{pow_p_5_8:ee(w,Uc,o)*r%o,b2:a}}function dd(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var kc=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function hd(r,e){let t=Bs,n=ue(e*e*e,t),s=ue(n*n*e,t),o=fd(r*s).pow_p_5_8,i=ue(r*n*o,t),a=ue(e*i*i,t),c=i,l=ue(i*kc,t),u=a===r,f=a===ue(-r,t),h=a===ue(-r*kc,t);return u&&(i=c),(f||h)&&(i=l),Tc(i,t)&&(i=ue(-i,t)),{isValid:u||f,value:i}}var pd=Pc(ld,{uvRatio:hd});function md(r){return Nc(pd,hc,Object.assign({adjustScalarBytes:dd},r))}var Mc=md({});var zr=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},On=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 On("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 Ue=Kc;var Pn=32;var Os,yd=(async()=>{try{return await Ue.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function gd(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await Ue.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await Ue.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 bd(r,e,t){return Mc.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function qc(r,e,t){return Os==null&&(Os=await yd),Os?gd(r,e,t):bd(r,e,t)}function Nn(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Un=class{type="Ed25519";raw;constructor(e){this.raw=Ps(e,Pn)}toMultihash(){return Me.digest(We(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 s=qc(this.raw,t,e);return Nn(s)?s.then(o=>(n?.signal?.throwIfAborted(),o)):s}};function Ns(r){return r=Ps(r,Pn),new Un(r)}function Ps(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new ae(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var xd=Math.pow(2,7),Ed=Math.pow(2,14),Sd=Math.pow(2,21),Us=Math.pow(2,28),ks=Math.pow(2,35),Ms=Math.pow(2,42),Ks=Math.pow(2,49),Y=128,we=127;function De(r){if(r<xd)return 1;if(r<Ed)return 2;if(r<Sd)return 3;if(r<Us)return 4;if(r<ks)return 5;if(r<Ms)return 6;if(r<Ks)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function mr(r,e,t=0){switch(De(r)){case 8:e[t++]=r&255|Y,r/=128;case 7:e[t++]=r&255|Y,r/=128;case 6:e[t++]=r&255|Y,r/=128;case 5:e[t++]=r&255|Y,r/=128;case 4:e[t++]=r&255|Y,r>>>=7;case 3:e[t++]=r&255|Y,r>>>=7;case 2:e[t++]=r&255|Y,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function vd(r,e,t=0){switch(De(r)){case 8:e.set(t++,r&255|Y),r/=128;case 7:e.set(t++,r&255|Y),r/=128;case 6:e.set(t++,r&255|Y),r/=128;case 5:e.set(t++,r&255|Y),r/=128;case 4:e.set(t++,r&255|Y),r>>>=7;case 3:e.set(t++,r&255|Y),r>>>=7;case 2:e.set(t++,r&255|Y),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function qs(r,e){let t=r[e],n=0;if(n+=t&we,t<Y||(t=r[e+1],n+=(t&we)<<7,t<Y)||(t=r[e+2],n+=(t&we)<<14,t<Y)||(t=r[e+3],n+=(t&we)<<21,t<Y)||(t=r[e+4],n+=(t&we)*Us,t<Y)||(t=r[e+5],n+=(t&we)*ks,t<Y)||(t=r[e+6],n+=(t&we)*Ms,t<Y)||(t=r[e+7],n+=(t&we)*Ks,t<Y))return n;throw new RangeError("Could not decode varint")}function _d(r,e){let t=r.get(e),n=0;if(n+=t&we,t<Y||(t=r.get(e+1),n+=(t&we)<<7,t<Y)||(t=r.get(e+2),n+=(t&we)<<14,t<Y)||(t=r.get(e+3),n+=(t&we)<<21,t<Y)||(t=r.get(e+4),n+=(t&we)*Us,t<Y)||(t=r.get(e+5),n+=(t&we)*ks,t<Y)||(t=r.get(e+6),n+=(t&we)*Ms,t<Y)||(t=r.get(e+7),n+=(t&we)*Ks,t<Y))return n;throw new RangeError("Could not decode varint")}function yr(r,e,t=0){return e==null&&(e=Ae(De(r))),e instanceof Uint8Array?mr(r,e,t):vd(r,e,t)}function $r(r,e=0){return r instanceof Uint8Array?qs(r,e):_d(r,e)}var Fs=new Float32Array([-0]),xt=new Uint8Array(Fs.buffer);function Fc(r,e,t){Fs[0]=r,e[t]=xt[0],e[t+1]=xt[1],e[t+2]=xt[2],e[t+3]=xt[3]}function Hc(r,e){return xt[0]=r[e],xt[1]=r[e+1],xt[2]=r[e+2],xt[3]=r[e+3],Fs[0]}var Hs=new Float64Array([-0]),xe=new Uint8Array(Hs.buffer);function zc(r,e,t){Hs[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 $c(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],Hs[0]}var Ad=BigInt(Number.MAX_SAFE_INTEGER),Td=BigInt(Number.MIN_SAFE_INTEGER),Oe=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 kt;if(e<Ad&&e>Td)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,s=e-(n<<32n);return t&&(n=~n|0n,s=~s|0n,++s>Wc&&(s=0n,++n>Wc&&(n=0n))),new r(Number(s),Number(n))}static fromNumber(e){if(e===0)return kt;let t=e<0;t&&(e=-e);let n=e>>>0,s=(e-n)/4294967296>>>0;return t&&(s=~s>>>0,n=~n>>>0,++n>4294967295&&(n=0,++s>4294967295&&(s=0))),new r(n,s)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):kt}},kt=new Oe(0,0);kt.toBigInt=function(){return 0n};kt.zzEncode=kt.zzDecode=function(){return this};kt.length=function(){return 1};var Wc=4294967296n;function Gc(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 Yc(r,e,t){if(t-e<1)return"";let s,o=[],i=0,a;for(;e<t;)a=r[e++],a<128?o[i++]=a:a>191&&a<224?o[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,o[i++]=55296+(a>>10),o[i++]=56320+(a&1023)):o[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((s??(s=[])).push(String.fromCharCode.apply(String,o)),i=0);return s!=null?(i>0&&s.push(String.fromCharCode.apply(String,o.slice(0,i))),s.join("")):String.fromCharCode.apply(String,o.slice(0,i))}function zs(r,e,t){let n=t,s,o;for(let i=0;i<r.length;++i)s=r.charCodeAt(i),s<128?e[t++]=s:s<2048?(e[t++]=s>>6|192,e[t++]=s&63|128):(s&64512)===55296&&((o=r.charCodeAt(i+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++i,e[t++]=s>>18|240,e[t++]=s>>12&63|128,e[t++]=s>>6&63|128,e[t++]=s&63|128):(e[t++]=s>>12|224,e[t++]=s>>6&63|128,e[t++]=s&63|128);return t-n}function qe(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function kn(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var $s=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,qe(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 qe(this,4);return kn(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw qe(this,4);return kn(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw qe(this,4);let e=Hc(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw qe(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 qe(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Yc(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw qe(this,e);this.pos+=e}else do if(this.pos>=this.len)throw qe(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 Oe(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 qe(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 qe(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 qe(this,8);let e=kn(this.buf,this.pos+=4),t=kn(this.buf,this.pos+=4);return new Oe(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=qs(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 Wr(r){return new $s(r instanceof Uint8Array?r:r.subarray())}function Ce(r,e,t){let n=Wr(r);return e.decode(n,void 0,t)}function Ws(r){let e=r??8192,t=e>>>1,n,s=e;return function(i){if(i<1||i>t)return Ae(i);s+i>e&&(n=Ae(e),s=0);let a=n.subarray(s,s+=i);return(s&7)!==0&&(s=(s|7)+1),a}}var Mt=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}},Id=Ws();function Dd(r){return globalThis.Buffer!=null?Ae(r):Id(r)}var Yr=class{len;head;tail;states;constructor(){this.len=0,this.head=new Mt(Gs,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new Mt(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Xs((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(Mn,10,Oe.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Oe.fromBigInt(e);return this._push(Mn,t.length(),t)}uint64Number(e){return this._push(mr,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=Oe.fromBigInt(e).zzEncode();return this._push(Mn,t.length(),t)}sint64Number(e){let t=Oe.fromNumber(e).zzEncode();return this._push(Mn,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Ys,1,e?1:0)}fixed32(e){return this._push(Gr,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Oe.fromBigInt(e);return this._push(Gr,4,t.lo)._push(Gr,4,t.hi)}fixed64Number(e){let t=Oe.fromNumber(e);return this._push(Gr,4,t.lo)._push(Gr,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(Fc,4,e)}double(e){return this._push(zc,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(Ys,1,0):this.uint32(t)._push(Ld,t,e)}string(e){let t=Gc(e);return t!==0?this.uint32(t)._push(zs,t,e):this._push(Ys,1,0)}fork(){return this.states=new Zs(this),this.head=this.tail=new Mt(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 Mt(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=Dd(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function Ys(r,e,t){e[t]=r&255}function Cd(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var Xs=class extends Mt{next;constructor(e,t){super(Cd,e,t),this.next=void 0}};function Mn(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 Gr(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 Ld(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(Yr.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(Rd,e,r),this},Yr.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(Bd,e,r),this});function Rd(r,e,t){e.set(r,t)}function Bd(r,e,t){r.length<40?zs(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(K(r),t)}function js(){return new Yr}function Le(r,e){let t=js();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}function*Re(r,e,t){let n=Wr(r);yield*e.stream(n,void 0,"$",t)}var Kn={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function qn(r,e,t,n,s){return{name:r,type:e,encode:t,decode:n,stream:s}}function Kt(r){function e(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let t=function(i,a){let c=e(i);a.int32(c)},n=function(i){let a=i.int32();return e(a)},s=function*(i){let a=i.int32();yield e(a)};return qn("enum",Kn.VARINT,t,n,s)}function Be(r,e,t){return qn("message",Kn.LENGTH_DELIMITED,r,e,t)}var qt=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var ne;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(ne||(ne={}));var Qs;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(Qs||(Qs={}));(function(r){r.codec=()=>Kt(Qs)})(ne||(ne={}));var Ze;(function(r){let e;r.codec=()=>(e==null&&(e=Be((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.Type!=null&&(i.uint32(8),ne.codec().encode(o.Type,i)),o.Data!=null&&(i.uint32(18),i.bytes(o.Data)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.Type=ne.codec().decode(o);break}case 2:{c.Data=o.bytes();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:ne.codec().decode(o)};break}case 2:{yield{field:`${a}.Data`,value:o.bytes()};break}default:{o.skipType(u&7);break}}}})),e);function t(o){return Le(o,r.codec())}r.encode=t;function n(o,i){return Ce(o,r.codec(),i)}r.decode=n;function s(o,i){return Re(o,r.codec(),i)}r.stream=s})(Ze||(Ze={}));var Js;(function(r){let e;r.codec=()=>(e==null&&(e=Be((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.Type!=null&&(i.uint32(8),ne.codec().encode(o.Type,i)),o.Data!=null&&(i.uint32(18),i.bytes(o.Data)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.Type=ne.codec().decode(o);break}case 2:{c.Data=o.bytes();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:ne.codec().decode(o)};break}case 2:{yield{field:`${a}.Data`,value:o.bytes()};break}default:{o.skipType(u&7);break}}}})),e);function t(o){return Le(o,r.codec())}r.encode=t;function n(o,i){return Ce(o,r.codec(),i)}r.decode=n;function s(o,i){return Re(o,r.codec(),i)}r.stream=s})(Js||(Js={}));var Xr={};ve(Xr,{MAX_RSA_KEY_SIZE:()=>ei,generateRSAKeyPair:()=>eu,jwkToJWKKeyPair:()=>tu,jwkToPkcs1:()=>Ud,jwkToPkix:()=>oi,jwkToRSAPrivateKey:()=>ci,pkcs1MessageToJwk:()=>ri,pkcs1MessageToRSAPrivateKey:()=>si,pkcs1ToJwk:()=>Nd,pkcs1ToRSAPrivateKey:()=>Jc,pkixMessageToJwk:()=>ni,pkixMessageToRSAPublicKey:()=>ai,pkixToJwk:()=>kd,pkixToRSAPublicKey:()=>ii});var gr=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=Xr.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)}},Zr=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=Xr.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 ei=8192,ti=18,Od=1062,Pd=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function Nd(r){let e=tt(r);return ri(e)}function ri(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 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 ae("JWK was missing components");return pt([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 kd(r){let e=tt(r,{offset:0});return ni(e)}function ni(r){let e=tt(r[1],{offset:0});return{kty:"RSA",n:$(e[0],"base64url"),e:$(e[1],"base64url")}}function oi(r){if(r.n==null||r.e==null)throw new ae("JWK was missing components");return pt([Pd,_n(pt([Te(K(r.n,"base64url")),Te(K(r.e,"base64url"))]))]).subarray()}function Jc(r){let e=tt(r);return si(e)}function si(r){let e=ri(r);return ci(e)}function ii(r,e){if(r.byteLength>=Od)throw new Qt("Key size is too large");let t=tt(r,{offset:0});return ai(t,r,e)}function ai(r,e,t){let n=ni(r);if(t==null){let s=ur(Ze.encode({Type:ne.RSA,Data:e}));t=ze(ti,s)}return new gr(n,t)}function ci(r){if(nu(r)>ei)throw new ae("Key size is too large");let e=tu(r),t=ur(Ze.encode({Type:ne.RSA,Data:oi(e.publicKey)})),n=ze(ti,t);return new Zr(e.privateKey,new gr(e.publicKey,n))}async function eu(r){if(r>ei)throw new ae("Key size is too large");let e=await ru(r),t=ur(Ze.encode({Type:ne.RSA,Data:oi(e.publicKey)})),n=ze(ti,t);return new Zr(e.privateKey,new gr(e.publicKey,n))}function tu(r){if(r==null)throw new ae("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function ru(r,e){let t=await Ue.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 Md(t,e);return{privateKey:n[0],publicKey:n[1]}}async function jc(r,e,t){let n=await Ue.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let s=await Ue.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,e instanceof Uint8Array?e:e.subarray());return t?.signal?.throwIfAborted(),new Uint8Array(s,0,s.byteLength)}async function Qc(r,e,t,n){let s=await Ue.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let o=await Ue.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},s,e,t instanceof Uint8Array?t:t.subarray());return n?.signal?.throwIfAborted(),o}async function Md(r,e){if(r.privateKey==null||r.publicKey==null)throw new ae("Private and public key are required");let t=await Promise.all([Ue.get().subtle.exportKey("jwk",r.privateKey),Ue.get().subtle.exportKey("jwk",r.publicKey)]);return e?.signal?.throwIfAborted(),t}function nu(r){if(r.kty!=="RSA")throw new ae("invalid key type");if(r.n==null)throw new ae("invalid key modulus");return K(r.n,"base64url").length*8}var Vn=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if(An(e),k(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,s=new Uint8Array(n);s.set(t.length>n?e.create().update(t).digest():t);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=e.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),nt(s)}update(e){return ar(this),this.iHash.update(e),this}digestInto(e){ar(this),k(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:s,destroyed:o,blockLen:i,outputLen:a}=this;return e=e,e.finished=s,e.destroyed=o,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},ui=(r,e,t)=>new Vn(r,e).update(t).digest();ui.create=(r,e)=>new Vn(r,e);var ou=(r,e)=>(r+(r>=0?e:-e)/su)/e;function Kd(r,e,t){let[[n,s],[o,i]]=e,a=ou(i*r,t),c=ou(-s*r,t),l=r-a*n-c*o,u=-a*s-c*i,f=l<ct,h=u<ct;f&&(l=-l),h&&(u=-u);let p=Vr(Math.ceil(Ss(t)/2))+br;if(l<ct||l>=p||u<ct||u>=p)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:f,k1:l,k2neg:h,k2:u}}function fi(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function li(r,e){let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return at(t.lowS,"lowS"),at(t.prehash,"prehash"),t.format!==void 0&&fi(t.format),t}var di=class extends Error{constructor(e=""){super(e)}},Et={Err:di,_tlv:{encode:(r,e)=>{let{Err:t}=Et;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,s=Kr(n);if(s.length/2&128)throw new t("tlv.encode: long form length too big");let o=n>127?Kr(s.length/2|128):"";return Kr(r)+o+s+e},decode(r,e){let{Err:t}=Et,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 s=e[n++],o=!!(s&128),i=0;if(!o)i=s;else{let c=s&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let l=e.subarray(n,n+c);if(l.length!==c)throw new t("tlv.decode: length bytes not complete");if(l[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let u of l)i=i<<8|u;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}=Et;if(r<ct)throw new e("integer: negative integers are not allowed");let t=Kr(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}=Et;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 lr(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=Et,s=k(r,void 0,"signature"),{v:o,l:i}=n.decode(48,s);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,o),{v:l,l:u}=n.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(l)}},hexFromSig(r){let{_tlv:e,_int:t}=Et,n=e.encode(2,t.encode(r.r)),s=e.encode(2,t.encode(r.s)),o=n+s;return e.encode(48,o)}},ct=BigInt(0),br=BigInt(1),su=BigInt(2),Fn=BigInt(3),qd=BigInt(4);function iu(r,e={}){let t=Rn("weierstrass",r,e),{Fp:n,Fn:s}=t,o=t.CURVE,{h:i,n:a}=o;bt(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c}=e;if(c&&(!n.is0(o.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=cu(n,s);function u(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(L,g,b){let{x:m,y:_}=g.toAffine(),I=n.toBytes(m);if(at(b,"isCompressed"),b){u();let C=!n.isOdd(_);return Ie(au(C),I)}else return Ie(Uint8Array.of(4),I,n.toBytes(_))}function h(L){k(L,void 0,"Point");let{publicKey:g,publicKeyUncompressed:b}=l,m=L.length,_=L[0],I=L.subarray(1);if(m===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(oe){let Q=oe instanceof Error?": "+oe.message:"";throw new Error("bad point: is not on curve, sqrt error"+Q)}u();let O=n.isOdd(D);return(_&1)===1!==O&&(D=n.neg(D)),{x:C,y:D}}else if(m===b&&_===4){let C=n.BYTES,R=n.fromBytes(I.subarray(0,C)),D=n.fromBytes(I.subarray(C,C*2));if(!w(R,D))throw new Error("bad point: is not on curve");return{x:R,y:D}}else throw new Error(`bad point: got length ${m}, expected compressed=${g} or uncompressed=${b}`)}let p=e.toBytes||f,d=e.fromBytes||h;function v(L){let g=n.sqr(L),b=n.mul(g,L);return n.add(n.add(b,n.mul(L,o.a)),o.b)}function w(L,g){let b=n.sqr(g),m=v(L);return n.eql(b,m)}if(!w(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let y=n.mul(n.pow(o.a,Fn),qd),A=n.mul(n.sqr(o.b),BigInt(27));if(n.is0(n.add(y,A)))throw new Error("bad curve params: a or b");function x(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 Kd(L,c.basises,s.ORDER)}let M=fr((L,g)=>{let{X:b,Y:m,Z:_}=L;if(n.eql(_,n.ONE))return{x:b,y:m};let I=L.is0();g==null&&(g=I?n.ONE:n.inv(_));let C=n.mul(b,g),R=n.mul(m,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}}),V=fr(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(!w(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,m,_){return b=new E(n.mul(b.X,L),b.Y,b.Z),g=Hr(m,g),b=Hr(_,b),g.add(b)}class E{static BASE=new E(o.Gx,o.Gy,n.ONE);static ZERO=new E(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=s;X;Y;Z;constructor(g,b,m){this.X=x("x",g),this.Y=x("y",b,!0),this.Z=x("z",m),Object.freeze(this)}static CURVE(){return o}static fromAffine(g){let{x:b,y:m}=g||{};if(!g||!n.isValid(b)||!n.isValid(m))throw new Error("invalid affine point");if(g instanceof E)throw new Error("projective point not allowed");return n.is0(b)&&n.is0(m)?E.ZERO:new E(b,m,n.ONE)}static fromBytes(g){let b=E.fromAffine(d(k(g,void 0,"point")));return b.assertValidity(),b}static fromHex(g){return E.fromBytes(st(g))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,b=!0){return F.createCache(this,g),b||this.multiply(Fn),this}assertValidity(){V(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:m,Z:_}=this,{X:I,Y:C,Z:R}=g,D=n.eql(n.mul(b,R),n.mul(I,_)),O=n.eql(n.mul(m,R),n.mul(C,_));return D&&O}negate(){return new E(this.X,n.neg(this.Y),this.Z)}double(){let{a:g,b}=o,m=n.mul(b,Fn),{X:_,Y:I,Z:C}=this,R=n.ZERO,D=n.ZERO,O=n.ZERO,U=n.mul(_,_),oe=n.mul(I,I),Q=n.mul(C,C),W=n.mul(_,I);return W=n.add(W,W),O=n.mul(_,C),O=n.add(O,O),R=n.mul(g,O),D=n.mul(m,Q),D=n.add(R,D),R=n.sub(oe,D),D=n.add(oe,D),D=n.mul(R,D),R=n.mul(W,R),O=n.mul(m,O),Q=n.mul(g,Q),W=n.sub(U,Q),W=n.mul(g,W),W=n.add(W,O),O=n.add(U,U),U=n.add(O,U),U=n.add(U,Q),U=n.mul(U,W),D=n.add(D,U),Q=n.mul(I,C),Q=n.add(Q,Q),U=n.mul(Q,W),R=n.sub(R,U),O=n.mul(Q,oe),O=n.add(O,O),O=n.add(O,O),new E(R,D,O)}add(g){T(g);let{X:b,Y:m,Z:_}=this,{X:I,Y:C,Z:R}=g,D=n.ZERO,O=n.ZERO,U=n.ZERO,oe=o.a,Q=n.mul(o.b,Fn),W=n.mul(b,I),se=n.mul(m,C),me=n.mul(_,R),He=n.add(b,m),ie=n.add(I,C);He=n.mul(He,ie),ie=n.add(W,se),He=n.sub(He,ie),ie=n.add(b,_);let be=n.add(I,R);return ie=n.mul(ie,be),be=n.add(W,me),ie=n.sub(ie,be),be=n.add(m,_),D=n.add(C,R),be=n.mul(be,D),D=n.add(se,me),be=n.sub(be,D),U=n.mul(oe,ie),D=n.mul(Q,me),U=n.add(D,U),D=n.sub(se,U),U=n.add(se,U),O=n.mul(D,U),se=n.add(W,W),se=n.add(se,W),me=n.mul(oe,me),ie=n.mul(Q,ie),se=n.add(se,me),me=n.sub(W,me),me=n.mul(oe,me),ie=n.add(ie,me),W=n.mul(se,ie),O=n.add(O,W),W=n.mul(be,ie),D=n.mul(He,D),D=n.sub(D,W),W=n.mul(He,se),U=n.mul(be,U),U=n.add(U,W),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(!s.isValidNot0(g))throw new Error("invalid scalar: out of range");let m,_,I=C=>F.cached(this,C,R=>Ut(E,R));if(b){let{k1neg:C,k1:R,k2neg:D,k2:O}=P(g),{p:U,f:oe}=I(R),{p:Q,f:W}=I(O);_=oe.add(W),m=S(b.beta,U,Q,C,D)}else{let{p:C,f:R}=I(g);m=C,_=R}return Ut(E,[m,_])[0]}multiplyUnsafe(g){let{endo:b}=e,m=this;if(!s.isValid(g))throw new Error("invalid scalar: out of range");if(g===ct||m.is0())return E.ZERO;if(g===br)return m;if(F.hasCache(this))return this.multiply(g);if(b){let{k1neg:_,k1:I,k2neg:C,k2:R}=P(g),{p1:D,p2:O}=Oc(E,m,I,R);return S(b.beta,D,O,_,C)}else return F.unsafe(m,g)}toAffine(g){return M(this,g)}isTorsionFree(){let{isTorsionFree:g}=e;return i===br?!0:g?g(E,this):F.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:g}=e;return i===br?this:g?g(E,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(g=!0){return at(g,"isCompressed"),this.assertValidity(),p(E,this,g)}toHex(g=!0){return ot(this.toBytes(g))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let N=s.BITS,F=new pr(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 Vd(r,e={}){let{Fn:t}=r,n=e.randomBytes||cr,s=Object.assign(cu(r.Fp,t),{seed:Ts(t.ORDER)});function o(p){try{let d=t.fromBytes(p);return t.isValidNot0(d)}catch{return!1}}function i(p,d){let{publicKey:v,publicKeyUncompressed:w}=s;try{let y=p.length;return d===!0&&y!==v||d===!1&&y!==w?!1:!!r.fromBytes(p)}catch{return!1}}function a(p=n(s.seed)){return Is(k(p,s.seed,"seed"),t.ORDER)}function c(p,d=!0){return r.BASE.multiply(t.fromBytes(p)).toBytes(d)}function l(p){let{secretKey:d,publicKey:v,publicKeyUncompressed:w}=s;if(!Lt(p)||"_lengths"in t&&t._lengths||d===v)return;let y=k(p,void 0,"key").length;return y===v||y===w}function u(p,d,v=!0){if(l(p)===!0)throw new Error("first arg must be private key");if(l(d)===!1)throw new Error("second arg must be public key");let w=t.fromBytes(p);return r.fromBytes(d).multiply(w).toBytes(v)}let f={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a},h=Bn(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:h,Point:r,utils:f,lengths:s})}function uu(r,e,t={}){An(e),bt(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let n=t.randomBytes||cr,s=t.hmac||((b,m)=>ui(e,b,m)),{Fp:o,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:u,getSharedSecret:f,utils:h,lengths:p}=Vd(r,t),d={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},v=a*su<o.ORDER;function w(b){let m=a>>br;return b>m}function y(b,m){if(!i.isValidNot0(m))throw new Error(`invalid signature ${b}: out of range 1..Point.Fn.ORDER`);return m}function A(){if(v)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function x(b,m){fi(m);let _=p.signature,I=m==="compact"?_:m==="recovered"?_+1:void 0;return k(b,I)}class T{r;s;recovery;constructor(m,_,I){if(this.r=y("r",m),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(m,_=d.format){x(m,_);let I;if(_==="der"){let{r:O,s:U}=Et.toSig(k(m));return new T(O,U)}_==="recovered"&&(I=m[0],_="compact",m=m.subarray(1));let C=p.signature/2,R=m.subarray(0,C),D=m.subarray(C,C*2);return new T(i.fromBytes(R),i.fromBytes(D),I)}static fromHex(m,_){return this.fromBytes(st(m),_)}assertRecovery(){let{recovery:m}=this;if(m==null)throw new Error("invalid recovery id: must be present");return m}addRecoveryBit(m){return new T(this.r,this.s,m)}recoverPublicKey(m){let{r:_,s:I}=this,C=this.assertRecovery(),R=C===2||C===3?_+a:_;if(!o.isValid(R))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let D=o.toBytes(R),O=r.fromBytes(Ie(au((C&1)===0),D)),U=i.inv(R),oe=M(k(m,void 0,"msgHash")),Q=i.create(-oe*U),W=i.create(I*U),se=r.BASE.multiplyUnsafe(Q).add(O.multiplyUnsafe(W));if(se.is0())throw new Error("invalid recovery: point at infinify");return se.assertValidity(),se}hasHighS(){return w(this.s)}toBytes(m=d.format){if(fi(m),m==="der")return st(Et.hexFromSig(this));let{r:_,s:I}=this,C=i.toBytes(_),R=i.toBytes(I);return m==="recovered"?(A(),Ie(Uint8Array.of(this.assertRecovery()),C,R)):Ie(C,R)}toHex(m){return ot(this.toBytes(m))}}let P=t.bits2int||function(m){if(m.length>8192)throw new Error("input is too large");let _=lr(m),I=m.length*8-c;return I>0?_>>BigInt(I):_},M=t.bits2int_modN||function(m){return i.create(P(m))},V=Vr(c);function S(b){return qr("num < 2^"+c,b,ct,V),i.toBytes(b)}function E(b,m){return k(b,void 0,"message"),m?k(e(b),void 0,"prehashed message"):b}function N(b,m,_){let{lowS:I,prehash:C,extraEntropy:R}=li(_,d);b=E(b,C);let D=M(b),O=i.fromBytes(m);if(!i.isValidNot0(O))throw new Error("invalid private key");let U=[S(O),S(D)];if(R!=null&&R!==!1){let se=R===!0?n(p.secretKey):R;U.push(k(se,void 0,"extraEntropy"))}let oe=Ie(...U),Q=D;function W(se){let me=P(se);if(!i.isValidNot0(me))return;let He=i.inv(me),ie=r.BASE.multiply(me).toAffine(),be=i.create(ie.x);if(be===ct)return;let dn=i.create(He*i.create(Q+be*O));if(dn===ct)return;let ya=(ie.x===be?0:2)|Number(ie.y&br),ga=dn;return I&&w(dn)&&(ga=i.neg(dn),ya^=1),new T(be,ga,v?void 0:ya)}return{seed:oe,k2sig:W}}function F(b,m,_={}){let{seed:I,k2sig:C}=N(b,m,_);return yc(e.outputLen,i.BYTES,s)(I,C).toBytes(_.format)}function L(b,m,_,I={}){let{lowS:C,prehash:R,format:D}=li(I,d);if(_=k(_,void 0,"publicKey"),m=E(m,R),!Lt(b)){let O=b instanceof T?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+O)}x(b,D);try{let O=T.fromBytes(b,D),U=r.fromBytes(_);if(C&&O.hasHighS())return!1;let{r:oe,s:Q}=O,W=M(m),se=i.inv(Q),me=i.create(W*se),He=i.create(oe*se),ie=r.BASE.multiplyUnsafe(me).add(U.multiplyUnsafe(He));return ie.is0()?!1:i.create(ie.x)===oe}catch{return!1}}function g(b,m,_={}){let{prehash:I}=li(_,d);return m=E(m,I),T.fromBytes(b,"recovered").recoverPublicKey(m).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:f,utils:h,lengths:p,Point:r,sign:F,verify:L,recoverPublicKey:g,Signature:T,hash:e})}var pi={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Fd={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var lu=BigInt(2);function Hd(r){let e=pi.p,t=BigInt(3),n=BigInt(6),s=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,f=ee(u,t,e)*u%e,h=ee(f,t,e)*u%e,p=ee(h,lu,e)*l%e,d=ee(p,s,e)*p%e,v=ee(d,o,e)*d%e,w=ee(v,a,e)*v%e,y=ee(w,c,e)*w%e,A=ee(y,a,e)*v%e,x=ee(A,t,e)*u%e,T=ee(x,i,e)*d%e,P=ee(T,n,e)*l%e,M=ee(P,lu,e);if(!hi.eql(hi.sqr(M),r))throw new Error("Cannot find square root");return M}var hi=dr(pi.p,{sqrt:Hd}),zd=iu(pi,{Fp:hi,endo:Fd}),wr=uu(zd,ur);function fu(r,e,t,n){let s=sr.digest(t instanceof Uint8Array?t:t.subarray());if(Nn(s))return s.then(({digest:o})=>(n?.signal?.throwIfAborted(),wr.verify(e,o,r,{prehash:!1,format:"der"}))).catch(o=>{throw o.name==="AbortError"?o:new zr(String(o))});try{return n?.signal?.throwIfAborted(),wr.verify(e,s.digest,r,{prehash:!1,format:"der"})}catch(o){throw new zr(String(o))}}var Hn=class{type="secp256k1";raw;_key;constructor(e){this._key=hu(e),this.raw=du(this._key)}toMultihash(){return Me.digest(We(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 mi(r){return new Hn(r)}function du(r){return wr.Point.fromBytes(r).toBytes()}function hu(r){try{return wr.Point.fromBytes(r),r}catch(e){throw new Qt(String(e))}}function pu(r,e){let{Type:t,Data:n}=Ze.decode(r),s=n??new Uint8Array;switch(t){case ne.RSA:return ii(s,e);case ne.Ed25519:return Ns(s);case ne.secp256k1:return mi(s);case ne.ECDSA:return ls(s);default:throw new Jt}}function mu(r){let{Type:e,Data:t}=Ze.decode(r.digest),n=t??new Uint8Array;switch(e){case ne.Ed25519:return Ns(n);case ne.secp256k1:return mi(n);case ne.ECDSA:return ls(n);default:throw new Jt}}function We(r){return Ze.encode({Type:ne[r.type],Data:r.raw})}var yu=Symbol.for("nodejs.util.inspect.custom"),$d=114,jr=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()})`}[Uo]=!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($d,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()})`}},zn=class extends jr{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},$n=class extends jr{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},Wn=class extends jr{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},Wd=2336,Qr=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Me.digest(K(this.url))}[yu](){return`PeerId(${this.url})`}[Uo]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return le.createV1(Wd,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=$(e)),e.toString()===this.toString())}};var Gd=114,gu=2336;function yi(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=$e(te.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return Yd(le.parse(r));if(e==null)throw new ae('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=$e(e.decode(r))}return xr(t)}function xr(r){if(Xd(r))return new zn({multihash:r});if(Zd(r))try{let e=mu(r);if(e.type==="Ed25519")return new $n({multihash:r,publicKey:e});if(e.type==="secp256k1")return new Wn({multihash:r,publicKey:e})}catch{let t=$(r.digest);return new Qr(new URL(t))}throw new mn("Supplied PeerID Multihash is invalid")}function Yd(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==Gd&&r.code!==gu)throw new pn("Supplied PeerID CID is invalid");if(r.code===gu){let e=$(r.multihash.digest);return new Qr(new URL(e))}return xr(r.multihash)}function Zd(r){return r.code===Me.code}function Xd(r){return r.code===sr.code}var Jr;(function(r){let e;r.codec=()=>(e==null&&(e=Be((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.publicKey!=null&&o.publicKey.byteLength>0&&(i.uint32(10),i.bytes(o.publicKey)),o.payloadType!=null&&o.payloadType.byteLength>0&&(i.uint32(18),i.bytes(o.payloadType)),o.payload!=null&&o.payload.byteLength>0&&(i.uint32(26),i.bytes(o.payload)),o.signature!=null&&o.signature.byteLength>0&&(i.uint32(42),i.bytes(o.signature)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={publicKey:re(0),payloadType:re(0),payload:re(0),signature:re(0)},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.publicKey=o.bytes();break}case 2:{c.payloadType=o.bytes();break}case 3:{c.payload=o.bytes();break}case 5:{c.signature=o.bytes();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{yield{field:`${a}.publicKey`,value:o.bytes()};break}case 2:{yield{field:`${a}.payloadType`,value:o.bytes()};break}case 3:{yield{field:`${a}.payload`,value:o.bytes()};break}case 5:{yield{field:`${a}.signature`,value:o.bytes()};break}default:{o.skipType(u&7);break}}}})),e);function t(o){return Le(o,r.codec())}r.encode=t;function n(o,i){return Ce(o,r.codec(),i)}r.decode=n;function s(o,i){return Re(o,r.codec(),i)}r.stream=s})(Jr||(Jr={}));var Gn=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var en=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 s=e.domain,o=e.codec,i=e.marshal(),a=bu(s,o,i),c=await t.sign(a.subarray(),n);return new r({publicKey:t.publicKey,payloadType:o,payload:i,signature:c})};static openAndCertify=async(e,t,n)=>{let s=r.createFromProtobuf(e);if(!await s.validate(t,n))throw new Gn("Envelope signature is not valid for the given domain");return s};publicKey;payloadType;payload;signature;marshaled;constructor(e){let{publicKey:t,payloadType:n,payload:s,signature:o}=e;this.publicKey=t,this.payloadType=n,this.payload=s,this.signature=o}marshal(){return this.marshaled==null&&(this.marshaled=Jr.encode({publicKey:We(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),s=yr(n.byteLength),o=yr(e.length),i=yr(t.length);return new J(s,n,o,e,i,t)};var ge=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},ut=class extends Error{static name="ValidationError";name="ValidationError"},Yn=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Zn=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var Xn=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,s){return this.readAtomically(()=>{let o=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*s)-1;for(;;){let u=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let h=Number.parseInt(f,e);if(!Number.isNaN(h))return h});if(u===void 0)break;if(o*=e,o+=u,o>l||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:o})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let s=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[s]=i[0],t[s+1]=i[1],t[s+2]=i[2],t[s+3]=i[3],[s+4,!0]}let o=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(o===void 0)return[s,!1];t[s]=o>>8,t[s+1]=o&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,s]=e(t);if(n===16)return t;if(s||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let o=new Uint8Array(14),i=16-(n+2),[a]=e(o.subarray(0,i));return t.set(o.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var jd=45,Qd=15,jn=new Xn;function wu(r){if(!(r.length>Qd))return jn.new(r).parseWith(()=>jn.readIPv4Addr())}function xu(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>jd))return jn.new(r).parseWith(()=>jn.readIPv6Addr())}function Qn(r){return!!wu(r)}function Eu(r){return!!xu(r)}function bi(r){return e=>$(e,r)}function wi(r){return e=>K(e,r)}function Er(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Vt(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 s=Vt(n);return et([t,s],t.length+s.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=ht.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=Vt(n);return et([t,s],t.length+s.length)}function xi(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=$(e,"base32"),s=Er(t);return`${n}:${s}`}var Ei=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let s=parseInt(t,10);if(isNaN(s)||s<0||s>255)throw new ge("Invalid byte value in IP address");e[n]=s}),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 o=Qn(t[n]),i;o&&(i=Ei(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 o=[n,1];for(n=9-t.length;n>0;n--)o.push("0");t.splice.apply(t,o)}let s=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let o=parseInt(t[n],16);if(isNaN(o)||o<0||o>65535)throw new ge("Invalid byte value in IP address");s[e++]=o>>8&255,s[e++]=o&255}return s},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 s=r[n],o=r[n+1],i=`${s.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new 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 gi=Object.values(Or).map(r=>r.decoder),Jd=(function(){let r=gi[0].or(gi[1]);return gi.slice(2).forEach(e=>r=r.or(e)),r})();function Du(r){return Jd.decode(r)}function Cu(r){return e=>r.encoder.encode(e)}function eh(r){if(parseInt(r).toString()!==r)throw new ut("Value must be an integer")}function th(r){if(r<0)throw new ut("Value must be a positive integer, or zero")}function rh(r){return e=>{if(e>r)throw new ut(`Value must be smaller than or equal to ${r}`)}}function nh(...r){return e=>{for(let t of r)t(e)}}var tn=nh(eh,th,rh(65535));var pe=-1,Si=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)}))}},lt=new Si,bh=[{code:4,name:"ip4",size:32,valueToBytes:Ei,bytesToValue:Au,validate:r=>{if(!Qn(r))throw new ut(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Vt,bytesToValue:Er,validate:tn},{code:273,name:"udp",size:16,valueToBytes:Vt,bytesToValue:Er,validate:tn},{code:33,name:"dccp",size:16,valueToBytes:Vt,bytesToValue:Er,validate:tn},{code:41,name:"ip6",size:128,valueToBytes:_u,bytesToValue:Tu,stringToValue:Iu,validate:r=>{if(!Eu(r))throw new ut(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:pe},{code:43,name:"ipcidr",size:8,bytesToValue:bi("base10"),valueToBytes:wi("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:Vt,bytesToValue:Er,validate:tn},{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:bi("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?wi("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(jo),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}];bh.forEach(r=>{lt.addProtocol(r)});function Lu(r){let e=[],t=0;for(;t<r.length;){let n=$r(r,t),s=lt.getProtocol(n),o=De(n),i=wh(s,r,t+o),a=0;i>0&&s.size===pe&&(a=De(i));let c=o+a+i,l={code:n,name:s.name,bytes:r.subarray(t,t+c)};if(i>0){let u=t+o+a,f=r.subarray(u,u+i);l.value=s.bytesToValue?.(f)??$(f)}e.push(l),t+=c}return e}function Ru(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let s=lt.getProtocol(n.code),o=De(n.code),i,a=0,c=0;n.value!=null&&(i=s.valueToBytes?.(n.value)??K(n.value),a=i.byteLength,s.size===pe&&(c=De(a)));let l=new Uint8Array(o+c+a),u=0;mr(n.code,l,u),u+=o,i!=null&&(s.size===pe&&(mr(a,l,u),u+=c),l.set(i,u)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return et(t,e)}function Bu(r){if(r.charAt(0)!=="/")throw new ge('String multiaddr must start with "/"');let e=[],t="protocol",n="",s="";for(let o=1;o<r.length;o++){let i=r.charAt(o);i!=="/"&&(t==="protocol"?s+=r.charAt(o):n+=r.charAt(o));let a=o===r.length-1;if(i==="/"||a){let c=lt.getProtocol(s);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",s="",t="protocol";continue}else if(a)throw new ge(`Component ${s} was missing value`);t="value"}else if(t==="value"){let l={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new ge(`Component ${s} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",s="",t="protocol"}}}if(s!==""&&n!=="")throw new ge("Incomplete multiaddr");return e}function Ou(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=lt.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 wh(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:$r(e,t)}var xh=Symbol.for("nodejs.util.inspect.custom"),Ki=Symbol.for("@multiformats/multiaddr");function Eh(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 ro=class r{[Ki]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=Eh(e),t.validate!==!1&&Sh(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(),s=n.lastIndexOf(t);if(s<0)throw new Yn(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,s),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}equals(e){return fe(this.bytes,e.bytes)}[xh](){return`Multiaddr(${this.toString()})`}};function Sh(r){r.getComponents().forEach(e=>{let t=lt.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function Pu(r){return!!r?.[Ki]}function Pe(r){return new ro(r)}var qi={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 vh(r,e){let t=qi[e],n=Nu[e];for(let s=0;s<r.length;s++)n^=BigInt(r[s]),n=BigInt.asUintN(e,n*t);return n}function _h(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=qi[e],s=Nu[e],o=r;for(;o.length>0;){let i=Uu.encodeInto(o,t);o=o.slice(i.read);for(let a=0;a<i.written;a++)s^=BigInt(t[a]),s=BigInt.asUintN(e,s*n)}return s}function Vi(r,{size:e=32,utf8Buffer:t}={}){if(!qi[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 _h(r,e,t);r=Uu.encode(r)}return vh(r,e)}var rn={hash:r=>Number(Vi(r,{size:32})),hashV:(r,e)=>Ah(rn.hash(r,e))};function Ah(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),K(e,"base16")}var Fi=64,Ve=class{fp;h;seed;constructor(e,t,n,s=2){if(s>Fi)throw new TypeError("Invalid Fingerprint Size");let o=t.hashV(e,n),i=re(s);for(let a=0;a<i.length;a++)i[a]=o[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?fe(this.fp,e.fp):!1}};function $t(r,e){return Math.floor(Math.random()*(e-r))+r}var Wt=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof Ve))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof Ve))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 Ve))throw new TypeError("Invalid Fingerprint");let t=$t(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof Ve))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var Th=500,nn=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??rn,this.seed=e.seed??$t(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=K(e));let t=new Ve(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new Wt(this.bucketSize)),this.buckets[s]==null&&(this.buckets[s]=new Wt(this.bucketSize)),this.buckets[n].add(t)||this.buckets[s].add(t))return this.count++,!0;let o=[n,s],i=o[$t(0,o.length-1)];this.buckets[i]==null&&(this.buckets[i]=new Wt(this.bucketSize));for(let a=0;a<Th;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 Wt(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=K(e));let t=new Ve(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=this.buckets[n]?.has(t)??!1;if(s)return s;let o=(n^t.hash())%this.filterSize;return this.buckets[o]?.has(t)??!1}remove(e){typeof e=="string"&&(e=K(e));let t=new Ve(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=this.buckets[n]?.remove(t)??!1;if(s)return this.count--,s;let o=(n^t.hash())%this.filterSize,i=this.buckets[o]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},Ih={1:.5,2:.84,4:.95,8:.98};function Dh(r=.001){return r>.002?2:r>1e-5?4:8}function ku(r,e=.001){let t=Dh(e),n=Ih[t],s=Math.round(r/n),o=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),Fi);return{filterSize:s,bucketSize:t,fingerprintSize:o}}var no=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??rn,this.seed=e.seed??$t(0,Math.pow(2,10)),this.filterSeries=[new nn({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 nn({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 Ar(r,e=.001,t){return new no({...ku(r,e),...t??{}})}function Fe(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var oo=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},Tr=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new oo(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new oo(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let 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 St(r={}){return Ch(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 Ch(r,e){e=e??{};let t=e.onEnd,n=new Tr,s,o,i,a=Fe(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((w,y)=>{o=A=>{o=null,n.push(A);try{w(r(n))}catch(x){y(x)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Fe()})}},l=w=>o!=null?o(w):(n.push(w),s),u=w=>(n=new Tr,o!=null?o({error:w}):(n.push({error:w}),s)),f=w=>{if(i)return s;if(e?.objectMode!==!0&&w?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:w})},h=w=>i?s:(i=!0,w!=null?u(w):l({done:!0})),p=()=>(n=new Tr,h(),{done:!0}),d=w=>(h(w),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:p,throw:d,push:f,end:h,get readableLength(){return n.size},onEmpty:async w=>{let y=w?.signal;if(y?.throwIfAborted(),n.isEmpty())return;let A,x;y!=null&&(A=new Promise((T,P)=>{x=()=>{P(new Hi)},y.addEventListener("abort",x)}));try{await Promise.race([a.promise,A])}finally{x!=null&&y!=null&&y?.removeEventListener("abort",x)}}},t==null)return s;let v=s;return s={[Symbol.asyncIterator](){return this},next(){return v.next()},throw(w){return v.throw(w),t!=null&&(t(w),t=void 0),{done:!0}},return(){return v.return(),t!=null&&(t(),t=void 0),{done:!0}},push:f,end(w){return v.end(w),t!=null&&(t(w),t=void 0),s},get readableLength(){return v.readableLength},onEmpty:w=>v.onEmpty(w)},s}var zi=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},Mu=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function $i(r,e){let{milliseconds:t,fallback:n,message:s,customTimers:o={setTimeout,clearTimeout},signal:i}=e,a,c,u=new Promise((f,h)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(i?.aborted){h(Mu(i));return}if(i&&(c=()=>{h(Mu(i))},i.addEventListener("abort",c,{once:!0})),r.then(f,h),t===Number.POSITIVE_INFINITY)return;let p=new zi;a=o.setTimeout.call(void 0,()=>{if(n){try{f(n())}catch(d){h(d)}return}typeof r.cancel=="function"&&r.cancel(),s===!1?f():s instanceof Error?h(s):(p.message=s??`Promise timed out after ${t} milliseconds`,h(p))},t)}).finally(()=>{u.clear(),c&&i&&i.removeEventListener("abort",c)});return u.clear=()=>{o.clearTimeout.call(void 0,a),a=void 0},u}var Lh=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 Rh(r,e,t){let n,s=new Promise((o,i)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:l,removeListener:u}=Lh(r),f=async(...p)=>{let d=t.multiArgs?p:p[0];if(t.filter)try{if(!await t.filter(d))return}catch(v){n(),i(v);return}c.push(d),t.count===c.length&&(n(),o(c))},h=(...p)=>{n(),i(t.rejectionMultiArgs?p:p[0])};n=()=>{for(let p of a)u(p,f);for(let p of t.rejectionEvents)a.includes(p)||u(p,h)};for(let p of a)l(p,f);for(let p of t.rejectionEvents)a.includes(p)||l(p,h);t.signal&&t.signal.addEventListener("abort",()=>{h(t.signal.reason)},{once:!0}),t.resolveImmediately&&o(c)});if(s.cancel=n,typeof t.timeout=="number"){let o=$i(s,{milliseconds:t.timeout});return o.cancel=()=>{n(),o.clear()},o}return s}function Xe(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=Rh(r,e,t),s=n.then(o=>o[0]);return s.cancel=n.cancel,s}function Wi(r,e){let t,n=function(){let s=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(s,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var so=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}},Gt=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"};var io=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function Bh(r){return r.reason}async function vt(r,e,t){if(e==null)return r;let n=t?.translateError??Bh;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let s;try{return await Promise.race([r,new Promise((o,i)=>{s=()=>{i(n(e))},e.addEventListener("abort",s)})])}finally{s!=null&&e.removeEventListener("abort",s)}}var ao=class{deferred;signal;constructor(e){this.signal=e,this.deferred=Fe(),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 Oh(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var co=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=Oh(),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 ao(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 vt(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 uo=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=Wi(this.emitEmpty.bind(this),1),this.emitIdle=Wi(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 so;let n=new co(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(t).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let o=0;o<this.queue.length;o++)if(this.queue[o]===n){this.queue.splice(o,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s})}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 Xe(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await Xe(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Xe(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=St({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},s=c=>{c.detail!=null&&t.push(c.detail)},o=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new je("Queue aborted"))};this.addEventListener("completed",s),this.addEventListener("failure",o),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",s),this.removeEventListener("failure",o),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var Ph=Math.pow(2,20)*4,lo=class extends _e{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;onDrainPromise;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??Ph,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.onDrainPromise?.resolve()};this.addEventListener("drain",t);let n=s=>{this.onDrainPromise?.reject(s.error??new io)};this.addEventListener("close",n)}get readBufferLength(){return this.readBuffer.byteLength}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),vt(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let e=St(),t=o=>{e.push(o.data)};this.addEventListener("message",t);let n=o=>{e.end(o.error)};this.addEventListener("close",n);let s=()=>{e.end()};this.addEventListener("remoteCloseWrite",s);try{yield*e}finally{this.removeEventListener("message",t),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",s)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new ft(`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 wn(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new ft("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 ft("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 ft(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.append(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}unshift(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new ft(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.prepend(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(e){if(e.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(e),this.dispatchReadBuffer()}}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="message"&&this.readBuffer.byteLength>0&&queueMicrotask(()=>{this.dispatchReadBuffer()})}onRemoteReset(){this.log("remote reset"),this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.readBuffer.byteLength===0&&(this.readStatus="closed");let e=new hn;this.dispatchEvent(new xn(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 er))}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 s=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(s===0){e=!1;break}let o=this.writeBuffer.sublist(0,s),i=new J(o);this.writeBuffer.consume(o.byteLength);let a=this.sendData(o);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 bn(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 Dr(`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 Dr(`Write buffer length of ${this.writeBuffer.byteLength} exceeded limit of ${this.maxWriteBufferLength}, write status is ${this.writeStatus}`))}onMuxerNeedsDrain(){this.writableNeedsDrain=!0}onMuxerDrain(){this.safeDispatchEvent("drain")}};var fo=class extends lo{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 Xe(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 Xe(this,"drain",{...e,rejectionEvents:["close"]})),await this.sendClose(e),this.onTransportClosed())}};function ho(r){let e=new globalThis.AbortController;function t(){let o=r.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();e.abort(o);for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}for(let o of r){if(o?.aborted===!0){t();break}o?.addEventListener!=null&&o.addEventListener("abort",t)}function n(){for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",t)}let s=e.signal;return s.clear=n,s}var Gi=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=Fe(),this.haveNext=Fe()}[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=Fe(),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=Fe(),await vt(this.readNext.promise,t?.signal,t)}};function Ku(){return new Gi}function Nh(r){return r[Symbol.asyncIterator]!=null}async function Uh(r,e,t){try{await Promise.all(r.map(async n=>{for await(let s of n)await e.push(s,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*kh(r){let e=new AbortController,t=Ku();Uh(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*Mh(r){for(let e of r)yield*e}function Kh(...r){let e=[];for(let t of r)Nh(t)||e.push(t);return e.length===r.length?Mh(e):kh(r)}var qu=Kh;function Vu(r,...e){if(r==null)throw new Error("Empty pipeline");if(Yi(r)){let n=r;r=()=>n.source}else if(Hu(r)||Fu(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&Yi(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++)Yi(t[n])&&(t[n]=Vh(t[n]));return qh(...t)}var qh=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},Fu=r=>r?.[Symbol.asyncIterator]!=null,Hu=r=>r?.[Symbol.iterator]!=null,Yi=r=>r==null?!1:r.sink!=null&&r.source!=null,Vh=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=St({objectMode:!0});t.then(()=>{n.end()},i=>{n.end(i)});let s,o=r.source;if(Fu(o))s=async function*(){yield*o,n.end()};else if(Hu(o))s=function*(){yield*o,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return qu(n,s())}return r.source};var Fh=4194304,po=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 Hh(r){return typeof r?.closeRead=="function"}function zh(r){return typeof r?.close=="function"}function Zi(r){return Hh(r)?r.remoteWriteStatus!=="writable"&&r.readBufferLength===0:zh(r)?r.status!=="open":!1}function $h(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function Wh(r,e){let t=e?.maxBufferSize??Fh,n=new J,s,o=!1;if(!$h(r))throw new ae("Argument should be a Stream or a Multiaddr");let i=u=>{if(n.append(u.data),n.byteLength>t){let f=n.byteLength;n.consume(n.byteLength),s?.reject(new Error(`Read buffer overflow - ${f} > ${t}`))}s?.resolve()};r.addEventListener("message",i);let a=u=>{u.error!=null?s?.reject(u.error):s?.resolve()};r.addEventListener("close",a);let c=()=>{s?.resolve()};r.addEventListener("remoteCloseWrite",c);let l={readBuffer:n,async read(u){if(o===!0)throw new po("Stream was unwrapped");if(Zi(r)){if(n.byteLength===0&&u?.bytes==null)return null;if(u?.bytes!=null&&n.byteLength<u.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,u.bytes),new Gt(`Unexpected EOF - stream closed after reading ${n.byteLength}/${u.bytes} bytes`)}let f=u?.bytes??1;for(s=Promise.withResolvers();;){if(n.byteLength>=f){s.resolve();break}if(await vt(s.promise,u?.signal),Zi(r)){if(n.byteLength===0&&u?.bytes==null)return null;break}s=Promise.withResolvers()}let h=u?.bytes??n.byteLength;if(n.byteLength<h){if(Zi(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,h),new Gt(`Unexpected EOF - stream closed while reading ${n.byteLength}/${h} bytes`);return l.read(u)}let p=n.sublist(0,h);return n.consume(h),p},async write(u,f){if(o===!0)throw new po("Stream was unwrapped");r.send(u)||await Xe(r,"drain",{signal:f?.signal,rejectionEvents:["close"]})},unwrap(){return o||(o=!0,r.removeEventListener("message",i),r.removeEventListener("close",a),r.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.push(n))),r}};return l}function Gh(r,e={}){let t=Wh(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=De(e.maxDataLength));let n=e?.lengthDecoder??$r,s=e?.lengthEncoder??yr;return{async read(i){let a=-1,c=new J;for(;;){let u=await t.read({...i,bytes:1});if(u==null)break;c.append(u);try{a=n(c)}catch(f){if(f instanceof RangeError)continue;throw f}if(a<0)throw new 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 l=await t.read({...i,bytes:a});if(l==null)throw r.log.error("tried to read %d bytes but the stream closed",a),new Gt(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(l.byteLength!==a)throw r.log.error("read %d/%d bytes before the stream closed",l.byteLength,a),new Gt(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(i,a){await t.write(new J(s(i.byteLength),i),a)},async writeV(i,a){let c=new J(...i.flatMap(l=>[s(l.byteLength),l]));await t.write(c,a)},unwrap(){return t.unwrap()}}}function _t(r,e){let t=Gh(r,e),n={read:async(s,o)=>{let i=await t.read(o);return s.decode(i)},write:async(s,o,i)=>{await t.write(o.encode(s),i)},writeV:async(s,o,i)=>{await t.writeV(s.map(a=>o.encode(a)),i)},pb:s=>({read:async o=>n.read(s,o),write:async(o,i)=>n.write(o,s,i),writeV:async(o,i)=>n.writeV(o,s,i),unwrap:()=>n}),unwrap:()=>t.unwrap()};return n}function Yh(r){return r?.addEventListener!=null}function Zh(r){let e=St(),t,n=i=>{e.push(i.data)},s=()=>{e.end(),r.removeEventListener("message",n),r.removeEventListener("close",o),r.removeEventListener("remoteCloseWrite",s)},o=i=>{e.end(i.error),i.error!=null&&t?.reject(i.error),r.removeEventListener("message",n),r.removeEventListener("close",o),r.removeEventListener("remoteCloseWrite",s)};return r.addEventListener("message",n),r.addEventListener("close",o,{once:!0}),r.addEventListener("remoteCloseWrite",s,{once:!0}),{source:e,async sink(i){async function*a(){yield*i}let c=a();for(;;){t=Promise.withResolvers();let{done:l,value:u}=await Promise.race([c.next(),t.promise]);if(r.writeStatus==="closing"||r.writeStatus==="closed"||(u!=null&&(r.send(u)||await Promise.race([Xe(r,"drain",{rejectionEvents:["close"]})])),l===!0))break}await r.close()}}}function zu(...r){let e=r.map(t=>Yh(t)?Zh(t):t);return Vu(...e)}var Ir=class extends uo{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)}}),$u=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 s=n.match(e);s!==!1&&(t==null||s.length<t.length)&&(t=s)}return t??!1}}),G=(...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(s){if(s==null)return!1;let o=s.getComponents();for(let i of r){let a=i.match(o);if(a===!1)return!1;o=a}return o}function t(s){return e(s)!==!1}function n(s){let o=e(s);return o===!1?!1:o.length===0}return{matchers:r,matches:t,exactMatch:n}}var Xh=B(421),oE=j(Xh),yo=B(54),go=B(55),bo=B(56),ea=B(53),sE=j(yo,H(B(421))),iE=j(go,H(B(421))),aE=j(bo,H(B(421))),cE=j(Ee(ea,bo,yo,go),H(B(421))),Wu=G(B(4),H(B(43))),Gu=G(H(B(42)),B(41),H(B(43))),ta=Ee(Wu,Gu),Yt=Ee(ta,ea,yo,go,bo),uE=j(Ee(ta,G(Ee(ea,bo,yo,go),H(B(421))))),lE=j(Wu),fE=j(Gu),dE=j(ta),ra=G(Yt,B(6)),on=G(Yt,B(273)),hE=j(G(ra,H(B(421)))),pE=j(on),na=G(on,X(460),H(B(421))),wo=G(on,X(461),H(B(421))),jh=Ee(na,wo),mE=j(na),yE=j(wo),Ji=Ee(Yt,ra,on,na,wo),Yu=Ee(G(Ji,X(477),H(B(421)))),gE=j(Yu),Zu=Ee(G(Ji,X(478),H(B(421))),G(Ji,X(448),H(B(449)),X(477),H(B(421)))),bE=j(Zu),Xu=G(on,X(280),H(B(466)),H(B(466)),H(B(421))),wE=j(Xu),ju=G(wo,X(465),H(B(466)),H(B(466)),H(B(421))),xE=j(ju),mo=Ee(Yu,Zu,G(ra,H(B(421))),G(jh,H(B(421))),G(Yt,H(B(421))),Xu,ju,B(421)),Qu=j(mo),Qh=G(H(mo),X(290),$u(X(281)),H(B(421))),Zt=j(Qh),Jh=Ee(G(mo,X(290),X(281),H(B(421))),G(mo,X(281),H(B(421))),G(X(281),H(B(421)))),EE=j(Jh),ep=Ee(G(Yt,B(6),X(480),H(B(421))),G(Yt,X(480),H(B(421)))),SE=j(ep),tp=G(Yt,Ee(G(B(6,"443"),X(480)),G(B(6),X(443)),G(B(6),X(448),X(480)),G(X(448),X(480)),X(448),X(443)),H(B(421))),vE=j(tp),rp=Ee(G(B(777),H(B(421)))),_E=j(rp),np=Ee(G(B(400),H(B(421)))),AE=j(np);var oa=1e3,Ju=60*oa,el=15,tl=120*Ju,rl=1,xo=5e3,nl=100,sa="circuit-relay-source",sn=`${ba}-circuit-relay`,ol=2*Ju,sl=BigInt(1<<17),ke="/libp2p/circuit/relay/0.2.0/hop",Xt="/libp2p/circuit/relay/0.2.0/stop",il=30*oa,DE=30*oa,an=300,al=4096,cl=.001;var Z;(function(r){let e;(function(a){a.RESERVE="RESERVE",a.CONNECT="CONNECT",a.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(a){a[a.RESERVE=0]="RESERVE",a[a.CONNECT=1]="CONNECT",a[a.STATUS=2]="STATUS"})(t||(t={})),(function(a){a.codec=()=>Kt(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Be((a,c,l={})=>{l.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),r.Type.codec().encode(a.type,c)),a.peer!=null&&(c.uint32(18),At.codec().encode(a.peer,c)),a.reservation!=null&&(c.uint32(26),cn.codec().encode(a.reservation,c)),a.limit!=null&&(c.uint32(34),Tt.codec().encode(a.limit,c)),a.status!=null&&(c.uint32(40),q.codec().encode(a.status,c)),l.lengthDelimited!==!1&&c.ldelim()},(a,c,l={})=>{let u={},f=c==null?a.len:a.pos+c;for(;a.pos<f;){let h=a.uint32();switch(h>>>3){case 1:{u.type=r.Type.codec().decode(a);break}case 2:{u.peer=At.codec().decode(a,a.uint32(),{limits:l.limits?.peer});break}case 3:{u.reservation=cn.codec().decode(a,a.uint32(),{limits:l.limits?.reservation});break}case 4:{u.limit=Tt.codec().decode(a,a.uint32(),{limits:l.limits?.limit});break}case 5:{u.status=q.codec().decode(a);break}default:{a.skipType(h&7);break}}}return u},function*(a,c,l,u={}){let f=c==null?a.len:a.pos+c;for(;a.pos<f;){let h=a.uint32();switch(h>>>3){case 1:{yield{field:`${l}.type`,value:r.Type.codec().decode(a)};break}case 2:{yield*At.codec().stream(a,a.uint32(),`${l}.peer`,{limits:u.limits?.peer});break}case 3:{yield*cn.codec().stream(a,a.uint32(),`${l}.reservation`,{limits:u.limits?.reservation});break}case 4:{yield*Tt.codec().stream(a,a.uint32(),`${l}.limit`,{limits:u.limits?.limit});break}case 5:{yield{field:`${l}.status`,value:q.codec().decode(a)};break}default:{a.skipType(h&7);break}}}})),n);function s(a){return Le(a,r.codec())}r.encode=s;function o(a,c){return Ce(a,r.codec(),c)}r.decode=o;function i(a,c){return Re(a,r.codec(),c)}r.stream=i})(Z||(Z={}));var Ne;(function(r){let e;(function(a){a.CONNECT="CONNECT",a.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(a){a[a.CONNECT=0]="CONNECT",a[a.STATUS=1]="STATUS"})(t||(t={})),(function(a){a.codec=()=>Kt(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Be((a,c,l={})=>{l.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),r.Type.codec().encode(a.type,c)),a.peer!=null&&(c.uint32(18),At.codec().encode(a.peer,c)),a.limit!=null&&(c.uint32(26),Tt.codec().encode(a.limit,c)),a.status!=null&&(c.uint32(32),q.codec().encode(a.status,c)),l.lengthDelimited!==!1&&c.ldelim()},(a,c,l={})=>{let u={},f=c==null?a.len:a.pos+c;for(;a.pos<f;){let h=a.uint32();switch(h>>>3){case 1:{u.type=r.Type.codec().decode(a);break}case 2:{u.peer=At.codec().decode(a,a.uint32(),{limits:l.limits?.peer});break}case 3:{u.limit=Tt.codec().decode(a,a.uint32(),{limits:l.limits?.limit});break}case 4:{u.status=q.codec().decode(a);break}default:{a.skipType(h&7);break}}}return u},function*(a,c,l,u={}){let f=c==null?a.len:a.pos+c;for(;a.pos<f;){let h=a.uint32();switch(h>>>3){case 1:{yield{field:`${l}.type`,value:r.Type.codec().decode(a)};break}case 2:{yield*At.codec().stream(a,a.uint32(),`${l}.peer`,{limits:u.limits?.peer});break}case 3:{yield*Tt.codec().stream(a,a.uint32(),`${l}.limit`,{limits:u.limits?.limit});break}case 4:{yield{field:`${l}.status`,value:q.codec().decode(a)};break}default:{a.skipType(h&7);break}}}})),n);function s(a){return Le(a,r.codec())}r.encode=s;function o(a,c){return Ce(a,r.codec(),c)}r.decode=o;function i(a,c){return Re(a,r.codec(),c)}r.stream=i})(Ne||(Ne={}));var At;(function(r){let e;r.codec=()=>(e==null&&(e=Be((o,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),o.id!=null&&o.id.byteLength>0&&(i.uint32(10),i.bytes(o.id)),o.addrs!=null&&o.addrs.length>0)for(let c of o.addrs)i.uint32(18),i.bytes(c);a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={id:re(0),addrs:[]},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.id=o.bytes();break}case 2:{if(a.limits?.addrs!=null&&c.addrs.length===a.limits.addrs)throw new qt('Decode error - repeated field "addrs" had too many elements');c.addrs.push(o.bytes());break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l={addrs:0},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let f=o.uint32();switch(f>>>3){case 1:{yield{field:`${a}.id`,value:o.bytes()};break}case 2:{if(c.limits?.addrs!=null&&l.addrs===c.limits.addrs)throw new qt('Streaming decode error - repeated field "addrs" had too many elements');yield{field:`${a}.addrs[]`,index:l.addrs,value:o.bytes()},l.addrs++;break}default:{o.skipType(f&7);break}}}})),e);function t(o){return Le(o,r.codec())}r.encode=t;function n(o,i){return Ce(o,r.codec(),i)}r.decode=n;function s(o,i){return Re(o,r.codec(),i)}r.stream=s})(At||(At={}));var cn;(function(r){let e;r.codec=()=>(e==null&&(e=Be((o,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),o.expire!=null&&o.expire!==0n&&(i.uint32(8),i.uint64(o.expire)),o.addrs!=null&&o.addrs.length>0)for(let c of o.addrs)i.uint32(18),i.bytes(c);o.voucher!=null&&(i.uint32(26),un.codec().encode(o.voucher,i)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={expire:0n,addrs:[]},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.expire=o.uint64();break}case 2:{if(a.limits?.addrs!=null&&c.addrs.length===a.limits.addrs)throw new qt('Decode error - repeated field "addrs" had too many elements');c.addrs.push(o.bytes());break}case 3:{c.voucher=un.codec().decode(o,o.uint32(),{limits:a.limits?.voucher});break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l={addrs:0},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let f=o.uint32();switch(f>>>3){case 1:{yield{field:`${a}.expire`,value:o.uint64()};break}case 2:{if(c.limits?.addrs!=null&&l.addrs===c.limits.addrs)throw new qt('Streaming decode error - repeated field "addrs" had too many elements');yield{field:`${a}.addrs[]`,index:l.addrs,value:o.bytes()},l.addrs++;break}case 3:{yield*un.codec().stream(o,o.uint32(),`${a}.voucher`,{limits:c.limits?.voucher});break}default:{o.skipType(f&7);break}}}})),e);function t(o){return Le(o,r.codec())}r.encode=t;function n(o,i){return Ce(o,r.codec(),i)}r.decode=n;function s(o,i){return Re(o,r.codec(),i)}r.stream=s})(cn||(cn={}));var Tt;(function(r){let e;r.codec=()=>(e==null&&(e=Be((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.duration!=null&&(i.uint32(8),i.uint32(o.duration)),o.data!=null&&(i.uint32(16),i.uint64(o.data)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.duration=o.uint32();break}case 2:{c.data=o.uint64();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{yield{field:`${a}.duration`,value:o.uint32()};break}case 2:{yield{field:`${a}.data`,value:o.uint64()};break}default:{o.skipType(u&7);break}}}})),e);function t(o){return Le(o,r.codec())}r.encode=t;function n(o,i){return Ce(o,r.codec(),i)}r.decode=n;function s(o,i){return Re(o,r.codec(),i)}r.stream=s})(Tt||(Tt={}));var q;(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"})(q||(q={}));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=()=>Kt(ia)})(q||(q={}));var jt;(function(r){let e;r.codec=()=>(e==null&&(e=Be((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.relay!=null&&o.relay.byteLength>0&&(i.uint32(10),i.bytes(o.relay)),o.peer!=null&&o.peer.byteLength>0&&(i.uint32(18),i.bytes(o.peer)),o.expiration!=null&&o.expiration!==0n&&(i.uint32(24),i.uint64(o.expiration)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={relay:re(0),peer:re(0),expiration:0n},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.relay=o.bytes();break}case 2:{c.peer=o.bytes();break}case 3:{c.expiration=o.uint64();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{yield{field:`${a}.relay`,value:o.bytes()};break}case 2:{yield{field:`${a}.peer`,value:o.bytes()};break}case 3:{yield{field:`${a}.expiration`,value:o.uint64()};break}default:{o.skipType(u&7);break}}}})),e);function t(o){return Le(o,r.codec())}r.encode=t;function n(o,i){return Ce(o,r.codec(),i)}r.decode=n;function s(o,i){return Re(o,r.codec(),i)}r.stream=s})(jt||(jt={}));var un;(function(r){let e;r.codec=()=>(e==null&&(e=Be((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.publicKey!=null&&o.publicKey.byteLength>0&&(i.uint32(10),i.bytes(o.publicKey)),o.payloadType!=null&&o.payloadType.byteLength>0&&(i.uint32(18),i.bytes(o.payloadType)),o.payload!=null&&(i.uint32(26),jt.codec().encode(o.payload,i)),o.signature!=null&&o.signature.byteLength>0&&(i.uint32(42),i.bytes(o.signature)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={publicKey:re(0),payloadType:re(0),signature:re(0)},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.publicKey=o.bytes();break}case 2:{c.payloadType=o.bytes();break}case 3:{c.payload=jt.codec().decode(o,o.uint32(),{limits:a.limits?.payload});break}case 5:{c.signature=o.bytes();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{yield{field:`${a}.publicKey`,value:o.bytes()};break}case 2:{yield{field:`${a}.payloadType`,value:o.bytes()};break}case 3:{yield*jt.codec().stream(o,o.uint32(),`${a}.payload`,{limits:c.limits?.payload});break}case 5:{yield{field:`${a}.signature`,value:o.bytes()};break}default:{o.skipType(u&7);break}}}})),e);function t(o){return Le(o,r.codec())}r.encode=t;function n(o,i){return Ce(o,r.codec(),i)}r.decode=n;function s(o,i){return Re(o,r.codec(),i)}r.stream=s})(un||(un={}));var Eo=class extends Error{constructor(e="Transfer limit error"){super(e),this.name="TransferLimitError"}},So=class extends Error{constructor(e="Duration limit error"){super(e),this.name="DurationLimitError"}},ln=class extends Error{static name="HadEnoughRelaysError";name="HadEnoughRelaysError"},vo=class extends Error{static name="DoubleRelayError";name="DoubleRelayError"},_o=class extends Error{static name="RelayQueueFullError";name="RelayQueueFullError"};function ul(r,e,t){let n=e.remaining,s=o=>{let i=BigInt(o.data.byteLength);e.remaining-=i,e.remaining<0&&r.abort(new Eo(`data limit of ${n} bytes exceeded`))};r.addEventListener("message",s)}function ll(r,e,t,n,s){function o(u){r.abort(u),e.abort(u)}let i=[t,n.signal];if(n.limit?.duration!=null){s.log("limiting relayed connection duration to %dms",n.limit.duration);let u=AbortSignal.timeout(n.limit.duration);i.push(u)}let a=ho(i);let c;n.limit?.data!=null&&(c={remaining:n.limit.data});let l=()=>{let u;t.aborted?u=t.reason:u=new So(`duration limit of ${n.limit?.duration} ms exceeded`),o(u)};a.addEventListener("abort",l,{once:!0}),c!=null&&(ul(e,c,s),ul(r,c,s)),zu(r,e,r).catch(u=>{o(u)}).finally(()=>{a.clear()})}function aa(r){let e=r*BigInt(1e3),t=new Date().getTime();return Number(e-BigInt(t))}var fn=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}},Ao=j(G(Qu.matchers[0],X(290))),To=j(X(290));function Io(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),s=n.value;return n.done===!0||s==null?{done:!0,value:void 0}:{done:!1,value:e(s)}}};return t}var It=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 Io(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 Io(this.map.values(),e=>e.key)}values(){return Io(this.map.values(),e=>e.value)}get size(){return this.map.size}};var Do=class{filter;constructor(e,t){this.filter=Ar(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 Do(r,e)}var ua=class extends It{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 It,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 fl(r,e){let t=new fa(e?.errorMessage,e?.errorCode,e?.errorName),n=new AbortController,s=()=>{n.abort(t)},o=AbortSignal.timeout(r);o.addEventListener("abort",s);let i=n.signal;return i.reset=a=>{o?.removeEventListener("abort",s),o=AbortSignal.timeout(a??r),o.addEventListener("abort",()=>{n.abort(t)})},i.clear=()=>{o?.removeEventListener("abort",s),o=void 0},i}var Co=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??el,this.applyDefaultLimit=t.applyDefaultLimit!==!1,this.reservationTtl=t.reservationTtl??tl,this.defaultDurationLimit=t.defaultDurationLimit??ol,this.defaultDataLimit=t.defaultDataLimit??sl,this.reservations=la({metrics:e.metrics,name:"libp2p_circuit_relay_server_reservations_total"})}reserve(e,t,n){let s=this.reservations.get(e);if(this.reservations.size>=this.maxReservations&&s==null)return{status:q.RESERVATION_REFUSED};let o=new Date(Date.now()+this.reservationTtl),i;return this.applyDefaultLimit&&(i=n??{data:this.defaultDataLimit,duration:this.defaultDurationLimit}),s!=null?(this.log("refreshing reservation for client %p",e),s.signal.reset(this.reservationTtl)):(this.log("creating new reservation for client %p",e),s={addr:t,expiry:o,limit:i,signal:fl(this.reservationTtl)}),this.reservations.set(e,s),s.signal.addEventListener("abort",()=>{this.reservations.delete(e)}),{status:q.OK,expire:Math.round(o.getTime()/1e3)}}removeReservation(e){this.reservations.delete(e)}get(e){return this.reservations.get(e)}clear(){this.reservations.clear()}};var Lo=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 jt.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 op={maxOutboundStopStreams:an},Ro=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??il,this.maxInboundHopStreams=t.maxInboundHopStreams,this.maxOutboundHopStreams=t.maxOutboundHopStreams,this.maxOutboundStopStreams=t.maxOutboundStopStreams??op.maxOutboundStopStreams,this.reservationStore=new Co(e,t.reservations),this.shutdownController=new AbortController,this.shutdownController.signal,this.onHop=this.onHop.bind(this)}[Symbol.toStringTag]="@libp2p/circuit-relay-v2-server";isStarted(){return this.started}async start(){this.started||(await this.components.registrar.handle(ke,this.onHop,{maxInboundStreams:this.maxInboundHopStreams,maxOutboundStreams:this.maxOutboundHopStreams,runOnLimitedConnection:!0}),this.started=!0)}async stop(){this.reservationStore.clear(),this.shutdownController.abort(),await this.components.registrar.unhandle(ke),this.started=!1}async onHop(e,t){this.log("received circuit v2 hop protocol stream from %p",t.remotePeer);let n=AbortSignal.timeout(this.hopTimeout);let s={signal:n},o=_t(e);try{let i=await o.pb(Z).read(s);if(i?.type==null)throw new Error("request was invalid, could not read from stream");this.log("received",i.type),await this.handleHopProtocol({connection:t,stream:o,request:i},s)}catch(i){this.log.error("error while handling hop - %e",i),await o.pb(Z).write({type:Z.Type.STATUS,status:q.MALFORMED_MESSAGE},s),e.abort(i)}}async handleHopProtocol({stream:e,request:t,connection:n},s){switch(this.log("received hop message"),t.type){case Z.Type.RESERVE:await this.handleReserve({stream:e,request:t,connection:n},s);break;case Z.Type.CONNECT:await this.handleConnect({stream:e,request:t,connection:n},s);break;default:this.log.error("invalid hop request type %s via peer %p",t.type,n.remotePeer),await e.pb(Z).write({type:Z.Type.STATUS,status:q.UNEXPECTED_MESSAGE})}}async handleReserve({stream:e,connection:t},n){let s=e.pb(Z);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 s.write({type:Z.Type.STATUS,status:q.PERMISSION_DENIED},n);return}if(await this.components.connectionGater.denyInboundRelayReservation?.(t.remotePeer)===!0){this.log.error("reservation for %p denied by connection gater",t.remotePeer),await s.write({type:Z.Type.STATUS,status:q.PERMISSION_DENIED},n);return}let o=this.reservationStore.reserve(t.remotePeer,t.remoteAddr);try{if(o.status!==q.OK){await s.write({type:Z.Type.STATUS,status:o.status},n);return}if(o.expire!=null){let i=o.expire*1e3-Date.now();await this.components.peerStore.merge(t.remotePeer,{tags:{[sa]:{value:1,ttl:i}}},n)}await s.write({type:Z.Type.STATUS,status:q.OK,reservation:await this.makeReservation(t.remotePeer,BigInt(o.expire??0)),limit:this.reservationStore.get(t.remotePeer)?.limit},n),this.log("sent confirmation response to %s",t.remotePeer),await s.unwrap().unwrap().close(n)}catch(i){this.log.error("failed to send confirmation response to %p - %e",t.remotePeer,i),this.reservationStore.removeReservation(t.remotePeer);try{await this.components.peerStore.merge(t.remotePeer,{tags:{[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 o of this.components.addressManager.getAddresses())o.toString().includes("/p2p-circuit")||n.push(o.bytes);let s=await en.seal(new Lo({peer:e,relay:this.components.peerId,expiration:t}),this.components.privateKey);return{addrs:n,expire:t,voucher:{publicKey:We(s.publicKey),payloadType:s.payloadType,payload:{peer:e.toMultihash().bytes,relay:this.components.peerId.toMultihash().bytes,expiration:t},signature:s.signature}}}async handleConnect({stream:e,request:t,connection:n},s){let o=e.pb(Z);if(Zt.matches(n.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",n.remotePeer),await o.write({type:Z.Type.STATUS,status:q.PERMISSION_DENIED},s);return}this.log("hop connect request from %p",n.remotePeer);let i;try{if(t.peer==null)throw this.log.error("no peer info in hop connect request"),new Error("no peer info in request");t.peer.addrs.forEach(Pe),i=xr($e(t.peer.id))}catch(f){this.log.error("invalid hop connect request via peer %p - %e",n.remotePeer,f),await o.write({type:Z.Type.STATUS,status:q.MALFORMED_MESSAGE},s);return}let a=this.reservationStore.get(i);if(a==null){this.log.error("hop connect denied for destination peer %p not having a reservation for %p with status %s",i,n.remotePeer,q.NO_RESERVATION),await o.write({type:Z.Type.STATUS,status:q.NO_RESERVATION},s);return}if(await this.components.connectionGater.denyOutboundRelayedConnection?.(n.remotePeer,i)===!0){this.log.error("hop connect for %p to %p denied by connection gater",n.remotePeer,i),await o.write({type:Z.Type.STATUS,status:q.PERMISSION_DENIED},s);return}let c=this.components.connectionManager.getConnections(i);if(c.length===0){this.log("hop connect denied for destination peer %p not having a connection for %p as there is no destination connection",i,n.remotePeer),await o.write({type:Z.Type.STATUS,status:q.NO_RESERVATION},s);return}let l=c[0],u=await this.stopHop({connection:l,request:{type:Ne.Type.CONNECT,peer:{id:n.remotePeer.toMultihash().bytes,addrs:[]},limit:a?.limit}},s);if(u==null){this.log.error("failed to open stream to destination peer %p",l?.remotePeer),await o.write({type:Z.Type.STATUS,status:q.CONNECTION_FAILED},s);return}await o.write({type:Z.Type.STATUS,status:q.OK,limit:a?.limit},s),this.log("connection from %p to %p established - merging streams",n.remotePeer,i),ll(e.unwrap(),u,this.shutdownController.signal,a,{log:this.log})}async stopHop({connection:e,request:t},n){this.log("starting circuit relay v2 stop request to %s",e.remotePeer);let s=await e.newStream(Xt,{maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0,...n}),o=_t(s),i=o.pb(Ne);await i.write(t,n);let a;try{a=await i.read(n)}catch(c){this.log.error("error parsing stop message response from %p - %e",e.remotePeer,c)}if(a==null){this.log.error("could not read response from %p",e.remotePeer),await s.close(n);return}if(a.status===q.OK)return this.log("stop request to %p was successful",e.remotePeer),o.unwrap();this.log("stop request failed with code %d",a.status),await s.close(n)}get reservations(){return this.reservationStore.reservations}};var Dt=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var Bo=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(ke,{filter:this.filter,onConnect:e=>{this.log.trace("discovered relay %p queue (length: %d, active %d)",e,this.queue?.size,this.queue?.running),this.safeDispatchEvent("relay:discover",{detail:e})}}),this.started=!0}stop(){this.topologyId!=null&&this.components.registrar.unregister(this.topologyId),this.running&&this.stopDiscovery(),this.started=!1}startDiscovery(){this.running||(this.log("start discovery"),this.running=!0,this.discoveryController=new AbortController,this.discoveryController.signal,this.components.events.addEventListener("peer:discovery",this.onPeer),Promise.resolve().then(async()=>{this.log("searching peer store for relays");let e=await this.components.peerStore.all({filters:[n=>n.protocols.includes(ke)],orders:[()=>Math.random()<.5?1:-1,(n,s)=>{let o=dl(n),i=dl(s);return o>i?-1:i>o?1:0}]});for(let n of e)this.log.trace("found relay peer %p in peer store",n.id),this.safeDispatchEvent("relay:discover",{detail:n.id});this.log("found %d relay peers in peer store",e.length);let t=this.queue=new Ir({concurrency:5});this.log("start random walk");for await(let n of this.components.randomWalk.walk({signal:this.discoveryController.signal})){if(this.log.trace("found random peer %p",n.id),t.has(n.id)){this.log.trace("random peer %p was already in queue",n.id);continue}if(this.components.connectionManager.getConnections(n.id)?.length>0){this.log.trace("random peer %p was already connected",n.id);continue}if(!await this.components.connectionManager.isDialable(n.multiaddrs)){this.log.trace("random peer %p was not dialable",n.id,n.multiaddrs.map(s=>s.toString()));continue}t.queued>10&&(this.log.trace("wait for space in queue for %p",n.id),await t.onSizeLessThan(10,{signal:this.discoveryController.signal})),this.log("adding random peer %p to dial queue (length: %d, active %d)",n.id,t.size,t.running),t.add(this.dialPeer,{peerId:n.id,signal:this.discoveryController.signal}).catch(s=>{this.log.error("error opening connection to random peer %p - %e",n.id,s)})}this.log("stop random walk"),await t.onIdle()}).catch(e=>{this.discoveryController.signal.aborted||this.log.error("failed when finding relays on the network - %e",e)}))}stopDiscovery(){this.log("stop discovery"),this.running=!1,this.discoveryController?.abort(),this.queue?.clear(),this.components.events.removeEventListener("peer:discovery",this.onPeer)}onPeer(e){this.log.trace("maybe dialing discovered peer %p",e.detail.id),this.maybeDialPeer(e).catch(t=>{this.log.trace("error dialing discovered peer %p - %e",e.detail.id,t)})}async maybeDialPeer(e){if(this.queue==null)return;let t=e.detail.id,n=e.detail.multiaddrs;if(this.queue.has(t)){this.log.trace("random peer %p was already in queue",t);return}if(this.components.connectionManager.getConnections(t)?.length>0){this.log.trace("random peer %p was already connected",t);return}if(!await this.components.connectionManager.isDialable(n)){this.log.trace("random peer %p was not dialable",t);return}this.queue?.add(this.dialPeer,{peerId:e.detail.id,signal:this.discoveryController.signal}).catch(s=>{this.log.error("error opening connection to discovered peer %p - %e",e.detail.id,s)})}async dialPeer({peerId:e,signal:t}){let n=ho([AbortSignal.timeout(5e3),t]);try{await this.components.connectionManager.openConnection(e,{signal:n})}finally{n.clear()}}};function dl(r){let e=r.metadata.get("last-dial-success");return e==null?0:new Date($(e)).getTime()}var ha=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??xo,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(To.exactMatch(e))this.log("searching for circuit relay servers"),this.reservationId=this.reservationStore.reserveRelay();else if(Ao.exactMatch(e)){this.log("listen on specific relay server %a",e);let t=AbortSignal.timeout(this.listenTimeout);let n=e.decapsulate("/p2p-circuit"),s=await this.connectionManager.openConnection(n,{signal:t});if(!this.reservationStore.hasReservation(s.remotePeer)){this.log("making reservation on peer %p",s.remotePeer);let o=await this.reservationStore.addRelay(s.remotePeer,"configured");this.addedRelay(o)}}else throw new Ct(`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=>Pe(t).encapsulate("/p2p-circuit")),this.listeningAddrs.forEach(t=>{this.addressManager.confirmObservedAddr(t,{type:"transport"})}),queueMicrotask(()=>{this.safeDispatchEvent("listening")})}};function hl(r){return new ha(r)}var pl="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var ml=(r=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)e+=pl[t[r]&63];return e};var sp=60*1e3*10,ip=60*1e3*5,ap=30*1e3,Oo=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 It,this.pendingReservations=[],this.maxReservationQueueLength=t?.maxReservationQueueLength??nl,this.reservationCompletionTimeout=t?.reservationCompletionTimeout??xo,this.started=!1,this.relayFilter=Ar(100),this.reserveQueue=new Ir({concurrency:t?.reservationConcurrency??rl,metricName:"libp2p_relay_reservation_queue",metrics:e.metrics}),this.events.addEventListener("connection:close",n=>{[...this.reservations.values()].find(o=>o.connection===n.detail.id)!=null&&this.#t(n.detail.remotePeer).catch(o=>{this.log("could not remove relay %p - %e",n.detail,o)})})}isStarted(){return this.started}start(){this.started=!0}afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>t.tags.has(sn)]});this.log("removing tag from %d old relays",e.length),await Promise.all(e.map(async t=>{await this.peerStore.merge(t.id,{tags:{[sn]:void 0}})})),this.log("redialing %d old relays",e.length),await Promise.all(e.map(async t=>this.addRelay(t.id,"discovered"))),this.#r()}).catch(e=>{this.log.error("failed to clean up and redial old relays during afterStart - %e",e)})}stop(){this.reserveQueue.clear(),this.reservations.forEach(({timeout:e})=>{clearTimeout(e)}),this.reservations.clear(),this.started=!1}reserveRelay(){let e=ml();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 Ct("Cannot use self as relay");if(this.reserveQueue.size>this.maxReservationQueueLength)throw new _o("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 Ct("The relay was previously invalid");return this.log.trace("try to reserve relay slot with %p",e),this.reserveQueue.add(async()=>{let s=Date.now();try{let o=this.reservations.get(e);if(o!=null){let d=this.connectionManager.getConnections(e),v=!1;if(d.length===0&&this.log("already have relay reservation with %p but we are no longer connected",e),d.map(w=>w.id).includes(o.connection)&&(this.log("already have relay reservation with %p and the original connection is still open",e),v=!0),v&&aa(o.reservation.expire)>sp)return this.log("already have relay reservation with %p but we are still connected and it does not expire soon",e),{relay:e,details:o};await this.#t(e)}if(t==="discovered"&&this.pendingReservations.length===0)throw new ln("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 vo("not creating reservation over relayed connection");let c=await this.#e(a,{signal:i}),l=aa(c.expire);this.log("created reservation on relay peer %p, expiry date is %s",e,new Date(Date.now()+l).toString());let u=Math.min(Math.max(l-ip,ap),Math.pow(2,31)-1),f=setTimeout(()=>{this.log("refresh reservation to relay %p",e),this.addRelay(e,t).catch(async d=>{this.log.error("could not refresh reservation to relay %p - %e",e,d),await this.#t(e)}).catch(d=>{this.log.error("could not remove expired reservation to relay %p - %e",e,d)})},u),h;if(t==="discovered"){let d=this.pendingReservations.pop();if(d==null)throw new ln("Made reservation on relay but did not need any more discovered relays");h={timeout:f,reservation:c,type:t,connection:a.id,id:d}}else h={timeout:f,reservation:c,type:t,connection:a.id};this.reservations.set(e,h),await this.peerStore.merge(e,{tags:{[sn]:{value:1,ttl:l}}}),this.#r();let p={relay:e,details:h};return this.safeDispatchEvent("relay:created-reservation",{detail:p}),p}catch(o){throw t==="discovered"&&o.name==="HadEnoughRelaysError"||this.log.error("could not reserve slot on %p after %dms - %e",e,Date.now()-s,o),(o.name==="DialError"||o.name==="UnsupportedProtocolError")&&this.relayFilter.add(e.toMultihash().bytes),this.#t(e).catch(i=>{this.log.error("could not remove reservation on %p after reserving slot failed - %e",e,i)}),o}},{peerId:e})}hasReservation(e){return this.reservations.has(e)}getReservation(e){return this.reservations.get(e)?.reservation}reservationCount(e){return e==null?this.reservations.size:[...this.reservations.values()].reduce((t,n)=>(n.type===e&&t++,t),0)}cancelReservations(){[...this.reservations.values()].forEach(e=>{clearTimeout(e.timeout)}),this.reservations.clear()}async#e(e,t){t.signal?.throwIfAborted(),this.log("requesting reservation from %p",e.remotePeer);let n=await e.newStream(ke,t),o=_t(n).pb(Z);this.log.trace("send RESERVE to %p",e.remotePeer),await o.write({type:Z.Type.RESERVE},t);let i;try{this.log.trace("reading response from %p",e.remotePeer),i=await o.read(t)}catch(c){throw n.abort(c),c}finally{n.status!=="closed"&&await n.close(t)}if(this.log.trace("read response %s",i.status),i.status===q.OK&&i.reservation!=null){let c=new Set;c.add(e.remoteAddr.toString());for(let l of i.reservation.addrs){let u=Pe(l);u.getComponents().find(f=>f.code===421)==null&&(u=u.encapsulate(`/p2p/${e.remotePeer}`)),u=Pe(u.toString().replace(`/p2p/${e.remotePeer}/p2p/${e.remotePeer}`,`/p2p/${e.remotePeer}`)),c.add(u.toString())}return i.reservation.addrs=[...c].map(l=>Pe(l).bytes),i.reservation}let a=`reservation failed with status ${i.status??"undefined"}`;throw this.log.error(a),new Error(a)}async#t(e){let 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:{[sn]: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=Ar(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 fo{stream;init;constructor(e){super({...e,direction:e.stream.direction}),this.init=e,this.stream=e.stream,this.stream.addEventListener("close",t=>{this.onTransportClosed(t.error)}),this.stream.addEventListener("remoteCloseWrite",t=>{this.onRemoteCloseWrite(),this.close().catch(n=>{this.abort(n)})}),this.stream.addEventListener("message",t=>{e.onDataRead?.(t.data),this.onData(t.data)}),this.stream.addEventListener("drain",()=>{this.safeDispatchEvent("drain")})}sendData(e){return this.init.onDataWrite?.(e),{sentBytes:e.byteLength,canSendMore:this.stream.send(e)}}async sendClose(e){await this.stream.close(e)}sendReset(){this.stream.abort(new Error("An error occurred"))}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}};function ma(r){return new pa(r)}var cp=r=>{if(r.peer==null)return!1;try{r.peer.addrs.forEach(Pe)}catch{return!1}return!0},yl={maxInboundStopStreams:an,maxOutboundStopStreams:an,stopTimeout:3e4},Po=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??yl.maxInboundStopStreams,this.maxOutboundStopStreams=t.maxOutboundStopStreams??yl.maxOutboundStopStreams,this.shutdownController=new AbortController,this.discovery=new Bo(e,{filter:t.discoveryFilter??ca(al,cl)}),this.discovery.addEventListener("relay:discover",n=>{this.reservationStore.addRelay(n.detail,"discovered").catch(s=>{s.name!=="HadEnoughRelaysError"&&s.name!=="RelayQueueFullError"&&this.log.error("could not add discovered relay %p - %e",n.detail,s)})}),this.reservationStore=new Oo(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(Xt,this.onStop,{maxInboundStreams:this.maxInboundStopStreams,maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0}),await xa(this.discovery,this.reservationStore),this.started=!0}async stop(){this.shutdownController.abort(),await Ea(this.discovery,this.reservationStore),await this.components.registrar.unhandle(Xt),this.started=!1}async dial(e,t){let n=e.toString().split("/p2p-circuit"),s=Pe(n[0]),o=Pe(n[n.length-1]),i=s.getComponents().find(p=>p.code===421)?.value,a=o.getComponents().find(p=>p.code===421)?.value;if(i==null||a==null){let p=`ircuit relay dial to ${e.toString()} failed as address did not have both relay and destination PeerIDs`;throw this.log.error(`c${p}`),new gn(`C${p}`)}let c=yi(i),l=yi(a),f=this.components.connectionManager.getConnections(c)[0];f==null?(await this.components.peerStore.merge(c,{multiaddrs:[s]}),t.onProgress?.(new Dt("circuit-relay:open-connection")),f=await this.components.connectionManager.openConnection(c,t)):t.onProgress?.(new Dt("circuit-relay:reuse-connection"));let h;try{t.onProgress?.(new Dt("circuit-relay:open-hop-stream")),h=await f.newStream(ke,t);let p=_t(h).pb(Z);t.onProgress?.(new Dt("circuit-relay:write-connect-message")),await p.write({type:Z.Type.CONNECT,peer:{id:l.toMultihash().bytes,addrs:[Pe(o).bytes]}},t),t.onProgress?.(new Dt("circuit-relay:read-connect-response"));let d=await p.read(t);if(d.status!==q.OK)throw new yn(`failed to connect via relay with status ${d?.status?.toString()??"undefined"}`);let v=new fn(d.limit),w=ma({stream:p.unwrap().unwrap(),remoteAddr:e,localAddr:s.encapsulate(`/p2p-circuit/p2p/${this.components.peerId.toString()}`),onDataRead:v.onData,onDataWrite:v.onData,log:h.log.newScope("circuit-relay:connection")}),y=await this.components.upgrader.upgradeOutbound(w,{...t,limits:v.getLimits()});return y.log("outbound relayed connection established to %p with limits %o, over connection %s",y.remotePeer,d.limit??"none",f.id),y}catch(p){throw this.log.error("circuit relay dial to destination %p via relay %p failed - %e",l,c,p),h?.abort(p),p}}createListener(e){return hl({peerId:this.components.peerId,connectionManager:this.components.connectionManager,addressManager:this.components.addressManager,reservationStore:this.reservationStore,logger:this.components.logger})}listenFilter(e){return e=Array.isArray(e)?e:[e],e.filter(t=>Ao.exactMatch(t)||To.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 - %e",f)}let s=_t(e).pb(Ne),o=await s.read({signal:n});if(this.log("new circuit relay v2 stop stream from %p with type %s",t.remotePeer,o.type),o?.type===void 0){this.log.error("type was missing from circuit v2 stop protocol request from %s",t.remotePeer),await s.write({type:Ne.Type.STATUS,status:q.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}if(o.type!==Ne.Type.CONNECT){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await s.write({type:Ne.Type.STATUS,status:q.UNEXPECTED_MESSAGE},{signal:n}),await e.close({signal:n});return}if(!cp(o)){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await s.write({type:Ne.Type.STATUS,status:q.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}let i=xr($e(o.peer.id));if(await this.components.connectionGater.denyInboundRelayedConnection?.(t.remotePeer,i)===!0){this.log.error("connection gater denied inbound relayed connection from %p",t.remotePeer),await s.write({type:Ne.Type.STATUS,status:q.PERMISSION_DENIED},{signal:n}),await e.close({signal:n});return}this.log.trace("sending success response to %p",t.remotePeer),await s.write({type:Ne.Type.STATUS,status:q.OK},{signal:n});let a=new fn(o.limit),c=t.remoteAddr.encapsulate(`/p2p-circuit/p2p/${i.toString()}`),l=this.components.addressManager.getAddresses()[0],u=ma({stream:s.unwrap().unwrap(),remoteAddr:c,localAddr:l,onDataRead:a.onData,onDataWrite:a.onData,log:e.log.newScope("circuit-relay:connection")});await this.components.upgrader.upgradeInbound(u,{limits:a.getLimits(),signal:n}),u.log("inbound relayed connection established to %p with limits %o, over connection %s",i,o.limit??"none",t.id)}finally{n?.clear()}}};function up(r={}){return e=>new Ro(e,r)}function lp(r={}){return e=>new Po(e,r)}return El(fp);})();
|
|
2
|
+
"use strict";var Libp2PCircuitRelayV2=(()=>{var Vo=Object.defineProperty;var Pl=Object.getOwnPropertyDescriptor;var Nl=Object.getOwnPropertyNames;var Ul=Object.prototype.hasOwnProperty;var ve=(r,e)=>{for(var t in e)Vo(r,t,{get:e[t],enumerable:!0})},kl=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Nl(e))!Ul.call(r,s)&&s!==t&&Vo(r,s,{get:()=>e[s],enumerable:!(n=Pl(e,s))||n.enumerable});return r};var Ml=r=>kl(Vo({},"__esModule",{value:!0}),r);var Bp={};ve(Bp,{RELAY_V2_HOP_CODEC:()=>ke,RELAY_V2_STOP_CODEC:()=>Qt,circuitRelayServer:()=>Cp,circuitRelayTransport:()=>Lp});function Kl(r){return typeof r?.handleEvent=="function"}function Hl(r){return(r!==!0&&r!==!1&&r?.once)??!1}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){let s=Hl(n);super.addEventListener(e,i=>{if(s){let a=this.#e.get(i.type);a!=null&&(a=a.filter(({callback:c})=>c!==t),this.#e.set(i.type,a))}Kl(t)?t.handleEvent(i):t(i)},n);let o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:t,once:s})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let s=this.#e.get(e);s!=null&&(s=s.filter(({callback:o})=>o!==t),this.#e.set(e,s))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var Qe=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var ae=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},er=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var yn=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}};var pt=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},Lr=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}};var bn=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},gn=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var xn=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var wn=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}},Ot=class extends Error{static name="ListenError";constructor(e="Listen error"){super(e),this.name="ListenError"}};var tr=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var En=class extends Event{data;constructor(e,t){super("message",t),this.data=e}},rr=class extends Event{error;local;constructor(e,t,n){super("close",n),this.error=t,this.local=e}},Sn=class extends rr{constructor(e,t){super(!0,e,t)}},vn=class extends rr{constructor(e,t){super(!1,e,t)}};var Fo=Symbol.for("@libp2p/peer-id");var Ca="keep-alive";function La(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function Ba(...r){let e=[];for(let t of r)La(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 Ra(...r){let e=[];for(let t of r)La(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 Pa=Symbol.for("@libp2p/transport");var Oa;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Oa||(Oa={}));var Na=Symbol.for("@libp2p/service-capabilities"),Ua=Symbol.for("@libp2p/service-dependencies");var Yo={};ve(Yo,{base58btc:()=>te,base58flickr:()=>Wl});var f0=new Uint8Array(0);function ka(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 Ma(r){return new TextEncoder().encode(r)}function Ka(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 s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=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 S=0,x=0,y=0,A=h.length;y!==A&&h[y]===0;)y++,S++;for(var w=(A-y)*u+1>>>0,T=new Uint8Array(w);y!==A;){for(var P=h[y],M=0,q=w-1;(P!==0||M<x)&&q!==-1;q--,M++)P+=256*T[q]>>>0,T[q]=P%a>>>0,P=P/a>>>0;if(P!==0)throw new Error("Non-zero carry");x=M,y++}for(var v=w-x;v!==w&&T[v]===0;)v++;for(var E=c.repeat(S);v<w;++v)E+=r.charAt(T[v]);return E}function d(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var S=0;if(h[S]!==" "){for(var x=0,y=0;h[S]===c;)x++,S++;for(var A=(h.length-S)*l+1>>>0,w=new Uint8Array(A);h[S];){var T=t[h.charCodeAt(S)];if(T===255)return;for(var P=0,M=A-1;(T!==0||P<y)&&M!==-1;M--,P++)T+=a*w[M]>>>0,w[M]=T%256>>>0,T=T/256>>>0;if(T!==0)throw new Error("Non-zero carry");y=P,S++}if(h[S]!==" "){for(var q=A-y;q!==A&&w[q]===0;)q++;for(var v=new Uint8Array(x+(A-q)),E=x;q!==A;)v[E++]=w[q++];return v}}}function p(h){var S=d(h);if(S)return S;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:d,decode:p}}var Vl=ql,Fl=Vl,qa=Fl;var zo=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")}},$o=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Va(this,e)}},Go=class{decoders;constructor(e){this.decoders=e}or(e){return Va(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 Va(r,e){return new Go({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Wo=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new zo(e,t,n),this.decoder=new $o(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function nr({name:r,prefix:e,encode:t,decode:n}){return new Wo(r,e,t,n)}function mt({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=qa(t,r);return nr({prefix:e,name:r,encode:n,decode:o=>Je(s(o))})}function zl(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function $l(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function Gl(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function ce({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=Gl(n);return nr({prefix:e,name:r,encode(o){return $l(o,n,t)},decode(o){return zl(o,s,t,r)}})}var te=mt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Wl=mt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Zo={};ve(Zo,{base32:()=>yt,base32hex:()=>jl,base32hexpad:()=>Jl,base32hexpadupper:()=>ef,base32hexupper:()=>Ql,base32pad:()=>Zl,base32padupper:()=>Xl,base32upper:()=>Yl,base32z:()=>tf});var yt=ce({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Yl=ce({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Zl=ce({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Xl=ce({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),jl=ce({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Ql=ce({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Jl=ce({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),ef=ce({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),tf=ce({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Xo={};ve(Xo,{base36:()=>Br,base36upper:()=>rf});var Br=mt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),rf=mt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var nf=$a,Fa=128,of=127,sf=~of,af=Math.pow(2,31);function $a(r,e,t){e=e||[],t=t||0;for(var n=t;r>=af;)e[t++]=r&255|Fa,r/=128;for(;r&sf;)e[t++]=r&255|Fa,r>>>=7;return e[t]=r|0,$a.bytes=t-n+1,e}var cf=jo,uf=128,za=127;function jo(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw jo.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&za)<<s:(i&za)*Math.pow(2,s),s+=7}while(i>=uf);return jo.bytes=o-n,t}var lf=Math.pow(2,7),ff=Math.pow(2,14),df=Math.pow(2,21),hf=Math.pow(2,28),pf=Math.pow(2,35),mf=Math.pow(2,42),yf=Math.pow(2,49),bf=Math.pow(2,56),gf=Math.pow(2,63),xf=function(r){return r<lf?1:r<ff?2:r<df?3:r<hf?4:r<pf?5:r<mf?6:r<yf?7:r<bf?8:r<gf?9:10},wf={encode:nf,decode:cf,encodingLength:xf},Ef=wf,Rr=Ef;function Or(r,e=0){return[Rr.decode(r,e),Rr.decode.bytes]}function or(r,e,t=0){return Rr.encode(r,e,t),e}function sr(r){return Rr.encodingLength(r)}function $e(r,e){let t=e.byteLength,n=sr(r),s=n+sr(t),o=new Uint8Array(s+t);return or(r,o,0),or(t,o,n),o.set(e,s),new ir(r,t,e,o)}function Ge(r){let e=Je(r),[t,n]=Or(e),[s,o]=Or(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new ir(t,s,i,e)}function Ga(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&ka(r.bytes,t.bytes)}}var ir=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};function Wa(r,e){let{bytes:t,version:n}=r;return n===0?vf(t,Qo(r),e??te.encoder):_f(t,Qo(r),e??yt.encoder)}var Ya=new WeakMap;function Qo(r){let e=Ya.get(r);if(e==null){let t=new Map;return Ya.set(r,t),t}return e}var le=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}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!==Pr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Af)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=$e(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&&Ga(e.multihash,n.multihash)}toString(e){return Wa(this,e)}toJSON(){return{"/":Wa(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??Za(n,s,o.bytes))}else if(t[Tf]===!0){let{version:n,multihash:s,code:o}=t,i=Ge(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Pr)throw new Error(`Version 0 CID must use dag-pb (code: ${Pr}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=Za(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Pr,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=Je(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new ir(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,d]=Or(e.subarray(t));return t+=d,f},s=n(),o=Pr;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,s]=Sf(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Qo(o).set(n,e),o}};function Sf(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 yt.prefix:{let t=e??yt;return[yt.prefix,t.decode(r)]}case Br.prefix:{let t=e??Br;return[Br.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 vf(r,e,t){let{prefix:n}=t;if(n!==te.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function _f(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}var Pr=112,Af=18;function Za(r,e,t){let n=sr(r),s=n+sr(e),o=new Uint8Array(s+t.byteLength);return or(r,o,0),or(e,o,n),o.set(t,s),o}var Tf=Symbol.for("@ipld/js-cid/CID");var Jo={};ve(Jo,{identity:()=>Me});var Xa=0,If="identity",ja=Je;function Df(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 $e(Xa,ja(r))}var Me={code:Xa,name:If,encode:ja,digest:Df};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 tt(r,e){e==null&&(e=r.reduce((s,o)=>s+o.length,0));let t=Ae(e),n=0;for(let s of r)t.set(s,n),n+=s.length;return t}var Ja=Symbol.for("@achingbrain/uint8arraylist");function Qa(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let s=t+n.byteLength;if(e<s)return{buf:n,index:e-t};t=s}throw new RangeError("index is out of bounds")}function An(r){return!!r?.[Ja]}var J=class r{bufs;length;[Ja]=!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(An(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(An(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=Qa(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Qa(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(An(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:s}=this._subList(e,t);return tt(n,s)}subarray(e,t){let{bufs:n,length:s}=this._subList(e,t);return n.length===1?n[0]:tt(n,s)}sublist(e,t){let{bufs:n,length:s}=this._subList(e,t),o=new r;return o.length=s,o.bufs=[...n],o}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let n=[],s=0;for(let o=0;o<this.bufs.length;o++){let i=this.bufs[o],a=s,c=a+i.byteLength;if(s=c,e>=c)continue;let l=e>=a&&e<c,u=t>a&&t<=c;if(l&&u){if(e===a&&t===c){n.push(i);break}let f=e-a;n.push(i.subarray(f,f+(t-e)));break}if(l){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(u){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(!An(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let s=n.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let o=256,i=new Int32Array(o);for(let f=0;f<o;f++)i[f]=-1;for(let f=0;f<s;f++)i[n[f]]=f;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let f=t;f<=c;f+=u){u=0;for(let d=l;d>=0;d--){let p=this.get(f+d);if(n[d]!==p){u=Math.max(1,d-a[p]);break}}if(u===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 s=re(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,t,n),this.write(s,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let s=re(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,t,n),this.write(s,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let s=re(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,t,n),this.write(s,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=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 s=re(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,t,n),this.write(s,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let s=re(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,t,n),this.write(s,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let s=re(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,t,n),this.write(s,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let s=re(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,t,n),this.write(s,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let s=re(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,t,n),this.write(s,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!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((s,o)=>s+o.byteLength,0)),n.length=t,n}};var es={};ve(es,{base10:()=>Cf});var Cf=mt({prefix:"9",name:"base10",alphabet:"0123456789"});var ts={};ve(ts,{base16:()=>Lf,base16upper:()=>Bf});var Lf=ce({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Bf=ce({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var rs={};ve(rs,{base2:()=>Rf});var Rf=ce({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var ns={};ve(ns,{base256emoji:()=>kf});var ec=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}"),Of=ec.reduce((r,e,t)=>(r[t]=e,r),[]),Pf=ec.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function Nf(r){return r.reduce((e,t)=>(e+=Of[t],e),"")}function Uf(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let s=Pf[n];if(s==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}var kf=nr({prefix:"\u{1F680}",name:"base256emoji",encode:Nf,decode:Uf});var ss={};ve(ss,{base64:()=>Mf,base64pad:()=>Kf,base64url:()=>os,base64urlpad:()=>Hf});var Mf=ce({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Kf=ce({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),os=ce({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Hf=ce({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var is={};ve(is,{base8:()=>qf});var qf=ce({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var as={};ve(as,{identity:()=>Vf});var Vf=nr({prefix:"\0",name:"identity",encode:r=>Ka(r),decode:r=>Ma(r)});var Y0=new TextEncoder,Z0=new TextDecoder;var ls={};ve(ls,{sha256:()=>ar,sha512:()=>Gf});var $f=20;function us({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new cs(r,e,t,n,s)}var cs=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??$f,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?tc(n,this.code,t?.truncate):n.then(s=>tc(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function tc(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 $e(e,r)}function nc(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var ar=us({name:"sha2-256",code:18,encode:nc("SHA-256")}),Gf=us({name:"sha2-512",code:19,encode:nc("SHA-512")});var Nr={...as,...rs,...is,...es,...ts,...Zo,...Xo,...Yo,...ss,...ns},am={...ls,...Jo};function sc(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var oc=sc("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),fs=sc("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}),Wf={utf8:oc,"utf-8":oc,hex:Nr.base16,latin1:fs,ascii:fs,binary:fs,...Nr},Tn=Wf;function K(r,e="utf8"){let t=Tn[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function $(r,e="utf8"){let t=Tn[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var Yf=parseInt("11111",2),ds=parseInt("10000000",2),Zf=parseInt("01111111",2),ic={0:Ur,1:Ur,2:Xf,3:Jf,4:ed,5:Qf,6:jf,16:Ur,22:Ur,48:Ur};function rt(r,e={offset:0}){let t=r[e.offset]&Yf;if(e.offset++,ic[t]!=null)return ic[t](r,e);throw new Error("No decoder for tag "+t)}function kr(r,e){let t=0;if((r[e.offset]&ds)===ds){let n=r[e.offset]&Zf,s="0x";e.offset++;for(let o=0;o<n;o++,e.offset++)s+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(s,16)}else t=r[e.offset],e.offset++;return t}function Ur(r,e){kr(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=rt(r,e);if(n===null)break;t.push(n)}return t}function Xf(r,e){let t=kr(r,e),n=e.offset,s=e.offset+t,o=[];for(let i=n;i<s;i++)i===n&&r[i]===0||o.push(r[i]);return e.offset+=t,Uint8Array.from(o)}function jf(r,e){let t=kr(r,e),n=e.offset+t,s=r[e.offset];e.offset++;let o=0,i=0;s<40?(o=0,i=s):s<80?(o=1,i=s-40):(o=2,i=s-80);let a=`${o}.${i}`,c=[];for(;e.offset<n;){let l=r[e.offset];if(e.offset++,c.push(l&127),l<128){c.reverse();let u=0;for(let f=0;f<c.length;f++)u+=c[f]<<f*7;a+=`.${u}`,c=[]}}return a}function Qf(r,e){return e.offset++,null}function Jf(r,e){let t=kr(r,e),n=r[e.offset];e.offset++;let s=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return s}function ed(r,e){let t=kr(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function td(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 hs(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=td(r.byteLength);return new J(Uint8Array.from([e.byteLength|ds]),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]),hs(e),e)}function In(r){let e=Uint8Array.from([0]),t=new J(e,r);return new J(Uint8Array.from([3]),hs(t),t)}function bt(r,e=48){let t=new J;for(let n of r)t.append(n);return new J(Uint8Array.from([e]),hs(t),t)}async function ac(r,e,t,n){let s=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let o=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},s,e,t.subarray());return n?.signal?.throwIfAborted(),o}var rd=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),nd=Uint8Array.from([6,5,43,129,4,0,34]),od=Uint8Array.from([6,5,43,129,4,0,35]),sd={ext:!0,kty:"EC",crv:"P-256"},id={ext:!0,kty:"EC",crv:"P-384"},ad={ext:!0,kty:"EC",crv:"P-521"},ps=32,ms=48,ys=66;function bs(r){let e=rt(r);return cc(e)}function cc(r){let e=r[1][1][0],t=1,n,s;if(e.byteLength===ps*2+1)return n=$(e.subarray(t,t+ps),"base64url"),s=$(e.subarray(t+ps),"base64url"),new cr({...sd,key_ops:["verify"],x:n,y:s});if(e.byteLength===ms*2+1)return n=$(e.subarray(t,t+ms),"base64url"),s=$(e.subarray(t+ms),"base64url"),new cr({...id,key_ops:["verify"],x:n,y:s});if(e.byteLength===ys*2+1)return n=$(e.subarray(t,t+ys),"base64url"),s=$(e.subarray(t+ys),"base64url"),new cr({...ad,key_ops:["verify"],x:n,y:s});throw new ae(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function uc(r){return bt([Te(Uint8Array.from([1])),bt([cd(r.crv)],160),bt([In(new J(Uint8Array.from([4]),K(r.x??"","base64url"),K(r.y??"","base64url")))],161)]).subarray()}function cd(r){if(r==="P-256")return rd;if(r==="P-384")return nd;if(r==="P-521")return od;throw new ae(`Invalid curve ${r}`)}var cr=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=uc(this.jwk)),this._raw}toMultihash(){return Me.digest(We(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 ac(this.jwk,t,e,n)}};function Pt(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Ye(r,e=""){if(!Number.isSafeInteger(r)||r<0){let t=e&&`"${e}" `;throw new Error(`${t}expected integer >= 0, got ${r}`)}}function k(r,e,t=""){let n=Pt(r),s=r?.length,o=e!==void 0;if(!n||o&&s!==e){let i=t&&`"${t}" `,a=o?` of length ${e}`:"",c=n?`length=${s}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function Dn(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");Ye(r.outputLen),Ye(r.blockLen)}function ur(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 fc(r,e){k(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 ot(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function Cn(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Ke(r,e){return r<<32-e|r>>>e}var dc=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",ud=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function st(r){if(k(r),dc)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=ud[r[t]];return e}var nt={_0:48,_9:57,A:65,F:70,a:97,f:102};function lc(r){if(r>=nt._0&&r<=nt._9)return r-nt._0;if(r>=nt.A&&r<=nt.F)return r-(nt.A-10);if(r>=nt.a&&r<=nt.f)return r-(nt.a-10)}function it(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(dc)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 s=0,o=0;s<t;s++,o+=2){let i=lc(r.charCodeAt(o)),a=lc(r.charCodeAt(o+1));if(i===void 0||a===void 0){let c=r[o]+r[o+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+o)}n[s]=i*16+a}return n}function Ie(...r){let e=0;for(let n=0;n<r.length;n++){let s=r[n];k(s),e+=s.length}let t=new Uint8Array(e);for(let n=0,s=0;n<r.length;n++){let o=r[n];t.set(o,s),s+=o.length}return t}function gs(r,e={}){let t=(s,o)=>r(o).update(s).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=s=>r(s),Object.assign(t,e),Object.freeze(t)}function lr(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 xs=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function hc(r,e,t){return r&e^~r&t}function pc(r,e,t){return r&e^r&t^e&t}var Mr=class{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,s){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(e),this.view=Cn(this.buffer)}update(e){ur(this),k(e);let{view:t,buffer:n,blockLen:s}=this,o=e.length;for(let i=0;i<o;){let a=Math.min(s-this.pos,o-i);if(a===s){let c=Cn(e);for(;s<=o-i;i+=s)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){ur(this),fc(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:s,isLE:o}=this,{pos:i}=this;t[i++]=128,ot(this.buffer.subarray(i)),this.padOffset>s-i&&(this.process(n,0),i=0);for(let f=i;f<s;f++)t[f]=0;n.setBigUint64(s-8,BigInt(this.length*8),o),this.process(n,0);let a=Cn(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<l;f++)a.setUint32(4*f,u[f],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:s,finished:o,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=o,e.length=s,e.pos=a,s%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},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 Ln=BigInt(4294967295),mc=BigInt(32);function ld(r,e=!1){return e?{h:Number(r&Ln),l:Number(r>>mc&Ln)}:{h:Number(r>>mc&Ln)|0,l:Number(r&Ln)|0}}function yc(r,e=!1){let t=r.length,n=new Uint32Array(t),s=new Uint32Array(t);for(let o=0;o<t;o++){let{h:i,l:a}=ld(r[o],e);[n[o],s[o]]=[i,a]}return[n,s]}var ws=(r,e,t)=>r>>>t,Es=(r,e,t)=>r<<32-t|e>>>t,Nt=(r,e,t)=>r>>>t|e<<32-t,Ut=(r,e,t)=>r<<32-t|e>>>t,Kr=(r,e,t)=>r<<64-t|e>>>t-32,Hr=(r,e,t)=>r>>>t-32|e<<64-t;function Ze(r,e,t,n){let s=(e>>>0)+(n>>>0);return{h:r+t+(s/2**32|0)|0,l:s|0}}var bc=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),gc=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,xc=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),wc=(r,e,t,n,s)=>e+t+n+s+(r/2**32|0)|0,Ec=(r,e,t,n,s)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(s>>>0),Sc=(r,e,t,n,s,o)=>e+t+n+s+o+(r/2**32|0)|0;var dd=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]),gt=new Uint32Array(64),Ss=class extends Mr{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:s,E:o,F:i,G:a,H:c}=this;return[e,t,n,s,o,i,a,c]}set(e,t,n,s,o,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=s|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let f=0;f<16;f++,t+=4)gt[f]=e.getUint32(t,!1);for(let f=16;f<64;f++){let d=gt[f-15],p=gt[f-2],h=Ke(d,7)^Ke(d,18)^d>>>3,S=Ke(p,17)^Ke(p,19)^p>>>10;gt[f]=S+gt[f-7]+h+gt[f-16]|0}let{A:n,B:s,C:o,D:i,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){let d=Ke(a,6)^Ke(a,11)^Ke(a,25),p=u+d+hc(a,c,l)+dd[f]+gt[f]|0,S=(Ke(n,2)^Ke(n,13)^Ke(n,22))+pc(n,s,o)|0;u=l,l=c,c=a,a=i+p|0,i=o,o=s,s=n,n=p+S|0}n=n+this.A|0,s=s+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,s,o,i,a,c,l,u)}roundClean(){ot(gt)}destroy(){this.set(0,0,0,0,0,0,0,0),ot(this.buffer)}},vs=class extends Ss{A=at[0]|0;B=at[1]|0;C=at[2]|0;D=at[3]|0;E=at[4]|0;F=at[5]|0;G=at[6]|0;H=at[7]|0;constructor(){super(32)}};var vc=yc(["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))),hd=vc[0],pd=vc[1],xt=new Uint32Array(80),wt=new Uint32Array(80),_s=class extends Mr{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:n,Bl:s,Ch:o,Cl:i,Dh:a,Dl:c,Eh:l,El:u,Fh:f,Fl:d,Gh:p,Gl:h,Hh:S,Hl:x}=this;return[e,t,n,s,o,i,a,c,l,u,f,d,p,h,S,x]}set(e,t,n,s,o,i,a,c,l,u,f,d,p,h,S,x){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=s|0,this.Ch=o|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=f|0,this.Fl=d|0,this.Gh=p|0,this.Gl=h|0,this.Hh=S|0,this.Hl=x|0}process(e,t){for(let w=0;w<16;w++,t+=4)xt[w]=e.getUint32(t),wt[w]=e.getUint32(t+=4);for(let w=16;w<80;w++){let T=xt[w-15]|0,P=wt[w-15]|0,M=Nt(T,P,1)^Nt(T,P,8)^ws(T,P,7),q=Ut(T,P,1)^Ut(T,P,8)^Es(T,P,7),v=xt[w-2]|0,E=wt[w-2]|0,N=Nt(v,E,19)^Kr(v,E,61)^ws(v,E,6),V=Ut(v,E,19)^Hr(v,E,61)^Es(v,E,6),L=xc(q,V,wt[w-7],wt[w-16]),b=wc(L,M,N,xt[w-7],xt[w-16]);xt[w]=b|0,wt[w]=L|0}let{Ah:n,Al:s,Bh:o,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:f,El:d,Fh:p,Fl:h,Gh:S,Gl:x,Hh:y,Hl:A}=this;for(let w=0;w<80;w++){let T=Nt(f,d,14)^Nt(f,d,18)^Kr(f,d,41),P=Ut(f,d,14)^Ut(f,d,18)^Hr(f,d,41),M=f&p^~f&S,q=d&h^~d&x,v=Ec(A,P,q,pd[w],wt[w]),E=Sc(v,y,T,M,hd[w],xt[w]),N=v|0,V=Nt(n,s,28)^Kr(n,s,34)^Kr(n,s,39),L=Ut(n,s,28)^Hr(n,s,34)^Hr(n,s,39),b=n&o^n&a^o&a,g=s&i^s&c^i&c;y=S|0,A=x|0,S=p|0,x=h|0,p=f|0,h=d|0,{h:f,l:d}=Ze(l|0,u|0,E|0,N|0),l=a|0,u=c|0,a=o|0,c=i|0,o=n|0,i=s|0;let m=bc(N,L,g);n=gc(m,E,V,b),s=m|0}({h:n,l:s}=Ze(this.Ah|0,this.Al|0,n|0,s|0)),{h:o,l:i}=Ze(this.Bh|0,this.Bl|0,o|0,i|0),{h:a,l:c}=Ze(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=Ze(this.Dh|0,this.Dl|0,l|0,u|0),{h:f,l:d}=Ze(this.Eh|0,this.El|0,f|0,d|0),{h:p,l:h}=Ze(this.Fh|0,this.Fl|0,p|0,h|0),{h:S,l:x}=Ze(this.Gh|0,this.Gl|0,S|0,x|0),{h:y,l:A}=Ze(this.Hh|0,this.Hl|0,y|0,A|0),this.set(n,s,o,i,a,c,l,u,f,d,p,h,S,x,y,A)}roundClean(){ot(xt,wt)}destroy(){ot(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},As=class extends _s{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 _c=gs(()=>new vs,xs(1));var Ac=gs(()=>new As,xs(3));var Is=BigInt(0),Ts=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 Tc(r){if(typeof r=="bigint"){if(!Bn(r))throw new Error("positive bigint expected, got "+r)}else Ye(r);return r}function qr(r){let e=Tc(r).toString(16);return e.length&1?"0"+e:e}function Ic(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?Is:BigInt("0x"+r)}function fr(r){return Ic(st(r))}function kt(r){return Ic(st(On(k(r)).reverse()))}function Rn(r,e){Ye(e),r=Tc(r);let t=it(r.toString(16).padStart(e*2,"0"));if(t.length!==e)throw new Error("number too large");return t}function Ds(r,e){return Rn(r,e).reverse()}function On(r){return Uint8Array.from(r)}var Bn=r=>typeof r=="bigint"&&Is<=r;function md(r,e,t){return Bn(r)&&Bn(e)&&Bn(t)&&e<=r&&r<t}function Vr(r,e,t,n){if(!md(e,t,n))throw new Error("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function Cs(r){let e;for(e=0;r>Is;r>>=Ts,e+=1);return e}var Fr=r=>(Ts<<BigInt(r))-Ts;function Dc(r,e,t){if(Ye(r,"hashLen"),Ye(e,"qByteLen"),typeof t!="function")throw new Error("hmacFn must be a function");let n=x=>new Uint8Array(x),s=Uint8Array.of(),o=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(r),l=n(r),u=0,f=()=>{c.fill(1),l.fill(0),u=0},d=(...x)=>t(l,Ie(c,...x)),p=(x=s)=>{l=d(o,x),c=d(),x.length!==0&&(l=d(i,x),c=d())},h=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let x=0,y=[];for(;x<e;){c=d();let A=c.slice();y.push(A),x+=c.length}return Ie(...y)};return(x,y)=>{f(),p(x);let A;for(;!(A=y(h()));)p();return f(),A}}function Et(r,e={},t={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function n(o,i,a){let c=r[o];if(a&&c===void 0)return;let l=typeof c;if(l!==i||c===null)throw new Error(`param "${o}" is invalid: expected ${i}, got ${l}`)}let s=(o,i)=>Object.entries(o).forEach(([a,c])=>n(a,c,i));s(e,!1),s(t,!0)}function dr(r){let e=new WeakMap;return(t,...n)=>{let s=e.get(t);if(s!==void 0)return s;let o=r(t,...n);return e.set(t,o),o}}var Se=BigInt(0),de=BigInt(1),Mt=BigInt(2),Bc=BigInt(3),Rc=BigInt(4),Oc=BigInt(5),yd=BigInt(7),Pc=BigInt(8),bd=BigInt(9),Nc=BigInt(16);function ue(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 Cc(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=ue(r,e),n=e,s=Se,o=de,i=de,a=Se;for(;t!==Se;){let l=n/t,u=n%t,f=s-i*l,d=o-a*l;n=t,t=u,s=i,o=a,i=f,a=d}if(n!==de)throw new Error("invert: does not exist");return ue(s,e)}function Bs(r,e,t){if(!r.eql(r.sqr(e),t))throw new Error("Cannot find square root")}function Uc(r,e){let t=(r.ORDER+de)/Rc,n=r.pow(e,t);return Bs(r,n,e),n}function gd(r,e){let t=(r.ORDER-Oc)/Pc,n=r.mul(e,Mt),s=r.pow(n,t),o=r.mul(e,s),i=r.mul(r.mul(o,Mt),s),a=r.mul(o,r.sub(i,r.ONE));return Bs(r,a,e),a}function xd(r){let e=hr(r),t=kc(r),n=t(e,e.neg(e.ONE)),s=t(e,n),o=t(e,e.neg(n)),i=(r+yd)/Nc;return(a,c)=>{let l=a.pow(c,i),u=a.mul(l,n),f=a.mul(l,s),d=a.mul(l,o),p=a.eql(a.sqr(u),c),h=a.eql(a.sqr(f),c);l=a.cmov(l,u,p),u=a.cmov(d,f,h);let S=a.eql(a.sqr(u),c),x=a.cmov(l,u,S);return Bs(a,x,c),x}}function kc(r){if(r<Bc)throw new Error("sqrt is not defined for small field");let e=r-de,t=0;for(;e%Mt===Se;)e/=Mt,t++;let n=Mt,s=hr(r);for(;Lc(s,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return Uc;let o=s.pow(n,e),i=(e+de)/Mt;return function(c,l){if(c.is0(l))return l;if(Lc(c,l)!==1)throw new Error("Cannot find square root");let u=t,f=c.mul(c.ONE,o),d=c.pow(l,e),p=c.pow(l,i);for(;!c.eql(d,c.ONE);){if(c.is0(d))return c.ZERO;let h=1,S=c.sqr(d);for(;!c.eql(S,c.ONE);)if(h++,S=c.sqr(S),h===u)throw new Error("Cannot find square root");let x=de<<BigInt(u-h-1),y=c.pow(f,x);u=h,f=c.sqr(y),d=c.mul(d,f),p=c.mul(p,y)}return p}}function wd(r){return r%Rc===Bc?Uc:r%Pc===Oc?gd:r%Nc===bd?xd(r):kc(r)}var Mc=(r,e)=>(ue(r,e)&de)===de,Ed=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Rs(r){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=Ed.reduce((n,s)=>(n[s]="function",n),e);return Et(r,t),r}function Sd(r,e,t){if(t<Se)throw new Error("invalid exponent, negatives unsupported");if(t===Se)return r.ONE;if(t===de)return e;let n=r.ONE,s=e;for(;t>Se;)t&de&&(n=r.mul(n,s)),s=r.sqr(s),t>>=de;return n}function zr(r,e,t=!1){let n=new Array(e.length).fill(t?r.ZERO:void 0),s=e.reduce((i,a,c)=>r.is0(a)?i:(n[c]=i,r.mul(i,a)),r.ONE),o=r.inv(s);return e.reduceRight((i,a,c)=>r.is0(a)?i:(n[c]=r.mul(i,n[c]),r.mul(i,a)),o),n}function Lc(r,e){let t=(r.ORDER-de)/Mt,n=r.pow(e,t),s=r.eql(n,r.ONE),o=r.eql(n,r.ZERO),i=r.eql(n,r.neg(r.ONE));if(!s&&!o&&!i)throw new Error("invalid Legendre symbol result");return s?1:o?0:-1}function vd(r,e){e!==void 0&&Ye(e);let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}var Ls=class{ORDER;BITS;BYTES;isLE;ZERO=Se;ONE=de;_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:s,nByteLength:o}=vd(e,n);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=s,this.BYTES=o,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return ue(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&de)===de}neg(e){return ue(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return ue(e*e,this.ORDER)}add(e,t){return ue(e+t,this.ORDER)}sub(e,t){return ue(e-t,this.ORDER)}mul(e,t){return ue(e*t,this.ORDER)}pow(e,t){return Sd(this,e,t)}div(e,t){return ue(e*Cc(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 Cc(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=wd(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?Ds(e,this.BYTES):Rn(e,this.BYTES)}fromBytes(e,t=!1){k(e);let{_lengths:n,BYTES:s,isLE:o,ORDER:i,_mod:a}=this;if(n){if(!n.includes(e.length)||e.length>s)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let l=new Uint8Array(s);l.set(e,o?0:l.length-e.length),e=l}if(e.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+e.length);let c=o?kt(e):fr(e);if(a&&(c=ue(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return zr(this,e)}cmov(e,t,n){return n?t:e}};function hr(r,e={}){return new Ls(r,e)}function Kc(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 Os(r){let e=Kc(r);return e+Math.ceil(e/2)}function Ps(r,e,t=!1){k(r);let n=r.length,s=Kc(e),o=Os(e);if(n<16||n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);let i=t?kt(r):fr(r),a=ue(i,e-de)+de;return t?Ds(a,s):Rn(a,s)}var pr=BigInt(0),Kt=BigInt(1);function $r(r,e){let t=e.negate();return r?t:e}function Ht(r,e){let t=zr(r.Fp,e.map(n=>n.Z));return e.map((n,s)=>r.fromAffine(n.toAffine(t[s])))}function Fc(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function Ns(r,e){Fc(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1),s=2**r,o=Fr(r),i=BigInt(r);return{windows:t,windowSize:n,mask:o,maxNumber:s,shiftBy:i}}function Hc(r,e,t){let{windowSize:n,mask:s,maxNumber:o,shiftBy:i}=t,a=Number(r&s),c=r>>i;a>n&&(a-=o,c+=Kt);let l=e*n,u=l+Math.abs(a)-1,f=a===0,d=a<0,p=e%2!==0;return{nextN:c,offset:u,isZero:f,isNeg:d,isNegF:p,offsetF:l}}var Us=new WeakMap,zc=new WeakMap;function ks(r){return zc.get(r)||1}function qc(r){if(r!==pr)throw new Error("invalid wNAF")}var mr=class{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let s=e;for(;t>pr;)t&Kt&&(n=n.add(s)),s=s.double(),t>>=Kt;return n}precomputeWindow(e,t){let{windows:n,windowSize:s}=Ns(t,this.bits),o=[],i=e,a=i;for(let c=0;c<n;c++){a=i,o.push(a);for(let l=1;l<s;l++)a=a.add(i),o.push(a);i=a.double()}return o}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let s=this.ZERO,o=this.BASE,i=Ns(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:f,isNegF:d,offsetF:p}=Hc(n,a,i);n=c,u?o=o.add($r(d,t[p])):s=s.add($r(f,t[l]))}return qc(n),{p:s,f:o}}wNAFUnsafe(e,t,n,s=this.ZERO){let o=Ns(e,this.bits);for(let i=0;i<o.windows&&n!==pr;i++){let{nextN:a,offset:c,isZero:l,isNeg:u}=Hc(n,i,o);if(n=a,!l){let f=t[c];s=s.add(u?f.negate():f)}}return qc(n),s}getPrecomputes(e,t,n){let s=Us.get(t);return s||(s=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(s=n(s)),Us.set(t,s))),s}cached(e,t,n){let s=ks(e);return this.wNAF(s,this.getPrecomputes(s,e,n),t)}unsafe(e,t,n,s){let o=ks(e);return o===1?this._unsafeLadder(e,t,s):this.wNAFUnsafe(o,this.getPrecomputes(o,e,n),t,s)}createCache(e,t){Fc(t,this.bits),zc.set(e,t),Us.delete(e)}hasCache(e){return ks(e)!==1}};function $c(r,e,t,n){let s=e,o=r.ZERO,i=r.ZERO;for(;t>pr||n>pr;)t&Kt&&(o=o.add(s)),n&Kt&&(i=i.add(s)),s=s.double(),t>>=Kt,n>>=Kt;return{p1:o,p2:i}}function Vc(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Rs(e),e}else return hr(r,{isLE:t})}function Pn(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 l=e[c];if(!(typeof l=="bigint"&&l>pr))throw new Error(`CURVE.${c} must be positive bigint`)}let s=Vc(e.p,t.Fp,n),o=Vc(e.n,t.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!s.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:s,Fn:o}}function Nn(r,e){return function(n){let s=r(n);return{secretKey:s,publicKey:e(s)}}}var St=BigInt(0),he=BigInt(1),Ms=BigInt(2),_d=BigInt(8);function Ad(r,e,t,n){let s=r.sqr(t),o=r.sqr(n),i=r.add(r.mul(e.a,s),o),a=r.add(r.ONE,r.mul(e.d,r.mul(s,o)));return r.eql(i,a)}function Gc(r,e={}){let t=Pn("edwards",r,e,e.FpFnLE),{Fp:n,Fn:s}=t,o=t.CURVE,{h:i}=o;Et(e,{},{uvRatio:"function"});let a=Ms<<BigInt(s.BYTES*8)-he,c=x=>n.create(x),l=e.uvRatio||((x,y)=>{try{return{isValid:!0,value:n.sqrt(n.div(x,y))}}catch{return{isValid:!1,value:St}}});if(!Ad(n,o,o.Gx,o.Gy))throw new Error("bad curve params: generator point");function u(x,y,A=!1){let w=A?he:St;return Vr("coordinate "+x,y,w,a),y}function f(x){if(!(x instanceof h))throw new Error("EdwardsPoint expected")}let d=dr((x,y)=>{let{X:A,Y:w,Z:T}=x,P=x.is0();y==null&&(y=P?_d:n.inv(T));let M=c(A*y),q=c(w*y),v=n.mul(T,y);if(P)return{x:St,y:he};if(v!==he)throw new Error("invZ was invalid");return{x:M,y:q}}),p=dr(x=>{let{a:y,d:A}=o;if(x.is0())throw new Error("bad point: ZERO");let{X:w,Y:T,Z:P,T:M}=x,q=c(w*w),v=c(T*T),E=c(P*P),N=c(E*E),V=c(q*y),L=c(E*c(V+v)),b=c(N+c(A*c(q*v)));if(L!==b)throw new Error("bad point: equation left != right (1)");let g=c(w*T),m=c(P*M);if(g!==m)throw new Error("bad point: equation left != right (2)");return!0});class h{static BASE=new h(o.Gx,o.Gy,he,c(o.Gx*o.Gy));static ZERO=new h(St,he,he,St);static Fp=n;static Fn=s;X;Y;Z;T;constructor(y,A,w,T){this.X=u("x",y),this.Y=u("y",A),this.Z=u("z",w,!0),this.T=u("t",T),Object.freeze(this)}static CURVE(){return o}static fromAffine(y){if(y instanceof h)throw new Error("extended point not allowed");let{x:A,y:w}=y||{};return u("x",A),u("y",w),new h(A,w,he,c(A*w))}static fromBytes(y,A=!1){let w=n.BYTES,{a:T,d:P}=o;y=On(k(y,w,"point")),ct(A,"zip215");let M=On(y),q=y[w-1];M[w-1]=q&-129;let v=kt(M),E=A?a:n.ORDER;Vr("point.y",v,St,E);let N=c(v*v),V=c(N-he),L=c(P*N-T),{isValid:b,value:g}=l(V,L);if(!b)throw new Error("bad point: invalid y coordinate");let m=(g&he)===he,_=(q&128)!==0;if(!A&&g===St&&_)throw new Error("bad point: x=0 and x_0=1");return _!==m&&(g=c(-g)),h.fromAffine({x:g,y:v})}static fromHex(y,A=!1){return h.fromBytes(it(y),A)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=8,A=!0){return S.createCache(this,y),A||this.multiply(Ms),this}assertValidity(){p(this)}equals(y){f(y);let{X:A,Y:w,Z:T}=this,{X:P,Y:M,Z:q}=y,v=c(A*q),E=c(P*T),N=c(w*q),V=c(M*T);return v===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}=o,{X:A,Y:w,Z:T}=this,P=c(A*A),M=c(w*w),q=c(Ms*c(T*T)),v=c(y*P),E=A+w,N=c(c(E*E)-P-M),V=v+M,L=V-q,b=v-M,g=c(N*L),m=c(V*b),_=c(N*b),I=c(L*V);return new h(g,m,I,_)}add(y){f(y);let{a:A,d:w}=o,{X:T,Y:P,Z:M,T:q}=this,{X:v,Y:E,Z:N,T:V}=y,L=c(T*v),b=c(P*E),g=c(q*w*V),m=c(M*N),_=c((T+P)*(v+E)-L-b),I=m-g,C=m+g,B=c(b-A*L),D=c(_*I),O=c(C*B),U=c(_*B),oe=c(I*C);return new h(D,O,oe,U)}subtract(y){return this.add(y.negate())}multiply(y){if(!s.isValidNot0(y))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:A,f:w}=S.cached(this,y,T=>Ht(h,T));return Ht(h,[A,w])[0]}multiplyUnsafe(y,A=h.ZERO){if(!s.isValid(y))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return y===St?h.ZERO:this.is0()||y===he?this:S.unsafe(this,y,w=>Ht(h,w),A)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return S.unsafe(this,o.n).is0()}toAffine(y){return d(this,y)}clearCofactor(){return i===he?this:this.multiplyUnsafe(i)}toBytes(){let{x:y,y:A}=this.toAffine(),w=n.toBytes(A);return w[w.length-1]|=y&he?128:0,w}toHex(){return st(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let S=new mr(h,s.BITS);return h.BASE.precompute(8),h}function Wc(r,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');Et(t,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=t,{BASE:s,Fp:o,Fn:i}=r,a=t.randomBytes||lr,c=t.adjustScalarBytes||(v=>v),l=t.domain||((v,E,N)=>{if(ct(N,"phflag"),E.length||N)throw new Error("Contexts/pre-hash are not supported");return v});function u(v){return i.create(kt(v))}function f(v){let E=w.secretKey;k(v,w.secretKey,"secretKey");let N=k(e(v),2*E,"hashedSecretKey"),V=c(N.slice(0,E)),L=N.slice(E,2*E),b=u(V);return{head:V,prefix:L,scalar:b}}function d(v){let{head:E,prefix:N,scalar:V}=f(v),L=s.multiply(V),b=L.toBytes();return{head:E,prefix:N,scalar:V,point:L,pointBytes:b}}function p(v){return d(v).pointBytes}function h(v=Uint8Array.of(),...E){let N=Ie(...E);return u(e(l(N,k(v,void 0,"context"),!!n)))}function S(v,E,N={}){v=k(v,void 0,"message"),n&&(v=n(v));let{prefix:V,scalar:L,pointBytes:b}=d(E),g=h(N.context,V,v),m=s.multiply(g).toBytes(),_=h(N.context,m,b,v),I=i.create(g+_*L);if(!i.isValid(I))throw new Error("sign failed: invalid s");let C=Ie(m,i.toBytes(I));return k(C,w.signature,"result")}let x={zip215:!0};function y(v,E,N,V=x){let{context:L,zip215:b}=V,g=w.signature;v=k(v,g,"signature"),E=k(E,void 0,"message"),N=k(N,w.publicKey,"publicKey"),b!==void 0&&ct(b,"zip215"),n&&(E=n(E));let m=g/2,_=v.subarray(0,m),I=kt(v.subarray(m,g)),C,B,D;try{C=r.fromBytes(N,b),B=r.fromBytes(_,b),D=s.multiplyUnsafe(I)}catch{return!1}if(!b&&C.isSmallOrder())return!1;let O=h(L,B.toBytes(),C.toBytes(),E);return B.add(C.multiplyUnsafe(O)).subtract(D).clearCofactor().is0()}let A=o.BYTES,w={secretKey:A,publicKey:A,signature:2*A,seed:A};function T(v=a(w.seed)){return k(v,w.seed,"seed")}function P(v){return Pt(v)&&v.length===i.BYTES}function M(v,E){try{return!!r.fromBytes(v,E)}catch{return!1}}let q={getExtendedPublicKey:d,randomSecretKey:T,isValidSecretKey:P,isValidPublicKey:M,toMontgomery(v){let{y:E}=r.fromBytes(v),N=w.publicKey,V=N===32;if(!V&&N!==57)throw new Error("only defined for 25519 and 448");let L=V?o.div(he+E,he-E):o.div(E-he,E+he);return o.toBytes(L)},toMontgomerySecret(v){let E=w.secretKey;k(v,E);let N=e(v.subarray(0,E));return c(N).subarray(0,E)}};return Object.freeze({keygen:Nn(T,p),getPublicKey:p,sign:S,verify:y,utils:q,Point:r,lengths:w})}var Td=BigInt(1),Yc=BigInt(2);var Id=BigInt(5),Dd=BigInt(8),Ks=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Cd={p:Ks,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Dd,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Ld(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),s=BigInt(80),o=Ks,a=r*r%o*r%o,c=ee(a,Yc,o)*a%o,l=ee(c,Td,o)*r%o,u=ee(l,Id,o)*l%o,f=ee(u,e,o)*u%o,d=ee(f,t,o)*f%o,p=ee(d,n,o)*d%o,h=ee(p,s,o)*p%o,S=ee(h,s,o)*p%o,x=ee(S,e,o)*u%o;return{pow_p_5_8:ee(x,Yc,o)*r%o,b2:a}}function Bd(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var Zc=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Rd(r,e){let t=Ks,n=ue(e*e*e,t),s=ue(n*n*e,t),o=Ld(r*s).pow_p_5_8,i=ue(r*n*o,t),a=ue(e*i*i,t),c=i,l=ue(i*Zc,t),u=a===r,f=a===ue(-r,t),d=a===ue(-r*Zc,t);return u&&(i=c),(f||d)&&(i=l),Mc(i,t)&&(i=ue(-i,t)),{isValid:u||f,value:i}}var Od=Gc(Cd,{uvRatio:Rd});function Pd(r){return Wc(Od,Ac,Object.assign({adjustScalarBytes:Bd},r))}var Xc=Pd({});var Gr=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},Un=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var jc={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new Un("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 Ue=jc;var kn=32;var Hs,Nd=(async()=>{try{return await Ue.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function Ud(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await Ue.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await Ue.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 kd(r,e,t){return Xc.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function Qc(r,e,t){return Hs==null&&(Hs=await Nd),Hs?Ud(r,e,t):kd(r,e,t)}function Mn(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Kn=class{type="Ed25519";raw;constructor(e){this.raw=qs(e,kn)}toMultihash(){return Me.digest(We(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 s=Qc(this.raw,t,e);return Mn(s)?s.then(o=>(n?.signal?.throwIfAborted(),o)):s}};function Vs(r){return r=qs(r,kn),new Kn(r)}function qs(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new ae(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var Kd=Math.pow(2,7),Hd=Math.pow(2,14),qd=Math.pow(2,21),Fs=Math.pow(2,28),zs=Math.pow(2,35),$s=Math.pow(2,42),Gs=Math.pow(2,49),Y=128,xe=127;function De(r){if(r<Kd)return 1;if(r<Hd)return 2;if(r<qd)return 3;if(r<Fs)return 4;if(r<zs)return 5;if(r<$s)return 6;if(r<Gs)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function yr(r,e,t=0){switch(De(r)){case 8:e[t++]=r&255|Y,r/=128;case 7:e[t++]=r&255|Y,r/=128;case 6:e[t++]=r&255|Y,r/=128;case 5:e[t++]=r&255|Y,r/=128;case 4:e[t++]=r&255|Y,r>>>=7;case 3:e[t++]=r&255|Y,r>>>=7;case 2:e[t++]=r&255|Y,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function Vd(r,e,t=0){switch(De(r)){case 8:e.set(t++,r&255|Y),r/=128;case 7:e.set(t++,r&255|Y),r/=128;case 6:e.set(t++,r&255|Y),r/=128;case 5:e.set(t++,r&255|Y),r/=128;case 4:e.set(t++,r&255|Y),r>>>=7;case 3:e.set(t++,r&255|Y),r>>>=7;case 2:e.set(t++,r&255|Y),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function Ws(r,e){let t=r[e],n=0;if(n+=t&xe,t<Y||(t=r[e+1],n+=(t&xe)<<7,t<Y)||(t=r[e+2],n+=(t&xe)<<14,t<Y)||(t=r[e+3],n+=(t&xe)<<21,t<Y)||(t=r[e+4],n+=(t&xe)*Fs,t<Y)||(t=r[e+5],n+=(t&xe)*zs,t<Y)||(t=r[e+6],n+=(t&xe)*$s,t<Y)||(t=r[e+7],n+=(t&xe)*Gs,t<Y))return n;throw new RangeError("Could not decode varint")}function Fd(r,e){let t=r.get(e),n=0;if(n+=t&xe,t<Y||(t=r.get(e+1),n+=(t&xe)<<7,t<Y)||(t=r.get(e+2),n+=(t&xe)<<14,t<Y)||(t=r.get(e+3),n+=(t&xe)<<21,t<Y)||(t=r.get(e+4),n+=(t&xe)*Fs,t<Y)||(t=r.get(e+5),n+=(t&xe)*zs,t<Y)||(t=r.get(e+6),n+=(t&xe)*$s,t<Y)||(t=r.get(e+7),n+=(t&xe)*Gs,t<Y))return n;throw new RangeError("Could not decode varint")}function br(r,e,t=0){return e==null&&(e=Ae(De(r))),e instanceof Uint8Array?yr(r,e,t):Vd(r,e,t)}function Wr(r,e=0){return r instanceof Uint8Array?Ws(r,e):Fd(r,e)}var Zs=new Float32Array([-0]),vt=new Uint8Array(Zs.buffer);function eu(r,e,t){Zs[0]=r,e[t]=vt[0],e[t+1]=vt[1],e[t+2]=vt[2],e[t+3]=vt[3]}function tu(r,e){return vt[0]=r[e],vt[1]=r[e+1],vt[2]=r[e+2],vt[3]=r[e+3],Zs[0]}var Xs=new Float64Array([-0]),we=new Uint8Array(Xs.buffer);function ru(r,e,t){Xs[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 nu(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],Xs[0]}var zd=BigInt(Number.MAX_SAFE_INTEGER),$d=BigInt(Number.MIN_SAFE_INTEGER),Oe=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 qt;if(e<zd&&e>$d)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,s=e-(n<<32n);return t&&(n=~n|0n,s=~s|0n,++s>ou&&(s=0n,++n>ou&&(n=0n))),new r(Number(s),Number(n))}static fromNumber(e){if(e===0)return qt;let t=e<0;t&&(e=-e);let n=e>>>0,s=(e-n)/4294967296>>>0;return t&&(s=~s>>>0,n=~n>>>0,++n>4294967295&&(n=0,++s>4294967295&&(s=0))),new r(n,s)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):qt}},qt=new Oe(0,0);qt.toBigInt=function(){return 0n};qt.zzEncode=qt.zzDecode=function(){return this};qt.length=function(){return 1};var ou=4294967296n;function su(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 iu(r,e,t){if(t-e<1)return"";let s,o=[],i=0,a;for(;e<t;)a=r[e++],a<128?o[i++]=a:a>191&&a<224?o[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,o[i++]=55296+(a>>10),o[i++]=56320+(a&1023)):o[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((s??(s=[])).push(String.fromCharCode.apply(String,o)),i=0);return s!=null?(i>0&&s.push(String.fromCharCode.apply(String,o.slice(0,i))),s.join("")):String.fromCharCode.apply(String,o.slice(0,i))}function js(r,e,t){let n=t,s,o;for(let i=0;i<r.length;++i)s=r.charCodeAt(i),s<128?e[t++]=s:s<2048?(e[t++]=s>>6|192,e[t++]=s&63|128):(s&64512)===55296&&((o=r.charCodeAt(i+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++i,e[t++]=s>>18|240,e[t++]=s>>12&63|128,e[t++]=s>>6&63|128,e[t++]=s&63|128):(e[t++]=s>>12|224,e[t++]=s>>6&63|128,e[t++]=s&63|128);return t-n}function He(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Hn(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var Qs=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,He(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 He(this,4);return Hn(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw He(this,4);return Hn(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw He(this,4);let e=tu(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw He(this,4);let e=nu(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 He(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return iu(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw He(this,e);this.pos+=e}else do if(this.pos>=this.len)throw He(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 Oe(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 He(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 He(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 He(this,8);let e=Hn(this.buf,this.pos+=4),t=Hn(this.buf,this.pos+=4);return new Oe(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=Ws(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 Yr(r){return new Qs(r instanceof Uint8Array?r:r.subarray())}function Ce(r,e,t){let n=Yr(r);return e.decode(n,void 0,t)}function Js(r){let e=r??8192,t=e>>>1,n,s=e;return function(i){if(i<1||i>t)return Ae(i);s+i>e&&(n=Ae(e),s=0);let a=n.subarray(s,s+=i);return(s&7)!==0&&(s=(s|7)+1),a}}var Vt=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function ei(){}var ri=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},Gd=Js();function Wd(r){return globalThis.Buffer!=null?Ae(r):Gd(r)}var Xr=class{len;head;tail;states;constructor(){this.len=0,this.head=new Vt(ei,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new Vt(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new ni((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(qn,10,Oe.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Oe.fromBigInt(e);return this._push(qn,t.length(),t)}uint64Number(e){return this._push(yr,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=Oe.fromBigInt(e).zzEncode();return this._push(qn,t.length(),t)}sint64Number(e){let t=Oe.fromNumber(e).zzEncode();return this._push(qn,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(ti,1,e?1:0)}fixed32(e){return this._push(Zr,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Oe.fromBigInt(e);return this._push(Zr,4,t.lo)._push(Zr,4,t.hi)}fixed64Number(e){let t=Oe.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(eu,4,e)}double(e){return this._push(ru,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(ti,1,0):this.uint32(t)._push(Zd,t,e)}string(e){let t=su(e);return t!==0?this.uint32(t)._push(js,t,e):this._push(ti,1,0)}fork(){return this.states=new ri(this),this.head=this.tail=new Vt(ei,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Vt(ei,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=Wd(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function ti(r,e,t){e[t]=r&255}function Yd(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var ni=class extends Vt{next;constructor(e,t){super(Yd,e,t),this.next=void 0}};function qn(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 Zd(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(Xr.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(Xd,e,r),this},Xr.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(jd,e,r),this});function Xd(r,e,t){e.set(r,t)}function jd(r,e,t){r.length<40?js(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(K(r),t)}function oi(){return new Xr}function Le(r,e){let t=oi();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}function*Be(r,e,t){let n=Yr(r);yield*e.stream(n,void 0,"$",t)}var Vn={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function Fn(r,e,t,n,s){return{name:r,type:e,encode:t,decode:n,stream:s}}function Ft(r){function e(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let t=function(i,a){let c=e(i);a.int32(c)},n=function(i){let a=i.int32();return e(a)},s=function*(i){let a=i.int32();yield e(a)};return Fn("enum",Vn.VARINT,t,n,s)}function Re(r,e,t){return Fn("message",Vn.LENGTH_DELIMITED,r,e,t)}var zt=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var ne;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(ne||(ne={}));var si;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(si||(si={}));(function(r){r.codec=()=>Ft(si)})(ne||(ne={}));var Xe;(function(r){let e;r.codec=()=>(e==null&&(e=Re((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.Type!=null&&(i.uint32(8),ne.codec().encode(o.Type,i)),o.Data!=null&&(i.uint32(18),i.bytes(o.Data)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.Type=ne.codec().decode(o);break}case 2:{c.Data=o.bytes();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:ne.codec().decode(o)};break}case 2:{yield{field:`${a}.Data`,value:o.bytes()};break}default:{o.skipType(u&7);break}}}})),e);function t(o){return Le(o,r.codec())}r.encode=t;function n(o,i){return Ce(o,r.codec(),i)}r.decode=n;function s(o,i){return Be(o,r.codec(),i)}r.stream=s})(Xe||(Xe={}));var ii;(function(r){let e;r.codec=()=>(e==null&&(e=Re((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.Type!=null&&(i.uint32(8),ne.codec().encode(o.Type,i)),o.Data!=null&&(i.uint32(18),i.bytes(o.Data)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.Type=ne.codec().decode(o);break}case 2:{c.Data=o.bytes();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:ne.codec().decode(o)};break}case 2:{yield{field:`${a}.Data`,value:o.bytes()};break}default:{o.skipType(u&7);break}}}})),e);function t(o){return Le(o,r.codec())}r.encode=t;function n(o,i){return Ce(o,r.codec(),i)}r.decode=n;function s(o,i){return Be(o,r.codec(),i)}r.stream=s})(ii||(ii={}));function Qd(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}function ai(r,e,t=""){let n=Qd(r),s=r?.length,o=e!==void 0;if(!n||o&&s!==e){let i=t&&`"${t}" `,a=o?` of length ${e}`:"",c=n?`length=${s}`:`type=${typeof r}`,l=i+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(l):new TypeError(l)}return r}function ci(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 uu(r,e){ai(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length<t)throw new RangeError('"digestInto() output" expected to be of length >='+t)}function jr(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function zn(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function qe(r,e){return r<<32-e|r>>>e}function lu(r,e={}){let t=(s,o)=>r(o).update(s).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.canXOF=n.canXOF,t.create=s=>r(s),Object.assign(t,e),Object.freeze(t)}var fu=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});var Jr={};ve(Jr,{MAX_RSA_KEY_SIZE:()=>fi,generateRSAKeyPair:()=>bu,jwkToJWKKeyPair:()=>gu,jwkToPkcs1:()=>nh,jwkToPkix:()=>mi,jwkToRSAPrivateKey:()=>xi,pkcs1MessageToJwk:()=>hi,pkcs1MessageToRSAPrivateKey:()=>yi,pkcs1ToJwk:()=>rh,pkcs1ToRSAPrivateKey:()=>yu,pkixMessageToJwk:()=>pi,pkixMessageToRSAPublicKey:()=>gi,pkixToJwk:()=>oh,pkixToRSAPublicKey:()=>bi});function du(r,e,t){return r&e^~r&t}function hu(r,e,t){return r&e^r&t^e&t}var $n=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,s){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(e),this.view=zn(this.buffer)}update(e){ci(this),ai(e);let{view:t,buffer:n,blockLen:s}=this,o=e.length;for(let i=0;i<o;){let a=Math.min(s-this.pos,o-i);if(a===s){let c=zn(e);for(;s<=o-i;i+=s)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){ci(this),uu(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:s,isLE:o}=this,{pos:i}=this;t[i++]=128,jr(this.buffer.subarray(i)),this.padOffset>s-i&&(this.process(n,0),i=0);for(let f=i;f<s;f++)t[f]=0;n.setBigUint64(s-8,BigInt(this.length*8),o),this.process(n,0);let a=zn(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<l;f++)a.setUint32(4*f,u[f],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:s,finished:o,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=o,e.length=s,e.pos=a,s%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},ut=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Jd=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]),_t=new Uint32Array(64),ui=class extends $n{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:s,E:o,F:i,G:a,H:c}=this;return[e,t,n,s,o,i,a,c]}set(e,t,n,s,o,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=s|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let f=0;f<16;f++,t+=4)_t[f]=e.getUint32(t,!1);for(let f=16;f<64;f++){let d=_t[f-15],p=_t[f-2],h=qe(d,7)^qe(d,18)^d>>>3,S=qe(p,17)^qe(p,19)^p>>>10;_t[f]=S+_t[f-7]+h+_t[f-16]|0}let{A:n,B:s,C:o,D:i,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){let d=qe(a,6)^qe(a,11)^qe(a,25),p=u+d+du(a,c,l)+Jd[f]+_t[f]|0,S=(qe(n,2)^qe(n,13)^qe(n,22))+hu(n,s,o)|0;u=l,l=c,c=a,a=i+p|0,i=o,o=s,s=n,n=p+S|0}n=n+this.A|0,s=s+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,s,o,i,a,c,l,u)}roundClean(){jr(_t)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),jr(this.buffer)}},li=class extends ui{A=ut[0]|0;B=ut[1]|0;C=ut[2]|0;D=ut[3]|0;E=ut[4]|0;F=ut[5]|0;G=ut[6]|0;H=ut[7]|0;constructor(){super(32)}};var Gn=lu(()=>new li,fu(1));var gr=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=Jr.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 mu(this.jwk,t,e,n)}},Qr=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=Jr.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:fe(this.raw,e.raw)}sign(e,t){return pu(this.jwk,e,t)}};var fi=8192,di=18,eh=1062,th=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function rh(r){let e=rt(r);return hi(e)}function hi(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 nh(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 ae("JWK was missing components");return bt([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 oh(r){let e=rt(r,{offset:0});return pi(e)}function pi(r){let e=rt(r[1],{offset:0});return{kty:"RSA",n:$(e[0],"base64url"),e:$(e[1],"base64url")}}function mi(r){if(r.n==null||r.e==null)throw new ae("JWK was missing components");return bt([th,In(bt([Te(K(r.n,"base64url")),Te(K(r.e,"base64url"))]))]).subarray()}function yu(r){let e=rt(r);return yi(e)}function yi(r){let e=hi(r);return xi(e)}function bi(r,e){if(r.byteLength>=eh)throw new er("Key size is too large");let t=rt(r,{offset:0});return gi(t,r,e)}function gi(r,e,t){let n=pi(r);if(t==null){let s=Gn(Xe.encode({Type:ne.RSA,Data:e}));t=$e(di,s)}return new gr(n,t)}function xi(r){if(wu(r)>fi)throw new ae("Key size is too large");let e=gu(r),t=Gn(Xe.encode({Type:ne.RSA,Data:mi(e.publicKey)})),n=$e(di,t);return new Qr(e.privateKey,new gr(e.publicKey,n))}async function bu(r){if(r>fi)throw new ae("Key size is too large");let e=await xu(r),t=Gn(Xe.encode({Type:ne.RSA,Data:mi(e.publicKey)})),n=$e(di,t);return new Qr(e.privateKey,new gr(e.publicKey,n))}function gu(r){if(r==null)throw new ae("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function xu(r,e){let t=await Ue.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 sh(t,e);return{privateKey:n[0],publicKey:n[1]}}async function pu(r,e,t){let n=await Ue.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let s=await Ue.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,e instanceof Uint8Array?e:e.subarray());return t?.signal?.throwIfAborted(),new Uint8Array(s,0,s.byteLength)}async function mu(r,e,t,n){let s=await Ue.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let o=await Ue.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},s,e,t instanceof Uint8Array?t:t.subarray());return n?.signal?.throwIfAborted(),o}async function sh(r,e){if(r.privateKey==null||r.publicKey==null)throw new ae("Private and public key are required");let t=await Promise.all([Ue.get().subtle.exportKey("jwk",r.privateKey),Ue.get().subtle.exportKey("jwk",r.publicKey)]);return e?.signal?.throwIfAborted(),t}function wu(r){if(r.kty!=="RSA")throw new ae("invalid key type");if(r.n==null)throw new ae("invalid key modulus");return K(r.n,"base64url").length*8}var Wn=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if(Dn(e),k(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,s=new Uint8Array(n);s.set(t.length>n?e.create().update(t).digest():t);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=e.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),ot(s)}update(e){return ur(this),this.iHash.update(e),this}digestInto(e){ur(this),k(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:s,destroyed:o,blockLen:i,outputLen:a}=this;return e=e,e.finished=s,e.destroyed=o,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},wi=(r,e,t)=>new Wn(r,e).update(t).digest();wi.create=(r,e)=>new Wn(r,e);var Eu=(r,e)=>(r+(r>=0?e:-e)/Su)/e;function ih(r,e,t){let[[n,s],[o,i]]=e,a=Eu(i*r,t),c=Eu(-s*r,t),l=r-a*n-c*o,u=-a*s-c*i,f=l<lt,d=u<lt;f&&(l=-l),d&&(u=-u);let p=Fr(Math.ceil(Cs(t)/2))+xr;if(l<lt||l>=p||u<lt||u>=p)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:f,k1:l,k2neg:d,k2:u}}function Si(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function Ei(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&&Si(t.format),t}var vi=class extends Error{constructor(e=""){super(e)}},At={Err:vi,_tlv:{encode:(r,e)=>{let{Err:t}=At;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,s=qr(n);if(s.length/2&128)throw new t("tlv.encode: long form length too big");let o=n>127?qr(s.length/2|128):"";return qr(r)+o+s+e},decode(r,e){let{Err:t}=At,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 s=e[n++],o=!!(s&128),i=0;if(!o)i=s;else{let c=s&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let l=e.subarray(n,n+c);if(l.length!==c)throw new t("tlv.decode: length bytes not complete");if(l[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let u of l)i=i<<8|u;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}=At;if(r<lt)throw new e("integer: negative integers are not allowed");let t=qr(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(r){let{Err:e}=At;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 fr(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=At,s=k(r,void 0,"signature"),{v:o,l:i}=n.decode(48,s);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,o),{v:l,l:u}=n.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(l)}},hexFromSig(r){let{_tlv:e,_int:t}=At,n=e.encode(2,t.encode(r.r)),s=e.encode(2,t.encode(r.s)),o=n+s;return e.encode(48,o)}},lt=BigInt(0),xr=BigInt(1),Su=BigInt(2),Yn=BigInt(3),ah=BigInt(4);function vu(r,e={}){let t=Pn("weierstrass",r,e),{Fp:n,Fn:s}=t,o=t.CURVE,{h:i,n:a}=o;Et(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c}=e;if(c&&(!n.is0(o.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=Au(n,s);function u(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(L,b,g){let{x:m,y:_}=b.toAffine(),I=n.toBytes(m);if(ct(g,"isCompressed"),g){u();let C=!n.isOdd(_);return Ie(_u(C),I)}else return Ie(Uint8Array.of(4),I,n.toBytes(_))}function d(L){k(L,void 0,"Point");let{publicKey:b,publicKeyUncompressed:g}=l,m=L.length,_=L[0],I=L.subarray(1);if(m===b&&(_===2||_===3)){let C=n.fromBytes(I);if(!n.isValid(C))throw new Error("bad point: is not on curve, wrong x");let B=S(C),D;try{D=n.sqrt(B)}catch(oe){let Q=oe instanceof Error?": "+oe.message:"";throw new Error("bad point: is not on curve, sqrt error"+Q)}u();let O=n.isOdd(D);return(_&1)===1!==O&&(D=n.neg(D)),{x:C,y:D}}else if(m===g&&_===4){let C=n.BYTES,B=n.fromBytes(I.subarray(0,C)),D=n.fromBytes(I.subarray(C,C*2));if(!x(B,D))throw new Error("bad point: is not on curve");return{x:B,y:D}}else throw new Error(`bad point: got length ${m}, expected compressed=${b} or uncompressed=${g}`)}let p=e.toBytes||f,h=e.fromBytes||d;function S(L){let b=n.sqr(L),g=n.mul(b,L);return n.add(n.add(g,n.mul(L,o.a)),o.b)}function x(L,b){let g=n.sqr(b),m=S(L);return n.eql(g,m)}if(!x(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let y=n.mul(n.pow(o.a,Yn),ah),A=n.mul(n.sqr(o.b),BigInt(27));if(n.is0(n.add(y,A)))throw new Error("bad curve params: a or b");function w(L,b,g=!1){if(!n.isValid(b)||g&&n.is0(b))throw new Error(`bad point coordinate ${L}`);return b}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 ih(L,c.basises,s.ORDER)}let M=dr((L,b)=>{let{X:g,Y:m,Z:_}=L;if(n.eql(_,n.ONE))return{x:g,y:m};let I=L.is0();b==null&&(b=I?n.ONE:n.inv(_));let C=n.mul(g,b),B=n.mul(m,b),D=n.mul(_,b);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:B}}),q=dr(L=>{if(L.is0()){if(e.allowInfinityPoint&&!n.is0(L.Y))return;throw new Error("bad point: ZERO")}let{x:b,y:g}=L.toAffine();if(!n.isValid(b)||!n.isValid(g))throw new Error("bad point: x or y not field elements");if(!x(b,g))throw new Error("bad point: equation left != right");if(!L.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function v(L,b,g,m,_){return g=new E(n.mul(g.X,L),g.Y,g.Z),b=$r(m,b),g=$r(_,g),b.add(g)}class E{static BASE=new E(o.Gx,o.Gy,n.ONE);static ZERO=new E(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=s;X;Y;Z;constructor(b,g,m){this.X=w("x",b),this.Y=w("y",g,!0),this.Z=w("z",m),Object.freeze(this)}static CURVE(){return o}static fromAffine(b){let{x:g,y:m}=b||{};if(!b||!n.isValid(g)||!n.isValid(m))throw new Error("invalid affine point");if(b instanceof E)throw new Error("projective point not allowed");return n.is0(g)&&n.is0(m)?E.ZERO:new E(g,m,n.ONE)}static fromBytes(b){let g=E.fromAffine(h(k(b,void 0,"point")));return g.assertValidity(),g}static fromHex(b){return E.fromBytes(it(b))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(b=8,g=!0){return V.createCache(this,b),g||this.multiply(Yn),this}assertValidity(){q(this)}hasEvenY(){let{y:b}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(b)}equals(b){T(b);let{X:g,Y:m,Z:_}=this,{X:I,Y:C,Z:B}=b,D=n.eql(n.mul(g,B),n.mul(I,_)),O=n.eql(n.mul(m,B),n.mul(C,_));return D&&O}negate(){return new E(this.X,n.neg(this.Y),this.Z)}double(){let{a:b,b:g}=o,m=n.mul(g,Yn),{X:_,Y:I,Z:C}=this,B=n.ZERO,D=n.ZERO,O=n.ZERO,U=n.mul(_,_),oe=n.mul(I,I),Q=n.mul(C,C),W=n.mul(_,I);return W=n.add(W,W),O=n.mul(_,C),O=n.add(O,O),B=n.mul(b,O),D=n.mul(m,Q),D=n.add(B,D),B=n.sub(oe,D),D=n.add(oe,D),D=n.mul(B,D),B=n.mul(W,B),O=n.mul(m,O),Q=n.mul(b,Q),W=n.sub(U,Q),W=n.mul(b,W),W=n.add(W,O),O=n.add(U,U),U=n.add(O,U),U=n.add(U,Q),U=n.mul(U,W),D=n.add(D,U),Q=n.mul(I,C),Q=n.add(Q,Q),U=n.mul(Q,W),B=n.sub(B,U),O=n.mul(Q,oe),O=n.add(O,O),O=n.add(O,O),new E(B,D,O)}add(b){T(b);let{X:g,Y:m,Z:_}=this,{X:I,Y:C,Z:B}=b,D=n.ZERO,O=n.ZERO,U=n.ZERO,oe=o.a,Q=n.mul(o.b,Yn),W=n.mul(g,I),se=n.mul(m,C),me=n.mul(_,B),ze=n.add(g,m),ie=n.add(I,C);ze=n.mul(ze,ie),ie=n.add(W,se),ze=n.sub(ze,ie),ie=n.add(g,_);let ge=n.add(I,B);return ie=n.mul(ie,ge),ge=n.add(W,me),ie=n.sub(ie,ge),ge=n.add(m,_),D=n.add(C,B),ge=n.mul(ge,D),D=n.add(se,me),ge=n.sub(ge,D),U=n.mul(oe,ie),D=n.mul(Q,me),U=n.add(D,U),D=n.sub(se,U),U=n.add(se,U),O=n.mul(D,U),se=n.add(W,W),se=n.add(se,W),me=n.mul(oe,me),ie=n.mul(Q,ie),se=n.add(se,me),me=n.sub(W,me),me=n.mul(oe,me),ie=n.add(ie,me),W=n.mul(se,ie),O=n.add(O,W),W=n.mul(ge,ie),D=n.mul(ze,D),D=n.sub(D,W),W=n.mul(ze,se),U=n.mul(ge,U),U=n.add(U,W),new E(D,O,U)}subtract(b){return this.add(b.negate())}is0(){return this.equals(E.ZERO)}multiply(b){let{endo:g}=e;if(!s.isValidNot0(b))throw new Error("invalid scalar: out of range");let m,_,I=C=>V.cached(this,C,B=>Ht(E,B));if(g){let{k1neg:C,k1:B,k2neg:D,k2:O}=P(b),{p:U,f:oe}=I(B),{p:Q,f:W}=I(O);_=oe.add(W),m=v(g.beta,U,Q,C,D)}else{let{p:C,f:B}=I(b);m=C,_=B}return Ht(E,[m,_])[0]}multiplyUnsafe(b){let{endo:g}=e,m=this;if(!s.isValid(b))throw new Error("invalid scalar: out of range");if(b===lt||m.is0())return E.ZERO;if(b===xr)return m;if(V.hasCache(this))return this.multiply(b);if(g){let{k1neg:_,k1:I,k2neg:C,k2:B}=P(b),{p1:D,p2:O}=$c(E,m,I,B);return v(g.beta,D,O,_,C)}else return V.unsafe(m,b)}toAffine(b){return M(this,b)}isTorsionFree(){let{isTorsionFree:b}=e;return i===xr?!0:b?b(E,this):V.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:b}=e;return i===xr?this:b?b(E,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(b=!0){return ct(b,"isCompressed"),this.assertValidity(),p(E,this,b)}toHex(b=!0){return st(this.toBytes(b))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let N=s.BITS,V=new mr(E,e.endo?Math.ceil(N/2):N);return E.BASE.precompute(8),E}function _u(r){return Uint8Array.of(r?2:3)}function Au(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function ch(r,e={}){let{Fn:t}=r,n=e.randomBytes||lr,s=Object.assign(Au(r.Fp,t),{seed:Os(t.ORDER)});function o(p){try{let h=t.fromBytes(p);return t.isValidNot0(h)}catch{return!1}}function i(p,h){let{publicKey:S,publicKeyUncompressed:x}=s;try{let y=p.length;return h===!0&&y!==S||h===!1&&y!==x?!1:!!r.fromBytes(p)}catch{return!1}}function a(p=n(s.seed)){return Ps(k(p,s.seed,"seed"),t.ORDER)}function c(p,h=!0){return r.BASE.multiply(t.fromBytes(p)).toBytes(h)}function l(p){let{secretKey:h,publicKey:S,publicKeyUncompressed:x}=s;if(!Pt(p)||"_lengths"in t&&t._lengths||h===S)return;let y=k(p,void 0,"key").length;return y===S||y===x}function u(p,h,S=!0){if(l(p)===!0)throw new Error("first arg must be private key");if(l(h)===!1)throw new Error("second arg must be public key");let x=t.fromBytes(p);return r.fromBytes(h).multiply(x).toBytes(S)}let f={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a},d=Nn(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:d,Point:r,utils:f,lengths:s})}function Tu(r,e,t={}){Dn(e),Et(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let n=t.randomBytes||lr,s=t.hmac||((g,m)=>wi(e,g,m)),{Fp:o,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:u,getSharedSecret:f,utils:d,lengths:p}=ch(r,t),h={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},S=a*Su<o.ORDER;function x(g){let m=a>>xr;return g>m}function y(g,m){if(!i.isValidNot0(m))throw new Error(`invalid signature ${g}: out of range 1..Point.Fn.ORDER`);return m}function A(){if(S)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function w(g,m){Si(m);let _=p.signature,I=m==="compact"?_:m==="recovered"?_+1:void 0;return k(g,I)}class T{r;s;recovery;constructor(m,_,I){if(this.r=y("r",m),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(m,_=h.format){w(m,_);let I;if(_==="der"){let{r:O,s:U}=At.toSig(k(m));return new T(O,U)}_==="recovered"&&(I=m[0],_="compact",m=m.subarray(1));let C=p.signature/2,B=m.subarray(0,C),D=m.subarray(C,C*2);return new T(i.fromBytes(B),i.fromBytes(D),I)}static fromHex(m,_){return this.fromBytes(it(m),_)}assertRecovery(){let{recovery:m}=this;if(m==null)throw new Error("invalid recovery id: must be present");return m}addRecoveryBit(m){return new T(this.r,this.s,m)}recoverPublicKey(m){let{r:_,s:I}=this,C=this.assertRecovery(),B=C===2||C===3?_+a:_;if(!o.isValid(B))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let D=o.toBytes(B),O=r.fromBytes(Ie(_u((C&1)===0),D)),U=i.inv(B),oe=M(k(m,void 0,"msgHash")),Q=i.create(-oe*U),W=i.create(I*U),se=r.BASE.multiplyUnsafe(Q).add(O.multiplyUnsafe(W));if(se.is0())throw new Error("invalid recovery: point at infinify");return se.assertValidity(),se}hasHighS(){return x(this.s)}toBytes(m=h.format){if(Si(m),m==="der")return it(At.hexFromSig(this));let{r:_,s:I}=this,C=i.toBytes(_),B=i.toBytes(I);return m==="recovered"?(A(),Ie(Uint8Array.of(this.assertRecovery()),C,B)):Ie(C,B)}toHex(m){return st(this.toBytes(m))}}let P=t.bits2int||function(m){if(m.length>8192)throw new Error("input is too large");let _=fr(m),I=m.length*8-c;return I>0?_>>BigInt(I):_},M=t.bits2int_modN||function(m){return i.create(P(m))},q=Fr(c);function v(g){return Vr("num < 2^"+c,g,lt,q),i.toBytes(g)}function E(g,m){return k(g,void 0,"message"),m?k(e(g),void 0,"prehashed message"):g}function N(g,m,_){let{lowS:I,prehash:C,extraEntropy:B}=Ei(_,h);g=E(g,C);let D=M(g),O=i.fromBytes(m);if(!i.isValidNot0(O))throw new Error("invalid private key");let U=[v(O),v(D)];if(B!=null&&B!==!1){let se=B===!0?n(p.secretKey):B;U.push(k(se,void 0,"extraEntropy"))}let oe=Ie(...U),Q=D;function W(se){let me=P(se);if(!i.isValidNot0(me))return;let ze=i.inv(me),ie=r.BASE.multiply(me).toAffine(),ge=i.create(ie.x);if(ge===lt)return;let mn=i.create(ze*i.create(Q+ge*O));if(mn===lt)return;let Ia=(ie.x===ge?0:2)|Number(ie.y&xr),Da=mn;return I&&x(mn)&&(Da=i.neg(mn),Ia^=1),new T(ge,Da,S?void 0:Ia)}return{seed:oe,k2sig:W}}function V(g,m,_={}){let{seed:I,k2sig:C}=N(g,m,_);return Dc(e.outputLen,i.BYTES,s)(I,C).toBytes(_.format)}function L(g,m,_,I={}){let{lowS:C,prehash:B,format:D}=Ei(I,h);if(_=k(_,void 0,"publicKey"),m=E(m,B),!Pt(g)){let O=g instanceof T?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+O)}w(g,D);try{let O=T.fromBytes(g,D),U=r.fromBytes(_);if(C&&O.hasHighS())return!1;let{r:oe,s:Q}=O,W=M(m),se=i.inv(Q),me=i.create(W*se),ze=i.create(oe*se),ie=r.BASE.multiplyUnsafe(me).add(U.multiplyUnsafe(ze));return ie.is0()?!1:i.create(ie.x)===oe}catch{return!1}}function b(g,m,_={}){let{prehash:I}=Ei(_,h);return m=E(m,I),T.fromBytes(g,"recovered").recoverPublicKey(m).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:f,utils:d,lengths:p,Point:r,sign:V,verify:L,recoverPublicKey:b,Signature:T,hash:e})}var Ai={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},uh={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Iu=BigInt(2);function lh(r){let e=Ai.p,t=BigInt(3),n=BigInt(6),s=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,f=ee(u,t,e)*u%e,d=ee(f,t,e)*u%e,p=ee(d,Iu,e)*l%e,h=ee(p,s,e)*p%e,S=ee(h,o,e)*h%e,x=ee(S,a,e)*S%e,y=ee(x,c,e)*x%e,A=ee(y,a,e)*S%e,w=ee(A,t,e)*u%e,T=ee(w,i,e)*h%e,P=ee(T,n,e)*l%e,M=ee(P,Iu,e);if(!_i.eql(_i.sqr(M),r))throw new Error("Cannot find square root");return M}var _i=hr(Ai.p,{sqrt:lh}),fh=vu(Ai,{Fp:_i,endo:uh}),wr=Tu(fh,_c);function Du(r,e,t,n){let s=ar.digest(t instanceof Uint8Array?t:t.subarray());if(Mn(s))return s.then(({digest:o})=>(n?.signal?.throwIfAborted(),wr.verify(e,o,r,{prehash:!1,format:"der"}))).catch(o=>{throw o.name==="AbortError"?o:new Gr(String(o))});try{return n?.signal?.throwIfAborted(),wr.verify(e,s.digest,r,{prehash:!1,format:"der"})}catch(o){throw new Gr(String(o))}}var Zn=class{type="secp256k1";raw;_key;constructor(e){this._key=Lu(e),this.raw=Cu(this._key)}toMultihash(){return Me.digest(We(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 Du(this._key,t,e,n)}};function Ti(r){return new Zn(r)}function Cu(r){return wr.Point.fromBytes(r).toBytes()}function Lu(r){try{return wr.Point.fromBytes(r),r}catch(e){throw new er(String(e))}}function Bu(r,e){let{Type:t,Data:n}=Xe.decode(r),s=n??new Uint8Array;switch(t){case ne.RSA:return bi(s,e);case ne.Ed25519:return Vs(s);case ne.secp256k1:return Ti(s);case ne.ECDSA:return bs(s);default:throw new tr}}function Ru(r){let{Type:e,Data:t}=Xe.decode(r.digest),n=t??new Uint8Array;switch(e){case ne.Ed25519:return Vs(n);case ne.secp256k1:return Ti(n);case ne.ECDSA:return bs(n);default:throw new tr}}function We(r){return Xe.encode({Type:ne[r.type],Data:r.raw})}var Ou=Symbol.for("nodejs.util.inspect.custom"),dh=114,en=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()})`}[Fo]=!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(dh,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")}[Ou](){return`PeerId(${this.toString()})`}},Xn=class extends en{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},jn=class extends en{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},Qn=class extends en{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},hh=2336,tn=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Me.digest(K(this.url))}[Ou](){return`PeerId(${this.url})`}[Fo]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return le.createV1(hh,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=$(e)),e.toString()===this.toString())}};var ph=114,Pu=2336;function Ii(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=Ge(te.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return mh(le.parse(r));if(e==null)throw new ae('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=Ge(e.decode(r))}return Er(t)}function Er(r){if(bh(r))return new Xn({multihash:r});if(yh(r))try{let e=Ru(r);if(e.type==="Ed25519")return new jn({multihash:r,publicKey:e});if(e.type==="secp256k1")return new Qn({multihash:r,publicKey:e})}catch{let t=$(r.digest);return new tn(new URL(t))}throw new gn("Supplied PeerID Multihash is invalid")}function mh(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==ph&&r.code!==Pu)throw new bn("Supplied PeerID CID is invalid");if(r.code===Pu){let e=$(r.multihash.digest);return new tn(new URL(e))}return Er(r.multihash)}function yh(r){return r.code===Me.code}function bh(r){return r.code===ar.code}var rn;(function(r){let e;r.codec=()=>(e==null&&(e=Re((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.publicKey!=null&&o.publicKey.byteLength>0&&(i.uint32(10),i.bytes(o.publicKey)),o.payloadType!=null&&o.payloadType.byteLength>0&&(i.uint32(18),i.bytes(o.payloadType)),o.payload!=null&&o.payload.byteLength>0&&(i.uint32(26),i.bytes(o.payload)),o.signature!=null&&o.signature.byteLength>0&&(i.uint32(42),i.bytes(o.signature)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={publicKey:re(0),payloadType:re(0),payload:re(0),signature:re(0)},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.publicKey=o.bytes();break}case 2:{c.payloadType=o.bytes();break}case 3:{c.payload=o.bytes();break}case 5:{c.signature=o.bytes();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{yield{field:`${a}.publicKey`,value:o.bytes()};break}case 2:{yield{field:`${a}.payloadType`,value:o.bytes()};break}case 3:{yield{field:`${a}.payload`,value:o.bytes()};break}case 5:{yield{field:`${a}.signature`,value:o.bytes()};break}default:{o.skipType(u&7);break}}}})),e);function t(o){return Le(o,r.codec())}r.encode=t;function n(o,i){return Ce(o,r.codec(),i)}r.decode=n;function s(o,i){return Be(o,r.codec(),i)}r.stream=s})(rn||(rn={}));var Jn=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var nn=class r{static createFromProtobuf=e=>{let t=rn.decode(e),n=Bu(t.publicKey);return new r({publicKey:n,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t,n)=>{if(t==null)throw new Error("Missing private key");let s=e.domain,o=e.codec,i=e.marshal(),a=Nu(s,o,i),c=await t.sign(a.subarray(),n);return new r({publicKey:t.publicKey,payloadType:o,payload:i,signature:c})};static openAndCertify=async(e,t,n)=>{let s=r.createFromProtobuf(e);if(!await s.validate(t,n))throw new Jn("Envelope signature is not valid for the given domain");return s};publicKey;payloadType;payload;signature;marshaled;constructor(e){let{publicKey:t,payloadType:n,payload:s,signature:o}=e;this.publicKey=t,this.payloadType=n,this.payload=s,this.signature=o}marshal(){return this.marshaled==null&&(this.marshaled=rn.encode({publicKey:We(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=Nu(e,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,t)}},Nu=(r,e,t)=>{let n=K(r),s=br(n.byteLength),o=br(e.length),i=br(t.length);return new J(s,n,o,e,i,t)};var be=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},ft=class extends Error{static name="ValidationError";name="ValidationError"},eo=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},to=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var ro=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,s){return this.readAtomically(()=>{let o=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*s)-1;for(;;){let u=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let d=Number.parseInt(f,e);if(!Number.isNaN(d))return d});if(u===void 0)break;if(o*=e,o+=u,o>l||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:o})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let s=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[s]=i[0],t[s+1]=i[1],t[s+2]=i[2],t[s+3]=i[3],[s+4,!0]}let o=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(o===void 0)return[s,!1];t[s]=o>>8,t[s+1]=o&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,s]=e(t);if(n===16)return t;if(s||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let o=new Uint8Array(14),i=16-(n+2),[a]=e(o.subarray(0,i));return t.set(o.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var gh=45,xh=15,no=new ro;function Uu(r){if(!(r.length>xh))return no.new(r).parseWith(()=>no.readIPv4Addr())}function ku(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>gh))return no.new(r).parseWith(()=>no.readIPv6Addr())}function oo(r){return!!Uu(r)}function Mu(r){return!!ku(r)}function Ci(r){return e=>$(e,r)}function Li(r){return e=>K(e,r)}function Sr(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function $t(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 s=$t(n);return tt([t,s],t.length+s.length)}function Hu(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=yt.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=$t(n);return tt([t,s],t.length+s.length)}function Bi(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=$(e,"base32"),s=Sr(t);return`${n}:${s}`}var Ri=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let s=parseInt(t,10);if(isNaN(s)||s<0||s>255)throw new be("Invalid byte value in IP address");e[n]=s}),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 o=oo(t[n]),i;o&&(i=Ri(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 o=[n,1];for(n=9-t.length;n>0;n--)o.push("0");t.splice.apply(t,o)}let s=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let o=parseInt(t[n],16);if(isNaN(o)||o<0||o>65535)throw new be("Invalid byte value in IP address");s[e++]=o>>8&255,s[e++]=o&255}return s},Vu=function(r){if(r.byteLength!==4)throw new be("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},Fu=function(r){if(r.byteLength!==16)throw new be("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let s=r[n],o=r[n+1],i=`${s.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new be(`Invalid IPv6 address "${t}"`)}};function zu(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new be(`Invalid IPv6 address "${r}"`)}}var Di=Object.values(Nr).map(r=>r.decoder),wh=(function(){let r=Di[0].or(Di[1]);return Di.slice(2).forEach(e=>r=r.or(e)),r})();function $u(r){return wh.decode(r)}function Gu(r){return e=>r.encoder.encode(e)}function Eh(r){if(parseInt(r).toString()!==r)throw new ft("Value must be an integer")}function Sh(r){if(r<0)throw new ft("Value must be a positive integer, or zero")}function vh(r){return e=>{if(e>r)throw new ft(`Value must be smaller than or equal to ${r}`)}}function _h(...r){return e=>{for(let t of r)t(e)}}var on=_h(Eh,Sh,vh(65535));var pe=-1,Oi=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 to(`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)}))}},ht=new Oi,Mh=[{code:4,name:"ip4",size:32,valueToBytes:Ri,bytesToValue:Vu,validate:r=>{if(!oo(r))throw new ft(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:$t,bytesToValue:Sr,validate:on},{code:273,name:"udp",size:16,valueToBytes:$t,bytesToValue:Sr,validate:on},{code:33,name:"dccp",size:16,valueToBytes:$t,bytesToValue:Sr,validate:on},{code:41,name:"ip6",size:128,valueToBytes:qu,bytesToValue:Fu,stringToValue:zu,validate:r=>{if(!Mu(r))throw new ft(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:pe},{code:43,name:"ipcidr",size:8,bytesToValue:Ci("base10"),valueToBytes:Li("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:$t,bytesToValue:Sr,validate:on},{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:Ci("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Li("base58btc")(r):le.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Bi,valueToBytes:Ku},{code:445,name:"onion3",size:296,bytesToValue:Bi,valueToBytes:Hu},{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:Gu(os),valueToBytes:$u},{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}];Mh.forEach(r=>{ht.addProtocol(r)});function Wu(r){let e=[],t=0;for(;t<r.length;){let n=Wr(r,t),s=ht.getProtocol(n),o=De(n),i=Kh(s,r,t+o),a=0;i>0&&s.size===pe&&(a=De(i));let c=o+a+i,l={code:n,name:s.name,bytes:r.subarray(t,t+c)};if(i>0){let u=t+o+a,f=r.subarray(u,u+i);l.value=s.bytesToValue?.(f)??$(f)}e.push(l),t+=c}return e}function Yu(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let s=ht.getProtocol(n.code),o=De(n.code),i,a=0,c=0;n.value!=null&&(i=s.valueToBytes?.(n.value)??K(n.value),a=i.byteLength,s.size===pe&&(c=De(a)));let l=new Uint8Array(o+c+a),u=0;yr(n.code,l,u),u+=o,i!=null&&(s.size===pe&&(yr(a,l,u),u+=c),l.set(i,u)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return tt(t,e)}function Zu(r){if(r.charAt(0)!=="/")throw new be('String multiaddr must start with "/"');let e=[],t="protocol",n="",s="";for(let o=1;o<r.length;o++){let i=r.charAt(o);i!=="/"&&(t==="protocol"?s+=r.charAt(o):n+=r.charAt(o));let a=o===r.length-1;if(i==="/"||a){let c=ht.getProtocol(s);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",s="",t="protocol";continue}else if(a)throw new be(`Component ${s} was missing value`);t="value"}else if(t==="value"){let l={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new be(`Component ${s} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",s="",t="protocol"}}}if(s!==""&&n!=="")throw new be("Incomplete multiaddr");return e}function Xu(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=ht.getProtocol(e.code);if(t==null)throw new be(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function Kh(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:Wr(e,t)}var Hh=Symbol.for("nodejs.util.inspect.custom"),Xi=Symbol.for("@multiformats/multiaddr");function qh(r){if(r==null&&(r="/"),ju(r))return r.getComponents();if(r instanceof Uint8Array)return Wu(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),Zu(r);if(Array.isArray(r))return r;throw new be("Must be a string, Uint8Array, Component[], or another Multiaddr")}var uo=class r{[Xi]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=qh(e),t.validate!==!1&&Vh(this)}get bytes(){return this.#r==null&&(this.#r=Yu(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=Xu(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),s=n.lastIndexOf(t);if(s<0)throw new eo(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,s),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}equals(e){return fe(this.bytes,e.bytes)}[Hh](){return`Multiaddr(${this.toString()})`}};function Vh(r){r.getComponents().forEach(e=>{let t=ht.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function ju(r){return!!r?.[Xi]}function Pe(r){return new uo(r)}var ji={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Qu={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Ju=new globalThis.TextEncoder;function Fh(r,e){let t=ji[e],n=Qu[e];for(let s=0;s<r.length;s++)n^=BigInt(r[s]),n=BigInt.asUintN(e,n*t);return n}function zh(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=ji[e],s=Qu[e],o=r;for(;o.length>0;){let i=Ju.encodeInto(o,t);o=o.slice(i.read);for(let a=0;a<i.written;a++)s^=BigInt(t[a]),s=BigInt.asUintN(e,s*n)}return s}function Qi(r,{size:e=32,utf8Buffer:t}={}){if(!ji[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 zh(r,e,t);r=Ju.encode(r)}return Fh(r,e)}var sn={hash:r=>Number(Qi(r,{size:32})),hashV:(r,e)=>$h(sn.hash(r,e))};function $h(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),K(e,"base16")}var Ji=64,Ve=class{fp;h;seed;constructor(e,t,n,s=2){if(s>Ji)throw new TypeError("Invalid Fingerprint Size");let o=t.hashV(e,n),i=re(s);for(let a=0;a<i.length;a++)i[a]=o[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?fe(this.fp,e.fp):!1}};function Yt(r,e){return Math.floor(Math.random()*(e-r))+r}var Zt=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof Ve))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof Ve))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 Ve))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 Ve))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var Gh=500,an=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??sn,this.seed=e.seed??Yt(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=K(e));let t=new Ve(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new Zt(this.bucketSize)),this.buckets[s]==null&&(this.buckets[s]=new Zt(this.bucketSize)),this.buckets[n].add(t)||this.buckets[s].add(t))return this.count++,!0;let o=[n,s],i=o[Yt(0,o.length-1)];this.buckets[i]==null&&(this.buckets[i]=new Zt(this.bucketSize));for(let a=0;a<Gh;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 Zt(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=K(e));let t=new Ve(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=this.buckets[n]?.has(t)??!1;if(s)return s;let o=(n^t.hash())%this.filterSize;return this.buckets[o]?.has(t)??!1}remove(e){typeof e=="string"&&(e=K(e));let t=new Ve(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=this.buckets[n]?.remove(t)??!1;if(s)return this.count--,s;let o=(n^t.hash())%this.filterSize,i=this.buckets[o]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},Wh={1:.5,2:.84,4:.95,8:.98};function Yh(r=.001){return r>.002?2:r>1e-5?4:8}function el(r,e=.001){let t=Yh(e),n=Wh[t],s=Math.round(r/n),o=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),Ji);return{filterSize:s,bucketSize:t,fingerprintSize:o}}var lo=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??sn,this.seed=e.seed??Yt(0,Math.pow(2,10)),this.filterSeries=[new an({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 an({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 Tr(r,e=.001,t){return new lo({...el(r,e),...t??{}})}function Fe(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var fo=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}},Ir=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new fo(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 fo(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 ea=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Tt(r={}){return Zh(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 Zh(r,e){e=e??{};let t=e.onEnd,n=new Ir,s,o,i,a=Fe(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((x,y)=>{o=A=>{o=null,n.push(A);try{x(r(n))}catch(w){y(w)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Fe()})}},l=x=>o!=null?o(x):(n.push(x),s),u=x=>(n=new Ir,o!=null?o({error:x}):(n.push({error:x}),s)),f=x=>{if(i)return s;if(e?.objectMode!==!0&&x?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:x})},d=x=>i?s:(i=!0,x!=null?u(x):l({done:!0})),p=()=>(n=new Ir,d(),{done:!0}),h=x=>(d(x),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:p,throw:h,push:f,end:d,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 ea)},y.addEventListener("abort",w)}));try{await Promise.race([a.promise,A])}finally{w!=null&&y!=null&&y?.removeEventListener("abort",w)}}},t==null)return s;let S=s;return s={[Symbol.asyncIterator](){return this},next(){return S.next()},throw(x){return S.throw(x),t!=null&&(t(x),t=void 0),{done:!0}},return(){return S.return(),t!=null&&(t(),t=void 0),{done:!0}},push:f,end(x){return S.end(x),t!=null&&(t(x),t=void 0),s},get readableLength(){return S.readableLength},onEmpty:x=>S.onEmpty(x)},s}var ta=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},tl=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function ra(r,e){let{milliseconds:t,fallback:n,message:s,customTimers:o={setTimeout,clearTimeout},signal:i}=e,a,c,u=new Promise((f,d)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(i?.aborted){d(tl(i));return}if(i&&(c=()=>{d(tl(i))},i.addEventListener("abort",c,{once:!0})),r.then(f,d),t===Number.POSITIVE_INFINITY)return;let p=new ta;a=o.setTimeout.call(void 0,()=>{if(n){try{f(n())}catch(h){d(h)}return}typeof r.cancel=="function"&&r.cancel(),s===!1?f():s instanceof Error?d(s):(p.message=s??`Promise timed out after ${t} milliseconds`,d(p))},t)}).finally(()=>{u.clear(),c&&i&&i.removeEventListener("abort",c)});return u.clear=()=>{o.clearTimeout.call(void 0,a),a=void 0},u}var Xh=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 jh(r,e,t){let n,s=new Promise((o,i)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:l,removeListener:u}=Xh(r),f=async(...p)=>{let h=t.multiArgs?p:p[0];if(t.filter)try{if(!await t.filter(h))return}catch(S){n(),i(S);return}c.push(h),t.count===c.length&&(n(),o(c))},d=(...p)=>{n(),i(t.rejectionMultiArgs?p:p[0])};n=()=>{for(let p of a)u(p,f);for(let p of t.rejectionEvents)a.includes(p)||u(p,d)};for(let p of a)l(p,f);for(let p of t.rejectionEvents)a.includes(p)||l(p,d);t.signal&&t.signal.addEventListener("abort",()=>{d(t.signal.reason)},{once:!0}),t.resolveImmediately&&o(c)});if(s.cancel=n,typeof t.timeout=="number"){let o=ra(s,{milliseconds:t.timeout});return o.cancel=()=>{n(),o.clear()},o}return s}function je(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=jh(r,e,t),s=n.then(o=>o[0]);return s.cancel=n.cancel,s}function na(r,e){let t,n=function(){let s=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(s,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var ho=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}},Xt=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"};var po=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function Qh(r){return r.reason}async function It(r,e,t){if(e==null)return r;let n=t?.translateError??Qh;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let s;try{return await Promise.race([r,new Promise((o,i)=>{s=()=>{i(n(e))},e.addEventListener("abort",s)})])}finally{s!=null&&e.removeEventListener("abort",s)}}var mo=class{deferred;signal;onProgress;constructor(e){this.signal=e?.signal,this.onProgress=e?.onProgress,this.deferred=Fe(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Qe)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Jh(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var yo=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=Jh(),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 Qe),this.cleanup())}async join(e){let t=new mo(e);return this.recipients.push(t),e?.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await It(this.fn({...this.options??{},signal:this.controller.signal,onProgress:t=>{this.recipients.forEach(n=>{n.onProgress?.(t)})}}),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 bo=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=na(this.emitEmpty.bind(this),1),this.emitIdle=na(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 ho;let n=new yo(e,t);this.enqueue(n),this.safeDispatchEvent("add");let s=n.join(t).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o});return this.tryToStartAnother(),s}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Qe)}),this.clear()}async onEmpty(e){this.size!==0&&await je(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await je(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await je(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=Tt({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},s=c=>{c.detail!=null&&t.push(c.detail)},o=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new Qe("Queue aborted"))};this.addEventListener("completed",s),this.addEventListener("failure",o),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",s),this.removeEventListener("failure",o),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var ep=Math.pow(2,20)*4,go=class extends _e{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;onDrainPromise;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??ep,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.onDrainPromise?.resolve()};this.addEventListener("drain",t);let n=s=>{this.onDrainPromise?.reject(s.error??new po)};this.addEventListener("close",n)}get readBufferLength(){return this.readBuffer.byteLength}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),It(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let e=Tt(),t=o=>{e.push(o.data)};this.addEventListener("message",t);let n=o=>{e.end(o.error)};this.addEventListener("close",n);let s=()=>{e.end()};this.addEventListener("remoteCloseWrite",s);try{yield*e}finally{this.removeEventListener("message",t),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",s)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new pt(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",e.byteLength),this.writeBuffer.append(e),this.processSendQueue()}abort(e){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",e),this.status="aborted",this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle")),this.writeStatus="closed",this.remoteWriteStatus="closed",this.readStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now();try{this.sendReset(e)}catch(t){this.log("failed to send reset to remote - %e",t)}this.dispatchEvent(new Sn(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new pt("Cannot pause a stream that is closing/closed");this.readStatus!=="paused"&&(this.readStatus="paused",this.sendPause())}resume(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new pt("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new pt(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.append(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}unshift(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new pt(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.prepend(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(e){if(e.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(e),this.dispatchReadBuffer()}}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="message"&&this.readBuffer.byteLength>0&&queueMicrotask(()=>{this.dispatchReadBuffer()})}onRemoteReset(){this.log("remote reset"),this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.readBuffer.byteLength===0&&(this.readStatus="closed");let e=new yn;this.dispatchEvent(new vn(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 rr))}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 s=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(s===0){e=!1;break}let o=this.writeBuffer.sublist(0,s),i=new J(o);this.writeBuffer.consume(o.byteLength);let a=this.sendData(o);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 En(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 Lr(`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 Lr(`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 xo=class extends go{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 je(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 je(this,"drain",{...e,rejectionEvents:["close"]})),await this.sendClose(e),this.onTransportClosed())}};function wo(r){let e=new globalThis.AbortController;function t(){let o=r.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();e.abort(o);for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}for(let o of r){if(o?.aborted===!0){t();break}o?.addEventListener!=null&&o.addEventListener("abort",t)}function n(){for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",t)}let s=e.signal;return s.clear=n,s}var oa=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=Fe(),this.haveNext=Fe()}[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=Fe(),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=Fe(),await It(this.readNext.promise,t?.signal,t)}};function rl(){return new oa}function tp(r){return r[Symbol.asyncIterator]!=null}async function rp(r,e,t){try{await Promise.all(r.map(async n=>{for await(let s of n)await e.push(s,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*np(r){let e=new AbortController,t=rl();rp(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*op(r){for(let e of r)yield*e}function sp(...r){let e=[];for(let t of r)tp(t)||e.push(t);return e.length===r.length?op(e):np(r)}var nl=sp;function ol(r,...e){if(r==null)throw new Error("Empty pipeline");if(sa(r)){let n=r;r=()=>n.source}else if(il(r)||sl(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&sa(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++)sa(t[n])&&(t[n]=ap(t[n]));return ip(...t)}var ip=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},sl=r=>r?.[Symbol.asyncIterator]!=null,il=r=>r?.[Symbol.iterator]!=null,sa=r=>r==null?!1:r.sink!=null&&r.source!=null,ap=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=Tt({objectMode:!0});t.then(()=>{n.end()},i=>{n.end(i)});let s,o=r.source;if(sl(o))s=async function*(){yield*o,n.end()};else if(il(o))s=function*(){yield*o,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return nl(n,s())}return r.source};var cp=4194304,Eo=class extends Error{static name="UnwrappedError";name="UnwrappedError"},aa=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},ca=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},ua=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function up(r){return typeof r?.closeRead=="function"}function lp(r){return typeof r?.close=="function"}function ia(r){return up(r)?r.remoteWriteStatus!=="writable"&&r.readBufferLength===0:lp(r)?r.status!=="open":!1}function fp(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function dp(r,e){let t=e?.maxBufferSize??cp,n=new J,s,o=!1;if(!fp(r))throw new ae("Argument should be a Stream or a Multiaddr");let i=u=>{if(n.append(u.data),n.byteLength>t){let f=n.byteLength;n.consume(n.byteLength),s?.reject(new Error(`Read buffer overflow - ${f} > ${t}`))}s?.resolve()};r.addEventListener("message",i);let a=u=>{u.error!=null?s?.reject(u.error):s?.resolve()};r.addEventListener("close",a);let c=()=>{s?.resolve()};r.addEventListener("remoteCloseWrite",c);let l={readBuffer:n,async read(u){if(o===!0)throw new Eo("Stream was unwrapped");if(ia(r)){if(n.byteLength===0&&u?.bytes==null)return null;if(u?.bytes!=null&&n.byteLength<u.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,u.bytes),new Xt(`Unexpected EOF - stream closed after reading ${n.byteLength}/${u.bytes} bytes`)}let f=u?.bytes??1;for(s=Promise.withResolvers();;){if(n.byteLength>=f){s.resolve();break}if(await It(s.promise,u?.signal),ia(r)){if(n.byteLength===0&&u?.bytes==null)return null;break}s=Promise.withResolvers()}let d=u?.bytes??n.byteLength;if(n.byteLength<d){if(ia(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,d),new Xt(`Unexpected EOF - stream closed while reading ${n.byteLength}/${d} bytes`);return l.read(u)}let p=n.sublist(0,d);return n.consume(d),p},async write(u,f){if(o===!0)throw new Eo("Stream was unwrapped");r.send(u)||await je(r,"drain",{signal:f?.signal,rejectionEvents:["close"]})},unwrap(){return o||(o=!0,r.removeEventListener("message",i),r.removeEventListener("close",a),r.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.push(n))),r}};return l}function hp(r,e={}){let t=dp(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=De(e.maxDataLength));let n=e?.lengthDecoder??Wr,s=e?.lengthEncoder??br;return{async read(i){let a=-1,c=new J;for(;;){let u=await t.read({...i,bytes:1});if(u==null)break;c.append(u);try{a=n(c)}catch(f){if(f instanceof RangeError)continue;throw f}if(a<0)throw new aa("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new ua(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new ca(`Message length too long - ${a} > ${e.maxDataLength}`);let l=await t.read({...i,bytes:a});if(l==null)throw r.log.error("tried to read %d bytes but the stream closed",a),new Xt(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(l.byteLength!==a)throw r.log.error("read %d/%d bytes before the stream closed",l.byteLength,a),new Xt(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(i,a){await t.write(new J(s(i.byteLength),i),a)},async writeV(i,a){let c=new J(...i.flatMap(l=>[s(l.byteLength),l]));await t.write(c,a)},unwrap(){return t.unwrap()}}}function Dt(r,e){let t=hp(r,e),n={read:async(s,o)=>{let i=await t.read(o);return s.decode(i)},write:async(s,o,i)=>{await t.write(o.encode(s),i)},writeV:async(s,o,i)=>{await t.writeV(s.map(a=>o.encode(a)),i)},pb:s=>({read:async o=>n.read(s,o),write:async(o,i)=>n.write(o,s,i),writeV:async(o,i)=>n.writeV(o,s,i),unwrap:()=>n}),unwrap:()=>t.unwrap()};return n}function pp(r){return r?.addEventListener!=null}function mp(r){let e=Tt(),t,n=i=>{e.push(i.data)},s=()=>{e.end(),r.removeEventListener("message",n),r.removeEventListener("close",o),r.removeEventListener("remoteCloseWrite",s)},o=i=>{e.end(i.error),i.error!=null&&t?.reject(i.error),r.removeEventListener("message",n),r.removeEventListener("close",o),r.removeEventListener("remoteCloseWrite",s)};return r.addEventListener("message",n),r.addEventListener("close",o,{once:!0}),r.addEventListener("remoteCloseWrite",s,{once:!0}),{source:e,async sink(i){async function*a(){yield*i}let c=a();for(;;){t=Promise.withResolvers();let{done:l,value:u}=await Promise.race([c.next(),t.promise]);if(r.writeStatus==="closing"||r.writeStatus==="closed"||(u!=null&&(r.send(u)||await Promise.race([je(r,"drain",{rejectionEvents:["close"]})])),l===!0))break}await r.close()}}}function al(...r){let e=r.map(t=>pp(t)?mp(t):t);return ol(...e)}var Dr=class extends bo{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)}}),cl=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 s=n.match(e);s!==!1&&(t==null||s.length<t.length)&&(t=s)}return t??!1}}),z=(...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(s){if(s==null)return!1;let o=s.getComponents();for(let i of r){let a=i.match(o);if(a===!1)return!1;o=a}return o}function t(s){return e(s)!==!1}function n(s){let o=e(s);return o===!1?!1:o.length===0}return{matchers:r,matches:t,exactMatch:n}}var yp=R(421),O2=j(yp),vo=R(54),_o=R(55),Ao=R(56),fa=R(53),P2=j(vo,F(R(421))),N2=j(_o,F(R(421))),U2=j(Ao,F(R(421))),k2=j(Ee(fa,Ao,vo,_o),F(R(421))),ul=z(R(4),F(R(43))),ll=z(F(R(42)),R(41),F(R(43))),da=Ee(ul,ll),Cr=Ee(da,fa,vo,_o,Ao),M2=j(Ee(da,z(Ee(fa,Ao,vo,_o),F(R(421))))),K2=j(ul),H2=j(ll),q2=j(da),ha=z(Cr,R(6)),cn=z(Cr,R(273)),V2=j(z(ha,F(R(421)))),F2=j(cn),pa=z(cn,X(460),F(R(421))),To=z(cn,X(461),F(R(421))),bp=Ee(pa,To),z2=j(pa),$2=j(To),la=Ee(Cr,ha,cn,pa,To),fl=Ee(z(la,X(477),F(R(421)))),G2=j(fl),dl=Ee(z(la,X(478),F(R(421))),z(la,X(448),F(R(449)),X(477),F(R(421)))),W2=j(dl),hl=z(cn,X(280),F(R(466)),F(R(466)),F(R(421))),Y2=j(hl),pl=z(To,X(465),F(R(466)),F(R(466)),F(R(421))),Z2=j(pl),So=Ee(fl,dl,z(ha,F(R(421))),z(bp,F(R(421))),z(Cr,F(R(421))),hl,pl,R(421)),ml=j(So),gp=z(F(So),X(290),cl(X(281)),F(R(421))),jt=j(gp),xp=Ee(z(So,X(290),X(281),F(R(421))),z(So,X(281),F(R(421))),z(X(281),F(R(421)))),X2=j(xp),wp=z(Cr,Ee(z(R(6,"80")),z(R(6),X(480)),X(480)),F(R(481)),F(R(421))),j2=j(wp),Ep=z(Cr,Ee(z(R(6,"443")),z(R(6,"443"),X(480)),z(R(6),X(443)),z(R(6),X(448),X(480)),z(X(448),X(480)),X(448),X(443)),F(R(481)),F(R(421))),Q2=j(Ep),Sp=Ee(z(R(777),F(R(421)))),J2=j(Sp),vp=Ee(z(R(400),F(R(421)))),e1=j(vp);var ma=1e3,yl=60*ma,bl=15,gl=120*yl,xl=1,Io=5e3,wl=100,ya="circuit-relay-source",un=`${Ca}-circuit-relay`,El=2*yl,Sl=BigInt(1<<17),ke="/libp2p/circuit/relay/0.2.0/hop",Qt="/libp2p/circuit/relay/0.2.0/stop",vl=30*ma,n1=30*ma,ln=300,_l=4096,Al=.001;var Z;(function(r){let e;(function(a){a.RESERVE="RESERVE",a.CONNECT="CONNECT",a.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(a){a[a.RESERVE=0]="RESERVE",a[a.CONNECT=1]="CONNECT",a[a.STATUS=2]="STATUS"})(t||(t={})),(function(a){a.codec=()=>Ft(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Re((a,c,l={})=>{l.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),r.Type.codec().encode(a.type,c)),a.peer!=null&&(c.uint32(18),Ct.codec().encode(a.peer,c)),a.reservation!=null&&(c.uint32(26),fn.codec().encode(a.reservation,c)),a.limit!=null&&(c.uint32(34),Lt.codec().encode(a.limit,c)),a.status!=null&&(c.uint32(40),H.codec().encode(a.status,c)),l.lengthDelimited!==!1&&c.ldelim()},(a,c,l={})=>{let u={},f=c==null?a.len:a.pos+c;for(;a.pos<f;){let d=a.uint32();switch(d>>>3){case 1:{u.type=r.Type.codec().decode(a);break}case 2:{u.peer=Ct.codec().decode(a,a.uint32(),{limits:l.limits?.peer});break}case 3:{u.reservation=fn.codec().decode(a,a.uint32(),{limits:l.limits?.reservation});break}case 4:{u.limit=Lt.codec().decode(a,a.uint32(),{limits:l.limits?.limit});break}case 5:{u.status=H.codec().decode(a);break}default:{a.skipType(d&7);break}}}return u},function*(a,c,l,u={}){let f=c==null?a.len:a.pos+c;for(;a.pos<f;){let d=a.uint32();switch(d>>>3){case 1:{yield{field:`${l}.type`,value:r.Type.codec().decode(a)};break}case 2:{yield*Ct.codec().stream(a,a.uint32(),`${l}.peer`,{limits:u.limits?.peer});break}case 3:{yield*fn.codec().stream(a,a.uint32(),`${l}.reservation`,{limits:u.limits?.reservation});break}case 4:{yield*Lt.codec().stream(a,a.uint32(),`${l}.limit`,{limits:u.limits?.limit});break}case 5:{yield{field:`${l}.status`,value:H.codec().decode(a)};break}default:{a.skipType(d&7);break}}}})),n);function s(a){return Le(a,r.codec())}r.encode=s;function o(a,c){return Ce(a,r.codec(),c)}r.decode=o;function i(a,c){return Be(a,r.codec(),c)}r.stream=i})(Z||(Z={}));var Ne;(function(r){let e;(function(a){a.CONNECT="CONNECT",a.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(a){a[a.CONNECT=0]="CONNECT",a[a.STATUS=1]="STATUS"})(t||(t={})),(function(a){a.codec=()=>Ft(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Re((a,c,l={})=>{l.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),r.Type.codec().encode(a.type,c)),a.peer!=null&&(c.uint32(18),Ct.codec().encode(a.peer,c)),a.limit!=null&&(c.uint32(26),Lt.codec().encode(a.limit,c)),a.status!=null&&(c.uint32(32),H.codec().encode(a.status,c)),l.lengthDelimited!==!1&&c.ldelim()},(a,c,l={})=>{let u={},f=c==null?a.len:a.pos+c;for(;a.pos<f;){let d=a.uint32();switch(d>>>3){case 1:{u.type=r.Type.codec().decode(a);break}case 2:{u.peer=Ct.codec().decode(a,a.uint32(),{limits:l.limits?.peer});break}case 3:{u.limit=Lt.codec().decode(a,a.uint32(),{limits:l.limits?.limit});break}case 4:{u.status=H.codec().decode(a);break}default:{a.skipType(d&7);break}}}return u},function*(a,c,l,u={}){let f=c==null?a.len:a.pos+c;for(;a.pos<f;){let d=a.uint32();switch(d>>>3){case 1:{yield{field:`${l}.type`,value:r.Type.codec().decode(a)};break}case 2:{yield*Ct.codec().stream(a,a.uint32(),`${l}.peer`,{limits:u.limits?.peer});break}case 3:{yield*Lt.codec().stream(a,a.uint32(),`${l}.limit`,{limits:u.limits?.limit});break}case 4:{yield{field:`${l}.status`,value:H.codec().decode(a)};break}default:{a.skipType(d&7);break}}}})),n);function s(a){return Le(a,r.codec())}r.encode=s;function o(a,c){return Ce(a,r.codec(),c)}r.decode=o;function i(a,c){return Be(a,r.codec(),c)}r.stream=i})(Ne||(Ne={}));var Ct;(function(r){let e;r.codec=()=>(e==null&&(e=Re((o,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),o.id!=null&&o.id.byteLength>0&&(i.uint32(10),i.bytes(o.id)),o.addrs!=null&&o.addrs.length>0)for(let c of o.addrs)i.uint32(18),i.bytes(c);a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={id:re(0),addrs:[]},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.id=o.bytes();break}case 2:{if(a.limits?.addrs!=null&&c.addrs.length===a.limits.addrs)throw new zt('Decode error - repeated field "addrs" had too many elements');c.addrs.push(o.bytes());break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l={addrs:0},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let f=o.uint32();switch(f>>>3){case 1:{yield{field:`${a}.id`,value:o.bytes()};break}case 2:{if(c.limits?.addrs!=null&&l.addrs===c.limits.addrs)throw new zt('Streaming decode error - repeated field "addrs" had too many elements');yield{field:`${a}.addrs[]`,index:l.addrs,value:o.bytes()},l.addrs++;break}default:{o.skipType(f&7);break}}}})),e);function t(o){return Le(o,r.codec())}r.encode=t;function n(o,i){return Ce(o,r.codec(),i)}r.decode=n;function s(o,i){return Be(o,r.codec(),i)}r.stream=s})(Ct||(Ct={}));var fn;(function(r){let e;r.codec=()=>(e==null&&(e=Re((o,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),o.expire!=null&&o.expire!==0n&&(i.uint32(8),i.uint64(o.expire)),o.addrs!=null&&o.addrs.length>0)for(let c of o.addrs)i.uint32(18),i.bytes(c);o.voucher!=null&&(i.uint32(26),dn.codec().encode(o.voucher,i)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={expire:0n,addrs:[]},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.expire=o.uint64();break}case 2:{if(a.limits?.addrs!=null&&c.addrs.length===a.limits.addrs)throw new zt('Decode error - repeated field "addrs" had too many elements');c.addrs.push(o.bytes());break}case 3:{c.voucher=dn.codec().decode(o,o.uint32(),{limits:a.limits?.voucher});break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l={addrs:0},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let f=o.uint32();switch(f>>>3){case 1:{yield{field:`${a}.expire`,value:o.uint64()};break}case 2:{if(c.limits?.addrs!=null&&l.addrs===c.limits.addrs)throw new zt('Streaming decode error - repeated field "addrs" had too many elements');yield{field:`${a}.addrs[]`,index:l.addrs,value:o.bytes()},l.addrs++;break}case 3:{yield*dn.codec().stream(o,o.uint32(),`${a}.voucher`,{limits:c.limits?.voucher});break}default:{o.skipType(f&7);break}}}})),e);function t(o){return Le(o,r.codec())}r.encode=t;function n(o,i){return Ce(o,r.codec(),i)}r.decode=n;function s(o,i){return Be(o,r.codec(),i)}r.stream=s})(fn||(fn={}));var Lt;(function(r){let e;r.codec=()=>(e==null&&(e=Re((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.duration!=null&&(i.uint32(8),i.uint32(o.duration)),o.data!=null&&(i.uint32(16),i.uint64(o.data)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.duration=o.uint32();break}case 2:{c.data=o.uint64();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{yield{field:`${a}.duration`,value:o.uint32()};break}case 2:{yield{field:`${a}.data`,value:o.uint64()};break}default:{o.skipType(u&7);break}}}})),e);function t(o){return Le(o,r.codec())}r.encode=t;function n(o,i){return Ce(o,r.codec(),i)}r.decode=n;function s(o,i){return Be(o,r.codec(),i)}r.stream=s})(Lt||(Lt={}));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 ba;(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"})(ba||(ba={}));(function(r){r.codec=()=>Ft(ba)})(H||(H={}));var Jt;(function(r){let e;r.codec=()=>(e==null&&(e=Re((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.relay!=null&&o.relay.byteLength>0&&(i.uint32(10),i.bytes(o.relay)),o.peer!=null&&o.peer.byteLength>0&&(i.uint32(18),i.bytes(o.peer)),o.expiration!=null&&o.expiration!==0n&&(i.uint32(24),i.uint64(o.expiration)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={relay:re(0),peer:re(0),expiration:0n},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.relay=o.bytes();break}case 2:{c.peer=o.bytes();break}case 3:{c.expiration=o.uint64();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{yield{field:`${a}.relay`,value:o.bytes()};break}case 2:{yield{field:`${a}.peer`,value:o.bytes()};break}case 3:{yield{field:`${a}.expiration`,value:o.uint64()};break}default:{o.skipType(u&7);break}}}})),e);function t(o){return Le(o,r.codec())}r.encode=t;function n(o,i){return Ce(o,r.codec(),i)}r.decode=n;function s(o,i){return Be(o,r.codec(),i)}r.stream=s})(Jt||(Jt={}));var dn;(function(r){let e;r.codec=()=>(e==null&&(e=Re((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.publicKey!=null&&o.publicKey.byteLength>0&&(i.uint32(10),i.bytes(o.publicKey)),o.payloadType!=null&&o.payloadType.byteLength>0&&(i.uint32(18),i.bytes(o.payloadType)),o.payload!=null&&(i.uint32(26),Jt.codec().encode(o.payload,i)),o.signature!=null&&o.signature.byteLength>0&&(i.uint32(42),i.bytes(o.signature)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={publicKey:re(0),payloadType:re(0),signature:re(0)},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.publicKey=o.bytes();break}case 2:{c.payloadType=o.bytes();break}case 3:{c.payload=Jt.codec().decode(o,o.uint32(),{limits:a.limits?.payload});break}case 5:{c.signature=o.bytes();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{yield{field:`${a}.publicKey`,value:o.bytes()};break}case 2:{yield{field:`${a}.payloadType`,value:o.bytes()};break}case 3:{yield*Jt.codec().stream(o,o.uint32(),`${a}.payload`,{limits:c.limits?.payload});break}case 5:{yield{field:`${a}.signature`,value:o.bytes()};break}default:{o.skipType(u&7);break}}}})),e);function t(o){return Le(o,r.codec())}r.encode=t;function n(o,i){return Ce(o,r.codec(),i)}r.decode=n;function s(o,i){return Be(o,r.codec(),i)}r.stream=s})(dn||(dn={}));var Do=class extends Error{constructor(e="Transfer limit error"){super(e),this.name="TransferLimitError"}},Co=class extends Error{constructor(e="Duration limit error"){super(e),this.name="DurationLimitError"}},hn=class extends Error{static name="HadEnoughRelaysError";name="HadEnoughRelaysError"},Lo=class extends Error{static name="DoubleRelayError";name="DoubleRelayError"},Bo=class extends Error{static name="RelayQueueFullError";name="RelayQueueFullError"};function Tl(r,e,t){let n=e.remaining,s=o=>{let i=BigInt(o.data.byteLength);e.remaining-=i,e.remaining<0&&r.abort(new Do(`data limit of ${n} bytes exceeded`))};r.addEventListener("message",s)}function Il(r,e,t,n,s){function o(u){r.abort(u),e.abort(u)}let i=[t,n.signal];if(n.limit?.duration!=null){s.log("limiting relayed connection duration to %dms",n.limit.duration);let u=AbortSignal.timeout(n.limit.duration);i.push(u)}let a=wo(i);let c;n.limit?.data!=null&&(c={remaining:n.limit.data});let l=()=>{let u;t.aborted?u=t.reason:u=new Co(`duration limit of ${n.limit?.duration} ms exceeded`),o(u)};a.addEventListener("abort",l,{once:!0}),c!=null&&(Tl(e,c,s),Tl(r,c,s)),al(r,e,r).catch(u=>{o(u)}).finally(()=>{a.clear()})}function ga(r){let e=r*BigInt(1e3),t=new Date().getTime();return Number(e-BigInt(t))}var pn=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}},Ro=j(z(ml.matchers[0],X(290))),Oo=j(X(290));function Po(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),s=n.value;return n.done===!0||s==null?{done:!0,value:void 0}:{done:!1,value:e(s)}}};return t}var Bt=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 Po(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 Po(this.map.values(),e=>e.key)}values(){return Po(this.map.values(),e=>e.value)}get size(){return this.map.size}};var No=class{filter;constructor(e,t){this.filter=Tr(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 xa(r,e=.001){return new No(r,e)}var wa=class extends Bt{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 Ea(r){let{name:e,metrics:t}=r,n;return t!=null?n=new wa({name:e,metrics:t}):n=new Bt,n}var Sa=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 Sa(e?.errorMessage,e?.errorCode,e?.errorName),n=new AbortController,s=()=>{n.abort(t)},o=AbortSignal.timeout(r);o.addEventListener("abort",s);let i=n.signal;return i.reset=a=>{o?.removeEventListener("abort",s),o=AbortSignal.timeout(a??r),o.addEventListener("abort",()=>{n.abort(t)})},i.clear=()=>{o?.removeEventListener("abort",s),o=void 0},i}var Uo=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??gl,this.defaultDurationLimit=t.defaultDurationLimit??El,this.defaultDataLimit=t.defaultDataLimit??Sl,this.reservations=Ea({metrics:e.metrics,name:"libp2p_circuit_relay_server_reservations_total"})}reserve(e,t,n){let s=this.reservations.get(e);if(this.reservations.size>=this.maxReservations&&s==null)return{status:H.RESERVATION_REFUSED};let o=new Date(Date.now()+this.reservationTtl),i;return this.applyDefaultLimit&&(i=n??{data:this.defaultDataLimit,duration:this.defaultDurationLimit}),s!=null?(this.log("refreshing reservation for client %p",e),s.signal.reset(this.reservationTtl)):(this.log("creating new reservation for client %p",e),s={addr:t,expiry:o,limit:i,signal:Dl(this.reservationTtl)}),this.reservations.set(e,s),s.signal.addEventListener("abort",()=>{this.reservations.delete(e)}),{status:H.OK,expire:Math.round(o.getTime()/1e3)}}removeReservation(e){this.reservations.delete(e)}get(e){return this.reservations.get(e)}clear(){this.reservations.clear()}};var ko=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 Jt.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 _p={maxOutboundStopStreams:ln},Mo=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??vl,this.maxInboundHopStreams=t.maxInboundHopStreams,this.maxOutboundHopStreams=t.maxOutboundHopStreams,this.maxOutboundStopStreams=t.maxOutboundStopStreams??_p.maxOutboundStopStreams,this.reservationStore=new Uo(e,t.reservations),this.shutdownController=new AbortController,this.shutdownController.signal,this.onHop=this.onHop.bind(this)}[Symbol.toStringTag]="@libp2p/circuit-relay-v2-server";isStarted(){return this.started}async start(){this.started||(await this.components.registrar.handle(ke,this.onHop,{maxInboundStreams:this.maxInboundHopStreams,maxOutboundStreams:this.maxOutboundHopStreams,runOnLimitedConnection:!0}),this.started=!0)}async stop(){this.reservationStore.clear(),this.shutdownController.abort(),await this.components.registrar.unhandle(ke),this.started=!1}async onHop(e,t){this.log("received circuit v2 hop protocol stream from %p",t.remotePeer);let n=AbortSignal.timeout(this.hopTimeout);let s={signal:n},o=Dt(e);try{let i=await o.pb(Z).read(s);if(i?.type==null)throw new Error("request was invalid, could not read from stream");this.log("received",i.type),await this.handleHopProtocol({connection:t,stream:o,request:i},s)}catch(i){this.log.error("error while handling hop - %e",i),await o.pb(Z).write({type:Z.Type.STATUS,status:H.MALFORMED_MESSAGE},s),e.abort(i)}}async handleHopProtocol({stream:e,request:t,connection:n},s){switch(this.log("received hop message"),t.type){case Z.Type.RESERVE:await this.handleReserve({stream:e,request:t,connection:n},s);break;case Z.Type.CONNECT:await this.handleConnect({stream:e,request:t,connection:n},s);break;default:this.log.error("invalid hop request type %s via peer %p",t.type,n.remotePeer),await e.pb(Z).write({type:Z.Type.STATUS,status:H.UNEXPECTED_MESSAGE})}}async handleReserve({stream:e,connection:t},n){let s=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 s.write({type:Z.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 s.write({type:Z.Type.STATUS,status:H.PERMISSION_DENIED},n);return}let o=this.reservationStore.reserve(t.remotePeer,t.remoteAddr);try{if(o.status!==H.OK){await s.write({type:Z.Type.STATUS,status:o.status},n);return}if(o.expire!=null){let i=o.expire*1e3-Date.now();await this.components.peerStore.merge(t.remotePeer,{tags:{[ya]:{value:1,ttl:i}}},n)}await s.write({type:Z.Type.STATUS,status:H.OK,reservation:await this.makeReservation(t.remotePeer,BigInt(o.expire??0)),limit:this.reservationStore.get(t.remotePeer)?.limit},n),this.log("sent confirmation response to %s",t.remotePeer),await s.unwrap().unwrap().close(n)}catch(i){this.log.error("failed to send confirmation response to %p - %e",t.remotePeer,i),this.reservationStore.removeReservation(t.remotePeer);try{await this.components.peerStore.merge(t.remotePeer,{tags:{[ya]:void 0}},n)}catch(a){this.log.error("failed to untag relay source peer %p - %e",t.remotePeer,a)}}}async makeReservation(e,t){let n=[];for(let o of this.components.addressManager.getAddresses())o.toString().includes("/p2p-circuit")||n.push(o.bytes);let s=await nn.seal(new ko({peer:e,relay:this.components.peerId,expiration:t}),this.components.privateKey);return{addrs:n,expire:t,voucher:{publicKey:We(s.publicKey),payloadType:s.payloadType,payload:{peer:e.toMultihash().bytes,relay:this.components.peerId.toMultihash().bytes,expiration:t},signature:s.signature}}}async handleConnect({stream:e,request:t,connection:n},s){let o=e.pb(Z);if(jt.matches(n.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",n.remotePeer),await o.write({type:Z.Type.STATUS,status:H.PERMISSION_DENIED},s);return}this.log("hop connect request from %p",n.remotePeer);let i;try{if(t.peer==null)throw this.log.error("no peer info in hop connect request"),new Error("no peer info in request");t.peer.addrs.forEach(Pe),i=Er(Ge(t.peer.id))}catch(f){this.log.error("invalid hop connect request via peer %p - %e",n.remotePeer,f),await o.write({type:Z.Type.STATUS,status:H.MALFORMED_MESSAGE},s);return}let a=this.reservationStore.get(i);if(a==null){this.log.error("hop connect denied for destination peer %p not having a reservation for %p with status %s",i,n.remotePeer,H.NO_RESERVATION),await o.write({type:Z.Type.STATUS,status:H.NO_RESERVATION},s);return}if(await this.components.connectionGater.denyOutboundRelayedConnection?.(n.remotePeer,i)===!0){this.log.error("hop connect for %p to %p denied by connection gater",n.remotePeer,i),await o.write({type:Z.Type.STATUS,status:H.PERMISSION_DENIED},s);return}let c=this.components.connectionManager.getConnections(i);if(c.length===0){this.log("hop connect denied for destination peer %p not having a connection for %p as there is no destination connection",i,n.remotePeer),await o.write({type:Z.Type.STATUS,status:H.NO_RESERVATION},s);return}let l=c[0],u=await this.stopHop({connection:l,request:{type:Ne.Type.CONNECT,peer:{id:n.remotePeer.toMultihash().bytes,addrs:[]},limit:a?.limit}},s);if(u==null){this.log.error("failed to open stream to destination peer %p",l?.remotePeer),await o.write({type:Z.Type.STATUS,status:H.CONNECTION_FAILED},s);return}await o.write({type:Z.Type.STATUS,status:H.OK,limit:a?.limit},s),this.log("connection from %p to %p established - merging streams",n.remotePeer,i),Il(e.unwrap(),u,this.shutdownController.signal,a,{log:this.log})}async stopHop({connection:e,request:t},n){this.log("starting circuit relay v2 stop request to %s",e.remotePeer);let s=await e.newStream(Qt,{maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0,...n}),o=Dt(s),i=o.pb(Ne);await i.write(t,n);let a;try{a=await i.read(n)}catch(c){this.log.error("error parsing stop message response from %p - %e",e.remotePeer,c)}if(a==null){this.log.error("could not read response from %p",e.remotePeer),await s.close(n);return}if(a.status===H.OK)return this.log("stop request to %p was successful",e.remotePeer),o.unwrap();this.log("stop request failed with code %d",a.status),await s.close(n)}get reservations(){return this.reservationStore.reservations}};var Rt=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var Ko=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(ke,{filter:this.filter,onConnect:e=>{this.log.trace("discovered relay %p queue (length: %d, active %d)",e,this.queue?.size,this.queue?.running),this.safeDispatchEvent("relay:discover",{detail:e})}}),this.started=!0}stop(){this.topologyId!=null&&this.components.registrar.unregister(this.topologyId),this.running&&this.stopDiscovery(),this.started=!1}startDiscovery(){this.running||(this.log("start discovery"),this.running=!0,this.discoveryController=new AbortController,this.discoveryController.signal,this.components.events.addEventListener("peer:discovery",this.onPeer),Promise.resolve().then(async()=>{this.log("searching peer store for relays");let e=await this.components.peerStore.all({filters:[n=>n.protocols.includes(ke)],orders:[()=>Math.random()<.5?1:-1,(n,s)=>{let o=Cl(n),i=Cl(s);return o>i?-1:i>o?1:0}]});for(let n of e)this.log.trace("found relay peer %p in peer store",n.id),this.safeDispatchEvent("relay:discover",{detail:n.id});this.log("found %d relay peers in peer store",e.length);let t=this.queue=new Dr({concurrency:5});this.log("start random walk");for await(let n of this.components.randomWalk.walk({signal:this.discoveryController.signal})){if(this.log.trace("found random peer %p",n.id),t.has(n.id)){this.log.trace("random peer %p was already in queue",n.id);continue}if(this.components.connectionManager.getConnections(n.id)?.length>0){this.log.trace("random peer %p was already connected",n.id);continue}if(!await this.components.connectionManager.isDialable(n.multiaddrs)){this.log.trace("random peer %p was not dialable",n.id,n.multiaddrs.map(s=>s.toString()));continue}t.queued>10&&(this.log.trace("wait for space in queue for %p",n.id),await t.onSizeLessThan(10,{signal:this.discoveryController.signal})),this.log("adding random peer %p to dial queue (length: %d, active %d)",n.id,t.size,t.running),t.add(this.dialPeer,{peerId:n.id,signal:this.discoveryController.signal}).catch(s=>{this.log.error("error opening connection to random peer %p - %e",n.id,s)})}this.log("stop random walk"),await t.onIdle()}).catch(e=>{this.discoveryController.signal.aborted||this.log.error("failed when finding relays on the network - %e",e)}))}stopDiscovery(){this.log("stop discovery"),this.running=!1,this.discoveryController?.abort(),this.queue?.clear(),this.components.events.removeEventListener("peer:discovery",this.onPeer)}onPeer(e){this.log.trace("maybe dialing discovered peer %p",e.detail.id),this.maybeDialPeer(e).catch(t=>{this.log.trace("error dialing discovered peer %p - %e",e.detail.id,t)})}async maybeDialPeer(e){if(this.queue==null)return;let t=e.detail.id,n=e.detail.multiaddrs;if(this.queue.has(t)){this.log.trace("random peer %p was already in queue",t);return}if(this.components.connectionManager.getConnections(t)?.length>0){this.log.trace("random peer %p was already connected",t);return}if(!await this.components.connectionManager.isDialable(n)){this.log.trace("random peer %p was not dialable",t);return}this.queue?.add(this.dialPeer,{peerId:e.detail.id,signal:this.discoveryController.signal}).catch(s=>{this.log.error("error opening connection to discovered peer %p - %e",e.detail.id,s)})}async dialPeer({peerId:e,signal:t}){let n=wo([AbortSignal.timeout(5e3),t]);try{await this.components.connectionManager.openConnection(e,{signal:n})}finally{n.clear()}}};function Cl(r){let e=r.metadata.get("last-dial-success");return e==null?0:new Date($(e)).getTime()}var _a=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??Io,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(Oo.exactMatch(e))this.log("searching for circuit relay servers"),this.reservationId=this.reservationStore.reserveRelay();else if(Ro.exactMatch(e)){this.log("listen on specific relay server %a",e);let t=AbortSignal.timeout(this.listenTimeout);let n=e.decapsulate("/p2p-circuit"),s=await this.connectionManager.openConnection(n,{signal:t});if(!this.reservationStore.hasReservation(s.remotePeer)){this.log("making reservation on peer %p",s.remotePeer);let o=await this.reservationStore.addRelay(s.remotePeer,"configured");this.addedRelay(o)}}else throw new Ot(`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=>Pe(t).encapsulate("/p2p-circuit")),this.listeningAddrs.forEach(t=>{this.addressManager.confirmObservedAddr(t,{type:"transport"})}),queueMicrotask(()=>{this.safeDispatchEvent("listening")})}};function Ll(r){return new _a(r)}var Bl="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Rl=(r=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)e+=Bl[t[r]&63];return e};var Ap=60*1e3*10,Tp=60*1e3*5,Ip=30*1e3,Ho=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 Bt,this.pendingReservations=[],this.maxReservationQueueLength=t?.maxReservationQueueLength??wl,this.reservationCompletionTimeout=t?.reservationCompletionTimeout??Io,this.started=!1,this.relayFilter=Tr(100),this.reserveQueue=new Dr({concurrency:t?.reservationConcurrency??xl,metricName:"libp2p_relay_reservation_queue",metrics:e.metrics}),this.events.addEventListener("connection:close",n=>{[...this.reservations.values()].find(o=>o.connection===n.detail.id)!=null&&this.#t(n.detail.remotePeer).catch(o=>{this.log("could not remove relay %p - %e",n.detail,o)})})}isStarted(){return this.started}start(){this.started=!0}afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>t.tags.has(un)]});this.log("removing tag from %d old relays",e.length),await Promise.all(e.map(async t=>{await this.peerStore.merge(t.id,{tags:{[un]:void 0}})})),this.log("redialing %d old relays",e.length),await Promise.all(e.map(async t=>this.addRelay(t.id,"discovered"))),this.#r()}).catch(e=>{this.log.error("failed to clean up and redial old relays during afterStart - %e",e)})}stop(){this.reserveQueue.clear(),this.reservations.forEach(({timeout:e})=>{clearTimeout(e)}),this.reservations.clear(),this.started=!1}reserveRelay(){let e=Rl();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 Ot("Cannot use self as relay");if(this.reserveQueue.size>this.maxReservationQueueLength)throw new Bo("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 Ot("The relay was previously invalid");return this.log.trace("try to reserve relay slot with %p",e),this.reserveQueue.add(async()=>{let s=Date.now();try{let o=this.reservations.get(e);if(o!=null){let h=this.connectionManager.getConnections(e),S=!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(o.connection)&&(this.log("already have relay reservation with %p and the original connection is still open",e),S=!0),S&&ga(o.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:o};await this.#t(e)}if(t==="discovered"&&this.pendingReservations.length===0)throw new hn("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 Lo("not creating reservation over relayed connection");let c=await this.#e(a,{signal:i}),l=ga(c.expire);this.log("created reservation on relay peer %p, expiry date is %s",e,new Date(Date.now()+l).toString());let u=Math.min(Math.max(l-Tp,Ip),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)})},u),d;if(t==="discovered"){let h=this.pendingReservations.pop();if(h==null)throw new hn("Made reservation on relay but did not need any more discovered relays");d={timeout:f,reservation:c,type:t,connection:a.id,id:h}}else d={timeout:f,reservation:c,type:t,connection:a.id};this.reservations.set(e,d),await this.peerStore.merge(e,{tags:{[un]:{value:1,ttl:l}}}),this.#r();let p={relay:e,details:d};return this.safeDispatchEvent("relay:created-reservation",{detail:p}),p}catch(o){throw t==="discovered"&&o.name==="HadEnoughRelaysError"||this.log.error("could not reserve slot on %p after %dms - %e",e,Date.now()-s,o),(o.name==="DialError"||o.name==="UnsupportedProtocolError")&&this.relayFilter.add(e.toMultihash().bytes),this.#t(e).catch(i=>{this.log.error("could not remove reservation on %p after reserving slot failed - %e",e,i)}),o}},{peerId:e})}hasReservation(e){return this.reservations.has(e)}getReservation(e){return this.reservations.get(e)?.reservation}reservationCount(e){return e==null?this.reservations.size:[...this.reservations.values()].reduce((t,n)=>(n.type===e&&t++,t),0)}cancelReservations(){[...this.reservations.values()].forEach(e=>{clearTimeout(e.timeout)}),this.reservations.clear()}async#e(e,t){t.signal?.throwIfAborted(),this.log("requesting reservation from %p",e.remotePeer);let n=await e.newStream(ke,t),o=Dt(n).pb(Z);this.log.trace("send RESERVE to %p",e.remotePeer),await o.write({type:Z.Type.RESERVE},t);let i;try{this.log.trace("reading response from %p",e.remotePeer),i=await o.read(t)}catch(c){throw n.abort(c),c}finally{n.status!=="closed"&&await n.close(t)}if(this.log.trace("read response %s",i.status),i.status===H.OK&&i.reservation!=null){let c=new Set;c.add(e.remoteAddr.toString());for(let l of i.reservation.addrs){let u=Pe(l);u.getComponents().find(f=>f.code===421)==null&&(u=u.encapsulate(`/p2p/${e.remotePeer}`)),u=Pe(u.toString().replace(`/p2p/${e.remotePeer}/p2p/${e.remotePeer}`,`/p2p/${e.remotePeer}`)),c.add(u.toString())}return i.reservation.addrs=[...c].map(l=>Pe(l).bytes),i.reservation}let a=`reservation failed with status ${i.status??"undefined"}`;throw this.log.error(a),new Error(a)}async#t(e){let 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:{[un]: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=Tr(100),this.log("not discovered enough relays %d/%d",this.reservations.size,this.pendingReservations.length),this.safeDispatchEvent("relay:not-enough-relays")}};var Aa=class extends xo{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 Ta(r){return new Aa(r)}var Dp=r=>{if(r.peer==null)return!1;try{r.peer.addrs.forEach(Pe)}catch{return!1}return!0},Ol={maxInboundStopStreams:ln,maxOutboundStopStreams:ln,stopTimeout:3e4},qo=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 Ko(e,{filter:t.discoveryFilter??xa(_l,Al)}),this.discovery.addEventListener("relay:discover",n=>{this.reservationStore.addRelay(n.detail,"discovered").catch(s=>{s.name!=="HadEnoughRelaysError"&&s.name!=="RelayQueueFullError"&&this.log.error("could not add discovered relay %p - %e",n.detail,s)})}),this.reservationStore=new Ho(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";[Na]=["@libp2p/transport","@libp2p/circuit-relay-v2-transport"];get[Ua](){return this.discovery!=null?["@libp2p/identify"]:[]}[Pa]=!0;isStarted(){return this.started}async start(){this.shutdownController=new AbortController,this.shutdownController.signal,await this.components.registrar.handle(Qt,this.onStop,{maxInboundStreams:this.maxInboundStopStreams,maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0}),await Ba(this.discovery,this.reservationStore),this.started=!0}async stop(){this.shutdownController.abort(),await Ra(this.discovery,this.reservationStore),await this.components.registrar.unhandle(Qt),this.started=!1}async dial(e,t){let n=e.toString().split("/p2p-circuit"),s=Pe(n[0]),o=Pe(n[n.length-1]),i=s.getComponents().find(p=>p.code===421)?.value,a=o.getComponents().find(p=>p.code===421)?.value;if(i==null||a==null){let p=`ircuit relay dial to ${e.toString()} failed as address did not have both relay and destination PeerIDs`;throw this.log.error(`c${p}`),new wn(`C${p}`)}let c=Ii(i),l=Ii(a),f=this.components.connectionManager.getConnections(c)[0];f==null?(await this.components.peerStore.merge(c,{multiaddrs:[s]}),t.onProgress?.(new Rt("circuit-relay:open-connection")),f=await this.components.connectionManager.openConnection(c,t)):t.onProgress?.(new Rt("circuit-relay:reuse-connection"));let d;try{t.onProgress?.(new Rt("circuit-relay:open-hop-stream")),d=await f.newStream(ke,t);let p=Dt(d).pb(Z);t.onProgress?.(new Rt("circuit-relay:write-connect-message")),await p.write({type:Z.Type.CONNECT,peer:{id:l.toMultihash().bytes,addrs:[Pe(o).bytes]}},t),t.onProgress?.(new Rt("circuit-relay:read-connect-response"));let h=await p.read(t);if(h.status!==H.OK)throw new xn(`failed to connect via relay with status ${h?.status?.toString()??"undefined"}`);let S=new pn(h.limit),x=Ta({stream:p.unwrap().unwrap(),remoteAddr:e,localAddr:s.encapsulate(`/p2p-circuit/p2p/${this.components.peerId.toString()}`),onDataRead:S.onData,onDataWrite:S.onData,log:d.log.newScope("circuit-relay:connection")}),y=await this.components.upgrader.upgradeOutbound(x,{...t,limits:S.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(p){throw this.log.error("circuit relay dial to destination %p via relay %p failed - %e",l,c,p),d?.abort(p),p}}createListener(e){return Ll({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=>Ro.exactMatch(t)||Oo.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(f){this.log.error("failed to listen on a relay peer we were dialed via but did not have a reservation on - %e",f)}let s=Dt(e).pb(Ne),o=await s.read({signal:n});if(this.log("new circuit relay v2 stop stream from %p with type %s",t.remotePeer,o.type),o?.type===void 0){this.log.error("type was missing from circuit v2 stop protocol request from %s",t.remotePeer),await s.write({type:Ne.Type.STATUS,status:H.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}if(o.type!==Ne.Type.CONNECT){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await s.write({type:Ne.Type.STATUS,status:H.UNEXPECTED_MESSAGE},{signal:n}),await e.close({signal:n});return}if(!Dp(o)){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await s.write({type:Ne.Type.STATUS,status:H.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}let i=Er(Ge(o.peer.id));if(await this.components.connectionGater.denyInboundRelayedConnection?.(t.remotePeer,i)===!0){this.log.error("connection gater denied inbound relayed connection from %p",t.remotePeer),await s.write({type:Ne.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 s.write({type:Ne.Type.STATUS,status:H.OK},{signal:n});let a=new pn(o.limit),c=t.remoteAddr.encapsulate(`/p2p-circuit/p2p/${i.toString()}`),l=this.components.addressManager.getAddresses()[0],u=Ta({stream:s.unwrap().unwrap(),remoteAddr:c,localAddr:l,onDataRead:a.onData,onDataWrite:a.onData,log:e.log.newScope("circuit-relay:connection")});await this.components.upgrader.upgradeInbound(u,{limits:a.getLimits(),signal:n}),u.log("inbound relayed connection established to %p with limits %o, over connection %s",i,o.limit??"none",t.id)}finally{n?.clear()}}};function Cp(r={}){return e=>new Mo(e,r)}function Lp(r={}){return e=>new qo(e,r)}return Ml(Bp);})();
|
|
3
3
|
/*! Bundled license information:
|
|
4
4
|
|
|
5
5
|
@noble/hashes/utils.js:
|