@libp2p/circuit-relay-v2 4.1.7 → 4.2.0-90100be0c
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 Uo=Object.defineProperty;var bl=Object.getOwnPropertyDescriptor;var wl=Object.getOwnPropertyNames;var xl=Object.prototype.hasOwnProperty;var ve=(r,e)=>{for(var t in e)Uo(r,t,{get:e[t],enumerable:!0})},El=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of wl(e))!xl.call(r,s)&&s!==t&&Uo(r,s,{get:()=>e[s],enumerable:!(n=bl(e,s))||n.enumerable});return r};var Sl=r=>El(Uo({},"__esModule",{value:!0}),r);var fp={};ve(fp,{RELAY_V2_HOP_CODEC:()=>ke,RELAY_V2_STOP_CODEC:()=>Zt,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"}},jt=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 dt=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"}},Lt=class extends Error{static name="ListenError";constructor(e="Listen error"){super(e),this.name="ListenError"}};var Qt=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}},Jt=class extends Event{error;local;constructor(e,t,n){super("close",n),this.error=t,this.local=e}},wn=class extends Jt{constructor(e,t){super(!0,e,t)}},xn=class extends Jt{constructor(e,t){super(!1,e,t)}};var ko=Symbol.for("@libp2p/peer-id");var wa="keep-alive";function xa(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function Ea(...r){let e=[];for(let t of r)xa(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStart!=null&&await t.beforeStart()})),await Promise.all(e.map(async t=>{await t.start()})),await Promise.all(e.map(async t=>{t.afterStart!=null&&await t.afterStart()}))}async function Sa(...r){let e=[];for(let t of r)xa(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStop!=null&&await t.beforeStop()})),await Promise.all(e.map(async t=>{await t.stop()})),await Promise.all(e.map(async t=>{t.afterStop!=null&&await t.afterStop()}))}var _a=Symbol.for("@libp2p/transport");var va;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(va||(va={}));var Aa=Symbol.for("@libp2p/service-capabilities"),Ta=Symbol.for("@libp2p/service-dependencies");var Ho={};ve(Ho,{base58btc:()=>te,base58flickr:()=>Cl});var $p=new Uint8Array(0);function Ia(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 Da(r){return new TextEncoder().encode(r)}function Ca(r){return new TextDecoder().decode(r)}function vl(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 _l=vl,Al=_l,Ra=Al;var Mo=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")}},Ko=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 Ba(this,e)}},qo=class{decoders;constructor(e){this.decoders=e}or(e){return Ba(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 Ba(r,e){return new qo({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Vo=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 Mo(e,t,n),this.decoder=new Ko(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function er({name:r,prefix:e,encode:t,decode:n}){return new Vo(r,e,t,n)}function ht({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=Ra(t,r);return er({prefix:e,name:r,encode:n,decode:o=>Qe(s(o))})}function Tl(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 Il(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 Dl(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=Dl(n);return er({prefix:e,name:r,encode(o){return Il(o,n,t)},decode(o){return Tl(o,s,t,r)}})}var te=ht({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Cl=ht({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Fo={};ve(Fo,{base32:()=>pt,base32hex:()=>Ol,base32hexpad:()=>Nl,base32hexpadupper:()=>Ul,base32hexupper:()=>Pl,base32pad:()=>Rl,base32padupper:()=>Bl,base32upper:()=>Ll,base32z:()=>kl});var pt=ce({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Ll=ce({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Rl=ce({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Bl=ce({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Ol=ce({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Pl=ce({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Nl=ce({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Ul=ce({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),kl=ce({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var zo={};ve(zo,{base36:()=>Cr,base36upper:()=>Ml});var Cr=ht({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Ml=ht({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Kl=Na,Oa=128,ql=127,Vl=~ql,Hl=Math.pow(2,31);function Na(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Hl;)e[t++]=r&255|Oa,r/=128;for(;r&Vl;)e[t++]=r&255|Oa,r>>>=7;return e[t]=r|0,Na.bytes=t-n+1,e}var Fl=$o,zl=128,Pa=127;function $o(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw $o.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&Pa)<<s:(i&Pa)*Math.pow(2,s),s+=7}while(i>=zl);return $o.bytes=o-n,t}var $l=Math.pow(2,7),Wl=Math.pow(2,14),Gl=Math.pow(2,21),Yl=Math.pow(2,28),Zl=Math.pow(2,35),Xl=Math.pow(2,42),jl=Math.pow(2,49),Ql=Math.pow(2,56),Jl=Math.pow(2,63),ef=function(r){return r<$l?1:r<Wl?2:r<Gl?3:r<Yl?4:r<Zl?5:r<Xl?6:r<jl?7:r<Ql?8:r<Jl?9:10},tf={encode:Kl,decode:Fl,encodingLength:ef},rf=tf,Lr=rf;function Rr(r,e=0){return[Lr.decode(r,e),Lr.decode.bytes]}function tr(r,e,t=0){return Lr.encode(r,e,t),e}function rr(r){return Lr.encodingLength(r)}function ze(r,e){let t=e.byteLength,n=rr(r),s=n+rr(t),o=new Uint8Array(s+t);return tr(r,o,0),tr(t,o,n),o.set(e,s),new nr(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 nr(t,s,i,e)}function Ua(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Ia(r.bytes,t.bytes)}}var nr=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};function ka(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return of(t,Wo(r),e??te.encoder);default:return sf(t,Wo(r),e??pt.encoder)}}var Ma=new WeakMap;function Wo(r){let e=Ma.get(r);if(e==null){let t=new Map;return Ma.set(r,t),t}return e}var le=class r{code;version;multihash;bytes;"/";constructor(e,t,n,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!==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=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&&Ua(e.multihash,n.multihash)}toString(e){return ka(this,e)}toJSON(){return{"/":ka(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??Ka(n,s,o.bytes))}else if(t[cf]===!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=Ka(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 nr(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]=nf(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 Wo(o).set(n,e),o}};function nf(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 pt.prefix:{let t=e??pt;return[pt.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 of(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 sf(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,af=18;function Ka(r,e,t){let n=rr(r),s=n+rr(e),o=new Uint8Array(s+t.byteLength);return tr(r,o,0),tr(e,o,n),o.set(t,s),o}var cf=Symbol.for("@ipld/js-cid/CID");var Go={};ve(Go,{identity:()=>Me});var qa=0,uf="identity",Va=Qe;function lf(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(qa,Va(r))}var Me={code:qa,name:uf,encode:Va,digest:lf};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 Ha(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=Ha(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Ha(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 Yo={};ve(Yo,{base10:()=>ff});var ff=ht({prefix:"9",name:"base10",alphabet:"0123456789"});var Zo={};ve(Zo,{base16:()=>df,base16upper:()=>hf});var df=ce({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),hf=ce({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Xo={};ve(Xo,{base2:()=>pf});var pf=ce({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var jo={};ve(jo,{base256emoji:()=>wf});var za=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}"),mf=za.reduce((r,e,t)=>(r[t]=e,r),[]),yf=za.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function gf(r){return r.reduce((e,t)=>(e+=mf[t],e),"")}function bf(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let s=yf[n];if(s==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}var wf=er({prefix:"\u{1F680}",name:"base256emoji",encode:gf,decode:bf});var Jo={};ve(Jo,{base64:()=>xf,base64pad:()=>Ef,base64url:()=>Qo,base64urlpad:()=>Sf});var xf=ce({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Ef=ce({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Qo=ce({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Sf=ce({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var es={};ve(es,{base8:()=>vf});var vf=ce({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var ts={};ve(ts,{identity:()=>_f});var _f=er({prefix:"\0",name:"identity",encode:r=>Ca(r),decode:r=>Da(r)});var Dm=new TextEncoder,Cm=new TextDecoder;var os={};ve(os,{sha256:()=>or,sha512:()=>Df});var If=20;function ns({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new rs(r,e,t,n,s)}var rs=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??If,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?$a(n,this.code,t?.truncate):n.then(s=>$a(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function $a(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 Ga(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var or=ns({name:"sha2-256",code:18,encode:Ga("SHA-256")}),Df=ns({name:"sha2-512",code:19,encode:Ga("SHA-512")});var Or={...ts,...Xo,...es,...Yo,...Zo,...Fo,...zo,...Ho,...Jo,...jo},Vm={...os,...Go};function Za(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Ya=Za("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),ss=Za("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=Ae(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),Cf={utf8:Ya,"utf-8":Ya,hex:Or.base16,latin1:ss,ascii:ss,binary:ss,...Or},vn=Cf;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 Lf=parseInt("11111",2),is=parseInt("10000000",2),Rf=parseInt("01111111",2),Xa={0:Pr,1:Pr,2:Bf,3:Nf,4:Uf,5:Pf,6:Of,16:Pr,22:Pr,48:Pr};function tt(r,e={offset:0}){let t=r[e.offset]&Lf;if(e.offset++,Xa[t]!=null)return Xa[t](r,e);throw new Error("No decoder for tag "+t)}function Nr(r,e){let t=0;if((r[e.offset]&is)===is){let n=r[e.offset]&Rf,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 Bf(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 Of(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 Pf(r,e){return e.offset++,null}function Nf(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 Uf(r,e){let t=Nr(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function kf(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new J;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function as(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=kf(r.byteLength);return new J(Uint8Array.from([e.byteLength|is]),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]),as(e),e)}function _n(r){let e=Uint8Array.from([0]),t=new J(e,r);return new J(Uint8Array.from([3]),as(t),t)}function mt(r,e=48){let t=new J;for(let n of r)t.append(n);return new J(Uint8Array.from([e]),as(t),t)}async function ja(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 Mf=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Kf=Uint8Array.from([6,5,43,129,4,0,34]),qf=Uint8Array.from([6,5,43,129,4,0,35]),Vf={ext:!0,kty:"EC",crv:"P-256"},Hf={ext:!0,kty:"EC",crv:"P-384"},Ff={ext:!0,kty:"EC",crv:"P-521"},cs=32,us=48,ls=66;function fs(r){let e=tt(r);return Qa(e)}function Qa(r){let e=r[1][1][0],t=1,n,s;if(e.byteLength===cs*2+1)return n=$(e.subarray(t,t+cs),"base64url"),s=$(e.subarray(t+cs),"base64url"),new sr({...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 sr({...Hf,key_ops:["verify"],x:n,y:s});if(e.byteLength===ls*2+1)return n=$(e.subarray(t,t+ls),"base64url"),s=$(e.subarray(t+ls),"base64url"),new sr({...Ff,key_ops:["verify"],x:n,y:s});throw new ae(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function Ja(r){return mt([Te(Uint8Array.from([1])),mt([zf(r.crv)],160),mt([_n(new J(Uint8Array.from([4]),K(r.x??"","base64url"),K(r.y??"","base64url")))],161)]).subarray()}function zf(r){if(r==="P-256")return Mf;if(r==="P-384")return Kf;if(r==="P-521")return qf;throw new ae(`Invalid curve ${r}`)}var sr=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=Ja(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 ja(this.jwk,t,e,n)}};function Rt(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=Rt(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 ir(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 tc(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 rc=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",$f=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function ot(r){if(k(r),rc)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=$f[r[t]];return e}var rt={_0:48,_9:57,A:65,F:70,a:97,f:102};function ec(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(rc)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=ec(r.charCodeAt(o)),a=ec(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 ds(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 ar(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 hs=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function nc(r,e,t){return r&e^~r&t}function oc(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){ir(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){ir(this),tc(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),sc=BigInt(32);function Wf(r,e=!1){return e?{h:Number(r&In),l:Number(r>>sc&In)}:{h:Number(r>>sc&In)|0,l:Number(r&In)|0}}function ic(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}=Wf(r[o],e);[n[o],s[o]]=[i,a]}return[n,s]}var ps=(r,e,t)=>r>>>t,ms=(r,e,t)=>r<<32-t|e>>>t,Bt=(r,e,t)=>r>>>t|e<<32-t,Ot=(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 ac=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),cc=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,uc=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),lc=(r,e,t,n,s)=>e+t+n+s+(r/2**32|0)|0,fc=(r,e,t,n,s)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(s>>>0),dc=(r,e,t,n,s,o)=>e+t+n+s+o+(r/2**32|0)|0;var Yf=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),yt=new Uint32Array(64),ys=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)yt[f]=e.getUint32(t,!1);for(let f=16;f<64;f++){let h=yt[f-15],p=yt[f-2],d=Ke(h,7)^Ke(h,18)^h>>>3,v=Ke(p,17)^Ke(p,19)^p>>>10;yt[f]=v+yt[f-7]+d+yt[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+nc(a,c,l)+Yf[f]+yt[f]|0,v=(Ke(n,2)^Ke(n,13)^Ke(n,22))+oc(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(yt)}destroy(){this.set(0,0,0,0,0,0,0,0),nt(this.buffer)}},gs=class extends ys{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 hc=ic(["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))),Zf=hc[0],Xf=hc[1],gt=new Uint32Array(80),bt=new Uint32Array(80),bs=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)gt[x]=e.getUint32(t),bt[x]=e.getUint32(t+=4);for(let x=16;x<80;x++){let T=gt[x-15]|0,P=bt[x-15]|0,M=Bt(T,P,1)^Bt(T,P,8)^ps(T,P,7),V=Ot(T,P,1)^Ot(T,P,8)^ms(T,P,7),S=gt[x-2]|0,E=bt[x-2]|0,N=Bt(S,E,19)^kr(S,E,61)^ps(S,E,6),H=Ot(S,E,19)^Mr(S,E,61)^ms(S,E,6),L=uc(V,H,bt[x-7],bt[x-16]),g=lc(L,M,N,gt[x-7],gt[x-16]);gt[x]=g|0,bt[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=Bt(f,h,14)^Bt(f,h,18)^kr(f,h,41),P=Ot(f,h,14)^Ot(f,h,18)^Mr(f,h,41),M=f&p^~f&v,V=h&d^~h&w,S=fc(A,P,V,Xf[x],bt[x]),E=dc(S,y,T,M,Zf[x],gt[x]),N=S|0,H=Bt(n,s,28)^kr(n,s,34)^kr(n,s,39),L=Ot(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=ac(N,L,b);n=cc(m,E,H,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(gt,bt)}destroy(){nt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},ws=class extends bs{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 cr=ds(()=>new gs,hs(1));var pc=ds(()=>new ws,hs(3));var Es=BigInt(0),xs=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 mc(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=mc(r).toString(16);return e.length&1?"0"+e:e}function yc(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?Es:BigInt("0x"+r)}function ur(r){return yc(ot(r))}function Pt(r){return yc(ot(Ln(k(r)).reverse()))}function Cn(r,e){Ge(e),r=mc(r);let t=st(r.toString(16).padStart(e*2,"0"));if(t.length!==e)throw new Error("number too large");return t}function Ss(r,e){return Cn(r,e).reverse()}function Ln(r){return Uint8Array.from(r)}var Dn=r=>typeof r=="bigint"&&Es<=r;function jf(r,e,t){return Dn(r)&&Dn(e)&&Dn(t)&&e<=r&&r<t}function qr(r,e,t,n){if(!jf(e,t,n))throw new Error("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function vs(r){let e;for(e=0;r>Es;r>>=xs,e+=1);return e}var Vr=r=>(xs<<BigInt(r))-xs;function gc(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 wt(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 lr(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),Nt=BigInt(2),xc=BigInt(3),Ec=BigInt(4),Sc=BigInt(5),Qf=BigInt(7),vc=BigInt(8),Jf=BigInt(9),_c=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 bc(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 As(r,e,t){if(!r.eql(r.sqr(e),t))throw new Error("Cannot find square root")}function Ac(r,e){let t=(r.ORDER+de)/Ec,n=r.pow(e,t);return As(r,n,e),n}function ed(r,e){let t=(r.ORDER-Sc)/vc,n=r.mul(e,Nt),s=r.pow(n,t),o=r.mul(e,s),i=r.mul(r.mul(o,Nt),s),a=r.mul(o,r.sub(i,r.ONE));return As(r,a,e),a}function td(r){let e=fr(r),t=Tc(r),n=t(e,e.neg(e.ONE)),s=t(e,n),o=t(e,e.neg(n)),i=(r+Qf)/_c;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 As(a,w,c),w}}function Tc(r){if(r<xc)throw new Error("sqrt is not defined for small field");let e=r-de,t=0;for(;e%Nt===Se;)e/=Nt,t++;let n=Nt,s=fr(r);for(;wc(s,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return Ac;let o=s.pow(n,e),i=(e+de)/Nt;return function(c,l){if(c.is0(l))return l;if(wc(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 rd(r){return r%Ec===xc?Ac:r%vc===Sc?ed:r%_c===Jf?td(r):Tc(r)}var Ic=(r,e)=>(ue(r,e)&de)===de,nd=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ts(r){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=nd.reduce((n,s)=>(n[s]="function",n),e);return wt(r,t),r}function od(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 Hr(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 wc(r,e){let t=(r.ORDER-de)/Nt,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 sd(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 _s=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}=sd(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 od(this,e,t)}div(e,t){return ue(e*bc(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 bc(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=rd(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?Ss(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?Pt(e):ur(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 Hr(this,e)}cmov(e,t,n){return n?t:e}};function fr(r,e={}){return new _s(r,e)}function Dc(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 Is(r){let e=Dc(r);return e+Math.ceil(e/2)}function Ds(r,e,t=!1){k(r);let n=r.length,s=Dc(e),o=Is(e);if(n<16||n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);let i=t?Pt(r):ur(r),a=ue(i,e-de)+de;return t?Ss(a,s):Cn(a,s)}var dr=BigInt(0),Ut=BigInt(1);function Fr(r,e){let t=e.negate();return r?t:e}function kt(r,e){let t=Hr(r.Fp,e.map(n=>n.Z));return e.map((n,s)=>r.fromAffine(n.toAffine(t[s])))}function Bc(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function Cs(r,e){Bc(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 Cc(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+=Ut);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 Ls=new WeakMap,Oc=new WeakMap;function Rs(r){return Oc.get(r)||1}function Lc(r){if(r!==dr)throw new Error("invalid wNAF")}var hr=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>dr;)t&Ut&&(n=n.add(s)),s=s.double(),t>>=Ut;return n}precomputeWindow(e,t){let{windows:n,windowSize:s}=Cs(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=Cs(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:f,isNegF:h,offsetF:p}=Cc(n,a,i);n=c,u?o=o.add(Fr(h,t[p])):s=s.add(Fr(f,t[l]))}return Lc(n),{p:s,f:o}}wNAFUnsafe(e,t,n,s=this.ZERO){let o=Cs(e,this.bits);for(let i=0;i<o.windows&&n!==dr;i++){let{nextN:a,offset:c,isZero:l,isNeg:u}=Cc(n,i,o);if(n=a,!l){let f=t[c];s=s.add(u?f.negate():f)}}return Lc(n),s}getPrecomputes(e,t,n){let s=Ls.get(t);return s||(s=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(s=n(s)),Ls.set(t,s))),s}cached(e,t,n){let s=Rs(e);return this.wNAF(s,this.getPrecomputes(s,e,n),t)}unsafe(e,t,n,s){let o=Rs(e);return o===1?this._unsafeLadder(e,t,s):this.wNAFUnsafe(o,this.getPrecomputes(o,e,n),t,s)}createCache(e,t){Bc(t,this.bits),Oc.set(e,t),Ls.delete(e)}hasCache(e){return Rs(e)!==1}};function Pc(r,e,t,n){let s=e,o=r.ZERO,i=r.ZERO;for(;t>dr||n>dr;)t&Ut&&(o=o.add(s)),n&Ut&&(i=i.add(s)),s=s.double(),t>>=Ut,n>>=Ut;return{p1:o,p2:i}}function Rc(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Ts(e),e}else return fr(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>dr))throw new Error(`CURVE.${c} must be positive bigint`)}let s=Rc(e.p,t.Fp,n),o=Rc(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 xt=BigInt(0),he=BigInt(1),Bs=BigInt(2),id=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 Nc(r,e={}){let t=Rn("edwards",r,e,e.FpFnLE),{Fp:n,Fn:s}=t,o=t.CURVE,{h:i}=o;wt(e,{},{uvRatio:"function"});let a=Bs<<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:xt}}});if(!ad(n,o,o.Gx,o.Gy))throw new Error("bad curve params: generator point");function u(w,y,A=!1){let x=A?he:xt;return qr("coordinate "+w,y,x,a),y}function f(w){if(!(w instanceof d))throw new Error("EdwardsPoint expected")}let h=lr((w,y)=>{let{X:A,Y:x,Z:T}=w,P=w.is0();y==null&&(y=P?id:n.inv(T));let M=c(A*y),V=c(x*y),S=n.mul(T,y);if(P)return{x:xt,y:he};if(S!==he)throw new Error("invZ was invalid");return{x:M,y:V}}),p=lr(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),H=c(V*y),L=c(E*c(H+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(xt,he,he,xt);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=Pt(M),E=A?a:n.ORDER;qr("point.y",S,xt,E);let N=c(S*S),H=c(N-he),L=c(P*N-T),{isValid:g,value:b}=l(H,L);if(!g)throw new Error("bad point: invalid y coordinate");let m=(b&he)===he,_=(V&128)!==0;if(!A&&b===xt&&_)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(Bs),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),H=c(M*T);return S===E&&N===H}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(Bs*c(T*T)),S=c(y*P),E=A+x,N=c(c(E*E)-P-M),H=S+M,L=H-V,g=S-M,b=c(N*L),m=c(H*g),_=c(N*g),I=c(L*H);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:H}=y,L=c(T*S),g=c(P*E),b=c(V*x*H),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=>kt(d,T));return kt(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===xt?d.ZERO:this.is0()||y===he?this:v.unsafe(this,y,x=>kt(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 hr(d,s.BITS);return d.BASE.precompute(8),d}function Uc(r,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');wt(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||ar,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(Pt(S))}function f(S){let E=x.secretKey;k(S,x.secretKey,"secretKey");let N=k(e(S),2*E,"hashedSecretKey"),H=c(N.slice(0,E)),L=N.slice(E,2*E),g=u(H);return{head:H,prefix:L,scalar:g}}function h(S){let{head:E,prefix:N,scalar:H}=f(S),L=s.multiply(H),g=L.toBytes();return{head:E,prefix:N,scalar:H,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:H,scalar:L,pointBytes:g}=h(E),b=d(N.context,H,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,H=w){let{context:L,zip215:g}=H,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=Pt(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 Rt(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,H=N===32;if(!H&&N!==57)throw new Error("only defined for 25519 and 448");let L=H?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 cd=BigInt(1),kc=BigInt(2);var ud=BigInt(5),ld=BigInt(8),Os=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),fd={p:Os,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:ld,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function dd(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),s=BigInt(80),o=Os,a=r*r%o*r%o,c=ee(a,kc,o)*a%o,l=ee(c,cd,o)*r%o,u=ee(l,ud,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,kc,o)*r%o,b2:a}}function hd(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var Mc=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function pd(r,e){let t=Os,n=ue(e*e*e,t),s=ue(n*n*e,t),o=dd(r*s).pow_p_5_8,i=ue(r*n*o,t),a=ue(e*i*i,t),c=i,l=ue(i*Mc,t),u=a===r,f=a===ue(-r,t),h=a===ue(-r*Mc,t);return u&&(i=c),(f||h)&&(i=l),Ic(i,t)&&(i=ue(-i,t)),{isValid:u||f,value:i}}var md=Nc(fd,{uvRatio:pd});function yd(r){return Uc(md,pc,Object.assign({adjustScalarBytes:hd},r))}var Kc=yd({});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 qc={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=qc;var Pn=32;var Ps,gd=(async()=>{try{return await Ue.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function bd(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 wd(r,e,t){return Kc.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function Vc(r,e,t){return Ps==null&&(Ps=await gd),Ps?bd(r,e,t):wd(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=Ns(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=Vc(this.raw,t,e);return Nn(s)?s.then(o=>(n?.signal?.throwIfAborted(),o)):s}};function Us(r){return r=Ns(r,Pn),new Un(r)}function Ns(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 Ed=Math.pow(2,7),Sd=Math.pow(2,14),vd=Math.pow(2,21),ks=Math.pow(2,28),Ms=Math.pow(2,35),Ks=Math.pow(2,42),qs=Math.pow(2,49),Y=128,we=127;function De(r){if(r<Ed)return 1;if(r<Sd)return 2;if(r<vd)return 3;if(r<ks)return 4;if(r<Ms)return 5;if(r<Ks)return 6;if(r<qs)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function pr(r,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 _d(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 Vs(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)*ks,t<Y)||(t=r[e+5],n+=(t&we)*Ms,t<Y)||(t=r[e+6],n+=(t&we)*Ks,t<Y)||(t=r[e+7],n+=(t&we)*qs,t<Y))return n;throw new RangeError("Could not decode varint")}function Ad(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)*ks,t<Y)||(t=r.get(e+5),n+=(t&we)*Ms,t<Y)||(t=r.get(e+6),n+=(t&we)*Ks,t<Y)||(t=r.get(e+7),n+=(t&we)*qs,t<Y))return n;throw new RangeError("Could not decode varint")}function mr(r,e,t=0){return e==null&&(e=Ae(De(r))),e instanceof Uint8Array?pr(r,e,t):_d(r,e,t)}function $r(r,e=0){return r instanceof Uint8Array?Vs(r,e):Ad(r,e)}var Fs=new Float32Array([-0]),Et=new Uint8Array(Fs.buffer);function Fc(r,e,t){Fs[0]=r,e[t]=Et[0],e[t+1]=Et[1],e[t+2]=Et[2],e[t+3]=Et[3]}function zc(r,e){return Et[0]=r[e],Et[1]=r[e+1],Et[2]=r[e+2],Et[3]=r[e+3],Fs[0]}var zs=new Float64Array([-0]),xe=new Uint8Array(zs.buffer);function $c(r,e,t){zs[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 Wc(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],zs[0]}var Td=BigInt(Number.MAX_SAFE_INTEGER),Id=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 Mt;if(e<Td&&e>Id)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>Gc&&(s=0n,++n>Gc&&(n=0n))),new r(Number(s),Number(n))}static fromNumber(e){if(e===0)return Mt;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):Mt}},Mt=new Oe(0,0);Mt.toBigInt=function(){return 0n};Mt.zzEncode=Mt.zzDecode=function(){return this};Mt.length=function(){return 1};var Gc=4294967296n;function Yc(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function Zc(r,e,t){if(t-e<1)return"";let 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 $s(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 Ws=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=zc(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw qe(this,4);let e=Wc(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 Zc(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=Vs(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 Ws(r instanceof Uint8Array?r:r.subarray())}function Ce(r,e,t){let n=Wr(r);return e.decode(n,void 0,t)}function Gs(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 Kt=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function Ys(){}var Xs=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},Dd=Gs();function Cd(r){return globalThis.Buffer!=null?Ae(r):Dd(r)}var Yr=class{len;head;tail;states;constructor(){this.len=0,this.head=new Kt(Ys,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new Kt(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new js((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(pr,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(Zs,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($c,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(Zs,1,0):this.uint32(t)._push(Rd,t,e)}string(e){let t=Yc(e);return t!==0?this.uint32(t)._push($s,t,e):this._push(Zs,1,0)}fork(){return this.states=new Xs(this),this.head=this.tail=new Kt(Ys,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 Kt(Ys,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=Cd(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function Zs(r,e,t){e[t]=r&255}function Ld(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var js=class extends Kt{next;constructor(e,t){super(Ld,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 Rd(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(Bd,e,r),this},Yr.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(Od,e,r),this});function Bd(r,e,t){e.set(r,t)}function Od(r,e,t){r.length<40?$s(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(K(r),t)}function Qs(){return new Yr}function Le(r,e){let t=Qs();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 qt(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 Vt=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 Js;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(Js||(Js={}));(function(r){r.codec=()=>qt(Js)})(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 ei;(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})(ei||(ei={}));var Xr={};ve(Xr,{MAX_RSA_KEY_SIZE:()=>ti,generateRSAKeyPair:()=>tu,jwkToJWKKeyPair:()=>ru,jwkToPkcs1:()=>kd,jwkToPkix:()=>si,jwkToRSAPrivateKey:()=>ui,pkcs1MessageToJwk:()=>ni,pkcs1MessageToRSAPrivateKey:()=>ii,pkcs1ToJwk:()=>Ud,pkcs1ToRSAPrivateKey:()=>eu,pkixMessageToJwk:()=>oi,pkixMessageToRSAPublicKey:()=>ci,pkixToJwk:()=>Md,pkixToRSAPublicKey:()=>ai});var yr=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 Jc(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 Qc(this.jwk,e,t)}};var ti=8192,ri=18,Pd=1062,Nd=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function Ud(r){let e=tt(r);return ni(e)}function ni(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 kd(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 mt([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 Md(r){let e=tt(r,{offset:0});return oi(e)}function oi(r){let e=tt(r[1],{offset:0});return{kty:"RSA",n:$(e[0],"base64url"),e:$(e[1],"base64url")}}function si(r){if(r.n==null||r.e==null)throw new ae("JWK was missing components");return mt([Nd,_n(mt([Te(K(r.n,"base64url")),Te(K(r.e,"base64url"))]))]).subarray()}function eu(r){let e=tt(r);return ii(e)}function ii(r){let e=ni(r);return ui(e)}function ai(r,e){if(r.byteLength>=Pd)throw new jt("Key size is too large");let t=tt(r,{offset:0});return ci(t,r,e)}function ci(r,e,t){let n=oi(r);if(t==null){let s=cr(Ze.encode({Type:ne.RSA,Data:e}));t=ze(ri,s)}return new yr(n,t)}function ui(r){if(ou(r)>ti)throw new ae("Key size is too large");let e=ru(r),t=cr(Ze.encode({Type:ne.RSA,Data:si(e.publicKey)})),n=ze(ri,t);return new Zr(e.privateKey,new yr(e.publicKey,n))}async function tu(r){if(r>ti)throw new ae("Key size is too large");let e=await nu(r),t=cr(Ze.encode({Type:ne.RSA,Data:si(e.publicKey)})),n=ze(ri,t);return new Zr(e.privateKey,new yr(e.publicKey,n))}function ru(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 nu(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 Kd(t,e);return{privateKey:n[0],publicKey:n[1]}}async function Qc(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 Jc(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 Kd(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 ou(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 ir(this),this.iHash.update(e),this}digestInto(e){ir(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()}},li=(r,e,t)=>new Vn(r,e).update(t).digest();li.create=(r,e)=>new Vn(r,e);var su=(r,e)=>(r+(r>=0?e:-e)/iu)/e;function qd(r,e,t){let[[n,s],[o,i]]=e,a=su(i*r,t),c=su(-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(vs(t)/2))+gr;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 di(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function fi(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&&di(t.format),t}var hi=class extends Error{constructor(e=""){super(e)}},St={Err:hi,_tlv:{encode:(r,e)=>{let{Err:t}=St;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}=St,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}=St;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}=St;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 ur(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=St,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}=St,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),gr=BigInt(1),iu=BigInt(2),Hn=BigInt(3),Vd=BigInt(4);function au(r,e={}){let t=Rn("weierstrass",r,e),{Fp:n,Fn:s}=t,o=t.CURVE,{h:i,n:a}=o;wt(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=uu(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(cu(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,Hn),Vd),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 qd(L,c.basises,s.ORDER)}let M=lr((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=lr(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=Fr(m,g),b=Fr(_,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 H.createCache(this,g),b||this.multiply(Hn),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,Hn),{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),G=n.mul(_,I);return G=n.add(G,G),O=n.mul(_,C),O=n.add(O,O),R=n.mul(g,O),D=n.mul(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(G,R),O=n.mul(m,O),Q=n.mul(g,Q),G=n.sub(U,Q),G=n.mul(g,G),G=n.add(G,O),O=n.add(U,U),U=n.add(O,U),U=n.add(U,Q),U=n.mul(U,G),D=n.add(D,U),Q=n.mul(I,C),Q=n.add(Q,Q),U=n.mul(Q,G),R=n.sub(R,U),O=n.mul(Q,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,Hn),G=n.mul(b,I),se=n.mul(m,C),me=n.mul(_,R),Fe=n.add(b,m),ie=n.add(I,C);Fe=n.mul(Fe,ie),ie=n.add(G,se),Fe=n.sub(Fe,ie),ie=n.add(b,_);let be=n.add(I,R);return ie=n.mul(ie,be),be=n.add(G,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(G,G),se=n.add(se,G),me=n.mul(oe,me),ie=n.mul(Q,ie),se=n.add(se,me),me=n.sub(G,me),me=n.mul(oe,me),ie=n.add(ie,me),G=n.mul(se,ie),O=n.add(O,G),G=n.mul(be,ie),D=n.mul(Fe,D),D=n.sub(D,G),G=n.mul(Fe,se),U=n.mul(be,U),U=n.add(U,G),new E(D,O,U)}subtract(g){return this.add(g.negate())}is0(){return this.equals(E.ZERO)}multiply(g){let{endo:b}=e;if(!s.isValidNot0(g))throw new Error("invalid scalar: out of range");let m,_,I=C=>H.cached(this,C,R=>kt(E,R));if(b){let{k1neg:C,k1:R,k2neg:D,k2:O}=P(g),{p:U,f:oe}=I(R),{p:Q,f:G}=I(O);_=oe.add(G),m=S(b.beta,U,Q,C,D)}else{let{p:C,f:R}=I(g);m=C,_=R}return kt(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===gr)return m;if(H.hasCache(this))return this.multiply(g);if(b){let{k1neg:_,k1:I,k2neg:C,k2:R}=P(g),{p1:D,p2:O}=Pc(E,m,I,R);return S(b.beta,D,O,_,C)}else return H.unsafe(m,g)}toAffine(g){return M(this,g)}isTorsionFree(){let{isTorsionFree:g}=e;return i===gr?!0:g?g(E,this):H.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:g}=e;return i===gr?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,H=new hr(E,e.endo?Math.ceil(N/2):N);return E.BASE.precompute(8),E}function cu(r){return Uint8Array.of(r?2:3)}function uu(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Hd(r,e={}){let{Fn:t}=r,n=e.randomBytes||ar,s=Object.assign(uu(r.Fp,t),{seed:Is(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 Ds(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(!Rt(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 lu(r,e,t={}){An(e),wt(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let n=t.randomBytes||ar,s=t.hmac||((b,m)=>li(e,b,m)),{Fp:o,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:u,getSharedSecret:f,utils:h,lengths:p}=Hd(r,t),d={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},v=a*iu<o.ORDER;function w(b){let m=a>>gr;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){di(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}=St.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(cu((C&1)===0),D)),U=i.inv(R),oe=M(k(m,void 0,"msgHash")),Q=i.create(-oe*U),G=i.create(I*U),se=r.BASE.multiplyUnsafe(Q).add(O.multiplyUnsafe(G));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(di(m),m==="der")return st(St.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 _=ur(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}=fi(_,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 G(se){let me=P(se);if(!i.isValidNot0(me))return;let Fe=i.inv(me),ie=r.BASE.multiply(me).toAffine(),be=i.create(ie.x);if(be===ct)return;let dn=i.create(Fe*i.create(Q+be*O));if(dn===ct)return;let ga=(ie.x===be?0:2)|Number(ie.y&gr),ba=dn;return I&&w(dn)&&(ba=i.neg(dn),ga^=1),new T(be,ba,v?void 0:ga)}return{seed:oe,k2sig:G}}function H(b,m,_={}){let{seed:I,k2sig:C}=N(b,m,_);return gc(e.outputLen,i.BYTES,s)(I,C).toBytes(_.format)}function L(b,m,_,I={}){let{lowS:C,prehash:R,format:D}=fi(I,d);if(_=k(_,void 0,"publicKey"),m=E(m,R),!Rt(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,G=M(m),se=i.inv(Q),me=i.create(G*se),Fe=i.create(oe*se),ie=r.BASE.multiplyUnsafe(me).add(U.multiplyUnsafe(Fe));return ie.is0()?!1:i.create(ie.x)===oe}catch{return!1}}function g(b,m,_={}){let{prehash:I}=fi(_,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:H,verify:L,recoverPublicKey:g,Signature:T,hash:e})}var mi={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 fu=BigInt(2);function zd(r){let e=mi.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,fu,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,fu,e);if(!pi.eql(pi.sqr(M),r))throw new Error("Cannot find square root");return M}var pi=fr(mi.p,{sqrt:zd}),$d=au(mi,{Fp:pi,endo:Fd}),br=lu($d,cr);function du(r,e,t,n){let s=or.digest(t instanceof Uint8Array?t:t.subarray());if(Nn(s))return s.then(({digest:o})=>(n?.signal?.throwIfAborted(),br.verify(e,o,r,{prehash:!1,format:"der"}))).catch(o=>{throw o.name==="AbortError"?o:new zr(String(o))});try{return n?.signal?.throwIfAborted(),br.verify(e,s.digest,r,{prehash:!1,format:"der"})}catch(o){throw new zr(String(o))}}var Fn=class{type="secp256k1";raw;_key;constructor(e){this._key=pu(e),this.raw=hu(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 yi(r){return new Fn(r)}function hu(r){return br.Point.fromBytes(r).toBytes()}function pu(r){try{return br.Point.fromBytes(r),r}catch(e){throw new jt(String(e))}}function mu(r,e){let{Type:t,Data:n}=Ze.decode(r),s=n??new Uint8Array;switch(t){case ne.RSA:return ai(s,e);case ne.Ed25519:return Us(s);case ne.secp256k1:return yi(s);case ne.ECDSA:return fs(s);default:throw new Qt}}function yu(r){let{Type:e,Data:t}=Ze.decode(r.digest),n=t??new Uint8Array;switch(e){case ne.Ed25519:return Us(n);case ne.secp256k1:return yi(n);case ne.ECDSA:return fs(n);default:throw new Qt}}function We(r){return Ze.encode({Type:ne[r.type],Data:r.raw})}var gu=Symbol.for("nodejs.util.inspect.custom"),Wd=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()})`}[ko]=!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(Wd,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")}[gu](){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}},Gd=2336,Qr=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Me.digest(K(this.url))}[gu](){return`PeerId(${this.url})`}[ko]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return le.createV1(Gd,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=$(e)),e.toString()===this.toString())}};var Yd=114,bu=2336;function gi(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 Zd(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 wr(t)}function wr(r){if(jd(r))return new zn({multihash:r});if(Xd(r))try{let e=yu(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 Zd(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==Yd&&r.code!==bu)throw new pn("Supplied PeerID CID is invalid");if(r.code===bu){let e=$(r.multihash.digest);return new Qr(new URL(e))}return wr(r.multihash)}function Xd(r){return r.code===Me.code}function jd(r){return r.code===or.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=mu(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=wu(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=wu(e,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,t)}},wu=(r,e,t)=>{let n=K(r),s=mr(n.byteLength),o=mr(e.length),i=mr(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 Qd=45,Jd=15,jn=new Xn;function xu(r){if(!(r.length>Jd))return jn.new(r).parseWith(()=>jn.readIPv4Addr())}function Eu(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Qd))return jn.new(r).parseWith(()=>jn.readIPv6Addr())}function Qn(r){return!!xu(r)}function Su(r){return!!Eu(r)}function wi(r){return e=>$(e,r)}function xi(r){return e=>K(e,r)}function xr(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Ht(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}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!==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=Ht(n);return et([t,s],t.length+s.length)}function _u(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=pt.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=Ht(n);return et([t,s],t.length+s.length)}function Ei(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=$(e,"base32"),s=xr(t);return`${n}:${s}`}var Si=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},Au=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=Si(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},Tu=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(".")},Iu=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 Du(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 bi=Object.values(Or).map(r=>r.decoder),eh=(function(){let r=bi[0].or(bi[1]);return bi.slice(2).forEach(e=>r=r.or(e)),r})();function Cu(r){return eh.decode(r)}function Lu(r){return e=>r.encoder.encode(e)}function th(r){if(parseInt(r).toString()!==r)throw new ut("Value must be an integer")}function rh(r){if(r<0)throw new ut("Value must be a positive integer, or zero")}function nh(r){return e=>{if(e>r)throw new ut(`Value must be smaller than or equal to ${r}`)}}function oh(...r){return e=>{for(let t of r)t(e)}}var tn=oh(th,rh,nh(65535));var pe=-1,vi=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)}))}},ft=new vi,bh=[{code:4,name:"ip4",size:32,valueToBytes:Si,bytesToValue:Tu,validate:r=>{if(!Qn(r))throw new ut(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Ht,bytesToValue:xr,validate:tn},{code:273,name:"udp",size:16,valueToBytes:Ht,bytesToValue:xr,validate:tn},{code:33,name:"dccp",size:16,valueToBytes:Ht,bytesToValue:xr,validate:tn},{code:41,name:"ip6",size:128,valueToBytes:Au,bytesToValue:Iu,stringToValue:Du,validate:r=>{if(!Su(r))throw new ut(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:pe},{code:43,name:"ipcidr",size:8,bytesToValue:wi("base10"),valueToBytes:xi("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:Ht,bytesToValue:xr,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:wi("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?xi("base58btc")(r):le.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Ei,valueToBytes:vu},{code:445,name:"onion3",size:296,bytesToValue:Ei,valueToBytes:_u},{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:Lu(Qo),valueToBytes:Cu},{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=>{ft.addProtocol(r)});function Ru(r){let e=[],t=0;for(;t<r.length;){let n=$r(r,t),s=ft.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 Bu(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let s=ft.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;pr(n.code,l,u),u+=o,i!=null&&(s.size===pe&&(pr(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 Ou(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=ft.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 Pu(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=ft.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"),qi=Symbol.for("@multiformats/multiaddr");function Eh(r){if(r==null&&(r="/"),Nu(r))return r.getComponents();if(r instanceof Uint8Array)return Ru(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),Ou(r);if(Array.isArray(r))return r;throw new ge("Must be a string, Uint8Array, Component[], or another Multiaddr")}var no=class r{[qi]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=Eh(e),t.validate!==!1&&Sh(this)}get bytes(){return this.#r==null&&(this.#r=Bu(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=Pu(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=ft.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function Nu(r){return!!r?.[qi]}function Pe(r){return new no(r)}var Vi={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Uu={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},ku=new globalThis.TextEncoder;function vh(r,e){let t=Vi[e],n=Uu[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=Vi[e],s=Uu[e],o=r;for(;o.length>0;){let i=ku.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 Hi(r,{size:e=32,utf8Buffer:t}={}){if(!Vi[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=ku.encode(r)}return vh(r,e)}var rn={hash:r=>Number(Hi(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 Mu(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 oo=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 _r(r,e=.001,t){return new oo({...Mu(r,e),...t??{}})}function He(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var so=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}},Ar=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new so(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 so(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 zi=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function vt(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 Ar,s,o,i,a=He(),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=He()})}},l=w=>o!=null?o(w):(n.push(w),s),u=w=>(n=new Ar,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 Ar,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 zi)},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 $i=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},Ku=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function Wi(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(Ku(i));return}if(i&&(c=()=>{h(Ku(i))},i.addEventListener("abort",c,{once:!0})),r.then(f,h),t===Number.POSITIVE_INFINITY)return;let p=new $i;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=Wi(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 Gi(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 io=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 ao=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function Bh(r){return r.reason}async function _t(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 co=class{deferred;signal;constructor(e){this.signal=e,this.deferred=He(),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 uo=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 co(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 _t(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 lo=class extends _e{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=Gi(this.emitEmpty.bind(this),1),this.emitIdle=Gi(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new io;let n=new uo(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=vt({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,fo=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 ao)};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()),_t(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let e=vt(),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 dt(`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 dt("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 dt("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 dt(`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 dt(`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 Jt))}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 ho=class extends fo{remoteAddr;metricPrefix;metrics;constructor(e){super(e),this.metricPrefix=e.metricPrefix??"",this.metrics=e.metrics,this.remoteAddr=e.remoteAddr,this.addEventListener("close",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 po(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 Yi=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=He(),this.haveNext=He()}[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=He(),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=He(),await _t(this.readNext.promise,t?.signal,t)}};function qu(){return new Yi}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=qu();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 Vu=Kh;function Hu(r,...e){if(r==null)throw new Error("Empty pipeline");if(Zi(r)){let n=r;r=()=>n.source}else if(zu(r)||Fu(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&Zi(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let n=1;n<t.length-1;n++)Zi(t[n])&&(t[n]=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,zu=r=>r?.[Symbol.iterator]!=null,Zi=r=>r==null?!1:r.sink!=null&&r.source!=null,Vh=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=vt({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(zu(o))s=function*(){yield*o,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Vu(n,s())}return r.source};var Hh=4194304,mo=class extends Error{static name="UnwrappedError";name="UnwrappedError"},ji=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Qi=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ji=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Fh(r){return typeof r?.closeRead=="function"}function zh(r){return typeof r?.close=="function"}function Xi(r){return Fh(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??Hh,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 mo("Stream was unwrapped");if(Xi(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 _t(s.promise,u?.signal),Xi(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(Xi(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 mo("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??mr;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 ji("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new Ji(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new Qi(`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 At(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=vt(),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 $u(...r){let e=r.map(t=>Yh(t)?Zh(t):t);return Hu(...e)}var Tr=class extends lo{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var X=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),B=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),Wu=r=>({match:e=>r.match(e)===!1?e:!1}),F=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),Ee=(...r)=>({match:e=>{let t;for(let n of r){let 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 Xh=B(421),oE=j(Xh),go=B(54),bo=B(55),wo=B(56),ta=B(53),sE=j(go,F(B(421))),iE=j(bo,F(B(421))),aE=j(wo,F(B(421))),cE=j(Ee(ta,wo,go,bo),F(B(421))),Gu=z(B(4),F(B(43))),Yu=z(F(B(42)),B(41),F(B(43))),ra=Ee(Gu,Yu),Ir=Ee(ra,ta,go,bo,wo),uE=j(Ee(ra,z(Ee(ta,wo,go,bo),F(B(421))))),lE=j(Gu),fE=j(Yu),dE=j(ra),na=z(Ir,B(6)),on=z(Ir,B(273)),hE=j(z(na,F(B(421)))),pE=j(on),oa=z(on,X(460),F(B(421))),xo=z(on,X(461),F(B(421))),jh=Ee(oa,xo),mE=j(oa),yE=j(xo),ea=Ee(Ir,na,on,oa,xo),Zu=Ee(z(ea,X(477),F(B(421)))),gE=j(Zu),Xu=Ee(z(ea,X(478),F(B(421))),z(ea,X(448),F(B(449)),X(477),F(B(421)))),bE=j(Xu),ju=z(on,X(280),F(B(466)),F(B(466)),F(B(421))),wE=j(ju),Qu=z(xo,X(465),F(B(466)),F(B(466)),F(B(421))),xE=j(Qu),yo=Ee(Zu,Xu,z(na,F(B(421))),z(jh,F(B(421))),z(Ir,F(B(421))),ju,Qu,B(421)),Ju=j(yo),Qh=z(F(yo),X(290),Wu(X(281)),F(B(421))),Yt=j(Qh),Jh=Ee(z(yo,X(290),X(281),F(B(421))),z(yo,X(281),F(B(421))),z(X(281),F(B(421)))),EE=j(Jh),ep=z(Ir,Ee(z(B(6,"80")),z(B(6),X(480)),X(480)),F(B(481)),F(B(421))),SE=j(ep),tp=z(Ir,Ee(z(B(6,"443")),z(B(6,"443"),X(480)),z(B(6),X(443)),z(B(6),X(448),X(480)),z(X(448),X(480)),X(448),X(443)),F(B(481)),F(B(421))),vE=j(tp),rp=Ee(z(B(777),F(B(421)))),_E=j(rp),np=Ee(z(B(400),F(B(421)))),AE=j(np);var sa=1e3,el=60*sa,tl=15,rl=120*el,nl=1,Eo=5e3,ol=100,ia="circuit-relay-source",sn=`${wa}-circuit-relay`,sl=2*el,il=BigInt(1<<17),ke="/libp2p/circuit/relay/0.2.0/hop",Zt="/libp2p/circuit/relay/0.2.0/stop",al=30*sa,DE=30*sa,an=300,cl=4096,ul=.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=()=>qt(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),Tt.codec().encode(a.peer,c)),a.reservation!=null&&(c.uint32(26),cn.codec().encode(a.reservation,c)),a.limit!=null&&(c.uint32(34),It.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=Tt.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=It.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*Tt.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*It.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=()=>qt(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),Tt.codec().encode(a.peer,c)),a.limit!=null&&(c.uint32(26),It.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=Tt.codec().decode(a,a.uint32(),{limits:l.limits?.peer});break}case 3:{u.limit=It.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*Tt.codec().stream(a,a.uint32(),`${l}.peer`,{limits:u.limits?.peer});break}case 3:{yield*It.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 Tt;(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 Vt('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 Vt('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})(Tt||(Tt={}));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 Vt('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 Vt('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 It;(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})(It||(It={}));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 aa;(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"})(aa||(aa={}));(function(r){r.codec=()=>qt(aa)})(q||(q={}));var Xt;(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})(Xt||(Xt={}));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),Xt.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=Xt.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*Xt.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 So=class extends Error{constructor(e="Transfer limit error"){super(e),this.name="TransferLimitError"}},vo=class extends Error{constructor(e="Duration limit error"){super(e),this.name="DurationLimitError"}},ln=class extends Error{static name="HadEnoughRelaysError";name="HadEnoughRelaysError"},_o=class extends Error{static name="DoubleRelayError";name="DoubleRelayError"},Ao=class extends Error{static name="RelayQueueFullError";name="RelayQueueFullError"};function ll(r,e,t){let n=e.remaining,s=o=>{let i=BigInt(o.data.byteLength);e.remaining-=i,e.remaining<0&&r.abort(new So(`data limit of ${n} bytes exceeded`))};r.addEventListener("message",s)}function fl(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=po(i);let c;n.limit?.data!=null&&(c={remaining:n.limit.data});let l=()=>{let u;t.aborted?u=t.reason:u=new vo(`duration limit of ${n.limit?.duration} ms exceeded`),o(u)};a.addEventListener("abort",l,{once:!0}),c!=null&&(ll(e,c,s),ll(r,c,s)),$u(r,e,r).catch(u=>{o(u)}).finally(()=>{a.clear()})}function ca(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}},To=j(z(Ju.matchers[0],X(290))),Io=j(X(290));function Do(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 Dt=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 Do(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 Do(this.map.values(),e=>e.key)}values(){return Do(this.map.values(),e=>e.value)}get size(){return this.map.size}};var Co=class{filter;constructor(e,t){this.filter=_r(e,t)}has(e){return this.filter.has(e.toMultihash().bytes)}add(e){this.filter.add(e.toMultihash().bytes)}remove(e){this.filter.remove?.(e.toMultihash().bytes)}};function ua(r,e=.001){return new Co(r,e)}var la=class extends Dt{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 fa(r){let{name:e,metrics:t}=r,n;return t!=null?n=new la({name:e,metrics:t}):n=new Dt,n}var da=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 da(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 Lo=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??tl,this.applyDefaultLimit=t.applyDefaultLimit!==!1,this.reservationTtl=t.reservationTtl??rl,this.defaultDurationLimit=t.defaultDurationLimit??sl,this.defaultDataLimit=t.defaultDataLimit??il,this.reservations=fa({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:dl(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 Ro=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 Xt.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},Bo=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??al,this.maxInboundHopStreams=t.maxInboundHopStreams,this.maxOutboundHopStreams=t.maxOutboundHopStreams,this.maxOutboundStopStreams=t.maxOutboundStopStreams??op.maxOutboundStopStreams,this.reservationStore=new Lo(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=At(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),Yt.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:{[ia]:{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:{[ia]: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 Ro({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(Yt.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=wr($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),fl(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(Zt,{maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0,...n}),o=At(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 Ct=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var Oo=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=hl(n),i=hl(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 Tr({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=po([AbortSignal.timeout(5e3),t]);try{await this.components.connectionManager.openConnection(e,{signal:n})}finally{n.clear()}}};function hl(r){let e=r.metadata.get("last-dial-success");return e==null?0:new Date($(e)).getTime()}var pa=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??Eo,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(Io.exactMatch(e))this.log("searching for circuit relay servers"),this.reservationId=this.reservationStore.reserveRelay();else if(To.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 Lt(`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 pl(r){return new pa(r)}var ml="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var yl=(r=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)e+=ml[t[r]&63];return e};var sp=60*1e3*10,ip=60*1e3*5,ap=30*1e3,Po=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 Dt,this.pendingReservations=[],this.maxReservationQueueLength=t?.maxReservationQueueLength??ol,this.reservationCompletionTimeout=t?.reservationCompletionTimeout??Eo,this.started=!1,this.relayFilter=_r(100),this.reserveQueue=new Tr({concurrency:t?.reservationConcurrency??nl,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=yl();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 Lt("Cannot use self as relay");if(this.reserveQueue.size>this.maxReservationQueueLength)throw new Ao("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 Lt("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&&ca(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(Yt.matches(a.remoteAddr))throw new _o("not creating reservation over relayed connection");let c=await this.#e(a,{signal:i}),l=ca(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=At(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=_r(100),this.log("not discovered enough relays %d/%d",this.reservations.size,this.pendingReservations.length),this.safeDispatchEvent("relay:not-enough-relays")}};var ma=class extends ho{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 ya(r){return new ma(r)}var cp=r=>{if(r.peer==null)return!1;try{r.peer.addrs.forEach(Pe)}catch{return!1}return!0},gl={maxInboundStopStreams:an,maxOutboundStopStreams:an,stopTimeout:3e4},No=class{components;discovery;reservationStore;maxInboundStopStreams;maxOutboundStopStreams;started;log;shutdownController;constructor(e,t={}){this.components=e,this.log=e.logger.forComponent("libp2p:circuit-relay:transport"),this.maxInboundStopStreams=t.maxInboundStopStreams??gl.maxInboundStopStreams,this.maxOutboundStopStreams=t.maxOutboundStopStreams??gl.maxOutboundStopStreams,this.shutdownController=new AbortController,this.discovery=new Oo(e,{filter:t.discoveryFilter??ua(cl,ul)}),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 Po(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";[Aa]=["@libp2p/transport","@libp2p/circuit-relay-v2-transport"];get[Ta](){return this.discovery!=null?["@libp2p/identify"]:[]}[_a]=!0;isStarted(){return this.started}async start(){this.shutdownController=new AbortController,this.shutdownController.signal,await this.components.registrar.handle(Zt,this.onStop,{maxInboundStreams:this.maxInboundStopStreams,maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0}),await Ea(this.discovery,this.reservationStore),this.started=!0}async stop(){this.shutdownController.abort(),await Sa(this.discovery,this.reservationStore),await this.components.registrar.unhandle(Zt),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=gi(i),l=gi(a),f=this.components.connectionManager.getConnections(c)[0];f==null?(await this.components.peerStore.merge(c,{multiaddrs:[s]}),t.onProgress?.(new Ct("circuit-relay:open-connection")),f=await this.components.connectionManager.openConnection(c,t)):t.onProgress?.(new Ct("circuit-relay:reuse-connection"));let h;try{t.onProgress?.(new Ct("circuit-relay:open-hop-stream")),h=await f.newStream(ke,t);let p=At(h).pb(Z);t.onProgress?.(new Ct("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 Ct("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=ya({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 pl({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=>To.exactMatch(t)||Io.exactMatch(t))}dialFilter(e){return e=Array.isArray(e)?e:[e],e.filter(t=>Yt.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=At(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=wr($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=ya({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 Bo(e,r)}function lp(r={}){return e=>new No(e,r)}return Sl(fp);})();
|
|
3
3
|
/*! Bundled license information:
|
|
4
4
|
|
|
5
5
|
@noble/hashes/utils.js:
|