@libp2p/circuit-relay-v2 3.2.14 → 3.2.15

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 _o=Object.defineProperty;var Gu=Object.getOwnPropertyDescriptor;var Wu=Object.getOwnPropertyNames;var $u=Object.prototype.hasOwnProperty;var Lt=(r,t)=>{for(var e in t)_o(r,e,{get:t[e],enumerable:!0})},Zu=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Wu(t))!$u.call(r,o)&&o!==e&&_o(r,o,{get:()=>t[o],enumerable:!(n=Gu(t,o))||n.enumerable});return r};var Yu=r=>Zu(_o({},"__esModule",{value:!0}),r);var Ed={};Lt(Ed,{RELAY_V2_HOP_CODEC:()=>Ht,RELAY_V2_STOP_CODEC:()=>Fe,circuitRelayServer:()=>Tu,circuitRelayTransport:()=>qu});var Io=Symbol.for("@libp2p/peer-id");var To="keep-alive";var Ws=Symbol.for("@libp2p/transport");var Gs;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Gs||(Gs={}));var re=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"}},Ge=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}};var en=class extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}},rn=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}};var nn=class extends Error{static name="InvalidMessageError";constructor(t="Invalid message"){super(t),this.name="InvalidMessageError"}};var wr=class extends Error{static name="DialError";constructor(t="Dial error"){super(t),this.name="DialError"}},Le=class extends Error{static name="ListenError";constructor(t="Listen error"){super(t),this.name="ListenError"}};var We=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var Kt=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 $s(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function Zs(...r){let t=[];for(let e of r)$s(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 Ys(...r){let t=[];for(let e of r)$s(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 js=Symbol.for("@libp2p/service-capabilities"),Xs=Symbol.for("@libp2p/service-dependencies");var Po={};Lt(Po,{base58btc:()=>j,base58flickr:()=>rl});var Xd=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 ne(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 Js(r){return new TextEncoder().encode(r)}function ta(r){return new TextDecoder().decode(r)}function ju(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(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var m=0,_=0,R=0,V=g.length;R!==V&&g[R]===0;)R++,m++;for(var E=(V-R)*u+1>>>0,h=new Uint8Array(E);R!==V;){for(var x=g[R],I=0,T=E-1;(x!==0||I<_)&&T!==-1;T--,I++)x+=256*h[T]>>>0,h[T]=x%a>>>0,x=x/a>>>0;if(x!==0)throw new Error("Non-zero carry");_=I,R++}for(var L=E-_;L!==E&&h[L]===0;)L++;for(var N=c.repeat(m);L<E;++L)N+=r.charAt(h[L]);return N}function p(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var m=0;if(g[m]!==" "){for(var _=0,R=0;g[m]===c;)_++,m++;for(var V=(g.length-m)*l+1>>>0,E=new Uint8Array(V);g[m];){var h=e[g.charCodeAt(m)];if(h===255)return;for(var x=0,I=V-1;(h!==0||x<R)&&I!==-1;I--,x++)h+=a*E[I]>>>0,E[I]=h%256>>>0,h=h/256>>>0;if(h!==0)throw new Error("Non-zero carry");R=x,m++}if(g[m]!==" "){for(var T=V-R;T!==V&&E[T]===0;)T++;for(var L=new Uint8Array(_+(V-T)),N=_;T!==V;)L[N++]=E[T++];return L}}}function b(g){var m=p(g);if(m)return m;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:p,decode:b}}var Xu=ju,Qu=Xu,ra=Qu;var Lo=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")}},Ro=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 na(this,t)}},Co=class{decoders;constructor(t){this.decoders=t}or(t){return na(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 na(r,t){return new Co({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var Do=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 Lo(t,e,n),this.decoder=new Ro(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function $e({name:r,prefix:t,encode:e,decode:n}){return new Do(r,t,e,n)}function ye({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=ra(e,r);return $e({prefix:t,name:r,encode:n,decode:i=>ne(o(i))})}function Ju(r,t,e,n){let o=r.length;for(;r[o-1]==="=";)--o;let i=new Uint8Array(o*e/8|0),s=0,a=0,c=0;for(let l=0;l<o;++l){let u=t[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<e|u,s+=e,s>=8&&(s-=8,i[c++]=255&a>>s)}if(s>=e||(255&a<<8-s)!==0)throw new SyntaxError("Unexpected end of data");return i}function tl(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 el(r){let t={};for(let e=0;e<r.length;++e)t[r[e]]=e;return t}function it({name:r,prefix:t,bitsPerChar:e,alphabet:n}){let o=el(n);return $e({prefix:t,name:r,encode(i){return tl(i,n,e)},decode(i){return Ju(i,o,e,r)}})}var j=ye({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),rl=ye({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Bo={};Lt(Bo,{base32:()=>oe,base32hex:()=>sl,base32hexpad:()=>cl,base32hexpadupper:()=>ul,base32hexupper:()=>al,base32pad:()=>ol,base32padupper:()=>il,base32upper:()=>nl,base32z:()=>ll});var oe=it({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),nl=it({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ol=it({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),il=it({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),sl=it({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),al=it({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),cl=it({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),ul=it({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),ll=it({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var No={};Lt(No,{base36:()=>Er,base36upper:()=>fl});var Er=ye({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),fl=ye({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var hl=sa,oa=128,dl=127,pl=~dl,ml=Math.pow(2,31);function sa(r,t,e){t=t||[],e=e||0;for(var n=e;r>=ml;)t[e++]=r&255|oa,r/=128;for(;r&pl;)t[e++]=r&255|oa,r>>>=7;return t[e]=r|0,sa.bytes=e-n+1,t}var yl=Uo,gl=128,ia=127;function Uo(r,n){var e=0,n=n||0,o=0,i=n,s,a=r.length;do{if(i>=a)throw Uo.bytes=0,new RangeError("Could not decode varint");s=r[i++],e+=o<28?(s&ia)<<o:(s&ia)*Math.pow(2,o),o+=7}while(s>=gl);return Uo.bytes=i-n,e}var bl=Math.pow(2,7),xl=Math.pow(2,14),wl=Math.pow(2,21),El=Math.pow(2,28),Sl=Math.pow(2,35),vl=Math.pow(2,42),Al=Math.pow(2,49),_l=Math.pow(2,56),Il=Math.pow(2,63),Tl=function(r){return r<bl?1:r<xl?2:r<wl?3:r<El?4:r<Sl?5:r<vl?6:r<Al?7:r<_l?8:r<Il?9:10},Ll={encode:hl,decode:yl,encodingLength:Tl},Rl=Ll,Sr=Rl;function vr(r,t=0){return[Sr.decode(r,t),Sr.decode.bytes]}function Ze(r,t,e=0){return Sr.encode(r,t,e),t}function Ye(r){return Sr.encodingLength(r)}function Vt(r,t){let e=t.byteLength,n=Ye(r),o=n+Ye(e),i=new Uint8Array(o+e);return Ze(r,i,0),Ze(e,i,n),i.set(t,o),new je(r,e,t,i)}function qt(r){let t=ne(r),[e,n]=vr(t),[o,i]=vr(t.subarray(n)),s=t.subarray(n+i);if(s.byteLength!==o)throw new Error("Incorrect length");return new je(e,o,s,t)}function aa(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 je=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};function ca(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return Dl(e,Oo(r),t??j.encoder);default:return Pl(e,Oo(r),t??oe.encoder)}}var ua=new WeakMap;function Oo(r){let t=ua.get(r);if(t==null){let e=new Map;return ua.set(r,e),e}return t}var st=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!==Ar)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==Bl)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=Vt(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&&aa(t.multihash,n.multihash)}toString(t){return ca(this,t)}toJSON(){return{"/":ca(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??la(n,o,i.bytes))}else if(e[Nl]===!0){let{version:n,multihash:o,code:i}=e,s=qt(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!==Ar)throw new Error(`Version 0 CID must use dag-pb (code: ${Ar}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=la(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,Ar,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=ne(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 je(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,p]=vr(t.subarray(e));return e+=p,f},o=n(),i=Ar;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 Oo(i).set(n,t),i}};function Cl(r,t){switch(r[0]){case"Q":{let e=t??j;return[j.prefix,e.decode(`${j.prefix}${r}`)]}case j.prefix:{let e=t??j;return[j.prefix,e.decode(r)]}case oe.prefix:{let e=t??oe;return[oe.prefix,e.decode(r)]}case Er.prefix:{let e=t??Er;return[Er.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 Dl(r,t,e){let{prefix:n}=e;if(n!==j.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 Pl(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 Ar=112,Bl=18;function la(r,t,e){let n=Ye(r),o=n+Ye(t),i=new Uint8Array(o+e.byteLength);return Ze(r,i,0),Ze(t,i,n),i.set(e,o),i}var Nl=Symbol.for("@ipld/js-cid/CID");var ko={};Lt(ko,{identity:()=>Gt});var fa=0,Ul="identity",ha=ne;function Ol(r){return Vt(fa,ha(r))}var Gt={code:fa,name:Ul,encode:ha,digest:Ol};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 Rt(r=0){return new Uint8Array(r)}function Ut(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 pa=Symbol.for("@achingbrain/uint8arraylist");function da(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 sn(r){return!!r?.[pa]}var ct=class r{bufs;length;[pa]=!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(sn(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(sn(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=da(this.bufs,t);return e.buf[e.index]}set(t,e){let n=da(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(sn(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 Ut(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:Ut(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(!sn(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 p=l;p>=0;p--){let b=this.get(f+p);if(n[p]!==b){u=Math.max(1,p-a[b]);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=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=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=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 Mo={};Lt(Mo,{base10:()=>kl});var kl=ye({prefix:"9",name:"base10",alphabet:"0123456789"});var Ko={};Lt(Ko,{base16:()=>Ml,base16upper:()=>Kl});var Ml=it({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Kl=it({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var qo={};Lt(qo,{base2:()=>ql});var ql=it({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Fo={};Lt(Fo,{base256emoji:()=>Gl});var ma=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}"),Fl=ma.reduce((r,t,e)=>(r[e]=t,r),[]),Hl=ma.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function zl(r){return r.reduce((t,e)=>(t+=Fl[e],t),"")}function Vl(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=Hl[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var Gl=$e({prefix:"\u{1F680}",name:"base256emoji",encode:zl,decode:Vl});var zo={};Lt(zo,{base64:()=>Wl,base64pad:()=>$l,base64url:()=>Ho,base64urlpad:()=>Zl});var Wl=it({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),$l=it({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ho=it({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Zl=it({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Vo={};Lt(Vo,{base8:()=>Yl});var Yl=it({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Go={};Lt(Go,{identity:()=>jl});var jl=$e({prefix:"\0",name:"identity",encode:r=>ta(r),decode:r=>Js(r)});var Np=new TextEncoder,Up=new TextDecoder;var Zo={};Lt(Zo,{sha256:()=>Xe,sha512:()=>Jl});function $o({name:r,code:t,encode:e}){return new Wo(r,t,e)}var Wo=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?Vt(this.code,e):e.then(n=>Vt(this.code,n))}else throw Error("Unknown type, must be binary type")}};function ga(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var Xe=$o({name:"sha2-256",code:18,encode:ga("SHA-256")}),Jl=$o({name:"sha2-512",code:19,encode:ga("SHA-512")});var _r={...Go,...qo,...Vo,...Mo,...Ko,...Bo,...No,...Po,...zo,...Fo},$p={...Zo,...ko};function xa(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var ba=xa("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Yo=xa("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}),tf={utf8:ba,"utf-8":ba,hex:_r.base16,latin1:Yo,ascii:Yo,binary:Yo,..._r},an=tf;function q(r,t="utf8"){let e=an[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function k(r,t="utf8"){let e=an[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var ef=parseInt("11111",2),jo=parseInt("10000000",2),rf=parseInt("01111111",2),wa={0:Ir,1:Ir,2:nf,3:af,4:cf,5:sf,6:of,16:Ir,22:Ir,48:Ir};function ie(r,t={offset:0}){let e=r[t.offset]&ef;if(t.offset++,wa[e]!=null)return wa[e](r,t);throw new Error("No decoder for tag "+e)}function Tr(r,t){let e=0;if((r[t.offset]&jo)===jo){let n=r[t.offset]&rf,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 Ir(r,t){Tr(r,t);let e=[];for(;!(t.offset>=r.byteLength);){let n=ie(r,t);if(n===null)break;e.push(n)}return e}function nf(r,t){let e=Tr(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 of(r,t){let e=Tr(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 sf(r,t){return t.offset++,null}function af(r,t){let e=Tr(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 cf(r,t){let e=Tr(r,t),n=r.subarray(t.offset,t.offset+e);return t.offset+=e,n}function uf(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 Xo(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let t=uf(r.byteLength);return new ct(Uint8Array.from([t.byteLength|jo]),t)}function Ct(r){let t=new ct,e=128;return(r.subarray()[0]&e)===e&&t.append(Uint8Array.from([0])),t.append(r),new ct(Uint8Array.from([2]),Xo(t),t)}function cn(r){let t=Uint8Array.from([0]),e=new ct(t,r);return new ct(Uint8Array.from([3]),Xo(e),e)}function ge(r,t=48){let e=new ct;for(let n of r)e.append(n);return new ct(Uint8Array.from([t]),Xo(e),e)}async function Ea(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 lf=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),ff=Uint8Array.from([6,5,43,129,4,0,34]),hf=Uint8Array.from([6,5,43,129,4,0,35]),df={ext:!0,kty:"EC",crv:"P-256"},pf={ext:!0,kty:"EC",crv:"P-384"},mf={ext:!0,kty:"EC",crv:"P-521"},Qo=32,Jo=48,ti=66;function ei(r){let t=ie(r);return Sa(t)}function Sa(r){let t=r[1][1][0],e=1,n,o;if(t.byteLength===Qo*2+1)return n=k(t.subarray(e,e+Qo),"base64url"),o=k(t.subarray(e+Qo),"base64url"),new Qe({...df,key_ops:["verify"],x:n,y:o});if(t.byteLength===Jo*2+1)return n=k(t.subarray(e,e+Jo),"base64url"),o=k(t.subarray(e+Jo),"base64url"),new Qe({...pf,key_ops:["verify"],x:n,y:o});if(t.byteLength===ti*2+1)return n=k(t.subarray(e,e+ti),"base64url"),o=k(t.subarray(e+ti),"base64url"),new Qe({...mf,key_ops:["verify"],x:n,y:o});throw new ht(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function va(r){return ge([Ct(Uint8Array.from([1])),ge([yf(r.crv)],160),ge([cn(new ct(Uint8Array.from([4]),q(r.x??"","base64url"),q(r.y??"","base64url")))],161)]).subarray()}function yf(r){if(r==="P-256")return lf;if(r==="P-384")return ff;if(r==="P-521")return hf;throw new ht(`Invalid curve ${r}`)}var Qe=class{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=va(this.jwk)),this._raw}toMultihash(){return Gt.digest(Xt(this))}toCID(){return st.createV1(114,this.toMultihash())}toString(){return j.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 Ea(this.jwk,e,t)}};var Re=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function gf(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function un(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function Ce(r,...t){if(!gf(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 Aa(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");un(r.outputLen),un(r.blockLen)}function tr(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 _a(r,t){Ce(r);let e=t.outputLen;if(r.length<e)throw new Error("digestInto() expects output buffer of length at least "+e)}function se(...r){for(let t=0;t<r.length;t++)r[t].fill(0)}function ln(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Wt(r,t){return r<<32-t|r>>>t}function Ia(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function Lr(r){return typeof r=="string"&&(r=Ia(r)),Ce(r),r}function ri(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];Ce(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 Je=class{};function ni(r){let t=n=>r().update(Lr(n)).digest(),e=r();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>r(),t}function fn(r=32){if(Re&&typeof Re.getRandomValues=="function")return Re.getRandomValues(new Uint8Array(r));if(Re&&typeof Re.randomBytes=="function")return Uint8Array.from(Re.randomBytes(r));throw new Error("crypto.getRandomValues must be defined")}function bf(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 Ta(r,t,e){return r&t^~r&e}function La(r,t,e){return r&t^r&e^t&e}var Rr=class extends Je{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=ln(this.buffer)}update(t){tr(this),t=Lr(t),Ce(t);let{view:e,buffer:n,blockLen:o}=this,i=t.length;for(let s=0;s<i;){let a=Math.min(o-this.pos,i-s);if(a===o){let c=ln(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){tr(this),_a(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:o,isLE:i}=this,{pos:s}=this;e[s++]=128,se(this.buffer.subarray(s)),this.padOffset>o-s&&(this.process(n,0),s=0);for(let f=s;f<o;f++)e[f]=0;bf(n,o-8,BigInt(this.length*8),i),this.process(n,0);let a=ln(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.destroyed=s,t.finished=i,t.length=o,t.pos=a,o%e&&t.buffer.set(n),t}clone(){return this._cloneInto()}},ae=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var bt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var hn=BigInt(4294967295),Ra=BigInt(32);function xf(r,t=!1){return t?{h:Number(r&hn),l:Number(r>>Ra&hn)}:{h:Number(r>>Ra&hn)|0,l:Number(r&hn)|0}}function Ca(r,t=!1){let e=r.length,n=new Uint32Array(e),o=new Uint32Array(e);for(let i=0;i<e;i++){let{h:s,l:a}=xf(r[i],t);[n[i],o[i]]=[s,a]}return[n,o]}var oi=(r,t,e)=>r>>>e,ii=(r,t,e)=>r<<32-e|t>>>e,De=(r,t,e)=>r>>>e|t<<32-e,Pe=(r,t,e)=>r<<32-e|t>>>e,Cr=(r,t,e)=>r<<64-e|t>>>e-32,Dr=(r,t,e)=>r>>>e-32|t<<64-e;function Qt(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var Da=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),Pa=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,Ba=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),Na=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,Ua=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),Oa=(r,t,e,n,o,i)=>t+e+n+o+i+(r/2**32|0)|0;var Ef=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),be=new Uint32Array(64),dn=class extends Rr{constructor(t=32){super(64,t,8,!1),this.A=ae[0]|0,this.B=ae[1]|0,this.C=ae[2]|0,this.D=ae[3]|0,this.E=ae[4]|0,this.F=ae[5]|0,this.G=ae[6]|0,this.H=ae[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)be[f]=t.getUint32(e,!1);for(let f=16;f<64;f++){let p=be[f-15],b=be[f-2],g=Wt(p,7)^Wt(p,18)^p>>>3,m=Wt(b,17)^Wt(b,19)^b>>>10;be[f]=m+be[f-7]+g+be[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 p=Wt(a,6)^Wt(a,11)^Wt(a,25),b=u+p+Ta(a,c,l)+Ef[f]+be[f]|0,m=(Wt(n,2)^Wt(n,13)^Wt(n,22))+La(n,o,i)|0;u=l,l=c,c=a,a=s+b|0,s=i,i=o,o=n,n=b+m|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(){se(be)}destroy(){this.set(0,0,0,0,0,0,0,0),se(this.buffer)}};var ka=Ca(["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))),Sf=ka[0],vf=ka[1],xe=new Uint32Array(80),we=new Uint32Array(80),si=class extends Rr{constructor(t=64){super(128,t,16,!1),this.Ah=bt[0]|0,this.Al=bt[1]|0,this.Bh=bt[2]|0,this.Bl=bt[3]|0,this.Ch=bt[4]|0,this.Cl=bt[5]|0,this.Dh=bt[6]|0,this.Dl=bt[7]|0,this.Eh=bt[8]|0,this.El=bt[9]|0,this.Fh=bt[10]|0,this.Fl=bt[11]|0,this.Gh=bt[12]|0,this.Gl=bt[13]|0,this.Hh=bt[14]|0,this.Hl=bt[15]|0}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:p,Gh:b,Gl:g,Hh:m,Hl:_}=this;return[t,e,n,o,i,s,a,c,l,u,f,p,b,g,m,_]}set(t,e,n,o,i,s,a,c,l,u,f,p,b,g,m,_){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=p|0,this.Gh=b|0,this.Gl=g|0,this.Hh=m|0,this.Hl=_|0}process(t,e){for(let E=0;E<16;E++,e+=4)xe[E]=t.getUint32(e),we[E]=t.getUint32(e+=4);for(let E=16;E<80;E++){let h=xe[E-15]|0,x=we[E-15]|0,I=De(h,x,1)^De(h,x,8)^oi(h,x,7),T=Pe(h,x,1)^Pe(h,x,8)^ii(h,x,7),L=xe[E-2]|0,N=we[E-2]|0,K=De(L,N,19)^Cr(L,N,61)^oi(L,N,6),D=Pe(L,N,19)^Dr(L,N,61)^ii(L,N,6),U=Ba(T,D,we[E-7],we[E-16]),B=Na(U,I,K,xe[E-7],xe[E-16]);xe[E]=B|0,we[E]=U|0}let{Ah:n,Al:o,Bh:i,Bl:s,Ch:a,Cl:c,Dh:l,Dl:u,Eh:f,El:p,Fh:b,Fl:g,Gh:m,Gl:_,Hh:R,Hl:V}=this;for(let E=0;E<80;E++){let h=De(f,p,14)^De(f,p,18)^Cr(f,p,41),x=Pe(f,p,14)^Pe(f,p,18)^Dr(f,p,41),I=f&b^~f&m,T=p&g^~p&_,L=Ua(V,x,T,vf[E],we[E]),N=Oa(L,R,h,I,Sf[E],xe[E]),K=L|0,D=De(n,o,28)^Cr(n,o,34)^Cr(n,o,39),U=Pe(n,o,28)^Dr(n,o,34)^Dr(n,o,39),B=n&i^n&a^i&a,lt=o&s^o&c^s&c;R=m|0,V=_|0,m=b|0,_=g|0,b=f|0,g=p|0,{h:f,l:p}=Qt(l|0,u|0,N|0,K|0),l=a|0,u=c|0,a=i|0,c=s|0,i=n|0,s=o|0;let v=Da(K,U,lt);n=Pa(v,N,D,B),o=v|0}({h:n,l:o}=Qt(this.Ah|0,this.Al|0,n|0,o|0)),{h:i,l:s}=Qt(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=Qt(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=Qt(this.Dh|0,this.Dl|0,l|0,u|0),{h:f,l:p}=Qt(this.Eh|0,this.El|0,f|0,p|0),{h:b,l:g}=Qt(this.Fh|0,this.Fl|0,b|0,g|0),{h:m,l:_}=Qt(this.Gh|0,this.Gl|0,m|0,_|0),{h:R,l:V}=Qt(this.Hh|0,this.Hl|0,R|0,V|0),this.set(n,o,i,s,a,c,l,u,f,p,b,g,m,_,R,V)}roundClean(){se(xe,we)}destroy(){se(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var pn=ni(()=>new dn);var Ma=ni(()=>new si);var li=BigInt(0),ui=BigInt(1);function er(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function fi(r){if(!er(r))throw new Error("Uint8Array expected")}function Jt(r,t){if(typeof t!="boolean")throw new Error(r+" boolean expected, got "+t)}function Pr(r){let t=r.toString(16);return t.length&1?"0"+t:t}function Fa(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?li:BigInt("0x"+r)}var Ha=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Af=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function Ee(r){if(fi(r),Ha)return r.toHex();let t="";for(let e=0;e<r.length;e++)t+=Af[r[e]];return t}var ce={_0:48,_9:57,A:65,F:70,a:97,f:102};function Ka(r){if(r>=ce._0&&r<=ce._9)return r-ce._0;if(r>=ce.A&&r<=ce.F)return r-(ce.A-10);if(r>=ce.a&&r<=ce.f)return r-(ce.a-10)}function Br(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(Ha)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=Ka(r.charCodeAt(i)),a=Ka(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 ue(r){return Fa(Ee(r))}function Be(r){return fi(r),Fa(Ee(Uint8Array.from(r).reverse()))}function Ne(r,t){return Br(r.toString(16).padStart(t*2,"0"))}function rr(r,t){return Ne(r,t).reverse()}function rt(r,t,e){let n;if(typeof t=="string")try{n=Br(t)}catch(i){throw new Error(r+" must be hex string or Uint8Array, cause: "+i)}else if(er(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];fi(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 ai=r=>typeof r=="bigint"&&li<=r;function mn(r,t,e){return ai(r)&&ai(t)&&ai(e)&&t<=r&&r<e}function Ot(r,t,e,n){if(!mn(t,e,n))throw new Error("expected valid "+r+": "+e+" <= n < "+n+", got "+t)}function za(r){let t;for(t=0;r>li;r>>=ui,t+=1);return t}var Ue=r=>(ui<<BigInt(r))-ui,ci=r=>new Uint8Array(r),qa=r=>Uint8Array.from(r);function Va(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=ci(r),o=ci(r),i=0,s=()=>{n.fill(1),o.fill(0),i=0},a=(...f)=>e(o,n,...f),c=(f=ci(0))=>{o=a(qa([0]),f),n=a(),f.length!==0&&(o=a(qa([1]),f),n=a())},l=()=>{if(i++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,p=[];for(;f<t;){n=a();let b=n.slice();p.push(b),f+=n.length}return Se(...p)};return(f,p)=>{s(),c(f);let b;for(;!(b=p(l()));)c();return s(),b}}var _f={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"||er(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 le(r,t,e={}){let n=(o,i,s)=>{let a=_f[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 nr(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 _t=BigInt(0),mt=BigInt(1),Oe=BigInt(2),If=BigInt(3),Wa=BigInt(4),$a=BigInt(5),Za=BigInt(8);function J(r,t){let e=r%t;return e>=_t?e:t+e}function nt(r,t,e){let n=r;for(;t-- >_t;)n*=n,n%=e;return n}function yn(r,t){if(r===_t)throw new Error("invert: expected non-zero number");if(t<=_t)throw new Error("invert: expected positive modulus, got "+t);let e=J(r,t),n=t,o=_t,i=mt,s=mt,a=_t;for(;e!==_t;){let l=n/e,u=n%e,f=o-s*l,p=i-a*l;n=e,e=u,o=s,i=a,s=f,a=p}if(n!==mt)throw new Error("invert: does not exist");return J(o,t)}function Ya(r,t){let e=(r.ORDER+mt)/Wa,n=r.pow(t,e);if(!r.eql(r.sqr(n),t))throw new Error("Cannot find square root");return n}function Tf(r,t){let e=(r.ORDER-$a)/Za,n=r.mul(t,Oe),o=r.pow(n,e),i=r.mul(t,o),s=r.mul(r.mul(i,Oe),o),a=r.mul(i,r.sub(s,r.ONE));if(!r.eql(r.sqr(a),t))throw new Error("Cannot find square root");return a}function Lf(r){if(r<BigInt(3))throw new Error("sqrt is not defined for small field");let t=r-mt,e=0;for(;t%Oe===_t;)t/=Oe,e++;let n=Oe,o=fe(r);for(;Ga(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(e===1)return Ya;let i=o.pow(n,t),s=(t+mt)/Oe;return function(c,l){if(c.is0(l))return l;if(Ga(c,l)!==1)throw new Error("Cannot find square root");let u=e,f=c.mul(c.ONE,i),p=c.pow(l,t),b=c.pow(l,s);for(;!c.eql(p,c.ONE);){if(c.is0(p))return c.ZERO;let g=1,m=c.sqr(p);for(;!c.eql(m,c.ONE);)if(g++,m=c.sqr(m),g===u)throw new Error("Cannot find square root");let _=mt<<BigInt(u-g-1),R=c.pow(f,_);u=g,f=c.sqr(R),p=c.mul(p,f),b=c.mul(b,R)}return b}}function Rf(r){return r%Wa===If?Ya:r%Za===$a?Tf:Lf(r)}var ja=(r,t)=>(J(r,t)&mt)===mt,Cf=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function hi(r){let t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},e=Cf.reduce((n,o)=>(n[o]="function",n),t);return le(r,e)}function Df(r,t,e){if(e<_t)throw new Error("invalid exponent, negatives unsupported");if(e===_t)return r.ONE;if(e===mt)return t;let n=r.ONE,o=t;for(;e>_t;)e&mt&&(n=r.mul(n,o)),o=r.sqr(o),e>>=mt;return n}function or(r,t,e=!1){let n=new Array(t.length).fill(e?r.ZERO:void 0),o=t.reduce((s,a,c)=>r.is0(a)?s:(n[c]=s,r.mul(s,a)),r.ONE),i=r.inv(o);return t.reduceRight((s,a,c)=>r.is0(a)?s:(n[c]=r.mul(s,n[c]),r.mul(s,a)),i),n}function Ga(r,t){let e=(r.ORDER-mt)/Oe,n=r.pow(t,e),o=r.eql(n,r.ONE),i=r.eql(n,r.ZERO),s=r.eql(n,r.neg(r.ONE));if(!o&&!i&&!s)throw new Error("invalid Legendre symbol result");return o?1:i?0:-1}function di(r,t){t!==void 0&&un(t);let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}function fe(r,t,e=!1,n={}){if(r<=_t)throw new Error("invalid field: expected ORDER > 0, got "+r);let{nBitLength:o,nByteLength:i}=di(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:Ue(o),ZERO:_t,ONE:mt,create:c=>J(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return _t<=c&&c<r},is0:c=>c===_t,isOdd:c=>(c&mt)===mt,neg:c=>J(-c,r),eql:(c,l)=>c===l,sqr:c=>J(c*c,r),add:(c,l)=>J(c+l,r),sub:(c,l)=>J(c-l,r),mul:(c,l)=>J(c*l,r),pow:(c,l)=>Df(a,c,l),div:(c,l)=>J(c*yn(l,r),r),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>yn(c,r),sqrt:n.sqrt||(c=>(s||(s=Rf(r)),s(a,c))),toBytes:c=>e?rr(c,i):Ne(c,i),fromBytes:c=>{if(c.length!==i)throw new Error("Field.fromBytes: expected "+i+" bytes, got "+c.length);return e?Be(c):ue(c)},invertBatch:c=>or(a,c),cmov:(c,l,u)=>u?l:c});return Object.freeze(a)}function Xa(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 pi(r){let t=Xa(r);return t+Math.ceil(t/2)}function Qa(r,t,e=!1){let n=r.length,o=Xa(t),i=pi(t);if(n<16||n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);let s=e?Be(r):ue(r),a=J(s,t-mt)+mt;return e?rr(a,o):Ne(a,o)}var Ja=BigInt(0),xi=BigInt(1);function mi(r,t){let e=t.negate();return r?e:t}function ec(r,t){if(!Number.isSafeInteger(r)||r<=0||r>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+r)}function yi(r,t){ec(r,t);let e=Math.ceil(t/r)+1,n=2**(r-1),o=2**r,i=Ue(r),s=BigInt(r);return{windows:e,windowSize:n,mask:i,maxNumber:o,shiftBy:s}}function tc(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+=xi);let l=t*n,u=l+Math.abs(a)-1,f=a===0,p=a<0,b=t%2!==0;return{nextN:c,offset:u,isZero:f,isNeg:p,isNegF:b,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 gi=new WeakMap,rc=new WeakMap;function bi(r){return rc.get(r)||1}function gn(r,t){return{constTimeNegate:mi,hasPrecomputes(e){return bi(e)!==1},unsafeLadder(e,n,o=r.ZERO){let i=e;for(;n>Ja;)n&xi&&(o=o.add(i)),i=i.double(),n>>=xi;return o},precomputeWindow(e,n){let{windows:o,windowSize:i}=yi(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=yi(e,t);for(let c=0;c<a.windows;c++){let{nextN:l,offset:u,isZero:f,isNeg:p,isNegF:b,offsetF:g}=tc(o,c,a);o=l,f?s=s.add(mi(b,n[g])):i=i.add(mi(p,n[u]))}return{p:i,f:s}},wNAFUnsafe(e,n,o,i=r.ZERO){let s=yi(e,t);for(let a=0;a<s.windows&&o!==Ja;a++){let{nextN:c,offset:l,isZero:u,isNeg:f}=tc(o,a,s);if(o=c,!u){let p=n[l];i=i.add(f?p.negate():p)}}return i},getPrecomputes(e,n,o){let i=gi.get(n);return i||(i=this.precomputeWindow(n,e),e!==1&&gi.set(n,o(i))),i},wNAFCached(e,n,o){let i=bi(e);return this.wNAF(i,this.getPrecomputes(i,e,o),n)},wNAFCachedUnsafe(e,n,o,i){let s=bi(e);return s===1?this.unsafeLadder(e,n,i):this.wNAFUnsafe(s,this.getPrecomputes(s,e,o),n,i)},setWindowSize(e,n){ec(n,t),rc.set(e,n),gi.delete(e)}}}function bn(r,t,e,n){Pf(e,r),Bf(n,t);let o=e.length,i=n.length;if(o!==i)throw new Error("arrays of points and scalars must have equal length");let s=r.ZERO,a=za(BigInt(o)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let l=Ue(c),u=new Array(Number(l)+1).fill(s),f=Math.floor((t.BITS-1)/c)*c,p=s;for(let b=f;b>=0;b-=c){u.fill(s);for(let m=0;m<i;m++){let _=n[m],R=Number(_>>BigInt(b)&l);u[R]=u[R].add(e[m])}let g=s;for(let m=u.length-1,_=s;m>0;m--)_=_.add(u[m]),g=g.add(_);if(p=p.add(g),b!==0)for(let m=0;m<c;m++)p=p.double()}return p}function Nr(r){return hi(r.Fp),le(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...di(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var te=BigInt(0),It=BigInt(1),nc=BigInt(2),Nf=BigInt(8),Uf={zip215:!0};function Of(r){let t=Nr(r);return le(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function oc(r){let t=Of(r),{Fp:e,n,prehash:o,hash:i,randomBytes:s,nByteLength:a,h:c}=t,l=nc<<BigInt(a*8)-It,u=e.create,f=fe(t.n,t.nBitLength);function p(w,d){let y=e.sqr(w),A=e.sqr(d),P=e.add(e.mul(t.a,y),A),O=e.add(e.ONE,e.mul(t.d,e.mul(y,A)));return e.eql(P,O)}if(!p(t.Gx,t.Gy))throw new Error("bad curve params: generator point");let b=t.uvRatio||((w,d)=>{try{return{isValid:!0,value:e.sqrt(w*e.inv(d))}}catch{return{isValid:!1,value:te}}}),g=t.adjustScalarBytes||(w=>w),m=t.domain||((w,d,y)=>{if(Jt("phflag",y),d.length||y)throw new Error("Contexts/pre-hash are not supported");return w});function _(w,d,y=!1){let A=y?It:te;Ot("coordinate "+w,d,A,l)}function R(w){if(!(w instanceof h))throw new Error("ExtendedPoint expected")}let V=nr((w,d)=>{let{ex:y,ey:A,ez:P}=w,O=w.is0();d==null&&(d=O?Nf:e.inv(P));let z=u(y*d),G=u(A*d),W=u(P*d);if(O)return{x:te,y:It};if(W!==It)throw new Error("invZ was invalid");return{x:z,y:G}}),E=nr(w=>{let{a:d,d:y}=t;if(w.is0())throw new Error("bad point: ZERO");let{ex:A,ey:P,ez:O,et:z}=w,G=u(A*A),W=u(P*P),Y=u(O*O),ft=u(Y*Y),at=u(G*d),gt=u(Y*u(at+W)),Tt=u(ft+u(y*u(G*W)));if(gt!==Tt)throw new Error("bad point: equation left != right (1)");let pt=u(A*P),xt=u(O*z);if(pt!==xt)throw new Error("bad point: equation left != right (2)");return!0});class h{constructor(d,y,A,P){_("x",d),_("y",y),_("z",A,!0),_("t",P),this.ex=d,this.ey=y,this.ez=A,this.et=P,Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(d){if(d instanceof h)throw new Error("extended point not allowed");let{x:y,y:A}=d||{};return _("x",y),_("y",A),new h(y,A,It,u(y*A))}static normalizeZ(d){let y=or(e,d.map(A=>A.ez));return d.map((A,P)=>A.toAffine(y[P])).map(h.fromAffine)}static msm(d,y){return bn(h,f,d,y)}_setWindowSize(d){T.setWindowSize(this,d)}assertValidity(){E(this)}equals(d){R(d);let{ex:y,ey:A,ez:P}=this,{ex:O,ey:z,ez:G}=d,W=u(y*G),Y=u(O*P),ft=u(A*G),at=u(z*P);return W===Y&&ft===at}is0(){return this.equals(h.ZERO)}negate(){return new h(u(-this.ex),this.ey,this.ez,u(-this.et))}double(){let{a:d}=t,{ex:y,ey:A,ez:P}=this,O=u(y*y),z=u(A*A),G=u(nc*u(P*P)),W=u(d*O),Y=y+A,ft=u(u(Y*Y)-O-z),at=W+z,gt=at-G,Tt=W-z,pt=u(ft*gt),xt=u(at*Tt),Nt=u(ft*Tt),zt=u(gt*at);return new h(pt,xt,zt,Nt)}add(d){R(d);let{a:y,d:A}=t,{ex:P,ey:O,ez:z,et:G}=this,{ex:W,ey:Y,ez:ft,et:at}=d,gt=u(P*W),Tt=u(O*Y),pt=u(G*A*at),xt=u(z*ft),Nt=u((P+O)*(W+Y)-gt-Tt),zt=xt-pt,xr=xt+pt,Vs=u(Tt-y*gt),Fu=u(Nt*zt),Hu=u(xr*Vs),zu=u(Nt*Vs),Vu=u(zt*xr);return new h(Fu,Hu,Vu,zu)}subtract(d){return this.add(d.negate())}wNAF(d){return T.wNAFCached(this,d,h.normalizeZ)}multiply(d){let y=d;Ot("scalar",y,It,n);let{p:A,f:P}=this.wNAF(y);return h.normalizeZ([A,P])[0]}multiplyUnsafe(d,y=h.ZERO){let A=d;return Ot("scalar",A,te,n),A===te?I:this.is0()||A===It?this:T.wNAFCachedUnsafe(this,A,h.normalizeZ,y)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return T.unsafeLadder(this,n).is0()}toAffine(d){return V(this,d)}clearCofactor(){let{h:d}=t;return d===It?this:this.multiplyUnsafe(d)}static fromHex(d,y=!1){let{d:A,a:P}=t,O=e.BYTES;d=rt("pointHex",d,O),Jt("zip215",y);let z=d.slice(),G=d[O-1];z[O-1]=G&-129;let W=Be(z),Y=y?l:e.ORDER;Ot("pointHex.y",W,te,Y);let ft=u(W*W),at=u(ft-It),gt=u(A*ft-P),{isValid:Tt,value:pt}=b(at,gt);if(!Tt)throw new Error("Point.fromHex: invalid y coordinate");let xt=(pt&It)===It,Nt=(G&128)!==0;if(!y&&pt===te&&Nt)throw new Error("Point.fromHex: x=0 and x_0=1");return Nt!==xt&&(pt=u(-pt)),h.fromAffine({x:pt,y:W})}static fromPrivateKey(d){let{scalar:y}=K(d);return x.multiply(y)}toRawBytes(){let{x:d,y}=this.toAffine(),A=rr(y,e.BYTES);return A[A.length-1]|=d&It?128:0,A}toHex(){return Ee(this.toRawBytes())}}h.BASE=new h(t.Gx,t.Gy,It,u(t.Gx*t.Gy)),h.ZERO=new h(te,It,It,te);let{BASE:x,ZERO:I}=h,T=gn(h,a*8);function L(w){return J(w,n)}function N(w){return L(Be(w))}function K(w){let d=e.BYTES;w=rt("private key",w,d);let y=rt("hashed private key",i(w),2*d),A=g(y.slice(0,d)),P=y.slice(d,2*d),O=N(A);return{head:A,prefix:P,scalar:O}}function D(w){let{head:d,prefix:y,scalar:A}=K(w),P=x.multiply(A),O=P.toRawBytes();return{head:d,prefix:y,scalar:A,point:P,pointBytes:O}}function U(w){return D(w).pointBytes}function B(w=Uint8Array.of(),...d){let y=Se(...d);return N(i(m(y,rt("context",w),!!o)))}function lt(w,d,y={}){w=rt("message",w),o&&(w=o(w));let{prefix:A,scalar:P,pointBytes:O}=D(d),z=B(y.context,A,w),G=x.multiply(z).toRawBytes(),W=B(y.context,G,O,w),Y=L(z+W*P);Ot("signature.s",Y,te,n);let ft=Se(G,rr(Y,e.BYTES));return rt("result",ft,e.BYTES*2)}let v=Uf;function S(w,d,y,A=v){let{context:P,zip215:O}=A,z=e.BYTES;w=rt("signature",w,2*z),d=rt("message",d),y=rt("publicKey",y,z),O!==void 0&&Jt("zip215",O),o&&(d=o(d));let G=Be(w.slice(z,2*z)),W,Y,ft;try{W=h.fromHex(y,O),Y=h.fromHex(w.slice(0,z),O),ft=x.multiplyUnsafe(G)}catch{return!1}if(!O&&W.isSmallOrder())return!1;let at=B(P,Y.toRawBytes(),W.toRawBytes(),d);return Y.add(W.multiplyUnsafe(at)).subtract(ft).clearCofactor().equals(h.ZERO)}return x._setWindowSize(8),{CURVE:t,getPublicKey:U,sign:lt,verify:S,ExtendedPoint:h,utils:{getExtendedPublicKey:D,randomPrivateKey:()=>s(e.BYTES),precompute(w=8,d=h.BASE){return d._setWindowSize(w),d.multiply(BigInt(3)),d}}}}var wi=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),ic=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),jm=BigInt(0),kf=BigInt(1),sc=BigInt(2),Xm=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=wi,a=r*r%i*r%i,c=nt(a,sc,i)*a%i,l=nt(c,kf,i)*r%i,u=nt(l,Mf,i)*l%i,f=nt(u,t,i)*u%i,p=nt(f,e,i)*f%i,b=nt(p,n,i)*p%i,g=nt(b,o,i)*b%i,m=nt(g,o,i)*b%i,_=nt(m,t,i)*u%i;return{pow_p_5_8:nt(_,sc,i)*r%i,b2:a}}function Ff(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function Hf(r,t){let e=wi,n=J(t*t*t,e),o=J(n*n*t,e),i=qf(r*o).pow_p_5_8,s=J(r*n*i,e),a=J(t*s*s,e),c=s,l=J(s*ic,e),u=a===r,f=a===J(-r,e),p=a===J(-r*ic,e);return u&&(s=c),(f||p)&&(s=l),ja(s,e)&&(s=J(-s,e)),{isValid:u||f,value:s}}var ac=fe(wi,void 0,!0),zf={a:ac.create(BigInt(-1)),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:ac,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:Kf,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Ma,randomBytes:fn,adjustScalarBytes:Ff,uvRatio:Hf},cc=oc(zf);var xn=32;function uc(r,t,e){return cc.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}var wn=class{type="Ed25519";raw;constructor(t){this.raw=Ei(t,xn)}toMultihash(){return Gt.digest(Xt(this))}toCID(){return st.createV1(114,this.toMultihash())}toString(){return j.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 uc(this.raw,e,t)}};function Si(r){return r=Ei(r,xn),new wn(r)}function Ei(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),vi=Math.pow(2,28),Ai=Math.pow(2,35),_i=Math.pow(2,42),Ii=Math.pow(2,49),Z=128,wt=127;function Et(r){if(r<Gf)return 1;if(r<Wf)return 2;if(r<$f)return 3;if(r<vi)return 4;if(r<Ai)return 5;if(r<_i)return 6;if(r<Ii)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(Et(r)){case 8:t[e++]=r&255|Z,r/=128;case 7:t[e++]=r&255|Z,r/=128;case 6:t[e++]=r&255|Z,r/=128;case 5:t[e++]=r&255|Z,r/=128;case 4:t[e++]=r&255|Z,r>>>=7;case 3:t[e++]=r&255|Z,r>>>=7;case 2:t[e++]=r&255|Z,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|Z),r/=128;case 7:t.set(e++,r&255|Z),r/=128;case 6:t.set(e++,r&255|Z),r/=128;case 5:t.set(e++,r&255|Z),r/=128;case 4:t.set(e++,r&255|Z),r>>>=7;case 3:t.set(e++,r&255|Z),r>>>=7;case 2:t.set(e++,r&255|Z),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function Li(r,t){let e=r[t],n=0;if(n+=e&wt,e<Z||(e=r[t+1],n+=(e&wt)<<7,e<Z)||(e=r[t+2],n+=(e&wt)<<14,e<Z)||(e=r[t+3],n+=(e&wt)<<21,e<Z)||(e=r[t+4],n+=(e&wt)*vi,e<Z)||(e=r[t+5],n+=(e&wt)*Ai,e<Z)||(e=r[t+6],n+=(e&wt)*_i,e<Z)||(e=r[t+7],n+=(e&wt)*Ii,e<Z))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<Z||(e=r.get(t+1),n+=(e&wt)<<7,e<Z)||(e=r.get(t+2),n+=(e&wt)<<14,e<Z)||(e=r.get(t+3),n+=(e&wt)<<21,e<Z)||(e=r.get(t+4),n+=(e&wt)*vi,e<Z)||(e=r.get(t+5),n+=(e&wt)*Ai,e<Z)||(e=r.get(t+6),n+=(e&wt)*_i,e<Z)||(e=r.get(t+7),n+=(e&wt)*Ii,e<Z))return n;throw new RangeError("Could not decode varint")}function Ft(r,t,e=0){return t==null&&(t=Rt(Et(r))),t instanceof Uint8Array?Ti(r,t,e):Zf(r,t,e)}function he(r,t=0){return r instanceof Uint8Array?Li(r,t):Yf(r,t)}var Ri=new Float32Array([-0]),ve=new Uint8Array(Ri.buffer);function fc(r,t,e){Ri[0]=r,t[e]=ve[0],t[e+1]=ve[1],t[e+2]=ve[2],t[e+3]=ve[3]}function hc(r,t){return ve[0]=r[t],ve[1]=r[t+1],ve[2]=r[t+2],ve[3]=r[t+3],Ri[0]}var Ci=new Float64Array([-0]),St=new Uint8Array(Ci.buffer);function dc(r,t,e){Ci[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 pc(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],Ci[0]}var jf=BigInt(Number.MAX_SAFE_INTEGER),Xf=BigInt(Number.MIN_SAFE_INTEGER),kt=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 ke;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>mc&&(o=0n,++n>mc&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return ke;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):ke}},ke=new kt(0,0);ke.toBigInt=function(){return 0n};ke.zzEncode=ke.zzDecode=function(){return this};ke.length=function(){return 1};var mc=4294967296n;function yc(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 gc(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 Di(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 $t(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function Sn(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var Pi=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,$t(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 $t(this,4);return Sn(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw $t(this,4);return Sn(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw $t(this,4);let t=hc(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw $t(this,4);let t=pc(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 $t(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return gc(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw $t(this,t);this.pos+=t}else do if(this.pos>=this.len)throw $t(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 kt(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 $t(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 $t(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 $t(this,8);let t=Sn(this.buf,this.pos+=4),e=Sn(this.buf,this.pos+=4);return new kt(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=Li(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 Bi(r){return new Pi(r instanceof Uint8Array?r:r.subarray())}function Dt(r,t,e){let n=Bi(r);return t.decode(n,void 0,e)}function Ni(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 Me=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function Ui(){}var ki=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},Qf=Ni();function Jf(r){return globalThis.Buffer!=null?Rt(r):Qf(r)}var Or=class{len;head;tail;states;constructor(){this.len=0,this.head=new Me(Ui,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new Me(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new Mi((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(vn,10,kt.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=kt.fromBigInt(t);return this._push(vn,e.length(),e)}uint64Number(t){return this._push(Ti,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=kt.fromBigInt(t).zzEncode();return this._push(vn,e.length(),e)}sint64Number(t){let e=kt.fromNumber(t).zzEncode();return this._push(vn,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(Oi,1,t?1:0)}fixed32(t){return this._push(Ur,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=kt.fromBigInt(t);return this._push(Ur,4,e.lo)._push(Ur,4,e.hi)}fixed64Number(t){let e=kt.fromNumber(t);return this._push(Ur,4,e.lo)._push(Ur,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(fc,4,t)}double(t){return this._push(dc,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(Oi,1,0):this.uint32(e)._push(eh,e,t)}string(t){let e=yc(t);return e!==0?this.uint32(e)._push(Di,e,t):this._push(Oi,1,0)}fork(){return this.states=new ki(this),this.head=this.tail=new Me(Ui,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Me(Ui,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 Oi(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 Mi=class extends Me{next;constructor(t,e){super(th,t,e),this.next=void 0}};function vn(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 Ur(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&&(Or.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(rh,t,r),this},Or.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?Di(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(q(r),e)}function Ki(){return new Or}function Pt(r,t){let e=Ki();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var ir;(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"})(ir||(ir={}));function An(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function Ke(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 An("enum",ir.VARINT,e,n)}function Bt(r,t){return An("message",ir.LENGTH_DELIMITED,r,t)}var kr=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var ut;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(ut||(ut={}));var qi;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(qi||(qi={}));(function(r){r.codec=()=>Ke(qi)})(ut||(ut={}));var ee;(function(r){let t;r.codec=()=>(t==null&&(t=Bt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),ut.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=ut.codec().decode(e);break}case 2:{i.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Pt(e,r.codec()),r.decode=(e,n)=>Dt(e,r.codec(),n)})(ee||(ee={}));var Fi;(function(r){let t;r.codec=()=>(t==null&&(t=Bt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),ut.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=ut.codec().decode(e);break}case 2:{i.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Pt(e,r.codec()),r.decode=(e,n)=>Dt(e,r.codec(),n)})(Fi||(Fi={}));var Mr=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},_n=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var wc={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new _n("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 Ae=wc;var qr={};Lt(qr,{MAX_RSA_KEY_SIZE:()=>Hi,generateRSAKeyPair:()=>Ac,jwkToJWKKeyPair:()=>_c,jwkToPkcs1:()=>ah,jwkToPkix:()=>Wi,jwkToRSAPrivateKey:()=>ji,pkcs1MessageToJwk:()=>Vi,pkcs1MessageToRSAPrivateKey:()=>$i,pkcs1ToJwk:()=>sh,pkcs1ToRSAPrivateKey:()=>vc,pkixMessageToJwk:()=>Gi,pkixMessageToRSAPublicKey:()=>Yi,pkixToJwk:()=>ch,pkixToRSAPublicKey:()=>Zi});var In=pn;var sr=class{type="RSA";jwk;_raw;_multihash;constructor(t,e){this.jwk=t,this._multihash=e}get raw(){return this._raw==null&&(this._raw=qr.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return st.createV1(114,this._multihash)}toString(){return j.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 Sc(this.jwk,e,t)}},Kr=class{type="RSA";jwk;_raw;publicKey;constructor(t,e){this.jwk=t,this.publicKey=e}get raw(){return this._raw==null&&(this._raw=qr.jwkToPkcs1(this.jwk)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:dt(this.raw,t.raw)}sign(t){return Ec(this.jwk,t)}};var Hi=8192,zi=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=ie(r);return Vi(t)}function Vi(r){return{n:k(r[1],"base64url"),e:k(r[2],"base64url"),d:k(r[3],"base64url"),p:k(r[4],"base64url"),q:k(r[5],"base64url"),dp:k(r[6],"base64url"),dq:k(r[7],"base64url"),qi:k(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 ge([Ct(Uint8Array.from([0])),Ct(q(r.n,"base64url")),Ct(q(r.e,"base64url")),Ct(q(r.d,"base64url")),Ct(q(r.p,"base64url")),Ct(q(r.q,"base64url")),Ct(q(r.dp,"base64url")),Ct(q(r.dq,"base64url")),Ct(q(r.qi,"base64url"))]).subarray()}function ch(r){let t=ie(r,{offset:0});return Gi(t)}function Gi(r){let t=ie(r[1],{offset:0});return{kty:"RSA",n:k(t[0],"base64url"),e:k(t[1],"base64url")}}function Wi(r){if(r.n==null||r.e==null)throw new ht("JWK was missing components");return ge([ih,cn(ge([Ct(q(r.n,"base64url")),Ct(q(r.e,"base64url"))]))]).subarray()}function vc(r){let t=ie(r);return $i(t)}function $i(r){let t=Vi(r);return ji(t)}function Zi(r,t){if(r.byteLength>=oh)throw new Ge("Key size is too large");let e=ie(r,{offset:0});return Yi(e,r,t)}function Yi(r,t,e){let n=Gi(r);if(e==null){let o=In(ee.encode({Type:ut.RSA,Data:t}));e=Vt(zi,o)}return new sr(n,e)}function ji(r){if(Tc(r)>Hi)throw new ht("Key size is too large");let t=_c(r),e=In(ee.encode({Type:ut.RSA,Data:Wi(t.publicKey)})),n=Vt(zi,e);return new Kr(t.privateKey,new sr(t.publicKey,n))}async function Ac(r){if(r>Hi)throw new ht("Key size is too large");let t=await Ic(r),e=In(ee.encode({Type:ut.RSA,Data:Wi(t.publicKey)})),n=Vt(zi,e);return new Kr(t.privateKey,new sr(t.publicKey,n))}function _c(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 Ic(r){let t=await Ae.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 Ec(r,t){let e=await Ae.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Ae.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},e,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}async function Sc(r,t,e){let n=await Ae.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Ae.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([Ae.get().subtle.exportKey("jwk",r.privateKey),Ae.get().subtle.exportKey("jwk",r.publicKey)])}function Tc(r){if(r.kty!=="RSA")throw new ht("invalid key type");if(r.n==null)throw new ht("invalid key modulus");return q(r.n,"base64url").length*8}var Tn=class extends Je{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,Aa(t);let n=Lr(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),se(i)}update(t){return tr(this),this.iHash.update(t),this}digestInto(t){tr(this),Ce(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}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Xi=(r,t,e)=>new Tn(r,t).update(e).digest();Xi.create=(r,t)=>new Tn(r,t);function Lc(r){r.lowS!==void 0&&Jt("lowS",r.lowS),r.prehash!==void 0&&Jt("prehash",r.prehash)}function lh(r){let t=Nr(r);le(t,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});let{endo:e,Fp:n,a:o}=t;if(e){if(!n.eql(o,n.ZERO))throw new Error("invalid endo: CURVE.a must be 0");if(typeof e!="object"||typeof e.beta!="bigint"||typeof e.splitScalar!="function")throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function')}return Object.freeze({...t})}var ts=class extends Error{constructor(t=""){super(t)}},de={Err:ts,_tlv:{encode:(r,t)=>{let{Err:e}=de;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=Pr(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let i=n>127?Pr(o.length/2|128):"";return Pr(r)+i+o+t},decode(r,t){let{Err:e}=de,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}=de;if(r<pe)throw new t("integer: negative integers are not allowed");let e=Pr(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}=de;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 ue(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=de,o=rt("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}=de,n=t.encode(2,e.encode(r.r)),o=t.encode(2,e.encode(r.s)),i=n+o;return t.encode(48,i)}};function Qi(r,t){return Ee(Ne(r,t))}var pe=BigInt(0),yt=BigInt(1),Ay=BigInt(2),Ji=BigInt(3),fh=BigInt(4);function hh(r){let t=lh(r),{Fp:e}=t,n=fe(t.n,t.nBitLength),o=t.toBytes||((E,h,x)=>{let I=h.toAffine();return Se(Uint8Array.from([4]),e.toBytes(I.x),e.toBytes(I.y))}),i=t.fromBytes||(E=>{let h=E.subarray(1),x=e.fromBytes(h.subarray(0,e.BYTES)),I=e.fromBytes(h.subarray(e.BYTES,2*e.BYTES));return{x,y:I}});function s(E){let{a:h,b:x}=t,I=e.sqr(E),T=e.mul(I,E);return e.add(e.add(T,e.mul(E,h)),x)}function a(E,h){let x=e.sqr(h),I=s(E);return e.eql(x,I)}if(!a(t.Gx,t.Gy))throw new Error("bad curve params: generator point");let c=e.mul(e.pow(t.a,Ji),fh),l=e.mul(e.sqr(t.b),BigInt(27));if(e.is0(e.add(c,l)))throw new Error("bad curve params: a or b");function u(E){return mn(E,yt,t.n)}function f(E){let{allowedPrivateKeyLengths:h,nByteLength:x,wrapPrivateKey:I,n:T}=t;if(h&&typeof E!="bigint"){if(er(E)&&(E=Ee(E)),typeof E!="string"||!h.includes(E.length))throw new Error("invalid private key");E=E.padStart(x*2,"0")}let L;try{L=typeof E=="bigint"?E:ue(rt("private key",E,x))}catch{throw new Error("invalid private key, expected hex or "+x+" bytes, got "+typeof E)}return I&&(L=J(L,T)),Ot("private key",L,yt,T),L}function p(E){if(!(E instanceof m))throw new Error("ProjectivePoint expected")}let b=nr((E,h)=>{let{px:x,py:I,pz:T}=E;if(e.eql(T,e.ONE))return{x,y:I};let L=E.is0();h==null&&(h=L?e.ONE:e.inv(T));let N=e.mul(x,h),K=e.mul(I,h),D=e.mul(T,h);if(L)return{x:e.ZERO,y:e.ZERO};if(!e.eql(D,e.ONE))throw new Error("invZ was invalid");return{x:N,y:K}}),g=nr(E=>{if(E.is0()){if(t.allowInfinityPoint&&!e.is0(E.py))return;throw new Error("bad point: ZERO")}let{x:h,y:x}=E.toAffine();if(!e.isValid(h)||!e.isValid(x))throw new Error("bad point: x or y not FE");if(!a(h,x))throw new Error("bad point: equation left != right");if(!E.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class m{constructor(h,x,I){if(h==null||!e.isValid(h))throw new Error("x required");if(x==null||!e.isValid(x)||e.is0(x))throw new Error("y required");if(I==null||!e.isValid(I))throw new Error("z required");this.px=h,this.py=x,this.pz=I,Object.freeze(this)}static fromAffine(h){let{x,y:I}=h||{};if(!h||!e.isValid(x)||!e.isValid(I))throw new Error("invalid affine point");if(h instanceof m)throw new Error("projective point not allowed");let T=L=>e.eql(L,e.ZERO);return T(x)&&T(I)?m.ZERO:new m(x,I,e.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(h){let x=or(e,h.map(I=>I.pz));return h.map((I,T)=>I.toAffine(x[T])).map(m.fromAffine)}static fromHex(h){let x=m.fromAffine(i(rt("pointHex",h)));return x.assertValidity(),x}static fromPrivateKey(h){return m.BASE.multiply(f(h))}static msm(h,x){return bn(m,n,h,x)}_setWindowSize(h){V.setWindowSize(this,h)}assertValidity(){g(this)}hasEvenY(){let{y:h}=this.toAffine();if(e.isOdd)return!e.isOdd(h);throw new Error("Field doesn't support isOdd")}equals(h){p(h);let{px:x,py:I,pz:T}=this,{px:L,py:N,pz:K}=h,D=e.eql(e.mul(x,K),e.mul(L,T)),U=e.eql(e.mul(I,K),e.mul(N,T));return D&&U}negate(){return new m(this.px,e.neg(this.py),this.pz)}double(){let{a:h,b:x}=t,I=e.mul(x,Ji),{px:T,py:L,pz:N}=this,K=e.ZERO,D=e.ZERO,U=e.ZERO,B=e.mul(T,T),lt=e.mul(L,L),v=e.mul(N,N),S=e.mul(T,L);return S=e.add(S,S),U=e.mul(T,N),U=e.add(U,U),K=e.mul(h,U),D=e.mul(I,v),D=e.add(K,D),K=e.sub(lt,D),D=e.add(lt,D),D=e.mul(K,D),K=e.mul(S,K),U=e.mul(I,U),v=e.mul(h,v),S=e.sub(B,v),S=e.mul(h,S),S=e.add(S,U),U=e.add(B,B),B=e.add(U,B),B=e.add(B,v),B=e.mul(B,S),D=e.add(D,B),v=e.mul(L,N),v=e.add(v,v),B=e.mul(v,S),K=e.sub(K,B),U=e.mul(v,lt),U=e.add(U,U),U=e.add(U,U),new m(K,D,U)}add(h){p(h);let{px:x,py:I,pz:T}=this,{px:L,py:N,pz:K}=h,D=e.ZERO,U=e.ZERO,B=e.ZERO,lt=t.a,v=e.mul(t.b,Ji),S=e.mul(x,L),C=e.mul(I,N),w=e.mul(T,K),d=e.add(x,I),y=e.add(L,N);d=e.mul(d,y),y=e.add(S,C),d=e.sub(d,y),y=e.add(x,T);let A=e.add(L,K);return y=e.mul(y,A),A=e.add(S,w),y=e.sub(y,A),A=e.add(I,T),D=e.add(N,K),A=e.mul(A,D),D=e.add(C,w),A=e.sub(A,D),B=e.mul(lt,y),D=e.mul(v,w),B=e.add(D,B),D=e.sub(C,B),B=e.add(C,B),U=e.mul(D,B),C=e.add(S,S),C=e.add(C,S),w=e.mul(lt,w),y=e.mul(v,y),C=e.add(C,w),w=e.sub(S,w),w=e.mul(lt,w),y=e.add(y,w),S=e.mul(C,y),U=e.add(U,S),S=e.mul(A,y),D=e.mul(d,D),D=e.sub(D,S),S=e.mul(d,C),B=e.mul(A,B),B=e.add(B,S),new m(D,U,B)}subtract(h){return this.add(h.negate())}is0(){return this.equals(m.ZERO)}wNAF(h){return V.wNAFCached(this,h,m.normalizeZ)}multiplyUnsafe(h){let{endo:x,n:I}=t;Ot("scalar",h,pe,I);let T=m.ZERO;if(h===pe)return T;if(this.is0()||h===yt)return this;if(!x||V.hasPrecomputes(this))return V.wNAFCachedUnsafe(this,h,m.normalizeZ);let{k1neg:L,k1:N,k2neg:K,k2:D}=x.splitScalar(h),U=T,B=T,lt=this;for(;N>pe||D>pe;)N&yt&&(U=U.add(lt)),D&yt&&(B=B.add(lt)),lt=lt.double(),N>>=yt,D>>=yt;return L&&(U=U.negate()),K&&(B=B.negate()),B=new m(e.mul(B.px,x.beta),B.py,B.pz),U.add(B)}multiply(h){let{endo:x,n:I}=t;Ot("scalar",h,yt,I);let T,L;if(x){let{k1neg:N,k1:K,k2neg:D,k2:U}=x.splitScalar(h),{p:B,f:lt}=this.wNAF(K),{p:v,f:S}=this.wNAF(U);B=V.constTimeNegate(N,B),v=V.constTimeNegate(D,v),v=new m(e.mul(v.px,x.beta),v.py,v.pz),T=B.add(v),L=lt.add(S)}else{let{p:N,f:K}=this.wNAF(h);T=N,L=K}return m.normalizeZ([T,L])[0]}multiplyAndAddUnsafe(h,x,I){let T=m.BASE,L=(K,D)=>D===pe||D===yt||!K.equals(T)?K.multiplyUnsafe(D):K.multiply(D),N=L(this,x).add(L(h,I));return N.is0()?void 0:N}toAffine(h){return b(this,h)}isTorsionFree(){let{h,isTorsionFree:x}=t;if(h===yt)return!0;if(x)return x(m,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h,clearCofactor:x}=t;return h===yt?this:x?x(m,this):this.multiplyUnsafe(t.h)}toRawBytes(h=!0){return Jt("isCompressed",h),this.assertValidity(),o(m,this,h)}toHex(h=!0){return Jt("isCompressed",h),Ee(this.toRawBytes(h))}}m.BASE=new m(t.Gx,t.Gy,e.ONE),m.ZERO=new m(e.ZERO,e.ONE,e.ZERO);let{endo:_,nBitLength:R}=t,V=gn(m,_?Math.ceil(R/2):R);return{CURVE:t,ProjectivePoint:m,normPrivateKeyToScalar:f,weierstrassEquation:s,isWithinCurveOrder:u}}function dh(r){let t=Nr(r);return le(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function Rc(r){let t=dh(r),{Fp:e,n,nByteLength:o,nBitLength:i}=t,s=e.BYTES+1,a=2*e.BYTES+1;function c(v){return J(v,n)}function l(v){return yn(v,n)}let{ProjectivePoint:u,normPrivateKeyToScalar:f,weierstrassEquation:p,isWithinCurveOrder:b}=hh({...t,toBytes(v,S,C){let w=S.toAffine(),d=e.toBytes(w.x),y=Se;return Jt("isCompressed",C),C?y(Uint8Array.from([S.hasEvenY()?2:3]),d):y(Uint8Array.from([4]),d,e.toBytes(w.y))},fromBytes(v){let S=v.length,C=v[0],w=v.subarray(1);if(S===s&&(C===2||C===3)){let d=ue(w);if(!mn(d,yt,e.ORDER))throw new Error("Point is not on curve");let y=p(d),A;try{A=e.sqrt(y)}catch(z){let G=z instanceof Error?": "+z.message:"";throw new Error("Point is not on curve"+G)}let P=(A&yt)===yt;return(C&1)===1!==P&&(A=e.neg(A)),{x:d,y:A}}else if(S===a&&C===4){let d=e.fromBytes(w.subarray(0,e.BYTES)),y=e.fromBytes(w.subarray(e.BYTES,2*e.BYTES));return{x:d,y}}else{let d=s,y=a;throw new Error("invalid Point, expected length of "+d+", or uncompressed "+y+", got "+S)}}});function g(v){let S=n>>yt;return v>S}function m(v){return g(v)?c(-v):v}let _=(v,S,C)=>ue(v.slice(S,C));class R{constructor(S,C,w){Ot("r",S,yt,n),Ot("s",C,yt,n),this.r=S,this.s=C,w!=null&&(this.recovery=w),Object.freeze(this)}static fromCompact(S){let C=o;return S=rt("compactSignature",S,C*2),new R(_(S,0,C),_(S,C,2*C))}static fromDER(S){let{r:C,s:w}=de.toSig(rt("DER",S));return new R(C,w)}assertValidity(){}addRecoveryBit(S){return new R(this.r,this.s,S)}recoverPublicKey(S){let{r:C,s:w,recovery:d}=this,y=T(rt("msgHash",S));if(d==null||![0,1,2,3].includes(d))throw new Error("recovery id invalid");let A=d===2||d===3?C+t.n:C;if(A>=e.ORDER)throw new Error("recovery id 2 or 3 invalid");let P=(d&1)===0?"02":"03",O=u.fromHex(P+Qi(A,e.BYTES)),z=l(A),G=c(-y*z),W=c(w*z),Y=u.BASE.multiplyAndAddUnsafe(O,G,W);if(!Y)throw new Error("point at infinify");return Y.assertValidity(),Y}hasHighS(){return g(this.s)}normalizeS(){return this.hasHighS()?new R(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return Br(this.toDERHex())}toDERHex(){return de.hexFromSig(this)}toCompactRawBytes(){return Br(this.toCompactHex())}toCompactHex(){let S=o;return Qi(this.r,S)+Qi(this.s,S)}}let V={isValidPrivateKey(v){try{return f(v),!0}catch{return!1}},normPrivateKeyToScalar:f,randomPrivateKey:()=>{let v=pi(t.n);return Qa(t.randomBytes(v),t.n)},precompute(v=8,S=u.BASE){return S._setWindowSize(v),S.multiply(BigInt(3)),S}};function E(v,S=!0){return u.fromPrivateKey(v).toRawBytes(S)}function h(v){if(typeof v=="bigint")return!1;if(v instanceof u)return!0;let C=rt("key",v).length,w=e.BYTES,d=w+1,y=2*w+1;if(!(t.allowedPrivateKeyLengths||o===d))return C===d||C===y}function x(v,S,C=!0){if(h(v)===!0)throw new Error("first arg must be private key");if(h(S)===!1)throw new Error("second arg must be public key");return u.fromHex(S).multiply(f(v)).toRawBytes(C)}let I=t.bits2int||function(v){if(v.length>8192)throw new Error("input is too large");let S=ue(v),C=v.length*8-i;return C>0?S>>BigInt(C):S},T=t.bits2int_modN||function(v){return c(I(v))},L=Ue(i);function N(v){return Ot("num < 2^"+i,v,pe,L),Ne(v,o)}function K(v,S,C=D){if(["recovered","canonical"].some(at=>at in C))throw new Error("sign() legacy options not supported");let{hash:w,randomBytes:d}=t,{lowS:y,prehash:A,extraEntropy:P}=C;y==null&&(y=!0),v=rt("msgHash",v),Lc(C),A&&(v=rt("prehashed msgHash",w(v)));let O=T(v),z=f(S),G=[N(z),N(O)];if(P!=null&&P!==!1){let at=P===!0?d(e.BYTES):P;G.push(rt("extraEntropy",at))}let W=Se(...G),Y=O;function ft(at){let gt=I(at);if(!b(gt))return;let Tt=l(gt),pt=u.BASE.multiply(gt).toAffine(),xt=c(pt.x);if(xt===pe)return;let Nt=c(Tt*c(Y+xt*z));if(Nt===pe)return;let zt=(pt.x===xt?0:2)|Number(pt.y&yt),xr=Nt;return y&&g(Nt)&&(xr=m(Nt),zt^=1),new R(xt,xr,zt)}return{seed:W,k2sig:ft}}let D={lowS:t.lowS,prehash:!1},U={lowS:t.lowS,prehash:!1};function B(v,S,C=D){let{seed:w,k2sig:d}=K(v,S,C),y=t;return Va(y.hash.outputLen,y.nByteLength,y.hmac)(w,d)}u.BASE._setWindowSize(8);function lt(v,S,C,w=U){let d=v;S=rt("msgHash",S),C=rt("publicKey",C);let{lowS:y,prehash:A,format:P}=w;if(Lc(w),"strict"in w)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 d=="string"||er(d),z=!O&&!P&&typeof d=="object"&&d!==null&&typeof d.r=="bigint"&&typeof d.s=="bigint";if(!O&&!z)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let G,W;try{if(z&&(G=new R(d.r,d.s)),O){try{P!=="compact"&&(G=R.fromDER(d))}catch(zt){if(!(zt instanceof de.Err))throw zt}!G&&P!=="der"&&(G=R.fromCompact(d))}W=u.fromHex(C)}catch{return!1}if(!G||y&&G.hasHighS())return!1;A&&(S=t.hash(S));let{r:Y,s:ft}=G,at=T(S),gt=l(ft),Tt=c(at*gt),pt=c(Y*gt),xt=u.BASE.multiplyAndAddUnsafe(W,Tt,pt)?.toAffine();return xt?c(xt.x)===Y:!1}return{CURVE:t,getPublicKey:E,getSharedSecret:x,sign:B,verify:lt,ProjectivePoint:u,Signature:R,utils:V}}function ph(r){return{hash:r,hmac:(t,...e)=>Xi(r,t,ri(...e)),randomBytes:fn}}function Cc(r,t){let e=n=>Rc({...r,...ph(n)});return{...e(t),create:e}}var Bc=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Dc=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),mh=BigInt(0),yh=BigInt(1),es=BigInt(2),Pc=(r,t)=>(r+t/es)/t;function gh(r){let t=Bc,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,p=nt(f,e,t)*u%t,b=nt(p,es,t)*l%t,g=nt(b,o,t)*b%t,m=nt(g,i,t)*g%t,_=nt(m,a,t)*m%t,R=nt(_,c,t)*_%t,V=nt(R,a,t)*m%t,E=nt(V,e,t)*u%t,h=nt(E,s,t)*g%t,x=nt(h,n,t)*l%t,I=nt(x,es,t);if(!rs.eql(rs.sqr(I),r))throw new Error("Cannot find square root");return I}var rs=fe(Bc,void 0,void 0,{sqrt:gh}),ar=Cc({a:mh,b:BigInt(7),Fp:rs,n:Dc,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let t=Dc,e=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-yh*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=e,s=BigInt("0x100000000000000000000000000000000"),a=Pc(i*r,t),c=Pc(-n*r,t),l=J(r-a*e-c*o,t),u=J(-a*n-c*i,t),f=l>s,p=u>s;if(f&&(l=t-l),p&&(u=t-u),l>s||u>s)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:f,k1:l,k2neg:p,k2:u}}}},pn);function Nc(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function Uc(r,t,e){let n=Xe.digest(e instanceof Uint8Array?e:e.subarray());if(Nc(n))return n.then(({digest:o})=>ar.verify(t,o,r)).catch(o=>{throw new Mr(String(o))});try{return ar.verify(t,n.digest,r)}catch(o){throw new Mr(String(o))}}var Ln=class{type="secp256k1";raw;_key;constructor(t){this._key=kc(t),this.raw=Oc(this._key)}toMultihash(){return Gt.digest(Xt(this))}toCID(){return st.createV1(114,this.toMultihash())}toString(){return j.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 Uc(this._key,e,t)}};function ns(r){return new Ln(r)}function Oc(r){return ar.ProjectivePoint.fromHex(r).toRawBytes(!0)}function kc(r){try{return ar.ProjectivePoint.fromHex(r),r}catch(t){throw new Ge(String(t))}}function Mc(r,t){let{Type:e,Data:n}=ee.decode(r),o=n??new Uint8Array;switch(e){case ut.RSA:return Zi(o,t);case ut.Ed25519:return Si(o);case ut.secp256k1:return ns(o);case ut.ECDSA:return ei(o);default:throw new We}}function Kc(r){let{Type:t,Data:e}=ee.decode(r.digest),n=e??new Uint8Array;switch(t){case ut.Ed25519:return Si(n);case ut.secp256k1:return ns(n);case ut.ECDSA:return ei(n);default:throw new We}}function Xt(r){return ee.encode({Type:ut[r.type],Data:r.raw})}var qc=Symbol.for("nodejs.util.inspect.custom"),bh=114,Fr=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()})`}[Io]=!0;toString(){return this.string==null&&(this.string=j.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return st.createV1(bh,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")}[qc](){return`PeerId(${this.toString()})`}},Rn=class extends Fr{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},Cn=class extends Fr{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},Dn=class extends Fr{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},xh=2336,Hr=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=Gt.digest(q(this.url))}[qc](){return`PeerId(${this.url})`}[Io]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return st.createV1(xh,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=k(t)),t.toString()===this.toString())}};var wh=114,Fc=2336;function os(r,t){let e;if(r.charAt(0)==="1"||r.charAt(0)==="Q")e=qt(j.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return Eh(st.parse(r));if(t==null)throw new ht('Please pass a multibase decoder for strings that do not start with "1" or "Q"');e=qt(t.decode(r))}return cr(e)}function cr(r){if(vh(r))return new Rn({multihash:r});if(Sh(r))try{let t=Kc(r);if(t.type==="Ed25519")return new Cn({multihash:r,publicKey:t});if(t.type==="secp256k1")return new Dn({multihash:r,publicKey:t})}catch{let e=k(r.digest);return new Hr(new URL(e))}throw new rn("Supplied PeerID Multihash is invalid")}function Eh(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==wh&&r.code!==Fc)throw new en("Supplied PeerID CID is invalid");if(r.code===Fc){let t=k(r.multihash.digest);return new Hr(new URL(t))}return cr(r.multihash)}function Sh(r){return r.code===Gt.code}function vh(r){return r.code===Xe.code}var zr;(function(r){let t;r.codec=()=>(t==null&&(t=Bt((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=>Pt(e,r.codec()),r.decode=(e,n)=>Dt(e,r.codec(),n)})(zr||(zr={}));var Pn=class extends Error{constructor(t="Invalid signature"){super(t),this.name="InvalidSignatureError"}};var Vr=class r{static createFromProtobuf=async t=>{let e=zr.decode(t),n=Mc(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=Hc(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 Pn("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=zr.encode({publicKey:Xt(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(t){return t==null?!1:dt(this.marshal(),t.marshal())}async validate(t){let e=Hc(t,this.payloadType,this.payload);return this.publicKey.verify(e.subarray(),this.signature)}},Hc=(r,t,e)=>{let n=q(r),o=Ft(n.byteLength),i=Ft(t.length),s=Ft(e.length);return new ct(o,n,i,t,s,e)};var Bn=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 p=Number.parseInt(f,t);if(!Number.isNaN(p))return p});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 zc=45,Ah=15,ur=new Bn;function is(r){if(!(r.length>Ah))return ur.new(r).parseWith(()=>ur.readIPv4Addr())}function ss(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>zc))return ur.new(r).parseWith(()=>ur.readIPv6Addr())}function Nn(r,t=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>zc)return;let e=ur.new(r).parseWith(()=>ur.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 nb=parseInt("0xFFFF",16),ob=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Un(r){return!!is(r)}function On(r){return!!ss(r)}function kn(r){return!!Nn(r)}var Wc=Un,Rh=On,as=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(Rh(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let i=Wc(e[n]),s;i&&(s=as(e[n]),e[n]=k(s.slice(0,2),"base16")),s!=null&&++n<8&&e.splice(n,0,k(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 lr={},cs={},Dh=[[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"]];Dh.forEach(r=>{let t=Ph(...r);cs[t.code]=t,lr[t.name]=t});function Ph(r,t,e,n,o){return{code:r,size:t,name:e,resolvable:!!n,path:!!o}}function tt(r){if(typeof r=="number"){if(cs[r]!=null)return cs[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(lr[r]!=null)return lr[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var Fb=tt("ip4"),Hb=tt("ip6"),zb=tt("ipcidr");function hs(r,t){switch(tt(r).code){case 4:case 41:return Nh(t);case 42:return fs(t);case 43:return k(t,"base10");case 6:case 273:case 33:case 132:return jc(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return fs(t);case 421:return Mh(t);case 444:return Yc(t);case 445:return Yc(t);case 466:return kh(t);case 481:return globalThis.encodeURIComponent(fs(t));default:return k(t,"base16")}}function ds(r,t){switch(tt(r).code){case 4:return Zc(t);case 41:return Zc(t);case 42:return ls(t);case 43:return q(t,"base10");case 6:case 273:case 33:case 132:return ps(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return ls(t);case 421:return Uh(t);case 444:return Kh(t);case 445:return qh(t);case 466:return Oh(t);case 481:return ls(globalThis.decodeURIComponent(t));default:return q(t,"base16")}}var us=Object.values(_r).map(r=>r.decoder),Bh=function(){let r=us[0].or(us[1]);return us.slice(2).forEach(t=>r=r.or(t)),r}();function Zc(r){if(!kn(r))throw new Error("invalid ip address");return as(r)}function Nh(r){let t=$c(r,0,r.length);if(t==null)throw new Error("ipBuff is required");if(!kn(t))throw new Error("invalid ip address");return t}function ps(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,r),new Uint8Array(t)}function jc(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function ls(r){let t=q(r),e=Uint8Array.from(Ft(t.length));return Ut([e,t],e.length+t.length)}function fs(r){let t=he(r);if(r=r.slice(Et(t)),r.length!==t)throw new Error("inconsistent lengths");return k(r)}function Uh(r){let t;r[0]==="Q"||r[0]==="1"?t=qt(j.decode(`z${r}`)).bytes:t=st.parse(r).multihash.bytes;let e=Uint8Array.from(Ft(t.length));return Ut([e,t],e.length+t.length)}function Oh(r){let t=Bh.decode(r),e=Uint8Array.from(Ft(t.length));return Ut([e,t],e.length+t.length)}function kh(r){let t=he(r),e=r.slice(Et(t));if(e.length!==t)throw new Error("inconsistent lengths");return"u"+k(e,"base64url")}function Mh(r){let t=he(r),e=r.slice(Et(t));if(e.length!==t)throw new Error("inconsistent lengths");return k(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=oe.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=ps(n);return Ut([e,o],e.length+o.length)}function qh(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=oe.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=ps(n);return Ut([e,o],e.length+o.length)}function Yc(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=k(t,"base32"),o=jc(e);return`${n}:${o}`}function Xc(r){r=ms(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=tt(s);if(a.size===0){t.push([a.code]),e.push([a.code]);continue}if(i++,i>=o.length)throw new Mn("invalid address: "+r);if(a.path===!0){n=ms(o.slice(i).join("/")),t.push([a.code,ds(a.code,n)]),e.push([a.code,n]);break}let c=ds(a.code,o[i]);t.push([a.code,c]),e.push([a.code,hs(a.code,c)])}return{string:Qc(e),bytes:Kn(t),tuples:t,stringTuples:e,path:n}}function ys(r){let t=[],e=[],n=null,o=0;for(;o<r.length;){let i=he(r,o),s=Et(i),a=tt(i),c=Fh(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 Mn("Invalid address Uint8Array: "+k(r,"base16"));t.push([i,l]);let u=hs(i,l);if(e.push([i,u]),a.path===!0){n=u;break}}return{bytes:Uint8Array.from(r),string:Qc(e),tuples:t,stringTuples:e,path:n}}function Qc(r){let t=[];return r.map(e=>{let n=tt(e[0]);return t.push(n.name),e.length>1&&e[1]!=null&&t.push(e[1]),null}),ms(t.join("/"))}function Kn(r){return Ut(r.map(t=>{let e=tt(t[0]),n=Uint8Array.from(Ft(e.code));return t.length>1&&t[1]!=null&&(n=Ut([n,t[1]])),n}))}function Fh(r,t){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let e=he(t instanceof Uint8Array?t:Uint8Array.from(t));return e+Et(e)}}function ms(r){return"/"+r.trim().split("/").filter(t=>t).join("/")}var Mn=class extends Error{static name="ParseError";name="ParseError";constructor(t){super(`Error parsing address: ${t}`)}};var Hh=Symbol.for("nodejs.util.inspect.custom"),bs=Symbol.for("@multiformats/js-multiaddr/multiaddr"),zh=[tt("dns").code,tt("dns4").code,tt("dns6").code,tt("dnsaddr").code],gs=class extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}},qn=class r{bytes;#t;#e;#r;#n;[bs]=!0;constructor(t){t==null&&(t="");let e;if(t instanceof Uint8Array)e=ys(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=Xc(t)}else if(tu(t))e=ys(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=tt("tcp"),a=tt("udp"),c=tt("ip4"),l=tt("ip6"),u=tt("dns6"),f=tt("ip6zone");for(let[b,g]of this.stringTuples())b===f.code&&(i=`%${g??""}`),zh.includes(b)&&(e=s.name==="tcp"?"tcp":"udp",o=443,n=`${g??""}${i}`,t=b===u.code?6:4),(b===s.code||b===a.code)&&(e=tt(b).name==="tcp"?"tcp":"udp",o=parseInt(g??"")),(b===c.code||b===l.code)&&(e=tt(b).name==="tcp"?"tcp":"udp",n=`${g??""}${i}`,t=b===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({},tt(t)))}protoCodes(){return this.#e.map(([t])=>t)}protoNames(){return this.#e.map(([t])=>tt(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(Kn(e.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,o])=>{n===lr.p2p.code&&t.push([n,o]),n===lr["p2p-circuit"].code&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?k(j.decode(`z${n}`),"base58btc"):k(st.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=Jc.get(e.name);if(n==null)throw new gs(`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)}[Hh](){return`Multiaddr(${this.#t})`}};var Jc=new Map;function tu(r){return!!r?.[bs]}function vt(r){return new qn(r)}function Zt(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var Fn=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 qe(r,t,e){if(t==null)return r;if(t.aborted)return r.catch(()=>{}),Promise.reject(new Fn(e?.errorMessage,e?.errorCode,e?.errorName));let n,o=new Fn(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 xs=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=Zt(),this.haveNext=Zt()}[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=Zt(),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=Zt(),await qe(this.readNext.promise,e?.signal,e)}};function Hn(){return new xs}var zn=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function eu(r,t){let e=Hn();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=>{if(s?.signal?.throwIfAborted(),s?.bytes==null){let{done:c,value:l}=await qe(n.next(),s?.signal);return c===!0?null:l}for(;o.byteLength<s.bytes;){let{value:c,done:l}=await qe(n.next(),s?.signal);if(l===!0)throw new zn("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 Vn=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Gn=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Wn=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function ru(r,t={}){let e=eu(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=Et(t.maxDataLength));let n=t?.lengthDecoder??he,o=t?.lengthEncoder??Ft;return{read:async s=>{let a=-1,c=new ct;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 Vn("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new Wn("message length length too long");if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new Gn("message length too long");return e.read({...s,bytes:a})},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 _e(r,t){let e=ru(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 ws=1e3,nu=60*ws,$n=290,ou=15,iu=2*60*nu,su=1,Zn=2e3,au=100,Es="circuit-relay-source",Gr=`${To}-circuit-relay`,Ss=`${To}-circuit-relay-source`,cu=2*nu,uu=BigInt(1<<17),Ht="/libp2p/circuit/relay/0.2.0/hop",Fe="/libp2p/circuit/relay/0.2.0/stop",lu=30*ws,Ox=30*ws,Wr=300,fu=4096,hu=.001;var X;(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=()=>Ke(e)}(t=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Bt((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),fr.codec().encode(o.peer,i)),o.reservation!=null&&(i.uint32(26),Yn.codec().encode(o.reservation,i)),o.limit!=null&&(i.uint32(34),hr.codec().encode(o.limit,i)),o.status!=null&&(i.uint32(40),H.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=fr.codec().decode(o,o.uint32(),{limits:s.limits?.peer});break}case 3:{a.reservation=Yn.codec().decode(o,o.uint32(),{limits:s.limits?.reservation});break}case 4:{a.limit=hr.codec().decode(o,o.uint32(),{limits:s.limits?.limit});break}case 5:{a.status=H.codec().decode(o);break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>Pt(o,r.codec()),r.decode=(o,i)=>Dt(o,r.codec(),i)})(X||(X={}));var Mt;(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=()=>Ke(e)}(t=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Bt((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),fr.codec().encode(o.peer,i)),o.limit!=null&&(i.uint32(26),hr.codec().encode(o.limit,i)),o.status!=null&&(i.uint32(32),H.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=fr.codec().decode(o,o.uint32(),{limits:s.limits?.peer});break}case 3:{a.limit=hr.codec().decode(o,o.uint32(),{limits:s.limits?.limit});break}case 4:{a.status=H.codec().decode(o);break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>Pt(o,r.codec()),r.decode=(o,i)=>Dt(o,r.codec(),i)})(Mt||(Mt={}));var fr;(function(r){let t;r.codec=()=>(t==null&&(t=Bt((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 kr('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=>Pt(e,r.codec()),r.decode=(e,n)=>Dt(e,r.codec(),n)})(fr||(fr={}));var Yn;(function(r){let t;r.codec=()=>(t==null&&(t=Bt((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),jn.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 kr('Decode error - map field "addrs" had too many elements');i.addrs.push(e.bytes());break}case 3:{i.voucher=jn.codec().decode(e,e.uint32(),{limits:o.limits?.voucher});break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Pt(e,r.codec()),r.decode=(e,n)=>Dt(e,r.codec(),n)})(Yn||(Yn={}));var hr;(function(r){let t;r.codec=()=>(t==null&&(t=Bt((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=>Pt(e,r.codec()),r.decode=(e,n)=>Dt(e,r.codec(),n)})(hr||(hr={}));var H;(function(r){r.UNUSED="UNUSED",r.OK="OK",r.RESERVATION_REFUSED="RESERVATION_REFUSED",r.RESOURCE_LIMIT_EXCEEDED="RESOURCE_LIMIT_EXCEEDED",r.PERMISSION_DENIED="PERMISSION_DENIED",r.CONNECTION_FAILED="CONNECTION_FAILED",r.NO_RESERVATION="NO_RESERVATION",r.MALFORMED_MESSAGE="MALFORMED_MESSAGE",r.UNEXPECTED_MESSAGE="UNEXPECTED_MESSAGE"})(H||(H={}));var vs;(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"})(vs||(vs={}));(function(r){r.codec=()=>Ke(vs)})(H||(H={}));var dr;(function(r){let t;r.codec=()=>(t==null&&(t=Bt((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=>Pt(e,r.codec()),r.decode=(e,n)=>Dt(e,r.codec(),n)})(dr||(dr={}));var jn;(function(r){let t;r.codec=()=>(t==null&&(t=Bt((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),dr.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=dr.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=>Pt(e,r.codec()),r.decode=(e,n)=>Dt(e,r.codec(),n)})(jn||(jn={}));var Vh=r=>r.toString().split("/").slice(1),pr=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),M=r=>({match:t=>pr(e=>e===r).match(t),pattern:r}),He=()=>({match:r=>pr(t=>typeof t=="string").match(r),pattern:"{string}"}),mr=()=>({match:r=>pr(t=>!isNaN(parseInt(t))).match(r),pattern:"{number}"}),Q=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{j.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),$r=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{Ho.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),$=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 et(...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 Gh=Q(),Wx=et(Gh),Qn=F(M("dns4"),He()),Jn=F(M("dns6"),He()),to=F(M("dnsaddr"),He()),_s=F(M("dns"),He()),$x=et(Qn,$(Q())),Zx=et(Jn,$(Q())),Yx=et(to,$(Q())),jx=et(At(_s,to,Qn,Jn),$(Q())),du=F(M("ip4"),pr(Un)),pu=F(M("ip6"),pr(On)),Is=At(du,pu),me=At(Is,_s,Qn,Jn,to),Xx=et(At(Is,F(At(_s,to,Qn,Jn),$(Q())))),Qx=et(du),Jx=et(pu),tw=et(Is),Ts=F(me,M("tcp"),mr()),Zr=F(me,M("udp"),mr()),ew=et(F(Ts,$(Q()))),rw=et(Zr),Ls=F(Zr,M("quic"),$(Q())),eo=F(Zr,M("quic-v1"),$(Q())),Wh=At(Ls,eo),nw=et(Ls),ow=et(eo),As=At(me,Ts,Zr,Ls,eo),mu=At(F(As,M("ws"),$(Q()))),iw=et(mu),yu=At(F(As,M("wss"),$(Q())),F(As,M("tls"),$(F(M("sni"),He())),M("ws"),$(Q()))),sw=et(yu),gu=F(Zr,M("webrtc-direct"),$($r()),$($r()),$(Q())),aw=et(gu),bu=F(eo,M("webtransport"),$($r()),$($r()),$(Q())),cw=et(bu),Xn=At(mu,yu,F(Ts,$(Q())),F(Wh,$(Q())),F(me,$(Q())),gu,bu,Q()),xu=et(Xn),$h=F(Xn,M("p2p-circuit"),Q()),ro=et($h),Zh=At(F(Xn,M("p2p-circuit"),M("webrtc"),$(Q())),F(Xn,M("webrtc"),$(Q())),F(M("webrtc"),$(Q()))),uw=et(Zh),Yh=At(F(me,M("tcp"),mr(),M("http"),$(Q())),F(me,M("http"),$(Q()))),lw=et(Yh),jh=At(F(me,M("tcp"),At(F(M("443"),M("http")),F(mr(),M("https")),F(mr(),M("tls"),M("http"))),$(Q())),F(me,M("tls"),M("http"),$(Q())),F(me,M("https"),$(Q()))),fw=et(jh),Xh=At(F(M("memory"),He(),$(Q()))),hw=et(Xh);function no(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 oo=class extends Error{constructor(t="Transfer limit error"){super(t),this.name="TransferLimitError"}},Yr=class extends Error{constructor(t="Duration limit error"){super(t),this.name="DurationLimitError"}},jr=class extends Error{static name="HadEnoughRelaysError";name="HadEnoughRelaysError"},io=class extends Error{static name="DoubleRelayError";name="DoubleRelayError"},so=class extends Error{static name="RelayQueueFullError";name="RelayQueueFullError"};async function*wu(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 oo(`data limit of ${n} bytes exceeded`)}t.remaining-=i,yield o}}function Eu(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=no(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 Yr(`duration limit of ${n.limit?.duration} ms exceeded`))};a.addEventListener("abort",f,{once:!0}),t.sink(u==null?r.source:wu(r.source,u,o)).catch(p=>{o.log.error("error while relaying streams src -> dst",p),i(p)}).finally(()=>{c=!0,l&&(a.removeEventListener("abort",f),a.clear())})}),queueMicrotask(()=>{let f=()=>{o.log("relayed connection reached time limit"),r.abort(new Yr(`duration limit of ${n.limit?.duration} ms exceeded`))};a.addEventListener("abort",f,{once:!0}),r.sink(u==null?t.source:wu(t.source,u,o)).catch(p=>{o.log.error("error while relaying streams dst -> src",p),i(p)}).finally(()=>{l=!0,c&&(a.removeEventListener("abort",f),a.clear())})})}function Rs(r){let t=r*BigInt(1e3),e=new Date().getTime();return Number(t-BigInt(e))}var Xr=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}},ao=et(F(xu.matchers[0],M("p2p-circuit"))),co=et(M("p2p-circuit"));function uo(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 Ie=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 uo(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 uo(this.map.values(),t=>t.key)}values(){return uo(this.map.values(),t=>t.value)}get size(){return this.map.size}};var Cs={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Su={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},vu=new globalThis.TextEncoder;function Qh(r,t){let e=Cs[t],n=Su[t];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(t,n*e);return n}function Jh(r,t,e){if(e.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Cs[t],o=Su[t],i=r;for(;i.length>0;){let s=vu.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 Ds(r,{size:t=32,utf8Buffer:e}={}){if(!Cs[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 Jh(r,t,e);r=vu.encode(r)}return Qh(r,t)}var Qr={hash:r=>Number(Ds(r,{size:32})),hashV:(r,t)=>td(Qr.hash(r,t))};function td(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),q(t,"base16")}var Ps=64,Yt=class{fp;h;seed;constructor(t,e,n,o=2){if(o>Ps)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 ze(r,t){return Math.floor(Math.random()*(t-r))+r}var Ve=class{contents;constructor(t){this.contents=new Array(t).fill(null)}has(t){if(!(t instanceof Yt))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof Yt))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 Yt))throw new TypeError("Invalid Fingerprint");let e=ze(0,this.contents.length-1),n=this.contents[e];return this.contents[e]=t,n}remove(t){if(!(t instanceof Yt))throw new TypeError("Invalid Fingerprint");let e=this.contents.findIndex(n=>t.equals(n));return e>-1?(this.contents[e]=null,!0):!1}};var ed=500,Jr=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??Qr,this.seed=t.seed??ze(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=q(t));let e=new Yt(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 Ve(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new Ve(this.bucketSize)),this.buckets[n].add(e)||this.buckets[o].add(e))return this.count++,!0;let i=[n,o],s=i[ze(0,i.length-1)];this.buckets[s]==null&&(this.buckets[s]=new Ve(this.bucketSize));for(let a=0;a<ed;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 Ve(this.bucketSize)),this.buckets[s].add(c)))return this.count++,!0}return!1}has(t){typeof t=="string"&&(t=q(t));let e=new Yt(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=q(t));let e=new Yt(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}},rd={1:.5,2:.84,4:.95,8:.98};function nd(r=.001){return r>.002?2:r>1e-5?4:8}function Au(r,t=.001){let e=nd(t),n=rd[e],o=Math.round(r/n),i=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),Ps);return{filterSize:o,bucketSize:e,fingerprintSize:i}}var lo=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??Qr,this.seed=t.seed??ze(0,Math.pow(2,10)),this.filterSeries=[new Jr({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(t){if(typeof t=="string"&&(t=q(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 Jr({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=q(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=q(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 yr(r,t=.001,e){return new lo({...Au(r,t),...e??{}})}var fo=class{filter;constructor(t,e){this.filter=yr(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 Bs(r,t=.001){return new fo(r,t)}var Ns=class extends Ie{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 Us(r){let{name:t,metrics:e}=r,n;return e!=null?n=new Ns({name:t,metrics:e}):n=new Ie,n}var Os=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 _u(r,t){let e=new Os(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 ho=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??ou,this.applyDefaultLimit=e.applyDefaultLimit!==!1,this.reservationTtl=e.reservationTtl??iu,this.defaultDurationLimit=e.defaultDurationLimit??cu,this.defaultDataLimit=e.defaultDataLimit??uu,this.reservations=Us({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:H.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:_u(this.reservationTtl)}),this.reservations.set(t,o),o.signal.addEventListener("abort",()=>{this.reservations.delete(t)}),{status:H.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 po=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 dr.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 Iu=r=>r.protoCodes().includes($n),od={maxOutboundStopStreams:Wr},ks=class extends Kt{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??lu,this.maxInboundHopStreams=e.maxInboundHopStreams,this.maxOutboundHopStreams=e.maxOutboundHopStreams,this.maxOutboundStopStreams=e.maxOutboundStopStreams??od.maxOutboundStopStreams,this.reservationStore=new ho(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(Ht,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(Ht),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=_e(e);try{let i=await o.pb(X).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(X).write({type:X.Type.STATUS,status:H.MALFORMED_MESSAGE},n),e.abort(i)}}async handleHopProtocol({stream:t,request:e,connection:n},o){switch(this.log("received hop message"),e.type){case X.Type.RESERVE:await this.handleReserve({stream:t,request:e,connection:n},o);break;case X.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(X).write({type:X.Type.STATUS,status:H.UNEXPECTED_MESSAGE})}}async handleReserve({stream:t,connection:e},n){let o=t.pb(X);if(this.log("hop reserve request from %p",e.remotePeer),Iu(e.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",e.remotePeer),await o.write({type:X.Type.STATUS,status:H.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:X.Type.STATUS,status:H.PERMISSION_DENIED},n);return}let i=this.reservationStore.reserve(e.remotePeer,e.remoteAddr);try{if(i.status!==H.OK){await o.write({type:X.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:{[Es]:{value:1,ttl:s},[Ss]:{value:1,ttl:s}}})}await o.write({type:X.Type.STATUS,status:H.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:{[Es]: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 Vr.seal(new po({peer:t,relay:this.peerId,expiration:e}),this.privateKey);return{addrs:n,expire:e,voucher:{publicKey:Xt(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(X);if(Iu(n.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",n.remotePeer),await i.write({type:X.Type.STATUS,status:H.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=cr(qt(e.peer.id))}catch(p){this.log.error("invalid hop connect request via peer %p %s",n.remotePeer,p),await i.write({type:X.Type.STATUS,status:H.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,H.NO_RESERVATION),await i.write({type:X.Type.STATUS,status:H.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:X.Type.STATUS,status:H.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:X.Type.STATUS,status:H.NO_RESERVATION},o);return}let l=c[0],u=await this.stopHop({connection:l,request:{type:Mt.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:X.Type.STATUS,status:H.CONNECTION_FAILED},o);return}await i.write({type:X.Type.STATUS,status:H.OK,limit:a?.limit},o);let f=t.unwrap();this.log("connection from %p to %p established - merging streams",n.remotePeer,s),Eu(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([Fe],{maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0,...n}),i=_e(o),s=i.pb(Mt);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===H.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 Tu(r={}){return t=>new ks(t,r)}function id(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 Lu=id;function sd(r){return r[Symbol.asyncIterator]!=null}function Ru(r){return r?.then!=null}function ad(r,t){let e=0;if(sd(r))return async function*(){for await(let c of r){let l=t(c,e++);Ru(l)&&await l,yield c}}();let n=Lu(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++);Ru(l)&&await l,yield c}}();let a=t;return function*(){yield o;for(let c of n)a(c,e++),yield c}()}var Cu=ad;var mo=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}},gr=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new mo(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 mo(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 Ms=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function yo(r={}){return cd(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 cd(r,t){t=t??{};let e=t.onEnd,n=new gr,o,i,s,a=Zt(),c=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((_,R)=>{i=V=>{i=null,n.push(V);try{_(r(n))}catch(E){R(E)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Zt()})}},l=_=>i!=null?i(_):(n.push(_),o),u=_=>(n=new gr,i!=null?i({error:_}):(n.push({error:_}),o)),f=_=>{if(s)return o;if(t?.objectMode!==!0&&_?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:_})},p=_=>s?o:(s=!0,_!=null?u(_):l({done:!0})),b=()=>(n=new gr,p(),{done:!0}),g=_=>(p(_),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:b,throw:g,push:f,end:p,get readableLength(){return n.size},onEmpty:async _=>{let R=_?.signal;if(R?.throwIfAborted(),n.isEmpty())return;let V,E;R!=null&&(V=new Promise((h,x)=>{E=()=>{x(new Ms)},R.addEventListener("abort",E)}));try{await Promise.race([a.promise,V])}finally{E!=null&&R!=null&&R?.removeEventListener("abort",E)}}},e==null)return o;let m=o;return o={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(_){return m.throw(_),e!=null&&(e(_),e=void 0),{done:!0}},return(){return m.return(),e!=null&&(e(),e=void 0),{done:!0}},push:f,end(_){return m.end(_),e!=null&&(e(_),e=void 0),o},get readableLength(){return m.readableLength},onEmpty:_=>m.onEmpty(_)},o}function ud(r){return r[Symbol.asyncIterator]!=null}async function ld(r,t,e){try{await Promise.all(r.map(async n=>{for await(let o of n)await t.push(o,{signal:e}),e.throwIfAborted()})),await t.end(void 0,{signal:e})}catch(n){await t.end(n,{signal:e}).catch(()=>{})}}async function*fd(r){let t=new AbortController,e=Hn();ld(r,e,t.signal).catch(()=>{});try{yield*e}finally{t.abort()}}function*hd(r){for(let t of r)yield*t}function dd(...r){let t=[];for(let e of r)ud(e)||t.push(e);return t.length===r.length?hd(t):fd(r)}var Du=dd;function Pu(r,...t){if(r==null)throw new Error("Empty pipeline");if(Ks(r)){let n=r;r=()=>n.source}else if(Nu(r)||Bu(r)){let n=r;r=()=>n}let e=[r,...t];if(e.length>1&&Ks(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++)Ks(e[n])&&(e[n]=md(e[n]));return pd(...e)}var pd=(...r)=>{let t;for(;r.length>0;)t=r.shift()(t);return t},Bu=r=>r?.[Symbol.asyncIterator]!=null,Nu=r=>r?.[Symbol.iterator]!=null,Ks=r=>r==null?!1:r.sink!=null&&r.source!=null,md=r=>t=>{let e=r.sink(t);if(e?.then!=null){let n=yo({objectMode:!0});e.then(()=>{n.end()},s=>{n.end(s)});let o,i=r.source;if(Bu(i))o=async function*(){yield*i,n.end()};else if(Nu(i))o=function*(){yield*i,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Du(n,o())}return r.source};function qs(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 g=>{await l(g),b(!0)};let u=t.abort.bind(t);t.abort=g=>{u(g),b(!0)};let f=t.sink.bind(t);t.sink=async g=>{try{await f(Pu(g,m=>Cu(m,_=>i?.(_))))}catch(m){m.type!=="aborted"&&s.error("%s error in sink",e,m)}finally{c=!0,b()}};let p={log:s,sink:t.sink,source:async function*(){try{for await(let g of t.source)o?.(g),yield g}finally{a=!0,b()}}(),remoteAddr:e,timeline:{open:Date.now(),close:void 0},close:t.close,abort:t.abort};function b(g){g===!0&&(a=!0,c=!0),a&&c&&p.timeline.close==null&&(p.timeline.close=Date.now())}return p}var Te=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var Fs=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 go(r,t,e,n){let o=new Fs(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(p){a(),s(p);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)})}function Hs(r,t){let e,n=function(){let o=function(){e=void 0,r()};clearTimeout(e),e=setTimeout(o,t)};return n.start=()=>{},n.stop=()=>{clearTimeout(e)},n}var bo=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};var xo=class{deferred;signal;constructor(t){this.signal=t,this.deferred=Zt(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new re)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function yd(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var wo=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=yd(),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 re),this.cleanup())}async join(t={}){let e=new xo(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 qe(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 Eo=class extends Kt{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=[],this.emitEmpty=Hs(this.emitEmpty.bind(this),1),this.emitIdle=Hs(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!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 bo;let n=new wo(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 re)}),this.clear()}async onEmpty(t){this.size!==0&&await go(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await go(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await go(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=yo({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 re("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 br=class extends Eo{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};var So=class extends Kt{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(Ht,{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(Ht)],orders:[()=>Math.random()<.5?1:-1,(n,o)=>{let i=Uu(n),s=Uu(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 br({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=no([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 Uu(r){let t=r.metadata.get("last-dial-success");return t==null?0:new Date(k(t)).getTime()}var zs=class extends Kt{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??Zn,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(co.exactMatch(t))this.log("searching for circuit relay servers"),this.reservationId=this.reservationStore.reserveRelay();else if(ao.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 Le(`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 Ou(r){return new zs(r)}var ku="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Mu=(r=21)=>{let t="",e=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)t+=ku[e[r]&63];return t};var gd=60*1e3*10,bd=60*1e3*5,xd=30*1e3,vo=class extends Kt{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 Ie,this.pendingReservations=[],this.maxReservationQueueLength=e?.maxReservationQueueLength??au,this.reservationCompletionTimeout=e?.reservationCompletionTimeout??Zn,this.started=!1,this.relayFilter=yr(100),this.reserveQueue=new br({concurrency:e?.reservationConcurrency??su,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(Gr)]});this.log("removing tag from %d old relays",t.length),await Promise.all(t.map(async e=>{await this.peerStore.merge(e.id,{tags:{[Gr]: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=Mu();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 Le("Cannot use self as relay");if(this.reserveQueue.size>this.maxReservationQueueLength)throw new so("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 Le("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 g=this.connectionManager.getConnections(t),m=!1;if(g.length===0&&this.log("already have relay reservation with %p but we are no longer connected",t),g.map(_=>_.id).includes(i.connection)&&(this.log("already have relay reservation with %p and the original connection is still open",t),m=!0),m&&Rs(i.reservation.expire)>gd)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 jr("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(ro.matches(a.remoteAddr))throw new io("not creating reservation over relayed connection");let c=await this.#t(a,{signal:s}),l=Rs(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-bd,xd),Math.pow(2,31)-1),f=setTimeout(()=>{this.log("refresh reservation to relay %p",t),this.addRelay(t,e).catch(async g=>{this.log.error("could not refresh reservation to relay %p - %e",t,g),await this.#e(t)}).catch(g=>{this.log.error("could not remove expired reservation to relay %p - %e",t,g)})},u),p;if(e==="discovered"){let g=this.pendingReservations.pop();if(g==null)throw new jr("Made reservation on relay but did not need any more discovered relays");p={timeout:f,reservation:c,type:e,connection:a.id,id:g}}else p={timeout:f,reservation:c,type:e,connection:a.id};this.reservations.set(t,p),await this.peerStore.merge(t,{tags:{[Gr]:{value:1,ttl:l}}}),this.#r();let b={relay:t,details:p};return this.safeDispatchEvent("relay:created-reservation",{detail:b}),b}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(Ht,e),i=_e(n).pb(X);this.log.trace("send RESERVE to %p",t.remotePeer),await i.write({type:X.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===H.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:{[Gr]: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=yr(100),this.log("not discovered enough relays %d/%d",this.reservations.size,this.pendingReservations.length),this.safeDispatchEvent("relay:not-enough-relays")}};var wd=r=>{if(r.peer==null)return!1;try{r.peer.addrs.forEach(vt)}catch{return!1}return!0},Ku={maxInboundStopStreams:Wr,maxOutboundStopStreams:Wr,stopTimeout:3e4},Ao=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??Ku.maxInboundStopStreams,this.maxOutboundStopStreams=e.maxOutboundStopStreams??Ku.maxOutboundStopStreams,this.shutdownController=new AbortController,this.discovery=new So(t,{filter:e.discoveryFilter??Bs(fu,hu)}),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 vo(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";[js]=["@libp2p/transport","@libp2p/circuit-relay-v2-transport"];get[Xs](){return this.discovery!=null?["@libp2p/identify"]:[]}[Ws]=!0;isStarted(){return this.started}async start(){this.shutdownController=new AbortController,this.shutdownController.signal,await this.registrar.handle(Fe,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 Zs(this.discovery,this.reservationStore),this.started=!0}async stop(){this.shutdownController.abort(),await Ys(this.discovery,this.reservationStore),await this.registrar.unhandle(Fe),this.started=!1}async dial(t,e){if(t.protoCodes().filter(b=>b===$n).length!==1){let b="Invalid circuit relay address";throw this.log.error(b,t),new wr(b)}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 b=`ircuit relay dial to ${t.toString()} failed as address did not have both relay and destination PeerIDs`;throw this.log.error(`c${b}`),new wr(`C${b}`)}let c=os(s),l=os(a),f=this.connectionManager.getConnections(c)[0];f==null?(await this.peerStore.merge(c,{multiaddrs:[o]}),e.onProgress?.(new Te("circuit-relay:open-connection")),f=await this.connectionManager.openConnection(c,e)):e.onProgress?.(new Te("circuit-relay:reuse-connection"));let p;try{e.onProgress?.(new Te("circuit-relay:open-hop-stream")),p=await f.newStream(Ht,e);let b=_e(p),g=b.pb(X);e.onProgress?.(new Te("circuit-relay:write-connect-message")),await g.write({type:X.Type.CONNECT,peer:{id:l.toMultihash().bytes,addrs:[vt(i).bytes]}},e),e.onProgress?.(new Te("circuit-relay:read-connect-response"));let m=await g.read(e);if(m.status!==H.OK)throw new nn(`failed to connect via relay with status ${m?.status?.toString()??"undefined"}`);let _=new Xr(m.limit),R=qs({stream:b.unwrap(),remoteAddr:t,localAddr:o.encapsulate(`/p2p-circuit/p2p/${this.peerId.toString()}`),logger:this.logger,onDataRead:_.onData,onDataWrite:_.onData});return this.log("new outbound relayed connection %a",R.remoteAddr),await this.upgrader.upgradeOutbound(R,{...e,limits:_.getLimits()})}catch(b){throw this.log.error("circuit relay dial to destination %p via relay %p failed",l,c,b),p?.abort(b),b}}createListener(t){return Ou({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=>ao.exactMatch(e)||co.exactMatch(e))}dialFilter(t){return t=Array.isArray(t)?t:[t],t.filter(e=>ro.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=_e(e).pb(Mt),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:Mt.Type.STATUS,status:H.MALFORMED_MESSAGE},{signal:n}),await e.close();return}if(i.type!==Mt.Type.CONNECT){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await o.write({type:Mt.Type.STATUS,status:H.UNEXPECTED_MESSAGE},{signal:n}),await e.close();return}if(!wd(i)){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await o.write({type:Mt.Type.STATUS,status:H.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}let s=cr(qt(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:Mt.Type.STATUS,status:H.PERMISSION_DENIED},{signal:n}),await e.close({signal:n});return}this.log.trace("sending success response to %p",t.remotePeer),await o.write({type:Mt.Type.STATUS,status:H.OK},{signal:n});let a=new Xr(i.limit),c=t.remoteAddr.encapsulate(`/p2p-circuit/p2p/${s.toString()}`),l=this.addressManager.getAddresses()[0],u=qs({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 qu(r={}){return t=>new Ao(t,r)}return Yu(Ed);})();
2
+ "use strict";var Libp2PCircuitRelayV2=(()=>{var _o=Object.defineProperty;var Wu=Object.getOwnPropertyDescriptor;var $u=Object.getOwnPropertyNames;var Zu=Object.prototype.hasOwnProperty;var Lt=(r,t)=>{for(var e in t)_o(r,e,{get:t[e],enumerable:!0})},Yu=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of $u(t))!Zu.call(r,o)&&o!==e&&_o(r,o,{get:()=>t[o],enumerable:!(n=Wu(t,o))||n.enumerable});return r};var ju=r=>Yu(_o({},"__esModule",{value:!0}),r);var _d={};Lt(_d,{RELAY_V2_HOP_CODEC:()=>zt,RELAY_V2_STOP_CODEC:()=>Fe,circuitRelayServer:()=>Lu,circuitRelayTransport:()=>Fu});var Kt=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))}};var Io=Symbol.for("@libp2p/peer-id");var To="keep-alive";var Zs=Symbol.for("@libp2p/transport");var $s;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})($s||($s={}));var ne=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"}},Ge=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}};var tn=class extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}},en=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}};var rn=class extends Error{static name="InvalidMessageError";constructor(t="Invalid message"){super(t),this.name="InvalidMessageError"}};var xr=class extends Error{static name="DialError";constructor(t="Dial error"){super(t),this.name="DialError"}},Le=class extends Error{static name="ListenError";constructor(t="Listen error"){super(t),this.name="ListenError"}};var We=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};function Ys(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function js(...r){let t=[];for(let e of r)Ys(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 Xs(...r){let t=[];for(let e of r)Ys(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 Qs=Symbol.for("@libp2p/service-capabilities"),Js=Symbol.for("@libp2p/service-dependencies");var Po={};Lt(Po,{base58btc:()=>j,base58flickr:()=>nl});var tp=new Uint8Array(0);function ta(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 oe(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 ea(r){return new TextEncoder().encode(r)}function ra(r){return new TextDecoder().decode(r)}function Xu(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(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var m=0,_=0,C=0,V=g.length;C!==V&&g[C]===0;)C++,m++;for(var E=(V-C)*u+1>>>0,h=new Uint8Array(E);C!==V;){for(var w=g[C],I=0,T=E-1;(w!==0||I<_)&&T!==-1;T--,I++)w+=256*h[T]>>>0,h[T]=w%a>>>0,w=w/a>>>0;if(w!==0)throw new Error("Non-zero carry");_=I,C++}for(var L=E-_;L!==E&&h[L]===0;)L++;for(var N=c.repeat(m);L<E;++L)N+=r.charAt(h[L]);return N}function p(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var m=0;if(g[m]!==" "){for(var _=0,C=0;g[m]===c;)_++,m++;for(var V=(g.length-m)*l+1>>>0,E=new Uint8Array(V);g[m];){var h=e[g.charCodeAt(m)];if(h===255)return;for(var w=0,I=V-1;(h!==0||w<C)&&I!==-1;I--,w++)h+=a*E[I]>>>0,E[I]=h%256>>>0,h=h/256>>>0;if(h!==0)throw new Error("Non-zero carry");C=w,m++}if(g[m]!==" "){for(var T=V-C;T!==V&&E[T]===0;)T++;for(var L=new Uint8Array(_+(V-T)),N=_;T!==V;)L[N++]=E[T++];return L}}}function b(g){var m=p(g);if(m)return m;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:p,decode:b}}var Qu=Xu,Ju=Qu,oa=Ju;var Lo=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")}},Co=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 ia(this,t)}},Ro=class{decoders;constructor(t){this.decoders=t}or(t){return ia(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 ia(r,t){return new Ro({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var Do=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 Lo(t,e,n),this.decoder=new Co(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function $e({name:r,prefix:t,encode:e,decode:n}){return new Do(r,t,e,n)}function ge({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=oa(e,r);return $e({prefix:t,name:r,encode:n,decode:i=>oe(o(i))})}function tl(r,t,e,n){let o=r.length;for(;r[o-1]==="=";)--o;let i=new Uint8Array(o*e/8|0),s=0,a=0,c=0;for(let l=0;l<o;++l){let u=t[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<e|u,s+=e,s>=8&&(s-=8,i[c++]=255&a>>s)}if(s>=e||(255&a<<8-s)!==0)throw new SyntaxError("Unexpected end of data");return i}function el(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 rl(r){let t={};for(let e=0;e<r.length;++e)t[r[e]]=e;return t}function it({name:r,prefix:t,bitsPerChar:e,alphabet:n}){let o=rl(n);return $e({prefix:t,name:r,encode(i){return el(i,n,e)},decode(i){return tl(i,o,e,r)}})}var j=ge({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),nl=ge({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Bo={};Lt(Bo,{base32:()=>ie,base32hex:()=>al,base32hexpad:()=>ul,base32hexpadupper:()=>ll,base32hexupper:()=>cl,base32pad:()=>il,base32padupper:()=>sl,base32upper:()=>ol,base32z:()=>fl});var ie=it({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),ol=it({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),il=it({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),sl=it({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),al=it({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),cl=it({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),ul=it({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),ll=it({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),fl=it({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var No={};Lt(No,{base36:()=>Er,base36upper:()=>hl});var Er=ge({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),hl=ge({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var dl=ca,sa=128,pl=127,ml=~pl,yl=Math.pow(2,31);function ca(r,t,e){t=t||[],e=e||0;for(var n=e;r>=yl;)t[e++]=r&255|sa,r/=128;for(;r&ml;)t[e++]=r&255|sa,r>>>=7;return t[e]=r|0,ca.bytes=e-n+1,t}var gl=Uo,bl=128,aa=127;function Uo(r,n){var e=0,n=n||0,o=0,i=n,s,a=r.length;do{if(i>=a)throw Uo.bytes=0,new RangeError("Could not decode varint");s=r[i++],e+=o<28?(s&aa)<<o:(s&aa)*Math.pow(2,o),o+=7}while(s>=bl);return Uo.bytes=i-n,e}var wl=Math.pow(2,7),xl=Math.pow(2,14),El=Math.pow(2,21),Sl=Math.pow(2,28),vl=Math.pow(2,35),Al=Math.pow(2,42),_l=Math.pow(2,49),Il=Math.pow(2,56),Tl=Math.pow(2,63),Ll=function(r){return r<wl?1:r<xl?2:r<El?3:r<Sl?4:r<vl?5:r<Al?6:r<_l?7:r<Il?8:r<Tl?9:10},Cl={encode:dl,decode:gl,encodingLength:Ll},Rl=Cl,Sr=Rl;function vr(r,t=0){return[Sr.decode(r,t),Sr.decode.bytes]}function Ze(r,t,e=0){return Sr.encode(r,t,e),t}function Ye(r){return Sr.encodingLength(r)}function Gt(r,t){let e=t.byteLength,n=Ye(r),o=n+Ye(e),i=new Uint8Array(o+e);return Ze(r,i,0),Ze(e,i,n),i.set(t,o),new je(r,e,t,i)}function qt(r){let t=oe(r),[e,n]=vr(t),[o,i]=vr(t.subarray(n)),s=t.subarray(n+i);if(s.byteLength!==o)throw new Error("Incorrect length");return new je(e,o,s,t)}function ua(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&ta(r.bytes,e.bytes)}}var je=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};function la(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return Pl(e,Oo(r),t??j.encoder);default:return Bl(e,Oo(r),t??ie.encoder)}}var fa=new WeakMap;function Oo(r){let t=fa.get(r);if(t==null){let e=new Map;return fa.set(r,e),e}return t}var st=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!==Ar)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==Nl)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=Gt(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&&ua(t.multihash,n.multihash)}toString(t){return la(this,t)}toJSON(){return{"/":la(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??ha(n,o,i.bytes))}else if(e[Ul]===!0){let{version:n,multihash:o,code:i}=e,s=qt(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!==Ar)throw new Error(`Version 0 CID must use dag-pb (code: ${Ar}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=ha(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,Ar,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=oe(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 je(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,p]=vr(t.subarray(e));return e+=p,f},o=n(),i=Ar;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]=Dl(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 Oo(i).set(n,t),i}};function Dl(r,t){switch(r[0]){case"Q":{let e=t??j;return[j.prefix,e.decode(`${j.prefix}${r}`)]}case j.prefix:{let e=t??j;return[j.prefix,e.decode(r)]}case ie.prefix:{let e=t??ie;return[ie.prefix,e.decode(r)]}case Er.prefix:{let e=t??Er;return[Er.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 Pl(r,t,e){let{prefix:n}=e;if(n!==j.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 Bl(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 Ar=112,Nl=18;function ha(r,t,e){let n=Ye(r),o=n+Ye(t),i=new Uint8Array(o+e.byteLength);return Ze(r,i,0),Ze(t,i,n),i.set(e,o),i}var Ul=Symbol.for("@ipld/js-cid/CID");var ko={};Lt(ko,{identity:()=>Wt});var da=0,Ol="identity",pa=oe;function kl(r){return Gt(da,pa(r))}var Wt={code:da,name:Ol,encode:pa,digest:kl};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 Ct(r=0){return new Uint8Array(r)}function Ut(r,t){t==null&&(t=r.reduce((o,i)=>o+i.length,0));let e=Ct(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}var ya=Symbol.for("@achingbrain/uint8arraylist");function ma(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 on(r){return!!r?.[ya]}var ct=class r{bufs;length;[ya]=!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(on(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(on(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=ma(this.bufs,t);return e.buf[e.index]}set(t,e){let n=ma(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(on(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 Ut(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:Ut(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(!on(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 p=l;p>=0;p--){let b=this.get(f+p);if(n[p]!==b){u=Math.max(1,p-a[b]);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=Ct(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=Ct(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 Mo={};Lt(Mo,{base10:()=>Ml});var Ml=ge({prefix:"9",name:"base10",alphabet:"0123456789"});var Ko={};Lt(Ko,{base16:()=>Kl,base16upper:()=>ql});var Kl=it({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),ql=it({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var qo={};Lt(qo,{base2:()=>Fl});var Fl=it({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Fo={};Lt(Fo,{base256emoji:()=>Wl});var ga=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}"),Hl=ga.reduce((r,t,e)=>(r[e]=t,r),[]),zl=ga.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function Vl(r){return r.reduce((t,e)=>(t+=Hl[e],t),"")}function Gl(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=zl[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var Wl=$e({prefix:"\u{1F680}",name:"base256emoji",encode:Vl,decode:Gl});var zo={};Lt(zo,{base64:()=>$l,base64pad:()=>Zl,base64url:()=>Ho,base64urlpad:()=>Yl});var $l=it({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Zl=it({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ho=it({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Yl=it({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Vo={};Lt(Vo,{base8:()=>jl});var jl=it({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Go={};Lt(Go,{identity:()=>Xl});var Xl=$e({prefix:"\0",name:"identity",encode:r=>ra(r),decode:r=>ea(r)});var kp=new TextEncoder,Mp=new TextDecoder;var Zo={};Lt(Zo,{sha256:()=>Xe,sha512:()=>tf});function $o({name:r,code:t,encode:e}){return new Wo(r,t,e)}var Wo=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?Gt(this.code,e):e.then(n=>Gt(this.code,n))}else throw Error("Unknown type, must be binary type")}};function wa(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var Xe=$o({name:"sha2-256",code:18,encode:wa("SHA-256")}),tf=$o({name:"sha2-512",code:19,encode:wa("SHA-512")});var _r={...Go,...qo,...Vo,...Mo,...Ko,...Bo,...No,...Po,...zo,...Fo},jp={...Zo,...ko};function Ea(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var xa=Ea("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Yo=Ea("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=Ct(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),ef={utf8:xa,"utf-8":xa,hex:_r.base16,latin1:Yo,ascii:Yo,binary:Yo,..._r},sn=ef;function q(r,t="utf8"){let e=sn[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function k(r,t="utf8"){let e=sn[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var rf=parseInt("11111",2),jo=parseInt("10000000",2),nf=parseInt("01111111",2),Sa={0:Ir,1:Ir,2:of,3:cf,4:uf,5:af,6:sf,16:Ir,22:Ir,48:Ir};function se(r,t={offset:0}){let e=r[t.offset]&rf;if(t.offset++,Sa[e]!=null)return Sa[e](r,t);throw new Error("No decoder for tag "+e)}function Tr(r,t){let e=0;if((r[t.offset]&jo)===jo){let n=r[t.offset]&nf,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 Ir(r,t){Tr(r,t);let e=[];for(;!(t.offset>=r.byteLength);){let n=se(r,t);if(n===null)break;e.push(n)}return e}function of(r,t){let e=Tr(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 sf(r,t){let e=Tr(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 af(r,t){return t.offset++,null}function cf(r,t){let e=Tr(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 uf(r,t){let e=Tr(r,t),n=r.subarray(t.offset,t.offset+e);return t.offset+=e,n}function lf(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 Xo(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let t=lf(r.byteLength);return new ct(Uint8Array.from([t.byteLength|jo]),t)}function Rt(r){let t=new ct,e=128;return(r.subarray()[0]&e)===e&&t.append(Uint8Array.from([0])),t.append(r),new ct(Uint8Array.from([2]),Xo(t),t)}function an(r){let t=Uint8Array.from([0]),e=new ct(t,r);return new ct(Uint8Array.from([3]),Xo(e),e)}function be(r,t=48){let e=new ct;for(let n of r)e.append(n);return new ct(Uint8Array.from([t]),Xo(e),e)}async function va(r,t,e,n){let o=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let i=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,t,e.subarray());return n?.signal?.throwIfAborted(),i}var ff=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),hf=Uint8Array.from([6,5,43,129,4,0,34]),df=Uint8Array.from([6,5,43,129,4,0,35]),pf={ext:!0,kty:"EC",crv:"P-256"},mf={ext:!0,kty:"EC",crv:"P-384"},yf={ext:!0,kty:"EC",crv:"P-521"},Qo=32,Jo=48,ti=66;function ei(r){let t=se(r);return Aa(t)}function Aa(r){let t=r[1][1][0],e=1,n,o;if(t.byteLength===Qo*2+1)return n=k(t.subarray(e,e+Qo),"base64url"),o=k(t.subarray(e+Qo),"base64url"),new Qe({...pf,key_ops:["verify"],x:n,y:o});if(t.byteLength===Jo*2+1)return n=k(t.subarray(e,e+Jo),"base64url"),o=k(t.subarray(e+Jo),"base64url"),new Qe({...mf,key_ops:["verify"],x:n,y:o});if(t.byteLength===ti*2+1)return n=k(t.subarray(e,e+ti),"base64url"),o=k(t.subarray(e+ti),"base64url"),new Qe({...yf,key_ops:["verify"],x:n,y:o});throw new ht(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function _a(r){return be([Rt(Uint8Array.from([1])),be([gf(r.crv)],160),be([an(new ct(Uint8Array.from([4]),q(r.x??"","base64url"),q(r.y??"","base64url")))],161)]).subarray()}function gf(r){if(r==="P-256")return ff;if(r==="P-384")return hf;if(r==="P-521")return df;throw new ht(`Invalid curve ${r}`)}var Qe=class{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=_a(this.jwk)),this._raw}toMultihash(){return Wt.digest(Qt(this))}toCID(){return st.createV1(114,this.toMultihash())}toString(){return j.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,n){return va(this.jwk,e,t,n)}};var Ce=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function bf(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function cn(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function Re(r,...t){if(!bf(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 Ia(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");cn(r.outputLen),cn(r.blockLen)}function tr(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 Ta(r,t){Re(r);let e=t.outputLen;if(r.length<e)throw new Error("digestInto() expects output buffer of length at least "+e)}function ae(...r){for(let t=0;t<r.length;t++)r[t].fill(0)}function un(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function $t(r,t){return r<<32-t|r>>>t}function La(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function Lr(r){return typeof r=="string"&&(r=La(r)),Re(r),r}function ri(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];Re(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 Je=class{};function ni(r){let t=n=>r().update(Lr(n)).digest(),e=r();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>r(),t}function ln(r=32){if(Ce&&typeof Ce.getRandomValues=="function")return Ce.getRandomValues(new Uint8Array(r));if(Ce&&typeof Ce.randomBytes=="function")return Uint8Array.from(Ce.randomBytes(r));throw new Error("crypto.getRandomValues must be defined")}function wf(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 Ca(r,t,e){return r&t^~r&e}function Ra(r,t,e){return r&t^r&e^t&e}var Cr=class extends Je{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=un(this.buffer)}update(t){tr(this),t=Lr(t),Re(t);let{view:e,buffer:n,blockLen:o}=this,i=t.length;for(let s=0;s<i;){let a=Math.min(o-this.pos,i-s);if(a===o){let c=un(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){tr(this),Ta(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:o,isLE:i}=this,{pos:s}=this;e[s++]=128,ae(this.buffer.subarray(s)),this.padOffset>o-s&&(this.process(n,0),s=0);for(let f=s;f<o;f++)e[f]=0;wf(n,o-8,BigInt(this.length*8),i),this.process(n,0);let a=un(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.destroyed=s,t.finished=i,t.length=o,t.pos=a,o%e&&t.buffer.set(n),t}clone(){return this._cloneInto()}},ce=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var bt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var fn=BigInt(4294967295),Da=BigInt(32);function xf(r,t=!1){return t?{h:Number(r&fn),l:Number(r>>Da&fn)}:{h:Number(r>>Da&fn)|0,l:Number(r&fn)|0}}function Pa(r,t=!1){let e=r.length,n=new Uint32Array(e),o=new Uint32Array(e);for(let i=0;i<e;i++){let{h:s,l:a}=xf(r[i],t);[n[i],o[i]]=[s,a]}return[n,o]}var oi=(r,t,e)=>r>>>e,ii=(r,t,e)=>r<<32-e|t>>>e,De=(r,t,e)=>r>>>e|t<<32-e,Pe=(r,t,e)=>r<<32-e|t>>>e,Rr=(r,t,e)=>r<<64-e|t>>>e-32,Dr=(r,t,e)=>r>>>e-32|t<<64-e;function Jt(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var Ba=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),Na=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,Ua=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),Oa=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,ka=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),Ma=(r,t,e,n,o,i)=>t+e+n+o+i+(r/2**32|0)|0;var Sf=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),we=new Uint32Array(64),hn=class extends Cr{constructor(t=32){super(64,t,8,!1),this.A=ce[0]|0,this.B=ce[1]|0,this.C=ce[2]|0,this.D=ce[3]|0,this.E=ce[4]|0,this.F=ce[5]|0,this.G=ce[6]|0,this.H=ce[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)we[f]=t.getUint32(e,!1);for(let f=16;f<64;f++){let p=we[f-15],b=we[f-2],g=$t(p,7)^$t(p,18)^p>>>3,m=$t(b,17)^$t(b,19)^b>>>10;we[f]=m+we[f-7]+g+we[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 p=$t(a,6)^$t(a,11)^$t(a,25),b=u+p+Ca(a,c,l)+Sf[f]+we[f]|0,m=($t(n,2)^$t(n,13)^$t(n,22))+Ra(n,o,i)|0;u=l,l=c,c=a,a=s+b|0,s=i,i=o,o=n,n=b+m|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(){ae(we)}destroy(){this.set(0,0,0,0,0,0,0,0),ae(this.buffer)}};var Ka=Pa(["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))),vf=Ka[0],Af=Ka[1],xe=new Uint32Array(80),Ee=new Uint32Array(80),si=class extends Cr{constructor(t=64){super(128,t,16,!1),this.Ah=bt[0]|0,this.Al=bt[1]|0,this.Bh=bt[2]|0,this.Bl=bt[3]|0,this.Ch=bt[4]|0,this.Cl=bt[5]|0,this.Dh=bt[6]|0,this.Dl=bt[7]|0,this.Eh=bt[8]|0,this.El=bt[9]|0,this.Fh=bt[10]|0,this.Fl=bt[11]|0,this.Gh=bt[12]|0,this.Gl=bt[13]|0,this.Hh=bt[14]|0,this.Hl=bt[15]|0}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:p,Gh:b,Gl:g,Hh:m,Hl:_}=this;return[t,e,n,o,i,s,a,c,l,u,f,p,b,g,m,_]}set(t,e,n,o,i,s,a,c,l,u,f,p,b,g,m,_){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=p|0,this.Gh=b|0,this.Gl=g|0,this.Hh=m|0,this.Hl=_|0}process(t,e){for(let E=0;E<16;E++,e+=4)xe[E]=t.getUint32(e),Ee[E]=t.getUint32(e+=4);for(let E=16;E<80;E++){let h=xe[E-15]|0,w=Ee[E-15]|0,I=De(h,w,1)^De(h,w,8)^oi(h,w,7),T=Pe(h,w,1)^Pe(h,w,8)^ii(h,w,7),L=xe[E-2]|0,N=Ee[E-2]|0,K=De(L,N,19)^Rr(L,N,61)^oi(L,N,6),D=Pe(L,N,19)^Dr(L,N,61)^ii(L,N,6),U=Ua(T,D,Ee[E-7],Ee[E-16]),B=Oa(U,I,K,xe[E-7],xe[E-16]);xe[E]=B|0,Ee[E]=U|0}let{Ah:n,Al:o,Bh:i,Bl:s,Ch:a,Cl:c,Dh:l,Dl:u,Eh:f,El:p,Fh:b,Fl:g,Gh:m,Gl:_,Hh:C,Hl:V}=this;for(let E=0;E<80;E++){let h=De(f,p,14)^De(f,p,18)^Rr(f,p,41),w=Pe(f,p,14)^Pe(f,p,18)^Dr(f,p,41),I=f&b^~f&m,T=p&g^~p&_,L=ka(V,w,T,Af[E],Ee[E]),N=Ma(L,C,h,I,vf[E],xe[E]),K=L|0,D=De(n,o,28)^Rr(n,o,34)^Rr(n,o,39),U=Pe(n,o,28)^Dr(n,o,34)^Dr(n,o,39),B=n&i^n&a^i&a,lt=o&s^o&c^s&c;C=m|0,V=_|0,m=b|0,_=g|0,b=f|0,g=p|0,{h:f,l:p}=Jt(l|0,u|0,N|0,K|0),l=a|0,u=c|0,a=i|0,c=s|0,i=n|0,s=o|0;let v=Ba(K,U,lt);n=Na(v,N,D,B),o=v|0}({h:n,l:o}=Jt(this.Ah|0,this.Al|0,n|0,o|0)),{h:i,l:s}=Jt(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=Jt(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=Jt(this.Dh|0,this.Dl|0,l|0,u|0),{h:f,l:p}=Jt(this.Eh|0,this.El|0,f|0,p|0),{h:b,l:g}=Jt(this.Fh|0,this.Fl|0,b|0,g|0),{h:m,l:_}=Jt(this.Gh|0,this.Gl|0,m|0,_|0),{h:C,l:V}=Jt(this.Hh|0,this.Hl|0,C|0,V|0),this.set(n,o,i,s,a,c,l,u,f,p,b,g,m,_,C,V)}roundClean(){ae(xe,Ee)}destroy(){ae(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var dn=ni(()=>new hn);var qa=ni(()=>new si);var li=BigInt(0),ui=BigInt(1);function er(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function fi(r){if(!er(r))throw new Error("Uint8Array expected")}function te(r,t){if(typeof t!="boolean")throw new Error(r+" boolean expected, got "+t)}function Pr(r){let t=r.toString(16);return t.length&1?"0"+t:t}function za(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?li:BigInt("0x"+r)}var Va=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",_f=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function Se(r){if(fi(r),Va)return r.toHex();let t="";for(let e=0;e<r.length;e++)t+=_f[r[e]];return t}var ue={_0:48,_9:57,A:65,F:70,a:97,f:102};function Fa(r){if(r>=ue._0&&r<=ue._9)return r-ue._0;if(r>=ue.A&&r<=ue.F)return r-(ue.A-10);if(r>=ue.a&&r<=ue.f)return r-(ue.a-10)}function Br(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(Va)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=Fa(r.charCodeAt(i)),a=Fa(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 le(r){return za(Se(r))}function Be(r){return fi(r),za(Se(Uint8Array.from(r).reverse()))}function Ne(r,t){return Br(r.toString(16).padStart(t*2,"0"))}function rr(r,t){return Ne(r,t).reverse()}function rt(r,t,e){let n;if(typeof t=="string")try{n=Br(t)}catch(i){throw new Error(r+" must be hex string or Uint8Array, cause: "+i)}else if(er(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 ve(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];fi(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 ai=r=>typeof r=="bigint"&&li<=r;function pn(r,t,e){return ai(r)&&ai(t)&&ai(e)&&t<=r&&r<e}function Ot(r,t,e,n){if(!pn(t,e,n))throw new Error("expected valid "+r+": "+e+" <= n < "+n+", got "+t)}function Ga(r){let t;for(t=0;r>li;r>>=ui,t+=1);return t}var Ue=r=>(ui<<BigInt(r))-ui,ci=r=>new Uint8Array(r),Ha=r=>Uint8Array.from(r);function Wa(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=ci(r),o=ci(r),i=0,s=()=>{n.fill(1),o.fill(0),i=0},a=(...f)=>e(o,n,...f),c=(f=ci(0))=>{o=a(Ha([0]),f),n=a(),f.length!==0&&(o=a(Ha([1]),f),n=a())},l=()=>{if(i++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,p=[];for(;f<t;){n=a();let b=n.slice();p.push(b),f+=n.length}return ve(...p)};return(f,p)=>{s(),c(f);let b;for(;!(b=p(l()));)c();return s(),b}}var If={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"||er(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 fe(r,t,e={}){let n=(o,i,s)=>{let a=If[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 nr(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 _t=BigInt(0),mt=BigInt(1),Oe=BigInt(2),Tf=BigInt(3),Za=BigInt(4),Ya=BigInt(5),ja=BigInt(8);function J(r,t){let e=r%t;return e>=_t?e:t+e}function nt(r,t,e){let n=r;for(;t-- >_t;)n*=n,n%=e;return n}function mn(r,t){if(r===_t)throw new Error("invert: expected non-zero number");if(t<=_t)throw new Error("invert: expected positive modulus, got "+t);let e=J(r,t),n=t,o=_t,i=mt,s=mt,a=_t;for(;e!==_t;){let l=n/e,u=n%e,f=o-s*l,p=i-a*l;n=e,e=u,o=s,i=a,s=f,a=p}if(n!==mt)throw new Error("invert: does not exist");return J(o,t)}function Xa(r,t){let e=(r.ORDER+mt)/Za,n=r.pow(t,e);if(!r.eql(r.sqr(n),t))throw new Error("Cannot find square root");return n}function Lf(r,t){let e=(r.ORDER-Ya)/ja,n=r.mul(t,Oe),o=r.pow(n,e),i=r.mul(t,o),s=r.mul(r.mul(i,Oe),o),a=r.mul(i,r.sub(s,r.ONE));if(!r.eql(r.sqr(a),t))throw new Error("Cannot find square root");return a}function Cf(r){if(r<BigInt(3))throw new Error("sqrt is not defined for small field");let t=r-mt,e=0;for(;t%Oe===_t;)t/=Oe,e++;let n=Oe,o=he(r);for(;$a(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(e===1)return Xa;let i=o.pow(n,t),s=(t+mt)/Oe;return function(c,l){if(c.is0(l))return l;if($a(c,l)!==1)throw new Error("Cannot find square root");let u=e,f=c.mul(c.ONE,i),p=c.pow(l,t),b=c.pow(l,s);for(;!c.eql(p,c.ONE);){if(c.is0(p))return c.ZERO;let g=1,m=c.sqr(p);for(;!c.eql(m,c.ONE);)if(g++,m=c.sqr(m),g===u)throw new Error("Cannot find square root");let _=mt<<BigInt(u-g-1),C=c.pow(f,_);u=g,f=c.sqr(C),p=c.mul(p,f),b=c.mul(b,C)}return b}}function Rf(r){return r%Za===Tf?Xa:r%ja===Ya?Lf:Cf(r)}var Qa=(r,t)=>(J(r,t)&mt)===mt,Df=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function hi(r){let t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},e=Df.reduce((n,o)=>(n[o]="function",n),t);return fe(r,e)}function Pf(r,t,e){if(e<_t)throw new Error("invalid exponent, negatives unsupported");if(e===_t)return r.ONE;if(e===mt)return t;let n=r.ONE,o=t;for(;e>_t;)e&mt&&(n=r.mul(n,o)),o=r.sqr(o),e>>=mt;return n}function or(r,t,e=!1){let n=new Array(t.length).fill(e?r.ZERO:void 0),o=t.reduce((s,a,c)=>r.is0(a)?s:(n[c]=s,r.mul(s,a)),r.ONE),i=r.inv(o);return t.reduceRight((s,a,c)=>r.is0(a)?s:(n[c]=r.mul(s,n[c]),r.mul(s,a)),i),n}function $a(r,t){let e=(r.ORDER-mt)/Oe,n=r.pow(t,e),o=r.eql(n,r.ONE),i=r.eql(n,r.ZERO),s=r.eql(n,r.neg(r.ONE));if(!o&&!i&&!s)throw new Error("invalid Legendre symbol result");return o?1:i?0:-1}function di(r,t){t!==void 0&&cn(t);let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}function he(r,t,e=!1,n={}){if(r<=_t)throw new Error("invalid field: expected ORDER > 0, got "+r);let{nBitLength:o,nByteLength:i}=di(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:Ue(o),ZERO:_t,ONE:mt,create:c=>J(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return _t<=c&&c<r},is0:c=>c===_t,isOdd:c=>(c&mt)===mt,neg:c=>J(-c,r),eql:(c,l)=>c===l,sqr:c=>J(c*c,r),add:(c,l)=>J(c+l,r),sub:(c,l)=>J(c-l,r),mul:(c,l)=>J(c*l,r),pow:(c,l)=>Pf(a,c,l),div:(c,l)=>J(c*mn(l,r),r),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>mn(c,r),sqrt:n.sqrt||(c=>(s||(s=Rf(r)),s(a,c))),toBytes:c=>e?rr(c,i):Ne(c,i),fromBytes:c=>{if(c.length!==i)throw new Error("Field.fromBytes: expected "+i+" bytes, got "+c.length);return e?Be(c):le(c)},invertBatch:c=>or(a,c),cmov:(c,l,u)=>u?l:c});return Object.freeze(a)}function Ja(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 pi(r){let t=Ja(r);return t+Math.ceil(t/2)}function tc(r,t,e=!1){let n=r.length,o=Ja(t),i=pi(t);if(n<16||n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);let s=e?Be(r):le(r),a=J(s,t-mt)+mt;return e?rr(a,o):Ne(a,o)}var ec=BigInt(0),wi=BigInt(1);function mi(r,t){let e=t.negate();return r?e:t}function nc(r,t){if(!Number.isSafeInteger(r)||r<=0||r>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+r)}function yi(r,t){nc(r,t);let e=Math.ceil(t/r)+1,n=2**(r-1),o=2**r,i=Ue(r),s=BigInt(r);return{windows:e,windowSize:n,mask:i,maxNumber:o,shiftBy:s}}function rc(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+=wi);let l=t*n,u=l+Math.abs(a)-1,f=a===0,p=a<0,b=t%2!==0;return{nextN:c,offset:u,isZero:f,isNeg:p,isNegF:b,offsetF:l}}function Bf(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 Nf(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 gi=new WeakMap,oc=new WeakMap;function bi(r){return oc.get(r)||1}function yn(r,t){return{constTimeNegate:mi,hasPrecomputes(e){return bi(e)!==1},unsafeLadder(e,n,o=r.ZERO){let i=e;for(;n>ec;)n&wi&&(o=o.add(i)),i=i.double(),n>>=wi;return o},precomputeWindow(e,n){let{windows:o,windowSize:i}=yi(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=yi(e,t);for(let c=0;c<a.windows;c++){let{nextN:l,offset:u,isZero:f,isNeg:p,isNegF:b,offsetF:g}=rc(o,c,a);o=l,f?s=s.add(mi(b,n[g])):i=i.add(mi(p,n[u]))}return{p:i,f:s}},wNAFUnsafe(e,n,o,i=r.ZERO){let s=yi(e,t);for(let a=0;a<s.windows&&o!==ec;a++){let{nextN:c,offset:l,isZero:u,isNeg:f}=rc(o,a,s);if(o=c,!u){let p=n[l];i=i.add(f?p.negate():p)}}return i},getPrecomputes(e,n,o){let i=gi.get(n);return i||(i=this.precomputeWindow(n,e),e!==1&&gi.set(n,o(i))),i},wNAFCached(e,n,o){let i=bi(e);return this.wNAF(i,this.getPrecomputes(i,e,o),n)},wNAFCachedUnsafe(e,n,o,i){let s=bi(e);return s===1?this.unsafeLadder(e,n,i):this.wNAFUnsafe(s,this.getPrecomputes(s,e,o),n,i)},setWindowSize(e,n){nc(n,t),oc.set(e,n),gi.delete(e)}}}function gn(r,t,e,n){Bf(e,r),Nf(n,t);let o=e.length,i=n.length;if(o!==i)throw new Error("arrays of points and scalars must have equal length");let s=r.ZERO,a=Ga(BigInt(o)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let l=Ue(c),u=new Array(Number(l)+1).fill(s),f=Math.floor((t.BITS-1)/c)*c,p=s;for(let b=f;b>=0;b-=c){u.fill(s);for(let m=0;m<i;m++){let _=n[m],C=Number(_>>BigInt(b)&l);u[C]=u[C].add(e[m])}let g=s;for(let m=u.length-1,_=s;m>0;m--)_=_.add(u[m]),g=g.add(_);if(p=p.add(g),b!==0)for(let m=0;m<c;m++)p=p.double()}return p}function Nr(r){return hi(r.Fp),fe(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...di(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var ee=BigInt(0),It=BigInt(1),ic=BigInt(2),Uf=BigInt(8),Of={zip215:!0};function kf(r){let t=Nr(r);return fe(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function sc(r){let t=kf(r),{Fp:e,n,prehash:o,hash:i,randomBytes:s,nByteLength:a,h:c}=t,l=ic<<BigInt(a*8)-It,u=e.create,f=he(t.n,t.nBitLength);function p(x,d){let y=e.sqr(x),A=e.sqr(d),P=e.add(e.mul(t.a,y),A),O=e.add(e.ONE,e.mul(t.d,e.mul(y,A)));return e.eql(P,O)}if(!p(t.Gx,t.Gy))throw new Error("bad curve params: generator point");let b=t.uvRatio||((x,d)=>{try{return{isValid:!0,value:e.sqrt(x*e.inv(d))}}catch{return{isValid:!1,value:ee}}}),g=t.adjustScalarBytes||(x=>x),m=t.domain||((x,d,y)=>{if(te("phflag",y),d.length||y)throw new Error("Contexts/pre-hash are not supported");return x});function _(x,d,y=!1){let A=y?It:ee;Ot("coordinate "+x,d,A,l)}function C(x){if(!(x instanceof h))throw new Error("ExtendedPoint expected")}let V=nr((x,d)=>{let{ex:y,ey:A,ez:P}=x,O=x.is0();d==null&&(d=O?Uf:e.inv(P));let z=u(y*d),G=u(A*d),W=u(P*d);if(O)return{x:ee,y:It};if(W!==It)throw new Error("invZ was invalid");return{x:z,y:G}}),E=nr(x=>{let{a:d,d:y}=t;if(x.is0())throw new Error("bad point: ZERO");let{ex:A,ey:P,ez:O,et:z}=x,G=u(A*A),W=u(P*P),Y=u(O*O),ft=u(Y*Y),at=u(G*d),gt=u(Y*u(at+W)),Tt=u(ft+u(y*u(G*W)));if(gt!==Tt)throw new Error("bad point: equation left != right (1)");let pt=u(A*P),wt=u(O*z);if(pt!==wt)throw new Error("bad point: equation left != right (2)");return!0});class h{constructor(d,y,A,P){_("x",d),_("y",y),_("z",A,!0),_("t",P),this.ex=d,this.ey=y,this.ez=A,this.et=P,Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(d){if(d instanceof h)throw new Error("extended point not allowed");let{x:y,y:A}=d||{};return _("x",y),_("y",A),new h(y,A,It,u(y*A))}static normalizeZ(d){let y=or(e,d.map(A=>A.ez));return d.map((A,P)=>A.toAffine(y[P])).map(h.fromAffine)}static msm(d,y){return gn(h,f,d,y)}_setWindowSize(d){T.setWindowSize(this,d)}assertValidity(){E(this)}equals(d){C(d);let{ex:y,ey:A,ez:P}=this,{ex:O,ey:z,ez:G}=d,W=u(y*G),Y=u(O*P),ft=u(A*G),at=u(z*P);return W===Y&&ft===at}is0(){return this.equals(h.ZERO)}negate(){return new h(u(-this.ex),this.ey,this.ez,u(-this.et))}double(){let{a:d}=t,{ex:y,ey:A,ez:P}=this,O=u(y*y),z=u(A*A),G=u(ic*u(P*P)),W=u(d*O),Y=y+A,ft=u(u(Y*Y)-O-z),at=W+z,gt=at-G,Tt=W-z,pt=u(ft*gt),wt=u(at*Tt),Nt=u(ft*Tt),Vt=u(gt*at);return new h(pt,wt,Vt,Nt)}add(d){C(d);let{a:y,d:A}=t,{ex:P,ey:O,ez:z,et:G}=this,{ex:W,ey:Y,ez:ft,et:at}=d,gt=u(P*W),Tt=u(O*Y),pt=u(G*A*at),wt=u(z*ft),Nt=u((P+O)*(W+Y)-gt-Tt),Vt=wt-pt,wr=wt+pt,Ws=u(Tt-y*gt),Hu=u(Nt*Vt),zu=u(wr*Ws),Vu=u(Nt*Ws),Gu=u(Vt*wr);return new h(Hu,zu,Gu,Vu)}subtract(d){return this.add(d.negate())}wNAF(d){return T.wNAFCached(this,d,h.normalizeZ)}multiply(d){let y=d;Ot("scalar",y,It,n);let{p:A,f:P}=this.wNAF(y);return h.normalizeZ([A,P])[0]}multiplyUnsafe(d,y=h.ZERO){let A=d;return Ot("scalar",A,ee,n),A===ee?I:this.is0()||A===It?this:T.wNAFCachedUnsafe(this,A,h.normalizeZ,y)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return T.unsafeLadder(this,n).is0()}toAffine(d){return V(this,d)}clearCofactor(){let{h:d}=t;return d===It?this:this.multiplyUnsafe(d)}static fromHex(d,y=!1){let{d:A,a:P}=t,O=e.BYTES;d=rt("pointHex",d,O),te("zip215",y);let z=d.slice(),G=d[O-1];z[O-1]=G&-129;let W=Be(z),Y=y?l:e.ORDER;Ot("pointHex.y",W,ee,Y);let ft=u(W*W),at=u(ft-It),gt=u(A*ft-P),{isValid:Tt,value:pt}=b(at,gt);if(!Tt)throw new Error("Point.fromHex: invalid y coordinate");let wt=(pt&It)===It,Nt=(G&128)!==0;if(!y&&pt===ee&&Nt)throw new Error("Point.fromHex: x=0 and x_0=1");return Nt!==wt&&(pt=u(-pt)),h.fromAffine({x:pt,y:W})}static fromPrivateKey(d){let{scalar:y}=K(d);return w.multiply(y)}toRawBytes(){let{x:d,y}=this.toAffine(),A=rr(y,e.BYTES);return A[A.length-1]|=d&It?128:0,A}toHex(){return Se(this.toRawBytes())}}h.BASE=new h(t.Gx,t.Gy,It,u(t.Gx*t.Gy)),h.ZERO=new h(ee,It,It,ee);let{BASE:w,ZERO:I}=h,T=yn(h,a*8);function L(x){return J(x,n)}function N(x){return L(Be(x))}function K(x){let d=e.BYTES;x=rt("private key",x,d);let y=rt("hashed private key",i(x),2*d),A=g(y.slice(0,d)),P=y.slice(d,2*d),O=N(A);return{head:A,prefix:P,scalar:O}}function D(x){let{head:d,prefix:y,scalar:A}=K(x),P=w.multiply(A),O=P.toRawBytes();return{head:d,prefix:y,scalar:A,point:P,pointBytes:O}}function U(x){return D(x).pointBytes}function B(x=Uint8Array.of(),...d){let y=ve(...d);return N(i(m(y,rt("context",x),!!o)))}function lt(x,d,y={}){x=rt("message",x),o&&(x=o(x));let{prefix:A,scalar:P,pointBytes:O}=D(d),z=B(y.context,A,x),G=w.multiply(z).toRawBytes(),W=B(y.context,G,O,x),Y=L(z+W*P);Ot("signature.s",Y,ee,n);let ft=ve(G,rr(Y,e.BYTES));return rt("result",ft,e.BYTES*2)}let v=Of;function S(x,d,y,A=v){let{context:P,zip215:O}=A,z=e.BYTES;x=rt("signature",x,2*z),d=rt("message",d),y=rt("publicKey",y,z),O!==void 0&&te("zip215",O),o&&(d=o(d));let G=Be(x.slice(z,2*z)),W,Y,ft;try{W=h.fromHex(y,O),Y=h.fromHex(x.slice(0,z),O),ft=w.multiplyUnsafe(G)}catch{return!1}if(!O&&W.isSmallOrder())return!1;let at=B(P,Y.toRawBytes(),W.toRawBytes(),d);return Y.add(W.multiplyUnsafe(at)).subtract(ft).clearCofactor().equals(h.ZERO)}return w._setWindowSize(8),{CURVE:t,getPublicKey:U,sign:lt,verify:S,ExtendedPoint:h,utils:{getExtendedPublicKey:D,randomPrivateKey:()=>s(e.BYTES),precompute(x=8,d=h.BASE){return d._setWindowSize(x),d.multiply(BigInt(3)),d}}}}var xi=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),ac=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),Jm=BigInt(0),Mf=BigInt(1),cc=BigInt(2),t0=BigInt(3),Kf=BigInt(5),qf=BigInt(8);function Ff(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),i=xi,a=r*r%i*r%i,c=nt(a,cc,i)*a%i,l=nt(c,Mf,i)*r%i,u=nt(l,Kf,i)*l%i,f=nt(u,t,i)*u%i,p=nt(f,e,i)*f%i,b=nt(p,n,i)*p%i,g=nt(b,o,i)*b%i,m=nt(g,o,i)*b%i,_=nt(m,t,i)*u%i;return{pow_p_5_8:nt(_,cc,i)*r%i,b2:a}}function Hf(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function zf(r,t){let e=xi,n=J(t*t*t,e),o=J(n*n*t,e),i=Ff(r*o).pow_p_5_8,s=J(r*n*i,e),a=J(t*s*s,e),c=s,l=J(s*ac,e),u=a===r,f=a===J(-r,e),p=a===J(-r*ac,e);return u&&(s=c),(f||p)&&(s=l),Qa(s,e)&&(s=J(-s,e)),{isValid:u||f,value:s}}var uc=he(xi,void 0,!0),Vf={a:uc.create(BigInt(-1)),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:uc,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:qf,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:qa,randomBytes:ln,adjustScalarBytes:Hf,uvRatio:zf},lc=sc(Vf);var Ur=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 fc={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 Ft=fc;var wn=32;var Ei,Gf=(async()=>{try{return await Ft.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function Wf(r,t,e){if(r.buffer instanceof ArrayBuffer){let n=await Ft.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await Ft.get().subtle.verify({name:"Ed25519"},n,t,e instanceof Uint8Array?e:e.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function $f(r,t,e){return lc.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}async function hc(r,t,e){return Ei==null&&(Ei=await Gf),Ei?Wf(r,t,e):$f(r,t,e)}function xn(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var En=class{type="Ed25519";raw;constructor(t){this.raw=Si(t,wn)}toMultihash(){return Wt.digest(Qt(this))}toCID(){return st.createV1(114,this.toMultihash())}toString(){return j.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:dt(this.raw,t.raw)}verify(t,e,n){n?.signal?.throwIfAborted();let o=hc(this.raw,e,t);return xn(o)?o.then(i=>(n?.signal?.throwIfAborted(),i)):o}};function vi(r){return r=Si(r,wn),new En(r)}function Si(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 Yf=Math.pow(2,7),jf=Math.pow(2,14),Xf=Math.pow(2,21),Ai=Math.pow(2,28),_i=Math.pow(2,35),Ii=Math.pow(2,42),Ti=Math.pow(2,49),Z=128,xt=127;function Et(r){if(r<Yf)return 1;if(r<jf)return 2;if(r<Xf)return 3;if(r<Ai)return 4;if(r<_i)return 5;if(r<Ii)return 6;if(r<Ti)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Li(r,t,e=0){switch(Et(r)){case 8:t[e++]=r&255|Z,r/=128;case 7:t[e++]=r&255|Z,r/=128;case 6:t[e++]=r&255|Z,r/=128;case 5:t[e++]=r&255|Z,r/=128;case 4:t[e++]=r&255|Z,r>>>=7;case 3:t[e++]=r&255|Z,r>>>=7;case 2:t[e++]=r&255|Z,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function Qf(r,t,e=0){switch(Et(r)){case 8:t.set(e++,r&255|Z),r/=128;case 7:t.set(e++,r&255|Z),r/=128;case 6:t.set(e++,r&255|Z),r/=128;case 5:t.set(e++,r&255|Z),r/=128;case 4:t.set(e++,r&255|Z),r>>>=7;case 3:t.set(e++,r&255|Z),r>>>=7;case 2:t.set(e++,r&255|Z),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function Ci(r,t){let e=r[t],n=0;if(n+=e&xt,e<Z||(e=r[t+1],n+=(e&xt)<<7,e<Z)||(e=r[t+2],n+=(e&xt)<<14,e<Z)||(e=r[t+3],n+=(e&xt)<<21,e<Z)||(e=r[t+4],n+=(e&xt)*Ai,e<Z)||(e=r[t+5],n+=(e&xt)*_i,e<Z)||(e=r[t+6],n+=(e&xt)*Ii,e<Z)||(e=r[t+7],n+=(e&xt)*Ti,e<Z))return n;throw new RangeError("Could not decode varint")}function Jf(r,t){let e=r.get(t),n=0;if(n+=e&xt,e<Z||(e=r.get(t+1),n+=(e&xt)<<7,e<Z)||(e=r.get(t+2),n+=(e&xt)<<14,e<Z)||(e=r.get(t+3),n+=(e&xt)<<21,e<Z)||(e=r.get(t+4),n+=(e&xt)*Ai,e<Z)||(e=r.get(t+5),n+=(e&xt)*_i,e<Z)||(e=r.get(t+6),n+=(e&xt)*Ii,e<Z)||(e=r.get(t+7),n+=(e&xt)*Ti,e<Z))return n;throw new RangeError("Could not decode varint")}function Ht(r,t,e=0){return t==null&&(t=Ct(Et(r))),t instanceof Uint8Array?Li(r,t,e):Qf(r,t,e)}function de(r,t=0){return r instanceof Uint8Array?Ci(r,t):Jf(r,t)}var Ri=new Float32Array([-0]),Ae=new Uint8Array(Ri.buffer);function pc(r,t,e){Ri[0]=r,t[e]=Ae[0],t[e+1]=Ae[1],t[e+2]=Ae[2],t[e+3]=Ae[3]}function mc(r,t){return Ae[0]=r[t],Ae[1]=r[t+1],Ae[2]=r[t+2],Ae[3]=r[t+3],Ri[0]}var Di=new Float64Array([-0]),St=new Uint8Array(Di.buffer);function yc(r,t,e){Di[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 gc(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],Di[0]}var th=BigInt(Number.MAX_SAFE_INTEGER),eh=BigInt(Number.MIN_SAFE_INTEGER),kt=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 ke;if(t<th&&t>eh)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>bc&&(o=0n,++n>bc&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return ke;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):ke}},ke=new kt(0,0);ke.toBigInt=function(){return 0n};ke.zzEncode=ke.zzDecode=function(){return this};ke.length=function(){return 1};var bc=4294967296n;function wc(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 xc(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 Pi(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 Zt(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function vn(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var Bi=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,Zt(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 Zt(this,4);return vn(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Zt(this,4);return vn(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Zt(this,4);let t=mc(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw Zt(this,4);let t=gc(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 Zt(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return xc(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw Zt(this,t);this.pos+=t}else do if(this.pos>=this.len)throw Zt(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 kt(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 Zt(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 Zt(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 Zt(this,8);let t=vn(this.buf,this.pos+=4),e=vn(this.buf,this.pos+=4);return new kt(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=Ci(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 Ni(r){return new Bi(r instanceof Uint8Array?r:r.subarray())}function Dt(r,t,e){let n=Ni(r);return t.decode(n,void 0,e)}function Ui(r){let t=r??8192,e=t>>>1,n,o=t;return function(s){if(s<1||s>e)return Ct(s);o+s>t&&(n=Ct(t),o=0);let a=n.subarray(o,o+=s);return(o&7)!==0&&(o=(o|7)+1),a}}var Me=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function Oi(){}var Mi=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},rh=Ui();function nh(r){return globalThis.Buffer!=null?Ct(r):rh(r)}var kr=class{len;head;tail;states;constructor(){this.len=0,this.head=new Me(Oi,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new Me(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new Ki((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(An,10,kt.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=kt.fromBigInt(t);return this._push(An,e.length(),e)}uint64Number(t){return this._push(Li,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=kt.fromBigInt(t).zzEncode();return this._push(An,e.length(),e)}sint64Number(t){let e=kt.fromNumber(t).zzEncode();return this._push(An,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(ki,1,t?1:0)}fixed32(t){return this._push(Or,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=kt.fromBigInt(t);return this._push(Or,4,e.lo)._push(Or,4,e.hi)}fixed64Number(t){let e=kt.fromNumber(t);return this._push(Or,4,e.lo)._push(Or,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(pc,4,t)}double(t){return this._push(yc,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(ki,1,0):this.uint32(e)._push(ih,e,t)}string(t){let e=wc(t);return e!==0?this.uint32(e)._push(Pi,e,t):this._push(ki,1,0)}fork(){return this.states=new Mi(this),this.head=this.tail=new Me(Oi,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 Me(Oi,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=nh(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function ki(r,t,e){t[e]=r&255}function oh(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var Ki=class extends Me{next;constructor(t,e){super(oh,t,e),this.next=void 0}};function An(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 Or(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 ih(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(kr.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(sh,t,r),this},kr.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(ah,t,r),this});function sh(r,t,e){t.set(r,e)}function ah(r,t,e){r.length<40?Pi(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(q(r),e)}function qi(){return new kr}function Pt(r,t){let e=qi();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var ir;(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"})(ir||(ir={}));function _n(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function Ke(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 _n("enum",ir.VARINT,e,n)}function Bt(r,t){return _n("message",ir.LENGTH_DELIMITED,r,t)}var Mr=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var ut;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(ut||(ut={}));var Fi;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(Fi||(Fi={}));(function(r){r.codec=()=>Ke(Fi)})(ut||(ut={}));var re;(function(r){let t;r.codec=()=>(t==null&&(t=Bt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),ut.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=ut.codec().decode(e);break}case 2:{i.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Pt(e,r.codec()),r.decode=(e,n)=>Dt(e,r.codec(),n)})(re||(re={}));var Hi;(function(r){let t;r.codec=()=>(t==null&&(t=Bt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),ut.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=ut.codec().decode(e);break}case 2:{i.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Pt(e,r.codec()),r.decode=(e,n)=>Dt(e,r.codec(),n)})(Hi||(Hi={}));var qr={};Lt(qr,{MAX_RSA_KEY_SIZE:()=>zi,generateRSAKeyPair:()=>Ic,jwkToJWKKeyPair:()=>Tc,jwkToPkcs1:()=>fh,jwkToPkix:()=>$i,jwkToRSAPrivateKey:()=>Xi,pkcs1MessageToJwk:()=>Gi,pkcs1MessageToRSAPrivateKey:()=>Zi,pkcs1ToJwk:()=>lh,pkcs1ToRSAPrivateKey:()=>_c,pkixMessageToJwk:()=>Wi,pkixMessageToRSAPublicKey:()=>ji,pkixToJwk:()=>hh,pkixToRSAPublicKey:()=>Yi});var In=dn;var sr=class{type="RSA";jwk;_raw;_multihash;constructor(t,e){this.jwk=t,this._multihash=e}get raw(){return this._raw==null&&(this._raw=qr.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return st.createV1(114,this._multihash)}toString(){return j.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:dt(this.raw,t.raw)}verify(t,e,n){return Ac(this.jwk,e,t,n)}},Kr=class{type="RSA";jwk;_raw;publicKey;constructor(t,e){this.jwk=t,this.publicKey=e}get raw(){return this._raw==null&&(this._raw=qr.jwkToPkcs1(this.jwk)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:dt(this.raw,t.raw)}sign(t,e){return vc(this.jwk,t,e)}};var zi=8192,Vi=18,ch=1062,uh=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function lh(r){let t=se(r);return Gi(t)}function Gi(r){return{n:k(r[1],"base64url"),e:k(r[2],"base64url"),d:k(r[3],"base64url"),p:k(r[4],"base64url"),q:k(r[5],"base64url"),dp:k(r[6],"base64url"),dq:k(r[7],"base64url"),qi:k(r[8],"base64url"),kty:"RSA"}}function fh(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 be([Rt(Uint8Array.from([0])),Rt(q(r.n,"base64url")),Rt(q(r.e,"base64url")),Rt(q(r.d,"base64url")),Rt(q(r.p,"base64url")),Rt(q(r.q,"base64url")),Rt(q(r.dp,"base64url")),Rt(q(r.dq,"base64url")),Rt(q(r.qi,"base64url"))]).subarray()}function hh(r){let t=se(r,{offset:0});return Wi(t)}function Wi(r){let t=se(r[1],{offset:0});return{kty:"RSA",n:k(t[0],"base64url"),e:k(t[1],"base64url")}}function $i(r){if(r.n==null||r.e==null)throw new ht("JWK was missing components");return be([uh,an(be([Rt(q(r.n,"base64url")),Rt(q(r.e,"base64url"))]))]).subarray()}function _c(r){let t=se(r);return Zi(t)}function Zi(r){let t=Gi(r);return Xi(t)}function Yi(r,t){if(r.byteLength>=ch)throw new Ge("Key size is too large");let e=se(r,{offset:0});return ji(e,r,t)}function ji(r,t,e){let n=Wi(r);if(e==null){let o=In(re.encode({Type:ut.RSA,Data:t}));e=Gt(Vi,o)}return new sr(n,e)}function Xi(r){if(Cc(r)>zi)throw new ht("Key size is too large");let t=Tc(r),e=In(re.encode({Type:ut.RSA,Data:$i(t.publicKey)})),n=Gt(Vi,e);return new Kr(t.privateKey,new sr(t.publicKey,n))}async function Ic(r){if(r>zi)throw new ht("Key size is too large");let t=await Lc(r),e=In(re.encode({Type:ut.RSA,Data:$i(t.publicKey)})),n=Gt(Vi,e);return new Kr(t.privateKey,new sr(t.publicKey,n))}function Tc(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 Lc(r,t){let e=await Ft.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);t?.signal?.throwIfAborted();let n=await dh(e,t);return{privateKey:n[0],publicKey:n[1]}}async function vc(r,t,e){let n=await Ft.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);e?.signal?.throwIfAborted();let o=await Ft.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,t instanceof Uint8Array?t:t.subarray());return e?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function Ac(r,t,e,n){let o=await Ft.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let i=await Ft.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,t,e instanceof Uint8Array?e:e.subarray());return n?.signal?.throwIfAborted(),i}async function dh(r,t){if(r.privateKey==null||r.publicKey==null)throw new ht("Private and public key are required");let e=await Promise.all([Ft.get().subtle.exportKey("jwk",r.privateKey),Ft.get().subtle.exportKey("jwk",r.publicKey)]);return t?.signal?.throwIfAborted(),e}function Cc(r){if(r.kty!=="RSA")throw new ht("invalid key type");if(r.n==null)throw new ht("invalid key modulus");return q(r.n,"base64url").length*8}var Tn=class extends Je{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,Ia(t);let n=Lr(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),ae(i)}update(t){return tr(this),this.iHash.update(t),this}digestInto(t){tr(this),Re(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}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Qi=(r,t,e)=>new Tn(r,t).update(e).digest();Qi.create=(r,t)=>new Tn(r,t);function Rc(r){r.lowS!==void 0&&te("lowS",r.lowS),r.prehash!==void 0&&te("prehash",r.prehash)}function ph(r){let t=Nr(r);fe(t,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});let{endo:e,Fp:n,a:o}=t;if(e){if(!n.eql(o,n.ZERO))throw new Error("invalid endo: CURVE.a must be 0");if(typeof e!="object"||typeof e.beta!="bigint"||typeof e.splitScalar!="function")throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function')}return Object.freeze({...t})}var es=class extends Error{constructor(t=""){super(t)}},pe={Err:es,_tlv:{encode:(r,t)=>{let{Err:e}=pe;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=Pr(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let i=n>127?Pr(o.length/2|128):"";return Pr(r)+i+o+t},decode(r,t){let{Err:e}=pe,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}=pe;if(r<me)throw new t("integer: negative integers are not allowed");let e=Pr(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}=pe;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 le(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=pe,o=rt("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}=pe,n=t.encode(2,e.encode(r.r)),o=t.encode(2,e.encode(r.s)),i=n+o;return t.encode(48,i)}};function Ji(r,t){return Se(Ne(r,t))}var me=BigInt(0),yt=BigInt(1),By=BigInt(2),ts=BigInt(3),mh=BigInt(4);function yh(r){let t=ph(r),{Fp:e}=t,n=he(t.n,t.nBitLength),o=t.toBytes||((E,h,w)=>{let I=h.toAffine();return ve(Uint8Array.from([4]),e.toBytes(I.x),e.toBytes(I.y))}),i=t.fromBytes||(E=>{let h=E.subarray(1),w=e.fromBytes(h.subarray(0,e.BYTES)),I=e.fromBytes(h.subarray(e.BYTES,2*e.BYTES));return{x:w,y:I}});function s(E){let{a:h,b:w}=t,I=e.sqr(E),T=e.mul(I,E);return e.add(e.add(T,e.mul(E,h)),w)}function a(E,h){let w=e.sqr(h),I=s(E);return e.eql(w,I)}if(!a(t.Gx,t.Gy))throw new Error("bad curve params: generator point");let c=e.mul(e.pow(t.a,ts),mh),l=e.mul(e.sqr(t.b),BigInt(27));if(e.is0(e.add(c,l)))throw new Error("bad curve params: a or b");function u(E){return pn(E,yt,t.n)}function f(E){let{allowedPrivateKeyLengths:h,nByteLength:w,wrapPrivateKey:I,n:T}=t;if(h&&typeof E!="bigint"){if(er(E)&&(E=Se(E)),typeof E!="string"||!h.includes(E.length))throw new Error("invalid private key");E=E.padStart(w*2,"0")}let L;try{L=typeof E=="bigint"?E:le(rt("private key",E,w))}catch{throw new Error("invalid private key, expected hex or "+w+" bytes, got "+typeof E)}return I&&(L=J(L,T)),Ot("private key",L,yt,T),L}function p(E){if(!(E instanceof m))throw new Error("ProjectivePoint expected")}let b=nr((E,h)=>{let{px:w,py:I,pz:T}=E;if(e.eql(T,e.ONE))return{x:w,y:I};let L=E.is0();h==null&&(h=L?e.ONE:e.inv(T));let N=e.mul(w,h),K=e.mul(I,h),D=e.mul(T,h);if(L)return{x:e.ZERO,y:e.ZERO};if(!e.eql(D,e.ONE))throw new Error("invZ was invalid");return{x:N,y:K}}),g=nr(E=>{if(E.is0()){if(t.allowInfinityPoint&&!e.is0(E.py))return;throw new Error("bad point: ZERO")}let{x:h,y:w}=E.toAffine();if(!e.isValid(h)||!e.isValid(w))throw new Error("bad point: x or y not FE");if(!a(h,w))throw new Error("bad point: equation left != right");if(!E.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class m{constructor(h,w,I){if(h==null||!e.isValid(h))throw new Error("x required");if(w==null||!e.isValid(w)||e.is0(w))throw new Error("y required");if(I==null||!e.isValid(I))throw new Error("z required");this.px=h,this.py=w,this.pz=I,Object.freeze(this)}static fromAffine(h){let{x:w,y:I}=h||{};if(!h||!e.isValid(w)||!e.isValid(I))throw new Error("invalid affine point");if(h instanceof m)throw new Error("projective point not allowed");let T=L=>e.eql(L,e.ZERO);return T(w)&&T(I)?m.ZERO:new m(w,I,e.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(h){let w=or(e,h.map(I=>I.pz));return h.map((I,T)=>I.toAffine(w[T])).map(m.fromAffine)}static fromHex(h){let w=m.fromAffine(i(rt("pointHex",h)));return w.assertValidity(),w}static fromPrivateKey(h){return m.BASE.multiply(f(h))}static msm(h,w){return gn(m,n,h,w)}_setWindowSize(h){V.setWindowSize(this,h)}assertValidity(){g(this)}hasEvenY(){let{y:h}=this.toAffine();if(e.isOdd)return!e.isOdd(h);throw new Error("Field doesn't support isOdd")}equals(h){p(h);let{px:w,py:I,pz:T}=this,{px:L,py:N,pz:K}=h,D=e.eql(e.mul(w,K),e.mul(L,T)),U=e.eql(e.mul(I,K),e.mul(N,T));return D&&U}negate(){return new m(this.px,e.neg(this.py),this.pz)}double(){let{a:h,b:w}=t,I=e.mul(w,ts),{px:T,py:L,pz:N}=this,K=e.ZERO,D=e.ZERO,U=e.ZERO,B=e.mul(T,T),lt=e.mul(L,L),v=e.mul(N,N),S=e.mul(T,L);return S=e.add(S,S),U=e.mul(T,N),U=e.add(U,U),K=e.mul(h,U),D=e.mul(I,v),D=e.add(K,D),K=e.sub(lt,D),D=e.add(lt,D),D=e.mul(K,D),K=e.mul(S,K),U=e.mul(I,U),v=e.mul(h,v),S=e.sub(B,v),S=e.mul(h,S),S=e.add(S,U),U=e.add(B,B),B=e.add(U,B),B=e.add(B,v),B=e.mul(B,S),D=e.add(D,B),v=e.mul(L,N),v=e.add(v,v),B=e.mul(v,S),K=e.sub(K,B),U=e.mul(v,lt),U=e.add(U,U),U=e.add(U,U),new m(K,D,U)}add(h){p(h);let{px:w,py:I,pz:T}=this,{px:L,py:N,pz:K}=h,D=e.ZERO,U=e.ZERO,B=e.ZERO,lt=t.a,v=e.mul(t.b,ts),S=e.mul(w,L),R=e.mul(I,N),x=e.mul(T,K),d=e.add(w,I),y=e.add(L,N);d=e.mul(d,y),y=e.add(S,R),d=e.sub(d,y),y=e.add(w,T);let A=e.add(L,K);return y=e.mul(y,A),A=e.add(S,x),y=e.sub(y,A),A=e.add(I,T),D=e.add(N,K),A=e.mul(A,D),D=e.add(R,x),A=e.sub(A,D),B=e.mul(lt,y),D=e.mul(v,x),B=e.add(D,B),D=e.sub(R,B),B=e.add(R,B),U=e.mul(D,B),R=e.add(S,S),R=e.add(R,S),x=e.mul(lt,x),y=e.mul(v,y),R=e.add(R,x),x=e.sub(S,x),x=e.mul(lt,x),y=e.add(y,x),S=e.mul(R,y),U=e.add(U,S),S=e.mul(A,y),D=e.mul(d,D),D=e.sub(D,S),S=e.mul(d,R),B=e.mul(A,B),B=e.add(B,S),new m(D,U,B)}subtract(h){return this.add(h.negate())}is0(){return this.equals(m.ZERO)}wNAF(h){return V.wNAFCached(this,h,m.normalizeZ)}multiplyUnsafe(h){let{endo:w,n:I}=t;Ot("scalar",h,me,I);let T=m.ZERO;if(h===me)return T;if(this.is0()||h===yt)return this;if(!w||V.hasPrecomputes(this))return V.wNAFCachedUnsafe(this,h,m.normalizeZ);let{k1neg:L,k1:N,k2neg:K,k2:D}=w.splitScalar(h),U=T,B=T,lt=this;for(;N>me||D>me;)N&yt&&(U=U.add(lt)),D&yt&&(B=B.add(lt)),lt=lt.double(),N>>=yt,D>>=yt;return L&&(U=U.negate()),K&&(B=B.negate()),B=new m(e.mul(B.px,w.beta),B.py,B.pz),U.add(B)}multiply(h){let{endo:w,n:I}=t;Ot("scalar",h,yt,I);let T,L;if(w){let{k1neg:N,k1:K,k2neg:D,k2:U}=w.splitScalar(h),{p:B,f:lt}=this.wNAF(K),{p:v,f:S}=this.wNAF(U);B=V.constTimeNegate(N,B),v=V.constTimeNegate(D,v),v=new m(e.mul(v.px,w.beta),v.py,v.pz),T=B.add(v),L=lt.add(S)}else{let{p:N,f:K}=this.wNAF(h);T=N,L=K}return m.normalizeZ([T,L])[0]}multiplyAndAddUnsafe(h,w,I){let T=m.BASE,L=(K,D)=>D===me||D===yt||!K.equals(T)?K.multiplyUnsafe(D):K.multiply(D),N=L(this,w).add(L(h,I));return N.is0()?void 0:N}toAffine(h){return b(this,h)}isTorsionFree(){let{h,isTorsionFree:w}=t;if(h===yt)return!0;if(w)return w(m,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h,clearCofactor:w}=t;return h===yt?this:w?w(m,this):this.multiplyUnsafe(t.h)}toRawBytes(h=!0){return te("isCompressed",h),this.assertValidity(),o(m,this,h)}toHex(h=!0){return te("isCompressed",h),Se(this.toRawBytes(h))}}m.BASE=new m(t.Gx,t.Gy,e.ONE),m.ZERO=new m(e.ZERO,e.ONE,e.ZERO);let{endo:_,nBitLength:C}=t,V=yn(m,_?Math.ceil(C/2):C);return{CURVE:t,ProjectivePoint:m,normPrivateKeyToScalar:f,weierstrassEquation:s,isWithinCurveOrder:u}}function gh(r){let t=Nr(r);return fe(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function Dc(r){let t=gh(r),{Fp:e,n,nByteLength:o,nBitLength:i}=t,s=e.BYTES+1,a=2*e.BYTES+1;function c(v){return J(v,n)}function l(v){return mn(v,n)}let{ProjectivePoint:u,normPrivateKeyToScalar:f,weierstrassEquation:p,isWithinCurveOrder:b}=yh({...t,toBytes(v,S,R){let x=S.toAffine(),d=e.toBytes(x.x),y=ve;return te("isCompressed",R),R?y(Uint8Array.from([S.hasEvenY()?2:3]),d):y(Uint8Array.from([4]),d,e.toBytes(x.y))},fromBytes(v){let S=v.length,R=v[0],x=v.subarray(1);if(S===s&&(R===2||R===3)){let d=le(x);if(!pn(d,yt,e.ORDER))throw new Error("Point is not on curve");let y=p(d),A;try{A=e.sqrt(y)}catch(z){let G=z instanceof Error?": "+z.message:"";throw new Error("Point is not on curve"+G)}let P=(A&yt)===yt;return(R&1)===1!==P&&(A=e.neg(A)),{x:d,y:A}}else if(S===a&&R===4){let d=e.fromBytes(x.subarray(0,e.BYTES)),y=e.fromBytes(x.subarray(e.BYTES,2*e.BYTES));return{x:d,y}}else{let d=s,y=a;throw new Error("invalid Point, expected length of "+d+", or uncompressed "+y+", got "+S)}}});function g(v){let S=n>>yt;return v>S}function m(v){return g(v)?c(-v):v}let _=(v,S,R)=>le(v.slice(S,R));class C{constructor(S,R,x){Ot("r",S,yt,n),Ot("s",R,yt,n),this.r=S,this.s=R,x!=null&&(this.recovery=x),Object.freeze(this)}static fromCompact(S){let R=o;return S=rt("compactSignature",S,R*2),new C(_(S,0,R),_(S,R,2*R))}static fromDER(S){let{r:R,s:x}=pe.toSig(rt("DER",S));return new C(R,x)}assertValidity(){}addRecoveryBit(S){return new C(this.r,this.s,S)}recoverPublicKey(S){let{r:R,s:x,recovery:d}=this,y=T(rt("msgHash",S));if(d==null||![0,1,2,3].includes(d))throw new Error("recovery id invalid");let A=d===2||d===3?R+t.n:R;if(A>=e.ORDER)throw new Error("recovery id 2 or 3 invalid");let P=(d&1)===0?"02":"03",O=u.fromHex(P+Ji(A,e.BYTES)),z=l(A),G=c(-y*z),W=c(x*z),Y=u.BASE.multiplyAndAddUnsafe(O,G,W);if(!Y)throw new Error("point at infinify");return Y.assertValidity(),Y}hasHighS(){return g(this.s)}normalizeS(){return this.hasHighS()?new C(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return Br(this.toDERHex())}toDERHex(){return pe.hexFromSig(this)}toCompactRawBytes(){return Br(this.toCompactHex())}toCompactHex(){let S=o;return Ji(this.r,S)+Ji(this.s,S)}}let V={isValidPrivateKey(v){try{return f(v),!0}catch{return!1}},normPrivateKeyToScalar:f,randomPrivateKey:()=>{let v=pi(t.n);return tc(t.randomBytes(v),t.n)},precompute(v=8,S=u.BASE){return S._setWindowSize(v),S.multiply(BigInt(3)),S}};function E(v,S=!0){return u.fromPrivateKey(v).toRawBytes(S)}function h(v){if(typeof v=="bigint")return!1;if(v instanceof u)return!0;let R=rt("key",v).length,x=e.BYTES,d=x+1,y=2*x+1;if(!(t.allowedPrivateKeyLengths||o===d))return R===d||R===y}function w(v,S,R=!0){if(h(v)===!0)throw new Error("first arg must be private key");if(h(S)===!1)throw new Error("second arg must be public key");return u.fromHex(S).multiply(f(v)).toRawBytes(R)}let I=t.bits2int||function(v){if(v.length>8192)throw new Error("input is too large");let S=le(v),R=v.length*8-i;return R>0?S>>BigInt(R):S},T=t.bits2int_modN||function(v){return c(I(v))},L=Ue(i);function N(v){return Ot("num < 2^"+i,v,me,L),Ne(v,o)}function K(v,S,R=D){if(["recovered","canonical"].some(at=>at in R))throw new Error("sign() legacy options not supported");let{hash:x,randomBytes:d}=t,{lowS:y,prehash:A,extraEntropy:P}=R;y==null&&(y=!0),v=rt("msgHash",v),Rc(R),A&&(v=rt("prehashed msgHash",x(v)));let O=T(v),z=f(S),G=[N(z),N(O)];if(P!=null&&P!==!1){let at=P===!0?d(e.BYTES):P;G.push(rt("extraEntropy",at))}let W=ve(...G),Y=O;function ft(at){let gt=I(at);if(!b(gt))return;let Tt=l(gt),pt=u.BASE.multiply(gt).toAffine(),wt=c(pt.x);if(wt===me)return;let Nt=c(Tt*c(Y+wt*z));if(Nt===me)return;let Vt=(pt.x===wt?0:2)|Number(pt.y&yt),wr=Nt;return y&&g(Nt)&&(wr=m(Nt),Vt^=1),new C(wt,wr,Vt)}return{seed:W,k2sig:ft}}let D={lowS:t.lowS,prehash:!1},U={lowS:t.lowS,prehash:!1};function B(v,S,R=D){let{seed:x,k2sig:d}=K(v,S,R),y=t;return Wa(y.hash.outputLen,y.nByteLength,y.hmac)(x,d)}u.BASE._setWindowSize(8);function lt(v,S,R,x=U){let d=v;S=rt("msgHash",S),R=rt("publicKey",R);let{lowS:y,prehash:A,format:P}=x;if(Rc(x),"strict"in x)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 d=="string"||er(d),z=!O&&!P&&typeof d=="object"&&d!==null&&typeof d.r=="bigint"&&typeof d.s=="bigint";if(!O&&!z)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let G,W;try{if(z&&(G=new C(d.r,d.s)),O){try{P!=="compact"&&(G=C.fromDER(d))}catch(Vt){if(!(Vt instanceof pe.Err))throw Vt}!G&&P!=="der"&&(G=C.fromCompact(d))}W=u.fromHex(R)}catch{return!1}if(!G||y&&G.hasHighS())return!1;A&&(S=t.hash(S));let{r:Y,s:ft}=G,at=T(S),gt=l(ft),Tt=c(at*gt),pt=c(Y*gt),wt=u.BASE.multiplyAndAddUnsafe(W,Tt,pt)?.toAffine();return wt?c(wt.x)===Y:!1}return{CURVE:t,getPublicKey:E,getSharedSecret:w,sign:B,verify:lt,ProjectivePoint:u,Signature:C,utils:V}}function bh(r){return{hash:r,hmac:(t,...e)=>Qi(r,t,ri(...e)),randomBytes:ln}}function Pc(r,t){let e=n=>Dc({...r,...bh(n)});return{...e(t),create:e}}var Uc=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Bc=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),wh=BigInt(0),xh=BigInt(1),rs=BigInt(2),Nc=(r,t)=>(r+t/rs)/t;function Eh(r){let t=Uc,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,p=nt(f,e,t)*u%t,b=nt(p,rs,t)*l%t,g=nt(b,o,t)*b%t,m=nt(g,i,t)*g%t,_=nt(m,a,t)*m%t,C=nt(_,c,t)*_%t,V=nt(C,a,t)*m%t,E=nt(V,e,t)*u%t,h=nt(E,s,t)*g%t,w=nt(h,n,t)*l%t,I=nt(w,rs,t);if(!ns.eql(ns.sqr(I),r))throw new Error("Cannot find square root");return I}var ns=he(Uc,void 0,void 0,{sqrt:Eh}),ar=Pc({a:wh,b:BigInt(7),Fp:ns,n:Bc,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let t=Bc,e=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-xh*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=e,s=BigInt("0x100000000000000000000000000000000"),a=Nc(i*r,t),c=Nc(-n*r,t),l=J(r-a*e-c*o,t),u=J(-a*n-c*i,t),f=l>s,p=u>s;if(f&&(l=t-l),p&&(u=t-u),l>s||u>s)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:f,k1:l,k2neg:p,k2:u}}}},dn);function Oc(r,t,e,n){let o=Xe.digest(e instanceof Uint8Array?e:e.subarray());if(xn(o))return o.then(({digest:i})=>(n?.signal?.throwIfAborted(),ar.verify(t,i,r))).catch(i=>{throw i.name==="AbortError"?i:new Ur(String(i))});try{return n?.signal?.throwIfAborted(),ar.verify(t,o.digest,r)}catch(i){throw new Ur(String(i))}}var Ln=class{type="secp256k1";raw;_key;constructor(t){this._key=Mc(t),this.raw=kc(this._key)}toMultihash(){return Wt.digest(Qt(this))}toCID(){return st.createV1(114,this.toMultihash())}toString(){return j.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:dt(this.raw,t.raw)}verify(t,e,n){return Oc(this._key,e,t,n)}};function os(r){return new Ln(r)}function kc(r){return ar.ProjectivePoint.fromHex(r).toRawBytes(!0)}function Mc(r){try{return ar.ProjectivePoint.fromHex(r),r}catch(t){throw new Ge(String(t))}}function Kc(r,t){let{Type:e,Data:n}=re.decode(r),o=n??new Uint8Array;switch(e){case ut.RSA:return Yi(o,t);case ut.Ed25519:return vi(o);case ut.secp256k1:return os(o);case ut.ECDSA:return ei(o);default:throw new We}}function qc(r){let{Type:t,Data:e}=re.decode(r.digest),n=e??new Uint8Array;switch(t){case ut.Ed25519:return vi(n);case ut.secp256k1:return os(n);case ut.ECDSA:return ei(n);default:throw new We}}function Qt(r){return re.encode({Type:ut[r.type],Data:r.raw})}var Fc=Symbol.for("nodejs.util.inspect.custom"),Sh=114,Fr=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()})`}[Io]=!0;toString(){return this.string==null&&(this.string=j.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return st.createV1(Sh,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")}[Fc](){return`PeerId(${this.toString()})`}},Cn=class extends Fr{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},Rn=class extends Fr{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},Dn=class extends Fr{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},vh=2336,Hr=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=Wt.digest(q(this.url))}[Fc](){return`PeerId(${this.url})`}[Io]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return st.createV1(vh,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=k(t)),t.toString()===this.toString())}};var Ah=114,Hc=2336;function is(r,t){let e;if(r.charAt(0)==="1"||r.charAt(0)==="Q")e=qt(j.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return _h(st.parse(r));if(t==null)throw new ht('Please pass a multibase decoder for strings that do not start with "1" or "Q"');e=qt(t.decode(r))}return cr(e)}function cr(r){if(Th(r))return new Cn({multihash:r});if(Ih(r))try{let t=qc(r);if(t.type==="Ed25519")return new Rn({multihash:r,publicKey:t});if(t.type==="secp256k1")return new Dn({multihash:r,publicKey:t})}catch{let e=k(r.digest);return new Hr(new URL(e))}throw new en("Supplied PeerID Multihash is invalid")}function _h(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==Ah&&r.code!==Hc)throw new tn("Supplied PeerID CID is invalid");if(r.code===Hc){let t=k(r.multihash.digest);return new Hr(new URL(t))}return cr(r.multihash)}function Ih(r){return r.code===Wt.code}function Th(r){return r.code===Xe.code}var zr;(function(r){let t;r.codec=()=>(t==null&&(t=Bt((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=>Pt(e,r.codec()),r.decode=(e,n)=>Dt(e,r.codec(),n)})(zr||(zr={}));var Pn=class extends Error{constructor(t="Invalid signature"){super(t),this.name="InvalidSignatureError"}};var Vr=class r{static createFromProtobuf=t=>{let e=zr.decode(t),n=Kc(e.publicKey);return new r({publicKey:n,payloadType:e.payloadType,payload:e.payload,signature:e.signature})};static seal=async(t,e,n)=>{if(e==null)throw new Error("Missing private key");let o=t.domain,i=t.codec,s=t.marshal(),a=zc(o,i,s),c=await e.sign(a.subarray(),n);return new r({publicKey:e.publicKey,payloadType:i,payload:s,signature:c})};static openAndCertify=async(t,e,n)=>{let o=r.createFromProtobuf(t);if(!await o.validate(e,n))throw new Pn("Envelope signature is not valid for the given domain");return o};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=zr.encode({publicKey:Qt(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(t){return t==null?!1:dt(this.marshal(),t.marshal())}async validate(t,e){let n=zc(t,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,e)}},zc=(r,t,e)=>{let n=q(r),o=Ht(n.byteLength),i=Ht(t.length),s=Ht(e.length);return new ct(o,n,i,t,s,e)};var Bn=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 p=Number.parseInt(f,t);if(!Number.isNaN(p))return p});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 Vc=45,Lh=15,ur=new Bn;function ss(r){if(!(r.length>Lh))return ur.new(r).parseWith(()=>ur.readIPv4Addr())}function as(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Vc))return ur.new(r).parseWith(()=>ur.readIPv6Addr())}function Nn(r,t=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>Vc)return;let e=ur.new(r).parseWith(()=>ur.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 ub=parseInt("0xFFFF",16),lb=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Un(r){return!!ss(r)}function On(r){return!!as(r)}function kn(r){return!!Nn(r)}var $c=Un,Bh=On,cs=function(r){let t=0;if(r=r.toString().trim(),$c(r)){let e=new Uint8Array(t+4);return r.split(/\./g).forEach(n=>{e[t++]=parseInt(n,10)&255}),e}if(Bh(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let i=$c(e[n]),s;i&&(s=cs(e[n]),e[n]=k(s.slice(0,2),"base16")),s!=null&&++n<8&&e.splice(n,0,k(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")},Zc=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 lr={},us={},Uh=[[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"]];Uh.forEach(r=>{let t=Oh(...r);us[t.code]=t,lr[t.name]=t});function Oh(r,t,e,n,o){return{code:r,size:t,name:e,resolvable:!!n,path:!!o}}function tt(r){if(typeof r=="number"){if(us[r]!=null)return us[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(lr[r]!=null)return lr[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var $b=tt("ip4"),Zb=tt("ip6"),Yb=tt("ipcidr");function ds(r,t){switch(tt(r).code){case 4:case 41:return Mh(t);case 42:return hs(t);case 43:return k(t,"base10");case 6:case 273:case 33:case 132:return Xc(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return hs(t);case 421:return Hh(t);case 444:return jc(t);case 445:return jc(t);case 466:return Fh(t);case 481:return globalThis.encodeURIComponent(hs(t));default:return k(t,"base16")}}function ps(r,t){switch(tt(r).code){case 4:return Yc(t);case 41:return Yc(t);case 42:return fs(t);case 43:return q(t,"base10");case 6:case 273:case 33:case 132:return ms(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return fs(t);case 421:return Kh(t);case 444:return zh(t);case 445:return Vh(t);case 466:return qh(t);case 481:return fs(globalThis.decodeURIComponent(t));default:return q(t,"base16")}}var ls=Object.values(_r).map(r=>r.decoder),kh=function(){let r=ls[0].or(ls[1]);return ls.slice(2).forEach(t=>r=r.or(t)),r}();function Yc(r){if(!kn(r))throw new Error("invalid ip address");return cs(r)}function Mh(r){let t=Zc(r,0,r.length);if(t==null)throw new Error("ipBuff is required");if(!kn(t))throw new Error("invalid ip address");return t}function ms(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,r),new Uint8Array(t)}function Xc(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function fs(r){let t=q(r),e=Uint8Array.from(Ht(t.length));return Ut([e,t],e.length+t.length)}function hs(r){let t=de(r);if(r=r.slice(Et(t)),r.length!==t)throw new Error("inconsistent lengths");return k(r)}function Kh(r){let t;r[0]==="Q"||r[0]==="1"?t=qt(j.decode(`z${r}`)).bytes:t=st.parse(r).multihash.bytes;let e=Uint8Array.from(Ht(t.length));return Ut([e,t],e.length+t.length)}function qh(r){let t=kh.decode(r),e=Uint8Array.from(Ht(t.length));return Ut([e,t],e.length+t.length)}function Fh(r){let t=de(r),e=r.slice(Et(t));if(e.length!==t)throw new Error("inconsistent lengths");return"u"+k(e,"base64url")}function Hh(r){let t=de(r),e=r.slice(Et(t));if(e.length!==t)throw new Error("inconsistent lengths");return k(e,"base58btc")}function zh(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=ie.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=ms(n);return Ut([e,o],e.length+o.length)}function Vh(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=ie.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=ms(n);return Ut([e,o],e.length+o.length)}function jc(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=k(t,"base32"),o=Xc(e);return`${n}:${o}`}function Qc(r){r=ys(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=tt(s);if(a.size===0){t.push([a.code]),e.push([a.code]);continue}if(i++,i>=o.length)throw new Mn("invalid address: "+r);if(a.path===!0){n=ys(o.slice(i).join("/")),t.push([a.code,ps(a.code,n)]),e.push([a.code,n]);break}let c=ps(a.code,o[i]);t.push([a.code,c]),e.push([a.code,ds(a.code,c)])}return{string:Jc(e),bytes:Kn(t),tuples:t,stringTuples:e,path:n}}function gs(r){let t=[],e=[],n=null,o=0;for(;o<r.length;){let i=de(r,o),s=Et(i),a=tt(i),c=Gh(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 Mn("Invalid address Uint8Array: "+k(r,"base16"));t.push([i,l]);let u=ds(i,l);if(e.push([i,u]),a.path===!0){n=u;break}}return{bytes:Uint8Array.from(r),string:Jc(e),tuples:t,stringTuples:e,path:n}}function Jc(r){let t=[];return r.map(e=>{let n=tt(e[0]);return t.push(n.name),e.length>1&&e[1]!=null&&t.push(e[1]),null}),ys(t.join("/"))}function Kn(r){return Ut(r.map(t=>{let e=tt(t[0]),n=Uint8Array.from(Ht(e.code));return t.length>1&&t[1]!=null&&(n=Ut([n,t[1]])),n}))}function Gh(r,t){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let e=de(t instanceof Uint8Array?t:Uint8Array.from(t));return e+Et(e)}}function ys(r){return"/"+r.trim().split("/").filter(t=>t).join("/")}var Mn=class extends Error{static name="ParseError";name="ParseError";constructor(t){super(`Error parsing address: ${t}`)}};var Wh=Symbol.for("nodejs.util.inspect.custom"),ws=Symbol.for("@multiformats/js-multiaddr/multiaddr"),$h=[tt("dns").code,tt("dns4").code,tt("dns6").code,tt("dnsaddr").code],bs=class extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}},qn=class r{bytes;#t;#e;#r;#n;[ws]=!0;constructor(t){t==null&&(t="");let e;if(t instanceof Uint8Array)e=gs(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=Qc(t)}else if(eu(t))e=gs(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=tt("tcp"),a=tt("udp"),c=tt("ip4"),l=tt("ip6"),u=tt("dns6"),f=tt("ip6zone");for(let[b,g]of this.stringTuples())b===f.code&&(i=`%${g??""}`),$h.includes(b)&&(e=s.name==="tcp"?"tcp":"udp",o=443,n=`${g??""}${i}`,t=b===u.code?6:4),(b===s.code||b===a.code)&&(e=tt(b).name==="tcp"?"tcp":"udp",o=parseInt(g??"")),(b===c.code||b===l.code)&&(e=tt(b).name==="tcp"?"tcp":"udp",n=`${g??""}${i}`,t=b===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({},tt(t)))}protoCodes(){return this.#e.map(([t])=>t)}protoNames(){return this.#e.map(([t])=>tt(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(Kn(e.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,o])=>{n===lr.p2p.code&&t.push([n,o]),n===lr["p2p-circuit"].code&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?k(j.decode(`z${n}`),"base58btc"):k(st.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=tu.get(e.name);if(n==null)throw new bs(`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)}[Wh](){return`Multiaddr(${this.#t})`}};var tu=new Map;function eu(r){return!!r?.[ws]}function vt(r){return new qn(r)}function Yt(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var Fn=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 qe(r,t,e){if(t==null)return r;if(t.aborted)return r.catch(()=>{}),Promise.reject(new Fn(e?.errorMessage,e?.errorCode,e?.errorName));let n,o=new Fn(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 xs=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=Yt(),this.haveNext=Yt()}[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=Yt(),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=Yt(),await qe(this.readNext.promise,e?.signal,e)}};function Hn(){return new xs}var zn=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function ru(r,t){let e=Hn();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=>{if(s?.signal?.throwIfAborted(),s?.bytes==null){let{done:c,value:l}=await qe(n.next(),s?.signal);return c===!0?null:l}for(;o.byteLength<s.bytes;){let{value:c,done:l}=await qe(n.next(),s?.signal);if(l===!0)throw new zn("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 Vn=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Gn=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Wn=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function nu(r,t={}){let e=ru(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=Et(t.maxDataLength));let n=t?.lengthDecoder??de,o=t?.lengthEncoder??Ht;return{read:async s=>{let a=-1,c=new ct;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 Vn("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new Wn("message length length too long");if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new Gn("message length too long");return e.read({...s,bytes:a})},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 _e(r,t){let e=nu(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 Es=1e3,ou=60*Es,$n=290,iu=15,su=2*60*ou,au=1,Zn=2e3,cu=100,Ss="circuit-relay-source",Gr=`${To}-circuit-relay`,vs=`${To}-circuit-relay-source`,uu=2*ou,lu=BigInt(1<<17),zt="/libp2p/circuit/relay/0.2.0/hop",Fe="/libp2p/circuit/relay/0.2.0/stop",fu=30*Es,Hw=30*Es,Wr=300,hu=4096,du=.001;var X;(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=()=>Ke(e)}(t=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Bt((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),fr.codec().encode(o.peer,i)),o.reservation!=null&&(i.uint32(26),Yn.codec().encode(o.reservation,i)),o.limit!=null&&(i.uint32(34),hr.codec().encode(o.limit,i)),o.status!=null&&(i.uint32(40),H.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=fr.codec().decode(o,o.uint32(),{limits:s.limits?.peer});break}case 3:{a.reservation=Yn.codec().decode(o,o.uint32(),{limits:s.limits?.reservation});break}case 4:{a.limit=hr.codec().decode(o,o.uint32(),{limits:s.limits?.limit});break}case 5:{a.status=H.codec().decode(o);break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>Pt(o,r.codec()),r.decode=(o,i)=>Dt(o,r.codec(),i)})(X||(X={}));var Mt;(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=()=>Ke(e)}(t=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Bt((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),fr.codec().encode(o.peer,i)),o.limit!=null&&(i.uint32(26),hr.codec().encode(o.limit,i)),o.status!=null&&(i.uint32(32),H.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=fr.codec().decode(o,o.uint32(),{limits:s.limits?.peer});break}case 3:{a.limit=hr.codec().decode(o,o.uint32(),{limits:s.limits?.limit});break}case 4:{a.status=H.codec().decode(o);break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>Pt(o,r.codec()),r.decode=(o,i)=>Dt(o,r.codec(),i)})(Mt||(Mt={}));var fr;(function(r){let t;r.codec=()=>(t==null&&(t=Bt((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 Mr('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=>Pt(e,r.codec()),r.decode=(e,n)=>Dt(e,r.codec(),n)})(fr||(fr={}));var Yn;(function(r){let t;r.codec=()=>(t==null&&(t=Bt((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),jn.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 Mr('Decode error - map field "addrs" had too many elements');i.addrs.push(e.bytes());break}case 3:{i.voucher=jn.codec().decode(e,e.uint32(),{limits:o.limits?.voucher});break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Pt(e,r.codec()),r.decode=(e,n)=>Dt(e,r.codec(),n)})(Yn||(Yn={}));var hr;(function(r){let t;r.codec=()=>(t==null&&(t=Bt((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=>Pt(e,r.codec()),r.decode=(e,n)=>Dt(e,r.codec(),n)})(hr||(hr={}));var H;(function(r){r.UNUSED="UNUSED",r.OK="OK",r.RESERVATION_REFUSED="RESERVATION_REFUSED",r.RESOURCE_LIMIT_EXCEEDED="RESOURCE_LIMIT_EXCEEDED",r.PERMISSION_DENIED="PERMISSION_DENIED",r.CONNECTION_FAILED="CONNECTION_FAILED",r.NO_RESERVATION="NO_RESERVATION",r.MALFORMED_MESSAGE="MALFORMED_MESSAGE",r.UNEXPECTED_MESSAGE="UNEXPECTED_MESSAGE"})(H||(H={}));var 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=()=>Ke(As)})(H||(H={}));var dr;(function(r){let t;r.codec=()=>(t==null&&(t=Bt((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=>Pt(e,r.codec()),r.decode=(e,n)=>Dt(e,r.codec(),n)})(dr||(dr={}));var jn;(function(r){let t;r.codec=()=>(t==null&&(t=Bt((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),dr.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=dr.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=>Pt(e,r.codec()),r.decode=(e,n)=>Dt(e,r.codec(),n)})(jn||(jn={}));var Zh=r=>r.toString().split("/").slice(1),pr=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),M=r=>({match:t=>pr(e=>e===r).match(t),pattern:r}),He=()=>({match:r=>pr(t=>typeof t=="string").match(r),pattern:"{string}"}),mr=()=>({match:r=>pr(t=>!isNaN(parseInt(t))).match(r),pattern:"{number}"}),Q=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{j.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),$r=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{Ho.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),$=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 et(...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 Yh=Q(),Qw=et(Yh),Qn=F(M("dns4"),He()),Jn=F(M("dns6"),He()),to=F(M("dnsaddr"),He()),Is=F(M("dns"),He()),Jw=et(Qn,$(Q())),tx=et(Jn,$(Q())),ex=et(to,$(Q())),rx=et(At(Is,to,Qn,Jn),$(Q())),pu=F(M("ip4"),pr(Un)),mu=F(M("ip6"),pr(On)),Ts=At(pu,mu),ye=At(Ts,Is,Qn,Jn,to),nx=et(At(Ts,F(At(Is,to,Qn,Jn),$(Q())))),ox=et(pu),ix=et(mu),sx=et(Ts),Ls=F(ye,M("tcp"),mr()),Zr=F(ye,M("udp"),mr()),ax=et(F(Ls,$(Q()))),cx=et(Zr),Cs=F(Zr,M("quic"),$(Q())),eo=F(Zr,M("quic-v1"),$(Q())),jh=At(Cs,eo),ux=et(Cs),lx=et(eo),_s=At(ye,Ls,Zr,Cs,eo),yu=At(F(_s,M("ws"),$(Q()))),fx=et(yu),gu=At(F(_s,M("wss"),$(Q())),F(_s,M("tls"),$(F(M("sni"),He())),M("ws"),$(Q()))),hx=et(gu),bu=F(Zr,M("webrtc-direct"),$($r()),$($r()),$(Q())),dx=et(bu),wu=F(eo,M("webtransport"),$($r()),$($r()),$(Q())),px=et(wu),Xn=At(yu,gu,F(Ls,$(Q())),F(jh,$(Q())),F(ye,$(Q())),bu,wu,Q()),xu=et(Xn),Xh=F(Xn,M("p2p-circuit"),Q()),ro=et(Xh),Qh=At(F(Xn,M("p2p-circuit"),M("webrtc"),$(Q())),F(Xn,M("webrtc"),$(Q())),F(M("webrtc"),$(Q()))),mx=et(Qh),Jh=At(F(ye,M("tcp"),mr(),M("http"),$(Q())),F(ye,M("http"),$(Q()))),yx=et(Jh),td=At(F(ye,M("tcp"),At(F(M("443"),M("http")),F(mr(),M("https")),F(mr(),M("tls"),M("http"))),$(Q())),F(ye,M("tls"),M("http"),$(Q())),F(ye,M("https"),$(Q()))),gx=et(td),ed=At(F(M("memory"),He(),$(Q()))),bx=et(ed);function no(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 oo=class extends Error{constructor(t="Transfer limit error"){super(t),this.name="TransferLimitError"}},Yr=class extends Error{constructor(t="Duration limit error"){super(t),this.name="DurationLimitError"}},jr=class extends Error{static name="HadEnoughRelaysError";name="HadEnoughRelaysError"},io=class extends Error{static name="DoubleRelayError";name="DoubleRelayError"},so=class extends Error{static name="RelayQueueFullError";name="RelayQueueFullError"};async function*Eu(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 oo(`data limit of ${n} bytes exceeded`)}t.remaining-=i,yield o}}function Su(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=no(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 Yr(`duration limit of ${n.limit?.duration} ms exceeded`))};a.addEventListener("abort",f,{once:!0}),t.sink(u==null?r.source:Eu(r.source,u,o)).catch(p=>{o.log.error("error while relaying streams src -> dst",p),i(p)}).finally(()=>{c=!0,l&&(a.removeEventListener("abort",f),a.clear())})}),queueMicrotask(()=>{let f=()=>{o.log("relayed connection reached time limit"),r.abort(new Yr(`duration limit of ${n.limit?.duration} ms exceeded`))};a.addEventListener("abort",f,{once:!0}),r.sink(u==null?t.source:Eu(t.source,u,o)).catch(p=>{o.log.error("error while relaying streams dst -> src",p),i(p)}).finally(()=>{l=!0,c&&(a.removeEventListener("abort",f),a.clear())})})}function Rs(r){let t=r*BigInt(1e3),e=new Date().getTime();return Number(t-BigInt(e))}var Xr=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}},ao=et(F(xu.matchers[0],M("p2p-circuit"))),co=et(M("p2p-circuit"));function uo(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 Ie=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 uo(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 uo(this.map.values(),t=>t.key)}values(){return uo(this.map.values(),t=>t.value)}get size(){return this.map.size}};var Ds={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},vu={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Au=new globalThis.TextEncoder;function rd(r,t){let e=Ds[t],n=vu[t];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(t,n*e);return n}function nd(r,t,e){if(e.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Ds[t],o=vu[t],i=r;for(;i.length>0;){let s=Au.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 Ps(r,{size:t=32,utf8Buffer:e}={}){if(!Ds[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 nd(r,t,e);r=Au.encode(r)}return rd(r,t)}var Qr={hash:r=>Number(Ps(r,{size:32})),hashV:(r,t)=>od(Qr.hash(r,t))};function od(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),q(t,"base16")}var Bs=64,jt=class{fp;h;seed;constructor(t,e,n,o=2){if(o>Bs)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 ze(r,t){return Math.floor(Math.random()*(t-r))+r}var Ve=class{contents;constructor(t){this.contents=new Array(t).fill(null)}has(t){if(!(t instanceof jt))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof jt))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 jt))throw new TypeError("Invalid Fingerprint");let e=ze(0,this.contents.length-1),n=this.contents[e];return this.contents[e]=t,n}remove(t){if(!(t instanceof jt))throw new TypeError("Invalid Fingerprint");let e=this.contents.findIndex(n=>t.equals(n));return e>-1?(this.contents[e]=null,!0):!1}};var id=500,Jr=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??Qr,this.seed=t.seed??ze(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=q(t));let e=new jt(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 Ve(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new Ve(this.bucketSize)),this.buckets[n].add(e)||this.buckets[o].add(e))return this.count++,!0;let i=[n,o],s=i[ze(0,i.length-1)];this.buckets[s]==null&&(this.buckets[s]=new Ve(this.bucketSize));for(let a=0;a<id;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 Ve(this.bucketSize)),this.buckets[s].add(c)))return this.count++,!0}return!1}has(t){typeof t=="string"&&(t=q(t));let e=new jt(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=q(t));let e=new jt(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}},sd={1:.5,2:.84,4:.95,8:.98};function ad(r=.001){return r>.002?2:r>1e-5?4:8}function _u(r,t=.001){let e=ad(t),n=sd[e],o=Math.round(r/n),i=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),Bs);return{filterSize:o,bucketSize:e,fingerprintSize:i}}var lo=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??Qr,this.seed=t.seed??ze(0,Math.pow(2,10)),this.filterSeries=[new Jr({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(t){if(typeof t=="string"&&(t=q(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 Jr({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=q(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=q(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 yr(r,t=.001,e){return new lo({..._u(r,t),...e??{}})}var fo=class{filter;constructor(t,e){this.filter=yr(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 Ns(r,t=.001){return new fo(r,t)}var Us=class extends Ie{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 Os(r){let{name:t,metrics:e}=r,n;return e!=null?n=new Us({name:t,metrics:e}):n=new Ie,n}var ks=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 Iu(r,t){let e=new ks(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 ho=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??iu,this.applyDefaultLimit=e.applyDefaultLimit!==!1,this.reservationTtl=e.reservationTtl??su,this.defaultDurationLimit=e.defaultDurationLimit??uu,this.defaultDataLimit=e.defaultDataLimit??lu,this.reservations=Os({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:H.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:Iu(this.reservationTtl)}),this.reservations.set(t,o),o.signal.addEventListener("abort",()=>{this.reservations.delete(t)}),{status:H.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 po=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 dr.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 Tu=r=>r.protoCodes().includes($n),cd={maxOutboundStopStreams:Wr},Ms=class extends Kt{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??fu,this.maxInboundHopStreams=e.maxInboundHopStreams,this.maxOutboundHopStreams=e.maxOutboundHopStreams,this.maxOutboundStopStreams=e.maxOutboundStopStreams??cd.maxOutboundStopStreams,this.reservationStore=new ho(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(zt,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(zt),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=_e(e);try{let i=await o.pb(X).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(X).write({type:X.Type.STATUS,status:H.MALFORMED_MESSAGE},n),e.abort(i)}}async handleHopProtocol({stream:t,request:e,connection:n},o){switch(this.log("received hop message"),e.type){case X.Type.RESERVE:await this.handleReserve({stream:t,request:e,connection:n},o);break;case X.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(X).write({type:X.Type.STATUS,status:H.UNEXPECTED_MESSAGE})}}async handleReserve({stream:t,connection:e},n){let o=t.pb(X);if(this.log("hop reserve request from %p",e.remotePeer),Tu(e.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",e.remotePeer),await o.write({type:X.Type.STATUS,status:H.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:X.Type.STATUS,status:H.PERMISSION_DENIED},n);return}let i=this.reservationStore.reserve(e.remotePeer,e.remoteAddr);try{if(i.status!==H.OK){await o.write({type:X.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:{[Ss]:{value:1,ttl:s},[vs]:{value:1,ttl:s}}})}await o.write({type:X.Type.STATUS,status:H.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:{[Ss]:void 0,[vs]: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 Vr.seal(new po({peer:t,relay:this.peerId,expiration:e}),this.privateKey);return{addrs:n,expire:e,voucher:{publicKey:Qt(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(X);if(Tu(n.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",n.remotePeer),await i.write({type:X.Type.STATUS,status:H.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=cr(qt(e.peer.id))}catch(p){this.log.error("invalid hop connect request via peer %p %s",n.remotePeer,p),await i.write({type:X.Type.STATUS,status:H.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,H.NO_RESERVATION),await i.write({type:X.Type.STATUS,status:H.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:X.Type.STATUS,status:H.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:X.Type.STATUS,status:H.NO_RESERVATION},o);return}let l=c[0],u=await this.stopHop({connection:l,request:{type:Mt.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:X.Type.STATUS,status:H.CONNECTION_FAILED},o);return}await i.write({type:X.Type.STATUS,status:H.OK,limit:a?.limit},o);let f=t.unwrap();this.log("connection from %p to %p established - merging streams",n.remotePeer,s),Su(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([Fe],{maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0,...n}),i=_e(o),s=i.pb(Mt);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===H.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 Lu(r={}){return t=>new Ms(t,r)}function ud(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 Cu=ud;function ld(r){return r[Symbol.asyncIterator]!=null}function Ru(r){return r?.then!=null}function fd(r,t){let e=0;if(ld(r))return async function*(){for await(let c of r){let l=t(c,e++);Ru(l)&&await l,yield c}}();let n=Cu(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(let c of n){let l=t(c,e++);Ru(l)&&await l,yield c}}();let a=t;return function*(){yield o;for(let c of n)a(c,e++),yield c}()}var Du=fd;var mo=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}},gr=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new mo(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 mo(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 qs=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function yo(r={}){return hd(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 hd(r,t){t=t??{};let e=t.onEnd,n=new gr,o,i,s,a=Yt(),c=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((_,C)=>{i=V=>{i=null,n.push(V);try{_(r(n))}catch(E){C(E)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Yt()})}},l=_=>i!=null?i(_):(n.push(_),o),u=_=>(n=new gr,i!=null?i({error:_}):(n.push({error:_}),o)),f=_=>{if(s)return o;if(t?.objectMode!==!0&&_?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:_})},p=_=>s?o:(s=!0,_!=null?u(_):l({done:!0})),b=()=>(n=new gr,p(),{done:!0}),g=_=>(p(_),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:b,throw:g,push:f,end:p,get readableLength(){return n.size},onEmpty:async _=>{let C=_?.signal;if(C?.throwIfAborted(),n.isEmpty())return;let V,E;C!=null&&(V=new Promise((h,w)=>{E=()=>{w(new qs)},C.addEventListener("abort",E)}));try{await Promise.race([a.promise,V])}finally{E!=null&&C!=null&&C?.removeEventListener("abort",E)}}},e==null)return o;let m=o;return o={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(_){return m.throw(_),e!=null&&(e(_),e=void 0),{done:!0}},return(){return m.return(),e!=null&&(e(),e=void 0),{done:!0}},push:f,end(_){return m.end(_),e!=null&&(e(_),e=void 0),o},get readableLength(){return m.readableLength},onEmpty:_=>m.onEmpty(_)},o}function dd(r){return r[Symbol.asyncIterator]!=null}async function pd(r,t,e){try{await Promise.all(r.map(async n=>{for await(let o of n)await t.push(o,{signal:e}),e.throwIfAborted()})),await t.end(void 0,{signal:e})}catch(n){await t.end(n,{signal:e}).catch(()=>{})}}async function*md(r){let t=new AbortController,e=Hn();pd(r,e,t.signal).catch(()=>{});try{yield*e}finally{t.abort()}}function*yd(r){for(let t of r)yield*t}function gd(...r){let t=[];for(let e of r)dd(e)||t.push(e);return t.length===r.length?yd(t):md(r)}var Pu=gd;function Bu(r,...t){if(r==null)throw new Error("Empty pipeline");if(Fs(r)){let n=r;r=()=>n.source}else if(Uu(r)||Nu(r)){let n=r;r=()=>n}let e=[r,...t];if(e.length>1&&Fs(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++)Fs(e[n])&&(e[n]=wd(e[n]));return bd(...e)}var bd=(...r)=>{let t;for(;r.length>0;)t=r.shift()(t);return t},Nu=r=>r?.[Symbol.asyncIterator]!=null,Uu=r=>r?.[Symbol.iterator]!=null,Fs=r=>r==null?!1:r.sink!=null&&r.source!=null,wd=r=>t=>{let e=r.sink(t);if(e?.then!=null){let n=yo({objectMode:!0});e.then(()=>{n.end()},s=>{n.end(s)});let o,i=r.source;if(Nu(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 Pu(n,o())}return r.source};function Hs(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 g=>{await l(g),b(!0)};let u=t.abort.bind(t);t.abort=g=>{u(g),b(!0)};let f=t.sink.bind(t);t.sink=async g=>{try{await f(Bu(g,m=>Du(m,_=>i?.(_))))}catch(m){m.type!=="aborted"&&s.error("%s error in sink",e,m)}finally{c=!0,b()}};let p={log:s,sink:t.sink,source:async function*(){try{for await(let g of t.source)o?.(g),yield g}finally{a=!0,b()}}(),remoteAddr:e,timeline:{open:Date.now(),close:void 0},close:t.close,abort:t.abort};function b(g){g===!0&&(a=!0,c=!0),a&&c&&p.timeline.close==null&&(p.timeline.close=Date.now())}return p}var Te=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var zs=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 go(r,t,e,n){let o=new zs(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(p){a(),s(p);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)})}function Vs(r,t){let e,n=function(){let o=function(){e=void 0,r()};clearTimeout(e),e=setTimeout(o,t)};return n.start=()=>{},n.stop=()=>{clearTimeout(e)},n}var bo=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};var wo=class{deferred;signal;constructor(t){this.signal=t,this.deferred=Yt(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new ne)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function xd(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var xo=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=xd(),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 ne),this.cleanup())}async join(t={}){let e=new wo(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 qe(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 Eo=class extends Kt{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=[],this.emitEmpty=Vs(this.emitEmpty.bind(this),1),this.emitIdle=Vs(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!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 bo;let n=new xo(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 ne)}),this.clear()}async onEmpty(t){this.size!==0&&await go(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await go(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await go(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=yo({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 ne("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 br=class extends Eo{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};var So=class extends Kt{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(zt,{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(zt)],orders:[()=>Math.random()<.5?1:-1,(n,o)=>{let i=Ou(n),s=Ou(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 br({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=no([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 Ou(r){let t=r.metadata.get("last-dial-success");return t==null?0:new Date(k(t)).getTime()}var Gs=class extends Kt{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??Zn,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(co.exactMatch(t))this.log("searching for circuit relay servers"),this.reservationId=this.reservationStore.reserveRelay();else if(ao.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 Le(`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 ku(r){return new Gs(r)}var Mu="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Ku=(r=21)=>{let t="",e=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)t+=Mu[e[r]&63];return t};var Ed=60*1e3*10,Sd=60*1e3*5,vd=30*1e3,vo=class extends Kt{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 Ie,this.pendingReservations=[],this.maxReservationQueueLength=e?.maxReservationQueueLength??cu,this.reservationCompletionTimeout=e?.reservationCompletionTimeout??Zn,this.started=!1,this.relayFilter=yr(100),this.reserveQueue=new br({concurrency:e?.reservationConcurrency??au,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(Gr)]});this.log("removing tag from %d old relays",t.length),await Promise.all(t.map(async e=>{await this.peerStore.merge(e.id,{tags:{[Gr]: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=Ku();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 Le("Cannot use self as relay");if(this.reserveQueue.size>this.maxReservationQueueLength)throw new so("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 Le("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 g=this.connectionManager.getConnections(t),m=!1;if(g.length===0&&this.log("already have relay reservation with %p but we are no longer connected",t),g.map(_=>_.id).includes(i.connection)&&(this.log("already have relay reservation with %p and the original connection is still open",t),m=!0),m&&Rs(i.reservation.expire)>Ed)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 jr("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(ro.matches(a.remoteAddr))throw new io("not creating reservation over relayed connection");let c=await this.#t(a,{signal:s}),l=Rs(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-Sd,vd),Math.pow(2,31)-1),f=setTimeout(()=>{this.log("refresh reservation to relay %p",t),this.addRelay(t,e).catch(async g=>{this.log.error("could not refresh reservation to relay %p - %e",t,g),await this.#e(t)}).catch(g=>{this.log.error("could not remove expired reservation to relay %p - %e",t,g)})},u),p;if(e==="discovered"){let g=this.pendingReservations.pop();if(g==null)throw new jr("Made reservation on relay but did not need any more discovered relays");p={timeout:f,reservation:c,type:e,connection:a.id,id:g}}else p={timeout:f,reservation:c,type:e,connection:a.id};this.reservations.set(t,p),await this.peerStore.merge(t,{tags:{[Gr]:{value:1,ttl:l}}}),this.#r();let b={relay:t,details:p};return this.safeDispatchEvent("relay:created-reservation",{detail:b}),b}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(zt,e),i=_e(n).pb(X);this.log.trace("send RESERVE to %p",t.remotePeer),await i.write({type:X.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===H.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:{[Gr]: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=yr(100),this.log("not discovered enough relays %d/%d",this.reservations.size,this.pendingReservations.length),this.safeDispatchEvent("relay:not-enough-relays")}};var Ad=r=>{if(r.peer==null)return!1;try{r.peer.addrs.forEach(vt)}catch{return!1}return!0},qu={maxInboundStopStreams:Wr,maxOutboundStopStreams:Wr,stopTimeout:3e4},Ao=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??qu.maxInboundStopStreams,this.maxOutboundStopStreams=e.maxOutboundStopStreams??qu.maxOutboundStopStreams,this.shutdownController=new AbortController,this.discovery=new So(t,{filter:e.discoveryFilter??Ns(hu,du)}),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 vo(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";[Qs]=["@libp2p/transport","@libp2p/circuit-relay-v2-transport"];get[Js](){return this.discovery!=null?["@libp2p/identify"]:[]}[Zs]=!0;isStarted(){return this.started}async start(){this.shutdownController=new AbortController,this.shutdownController.signal,await this.registrar.handle(Fe,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 js(this.discovery,this.reservationStore),this.started=!0}async stop(){this.shutdownController.abort(),await Xs(this.discovery,this.reservationStore),await this.registrar.unhandle(Fe),this.started=!1}async dial(t,e){if(t.protoCodes().filter(b=>b===$n).length!==1){let b="Invalid circuit relay address";throw this.log.error(b,t),new xr(b)}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 b=`ircuit relay dial to ${t.toString()} failed as address did not have both relay and destination PeerIDs`;throw this.log.error(`c${b}`),new xr(`C${b}`)}let c=is(s),l=is(a),f=this.connectionManager.getConnections(c)[0];f==null?(await this.peerStore.merge(c,{multiaddrs:[o]}),e.onProgress?.(new Te("circuit-relay:open-connection")),f=await this.connectionManager.openConnection(c,e)):e.onProgress?.(new Te("circuit-relay:reuse-connection"));let p;try{e.onProgress?.(new Te("circuit-relay:open-hop-stream")),p=await f.newStream(zt,e);let b=_e(p),g=b.pb(X);e.onProgress?.(new Te("circuit-relay:write-connect-message")),await g.write({type:X.Type.CONNECT,peer:{id:l.toMultihash().bytes,addrs:[vt(i).bytes]}},e),e.onProgress?.(new Te("circuit-relay:read-connect-response"));let m=await g.read(e);if(m.status!==H.OK)throw new rn(`failed to connect via relay with status ${m?.status?.toString()??"undefined"}`);let _=new Xr(m.limit),C=Hs({stream:b.unwrap(),remoteAddr:t,localAddr:o.encapsulate(`/p2p-circuit/p2p/${this.peerId.toString()}`),logger:this.logger,onDataRead:_.onData,onDataWrite:_.onData});return this.log("new outbound relayed connection %a",C.remoteAddr),await this.upgrader.upgradeOutbound(C,{...e,limits:_.getLimits()})}catch(b){throw this.log.error("circuit relay dial to destination %p via relay %p failed",l,c,b),p?.abort(b),b}}createListener(t){return ku({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=>ao.exactMatch(e)||co.exactMatch(e))}dialFilter(t){return t=Array.isArray(t)?t:[t],t.filter(e=>ro.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=_e(e).pb(Mt),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:Mt.Type.STATUS,status:H.MALFORMED_MESSAGE},{signal:n}),await e.close();return}if(i.type!==Mt.Type.CONNECT){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await o.write({type:Mt.Type.STATUS,status:H.UNEXPECTED_MESSAGE},{signal:n}),await e.close();return}if(!Ad(i)){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await o.write({type:Mt.Type.STATUS,status:H.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}let s=cr(qt(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:Mt.Type.STATUS,status:H.PERMISSION_DENIED},{signal:n}),await e.close({signal:n});return}this.log.trace("sending success response to %p",t.remotePeer),await o.write({type:Mt.Type.STATUS,status:H.OK},{signal:n});let a=new Xr(i.limit),c=t.remoteAddr.encapsulate(`/p2p-circuit/p2p/${s.toString()}`),l=this.addressManager.getAddresses()[0],u=Hs({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 Fu(r={}){return t=>new Ao(t,r)}return ju(_d);})();
3
3
  /*! Bundled license information:
4
4
 
5
5
  @noble/hashes/esm/utils.js: