@libp2p/circuit-relay-v2 3.2.8 → 3.2.9-3833353bd

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 bo=Object.defineProperty;var Au=Object.getOwnPropertyDescriptor;var _u=Object.getOwnPropertyNames;var Iu=Object.prototype.hasOwnProperty;var _t=(r,t)=>{for(var e in t)bo(r,e,{get:t[e],enumerable:!0})},Tu=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of _u(t))!Iu.call(r,o)&&o!==e&&bo(r,o,{get:()=>t[o],enumerable:!(n=Au(t,o))||n.enumerable});return r};var Lu=r=>Tu(bo({},"__esModule",{value:!0}),r);var xd={};_t(xd,{RELAY_V2_HOP_CODEC:()=>qt,RELAY_V2_STOP_CODEC:()=>Me,circuitRelayServer:()=>ru,circuitRelayTransport:()=>mu});var xo=Symbol.for("@libp2p/peer-id");var wo="keep-alive";var Us=Symbol.for("@libp2p/transport");var Ns;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Ns||(Ns={}));var Jt=class extends Error{static name="AbortError";constructor(t="The operation was aborted"){super(t),this.name="AbortError"}};var bt=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},Fe=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}};var Gr=class extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}},Wr=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}};var Zr=class extends Error{static name="InvalidMessageError";constructor(t="Invalid message"){super(t),this.name="InvalidMessageError"}};var pr=class extends Error{static name="DialError";constructor(t="Dial error"){super(t),this.name="DialError"}},Ie=class extends Error{static name="ListenError";constructor(t="Listen error"){super(t),this.name="ListenError"}};var ze=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var Ot=class extends EventTarget{#t=new Map;constructor(){super()}listenerCount(t){let e=this.#t.get(t);return e==null?0:e.length}addEventListener(t,e,n){super.addEventListener(t,e,n);let o=this.#t.get(t);o==null&&(o=[],this.#t.set(t,o)),o.push({callback:e,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(t,e,n){super.removeEventListener(t.toString(),e??null,n);let o=this.#t.get(t);o!=null&&(o=o.filter(({callback:i})=>i!==e),this.#t.set(t,o))}dispatchEvent(t){let e=super.dispatchEvent(t),n=this.#t.get(t.type);return n==null||(n=n.filter(({once:o})=>!o),this.#t.set(t.type,n)),e}safeDispatchEvent(t,e={}){return this.dispatchEvent(new CustomEvent(t,e))}};function Os(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function Ms(...r){let t=[];for(let e of r)Os(e)&&t.push(e);await Promise.all(t.map(async e=>{e.beforeStart!=null&&await e.beforeStart()})),await Promise.all(t.map(async e=>{await e.start()})),await Promise.all(t.map(async e=>{e.afterStart!=null&&await e.afterStart()}))}async function ks(...r){let t=[];for(let e of r)Os(e)&&t.push(e);await Promise.all(t.map(async e=>{e.beforeStop!=null&&await e.beforeStop()})),await Promise.all(t.map(async e=>{await e.stop()})),await Promise.all(t.map(async e=>{e.afterStop!=null&&await e.afterStop()}))}var Ks=Symbol.for("@libp2p/service-capabilities"),qs=Symbol.for("@libp2p/service-dependencies");var _o={};_t(_o,{base58btc:()=>Q,base58flickr:()=>Nu});var Yd=new Uint8Array(0);function Fs(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function te(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 zs(r){return new TextEncoder().encode(r)}function Vs(r){return new TextDecoder().decode(r)}function Ru(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var o=0;o<r.length;o++){var i=r.charAt(o),s=i.charCodeAt(0);if(e[s]!==255)throw new TypeError(i+" is ambiguous");e[s]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function f(y){if(y instanceof Uint8Array||(ArrayBuffer.isView(y)?y=new Uint8Array(y.buffer,y.byteOffset,y.byteLength):Array.isArray(y)&&(y=Uint8Array.from(y))),!(y instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(y.length===0)return"";for(var b=0,h=0,w=0,v=y.length;w!==v&&y[w]===0;)w++,b++;for(var m=(v-w)*u+1>>>0,_=new Uint8Array(m);w!==v;){for(var B=y[w],C=0,I=m-1;(B!==0||C<h)&&I!==-1;I--,C++)B+=256*_[I]>>>0,_[I]=B%a>>>0,B=B/a>>>0;if(B!==0)throw new Error("Non-zero carry");h=C,w++}for(var R=m-h;R!==m&&_[R]===0;)R++;for(var T=c.repeat(b);R<m;++R)T+=r.charAt(_[R]);return T}function d(y){if(typeof y!="string")throw new TypeError("Expected String");if(y.length===0)return new Uint8Array;var b=0;if(y[b]!==" "){for(var h=0,w=0;y[b]===c;)h++,b++;for(var v=(y.length-b)*l+1>>>0,m=new Uint8Array(v);y[b];){var _=e[y.charCodeAt(b)];if(_===255)return;for(var B=0,C=v-1;(_!==0||B<w)&&C!==-1;C--,B++)_+=a*m[C]>>>0,m[C]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");w=B,b++}if(y[b]!==" "){for(var I=v-w;I!==v&&m[I]===0;)I++;for(var R=new Uint8Array(h+(v-I)),T=h;I!==v;)R[T++]=m[I++];return R}}}function g(y){var b=d(y);if(b)return b;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:d,decode:g}}var Bu=Ru,Cu=Bu,Gs=Cu;var Eo=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},vo=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){this.name=t,this.prefix=e;let o=e.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return Ws(this,t)}},So=class{decoders;constructor(t){this.decoders=t}or(t){return Ws(this,t)}decode(t){let e=t[0],n=this.decoders[e];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Ws(r,t){return new So({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var Ao=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,o){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=o,this.encoder=new Eo(t,e,n),this.decoder=new vo(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Ve({name:r,prefix:t,encode:e,decode:n}){return new Ao(r,t,e,n)}function fe({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=Gs(e,r);return Ve({prefix:t,name:r,encode:n,decode:i=>te(o(i))})}function Du(r,t,e,n){let o={};for(let u=0;u<t.length;++u)o[t[u]]=u;let i=r.length;for(;r[i-1]==="=";)--i;let s=new Uint8Array(i*e/8|0),a=0,c=0,l=0;for(let u=0;u<i;++u){let f=o[r[u]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<e|f,a+=e,a>=8&&(a-=8,s[l++]=255&c>>a)}if(a>=e||(255&c<<8-a)!==0)throw new SyntaxError("Unexpected end of data");return s}function Pu(r,t,e){let n=t[t.length-1]==="=",o=(1<<e)-1,i="",s=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],s+=8;s>e;)s-=e,i+=t[o&a>>s];if(s!==0&&(i+=t[o&a<<e-s]),n)for(;(i.length*e&7)!==0;)i+="=";return i}function st({name:r,prefix:t,bitsPerChar:e,alphabet:n}){return Ve({prefix:t,name:r,encode(o){return Pu(o,n,e)},decode(o){return Du(o,n,e,r)}})}var Q=fe({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Nu=fe({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Io={};_t(Io,{base32:()=>ee,base32hex:()=>ku,base32hexpad:()=>qu,base32hexpadupper:()=>Fu,base32hexupper:()=>Ku,base32pad:()=>Ou,base32padupper:()=>Mu,base32upper:()=>Uu,base32z:()=>zu});var ee=st({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Uu=st({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Ou=st({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Mu=st({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),ku=st({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Ku=st({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),qu=st({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Fu=st({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),zu=st({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var To={};_t(To,{base36:()=>mr,base36upper:()=>Vu});var mr=fe({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Vu=fe({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Hu=Ys,Zs=128,Gu=127,Wu=~Gu,Zu=Math.pow(2,31);function Ys(r,t,e){t=t||[],e=e||0;for(var n=e;r>=Zu;)t[e++]=r&255|Zs,r/=128;for(;r&Wu;)t[e++]=r&255|Zs,r>>>=7;return t[e]=r|0,Ys.bytes=e-n+1,t}var $u=Lo,Yu=128,$s=127;function Lo(r,n){var e=0,n=n||0,o=0,i=n,s,a=r.length;do{if(i>=a)throw Lo.bytes=0,new RangeError("Could not decode varint");s=r[i++],e+=o<28?(s&$s)<<o:(s&$s)*Math.pow(2,o),o+=7}while(s>=Yu);return Lo.bytes=i-n,e}var Xu=Math.pow(2,7),Qu=Math.pow(2,14),ju=Math.pow(2,21),Ju=Math.pow(2,28),tl=Math.pow(2,35),el=Math.pow(2,42),rl=Math.pow(2,49),nl=Math.pow(2,56),ol=Math.pow(2,63),il=function(r){return r<Xu?1:r<Qu?2:r<ju?3:r<Ju?4:r<tl?5:r<el?6:r<rl?7:r<nl?8:r<ol?9:10},sl={encode:Hu,decode:$u,encodingLength:il},al=sl,yr=al;function gr(r,t=0){return[yr.decode(r,t),yr.decode.bytes]}function He(r,t,e=0){return yr.encode(r,t,e),t}function Ge(r){return yr.encodingLength(r)}function Ft(r,t){let e=t.byteLength,n=Ge(r),o=n+Ge(e),i=new Uint8Array(o+e);return He(r,i,0),He(e,i,n),i.set(t,o),new We(r,e,t,i)}function Mt(r){let t=te(r),[e,n]=gr(t),[o,i]=gr(t.subarray(n)),s=t.subarray(n+i);if(s.byteLength!==o)throw new Error("Incorrect length");return new We(e,o,s,t)}function Xs(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&Fs(r.bytes,e.bytes)}}var We=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};function Qs(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return ul(e,Ro(r),t??Q.encoder);default:return ll(e,Ro(r),t??ee.encoder)}}var js=new WeakMap;function Ro(r){let t=js.get(r);if(t==null){let e=new Map;return js.set(r,e),e}return t}var at=class r{code;version;multihash;bytes;"/";constructor(t,e,n,o){this.code=e,this.version=t,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:t,multihash:e}=this;if(t!==br)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==fl)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}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:t,digest:e}=this.multihash,n=Ft(t,e);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(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&Xs(t.multihash,n.multihash)}toString(t){return Qs(this,t)}toJSON(){return{"/":Qs(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:o,multihash:i,bytes:s}=e;return new r(n,o,i,s??Js(n,o,i.bytes))}else if(e[hl]===!0){let{version:n,multihash:o,code:i}=e,s=Mt(o);return r.create(n,i,s)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==br)throw new Error(`Version 0 CID must use dag-pb (code: ${br}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=Js(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,br,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,o=te(t.subarray(n,n+e.multihashSize));if(o.byteLength!==e.multihashSize)throw new Error("Incorrect length");let i=o.subarray(e.multihashSize-e.digestSize),s=new We(e.multihashCode,e.digestSize,i,o);return[e.version===0?r.createV0(s):r.createV1(e.codec,s),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[f,d]=gr(t.subarray(e));return e+=d,f},o=n(),i=br;if(o===18?(o=0,e=0):i=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let s=e,a=n(),c=n(),l=e+c,u=l-s;return{version:o,codec:i,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(t,e){let[n,o]=cl(t,e),i=r.decode(o);if(i.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Ro(i).set(n,t),i}};function cl(r,t){switch(r[0]){case"Q":{let e=t??Q;return[Q.prefix,e.decode(`${Q.prefix}${r}`)]}case Q.prefix:{let e=t??Q;return[Q.prefix,e.decode(r)]}case ee.prefix:{let e=t??ee;return[ee.prefix,e.decode(r)]}case mr.prefix:{let e=t??mr;return[mr.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function ul(r,t,e){let{prefix:n}=e;if(n!==Q.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let o=t.get(n);if(o==null){let i=e.encode(r).slice(1);return t.set(n,i),i}else return o}function ll(r,t,e){let{prefix:n}=e,o=t.get(n);if(o==null){let i=e.encode(r);return t.set(n,i),i}else return o}var br=112,fl=18;function Js(r,t,e){let n=Ge(r),o=n+Ge(t),i=new Uint8Array(o+e.byteLength);return He(r,i,0),He(t,i,n),i.set(e,o),i}var hl=Symbol.for("@ipld/js-cid/CID");var Bo={};_t(Bo,{identity:()=>re});var ta=0,dl="identity",ea=te;function pl(r){return Ft(ta,ea(r))}var re={code:ta,name:dl,encode:ea,digest:pl};function pt(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function ra(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function ml(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Ze(r,...t){if(!ml(r))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(r.length))throw new Error("Uint8Array expected of length "+t+", got length="+r.length)}function na(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");ra(r.outputLen),ra(r.blockLen)}function $e(r,t=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(t&&r.finished)throw new Error("Hash#digest() has already been called")}function oa(r,t){Ze(r);let e=t.outputLen;if(r.length<e)throw new Error("digestInto() expects output buffer of length at least "+e)}var Te=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Yr(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function zt(r,t){return r<<32-t|r>>>t}function ia(r){if(typeof r!="string")throw new Error("utf8ToBytes expected string, got "+typeof r);return new Uint8Array(new TextEncoder().encode(r))}function xr(r){return typeof r=="string"&&(r=ia(r)),Ze(r),r}function Co(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];Ze(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let i=r[n];e.set(i,o),o+=i.length}return e}var Ye=class{clone(){return this._cloneInto()}};function Xr(r){let t=n=>r().update(xr(n)).digest(),e=r();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>r(),t}function Qr(r=32){if(Te&&typeof Te.getRandomValues=="function")return Te.getRandomValues(new Uint8Array(r));if(Te&&typeof Te.randomBytes=="function")return Te.randomBytes(r);throw new Error("crypto.getRandomValues must be defined")}function yl(r,t,e,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(t,e,n);let o=BigInt(32),i=BigInt(4294967295),s=Number(e>>o&i),a=Number(e&i),c=n?4:0,l=n?0:4;r.setUint32(t+c,s,n),r.setUint32(t+l,a,n)}function sa(r,t,e){return r&t^~r&e}function aa(r,t,e){return r&t^r&e^t&e}var Xe=class extends Ye{constructor(t,e,n,o){super(),this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=Yr(this.buffer)}update(t){$e(this);let{view:e,buffer:n,blockLen:o}=this;t=xr(t);let i=t.length;for(let s=0;s<i;){let a=Math.min(o-this.pos,i-s);if(a===o){let c=Yr(t);for(;o<=i-s;s+=o)this.process(c,s);continue}n.set(t.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===o&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){$e(this),oa(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:o,isLE:i}=this,{pos:s}=this;e[s++]=128,this.buffer.subarray(s).fill(0),this.padOffset>o-s&&(this.process(n,0),s=0);for(let f=s;f<o;f++)e[f]=0;yl(n,o-8,BigInt(this.length*8),i),this.process(n,0);let a=Yr(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should 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],i)}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:e,buffer:n,length:o,finished:i,destroyed:s,pos:a}=this;return t.length=o,t.pos=a,t.finished=i,t.destroyed=s,o%e&&t.buffer.set(n),t}};var jr=BigInt(4294967295),Do=BigInt(32);function ca(r,t=!1){return t?{h:Number(r&jr),l:Number(r>>Do&jr)}:{h:Number(r>>Do&jr)|0,l:Number(r&jr)|0}}function gl(r,t=!1){let e=new Uint32Array(r.length),n=new Uint32Array(r.length);for(let o=0;o<r.length;o++){let{h:i,l:s}=ca(r[o],t);[e[o],n[o]]=[i,s]}return[e,n]}var bl=(r,t)=>BigInt(r>>>0)<<Do|BigInt(t>>>0),xl=(r,t,e)=>r>>>e,wl=(r,t,e)=>r<<32-e|t>>>e,El=(r,t,e)=>r>>>e|t<<32-e,vl=(r,t,e)=>r<<32-e|t>>>e,Sl=(r,t,e)=>r<<64-e|t>>>e-32,Al=(r,t,e)=>r>>>e-32|t<<64-e,_l=(r,t)=>t,Il=(r,t)=>r,Tl=(r,t,e)=>r<<e|t>>>32-e,Ll=(r,t,e)=>t<<e|r>>>32-e,Rl=(r,t,e)=>t<<e-32|r>>>64-e,Bl=(r,t,e)=>r<<e-32|t>>>64-e;function Cl(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var Dl=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),Pl=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,Nl=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),Ul=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,Ol=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),Ml=(r,t,e,n,o,i)=>t+e+n+o+i+(r/2**32|0)|0;var kl={fromBig:ca,split:gl,toBig:bl,shrSH:xl,shrSL:wl,rotrSH:El,rotrSL:vl,rotrBH:Sl,rotrBL:Al,rotr32H:_l,rotr32L:Il,rotlSH:Tl,rotlSL:Ll,rotlBH:Rl,rotlBL:Bl,add:Cl,add3L:Dl,add3H:Pl,add4L:Nl,add4H:Ul,add5H:Ml,add5L:Ol},U=kl;var[Kl,ql]=U.split(["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))),he=new Uint32Array(80),de=new Uint32Array(80),Po=class extends Xe{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){let{Ah:t,Al:e,Bh:n,Bl:o,Ch:i,Cl:s,Dh:a,Dl:c,Eh:l,El:u,Fh:f,Fl:d,Gh:g,Gl:y,Hh:b,Hl:h}=this;return[t,e,n,o,i,s,a,c,l,u,f,d,g,y,b,h]}set(t,e,n,o,i,s,a,c,l,u,f,d,g,y,b,h){this.Ah=t|0,this.Al=e|0,this.Bh=n|0,this.Bl=o|0,this.Ch=i|0,this.Cl=s|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=f|0,this.Fl=d|0,this.Gh=g|0,this.Gl=y|0,this.Hh=b|0,this.Hl=h|0}process(t,e){for(let m=0;m<16;m++,e+=4)he[m]=t.getUint32(e),de[m]=t.getUint32(e+=4);for(let m=16;m<80;m++){let _=he[m-15]|0,B=de[m-15]|0,C=U.rotrSH(_,B,1)^U.rotrSH(_,B,8)^U.shrSH(_,B,7),I=U.rotrSL(_,B,1)^U.rotrSL(_,B,8)^U.shrSL(_,B,7),R=he[m-2]|0,T=de[m-2]|0,et=U.rotrSH(R,T,19)^U.rotrBH(R,T,61)^U.shrSH(R,T,6),H=U.rotrSL(R,T,19)^U.rotrBL(R,T,61)^U.shrSL(R,T,6),q=U.add4L(I,H,de[m-7],de[m-16]),ut=U.add4H(q,C,et,he[m-7],he[m-16]);he[m]=ut|0,de[m]=q|0}let{Ah:n,Al:o,Bh:i,Bl:s,Ch:a,Cl:c,Dh:l,Dl:u,Eh:f,El:d,Fh:g,Fl:y,Gh:b,Gl:h,Hh:w,Hl:v}=this;for(let m=0;m<80;m++){let _=U.rotrSH(f,d,14)^U.rotrSH(f,d,18)^U.rotrBH(f,d,41),B=U.rotrSL(f,d,14)^U.rotrSL(f,d,18)^U.rotrBL(f,d,41),C=f&g^~f&b,I=d&y^~d&h,R=U.add5L(v,B,I,ql[m],de[m]),T=U.add5H(R,w,_,C,Kl[m],he[m]),et=R|0,H=U.rotrSH(n,o,28)^U.rotrBH(n,o,34)^U.rotrBH(n,o,39),q=U.rotrSL(n,o,28)^U.rotrBL(n,o,34)^U.rotrBL(n,o,39),ut=n&i^n&a^i&a,S=o&s^o&c^s&c;w=b|0,v=h|0,b=g|0,h=y|0,g=f|0,y=d|0,{h:f,l:d}=U.add(l|0,u|0,T|0,et|0),l=a|0,u=c|0,a=i|0,c=s|0,i=n|0,s=o|0;let L=U.add3L(et,q,S);n=U.add3H(L,T,H,ut),o=L|0}({h:n,l:o}=U.add(this.Ah|0,this.Al|0,n|0,o|0)),{h:i,l:s}=U.add(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=U.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=U.add(this.Dh|0,this.Dl|0,l|0,u|0),{h:f,l:d}=U.add(this.Eh|0,this.El|0,f|0,d|0),{h:g,l:y}=U.add(this.Fh|0,this.Fl|0,g|0,y|0),{h:b,l:h}=U.add(this.Gh|0,this.Gl|0,b|0,h|0),{h:w,l:v}=U.add(this.Hh|0,this.Hl|0,w|0,v|0),this.set(n,o,i,s,a,c,l,u,f,d,g,y,b,h,w,v)}roundClean(){he.fill(0),de.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var ua=Xr(()=>new Po);var en={};_t(en,{aInRange:()=>Tt,abool:()=>Vt,abytes:()=>Qe,bitGet:()=>Wl,bitLen:()=>Mo,bitMask:()=>Er,bitSet:()=>Zl,bytesToHex:()=>oe,bytesToNumberBE:()=>ie,bytesToNumberLE:()=>me,concatBytes:()=>se,createHmacDrbg:()=>ko,ensureBytes:()=>ot,equalBytes:()=>Hl,hexToBytes:()=>Re,hexToNumber:()=>Oo,inRange:()=>wr,isBytes:()=>pe,memoized:()=>Ce,notImplemented:()=>Yl,numberToBytesBE:()=>ye,numberToBytesLE:()=>Be,numberToHexUnpadded:()=>Le,numberToVarBytesBE:()=>Vl,utf8ToBytes:()=>Gl,validateObject:()=>Xt});var Jr=BigInt(0),tn=BigInt(1),Fl=BigInt(2);function pe(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Qe(r){if(!pe(r))throw new Error("Uint8Array expected")}function Vt(r,t){if(typeof t!="boolean")throw new Error(r+" boolean expected, got "+t)}var zl=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function oe(r){Qe(r);let t="";for(let e=0;e<r.length;e++)t+=zl[r[e]];return t}function Le(r){let t=r.toString(16);return t.length&1?"0"+t:t}function Oo(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?Jr:BigInt("0x"+r)}var ne={_0:48,_9:57,A:65,F:70,a:97,f:102};function la(r){if(r>=ne._0&&r<=ne._9)return r-ne._0;if(r>=ne.A&&r<=ne.F)return r-(ne.A-10);if(r>=ne.a&&r<=ne.f)return r-(ne.a-10)}function Re(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);let t=r.length,e=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(e);for(let o=0,i=0;o<e;o++,i+=2){let s=la(r.charCodeAt(i)),a=la(r.charCodeAt(i+1));if(s===void 0||a===void 0){let c=r[i]+r[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}n[o]=s*16+a}return n}function ie(r){return Oo(oe(r))}function me(r){return Qe(r),Oo(oe(Uint8Array.from(r).reverse()))}function ye(r,t){return Re(r.toString(16).padStart(t*2,"0"))}function Be(r,t){return ye(r,t).reverse()}function Vl(r){return Re(Le(r))}function ot(r,t,e){let n;if(typeof t=="string")try{n=Re(t)}catch(i){throw new Error(r+" must be hex string or Uint8Array, cause: "+i)}else if(pe(t))n=Uint8Array.from(t);else throw new Error(r+" must be hex string or Uint8Array");let o=n.length;if(typeof e=="number"&&o!==e)throw new Error(r+" of length "+e+" expected, got "+o);return n}function se(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];Qe(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let i=r[n];e.set(i,o),o+=i.length}return e}function Hl(r,t){if(r.length!==t.length)return!1;let e=0;for(let n=0;n<r.length;n++)e|=r[n]^t[n];return e===0}function Gl(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}var No=r=>typeof r=="bigint"&&Jr<=r;function wr(r,t,e){return No(r)&&No(t)&&No(e)&&t<=r&&r<e}function Tt(r,t,e,n){if(!wr(t,e,n))throw new Error("expected valid "+r+": "+e+" <= n < "+n+", got "+t)}function Mo(r){let t;for(t=0;r>Jr;r>>=tn,t+=1);return t}function Wl(r,t){return r>>BigInt(t)&tn}function Zl(r,t,e){return r|(e?tn:Jr)<<BigInt(t)}var Er=r=>(Fl<<BigInt(r-1))-tn,Uo=r=>new Uint8Array(r),fa=r=>Uint8Array.from(r);function ko(r,t,e){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof e!="function")throw new Error("hmacFn must be a function");let n=Uo(r),o=Uo(r),i=0,s=()=>{n.fill(1),o.fill(0),i=0},a=(...f)=>e(o,n,...f),c=(f=Uo())=>{o=a(fa([0]),f),n=a(),f.length!==0&&(o=a(fa([1]),f),n=a())},l=()=>{if(i++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,d=[];for(;f<t;){n=a();let g=n.slice();d.push(g),f+=n.length}return se(...d)};return(f,d)=>{s(),c(f);let g;for(;!(g=d(l()));)c();return s(),g}}var $l={bigint:r=>typeof r=="bigint",function:r=>typeof r=="function",boolean:r=>typeof r=="boolean",string:r=>typeof r=="string",stringOrUint8Array:r=>typeof r=="string"||pe(r),isSafeInteger:r=>Number.isSafeInteger(r),array:r=>Array.isArray(r),field:(r,t)=>t.Fp.isValid(r),hash:r=>typeof r=="function"&&Number.isSafeInteger(r.outputLen)};function Xt(r,t,e={}){let n=(o,i,s)=>{let a=$l[i];if(typeof a!="function")throw new Error("invalid validator function");let c=r[o];if(!(s&&c===void 0)&&!a(c,r))throw new Error("param "+String(o)+" is invalid. Expected "+i+", got "+c)};for(let[o,i]of Object.entries(t))n(o,i,!1);for(let[o,i]of Object.entries(e))n(o,i,!0);return r}var Yl=()=>{throw new Error("not implemented")};function Ce(r){let t=new WeakMap;return(e,...n)=>{let o=t.get(e);if(o!==void 0)return o;let i=r(e,...n);return t.set(e,i),i}}var lt=BigInt(0),rt=BigInt(1),De=BigInt(2),Xl=BigInt(3),Ko=BigInt(4),ha=BigInt(5),da=BigInt(8),Ql=BigInt(9),jl=BigInt(16);function Y(r,t){let e=r%t;return e>=lt?e:t+e}function Jl(r,t,e){if(t<lt)throw new Error("invalid exponent, negatives unsupported");if(e<=lt)throw new Error("invalid modulus");if(e===rt)return lt;let n=rt;for(;t>lt;)t&rt&&(n=n*r%e),r=r*r%e,t>>=rt;return n}function nt(r,t,e){let n=r;for(;t-- >lt;)n*=n,n%=e;return n}function rn(r,t){if(r===lt)throw new Error("invert: expected non-zero number");if(t<=lt)throw new Error("invert: expected positive modulus, got "+t);let e=Y(r,t),n=t,o=lt,i=rt,s=rt,a=lt;for(;e!==lt;){let l=n/e,u=n%e,f=o-s*l,d=i-a*l;n=e,e=u,o=s,i=a,s=f,a=d}if(n!==rt)throw new Error("invert: does not exist");return Y(o,t)}function tf(r){let t=(r-rt)/De,e,n,o;for(e=r-rt,n=0;e%De===lt;e/=De,n++);for(o=De;o<r&&Jl(o,t,r)!==r-rt;o++)if(o>1e3)throw new Error("Cannot find square root: likely non-prime P");if(n===1){let s=(r+rt)/Ko;return function(c,l){let u=c.pow(l,s);if(!c.eql(c.sqr(u),l))throw new Error("Cannot find square root");return u}}let i=(e+rt)/De;return function(a,c){if(a.pow(c,t)===a.neg(a.ONE))throw new Error("Cannot find square root");let l=n,u=a.pow(a.mul(a.ONE,o),e),f=a.pow(c,i),d=a.pow(c,e);for(;!a.eql(d,a.ONE);){if(a.eql(d,a.ZERO))return a.ZERO;let g=1;for(let b=a.sqr(d);g<l&&!a.eql(b,a.ONE);g++)b=a.sqr(b);let y=a.pow(u,rt<<BigInt(l-g-1));u=a.sqr(y),f=a.mul(f,y),d=a.mul(d,u),l=g}return f}}function ef(r){if(r%Ko===Xl){let t=(r+rt)/Ko;return function(n,o){let i=n.pow(o,t);if(!n.eql(n.sqr(i),o))throw new Error("Cannot find square root");return i}}if(r%da===ha){let t=(r-ha)/da;return function(n,o){let i=n.mul(o,De),s=n.pow(i,t),a=n.mul(o,s),c=n.mul(n.mul(a,De),s),l=n.mul(a,n.sub(c,n.ONE));if(!n.eql(n.sqr(l),o))throw new Error("Cannot find square root");return l}}return r%jl,tf(r)}var pa=(r,t)=>(Y(r,t)&rt)===rt,rf=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function qo(r){let t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},e=rf.reduce((n,o)=>(n[o]="function",n),t);return Xt(r,e)}function nf(r,t,e){if(e<lt)throw new Error("invalid exponent, negatives unsupported");if(e===lt)return r.ONE;if(e===rt)return t;let n=r.ONE,o=t;for(;e>lt;)e&rt&&(n=r.mul(n,o)),o=r.sqr(o),e>>=rt;return n}function of(r,t){let e=new Array(t.length),n=t.reduce((i,s,a)=>r.is0(s)?i:(e[a]=i,r.mul(i,s)),r.ONE),o=r.inv(n);return t.reduceRight((i,s,a)=>r.is0(s)?i:(e[a]=r.mul(i,e[a]),r.mul(i,s)),o),e}function Fo(r,t){let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}function ge(r,t,e=!1,n={}){if(r<=lt)throw new Error("invalid field: expected ORDER > 0, got "+r);let{nBitLength:o,nByteLength:i}=Fo(r,t);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let s,a=Object.freeze({ORDER:r,isLE:e,BITS:o,BYTES:i,MASK:Er(o),ZERO:lt,ONE:rt,create:c=>Y(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return lt<=c&&c<r},is0:c=>c===lt,isOdd:c=>(c&rt)===rt,neg:c=>Y(-c,r),eql:(c,l)=>c===l,sqr:c=>Y(c*c,r),add:(c,l)=>Y(c+l,r),sub:(c,l)=>Y(c-l,r),mul:(c,l)=>Y(c*l,r),pow:(c,l)=>nf(a,c,l),div:(c,l)=>Y(c*rn(l,r),r),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>rn(c,r),sqrt:n.sqrt||(c=>(s||(s=ef(r)),s(a,c))),invertBatch:c=>of(a,c),cmov:(c,l,u)=>u?l:c,toBytes:c=>e?Be(c,i):ye(c,i),fromBytes:c=>{if(c.length!==i)throw new Error("Field.fromBytes: expected "+i+" bytes, got "+c.length);return e?me(c):ie(c)}});return Object.freeze(a)}function ma(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let t=r.toString(2).length;return Math.ceil(t/8)}function zo(r){let t=ma(r);return t+Math.ceil(t/2)}function ya(r,t,e=!1){let n=r.length,o=ma(t),i=zo(t);if(n<16||n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);let s=e?me(r):ie(r),a=Y(s,t-rt)+rt;return e?Be(a,o):ye(a,o)}var ga=BigInt(0),nn=BigInt(1);function Vo(r,t){let e=t.negate();return r?e:t}function ba(r,t){if(!Number.isSafeInteger(r)||r<=0||r>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+r)}function Ho(r,t){ba(r,t);let e=Math.ceil(t/r)+1,n=2**(r-1);return{windows:e,windowSize:n}}function sf(r,t){if(!Array.isArray(r))throw new Error("array expected");r.forEach((e,n)=>{if(!(e instanceof t))throw new Error("invalid point at index "+n)})}function af(r,t){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((e,n)=>{if(!t.isValid(e))throw new Error("invalid scalar at index "+n)})}var Go=new WeakMap,xa=new WeakMap;function Wo(r){return xa.get(r)||1}function on(r,t){return{constTimeNegate:Vo,hasPrecomputes(e){return Wo(e)!==1},unsafeLadder(e,n,o=r.ZERO){let i=e;for(;n>ga;)n&nn&&(o=o.add(i)),i=i.double(),n>>=nn;return o},precomputeWindow(e,n){let{windows:o,windowSize:i}=Ho(n,t),s=[],a=e,c=a;for(let l=0;l<o;l++){c=a,s.push(c);for(let u=1;u<i;u++)c=c.add(a),s.push(c);a=c.double()}return s},wNAF(e,n,o){let{windows:i,windowSize:s}=Ho(e,t),a=r.ZERO,c=r.BASE,l=BigInt(2**e-1),u=2**e,f=BigInt(e);for(let d=0;d<i;d++){let g=d*s,y=Number(o&l);o>>=f,y>s&&(y-=u,o+=nn);let b=g,h=g+Math.abs(y)-1,w=d%2!==0,v=y<0;y===0?c=c.add(Vo(w,n[b])):a=a.add(Vo(v,n[h]))}return{p:a,f:c}},wNAFUnsafe(e,n,o,i=r.ZERO){let{windows:s,windowSize:a}=Ho(e,t),c=BigInt(2**e-1),l=2**e,u=BigInt(e);for(let f=0;f<s;f++){let d=f*a;if(o===ga)break;let g=Number(o&c);if(o>>=u,g>a&&(g-=l,o+=nn),g===0)continue;let y=n[d+Math.abs(g)-1];g<0&&(y=y.negate()),i=i.add(y)}return i},getPrecomputes(e,n,o){let i=Go.get(n);return i||(i=this.precomputeWindow(n,e),e!==1&&Go.set(n,o(i))),i},wNAFCached(e,n,o){let i=Wo(e);return this.wNAF(i,this.getPrecomputes(i,e,o),n)},wNAFCachedUnsafe(e,n,o,i){let s=Wo(e);return s===1?this.unsafeLadder(e,n,i):this.wNAFUnsafe(s,this.getPrecomputes(s,e,o),n,i)},setWindowSize(e,n){ba(n,t),xa.set(e,n),Go.delete(e)}}}function sn(r,t,e,n){if(sf(e,r),af(n,t),e.length!==n.length)throw new Error("arrays of points and scalars must have equal length");let o=r.ZERO,i=Mo(BigInt(e.length)),s=i>12?i-3:i>4?i-2:i?2:1,a=(1<<s)-1,c=new Array(a+1).fill(o),l=Math.floor((t.BITS-1)/s)*s,u=o;for(let f=l;f>=0;f-=s){c.fill(o);for(let g=0;g<n.length;g++){let y=n[g],b=Number(y>>BigInt(f)&BigInt(a));c[b]=c[b].add(e[g])}let d=o;for(let g=c.length-1,y=o;g>0;g--)y=y.add(c[g]),d=d.add(y);if(u=u.add(d),f!==0)for(let g=0;g<s;g++)u=u.double()}return u}function vr(r){return qo(r.Fp),Xt(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Fo(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var Ht=BigInt(0),Lt=BigInt(1),an=BigInt(2),cf=BigInt(8),uf={zip215:!0};function lf(r){let t=vr(r);return Xt(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function wa(r){let t=lf(r),{Fp:e,n,prehash:o,hash:i,randomBytes:s,nByteLength:a,h:c}=t,l=an<<BigInt(a*8)-Lt,u=e.create,f=ge(t.n,t.nBitLength),d=t.uvRatio||((x,p)=>{try{return{isValid:!0,value:e.sqrt(x*e.inv(p))}}catch{return{isValid:!1,value:Ht}}}),g=t.adjustScalarBytes||(x=>x),y=t.domain||((x,p,E)=>{if(Vt("phflag",E),p.length||E)throw new Error("Contexts/pre-hash are not supported");return x});function b(x,p){Tt("coordinate "+x,p,Ht,l)}function h(x){if(!(x instanceof m))throw new Error("ExtendedPoint expected")}let w=Ce((x,p)=>{let{ex:E,ey:A,ez:D}=x,P=x.is0();p==null&&(p=P?cf:e.inv(D));let O=u(E*p),F=u(A*p),N=u(D*p);if(P)return{x:Ht,y:Lt};if(N!==Lt)throw new Error("invZ was invalid");return{x:O,y:F}}),v=Ce(x=>{let{a:p,d:E}=t;if(x.is0())throw new Error("bad point: ZERO");let{ex:A,ey:D,ez:P,et:O}=x,F=u(A*A),N=u(D*D),Z=u(P*P),J=u(Z*Z),ht=u(F*p),dt=u(Z*u(ht+N)),yt=u(J+u(E*u(F*N)));if(dt!==yt)throw new Error("bad point: equation left != right (1)");let gt=u(A*D),It=u(P*O);if(gt!==It)throw new Error("bad point: equation left != right (2)");return!0});class m{constructor(p,E,A,D){this.ex=p,this.ey=E,this.ez=A,this.et=D,b("x",p),b("y",E),b("z",A),b("t",D),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(p){if(p instanceof m)throw new Error("extended point not allowed");let{x:E,y:A}=p||{};return b("x",E),b("y",A),new m(E,A,Lt,u(E*A))}static normalizeZ(p){let E=e.invertBatch(p.map(A=>A.ez));return p.map((A,D)=>A.toAffine(E[D])).map(m.fromAffine)}static msm(p,E){return sn(m,f,p,E)}_setWindowSize(p){C.setWindowSize(this,p)}assertValidity(){v(this)}equals(p){h(p);let{ex:E,ey:A,ez:D}=this,{ex:P,ey:O,ez:F}=p,N=u(E*F),Z=u(P*D),J=u(A*F),ht=u(O*D);return N===Z&&J===ht}is0(){return this.equals(m.ZERO)}negate(){return new m(u(-this.ex),this.ey,this.ez,u(-this.et))}double(){let{a:p}=t,{ex:E,ey:A,ez:D}=this,P=u(E*E),O=u(A*A),F=u(an*u(D*D)),N=u(p*P),Z=E+A,J=u(u(Z*Z)-P-O),ht=N+O,dt=ht-F,yt=N-O,gt=u(J*dt),It=u(ht*yt),At=u(J*yt),$t=u(dt*ht);return new m(gt,It,$t,At)}add(p){h(p);let{a:E,d:A}=t,{ex:D,ey:P,ez:O,et:F}=this,{ex:N,ey:Z,ez:J,et:ht}=p;if(E===BigInt(-1)){let Ts=u((P-D)*(Z+N)),Ls=u((P+D)*(Z-N)),go=u(Ls-Ts);if(go===Ht)return this.double();let Rs=u(O*an*ht),Bs=u(F*an*J),Cs=Bs+Rs,Ds=Ls+Ts,Ps=Bs-Rs,wu=u(Cs*go),Eu=u(Ds*Ps),vu=u(Cs*Ps),Su=u(go*Ds);return new m(wu,Eu,Su,vu)}let dt=u(D*N),yt=u(P*Z),gt=u(F*A*ht),It=u(O*J),At=u((D+P)*(N+Z)-dt-yt),$t=It-gt,jt=It+gt,dr=u(yt-E*dt),yu=u(At*$t),gu=u(jt*dr),bu=u(At*dr),xu=u($t*jt);return new m(yu,gu,xu,bu)}subtract(p){return this.add(p.negate())}wNAF(p){return C.wNAFCached(this,p,m.normalizeZ)}multiply(p){let E=p;Tt("scalar",E,Lt,n);let{p:A,f:D}=this.wNAF(E);return m.normalizeZ([A,D])[0]}multiplyUnsafe(p,E=m.ZERO){let A=p;return Tt("scalar",A,Ht,n),A===Ht?B:this.is0()||A===Lt?this:C.wNAFCachedUnsafe(this,A,m.normalizeZ,E)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return C.unsafeLadder(this,n).is0()}toAffine(p){return w(this,p)}clearCofactor(){let{h:p}=t;return p===Lt?this:this.multiplyUnsafe(p)}static fromHex(p,E=!1){let{d:A,a:D}=t,P=e.BYTES;p=ot("pointHex",p,P),Vt("zip215",E);let O=p.slice(),F=p[P-1];O[P-1]=F&-129;let N=me(O),Z=E?l:e.ORDER;Tt("pointHex.y",N,Ht,Z);let J=u(N*N),ht=u(J-Lt),dt=u(A*J-D),{isValid:yt,value:gt}=d(ht,dt);if(!yt)throw new Error("Point.fromHex: invalid y coordinate");let It=(gt&Lt)===Lt,At=(F&128)!==0;if(!E&&gt===Ht&&At)throw new Error("Point.fromHex: x=0 and x_0=1");return At!==It&&(gt=u(-gt)),m.fromAffine({x:gt,y:N})}static fromPrivateKey(p){return T(p).point}toRawBytes(){let{x:p,y:E}=this.toAffine(),A=Be(E,e.BYTES);return A[A.length-1]|=p&Lt?128:0,A}toHex(){return oe(this.toRawBytes())}}m.BASE=new m(t.Gx,t.Gy,Lt,u(t.Gx*t.Gy)),m.ZERO=new m(Ht,Lt,Lt,Ht);let{BASE:_,ZERO:B}=m,C=on(m,a*8);function I(x){return Y(x,n)}function R(x){return I(me(x))}function T(x){let p=e.BYTES;x=ot("private key",x,p);let E=ot("hashed private key",i(x),2*p),A=g(E.slice(0,p)),D=E.slice(p,2*p),P=R(A),O=_.multiply(P),F=O.toRawBytes();return{head:A,prefix:D,scalar:P,point:O,pointBytes:F}}function et(x){return T(x).pointBytes}function H(x=new Uint8Array,...p){let E=se(...p);return R(i(y(E,ot("context",x),!!o)))}function q(x,p,E={}){x=ot("message",x),o&&(x=o(x));let{prefix:A,scalar:D,pointBytes:P}=T(p),O=H(E.context,A,x),F=_.multiply(O).toRawBytes(),N=H(E.context,F,P,x),Z=I(O+N*D);Tt("signature.s",Z,Ht,n);let J=se(F,Be(Z,e.BYTES));return ot("result",J,e.BYTES*2)}let ut=uf;function S(x,p,E,A=ut){let{context:D,zip215:P}=A,O=e.BYTES;x=ot("signature",x,2*O),p=ot("message",p),E=ot("publicKey",E,O),P!==void 0&&Vt("zip215",P),o&&(p=o(p));let F=me(x.slice(O,2*O)),N,Z,J;try{N=m.fromHex(E,P),Z=m.fromHex(x.slice(0,O),P),J=_.multiplyUnsafe(F)}catch{return!1}if(!P&&N.isSmallOrder())return!1;let ht=H(D,Z.toRawBytes(),N.toRawBytes(),p);return Z.add(N.multiplyUnsafe(ht)).subtract(J).clearCofactor().equals(m.ZERO)}return _._setWindowSize(8),{CURVE:t,getPublicKey:et,sign:q,verify:S,ExtendedPoint:m,utils:{getExtendedPublicKey:T,randomPrivateKey:()=>s(e.BYTES),precompute(x=8,p=m.BASE){return p._setWindowSize(x),p.multiply(BigInt(3)),p}}}}var Zo=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Ea=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),Fp=BigInt(0),ff=BigInt(1),va=BigInt(2),zp=BigInt(3),hf=BigInt(5),df=BigInt(8);function pf(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),i=Zo,a=r*r%i*r%i,c=nt(a,va,i)*a%i,l=nt(c,ff,i)*r%i,u=nt(l,hf,i)*l%i,f=nt(u,t,i)*u%i,d=nt(f,e,i)*f%i,g=nt(d,n,i)*d%i,y=nt(g,o,i)*g%i,b=nt(y,o,i)*g%i,h=nt(b,t,i)*u%i;return{pow_p_5_8:nt(h,va,i)*r%i,b2:a}}function mf(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function yf(r,t){let e=Zo,n=Y(t*t*t,e),o=Y(n*n*t,e),i=pf(r*o).pow_p_5_8,s=Y(r*n*i,e),a=Y(t*s*s,e),c=s,l=Y(s*Ea,e),u=a===r,f=a===Y(-r,e),d=a===Y(-r*Ea,e);return u&&(s=c),(f||d)&&(s=l),pa(s,e)&&(s=Y(-s,e)),{isValid:u||f,value:s}}var gf=ge(Zo,void 0,!0),bf={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:gf,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:df,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:ua,randomBytes:Qr,adjustScalarBytes:mf,uvRatio:yf},Sa=wa(bf);var cn=32;function Aa(r,t,e){return Sa.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}var un=class{type="Ed25519";raw;constructor(t){this.raw=$o(t,cn)}toMultihash(){return re.digest(be(this))}toCID(){return at.createV1(114,this.toMultihash())}toString(){return Q.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:pt(this.raw,t.raw)}verify(t,e){return Aa(this.raw,e,t)}};function Yo(r){return r=$o(r,cn),new un(r)}function $o(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new bt(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}function it(r=0){return new Uint8Array(r)}function Rt(r=0){return new Uint8Array(r)}var wf=Math.pow(2,7),Ef=Math.pow(2,14),vf=Math.pow(2,21),Xo=Math.pow(2,28),Qo=Math.pow(2,35),jo=Math.pow(2,42),Jo=Math.pow(2,49),W=128,xt=127;function wt(r){if(r<wf)return 1;if(r<Ef)return 2;if(r<vf)return 3;if(r<Xo)return 4;if(r<Qo)return 5;if(r<jo)return 6;if(r<Jo)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function ti(r,t,e=0){switch(wt(r)){case 8:t[e++]=r&255|W,r/=128;case 7:t[e++]=r&255|W,r/=128;case 6:t[e++]=r&255|W,r/=128;case 5:t[e++]=r&255|W,r/=128;case 4:t[e++]=r&255|W,r>>>=7;case 3:t[e++]=r&255|W,r>>>=7;case 2:t[e++]=r&255|W,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function Sf(r,t,e=0){switch(wt(r)){case 8:t.set(e++,r&255|W),r/=128;case 7:t.set(e++,r&255|W),r/=128;case 6:t.set(e++,r&255|W),r/=128;case 5:t.set(e++,r&255|W),r/=128;case 4:t.set(e++,r&255|W),r>>>=7;case 3:t.set(e++,r&255|W),r>>>=7;case 2:t.set(e++,r&255|W),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function ei(r,t){let e=r[t],n=0;if(n+=e&xt,e<W||(e=r[t+1],n+=(e&xt)<<7,e<W)||(e=r[t+2],n+=(e&xt)<<14,e<W)||(e=r[t+3],n+=(e&xt)<<21,e<W)||(e=r[t+4],n+=(e&xt)*Xo,e<W)||(e=r[t+5],n+=(e&xt)*Qo,e<W)||(e=r[t+6],n+=(e&xt)*jo,e<W)||(e=r[t+7],n+=(e&xt)*Jo,e<W))return n;throw new RangeError("Could not decode varint")}function Af(r,t){let e=r.get(t),n=0;if(n+=e&xt,e<W||(e=r.get(t+1),n+=(e&xt)<<7,e<W)||(e=r.get(t+2),n+=(e&xt)<<14,e<W)||(e=r.get(t+3),n+=(e&xt)<<21,e<W)||(e=r.get(t+4),n+=(e&xt)*Xo,e<W)||(e=r.get(t+5),n+=(e&xt)*Qo,e<W)||(e=r.get(t+6),n+=(e&xt)*jo,e<W)||(e=r.get(t+7),n+=(e&xt)*Jo,e<W))return n;throw new RangeError("Could not decode varint")}function kt(r,t,e=0){return t==null&&(t=Rt(wt(r))),t instanceof Uint8Array?ti(r,t,e):Sf(r,t,e)}function ae(r,t=0){return r instanceof Uint8Array?ei(r,t):Af(r,t)}var ri=new Float32Array([-0]),xe=new Uint8Array(ri.buffer);function Ia(r,t,e){ri[0]=r,t[e]=xe[0],t[e+1]=xe[1],t[e+2]=xe[2],t[e+3]=xe[3]}function Ta(r,t){return xe[0]=r[t],xe[1]=r[t+1],xe[2]=r[t+2],xe[3]=r[t+3],ri[0]}var ni=new Float64Array([-0]),Et=new Uint8Array(ni.buffer);function La(r,t,e){ni[0]=r,t[e]=Et[0],t[e+1]=Et[1],t[e+2]=Et[2],t[e+3]=Et[3],t[e+4]=Et[4],t[e+5]=Et[5],t[e+6]=Et[6],t[e+7]=Et[7]}function Ra(r,t){return Et[0]=r[t],Et[1]=r[t+1],Et[2]=r[t+2],Et[3]=r[t+3],Et[4]=r[t+4],Et[5]=r[t+5],Et[6]=r[t+6],Et[7]=r[t+7],ni[0]}var _f=BigInt(Number.MAX_SAFE_INTEGER),If=BigInt(Number.MIN_SAFE_INTEGER),Pt=class r{lo;hi;constructor(t,e){this.lo=t|0,this.hi=e|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(e+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(BigInt(e)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?e===0?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return Pe;if(t<_f&&t>If)return this.fromNumber(Number(t));let e=t<0n;e&&(t=-t);let n=t>>32n,o=t-(n<<32n);return e&&(n=~n|0n,o=~o|0n,++o>Ba&&(o=0n,++n>Ba&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return Pe;let e=t<0;e&&(t=-t);let n=t>>>0,o=(t-n)/4294967296>>>0;return e&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(t){return typeof t=="number"?r.fromNumber(t):typeof t=="bigint"?r.fromBigInt(t):typeof t=="string"?r.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new r(t.low>>>0,t.high>>>0):Pe}},Pe=new Pt(0,0);Pe.toBigInt=function(){return 0n};Pe.zzEncode=Pe.zzDecode=function(){return this};Pe.length=function(){return 1};var Ba=4294967296n;function Ca(r){let t=0,e=0;for(let n=0;n<r.length;++n)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:(e&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function Da(r,t,e){if(e-t<1)return"";let o,i=[],s=0,a;for(;t<e;)a=r[t++],a<128?i[s++]=a:a>191&&a<224?i[s++]=(a&31)<<6|r[t++]&63:a>239&&a<365?(a=((a&7)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,i[s++]=55296+(a>>10),i[s++]=56320+(a&1023)):i[s++]=(a&15)<<12|(r[t++]&63)<<6|r[t++]&63,s>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,i)),s=0);return o!=null?(s>0&&o.push(String.fromCharCode.apply(String,i.slice(0,s))),o.join("")):String.fromCharCode.apply(String,i.slice(0,s))}function oi(r,t,e){let n=e,o,i;for(let s=0;s<r.length;++s)o=r.charCodeAt(s),o<128?t[e++]=o:o<2048?(t[e++]=o>>6|192,t[e++]=o&63|128):(o&64512)===55296&&((i=r.charCodeAt(s+1))&64512)===56320?(o=65536+((o&1023)<<10)+(i&1023),++s,t[e++]=o>>18|240,t[e++]=o>>12&63|128,t[e++]=o>>6&63|128,t[e++]=o&63|128):(t[e++]=o>>12|224,t[e++]=o>>6&63|128,t[e++]=o&63|128);return e-n}function Gt(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function fn(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var ii=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,Gt(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Gt(this,4);return fn(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Gt(this,4);return fn(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Gt(this,4);let t=Ta(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw Gt(this,4);let t=Ra(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw Gt(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return Da(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw Gt(this,t);this.pos+=t}else do if(this.pos>=this.len)throw Gt(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new Pt(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw Gt(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw Gt(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Gt(this,8);let t=fn(this.buf,this.pos+=4),e=fn(this.buf,this.pos+=4);return new Pt(t,e)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=ei(this.buf,this.pos);return this.pos+=wt(t),t}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 si(r){return new ii(r instanceof Uint8Array?r:r.subarray())}function Bt(r,t,e){let n=si(r);return t.decode(n,void 0,e)}var ai={};_t(ai,{base10:()=>Tf});var Tf=fe({prefix:"9",name:"base10",alphabet:"0123456789"});var ci={};_t(ci,{base16:()=>Lf,base16upper:()=>Rf});var Lf=st({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Rf=st({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var ui={};_t(ui,{base2:()=>Bf});var Bf=st({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var li={};_t(li,{base256emoji:()=>Uf});var Na=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}"),Cf=Na.reduce((r,t,e)=>(r[e]=t,r),[]),Df=Na.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function Pf(r){return r.reduce((t,e)=>(t+=Cf[e],t),"")}function Nf(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=Df[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var Uf=Ve({prefix:"\u{1F680}",name:"base256emoji",encode:Pf,decode:Nf});var hi={};_t(hi,{base64:()=>Of,base64pad:()=>Mf,base64url:()=>fi,base64urlpad:()=>kf});var Of=st({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Mf=st({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),fi=st({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),kf=st({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var di={};_t(di,{base8:()=>Kf});var Kf=st({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var pi={};_t(pi,{identity:()=>qf});var qf=Ve({prefix:"\0",name:"identity",encode:r=>Vs(r),decode:r=>zs(r)});var Am=new TextEncoder,_m=new TextDecoder;var gi={};_t(gi,{sha256:()=>je,sha512:()=>Vf});function yi({name:r,code:t,encode:e}){return new mi(r,t,e)}var mi=class{name;code;encode;constructor(t,e,n){this.name=t,this.code=e,this.encode=n}digest(t){if(t instanceof Uint8Array){let e=this.encode(t);return e instanceof Uint8Array?Ft(this.code,e):e.then(n=>Ft(this.code,n))}else throw Error("Unknown type, must be binary type")}};function Oa(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var je=yi({name:"sha2-256",code:18,encode:Oa("SHA-256")}),Vf=yi({name:"sha2-512",code:19,encode:Oa("SHA-512")});var Sr={...pi,...ui,...di,...ai,...ci,...Io,...To,..._o,...hi,...li},Mm={...gi,...Bo};function ka(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var Ma=ka("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),bi=ka("ascii","a",r=>{let t="a";for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return t},r=>{r=r.substring(1);let t=Rt(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),Hf={utf8:Ma,"utf-8":Ma,hex:Sr.base16,latin1:bi,ascii:bi,binary:bi,...Sr},hn=Hf;function z(r,t="utf8"){let e=hn[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function xi(r){let t=r??8192,e=t>>>1,n,o=t;return function(s){if(s<1||s>e)return Rt(s);o+s>t&&(n=Rt(t),o=0);let a=n.subarray(o,o+=s);return(o&7)!==0&&(o=(o|7)+1),a}}var Ne=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function wi(){}var vi=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},Gf=xi();function Wf(r){return globalThis.Buffer!=null?Rt(r):Gf(r)}var _r=class{len;head;tail;states;constructor(){this.len=0,this.head=new Ne(wi,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new Ne(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new Si((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(dn,10,Pt.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=Pt.fromBigInt(t);return this._push(dn,e.length(),e)}uint64Number(t){return this._push(ti,wt(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let e=Pt.fromBigInt(t).zzEncode();return this._push(dn,e.length(),e)}sint64Number(t){let e=Pt.fromNumber(t).zzEncode();return this._push(dn,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(Ei,1,t?1:0)}fixed32(t){return this._push(Ar,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=Pt.fromBigInt(t);return this._push(Ar,4,e.lo)._push(Ar,4,e.hi)}fixed64Number(t){let e=Pt.fromNumber(t);return this._push(Ar,4,e.lo)._push(Ar,4,e.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(Ia,4,t)}double(t){return this._push(La,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(Ei,1,0):this.uint32(e)._push($f,e,t)}string(t){let e=Ca(t);return e!==0?this.uint32(e)._push(oi,e,t):this._push(Ei,1,0)}fork(){return this.states=new vi(this),this.head=this.tail=new Ne(wi,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 Ne(wi,0,0),this.len=0),this}ldelim(){let t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=e,this.len+=n),this}finish(){let t=this.head.next,e=Wf(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function Ei(r,t,e){t[e]=r&255}function Zf(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var Si=class extends Ne{next;constructor(t,e){super(Zf,t,e),this.next=void 0}};function dn(r,t,e){for(;r.hi!==0;)t[e++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)t[e++]=r.lo&127|128,r.lo=r.lo>>>7;t[e++]=r.lo}function Ar(r,t,e){t[e]=r&255,t[e+1]=r>>>8&255,t[e+2]=r>>>16&255,t[e+3]=r>>>24}function $f(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(_r.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(Yf,t,r),this},_r.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(Xf,t,r),this});function Yf(r,t,e){t.set(r,e)}function Xf(r,t,e){r.length<40?oi(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(z(r),e)}function Ai(){return new _r}function Ct(r,t){let e=Ai();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var Je;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(Je||(Je={}));function pn(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function Ue(r){function t(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let e=function(i,s){let a=t(i);s.int32(a)},n=function(i){let s=i.int32();return t(s)};return pn("enum",Je.VARINT,e,n)}function Dt(r,t){return pn("message",Je.LENGTH_DELIMITED,r,t)}var Ir=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var ft;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1"})(ft||(ft={}));var _i;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1"})(_i||(_i={}));(function(r){r.codec=()=>Ue(_i)})(ft||(ft={}));var Qt;(function(r){let t;r.codec=()=>(t==null&&(t=Dt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),ft.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let i={},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let a=e.uint32();switch(a>>>3){case 1:{i.Type=ft.codec().decode(e);break}case 2:{i.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Ct(e,r.codec()),r.decode=(e,n)=>Bt(e,r.codec(),n)})(Qt||(Qt={}));var Ii;(function(r){let t;r.codec=()=>(t==null&&(t=Dt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),ft.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let i={},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let a=e.uint32();switch(a>>>3){case 1:{i.Type=ft.codec().decode(e);break}case 2:{i.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Ct(e,r.codec()),r.decode=(e,n)=>Bt(e,r.codec(),n)})(Ii||(Ii={}));var Rr={};_t(Rr,{MAX_RSA_KEY_SIZE:()=>Ci,generateRSAKeyPair:()=>Ja,jwkToJWKKeyPair:()=>tc,jwkToPkcs1:()=>ch,jwkToPkix:()=>Pi,jwkToRSAPrivateKey:()=>ja,pkcs1ToJwk:()=>Ya,pkcs1ToRSAPrivateKey:()=>Qa,pkixToJwk:()=>Xa,pkixToRSAPublicKey:()=>Ni});var Qf=new Uint32Array([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]),we=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ee=new Uint32Array(64),Ti=class extends Xe{constructor(){super(64,32,8,!1),this.A=we[0]|0,this.B=we[1]|0,this.C=we[2]|0,this.D=we[3]|0,this.E=we[4]|0,this.F=we[5]|0,this.G=we[6]|0,this.H=we[7]|0}get(){let{A:t,B:e,C:n,D:o,E:i,F:s,G:a,H:c}=this;return[t,e,n,o,i,s,a,c]}set(t,e,n,o,i,s,a,c){this.A=t|0,this.B=e|0,this.C=n|0,this.D=o|0,this.E=i|0,this.F=s|0,this.G=a|0,this.H=c|0}process(t,e){for(let f=0;f<16;f++,e+=4)Ee[f]=t.getUint32(e,!1);for(let f=16;f<64;f++){let d=Ee[f-15],g=Ee[f-2],y=zt(d,7)^zt(d,18)^d>>>3,b=zt(g,17)^zt(g,19)^g>>>10;Ee[f]=b+Ee[f-7]+y+Ee[f-16]|0}let{A:n,B:o,C:i,D:s,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){let d=zt(a,6)^zt(a,11)^zt(a,25),g=u+d+sa(a,c,l)+Qf[f]+Ee[f]|0,b=(zt(n,2)^zt(n,13)^zt(n,22))+aa(n,o,i)|0;u=l,l=c,c=a,a=s+g|0,s=i,i=o,o=n,n=g+b|0}n=n+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,o,i,s,a,c,l,u)}roundClean(){Ee.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var tr=Xr(()=>new Ti);function V(r,t="utf8"){let e=hn[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}function Nt(r,t){t==null&&(t=r.reduce((o,i)=>o+i.length,0));let e=Rt(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}var Fa=Symbol.for("@achingbrain/uint8arraylist");function qa(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let o=e+n.byteLength;if(t<o)return{buf:n,index:t-e};e=o}throw new RangeError("index is out of bounds")}function mn(r){return!!r?.[Fa]}var ct=class r{bufs;length;[Fa]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let n of t)if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.push(n);else if(mn(n))e+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let n of t.reverse())if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.unshift(n);else if(mn(n))e+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=qa(this.bufs,t);return e.buf[e.index]}set(t,e){let n=qa(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else if(mn(t))for(let n=0;n<t.length;n++)this.set(e+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:n,length:o}=this._subList(t,e);return Nt(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:Nt(n,o)}sublist(t,e){let{bufs:n,length:o}=this._subList(t,e),i=new r;return i.length=o,i.bufs=[...n],i}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let i=0;i<this.bufs.length;i++){let s=this.bufs[i],a=o,c=a+s.byteLength;if(o=c,t>=c)continue;let l=t>=a&&t<c,u=e>a&&e<=c;if(l&&u){if(t===a&&e===c){n.push(s);break}let f=t-a;n.push(s.subarray(f,f+(e-t)));break}if(l){if(t===0){n.push(s);continue}n.push(s.subarray(t-a));continue}if(u){if(e===c){n.push(s);break}n.push(s.subarray(0,e-a));break}n.push(s)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!mn(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let i=256,s=new Int32Array(i);for(let f=0;f<i;f++)s[f]=-1;for(let f=0;f<o;f++)s[n[f]]=f;let a=s,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let f=e;f<=c;f+=u){u=0;for(let d=l;d>=0;d--){let g=this.get(f+d);if(n[d]!==g){u=Math.max(1,d-a[g]);break}}if(u===0)return f}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=Rt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let o=it(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,e,n),this.write(o,t)}getInt32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){let o=it(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,e,n),this.write(o,t)}getBigInt64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){let o=it(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,e,n),this.write(o,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let n=Rt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let o=it(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,e,n),this.write(o,t)}getUint32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){let o=it(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,e,n),this.write(o,t)}getBigUint64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){let o=it(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,e,n),this.write(o,t)}getFloat32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){let o=it(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,e,n),this.write(o,t)}getFloat64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){let o=it(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,e,n),this.write(o,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!pt(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((o,i)=>o+i.byteLength,0)),n.length=e,n}};var jf=parseInt("11111",2),Ri=parseInt("10000000",2),Jf=parseInt("01111111",2),za={2:th,3:nh,5:rh,6:eh,16:Li,22:Li,48:Li};function Tr(r,t={offset:0}){let e=r[t.offset]&jf;if(t.offset++,za[e]!=null)return za[e](r,t);throw new Error("No decoder for tag "+e)}function yn(r,t){let e=0;if((r[t.offset]&Ri)===Ri){let n=r[t.offset]&Jf,o="0x";t.offset++;for(let i=0;i<n;i++,t.offset++)o+=r[t.offset].toString(16).padStart(2,"0");e=parseInt(o,16)}else e=r[t.offset],t.offset++;return e}function Li(r,t){yn(r,t);let e=[];for(;!(t.offset>=r.byteLength);){let n=Tr(r,t);if(n===null)break;e.push(n)}return e}function th(r,t){let e=yn(r,t),n=t.offset,o=t.offset+e,i=[];for(let s=n;s<o;s++)s===n&&r[s]===0||i.push(r[s]);return t.offset+=e,Uint8Array.from(i)}function eh(r,t){let e=yn(r,t);return t.offset+=e,["oid-unimplemented"]}function rh(r,t){return t.offset++,null}function nh(r,t){let e=yn(r,t),n=r[t.offset];t.offset++;let o=r.subarray(t.offset,t.offset+e);if(t.offset+=e,n!==0)throw new Error("Unused bits in bit string is unimplemented");return Tr(o,{offset:0})}function oh(r){let t=r.toString(16);t.length%2===1&&(t="0"+t);let e=new ct;for(let n=0;n<t.length;n+=2)e.append(Uint8Array.from([parseInt(`${t[n]}${t[n+1]}`,16)]));return e}function Bi(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let t=oh(r.byteLength);return new ct(Uint8Array.from([t.byteLength|Ri]),t)}function Kt(r){let t=new ct,e=parseInt("10000000",2);return(r.subarray()[0]&e)===e&&t.append(Uint8Array.from([0])),t.append(r),new ct(Uint8Array.from([2]),Bi(t),t)}function Va(r){let t=Uint8Array.from([0]),e=new ct(t,r);return new ct(Uint8Array.from([3]),Bi(e),e)}function gn(r){let t=new ct;for(let e of r)t.append(e);return new ct(Uint8Array.from([48]),Bi(t),t)}var Lr=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},bn=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var Ha={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new bn("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 t}};var ve=Ha;async function Ga(r){let t=await ve.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),e=await ih(t);return{privateKey:e[0],publicKey:e[1]}}async function Wa(r,t){let e=await ve.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await ve.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},e,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}async function Za(r,t,e){let n=await ve.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return ve.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,e instanceof Uint8Array?e:e.subarray())}async function ih(r){if(r.privateKey==null||r.publicKey==null)throw new bt("Private and public key are required");return Promise.all([ve.get().subtle.exportKey("jwk",r.privateKey),ve.get().subtle.exportKey("jwk",r.publicKey)])}function $a(r){if(r.kty!=="RSA")throw new bt("invalid key type");if(r.n==null)throw new bt("invalid key modulus");return z(r.n,"base64url").length*8}var er=class{type="RSA";_key;_raw;_multihash;constructor(t,e){this._key=t,this._multihash=e}get raw(){return this._raw==null&&(this._raw=Rr.jwkToPkix(this._key)),this._raw}toMultihash(){return this._multihash}toCID(){return at.createV1(114,this._multihash)}toString(){return Q.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:pt(this.raw,t.raw)}verify(t,e){return Za(this._key,e,t)}},Br=class{type="RSA";_key;_raw;publicKey;constructor(t,e){this._key=t,this.publicKey=e}get raw(){return this._raw==null&&(this._raw=Rr.jwkToPkcs1(this._key)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:pt(this.raw,t.raw)}sign(t){return Wa(this._key,t)}};var Ci=8192,Di=18,sh=1062,ah=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function Ya(r){let t=Tr(r);return{n:V(t[1],"base64url"),e:V(t[2],"base64url"),d:V(t[3],"base64url"),p:V(t[4],"base64url"),q:V(t[5],"base64url"),dp:V(t[6],"base64url"),dq:V(t[7],"base64url"),qi:V(t[8],"base64url"),kty:"RSA"}}function ch(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 bt("JWK was missing components");return gn([Kt(Uint8Array.from([0])),Kt(z(r.n,"base64url")),Kt(z(r.e,"base64url")),Kt(z(r.d,"base64url")),Kt(z(r.p,"base64url")),Kt(z(r.q,"base64url")),Kt(z(r.dp,"base64url")),Kt(z(r.dq,"base64url")),Kt(z(r.qi,"base64url"))]).subarray()}function Xa(r){let t=Tr(r,{offset:0});return{kty:"RSA",n:V(t[1][0],"base64url"),e:V(t[1][1],"base64url")}}function Pi(r){if(r.n==null||r.e==null)throw new bt("JWK was missing components");return gn([ah,Va(gn([Kt(z(r.n,"base64url")),Kt(z(r.e,"base64url"))]))]).subarray()}function Qa(r){let t=Ya(r);return ja(t)}function Ni(r,t){if(r.byteLength>=sh)throw new Fe("Key size is too large");let e=Xa(r);if(t==null){let n=tr(Qt.encode({Type:ft.RSA,Data:r}));t=Ft(Di,n)}return new er(e,t)}function ja(r){if($a(r)>Ci)throw new bt("Key size is too large");let t=tc(r),e=tr(Qt.encode({Type:ft.RSA,Data:Pi(t.publicKey)})),n=Ft(Di,e);return new Br(t.privateKey,new er(t.publicKey,n))}async function Ja(r){if(r>Ci)throw new bt("Key size is too large");let t=await Ga(r),e=tr(Qt.encode({Type:ft.RSA,Data:Pi(t.publicKey)})),n=Ft(Di,e);return new Br(t.privateKey,new er(t.publicKey,n))}function tc(r){if(r==null)throw new bt("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}var xn=class extends Ye{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,na(t);let n=xr(e);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,i=new Uint8Array(o);i.set(n.length>o?t.create().update(n).digest():n);for(let s=0;s<i.length;s++)i[s]^=54;this.iHash.update(i),this.oHash=t.create();for(let s=0;s<i.length;s++)i[s]^=106;this.oHash.update(i),i.fill(0)}update(t){return $e(this),this.iHash.update(t),this}digestInto(t){$e(this),Ze(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));let{oHash:e,iHash:n,finished:o,destroyed:i,blockLen:s,outputLen:a}=this;return t=t,t.finished=o,t.destroyed=i,t.blockLen=s,t.outputLen=a,t.oHash=e._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Ui=(r,t,e)=>new xn(r,t).update(e).digest();Ui.create=(r,t)=>new xn(r,t);function ec(r){r.lowS!==void 0&&Vt("lowS",r.lowS),r.prehash!==void 0&&Vt("prehash",r.prehash)}function uh(r){let t=vr(r);Xt(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:e,Fp:n,a:o}=t;if(e){if(!n.eql(o,n.ZERO))throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0");if(typeof e!="object"||typeof e.beta!="bigint"||typeof e.splitScalar!="function")throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...t})}var{bytesToNumberBE:lh,hexToBytes:fh}=en,Oi=class extends Error{constructor(t=""){super(t)}},ce={Err:Oi,_tlv:{encode:(r,t)=>{let{Err:e}=ce;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length&1)throw new e("tlv.encode: unpadded data");let n=t.length/2,o=Le(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let i=n>127?Le(o.length/2|128):"";return Le(r)+i+o+t},decode(r,t){let{Err:e}=ce,n=0;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length<2||t[n++]!==r)throw new e("tlv.decode: wrong tlv");let o=t[n++],i=!!(o&128),s=0;if(!i)s=o;else{let c=o&127;if(!c)throw new e("tlv.decode(long): indefinite length not supported");if(c>4)throw new e("tlv.decode(long): byte length is too big");let l=t.subarray(n,n+c);if(l.length!==c)throw new e("tlv.decode: length bytes not complete");if(l[0]===0)throw new e("tlv.decode(long): zero leftmost byte");for(let u of l)s=s<<8|u;if(n+=c,s<128)throw new e("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+s);if(a.length!==s)throw new e("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+s)}}},_int:{encode(r){let{Err:t}=ce;if(r<ue)throw new t("integer: negative integers are not allowed");let e=Le(r);if(Number.parseInt(e[0],16)&8&&(e="00"+e),e.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return e},decode(r){let{Err:t}=ce;if(r[0]&128)throw new t("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return lh(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=ce,o=typeof r=="string"?fh(r):r;Qe(o);let{v:i,l:s}=n.decode(48,o);if(s.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,i),{v:l,l:u}=n.decode(2,c);if(u.length)throw new t("invalid signature: left bytes after parsing");return{r:e.decode(a),s:e.decode(l)}},hexFromSig(r){let{_tlv:t,_int:e}=ce,n=t.encode(2,e.encode(r.r)),o=t.encode(2,e.encode(r.s)),i=n+o;return t.encode(48,i)}},ue=BigInt(0),mt=BigInt(1),iy=BigInt(2),rc=BigInt(3),sy=BigInt(4);function hh(r){let t=uh(r),{Fp:e}=t,n=ge(t.n,t.nBitLength),o=t.toBytes||((b,h,w)=>{let v=h.toAffine();return se(Uint8Array.from([4]),e.toBytes(v.x),e.toBytes(v.y))}),i=t.fromBytes||(b=>{let h=b.subarray(1),w=e.fromBytes(h.subarray(0,e.BYTES)),v=e.fromBytes(h.subarray(e.BYTES,2*e.BYTES));return{x:w,y:v}});function s(b){let{a:h,b:w}=t,v=e.sqr(b),m=e.mul(v,b);return e.add(e.add(m,e.mul(b,h)),w)}if(!e.eql(e.sqr(t.Gy),s(t.Gx)))throw new Error("bad generator point: equation left != right");function a(b){return wr(b,mt,t.n)}function c(b){let{allowedPrivateKeyLengths:h,nByteLength:w,wrapPrivateKey:v,n:m}=t;if(h&&typeof b!="bigint"){if(pe(b)&&(b=oe(b)),typeof b!="string"||!h.includes(b.length))throw new Error("invalid private key");b=b.padStart(w*2,"0")}let _;try{_=typeof b=="bigint"?b:ie(ot("private key",b,w))}catch{throw new Error("invalid private key, expected hex or "+w+" bytes, got "+typeof b)}return v&&(_=Y(_,m)),Tt("private key",_,mt,m),_}function l(b){if(!(b instanceof d))throw new Error("ProjectivePoint expected")}let u=Ce((b,h)=>{let{px:w,py:v,pz:m}=b;if(e.eql(m,e.ONE))return{x:w,y:v};let _=b.is0();h==null&&(h=_?e.ONE:e.inv(m));let B=e.mul(w,h),C=e.mul(v,h),I=e.mul(m,h);if(_)return{x:e.ZERO,y:e.ZERO};if(!e.eql(I,e.ONE))throw new Error("invZ was invalid");return{x:B,y:C}}),f=Ce(b=>{if(b.is0()){if(t.allowInfinityPoint&&!e.is0(b.py))return;throw new Error("bad point: ZERO")}let{x:h,y:w}=b.toAffine();if(!e.isValid(h)||!e.isValid(w))throw new Error("bad point: x or y not FE");let v=e.sqr(w),m=s(h);if(!e.eql(v,m))throw new Error("bad point: equation left != right");if(!b.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class d{constructor(h,w,v){if(this.px=h,this.py=w,this.pz=v,h==null||!e.isValid(h))throw new Error("x required");if(w==null||!e.isValid(w))throw new Error("y required");if(v==null||!e.isValid(v))throw new Error("z required");Object.freeze(this)}static fromAffine(h){let{x:w,y:v}=h||{};if(!h||!e.isValid(w)||!e.isValid(v))throw new Error("invalid affine point");if(h instanceof d)throw new Error("projective point not allowed");let m=_=>e.eql(_,e.ZERO);return m(w)&&m(v)?d.ZERO:new d(w,v,e.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(h){let w=e.invertBatch(h.map(v=>v.pz));return h.map((v,m)=>v.toAffine(w[m])).map(d.fromAffine)}static fromHex(h){let w=d.fromAffine(i(ot("pointHex",h)));return w.assertValidity(),w}static fromPrivateKey(h){return d.BASE.multiply(c(h))}static msm(h,w){return sn(d,n,h,w)}_setWindowSize(h){y.setWindowSize(this,h)}assertValidity(){f(this)}hasEvenY(){let{y:h}=this.toAffine();if(e.isOdd)return!e.isOdd(h);throw new Error("Field doesn't support isOdd")}equals(h){l(h);let{px:w,py:v,pz:m}=this,{px:_,py:B,pz:C}=h,I=e.eql(e.mul(w,C),e.mul(_,m)),R=e.eql(e.mul(v,C),e.mul(B,m));return I&&R}negate(){return new d(this.px,e.neg(this.py),this.pz)}double(){let{a:h,b:w}=t,v=e.mul(w,rc),{px:m,py:_,pz:B}=this,C=e.ZERO,I=e.ZERO,R=e.ZERO,T=e.mul(m,m),et=e.mul(_,_),H=e.mul(B,B),q=e.mul(m,_);return q=e.add(q,q),R=e.mul(m,B),R=e.add(R,R),C=e.mul(h,R),I=e.mul(v,H),I=e.add(C,I),C=e.sub(et,I),I=e.add(et,I),I=e.mul(C,I),C=e.mul(q,C),R=e.mul(v,R),H=e.mul(h,H),q=e.sub(T,H),q=e.mul(h,q),q=e.add(q,R),R=e.add(T,T),T=e.add(R,T),T=e.add(T,H),T=e.mul(T,q),I=e.add(I,T),H=e.mul(_,B),H=e.add(H,H),T=e.mul(H,q),C=e.sub(C,T),R=e.mul(H,et),R=e.add(R,R),R=e.add(R,R),new d(C,I,R)}add(h){l(h);let{px:w,py:v,pz:m}=this,{px:_,py:B,pz:C}=h,I=e.ZERO,R=e.ZERO,T=e.ZERO,et=t.a,H=e.mul(t.b,rc),q=e.mul(w,_),ut=e.mul(v,B),S=e.mul(m,C),L=e.add(w,v),x=e.add(_,B);L=e.mul(L,x),x=e.add(q,ut),L=e.sub(L,x),x=e.add(w,m);let p=e.add(_,C);return x=e.mul(x,p),p=e.add(q,S),x=e.sub(x,p),p=e.add(v,m),I=e.add(B,C),p=e.mul(p,I),I=e.add(ut,S),p=e.sub(p,I),T=e.mul(et,x),I=e.mul(H,S),T=e.add(I,T),I=e.sub(ut,T),T=e.add(ut,T),R=e.mul(I,T),ut=e.add(q,q),ut=e.add(ut,q),S=e.mul(et,S),x=e.mul(H,x),ut=e.add(ut,S),S=e.sub(q,S),S=e.mul(et,S),x=e.add(x,S),q=e.mul(ut,x),R=e.add(R,q),q=e.mul(p,x),I=e.mul(L,I),I=e.sub(I,q),q=e.mul(L,ut),T=e.mul(p,T),T=e.add(T,q),new d(I,R,T)}subtract(h){return this.add(h.negate())}is0(){return this.equals(d.ZERO)}wNAF(h){return y.wNAFCached(this,h,d.normalizeZ)}multiplyUnsafe(h){let{endo:w,n:v}=t;Tt("scalar",h,ue,v);let m=d.ZERO;if(h===ue)return m;if(this.is0()||h===mt)return this;if(!w||y.hasPrecomputes(this))return y.wNAFCachedUnsafe(this,h,d.normalizeZ);let{k1neg:_,k1:B,k2neg:C,k2:I}=w.splitScalar(h),R=m,T=m,et=this;for(;B>ue||I>ue;)B&mt&&(R=R.add(et)),I&mt&&(T=T.add(et)),et=et.double(),B>>=mt,I>>=mt;return _&&(R=R.negate()),C&&(T=T.negate()),T=new d(e.mul(T.px,w.beta),T.py,T.pz),R.add(T)}multiply(h){let{endo:w,n:v}=t;Tt("scalar",h,mt,v);let m,_;if(w){let{k1neg:B,k1:C,k2neg:I,k2:R}=w.splitScalar(h),{p:T,f:et}=this.wNAF(C),{p:H,f:q}=this.wNAF(R);T=y.constTimeNegate(B,T),H=y.constTimeNegate(I,H),H=new d(e.mul(H.px,w.beta),H.py,H.pz),m=T.add(H),_=et.add(q)}else{let{p:B,f:C}=this.wNAF(h);m=B,_=C}return d.normalizeZ([m,_])[0]}multiplyAndAddUnsafe(h,w,v){let m=d.BASE,_=(C,I)=>I===ue||I===mt||!C.equals(m)?C.multiplyUnsafe(I):C.multiply(I),B=_(this,w).add(_(h,v));return B.is0()?void 0:B}toAffine(h){return u(this,h)}isTorsionFree(){let{h,isTorsionFree:w}=t;if(h===mt)return!0;if(w)return w(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h,clearCofactor:w}=t;return h===mt?this:w?w(d,this):this.multiplyUnsafe(t.h)}toRawBytes(h=!0){return Vt("isCompressed",h),this.assertValidity(),o(d,this,h)}toHex(h=!0){return Vt("isCompressed",h),oe(this.toRawBytes(h))}}d.BASE=new d(t.Gx,t.Gy,e.ONE),d.ZERO=new d(e.ZERO,e.ONE,e.ZERO);let g=t.nBitLength,y=on(d,t.endo?Math.ceil(g/2):g);return{CURVE:t,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:s,isWithinCurveOrder:a}}function dh(r){let t=vr(r);return Xt(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function nc(r){let t=dh(r),{Fp:e,n}=t,o=e.BYTES+1,i=2*e.BYTES+1;function s(S){return Y(S,n)}function a(S){return rn(S,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:u,isWithinCurveOrder:f}=hh({...t,toBytes(S,L,x){let p=L.toAffine(),E=e.toBytes(p.x),A=se;return Vt("isCompressed",x),x?A(Uint8Array.from([L.hasEvenY()?2:3]),E):A(Uint8Array.from([4]),E,e.toBytes(p.y))},fromBytes(S){let L=S.length,x=S[0],p=S.subarray(1);if(L===o&&(x===2||x===3)){let E=ie(p);if(!wr(E,mt,e.ORDER))throw new Error("Point is not on curve");let A=u(E),D;try{D=e.sqrt(A)}catch(F){let N=F instanceof Error?": "+F.message:"";throw new Error("Point is not on curve"+N)}let P=(D&mt)===mt;return(x&1)===1!==P&&(D=e.neg(D)),{x:E,y:D}}else if(L===i&&x===4){let E=e.fromBytes(p.subarray(0,e.BYTES)),A=e.fromBytes(p.subarray(e.BYTES,2*e.BYTES));return{x:E,y:A}}else{let E=o,A=i;throw new Error("invalid Point, expected length of "+E+", or uncompressed "+A+", got "+L)}}}),d=S=>oe(ye(S,t.nByteLength));function g(S){let L=n>>mt;return S>L}function y(S){return g(S)?s(-S):S}let b=(S,L,x)=>ie(S.slice(L,x));class h{constructor(L,x,p){this.r=L,this.s=x,this.recovery=p,this.assertValidity()}static fromCompact(L){let x=t.nByteLength;return L=ot("compactSignature",L,x*2),new h(b(L,0,x),b(L,x,2*x))}static fromDER(L){let{r:x,s:p}=ce.toSig(ot("DER",L));return new h(x,p)}assertValidity(){Tt("r",this.r,mt,n),Tt("s",this.s,mt,n)}addRecoveryBit(L){return new h(this.r,this.s,L)}recoverPublicKey(L){let{r:x,s:p,recovery:E}=this,A=C(ot("msgHash",L));if(E==null||![0,1,2,3].includes(E))throw new Error("recovery id invalid");let D=E===2||E===3?x+t.n:x;if(D>=e.ORDER)throw new Error("recovery id 2 or 3 invalid");let P=(E&1)===0?"02":"03",O=c.fromHex(P+d(D)),F=a(D),N=s(-A*F),Z=s(p*F),J=c.BASE.multiplyAndAddUnsafe(O,N,Z);if(!J)throw new Error("point at infinify");return J.assertValidity(),J}hasHighS(){return g(this.s)}normalizeS(){return this.hasHighS()?new h(this.r,s(-this.s),this.recovery):this}toDERRawBytes(){return Re(this.toDERHex())}toDERHex(){return ce.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Re(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}let w={isValidPrivateKey(S){try{return l(S),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{let S=zo(t.n);return ya(t.randomBytes(S),t.n)},precompute(S=8,L=c.BASE){return L._setWindowSize(S),L.multiply(BigInt(3)),L}};function v(S,L=!0){return c.fromPrivateKey(S).toRawBytes(L)}function m(S){let L=pe(S),x=typeof S=="string",p=(L||x)&&S.length;return L?p===o||p===i:x?p===2*o||p===2*i:S instanceof c}function _(S,L,x=!0){if(m(S))throw new Error("first arg must be private key");if(!m(L))throw new Error("second arg must be public key");return c.fromHex(L).multiply(l(S)).toRawBytes(x)}let B=t.bits2int||function(S){if(S.length>8192)throw new Error("input is too large");let L=ie(S),x=S.length*8-t.nBitLength;return x>0?L>>BigInt(x):L},C=t.bits2int_modN||function(S){return s(B(S))},I=Er(t.nBitLength);function R(S){return Tt("num < 2^"+t.nBitLength,S,ue,I),ye(S,t.nByteLength)}function T(S,L,x=et){if(["recovered","canonical"].some(dt=>dt in x))throw new Error("sign() legacy options not supported");let{hash:p,randomBytes:E}=t,{lowS:A,prehash:D,extraEntropy:P}=x;A==null&&(A=!0),S=ot("msgHash",S),ec(x),D&&(S=ot("prehashed msgHash",p(S)));let O=C(S),F=l(L),N=[R(F),R(O)];if(P!=null&&P!==!1){let dt=P===!0?E(e.BYTES):P;N.push(ot("extraEntropy",dt))}let Z=se(...N),J=O;function ht(dt){let yt=B(dt);if(!f(yt))return;let gt=a(yt),It=c.BASE.multiply(yt).toAffine(),At=s(It.x);if(At===ue)return;let $t=s(gt*s(J+At*F));if($t===ue)return;let jt=(It.x===At?0:2)|Number(It.y&mt),dr=$t;return A&&g($t)&&(dr=y($t),jt^=1),new h(At,dr,jt)}return{seed:Z,k2sig:ht}}let et={lowS:t.lowS,prehash:!1},H={lowS:t.lowS,prehash:!1};function q(S,L,x=et){let{seed:p,k2sig:E}=T(S,L,x),A=t;return ko(A.hash.outputLen,A.nByteLength,A.hmac)(p,E)}c.BASE._setWindowSize(8);function ut(S,L,x,p=H){let E=S;L=ot("msgHash",L),x=ot("publicKey",x);let{lowS:A,prehash:D,format:P}=p;if(ec(p),"strict"in p)throw new Error("options.strict was renamed to lowS");if(P!==void 0&&P!=="compact"&&P!=="der")throw new Error("format must be compact or der");let O=typeof E=="string"||pe(E),F=!O&&!P&&typeof E=="object"&&E!==null&&typeof E.r=="bigint"&&typeof E.s=="bigint";if(!O&&!F)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let N,Z;try{if(F&&(N=new h(E.r,E.s)),O){try{P!=="compact"&&(N=h.fromDER(E))}catch(jt){if(!(jt instanceof ce.Err))throw jt}!N&&P!=="der"&&(N=h.fromCompact(E))}Z=c.fromHex(x)}catch{return!1}if(!N||A&&N.hasHighS())return!1;D&&(L=t.hash(L));let{r:J,s:ht}=N,dt=C(L),yt=a(ht),gt=s(dt*yt),It=s(J*yt),At=c.BASE.multiplyAndAddUnsafe(Z,gt,It)?.toAffine();return At?s(At.x)===J:!1}return{CURVE:t,getPublicKey:v,getSharedSecret:_,sign:q,verify:ut,ProjectivePoint:c,Signature:h,utils:w}}function ph(r){return{hash:r,hmac:(t,...e)=>Ui(r,t,Co(...e)),randomBytes:Qr}}function oc(r,t){let e=n=>nc({...r,...ph(n)});return{...e(t),create:e}}var ac=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),ic=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),mh=BigInt(1),Mi=BigInt(2),sc=(r,t)=>(r+t/Mi)/t;function yh(r){let t=ac,e=BigInt(3),n=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%t,u=l*l*r%t,f=nt(u,e,t)*u%t,d=nt(f,e,t)*u%t,g=nt(d,Mi,t)*l%t,y=nt(g,o,t)*g%t,b=nt(y,i,t)*y%t,h=nt(b,a,t)*b%t,w=nt(h,c,t)*h%t,v=nt(w,a,t)*b%t,m=nt(v,e,t)*u%t,_=nt(m,s,t)*y%t,B=nt(_,n,t)*l%t,C=nt(B,Mi,t);if(!ki.eql(ki.sqr(C),r))throw new Error("Cannot find square root");return C}var ki=ge(ac,void 0,void 0,{sqrt:yh}),Oe=oc({a:BigInt(0),b:BigInt(7),Fp:ki,n:ic,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let t=ic,e=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-mh*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=e,s=BigInt("0x100000000000000000000000000000000"),a=sc(i*r,t),c=sc(-n*r,t),l=Y(r-a*e-c*o,t),u=Y(-a*n-c*i,t),f=l>s,d=u>s;if(f&&(l=t-l),d&&(u=t-u),l>s||u>s)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:f,k1:l,k2neg:d,k2:u}}}},tr),my=BigInt(0);var yy=Oe.ProjectivePoint;function cc(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function uc(r,t,e){let n=je.digest(e instanceof Uint8Array?e:e.subarray());if(cc(n))return n.then(({digest:o})=>Oe.verify(t,o,r)).catch(o=>{throw new Lr(String(o))});try{return Oe.verify(t,n.digest,r)}catch(o){throw new Lr(String(o))}}var wn=class{type="secp256k1";raw;_key;constructor(t){this._key=fc(t),this.raw=lc(this._key)}toMultihash(){return re.digest(be(this))}toCID(){return at.createV1(114,this.toMultihash())}toString(){return Q.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:pt(this.raw,t.raw)}verify(t,e){return uc(this._key,e,t)}};function Ki(r){return new wn(r)}function lc(r){return Oe.ProjectivePoint.fromHex(r).toRawBytes(!0)}function fc(r){try{return Oe.ProjectivePoint.fromHex(r),r}catch(t){throw new Fe(String(t))}}function hc(r,t){let{Type:e,Data:n}=Qt.decode(r),o=n??new Uint8Array;switch(e){case ft.RSA:return Ni(o,t);case ft.Ed25519:return Yo(o);case ft.secp256k1:return Ki(o);default:throw new ze}}function dc(r){let{Type:t,Data:e}=Qt.decode(r.digest),n=e??new Uint8Array;switch(t){case ft.Ed25519:return Yo(n);case ft.secp256k1:return Ki(n);default:throw new ze}}function be(r){return Qt.encode({Type:ft[r.type],Data:r.raw})}var pc=Symbol.for("nodejs.util.inspect.custom"),gh=114,Cr=class{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[xo]=!0;toString(){return this.string==null&&(this.string=Q.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return at.createV1(gh,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return pt(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return pt(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[pc](){return`PeerId(${this.toString()})`}},En=class extends Cr{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},vn=class extends Cr{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},Sn=class extends Cr{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},bh=2336,Dr=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=re.digest(z(this.url))}[pc](){return`PeerId(${this.url})`}[xo]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return at.createV1(bh,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=V(t)),t.toString()===this.toString())}};var xh=114,mc=2336;function qi(r,t){let e;if(r.charAt(0)==="1"||r.charAt(0)==="Q")e=Mt(Q.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return wh(at.parse(r));if(t==null)throw new bt('Please pass a multibase decoder for strings that do not start with "1" or "Q"');e=Mt(t.decode(r))}return rr(e)}function rr(r){if(vh(r))return new En({multihash:r});if(Eh(r))try{let t=dc(r);if(t.type==="Ed25519")return new vn({multihash:r,publicKey:t});if(t.type==="secp256k1")return new Sn({multihash:r,publicKey:t})}catch{let e=V(r.digest);return new Dr(new URL(e))}throw new Wr("Supplied PeerID Multihash is invalid")}function wh(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==xh&&r.code!==mc)throw new Gr("Supplied PeerID CID is invalid");if(r.code===mc){let t=V(r.multihash.digest);return new Dr(new URL(t))}return rr(r.multihash)}function Eh(r){return r.code===re.code}function vh(r){return r.code===je.code}var Pr;(function(r){let t;r.codec=()=>(t==null&&(t=Dt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.publicKey!=null&&e.publicKey.byteLength>0&&(n.uint32(10),n.bytes(e.publicKey)),e.payloadType!=null&&e.payloadType.byteLength>0&&(n.uint32(18),n.bytes(e.payloadType)),e.payload!=null&&e.payload.byteLength>0&&(n.uint32(26),n.bytes(e.payload)),e.signature!=null&&e.signature.byteLength>0&&(n.uint32(42),n.bytes(e.signature)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let i={publicKey:it(0),payloadType:it(0),payload:it(0),signature:it(0)},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let a=e.uint32();switch(a>>>3){case 1:{i.publicKey=e.bytes();break}case 2:{i.payloadType=e.bytes();break}case 3:{i.payload=e.bytes();break}case 5:{i.signature=e.bytes();break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Ct(e,r.codec()),r.decode=(e,n)=>Bt(e,r.codec(),n)})(Pr||(Pr={}));var An=class extends Error{constructor(t="Invalid signature"){super(t),this.name="InvalidSignatureError"}};var Nr=class r{static createFromProtobuf=async t=>{let e=Pr.decode(t),n=hc(e.publicKey);return new r({publicKey:n,payloadType:e.payloadType,payload:e.payload,signature:e.signature})};static seal=async(t,e)=>{if(e==null)throw new Error("Missing private key");let n=t.domain,o=t.codec,i=t.marshal(),s=yc(n,o,i),a=await e.sign(s.subarray());return new r({publicKey:e.publicKey,payloadType:o,payload:i,signature:a})};static openAndCertify=async(t,e)=>{let n=await r.createFromProtobuf(t);if(!await n.validate(e))throw new An("Envelope signature is not valid for the given domain");return n};publicKey;payloadType;payload;signature;marshaled;constructor(t){let{publicKey:e,payloadType:n,payload:o,signature:i}=t;this.publicKey=e,this.payloadType=n,this.payload=o,this.signature=i}marshal(){return this.marshaled==null&&(this.marshaled=Pr.encode({publicKey:be(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(t){return pt(this.marshal(),t.marshal())}async validate(t){let e=yc(t,this.payloadType,this.payload);return this.publicKey.verify(e.subarray(),this.signature)}},yc=(r,t,e)=>{let n=z(r),o=kt(n.byteLength),i=kt(t.length),s=kt(e.length);return new ct(o,n,i,t,s,e)};var _n=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let e=this.index,n=t();return n===void 0&&(this.index=e),n}parseWith(t){let e=t();if(this.index===this.input.length)return e}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(t){return this.readAtomically(()=>{let e=this.readChar();if(e===t)return e})}readSeparator(t,e,n){return this.readAtomically(()=>{if(!(e>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,e,n,o){return this.readAtomically(()=>{let i=0,s=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let u=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let d=Number.parseInt(f,t);if(!Number.isNaN(d))return d});if(u===void 0)break;if(i*=t,i+=u,i>l||(s+=1,e!==void 0&&s>e))return}if(s!==0)return!n&&c&&s>1?void 0:i})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let e=0;e<t.length;e++){let n=this.readSeparator(".",e,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[e]=n}return t})}readIPv6Addr(){let t=e=>{for(let n=0;n<e.length/2;n++){let o=n*2;if(n<e.length-3){let s=this.readSeparator(":",n,()=>this.readIPv4Addr());if(s!==void 0)return e[o]=s[0],e[o+1]=s[1],e[o+2]=s[2],e[o+3]=s[3],[o+4,!0]}let i=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(i===void 0)return[o,!1];e[o]=i>>8,e[o+1]=i&255}return[e.length,!1]};return this.readAtomically(()=>{let e=new Uint8Array(16),[n,o]=t(e);if(n===16)return e;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let i=new Uint8Array(14),s=16-(n+2),[a]=t(i.subarray(0,s));return e.set(i.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var gc=45,Sh=15,nr=new _n;function Fi(r){if(!(r.length>Sh))return nr.new(r).parseWith(()=>nr.readIPv4Addr())}function zi(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>gc))return nr.new(r).parseWith(()=>nr.readIPv6Addr())}function In(r,t=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>gc)return;let e=nr.new(r).parseWith(()=>nr.readIPAddr());if(e)return t&&e.length===4?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,e[0],e[1],e[2],e[3]]):e}var Mg=parseInt("0xFFFF",16),kg=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Tn(r){return!!Fi(r)}function Ln(r){return!!zi(r)}function Rn(r){return!!In(r)}var wc=Tn,Lh=Ln,Vi=function(r){let t=0;if(r=r.toString().trim(),wc(r)){let e=new Uint8Array(t+4);return r.split(/\./g).forEach(n=>{e[t++]=parseInt(n,10)&255}),e}if(Lh(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let i=wc(e[n]),s;i&&(s=Vi(e[n]),e[n]=V(s.slice(0,2),"base16")),s!=null&&++n<8&&e.splice(n,0,V(s.slice(2,4),"base16"))}if(e[0]==="")for(;e.length<8;)e.unshift("0");else if(e[e.length-1]==="")for(;e.length<8;)e.push("0");else if(e.length<8){for(n=0;n<e.length&&e[n]!=="";n++);let i=[n,1];for(n=9-e.length;n>0;n--)i.push("0");e.splice.apply(e,i)}let o=new Uint8Array(t+16);for(n=0;n<e.length;n++){let i=parseInt(e[n],16);o[t++]=i>>8&255,o[t++]=i&255}return o}throw new Error("invalid ip address")},Ec=function(r,t=0,e){t=~~t,e=e??r.length-t;let n=new DataView(r.buffer);if(e===4){let o=[];for(let i=0;i<e;i++)o.push(r[t+i]);return o.join(".")}if(e===16){let o=[];for(let i=0;i<e;i+=2)o.push(n.getUint16(t+i).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var or={},Hi={},Bh=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,-1,"ip6zone"],[43,8,"ipcidr"],[53,-1,"dns",!0],[54,-1,"dns4",!0],[55,-1,"dns6",!0],[56,-1,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,-1,"unix",!1,!0],[421,-1,"ipfs"],[421,-1,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,-1,"garlic64"],[448,0,"tls"],[449,-1,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,-1,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,-1,"http-path"],[777,-1,"memory"]];Bh.forEach(r=>{let t=Ch(...r);Hi[t.code]=t,or[t.name]=t});function Ch(r,t,e,n,o){return{code:r,size:t,name:e,resolvable:!!n,path:!!o}}function j(r){if(typeof r=="number"){if(Hi[r]!=null)return Hi[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(or[r]!=null)return or[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var Eb=j("ip4"),vb=j("ip6"),Sb=j("ipcidr");function $i(r,t){switch(j(r).code){case 4:case 41:return Ph(t);case 42:return Zi(t);case 43:return V(t,"base10");case 6:case 273:case 33:case 132:return Ac(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Zi(t);case 421:return Mh(t);case 444:return Sc(t);case 445:return Sc(t);case 466:return Oh(t);case 481:return globalThis.encodeURIComponent(Zi(t));default:return V(t,"base16")}}function Yi(r,t){switch(j(r).code){case 4:return vc(t);case 41:return vc(t);case 42:return Wi(t);case 43:return z(t,"base10");case 6:case 273:case 33:case 132:return Xi(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Wi(t);case 421:return Nh(t);case 444:return kh(t);case 445:return Kh(t);case 466:return Uh(t);case 481:return Wi(globalThis.decodeURIComponent(t));default:return z(t,"base16")}}var Gi=Object.values(Sr).map(r=>r.decoder),Dh=function(){let r=Gi[0].or(Gi[1]);return Gi.slice(2).forEach(t=>r=r.or(t)),r}();function vc(r){if(!Rn(r))throw new Error("invalid ip address");return Vi(r)}function Ph(r){let t=Ec(r,0,r.length);if(t==null)throw new Error("ipBuff is required");if(!Rn(t))throw new Error("invalid ip address");return t}function Xi(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,r),new Uint8Array(t)}function Ac(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function Wi(r){let t=z(r),e=Uint8Array.from(kt(t.length));return Nt([e,t],e.length+t.length)}function Zi(r){let t=ae(r);if(r=r.slice(wt(t)),r.length!==t)throw new Error("inconsistent lengths");return V(r)}function Nh(r){let t;r[0]==="Q"||r[0]==="1"?t=Mt(Q.decode(`z${r}`)).bytes:t=at.parse(r).multihash.bytes;let e=Uint8Array.from(kt(t.length));return Nt([e,t],e.length+t.length)}function Uh(r){let t=Dh.decode(r),e=Uint8Array.from(kt(t.length));return Nt([e,t],e.length+t.length)}function Oh(r){let t=ae(r),e=r.slice(wt(t));if(e.length!==t)throw new Error("inconsistent lengths");return"u"+V(e,"base64url")}function Mh(r){let t=ae(r),e=r.slice(wt(t));if(e.length!==t)throw new Error("inconsistent lengths");return V(e,"base58btc")}function kh(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==16)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);let e=ee.decode("b"+t[0]),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Xi(n);return Nt([e,o],e.length+o.length)}function Kh(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let e=ee.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Xi(n);return Nt([e,o],e.length+o.length)}function Sc(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=V(t,"base32"),o=Ac(e);return`${n}:${o}`}function _c(r){r=Qi(r);let t=[],e=[],n=null,o=r.split("/").slice(1);if(o.length===1&&o[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let i=0;i<o.length;i++){let s=o[i],a=j(s);if(a.size===0){t.push([a.code]),e.push([a.code]);continue}if(i++,i>=o.length)throw new Bn("invalid address: "+r);if(a.path===!0){n=Qi(o.slice(i).join("/")),t.push([a.code,Yi(a.code,n)]),e.push([a.code,n]);break}let c=Yi(a.code,o[i]);t.push([a.code,c]),e.push([a.code,$i(a.code,c)])}return{string:Ic(e),bytes:Cn(t),tuples:t,stringTuples:e,path:n}}function ji(r){let t=[],e=[],n=null,o=0;for(;o<r.length;){let i=ae(r,o),s=wt(i),a=j(i),c=qh(a,r.slice(o+s));if(c===0){t.push([i]),e.push([i]),o+=s;continue}let l=r.slice(o+s,o+s+c);if(o+=c+s,o>r.length)throw new Bn("Invalid address Uint8Array: "+V(r,"base16"));t.push([i,l]);let u=$i(i,l);if(e.push([i,u]),a.path===!0){n=u;break}}return{bytes:Uint8Array.from(r),string:Ic(e),tuples:t,stringTuples:e,path:n}}function Ic(r){let t=[];return r.map(e=>{let n=j(e[0]);return t.push(n.name),e.length>1&&e[1]!=null&&t.push(e[1]),null}),Qi(t.join("/"))}function Cn(r){return Nt(r.map(t=>{let e=j(t[0]),n=Uint8Array.from(kt(e.code));return t.length>1&&t[1]!=null&&(n=Nt([n,t[1]])),n}))}function qh(r,t){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let e=ae(t instanceof Uint8Array?t:Uint8Array.from(t));return e+wt(e)}}function Qi(r){return"/"+r.trim().split("/").filter(t=>t).join("/")}var Bn=class extends Error{static name="ParseError";name="ParseError";constructor(t){super(`Error parsing address: ${t}`)}};var Fh=Symbol.for("nodejs.util.inspect.custom"),ts=Symbol.for("@multiformats/js-multiaddr/multiaddr"),zh=[j("dns").code,j("dns4").code,j("dns6").code,j("dnsaddr").code],Ji=class extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}},Dn=class r{bytes;#t;#e;#r;#n;[ts]=!0;constructor(t){t==null&&(t="");let e;if(t instanceof Uint8Array)e=ji(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=_c(t)}else if(Lc(t))e=ji(t.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=e.bytes,this.#t=e.string,this.#e=e.tuples,this.#r=e.stringTuples,this.#n=e.path}toString(){return this.#t}toJSON(){return this.toString()}toOptions(){let t,e,n,o,i="",s=j("tcp"),a=j("udp"),c=j("ip4"),l=j("ip6"),u=j("dns6"),f=j("ip6zone");for(let[g,y]of this.stringTuples())g===f.code&&(i=`%${y??""}`),zh.includes(g)&&(e=s.name==="tcp"?"tcp":"udp",o=443,n=`${y??""}${i}`,t=g===u.code?6:4),(g===s.code||g===a.code)&&(e=j(g).name==="tcp"?"tcp":"udp",o=parseInt(y??"")),(g===c.code||g===l.code)&&(e=j(g).name==="tcp"?"tcp":"udp",n=`${y??""}${i}`,t=g===l.code?6:4);if(t==null||e==null||n==null||o==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:t,host:n,transport:e,port:o}}protos(){return this.#e.map(([t])=>Object.assign({},j(t)))}protoCodes(){return this.#e.map(([t])=>t)}protoNames(){return this.#e.map(([t])=>j(t).name)}tuples(){return this.#e.map(([t,e])=>e==null?[t]:[t,e])}stringTuples(){return this.#r.map(([t,e])=>e==null?[t]:[t,e])}encapsulate(t){return t=new r(t),new r(this.toString()+t.toString())}decapsulate(t){let e=t.toString(),n=this.toString(),o=n.lastIndexOf(e);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${t.toString()}`);return new r(n.slice(0,o))}decapsulateCode(t){let e=this.tuples();for(let n=e.length-1;n>=0;n--)if(e[n][0]===t)return new r(Cn(e.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,o])=>{n===or.p2p.code&&t.push([n,o]),n===or["p2p-circuit"].code&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?V(Q.decode(`z${n}`),"base58btc"):V(at.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#n}equals(t){return pt(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(i=>i.resolvable);if(e==null)return[this];let n=Tc.get(e.name);if(n==null)throw new Ji(`no available resolver for ${e.name}`);return(await n(this,t)).map(i=>vt(i))}nodeAddress(){let t=this.toOptions();if(t.transport!=="tcp"&&t.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${t.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:t.family,address:t.host,port:t.port}}isThinWaistAddress(t){let e=(t??this).protos();return!(e.length!==2||e[0].code!==4&&e[0].code!==41||e[1].code!==6&&e[1].code!==273)}[Fh](){return`Multiaddr(${this.#t})`}};var Tc=new Map;function Lc(r){return!!r?.[ts]}function vt(r){return new Dn(r)}function Wt(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var Pn=class extends Error{type;code;constructor(t,e,n){super(t??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=e??"ABORT_ERR"}};async function Nn(r,t,e){if(t==null)return r;if(t.aborted)return r.catch(()=>{}),Promise.reject(new Pn(e?.errorMessage,e?.errorCode,e?.errorName));let n,o=new Pn(e?.errorMessage,e?.errorCode,e?.errorName);try{return await Promise.race([r,new Promise((i,s)=>{n=()=>{s(o)},t.addEventListener("abort",n)})])}finally{n!=null&&t.removeEventListener("abort",n)}}var es=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=Wt(),this.haveNext=Wt()}[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 t=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=Wt(),t}async throw(t){return this.ended=!0,t!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(t)),{done:!0,value:void 0}}async return(){let t={done:!0,value:void 0};return this.ended=!0,this.nextResult=t,this.haveNext.resolve(),t}async push(t,e){await this._push(t,e)}async end(t,e){t!=null?await this.throw(t):await this._push(void 0,e)}async _push(t,e){if(t!=null&&this.ended)throw new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;t!=null?this.nextResult={done:!1,value:t}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=Wt(),await Nn(this.readNext.promise,e?.signal,e)}};function Rc(){return new es}var Un=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var rs=class extends Error{code;constructor(t,e){super(t),this.code=e}},ns=class extends rs{type;constructor(t){super(t,"ABORT_ERR"),this.type="aborted",this.name="AbortError"}};function Bc(r,t){let e=Rc();r.sink(e).catch(async s=>{await e.end(s)}),r.sink=async s=>{for await(let a of s)await e.push(a);await e.end()};let n=r.source;r.source[Symbol.iterator]!=null?n=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(n=r.source[Symbol.asyncIterator]());let o=new ct;return{read:async(s,a)=>{a?.signal?.throwIfAborted();let c,l=new Promise((u,f)=>{c=()=>{f(new ns("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(s==null){let{done:f,value:d}=await Promise.race([n.next(),l]);return f===!0?new ct:d}for(;o.byteLength<s;){let{value:f,done:d}=await Promise.race([n.next(),l]);if(d===!0)throw new Un("unexpected end of input");o.append(f)}let u=o.sublist(0,s);return o.consume(s),u}finally{c!=null&&a?.signal?.removeEventListener("abort",c)}},write:async(s,a)=>{a?.signal?.throwIfAborted(),s instanceof Uint8Array?await e.push(s,a):await e.push(s.subarray(),a)},unwrap:()=>{if(o.byteLength>0){let s=r.source;r.source=async function*(){t?.yieldBytes===!1?yield o:yield*o,yield*s}()}return r}}}var On=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Mn=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},kn=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Cc(r,t={}){let e=Bc(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=wt(t.maxDataLength));let n=t?.lengthDecoder??ae,o=t?.lengthEncoder??kt;return{read:async s=>{let a=-1,c=new ct;for(;;){c.append(await e.read(1,s));try{a=n(c)}catch(l){if(l instanceof RangeError)continue;throw l}if(a<0)throw new On("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new kn("message length length too long");if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new Mn("message length too long");return e.read(a,s)},write:async(s,a)=>{await e.write(new ct(o(s.byteLength),s),a)},writeV:async(s,a)=>{let c=new ct(...s.flatMap(l=>[o(l.byteLength),l]));await e.write(c,a)},unwrap:()=>e.unwrap()}}function Se(r,t){let e=Cc(r,t),n={read:async(o,i)=>{let s=await e.read(i);return o.decode(s)},write:async(o,i,s)=>{await e.write(i.encode(o),s)},writeV:async(o,i,s)=>{await e.writeV(o.map(a=>i.encode(a)),s)},pb:o=>({read:async i=>n.read(o,i),write:async(i,s)=>n.write(i,o,s),writeV:async(i,s)=>n.writeV(i,o,s),unwrap:()=>n}),unwrap:()=>e.unwrap()};return n}var os=1e3,Dc=60*os,Kn=290,Pc=15,Nc=2*60*Dc,Uc=1,qn=2e3,Oc=100,is="circuit-relay-source",Ur=`${wo}-circuit-relay`,ss=`${wo}-circuit-relay-source`,Mc=2*Dc,kc=BigInt(1<<17),qt="/libp2p/circuit/relay/0.2.0/hop",Me="/libp2p/circuit/relay/0.2.0/stop",Kc=30*os,mx=30*os,Or=300,qc=4096,Fc=.001;var $;(function(r){let t;(function(o){o.RESERVE="RESERVE",o.CONNECT="CONNECT",o.STATUS="STATUS"})(t=r.Type||(r.Type={}));let e;(function(o){o[o.RESERVE=0]="RESERVE",o[o.CONNECT=1]="CONNECT",o[o.STATUS=2]="STATUS"})(e||(e={})),function(o){o.codec=()=>Ue(e)}(t=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Dt((o,i,s={})=>{s.lengthDelimited!==!1&&i.fork(),o.type!=null&&(i.uint32(8),r.Type.codec().encode(o.type,i)),o.peer!=null&&(i.uint32(18),ir.codec().encode(o.peer,i)),o.reservation!=null&&(i.uint32(26),Fn.codec().encode(o.reservation,i)),o.limit!=null&&(i.uint32(34),sr.codec().encode(o.limit,i)),o.status!=null&&(i.uint32(40),k.codec().encode(o.status,i)),s.lengthDelimited!==!1&&i.ldelim()},(o,i,s={})=>{let a={},c=i==null?o.len:o.pos+i;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.type=r.Type.codec().decode(o);break}case 2:{a.peer=ir.codec().decode(o,o.uint32(),{limits:s.limits?.peer});break}case 3:{a.reservation=Fn.codec().decode(o,o.uint32(),{limits:s.limits?.reservation});break}case 4:{a.limit=sr.codec().decode(o,o.uint32(),{limits:s.limits?.limit});break}case 5:{a.status=k.codec().decode(o);break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>Ct(o,r.codec()),r.decode=(o,i)=>Bt(o,r.codec(),i)})($||($={}));var Ut;(function(r){let t;(function(o){o.CONNECT="CONNECT",o.STATUS="STATUS"})(t=r.Type||(r.Type={}));let e;(function(o){o[o.CONNECT=0]="CONNECT",o[o.STATUS=1]="STATUS"})(e||(e={})),function(o){o.codec=()=>Ue(e)}(t=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Dt((o,i,s={})=>{s.lengthDelimited!==!1&&i.fork(),o.type!=null&&(i.uint32(8),r.Type.codec().encode(o.type,i)),o.peer!=null&&(i.uint32(18),ir.codec().encode(o.peer,i)),o.limit!=null&&(i.uint32(26),sr.codec().encode(o.limit,i)),o.status!=null&&(i.uint32(32),k.codec().encode(o.status,i)),s.lengthDelimited!==!1&&i.ldelim()},(o,i,s={})=>{let a={},c=i==null?o.len:o.pos+i;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.type=r.Type.codec().decode(o);break}case 2:{a.peer=ir.codec().decode(o,o.uint32(),{limits:s.limits?.peer});break}case 3:{a.limit=sr.codec().decode(o,o.uint32(),{limits:s.limits?.limit});break}case 4:{a.status=k.codec().decode(o);break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>Ct(o,r.codec()),r.decode=(o,i)=>Bt(o,r.codec(),i)})(Ut||(Ut={}));var ir;(function(r){let t;r.codec=()=>(t==null&&(t=Dt((e,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),e.id!=null&&e.id.byteLength>0&&(n.uint32(10),n.bytes(e.id)),e.addrs!=null)for(let i of e.addrs)n.uint32(18),n.bytes(i);o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let i={id:it(0),addrs:[]},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let a=e.uint32();switch(a>>>3){case 1:{i.id=e.bytes();break}case 2:{if(o.limits?.addrs!=null&&i.addrs.length===o.limits.addrs)throw new Ir('Decode error - map field "addrs" had too many elements');i.addrs.push(e.bytes());break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Ct(e,r.codec()),r.decode=(e,n)=>Bt(e,r.codec(),n)})(ir||(ir={}));var Fn;(function(r){let t;r.codec=()=>(t==null&&(t=Dt((e,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),e.expire!=null&&e.expire!==0n&&(n.uint32(8),n.uint64(e.expire)),e.addrs!=null)for(let i of e.addrs)n.uint32(18),n.bytes(i);e.voucher!=null&&(n.uint32(26),zn.codec().encode(e.voucher,n)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let i={expire:0n,addrs:[]},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let a=e.uint32();switch(a>>>3){case 1:{i.expire=e.uint64();break}case 2:{if(o.limits?.addrs!=null&&i.addrs.length===o.limits.addrs)throw new Ir('Decode error - map field "addrs" had too many elements');i.addrs.push(e.bytes());break}case 3:{i.voucher=zn.codec().decode(e,e.uint32(),{limits:o.limits?.voucher});break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Ct(e,r.codec()),r.decode=(e,n)=>Bt(e,r.codec(),n)})(Fn||(Fn={}));var sr;(function(r){let t;r.codec=()=>(t==null&&(t=Dt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.duration!=null&&(n.uint32(8),n.uint32(e.duration)),e.data!=null&&(n.uint32(16),n.uint64(e.data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let i={},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let a=e.uint32();switch(a>>>3){case 1:{i.duration=e.uint32();break}case 2:{i.data=e.uint64();break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Ct(e,r.codec()),r.decode=(e,n)=>Bt(e,r.codec(),n)})(sr||(sr={}));var k;(function(r){r.UNUSED="UNUSED",r.OK="OK",r.RESERVATION_REFUSED="RESERVATION_REFUSED",r.RESOURCE_LIMIT_EXCEEDED="RESOURCE_LIMIT_EXCEEDED",r.PERMISSION_DENIED="PERMISSION_DENIED",r.CONNECTION_FAILED="CONNECTION_FAILED",r.NO_RESERVATION="NO_RESERVATION",r.MALFORMED_MESSAGE="MALFORMED_MESSAGE",r.UNEXPECTED_MESSAGE="UNEXPECTED_MESSAGE"})(k||(k={}));var as;(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"})(as||(as={}));(function(r){r.codec=()=>Ue(as)})(k||(k={}));var ar;(function(r){let t;r.codec=()=>(t==null&&(t=Dt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.relay!=null&&e.relay.byteLength>0&&(n.uint32(10),n.bytes(e.relay)),e.peer!=null&&e.peer.byteLength>0&&(n.uint32(18),n.bytes(e.peer)),e.expiration!=null&&e.expiration!==0n&&(n.uint32(24),n.uint64(e.expiration)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let i={relay:it(0),peer:it(0),expiration:0n},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let a=e.uint32();switch(a>>>3){case 1:{i.relay=e.bytes();break}case 2:{i.peer=e.bytes();break}case 3:{i.expiration=e.uint64();break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Ct(e,r.codec()),r.decode=(e,n)=>Bt(e,r.codec(),n)})(ar||(ar={}));var zn;(function(r){let t;r.codec=()=>(t==null&&(t=Dt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.publicKey!=null&&e.publicKey.byteLength>0&&(n.uint32(10),n.bytes(e.publicKey)),e.payloadType!=null&&e.payloadType.byteLength>0&&(n.uint32(18),n.bytes(e.payloadType)),e.payload!=null&&(n.uint32(26),ar.codec().encode(e.payload,n)),e.signature!=null&&e.signature.byteLength>0&&(n.uint32(42),n.bytes(e.signature)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let i={publicKey:it(0),payloadType:it(0),signature:it(0)},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let a=e.uint32();switch(a>>>3){case 1:{i.publicKey=e.bytes();break}case 2:{i.payloadType=e.bytes();break}case 3:{i.payload=ar.codec().decode(e,e.uint32(),{limits:o.limits?.payload});break}case 5:{i.signature=e.bytes();break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Ct(e,r.codec()),r.decode=(e,n)=>Bt(e,r.codec(),n)})(zn||(zn={}));var Vh=r=>r.toString().split("/").slice(1),cr=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),M=r=>({match:t=>cr(e=>e===r).match(t),pattern:r}),ke=()=>({match:r=>cr(t=>typeof t=="string").match(r),pattern:"{string}"}),Mr=()=>({match:r=>cr(t=>!isNaN(parseInt(t))).match(r),pattern:"{number}"}),X=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{Q.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),kr=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{fi.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),G=r=>({match:t=>{let e=r.match(t);return e===!1?t:e},pattern:`optional(${r.pattern})`}),St=(...r)=>({match:t=>{let e;for(let n of r){let o=n.match(t);o!==!1&&(e==null||o.length<e.length)&&(e=o)}return e??!1},pattern:`or(${r.map(t=>t.pattern).join(", ")})`}),K=(...r)=>({match:t=>{for(let e of r){let n=e.match(t);if(n===!1)return!1;t=n}return t},pattern:`and(${r.map(t=>t.pattern).join(", ")})`});function tt(...r){function t(o){let i=Vh(o);for(let s of r){let a=s.match(i);if(a===!1)return!1;i=a}return i}function e(o){return t(o)!==!1}function n(o){let i=t(o);return i===!1?!1:i.length===0}return{matchers:r,matches:e,exactMatch:n}}var Hn=K(M("dns4"),ke()),Gn=K(M("dns6"),ke()),Wn=K(M("dnsaddr"),ke()),us=K(M("dns"),ke()),_x=tt(Hn,G(X())),Ix=tt(Gn,G(X())),Tx=tt(Wn,G(X())),Lx=tt(St(us,Wn,Hn,Gn),G(X())),zc=K(M("ip4"),cr(Tn)),Vc=K(M("ip6"),cr(Ln)),ls=St(zc,Vc),le=St(ls,us,Hn,Gn,Wn),Rx=tt(St(ls,K(St(us,Wn,Hn,Gn),G(X())))),Bx=tt(zc),Cx=tt(Vc),Dx=tt(ls),fs=K(le,M("tcp"),Mr()),Kr=K(le,M("udp"),Mr()),Px=tt(K(fs,G(X()))),Nx=tt(Kr),hs=K(Kr,M("quic"),G(X())),Zn=K(Kr,M("quic-v1"),G(X())),Hh=St(hs,Zn),Ux=tt(hs),Ox=tt(Zn),cs=St(le,fs,Kr,hs,Zn),Hc=St(K(cs,M("ws"),G(X()))),Mx=tt(Hc),Gc=St(K(cs,M("wss"),G(X())),K(cs,M("tls"),G(K(M("sni"),ke())),M("ws"),G(X()))),kx=tt(Gc),Wc=K(Kr,M("webrtc-direct"),G(kr()),G(kr()),G(X())),Kx=tt(Wc),Zc=K(Zn,M("webtransport"),G(kr()),G(kr()),G(X())),qx=tt(Zc),Vn=St(Hc,Gc,K(fs,G(X())),K(Hh,G(X())),K(le,G(X())),Wc,Zc,X()),$c=tt(Vn),Gh=K(Vn,M("p2p-circuit"),X()),$n=tt(Gh),Wh=St(K(Vn,M("p2p-circuit"),M("webrtc"),G(X())),K(Vn,M("webrtc"),G(X())),K(M("webrtc"),G(X()))),Fx=tt(Wh),Zh=St(K(le,M("tcp"),Mr(),M("http"),G(X())),K(le,M("http"),G(X()))),zx=tt(Zh),$h=St(K(le,M("tcp"),St(K(M("443"),M("http")),K(Mr(),M("https"))),G(X())),K(le,M("tls"),M("http"),G(X())),K(le,M("https"),G(X()))),Vx=tt($h),Yh=St(K(M("memory"),ke(),G(X()))),Hx=tt(Yh);function Yn(r){let t=new globalThis.AbortController;function e(){t.abort();for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",e)}for(let i of r){if(i?.aborted===!0){e();break}i?.addEventListener!=null&&i.addEventListener("abort",e)}function n(){for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",e)}let o=t.signal;return o.clear=n,o}var Xn=class extends Error{constructor(t="Transfer limit error"){super(t),this.name="TransferLimitError"}},qr=class extends Error{constructor(t="Duration limit error"){super(t),this.name="DurationLimitError"}},Fr=class extends Error{static name="HadEnoughRelaysError";name="HadEnoughRelaysError"},Qn=class extends Error{static name="DoubleRelayError";name="DoubleRelayError"},jn=class extends Error{static name="RelayQueueFullError";name="RelayQueueFullError"};async function*Yc(r,t,e){let n=t.remaining;for await(let o of r){let i=BigInt(o.byteLength);if(t.remaining-i<0){let s=Number(t.remaining);t.remaining=0n;try{s!==0&&(yield o.subarray(0,s))}catch(a){e.log.error(a)}throw new Xn(`data limit of ${n} bytes exceeded`)}t.remaining-=i,yield o}}function Xc(r,t,e,n,o){function i(f){r.abort(f),t.abort(f)}let s=[e,n.signal];n.limit?.duration!=null&&(o.log("limiting relayed connection duration to %dms",n.limit.duration),s.push(AbortSignal.timeout(n.limit.duration)));let a=Yn(s),c=!1,l=!1,u;n.limit?.data!=null&&(u={remaining:n.limit.data}),queueMicrotask(()=>{let f=()=>{o.log("relayed connection reached time limit"),t.abort(new qr(`duration limit of ${n.limit?.duration} ms exceeded`))};a.addEventListener("abort",f,{once:!0}),t.sink(u==null?r.source:Yc(r.source,u,o)).catch(d=>{o.log.error("error while relaying streams src -> dst",d),i(d)}).finally(()=>{c=!0,l&&(a.removeEventListener("abort",f),a.clear())})}),queueMicrotask(()=>{let f=()=>{o.log("relayed connection reached time limit"),r.abort(new qr(`duration limit of ${n.limit?.duration} ms exceeded`))};a.addEventListener("abort",f,{once:!0}),r.sink(u==null?t.source:Yc(t.source,u,o)).catch(d=>{o.log.error("error while relaying streams dst -> src",d),i(d)}).finally(()=>{l=!0,c&&(a.removeEventListener("abort",f),a.clear())})})}function ds(r){let t=r*BigInt(1e3),e=new Date().getTime();return Number(t-BigInt(e))}var zr=class{expires;bytes;constructor(t){t?.duration!=null&&t?.duration!==0&&(this.expires=Date.now()+t.duration*1e3),this.bytes=t?.data,this.bytes===0n&&(this.bytes=void 0),this.onData=this.onData.bind(this)}onData(t){this.bytes!=null&&(this.bytes-=BigInt(t.byteLength),this.bytes<0n&&(this.bytes=0n))}getLimits(){if(this.expires==null&&this.bytes==null)return;let t={};if(this.bytes!=null){let e=this;Object.defineProperty(t,"bytes",{get(){return e.bytes}})}if(this.expires!=null){let e=this;Object.defineProperty(t,"seconds",{get(){return Math.round(((e.expires??0)-Date.now())/1e3)}})}return t}},Jn=tt(K($c.matchers[0],M("p2p-circuit"))),to=tt(M("p2p-circuit"));function eo(r,t){let e={[Symbol.iterator]:()=>e,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:t(o)}}};return e}var Ae=class{map;constructor(t){if(this.map=new Map,t!=null)for(let[e,n]of t.entries())this.map.set(e.toString(),{key:e,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(t){return this.map.delete(t.toString())}entries(){return eo(this.map.entries(),t=>[t[1].key,t[1].value])}forEach(t){this.map.forEach((e,n)=>{t(e.value,e.key,this)})}get(t){return this.map.get(t.toString())?.value}has(t){return this.map.has(t.toString())}set(t,e){this.map.set(t.toString(),{key:t,value:e})}keys(){return eo(this.map.values(),t=>t.key)}values(){return eo(this.map.values(),t=>t.value)}get size(){return this.map.size}};var ps={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Qc={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},jc=new globalThis.TextEncoder;function Xh(r,t){let e=ps[t],n=Qc[t];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(t,n*e);return n}function Qh(r,t,e){if(e.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=ps[t],o=Qc[t],i=r;for(;i.length>0;){let s=jc.encodeInto(i,e);i=i.slice(s.read);for(let a=0;a<s.written;a++)o^=BigInt(e[a]),o=BigInt.asUintN(t,o*n)}return o}function ms(r,{size:t=32,utf8Buffer:e}={}){if(!ps[t])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(e)return Qh(r,t,e);r=jc.encode(r)}return Xh(r,t)}var Vr={hash:r=>Number(ms(r,{size:32})),hashV:(r,t)=>jh(Vr.hash(r,t))};function jh(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),z(t,"base16")}var ys=64,Zt=class{fp;h;seed;constructor(t,e,n,o=2){if(o>ys)throw new TypeError("Invalid Fingerprint Size");let i=e.hashV(t,n),s=it(o);for(let a=0;a<s.length;a++)s[a]=i[a];s.length===0&&(s[0]=7),this.fp=s,this.h=e,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(t){return t?.fp instanceof Uint8Array?pt(this.fp,t.fp):!1}};function Ke(r,t){return Math.floor(Math.random()*(t-r))+r}var qe=class{contents;constructor(t){this.contents=new Array(t).fill(null)}has(t){if(!(t instanceof Zt))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof Zt))throw new TypeError("Invalid Fingerprint");for(let e=0;e<this.contents.length;e++)if(this.contents[e]==null)return this.contents[e]=t,!0;return!0}swap(t){if(!(t instanceof Zt))throw new TypeError("Invalid Fingerprint");let e=Ke(0,this.contents.length-1),n=this.contents[e];return this.contents[e]=t,n}remove(t){if(!(t instanceof Zt))throw new TypeError("Invalid Fingerprint");let e=this.contents.findIndex(n=>t.equals(n));return e>-1?(this.contents[e]=null,!0):!1}};var Jh=500,Hr=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(t){this.filterSize=t.filterSize,this.bucketSize=t.bucketSize??4,this.fingerprintSize=t.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=t.hash??Vr,this.seed=t.seed??Ke(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=z(t));let e=new Zt(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=(n^e.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new qe(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new qe(this.bucketSize)),this.buckets[n].add(e)||this.buckets[o].add(e))return this.count++,!0;let i=[n,o],s=i[Ke(0,i.length-1)];this.buckets[s]==null&&(this.buckets[s]=new qe(this.bucketSize));for(let a=0;a<Jh;a++){let c=this.buckets[s].swap(e);if(c!=null&&(s=(s^c.hash())%this.filterSize,this.buckets[s]==null&&(this.buckets[s]=new qe(this.bucketSize)),this.buckets[s].add(c)))return this.count++,!0}return!1}has(t){typeof t=="string"&&(t=z(t));let e=new Zt(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=this.buckets[n]?.has(e)??!1;if(o)return o;let i=(n^e.hash())%this.filterSize;return this.buckets[i]?.has(e)??!1}remove(t){typeof t=="string"&&(t=z(t));let e=new Zt(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=this.buckets[n]?.remove(e)??!1;if(o)return this.count--,o;let i=(n^e.hash())%this.filterSize,s=this.buckets[i]?.remove(e)??!1;return s&&this.count--,s}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},td={1:.5,2:.84,4:.95,8:.98};function ed(r=.001){return r>.002?2:r>1e-5?4:8}function Jc(r,t=.001){let e=ed(t),n=td[e],o=Math.round(r/n),i=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),ys);return{filterSize:o,bucketSize:e,fingerprintSize:i}}var ro=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(t){this.bucketSize=t.bucketSize??4,this.filterSize=t.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=t.fingerprintSize??2,this.scale=t.scale??2,this.hash=t.hash??Vr,this.seed=t.seed??Ke(0,Math.pow(2,10)),this.filterSeries=[new Hr({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(t){if(typeof t=="string"&&(t=z(t)),this.has(t))return!0;let e=this.filterSeries.find(n=>n.reliable);if(e==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);e=new Hr({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(e)}return e.add(t)}has(t){typeof t=="string"&&(t=z(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].has(t))return!0;return!1}remove(t){typeof t=="string"&&(t=z(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].remove(t))return!0;return!1}get count(){return this.filterSeries.reduce((t,e)=>t+e.count,0)}};function ur(r,t=.001,e){return new ro({...Jc(r,t),...e??{}})}var no=class{filter;constructor(t,e){this.filter=ur(t,e)}has(t){return this.filter.has(t.toMultihash().bytes)}add(t){this.filter.add(t.toMultihash().bytes)}remove(t){this.filter.remove?.(t.toMultihash().bytes)}};function gs(r,t=.001){return new no(r,t)}var bs=class extends Ae{metric;constructor(t){super();let{name:e,metrics:n}=t;this.metric=n.registerMetric(e),this.updateComponentMetric()}set(t,e){return super.set(t,e),this.updateComponentMetric(),this}delete(t){let e=super.delete(t);return this.updateComponentMetric(),e}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function xs(r){let{name:t,metrics:e}=r,n;return e!=null?n=new bs({name:t,metrics:e}):n=new Ae,n}var ws=class extends Error{type;code;constructor(t,e,n){super(t??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=e??"ABORT_ERR"}};function tu(r,t){let e=new ws(t?.errorMessage,t?.errorCode,t?.errorName),n=new AbortController,o=()=>{n.abort(e)},i=AbortSignal.timeout(r);i.addEventListener("abort",o);let s=n.signal;return s.reset=a=>{i?.removeEventListener("abort",o),i=AbortSignal.timeout(a??r),i.addEventListener("abort",()=>{n.abort(e)})},s.clear=()=>{i?.removeEventListener("abort",o),i=void 0},s}var oo=class{reservations;maxReservations;applyDefaultLimit;reservationTtl;defaultDurationLimit;defaultDataLimit;log;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:circuit-relay:server:reservation-store"),this.maxReservations=e.maxReservations??Pc,this.applyDefaultLimit=e.applyDefaultLimit!==!1,this.reservationTtl=e.reservationTtl??Nc,this.defaultDurationLimit=e.defaultDurationLimit??Mc,this.defaultDataLimit=e.defaultDataLimit??kc,this.reservations=xs({metrics:t.metrics,name:"libp2p_circuit_relay_server_reservations_total"})}reserve(t,e,n){let o=this.reservations.get(t);if(this.reservations.size>=this.maxReservations&&o==null)return{status:k.RESERVATION_REFUSED};let i=new Date(Date.now()+this.reservationTtl),s;return this.applyDefaultLimit&&(s=n??{data:this.defaultDataLimit,duration:this.defaultDurationLimit}),o!=null?(this.log("refreshing reservation for client %p",t),o.signal.reset(this.reservationTtl)):(this.log("creating new reservation for client %p",t),o={addr:e,expiry:i,limit:s,signal:tu(this.reservationTtl)}),this.reservations.set(t,o),o.signal.addEventListener("abort",()=>{this.reservations.delete(t)}),{status:k.OK,expire:Math.round(i.getTime()/1e3)}}removeReservation(t){this.reservations.delete(t)}get(t){return this.reservations.get(t)}clear(){this.reservations.clear()}};var io=class r{domain="libp2p-relay-rsvp";codec=new Uint8Array([3,2]);relay;peer;expiration;constructor({relay:t,peer:e,expiration:n}){this.relay=t,this.peer=e,this.expiration=n}marshal(){return ar.encode({relay:this.relay.toMultihash().bytes,peer:this.peer.toMultihash().bytes,expiration:BigInt(this.expiration)})}equals(t){return!(!(t instanceof r)||!this.peer.equals(t.peer)||!this.relay.equals(t.relay)||this.expiration!==t.expiration)}};var eu=r=>r.protoCodes().includes(Kn),rd={maxOutboundStopStreams:Or},Es=class extends Ot{registrar;peerStore;addressManager;peerId;privateKey;connectionManager;connectionGater;reservationStore;started;hopTimeout;shutdownController;maxInboundHopStreams;maxOutboundHopStreams;maxOutboundStopStreams;log;constructor(t,e={}){super(),this.log=t.logger.forComponent("libp2p:circuit-relay:server"),this.registrar=t.registrar,this.peerStore=t.peerStore,this.addressManager=t.addressManager,this.peerId=t.peerId,this.privateKey=t.privateKey,this.connectionManager=t.connectionManager,this.connectionGater=t.connectionGater,this.started=!1,this.hopTimeout=e?.hopTimeout??Kc,this.maxInboundHopStreams=e.maxInboundHopStreams,this.maxOutboundHopStreams=e.maxOutboundHopStreams,this.maxOutboundStopStreams=e.maxOutboundStopStreams??rd.maxOutboundStopStreams,this.reservationStore=new oo(t,e.reservations),this.shutdownController=new AbortController,this.shutdownController.signal}[Symbol.toStringTag]="@libp2p/circuit-relay-v2-server";isStarted(){return this.started}async start(){this.started||(await this.registrar.handle(qt,t=>{this.onHop(t).catch(e=>{this.log.error(e)})},{maxInboundStreams:this.maxInboundHopStreams,maxOutboundStreams:this.maxOutboundHopStreams,runOnLimitedConnection:!0}),this.started=!0)}async stop(){this.reservationStore.clear(),this.shutdownController.abort(),await this.registrar.unhandle(qt),this.started=!1}async onHop({connection:t,stream:e}){this.log("received circuit v2 hop protocol stream from %p",t.remotePeer);let n={signal:AbortSignal.timeout(this.hopTimeout)},o=Se(e);try{let i=await o.pb($).read(n);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},n)}catch(i){this.log.error("error while handling hop",i),await o.pb($).write({type:$.Type.STATUS,status:k.MALFORMED_MESSAGE},n),e.abort(i)}}async handleHopProtocol({stream:t,request:e,connection:n},o){switch(this.log("received hop message"),e.type){case $.Type.RESERVE:await this.handleReserve({stream:t,request:e,connection:n},o);break;case $.Type.CONNECT:await this.handleConnect({stream:t,request:e,connection:n},o);break;default:this.log.error("invalid hop request type %s via peer %p",e.type,n.remotePeer),await t.pb($).write({type:$.Type.STATUS,status:k.UNEXPECTED_MESSAGE})}}async handleReserve({stream:t,connection:e},n){let o=t.pb($);if(this.log("hop reserve request from %p",e.remotePeer),eu(e.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",e.remotePeer),await o.write({type:$.Type.STATUS,status:k.PERMISSION_DENIED},n);return}if(await this.connectionGater.denyInboundRelayReservation?.(e.remotePeer)===!0){this.log.error("reservation for %p denied by connection gater",e.remotePeer),await o.write({type:$.Type.STATUS,status:k.PERMISSION_DENIED},n);return}let i=this.reservationStore.reserve(e.remotePeer,e.remoteAddr);try{if(i.status!==k.OK){await o.write({type:$.Type.STATUS,status:i.status},n);return}if(i.expire!=null){let s=i.expire*1e3-Date.now();await this.peerStore.merge(e.remotePeer,{tags:{[is]:{value:1,ttl:s},[ss]:{value:1,ttl:s}}})}await o.write({type:$.Type.STATUS,status:k.OK,reservation:await this.makeReservation(e.remotePeer,BigInt(i.expire??0)),limit:this.reservationStore.get(e.remotePeer)?.limit},n),this.log("sent confirmation response to %s",e.remotePeer)}catch(s){this.log.error("failed to send confirmation response to %p - %e",e.remotePeer,s),this.reservationStore.removeReservation(e.remotePeer);try{await this.peerStore.merge(e.remotePeer,{tags:{[is]:void 0,[ss]:void 0}})}catch(a){this.log.error("failed to untag relay source peer %p - %e",e.remotePeer,a)}}}async makeReservation(t,e){let n=[];for(let i of this.addressManager.getAddresses())i.toString().includes("/p2p-circuit")||n.push(i.bytes);let o=await Nr.seal(new io({peer:t,relay:this.peerId,expiration:e}),this.privateKey);return{addrs:n,expire:e,voucher:{publicKey:be(o.publicKey),payloadType:o.payloadType,payload:{peer:t.toMultihash().bytes,relay:this.peerId.toMultihash().bytes,expiration:e},signature:o.signature}}}async handleConnect({stream:t,request:e,connection:n},o){let i=t.pb($);if(eu(n.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",n.remotePeer),await i.write({type:$.Type.STATUS,status:k.PERMISSION_DENIED},o);return}this.log("hop connect request from %p",n.remotePeer);let s;try{if(e.peer==null)throw this.log.error("no peer info in hop connect request"),new Error("no peer info in request");e.peer.addrs.forEach(vt),s=rr(Mt(e.peer.id))}catch(d){this.log.error("invalid hop connect request via peer %p %s",n.remotePeer,d),await i.write({type:$.Type.STATUS,status:k.MALFORMED_MESSAGE},o);return}let a=this.reservationStore.get(s);if(a==null){this.log.error("hop connect denied for destination peer %p not having a reservation for %p with status %s",s,n.remotePeer,k.NO_RESERVATION),await i.write({type:$.Type.STATUS,status:k.NO_RESERVATION},o);return}if(await this.connectionGater.denyOutboundRelayedConnection?.(n.remotePeer,s)===!0){this.log.error("hop connect for %p to %p denied by connection gater",n.remotePeer,s),await i.write({type:$.Type.STATUS,status:k.PERMISSION_DENIED},o);return}let c=this.connectionManager.getConnections(s);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",s,n.remotePeer),await i.write({type:$.Type.STATUS,status:k.NO_RESERVATION},o);return}let l=c[0],u=await this.stopHop({connection:l,request:{type:Ut.Type.CONNECT,peer:{id:n.remotePeer.toMultihash().bytes,addrs:[]},limit:a?.limit}},o);if(u==null){this.log.error("failed to open stream to destination peer %p",l?.remotePeer),await i.write({type:$.Type.STATUS,status:k.CONNECTION_FAILED},o);return}await i.write({type:$.Type.STATUS,status:k.OK,limit:a?.limit},o);let f=t.unwrap();this.log("connection from %p to %p established - merging streams",n.remotePeer,s),Xc(f,u,this.shutdownController.signal,a,{log:this.log})}async stopHop({connection:t,request:e},n){this.log("starting circuit relay v2 stop request to %s",t.remotePeer);let o=await t.newStream([Me],{maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0,...n}),i=Se(o),s=i.pb(Ut);await s.write(e,n);let a;try{a=await s.read(n)}catch{this.log.error("error parsing stop message response from %p",t.remotePeer)}if(a==null){this.log.error("could not read response from %p",t.remotePeer),await o.close(n);return}if(a.status===k.OK)return this.log("stop request to %p was successful",t.remotePeer),i.unwrap();this.log("stop request failed with code %d",a.status),await o.close(n)}get reservations(){return this.reservationStore.reservations}};function ru(r={}){return t=>new Es(t,r)}function nd(r){let[t,e]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>t.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:t.next(),[e](){return this}}}var nu=nd;function od(r){return r[Symbol.asyncIterator]!=null}function ou(r){return r?.then!=null}function id(r,t){let e=0;if(od(r))return async function*(){for await(let c of r){let l=t(c,e++);ou(l)&&await l,yield c}}();let n=nu(r),{value:o,done:i}=n.next();if(i===!0)return function*(){}();if(typeof t(o,e++)?.then=="function")return async function*(){yield o;for await(let c of n){let l=t(c,e++);ou(l)&&await l,yield c}}();let a=t;return function*(){yield o;for(let c of n)a(c,e++),yield c}()}var iu=id;var ao=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||(t-1&t)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},lr=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new ao(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){let e=this.head;this.head=e.next=new ao(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let e=this.tail.next;this.tail.next=null,this.tail=e,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var vs=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function fr(r={}){return sd(e=>{let n=e.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function sd(r,t){t=t??{};let e=t.onEnd,n=new lr,o,i,s,a=Wt(),c=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((h,w)=>{i=v=>{i=null,n.push(v);try{h(r(n))}catch(m){w(m)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Wt()})}},l=h=>i!=null?i(h):(n.push(h),o),u=h=>(n=new lr,i!=null?i({error:h}):(n.push({error:h}),o)),f=h=>{if(s)return o;if(t?.objectMode!==!0&&h?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:h})},d=h=>s?o:(s=!0,h!=null?u(h):l({done:!0})),g=()=>(n=new lr,d(),{done:!0}),y=h=>(d(h),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:g,throw:y,push:f,end:d,get readableLength(){return n.size},onEmpty:async h=>{let w=h?.signal;if(w?.throwIfAborted(),n.isEmpty())return;let v,m;w!=null&&(v=new Promise((_,B)=>{m=()=>{B(new vs)},w.addEventListener("abort",m)}));try{await Promise.race([a.promise,v])}finally{m!=null&&w!=null&&w?.removeEventListener("abort",m)}}},e==null)return o;let b=o;return o={[Symbol.asyncIterator](){return this},next(){return b.next()},throw(h){return b.throw(h),e!=null&&(e(h),e=void 0),{done:!0}},return(){return b.return(),e!=null&&(e(),e=void 0),{done:!0}},push:f,end(h){return b.end(h),e!=null&&(e(h),e=void 0),o},get readableLength(){return b.readableLength},onEmpty:h=>b.onEmpty(h)},o}function ad(r){return r[Symbol.asyncIterator]!=null}async function cd(r,t){try{await Promise.all(r.map(async e=>{for await(let n of e)t.push(n)})),t.end()}catch(e){t.end(e)}}async function*ud(r){let t=fr({objectMode:!0});cd(r,t).catch(()=>{}),yield*t}function*ld(r){for(let t of r)yield*t}function fd(...r){let t=[];for(let e of r)ad(e)||t.push(e);return t.length===r.length?ld(t):ud(r)}var su=fd;function au(r,...t){if(r==null)throw new Error("Empty pipeline");if(Ss(r)){let n=r;r=()=>n.source}else if(uu(r)||cu(r)){let n=r;r=()=>n}let e=[r,...t];if(e.length>1&&Ss(e[e.length-1])&&(e[e.length-1]=e[e.length-1].sink),e.length>2)for(let n=1;n<e.length-1;n++)Ss(e[n])&&(e[n]=dd(e[n]));return hd(...e)}var hd=(...r)=>{let t;for(;r.length>0;)t=r.shift()(t);return t},cu=r=>r?.[Symbol.asyncIterator]!=null,uu=r=>r?.[Symbol.iterator]!=null,Ss=r=>r==null?!1:r.sink!=null&&r.source!=null,dd=r=>t=>{let e=r.sink(t);if(e?.then!=null){let n=fr({objectMode:!0});e.then(()=>{n.end()},s=>{n.end(s)});let o,i=r.source;if(cu(i))o=async function*(){yield*i,n.end()};else if(uu(i))o=function*(){yield*i,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return su(n,o())}return r.source};function As(r){let{stream:t,remoteAddr:e,logger:n,onDataRead:o,onDataWrite:i}=r,s=n.forComponent("libp2p:stream:converter"),a=!1,c=!1,l=t.close.bind(t);t.close=async y=>{await l(y),g(!0)};let u=t.abort.bind(t);t.abort=y=>{u(y),g(!0)};let f=t.sink.bind(t);t.sink=async y=>{try{await f(au(y,b=>iu(b,h=>i?.(h))))}catch(b){b.type!=="aborted"&&s.error("%s error in sink",e,b)}finally{c=!0,g()}};let d={log:s,sink:t.sink,source:async function*(){try{for await(let y of t.source)o?.(y),yield y}finally{a=!0,g()}}(),remoteAddr:e,timeline:{open:Date.now(),close:void 0},close:t.close,abort:t.abort};function g(y){y===!0&&(a=!0,c=!0),a&&c&&d.timeline.close==null&&(d.timeline.close=Date.now())}return d}var _e=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var _s=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=e??"ABORT_ERR"}};async function co(r,t,e,n){let o=new _s(n?.errorMessage,n?.errorCode);return e?.aborted===!0?Promise.reject(o):new Promise((i,s)=>{function a(){e?.removeEventListener("abort",u),r.removeEventListener(t,c),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,l)}let c=f=>{try{if(n?.filter?.(f)===!1)return}catch(d){a(),s(d);return}a(),i(f)},l=f=>{a(),s(f.detail)},u=()=>{a(),s(o)};e?.addEventListener("abort",u),r.addEventListener(t,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,l)})}var uo=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};var lo=class{deferred;signal;constructor(t){this.signal=t,this.deferred=Wt(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Jt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function pd(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var fo=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=pd(),this.status="queued",this.fn=t,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(t){this.controller.abort(t)}onAbort(){this.recipients.reduce((e,n)=>e&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Jt),this.cleanup())}async join(t={}){let e=new lo(t.signal);return this.recipients.push(e),t.signal?.addEventListener("abort",this.onAbort),e.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let t=await Nn(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(e=>{e.deferred.resolve(t)}),this.status="complete"}catch(t){this.recipients.forEach(e=>{e.deferred.reject(t)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(t=>{t.cleanup(),t.signal?.removeEventListener("abort",this.onAbort)})}};var ho=class extends Ot{concurrency;maxSize;queue;pending;sort;constructor(t={}){super(),this.concurrency=t.concurrency??Number.POSITIVE_INFINITY,this.maxSize=t.maxSize??Number.POSITIVE_INFINITY,this.pending=0,t.metricName!=null&&t.metrics?.registerMetricGroup(t.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=t.sort,this.queue=[]}tryToStartAnother(){if(this.size===0)return queueMicrotask(()=>{this.safeDispatchEvent("empty")}),this.running===0&&queueMicrotask(()=>{this.safeDispatchEvent("idle")}),!1;if(this.pending<this.concurrency){let t;for(let e of this.queue)if(e.status==="queued"){t=e;break}return t==null?!1:(this.safeDispatchEvent("active"),this.pending++,t.run().finally(()=>{for(let e=0;e<this.queue.length;e++)if(this.queue[e]===t){this.queue.splice(e,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(t){this.queue.push(t),this.sort!=null&&this.queue.sort(this.sort)}async add(t,e){if(e?.signal?.throwIfAborted(),this.size===this.maxSize)throw new uo;let n=new fo(t,e);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(e).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("error",{detail:o}),this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(t=>{t.abort(new Jt)}),this.clear()}async onEmpty(t){this.size!==0&&await co(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await co(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await co(this,"idle",t?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(t){t?.signal?.throwIfAborted();let e=fr({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),e.end(c)},o=c=>{c.detail!=null&&e.push(c.detail)},i=c=>{n(c.detail)},s=()=>{n()},a=()=>{n(new Jt("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("error",i),this.addEventListener("idle",s),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("completed",o),this.removeEventListener("error",i),this.removeEventListener("idle",s),t?.signal?.removeEventListener("abort",a),n()}}};var hr=class extends ho{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};var po=class extends Ot{peerStore;registrar;connectionManager;randomWalk;started;running;topologyId;log;discoveryController;filter;queue;constructor(t,e={}){super(),this.log=t.logger.forComponent("libp2p:circuit-relay:discover-relays"),this.started=!1,this.running=!1,this.peerStore=t.peerStore,this.registrar=t.registrar,this.connectionManager=t.connectionManager,this.randomWalk=t.randomWalk,this.filter=e.filter,this.discoveryController=new AbortController,this.discoveryController.signal}isStarted(){return this.started}async start(){this.topologyId=await this.registrar.register(qt,{filter:this.filter,onConnect:t=>{this.log.trace("discovered relay %p queue (length: %d, active %d)",t,this.queue?.size,this.queue?.running),this.safeDispatchEvent("relay:discover",{detail:t})}}),this.started=!0}stop(){this.topologyId!=null&&this.registrar.unregister(this.topologyId),this.discoveryController?.abort(),this.started=!1}startDiscovery(){this.running||(this.log("start discovery"),this.running=!0,this.discoveryController=new AbortController,this.discoveryController.signal,Promise.resolve().then(async()=>{this.log("searching peer store for relays");let t=await this.peerStore.all({filters:[n=>n.protocols.includes(qt)],orders:[()=>Math.random()<.5?1:-1,(n,o)=>{let i=lu(n),s=lu(o);return i>s?-1:s>i?1:0}]});for(let n of t)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",t.length);let e=this.queue=new hr({concurrency:5});this.log("start random walk");for await(let n of this.randomWalk.walk({signal:this.discoveryController.signal})){if(this.log.trace("found random peer %p",n.id),e.has(n.id)){this.log.trace("random peer %p was already in queue",n.id);continue}if(this.connectionManager.getConnections(n.id)?.length>0){this.log.trace("random peer %p was already connected",n.id);continue}if(!await this.connectionManager.isDialable(n.multiaddrs)){this.log.trace("random peer %p was not dialable",n.id,n.multiaddrs.map(o=>o.toString()));continue}e.queued>10&&(this.log.trace("wait for space in queue for %p",n.id),await e.onSizeLessThan(10,{signal:this.discoveryController.signal})),this.log("adding random peer %p to dial queue (length: %d, active %d)",n.id,e.size,e.running),e.add(async()=>{let o=Yn([this.discoveryController.signal,AbortSignal.timeout(5e3)]);try{await this.connectionManager.openConnection(n.id,{signal:o})}finally{o.clear()}},{peerId:n.id,signal:this.discoveryController.signal}).catch(o=>{this.log.error("error opening connection to random peer %p",n.id,o)})}this.log("stop random walk"),await e.onIdle()}).catch(t=>{this.discoveryController.signal.aborted||this.log.error("failed when finding relays on the network",t)}))}stopDiscovery(){this.log("stop discovery"),this.running=!1,this.discoveryController?.abort()}};function lu(r){let t=r.metadata.get("last-dial-success");return t==null?0:new Date(V(t)).getTime()}var Is=class extends Ot{connectionManager;addressManager;reservationStore;listeningAddrs;log;listenTimeout;reservationId;relay;constructor(t,e={}){super(),this.log=t.logger.forComponent("libp2p:circuit-relay:transport:listener"),this.connectionManager=t.connectionManager,this.addressManager=t.addressManager,this.reservationStore=t.reservationStore,this.listeningAddrs=[],this.listenTimeout=e.listenTimeout??qn,this.reservationStore.addEventListener("relay:removed",this._onRemoveRelayPeer),this.reservationStore.addEventListener("relay:created-reservation",this._onAddRelayPeer)}_onRemoveRelayPeer=t=>{this.log("relay removed %p our relay %p",t.detail.relay,this.relay,this.relay?.equals(t.detail.relay)),this.relay?.equals(t.detail.relay)===!0&&(this.log("relay peer removed %p",t.detail.relay),this.listeningAddrs.forEach(e=>{this.addressManager.removeObservedAddr(e)}),this.listeningAddrs=[],this.safeDispatchEvent("listening"))};_onAddRelayPeer=t=>{let{details:e}=t.detail;e.type!=="configured"&&e.id===this.reservationId&&this.addedRelay(t.detail)};async listen(t){if(to.exactMatch(t))this.log("searching for circuit relay servers"),this.reservationId=this.reservationStore.reserveRelay();else if(Jn.exactMatch(t)){this.log("listen on specific relay server %a",t);let e=AbortSignal.timeout(this.listenTimeout);let n=t.decapsulate("/p2p-circuit"),o=await this.connectionManager.openConnection(n,{signal:e});if(!this.reservationStore.hasReservation(o.remotePeer)){this.log("making reservation on peer %p",o.remotePeer);let i=await this.reservationStore.addRelay(o.remotePeer,"configured");this.addedRelay(i)}}else throw new Ie(`Could not listen on p2p-circuit address "${t}"`)}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(t){this.log("relay peer added %p",t.relay),this.relay=t.relay,this.listeningAddrs=t.details.reservation.addrs.map(e=>vt(e).encapsulate("/p2p-circuit")),this.listeningAddrs.forEach(e=>{this.addressManager.confirmObservedAddr(e,{type:"transport"})}),queueMicrotask(()=>{this.safeDispatchEvent("listening")})}};function fu(r){return new Is(r)}var hu="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var du=(r=21)=>{let t="",e=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)t+=hu[e[r]&63];return t};var md=60*1e3*10,yd=60*1e3*5,gd=30*1e3,mo=class extends Ot{peerId;connectionManager;peerStore;events;reserveQueue;reservations;pendingReservations;maxReservationQueueLength;reservationCompletionTimeout;started;log;relayFilter;constructor(t,e){super(),this.log=t.logger.forComponent("libp2p:circuit-relay:transport:reservation-store"),this.peerId=t.peerId,this.connectionManager=t.connectionManager,this.peerStore=t.peerStore,this.events=t.events,this.reservations=new Ae,this.pendingReservations=[],this.maxReservationQueueLength=e?.maxReservationQueueLength??Oc,this.reservationCompletionTimeout=e?.reservationCompletionTimeout??qn,this.started=!1,this.relayFilter=ur(100),this.reserveQueue=new hr({concurrency:e?.reservationConcurrency??Uc,metricName:"libp2p_relay_reservation_queue",metrics:t.metrics}),this.events.addEventListener("connection:close",n=>{[...this.reservations.values()].find(i=>i.connection===n.detail.id)!=null&&this.#e(n.detail.remotePeer).catch(i=>{this.log("could not remove relay %p - %e",n.detail,i)})})}isStarted(){return this.started}start(){this.started=!0}afterStart(){Promise.resolve().then(async()=>{let t=await this.peerStore.all({filters:[e=>e.tags.has(Ur)]});this.log("removing tag from %d old relays",t.length),await Promise.all(t.map(async e=>{await this.peerStore.merge(e.id,{tags:{[Ur]:void 0}})})),this.log("redialing %d old relays",t.length),await Promise.all(t.map(async e=>this.addRelay(e.id,"discovered"))),this.#r()}).catch(t=>{this.log.error(t)})}stop(){this.reserveQueue.clear(),this.reservations.forEach(({timeout:t})=>{clearTimeout(t)}),this.reservations.clear(),this.started=!1}reserveRelay(){let t=du();return this.pendingReservations.push(t),this.#r(),t}async addRelay(t,e){if(this.peerId.equals(t))throw this.log.trace("not trying to use self as relay"),new Ie("Cannot use self as relay");if(this.reserveQueue.size>this.maxReservationQueueLength)throw new jn("The reservation queue is full");let n=this.reserveQueue.find(t);if(n!=null)return this.log.trace("potential relay peer %p is already in the reservation queue",t),n.join();if(this.relayFilter.has(t.toMultihash().bytes))throw new Ie("The relay was previously invalid");return this.log.trace("try to reserve relay slot with %p",t),this.reserveQueue.add(async()=>{let o=Date.now();try{let i=this.reservations.get(t);if(i!=null){let y=this.connectionManager.getConnections(t),b=!1;if(y.length===0&&this.log("already have relay reservation with %p but we are no longer connected",t),y.map(h=>h.id).includes(i.connection)&&(this.log("already have relay reservation with %p and the original connection is still open",t),b=!0),b&&ds(i.reservation.expire)>md)return this.log("already have relay reservation with %p but we are still connected and it does not expire soon",t),{relay:t,details:i};await this.#e(t)}if(e==="discovered"&&this.pendingReservations.length===0)throw new Fr("Not making reservation on discovered relay because we do not need any more relays");let s=AbortSignal.timeout(this.reservationCompletionTimeout);let a=await this.connectionManager.openConnection(t,{signal:s});if($n.matches(a.remoteAddr))throw new Qn("not creating reservation over relayed connection");let c=await this.#t(a,{signal:s}),l=ds(c.expire);this.log("created reservation on relay peer %p, expiry date is %s",t,new Date(Date.now()+l).toString());let u=Math.min(Math.max(l-yd,gd),Math.pow(2,31)-1),f=setTimeout(()=>{this.log("refresh reservation to relay %p",t),this.addRelay(t,e).catch(async y=>{this.log.error("could not refresh reservation to relay %p - %e",t,y),await this.#e(t)}).catch(y=>{this.log.error("could not remove expired reservation to relay %p - %e",t,y)})},u),d;if(e==="discovered"){let y=this.pendingReservations.pop();if(y==null)throw new Fr("Made reservation on relay but did not need any more discovered relays");d={timeout:f,reservation:c,type:e,connection:a.id,id:y}}else d={timeout:f,reservation:c,type:e,connection:a.id};this.reservations.set(t,d),await this.peerStore.merge(t,{tags:{[Ur]:{value:1,ttl:l}}}),this.#r();let g={relay:t,details:d};return this.safeDispatchEvent("relay:created-reservation",{detail:g}),g}catch(i){throw e==="discovered"&&i.name==="HadEnoughRelaysError"||this.log.error("could not reserve slot on %p after %dms - %e",t,Date.now()-o,i),(i.name==="DialError"||i.name==="UnsupportedProtocolError")&&this.relayFilter.add(t.toMultihash().bytes),this.#e(t).catch(s=>{this.log.error("could not remove reservation on %p after reserving slot failed - %e",t,s)}),i}},{peerId:t})}hasReservation(t){return this.reservations.has(t)}getReservation(t){return this.reservations.get(t)?.reservation}reservationCount(t){return t==null?this.reservations.size:[...this.reservations.values()].reduce((e,n)=>(n.type===t&&e++,e),0)}cancelReservations(){[...this.reservations.values()].forEach(t=>{clearTimeout(t.timeout)}),this.reservations.clear()}async#t(t,e){e.signal?.throwIfAborted(),this.log("requesting reservation from %p",t.remotePeer);let n=await t.newStream(qt,e),i=Se(n).pb($);this.log.trace("send RESERVE to %p",t.remotePeer),await i.write({type:$.Type.RESERVE},e);let s;try{this.log.trace("reading response from %p",t.remotePeer),s=await i.read(e)}catch(c){throw n.abort(c),c}finally{n.status!=="closed"&&await n.close(e)}if(this.log.trace("read response %o",s),s.status===k.OK&&s.reservation!=null){let c=new Set;c.add(t.remoteAddr.toString());for(let l of s.reservation.addrs){let u=vt(l);u.getPeerId()==null&&(u=u.encapsulate(`/p2p/${t.remotePeer}`)),u=vt(u.toString().replace(`/p2p/${t.remotePeer}/p2p/${t.remotePeer}`,`/p2p/${t.remotePeer}`)),c.add(u.toString())}return s.reservation.addrs=[...c].map(l=>vt(l).bytes),s.reservation}let a=`reservation failed with status ${s.status??"undefined"}`;throw this.log.error(a),new Error(a)}async#e(t){let e=this.reservations.get(t);e!=null&&(this.log("removing relay reservation with %p from local store",t),clearTimeout(e.timeout),this.reservations.delete(t),e.type==="discovered"&&this.pendingReservations.push(e.id),await this.peerStore.merge(t,{tags:{[Ur]:void 0}}),this.safeDispatchEvent("relay:removed",{detail:{relay:t,details:e}}),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=ur(100),this.log("not discovered enough relays %d/%d",this.reservations.size,this.pendingReservations.length),this.safeDispatchEvent("relay:not-enough-relays")}};var bd=r=>{if(r.peer==null)return!1;try{r.peer.addrs.forEach(vt)}catch{return!1}return!0},pu={maxInboundStopStreams:Or,maxOutboundStopStreams:Or,stopTimeout:3e4},yo=class{discovery;registrar;peerStore;connectionManager;transportManager;peerId;upgrader;addressManager;connectionGater;reservationStore;logger;maxInboundStopStreams;maxOutboundStopStreams;started;log;shutdownController;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:circuit-relay:transport"),this.registrar=t.registrar,this.peerStore=t.peerStore,this.connectionManager=t.connectionManager,this.transportManager=t.transportManager,this.logger=t.logger,this.peerId=t.peerId,this.upgrader=t.upgrader,this.addressManager=t.addressManager,this.connectionGater=t.connectionGater,this.maxInboundStopStreams=e.maxInboundStopStreams??pu.maxInboundStopStreams,this.maxOutboundStopStreams=e.maxOutboundStopStreams??pu.maxOutboundStopStreams,this.shutdownController=new AbortController,this.discovery=new po(t,{filter:e.discoveryFilter??gs(qc,Fc)}),this.discovery.addEventListener("relay:discover",n=>{this.reservationStore.addRelay(n.detail,"discovered").catch(o=>{o.name!=="HadEnoughRelaysError"&&o.name!=="RelayQueueFullError"&&this.log.error("could not add discovered relay %p",n.detail,o)})}),this.reservationStore=new mo(t,e),this.reservationStore.addEventListener("relay:not-enough-relays",()=>{this.discovery?.startDiscovery()}),this.reservationStore.addEventListener("relay:found-enough-relays",()=>{this.discovery?.stopDiscovery()}),this.started=!1}[Symbol.toStringTag]="@libp2p/circuit-relay-v2-transport";[Ks]=["@libp2p/transport","@libp2p/circuit-relay-v2-transport"];get[qs](){return this.discovery!=null?["@libp2p/identify"]:[]}[Us]=!0;isStarted(){return this.started}async start(){this.shutdownController=new AbortController,await this.registrar.handle(Me,t=>{let e=this.upgrader.createInboundAbortSignal(this.shutdownController.signal);this.onStop(t,e).catch(n=>{this.log.error("error while handling STOP protocol",n),t.stream.abort(n)}).finally(()=>{e.clear()})},{maxInboundStreams:this.maxInboundStopStreams,maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0}),await Ms(this.discovery,this.reservationStore),this.started=!0}async stop(){this.shutdownController.abort(),await ks(this.discovery,this.reservationStore),await this.registrar.unhandle(Me),this.started=!1}async dial(t,e){if(t.protoCodes().filter(g=>g===Kn).length!==1){let g="Invalid circuit relay address";throw this.log.error(g,t),new pr(g)}let n=t.toString().split("/p2p-circuit"),o=vt(n[0]),i=vt(n[n.length-1]),s=o.getPeerId(),a=i.getPeerId();if(s==null||a==null){let g=`ircuit relay dial to ${t.toString()} failed as address did not have both relay and destination PeerIDs`;throw this.log.error(`c${g}`),new pr(`C${g}`)}let c=qi(s),l=qi(a),f=this.connectionManager.getConnections(c)[0];f==null?(await this.peerStore.merge(c,{multiaddrs:[o]}),e.onProgress?.(new _e("circuit-relay:open-connection")),f=await this.connectionManager.openConnection(c,e)):e.onProgress?.(new _e("circuit-relay:reuse-connection"));let d;try{e.onProgress?.(new _e("circuit-relay:open-hop-stream")),d=await f.newStream(qt,e);let g=Se(d),y=g.pb($);e.onProgress?.(new _e("circuit-relay:write-connect-message")),await y.write({type:$.Type.CONNECT,peer:{id:l.toMultihash().bytes,addrs:[vt(i).bytes]}},e),e.onProgress?.(new _e("circuit-relay:read-connect-response"));let b=await y.read(e);if(b.status!==k.OK)throw new Zr(`failed to connect via relay with status ${b?.status?.toString()??"undefined"}`);let h=new zr(b.limit),w=As({stream:g.unwrap(),remoteAddr:t,localAddr:o.encapsulate(`/p2p-circuit/p2p/${this.peerId.toString()}`),logger:this.logger,onDataRead:h.onData,onDataWrite:h.onData});return this.log("new outbound relayed connection %a",w.remoteAddr),await this.upgrader.upgradeOutbound(w,{...e,limits:h.getLimits()})}catch(g){throw this.log.error("circuit relay dial to destination %p via relay %p failed",l,c,g),d?.abort(g),g}}createListener(t){return fu({peerId:this.peerId,connectionManager:this.connectionManager,addressManager:this.addressManager,reservationStore:this.reservationStore,logger:this.logger})}listenFilter(t){return t=Array.isArray(t)?t:[t],t.filter(e=>Jn.exactMatch(e)||to.exactMatch(e))}dialFilter(t){return t=Array.isArray(t)?t:[t],t.filter(e=>$n.exactMatch(e))}async onStop({connection:t,stream:e},n){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.transportManager.listen([t.remoteAddr.encapsulate("/p2p-circuit")])}catch(f){this.log.error("failed to listen on a relay peer we were dialed via but did not have a reservation on",f)}let o=Se(e).pb(Ut),i=await o.read({signal:n});if(this.log("new circuit relay v2 stop stream from %p with type %s",t.remotePeer,i.type),i?.type===void 0){this.log.error("type was missing from circuit v2 stop protocol request from %s",t.remotePeer),await o.write({type:Ut.Type.STATUS,status:k.MALFORMED_MESSAGE},{signal:n}),await e.close();return}if(i.type!==Ut.Type.CONNECT){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await o.write({type:Ut.Type.STATUS,status:k.UNEXPECTED_MESSAGE},{signal:n}),await e.close();return}if(!bd(i)){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await o.write({type:Ut.Type.STATUS,status:k.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}let s=rr(Mt(i.peer.id));if(await this.connectionGater.denyInboundRelayedConnection?.(t.remotePeer,s)===!0){this.log.error("connection gater denied inbound relayed connection from %p",t.remotePeer),await o.write({type:Ut.Type.STATUS,status:k.PERMISSION_DENIED},{signal:n}),await e.close({signal:n});return}this.log.trace("sending success response to %p",t.remotePeer),await o.write({type:Ut.Type.STATUS,status:k.OK},{signal:n});let a=new zr(i.limit),c=t.remoteAddr.encapsulate(`/p2p-circuit/p2p/${s.toString()}`),l=this.addressManager.getAddresses()[0],u=As({stream:o.unwrap().unwrap(),remoteAddr:c,localAddr:l,logger:this.logger,onDataRead:a.onData,onDataWrite:a.onData});this.log("new inbound relayed connection %a",u.remoteAddr),await this.upgrader.upgradeInbound(u,{limits:a.getLimits(),signal:n}),this.log("%s connection %a upgraded","inbound",u.remoteAddr)}};function mu(r={}){return t=>new yo(t,r)}return Lu(xd);})();
2
+ "use strict";var Libp2PCircuitRelayV2=(()=>{var mo=Object.defineProperty;var vu=Object.getOwnPropertyDescriptor;var Au=Object.getOwnPropertyNames;var _u=Object.prototype.hasOwnProperty;var Tt=(r,t)=>{for(var e in t)mo(r,e,{get:t[e],enumerable:!0})},Iu=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Au(t))!_u.call(r,o)&&o!==e&&mo(r,o,{get:()=>t[o],enumerable:!(n=vu(t,o))||n.enumerable});return r};var Tu=r=>Iu(mo({},"__esModule",{value:!0}),r);var xd={};Tt(xd,{RELAY_V2_HOP_CODEC:()=>Ft,RELAY_V2_STOP_CODEC:()=>Me,circuitRelayServer:()=>iu,circuitRelayTransport:()=>bu});var yo=Symbol.for("@libp2p/peer-id");var go="keep-alive";var Ns=Symbol.for("@libp2p/transport");var Bs;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Bs||(Bs={}));var te=class extends Error{static name="AbortError";constructor(t="The operation was aborted"){super(t),this.name="AbortError"}};var ht=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},ze=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}};var $r=class extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}},Zr=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}};var Yr=class extends Error{static name="InvalidMessageError";constructor(t="Invalid message"){super(t),this.name="InvalidMessageError"}};var mr=class extends Error{static name="DialError";constructor(t="Dial error"){super(t),this.name="DialError"}},_e=class extends Error{static name="ListenError";constructor(t="Listen error"){super(t),this.name="ListenError"}};var He=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var Mt=class extends EventTarget{#t=new Map;constructor(){super()}listenerCount(t){let e=this.#t.get(t);return e==null?0:e.length}addEventListener(t,e,n){super.addEventListener(t,e,n);let o=this.#t.get(t);o==null&&(o=[],this.#t.set(t,o)),o.push({callback:e,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(t,e,n){super.removeEventListener(t.toString(),e??null,n);let o=this.#t.get(t);o!=null&&(o=o.filter(({callback:i})=>i!==e),this.#t.set(t,o))}dispatchEvent(t){let e=super.dispatchEvent(t),n=this.#t.get(t.type);return n==null||(n=n.filter(({once:o})=>!o),this.#t.set(t.type,n)),e}safeDispatchEvent(t,e={}){return this.dispatchEvent(new CustomEvent(t,e))}};function Us(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function Os(...r){let t=[];for(let e of r)Us(e)&&t.push(e);await Promise.all(t.map(async e=>{e.beforeStart!=null&&await e.beforeStart()})),await Promise.all(t.map(async e=>{await e.start()})),await Promise.all(t.map(async e=>{e.afterStart!=null&&await e.afterStart()}))}async function ks(...r){let t=[];for(let e of r)Us(e)&&t.push(e);await Promise.all(t.map(async e=>{e.beforeStop!=null&&await e.beforeStop()})),await Promise.all(t.map(async e=>{await e.stop()})),await Promise.all(t.map(async e=>{e.afterStop!=null&&await e.afterStop()}))}var Ms=Symbol.for("@libp2p/service-capabilities"),Ks=Symbol.for("@libp2p/service-dependencies");var So={};Tt(So,{base58btc:()=>Y,base58flickr:()=>Bu});var Yd=new Uint8Array(0);function qs(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function ee(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 Fs(r){return new TextEncoder().encode(r)}function zs(r){return new TextDecoder().decode(r)}function Lu(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var o=0;o<r.length;o++){var i=r.charAt(o),s=i.charCodeAt(0);if(e[s]!==255)throw new TypeError(i+" is ambiguous");e[s]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function f(b){if(b instanceof Uint8Array||(ArrayBuffer.isView(b)?b=new Uint8Array(b.buffer,b.byteOffset,b.byteLength):Array.isArray(b)&&(b=Uint8Array.from(b))),!(b instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(b.length===0)return"";for(var y=0,h=0,x=0,v=b.length;x!==v&&b[x]===0;)x++,y++;for(var p=(v-x)*u+1>>>0,_=new Uint8Array(p);x!==v;){for(var D=b[x],P=0,T=p-1;(D!==0||P<h)&&T!==-1;T--,P++)D+=256*_[T]>>>0,_[T]=D%a>>>0,D=D/a>>>0;if(D!==0)throw new Error("Non-zero carry");h=P,x++}for(var L=p-h;L!==p&&_[L]===0;)L++;for(var C=c.repeat(y);L<p;++L)C+=r.charAt(_[L]);return C}function d(b){if(typeof b!="string")throw new TypeError("Expected String");if(b.length===0)return new Uint8Array;var y=0;if(b[y]!==" "){for(var h=0,x=0;b[y]===c;)h++,y++;for(var v=(b.length-y)*l+1>>>0,p=new Uint8Array(v);b[y];){var _=e[b.charCodeAt(y)];if(_===255)return;for(var D=0,P=v-1;(_!==0||D<x)&&P!==-1;P--,D++)_+=a*p[P]>>>0,p[P]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");x=D,y++}if(b[y]!==" "){for(var T=v-x;T!==v&&p[T]===0;)T++;for(var L=new Uint8Array(h+(v-T)),C=h;T!==v;)L[C++]=p[T++];return L}}}function g(b){var y=d(b);if(y)return y;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:d,decode:g}}var Cu=Lu,Ru=Cu,Vs=Ru;var bo=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},xo=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){this.name=t,this.prefix=e;let o=e.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return Gs(this,t)}},wo=class{decoders;constructor(t){this.decoders=t}or(t){return Gs(this,t)}decode(t){let e=t[0],n=this.decoders[e];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Gs(r,t){return new wo({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var Eo=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,o){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=o,this.encoder=new bo(t,e,n),this.decoder=new xo(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Ve({name:r,prefix:t,encode:e,decode:n}){return new Eo(r,t,e,n)}function fe({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=Vs(e,r);return Ve({prefix:t,name:r,encode:n,decode:i=>ee(o(i))})}function Du(r,t,e,n){let o={};for(let u=0;u<t.length;++u)o[t[u]]=u;let i=r.length;for(;r[i-1]==="=";)--i;let s=new Uint8Array(i*e/8|0),a=0,c=0,l=0;for(let u=0;u<i;++u){let f=o[r[u]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<e|f,a+=e,a>=8&&(a-=8,s[l++]=255&c>>a)}if(a>=e||(255&c<<8-a)!==0)throw new SyntaxError("Unexpected end of data");return s}function Pu(r,t,e){let n=t[t.length-1]==="=",o=(1<<e)-1,i="",s=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],s+=8;s>e;)s-=e,i+=t[o&a>>s];if(s!==0&&(i+=t[o&a<<e-s]),n)for(;(i.length*e&7)!==0;)i+="=";return i}function st({name:r,prefix:t,bitsPerChar:e,alphabet:n}){return Ve({prefix:t,name:r,encode(o){return Pu(o,n,e)},decode(o){return Du(o,n,e,r)}})}var Y=fe({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Bu=fe({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var vo={};Tt(vo,{base32:()=>re,base32hex:()=>ku,base32hexpad:()=>Ku,base32hexpadupper:()=>qu,base32hexupper:()=>Mu,base32pad:()=>Uu,base32padupper:()=>Ou,base32upper:()=>Nu,base32z:()=>Fu});var re=st({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Nu=st({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Uu=st({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Ou=st({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),ku=st({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Mu=st({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Ku=st({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),qu=st({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Fu=st({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Ao={};Tt(Ao,{base36:()=>yr,base36upper:()=>zu});var yr=fe({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),zu=fe({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Hu=Zs,Ws=128,Vu=127,Gu=~Vu,Wu=Math.pow(2,31);function Zs(r,t,e){t=t||[],e=e||0;for(var n=e;r>=Wu;)t[e++]=r&255|Ws,r/=128;for(;r&Gu;)t[e++]=r&255|Ws,r>>>=7;return t[e]=r|0,Zs.bytes=e-n+1,t}var $u=_o,Zu=128,$s=127;function _o(r,n){var e=0,n=n||0,o=0,i=n,s,a=r.length;do{if(i>=a)throw _o.bytes=0,new RangeError("Could not decode varint");s=r[i++],e+=o<28?(s&$s)<<o:(s&$s)*Math.pow(2,o),o+=7}while(s>=Zu);return _o.bytes=i-n,e}var Yu=Math.pow(2,7),ju=Math.pow(2,14),Xu=Math.pow(2,21),Qu=Math.pow(2,28),Ju=Math.pow(2,35),tl=Math.pow(2,42),el=Math.pow(2,49),rl=Math.pow(2,56),nl=Math.pow(2,63),ol=function(r){return r<Yu?1:r<ju?2:r<Xu?3:r<Qu?4:r<Ju?5:r<tl?6:r<el?7:r<rl?8:r<nl?9:10},il={encode:Hu,decode:$u,encodingLength:ol},sl=il,gr=sl;function br(r,t=0){return[gr.decode(r,t),gr.decode.bytes]}function Ge(r,t,e=0){return gr.encode(r,t,e),t}function We(r){return gr.encodingLength(r)}function Ht(r,t){let e=t.byteLength,n=We(r),o=n+We(e),i=new Uint8Array(o+e);return Ge(r,i,0),Ge(e,i,n),i.set(t,o),new $e(r,e,t,i)}function Kt(r){let t=ee(r),[e,n]=br(t),[o,i]=br(t.subarray(n)),s=t.subarray(n+i);if(s.byteLength!==o)throw new Error("Incorrect length");return new $e(e,o,s,t)}function Ys(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&qs(r.bytes,e.bytes)}}var $e=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};function js(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return cl(e,Io(r),t??Y.encoder);default:return ul(e,Io(r),t??re.encoder)}}var Xs=new WeakMap;function Io(r){let t=Xs.get(r);if(t==null){let e=new Map;return Xs.set(r,e),e}return t}var at=class r{code;version;multihash;bytes;"/";constructor(t,e,n,o){this.code=e,this.version=t,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:t,multihash:e}=this;if(t!==xr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==ll)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}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:t,digest:e}=this.multihash,n=Ht(t,e);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(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&Ys(t.multihash,n.multihash)}toString(t){return js(this,t)}toJSON(){return{"/":js(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:o,multihash:i,bytes:s}=e;return new r(n,o,i,s??Qs(n,o,i.bytes))}else if(e[fl]===!0){let{version:n,multihash:o,code:i}=e,s=Kt(o);return r.create(n,i,s)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==xr)throw new Error(`Version 0 CID must use dag-pb (code: ${xr}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=Qs(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,xr,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,o=ee(t.subarray(n,n+e.multihashSize));if(o.byteLength!==e.multihashSize)throw new Error("Incorrect length");let i=o.subarray(e.multihashSize-e.digestSize),s=new $e(e.multihashCode,e.digestSize,i,o);return[e.version===0?r.createV0(s):r.createV1(e.codec,s),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[f,d]=br(t.subarray(e));return e+=d,f},o=n(),i=xr;if(o===18?(o=0,e=0):i=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let s=e,a=n(),c=n(),l=e+c,u=l-s;return{version:o,codec:i,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(t,e){let[n,o]=al(t,e),i=r.decode(o);if(i.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Io(i).set(n,t),i}};function al(r,t){switch(r[0]){case"Q":{let e=t??Y;return[Y.prefix,e.decode(`${Y.prefix}${r}`)]}case Y.prefix:{let e=t??Y;return[Y.prefix,e.decode(r)]}case re.prefix:{let e=t??re;return[re.prefix,e.decode(r)]}case yr.prefix:{let e=t??yr;return[yr.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function cl(r,t,e){let{prefix:n}=e;if(n!==Y.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let o=t.get(n);if(o==null){let i=e.encode(r).slice(1);return t.set(n,i),i}else return o}function ul(r,t,e){let{prefix:n}=e,o=t.get(n);if(o==null){let i=e.encode(r);return t.set(n,i),i}else return o}var xr=112,ll=18;function Qs(r,t,e){let n=We(r),o=n+We(t),i=new Uint8Array(o+e.byteLength);return Ge(r,i,0),Ge(t,i,n),i.set(e,o),i}var fl=Symbol.for("@ipld/js-cid/CID");var To={};Tt(To,{identity:()=>Vt});var Js=0,hl="identity",ta=ee;function dl(r){return Ht(Js,ta(r))}var Vt={code:Js,name:hl,encode:ta,digest:dl};function dt(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function ot(r=0){return new Uint8Array(r)}function Lt(r=0){return new Uint8Array(r)}function Nt(r,t){t==null&&(t=r.reduce((o,i)=>o+i.length,0));let e=Lt(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}var ra=Symbol.for("@achingbrain/uint8arraylist");function ea(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let o=e+n.byteLength;if(t<o)return{buf:n,index:t-e};e=o}throw new RangeError("index is out of bounds")}function Xr(r){return!!r?.[ra]}var ut=class r{bufs;length;[ra]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let n of t)if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.push(n);else if(Xr(n))e+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let n of t.reverse())if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.unshift(n);else if(Xr(n))e+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=ea(this.bufs,t);return e.buf[e.index]}set(t,e){let n=ea(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else if(Xr(t))for(let n=0;n<t.length;n++)this.set(e+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:n,length:o}=this._subList(t,e);return Nt(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:Nt(n,o)}sublist(t,e){let{bufs:n,length:o}=this._subList(t,e),i=new r;return i.length=o,i.bufs=[...n],i}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let i=0;i<this.bufs.length;i++){let s=this.bufs[i],a=o,c=a+s.byteLength;if(o=c,t>=c)continue;let l=t>=a&&t<c,u=e>a&&e<=c;if(l&&u){if(t===a&&e===c){n.push(s);break}let f=t-a;n.push(s.subarray(f,f+(e-t)));break}if(l){if(t===0){n.push(s);continue}n.push(s.subarray(t-a));continue}if(u){if(e===c){n.push(s);break}n.push(s.subarray(0,e-a));break}n.push(s)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!Xr(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let i=256,s=new Int32Array(i);for(let f=0;f<i;f++)s[f]=-1;for(let f=0;f<o;f++)s[n[f]]=f;let a=s,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let f=e;f<=c;f+=u){u=0;for(let d=l;d>=0;d--){let g=this.get(f+d);if(n[d]!==g){u=Math.max(1,d-a[g]);break}}if(u===0)return f}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=Lt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let o=ot(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,e,n),this.write(o,t)}getInt32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){let o=ot(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,e,n),this.write(o,t)}getBigInt64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){let o=ot(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,e,n),this.write(o,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let n=Lt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let o=ot(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,e,n),this.write(o,t)}getUint32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){let o=ot(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,e,n),this.write(o,t)}getBigUint64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){let o=ot(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,e,n),this.write(o,t)}getFloat32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){let o=ot(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,e,n),this.write(o,t)}getFloat64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){let o=ot(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,e,n),this.write(o,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!dt(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((o,i)=>o+i.byteLength,0)),n.length=e,n}};var Lo={};Tt(Lo,{base10:()=>pl});var pl=fe({prefix:"9",name:"base10",alphabet:"0123456789"});var Co={};Tt(Co,{base16:()=>ml,base16upper:()=>yl});var ml=st({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),yl=st({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Ro={};Tt(Ro,{base2:()=>gl});var gl=st({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Do={};Tt(Do,{base256emoji:()=>Sl});var na=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}"),bl=na.reduce((r,t,e)=>(r[e]=t,r),[]),xl=na.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function wl(r){return r.reduce((t,e)=>(t+=bl[e],t),"")}function El(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=xl[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var Sl=Ve({prefix:"\u{1F680}",name:"base256emoji",encode:wl,decode:El});var Bo={};Tt(Bo,{base64:()=>vl,base64pad:()=>Al,base64url:()=>Po,base64urlpad:()=>_l});var vl=st({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Al=st({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Po=st({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),_l=st({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var No={};Tt(No,{base8:()=>Il});var Il=st({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Uo={};Tt(Uo,{identity:()=>Tl});var Tl=Ve({prefix:"\0",name:"identity",encode:r=>zs(r),decode:r=>Fs(r)});var Pp=new TextEncoder,Bp=new TextDecoder;var Mo={};Tt(Mo,{sha256:()=>Ze,sha512:()=>Rl});function ko({name:r,code:t,encode:e}){return new Oo(r,t,e)}var Oo=class{name;code;encode;constructor(t,e,n){this.name=t,this.code=e,this.encode=n}digest(t){if(t instanceof Uint8Array){let e=this.encode(t);return e instanceof Uint8Array?Ht(this.code,e):e.then(n=>Ht(this.code,n))}else throw Error("Unknown type, must be binary type")}};function ia(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var Ze=ko({name:"sha2-256",code:18,encode:ia("SHA-256")}),Rl=ko({name:"sha2-512",code:19,encode:ia("SHA-512")});var wr={...Uo,...Ro,...No,...Lo,...Co,...vo,...Ao,...So,...Bo,...Do},Gp={...Mo,...To};function aa(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var sa=aa("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Ko=aa("ascii","a",r=>{let t="a";for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return t},r=>{r=r.substring(1);let t=Lt(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),Dl={utf8:sa,"utf-8":sa,hex:wr.base16,latin1:Ko,ascii:Ko,binary:Ko,...wr},Qr=Dl;function M(r,t="utf8"){let e=Qr[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function O(r,t="utf8"){let e=Qr[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var Pl=parseInt("11111",2),qo=parseInt("10000000",2),Bl=parseInt("01111111",2),ca={0:Er,1:Er,2:Nl,3:kl,4:Ml,5:Ol,6:Ul,16:Er,22:Er,48:Er};function ne(r,t={offset:0}){let e=r[t.offset]&Pl;if(t.offset++,ca[e]!=null)return ca[e](r,t);throw new Error("No decoder for tag "+e)}function Sr(r,t){let e=0;if((r[t.offset]&qo)===qo){let n=r[t.offset]&Bl,o="0x";t.offset++;for(let i=0;i<n;i++,t.offset++)o+=r[t.offset].toString(16).padStart(2,"0");e=parseInt(o,16)}else e=r[t.offset],t.offset++;return e}function Er(r,t){Sr(r,t);let e=[];for(;!(t.offset>=r.byteLength);){let n=ne(r,t);if(n===null)break;e.push(n)}return e}function Nl(r,t){let e=Sr(r,t),n=t.offset,o=t.offset+e,i=[];for(let s=n;s<o;s++)s===n&&r[s]===0||i.push(r[s]);return t.offset+=e,Uint8Array.from(i)}function Ul(r,t){let e=Sr(r,t),n=t.offset+e,o=r[t.offset];t.offset++;let i=0,s=0;o<40?(i=0,s=o):o<80?(i=1,s=o-40):(i=2,s=o-80);let a=`${i}.${s}`,c=[];for(;t.offset<n;){let l=r[t.offset];if(t.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 Ol(r,t){return t.offset++,null}function kl(r,t){let e=Sr(r,t),n=r[t.offset];t.offset++;let o=r.subarray(t.offset,t.offset+e-1);if(t.offset+=e,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function Ml(r,t){let e=Sr(r,t),n=r.subarray(t.offset,t.offset+e);return t.offset+=e,n}function Kl(r){let t=r.toString(16);t.length%2===1&&(t="0"+t);let e=new ut;for(let n=0;n<t.length;n+=2)e.append(Uint8Array.from([parseInt(`${t[n]}${t[n+1]}`,16)]));return e}function Fo(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let t=Kl(r.byteLength);return new ut(Uint8Array.from([t.byteLength|qo]),t)}function Ct(r){let t=new ut,e=128;return(r.subarray()[0]&e)===e&&t.append(Uint8Array.from([0])),t.append(r),new ut(Uint8Array.from([2]),Fo(t),t)}function Jr(r){let t=Uint8Array.from([0]),e=new ut(t,r);return new ut(Uint8Array.from([3]),Fo(e),e)}function he(r,t=48){let e=new ut;for(let n of r)e.append(n);return new ut(Uint8Array.from([t]),Fo(e),e)}async function ua(r,t,e){let n=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);return crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},n,t,e.subarray())}var ql=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Fl=Uint8Array.from([6,5,43,129,4,0,34]),zl=Uint8Array.from([6,5,43,129,4,0,35]),Hl={ext:!0,kty:"EC",crv:"P-256"},Vl={ext:!0,kty:"EC",crv:"P-384"},Gl={ext:!0,kty:"EC",crv:"P-521"},zo=32,Ho=48,Vo=66;function Go(r){let t=ne(r);return la(t)}function la(r){let t=r[1][1][0],e=1,n,o;if(t.byteLength===zo*2+1)return n=O(t.subarray(e,e+zo),"base64url"),o=O(t.subarray(e+zo),"base64url"),new Ye({...Hl,key_ops:["verify"],x:n,y:o});if(t.byteLength===Ho*2+1)return n=O(t.subarray(e,e+Ho),"base64url"),o=O(t.subarray(e+Ho),"base64url"),new Ye({...Vl,key_ops:["verify"],x:n,y:o});if(t.byteLength===Vo*2+1)return n=O(t.subarray(e,e+Vo),"base64url"),o=O(t.subarray(e+Vo),"base64url"),new Ye({...Gl,key_ops:["verify"],x:n,y:o});throw new ht(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function fa(r){return he([Ct(Uint8Array.from([1])),he([Wl(r.crv)],160),he([Jr(new ut(Uint8Array.from([4]),M(r.x??"","base64url"),M(r.y??"","base64url")))],161)]).subarray()}function Wl(r){if(r==="P-256")return ql;if(r==="P-384")return Fl;if(r==="P-521")return zl;throw new ht(`Invalid curve ${r}`)}var Ye=class{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=fa(this.jwk)),this._raw}toMultihash(){return Vt.digest(jt(this))}toCID(){return at.createV1(114,this.toMultihash())}toString(){return Y.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:dt(this.raw,t.raw)}async verify(t,e){return ua(this.jwk,e,t)}};function ha(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function $l(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function je(r,...t){if(!$l(r))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(r.length))throw new Error("Uint8Array expected of length "+t+", got length="+r.length)}function da(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");ha(r.outputLen),ha(r.blockLen)}function Xe(r,t=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(t&&r.finished)throw new Error("Hash#digest() has already been called")}function pa(r,t){je(r);let e=t.outputLen;if(r.length<e)throw new Error("digestInto() expects output buffer of length at least "+e)}var Ie=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function tn(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Gt(r,t){return r<<32-t|r>>>t}var Im=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function";function ma(r){if(typeof r!="string")throw new Error("utf8ToBytes expected string, got "+typeof r);return new Uint8Array(new TextEncoder().encode(r))}function vr(r){return typeof r=="string"&&(r=ma(r)),je(r),r}function Wo(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];je(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let i=r[n];e.set(i,o),o+=i.length}return e}var Qe=class{clone(){return this._cloneInto()}};function en(r){let t=n=>r().update(vr(n)).digest(),e=r();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>r(),t}function rn(r=32){if(Ie&&typeof Ie.getRandomValues=="function")return Ie.getRandomValues(new Uint8Array(r));if(Ie&&typeof Ie.randomBytes=="function")return Uint8Array.from(Ie.randomBytes(r));throw new Error("crypto.getRandomValues must be defined")}function Zl(r,t,e,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(t,e,n);let o=BigInt(32),i=BigInt(4294967295),s=Number(e>>o&i),a=Number(e&i),c=n?4:0,l=n?0:4;r.setUint32(t+c,s,n),r.setUint32(t+l,a,n)}function ya(r,t,e){return r&t^~r&e}function ga(r,t,e){return r&t^r&e^t&e}var Je=class extends Qe{constructor(t,e,n,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(t),this.view=tn(this.buffer)}update(t){Xe(this);let{view:e,buffer:n,blockLen:o}=this;t=vr(t);let i=t.length;for(let s=0;s<i;){let a=Math.min(o-this.pos,i-s);if(a===o){let c=tn(t);for(;o<=i-s;s+=o)this.process(c,s);continue}n.set(t.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===o&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){Xe(this),pa(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:o,isLE:i}=this,{pos:s}=this;e[s++]=128,this.buffer.subarray(s).fill(0),this.padOffset>o-s&&(this.process(n,0),s=0);for(let f=s;f<o;f++)e[f]=0;Zl(n,o-8,BigInt(this.length*8),i),this.process(n,0);let a=tn(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should 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],i)}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:e,buffer:n,length:o,finished:i,destroyed:s,pos:a}=this;return t.length=o,t.pos=a,t.finished=i,t.destroyed=s,o%e&&t.buffer.set(n),t}};var Yl=new Uint32Array([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]),de=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),pe=new Uint32Array(64),$o=class extends Je{constructor(t=32){super(64,t,8,!1),this.A=de[0]|0,this.B=de[1]|0,this.C=de[2]|0,this.D=de[3]|0,this.E=de[4]|0,this.F=de[5]|0,this.G=de[6]|0,this.H=de[7]|0}get(){let{A:t,B:e,C:n,D:o,E:i,F:s,G:a,H:c}=this;return[t,e,n,o,i,s,a,c]}set(t,e,n,o,i,s,a,c){this.A=t|0,this.B=e|0,this.C=n|0,this.D=o|0,this.E=i|0,this.F=s|0,this.G=a|0,this.H=c|0}process(t,e){for(let f=0;f<16;f++,e+=4)pe[f]=t.getUint32(e,!1);for(let f=16;f<64;f++){let d=pe[f-15],g=pe[f-2],b=Gt(d,7)^Gt(d,18)^d>>>3,y=Gt(g,17)^Gt(g,19)^g>>>10;pe[f]=y+pe[f-7]+b+pe[f-16]|0}let{A:n,B:o,C:i,D:s,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){let d=Gt(a,6)^Gt(a,11)^Gt(a,25),g=u+d+ya(a,c,l)+Yl[f]+pe[f]|0,y=(Gt(n,2)^Gt(n,13)^Gt(n,22))+ga(n,o,i)|0;u=l,l=c,c=a,a=s+g|0,s=i,i=o,o=n,n=g+y|0}n=n+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,o,i,s,a,c,l,u)}roundClean(){pe.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var Te=en(()=>new $o);var nn=BigInt(4294967295),Zo=BigInt(32);function ba(r,t=!1){return t?{h:Number(r&nn),l:Number(r>>Zo&nn)}:{h:Number(r>>Zo&nn)|0,l:Number(r&nn)|0}}function jl(r,t=!1){let e=new Uint32Array(r.length),n=new Uint32Array(r.length);for(let o=0;o<r.length;o++){let{h:i,l:s}=ba(r[o],t);[e[o],n[o]]=[i,s]}return[e,n]}var Xl=(r,t)=>BigInt(r>>>0)<<Zo|BigInt(t>>>0),Ql=(r,t,e)=>r>>>e,Jl=(r,t,e)=>r<<32-e|t>>>e,tf=(r,t,e)=>r>>>e|t<<32-e,ef=(r,t,e)=>r<<32-e|t>>>e,rf=(r,t,e)=>r<<64-e|t>>>e-32,nf=(r,t,e)=>r>>>e-32|t<<64-e,of=(r,t)=>t,sf=(r,t)=>r,af=(r,t,e)=>r<<e|t>>>32-e,cf=(r,t,e)=>t<<e|r>>>32-e,uf=(r,t,e)=>t<<e-32|r>>>64-e,lf=(r,t,e)=>r<<e-32|t>>>64-e;function ff(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var hf=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),df=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,pf=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),mf=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,yf=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),gf=(r,t,e,n,o,i)=>t+e+n+o+i+(r/2**32|0)|0;var bf={fromBig:ba,split:jl,toBig:Xl,shrSH:Ql,shrSL:Jl,rotrSH:tf,rotrSL:ef,rotrBH:rf,rotrBL:nf,rotr32H:of,rotr32L:sf,rotlSH:af,rotlSL:cf,rotlBH:uf,rotlBL:lf,add:ff,add3L:hf,add3H:df,add4L:pf,add4H:mf,add5H:gf,add5L:yf},N=bf;var[xf,wf]=N.split(["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))),me=new Uint32Array(80),ye=new Uint32Array(80),Yo=class extends Je{constructor(t=64){super(128,t,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){let{Ah:t,Al:e,Bh:n,Bl:o,Ch:i,Cl:s,Dh:a,Dl:c,Eh:l,El:u,Fh:f,Fl:d,Gh:g,Gl:b,Hh:y,Hl:h}=this;return[t,e,n,o,i,s,a,c,l,u,f,d,g,b,y,h]}set(t,e,n,o,i,s,a,c,l,u,f,d,g,b,y,h){this.Ah=t|0,this.Al=e|0,this.Bh=n|0,this.Bl=o|0,this.Ch=i|0,this.Cl=s|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=f|0,this.Fl=d|0,this.Gh=g|0,this.Gl=b|0,this.Hh=y|0,this.Hl=h|0}process(t,e){for(let p=0;p<16;p++,e+=4)me[p]=t.getUint32(e),ye[p]=t.getUint32(e+=4);for(let p=16;p<80;p++){let _=me[p-15]|0,D=ye[p-15]|0,P=N.rotrSH(_,D,1)^N.rotrSH(_,D,8)^N.shrSH(_,D,7),T=N.rotrSL(_,D,1)^N.rotrSL(_,D,8)^N.shrSL(_,D,7),L=me[p-2]|0,C=ye[p-2]|0,et=N.rotrSH(L,C,19)^N.rotrBH(L,C,61)^N.shrSH(L,C,6),W=N.rotrSL(L,C,19)^N.rotrBL(L,C,61)^N.shrSL(L,C,6),k=N.add4L(T,W,ye[p-7],ye[p-16]),pt=N.add4H(k,P,et,me[p-7],me[p-16]);me[p]=pt|0,ye[p]=k|0}let{Ah:n,Al:o,Bh:i,Bl:s,Ch:a,Cl:c,Dh:l,Dl:u,Eh:f,El:d,Fh:g,Fl:b,Gh:y,Gl:h,Hh:x,Hl:v}=this;for(let p=0;p<80;p++){let _=N.rotrSH(f,d,14)^N.rotrSH(f,d,18)^N.rotrBH(f,d,41),D=N.rotrSL(f,d,14)^N.rotrSL(f,d,18)^N.rotrBL(f,d,41),P=f&g^~f&y,T=d&b^~d&h,L=N.add5L(v,D,T,wf[p],ye[p]),C=N.add5H(L,x,_,P,xf[p],me[p]),et=L|0,W=N.rotrSH(n,o,28)^N.rotrBH(n,o,34)^N.rotrBH(n,o,39),k=N.rotrSL(n,o,28)^N.rotrBL(n,o,34)^N.rotrBL(n,o,39),pt=n&i^n&a^i&a,S=o&s^o&c^s&c;x=y|0,v=h|0,y=g|0,h=b|0,g=f|0,b=d|0,{h:f,l:d}=N.add(l|0,u|0,C|0,et|0),l=a|0,u=c|0,a=i|0,c=s|0,i=n|0,s=o|0;let I=N.add3L(et,k,S);n=N.add3H(I,C,W,pt),o=I|0}({h:n,l:o}=N.add(this.Ah|0,this.Al|0,n|0,o|0)),{h:i,l:s}=N.add(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=N.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=N.add(this.Dh|0,this.Dl|0,l|0,u|0),{h:f,l:d}=N.add(this.Eh|0,this.El|0,f|0,d|0),{h:g,l:b}=N.add(this.Fh|0,this.Fl|0,g|0,b|0),{h:y,l:h}=N.add(this.Gh|0,this.Gl|0,y|0,h|0),{h:x,l:v}=N.add(this.Hh|0,this.Hl|0,x|0,v|0),this.set(n,o,i,s,a,c,l,u,f,d,g,b,y,h,x,v)}roundClean(){me.fill(0),ye.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var jo=en(()=>new Yo);var ti=BigInt(0),Jo=BigInt(1);function Le(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function ei(r){if(!Le(r))throw new Error("Uint8Array expected")}function Xt(r,t){if(typeof t!="boolean")throw new Error(r+" boolean expected, got "+t)}function Ar(r){let t=r.toString(16);return t.length&1?"0"+t:t}function Ea(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?ti:BigInt("0x"+r)}var Sa=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Ef=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function ge(r){if(ei(r),Sa)return r.toHex();let t="";for(let e=0;e<r.length;e++)t+=Ef[r[e]];return t}var oe={_0:48,_9:57,A:65,F:70,a:97,f:102};function xa(r){if(r>=oe._0&&r<=oe._9)return r-oe._0;if(r>=oe.A&&r<=oe.F)return r-(oe.A-10);if(r>=oe.a&&r<=oe.f)return r-(oe.a-10)}function _r(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(Sa)return Uint8Array.fromHex(r);let t=r.length,e=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(e);for(let o=0,i=0;o<e;o++,i+=2){let s=xa(r.charCodeAt(i)),a=xa(r.charCodeAt(i+1));if(s===void 0||a===void 0){let c=r[i]+r[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}n[o]=s*16+a}return n}function ie(r){return Ea(ge(r))}function Ce(r){return ei(r),Ea(ge(Uint8Array.from(r).reverse()))}function Re(r,t){return _r(r.toString(16).padStart(t*2,"0"))}function tr(r,t){return Re(r,t).reverse()}function it(r,t,e){let n;if(typeof t=="string")try{n=_r(t)}catch(i){throw new Error(r+" must be hex string or Uint8Array, cause: "+i)}else if(Le(t))n=Uint8Array.from(t);else throw new Error(r+" must be hex string or Uint8Array");let o=n.length;if(typeof e=="number"&&o!==e)throw new Error(r+" of length "+e+" expected, got "+o);return n}function be(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];ei(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let i=r[n];e.set(i,o),o+=i.length}return e}var Xo=r=>typeof r=="bigint"&&ti<=r;function on(r,t,e){return Xo(r)&&Xo(t)&&Xo(e)&&t<=r&&r<e}function Ut(r,t,e,n){if(!on(t,e,n))throw new Error("expected valid "+r+": "+e+" <= n < "+n+", got "+t)}function va(r){let t;for(t=0;r>ti;r>>=Jo,t+=1);return t}var De=r=>(Jo<<BigInt(r))-Jo,Qo=r=>new Uint8Array(r),wa=r=>Uint8Array.from(r);function Aa(r,t,e){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof e!="function")throw new Error("hmacFn must be a function");let n=Qo(r),o=Qo(r),i=0,s=()=>{n.fill(1),o.fill(0),i=0},a=(...f)=>e(o,n,...f),c=(f=Qo(0))=>{o=a(wa([0]),f),n=a(),f.length!==0&&(o=a(wa([1]),f),n=a())},l=()=>{if(i++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,d=[];for(;f<t;){n=a();let g=n.slice();d.push(g),f+=n.length}return be(...d)};return(f,d)=>{s(),c(f);let g;for(;!(g=d(l()));)c();return s(),g}}var Sf={bigint:r=>typeof r=="bigint",function:r=>typeof r=="function",boolean:r=>typeof r=="boolean",string:r=>typeof r=="string",stringOrUint8Array:r=>typeof r=="string"||Le(r),isSafeInteger:r=>Number.isSafeInteger(r),array:r=>Array.isArray(r),field:(r,t)=>t.Fp.isValid(r),hash:r=>typeof r=="function"&&Number.isSafeInteger(r.outputLen)};function se(r,t,e={}){let n=(o,i,s)=>{let a=Sf[i];if(typeof a!="function")throw new Error("invalid validator function");let c=r[o];if(!(s&&c===void 0)&&!a(c,r))throw new Error("param "+String(o)+" is invalid. Expected "+i+", got "+c)};for(let[o,i]of Object.entries(t))n(o,i,!1);for(let[o,i]of Object.entries(e))n(o,i,!0);return r}function er(r){let t=new WeakMap;return(e,...n)=>{let o=t.get(e);if(o!==void 0)return o;let i=r(e,...n);return t.set(e,i),i}}var mt=BigInt(0),rt=BigInt(1),Pe=BigInt(2),vf=BigInt(3),ri=BigInt(4),_a=BigInt(5),Ia=BigInt(8),Af=BigInt(9),_f=BigInt(16);function Q(r,t){let e=r%t;return e>=mt?e:t+e}function If(r,t,e){if(t<mt)throw new Error("invalid exponent, negatives unsupported");if(e<=mt)throw new Error("invalid modulus");if(e===rt)return mt;let n=rt;for(;t>mt;)t&rt&&(n=n*r%e),r=r*r%e,t>>=rt;return n}function nt(r,t,e){let n=r;for(;t-- >mt;)n*=n,n%=e;return n}function sn(r,t){if(r===mt)throw new Error("invert: expected non-zero number");if(t<=mt)throw new Error("invert: expected positive modulus, got "+t);let e=Q(r,t),n=t,o=mt,i=rt,s=rt,a=mt;for(;e!==mt;){let l=n/e,u=n%e,f=o-s*l,d=i-a*l;n=e,e=u,o=s,i=a,s=f,a=d}if(n!==rt)throw new Error("invert: does not exist");return Q(o,t)}function Tf(r){let t=(r-rt)/Pe,e,n,o;for(e=r-rt,n=0;e%Pe===mt;e/=Pe,n++);for(o=Pe;o<r&&If(o,t,r)!==r-rt;o++)if(o>1e3)throw new Error("Cannot find square root: likely non-prime P");if(n===1){let s=(r+rt)/ri;return function(c,l){let u=c.pow(l,s);if(!c.eql(c.sqr(u),l))throw new Error("Cannot find square root");return u}}let i=(e+rt)/Pe;return function(a,c){if(a.pow(c,t)===a.neg(a.ONE))throw new Error("Cannot find square root");let l=n,u=a.pow(a.mul(a.ONE,o),e),f=a.pow(c,i),d=a.pow(c,e);for(;!a.eql(d,a.ONE);){if(a.eql(d,a.ZERO))return a.ZERO;let g=1;for(let y=a.sqr(d);g<l&&!a.eql(y,a.ONE);g++)y=a.sqr(y);let b=a.pow(u,rt<<BigInt(l-g-1));u=a.sqr(b),f=a.mul(f,b),d=a.mul(d,u),l=g}return f}}function Lf(r){if(r%ri===vf){let t=(r+rt)/ri;return function(n,o){let i=n.pow(o,t);if(!n.eql(n.sqr(i),o))throw new Error("Cannot find square root");return i}}if(r%Ia===_a){let t=(r-_a)/Ia;return function(n,o){let i=n.mul(o,Pe),s=n.pow(i,t),a=n.mul(o,s),c=n.mul(n.mul(a,Pe),s),l=n.mul(a,n.sub(c,n.ONE));if(!n.eql(n.sqr(l),o))throw new Error("Cannot find square root");return l}}return r%_f,Tf(r)}var Ta=(r,t)=>(Q(r,t)&rt)===rt,Cf=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function ni(r){let t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},e=Cf.reduce((n,o)=>(n[o]="function",n),t);return se(r,e)}function Rf(r,t,e){if(e<mt)throw new Error("invalid exponent, negatives unsupported");if(e===mt)return r.ONE;if(e===rt)return t;let n=r.ONE,o=t;for(;e>mt;)e&rt&&(n=r.mul(n,o)),o=r.sqr(o),e>>=rt;return n}function Df(r,t){let e=new Array(t.length),n=t.reduce((i,s,a)=>r.is0(s)?i:(e[a]=i,r.mul(i,s)),r.ONE),o=r.inv(n);return t.reduceRight((i,s,a)=>r.is0(s)?i:(e[a]=r.mul(i,e[a]),r.mul(i,s)),o),e}function oi(r,t){let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}function xe(r,t,e=!1,n={}){if(r<=mt)throw new Error("invalid field: expected ORDER > 0, got "+r);let{nBitLength:o,nByteLength:i}=oi(r,t);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let s,a=Object.freeze({ORDER:r,isLE:e,BITS:o,BYTES:i,MASK:De(o),ZERO:mt,ONE:rt,create:c=>Q(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return mt<=c&&c<r},is0:c=>c===mt,isOdd:c=>(c&rt)===rt,neg:c=>Q(-c,r),eql:(c,l)=>c===l,sqr:c=>Q(c*c,r),add:(c,l)=>Q(c+l,r),sub:(c,l)=>Q(c-l,r),mul:(c,l)=>Q(c*l,r),pow:(c,l)=>Rf(a,c,l),div:(c,l)=>Q(c*sn(l,r),r),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>sn(c,r),sqrt:n.sqrt||(c=>(s||(s=Lf(r)),s(a,c))),invertBatch:c=>Df(a,c),cmov:(c,l,u)=>u?l:c,toBytes:c=>e?tr(c,i):Re(c,i),fromBytes:c=>{if(c.length!==i)throw new Error("Field.fromBytes: expected "+i+" bytes, got "+c.length);return e?Ce(c):ie(c)}});return Object.freeze(a)}function La(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let t=r.toString(2).length;return Math.ceil(t/8)}function ii(r){let t=La(r);return t+Math.ceil(t/2)}function Ca(r,t,e=!1){let n=r.length,o=La(t),i=ii(t);if(n<16||n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);let s=e?Ce(r):ie(r),a=Q(s,t-rt)+rt;return e?tr(a,o):Re(a,o)}var Ra=BigInt(0),li=BigInt(1);function si(r,t){let e=t.negate();return r?e:t}function Pa(r,t){if(!Number.isSafeInteger(r)||r<=0||r>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+r)}function ai(r,t){Pa(r,t);let e=Math.ceil(t/r)+1,n=2**(r-1),o=2**r,i=De(r),s=BigInt(r);return{windows:e,windowSize:n,mask:i,maxNumber:o,shiftBy:s}}function Da(r,t,e){let{windowSize:n,mask:o,maxNumber:i,shiftBy:s}=e,a=Number(r&o),c=r>>s;a>n&&(a-=i,c+=li);let l=t*n,u=l+Math.abs(a)-1,f=a===0,d=a<0,g=t%2!==0;return{nextN:c,offset:u,isZero:f,isNeg:d,isNegF:g,offsetF:l}}function Pf(r,t){if(!Array.isArray(r))throw new Error("array expected");r.forEach((e,n)=>{if(!(e instanceof t))throw new Error("invalid point at index "+n)})}function Bf(r,t){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((e,n)=>{if(!t.isValid(e))throw new Error("invalid scalar at index "+n)})}var ci=new WeakMap,Ba=new WeakMap;function ui(r){return Ba.get(r)||1}function an(r,t){return{constTimeNegate:si,hasPrecomputes(e){return ui(e)!==1},unsafeLadder(e,n,o=r.ZERO){let i=e;for(;n>Ra;)n&li&&(o=o.add(i)),i=i.double(),n>>=li;return o},precomputeWindow(e,n){let{windows:o,windowSize:i}=ai(n,t),s=[],a=e,c=a;for(let l=0;l<o;l++){c=a,s.push(c);for(let u=1;u<i;u++)c=c.add(a),s.push(c);a=c.double()}return s},wNAF(e,n,o){let i=r.ZERO,s=r.BASE,a=ai(e,t);for(let c=0;c<a.windows;c++){let{nextN:l,offset:u,isZero:f,isNeg:d,isNegF:g,offsetF:b}=Da(o,c,a);o=l,f?s=s.add(si(g,n[b])):i=i.add(si(d,n[u]))}return{p:i,f:s}},wNAFUnsafe(e,n,o,i=r.ZERO){let s=ai(e,t);for(let a=0;a<s.windows&&o!==Ra;a++){let{nextN:c,offset:l,isZero:u,isNeg:f}=Da(o,a,s);if(o=c,!u){let d=n[l];i=i.add(f?d.negate():d)}}return i},getPrecomputes(e,n,o){let i=ci.get(n);return i||(i=this.precomputeWindow(n,e),e!==1&&ci.set(n,o(i))),i},wNAFCached(e,n,o){let i=ui(e);return this.wNAF(i,this.getPrecomputes(i,e,o),n)},wNAFCachedUnsafe(e,n,o,i){let s=ui(e);return s===1?this.unsafeLadder(e,n,i):this.wNAFUnsafe(s,this.getPrecomputes(s,e,o),n,i)},setWindowSize(e,n){Pa(n,t),Ba.set(e,n),ci.delete(e)}}}function cn(r,t,e,n){if(Pf(e,r),Bf(n,t),e.length!==n.length)throw new Error("arrays of points and scalars must have equal length");let o=r.ZERO,i=va(BigInt(e.length)),s=i>12?i-3:i>4?i-2:i?2:1,a=De(s),c=new Array(Number(a)+1).fill(o),l=Math.floor((t.BITS-1)/s)*s,u=o;for(let f=l;f>=0;f-=s){c.fill(o);for(let g=0;g<n.length;g++){let b=n[g],y=Number(b>>BigInt(f)&a);c[y]=c[y].add(e[g])}let d=o;for(let g=c.length-1,b=o;g>0;g--)b=b.add(c[g]),d=d.add(b);if(u=u.add(d),f!==0)for(let g=0;g<s;g++)u=u.double()}return u}function Ir(r){return ni(r.Fp),se(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...oi(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var Qt=BigInt(0),_t=BigInt(1),Na=BigInt(2),Nf=BigInt(8),Uf={zip215:!0};function Of(r){let t=Ir(r);return se(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function Ua(r){let t=Of(r),{Fp:e,n,prehash:o,hash:i,randomBytes:s,nByteLength:a,h:c}=t,l=Na<<BigInt(a*8)-_t,u=e.create,f=xe(t.n,t.nBitLength),d=t.uvRatio||((w,m)=>{try{return{isValid:!0,value:e.sqrt(w*e.inv(m))}}catch{return{isValid:!1,value:Qt}}}),g=t.adjustScalarBytes||(w=>w),b=t.domain||((w,m,E)=>{if(Xt("phflag",E),m.length||E)throw new Error("Contexts/pre-hash are not supported");return w});function y(w,m,E=!1){let A=E?_t:Qt;Ut("coordinate "+w,m,A,l)}function h(w){if(!(w instanceof p))throw new Error("ExtendedPoint expected")}let x=er((w,m)=>{let{ex:E,ey:A,ez:B}=w,U=w.is0();m==null&&(m=U?Nf:e.inv(B));let z=u(E*m),H=u(A*m),V=u(B*m);if(U)return{x:Qt,y:_t};if(V!==_t)throw new Error("invZ was invalid");return{x:z,y:H}}),v=er(w=>{let{a:m,d:E}=t;if(w.is0())throw new Error("bad point: ZERO");let{ex:A,ey:B,ez:U,et:z}=w,H=u(A*A),V=u(B*B),Z=u(U*U),ft=u(Z*Z),ct=u(H*m),bt=u(Z*u(ct+V)),It=u(ft+u(E*u(H*V)));if(bt!==It)throw new Error("bad point: equation left != right (1)");let yt=u(A*B),xt=u(U*z);if(yt!==xt)throw new Error("bad point: equation left != right (2)");return!0});class p{constructor(m,E,A,B){y("x",m),y("y",E),y("z",A,!0),y("t",B),this.ex=m,this.ey=E,this.ez=A,this.et=B,Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(m){if(m instanceof p)throw new Error("extended point not allowed");let{x:E,y:A}=m||{};return y("x",E),y("y",A),new p(E,A,_t,u(E*A))}static normalizeZ(m){let E=e.invertBatch(m.map(A=>A.ez));return m.map((A,B)=>A.toAffine(E[B])).map(p.fromAffine)}static msm(m,E){return cn(p,f,m,E)}_setWindowSize(m){P.setWindowSize(this,m)}assertValidity(){v(this)}equals(m){h(m);let{ex:E,ey:A,ez:B}=this,{ex:U,ey:z,ez:H}=m,V=u(E*H),Z=u(U*B),ft=u(A*H),ct=u(z*B);return V===Z&&ft===ct}is0(){return this.equals(p.ZERO)}negate(){return new p(u(-this.ex),this.ey,this.ez,u(-this.et))}double(){let{a:m}=t,{ex:E,ey:A,ez:B}=this,U=u(E*E),z=u(A*A),H=u(Na*u(B*B)),V=u(m*U),Z=E+A,ft=u(u(Z*Z)-U-z),ct=V+z,bt=ct-H,It=V-z,yt=u(ft*bt),xt=u(ct*It),Bt=u(ft*It),zt=u(bt*ct);return new p(yt,xt,zt,Bt)}add(m){h(m);let{a:E,d:A}=t,{ex:B,ey:U,ez:z,et:H}=this,{ex:V,ey:Z,ez:ft,et:ct}=m,bt=u(B*V),It=u(U*Z),yt=u(H*A*ct),xt=u(z*ft),Bt=u((B+U)*(V+Z)-bt-It),zt=xt-yt,pr=xt+yt,Ps=u(It-E*bt),xu=u(Bt*zt),wu=u(pr*Ps),Eu=u(Bt*Ps),Su=u(zt*pr);return new p(xu,wu,Su,Eu)}subtract(m){return this.add(m.negate())}wNAF(m){return P.wNAFCached(this,m,p.normalizeZ)}multiply(m){let E=m;Ut("scalar",E,_t,n);let{p:A,f:B}=this.wNAF(E);return p.normalizeZ([A,B])[0]}multiplyUnsafe(m,E=p.ZERO){let A=m;return Ut("scalar",A,Qt,n),A===Qt?D:this.is0()||A===_t?this:P.wNAFCachedUnsafe(this,A,p.normalizeZ,E)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return P.unsafeLadder(this,n).is0()}toAffine(m){return x(this,m)}clearCofactor(){let{h:m}=t;return m===_t?this:this.multiplyUnsafe(m)}static fromHex(m,E=!1){let{d:A,a:B}=t,U=e.BYTES;m=it("pointHex",m,U),Xt("zip215",E);let z=m.slice(),H=m[U-1];z[U-1]=H&-129;let V=Ce(z),Z=E?l:e.ORDER;Ut("pointHex.y",V,Qt,Z);let ft=u(V*V),ct=u(ft-_t),bt=u(A*ft-B),{isValid:It,value:yt}=d(ct,bt);if(!It)throw new Error("Point.fromHex: invalid y coordinate");let xt=(yt&_t)===_t,Bt=(H&128)!==0;if(!E&&yt===Qt&&Bt)throw new Error("Point.fromHex: x=0 and x_0=1");return Bt!==xt&&(yt=u(-yt)),p.fromAffine({x:yt,y:V})}static fromPrivateKey(m){let{scalar:E}=C(m);return _.multiply(E)}toRawBytes(){let{x:m,y:E}=this.toAffine(),A=tr(E,e.BYTES);return A[A.length-1]|=m&_t?128:0,A}toHex(){return ge(this.toRawBytes())}}p.BASE=new p(t.Gx,t.Gy,_t,u(t.Gx*t.Gy)),p.ZERO=new p(Qt,_t,_t,Qt);let{BASE:_,ZERO:D}=p,P=an(p,a*8);function T(w){return Q(w,n)}function L(w){return T(Ce(w))}function C(w){let m=e.BYTES;w=it("private key",w,m);let E=it("hashed private key",i(w),2*m),A=g(E.slice(0,m)),B=E.slice(m,2*m),U=L(A);return{head:A,prefix:B,scalar:U}}function et(w){let{head:m,prefix:E,scalar:A}=C(w),B=_.multiply(A),U=B.toRawBytes();return{head:m,prefix:E,scalar:A,point:B,pointBytes:U}}function W(w){return et(w).pointBytes}function k(w=new Uint8Array,...m){let E=be(...m);return L(i(b(E,it("context",w),!!o)))}function pt(w,m,E={}){w=it("message",w),o&&(w=o(w));let{prefix:A,scalar:B,pointBytes:U}=et(m),z=k(E.context,A,w),H=_.multiply(z).toRawBytes(),V=k(E.context,H,U,w),Z=T(z+V*B);Ut("signature.s",Z,Qt,n);let ft=be(H,tr(Z,e.BYTES));return it("result",ft,e.BYTES*2)}let S=Uf;function I(w,m,E,A=S){let{context:B,zip215:U}=A,z=e.BYTES;w=it("signature",w,2*z),m=it("message",m),E=it("publicKey",E,z),U!==void 0&&Xt("zip215",U),o&&(m=o(m));let H=Ce(w.slice(z,2*z)),V,Z,ft;try{V=p.fromHex(E,U),Z=p.fromHex(w.slice(0,z),U),ft=_.multiplyUnsafe(H)}catch{return!1}if(!U&&V.isSmallOrder())return!1;let ct=k(B,Z.toRawBytes(),V.toRawBytes(),m);return Z.add(V.multiplyUnsafe(ct)).subtract(ft).clearCofactor().equals(p.ZERO)}return _._setWindowSize(8),{CURVE:t,getPublicKey:W,sign:pt,verify:I,ExtendedPoint:p,utils:{getExtendedPublicKey:et,randomPrivateKey:()=>s(e.BYTES),precompute(w=8,m=p.BASE){return m._setWindowSize(w),m.multiply(BigInt(3)),m}}}}var fi=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Oa=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),a0=BigInt(0),kf=BigInt(1),ka=BigInt(2),c0=BigInt(3),Mf=BigInt(5),Kf=BigInt(8);function qf(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),i=fi,a=r*r%i*r%i,c=nt(a,ka,i)*a%i,l=nt(c,kf,i)*r%i,u=nt(l,Mf,i)*l%i,f=nt(u,t,i)*u%i,d=nt(f,e,i)*f%i,g=nt(d,n,i)*d%i,b=nt(g,o,i)*g%i,y=nt(b,o,i)*g%i,h=nt(y,t,i)*u%i;return{pow_p_5_8:nt(h,ka,i)*r%i,b2:a}}function Ff(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function zf(r,t){let e=fi,n=Q(t*t*t,e),o=Q(n*n*t,e),i=qf(r*o).pow_p_5_8,s=Q(r*n*i,e),a=Q(t*s*s,e),c=s,l=Q(s*Oa,e),u=a===r,f=a===Q(-r,e),d=a===Q(-r*Oa,e);return u&&(s=c),(f||d)&&(s=l),Ta(s,e)&&(s=Q(-s,e)),{isValid:u||f,value:s}}var Ma=xe(fi,void 0,!0),Hf={a:Ma.create(BigInt(-1)),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Ma,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:Kf,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:jo,randomBytes:rn,adjustScalarBytes:Ff,uvRatio:zf},Ka=Ua(Hf);var un=32;function qa(r,t,e){return Ka.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}var ln=class{type="Ed25519";raw;constructor(t){this.raw=hi(t,un)}toMultihash(){return Vt.digest(jt(this))}toCID(){return at.createV1(114,this.toMultihash())}toString(){return Y.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:dt(this.raw,t.raw)}verify(t,e){return qa(this.raw,e,t)}};function di(r){return r=hi(r,un),new ln(r)}function hi(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new ht(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}var Gf=Math.pow(2,7),Wf=Math.pow(2,14),$f=Math.pow(2,21),pi=Math.pow(2,28),mi=Math.pow(2,35),yi=Math.pow(2,42),gi=Math.pow(2,49),$=128,wt=127;function Et(r){if(r<Gf)return 1;if(r<Wf)return 2;if(r<$f)return 3;if(r<pi)return 4;if(r<mi)return 5;if(r<yi)return 6;if(r<gi)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function bi(r,t,e=0){switch(Et(r)){case 8:t[e++]=r&255|$,r/=128;case 7:t[e++]=r&255|$,r/=128;case 6:t[e++]=r&255|$,r/=128;case 5:t[e++]=r&255|$,r/=128;case 4:t[e++]=r&255|$,r>>>=7;case 3:t[e++]=r&255|$,r>>>=7;case 2:t[e++]=r&255|$,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function Zf(r,t,e=0){switch(Et(r)){case 8:t.set(e++,r&255|$),r/=128;case 7:t.set(e++,r&255|$),r/=128;case 6:t.set(e++,r&255|$),r/=128;case 5:t.set(e++,r&255|$),r/=128;case 4:t.set(e++,r&255|$),r>>>=7;case 3:t.set(e++,r&255|$),r>>>=7;case 2:t.set(e++,r&255|$),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function xi(r,t){let e=r[t],n=0;if(n+=e&wt,e<$||(e=r[t+1],n+=(e&wt)<<7,e<$)||(e=r[t+2],n+=(e&wt)<<14,e<$)||(e=r[t+3],n+=(e&wt)<<21,e<$)||(e=r[t+4],n+=(e&wt)*pi,e<$)||(e=r[t+5],n+=(e&wt)*mi,e<$)||(e=r[t+6],n+=(e&wt)*yi,e<$)||(e=r[t+7],n+=(e&wt)*gi,e<$))return n;throw new RangeError("Could not decode varint")}function Yf(r,t){let e=r.get(t),n=0;if(n+=e&wt,e<$||(e=r.get(t+1),n+=(e&wt)<<7,e<$)||(e=r.get(t+2),n+=(e&wt)<<14,e<$)||(e=r.get(t+3),n+=(e&wt)<<21,e<$)||(e=r.get(t+4),n+=(e&wt)*pi,e<$)||(e=r.get(t+5),n+=(e&wt)*mi,e<$)||(e=r.get(t+6),n+=(e&wt)*yi,e<$)||(e=r.get(t+7),n+=(e&wt)*gi,e<$))return n;throw new RangeError("Could not decode varint")}function qt(r,t,e=0){return t==null&&(t=Lt(Et(r))),t instanceof Uint8Array?bi(r,t,e):Zf(r,t,e)}function ae(r,t=0){return r instanceof Uint8Array?xi(r,t):Yf(r,t)}var wi=new Float32Array([-0]),we=new Uint8Array(wi.buffer);function za(r,t,e){wi[0]=r,t[e]=we[0],t[e+1]=we[1],t[e+2]=we[2],t[e+3]=we[3]}function Ha(r,t){return we[0]=r[t],we[1]=r[t+1],we[2]=r[t+2],we[3]=r[t+3],wi[0]}var Ei=new Float64Array([-0]),St=new Uint8Array(Ei.buffer);function Va(r,t,e){Ei[0]=r,t[e]=St[0],t[e+1]=St[1],t[e+2]=St[2],t[e+3]=St[3],t[e+4]=St[4],t[e+5]=St[5],t[e+6]=St[6],t[e+7]=St[7]}function Ga(r,t){return St[0]=r[t],St[1]=r[t+1],St[2]=r[t+2],St[3]=r[t+3],St[4]=r[t+4],St[5]=r[t+5],St[6]=r[t+6],St[7]=r[t+7],Ei[0]}var jf=BigInt(Number.MAX_SAFE_INTEGER),Xf=BigInt(Number.MIN_SAFE_INTEGER),Ot=class r{lo;hi;constructor(t,e){this.lo=t|0,this.hi=e|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(e+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(BigInt(e)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?e===0?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return Be;if(t<jf&&t>Xf)return this.fromNumber(Number(t));let e=t<0n;e&&(t=-t);let n=t>>32n,o=t-(n<<32n);return e&&(n=~n|0n,o=~o|0n,++o>Wa&&(o=0n,++n>Wa&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return Be;let e=t<0;e&&(t=-t);let n=t>>>0,o=(t-n)/4294967296>>>0;return e&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(t){return typeof t=="number"?r.fromNumber(t):typeof t=="bigint"?r.fromBigInt(t):typeof t=="string"?r.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new r(t.low>>>0,t.high>>>0):Be}},Be=new Ot(0,0);Be.toBigInt=function(){return 0n};Be.zzEncode=Be.zzDecode=function(){return this};Be.length=function(){return 1};var Wa=4294967296n;function $a(r){let t=0,e=0;for(let n=0;n<r.length;++n)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:(e&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function Za(r,t,e){if(e-t<1)return"";let o,i=[],s=0,a;for(;t<e;)a=r[t++],a<128?i[s++]=a:a>191&&a<224?i[s++]=(a&31)<<6|r[t++]&63:a>239&&a<365?(a=((a&7)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,i[s++]=55296+(a>>10),i[s++]=56320+(a&1023)):i[s++]=(a&15)<<12|(r[t++]&63)<<6|r[t++]&63,s>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,i)),s=0);return o!=null?(s>0&&o.push(String.fromCharCode.apply(String,i.slice(0,s))),o.join("")):String.fromCharCode.apply(String,i.slice(0,s))}function Si(r,t,e){let n=e,o,i;for(let s=0;s<r.length;++s)o=r.charCodeAt(s),o<128?t[e++]=o:o<2048?(t[e++]=o>>6|192,t[e++]=o&63|128):(o&64512)===55296&&((i=r.charCodeAt(s+1))&64512)===56320?(o=65536+((o&1023)<<10)+(i&1023),++s,t[e++]=o>>18|240,t[e++]=o>>12&63|128,t[e++]=o>>6&63|128,t[e++]=o&63|128):(t[e++]=o>>12|224,t[e++]=o>>6&63|128,t[e++]=o&63|128);return e-n}function Wt(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function hn(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var vi=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,Wt(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Wt(this,4);return hn(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Wt(this,4);return hn(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Wt(this,4);let t=Ha(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw Wt(this,4);let t=Ga(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw Wt(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return Za(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw Wt(this,t);this.pos+=t}else do if(this.pos>=this.len)throw Wt(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new Ot(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw Wt(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw Wt(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Wt(this,8);let t=hn(this.buf,this.pos+=4),e=hn(this.buf,this.pos+=4);return new Ot(t,e)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=xi(this.buf,this.pos);return this.pos+=Et(t),t}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function Ai(r){return new vi(r instanceof Uint8Array?r:r.subarray())}function Rt(r,t,e){let n=Ai(r);return t.decode(n,void 0,e)}function _i(r){let t=r??8192,e=t>>>1,n,o=t;return function(s){if(s<1||s>e)return Lt(s);o+s>t&&(n=Lt(t),o=0);let a=n.subarray(o,o+=s);return(o&7)!==0&&(o=(o|7)+1),a}}var Ne=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function Ii(){}var Li=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},Qf=_i();function Jf(r){return globalThis.Buffer!=null?Lt(r):Qf(r)}var Lr=class{len;head;tail;states;constructor(){this.len=0,this.head=new Ne(Ii,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new Ne(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new Ci((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(dn,10,Ot.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=Ot.fromBigInt(t);return this._push(dn,e.length(),e)}uint64Number(t){return this._push(bi,Et(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let e=Ot.fromBigInt(t).zzEncode();return this._push(dn,e.length(),e)}sint64Number(t){let e=Ot.fromNumber(t).zzEncode();return this._push(dn,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(Ti,1,t?1:0)}fixed32(t){return this._push(Tr,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=Ot.fromBigInt(t);return this._push(Tr,4,e.lo)._push(Tr,4,e.hi)}fixed64Number(t){let e=Ot.fromNumber(t);return this._push(Tr,4,e.lo)._push(Tr,4,e.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(za,4,t)}double(t){return this._push(Va,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(Ti,1,0):this.uint32(e)._push(eh,e,t)}string(t){let e=$a(t);return e!==0?this.uint32(e)._push(Si,e,t):this._push(Ti,1,0)}fork(){return this.states=new Li(this),this.head=this.tail=new Ne(Ii,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 Ne(Ii,0,0),this.len=0),this}ldelim(){let t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=e,this.len+=n),this}finish(){let t=this.head.next,e=Jf(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function Ti(r,t,e){t[e]=r&255}function th(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var Ci=class extends Ne{next;constructor(t,e){super(th,t,e),this.next=void 0}};function dn(r,t,e){for(;r.hi!==0;)t[e++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)t[e++]=r.lo&127|128,r.lo=r.lo>>>7;t[e++]=r.lo}function Tr(r,t,e){t[e]=r&255,t[e+1]=r>>>8&255,t[e+2]=r>>>16&255,t[e+3]=r>>>24}function eh(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(Lr.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(rh,t,r),this},Lr.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(nh,t,r),this});function rh(r,t,e){t.set(r,e)}function nh(r,t,e){r.length<40?Si(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(M(r),e)}function Ri(){return new Lr}function Dt(r,t){let e=Ri();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var rr;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(rr||(rr={}));function pn(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function Ue(r){function t(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let e=function(i,s){let a=t(i);s.int32(a)},n=function(i){let s=i.int32();return t(s)};return pn("enum",rr.VARINT,e,n)}function Pt(r,t){return pn("message",rr.LENGTH_DELIMITED,r,t)}var Cr=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var lt;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(lt||(lt={}));var Di;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(Di||(Di={}));(function(r){r.codec=()=>Ue(Di)})(lt||(lt={}));var Jt;(function(r){let t;r.codec=()=>(t==null&&(t=Pt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),lt.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let i={},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let a=e.uint32();switch(a>>>3){case 1:{i.Type=lt.codec().decode(e);break}case 2:{i.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Dt(e,r.codec()),r.decode=(e,n)=>Rt(e,r.codec(),n)})(Jt||(Jt={}));var Pi;(function(r){let t;r.codec=()=>(t==null&&(t=Pt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),lt.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let i={},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let a=e.uint32();switch(a>>>3){case 1:{i.Type=lt.codec().decode(e);break}case 2:{i.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Dt(e,r.codec()),r.decode=(e,n)=>Rt(e,r.codec(),n)})(Pi||(Pi={}));var Rr=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},mn=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var Xa={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new mn("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 t}};var Ee=Xa;var Pr={};Tt(Pr,{MAX_RSA_KEY_SIZE:()=>Bi,generateRSAKeyPair:()=>ec,jwkToJWKKeyPair:()=>rc,jwkToPkcs1:()=>ah,jwkToPkix:()=>ki,jwkToRSAPrivateKey:()=>Fi,pkcs1MessageToJwk:()=>Ui,pkcs1MessageToRSAPrivateKey:()=>Mi,pkcs1ToJwk:()=>sh,pkcs1ToRSAPrivateKey:()=>tc,pkixMessageToJwk:()=>Oi,pkixMessageToRSAPublicKey:()=>qi,pkixToJwk:()=>ch,pkixToRSAPublicKey:()=>Ki});var nr=class{type="RSA";jwk;_raw;_multihash;constructor(t,e){this.jwk=t,this._multihash=e}get raw(){return this._raw==null&&(this._raw=Pr.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return at.createV1(114,this._multihash)}toString(){return Y.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:dt(this.raw,t.raw)}verify(t,e){return Ja(this.jwk,e,t)}},Dr=class{type="RSA";jwk;_raw;publicKey;constructor(t,e){this.jwk=t,this.publicKey=e}get raw(){return this._raw==null&&(this._raw=Pr.jwkToPkcs1(this.jwk)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:dt(this.raw,t.raw)}sign(t){return Qa(this.jwk,t)}};var Bi=8192,Ni=18,oh=1062,ih=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function sh(r){let t=ne(r);return Ui(t)}function Ui(r){return{n:O(r[1],"base64url"),e:O(r[2],"base64url"),d:O(r[3],"base64url"),p:O(r[4],"base64url"),q:O(r[5],"base64url"),dp:O(r[6],"base64url"),dq:O(r[7],"base64url"),qi:O(r[8],"base64url"),kty:"RSA"}}function ah(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 ht("JWK was missing components");return he([Ct(Uint8Array.from([0])),Ct(M(r.n,"base64url")),Ct(M(r.e,"base64url")),Ct(M(r.d,"base64url")),Ct(M(r.p,"base64url")),Ct(M(r.q,"base64url")),Ct(M(r.dp,"base64url")),Ct(M(r.dq,"base64url")),Ct(M(r.qi,"base64url"))]).subarray()}function ch(r){let t=ne(r,{offset:0});return Oi(t)}function Oi(r){let t=ne(r[1],{offset:0});return{kty:"RSA",n:O(t[0],"base64url"),e:O(t[1],"base64url")}}function ki(r){if(r.n==null||r.e==null)throw new ht("JWK was missing components");return he([ih,Jr(he([Ct(M(r.n,"base64url")),Ct(M(r.e,"base64url"))]))]).subarray()}function tc(r){let t=ne(r);return Mi(t)}function Mi(r){let t=Ui(r);return Fi(t)}function Ki(r,t){if(r.byteLength>=oh)throw new ze("Key size is too large");let e=ne(r,{offset:0});return qi(e,r,t)}function qi(r,t,e){let n=Oi(r);if(e==null){let o=Te(Jt.encode({Type:lt.RSA,Data:t}));e=Ht(Ni,o)}return new nr(n,e)}function Fi(r){if(oc(r)>Bi)throw new ht("Key size is too large");let t=rc(r),e=Te(Jt.encode({Type:lt.RSA,Data:ki(t.publicKey)})),n=Ht(Ni,e);return new Dr(t.privateKey,new nr(t.publicKey,n))}async function ec(r){if(r>Bi)throw new ht("Key size is too large");let t=await nc(r),e=Te(Jt.encode({Type:lt.RSA,Data:ki(t.publicKey)})),n=Ht(Ni,e);return new Dr(t.privateKey,new nr(t.publicKey,n))}function rc(r){if(r==null)throw new ht("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function nc(r){let t=await Ee.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),e=await uh(t);return{privateKey:e[0],publicKey:e[1]}}async function Qa(r,t){let e=await Ee.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Ee.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},e,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}async function Ja(r,t,e){let n=await Ee.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Ee.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,e instanceof Uint8Array?e:e.subarray())}async function uh(r){if(r.privateKey==null||r.publicKey==null)throw new ht("Private and public key are required");return Promise.all([Ee.get().subtle.exportKey("jwk",r.privateKey),Ee.get().subtle.exportKey("jwk",r.publicKey)])}function oc(r){if(r.kty!=="RSA")throw new ht("invalid key type");if(r.n==null)throw new ht("invalid key modulus");return M(r.n,"base64url").length*8}var yn=class extends Qe{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,da(t);let n=vr(e);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,i=new Uint8Array(o);i.set(n.length>o?t.create().update(n).digest():n);for(let s=0;s<i.length;s++)i[s]^=54;this.iHash.update(i),this.oHash=t.create();for(let s=0;s<i.length;s++)i[s]^=106;this.oHash.update(i),i.fill(0)}update(t){return Xe(this),this.iHash.update(t),this}digestInto(t){Xe(this),je(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));let{oHash:e,iHash:n,finished:o,destroyed:i,blockLen:s,outputLen:a}=this;return t=t,t.finished=o,t.destroyed=i,t.blockLen=s,t.outputLen=a,t.oHash=e._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},zi=(r,t,e)=>new yn(r,t).update(e).digest();zi.create=(r,t)=>new yn(r,t);function ic(r){r.lowS!==void 0&&Xt("lowS",r.lowS),r.prehash!==void 0&&Xt("prehash",r.prehash)}function lh(r){let t=Ir(r);se(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:e,Fp:n,a:o}=t;if(e){if(!n.eql(o,n.ZERO))throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0");if(typeof e!="object"||typeof e.beta!="bigint"||typeof e.splitScalar!="function")throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...t})}var Hi=class extends Error{constructor(t=""){super(t)}},ce={Err:Hi,_tlv:{encode:(r,t)=>{let{Err:e}=ce;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length&1)throw new e("tlv.encode: unpadded data");let n=t.length/2,o=Ar(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let i=n>127?Ar(o.length/2|128):"";return Ar(r)+i+o+t},decode(r,t){let{Err:e}=ce,n=0;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length<2||t[n++]!==r)throw new e("tlv.decode: wrong tlv");let o=t[n++],i=!!(o&128),s=0;if(!i)s=o;else{let c=o&127;if(!c)throw new e("tlv.decode(long): indefinite length not supported");if(c>4)throw new e("tlv.decode(long): byte length is too big");let l=t.subarray(n,n+c);if(l.length!==c)throw new e("tlv.decode: length bytes not complete");if(l[0]===0)throw new e("tlv.decode(long): zero leftmost byte");for(let u of l)s=s<<8|u;if(n+=c,s<128)throw new e("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+s);if(a.length!==s)throw new e("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+s)}}},_int:{encode(r){let{Err:t}=ce;if(r<ue)throw new t("integer: negative integers are not allowed");let e=Ar(r);if(Number.parseInt(e[0],16)&8&&(e="00"+e),e.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return e},decode(r){let{Err:t}=ce;if(r[0]&128)throw new t("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return ie(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=ce,o=it("signature",r),{v:i,l:s}=n.decode(48,o);if(s.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,i),{v:l,l:u}=n.decode(2,c);if(u.length)throw new t("invalid signature: left bytes after parsing");return{r:e.decode(a),s:e.decode(l)}},hexFromSig(r){let{_tlv:t,_int:e}=ce,n=t.encode(2,e.encode(r.r)),o=t.encode(2,e.encode(r.s)),i=n+o;return t.encode(48,i)}},ue=BigInt(0),gt=BigInt(1),Ny=BigInt(2),sc=BigInt(3),Uy=BigInt(4);function fh(r){let t=lh(r),{Fp:e}=t,n=xe(t.n,t.nBitLength),o=t.toBytes||((y,h,x)=>{let v=h.toAffine();return be(Uint8Array.from([4]),e.toBytes(v.x),e.toBytes(v.y))}),i=t.fromBytes||(y=>{let h=y.subarray(1),x=e.fromBytes(h.subarray(0,e.BYTES)),v=e.fromBytes(h.subarray(e.BYTES,2*e.BYTES));return{x,y:v}});function s(y){let{a:h,b:x}=t,v=e.sqr(y),p=e.mul(v,y);return e.add(e.add(p,e.mul(y,h)),x)}if(!e.eql(e.sqr(t.Gy),s(t.Gx)))throw new Error("bad generator point: equation left != right");function a(y){return on(y,gt,t.n)}function c(y){let{allowedPrivateKeyLengths:h,nByteLength:x,wrapPrivateKey:v,n:p}=t;if(h&&typeof y!="bigint"){if(Le(y)&&(y=ge(y)),typeof y!="string"||!h.includes(y.length))throw new Error("invalid private key");y=y.padStart(x*2,"0")}let _;try{_=typeof y=="bigint"?y:ie(it("private key",y,x))}catch{throw new Error("invalid private key, expected hex or "+x+" bytes, got "+typeof y)}return v&&(_=Q(_,p)),Ut("private key",_,gt,p),_}function l(y){if(!(y instanceof d))throw new Error("ProjectivePoint expected")}let u=er((y,h)=>{let{px:x,py:v,pz:p}=y;if(e.eql(p,e.ONE))return{x,y:v};let _=y.is0();h==null&&(h=_?e.ONE:e.inv(p));let D=e.mul(x,h),P=e.mul(v,h),T=e.mul(p,h);if(_)return{x:e.ZERO,y:e.ZERO};if(!e.eql(T,e.ONE))throw new Error("invZ was invalid");return{x:D,y:P}}),f=er(y=>{if(y.is0()){if(t.allowInfinityPoint&&!e.is0(y.py))return;throw new Error("bad point: ZERO")}let{x:h,y:x}=y.toAffine();if(!e.isValid(h)||!e.isValid(x))throw new Error("bad point: x or y not FE");let v=e.sqr(x),p=s(h);if(!e.eql(v,p))throw new Error("bad point: equation left != right");if(!y.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class d{constructor(h,x,v){if(h==null||!e.isValid(h))throw new Error("x required");if(x==null||!e.isValid(x))throw new Error("y required");if(v==null||!e.isValid(v))throw new Error("z required");this.px=h,this.py=x,this.pz=v,Object.freeze(this)}static fromAffine(h){let{x,y:v}=h||{};if(!h||!e.isValid(x)||!e.isValid(v))throw new Error("invalid affine point");if(h instanceof d)throw new Error("projective point not allowed");let p=_=>e.eql(_,e.ZERO);return p(x)&&p(v)?d.ZERO:new d(x,v,e.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(h){let x=e.invertBatch(h.map(v=>v.pz));return h.map((v,p)=>v.toAffine(x[p])).map(d.fromAffine)}static fromHex(h){let x=d.fromAffine(i(it("pointHex",h)));return x.assertValidity(),x}static fromPrivateKey(h){return d.BASE.multiply(c(h))}static msm(h,x){return cn(d,n,h,x)}_setWindowSize(h){b.setWindowSize(this,h)}assertValidity(){f(this)}hasEvenY(){let{y:h}=this.toAffine();if(e.isOdd)return!e.isOdd(h);throw new Error("Field doesn't support isOdd")}equals(h){l(h);let{px:x,py:v,pz:p}=this,{px:_,py:D,pz:P}=h,T=e.eql(e.mul(x,P),e.mul(_,p)),L=e.eql(e.mul(v,P),e.mul(D,p));return T&&L}negate(){return new d(this.px,e.neg(this.py),this.pz)}double(){let{a:h,b:x}=t,v=e.mul(x,sc),{px:p,py:_,pz:D}=this,P=e.ZERO,T=e.ZERO,L=e.ZERO,C=e.mul(p,p),et=e.mul(_,_),W=e.mul(D,D),k=e.mul(p,_);return k=e.add(k,k),L=e.mul(p,D),L=e.add(L,L),P=e.mul(h,L),T=e.mul(v,W),T=e.add(P,T),P=e.sub(et,T),T=e.add(et,T),T=e.mul(P,T),P=e.mul(k,P),L=e.mul(v,L),W=e.mul(h,W),k=e.sub(C,W),k=e.mul(h,k),k=e.add(k,L),L=e.add(C,C),C=e.add(L,C),C=e.add(C,W),C=e.mul(C,k),T=e.add(T,C),W=e.mul(_,D),W=e.add(W,W),C=e.mul(W,k),P=e.sub(P,C),L=e.mul(W,et),L=e.add(L,L),L=e.add(L,L),new d(P,T,L)}add(h){l(h);let{px:x,py:v,pz:p}=this,{px:_,py:D,pz:P}=h,T=e.ZERO,L=e.ZERO,C=e.ZERO,et=t.a,W=e.mul(t.b,sc),k=e.mul(x,_),pt=e.mul(v,D),S=e.mul(p,P),I=e.add(x,v),R=e.add(_,D);I=e.mul(I,R),R=e.add(k,pt),I=e.sub(I,R),R=e.add(x,p);let w=e.add(_,P);return R=e.mul(R,w),w=e.add(k,S),R=e.sub(R,w),w=e.add(v,p),T=e.add(D,P),w=e.mul(w,T),T=e.add(pt,S),w=e.sub(w,T),C=e.mul(et,R),T=e.mul(W,S),C=e.add(T,C),T=e.sub(pt,C),C=e.add(pt,C),L=e.mul(T,C),pt=e.add(k,k),pt=e.add(pt,k),S=e.mul(et,S),R=e.mul(W,R),pt=e.add(pt,S),S=e.sub(k,S),S=e.mul(et,S),R=e.add(R,S),k=e.mul(pt,R),L=e.add(L,k),k=e.mul(w,R),T=e.mul(I,T),T=e.sub(T,k),k=e.mul(I,pt),C=e.mul(w,C),C=e.add(C,k),new d(T,L,C)}subtract(h){return this.add(h.negate())}is0(){return this.equals(d.ZERO)}wNAF(h){return b.wNAFCached(this,h,d.normalizeZ)}multiplyUnsafe(h){let{endo:x,n:v}=t;Ut("scalar",h,ue,v);let p=d.ZERO;if(h===ue)return p;if(this.is0()||h===gt)return this;if(!x||b.hasPrecomputes(this))return b.wNAFCachedUnsafe(this,h,d.normalizeZ);let{k1neg:_,k1:D,k2neg:P,k2:T}=x.splitScalar(h),L=p,C=p,et=this;for(;D>ue||T>ue;)D&gt&&(L=L.add(et)),T&gt&&(C=C.add(et)),et=et.double(),D>>=gt,T>>=gt;return _&&(L=L.negate()),P&&(C=C.negate()),C=new d(e.mul(C.px,x.beta),C.py,C.pz),L.add(C)}multiply(h){let{endo:x,n:v}=t;Ut("scalar",h,gt,v);let p,_;if(x){let{k1neg:D,k1:P,k2neg:T,k2:L}=x.splitScalar(h),{p:C,f:et}=this.wNAF(P),{p:W,f:k}=this.wNAF(L);C=b.constTimeNegate(D,C),W=b.constTimeNegate(T,W),W=new d(e.mul(W.px,x.beta),W.py,W.pz),p=C.add(W),_=et.add(k)}else{let{p:D,f:P}=this.wNAF(h);p=D,_=P}return d.normalizeZ([p,_])[0]}multiplyAndAddUnsafe(h,x,v){let p=d.BASE,_=(P,T)=>T===ue||T===gt||!P.equals(p)?P.multiplyUnsafe(T):P.multiply(T),D=_(this,x).add(_(h,v));return D.is0()?void 0:D}toAffine(h){return u(this,h)}isTorsionFree(){let{h,isTorsionFree:x}=t;if(h===gt)return!0;if(x)return x(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h,clearCofactor:x}=t;return h===gt?this:x?x(d,this):this.multiplyUnsafe(t.h)}toRawBytes(h=!0){return Xt("isCompressed",h),this.assertValidity(),o(d,this,h)}toHex(h=!0){return Xt("isCompressed",h),ge(this.toRawBytes(h))}}d.BASE=new d(t.Gx,t.Gy,e.ONE),d.ZERO=new d(e.ZERO,e.ONE,e.ZERO);let g=t.nBitLength,b=an(d,t.endo?Math.ceil(g/2):g);return{CURVE:t,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:s,isWithinCurveOrder:a}}function hh(r){let t=Ir(r);return se(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function ac(r){let t=hh(r),{Fp:e,n}=t,o=e.BYTES+1,i=2*e.BYTES+1;function s(S){return Q(S,n)}function a(S){return sn(S,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:u,isWithinCurveOrder:f}=fh({...t,toBytes(S,I,R){let w=I.toAffine(),m=e.toBytes(w.x),E=be;return Xt("isCompressed",R),R?E(Uint8Array.from([I.hasEvenY()?2:3]),m):E(Uint8Array.from([4]),m,e.toBytes(w.y))},fromBytes(S){let I=S.length,R=S[0],w=S.subarray(1);if(I===o&&(R===2||R===3)){let m=ie(w);if(!on(m,gt,e.ORDER))throw new Error("Point is not on curve");let E=u(m),A;try{A=e.sqrt(E)}catch(z){let H=z instanceof Error?": "+z.message:"";throw new Error("Point is not on curve"+H)}let B=(A&gt)===gt;return(R&1)===1!==B&&(A=e.neg(A)),{x:m,y:A}}else if(I===i&&R===4){let m=e.fromBytes(w.subarray(0,e.BYTES)),E=e.fromBytes(w.subarray(e.BYTES,2*e.BYTES));return{x:m,y:E}}else{let m=o,E=i;throw new Error("invalid Point, expected length of "+m+", or uncompressed "+E+", got "+I)}}}),d=S=>ge(Re(S,t.nByteLength));function g(S){let I=n>>gt;return S>I}function b(S){return g(S)?s(-S):S}let y=(S,I,R)=>ie(S.slice(I,R));class h{constructor(I,R,w){Ut("r",I,gt,n),Ut("s",R,gt,n),this.r=I,this.s=R,w!=null&&(this.recovery=w),Object.freeze(this)}static fromCompact(I){let R=t.nByteLength;return I=it("compactSignature",I,R*2),new h(y(I,0,R),y(I,R,2*R))}static fromDER(I){let{r:R,s:w}=ce.toSig(it("DER",I));return new h(R,w)}assertValidity(){}addRecoveryBit(I){return new h(this.r,this.s,I)}recoverPublicKey(I){let{r:R,s:w,recovery:m}=this,E=P(it("msgHash",I));if(m==null||![0,1,2,3].includes(m))throw new Error("recovery id invalid");let A=m===2||m===3?R+t.n:R;if(A>=e.ORDER)throw new Error("recovery id 2 or 3 invalid");let B=(m&1)===0?"02":"03",U=c.fromHex(B+d(A)),z=a(A),H=s(-E*z),V=s(w*z),Z=c.BASE.multiplyAndAddUnsafe(U,H,V);if(!Z)throw new Error("point at infinify");return Z.assertValidity(),Z}hasHighS(){return g(this.s)}normalizeS(){return this.hasHighS()?new h(this.r,s(-this.s),this.recovery):this}toDERRawBytes(){return _r(this.toDERHex())}toDERHex(){return ce.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return _r(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}let x={isValidPrivateKey(S){try{return l(S),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{let S=ii(t.n);return Ca(t.randomBytes(S),t.n)},precompute(S=8,I=c.BASE){return I._setWindowSize(S),I.multiply(BigInt(3)),I}};function v(S,I=!0){return c.fromPrivateKey(S).toRawBytes(I)}function p(S){let I=Le(S),R=typeof S=="string",w=(I||R)&&S.length;return I?w===o||w===i:R?w===2*o||w===2*i:S instanceof c}function _(S,I,R=!0){if(p(S))throw new Error("first arg must be private key");if(!p(I))throw new Error("second arg must be public key");return c.fromHex(I).multiply(l(S)).toRawBytes(R)}let D=t.bits2int||function(S){if(S.length>8192)throw new Error("input is too large");let I=ie(S),R=S.length*8-t.nBitLength;return R>0?I>>BigInt(R):I},P=t.bits2int_modN||function(S){return s(D(S))},T=De(t.nBitLength);function L(S){return Ut("num < 2^"+t.nBitLength,S,ue,T),Re(S,t.nByteLength)}function C(S,I,R=et){if(["recovered","canonical"].some(ct=>ct in R))throw new Error("sign() legacy options not supported");let{hash:w,randomBytes:m}=t,{lowS:E,prehash:A,extraEntropy:B}=R;E==null&&(E=!0),S=it("msgHash",S),ic(R),A&&(S=it("prehashed msgHash",w(S)));let U=P(S),z=l(I),H=[L(z),L(U)];if(B!=null&&B!==!1){let ct=B===!0?m(e.BYTES):B;H.push(it("extraEntropy",ct))}let V=be(...H),Z=U;function ft(ct){let bt=D(ct);if(!f(bt))return;let It=a(bt),yt=c.BASE.multiply(bt).toAffine(),xt=s(yt.x);if(xt===ue)return;let Bt=s(It*s(Z+xt*z));if(Bt===ue)return;let zt=(yt.x===xt?0:2)|Number(yt.y&gt),pr=Bt;return E&&g(Bt)&&(pr=b(Bt),zt^=1),new h(xt,pr,zt)}return{seed:V,k2sig:ft}}let et={lowS:t.lowS,prehash:!1},W={lowS:t.lowS,prehash:!1};function k(S,I,R=et){let{seed:w,k2sig:m}=C(S,I,R),E=t;return Aa(E.hash.outputLen,E.nByteLength,E.hmac)(w,m)}c.BASE._setWindowSize(8);function pt(S,I,R,w=W){let m=S;I=it("msgHash",I),R=it("publicKey",R);let{lowS:E,prehash:A,format:B}=w;if(ic(w),"strict"in w)throw new Error("options.strict was renamed to lowS");if(B!==void 0&&B!=="compact"&&B!=="der")throw new Error("format must be compact or der");let U=typeof m=="string"||Le(m),z=!U&&!B&&typeof m=="object"&&m!==null&&typeof m.r=="bigint"&&typeof m.s=="bigint";if(!U&&!z)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let H,V;try{if(z&&(H=new h(m.r,m.s)),U){try{B!=="compact"&&(H=h.fromDER(m))}catch(zt){if(!(zt instanceof ce.Err))throw zt}!H&&B!=="der"&&(H=h.fromCompact(m))}V=c.fromHex(R)}catch{return!1}if(!H||E&&H.hasHighS())return!1;A&&(I=t.hash(I));let{r:Z,s:ft}=H,ct=P(I),bt=a(ft),It=s(ct*bt),yt=s(Z*bt),xt=c.BASE.multiplyAndAddUnsafe(V,It,yt)?.toAffine();return xt?s(xt.x)===Z:!1}return{CURVE:t,getPublicKey:v,getSharedSecret:_,sign:k,verify:pt,ProjectivePoint:c,Signature:h,utils:x}}function dh(r){return{hash:r,hmac:(t,...e)=>zi(r,t,Wo(...e)),randomBytes:rn}}function cc(r,t){let e=n=>ac({...r,...dh(n)});return{...e(t),create:e}}var fc=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),uc=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),ph=BigInt(1),Vi=BigInt(2),lc=(r,t)=>(r+t/Vi)/t;function mh(r){let t=fc,e=BigInt(3),n=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%t,u=l*l*r%t,f=nt(u,e,t)*u%t,d=nt(f,e,t)*u%t,g=nt(d,Vi,t)*l%t,b=nt(g,o,t)*g%t,y=nt(b,i,t)*b%t,h=nt(y,a,t)*y%t,x=nt(h,c,t)*h%t,v=nt(x,a,t)*y%t,p=nt(v,e,t)*u%t,_=nt(p,s,t)*b%t,D=nt(_,n,t)*l%t,P=nt(D,Vi,t);if(!Gi.eql(Gi.sqr(P),r))throw new Error("Cannot find square root");return P}var Gi=xe(fc,void 0,void 0,{sqrt:mh}),Oe=cc({a:BigInt(0),b:BigInt(7),Fp:Gi,n:uc,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let t=uc,e=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-ph*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=e,s=BigInt("0x100000000000000000000000000000000"),a=lc(i*r,t),c=lc(-n*r,t),l=Q(r-a*e-c*o,t),u=Q(-a*n-c*i,t),f=l>s,d=u>s;if(f&&(l=t-l),d&&(u=t-u),l>s||u>s)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:f,k1:l,k2neg:d,k2:u}}}},Te),Vy=BigInt(0);var Gy=Oe.ProjectivePoint;function hc(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function dc(r,t,e){let n=Ze.digest(e instanceof Uint8Array?e:e.subarray());if(hc(n))return n.then(({digest:o})=>Oe.verify(t,o,r)).catch(o=>{throw new Rr(String(o))});try{return Oe.verify(t,n.digest,r)}catch(o){throw new Rr(String(o))}}var gn=class{type="secp256k1";raw;_key;constructor(t){this._key=mc(t),this.raw=pc(this._key)}toMultihash(){return Vt.digest(jt(this))}toCID(){return at.createV1(114,this.toMultihash())}toString(){return Y.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:dt(this.raw,t.raw)}verify(t,e){return dc(this._key,e,t)}};function Wi(r){return new gn(r)}function pc(r){return Oe.ProjectivePoint.fromHex(r).toRawBytes(!0)}function mc(r){try{return Oe.ProjectivePoint.fromHex(r),r}catch(t){throw new ze(String(t))}}function yc(r,t){let{Type:e,Data:n}=Jt.decode(r),o=n??new Uint8Array;switch(e){case lt.RSA:return Ki(o,t);case lt.Ed25519:return di(o);case lt.secp256k1:return Wi(o);case lt.ECDSA:return Go(o);default:throw new He}}function gc(r){let{Type:t,Data:e}=Jt.decode(r.digest),n=e??new Uint8Array;switch(t){case lt.Ed25519:return di(n);case lt.secp256k1:return Wi(n);case lt.ECDSA:return Go(n);default:throw new He}}function jt(r){return Jt.encode({Type:lt[r.type],Data:r.raw})}var bc=Symbol.for("nodejs.util.inspect.custom"),yh=114,Br=class{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[yo]=!0;toString(){return this.string==null&&(this.string=Y.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return at.createV1(yh,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return dt(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return dt(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[bc](){return`PeerId(${this.toString()})`}},bn=class extends Br{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},xn=class extends Br{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},wn=class extends Br{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},gh=2336,Nr=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=Vt.digest(M(this.url))}[bc](){return`PeerId(${this.url})`}[yo]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return at.createV1(gh,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=O(t)),t.toString()===this.toString())}};var bh=114,xc=2336;function $i(r,t){let e;if(r.charAt(0)==="1"||r.charAt(0)==="Q")e=Kt(Y.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return xh(at.parse(r));if(t==null)throw new ht('Please pass a multibase decoder for strings that do not start with "1" or "Q"');e=Kt(t.decode(r))}return or(e)}function or(r){if(Eh(r))return new bn({multihash:r});if(wh(r))try{let t=gc(r);if(t.type==="Ed25519")return new xn({multihash:r,publicKey:t});if(t.type==="secp256k1")return new wn({multihash:r,publicKey:t})}catch{let e=O(r.digest);return new Nr(new URL(e))}throw new Zr("Supplied PeerID Multihash is invalid")}function xh(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==bh&&r.code!==xc)throw new $r("Supplied PeerID CID is invalid");if(r.code===xc){let t=O(r.multihash.digest);return new Nr(new URL(t))}return or(r.multihash)}function wh(r){return r.code===Vt.code}function Eh(r){return r.code===Ze.code}var Ur;(function(r){let t;r.codec=()=>(t==null&&(t=Pt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.publicKey!=null&&e.publicKey.byteLength>0&&(n.uint32(10),n.bytes(e.publicKey)),e.payloadType!=null&&e.payloadType.byteLength>0&&(n.uint32(18),n.bytes(e.payloadType)),e.payload!=null&&e.payload.byteLength>0&&(n.uint32(26),n.bytes(e.payload)),e.signature!=null&&e.signature.byteLength>0&&(n.uint32(42),n.bytes(e.signature)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let i={publicKey:ot(0),payloadType:ot(0),payload:ot(0),signature:ot(0)},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let a=e.uint32();switch(a>>>3){case 1:{i.publicKey=e.bytes();break}case 2:{i.payloadType=e.bytes();break}case 3:{i.payload=e.bytes();break}case 5:{i.signature=e.bytes();break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Dt(e,r.codec()),r.decode=(e,n)=>Rt(e,r.codec(),n)})(Ur||(Ur={}));var En=class extends Error{constructor(t="Invalid signature"){super(t),this.name="InvalidSignatureError"}};var Or=class r{static createFromProtobuf=async t=>{let e=Ur.decode(t),n=yc(e.publicKey);return new r({publicKey:n,payloadType:e.payloadType,payload:e.payload,signature:e.signature})};static seal=async(t,e)=>{if(e==null)throw new Error("Missing private key");let n=t.domain,o=t.codec,i=t.marshal(),s=wc(n,o,i),a=await e.sign(s.subarray());return new r({publicKey:e.publicKey,payloadType:o,payload:i,signature:a})};static openAndCertify=async(t,e)=>{let n=await r.createFromProtobuf(t);if(!await n.validate(e))throw new En("Envelope signature is not valid for the given domain");return n};publicKey;payloadType;payload;signature;marshaled;constructor(t){let{publicKey:e,payloadType:n,payload:o,signature:i}=t;this.publicKey=e,this.payloadType=n,this.payload=o,this.signature=i}marshal(){return this.marshaled==null&&(this.marshaled=Ur.encode({publicKey:jt(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(t){return dt(this.marshal(),t.marshal())}async validate(t){let e=wc(t,this.payloadType,this.payload);return this.publicKey.verify(e.subarray(),this.signature)}},wc=(r,t,e)=>{let n=M(r),o=qt(n.byteLength),i=qt(t.length),s=qt(e.length);return new ut(o,n,i,t,s,e)};var Sn=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let e=this.index,n=t();return n===void 0&&(this.index=e),n}parseWith(t){let e=t();if(this.index===this.input.length)return e}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(t){return this.readAtomically(()=>{let e=this.readChar();if(e===t)return e})}readSeparator(t,e,n){return this.readAtomically(()=>{if(!(e>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,e,n,o){return this.readAtomically(()=>{let i=0,s=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let u=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let d=Number.parseInt(f,t);if(!Number.isNaN(d))return d});if(u===void 0)break;if(i*=t,i+=u,i>l||(s+=1,e!==void 0&&s>e))return}if(s!==0)return!n&&c&&s>1?void 0:i})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let e=0;e<t.length;e++){let n=this.readSeparator(".",e,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[e]=n}return t})}readIPv6Addr(){let t=e=>{for(let n=0;n<e.length/2;n++){let o=n*2;if(n<e.length-3){let s=this.readSeparator(":",n,()=>this.readIPv4Addr());if(s!==void 0)return e[o]=s[0],e[o+1]=s[1],e[o+2]=s[2],e[o+3]=s[3],[o+4,!0]}let i=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(i===void 0)return[o,!1];e[o]=i>>8,e[o+1]=i&255}return[e.length,!1]};return this.readAtomically(()=>{let e=new Uint8Array(16),[n,o]=t(e);if(n===16)return e;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let i=new Uint8Array(14),s=16-(n+2),[a]=t(i.subarray(0,s));return e.set(i.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Ec=45,Sh=15,ir=new Sn;function Zi(r){if(!(r.length>Sh))return ir.new(r).parseWith(()=>ir.readIPv4Addr())}function Yi(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Ec))return ir.new(r).parseWith(()=>ir.readIPv6Addr())}function vn(r,t=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>Ec)return;let e=ir.new(r).parseWith(()=>ir.readIPAddr());if(e)return t&&e.length===4?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,e[0],e[1],e[2],e[3]]):e}var yb=parseInt("0xFFFF",16),gb=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function An(r){return!!Zi(r)}function _n(r){return!!Yi(r)}function In(r){return!!vn(r)}var Ac=An,Th=_n,ji=function(r){let t=0;if(r=r.toString().trim(),Ac(r)){let e=new Uint8Array(t+4);return r.split(/\./g).forEach(n=>{e[t++]=parseInt(n,10)&255}),e}if(Th(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let i=Ac(e[n]),s;i&&(s=ji(e[n]),e[n]=O(s.slice(0,2),"base16")),s!=null&&++n<8&&e.splice(n,0,O(s.slice(2,4),"base16"))}if(e[0]==="")for(;e.length<8;)e.unshift("0");else if(e[e.length-1]==="")for(;e.length<8;)e.push("0");else if(e.length<8){for(n=0;n<e.length&&e[n]!=="";n++);let i=[n,1];for(n=9-e.length;n>0;n--)i.push("0");e.splice.apply(e,i)}let o=new Uint8Array(t+16);for(n=0;n<e.length;n++){let i=parseInt(e[n],16);o[t++]=i>>8&255,o[t++]=i&255}return o}throw new Error("invalid ip address")},_c=function(r,t=0,e){t=~~t,e=e??r.length-t;let n=new DataView(r.buffer);if(e===4){let o=[];for(let i=0;i<e;i++)o.push(r[t+i]);return o.join(".")}if(e===16){let o=[];for(let i=0;i<e;i+=2)o.push(n.getUint16(t+i).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var sr={},Xi={},Ch=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,-1,"ip6zone"],[43,8,"ipcidr"],[53,-1,"dns",!0],[54,-1,"dns4",!0],[55,-1,"dns6",!0],[56,-1,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,-1,"unix",!1,!0],[421,-1,"ipfs"],[421,-1,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,-1,"garlic64"],[448,0,"tls"],[449,-1,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,-1,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,-1,"http-path"],[777,-1,"memory"]];Ch.forEach(r=>{let t=Rh(...r);Xi[t.code]=t,sr[t.name]=t});function Rh(r,t,e,n,o){return{code:r,size:t,name:e,resolvable:!!n,path:!!o}}function J(r){if(typeof r=="number"){if(Xi[r]!=null)return Xi[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(sr[r]!=null)return sr[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var tx=J("ip4"),ex=J("ip6"),rx=J("ipcidr");function es(r,t){switch(J(r).code){case 4:case 41:return Ph(t);case 42:return ts(t);case 43:return O(t,"base10");case 6:case 273:case 33:case 132:return Lc(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return ts(t);case 421:return Oh(t);case 444:return Tc(t);case 445:return Tc(t);case 466:return Uh(t);case 481:return globalThis.encodeURIComponent(ts(t));default:return O(t,"base16")}}function rs(r,t){switch(J(r).code){case 4:return Ic(t);case 41:return Ic(t);case 42:return Ji(t);case 43:return M(t,"base10");case 6:case 273:case 33:case 132:return ns(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Ji(t);case 421:return Bh(t);case 444:return kh(t);case 445:return Mh(t);case 466:return Nh(t);case 481:return Ji(globalThis.decodeURIComponent(t));default:return M(t,"base16")}}var Qi=Object.values(wr).map(r=>r.decoder),Dh=function(){let r=Qi[0].or(Qi[1]);return Qi.slice(2).forEach(t=>r=r.or(t)),r}();function Ic(r){if(!In(r))throw new Error("invalid ip address");return ji(r)}function Ph(r){let t=_c(r,0,r.length);if(t==null)throw new Error("ipBuff is required");if(!In(t))throw new Error("invalid ip address");return t}function ns(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,r),new Uint8Array(t)}function Lc(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function Ji(r){let t=M(r),e=Uint8Array.from(qt(t.length));return Nt([e,t],e.length+t.length)}function ts(r){let t=ae(r);if(r=r.slice(Et(t)),r.length!==t)throw new Error("inconsistent lengths");return O(r)}function Bh(r){let t;r[0]==="Q"||r[0]==="1"?t=Kt(Y.decode(`z${r}`)).bytes:t=at.parse(r).multihash.bytes;let e=Uint8Array.from(qt(t.length));return Nt([e,t],e.length+t.length)}function Nh(r){let t=Dh.decode(r),e=Uint8Array.from(qt(t.length));return Nt([e,t],e.length+t.length)}function Uh(r){let t=ae(r),e=r.slice(Et(t));if(e.length!==t)throw new Error("inconsistent lengths");return"u"+O(e,"base64url")}function Oh(r){let t=ae(r),e=r.slice(Et(t));if(e.length!==t)throw new Error("inconsistent lengths");return O(e,"base58btc")}function kh(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==16)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);let e=re.decode("b"+t[0]),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=ns(n);return Nt([e,o],e.length+o.length)}function Mh(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let e=re.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=ns(n);return Nt([e,o],e.length+o.length)}function Tc(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=O(t,"base32"),o=Lc(e);return`${n}:${o}`}function Cc(r){r=os(r);let t=[],e=[],n=null,o=r.split("/").slice(1);if(o.length===1&&o[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let i=0;i<o.length;i++){let s=o[i],a=J(s);if(a.size===0){t.push([a.code]),e.push([a.code]);continue}if(i++,i>=o.length)throw new Tn("invalid address: "+r);if(a.path===!0){n=os(o.slice(i).join("/")),t.push([a.code,rs(a.code,n)]),e.push([a.code,n]);break}let c=rs(a.code,o[i]);t.push([a.code,c]),e.push([a.code,es(a.code,c)])}return{string:Rc(e),bytes:Ln(t),tuples:t,stringTuples:e,path:n}}function is(r){let t=[],e=[],n=null,o=0;for(;o<r.length;){let i=ae(r,o),s=Et(i),a=J(i),c=Kh(a,r.slice(o+s));if(c===0){t.push([i]),e.push([i]),o+=s;continue}let l=r.slice(o+s,o+s+c);if(o+=c+s,o>r.length)throw new Tn("Invalid address Uint8Array: "+O(r,"base16"));t.push([i,l]);let u=es(i,l);if(e.push([i,u]),a.path===!0){n=u;break}}return{bytes:Uint8Array.from(r),string:Rc(e),tuples:t,stringTuples:e,path:n}}function Rc(r){let t=[];return r.map(e=>{let n=J(e[0]);return t.push(n.name),e.length>1&&e[1]!=null&&t.push(e[1]),null}),os(t.join("/"))}function Ln(r){return Nt(r.map(t=>{let e=J(t[0]),n=Uint8Array.from(qt(e.code));return t.length>1&&t[1]!=null&&(n=Nt([n,t[1]])),n}))}function Kh(r,t){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let e=ae(t instanceof Uint8Array?t:Uint8Array.from(t));return e+Et(e)}}function os(r){return"/"+r.trim().split("/").filter(t=>t).join("/")}var Tn=class extends Error{static name="ParseError";name="ParseError";constructor(t){super(`Error parsing address: ${t}`)}};var qh=Symbol.for("nodejs.util.inspect.custom"),as=Symbol.for("@multiformats/js-multiaddr/multiaddr"),Fh=[J("dns").code,J("dns4").code,J("dns6").code,J("dnsaddr").code],ss=class extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}},Cn=class r{bytes;#t;#e;#r;#n;[as]=!0;constructor(t){t==null&&(t="");let e;if(t instanceof Uint8Array)e=is(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=Cc(t)}else if(Pc(t))e=is(t.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=e.bytes,this.#t=e.string,this.#e=e.tuples,this.#r=e.stringTuples,this.#n=e.path}toString(){return this.#t}toJSON(){return this.toString()}toOptions(){let t,e,n,o,i="",s=J("tcp"),a=J("udp"),c=J("ip4"),l=J("ip6"),u=J("dns6"),f=J("ip6zone");for(let[g,b]of this.stringTuples())g===f.code&&(i=`%${b??""}`),Fh.includes(g)&&(e=s.name==="tcp"?"tcp":"udp",o=443,n=`${b??""}${i}`,t=g===u.code?6:4),(g===s.code||g===a.code)&&(e=J(g).name==="tcp"?"tcp":"udp",o=parseInt(b??"")),(g===c.code||g===l.code)&&(e=J(g).name==="tcp"?"tcp":"udp",n=`${b??""}${i}`,t=g===l.code?6:4);if(t==null||e==null||n==null||o==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:t,host:n,transport:e,port:o}}protos(){return this.#e.map(([t])=>Object.assign({},J(t)))}protoCodes(){return this.#e.map(([t])=>t)}protoNames(){return this.#e.map(([t])=>J(t).name)}tuples(){return this.#e.map(([t,e])=>e==null?[t]:[t,e])}stringTuples(){return this.#r.map(([t,e])=>e==null?[t]:[t,e])}encapsulate(t){return t=new r(t),new r(this.toString()+t.toString())}decapsulate(t){let e=t.toString(),n=this.toString(),o=n.lastIndexOf(e);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${t.toString()}`);return new r(n.slice(0,o))}decapsulateCode(t){let e=this.tuples();for(let n=e.length-1;n>=0;n--)if(e[n][0]===t)return new r(Ln(e.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,o])=>{n===sr.p2p.code&&t.push([n,o]),n===sr["p2p-circuit"].code&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?O(Y.decode(`z${n}`),"base58btc"):O(at.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#n}equals(t){return dt(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(i=>i.resolvable);if(e==null)return[this];let n=Dc.get(e.name);if(n==null)throw new ss(`no available resolver for ${e.name}`);return(await n(this,t)).map(i=>vt(i))}nodeAddress(){let t=this.toOptions();if(t.transport!=="tcp"&&t.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${t.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:t.family,address:t.host,port:t.port}}isThinWaistAddress(t){let e=(t??this).protos();return!(e.length!==2||e[0].code!==4&&e[0].code!==41||e[1].code!==6&&e[1].code!==273)}[qh](){return`Multiaddr(${this.#t})`}};var Dc=new Map;function Pc(r){return!!r?.[as]}function vt(r){return new Cn(r)}function $t(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var Rn=class extends Error{type;code;constructor(t,e,n){super(t??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=e??"ABORT_ERR"}};async function ke(r,t,e){if(t==null)return r;if(t.aborted)return r.catch(()=>{}),Promise.reject(new Rn(e?.errorMessage,e?.errorCode,e?.errorName));let n,o=new Rn(e?.errorMessage,e?.errorCode,e?.errorName);try{return await Promise.race([r,new Promise((i,s)=>{n=()=>{s(o)},t.addEventListener("abort",n)})])}finally{n!=null&&t.removeEventListener("abort",n)}}var cs=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=$t(),this.haveNext=$t()}[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 t=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=$t(),t}async throw(t){return this.ended=!0,this.error=t,t!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(t)),{done:!0,value:void 0}}async return(){let t={done:!0,value:void 0};return this.ended=!0,this.nextResult=t,this.haveNext.resolve(),t}async push(t,e){await this._push(t,e)}async end(t,e){t!=null?await this.throw(t):await this._push(void 0,e)}async _push(t,e){if(t!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;t!=null?this.nextResult={done:!1,value:t}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=$t(),await ke(this.readNext.promise,e?.signal,e)}};function Dn(){return new cs}var Pn=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Bc(r,t){let e=Dn();r.sink(e).catch(async s=>{await e.end(s)}),r.sink=async s=>{for await(let a of s)await e.push(a);await e.end()};let n=r.source;r.source[Symbol.iterator]!=null?n=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(n=r.source[Symbol.asyncIterator]());let o=new ut;return{read:async s=>{if(s?.signal?.throwIfAborted(),s?.bytes==null){let{done:c,value:l}=await ke(n.next(),s?.signal);return c===!0?null:l}for(;o.byteLength<s.bytes;){let{value:c,done:l}=await ke(n.next(),s?.signal);if(l===!0)throw new Pn("unexpected end of input");o.append(c)}let a=o.sublist(0,s.bytes);return o.consume(s.bytes),a},write:async(s,a)=>{a?.signal?.throwIfAborted(),s instanceof Uint8Array?await e.push(s,a):await e.push(s.subarray(),a)},unwrap:()=>{if(o.byteLength>0){let s=r.source;r.source=async function*(){t?.yieldBytes===!1?yield o:yield*o,yield*s}()}return r}}}var Bn=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Nn=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Un=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Nc(r,t={}){let e=Bc(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=Et(t.maxDataLength));let n=t?.lengthDecoder??ae,o=t?.lengthEncoder??qt;return{read:async s=>{let a=-1,c=new ut;for(;;){c.append(await e.read({...s,bytes:1}));try{a=n(c)}catch(l){if(l instanceof RangeError)continue;throw l}if(a<0)throw new Bn("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new Un("message length length too long");if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new Nn("message length too long");return e.read({...s,bytes:a})},write:async(s,a)=>{await e.write(new ut(o(s.byteLength),s),a)},writeV:async(s,a)=>{let c=new ut(...s.flatMap(l=>[o(l.byteLength),l]));await e.write(c,a)},unwrap:()=>e.unwrap()}}function Se(r,t){let e=Nc(r,t),n={read:async(o,i)=>{let s=await e.read(i);return o.decode(s)},write:async(o,i,s)=>{await e.write(i.encode(o),s)},writeV:async(o,i,s)=>{await e.writeV(o.map(a=>i.encode(a)),s)},pb:o=>({read:async i=>n.read(o,i),write:async(i,s)=>n.write(i,o,s),writeV:async(i,s)=>n.writeV(i,o,s),unwrap:()=>n}),unwrap:()=>e.unwrap()};return n}var us=1e3,Uc=60*us,On=290,Oc=15,kc=2*60*Uc,Mc=1,kn=2e3,Kc=100,ls="circuit-relay-source",kr=`${go}-circuit-relay`,fs=`${go}-circuit-relay-source`,qc=2*Uc,Fc=BigInt(1<<17),Ft="/libp2p/circuit/relay/0.2.0/hop",Me="/libp2p/circuit/relay/0.2.0/stop",zc=30*us,Yx=30*us,Mr=300,Hc=4096,Vc=.001;var j;(function(r){let t;(function(o){o.RESERVE="RESERVE",o.CONNECT="CONNECT",o.STATUS="STATUS"})(t=r.Type||(r.Type={}));let e;(function(o){o[o.RESERVE=0]="RESERVE",o[o.CONNECT=1]="CONNECT",o[o.STATUS=2]="STATUS"})(e||(e={})),function(o){o.codec=()=>Ue(e)}(t=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Pt((o,i,s={})=>{s.lengthDelimited!==!1&&i.fork(),o.type!=null&&(i.uint32(8),r.Type.codec().encode(o.type,i)),o.peer!=null&&(i.uint32(18),ar.codec().encode(o.peer,i)),o.reservation!=null&&(i.uint32(26),Mn.codec().encode(o.reservation,i)),o.limit!=null&&(i.uint32(34),cr.codec().encode(o.limit,i)),o.status!=null&&(i.uint32(40),q.codec().encode(o.status,i)),s.lengthDelimited!==!1&&i.ldelim()},(o,i,s={})=>{let a={},c=i==null?o.len:o.pos+i;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.type=r.Type.codec().decode(o);break}case 2:{a.peer=ar.codec().decode(o,o.uint32(),{limits:s.limits?.peer});break}case 3:{a.reservation=Mn.codec().decode(o,o.uint32(),{limits:s.limits?.reservation});break}case 4:{a.limit=cr.codec().decode(o,o.uint32(),{limits:s.limits?.limit});break}case 5:{a.status=q.codec().decode(o);break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>Dt(o,r.codec()),r.decode=(o,i)=>Rt(o,r.codec(),i)})(j||(j={}));var kt;(function(r){let t;(function(o){o.CONNECT="CONNECT",o.STATUS="STATUS"})(t=r.Type||(r.Type={}));let e;(function(o){o[o.CONNECT=0]="CONNECT",o[o.STATUS=1]="STATUS"})(e||(e={})),function(o){o.codec=()=>Ue(e)}(t=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Pt((o,i,s={})=>{s.lengthDelimited!==!1&&i.fork(),o.type!=null&&(i.uint32(8),r.Type.codec().encode(o.type,i)),o.peer!=null&&(i.uint32(18),ar.codec().encode(o.peer,i)),o.limit!=null&&(i.uint32(26),cr.codec().encode(o.limit,i)),o.status!=null&&(i.uint32(32),q.codec().encode(o.status,i)),s.lengthDelimited!==!1&&i.ldelim()},(o,i,s={})=>{let a={},c=i==null?o.len:o.pos+i;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.type=r.Type.codec().decode(o);break}case 2:{a.peer=ar.codec().decode(o,o.uint32(),{limits:s.limits?.peer});break}case 3:{a.limit=cr.codec().decode(o,o.uint32(),{limits:s.limits?.limit});break}case 4:{a.status=q.codec().decode(o);break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>Dt(o,r.codec()),r.decode=(o,i)=>Rt(o,r.codec(),i)})(kt||(kt={}));var ar;(function(r){let t;r.codec=()=>(t==null&&(t=Pt((e,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),e.id!=null&&e.id.byteLength>0&&(n.uint32(10),n.bytes(e.id)),e.addrs!=null)for(let i of e.addrs)n.uint32(18),n.bytes(i);o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let i={id:ot(0),addrs:[]},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let a=e.uint32();switch(a>>>3){case 1:{i.id=e.bytes();break}case 2:{if(o.limits?.addrs!=null&&i.addrs.length===o.limits.addrs)throw new Cr('Decode error - map field "addrs" had too many elements');i.addrs.push(e.bytes());break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Dt(e,r.codec()),r.decode=(e,n)=>Rt(e,r.codec(),n)})(ar||(ar={}));var Mn;(function(r){let t;r.codec=()=>(t==null&&(t=Pt((e,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),e.expire!=null&&e.expire!==0n&&(n.uint32(8),n.uint64(e.expire)),e.addrs!=null)for(let i of e.addrs)n.uint32(18),n.bytes(i);e.voucher!=null&&(n.uint32(26),Kn.codec().encode(e.voucher,n)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let i={expire:0n,addrs:[]},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let a=e.uint32();switch(a>>>3){case 1:{i.expire=e.uint64();break}case 2:{if(o.limits?.addrs!=null&&i.addrs.length===o.limits.addrs)throw new Cr('Decode error - map field "addrs" had too many elements');i.addrs.push(e.bytes());break}case 3:{i.voucher=Kn.codec().decode(e,e.uint32(),{limits:o.limits?.voucher});break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Dt(e,r.codec()),r.decode=(e,n)=>Rt(e,r.codec(),n)})(Mn||(Mn={}));var cr;(function(r){let t;r.codec=()=>(t==null&&(t=Pt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.duration!=null&&(n.uint32(8),n.uint32(e.duration)),e.data!=null&&(n.uint32(16),n.uint64(e.data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let i={},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let a=e.uint32();switch(a>>>3){case 1:{i.duration=e.uint32();break}case 2:{i.data=e.uint64();break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Dt(e,r.codec()),r.decode=(e,n)=>Rt(e,r.codec(),n)})(cr||(cr={}));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 hs;(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"})(hs||(hs={}));(function(r){r.codec=()=>Ue(hs)})(q||(q={}));var ur;(function(r){let t;r.codec=()=>(t==null&&(t=Pt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.relay!=null&&e.relay.byteLength>0&&(n.uint32(10),n.bytes(e.relay)),e.peer!=null&&e.peer.byteLength>0&&(n.uint32(18),n.bytes(e.peer)),e.expiration!=null&&e.expiration!==0n&&(n.uint32(24),n.uint64(e.expiration)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let i={relay:ot(0),peer:ot(0),expiration:0n},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let a=e.uint32();switch(a>>>3){case 1:{i.relay=e.bytes();break}case 2:{i.peer=e.bytes();break}case 3:{i.expiration=e.uint64();break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Dt(e,r.codec()),r.decode=(e,n)=>Rt(e,r.codec(),n)})(ur||(ur={}));var Kn;(function(r){let t;r.codec=()=>(t==null&&(t=Pt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.publicKey!=null&&e.publicKey.byteLength>0&&(n.uint32(10),n.bytes(e.publicKey)),e.payloadType!=null&&e.payloadType.byteLength>0&&(n.uint32(18),n.bytes(e.payloadType)),e.payload!=null&&(n.uint32(26),ur.codec().encode(e.payload,n)),e.signature!=null&&e.signature.byteLength>0&&(n.uint32(42),n.bytes(e.signature)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let i={publicKey:ot(0),payloadType:ot(0),signature:ot(0)},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let a=e.uint32();switch(a>>>3){case 1:{i.publicKey=e.bytes();break}case 2:{i.payloadType=e.bytes();break}case 3:{i.payload=ur.codec().decode(e,e.uint32(),{limits:o.limits?.payload});break}case 5:{i.signature=e.bytes();break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Dt(e,r.codec()),r.decode=(e,n)=>Rt(e,r.codec(),n)})(Kn||(Kn={}));var zh=r=>r.toString().split("/").slice(1),lr=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),K=r=>({match:t=>lr(e=>e===r).match(t),pattern:r}),Ke=()=>({match:r=>lr(t=>typeof t=="string").match(r),pattern:"{string}"}),Kr=()=>({match:r=>lr(t=>!isNaN(parseInt(t))).match(r),pattern:"{number}"}),X=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{Y.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),qr=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{Po.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),G=r=>({match:t=>{let e=r.match(t);return e===!1?t:e},pattern:`optional(${r.pattern})`}),At=(...r)=>({match:t=>{let e;for(let n of r){let o=n.match(t);o!==!1&&(e==null||o.length<e.length)&&(e=o)}return e??!1},pattern:`or(${r.map(t=>t.pattern).join(", ")})`}),F=(...r)=>({match:t=>{for(let e of r){let n=e.match(t);if(n===!1)return!1;t=n}return t},pattern:`and(${r.map(t=>t.pattern).join(", ")})`});function tt(...r){function t(o){let i=zh(o);for(let s of r){let a=s.match(i);if(a===!1)return!1;i=a}return i}function e(o){return t(o)!==!1}function n(o){let i=t(o);return i===!1?!1:i.length===0}return{matchers:r,matches:e,exactMatch:n}}var Hh=X(),iw=tt(Hh),Fn=F(K("dns4"),Ke()),zn=F(K("dns6"),Ke()),Hn=F(K("dnsaddr"),Ke()),ps=F(K("dns"),Ke()),sw=tt(Fn,G(X())),aw=tt(zn,G(X())),cw=tt(Hn,G(X())),uw=tt(At(ps,Hn,Fn,zn),G(X())),Gc=F(K("ip4"),lr(An)),Wc=F(K("ip6"),lr(_n)),ms=At(Gc,Wc),le=At(ms,ps,Fn,zn,Hn),lw=tt(At(ms,F(At(ps,Hn,Fn,zn),G(X())))),fw=tt(Gc),hw=tt(Wc),dw=tt(ms),ys=F(le,K("tcp"),Kr()),Fr=F(le,K("udp"),Kr()),pw=tt(F(ys,G(X()))),mw=tt(Fr),gs=F(Fr,K("quic"),G(X())),Vn=F(Fr,K("quic-v1"),G(X())),Vh=At(gs,Vn),yw=tt(gs),gw=tt(Vn),ds=At(le,ys,Fr,gs,Vn),$c=At(F(ds,K("ws"),G(X()))),bw=tt($c),Zc=At(F(ds,K("wss"),G(X())),F(ds,K("tls"),G(F(K("sni"),Ke())),K("ws"),G(X()))),xw=tt(Zc),Yc=F(Fr,K("webrtc-direct"),G(qr()),G(qr()),G(X())),ww=tt(Yc),jc=F(Vn,K("webtransport"),G(qr()),G(qr()),G(X())),Ew=tt(jc),qn=At($c,Zc,F(ys,G(X())),F(Vh,G(X())),F(le,G(X())),Yc,jc,X()),Xc=tt(qn),Gh=F(qn,K("p2p-circuit"),X()),Gn=tt(Gh),Wh=At(F(qn,K("p2p-circuit"),K("webrtc"),G(X())),F(qn,K("webrtc"),G(X())),F(K("webrtc"),G(X()))),Sw=tt(Wh),$h=At(F(le,K("tcp"),Kr(),K("http"),G(X())),F(le,K("http"),G(X()))),vw=tt($h),Zh=At(F(le,K("tcp"),At(F(K("443"),K("http")),F(Kr(),K("https"))),G(X())),F(le,K("tls"),K("http"),G(X())),F(le,K("https"),G(X()))),Aw=tt(Zh),Yh=At(F(K("memory"),Ke(),G(X()))),_w=tt(Yh);function Wn(r){let t=new globalThis.AbortController;function e(){t.abort();for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",e)}for(let i of r){if(i?.aborted===!0){e();break}i?.addEventListener!=null&&i.addEventListener("abort",e)}function n(){for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",e)}let o=t.signal;return o.clear=n,o}var $n=class extends Error{constructor(t="Transfer limit error"){super(t),this.name="TransferLimitError"}},zr=class extends Error{constructor(t="Duration limit error"){super(t),this.name="DurationLimitError"}},Hr=class extends Error{static name="HadEnoughRelaysError";name="HadEnoughRelaysError"},Zn=class extends Error{static name="DoubleRelayError";name="DoubleRelayError"},Yn=class extends Error{static name="RelayQueueFullError";name="RelayQueueFullError"};async function*Qc(r,t,e){let n=t.remaining;for await(let o of r){let i=BigInt(o.byteLength);if(t.remaining-i<0){let s=Number(t.remaining);t.remaining=0n;try{s!==0&&(yield o.subarray(0,s))}catch(a){e.log.error(a)}throw new $n(`data limit of ${n} bytes exceeded`)}t.remaining-=i,yield o}}function Jc(r,t,e,n,o){function i(f){r.abort(f),t.abort(f)}let s=[e,n.signal];n.limit?.duration!=null&&(o.log("limiting relayed connection duration to %dms",n.limit.duration),s.push(AbortSignal.timeout(n.limit.duration)));let a=Wn(s),c=!1,l=!1,u;n.limit?.data!=null&&(u={remaining:n.limit.data}),queueMicrotask(()=>{let f=()=>{o.log("relayed connection reached time limit"),t.abort(new zr(`duration limit of ${n.limit?.duration} ms exceeded`))};a.addEventListener("abort",f,{once:!0}),t.sink(u==null?r.source:Qc(r.source,u,o)).catch(d=>{o.log.error("error while relaying streams src -> dst",d),i(d)}).finally(()=>{c=!0,l&&(a.removeEventListener("abort",f),a.clear())})}),queueMicrotask(()=>{let f=()=>{o.log("relayed connection reached time limit"),r.abort(new zr(`duration limit of ${n.limit?.duration} ms exceeded`))};a.addEventListener("abort",f,{once:!0}),r.sink(u==null?t.source:Qc(t.source,u,o)).catch(d=>{o.log.error("error while relaying streams dst -> src",d),i(d)}).finally(()=>{l=!0,c&&(a.removeEventListener("abort",f),a.clear())})})}function bs(r){let t=r*BigInt(1e3),e=new Date().getTime();return Number(t-BigInt(e))}var Vr=class{expires;bytes;constructor(t){t?.duration!=null&&t?.duration!==0&&(this.expires=Date.now()+t.duration*1e3),this.bytes=t?.data,this.bytes===0n&&(this.bytes=void 0),this.onData=this.onData.bind(this)}onData(t){this.bytes!=null&&(this.bytes-=BigInt(t.byteLength),this.bytes<0n&&(this.bytes=0n))}getLimits(){if(this.expires==null&&this.bytes==null)return;let t={};if(this.bytes!=null){let e=this;Object.defineProperty(t,"bytes",{get(){return e.bytes}})}if(this.expires!=null){let e=this;Object.defineProperty(t,"seconds",{get(){return Math.round(((e.expires??0)-Date.now())/1e3)}})}return t}},jn=tt(F(Xc.matchers[0],K("p2p-circuit"))),Xn=tt(K("p2p-circuit"));function Qn(r,t){let e={[Symbol.iterator]:()=>e,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:t(o)}}};return e}var ve=class{map;constructor(t){if(this.map=new Map,t!=null)for(let[e,n]of t.entries())this.map.set(e.toString(),{key:e,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(t){return this.map.delete(t.toString())}entries(){return Qn(this.map.entries(),t=>[t[1].key,t[1].value])}forEach(t){this.map.forEach((e,n)=>{t(e.value,e.key,this)})}get(t){return this.map.get(t.toString())?.value}has(t){return this.map.has(t.toString())}set(t,e){this.map.set(t.toString(),{key:t,value:e})}keys(){return Qn(this.map.values(),t=>t.key)}values(){return Qn(this.map.values(),t=>t.value)}get size(){return this.map.size}};var xs={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},tu={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},eu=new globalThis.TextEncoder;function jh(r,t){let e=xs[t],n=tu[t];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(t,n*e);return n}function Xh(r,t,e){if(e.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=xs[t],o=tu[t],i=r;for(;i.length>0;){let s=eu.encodeInto(i,e);i=i.slice(s.read);for(let a=0;a<s.written;a++)o^=BigInt(e[a]),o=BigInt.asUintN(t,o*n)}return o}function ws(r,{size:t=32,utf8Buffer:e}={}){if(!xs[t])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(e)return Xh(r,t,e);r=eu.encode(r)}return jh(r,t)}var Gr={hash:r=>Number(ws(r,{size:32})),hashV:(r,t)=>Qh(Gr.hash(r,t))};function Qh(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),M(t,"base16")}var Es=64,Zt=class{fp;h;seed;constructor(t,e,n,o=2){if(o>Es)throw new TypeError("Invalid Fingerprint Size");let i=e.hashV(t,n),s=ot(o);for(let a=0;a<s.length;a++)s[a]=i[a];s.length===0&&(s[0]=7),this.fp=s,this.h=e,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(t){return t?.fp instanceof Uint8Array?dt(this.fp,t.fp):!1}};function qe(r,t){return Math.floor(Math.random()*(t-r))+r}var Fe=class{contents;constructor(t){this.contents=new Array(t).fill(null)}has(t){if(!(t instanceof Zt))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof Zt))throw new TypeError("Invalid Fingerprint");for(let e=0;e<this.contents.length;e++)if(this.contents[e]==null)return this.contents[e]=t,!0;return!0}swap(t){if(!(t instanceof Zt))throw new TypeError("Invalid Fingerprint");let e=qe(0,this.contents.length-1),n=this.contents[e];return this.contents[e]=t,n}remove(t){if(!(t instanceof Zt))throw new TypeError("Invalid Fingerprint");let e=this.contents.findIndex(n=>t.equals(n));return e>-1?(this.contents[e]=null,!0):!1}};var Jh=500,Wr=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(t){this.filterSize=t.filterSize,this.bucketSize=t.bucketSize??4,this.fingerprintSize=t.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=t.hash??Gr,this.seed=t.seed??qe(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=M(t));let e=new Zt(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=(n^e.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new Fe(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new Fe(this.bucketSize)),this.buckets[n].add(e)||this.buckets[o].add(e))return this.count++,!0;let i=[n,o],s=i[qe(0,i.length-1)];this.buckets[s]==null&&(this.buckets[s]=new Fe(this.bucketSize));for(let a=0;a<Jh;a++){let c=this.buckets[s].swap(e);if(c!=null&&(s=(s^c.hash())%this.filterSize,this.buckets[s]==null&&(this.buckets[s]=new Fe(this.bucketSize)),this.buckets[s].add(c)))return this.count++,!0}return!1}has(t){typeof t=="string"&&(t=M(t));let e=new Zt(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=this.buckets[n]?.has(e)??!1;if(o)return o;let i=(n^e.hash())%this.filterSize;return this.buckets[i]?.has(e)??!1}remove(t){typeof t=="string"&&(t=M(t));let e=new Zt(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=this.buckets[n]?.remove(e)??!1;if(o)return this.count--,o;let i=(n^e.hash())%this.filterSize,s=this.buckets[i]?.remove(e)??!1;return s&&this.count--,s}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},td={1:.5,2:.84,4:.95,8:.98};function ed(r=.001){return r>.002?2:r>1e-5?4:8}function ru(r,t=.001){let e=ed(t),n=td[e],o=Math.round(r/n),i=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),Es);return{filterSize:o,bucketSize:e,fingerprintSize:i}}var Jn=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(t){this.bucketSize=t.bucketSize??4,this.filterSize=t.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=t.fingerprintSize??2,this.scale=t.scale??2,this.hash=t.hash??Gr,this.seed=t.seed??qe(0,Math.pow(2,10)),this.filterSeries=[new Wr({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(t){if(typeof t=="string"&&(t=M(t)),this.has(t))return!0;let e=this.filterSeries.find(n=>n.reliable);if(e==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);e=new Wr({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(e)}return e.add(t)}has(t){typeof t=="string"&&(t=M(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].has(t))return!0;return!1}remove(t){typeof t=="string"&&(t=M(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].remove(t))return!0;return!1}get count(){return this.filterSeries.reduce((t,e)=>t+e.count,0)}};function fr(r,t=.001,e){return new Jn({...ru(r,t),...e??{}})}var to=class{filter;constructor(t,e){this.filter=fr(t,e)}has(t){return this.filter.has(t.toMultihash().bytes)}add(t){this.filter.add(t.toMultihash().bytes)}remove(t){this.filter.remove?.(t.toMultihash().bytes)}};function Ss(r,t=.001){return new to(r,t)}var vs=class extends ve{metric;constructor(t){super();let{name:e,metrics:n}=t;this.metric=n.registerMetric(e),this.updateComponentMetric()}set(t,e){return super.set(t,e),this.updateComponentMetric(),this}delete(t){let e=super.delete(t);return this.updateComponentMetric(),e}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function As(r){let{name:t,metrics:e}=r,n;return e!=null?n=new vs({name:t,metrics:e}):n=new ve,n}var _s=class extends Error{type;code;constructor(t,e,n){super(t??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=e??"ABORT_ERR"}};function nu(r,t){let e=new _s(t?.errorMessage,t?.errorCode,t?.errorName),n=new AbortController,o=()=>{n.abort(e)},i=AbortSignal.timeout(r);i.addEventListener("abort",o);let s=n.signal;return s.reset=a=>{i?.removeEventListener("abort",o),i=AbortSignal.timeout(a??r),i.addEventListener("abort",()=>{n.abort(e)})},s.clear=()=>{i?.removeEventListener("abort",o),i=void 0},s}var eo=class{reservations;maxReservations;applyDefaultLimit;reservationTtl;defaultDurationLimit;defaultDataLimit;log;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:circuit-relay:server:reservation-store"),this.maxReservations=e.maxReservations??Oc,this.applyDefaultLimit=e.applyDefaultLimit!==!1,this.reservationTtl=e.reservationTtl??kc,this.defaultDurationLimit=e.defaultDurationLimit??qc,this.defaultDataLimit=e.defaultDataLimit??Fc,this.reservations=As({metrics:t.metrics,name:"libp2p_circuit_relay_server_reservations_total"})}reserve(t,e,n){let o=this.reservations.get(t);if(this.reservations.size>=this.maxReservations&&o==null)return{status:q.RESERVATION_REFUSED};let i=new Date(Date.now()+this.reservationTtl),s;return this.applyDefaultLimit&&(s=n??{data:this.defaultDataLimit,duration:this.defaultDurationLimit}),o!=null?(this.log("refreshing reservation for client %p",t),o.signal.reset(this.reservationTtl)):(this.log("creating new reservation for client %p",t),o={addr:e,expiry:i,limit:s,signal:nu(this.reservationTtl)}),this.reservations.set(t,o),o.signal.addEventListener("abort",()=>{this.reservations.delete(t)}),{status:q.OK,expire:Math.round(i.getTime()/1e3)}}removeReservation(t){this.reservations.delete(t)}get(t){return this.reservations.get(t)}clear(){this.reservations.clear()}};var ro=class r{domain="libp2p-relay-rsvp";codec=new Uint8Array([3,2]);relay;peer;expiration;constructor({relay:t,peer:e,expiration:n}){this.relay=t,this.peer=e,this.expiration=n}marshal(){return ur.encode({relay:this.relay.toMultihash().bytes,peer:this.peer.toMultihash().bytes,expiration:BigInt(this.expiration)})}equals(t){return!(!(t instanceof r)||!this.peer.equals(t.peer)||!this.relay.equals(t.relay)||this.expiration!==t.expiration)}};var ou=r=>r.protoCodes().includes(On),rd={maxOutboundStopStreams:Mr},Is=class extends Mt{registrar;peerStore;addressManager;peerId;privateKey;connectionManager;connectionGater;reservationStore;started;hopTimeout;shutdownController;maxInboundHopStreams;maxOutboundHopStreams;maxOutboundStopStreams;log;constructor(t,e={}){super(),this.log=t.logger.forComponent("libp2p:circuit-relay:server"),this.registrar=t.registrar,this.peerStore=t.peerStore,this.addressManager=t.addressManager,this.peerId=t.peerId,this.privateKey=t.privateKey,this.connectionManager=t.connectionManager,this.connectionGater=t.connectionGater,this.started=!1,this.hopTimeout=e?.hopTimeout??zc,this.maxInboundHopStreams=e.maxInboundHopStreams,this.maxOutboundHopStreams=e.maxOutboundHopStreams,this.maxOutboundStopStreams=e.maxOutboundStopStreams??rd.maxOutboundStopStreams,this.reservationStore=new eo(t,e.reservations),this.shutdownController=new AbortController,this.shutdownController.signal}[Symbol.toStringTag]="@libp2p/circuit-relay-v2-server";isStarted(){return this.started}async start(){this.started||(await this.registrar.handle(Ft,t=>{this.onHop(t).catch(e=>{this.log.error(e)})},{maxInboundStreams:this.maxInboundHopStreams,maxOutboundStreams:this.maxOutboundHopStreams,runOnLimitedConnection:!0}),this.started=!0)}async stop(){this.reservationStore.clear(),this.shutdownController.abort(),await this.registrar.unhandle(Ft),this.started=!1}async onHop({connection:t,stream:e}){this.log("received circuit v2 hop protocol stream from %p",t.remotePeer);let n={signal:AbortSignal.timeout(this.hopTimeout)},o=Se(e);try{let i=await o.pb(j).read(n);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},n)}catch(i){this.log.error("error while handling hop",i),await o.pb(j).write({type:j.Type.STATUS,status:q.MALFORMED_MESSAGE},n),e.abort(i)}}async handleHopProtocol({stream:t,request:e,connection:n},o){switch(this.log("received hop message"),e.type){case j.Type.RESERVE:await this.handleReserve({stream:t,request:e,connection:n},o);break;case j.Type.CONNECT:await this.handleConnect({stream:t,request:e,connection:n},o);break;default:this.log.error("invalid hop request type %s via peer %p",e.type,n.remotePeer),await t.pb(j).write({type:j.Type.STATUS,status:q.UNEXPECTED_MESSAGE})}}async handleReserve({stream:t,connection:e},n){let o=t.pb(j);if(this.log("hop reserve request from %p",e.remotePeer),ou(e.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",e.remotePeer),await o.write({type:j.Type.STATUS,status:q.PERMISSION_DENIED},n);return}if(await this.connectionGater.denyInboundRelayReservation?.(e.remotePeer)===!0){this.log.error("reservation for %p denied by connection gater",e.remotePeer),await o.write({type:j.Type.STATUS,status:q.PERMISSION_DENIED},n);return}let i=this.reservationStore.reserve(e.remotePeer,e.remoteAddr);try{if(i.status!==q.OK){await o.write({type:j.Type.STATUS,status:i.status},n);return}if(i.expire!=null){let s=i.expire*1e3-Date.now();await this.peerStore.merge(e.remotePeer,{tags:{[ls]:{value:1,ttl:s},[fs]:{value:1,ttl:s}}})}await o.write({type:j.Type.STATUS,status:q.OK,reservation:await this.makeReservation(e.remotePeer,BigInt(i.expire??0)),limit:this.reservationStore.get(e.remotePeer)?.limit},n),this.log("sent confirmation response to %s",e.remotePeer)}catch(s){this.log.error("failed to send confirmation response to %p - %e",e.remotePeer,s),this.reservationStore.removeReservation(e.remotePeer);try{await this.peerStore.merge(e.remotePeer,{tags:{[ls]:void 0,[fs]:void 0}})}catch(a){this.log.error("failed to untag relay source peer %p - %e",e.remotePeer,a)}}}async makeReservation(t,e){let n=[];for(let i of this.addressManager.getAddresses())i.toString().includes("/p2p-circuit")||n.push(i.bytes);let o=await Or.seal(new ro({peer:t,relay:this.peerId,expiration:e}),this.privateKey);return{addrs:n,expire:e,voucher:{publicKey:jt(o.publicKey),payloadType:o.payloadType,payload:{peer:t.toMultihash().bytes,relay:this.peerId.toMultihash().bytes,expiration:e},signature:o.signature}}}async handleConnect({stream:t,request:e,connection:n},o){let i=t.pb(j);if(ou(n.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",n.remotePeer),await i.write({type:j.Type.STATUS,status:q.PERMISSION_DENIED},o);return}this.log("hop connect request from %p",n.remotePeer);let s;try{if(e.peer==null)throw this.log.error("no peer info in hop connect request"),new Error("no peer info in request");e.peer.addrs.forEach(vt),s=or(Kt(e.peer.id))}catch(d){this.log.error("invalid hop connect request via peer %p %s",n.remotePeer,d),await i.write({type:j.Type.STATUS,status:q.MALFORMED_MESSAGE},o);return}let a=this.reservationStore.get(s);if(a==null){this.log.error("hop connect denied for destination peer %p not having a reservation for %p with status %s",s,n.remotePeer,q.NO_RESERVATION),await i.write({type:j.Type.STATUS,status:q.NO_RESERVATION},o);return}if(await this.connectionGater.denyOutboundRelayedConnection?.(n.remotePeer,s)===!0){this.log.error("hop connect for %p to %p denied by connection gater",n.remotePeer,s),await i.write({type:j.Type.STATUS,status:q.PERMISSION_DENIED},o);return}let c=this.connectionManager.getConnections(s);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",s,n.remotePeer),await i.write({type:j.Type.STATUS,status:q.NO_RESERVATION},o);return}let l=c[0],u=await this.stopHop({connection:l,request:{type:kt.Type.CONNECT,peer:{id:n.remotePeer.toMultihash().bytes,addrs:[]},limit:a?.limit}},o);if(u==null){this.log.error("failed to open stream to destination peer %p",l?.remotePeer),await i.write({type:j.Type.STATUS,status:q.CONNECTION_FAILED},o);return}await i.write({type:j.Type.STATUS,status:q.OK,limit:a?.limit},o);let f=t.unwrap();this.log("connection from %p to %p established - merging streams",n.remotePeer,s),Jc(f,u,this.shutdownController.signal,a,{log:this.log})}async stopHop({connection:t,request:e},n){this.log("starting circuit relay v2 stop request to %s",t.remotePeer);let o=await t.newStream([Me],{maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0,...n}),i=Se(o),s=i.pb(kt);await s.write(e,n);let a;try{a=await s.read(n)}catch{this.log.error("error parsing stop message response from %p",t.remotePeer)}if(a==null){this.log.error("could not read response from %p",t.remotePeer),await o.close(n);return}if(a.status===q.OK)return this.log("stop request to %p was successful",t.remotePeer),i.unwrap();this.log("stop request failed with code %d",a.status),await o.close(n)}get reservations(){return this.reservationStore.reservations}};function iu(r={}){return t=>new Is(t,r)}function nd(r){let[t,e]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>t.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:t.next(),[e](){return this}}}var su=nd;function od(r){return r[Symbol.asyncIterator]!=null}function au(r){return r?.then!=null}function id(r,t){let e=0;if(od(r))return async function*(){for await(let c of r){let l=t(c,e++);au(l)&&await l,yield c}}();let n=su(r),{value:o,done:i}=n.next();if(i===!0)return function*(){}();if(typeof t(o,e++)?.then=="function")return async function*(){yield o;for await(let c of n){let l=t(c,e++);au(l)&&await l,yield c}}();let a=t;return function*(){yield o;for(let c of n)a(c,e++),yield c}()}var cu=id;var oo=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||(t-1&t)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},hr=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new oo(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){let e=this.head;this.head=e.next=new oo(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let e=this.tail.next;this.tail.next=null,this.tail=e,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var Ts=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function io(r={}){return sd(e=>{let n=e.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function sd(r,t){t=t??{};let e=t.onEnd,n=new hr,o,i,s,a=$t(),c=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((h,x)=>{i=v=>{i=null,n.push(v);try{h(r(n))}catch(p){x(p)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=$t()})}},l=h=>i!=null?i(h):(n.push(h),o),u=h=>(n=new hr,i!=null?i({error:h}):(n.push({error:h}),o)),f=h=>{if(s)return o;if(t?.objectMode!==!0&&h?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:h})},d=h=>s?o:(s=!0,h!=null?u(h):l({done:!0})),g=()=>(n=new hr,d(),{done:!0}),b=h=>(d(h),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:g,throw:b,push:f,end:d,get readableLength(){return n.size},onEmpty:async h=>{let x=h?.signal;if(x?.throwIfAborted(),n.isEmpty())return;let v,p;x!=null&&(v=new Promise((_,D)=>{p=()=>{D(new Ts)},x.addEventListener("abort",p)}));try{await Promise.race([a.promise,v])}finally{p!=null&&x!=null&&x?.removeEventListener("abort",p)}}},e==null)return o;let y=o;return o={[Symbol.asyncIterator](){return this},next(){return y.next()},throw(h){return y.throw(h),e!=null&&(e(h),e=void 0),{done:!0}},return(){return y.return(),e!=null&&(e(),e=void 0),{done:!0}},push:f,end(h){return y.end(h),e!=null&&(e(h),e=void 0),o},get readableLength(){return y.readableLength},onEmpty:h=>y.onEmpty(h)},o}function ad(r){return r[Symbol.asyncIterator]!=null}async function cd(r,t){try{await Promise.all(r.map(async e=>{for await(let n of e)await t.push(n)})),await t.end()}catch(e){await t.end(e).catch(()=>{})}}async function*ud(r){let t=Dn();cd(r,t).catch(()=>{}),yield*t}function*ld(r){for(let t of r)yield*t}function fd(...r){let t=[];for(let e of r)ad(e)||t.push(e);return t.length===r.length?ld(t):ud(r)}var uu=fd;function lu(r,...t){if(r==null)throw new Error("Empty pipeline");if(Ls(r)){let n=r;r=()=>n.source}else if(hu(r)||fu(r)){let n=r;r=()=>n}let e=[r,...t];if(e.length>1&&Ls(e[e.length-1])&&(e[e.length-1]=e[e.length-1].sink),e.length>2)for(let n=1;n<e.length-1;n++)Ls(e[n])&&(e[n]=dd(e[n]));return hd(...e)}var hd=(...r)=>{let t;for(;r.length>0;)t=r.shift()(t);return t},fu=r=>r?.[Symbol.asyncIterator]!=null,hu=r=>r?.[Symbol.iterator]!=null,Ls=r=>r==null?!1:r.sink!=null&&r.source!=null,dd=r=>t=>{let e=r.sink(t);if(e?.then!=null){let n=io({objectMode:!0});e.then(()=>{n.end()},s=>{n.end(s)});let o,i=r.source;if(fu(i))o=async function*(){yield*i,n.end()};else if(hu(i))o=function*(){yield*i,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return uu(n,o())}return r.source};function Cs(r){let{stream:t,remoteAddr:e,logger:n,onDataRead:o,onDataWrite:i}=r,s=n.forComponent("libp2p:stream:converter"),a=!1,c=!1,l=t.close.bind(t);t.close=async b=>{await l(b),g(!0)};let u=t.abort.bind(t);t.abort=b=>{u(b),g(!0)};let f=t.sink.bind(t);t.sink=async b=>{try{await f(lu(b,y=>cu(y,h=>i?.(h))))}catch(y){y.type!=="aborted"&&s.error("%s error in sink",e,y)}finally{c=!0,g()}};let d={log:s,sink:t.sink,source:async function*(){try{for await(let b of t.source)o?.(b),yield b}finally{a=!0,g()}}(),remoteAddr:e,timeline:{open:Date.now(),close:void 0},close:t.close,abort:t.abort};function g(b){b===!0&&(a=!0,c=!0),a&&c&&d.timeline.close==null&&(d.timeline.close=Date.now())}return d}var Ae=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var Rs=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=e??"ABORT_ERR"}};async function so(r,t,e,n){let o=new Rs(n?.errorMessage,n?.errorCode);return e?.aborted===!0?Promise.reject(o):new Promise((i,s)=>{function a(){e?.removeEventListener("abort",u),r.removeEventListener(t,c),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,l)}let c=f=>{try{if(n?.filter?.(f)===!1)return}catch(d){a(),s(d);return}a(),i(f)},l=f=>{a(),s(f.detail)},u=()=>{a(),s(o)};e?.addEventListener("abort",u),r.addEventListener(t,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,l)})}var ao=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};var co=class{deferred;signal;constructor(t){this.signal=t,this.deferred=$t(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new te)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function pd(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var uo=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=pd(),this.status="queued",this.fn=t,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(t){this.controller.abort(t)}onAbort(){this.recipients.reduce((e,n)=>e&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new te),this.cleanup())}async join(t={}){let e=new co(t.signal);return this.recipients.push(e),t.signal?.addEventListener("abort",this.onAbort),e.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let t=await ke(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(e=>{e.deferred.resolve(t)}),this.status="complete"}catch(t){this.recipients.forEach(e=>{e.deferred.reject(t)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(t=>{t.cleanup(),t.signal?.removeEventListener("abort",this.onAbort)})}};var lo=class extends Mt{concurrency;maxSize;queue;pending;sort;constructor(t={}){super(),this.concurrency=t.concurrency??Number.POSITIVE_INFINITY,this.maxSize=t.maxSize??Number.POSITIVE_INFINITY,this.pending=0,t.metricName!=null&&t.metrics?.registerMetricGroup(t.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=t.sort,this.queue=[]}tryToStartAnother(){if(this.size===0)return queueMicrotask(()=>{this.safeDispatchEvent("empty")}),this.running===0&&queueMicrotask(()=>{this.safeDispatchEvent("idle")}),!1;if(this.pending<this.concurrency){let t;for(let e of this.queue)if(e.status==="queued"){t=e;break}return t==null?!1:(this.safeDispatchEvent("active"),this.pending++,t.run().finally(()=>{for(let e=0;e<this.queue.length;e++)if(this.queue[e]===t){this.queue.splice(e,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(t){this.queue.push(t),this.sort!=null&&this.queue.sort(this.sort)}async add(t,e){if(e?.signal?.throwIfAborted(),this.size===this.maxSize)throw new ao;let n=new uo(t,e);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(e).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("error",{detail:o}),this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(t=>{t.abort(new te)}),this.clear()}async onEmpty(t){this.size!==0&&await so(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await so(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await so(this,"idle",t?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(t){t?.signal?.throwIfAborted();let e=io({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),e.end(c)},o=c=>{c.detail!=null&&e.push(c.detail)},i=c=>{n(c.detail)},s=()=>{n()},a=()=>{n(new te("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("error",i),this.addEventListener("idle",s),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("completed",o),this.removeEventListener("error",i),this.removeEventListener("idle",s),t?.signal?.removeEventListener("abort",a),n()}}};var dr=class extends lo{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};var fo=class extends Mt{peerStore;registrar;connectionManager;randomWalk;started;running;topologyId;log;discoveryController;filter;queue;constructor(t,e={}){super(),this.log=t.logger.forComponent("libp2p:circuit-relay:discover-relays"),this.started=!1,this.running=!1,this.peerStore=t.peerStore,this.registrar=t.registrar,this.connectionManager=t.connectionManager,this.randomWalk=t.randomWalk,this.filter=e.filter,this.discoveryController=new AbortController,this.discoveryController.signal}isStarted(){return this.started}async start(){this.topologyId=await this.registrar.register(Ft,{filter:this.filter,onConnect:t=>{this.log.trace("discovered relay %p queue (length: %d, active %d)",t,this.queue?.size,this.queue?.running),this.safeDispatchEvent("relay:discover",{detail:t})}}),this.started=!0}stop(){this.topologyId!=null&&this.registrar.unregister(this.topologyId),this.discoveryController?.abort(),this.started=!1}startDiscovery(){this.running||(this.log("start discovery"),this.running=!0,this.discoveryController=new AbortController,this.discoveryController.signal,Promise.resolve().then(async()=>{this.log("searching peer store for relays");let t=await this.peerStore.all({filters:[n=>n.protocols.includes(Ft)],orders:[()=>Math.random()<.5?1:-1,(n,o)=>{let i=du(n),s=du(o);return i>s?-1:s>i?1:0}]});for(let n of t)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",t.length);let e=this.queue=new dr({concurrency:5});this.log("start random walk");for await(let n of this.randomWalk.walk({signal:this.discoveryController.signal})){if(this.log.trace("found random peer %p",n.id),e.has(n.id)){this.log.trace("random peer %p was already in queue",n.id);continue}if(this.connectionManager.getConnections(n.id)?.length>0){this.log.trace("random peer %p was already connected",n.id);continue}if(!await this.connectionManager.isDialable(n.multiaddrs)){this.log.trace("random peer %p was not dialable",n.id,n.multiaddrs.map(o=>o.toString()));continue}e.queued>10&&(this.log.trace("wait for space in queue for %p",n.id),await e.onSizeLessThan(10,{signal:this.discoveryController.signal})),this.log("adding random peer %p to dial queue (length: %d, active %d)",n.id,e.size,e.running),e.add(async()=>{let o=Wn([this.discoveryController.signal,AbortSignal.timeout(5e3)]);try{await this.connectionManager.openConnection(n.id,{signal:o})}finally{o.clear()}},{peerId:n.id,signal:this.discoveryController.signal}).catch(o=>{this.log.error("error opening connection to random peer %p",n.id,o)})}this.log("stop random walk"),await e.onIdle()}).catch(t=>{this.discoveryController.signal.aborted||this.log.error("failed when finding relays on the network",t)}))}stopDiscovery(){this.log("stop discovery"),this.running=!1,this.discoveryController?.abort()}};function du(r){let t=r.metadata.get("last-dial-success");return t==null?0:new Date(O(t)).getTime()}var Ds=class extends Mt{connectionManager;addressManager;reservationStore;listeningAddrs;log;listenTimeout;reservationId;relay;constructor(t,e={}){super(),this.log=t.logger.forComponent("libp2p:circuit-relay:transport:listener"),this.connectionManager=t.connectionManager,this.addressManager=t.addressManager,this.reservationStore=t.reservationStore,this.listeningAddrs=[],this.listenTimeout=e.listenTimeout??kn,this.reservationStore.addEventListener("relay:removed",this._onRemoveRelayPeer),this.reservationStore.addEventListener("relay:created-reservation",this._onAddRelayPeer)}_onRemoveRelayPeer=t=>{this.log("relay removed %p our relay %p",t.detail.relay,this.relay,this.relay?.equals(t.detail.relay)),this.relay?.equals(t.detail.relay)===!0&&(this.log("relay peer removed %p",t.detail.relay),this.listeningAddrs.forEach(e=>{this.addressManager.removeObservedAddr(e)}),this.listeningAddrs=[],this.safeDispatchEvent("listening"))};_onAddRelayPeer=t=>{let{details:e}=t.detail;e.type!=="configured"&&e.id===this.reservationId&&this.addedRelay(t.detail)};async listen(t){if(Xn.exactMatch(t))this.log("searching for circuit relay servers"),this.reservationId=this.reservationStore.reserveRelay();else if(jn.exactMatch(t)){this.log("listen on specific relay server %a",t);let e=AbortSignal.timeout(this.listenTimeout);let n=t.decapsulate("/p2p-circuit"),o=await this.connectionManager.openConnection(n,{signal:e});if(!this.reservationStore.hasReservation(o.remotePeer)){this.log("making reservation on peer %p",o.remotePeer);let i=await this.reservationStore.addRelay(o.remotePeer,"configured");this.addedRelay(i)}}else throw new _e(`Could not listen on p2p-circuit address "${t}"`)}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(t){this.log("relay peer added %p",t.relay),this.relay=t.relay,this.listeningAddrs=t.details.reservation.addrs.map(e=>vt(e).encapsulate("/p2p-circuit")),this.listeningAddrs.forEach(e=>{this.addressManager.confirmObservedAddr(e,{type:"transport"})}),queueMicrotask(()=>{this.safeDispatchEvent("listening")})}};function pu(r){return new Ds(r)}var mu="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var yu=(r=21)=>{let t="",e=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)t+=mu[e[r]&63];return t};var md=60*1e3*10,yd=60*1e3*5,gd=30*1e3,ho=class extends Mt{peerId;connectionManager;peerStore;events;reserveQueue;reservations;pendingReservations;maxReservationQueueLength;reservationCompletionTimeout;started;log;relayFilter;constructor(t,e){super(),this.log=t.logger.forComponent("libp2p:circuit-relay:transport:reservation-store"),this.peerId=t.peerId,this.connectionManager=t.connectionManager,this.peerStore=t.peerStore,this.events=t.events,this.reservations=new ve,this.pendingReservations=[],this.maxReservationQueueLength=e?.maxReservationQueueLength??Kc,this.reservationCompletionTimeout=e?.reservationCompletionTimeout??kn,this.started=!1,this.relayFilter=fr(100),this.reserveQueue=new dr({concurrency:e?.reservationConcurrency??Mc,metricName:"libp2p_relay_reservation_queue",metrics:t.metrics}),this.events.addEventListener("connection:close",n=>{[...this.reservations.values()].find(i=>i.connection===n.detail.id)!=null&&this.#e(n.detail.remotePeer).catch(i=>{this.log("could not remove relay %p - %e",n.detail,i)})})}isStarted(){return this.started}start(){this.started=!0}afterStart(){Promise.resolve().then(async()=>{let t=await this.peerStore.all({filters:[e=>e.tags.has(kr)]});this.log("removing tag from %d old relays",t.length),await Promise.all(t.map(async e=>{await this.peerStore.merge(e.id,{tags:{[kr]:void 0}})})),this.log("redialing %d old relays",t.length),await Promise.all(t.map(async e=>this.addRelay(e.id,"discovered"))),this.#r()}).catch(t=>{this.log.error(t)})}stop(){this.reserveQueue.clear(),this.reservations.forEach(({timeout:t})=>{clearTimeout(t)}),this.reservations.clear(),this.started=!1}reserveRelay(){let t=yu();return this.pendingReservations.push(t),this.#r(),t}async addRelay(t,e){if(this.peerId.equals(t))throw this.log.trace("not trying to use self as relay"),new _e("Cannot use self as relay");if(this.reserveQueue.size>this.maxReservationQueueLength)throw new Yn("The reservation queue is full");let n=this.reserveQueue.find(t);if(n!=null)return this.log.trace("potential relay peer %p is already in the reservation queue",t),n.join();if(this.relayFilter.has(t.toMultihash().bytes))throw new _e("The relay was previously invalid");return this.log.trace("try to reserve relay slot with %p",t),this.reserveQueue.add(async()=>{let o=Date.now();try{let i=this.reservations.get(t);if(i!=null){let b=this.connectionManager.getConnections(t),y=!1;if(b.length===0&&this.log("already have relay reservation with %p but we are no longer connected",t),b.map(h=>h.id).includes(i.connection)&&(this.log("already have relay reservation with %p and the original connection is still open",t),y=!0),y&&bs(i.reservation.expire)>md)return this.log("already have relay reservation with %p but we are still connected and it does not expire soon",t),{relay:t,details:i};await this.#e(t)}if(e==="discovered"&&this.pendingReservations.length===0)throw new Hr("Not making reservation on discovered relay because we do not need any more relays");let s=AbortSignal.timeout(this.reservationCompletionTimeout);let a=await this.connectionManager.openConnection(t,{signal:s});if(Gn.matches(a.remoteAddr))throw new Zn("not creating reservation over relayed connection");let c=await this.#t(a,{signal:s}),l=bs(c.expire);this.log("created reservation on relay peer %p, expiry date is %s",t,new Date(Date.now()+l).toString());let u=Math.min(Math.max(l-yd,gd),Math.pow(2,31)-1),f=setTimeout(()=>{this.log("refresh reservation to relay %p",t),this.addRelay(t,e).catch(async b=>{this.log.error("could not refresh reservation to relay %p - %e",t,b),await this.#e(t)}).catch(b=>{this.log.error("could not remove expired reservation to relay %p - %e",t,b)})},u),d;if(e==="discovered"){let b=this.pendingReservations.pop();if(b==null)throw new Hr("Made reservation on relay but did not need any more discovered relays");d={timeout:f,reservation:c,type:e,connection:a.id,id:b}}else d={timeout:f,reservation:c,type:e,connection:a.id};this.reservations.set(t,d),await this.peerStore.merge(t,{tags:{[kr]:{value:1,ttl:l}}}),this.#r();let g={relay:t,details:d};return this.safeDispatchEvent("relay:created-reservation",{detail:g}),g}catch(i){throw e==="discovered"&&i.name==="HadEnoughRelaysError"||this.log.error("could not reserve slot on %p after %dms - %e",t,Date.now()-o,i),(i.name==="DialError"||i.name==="UnsupportedProtocolError")&&this.relayFilter.add(t.toMultihash().bytes),this.#e(t).catch(s=>{this.log.error("could not remove reservation on %p after reserving slot failed - %e",t,s)}),i}},{peerId:t})}hasReservation(t){return this.reservations.has(t)}getReservation(t){return this.reservations.get(t)?.reservation}reservationCount(t){return t==null?this.reservations.size:[...this.reservations.values()].reduce((e,n)=>(n.type===t&&e++,e),0)}cancelReservations(){[...this.reservations.values()].forEach(t=>{clearTimeout(t.timeout)}),this.reservations.clear()}async#t(t,e){e.signal?.throwIfAborted(),this.log("requesting reservation from %p",t.remotePeer);let n=await t.newStream(Ft,e),i=Se(n).pb(j);this.log.trace("send RESERVE to %p",t.remotePeer),await i.write({type:j.Type.RESERVE},e);let s;try{this.log.trace("reading response from %p",t.remotePeer),s=await i.read(e)}catch(c){throw n.abort(c),c}finally{n.status!=="closed"&&await n.close(e)}if(this.log.trace("read response %o",s),s.status===q.OK&&s.reservation!=null){let c=new Set;c.add(t.remoteAddr.toString());for(let l of s.reservation.addrs){let u=vt(l);u.getPeerId()==null&&(u=u.encapsulate(`/p2p/${t.remotePeer}`)),u=vt(u.toString().replace(`/p2p/${t.remotePeer}/p2p/${t.remotePeer}`,`/p2p/${t.remotePeer}`)),c.add(u.toString())}return s.reservation.addrs=[...c].map(l=>vt(l).bytes),s.reservation}let a=`reservation failed with status ${s.status??"undefined"}`;throw this.log.error(a),new Error(a)}async#e(t){let e=this.reservations.get(t);e!=null&&(this.log("removing relay reservation with %p from local store",t),clearTimeout(e.timeout),this.reservations.delete(t),e.type==="discovered"&&this.pendingReservations.push(e.id),await this.peerStore.merge(t,{tags:{[kr]:void 0}}),this.safeDispatchEvent("relay:removed",{detail:{relay:t,details:e}}),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=fr(100),this.log("not discovered enough relays %d/%d",this.reservations.size,this.pendingReservations.length),this.safeDispatchEvent("relay:not-enough-relays")}};var bd=r=>{if(r.peer==null)return!1;try{r.peer.addrs.forEach(vt)}catch{return!1}return!0},gu={maxInboundStopStreams:Mr,maxOutboundStopStreams:Mr,stopTimeout:3e4},po=class{discovery;registrar;peerStore;connectionManager;transportManager;peerId;upgrader;addressManager;connectionGater;reservationStore;logger;maxInboundStopStreams;maxOutboundStopStreams;started;log;shutdownController;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:circuit-relay:transport"),this.registrar=t.registrar,this.peerStore=t.peerStore,this.connectionManager=t.connectionManager,this.transportManager=t.transportManager,this.logger=t.logger,this.peerId=t.peerId,this.upgrader=t.upgrader,this.addressManager=t.addressManager,this.connectionGater=t.connectionGater,this.maxInboundStopStreams=e.maxInboundStopStreams??gu.maxInboundStopStreams,this.maxOutboundStopStreams=e.maxOutboundStopStreams??gu.maxOutboundStopStreams,this.shutdownController=new AbortController,this.discovery=new fo(t,{filter:e.discoveryFilter??Ss(Hc,Vc)}),this.discovery.addEventListener("relay:discover",n=>{this.reservationStore.addRelay(n.detail,"discovered").catch(o=>{o.name!=="HadEnoughRelaysError"&&o.name!=="RelayQueueFullError"&&this.log.error("could not add discovered relay %p",n.detail,o)})}),this.reservationStore=new ho(t,e),this.reservationStore.addEventListener("relay:not-enough-relays",()=>{this.discovery?.startDiscovery()}),this.reservationStore.addEventListener("relay:found-enough-relays",()=>{this.discovery?.stopDiscovery()}),this.started=!1}[Symbol.toStringTag]="@libp2p/circuit-relay-v2-transport";[Ms]=["@libp2p/transport","@libp2p/circuit-relay-v2-transport"];get[Ks](){return this.discovery!=null?["@libp2p/identify"]:[]}[Ns]=!0;isStarted(){return this.started}async start(){this.shutdownController=new AbortController,await this.registrar.handle(Me,t=>{let e=this.upgrader.createInboundAbortSignal(this.shutdownController.signal);this.onStop(t,e).catch(n=>{this.log.error("error while handling STOP protocol",n),t.stream.abort(n)}).finally(()=>{e.clear()})},{maxInboundStreams:this.maxInboundStopStreams,maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0}),await Os(this.discovery,this.reservationStore),this.started=!0}async stop(){this.shutdownController.abort(),await ks(this.discovery,this.reservationStore),await this.registrar.unhandle(Me),this.started=!1}async dial(t,e){if(t.protoCodes().filter(g=>g===On).length!==1){let g="Invalid circuit relay address";throw this.log.error(g,t),new mr(g)}let n=t.toString().split("/p2p-circuit"),o=vt(n[0]),i=vt(n[n.length-1]),s=o.getPeerId(),a=i.getPeerId();if(s==null||a==null){let g=`ircuit relay dial to ${t.toString()} failed as address did not have both relay and destination PeerIDs`;throw this.log.error(`c${g}`),new mr(`C${g}`)}let c=$i(s),l=$i(a),f=this.connectionManager.getConnections(c)[0];f==null?(await this.peerStore.merge(c,{multiaddrs:[o]}),e.onProgress?.(new Ae("circuit-relay:open-connection")),f=await this.connectionManager.openConnection(c,e)):e.onProgress?.(new Ae("circuit-relay:reuse-connection"));let d;try{e.onProgress?.(new Ae("circuit-relay:open-hop-stream")),d=await f.newStream(Ft,e);let g=Se(d),b=g.pb(j);e.onProgress?.(new Ae("circuit-relay:write-connect-message")),await b.write({type:j.Type.CONNECT,peer:{id:l.toMultihash().bytes,addrs:[vt(i).bytes]}},e),e.onProgress?.(new Ae("circuit-relay:read-connect-response"));let y=await b.read(e);if(y.status!==q.OK)throw new Yr(`failed to connect via relay with status ${y?.status?.toString()??"undefined"}`);let h=new Vr(y.limit),x=Cs({stream:g.unwrap(),remoteAddr:t,localAddr:o.encapsulate(`/p2p-circuit/p2p/${this.peerId.toString()}`),logger:this.logger,onDataRead:h.onData,onDataWrite:h.onData});return this.log("new outbound relayed connection %a",x.remoteAddr),await this.upgrader.upgradeOutbound(x,{...e,limits:h.getLimits()})}catch(g){throw this.log.error("circuit relay dial to destination %p via relay %p failed",l,c,g),d?.abort(g),g}}createListener(t){return pu({peerId:this.peerId,connectionManager:this.connectionManager,addressManager:this.addressManager,reservationStore:this.reservationStore,logger:this.logger})}listenFilter(t){return t=Array.isArray(t)?t:[t],t.filter(e=>jn.exactMatch(e)||Xn.exactMatch(e))}dialFilter(t){return t=Array.isArray(t)?t:[t],t.filter(e=>Gn.exactMatch(e))}async onStop({connection:t,stream:e},n){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.transportManager.listen([t.remoteAddr.encapsulate("/p2p-circuit")])}catch(f){this.log.error("failed to listen on a relay peer we were dialed via but did not have a reservation on",f)}let o=Se(e).pb(kt),i=await o.read({signal:n});if(this.log("new circuit relay v2 stop stream from %p with type %s",t.remotePeer,i.type),i?.type===void 0){this.log.error("type was missing from circuit v2 stop protocol request from %s",t.remotePeer),await o.write({type:kt.Type.STATUS,status:q.MALFORMED_MESSAGE},{signal:n}),await e.close();return}if(i.type!==kt.Type.CONNECT){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await o.write({type:kt.Type.STATUS,status:q.UNEXPECTED_MESSAGE},{signal:n}),await e.close();return}if(!bd(i)){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await o.write({type:kt.Type.STATUS,status:q.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}let s=or(Kt(i.peer.id));if(await this.connectionGater.denyInboundRelayedConnection?.(t.remotePeer,s)===!0){this.log.error("connection gater denied inbound relayed connection from %p",t.remotePeer),await o.write({type:kt.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 o.write({type:kt.Type.STATUS,status:q.OK},{signal:n});let a=new Vr(i.limit),c=t.remoteAddr.encapsulate(`/p2p-circuit/p2p/${s.toString()}`),l=this.addressManager.getAddresses()[0],u=Cs({stream:o.unwrap().unwrap(),remoteAddr:c,localAddr:l,logger:this.logger,onDataRead:a.onData,onDataWrite:a.onData});this.log("new inbound relayed connection %a",u.remoteAddr),await this.upgrader.upgradeInbound(u,{limits:a.getLimits(),signal:n}),this.log("%s connection %a upgraded","inbound",u.remoteAddr)}};function bu(r={}){return t=>new po(t,r)}return Tu(xd);})();
3
3
  /*! Bundled license information:
4
4
 
5
5
  @noble/hashes/esm/utils.js:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@libp2p/circuit-relay-v2",
3
- "version": "3.2.8",
3
+ "version": "3.2.9-3833353bd",
4
4
  "description": "Implementation of Circuit Relay v2",
5
5
  "license": "Apache-2.0 OR MIT",
6
6
  "homepage": "https://github.com/libp2p/js-libp2p/tree/main/packages/transport-circuit-relay-v2#readme",
@@ -52,17 +52,17 @@
52
52
  "doc-check": "aegir doc-check"
53
53
  },
54
54
  "dependencies": {
55
- "@libp2p/crypto": "^5.0.15",
56
- "@libp2p/interface": "^2.7.0",
57
- "@libp2p/interface-internal": "^2.3.9",
58
- "@libp2p/peer-collections": "^6.0.25",
59
- "@libp2p/peer-id": "^5.1.0",
60
- "@libp2p/peer-record": "^8.0.25",
61
- "@libp2p/utils": "^6.6.0",
55
+ "@libp2p/crypto": "5.1.0-3833353bd",
56
+ "@libp2p/interface": "2.8.0-3833353bd",
57
+ "@libp2p/interface-internal": "2.3.10-3833353bd",
58
+ "@libp2p/peer-collections": "6.0.26-3833353bd",
59
+ "@libp2p/peer-id": "5.1.1-3833353bd",
60
+ "@libp2p/peer-record": "8.0.26-3833353bd",
61
+ "@libp2p/utils": "6.6.1-3833353bd",
62
62
  "@multiformats/multiaddr": "^12.3.3",
63
63
  "@multiformats/multiaddr-matcher": "^1.6.0",
64
64
  "any-signal": "^4.1.1",
65
- "it-protobuf-stream": "^1.1.5",
65
+ "it-protobuf-stream": "^2.0.1",
66
66
  "it-stream-types": "^2.0.2",
67
67
  "multiformats": "^13.3.1",
68
68
  "nanoid": "^5.0.9",
@@ -73,8 +73,8 @@
73
73
  "uint8arrays": "^5.1.0"
74
74
  },
75
75
  "devDependencies": {
76
- "@libp2p/interface-compliance-tests": "^6.4.2",
77
- "@libp2p/logger": "^5.1.13",
76
+ "@libp2p/interface-compliance-tests": "6.4.3-3833353bd",
77
+ "@libp2p/logger": "5.1.14-3833353bd",
78
78
  "aegir": "^45.1.1",
79
79
  "delay": "^6.0.0",
80
80
  "it-drain": "^3.0.7",
@@ -1,23 +0,0 @@
1
- {
2
- "codec": "https://libp2p.github.io/js-libp2p/functions/_libp2p_circuit_relay_v2.Limit.codec.html",
3
- "decode": "https://libp2p.github.io/js-libp2p/functions/_libp2p_circuit_relay_v2.Limit.decode.html",
4
- "encode": "https://libp2p.github.io/js-libp2p/functions/_libp2p_circuit_relay_v2.Limit.encode.html",
5
- "CircuitRelayServerComponents": "https://libp2p.github.io/js-libp2p/interfaces/_libp2p_circuit_relay_v2.CircuitRelayServerComponents.html",
6
- "CircuitRelayServerInit": "https://libp2p.github.io/js-libp2p/interfaces/_libp2p_circuit_relay_v2.CircuitRelayServerInit.html",
7
- "CircuitRelayService": "https://libp2p.github.io/js-libp2p/interfaces/_libp2p_circuit_relay_v2.CircuitRelayService.html",
8
- ".:CircuitRelayService": "https://libp2p.github.io/js-libp2p/interfaces/_libp2p_circuit_relay_v2.CircuitRelayService.html",
9
- "CircuitRelayServiceEvents": "https://libp2p.github.io/js-libp2p/interfaces/_libp2p_circuit_relay_v2.CircuitRelayServiceEvents.html",
10
- ".:CircuitRelayServiceEvents": "https://libp2p.github.io/js-libp2p/interfaces/_libp2p_circuit_relay_v2.CircuitRelayServiceEvents.html",
11
- "CircuitRelayTransportComponents": "https://libp2p.github.io/js-libp2p/interfaces/_libp2p_circuit_relay_v2.CircuitRelayTransportComponents.html",
12
- "CircuitRelayTransportInit": "https://libp2p.github.io/js-libp2p/interfaces/_libp2p_circuit_relay_v2.CircuitRelayTransportInit.html",
13
- "Limit": "https://libp2p.github.io/js-libp2p/interfaces/_libp2p_circuit_relay_v2.Limit-1.html",
14
- "RelayDiscoveryComponents": "https://libp2p.github.io/js-libp2p/interfaces/_libp2p_circuit_relay_v2.RelayDiscoveryComponents.html",
15
- "RelayReservation": "https://libp2p.github.io/js-libp2p/interfaces/_libp2p_circuit_relay_v2.RelayReservation.html",
16
- ".:RelayReservation": "https://libp2p.github.io/js-libp2p/interfaces/_libp2p_circuit_relay_v2.RelayReservation.html",
17
- "ServerReservationStoreInit": "https://libp2p.github.io/js-libp2p/interfaces/_libp2p_circuit_relay_v2.ServerReservationStoreInit.html",
18
- "TransportReservationStoreInit": "https://libp2p.github.io/js-libp2p/interfaces/_libp2p_circuit_relay_v2.TransportReservationStoreInit.html",
19
- "RELAY_V2_HOP_CODEC": "https://libp2p.github.io/js-libp2p/variables/_libp2p_circuit_relay_v2.RELAY_V2_HOP_CODEC.html",
20
- "RELAY_V2_STOP_CODEC": "https://libp2p.github.io/js-libp2p/variables/_libp2p_circuit_relay_v2.RELAY_V2_STOP_CODEC.html",
21
- "circuitRelayServer": "https://libp2p.github.io/js-libp2p/functions/_libp2p_circuit_relay_v2.circuitRelayServer.html",
22
- "circuitRelayTransport": "https://libp2p.github.io/js-libp2p/functions/_libp2p_circuit_relay_v2.circuitRelayTransport.html"
23
- }