@libp2p/circuit-relay-v2 3.2.23-cf9aab5c8 → 3.2.24-f5932c294

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 Qo=Object.defineProperty;var Ll=Object.getOwnPropertyDescriptor;var Ol=Object.getOwnPropertyNames;var Nl=Object.prototype.hasOwnProperty;var It=(r,t)=>{for(var e in t)Qo(r,e,{get:t[e],enumerable:!0})},Ul=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ol(t))!Nl.call(r,o)&&o!==e&&Qo(r,o,{get:()=>t[o],enumerable:!(n=Ll(t,o))||n.enumerable});return r};var Ml=r=>Ul(Qo({},"__esModule",{value:!0}),r);var Lp={};It(Lp,{RELAY_V2_HOP_CODEC:()=>Ft,RELAY_V2_STOP_CODEC:()=>We,circuitRelayServer:()=>bl,circuitRelayTransport:()=>Rl});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 Jo=Symbol.for("@libp2p/peer-id");var ti="keep-alive";var Ba=Symbol.for("@libp2p/transport");var Pa;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Pa||(Pa={}));var te=class extends Error{static name="AbortError";constructor(t="The operation was aborted"){super(t),this.name="AbortError"}};var lt=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},Qe=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"}},Cn=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}};var Dn=class extends Error{static name="InvalidMessageError";constructor(t="Invalid message"){super(t),this.name="InvalidMessageError"}};var Nr=class extends Error{static name="DialError";constructor(t="Dial error"){super(t),this.name="DialError"}},Oe=class extends Error{static name="ListenError";constructor(t="Listen error"){super(t),this.name="ListenError"}};var Je=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};function Ra(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function La(...r){let t=[];for(let e of r)Ra(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 Oa(...r){let t=[];for(let e of r)Ra(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 Na=Symbol.for("@libp2p/service-capabilities"),Ua=Symbol.for("@libp2p/service-dependencies");var ii={};It(ii,{base58btc:()=>J,base58flickr:()=>zl});var cm=new Uint8Array(0);function Ma(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function ee(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function ka(r){return new TextEncoder().encode(r)}function Ka(r){return new TextDecoder().decode(r)}function kl(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),u=Math.log(a)/Math.log(256),h=Math.log(256)/Math.log(a);function f(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var x=0,S=0,g=0,_=p.length;g!==_&&p[g]===0;)g++,x++;for(var w=(_-g)*h+1>>>0,C=new Uint8Array(w);g!==_;){for(var L=p[g],V=0,q=w-1;(L!==0||V<S)&&q!==-1;q--,V++)L+=256*C[q]>>>0,C[q]=L%a>>>0,L=L/a>>>0;if(L!==0)throw new Error("Non-zero carry");S=V,g++}for(var N=w-S;N!==w&&C[N]===0;)N++;for(var E=c.repeat(x);N<w;++N)E+=r.charAt(C[N]);return E}function l(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var x=0;if(p[x]!==" "){for(var S=0,g=0;p[x]===c;)S++,x++;for(var _=(p.length-x)*u+1>>>0,w=new Uint8Array(_);p[x];){var C=e[p.charCodeAt(x)];if(C===255)return;for(var L=0,V=_-1;(C!==0||L<g)&&V!==-1;V--,L++)C+=a*w[V]>>>0,w[V]=C%256>>>0,C=C/256>>>0;if(C!==0)throw new Error("Non-zero carry");g=L,x++}if(p[x]!==" "){for(var q=_-g;q!==_&&w[q]===0;)q++;for(var N=new Uint8Array(S+(_-q)),E=S;q!==_;)N[E++]=w[q++];return N}}}function d(p){var x=l(p);if(x)return x;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:l,decode:d}}var Kl=kl,ql=Kl,Va=ql;var ei=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")}},ri=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 Fa(this,t)}},ni=class{decoders;constructor(t){this.decoders=t}or(t){return Fa(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 Fa(r,t){return new ni({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var oi=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 ei(t,e,n),this.decoder=new ri(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function tr({name:r,prefix:t,encode:e,decode:n}){return new oi(r,t,e,n)}function we({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=Va(e,r);return tr({prefix:t,name:r,encode:n,decode:i=>ee(o(i))})}function Vl(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 u=0;u<o;++u){let h=t[r[u]];if(h===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<e|h,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 Fl(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 Hl(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=Hl(n);return tr({prefix:t,name:r,encode(i){return Fl(i,n,e)},decode(i){return Vl(i,o,e,r)}})}var J=we({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),zl=we({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var si={};It(si,{base32:()=>Ee,base32hex:()=>Wl,base32hexpad:()=>Xl,base32hexpadupper:()=>jl,base32hexupper:()=>Yl,base32pad:()=>$l,base32padupper:()=>Zl,base32upper:()=>Gl,base32z:()=>Ql});var Ee=it({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Gl=it({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),$l=it({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Zl=it({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Wl=it({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Yl=it({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Xl=it({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),jl=it({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Ql=it({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var ai={};It(ai,{base36:()=>Ur,base36upper:()=>Jl});var Ur=we({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Jl=we({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var tf=Ga,Ha=128,ef=127,rf=~ef,nf=Math.pow(2,31);function Ga(r,t,e){t=t||[],e=e||0;for(var n=e;r>=nf;)t[e++]=r&255|Ha,r/=128;for(;r&rf;)t[e++]=r&255|Ha,r>>>=7;return t[e]=r|0,Ga.bytes=e-n+1,t}var of=ci,sf=128,za=127;function ci(r,n){var e=0,n=n||0,o=0,i=n,s,a=r.length;do{if(i>=a)throw ci.bytes=0,new RangeError("Could not decode varint");s=r[i++],e+=o<28?(s&za)<<o:(s&za)*Math.pow(2,o),o+=7}while(s>=sf);return ci.bytes=i-n,e}var af=Math.pow(2,7),cf=Math.pow(2,14),uf=Math.pow(2,21),lf=Math.pow(2,28),ff=Math.pow(2,35),hf=Math.pow(2,42),df=Math.pow(2,49),pf=Math.pow(2,56),mf=Math.pow(2,63),yf=function(r){return r<af?1:r<cf?2:r<uf?3:r<lf?4:r<ff?5:r<hf?6:r<df?7:r<pf?8:r<mf?9:10},gf={encode:tf,decode:of,encodingLength:yf},bf=gf,Mr=bf;function kr(r,t=0){return[Mr.decode(r,t),Mr.decode.bytes]}function er(r,t,e=0){return Mr.encode(r,t,e),t}function rr(r){return Mr.encodingLength(r)}function Ht(r,t){let e=t.byteLength,n=rr(r),o=n+rr(e),i=new Uint8Array(o+e);return er(r,i,0),er(e,i,n),i.set(t,o),new nr(r,e,t,i)}function Yt(r){let t=ee(r),[e,n]=kr(t),[o,i]=kr(t.subarray(n)),s=t.subarray(n+i);if(s.byteLength!==o)throw new Error("Incorrect length");return new nr(e,o,s,t)}function $a(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&Ma(r.bytes,e.bytes)}}var nr=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};function Za(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return wf(e,ui(r),t??J.encoder);default:return Ef(e,ui(r),t??Ee.encoder)}}var Wa=new WeakMap;function ui(r){let t=Wa.get(r);if(t==null){let e=new Map;return Wa.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!==Kr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==Sf)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:t,digest:e}=this.multihash,n=Ht(t,e);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&$a(t.multihash,n.multihash)}toString(t){return Za(this,t)}toJSON(){return{"/":Za(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??Ya(n,o,i.bytes))}else if(e[vf]===!0){let{version:n,multihash:o,code:i}=e,s=Yt(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!==Kr)throw new Error(`Version 0 CID must use dag-pb (code: ${Kr}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=Ya(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,Kr,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,o=ee(t.subarray(n,n+e.multihashSize));if(o.byteLength!==e.multihashSize)throw new Error("Incorrect length");let i=o.subarray(e.multihashSize-e.digestSize),s=new nr(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,l]=kr(t.subarray(e));return e+=l,f},o=n(),i=Kr;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(),u=e+c,h=u-s;return{version:o,codec:i,multihashCode:a,digestSize:c,multihashSize:h,size:u}}static parse(t,e){let[n,o]=xf(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 ui(i).set(n,t),i}};function xf(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 Ee.prefix:{let e=t??Ee;return[Ee.prefix,e.decode(r)]}case Ur.prefix:{let e=t??Ur;return[Ur.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 wf(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 Ef(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 Kr=112,Sf=18;function Ya(r,t,e){let n=rr(r),o=n+rr(t),i=new Uint8Array(o+e.byteLength);return er(r,i,0),er(t,i,n),i.set(e,o),i}var vf=Symbol.for("@ipld/js-cid/CID");var li={};It(li,{identity:()=>zt});var Xa=0,_f="identity",ja=ee;function Af(r){return Ht(Xa,ja(r))}var zt={code:Xa,name:_f,encode:ja,digest:Af};function ft(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 et(r=0){return new Uint8Array(r)}function Tt(r=0){return new Uint8Array(r)}function ne(r,t){t==null&&(t=r.reduce((o,i)=>o+i.length,0));let e=Tt(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}var Ja=Symbol.for("@achingbrain/uint8arraylist");function Qa(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let o=e+n.byteLength;if(t<o)return{buf:n,index:t-e};e=o}throw new RangeError("index is out of bounds")}function Bn(r){return!!r?.[Ja]}var ct=class r{bufs;length;[Ja]=!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(Bn(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(Bn(n))e+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=Qa(this.bufs,t);return e.buf[e.index]}set(t,e){let n=Qa(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else if(Bn(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 ne(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:ne(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 u=t>=a&&t<c,h=e>a&&e<=c;if(u&&h){if(t===a&&e===c){n.push(s);break}let f=t-a;n.push(s.subarray(f,f+(e-t)));break}if(u){if(t===0){n.push(s);continue}n.push(s.subarray(t-a));continue}if(h){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(!Bn(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,u=n.byteLength-1,h;for(let f=e;f<=c;f+=h){h=0;for(let l=u;l>=0;l--){let d=this.get(f+l);if(n[l]!==d){h=Math.max(1,l-a[d]);break}}if(h===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=Tt(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=et(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=et(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=et(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=Tt(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=et(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=et(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=et(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=et(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=et(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(!ft(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 fi={};It(fi,{base10:()=>If});var If=we({prefix:"9",name:"base10",alphabet:"0123456789"});var hi={};It(hi,{base16:()=>Tf,base16upper:()=>Cf});var Tf=it({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Cf=it({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var di={};It(di,{base2:()=>Df});var Df=it({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var pi={};It(pi,{base256emoji:()=>Of});var tc=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),Pf=tc.reduce((r,t,e)=>(r[e]=t,r),[]),Bf=tc.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function Rf(r){return r.reduce((t,e)=>(t+=Pf[e],t),"")}function Lf(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=Bf[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var Of=tr({prefix:"\u{1F680}",name:"base256emoji",encode:Rf,decode:Lf});var yi={};It(yi,{base64:()=>Nf,base64pad:()=>Uf,base64url:()=>mi,base64urlpad:()=>Mf});var Nf=it({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Uf=it({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),mi=it({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Mf=it({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var gi={};It(gi,{base8:()=>kf});var kf=it({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var bi={};It(bi,{identity:()=>Kf});var Kf=tr({prefix:"\0",name:"identity",encode:r=>Ka(r),decode:r=>ka(r)});var Gm=new TextEncoder,$m=new TextDecoder;var Ei={};It(Ei,{sha256:()=>or,sha512:()=>Ff});function wi({name:r,code:t,encode:e}){return new xi(r,t,e)}var xi=class{name;code;encode;constructor(t,e,n){this.name=t,this.code=e,this.encode=n}digest(t){if(t instanceof Uint8Array){let e=this.encode(t);return e instanceof Uint8Array?Ht(this.code,e):e.then(n=>Ht(this.code,n))}else throw Error("Unknown type, must be binary type")}};function rc(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var or=wi({name:"sha2-256",code:18,encode:rc("SHA-256")}),Ff=wi({name:"sha2-512",code:19,encode:rc("SHA-512")});var qr={...bi,...di,...gi,...fi,...hi,...si,...ai,...ii,...yi,...pi},o0={...Ei,...li};function oc(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var nc=oc("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Si=oc("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=Tt(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),Hf={utf8:nc,"utf-8":nc,hex:qr.base16,latin1:Si,ascii:Si,binary:Si,...qr},Rn=Hf;function k(r,t="utf8"){let e=Rn[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function K(r,t="utf8"){let e=Rn[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var zf=parseInt("11111",2),vi=parseInt("10000000",2),Gf=parseInt("01111111",2),ic={0:Vr,1:Vr,2:$f,3:Yf,4:Xf,5:Wf,6:Zf,16:Vr,22:Vr,48:Vr};function oe(r,t={offset:0}){let e=r[t.offset]&zf;if(t.offset++,ic[e]!=null)return ic[e](r,t);throw new Error("No decoder for tag "+e)}function Fr(r,t){let e=0;if((r[t.offset]&vi)===vi){let n=r[t.offset]&Gf,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 Vr(r,t){Fr(r,t);let e=[];for(;!(t.offset>=r.byteLength);){let n=oe(r,t);if(n===null)break;e.push(n)}return e}function $f(r,t){let e=Fr(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 Zf(r,t){let e=Fr(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 u=r[t.offset];if(t.offset++,c.push(u&127),u<128){c.reverse();let h=0;for(let f=0;f<c.length;f++)h+=c[f]<<f*7;a+=`.${h}`,c=[]}}return a}function Wf(r,t){return t.offset++,null}function Yf(r,t){let e=Fr(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 Xf(r,t){let e=Fr(r,t),n=r.subarray(t.offset,t.offset+e);return t.offset+=e,n}function jf(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 _i(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let t=jf(r.byteLength);return new ct(Uint8Array.from([t.byteLength|vi]),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]),_i(t),t)}function Ln(r){let t=Uint8Array.from([0]),e=new ct(t,r);return new ct(Uint8Array.from([3]),_i(e),e)}function Se(r,t=48){let e=new ct;for(let n of r)e.append(n);return new ct(Uint8Array.from([t]),_i(e),e)}async function sc(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 Qf=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Jf=Uint8Array.from([6,5,43,129,4,0,34]),th=Uint8Array.from([6,5,43,129,4,0,35]),eh={ext:!0,kty:"EC",crv:"P-256"},rh={ext:!0,kty:"EC",crv:"P-384"},nh={ext:!0,kty:"EC",crv:"P-521"},Ai=32,Ii=48,Ti=66;function Ci(r){let t=oe(r);return ac(t)}function ac(r){let t=r[1][1][0],e=1,n,o;if(t.byteLength===Ai*2+1)return n=K(t.subarray(e,e+Ai),"base64url"),o=K(t.subarray(e+Ai),"base64url"),new ir({...eh,key_ops:["verify"],x:n,y:o});if(t.byteLength===Ii*2+1)return n=K(t.subarray(e,e+Ii),"base64url"),o=K(t.subarray(e+Ii),"base64url"),new ir({...rh,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 ir({...nh,key_ops:["verify"],x:n,y:o});throw new lt(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function cc(r){return Se([Ct(Uint8Array.from([1])),Se([oh(r.crv)],160),Se([Ln(new ct(Uint8Array.from([4]),k(r.x??"","base64url"),k(r.y??"","base64url")))],161)]).subarray()}function oh(r){if(r==="P-256")return Qf;if(r==="P-384")return Jf;if(r==="P-521")return th;throw new lt(`Invalid curve ${r}`)}var ir=class{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=cc(this.jwk)),this._raw}toMultihash(){return zt.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:ft(this.raw,t.raw)}async verify(t,e,n){return sc(this.jwk,e,t,n)}};var Ne=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function se(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Hr(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function Dt(r,...t){if(!se(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 On(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Hr(r.outputLen),Hr(r.blockLen)}function ar(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 lc(r,t){Dt(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 Nn(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Gt(r,t){return r<<32-t|r>>>t}var fc=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",ih=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function qt(r){if(Dt(r),fc)return r.toHex();let t="";for(let e=0;e<r.length;e++)t+=ih[r[e]];return t}var ie={_0:48,_9:57,A:65,F:70,a:97,f:102};function uc(r){if(r>=ie._0&&r<=ie._9)return r-ie._0;if(r>=ie.A&&r<=ie.F)return r-(ie.A-10);if(r>=ie.a&&r<=ie.f)return r-(ie.a-10)}function Ue(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(fc)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=uc(r.charCodeAt(i)),a=uc(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 Di(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function zr(r){return typeof r=="string"&&(r=Di(r)),Dt(r),r}function vt(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];Dt(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 sr=class{};function Pi(r){let t=n=>r().update(zr(n)).digest(),e=r();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>r(),t}function cr(r=32){if(Ne&&typeof Ne.getRandomValues=="function")return Ne.getRandomValues(new Uint8Array(r));if(Ne&&typeof Ne.randomBytes=="function")return Uint8Array.from(Ne.randomBytes(r));throw new Error("crypto.getRandomValues must be defined")}function sh(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,u=n?0:4;r.setUint32(t+c,s,n),r.setUint32(t+u,a,n)}function hc(r,t,e){return r&t^~r&e}function dc(r,t,e){return r&t^r&e^t&e}var Gr=class extends sr{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=Nn(this.buffer)}update(t){ar(this),t=zr(t),Dt(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=Nn(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){ar(this),lc(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;sh(n,o-8,BigInt(this.length*8),i),this.process(n,0);let a=Nn(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,h=this.get();if(u>h.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)a.setUint32(4*f,h[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 yt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Un=BigInt(4294967295),pc=BigInt(32);function ah(r,t=!1){return t?{h:Number(r&Un),l:Number(r>>pc&Un)}:{h:Number(r>>pc&Un)|0,l:Number(r&Un)|0}}function mc(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}=ah(r[i],t);[n[i],o[i]]=[s,a]}return[n,o]}var Bi=(r,t,e)=>r>>>e,Ri=(r,t,e)=>r<<32-e|t>>>e,Me=(r,t,e)=>r>>>e|t<<32-e,ke=(r,t,e)=>r<<32-e|t>>>e,$r=(r,t,e)=>r<<64-e|t>>>e-32,Zr=(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 yc=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),gc=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,bc=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),xc=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,wc=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),Ec=(r,t,e,n,o,i)=>t+e+n+o+i+(r/2**32|0)|0;var uh=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]),ve=new Uint32Array(64),Mn=class extends Gr{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)ve[f]=t.getUint32(e,!1);for(let f=16;f<64;f++){let l=ve[f-15],d=ve[f-2],p=Gt(l,7)^Gt(l,18)^l>>>3,x=Gt(d,17)^Gt(d,19)^d>>>10;ve[f]=x+ve[f-7]+p+ve[f-16]|0}let{A:n,B:o,C:i,D:s,E:a,F:c,G:u,H:h}=this;for(let f=0;f<64;f++){let l=Gt(a,6)^Gt(a,11)^Gt(a,25),d=h+l+hc(a,c,u)+uh[f]+ve[f]|0,x=(Gt(n,2)^Gt(n,13)^Gt(n,22))+dc(n,o,i)|0;h=u,u=c,c=a,a=s+d|0,s=i,i=o,o=n,n=d+x|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,u=u+this.G|0,h=h+this.H|0,this.set(n,o,i,s,a,c,u,h)}roundClean(){ae(ve)}destroy(){this.set(0,0,0,0,0,0,0,0),ae(this.buffer)}};var Sc=mc(["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))),lh=Sc[0],fh=Sc[1],_e=new Uint32Array(80),Ae=new Uint32Array(80),Li=class extends Gr{constructor(t=64){super(128,t,16,!1),this.Ah=yt[0]|0,this.Al=yt[1]|0,this.Bh=yt[2]|0,this.Bl=yt[3]|0,this.Ch=yt[4]|0,this.Cl=yt[5]|0,this.Dh=yt[6]|0,this.Dl=yt[7]|0,this.Eh=yt[8]|0,this.El=yt[9]|0,this.Fh=yt[10]|0,this.Fl=yt[11]|0,this.Gh=yt[12]|0,this.Gl=yt[13]|0,this.Hh=yt[14]|0,this.Hl=yt[15]|0}get(){let{Ah:t,Al:e,Bh:n,Bl:o,Ch:i,Cl:s,Dh:a,Dl:c,Eh:u,El:h,Fh:f,Fl:l,Gh:d,Gl:p,Hh:x,Hl:S}=this;return[t,e,n,o,i,s,a,c,u,h,f,l,d,p,x,S]}set(t,e,n,o,i,s,a,c,u,h,f,l,d,p,x,S){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=u|0,this.El=h|0,this.Fh=f|0,this.Fl=l|0,this.Gh=d|0,this.Gl=p|0,this.Hh=x|0,this.Hl=S|0}process(t,e){for(let w=0;w<16;w++,e+=4)_e[w]=t.getUint32(e),Ae[w]=t.getUint32(e+=4);for(let w=16;w<80;w++){let C=_e[w-15]|0,L=Ae[w-15]|0,V=Me(C,L,1)^Me(C,L,8)^Bi(C,L,7),q=ke(C,L,1)^ke(C,L,8)^Ri(C,L,7),N=_e[w-2]|0,E=Ae[w-2]|0,D=Me(N,E,19)^$r(N,E,61)^Bi(N,E,6),U=ke(N,E,19)^Zr(N,E,61)^Ri(N,E,6),P=bc(q,U,Ae[w-7],Ae[w-16]),b=xc(P,V,D,_e[w-7],_e[w-16]);_e[w]=b|0,Ae[w]=P|0}let{Ah:n,Al:o,Bh:i,Bl:s,Ch:a,Cl:c,Dh:u,Dl:h,Eh:f,El:l,Fh:d,Fl:p,Gh:x,Gl:S,Hh:g,Hl:_}=this;for(let w=0;w<80;w++){let C=Me(f,l,14)^Me(f,l,18)^$r(f,l,41),L=ke(f,l,14)^ke(f,l,18)^Zr(f,l,41),V=f&d^~f&x,q=l&p^~l&S,N=wc(_,L,q,fh[w],Ae[w]),E=Ec(N,g,C,V,lh[w],_e[w]),D=N|0,U=Me(n,o,28)^$r(n,o,34)^$r(n,o,39),P=ke(n,o,28)^Zr(n,o,34)^Zr(n,o,39),b=n&i^n&a^i&a,m=o&s^o&c^s&c;g=x|0,_=S|0,x=d|0,S=p|0,d=f|0,p=l|0,{h:f,l}=jt(u|0,h|0,E|0,D|0),u=a|0,h=c|0,a=i|0,c=s|0,i=n|0,s=o|0;let y=yc(D,P,m);n=gc(y,E,U,b),o=y|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:u,l:h}=jt(this.Dh|0,this.Dl|0,u|0,h|0),{h:f,l}=jt(this.Eh|0,this.El|0,f|0,l|0),{h:d,l:p}=jt(this.Fh|0,this.Fl|0,d|0,p|0),{h:x,l:S}=jt(this.Gh|0,this.Gl|0,x|0,S|0),{h:g,l:_}=jt(this.Hh|0,this.Hl|0,g|0,_|0),this.set(n,o,i,s,a,c,u,h,f,l,d,p,x,S,g,_)}roundClean(){ae(_e,Ae)}destroy(){ae(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var kn=Pi(()=>new Mn);var vc=Pi(()=>new Li);var Ui=BigInt(0),Ni=BigInt(1);function ue(r,t=""){if(typeof r!="boolean"){let e=t&&`"${t}"`;throw new Error(e+"expected boolean, got type="+typeof r)}return r}function Ot(r,t,e=""){let n=se(r),o=r?.length,i=t!==void 0;if(!n||i&&o!==t){let s=e&&`"${e}" `,a=i?` of length ${t}`:"",c=n?`length=${o}`:`type=${typeof r}`;throw new Error(s+"expected Uint8Array"+a+", got "+c)}return r}function Wr(r){let t=r.toString(16);return t.length&1?"0"+t:t}function _c(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?Ui:BigInt("0x"+r)}function ur(r){return _c(qt(r))}function le(r){return Dt(r),_c(qt(Uint8Array.from(r).reverse()))}function Kn(r,t){return Ue(r.toString(16).padStart(t*2,"0"))}function Mi(r,t){return Kn(r,t).reverse()}function Y(r,t,e){let n;if(typeof t=="string")try{n=Ue(t)}catch(i){throw new Error(r+" must be hex string or Uint8Array, cause: "+i)}else if(se(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 Ac(r,t){if(r.length!==t.length)return!1;let e=0;for(let n=0;n<r.length;n++)e|=r[n]^t[n];return e===0}function ki(r){return Uint8Array.from(r)}var Oi=r=>typeof r=="bigint"&&Ui<=r;function Ic(r,t,e){return Oi(r)&&Oi(t)&&Oi(e)&&t<=r&&r<e}function Yr(r,t,e,n){if(!Ic(t,e,n))throw new Error("expected valid "+r+": "+e+" <= n < "+n+", got "+t)}function qn(r){let t;for(t=0;r>Ui;r>>=Ni,t+=1);return t}var Ie=r=>(Ni<<BigInt(r))-Ni;function Tc(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=d=>new Uint8Array(d),o=d=>Uint8Array.of(d),i=n(r),s=n(r),a=0,c=()=>{i.fill(1),s.fill(0),a=0},u=(...d)=>e(s,i,...d),h=(d=n(0))=>{s=u(o(0),d),i=u(),d.length!==0&&(s=u(o(1),d),i=u())},f=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let d=0,p=[];for(;d<t;){i=u();let x=i.slice();p.push(x),d+=i.length}return vt(...p)};return(d,p)=>{c(),h(d);let x;for(;!(x=p(f()));)h();return c(),x}}function Te(r,t,e={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function n(o,i,s){let a=r[o];if(s&&a===void 0)return;let c=typeof a;if(c!==i||a===null)throw new Error(`param "${o}" is invalid: expected ${i}, got ${c}`)}Object.entries(t).forEach(([o,i])=>n(o,i,!1)),Object.entries(e).forEach(([o,i])=>n(o,i,!0))}var Ki=()=>{throw new Error("not implemented")};function lr(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),dt=BigInt(1),Ke=BigInt(2),Pc=BigInt(3),Bc=BigInt(4),Rc=BigInt(5),hh=BigInt(7),Lc=BigInt(8),dh=BigInt(9),Oc=BigInt(16);function at(r,t){let e=r%t;return e>=_t?e:t+e}function tt(r,t,e){let n=r;for(;t-- >_t;)n*=n,n%=e;return n}function Cc(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=at(r,t),n=t,o=_t,i=dt,s=dt,a=_t;for(;e!==_t;){let u=n/e,h=n%e,f=o-s*u,l=i-a*u;n=e,e=h,o=s,i=a,s=f,a=l}if(n!==dt)throw new Error("invert: does not exist");return at(o,t)}function qi(r,t,e){if(!r.eql(r.sqr(t),e))throw new Error("Cannot find square root")}function Nc(r,t){let e=(r.ORDER+dt)/Bc,n=r.pow(t,e);return qi(r,n,t),n}function ph(r,t){let e=(r.ORDER-Rc)/Lc,n=r.mul(t,Ke),o=r.pow(n,e),i=r.mul(t,o),s=r.mul(r.mul(i,Ke),o),a=r.mul(i,r.sub(s,r.ONE));return qi(r,a,t),a}function mh(r){let t=Nt(r),e=Uc(r),n=e(t,t.neg(t.ONE)),o=e(t,n),i=e(t,t.neg(n)),s=(r+hh)/Oc;return(a,c)=>{let u=a.pow(c,s),h=a.mul(u,n),f=a.mul(u,o),l=a.mul(u,i),d=a.eql(a.sqr(h),c),p=a.eql(a.sqr(f),c);u=a.cmov(u,h,d),h=a.cmov(l,f,p);let x=a.eql(a.sqr(h),c),S=a.cmov(u,h,x);return qi(a,S,c),S}}function Uc(r){if(r<Pc)throw new Error("sqrt is not defined for small field");let t=r-dt,e=0;for(;t%Ke===_t;)t/=Ke,e++;let n=Ke,o=Nt(r);for(;Dc(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(e===1)return Nc;let i=o.pow(n,t),s=(t+dt)/Ke;return function(c,u){if(c.is0(u))return u;if(Dc(c,u)!==1)throw new Error("Cannot find square root");let h=e,f=c.mul(c.ONE,i),l=c.pow(u,t),d=c.pow(u,s);for(;!c.eql(l,c.ONE);){if(c.is0(l))return c.ZERO;let p=1,x=c.sqr(l);for(;!c.eql(x,c.ONE);)if(p++,x=c.sqr(x),p===h)throw new Error("Cannot find square root");let S=dt<<BigInt(h-p-1),g=c.pow(f,S);h=p,f=c.sqr(g),l=c.mul(l,f),d=c.mul(d,g)}return d}}function yh(r){return r%Bc===Pc?Nc:r%Lc===Rc?ph:r%Oc===dh?mh(r):Uc(r)}var fe=(r,t)=>(at(r,t)&dt)===dt,gh=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Vi(r){let t={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},e=gh.reduce((n,o)=>(n[o]="function",n),t);return Te(r,e),r}function bh(r,t,e){if(e<_t)throw new Error("invalid exponent, negatives unsupported");if(e===_t)return r.ONE;if(e===dt)return t;let n=r.ONE,o=t;for(;e>_t;)e&dt&&(n=r.mul(n,o)),o=r.sqr(o),e>>=dt;return n}function Xr(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 Dc(r,t){let e=(r.ORDER-dt)/Ke,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 Vn(r,t){t!==void 0&&Hr(t);let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}function Nt(r,t,e=!1,n={}){if(r<=_t)throw new Error("invalid field: expected ORDER > 0, got "+r);let o,i,s=!1,a;if(typeof t=="object"&&t!=null){if(n.sqrt||e)throw new Error("cannot specify opts in two arguments");let l=t;l.BITS&&(o=l.BITS),l.sqrt&&(i=l.sqrt),typeof l.isLE=="boolean"&&(e=l.isLE),typeof l.modFromBytes=="boolean"&&(s=l.modFromBytes),a=l.allowedLengths}else typeof t=="number"&&(o=t),n.sqrt&&(i=n.sqrt);let{nBitLength:c,nByteLength:u}=Vn(r,o);if(u>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let h,f=Object.freeze({ORDER:r,isLE:e,BITS:c,BYTES:u,MASK:Ie(c),ZERO:_t,ONE:dt,allowedLengths:a,create:l=>at(l,r),isValid:l=>{if(typeof l!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof l);return _t<=l&&l<r},is0:l=>l===_t,isValidNot0:l=>!f.is0(l)&&f.isValid(l),isOdd:l=>(l&dt)===dt,neg:l=>at(-l,r),eql:(l,d)=>l===d,sqr:l=>at(l*l,r),add:(l,d)=>at(l+d,r),sub:(l,d)=>at(l-d,r),mul:(l,d)=>at(l*d,r),pow:(l,d)=>bh(f,l,d),div:(l,d)=>at(l*Cc(d,r),r),sqrN:l=>l*l,addN:(l,d)=>l+d,subN:(l,d)=>l-d,mulN:(l,d)=>l*d,inv:l=>Cc(l,r),sqrt:i||(l=>(h||(h=yh(r)),h(f,l))),toBytes:l=>e?Mi(l,u):Kn(l,u),fromBytes:(l,d=!0)=>{if(a){if(!a.includes(l.length)||l.length>u)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+l.length);let x=new Uint8Array(u);x.set(l,e?0:x.length-l.length),l=x}if(l.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+l.length);let p=e?le(l):ur(l);if(s&&(p=at(p,r)),!d&&!f.isValid(p))throw new Error("invalid field element: outside of range 0..ORDER");return p},invertBatch:l=>Xr(f,l),cmov:(l,d,p)=>p?d:l});return Object.freeze(f)}function Mc(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 Fi(r){let t=Mc(r);return t+Math.ceil(t/2)}function Hi(r,t,e=!1){let n=r.length,o=Mc(t),i=Fi(t);if(n<16||n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);let s=e?le(r):ur(r),a=at(s,t-dt)+dt;return e?Mi(a,o):Kn(a,o)}var fr=BigInt(0),qe=BigInt(1);function jr(r,t){let e=t.negate();return r?e:t}function he(r,t){let e=Xr(r.Fp,t.map(n=>n.Z));return t.map((n,o)=>r.fromAffine(n.toAffine(e[o])))}function Vc(r,t){if(!Number.isSafeInteger(r)||r<=0||r>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+r)}function zi(r,t){Vc(r,t);let e=Math.ceil(t/r)+1,n=2**(r-1),o=2**r,i=Ie(r),s=BigInt(r);return{windows:e,windowSize:n,mask:i,maxNumber:o,shiftBy:s}}function kc(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+=qe);let u=t*n,h=u+Math.abs(a)-1,f=a===0,l=a<0,d=t%2!==0;return{nextN:c,offset:h,isZero:f,isNeg:l,isNegF:d,offsetF:u}}function xh(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 wh(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,Fc=new WeakMap;function $i(r){return Fc.get(r)||1}function Kc(r){if(r!==fr)throw new Error("invalid wNAF")}var hr=class{constructor(t,e){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=e}_unsafeLadder(t,e,n=this.ZERO){let o=t;for(;e>fr;)e&qe&&(n=n.add(o)),o=o.double(),e>>=qe;return n}precomputeWindow(t,e){let{windows:n,windowSize:o}=zi(e,this.bits),i=[],s=t,a=s;for(let c=0;c<n;c++){a=s,i.push(a);for(let u=1;u<o;u++)a=a.add(s),i.push(a);s=a.double()}return i}wNAF(t,e,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,i=this.BASE,s=zi(t,this.bits);for(let a=0;a<s.windows;a++){let{nextN:c,offset:u,isZero:h,isNeg:f,isNegF:l,offsetF:d}=kc(n,a,s);n=c,h?i=i.add(jr(l,e[d])):o=o.add(jr(f,e[u]))}return Kc(n),{p:o,f:i}}wNAFUnsafe(t,e,n,o=this.ZERO){let i=zi(t,this.bits);for(let s=0;s<i.windows&&n!==fr;s++){let{nextN:a,offset:c,isZero:u,isNeg:h}=kc(n,s,i);if(n=a,!u){let f=e[c];o=o.add(h?f.negate():f)}}return Kc(n),o}getPrecomputes(t,e,n){let o=Gi.get(e);return o||(o=this.precomputeWindow(e,t),t!==1&&(typeof n=="function"&&(o=n(o)),Gi.set(e,o))),o}cached(t,e,n){let o=$i(t);return this.wNAF(o,this.getPrecomputes(o,t,n),e)}unsafe(t,e,n,o){let i=$i(t);return i===1?this._unsafeLadder(t,e,o):this.wNAFUnsafe(i,this.getPrecomputes(i,t,n),e,o)}createCache(t,e){Vc(e,this.bits),Fc.set(t,e),Gi.delete(t)}hasCache(t){return $i(t)!==1}};function Hc(r,t,e,n){let o=t,i=r.ZERO,s=r.ZERO;for(;e>fr||n>fr;)e&qe&&(i=i.add(o)),n&qe&&(s=s.add(o)),o=o.double(),e>>=qe,n>>=qe;return{p1:i,p2:s}}function dr(r,t,e,n){xh(e,r),wh(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=qn(BigInt(o)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let u=Ie(c),h=new Array(Number(u)+1).fill(s),f=Math.floor((t.BITS-1)/c)*c,l=s;for(let d=f;d>=0;d-=c){h.fill(s);for(let x=0;x<i;x++){let S=n[x],g=Number(S>>BigInt(d)&u);h[g]=h[g].add(e[x])}let p=s;for(let x=h.length-1,S=s;x>0;x--)S=S.add(h[x]),p=p.add(S);if(l=l.add(p),d!==0)for(let x=0;x<c;x++)l=l.double()}return l}function qc(r,t,e){if(t){if(t.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Vi(t),t}else return Nt(r,{isLE:e})}function Fn(r,t,e={},n){if(n===void 0&&(n=r==="edwards"),!t||typeof t!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let u=t[c];if(!(typeof u=="bigint"&&u>fr))throw new Error(`CURVE.${c} must be positive bigint`)}let o=qc(t.p,e.Fp,n),i=qc(t.n,e.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(t[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:i}}var Ce=BigInt(0),pt=BigInt(1),Zi=BigInt(2),Eh=BigInt(8);function Sh(r,t,e,n){let o=r.sqr(e),i=r.sqr(n),s=r.add(r.mul(t.a,o),i),a=r.add(r.ONE,r.mul(t.d,r.mul(o,i)));return r.eql(s,a)}function vh(r,t={}){let e=Fn("edwards",r,t,t.FpFnLE),{Fp:n,Fn:o}=e,i=e.CURVE,{h:s}=i;Te(t,{},{uvRatio:"function"});let a=Zi<<BigInt(o.BYTES*8)-pt,c=S=>n.create(S),u=t.uvRatio||((S,g)=>{try{return{isValid:!0,value:n.sqrt(n.div(S,g))}}catch{return{isValid:!1,value:Ce}}});if(!Sh(n,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function h(S,g,_=!1){let w=_?pt:Ce;return Yr("coordinate "+S,g,w,a),g}function f(S){if(!(S instanceof p))throw new Error("ExtendedPoint expected")}let l=lr((S,g)=>{let{X:_,Y:w,Z:C}=S,L=S.is0();g==null&&(g=L?Eh:n.inv(C));let V=c(_*g),q=c(w*g),N=n.mul(C,g);if(L)return{x:Ce,y:pt};if(N!==pt)throw new Error("invZ was invalid");return{x:V,y:q}}),d=lr(S=>{let{a:g,d:_}=i;if(S.is0())throw new Error("bad point: ZERO");let{X:w,Y:C,Z:L,T:V}=S,q=c(w*w),N=c(C*C),E=c(L*L),D=c(E*E),U=c(q*g),P=c(E*c(U+N)),b=c(D+c(_*c(q*N)));if(P!==b)throw new Error("bad point: equation left != right (1)");let m=c(w*C),y=c(L*V);if(m!==y)throw new Error("bad point: equation left != right (2)");return!0});class p{constructor(g,_,w,C){this.X=h("x",g),this.Y=h("y",_),this.Z=h("z",w,!0),this.T=h("t",C),Object.freeze(this)}static CURVE(){return i}static fromAffine(g){if(g instanceof p)throw new Error("extended point not allowed");let{x:_,y:w}=g||{};return h("x",_),h("y",w),new p(_,w,pt,c(_*w))}static fromBytes(g,_=!1){let w=n.BYTES,{a:C,d:L}=i;g=ki(Ot(g,w,"point")),ue(_,"zip215");let V=ki(g),q=g[w-1];V[w-1]=q&-129;let N=le(V),E=_?a:n.ORDER;Yr("point.y",N,Ce,E);let D=c(N*N),U=c(D-pt),P=c(L*D-C),{isValid:b,value:m}=u(U,P);if(!b)throw new Error("bad point: invalid y coordinate");let y=(m&pt)===pt,v=(q&128)!==0;if(!_&&m===Ce&&v)throw new Error("bad point: x=0 and x_0=1");return v!==y&&(m=c(-m)),p.fromAffine({x:m,y:N})}static fromHex(g,_=!1){return p.fromBytes(Y("point",g),_)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,_=!0){return x.createCache(this,g),_||this.multiply(Zi),this}assertValidity(){d(this)}equals(g){f(g);let{X:_,Y:w,Z:C}=this,{X:L,Y:V,Z:q}=g,N=c(_*q),E=c(L*C),D=c(w*q),U=c(V*C);return N===E&&D===U}is0(){return this.equals(p.ZERO)}negate(){return new p(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:g}=i,{X:_,Y:w,Z:C}=this,L=c(_*_),V=c(w*w),q=c(Zi*c(C*C)),N=c(g*L),E=_+w,D=c(c(E*E)-L-V),U=N+V,P=U-q,b=N-V,m=c(D*P),y=c(U*b),v=c(D*b),A=c(P*U);return new p(m,y,A,v)}add(g){f(g);let{a:_,d:w}=i,{X:C,Y:L,Z:V,T:q}=this,{X:N,Y:E,Z:D,T:U}=g,P=c(C*N),b=c(L*E),m=c(q*w*U),y=c(V*D),v=c((C+L)*(N+E)-P-b),A=y-m,B=y+m,I=c(b-_*P),T=c(v*A),O=c(B*I),M=c(v*I),rt=c(A*B);return new p(T,O,rt,M)}subtract(g){return this.add(g.negate())}multiply(g){if(!o.isValidNot0(g))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:_,f:w}=x.cached(this,g,C=>he(p,C));return he(p,[_,w])[0]}multiplyUnsafe(g,_=p.ZERO){if(!o.isValid(g))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return g===Ce?p.ZERO:this.is0()||g===pt?this:x.unsafe(this,g,w=>he(p,w),_)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}isTorsionFree(){return x.unsafe(this,i.n).is0()}toAffine(g){return l(this,g)}clearCofactor(){return s===pt?this:this.multiplyUnsafe(s)}toBytes(){let{x:g,y:_}=this.toAffine(),w=n.toBytes(_);return w[w.length-1]|=g&pt?128:0,w}toHex(){return qt(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(g){return he(p,g)}static msm(g,_){return dr(p,o,g,_)}_setWindowSize(g){this.precompute(g)}toRawBytes(){return this.toBytes()}}p.BASE=new p(i.Gx,i.Gy,pt,c(i.Gx*i.Gy)),p.ZERO=new p(Ce,pt,pt,Ce),p.Fp=n,p.Fn=o;let x=new hr(p,o.BITS);return p.BASE.precompute(8),p}var Hn=class{constructor(t){this.ep=t}static fromBytes(t){Ki()}static fromHex(t){Ki()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(t){return this.ep.toAffine(t)}toHex(){return qt(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(t){return this.assertSame(t),this.init(this.ep.add(t.ep))}subtract(t){return this.assertSame(t),this.init(this.ep.subtract(t.ep))}multiply(t){return this.init(this.ep.multiply(t))}multiplyUnsafe(t){return this.init(this.ep.multiplyUnsafe(t))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(t,e){return this.init(this.ep.precompute(t,e))}toRawBytes(){return this.toBytes()}};function _h(r,t,e={}){if(typeof t!="function")throw new Error('"hash" function param is required');Te(e,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=e,{BASE:o,Fp:i,Fn:s}=r,a=e.randomBytes||cr,c=e.adjustScalarBytes||(E=>E),u=e.domain||((E,D,U)=>{if(ue(U,"phflag"),D.length||U)throw new Error("Contexts/pre-hash are not supported");return E});function h(E){return s.create(le(E))}function f(E){let D=w.secretKey;E=Y("private key",E,D);let U=Y("hashed private key",t(E),2*D),P=c(U.slice(0,D)),b=U.slice(D,2*D),m=h(P);return{head:P,prefix:b,scalar:m}}function l(E){let{head:D,prefix:U,scalar:P}=f(E),b=o.multiply(P),m=b.toBytes();return{head:D,prefix:U,scalar:P,point:b,pointBytes:m}}function d(E){return l(E).pointBytes}function p(E=Uint8Array.of(),...D){let U=vt(...D);return h(t(u(U,Y("context",E),!!n)))}function x(E,D,U={}){E=Y("message",E),n&&(E=n(E));let{prefix:P,scalar:b,pointBytes:m}=l(D),y=p(U.context,P,E),v=o.multiply(y).toBytes(),A=p(U.context,v,m,E),B=s.create(y+A*b);if(!s.isValid(B))throw new Error("sign failed: invalid s");let I=vt(v,s.toBytes(B));return Ot(I,w.signature,"result")}let S={zip215:!0};function g(E,D,U,P=S){let{context:b,zip215:m}=P,y=w.signature;E=Y("signature",E,y),D=Y("message",D),U=Y("publicKey",U,w.publicKey),m!==void 0&&ue(m,"zip215"),n&&(D=n(D));let v=y/2,A=E.subarray(0,v),B=le(E.subarray(v,y)),I,T,O;try{I=r.fromBytes(U,m),T=r.fromBytes(A,m),O=o.multiplyUnsafe(B)}catch{return!1}if(!m&&I.isSmallOrder())return!1;let M=p(b,T.toBytes(),I.toBytes(),D);return T.add(I.multiplyUnsafe(M)).subtract(O).clearCofactor().is0()}let _=i.BYTES,w={secretKey:_,publicKey:_,signature:2*_,seed:_};function C(E=a(w.seed)){return Ot(E,w.seed,"seed")}function L(E){let D=N.randomSecretKey(E);return{secretKey:D,publicKey:d(D)}}function V(E){return se(E)&&E.length===s.BYTES}function q(E,D){try{return!!r.fromBytes(E,D)}catch{return!1}}let N={getExtendedPublicKey:l,randomSecretKey:C,isValidSecretKey:V,isValidPublicKey:q,toMontgomery(E){let{y:D}=r.fromBytes(E),U=w.publicKey,P=U===32;if(!P&&U!==57)throw new Error("only defined for 25519 and 448");let b=P?i.div(pt+D,pt-D):i.div(D-pt,D+pt);return i.toBytes(b)},toMontgomeryPriv(E){let D=w.secretKey;Ot(E,D);let U=t(E.subarray(0,D));return c(U).subarray(0,D)},randomPrivateKey:C,precompute(E=8,D=r.BASE){return D.precompute(E,!1)}};return Object.freeze({keygen:L,getPublicKey:d,sign:x,verify:g,utils:N,Point:r,lengths:w})}function Ah(r){let t={a:r.a,d:r.d,p:r.Fp.ORDER,n:r.n,h:r.h,Gx:r.Gx,Gy:r.Gy},e=r.Fp,n=Nt(t.n,r.nBitLength,!0),o={Fp:e,Fn:n,uvRatio:r.uvRatio},i={randomBytes:r.randomBytes,adjustScalarBytes:r.adjustScalarBytes,domain:r.domain,prehash:r.prehash,mapToCurve:r.mapToCurve};return{CURVE:t,curveOpts:o,hash:r.hash,eddsaOpts:i}}function Ih(r,t){let e=t.Point;return Object.assign({},t,{ExtendedPoint:e,CURVE:r,nBitLength:e.Fn.BITS,nByteLength:e.Fn.BYTES})}function zc(r){let{CURVE:t,curveOpts:e,hash:n,eddsaOpts:o}=Ah(r),i=vh(t,e),s=_h(i,n,o);return Ih(r,s)}var Th=BigInt(0),de=BigInt(1),Gc=BigInt(2),hy=BigInt(3),Ch=BigInt(5),Dh=BigInt(8),pr=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Qr={p:pr,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Dh,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Ph(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),i=pr,a=r*r%i*r%i,c=tt(a,Gc,i)*a%i,u=tt(c,de,i)*r%i,h=tt(u,Ch,i)*u%i,f=tt(h,t,i)*h%i,l=tt(f,e,i)*f%i,d=tt(l,n,i)*l%i,p=tt(d,o,i)*d%i,x=tt(p,o,i)*d%i,S=tt(x,t,i)*h%i;return{pow_p_5_8:tt(S,Gc,i)*r%i,b2:a}}function Bh(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var Wi=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function ji(r,t){let e=pr,n=at(t*t*t,e),o=at(n*n*t,e),i=Ph(r*o).pow_p_5_8,s=at(r*n*i,e),a=at(t*s*s,e),c=s,u=at(s*Wi,e),h=a===r,f=a===at(-r,e),l=a===at(-r*Wi,e);return h&&(s=c),(f||l)&&(s=u),fe(s,e)&&(s=at(-s,e)),{isValid:h||f,value:s}}var De=Nt(Qr.p,{isLE:!0}),Rh=Nt(Qr.n,{isLE:!0}),Lh={...Qr,Fp:De,hash:vc,adjustScalarBytes:Bh,uvRatio:ji},pe=zc(Lh);var Yi=Wi,Oh=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Nh=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),Uh=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),Mh=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),$c=r=>ji(de,r),kh=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Xi=r=>pe.Point.Fp.create(le(r)&kh);function Zc(r){let{d:t}=Qr,e=pr,n=g=>De.create(g),o=n(Yi*r*r),i=n((o+de)*Uh),s=BigInt(-1),a=n((s-t*o)*n(o+t)),{isValid:c,value:u}=ji(i,a),h=n(u*r);fe(h,e)||(h=n(-h)),c||(u=h),c||(s=o);let f=n(s*(o-de)*Mh-a),l=u*u,d=n((u+u)*a),p=n(f*Oh),x=n(de-l),S=n(de+l);return new pe.Point(n(d*S),n(x*p),n(p*S),n(d*x))}function Kh(r){Dt(r,64);let t=Xi(r.subarray(0,32)),e=Zc(t),n=Xi(r.subarray(32,64)),o=Zc(n);return new me(e.add(o))}var me=class r extends Hn{constructor(t){super(t)}static fromAffine(t){return new r(pe.Point.fromAffine(t))}assertSame(t){if(!(t instanceof r))throw new Error("RistrettoPoint expected")}init(t){return new r(t)}static hashToCurve(t){return Kh(Y("ristrettoHash",t,64))}static fromBytes(t){Dt(t,32);let{a:e,d:n}=Qr,o=pr,i=C=>De.create(C),s=Xi(t);if(!Ac(De.toBytes(s),t)||fe(s,o))throw new Error("invalid ristretto255 encoding 1");let a=i(s*s),c=i(de+e*a),u=i(de-e*a),h=i(c*c),f=i(u*u),l=i(e*n*h-f),{isValid:d,value:p}=$c(i(l*f)),x=i(p*u),S=i(p*x*l),g=i((s+s)*x);fe(g,o)&&(g=i(-g));let _=i(c*S),w=i(g*_);if(!d||fe(w,o)||_===Th)throw new Error("invalid ristretto255 encoding 2");return new r(new pe.Point(g,_,de,w))}static fromHex(t){return r.fromBytes(Y("ristrettoHex",t,32))}static msm(t,e){return dr(r,pe.Point.Fn,t,e)}toBytes(){let{X:t,Y:e,Z:n,T:o}=this.ep,i=pr,s=S=>De.create(S),a=s(s(n+e)*s(n-e)),c=s(t*e),u=s(c*c),{value:h}=$c(s(a*u)),f=s(h*a),l=s(h*c),d=s(f*l*o),p;if(fe(o*d,i)){let S=s(e*Yi),g=s(t*Yi);t=S,e=g,p=s(f*Nh)}else p=l;fe(t*d,i)&&(e=s(-e));let x=s((n-e)*p);return fe(x,i)&&(x=s(-x)),De.toBytes(x)}equals(t){this.assertSame(t);let{X:e,Y:n}=this.ep,{X:o,Y:i}=t.ep,s=u=>De.create(u),a=s(e*i)===s(n*o),c=s(n*i)===s(e*o);return a||c}is0(){return this.equals(r.ZERO)}};me.BASE=new me(pe.Point.BASE);me.ZERO=new me(pe.Point.ZERO);me.Fp=De;me.Fn=Rh;var Jr=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},zn=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 zn("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return t}};var Vt=Wc;var Gn=32;var Qi,qh=(async()=>{try{return await Vt.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function Vh(r,t,e){if(r.buffer instanceof ArrayBuffer){let n=await Vt.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await Vt.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 Fh(r,t,e){return pe.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}async function Yc(r,t,e){return Qi==null&&(Qi=await qh),Qi?Vh(r,t,e):Fh(r,t,e)}function $n(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Zn=class{type="Ed25519";raw;constructor(t){this.raw=Ji(t,Gn)}toMultihash(){return zt.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:ft(this.raw,t.raw)}verify(t,e,n){n?.signal?.throwIfAborted();let o=Yc(this.raw,e,t);return $n(o)?o.then(i=>(n?.signal?.throwIfAborted(),i)):o}};function ts(r){return r=Ji(r,Gn),new Zn(r)}function Ji(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new lt(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}var zh=Math.pow(2,7),Gh=Math.pow(2,14),$h=Math.pow(2,21),es=Math.pow(2,28),rs=Math.pow(2,35),ns=Math.pow(2,42),os=Math.pow(2,49),Z=128,xt=127;function Pt(r){if(r<zh)return 1;if(r<Gh)return 2;if(r<$h)return 3;if(r<es)return 4;if(r<rs)return 5;if(r<ns)return 6;if(r<os)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function mr(r,t,e=0){switch(Pt(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 Zh(r,t,e=0){switch(Pt(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 is(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)*es,e<Z)||(e=r[t+5],n+=(e&xt)*rs,e<Z)||(e=r[t+6],n+=(e&xt)*ns,e<Z)||(e=r[t+7],n+=(e&xt)*os,e<Z))return n;throw new RangeError("Could not decode varint")}function Wh(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)*es,e<Z)||(e=r.get(t+5),n+=(e&xt)*rs,e<Z)||(e=r.get(t+6),n+=(e&xt)*ns,e<Z)||(e=r.get(t+7),n+=(e&xt)*os,e<Z))return n;throw new RangeError("Could not decode varint")}function yr(r,t,e=0){return t==null&&(t=Tt(Pt(r))),t instanceof Uint8Array?mr(r,t,e):Zh(r,t,e)}function tn(r,t=0){return r instanceof Uint8Array?is(r,t):Wh(r,t)}var as=new Float32Array([-0]),Pe=new Uint8Array(as.buffer);function jc(r,t,e){as[0]=r,t[e]=Pe[0],t[e+1]=Pe[1],t[e+2]=Pe[2],t[e+3]=Pe[3]}function Qc(r,t){return Pe[0]=r[t],Pe[1]=r[t+1],Pe[2]=r[t+2],Pe[3]=r[t+3],as[0]}var cs=new Float64Array([-0]),wt=new Uint8Array(cs.buffer);function Jc(r,t,e){cs[0]=r,t[e]=wt[0],t[e+1]=wt[1],t[e+2]=wt[2],t[e+3]=wt[3],t[e+4]=wt[4],t[e+5]=wt[5],t[e+6]=wt[6],t[e+7]=wt[7]}function tu(r,t){return wt[0]=r[t],wt[1]=r[t+1],wt[2]=r[t+2],wt[3]=r[t+3],wt[4]=r[t+4],wt[5]=r[t+5],wt[6]=r[t+6],wt[7]=r[t+7],cs[0]}var Yh=BigInt(Number.MAX_SAFE_INTEGER),Xh=BigInt(Number.MIN_SAFE_INTEGER),Ut=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 Ve;if(t<Yh&&t>Xh)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>eu&&(o=0n,++n>eu&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return Ve;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):Ve}},Ve=new Ut(0,0);Ve.toBigInt=function(){return 0n};Ve.zzEncode=Ve.zzDecode=function(){return this};Ve.length=function(){return 1};var eu=4294967296n;function ru(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 nu(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 us(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 Wn(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var ls=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 Wn(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw $t(this,4);return Wn(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw $t(this,4);let t=Qc(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw $t(this,4);let t=tu(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 nu(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 Ut(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=Wn(this.buf,this.pos+=4),e=Wn(this.buf,this.pos+=4);return new Ut(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=is(this.buf,this.pos);return this.pos+=Pt(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 fs(r){return new ls(r instanceof Uint8Array?r:r.subarray())}function Bt(r,t,e){let n=fs(r);return t.decode(n,void 0,e)}function hs(r){let t=r??8192,e=t>>>1,n,o=t;return function(s){if(s<1||s>e)return Tt(s);o+s>t&&(n=Tt(t),o=0);let a=n.subarray(o,o+=s);return(o&7)!==0&&(o=(o|7)+1),a}}var Fe=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function ds(){}var ms=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},jh=hs();function Qh(r){return globalThis.Buffer!=null?Tt(r):jh(r)}var rn=class{len;head;tail;states;constructor(){this.len=0,this.head=new Fe(ds,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new Fe(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new ys((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(Yn,10,Ut.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=Ut.fromBigInt(t);return this._push(Yn,e.length(),e)}uint64Number(t){return this._push(mr,Pt(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=Ut.fromBigInt(t).zzEncode();return this._push(Yn,e.length(),e)}sint64Number(t){let e=Ut.fromNumber(t).zzEncode();return this._push(Yn,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(ps,1,t?1:0)}fixed32(t){return this._push(en,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=Ut.fromBigInt(t);return this._push(en,4,e.lo)._push(en,4,e.hi)}fixed64Number(t){let e=Ut.fromNumber(t);return this._push(en,4,e.lo)._push(en,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(jc,4,t)}double(t){return this._push(Jc,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(ps,1,0):this.uint32(e)._push(td,e,t)}string(t){let e=ru(t);return e!==0?this.uint32(e)._push(us,e,t):this._push(ps,1,0)}fork(){return this.states=new ms(this),this.head=this.tail=new Fe(ds,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 Fe(ds,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=Qh(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function ps(r,t,e){t[e]=r&255}function Jh(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var ys=class extends Fe{next;constructor(t,e){super(Jh,t,e),this.next=void 0}};function Yn(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 en(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 td(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(rn.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(ed,t,r),this},rn.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(rd,t,r),this});function ed(r,t,e){t.set(r,e)}function rd(r,t,e){r.length<40?us(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(k(r),e)}function gs(){return new rn}function Rt(r,t){let e=gs();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var gr;(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"})(gr||(gr={}));function Xn(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function He(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 Xn("enum",gr.VARINT,e,n)}function Lt(r,t){return Xn("message",gr.LENGTH_DELIMITED,r,t)}var nn=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 bs;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(bs||(bs={}));(function(r){r.codec=()=>He(bs)})(ut||(ut={}));var Qt;(function(r){let t;r.codec=()=>(t==null&&(t=Lt((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=>Rt(e,r.codec()),r.decode=(e,n)=>Bt(e,r.codec(),n)})(Qt||(Qt={}));var xs;(function(r){let t;r.codec=()=>(t==null&&(t=Lt((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=>Rt(e,r.codec()),r.decode=(e,n)=>Bt(e,r.codec(),n)})(xs||(xs={}));var sn={};It(sn,{MAX_RSA_KEY_SIZE:()=>ws,generateRSAKeyPair:()=>uu,jwkToJWKKeyPair:()=>lu,jwkToPkcs1:()=>sd,jwkToPkix:()=>_s,jwkToRSAPrivateKey:()=>Cs,pkcs1MessageToJwk:()=>Ss,pkcs1MessageToRSAPrivateKey:()=>As,pkcs1ToJwk:()=>id,pkcs1ToRSAPrivateKey:()=>cu,pkixMessageToJwk:()=>vs,pkixMessageToRSAPublicKey:()=>Ts,pkixToJwk:()=>ad,pkixToRSAPublicKey:()=>Is});var jn=kn;var br=class{type="RSA";jwk;_raw;_multihash;constructor(t,e){this.jwk=t,this._multihash=e}get raw(){return this._raw==null&&(this._raw=sn.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:ft(this.raw,t.raw)}verify(t,e,n){return au(this.jwk,e,t,n)}},on=class{type="RSA";jwk;_raw;publicKey;constructor(t,e){this.jwk=t,this.publicKey=e}get raw(){return this._raw==null&&(this._raw=sn.jwkToPkcs1(this.jwk)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:ft(this.raw,t.raw)}sign(t,e){return su(this.jwk,t,e)}};var ws=8192,Es=18,nd=1062,od=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function id(r){let t=oe(r);return Ss(t)}function Ss(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 sd(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 lt("JWK was missing components");return Se([Ct(Uint8Array.from([0])),Ct(k(r.n,"base64url")),Ct(k(r.e,"base64url")),Ct(k(r.d,"base64url")),Ct(k(r.p,"base64url")),Ct(k(r.q,"base64url")),Ct(k(r.dp,"base64url")),Ct(k(r.dq,"base64url")),Ct(k(r.qi,"base64url"))]).subarray()}function ad(r){let t=oe(r,{offset:0});return vs(t)}function vs(r){let t=oe(r[1],{offset:0});return{kty:"RSA",n:K(t[0],"base64url"),e:K(t[1],"base64url")}}function _s(r){if(r.n==null||r.e==null)throw new lt("JWK was missing components");return Se([od,Ln(Se([Ct(k(r.n,"base64url")),Ct(k(r.e,"base64url"))]))]).subarray()}function cu(r){let t=oe(r);return As(t)}function As(r){let t=Ss(r);return Cs(t)}function Is(r,t){if(r.byteLength>=nd)throw new Qe("Key size is too large");let e=oe(r,{offset:0});return Ts(e,r,t)}function Ts(r,t,e){let n=vs(r);if(e==null){let o=jn(Qt.encode({Type:ut.RSA,Data:t}));e=Ht(Es,o)}return new br(n,e)}function Cs(r){if(hu(r)>ws)throw new lt("Key size is too large");let t=lu(r),e=jn(Qt.encode({Type:ut.RSA,Data:_s(t.publicKey)})),n=Ht(Es,e);return new on(t.privateKey,new br(t.publicKey,n))}async function uu(r){if(r>ws)throw new lt("Key size is too large");let t=await fu(r),e=jn(Qt.encode({Type:ut.RSA,Data:_s(t.publicKey)})),n=Ht(Es,e);return new on(t.privateKey,new br(t.publicKey,n))}function lu(r){if(r==null)throw new lt("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function fu(r,t){let e=await Vt.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 cd(e,t);return{privateKey:n[0],publicKey:n[1]}}async function su(r,t,e){let n=await Vt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);e?.signal?.throwIfAborted();let o=await Vt.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 au(r,t,e,n){let o=await Vt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let i=await Vt.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,t,e instanceof Uint8Array?e:e.subarray());return n?.signal?.throwIfAborted(),i}async function cd(r,t){if(r.privateKey==null||r.publicKey==null)throw new lt("Private and public key are required");let e=await Promise.all([Vt.get().subtle.exportKey("jwk",r.privateKey),Vt.get().subtle.exportKey("jwk",r.publicKey)]);return t?.signal?.throwIfAborted(),e}function hu(r){if(r.kty!=="RSA")throw new lt("invalid key type");if(r.n==null)throw new lt("invalid key modulus");return k(r.n,"base64url").length*8}var Qn=class extends sr{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,On(t);let n=zr(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 ar(this),this.iHash.update(t),this}digestInto(t){ar(this),Dt(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()}},Ds=(r,t,e)=>new Qn(r,t).update(e).digest();Ds.create=(r,t)=>new Qn(r,t);var du=(r,t)=>(r+(r>=0?t:-t)/pu)/t;function ud(r,t,e){let[[n,o],[i,s]]=t,a=du(s*r,e),c=du(-o*r,e),u=r-a*n-c*i,h=-a*o-c*s,f=u<ge,l=h<ge;f&&(u=-u),l&&(h=-h);let d=Ie(Math.ceil(qn(e)/2))+wr;if(u<ge||u>=d||h<ge||h>=d)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:f,k1:u,k2neg:l,k2:h}}function Bs(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function Ps(r,t){let e={};for(let n of Object.keys(t))e[n]=r[n]===void 0?t[n]:r[n];return ue(e.lowS,"lowS"),ue(e.prehash,"prehash"),e.format!==void 0&&Bs(e.format),e}var Rs=class extends Error{constructor(t=""){super(t)}},ye={Err:Rs,_tlv:{encode:(r,t)=>{let{Err:e}=ye;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=Wr(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let i=n>127?Wr(o.length/2|128):"";return Wr(r)+i+o+t},decode(r,t){let{Err:e}=ye,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 u=t.subarray(n,n+c);if(u.length!==c)throw new e("tlv.decode: length bytes not complete");if(u[0]===0)throw new e("tlv.decode(long): zero leftmost byte");for(let h of u)s=s<<8|h;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}=ye;if(r<ge)throw new t("integer: negative integers are not allowed");let e=Wr(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}=ye;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 ur(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=ye,o=Y("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:u,l:h}=n.decode(2,c);if(h.length)throw new t("invalid signature: left bytes after parsing");return{r:e.decode(a),s:e.decode(u)}},hexFromSig(r){let{_tlv:t,_int:e}=ye,n=t.encode(2,e.encode(r.r)),o=t.encode(2,e.encode(r.s)),i=n+o;return t.encode(48,i)}},ge=BigInt(0),wr=BigInt(1),pu=BigInt(2),Jn=BigInt(3),ld=BigInt(4);function xr(r,t){let{BYTES:e}=r,n;if(typeof t=="bigint")n=t;else{let o=Y("private key",t);try{n=r.fromBytes(o)}catch{throw new Error(`invalid private key: expected ui8a of size ${e}, got ${typeof t}`)}}if(!r.isValidNot0(n))throw new Error("invalid private key: out of range [1..N-1]");return n}function fd(r,t={}){let e=Fn("weierstrass",r,t),{Fp:n,Fn:o}=e,i=e.CURVE,{h:s,n:a}=i;Te(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:c}=t;if(c&&(!n.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let u=yu(n,o);function h(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(P,b,m){let{x:y,y:v}=b.toAffine(),A=n.toBytes(y);if(ue(m,"isCompressed"),m){h();let B=!n.isOdd(v);return vt(mu(B),A)}else return vt(Uint8Array.of(4),A,n.toBytes(v))}function l(P){Ot(P,void 0,"Point");let{publicKey:b,publicKeyUncompressed:m}=u,y=P.length,v=P[0],A=P.subarray(1);if(y===b&&(v===2||v===3)){let B=n.fromBytes(A);if(!n.isValid(B))throw new Error("bad point: is not on curve, wrong x");let I=x(B),T;try{T=n.sqrt(I)}catch(rt){let Q=rt instanceof Error?": "+rt.message:"";throw new Error("bad point: is not on curve, sqrt error"+Q)}h();let O=n.isOdd(T);return(v&1)===1!==O&&(T=n.neg(T)),{x:B,y:T}}else if(y===m&&v===4){let B=n.BYTES,I=n.fromBytes(A.subarray(0,B)),T=n.fromBytes(A.subarray(B,B*2));if(!S(I,T))throw new Error("bad point: is not on curve");return{x:I,y:T}}else throw new Error(`bad point: got length ${y}, expected compressed=${b} or uncompressed=${m}`)}let d=t.toBytes||f,p=t.fromBytes||l;function x(P){let b=n.sqr(P),m=n.mul(b,P);return n.add(n.add(m,n.mul(P,i.a)),i.b)}function S(P,b){let m=n.sqr(b),y=x(P);return n.eql(m,y)}if(!S(i.Gx,i.Gy))throw new Error("bad curve params: generator point");let g=n.mul(n.pow(i.a,Jn),ld),_=n.mul(n.sqr(i.b),BigInt(27));if(n.is0(n.add(g,_)))throw new Error("bad curve params: a or b");function w(P,b,m=!1){if(!n.isValid(b)||m&&n.is0(b))throw new Error(`bad point coordinate ${P}`);return b}function C(P){if(!(P instanceof E))throw new Error("ProjectivePoint expected")}function L(P){if(!c||!c.basises)throw new Error("no endo");return ud(P,c.basises,o.ORDER)}let V=lr((P,b)=>{let{X:m,Y:y,Z:v}=P;if(n.eql(v,n.ONE))return{x:m,y};let A=P.is0();b==null&&(b=A?n.ONE:n.inv(v));let B=n.mul(m,b),I=n.mul(y,b),T=n.mul(v,b);if(A)return{x:n.ZERO,y:n.ZERO};if(!n.eql(T,n.ONE))throw new Error("invZ was invalid");return{x:B,y:I}}),q=lr(P=>{if(P.is0()){if(t.allowInfinityPoint&&!n.is0(P.Y))return;throw new Error("bad point: ZERO")}let{x:b,y:m}=P.toAffine();if(!n.isValid(b)||!n.isValid(m))throw new Error("bad point: x or y not field elements");if(!S(b,m))throw new Error("bad point: equation left != right");if(!P.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function N(P,b,m,y,v){return m=new E(n.mul(m.X,P),m.Y,m.Z),b=jr(y,b),m=jr(v,m),b.add(m)}class E{constructor(b,m,y){this.X=w("x",b),this.Y=w("y",m,!0),this.Z=w("z",y),Object.freeze(this)}static CURVE(){return i}static fromAffine(b){let{x:m,y}=b||{};if(!b||!n.isValid(m)||!n.isValid(y))throw new Error("invalid affine point");if(b instanceof E)throw new Error("projective point not allowed");return n.is0(m)&&n.is0(y)?E.ZERO:new E(m,y,n.ONE)}static fromBytes(b){let m=E.fromAffine(p(Ot(b,void 0,"point")));return m.assertValidity(),m}static fromHex(b){return E.fromBytes(Y("pointHex",b))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(b=8,m=!0){return U.createCache(this,b),m||this.multiply(Jn),this}assertValidity(){q(this)}hasEvenY(){let{y:b}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(b)}equals(b){C(b);let{X:m,Y:y,Z:v}=this,{X:A,Y:B,Z:I}=b,T=n.eql(n.mul(m,I),n.mul(A,v)),O=n.eql(n.mul(y,I),n.mul(B,v));return T&&O}negate(){return new E(this.X,n.neg(this.Y),this.Z)}double(){let{a:b,b:m}=i,y=n.mul(m,Jn),{X:v,Y:A,Z:B}=this,I=n.ZERO,T=n.ZERO,O=n.ZERO,M=n.mul(v,v),rt=n.mul(A,A),Q=n.mul(B,B),z=n.mul(v,A);return z=n.add(z,z),O=n.mul(v,B),O=n.add(O,O),I=n.mul(b,O),T=n.mul(y,Q),T=n.add(I,T),I=n.sub(rt,T),T=n.add(rt,T),T=n.mul(I,T),I=n.mul(z,I),O=n.mul(y,O),Q=n.mul(b,Q),z=n.sub(M,Q),z=n.mul(b,z),z=n.add(z,O),O=n.add(M,M),M=n.add(O,M),M=n.add(M,Q),M=n.mul(M,z),T=n.add(T,M),Q=n.mul(A,B),Q=n.add(Q,Q),M=n.mul(Q,z),I=n.sub(I,M),O=n.mul(Q,rt),O=n.add(O,O),O=n.add(O,O),new E(I,T,O)}add(b){C(b);let{X:m,Y:y,Z:v}=this,{X:A,Y:B,Z:I}=b,T=n.ZERO,O=n.ZERO,M=n.ZERO,rt=i.a,Q=n.mul(i.b,Jn),z=n.mul(m,A),nt=n.mul(y,B),ht=n.mul(v,I),At=n.add(m,y),ot=n.add(A,B);At=n.mul(At,ot),ot=n.add(z,nt),At=n.sub(At,ot),ot=n.add(m,v);let bt=n.add(A,I);return ot=n.mul(ot,bt),bt=n.add(z,ht),ot=n.sub(ot,bt),bt=n.add(y,v),T=n.add(B,I),bt=n.mul(bt,T),T=n.add(nt,ht),bt=n.sub(bt,T),M=n.mul(rt,ot),T=n.mul(Q,ht),M=n.add(T,M),T=n.sub(nt,M),M=n.add(nt,M),O=n.mul(T,M),nt=n.add(z,z),nt=n.add(nt,z),ht=n.mul(rt,ht),ot=n.mul(Q,ot),nt=n.add(nt,ht),ht=n.sub(z,ht),ht=n.mul(rt,ht),ot=n.add(ot,ht),z=n.mul(nt,ot),O=n.add(O,z),z=n.mul(bt,ot),T=n.mul(At,T),T=n.sub(T,z),z=n.mul(At,nt),M=n.mul(bt,M),M=n.add(M,z),new E(T,O,M)}subtract(b){return this.add(b.negate())}is0(){return this.equals(E.ZERO)}multiply(b){let{endo:m}=t;if(!o.isValidNot0(b))throw new Error("invalid scalar: out of range");let y,v,A=B=>U.cached(this,B,I=>he(E,I));if(m){let{k1neg:B,k1:I,k2neg:T,k2:O}=L(b),{p:M,f:rt}=A(I),{p:Q,f:z}=A(O);v=rt.add(z),y=N(m.beta,M,Q,B,T)}else{let{p:B,f:I}=A(b);y=B,v=I}return he(E,[y,v])[0]}multiplyUnsafe(b){let{endo:m}=t,y=this;if(!o.isValid(b))throw new Error("invalid scalar: out of range");if(b===ge||y.is0())return E.ZERO;if(b===wr)return y;if(U.hasCache(this))return this.multiply(b);if(m){let{k1neg:v,k1:A,k2neg:B,k2:I}=L(b),{p1:T,p2:O}=Hc(E,y,A,I);return N(m.beta,T,O,v,B)}else return U.unsafe(y,b)}multiplyAndAddUnsafe(b,m,y){let v=this.multiplyUnsafe(m).add(b.multiplyUnsafe(y));return v.is0()?void 0:v}toAffine(b){return V(this,b)}isTorsionFree(){let{isTorsionFree:b}=t;return s===wr?!0:b?b(E,this):U.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:b}=t;return s===wr?this:b?b(E,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(b=!0){return ue(b,"isCompressed"),this.assertValidity(),d(E,this,b)}toHex(b=!0){return qt(this.toBytes(b))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(b=!0){return this.toBytes(b)}_setWindowSize(b){this.precompute(b)}static normalizeZ(b){return he(E,b)}static msm(b,m){return dr(E,o,b,m)}static fromPrivateKey(b){return E.BASE.multiply(xr(o,b))}}E.BASE=new E(i.Gx,i.Gy,n.ONE),E.ZERO=new E(n.ZERO,n.ONE,n.ZERO),E.Fp=n,E.Fn=o;let D=o.BITS,U=new hr(E,t.endo?Math.ceil(D/2):D);return E.BASE.precompute(8),E}function mu(r){return Uint8Array.of(r?2:3)}function yu(r,t){return{secretKey:t.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function hd(r,t={}){let{Fn:e}=r,n=t.randomBytes||cr,o=Object.assign(yu(r.Fp,e),{seed:Fi(e.ORDER)});function i(d){try{return!!xr(e,d)}catch{return!1}}function s(d,p){let{publicKey:x,publicKeyUncompressed:S}=o;try{let g=d.length;return p===!0&&g!==x||p===!1&&g!==S?!1:!!r.fromBytes(d)}catch{return!1}}function a(d=n(o.seed)){return Hi(Ot(d,o.seed,"seed"),e.ORDER)}function c(d,p=!0){return r.BASE.multiply(xr(e,d)).toBytes(p)}function u(d){let p=a(d);return{secretKey:p,publicKey:c(p)}}function h(d){if(typeof d=="bigint")return!1;if(d instanceof r)return!0;let{secretKey:p,publicKey:x,publicKeyUncompressed:S}=o;if(e.allowedLengths||p===x)return;let g=Y("key",d).length;return g===x||g===S}function f(d,p,x=!0){if(h(d)===!0)throw new Error("first arg must be private key");if(h(p)===!1)throw new Error("second arg must be public key");let S=xr(e,d);return r.fromHex(p).multiply(S).toBytes(x)}return Object.freeze({getPublicKey:c,getSharedSecret:f,keygen:u,Point:r,utils:{isValidSecretKey:i,isValidPublicKey:s,randomSecretKey:a,isValidPrivateKey:i,randomPrivateKey:a,normPrivateKeyToScalar:d=>xr(e,d),precompute(d=8,p=r.BASE){return p.precompute(d,!1)}},lengths:o})}function dd(r,t,e={}){On(t),Te(e,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let n=e.randomBytes||cr,o=e.hmac||((m,...y)=>Ds(t,m,vt(...y))),{Fp:i,Fn:s}=r,{ORDER:a,BITS:c}=s,{keygen:u,getPublicKey:h,getSharedSecret:f,utils:l,lengths:d}=hd(r,e),p={prehash:!1,lowS:typeof e.lowS=="boolean"?e.lowS:!1,format:void 0,extraEntropy:!1},x="compact";function S(m){let y=a>>wr;return m>y}function g(m,y){if(!s.isValidNot0(y))throw new Error(`invalid signature ${m}: out of range 1..Point.Fn.ORDER`);return y}function _(m,y){Bs(y);let v=d.signature,A=y==="compact"?v:y==="recovered"?v+1:void 0;return Ot(m,A,`${y} signature`)}class w{constructor(y,v,A){this.r=g("r",y),this.s=g("s",v),A!=null&&(this.recovery=A),Object.freeze(this)}static fromBytes(y,v=x){_(y,v);let A;if(v==="der"){let{r:O,s:M}=ye.toSig(Ot(y));return new w(O,M)}v==="recovered"&&(A=y[0],v="compact",y=y.subarray(1));let B=s.BYTES,I=y.subarray(0,B),T=y.subarray(B,B*2);return new w(s.fromBytes(I),s.fromBytes(T),A)}static fromHex(y,v){return this.fromBytes(Ue(y),v)}addRecoveryBit(y){return new w(this.r,this.s,y)}recoverPublicKey(y){let v=i.ORDER,{r:A,s:B,recovery:I}=this;if(I==null||![0,1,2,3].includes(I))throw new Error("recovery id invalid");if(a*pu<v&&I>1)throw new Error("recovery id is ambiguous for h>1 curve");let O=I===2||I===3?A+a:A;if(!i.isValid(O))throw new Error("recovery id 2 or 3 invalid");let M=i.toBytes(O),rt=r.fromBytes(vt(mu((I&1)===0),M)),Q=s.inv(O),z=L(Y("msgHash",y)),nt=s.create(-z*Q),ht=s.create(B*Q),At=r.BASE.multiplyUnsafe(nt).add(rt.multiplyUnsafe(ht));if(At.is0())throw new Error("point at infinify");return At.assertValidity(),At}hasHighS(){return S(this.s)}toBytes(y=x){if(Bs(y),y==="der")return Ue(ye.hexFromSig(this));let v=s.toBytes(this.r),A=s.toBytes(this.s);if(y==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return vt(Uint8Array.of(this.recovery),v,A)}return vt(v,A)}toHex(y){return qt(this.toBytes(y))}assertValidity(){}static fromCompact(y){return w.fromBytes(Y("sig",y),"compact")}static fromDER(y){return w.fromBytes(Y("sig",y),"der")}normalizeS(){return this.hasHighS()?new w(this.r,s.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return qt(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return qt(this.toBytes("compact"))}}let C=e.bits2int||function(y){if(y.length>8192)throw new Error("input is too large");let v=ur(y),A=y.length*8-c;return A>0?v>>BigInt(A):v},L=e.bits2int_modN||function(y){return s.create(C(y))},V=Ie(c);function q(m){return Yr("num < 2^"+c,m,ge,V),s.toBytes(m)}function N(m,y){return Ot(m,void 0,"message"),y?Ot(t(m),void 0,"prehashed message"):m}function E(m,y,v){if(["recovered","canonical"].some(nt=>nt in v))throw new Error("sign() legacy options not supported");let{lowS:A,prehash:B,extraEntropy:I}=Ps(v,p);m=N(m,B);let T=L(m),O=xr(s,y),M=[q(O),q(T)];if(I!=null&&I!==!1){let nt=I===!0?n(d.secretKey):I;M.push(Y("extraEntropy",nt))}let rt=vt(...M),Q=T;function z(nt){let ht=C(nt);if(!s.isValidNot0(ht))return;let At=s.inv(ht),ot=r.BASE.multiply(ht).toAffine(),bt=s.create(ot.x);if(bt===ge)return;let In=s.create(At*s.create(Q+bt*O));if(In===ge)return;let Ca=(ot.x===bt?0:2)|Number(ot.y&wr),Da=In;return A&&S(In)&&(Da=s.neg(In),Ca^=1),new w(bt,Da,Ca)}return{seed:rt,k2sig:z}}function D(m,y,v={}){m=Y("message",m);let{seed:A,k2sig:B}=E(m,y,v);return Tc(t.outputLen,s.BYTES,o)(A,B)}function U(m){let y,v=typeof m=="string"||se(m),A=!v&&m!==null&&typeof m=="object"&&typeof m.r=="bigint"&&typeof m.s=="bigint";if(!v&&!A)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(A)y=new w(m.r,m.s);else if(v){try{y=w.fromBytes(Y("sig",m),"der")}catch(B){if(!(B instanceof ye.Err))throw B}if(!y)try{y=w.fromBytes(Y("sig",m),"compact")}catch{return!1}}return y||!1}function P(m,y,v,A={}){let{lowS:B,prehash:I,format:T}=Ps(A,p);if(v=Y("publicKey",v),y=N(Y("message",y),I),"strict"in A)throw new Error("options.strict was renamed to lowS");let O=T===void 0?U(m):w.fromBytes(Y("sig",m),T);if(O===!1)return!1;try{let M=r.fromBytes(v);if(B&&O.hasHighS())return!1;let{r:rt,s:Q}=O,z=L(y),nt=s.inv(Q),ht=s.create(z*nt),At=s.create(rt*nt),ot=r.BASE.multiplyUnsafe(ht).add(M.multiplyUnsafe(At));return ot.is0()?!1:s.create(ot.x)===rt}catch{return!1}}function b(m,y,v={}){let{prehash:A}=Ps(v,p);return y=N(y,A),w.fromBytes(m,"recovered").recoverPublicKey(y).toBytes()}return Object.freeze({keygen:u,getPublicKey:h,getSharedSecret:f,utils:l,lengths:d,Point:r,sign:D,verify:P,recoverPublicKey:b,Signature:w,hash:t})}function pd(r){let t={a:r.a,b:r.b,p:r.Fp.ORDER,n:r.n,h:r.h,Gx:r.Gx,Gy:r.Gy},e=r.Fp,n=r.allowedPrivateKeyLengths?Array.from(new Set(r.allowedPrivateKeyLengths.map(s=>Math.ceil(s/2)))):void 0,o=Nt(t.n,{BITS:r.nBitLength,allowedLengths:n,modFromBytes:r.wrapPrivateKey}),i={Fp:e,Fn:o,allowInfinityPoint:r.allowInfinityPoint,endo:r.endo,isTorsionFree:r.isTorsionFree,clearCofactor:r.clearCofactor,fromBytes:r.fromBytes,toBytes:r.toBytes};return{CURVE:t,curveOpts:i}}function md(r){let{CURVE:t,curveOpts:e}=pd(r),n={hmac:r.hmac,randomBytes:r.randomBytes,lowS:r.lowS,bits2int:r.bits2int,bits2int_modN:r.bits2int_modN};return{CURVE:t,curveOpts:e,hash:r.hash,ecdsaOpts:n}}function yd(r,t){let e=t.Point;return Object.assign({},t,{ProjectivePoint:e,CURVE:Object.assign({},r,Vn(e.Fn.ORDER,e.Fn.BITS))})}function gu(r){let{CURVE:t,curveOpts:e,hash:n,ecdsaOpts:o}=md(r),i=fd(t,e),s=dd(i,n,o);return yd(r,s)}function bu(r,t){let e=n=>gu({...r,hash:n});return{...e(t),create:e}}var Os={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},gd={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var xu=BigInt(2);function bd(r){let t=Os.p,e=BigInt(3),n=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),u=r*r*r%t,h=u*u*r%t,f=tt(h,e,t)*h%t,l=tt(f,e,t)*h%t,d=tt(l,xu,t)*u%t,p=tt(d,o,t)*d%t,x=tt(p,i,t)*p%t,S=tt(x,a,t)*x%t,g=tt(S,c,t)*S%t,_=tt(g,a,t)*x%t,w=tt(_,e,t)*h%t,C=tt(w,s,t)*p%t,L=tt(C,n,t)*u%t,V=tt(L,xu,t);if(!Ls.eql(Ls.sqr(V),r))throw new Error("Cannot find square root");return V}var Ls=Nt(Os.p,{sqrt:bd}),Er=bu({...Os,Fp:Ls,lowS:!0,endo:gd},kn);function wu(r,t,e,n){let o=or.digest(e instanceof Uint8Array?e:e.subarray());if($n(o))return o.then(({digest:i})=>(n?.signal?.throwIfAborted(),Er.verify(t,i,r))).catch(i=>{throw i.name==="AbortError"?i:new Jr(String(i))});try{return n?.signal?.throwIfAborted(),Er.verify(t,o.digest,r)}catch(i){throw new Jr(String(i))}}var to=class{type="secp256k1";raw;_key;constructor(t){this._key=Su(t),this.raw=Eu(this._key)}toMultihash(){return zt.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:ft(this.raw,t.raw)}verify(t,e,n){return wu(this._key,e,t,n)}};function Ns(r){return new to(r)}function Eu(r){return Er.ProjectivePoint.fromHex(r).toRawBytes(!0)}function Su(r){try{return Er.ProjectivePoint.fromHex(r),r}catch(t){throw new Qe(String(t))}}function vu(r,t){let{Type:e,Data:n}=Qt.decode(r),o=n??new Uint8Array;switch(e){case ut.RSA:return Is(o,t);case ut.Ed25519:return ts(o);case ut.secp256k1:return Ns(o);case ut.ECDSA:return Ci(o);default:throw new Je}}function _u(r){let{Type:t,Data:e}=Qt.decode(r.digest),n=e??new Uint8Array;switch(t){case ut.Ed25519:return ts(n);case ut.secp256k1:return Ns(n);case ut.ECDSA:return Ci(n);default:throw new Je}}function Xt(r){return Qt.encode({Type:ut[r.type],Data:r.raw})}var Au=Symbol.for("nodejs.util.inspect.custom"),xd=114,an=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()})`}[Jo]=!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(xd,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return ft(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return ft(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[Au](){return`PeerId(${this.toString()})`}},eo=class extends an{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},ro=class extends an{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},no=class extends an{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},wd=2336,cn=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=zt.digest(k(this.url))}[Au](){return`PeerId(${this.url})`}[Jo]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return st.createV1(wd,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=K(t)),t.toString()===this.toString())}};var Ed=114,Iu=2336;function Us(r,t){let e;if(r.charAt(0)==="1"||r.charAt(0)==="Q")e=Yt(J.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return Sd(st.parse(r));if(t==null)throw new lt('Please pass a multibase decoder for strings that do not start with "1" or "Q"');e=Yt(t.decode(r))}return Sr(e)}function Sr(r){if(_d(r))return new eo({multihash:r});if(vd(r))try{let t=_u(r);if(t.type==="Ed25519")return new ro({multihash:r,publicKey:t});if(t.type==="secp256k1")return new no({multihash:r,publicKey:t})}catch{let e=K(r.digest);return new cn(new URL(e))}throw new Cn("Supplied PeerID Multihash is invalid")}function Sd(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==Ed&&r.code!==Iu)throw new Tn("Supplied PeerID CID is invalid");if(r.code===Iu){let t=K(r.multihash.digest);return new cn(new URL(t))}return Sr(r.multihash)}function vd(r){return r.code===zt.code}function _d(r){return r.code===or.code}var un;(function(r){let t;r.codec=()=>(t==null&&(t=Lt((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:et(0),payloadType:et(0),payload:et(0),signature:et(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=>Rt(e,r.codec()),r.decode=(e,n)=>Bt(e,r.codec(),n)})(un||(un={}));var oo=class extends Error{constructor(t="Invalid signature"){super(t),this.name="InvalidSignatureError"}};var ln=class r{static createFromProtobuf=t=>{let e=un.decode(t),n=vu(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=Tu(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 oo("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=un.encode({publicKey:Xt(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(t){return t==null?!1:ft(this.marshal(),t.marshal())}async validate(t,e){let n=Tu(t,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,e)}},Tu=(r,t,e)=>{let n=k(r),o=yr(n.byteLength),i=yr(t.length),s=yr(e.length);return new ct(o,n,i,t,s,e)};var gt=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},be=class extends Error{static name="ValidationError";name="ValidationError"},fn=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},io=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var so=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",u=2**(8*o)-1;for(;;){let h=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let l=Number.parseInt(f,t);if(!Number.isNaN(l))return l});if(h===void 0)break;if(i*=t,i+=h,i>u||(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 Ad=45,Id=15,ao=new so;function Ms(r){if(!(r.length>Id))return ao.new(r).parseWith(()=>ao.readIPv4Addr())}function ks(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Ad))return ao.new(r).parseWith(()=>ao.readIPv6Addr())}function co(r){return!!Ms(r)}function Du(r){return!!ks(r)}function qs(r){return t=>K(t,r)}function Vs(r){return t=>k(t,r)}function vr(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function ze(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(t)}function Pu(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=k(t[0],"base32"),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=ze(n);return ne([e,o],e.length+o.length)}function Bu(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let e=Ee.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=ze(n);return ne([e,o],e.length+o.length)}function Fs(r){let t=r.subarray(0,r.length-2),e=r.subarray(r.length-2),n=K(t,"base32"),o=vr(e);return`${n}:${o}`}var Hs=function(r){r=r.toString().trim();let t=new Uint8Array(4);return r.split(/\./g).forEach((e,n)=>{let o=parseInt(e,10);if(isNaN(o)||o<0||o>255)throw new gt("Invalid byte value in IP address");t[n]=o}),t},Ru=function(r){let t=0;r=r.toString().trim();let e=r.split(":",8),n;for(n=0;n<e.length;n++){let i=co(e[n]),s;i&&(s=Hs(e[n]),e[n]=K(s.subarray(0,2),"base16")),s!=null&&++n<8&&e.splice(n,0,K(s.subarray(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++){e[n]===""&&(e[n]="0");let i=parseInt(e[n],16);if(isNaN(i)||i<0||i>65535)throw new gt("Invalid byte value in IP address");o[t++]=i>>8&255,o[t++]=i&255}return o},Lu=function(r){if(r.byteLength!==4)throw new gt("IPv4 address was incorrect length");let t=[];for(let e=0;e<r.byteLength;e++)t.push(r[e]);return t.join(".")},Ou=function(r){if(r.byteLength!==16)throw new gt("IPv6 address was incorrect length");let t=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],i=r[n+1],s=`${o.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`;t.push(s)}let e=t.join(":");try{let n=new URL(`http://[${e}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new gt(`Invalid IPv6 address "${e}"`)}};function Nu(r){try{let t=new URL(`http://[${r}]`);return t.hostname.substring(1,t.hostname.length-1)}catch{throw new gt(`Invalid IPv6 address "${r}"`)}}var Ks=Object.values(qr).map(r=>r.decoder),Td=function(){let r=Ks[0].or(Ks[1]);return Ks.slice(2).forEach(t=>r=r.or(t)),r}();function Uu(r){return Td.decode(r)}function Mu(r){return t=>r.encoder.encode(t)}function Cd(r){if(parseInt(r).toString()!==r)throw new be("Value must be an integer")}function Dd(r){if(r<0)throw new be("Value must be a positive integer, or zero")}function Pd(r){return t=>{if(t>r)throw new be(`Value must be smaller than or equal to ${r}`)}}function Bd(...r){return t=>{for(let e of r)e(t)}}var hn=Bd(Cd,Dd,Pd(65535));var mt=-1,zs=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(t){let e;if(typeof t=="string"?e=this.protocolsByName.get(t):e=this.protocolsByCode.get(t),e==null)throw new io(`Protocol ${t} was unknown`);return e}addProtocol(t){this.protocolsByCode.set(t.code,t),this.protocolsByName.set(t.name,t),t.aliases?.forEach(e=>{this.protocolsByName.set(e,t)})}removeProtocol(t){let e=this.protocolsByCode.get(t);e!=null&&(this.protocolsByCode.delete(e.code),this.protocolsByName.delete(e.name),e.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},Mt=new zs,$d=[{code:4,name:"ip4",size:32,valueToBytes:Hs,bytesToValue:Lu,validate:r=>{if(!co(r))throw new be(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:ze,bytesToValue:vr,validate:hn},{code:273,name:"udp",size:16,valueToBytes:ze,bytesToValue:vr,validate:hn},{code:33,name:"dccp",size:16,valueToBytes:ze,bytesToValue:vr,validate:hn},{code:41,name:"ip6",size:128,valueToBytes:Ru,bytesToValue:Ou,stringToValue:Nu,validate:r=>{if(!Du(r))throw new be(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:mt},{code:43,name:"ipcidr",size:8,bytesToValue:qs("base10"),valueToBytes:Vs("base10")},{code:53,name:"dns",size:mt,resolvable:!0},{code:54,name:"dns4",size:mt,resolvable:!0},{code:55,name:"dns6",size:mt,resolvable:!0},{code:56,name:"dnsaddr",size:mt,resolvable:!0},{code:132,name:"sctp",size:16,valueToBytes:ze,bytesToValue:vr,validate:hn},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:mt,path:!0,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:mt,bytesToValue:qs("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Vs("base58btc")(r):st.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Fs,valueToBytes:Pu},{code:445,name:"onion3",size:296,bytesToValue:Fs,valueToBytes:Bu},{code:446,name:"garlic64",size:mt},{code:447,name:"garlic32",size:mt},{code:448,name:"tls"},{code:449,name:"sni",size:mt},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:mt,bytesToValue:Mu(mi),valueToBytes:Uu},{code:480,name:"http"},{code:481,name:"http-path",size:mt,stringToValue:r=>`/${decodeURIComponent(r)}`,valueToString:r=>encodeURIComponent(r.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:mt}];$d.forEach(r=>{Mt.addProtocol(r)});function ku(r){let t=[],e=0;for(;e<r.length;){let n=tn(r,e),o=Mt.getProtocol(n),i=Pt(n),s=Zd(o,r,e+i),a=0;s>0&&o.size===mt&&(a=Pt(s));let c=i+a+s,u={code:n,name:o.name,bytes:r.subarray(e,e+c)};if(s>0){let h=e+i+a,f=r.subarray(h,h+s);u.value=o.bytesToValue?.(f)??K(f)}t.push(u),e+=c}return t}function Ku(r){let t=0,e=[];for(let n of r){if(n.bytes==null){let o=Mt.getProtocol(n.code),i=Pt(n.code),s,a=0,c=0;n.value!=null&&(s=o.valueToBytes?.(n.value)??k(n.value),a=s.byteLength,o.size===mt&&(c=Pt(a)));let u=new Uint8Array(i+c+a),h=0;mr(n.code,u,h),h+=i,s!=null&&(o.size===mt&&(mr(a,u,h),h+=c),u.set(s,h)),n.bytes=u}e.push(n.bytes),t+=n.bytes.byteLength}return ne(e,t)}function qu(r){if(r.charAt(0)!=="/")throw new gt('String multiaddr must start with "/"');let t=[],e="protocol",n="",o="";for(let i=1;i<r.length;i++){let s=r.charAt(i);s!=="/"&&(e==="protocol"?o+=r.charAt(i):n+=r.charAt(i));let a=i===r.length-1;if(s==="/"||a){let c=Mt.getProtocol(o);if(e==="protocol"){if(c.size==null||c.size===0){t.push({code:c.code,name:c.name}),n="",o="",e="protocol";continue}else if(a)throw new gt(`Component ${o} was missing value`);e="value"}else if(e==="value"){let u={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new gt(`Component ${o} was missing value`);u.value=c.stringToValue?.(n)??n}t.push(u),n="",o="",e="protocol"}}}if(o!==""&&n!=="")throw new gt("Incomplete multiaddr");return t}function Vu(r){return`/${r.flatMap(t=>{if(t.value==null)return t.name;let e=Mt.getProtocol(t.code);if(e==null)throw new gt(`Unknown protocol code ${t.code}`);return[t.name,e.valueToString?.(t.value)??t.value]}).join("/")}`}function Zd(r,t,e){return r.size==null||r.size===0?0:r.size>0?r.size/8:tn(t,e)}var Wd=Symbol.for("nodejs.util.inspect.custom"),ta=Symbol.for("@multiformats/multiaddr"),Yd=[53,54,55,56],Js=class extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}};function Xd(r){if(r==null&&(r="/"),Hu(r))return r.getComponents();if(r instanceof Uint8Array)return ku(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),qu(r);if(Array.isArray(r))return r;throw new gt("Must be a string, Uint8Array, Component[], or another Multiaddr")}var ho=class r{[ta]=!0;#t;#e;#r;constructor(t="/",e={}){this.#t=Xd(t),e.validate!==!1&&jd(this)}get bytes(){return this.#r==null&&(this.#r=Ku(this.#t)),this.#r}toString(){return this.#e==null&&(this.#e=Vu(this.#t)),this.#e}toJSON(){return this.toString()}toOptions(){let t,e,n,o,i="";for(let{code:a,name:c,value:u}of this.#t)a===42&&(i=`%${u??""}`),Yd.includes(a)&&(e="tcp",o=443,n=`${u??""}${i}`,t=a===55?6:4),(a===6||a===273)&&(e=c==="tcp"?"tcp":"udp",o=parseInt(u??"")),(a===4||a===41)&&(e="tcp",n=`${u??""}${i}`,t=a===41?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}}getComponents(){return[...this.#t]}protos(){return this.#t.map(({code:t,value:e})=>{let n=Mt.getProtocol(t);return{code:t,size:n.size??0,name:n.name,resolvable:!!n.resolvable,path:!!n.path}})}protoCodes(){return this.#t.map(({code:t})=>t)}protoNames(){return this.#t.map(({name:t})=>t)}tuples(){return this.#t.map(({code:t,value:e})=>{if(e==null)return[t];let n=Mt.getProtocol(t),o=[t];return e!=null&&o.push(n.valueToBytes?.(e)??k(e)),o})}stringTuples(){return this.#t.map(({code:t,value:e})=>e==null?[t]:[t,e])}encapsulate(t){let e=new r(t);return new r([...this.#t,...e.getComponents()],{validate:!1})}decapsulate(t){let e=t.toString(),n=this.toString(),o=n.lastIndexOf(e);if(o<0)throw new fn(`Address ${this.toString()} does not contain subaddress: ${t.toString()}`);return new r(n.slice(0,o),{validate:!1})}decapsulateCode(t){let e;for(let n=this.#t.length-1;n>-1;n--)if(this.#t[n].code===t){e=n;break}return new r(this.#t.slice(0,e),{validate:!1})}getPeerId(){try{let t=[];this.#t.forEach(({code:n,value:o})=>{n===421&&t.push([n,o]),n===290&&(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(){for(let t of this.#t)if(Mt.getProtocol(t.code).path)return t.value??null;return null}equals(t){return ft(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(i=>i.resolvable);if(e==null)return[this];let n=Fu.get(e.name);if(n==null)throw new Js(`no available resolver for ${e.name}`);return(await n(this,t)).map(i=>Et(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(){return!(this.#t.length!==2||this.#t[0].code!==4&&this.#t[0].code!==41||this.#t[1].code!==6&&this.#t[1].code!==273)}[Wd](){return`Multiaddr(${this.toString()})`}};function jd(r){r.getComponents().forEach(t=>{let e=Mt.getProtocol(t.code);t.value!=null&&e.validate?.(t.value)})}var iw=parseInt("0xFFFF",16),sw=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);var Fu=new Map;function Hu(r){return!!r?.[ta]}function Et(r){return new ho(r)}function Zt(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var po=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 Ze(r,t,e){if(t==null)return r;if(t.aborted)return r.catch(()=>{}),Promise.reject(new po(e?.errorMessage,e?.errorCode,e?.errorName));let n,o=new po(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 ea=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 Ze(this.readNext.promise,e?.signal,e)}};function mo(){return new ea}var yo=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function $u(r,t){let e=mo();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:u}=await Ze(n.next(),s?.signal);return c===!0?null:u}for(;o.byteLength<s.bytes;){let{value:c,done:u}=await Ze(n.next(),s?.signal);if(u===!0)throw new yo("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 go=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},bo=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},xo=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Zu(r,t={}){let e=$u(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=Pt(t.maxDataLength));let n=t?.lengthDecoder??tn,o=t?.lengthEncoder??yr;return{read:async s=>{let a=-1,c=new ct;for(;;){c.append(await e.read({...s,bytes:1}));try{a=n(c)}catch(u){if(u instanceof RangeError)continue;throw u}if(a<0)throw new go("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new xo("message length length too long");if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new bo("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(u=>[o(u.byteLength),u]));await e.write(c,a)},unwrap:()=>e.unwrap()}}function Be(r,t){let e=Zu(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 ra=1e3,Wu=60*ra,wo=290,Yu=15,Xu=120*Wu,ju=1,Eo=2e3,Qu=100,na="circuit-relay-source",bn=`${ti}-circuit-relay`,oa=`${ti}-circuit-relay-source`,Ju=2*Wu,tl=BigInt(1<<17),Ft="/libp2p/circuit/relay/0.2.0/hop",We="/libp2p/circuit/relay/0.2.0/stop",el=30*ra,h2=30*ra,xn=300,rl=4096,nl=.001;var W;(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=()=>He(e)}(t=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Lt((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),Dr.codec().encode(o.peer,i)),o.reservation!=null&&(i.uint32(26),So.codec().encode(o.reservation,i)),o.limit!=null&&(i.uint32(34),Pr.codec().encode(o.limit,i)),o.status!=null&&(i.uint32(40),F.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 u=o.uint32();switch(u>>>3){case 1:{a.type=r.Type.codec().decode(o);break}case 2:{a.peer=Dr.codec().decode(o,o.uint32(),{limits:s.limits?.peer});break}case 3:{a.reservation=So.codec().decode(o,o.uint32(),{limits:s.limits?.reservation});break}case 4:{a.limit=Pr.codec().decode(o,o.uint32(),{limits:s.limits?.limit});break}case 5:{a.status=F.codec().decode(o);break}default:{o.skipType(u&7);break}}}return a})),n),r.encode=o=>Rt(o,r.codec()),r.decode=(o,i)=>Bt(o,r.codec(),i)})(W||(W={}));var kt;(function(r){let t;(function(o){o.CONNECT="CONNECT",o.STATUS="STATUS"})(t=r.Type||(r.Type={}));let e;(function(o){o[o.CONNECT=0]="CONNECT",o[o.STATUS=1]="STATUS"})(e||(e={})),function(o){o.codec=()=>He(e)}(t=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Lt((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),Dr.codec().encode(o.peer,i)),o.limit!=null&&(i.uint32(26),Pr.codec().encode(o.limit,i)),o.status!=null&&(i.uint32(32),F.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 u=o.uint32();switch(u>>>3){case 1:{a.type=r.Type.codec().decode(o);break}case 2:{a.peer=Dr.codec().decode(o,o.uint32(),{limits:s.limits?.peer});break}case 3:{a.limit=Pr.codec().decode(o,o.uint32(),{limits:s.limits?.limit});break}case 4:{a.status=F.codec().decode(o);break}default:{o.skipType(u&7);break}}}return a})),n),r.encode=o=>Rt(o,r.codec()),r.decode=(o,i)=>Bt(o,r.codec(),i)})(kt||(kt={}));var Dr;(function(r){let t;r.codec=()=>(t==null&&(t=Lt((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:et(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 nn('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=>Rt(e,r.codec()),r.decode=(e,n)=>Bt(e,r.codec(),n)})(Dr||(Dr={}));var So;(function(r){let t;r.codec=()=>(t==null&&(t=Lt((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),vo.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 nn('Decode error - map field "addrs" had too many elements');i.addrs.push(e.bytes());break}case 3:{i.voucher=vo.codec().decode(e,e.uint32(),{limits:o.limits?.voucher});break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Rt(e,r.codec()),r.decode=(e,n)=>Bt(e,r.codec(),n)})(So||(So={}));var Pr;(function(r){let t;r.codec=()=>(t==null&&(t=Lt((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=>Rt(e,r.codec()),r.decode=(e,n)=>Bt(e,r.codec(),n)})(Pr||(Pr={}));var F;(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"})(F||(F={}));var ia;(function(r){r[r.UNUSED=0]="UNUSED",r[r.OK=100]="OK",r[r.RESERVATION_REFUSED=200]="RESERVATION_REFUSED",r[r.RESOURCE_LIMIT_EXCEEDED=201]="RESOURCE_LIMIT_EXCEEDED",r[r.PERMISSION_DENIED=202]="PERMISSION_DENIED",r[r.CONNECTION_FAILED=203]="CONNECTION_FAILED",r[r.NO_RESERVATION=204]="NO_RESERVATION",r[r.MALFORMED_MESSAGE=400]="MALFORMED_MESSAGE",r[r.UNEXPECTED_MESSAGE=401]="UNEXPECTED_MESSAGE"})(ia||(ia={}));(function(r){r.codec=()=>He(ia)})(F||(F={}));var Br;(function(r){let t;r.codec=()=>(t==null&&(t=Lt((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:et(0),peer:et(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=>Rt(e,r.codec()),r.decode=(e,n)=>Bt(e,r.codec(),n)})(Br||(Br={}));var vo;(function(r){let t;r.codec=()=>(t==null&&(t=Lt((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),Br.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:et(0),payloadType:et(0),signature:et(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=Br.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=>Rt(e,r.codec()),r.decode=(e,n)=>Bt(e,r.codec(),n)})(vo||(vo={}));var j=r=>({match:t=>{let e=t[0];return e==null||e.code!==r||e.value!=null?!1:t.slice(1)}}),R=(r,t)=>({match:e=>{let n=e[0];return n?.code!==r||n.value==null||t!=null&&n.value!==t?!1:e.slice(1)}}),H=r=>({match:t=>{let e=r.match(t);return e===!1?t:e}}),St=(...r)=>({match:t=>{let e;for(let n of r){let o=n.match(t);o!==!1&&(e==null||o.length<e.length)&&(e=o)}return e??!1}}),G=(...r)=>({match:t=>{for(let e of r){let n=e.match(t);if(n===!1)return!1;t=n}return t}});function X(...r){function t(o){if(o==null)return!1;let i=o.getComponents();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 rp=R(421),w2=X(rp),Ao=R(54),Io=R(55),To=R(56),aa=R(53),E2=X(Ao,H(R(421))),S2=X(Io,H(R(421))),v2=X(To,H(R(421))),_2=X(St(aa,To,Ao,Io),H(R(421))),ol=G(R(4),H(R(43))),il=G(H(R(42)),R(41),H(R(43))),ca=St(ol,il),Ye=St(ca,aa,Ao,Io,To),A2=X(St(ca,G(St(aa,To,Ao,Io),H(R(421))))),I2=X(ol),T2=X(il),C2=X(ca),ua=G(Ye,R(6)),wn=G(Ye,R(273)),D2=X(G(ua,H(R(421)))),P2=X(wn),la=G(wn,j(460),H(R(421))),Co=G(wn,j(461),H(R(421))),np=St(la,Co),B2=X(la),R2=X(Co),sa=St(Ye,ua,wn,la,Co),sl=St(G(sa,j(477),H(R(421)))),L2=X(sl),al=St(G(sa,j(478),H(R(421))),G(sa,j(448),H(R(449)),j(477),H(R(421)))),O2=X(al),cl=G(wn,j(280),H(R(466)),H(R(466)),H(R(421))),N2=X(cl),ul=G(Co,j(465),H(R(466)),H(R(466)),H(R(421))),U2=X(ul),_o=St(sl,al,G(ua,H(R(421))),G(np,H(R(421))),G(Ye,H(R(421))),cl,ul,R(421)),ll=X(_o),op=G(_o,j(290),R(421)),Do=X(op),ip=St(G(_o,j(290),j(281),H(R(421))),G(_o,j(281),H(R(421))),G(j(281),H(R(421)))),M2=X(ip),sp=St(G(Ye,R(6),j(480),H(R(421))),G(Ye,j(480),H(R(421)))),k2=X(sp),ap=G(Ye,St(G(R(6,"443"),j(480)),G(R(6),j(443)),G(R(6),j(448),j(480)),G(j(448),j(480)),j(448),j(443)),H(R(421))),K2=X(ap),cp=St(G(R(777),H(R(421)))),q2=X(cp),up=St(G(R(400),H(R(421)))),V2=X(up);function Po(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 Bo=class extends Error{constructor(t="Transfer limit error"){super(t),this.name="TransferLimitError"}},En=class extends Error{constructor(t="Duration limit error"){super(t),this.name="DurationLimitError"}},Sn=class extends Error{static name="HadEnoughRelaysError";name="HadEnoughRelaysError"},Ro=class extends Error{static name="DoubleRelayError";name="DoubleRelayError"},Lo=class extends Error{static name="RelayQueueFullError";name="RelayQueueFullError"};async function*fl(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 Bo(`data limit of ${n} bytes exceeded`)}t.remaining-=i,yield o}}function hl(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=Po(s),c=!1,u=!1,h;n.limit?.data!=null&&(h={remaining:n.limit.data}),queueMicrotask(()=>{let f=()=>{o.log("relayed connection reached time limit"),t.abort(new En(`duration limit of ${n.limit?.duration} ms exceeded`))};a.addEventListener("abort",f,{once:!0}),t.sink(h==null?r.source:fl(r.source,h,o)).catch(l=>{o.log.error("error while relaying streams src -> dst",l),i(l)}).finally(()=>{c=!0,u&&(a.removeEventListener("abort",f),a.clear())})}),queueMicrotask(()=>{let f=()=>{o.log("relayed connection reached time limit"),r.abort(new En(`duration limit of ${n.limit?.duration} ms exceeded`))};a.addEventListener("abort",f,{once:!0}),r.sink(h==null?t.source:fl(t.source,h,o)).catch(l=>{o.log.error("error while relaying streams dst -> src",l),i(l)}).finally(()=>{u=!0,c&&(a.removeEventListener("abort",f),a.clear())})})}function fa(r){let t=r*BigInt(1e3),e=new Date().getTime();return Number(t-BigInt(e))}var vn=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}},Oo=X(G(ll.matchers[0],j(290))),No=X(j(290));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 Re=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 ha={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},dl={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},pl=new globalThis.TextEncoder;function lp(r,t){let e=ha[t],n=dl[t];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(t,n*e);return n}function fp(r,t,e){if(e.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=ha[t],o=dl[t],i=r;for(;i.length>0;){let s=pl.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 da(r,{size:t=32,utf8Buffer:e}={}){if(!ha[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 fp(r,t,e);r=pl.encode(r)}return lp(r,t)}var _n={hash:r=>Number(da(r,{size:32})),hashV:(r,t)=>hp(_n.hash(r,t))};function hp(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),k(t,"base16")}var pa=64,Wt=class{fp;h;seed;constructor(t,e,n,o=2){if(o>pa)throw new TypeError("Invalid Fingerprint Size");let i=e.hashV(t,n),s=et(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?ft(this.fp,t.fp):!1}};function Xe(r,t){return Math.floor(Math.random()*(t-r))+r}var je=class{contents;constructor(t){this.contents=new Array(t).fill(null)}has(t){if(!(t instanceof Wt))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof Wt))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 Wt))throw new TypeError("Invalid Fingerprint");let e=Xe(0,this.contents.length-1),n=this.contents[e];return this.contents[e]=t,n}remove(t){if(!(t instanceof Wt))throw new TypeError("Invalid Fingerprint");let e=this.contents.findIndex(n=>t.equals(n));return e>-1?(this.contents[e]=null,!0):!1}};var dp=500,An=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??_n,this.seed=t.seed??Xe(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=k(t));let e=new Wt(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 je(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new je(this.bucketSize)),this.buckets[n].add(e)||this.buckets[o].add(e))return this.count++,!0;let i=[n,o],s=i[Xe(0,i.length-1)];this.buckets[s]==null&&(this.buckets[s]=new je(this.bucketSize));for(let a=0;a<dp;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 je(this.bucketSize)),this.buckets[s].add(c)))return this.count++,!0}return!1}has(t){typeof t=="string"&&(t=k(t));let e=new Wt(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=k(t));let e=new Wt(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}},pp={1:.5,2:.84,4:.95,8:.98};function mp(r=.001){return r>.002?2:r>1e-5?4:8}function ml(r,t=.001){let e=mp(t),n=pp[e],o=Math.round(r/n),i=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),pa);return{filterSize:o,bucketSize:e,fingerprintSize:i}}var Mo=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??_n,this.seed=t.seed??Xe(0,Math.pow(2,10)),this.filterSeries=[new An({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(t){if(typeof t=="string"&&(t=k(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 An({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=k(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=k(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 Rr(r,t=.001,e){return new Mo({...ml(r,t),...e??{}})}var ko=class{filter;constructor(t,e){this.filter=Rr(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 ma(r,t=.001){return new ko(r,t)}var ya=class extends Re{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 ga(r){let{name:t,metrics:e}=r,n;return e!=null?n=new ya({name:t,metrics:e}):n=new Re,n}var ba=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 yl(r,t){let e=new ba(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 Ko=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??Yu,this.applyDefaultLimit=e.applyDefaultLimit!==!1,this.reservationTtl=e.reservationTtl??Xu,this.defaultDurationLimit=e.defaultDurationLimit??Ju,this.defaultDataLimit=e.defaultDataLimit??tl,this.reservations=ga({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:F.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:yl(this.reservationTtl)}),this.reservations.set(t,o),o.signal.addEventListener("abort",()=>{this.reservations.delete(t)}),{status:F.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 qo=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 Br.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 gl=r=>r.protoCodes().includes(wo),yp={maxOutboundStopStreams:xn},xa=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??el,this.maxInboundHopStreams=e.maxInboundHopStreams,this.maxOutboundHopStreams=e.maxOutboundHopStreams,this.maxOutboundStopStreams=e.maxOutboundStopStreams??yp.maxOutboundStopStreams,this.reservationStore=new Ko(t,e.reservations),this.shutdownController=new AbortController,this.shutdownController.signal}[Symbol.toStringTag]="@libp2p/circuit-relay-v2-server";isStarted(){return this.started}async start(){this.started||(await this.registrar.handle(Ft,t=>{this.onHop(t).catch(e=>{this.log.error(e)})},{maxInboundStreams:this.maxInboundHopStreams,maxOutboundStreams:this.maxOutboundHopStreams,runOnLimitedConnection:!0}),this.started=!0)}async stop(){this.reservationStore.clear(),this.shutdownController.abort(),await this.registrar.unhandle(Ft),this.started=!1}async onHop({connection:t,stream:e}){this.log("received circuit v2 hop protocol stream from %p",t.remotePeer);let n={signal:AbortSignal.timeout(this.hopTimeout)},o=Be(e);try{let i=await o.pb(W).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(W).write({type:W.Type.STATUS,status:F.MALFORMED_MESSAGE},n),e.abort(i)}}async handleHopProtocol({stream:t,request:e,connection:n},o){switch(this.log("received hop message"),e.type){case W.Type.RESERVE:await this.handleReserve({stream:t,request:e,connection:n},o);break;case W.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(W).write({type:W.Type.STATUS,status:F.UNEXPECTED_MESSAGE})}}async handleReserve({stream:t,connection:e},n){let o=t.pb(W);if(this.log("hop reserve request from %p",e.remotePeer),gl(e.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",e.remotePeer),await o.write({type:W.Type.STATUS,status:F.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:W.Type.STATUS,status:F.PERMISSION_DENIED},n);return}let i=this.reservationStore.reserve(e.remotePeer,e.remoteAddr);try{if(i.status!==F.OK){await o.write({type:W.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:{[na]:{value:1,ttl:s},[oa]:{value:1,ttl:s}}})}await o.write({type:W.Type.STATUS,status:F.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:{[na]:void 0,[oa]: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 ln.seal(new qo({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(W);if(gl(n.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",n.remotePeer),await i.write({type:W.Type.STATUS,status:F.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(Et),s=Sr(Yt(e.peer.id))}catch(l){this.log.error("invalid hop connect request via peer %p %s",n.remotePeer,l),await i.write({type:W.Type.STATUS,status:F.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,F.NO_RESERVATION),await i.write({type:W.Type.STATUS,status:F.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:W.Type.STATUS,status:F.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:W.Type.STATUS,status:F.NO_RESERVATION},o);return}let u=c[0],h=await this.stopHop({connection:u,request:{type:kt.Type.CONNECT,peer:{id:n.remotePeer.toMultihash().bytes,addrs:[]},limit:a?.limit}},o);if(h==null){this.log.error("failed to open stream to destination peer %p",u?.remotePeer),await i.write({type:W.Type.STATUS,status:F.CONNECTION_FAILED},o);return}await i.write({type:W.Type.STATUS,status:F.OK,limit:a?.limit},o);let f=t.unwrap();this.log("connection from %p to %p established - merging streams",n.remotePeer,s),hl(f,h,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([We],{maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0,...n}),i=Be(o),s=i.pb(kt);await s.write(e,n);let a;try{a=await s.read(n)}catch{this.log.error("error parsing stop message response from %p",t.remotePeer)}if(a==null){this.log.error("could not read response from %p",t.remotePeer),await o.close(n);return}if(a.status===F.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 bl(r={}){return t=>new xa(t,r)}function gp(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 xl=gp;function bp(r){return r[Symbol.asyncIterator]!=null}function wl(r){return r?.then!=null}function xp(r,t){let e=0;if(bp(r))return async function*(){for await(let c of r){let u=t(c,e++);wl(u)&&await u,yield c}}();let n=xl(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 u=t(c,e++);wl(u)&&await u,yield c}}();let a=t;return function*(){yield o;for(let c of n)a(c,e++),yield c}()}var El=xp;var Vo=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||(t-1&t)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},Lr=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new Vo(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 Vo(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 Ea=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function Fo(r={}){return wp(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 wp(r,t){t=t??{};let e=t.onEnd,n=new Lr,o,i,s,a=Zt(),c=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((S,g)=>{i=_=>{i=null,n.push(_);try{S(r(n))}catch(w){g(w)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Zt()})}},u=S=>i!=null?i(S):(n.push(S),o),h=S=>(n=new Lr,i!=null?i({error:S}):(n.push({error:S}),o)),f=S=>{if(s)return o;if(t?.objectMode!==!0&&S?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:S})},l=S=>s?o:(s=!0,S!=null?h(S):u({done:!0})),d=()=>(n=new Lr,l(),{done:!0}),p=S=>(l(S),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:d,throw:p,push:f,end:l,get readableLength(){return n.size},onEmpty:async S=>{let g=S?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let _,w;g!=null&&(_=new Promise((C,L)=>{w=()=>{L(new Ea)},g.addEventListener("abort",w)}));try{await Promise.race([a.promise,_])}finally{w!=null&&g!=null&&g?.removeEventListener("abort",w)}}},e==null)return o;let x=o;return o={[Symbol.asyncIterator](){return this},next(){return x.next()},throw(S){return x.throw(S),e!=null&&(e(S),e=void 0),{done:!0}},return(){return x.return(),e!=null&&(e(),e=void 0),{done:!0}},push:f,end(S){return x.end(S),e!=null&&(e(S),e=void 0),o},get readableLength(){return x.readableLength},onEmpty:S=>x.onEmpty(S)},o}function Ep(r){return r[Symbol.asyncIterator]!=null}async function Sp(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*vp(r){let t=new AbortController,e=mo();Sp(r,e,t.signal).catch(()=>{});try{yield*e}finally{t.abort()}}function*_p(r){for(let t of r)yield*t}function Ap(...r){let t=[];for(let e of r)Ep(e)||t.push(e);return t.length===r.length?_p(t):vp(r)}var Sl=Ap;function vl(r,...t){if(r==null)throw new Error("Empty pipeline");if(Sa(r)){let n=r;r=()=>n.source}else if(Al(r)||_l(r)){let n=r;r=()=>n}let e=[r,...t];if(e.length>1&&Sa(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++)Sa(e[n])&&(e[n]=Tp(e[n]));return Ip(...e)}var Ip=(...r)=>{let t;for(;r.length>0;)t=r.shift()(t);return t},_l=r=>r?.[Symbol.asyncIterator]!=null,Al=r=>r?.[Symbol.iterator]!=null,Sa=r=>r==null?!1:r.sink!=null&&r.source!=null,Tp=r=>t=>{let e=r.sink(t);if(e?.then!=null){let n=Fo({objectMode:!0});e.then(()=>{n.end()},s=>{n.end(s)});let o,i=r.source;if(_l(i))o=async function*(){yield*i,n.end()};else if(Al(i))o=function*(){yield*i,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Sl(n,o())}return r.source};function va(r){let{stream:t,remoteAddr:e,log:n,onDataRead:o,onDataWrite:i}=r,s=!1,a=!1,c=t.close.bind(t);t.close=async d=>{await c(d),l(!0)};let u=t.abort.bind(t);t.abort=d=>{u(d),l(!0)};let h=t.sink.bind(t);t.sink=async d=>{try{await h(vl(d,p=>El(p,x=>i?.(x))))}catch(p){f.log.error("errored - %e",p),p.type!=="aborted"&&f.log.error("%s error in sink - %e",e,p)}finally{a=!0,l()}};let f={log:n.newScope("stream-to-maconn"),sink:t.sink,source:async function*(){try{for await(let d of t.source)o?.(d),yield d}finally{s=!0,l()}}(),remoteAddr:e,timeline:{open:Date.now(),close:void 0},close:t.close,abort:t.abort};function l(d){d===!0&&(s=!0,a=!0),s&&a&&f.timeline.close==null&&(f.timeline.close=Date.now())}return f}var Le=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var Ho=class extends Error{static name="AbortError";name="AbortError";constructor(t="The operation was aborted",...e){super(t,...e)}};async function zo(r,t,e,n){let o=new Ho(n?.errorMessage);n?.errorCode!=null&&(o.code=n.errorCode);let i=n?.errorEvent??"error";return e?.aborted===!0?Promise.reject(o):new Promise((s,a)=>{function c(){Aa(e,"abort",f),Aa(r,t,u),Aa(r,i,h)}let u=l=>{try{if(n?.filter?.(l)===!1)return}catch(d){c(),a(d);return}c(),s(l)},h=l=>{if(c(),l instanceof Error){a(l);return}a(l.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},f=()=>{c(),a(o)};_a(e,"abort",f),_a(r,t,u),_a(r,i,h)})}function _a(r,t,e){r!=null&&(Il(r)?r.addEventListener(t,e):r.addListener(t,e))}function Aa(r,t,e){r!=null&&(Il(r)?r.removeEventListener(t,e):r.removeListener(t,e))}function Il(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}function Ia(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 Go=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};var $o=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 te)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Cp(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Zo=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=Cp(),this.status="queued",this.fn=t,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(t){this.controller.abort(t)}onAbort(){this.recipients.reduce((e,n)=>e&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new te),this.cleanup())}async join(t={}){let e=new $o(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 Ze(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 Wo=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=Ia(this.emitEmpty.bind(this),1),this.emitIdle=Ia(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 Go;let n=new Zo(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("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(t=>{t.abort(new te)}),this.clear()}async onEmpty(t){this.size!==0&&await zo(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await zo(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await zo(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=Fo({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.error)},s=()=>{n()},a=()=>{n(new te("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",i),this.addEventListener("idle",s),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",i),this.removeEventListener("idle",s),t?.signal?.removeEventListener("abort",a),n()}}};var Or=class extends Wo{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};var Yo=class extends Kt{components;started;running;topologyId;log;discoveryController;filter;queue;constructor(t,e={}){super(),this.log=t.logger.forComponent("libp2p:circuit-relay:discover-relays"),this.components=t,this.started=!1,this.running=!1,this.filter=e.filter,this.discoveryController=new AbortController,this.discoveryController.signal,this.dialPeer=this.dialPeer.bind(this),this.onPeer=this.onPeer.bind(this)}isStarted(){return this.started}async start(){this.topologyId=await this.components.registrar.register(Ft,{filter:this.filter,onConnect:t=>{this.log.trace("discovered relay %p queue (length: %d, active %d)",t,this.queue?.size,this.queue?.running),this.safeDispatchEvent("relay:discover",{detail:t})}}),this.started=!0}stop(){this.topologyId!=null&&this.components.registrar.unregister(this.topologyId),this.running&&this.stopDiscovery(),this.started=!1}startDiscovery(){this.running||(this.log("start discovery"),this.running=!0,this.discoveryController=new AbortController,this.discoveryController.signal,this.components.events.addEventListener("peer:discovery",this.onPeer),Promise.resolve().then(async()=>{this.log("searching peer store for relays");let t=await this.components.peerStore.all({filters:[n=>n.protocols.includes(Ft)],orders:[()=>Math.random()<.5?1:-1,(n,o)=>{let i=Tl(n),s=Tl(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 Or({concurrency:5});this.log("start random walk");for await(let n of this.components.randomWalk.walk({signal:this.discoveryController.signal})){if(this.log.trace("found random peer %p",n.id),e.has(n.id)){this.log.trace("random peer %p was already in queue",n.id);continue}if(this.components.connectionManager.getConnections(n.id)?.length>0){this.log.trace("random peer %p was already connected",n.id);continue}if(!await this.components.connectionManager.isDialable(n.multiaddrs)){this.log.trace("random peer %p was not dialable",n.id,n.multiaddrs.map(o=>o.toString()));continue}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(this.dialPeer,{peerId:n.id,signal:this.discoveryController.signal}).catch(o=>{this.log.error("error opening connection to random peer %p",n.id,o)})}this.log("stop random walk"),await 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(),this.queue?.clear(),this.components.events.removeEventListener("peer:discovery",this.onPeer)}onPeer(t){this.log.trace("maybe dialing discovered peer %p - %e",t.detail.id),this.maybeDialPeer(t).catch(e=>{this.log.trace("error dialing discovered peer %p - %e",t.detail.id,e)})}async maybeDialPeer(t){if(this.queue==null)return;let e=t.detail.id,n=t.detail.multiaddrs;if(this.queue.has(e)){this.log.trace("random peer %p was already in queue",e);return}if(this.components.connectionManager.getConnections(e)?.length>0){this.log.trace("random peer %p was already connected",e);return}if(!await this.components.connectionManager.isDialable(n)){this.log.trace("random peer %p was not dialable",e);return}this.queue?.add(this.dialPeer,{peerId:t.detail.id,signal:this.discoveryController.signal}).catch(o=>{this.log.error("error opening connection to discovered peer %p",t.detail.id,o)})}async dialPeer({peerId:t,signal:e}){let n=Po([AbortSignal.timeout(5e3),e]);try{await this.components.connectionManager.openConnection(t,{signal:n})}finally{n.clear()}}};function Tl(r){let t=r.metadata.get("last-dial-success");return t==null?0:new Date(K(t)).getTime()}var Ta=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??Eo,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(No.exactMatch(t))this.log("searching for circuit relay servers"),this.reservationId=this.reservationStore.reserveRelay();else if(Oo.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 Oe(`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=>Et(e).encapsulate("/p2p-circuit")),this.listeningAddrs.forEach(e=>{this.addressManager.confirmObservedAddr(e,{type:"transport"})}),queueMicrotask(()=>{this.safeDispatchEvent("listening")})}};function Cl(r){return new Ta(r)}var Dl="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Pl=(r=21)=>{let t="",e=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)t+=Dl[e[r]&63];return t};var Dp=60*1e3*10,Pp=60*1e3*5,Bp=30*1e3,Xo=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 Re,this.pendingReservations=[],this.maxReservationQueueLength=e?.maxReservationQueueLength??Qu,this.reservationCompletionTimeout=e?.reservationCompletionTimeout??Eo,this.started=!1,this.relayFilter=Rr(100),this.reserveQueue=new Or({concurrency:e?.reservationConcurrency??ju,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(bn)]});this.log("removing tag from %d old relays",t.length),await Promise.all(t.map(async e=>{await this.peerStore.merge(e.id,{tags:{[bn]: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=Pl();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 Oe("Cannot use self as relay");if(this.reserveQueue.size>this.maxReservationQueueLength)throw new Lo("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 Oe("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 p=this.connectionManager.getConnections(t),x=!1;if(p.length===0&&this.log("already have relay reservation with %p but we are no longer connected",t),p.map(S=>S.id).includes(i.connection)&&(this.log("already have relay reservation with %p and the original connection is still open",t),x=!0),x&&fa(i.reservation.expire)>Dp)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 Sn("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(Do.matches(a.remoteAddr))throw new Ro("not creating reservation over relayed connection");let c=await this.#t(a,{signal:s}),u=fa(c.expire);this.log("created reservation on relay peer %p, expiry date is %s",t,new Date(Date.now()+u).toString());let h=Math.min(Math.max(u-Pp,Bp),Math.pow(2,31)-1),f=setTimeout(()=>{this.log("refresh reservation to relay %p",t),this.addRelay(t,e).catch(async p=>{this.log.error("could not refresh reservation to relay %p - %e",t,p),await this.#e(t)}).catch(p=>{this.log.error("could not remove expired reservation to relay %p - %e",t,p)})},h),l;if(e==="discovered"){let p=this.pendingReservations.pop();if(p==null)throw new Sn("Made reservation on relay but did not need any more discovered relays");l={timeout:f,reservation:c,type:e,connection:a.id,id:p}}else l={timeout:f,reservation:c,type:e,connection:a.id};this.reservations.set(t,l),await this.peerStore.merge(t,{tags:{[bn]:{value:1,ttl:u}}}),this.#r();let d={relay:t,details:l};return this.safeDispatchEvent("relay:created-reservation",{detail:d}),d}catch(i){throw e==="discovered"&&i.name==="HadEnoughRelaysError"||this.log.error("could not reserve slot on %p after %dms - %e",t,Date.now()-o,i),(i.name==="DialError"||i.name==="UnsupportedProtocolError")&&this.relayFilter.add(t.toMultihash().bytes),this.#e(t).catch(s=>{this.log.error("could not remove reservation on %p after reserving slot failed - %e",t,s)}),i}},{peerId:t})}hasReservation(t){return this.reservations.has(t)}getReservation(t){return this.reservations.get(t)?.reservation}reservationCount(t){return t==null?this.reservations.size:[...this.reservations.values()].reduce((e,n)=>(n.type===t&&e++,e),0)}cancelReservations(){[...this.reservations.values()].forEach(t=>{clearTimeout(t.timeout)}),this.reservations.clear()}async#t(t,e){e.signal?.throwIfAborted(),this.log("requesting reservation from %p",t.remotePeer);let n=await t.newStream(Ft,e),i=Be(n).pb(W);this.log.trace("send RESERVE to %p",t.remotePeer),await i.write({type:W.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===F.OK&&s.reservation!=null){let c=new Set;c.add(t.remoteAddr.toString());for(let u of s.reservation.addrs){let h=Et(u);h.getPeerId()==null&&(h=h.encapsulate(`/p2p/${t.remotePeer}`)),h=Et(h.toString().replace(`/p2p/${t.remotePeer}/p2p/${t.remotePeer}`,`/p2p/${t.remotePeer}`)),c.add(h.toString())}return s.reservation.addrs=[...c].map(u=>Et(u).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:{[bn]: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=Rr(100),this.log("not discovered enough relays %d/%d",this.reservations.size,this.pendingReservations.length),this.safeDispatchEvent("relay:not-enough-relays")}};var Rp=r=>{if(r.peer==null)return!1;try{r.peer.addrs.forEach(Et)}catch{return!1}return!0},Bl={maxInboundStopStreams:xn,maxOutboundStopStreams:xn,stopTimeout:3e4},jo=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??Bl.maxInboundStopStreams,this.maxOutboundStopStreams=e.maxOutboundStopStreams??Bl.maxOutboundStopStreams,this.shutdownController=new AbortController,this.discovery=new Yo(t,{filter:e.discoveryFilter??ma(rl,nl)}),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 Xo(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";[Na]=["@libp2p/transport","@libp2p/circuit-relay-v2-transport"];get[Ua](){return this.discovery!=null?["@libp2p/identify"]:[]}[Ba]=!0;isStarted(){return this.started}async start(){this.shutdownController=new AbortController,this.shutdownController.signal,await this.registrar.handle(We,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 La(this.discovery,this.reservationStore),this.started=!0}async stop(){this.shutdownController.abort(),await Oa(this.discovery,this.reservationStore),await this.registrar.unhandle(We),this.started=!1}async dial(t,e){if(t.protoCodes().filter(d=>d===wo).length!==1){let d="Invalid circuit relay address";throw this.log.error(d,t),new Nr(d)}let n=t.toString().split("/p2p-circuit"),o=Et(n[0]),i=Et(n[n.length-1]),s=o.getPeerId(),a=i.getPeerId();if(s==null||a==null){let d=`ircuit relay dial to ${t.toString()} failed as address did not have both relay and destination PeerIDs`;throw this.log.error(`c${d}`),new Nr(`C${d}`)}let c=Us(s),u=Us(a),f=this.connectionManager.getConnections(c)[0];f==null?(await this.peerStore.merge(c,{multiaddrs:[o]}),e.onProgress?.(new Le("circuit-relay:open-connection")),f=await this.connectionManager.openConnection(c,e)):e.onProgress?.(new Le("circuit-relay:reuse-connection"));let l;try{e.onProgress?.(new Le("circuit-relay:open-hop-stream")),l=await f.newStream(Ft,e);let d=Be(l),p=d.pb(W);e.onProgress?.(new Le("circuit-relay:write-connect-message")),await p.write({type:W.Type.CONNECT,peer:{id:u.toMultihash().bytes,addrs:[Et(i).bytes]}},e),e.onProgress?.(new Le("circuit-relay:read-connect-response"));let x=await p.read(e);if(x.status!==F.OK)throw new Dn(`failed to connect via relay with status ${x?.status?.toString()??"undefined"}`);let S=new vn(x.limit),g=va({stream:d.unwrap(),remoteAddr:t,localAddr:o.encapsulate(`/p2p-circuit/p2p/${this.peerId.toString()}`),log:this.log,onDataRead:S.onData,onDataWrite:S.onData}),_=await this.upgrader.upgradeOutbound(g,{...e,limits:S.getLimits()});return _.log("outbound relayed connection established to %p with limits %o, over connection %s",_.remotePeer,x.limit??"none",f.id),_}catch(d){throw this.log.error("circuit relay dial to destination %p via relay %p failed",u,c,d),l?.abort(d),d}}createListener(t){return Cl({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=>Oo.exactMatch(e)||No.exactMatch(e))}dialFilter(t){return t=Array.isArray(t)?t:[t],t.filter(e=>Do.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=Be(e).pb(kt),i=await o.read({signal:n});if(this.log("new circuit relay v2 stop stream from %p with type %s",t.remotePeer,i.type),i?.type===void 0){this.log.error("type was missing from circuit v2 stop protocol request from %s",t.remotePeer),await o.write({type:kt.Type.STATUS,status:F.MALFORMED_MESSAGE},{signal:n}),await e.close();return}if(i.type!==kt.Type.CONNECT){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await o.write({type:kt.Type.STATUS,status:F.UNEXPECTED_MESSAGE},{signal:n}),await e.close();return}if(!Rp(i)){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await o.write({type:kt.Type.STATUS,status:F.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}let s=Sr(Yt(i.peer.id));if(await this.connectionGater.denyInboundRelayedConnection?.(t.remotePeer,s)===!0){this.log.error("connection gater denied inbound relayed connection from %p",t.remotePeer),await o.write({type:kt.Type.STATUS,status:F.PERMISSION_DENIED},{signal:n}),await e.close({signal:n});return}this.log.trace("sending success response to %p",t.remotePeer),await o.write({type:kt.Type.STATUS,status:F.OK},{signal:n});let a=new vn(i.limit),c=t.remoteAddr.encapsulate(`/p2p-circuit/p2p/${s.toString()}`),u=this.addressManager.getAddresses()[0],h=va({stream:o.unwrap().unwrap(),remoteAddr:c,localAddr:u,log:this.log,onDataRead:a.onData,onDataWrite:a.onData});await this.upgrader.upgradeInbound(h,{limits:a.getLimits(),signal:n}),h.log("inbound relayed connection established to %p with limits %o, over connection %s",s,i.limit??"none",t.id)}};function Rl(r={}){return t=>new jo(t,r)}return Ml(Lp);})();
2
+ "use strict";var Libp2PCircuitRelayV2=(()=>{var Qo=Object.defineProperty;var Ol=Object.getOwnPropertyDescriptor;var Nl=Object.getOwnPropertyNames;var Ul=Object.prototype.hasOwnProperty;var It=(r,t)=>{for(var e in t)Qo(r,e,{get:t[e],enumerable:!0})},Ml=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Nl(t))!Ul.call(r,o)&&o!==e&&Qo(r,o,{get:()=>t[o],enumerable:!(n=Ol(t,o))||n.enumerable});return r};var kl=r=>Ml(Qo({},"__esModule",{value:!0}),r);var Np={};It(Np,{RELAY_V2_HOP_CODEC:()=>Ft,RELAY_V2_STOP_CODEC:()=>We,circuitRelayServer:()=>xl,circuitRelayTransport:()=>Rl});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 Jo=Symbol.for("@libp2p/peer-id");var ti="keep-alive";var Ba=Symbol.for("@libp2p/transport");var Pa;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Pa||(Pa={}));var te=class extends Error{static name="AbortError";constructor(t="The operation was aborted"){super(t),this.name="AbortError"}};var lt=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},Qe=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"}},Cn=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}};var Dn=class extends Error{static name="InvalidMessageError";constructor(t="Invalid message"){super(t),this.name="InvalidMessageError"}};var Nr=class extends Error{static name="DialError";constructor(t="Dial error"){super(t),this.name="DialError"}},Oe=class extends Error{static name="ListenError";constructor(t="Listen error"){super(t),this.name="ListenError"}};var Je=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};function La(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function Ra(...r){let t=[];for(let e of r)La(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 Oa(...r){let t=[];for(let e of r)La(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 Na=Symbol.for("@libp2p/service-capabilities"),Ua=Symbol.for("@libp2p/service-dependencies");var ii={};It(ii,{base58btc:()=>J,base58flickr:()=>Gl});var lm=new Uint8Array(0);function Ma(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function ee(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function ka(r){return new TextEncoder().encode(r)}function Ka(r){return new TextDecoder().decode(r)}function Kl(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),u=Math.log(a)/Math.log(256),h=Math.log(256)/Math.log(a);function f(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var x=0,S=0,g=0,_=p.length;g!==_&&p[g]===0;)g++,x++;for(var w=(_-g)*h+1>>>0,C=new Uint8Array(w);g!==_;){for(var R=p[g],V=0,q=w-1;(R!==0||V<S)&&q!==-1;q--,V++)R+=256*C[q]>>>0,C[q]=R%a>>>0,R=R/a>>>0;if(R!==0)throw new Error("Non-zero carry");S=V,g++}for(var N=w-S;N!==w&&C[N]===0;)N++;for(var E=c.repeat(x);N<w;++N)E+=r.charAt(C[N]);return E}function l(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var x=0;if(p[x]!==" "){for(var S=0,g=0;p[x]===c;)S++,x++;for(var _=(p.length-x)*u+1>>>0,w=new Uint8Array(_);p[x];){var C=e[p.charCodeAt(x)];if(C===255)return;for(var R=0,V=_-1;(C!==0||R<g)&&V!==-1;V--,R++)C+=a*w[V]>>>0,w[V]=C%256>>>0,C=C/256>>>0;if(C!==0)throw new Error("Non-zero carry");g=R,x++}if(p[x]!==" "){for(var q=_-g;q!==_&&w[q]===0;)q++;for(var N=new Uint8Array(S+(_-q)),E=S;q!==_;)N[E++]=w[q++];return N}}}function d(p){var x=l(p);if(x)return x;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:l,decode:d}}var ql=Kl,Vl=ql,Va=Vl;var ei=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")}},ri=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 Fa(this,t)}},ni=class{decoders;constructor(t){this.decoders=t}or(t){return Fa(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 Fa(r,t){return new ni({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var oi=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 ei(t,e,n),this.decoder=new ri(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function tr({name:r,prefix:t,encode:e,decode:n}){return new oi(r,t,e,n)}function we({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=Va(e,r);return tr({prefix:t,name:r,encode:n,decode:i=>ee(o(i))})}function Fl(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 u=0;u<o;++u){let h=t[r[u]];if(h===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<e|h,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 Hl(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 zl(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=zl(n);return tr({prefix:t,name:r,encode(i){return Hl(i,n,e)},decode(i){return Fl(i,o,e,r)}})}var J=we({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Gl=we({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var si={};It(si,{base32:()=>Ee,base32hex:()=>Yl,base32hexpad:()=>jl,base32hexpadupper:()=>Ql,base32hexupper:()=>Xl,base32pad:()=>Zl,base32padupper:()=>Wl,base32upper:()=>$l,base32z:()=>Jl});var Ee=it({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),$l=it({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Zl=it({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Wl=it({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Yl=it({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Xl=it({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),jl=it({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Ql=it({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Jl=it({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var ai={};It(ai,{base36:()=>Ur,base36upper:()=>tf});var Ur=we({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),tf=we({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var ef=Ga,Ha=128,rf=127,nf=~rf,of=Math.pow(2,31);function Ga(r,t,e){t=t||[],e=e||0;for(var n=e;r>=of;)t[e++]=r&255|Ha,r/=128;for(;r&nf;)t[e++]=r&255|Ha,r>>>=7;return t[e]=r|0,Ga.bytes=e-n+1,t}var sf=ci,af=128,za=127;function ci(r,n){var e=0,n=n||0,o=0,i=n,s,a=r.length;do{if(i>=a)throw ci.bytes=0,new RangeError("Could not decode varint");s=r[i++],e+=o<28?(s&za)<<o:(s&za)*Math.pow(2,o),o+=7}while(s>=af);return ci.bytes=i-n,e}var cf=Math.pow(2,7),uf=Math.pow(2,14),lf=Math.pow(2,21),ff=Math.pow(2,28),hf=Math.pow(2,35),df=Math.pow(2,42),pf=Math.pow(2,49),mf=Math.pow(2,56),yf=Math.pow(2,63),gf=function(r){return r<cf?1:r<uf?2:r<lf?3:r<ff?4:r<hf?5:r<df?6:r<pf?7:r<mf?8:r<yf?9:10},bf={encode:ef,decode:sf,encodingLength:gf},xf=bf,Mr=xf;function kr(r,t=0){return[Mr.decode(r,t),Mr.decode.bytes]}function er(r,t,e=0){return Mr.encode(r,t,e),t}function rr(r){return Mr.encodingLength(r)}function Wt(r,t){let e=t.byteLength,n=rr(r),o=n+rr(e),i=new Uint8Array(o+e);return er(r,i,0),er(e,i,n),i.set(t,o),new nr(r,e,t,i)}function Yt(r){let t=ee(r),[e,n]=kr(t),[o,i]=kr(t.subarray(n)),s=t.subarray(n+i);if(s.byteLength!==o)throw new Error("Incorrect length");return new nr(e,o,s,t)}function $a(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&Ma(r.bytes,e.bytes)}}var nr=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};function Za(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return Ef(e,ui(r),t??J.encoder);default:return Sf(e,ui(r),t??Ee.encoder)}}var Wa=new WeakMap;function ui(r){let t=Wa.get(r);if(t==null){let e=new Map;return Wa.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!==Kr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==vf)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=Wt(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&&$a(t.multihash,n.multihash)}toString(t){return Za(this,t)}toJSON(){return{"/":Za(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??Ya(n,o,i.bytes))}else if(e[_f]===!0){let{version:n,multihash:o,code:i}=e,s=Yt(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!==Kr)throw new Error(`Version 0 CID must use dag-pb (code: ${Kr}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=Ya(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,Kr,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,o=ee(t.subarray(n,n+e.multihashSize));if(o.byteLength!==e.multihashSize)throw new Error("Incorrect length");let i=o.subarray(e.multihashSize-e.digestSize),s=new nr(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,l]=kr(t.subarray(e));return e+=l,f},o=n(),i=Kr;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(),u=e+c,h=u-s;return{version:o,codec:i,multihashCode:a,digestSize:c,multihashSize:h,size:u}}static parse(t,e){let[n,o]=wf(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 ui(i).set(n,t),i}};function wf(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 Ee.prefix:{let e=t??Ee;return[Ee.prefix,e.decode(r)]}case Ur.prefix:{let e=t??Ur;return[Ur.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 Ef(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 Sf(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 Kr=112,vf=18;function Ya(r,t,e){let n=rr(r),o=n+rr(t),i=new Uint8Array(o+e.byteLength);return er(r,i,0),er(t,i,n),i.set(e,o),i}var _f=Symbol.for("@ipld/js-cid/CID");var li={};It(li,{identity:()=>Ht});var Xa=0,Af="identity",ja=ee;function If(r,t){if(t?.truncate!=null&&t.truncate!==r.byteLength){if(t.truncate<0||t.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t.truncate)}return Wt(Xa,ja(r))}var Ht={code:Xa,name:Af,encode:ja,digest:If};function ft(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 et(r=0){return new Uint8Array(r)}function Tt(r=0){return new Uint8Array(r)}function ne(r,t){t==null&&(t=r.reduce((o,i)=>o+i.length,0));let e=Tt(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}var Ja=Symbol.for("@achingbrain/uint8arraylist");function Qa(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let o=e+n.byteLength;if(t<o)return{buf:n,index:t-e};e=o}throw new RangeError("index is out of bounds")}function Bn(r){return!!r?.[Ja]}var ct=class r{bufs;length;[Ja]=!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(Bn(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(Bn(n))e+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=Qa(this.bufs,t);return e.buf[e.index]}set(t,e){let n=Qa(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else if(Bn(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 ne(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:ne(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 u=t>=a&&t<c,h=e>a&&e<=c;if(u&&h){if(t===a&&e===c){n.push(s);break}let f=t-a;n.push(s.subarray(f,f+(e-t)));break}if(u){if(t===0){n.push(s);continue}n.push(s.subarray(t-a));continue}if(h){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(!Bn(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,u=n.byteLength-1,h;for(let f=e;f<=c;f+=h){h=0;for(let l=u;l>=0;l--){let d=this.get(f+l);if(n[l]!==d){h=Math.max(1,l-a[d]);break}}if(h===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=Tt(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=et(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=et(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=et(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=Tt(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=et(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=et(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=et(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=et(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=et(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(!ft(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 fi={};It(fi,{base10:()=>Tf});var Tf=we({prefix:"9",name:"base10",alphabet:"0123456789"});var hi={};It(hi,{base16:()=>Cf,base16upper:()=>Df});var Cf=it({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Df=it({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var di={};It(di,{base2:()=>Pf});var Pf=it({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var pi={};It(pi,{base256emoji:()=>Nf});var tc=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}"),Bf=tc.reduce((r,t,e)=>(r[e]=t,r),[]),Lf=tc.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function Rf(r){return r.reduce((t,e)=>(t+=Bf[e],t),"")}function Of(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=Lf[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var Nf=tr({prefix:"\u{1F680}",name:"base256emoji",encode:Rf,decode:Of});var yi={};It(yi,{base64:()=>Uf,base64pad:()=>Mf,base64url:()=>mi,base64urlpad:()=>kf});var Uf=it({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Mf=it({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),mi=it({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),kf=it({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var gi={};It(gi,{base8:()=>Kf});var Kf=it({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var bi={};It(bi,{identity:()=>qf});var qf=tr({prefix:"\0",name:"identity",encode:r=>Ka(r),decode:r=>ka(r)});var Zm=new TextEncoder,Wm=new TextDecoder;var Ei={};It(Ei,{sha256:()=>or,sha512:()=>zf});var Hf=20;function wi({name:r,code:t,encode:e,minDigestLength:n,maxDigestLength:o}){return new xi(r,t,e,n,o)}var xi=class{name;code;encode;minDigestLength;maxDigestLength;constructor(t,e,n,o,i){this.name=t,this.code=e,this.encode=n,this.minDigestLength=o??Hf,this.maxDigestLength=i}digest(t,e){if(e?.truncate!=null){if(e.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&e.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(t instanceof Uint8Array){let n=this.encode(t);return n instanceof Uint8Array?ec(n,this.code,e?.truncate):n.then(o=>ec(o,this.code,e?.truncate))}else throw Error("Unknown type, must be binary type")}};function ec(r,t,e){if(e!=null&&e!==r.byteLength){if(e>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e)}return Wt(t,r)}function nc(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var or=wi({name:"sha2-256",code:18,encode:nc("SHA-256")}),zf=wi({name:"sha2-512",code:19,encode:nc("SHA-512")});var qr={...bi,...di,...gi,...fi,...hi,...si,...ai,...ii,...yi,...pi},s0={...Ei,...li};function ic(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var oc=ic("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Si=ic("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=Tt(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),Gf={utf8:oc,"utf-8":oc,hex:qr.base16,latin1:Si,ascii:Si,binary:Si,...qr},Ln=Gf;function k(r,t="utf8"){let e=Ln[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function K(r,t="utf8"){let e=Ln[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var $f=parseInt("11111",2),vi=parseInt("10000000",2),Zf=parseInt("01111111",2),sc={0:Vr,1:Vr,2:Wf,3:jf,4:Qf,5:Xf,6:Yf,16:Vr,22:Vr,48:Vr};function oe(r,t={offset:0}){let e=r[t.offset]&$f;if(t.offset++,sc[e]!=null)return sc[e](r,t);throw new Error("No decoder for tag "+e)}function Fr(r,t){let e=0;if((r[t.offset]&vi)===vi){let n=r[t.offset]&Zf,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 Vr(r,t){Fr(r,t);let e=[];for(;!(t.offset>=r.byteLength);){let n=oe(r,t);if(n===null)break;e.push(n)}return e}function Wf(r,t){let e=Fr(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 Yf(r,t){let e=Fr(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 u=r[t.offset];if(t.offset++,c.push(u&127),u<128){c.reverse();let h=0;for(let f=0;f<c.length;f++)h+=c[f]<<f*7;a+=`.${h}`,c=[]}}return a}function Xf(r,t){return t.offset++,null}function jf(r,t){let e=Fr(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 Qf(r,t){let e=Fr(r,t),n=r.subarray(t.offset,t.offset+e);return t.offset+=e,n}function Jf(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 _i(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let t=Jf(r.byteLength);return new ct(Uint8Array.from([t.byteLength|vi]),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]),_i(t),t)}function Rn(r){let t=Uint8Array.from([0]),e=new ct(t,r);return new ct(Uint8Array.from([3]),_i(e),e)}function Se(r,t=48){let e=new ct;for(let n of r)e.append(n);return new ct(Uint8Array.from([t]),_i(e),e)}async function ac(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 th=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),eh=Uint8Array.from([6,5,43,129,4,0,34]),rh=Uint8Array.from([6,5,43,129,4,0,35]),nh={ext:!0,kty:"EC",crv:"P-256"},oh={ext:!0,kty:"EC",crv:"P-384"},ih={ext:!0,kty:"EC",crv:"P-521"},Ai=32,Ii=48,Ti=66;function Ci(r){let t=oe(r);return cc(t)}function cc(r){let t=r[1][1][0],e=1,n,o;if(t.byteLength===Ai*2+1)return n=K(t.subarray(e,e+Ai),"base64url"),o=K(t.subarray(e+Ai),"base64url"),new ir({...nh,key_ops:["verify"],x:n,y:o});if(t.byteLength===Ii*2+1)return n=K(t.subarray(e,e+Ii),"base64url"),o=K(t.subarray(e+Ii),"base64url"),new ir({...oh,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 ir({...ih,key_ops:["verify"],x:n,y:o});throw new lt(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function uc(r){return Se([Ct(Uint8Array.from([1])),Se([sh(r.crv)],160),Se([Rn(new ct(Uint8Array.from([4]),k(r.x??"","base64url"),k(r.y??"","base64url")))],161)]).subarray()}function sh(r){if(r==="P-256")return th;if(r==="P-384")return eh;if(r==="P-521")return rh;throw new lt(`Invalid curve ${r}`)}var ir=class{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=uc(this.jwk)),this._raw}toMultihash(){return Ht.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:ft(this.raw,t.raw)}async verify(t,e,n){return ac(this.jwk,e,t,n)}};var Ne=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function se(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Hr(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function Dt(r,...t){if(!se(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 On(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Hr(r.outputLen),Hr(r.blockLen)}function ar(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 fc(r,t){Dt(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 Nn(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function zt(r,t){return r<<32-t|r>>>t}var hc=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",ah=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function qt(r){if(Dt(r),hc)return r.toHex();let t="";for(let e=0;e<r.length;e++)t+=ah[r[e]];return t}var ie={_0:48,_9:57,A:65,F:70,a:97,f:102};function lc(r){if(r>=ie._0&&r<=ie._9)return r-ie._0;if(r>=ie.A&&r<=ie.F)return r-(ie.A-10);if(r>=ie.a&&r<=ie.f)return r-(ie.a-10)}function Ue(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(hc)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=lc(r.charCodeAt(i)),a=lc(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 Di(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function zr(r){return typeof r=="string"&&(r=Di(r)),Dt(r),r}function vt(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];Dt(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 sr=class{};function Pi(r){let t=n=>r().update(zr(n)).digest(),e=r();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>r(),t}function cr(r=32){if(Ne&&typeof Ne.getRandomValues=="function")return Ne.getRandomValues(new Uint8Array(r));if(Ne&&typeof Ne.randomBytes=="function")return Uint8Array.from(Ne.randomBytes(r));throw new Error("crypto.getRandomValues must be defined")}function ch(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,u=n?0:4;r.setUint32(t+c,s,n),r.setUint32(t+u,a,n)}function dc(r,t,e){return r&t^~r&e}function pc(r,t,e){return r&t^r&e^t&e}var Gr=class extends sr{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=Nn(this.buffer)}update(t){ar(this),t=zr(t),Dt(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=Nn(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){ar(this),fc(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;ch(n,o-8,BigInt(this.length*8),i),this.process(n,0);let a=Nn(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,h=this.get();if(u>h.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)a.setUint32(4*f,h[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 yt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Un=BigInt(4294967295),mc=BigInt(32);function uh(r,t=!1){return t?{h:Number(r&Un),l:Number(r>>mc&Un)}:{h:Number(r>>mc&Un)|0,l:Number(r&Un)|0}}function yc(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}=uh(r[i],t);[n[i],o[i]]=[s,a]}return[n,o]}var Bi=(r,t,e)=>r>>>e,Li=(r,t,e)=>r<<32-e|t>>>e,Me=(r,t,e)=>r>>>e|t<<32-e,ke=(r,t,e)=>r<<32-e|t>>>e,$r=(r,t,e)=>r<<64-e|t>>>e-32,Zr=(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 gc=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),bc=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,xc=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),wc=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,Ec=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),Sc=(r,t,e,n,o,i)=>t+e+n+o+i+(r/2**32|0)|0;var fh=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]),ve=new Uint32Array(64),Mn=class extends Gr{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)ve[f]=t.getUint32(e,!1);for(let f=16;f<64;f++){let l=ve[f-15],d=ve[f-2],p=zt(l,7)^zt(l,18)^l>>>3,x=zt(d,17)^zt(d,19)^d>>>10;ve[f]=x+ve[f-7]+p+ve[f-16]|0}let{A:n,B:o,C:i,D:s,E:a,F:c,G:u,H:h}=this;for(let f=0;f<64;f++){let l=zt(a,6)^zt(a,11)^zt(a,25),d=h+l+dc(a,c,u)+fh[f]+ve[f]|0,x=(zt(n,2)^zt(n,13)^zt(n,22))+pc(n,o,i)|0;h=u,u=c,c=a,a=s+d|0,s=i,i=o,o=n,n=d+x|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,u=u+this.G|0,h=h+this.H|0,this.set(n,o,i,s,a,c,u,h)}roundClean(){ae(ve)}destroy(){this.set(0,0,0,0,0,0,0,0),ae(this.buffer)}};var vc=yc(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(r=>BigInt(r))),hh=vc[0],dh=vc[1],_e=new Uint32Array(80),Ae=new Uint32Array(80),Ri=class extends Gr{constructor(t=64){super(128,t,16,!1),this.Ah=yt[0]|0,this.Al=yt[1]|0,this.Bh=yt[2]|0,this.Bl=yt[3]|0,this.Ch=yt[4]|0,this.Cl=yt[5]|0,this.Dh=yt[6]|0,this.Dl=yt[7]|0,this.Eh=yt[8]|0,this.El=yt[9]|0,this.Fh=yt[10]|0,this.Fl=yt[11]|0,this.Gh=yt[12]|0,this.Gl=yt[13]|0,this.Hh=yt[14]|0,this.Hl=yt[15]|0}get(){let{Ah:t,Al:e,Bh:n,Bl:o,Ch:i,Cl:s,Dh:a,Dl:c,Eh:u,El:h,Fh:f,Fl:l,Gh:d,Gl:p,Hh:x,Hl:S}=this;return[t,e,n,o,i,s,a,c,u,h,f,l,d,p,x,S]}set(t,e,n,o,i,s,a,c,u,h,f,l,d,p,x,S){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=u|0,this.El=h|0,this.Fh=f|0,this.Fl=l|0,this.Gh=d|0,this.Gl=p|0,this.Hh=x|0,this.Hl=S|0}process(t,e){for(let w=0;w<16;w++,e+=4)_e[w]=t.getUint32(e),Ae[w]=t.getUint32(e+=4);for(let w=16;w<80;w++){let C=_e[w-15]|0,R=Ae[w-15]|0,V=Me(C,R,1)^Me(C,R,8)^Bi(C,R,7),q=ke(C,R,1)^ke(C,R,8)^Li(C,R,7),N=_e[w-2]|0,E=Ae[w-2]|0,D=Me(N,E,19)^$r(N,E,61)^Bi(N,E,6),U=ke(N,E,19)^Zr(N,E,61)^Li(N,E,6),P=xc(q,U,Ae[w-7],Ae[w-16]),b=wc(P,V,D,_e[w-7],_e[w-16]);_e[w]=b|0,Ae[w]=P|0}let{Ah:n,Al:o,Bh:i,Bl:s,Ch:a,Cl:c,Dh:u,Dl:h,Eh:f,El:l,Fh:d,Fl:p,Gh:x,Gl:S,Hh:g,Hl:_}=this;for(let w=0;w<80;w++){let C=Me(f,l,14)^Me(f,l,18)^$r(f,l,41),R=ke(f,l,14)^ke(f,l,18)^Zr(f,l,41),V=f&d^~f&x,q=l&p^~l&S,N=Ec(_,R,q,dh[w],Ae[w]),E=Sc(N,g,C,V,hh[w],_e[w]),D=N|0,U=Me(n,o,28)^$r(n,o,34)^$r(n,o,39),P=ke(n,o,28)^Zr(n,o,34)^Zr(n,o,39),b=n&i^n&a^i&a,m=o&s^o&c^s&c;g=x|0,_=S|0,x=d|0,S=p|0,d=f|0,p=l|0,{h:f,l}=jt(u|0,h|0,E|0,D|0),u=a|0,h=c|0,a=i|0,c=s|0,i=n|0,s=o|0;let y=gc(D,P,m);n=bc(y,E,U,b),o=y|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:u,l:h}=jt(this.Dh|0,this.Dl|0,u|0,h|0),{h:f,l}=jt(this.Eh|0,this.El|0,f|0,l|0),{h:d,l:p}=jt(this.Fh|0,this.Fl|0,d|0,p|0),{h:x,l:S}=jt(this.Gh|0,this.Gl|0,x|0,S|0),{h:g,l:_}=jt(this.Hh|0,this.Hl|0,g|0,_|0),this.set(n,o,i,s,a,c,u,h,f,l,d,p,x,S,g,_)}roundClean(){ae(_e,Ae)}destroy(){ae(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var kn=Pi(()=>new Mn);var _c=Pi(()=>new Ri);var Ui=BigInt(0),Ni=BigInt(1);function ue(r,t=""){if(typeof r!="boolean"){let e=t&&`"${t}"`;throw new Error(e+"expected boolean, got type="+typeof r)}return r}function Ot(r,t,e=""){let n=se(r),o=r?.length,i=t!==void 0;if(!n||i&&o!==t){let s=e&&`"${e}" `,a=i?` of length ${t}`:"",c=n?`length=${o}`:`type=${typeof r}`;throw new Error(s+"expected Uint8Array"+a+", got "+c)}return r}function Wr(r){let t=r.toString(16);return t.length&1?"0"+t:t}function Ac(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?Ui:BigInt("0x"+r)}function ur(r){return Ac(qt(r))}function le(r){return Dt(r),Ac(qt(Uint8Array.from(r).reverse()))}function Kn(r,t){return Ue(r.toString(16).padStart(t*2,"0"))}function Mi(r,t){return Kn(r,t).reverse()}function Y(r,t,e){let n;if(typeof t=="string")try{n=Ue(t)}catch(i){throw new Error(r+" must be hex string or Uint8Array, cause: "+i)}else if(se(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 Ic(r,t){if(r.length!==t.length)return!1;let e=0;for(let n=0;n<r.length;n++)e|=r[n]^t[n];return e===0}function ki(r){return Uint8Array.from(r)}var Oi=r=>typeof r=="bigint"&&Ui<=r;function Tc(r,t,e){return Oi(r)&&Oi(t)&&Oi(e)&&t<=r&&r<e}function Yr(r,t,e,n){if(!Tc(t,e,n))throw new Error("expected valid "+r+": "+e+" <= n < "+n+", got "+t)}function qn(r){let t;for(t=0;r>Ui;r>>=Ni,t+=1);return t}var Ie=r=>(Ni<<BigInt(r))-Ni;function Cc(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=d=>new Uint8Array(d),o=d=>Uint8Array.of(d),i=n(r),s=n(r),a=0,c=()=>{i.fill(1),s.fill(0),a=0},u=(...d)=>e(s,i,...d),h=(d=n(0))=>{s=u(o(0),d),i=u(),d.length!==0&&(s=u(o(1),d),i=u())},f=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let d=0,p=[];for(;d<t;){i=u();let x=i.slice();p.push(x),d+=i.length}return vt(...p)};return(d,p)=>{c(),h(d);let x;for(;!(x=p(f()));)h();return c(),x}}function Te(r,t,e={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function n(o,i,s){let a=r[o];if(s&&a===void 0)return;let c=typeof a;if(c!==i||a===null)throw new Error(`param "${o}" is invalid: expected ${i}, got ${c}`)}Object.entries(t).forEach(([o,i])=>n(o,i,!1)),Object.entries(e).forEach(([o,i])=>n(o,i,!0))}var Ki=()=>{throw new Error("not implemented")};function lr(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),dt=BigInt(1),Ke=BigInt(2),Bc=BigInt(3),Lc=BigInt(4),Rc=BigInt(5),ph=BigInt(7),Oc=BigInt(8),mh=BigInt(9),Nc=BigInt(16);function at(r,t){let e=r%t;return e>=_t?e:t+e}function tt(r,t,e){let n=r;for(;t-- >_t;)n*=n,n%=e;return n}function Dc(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=at(r,t),n=t,o=_t,i=dt,s=dt,a=_t;for(;e!==_t;){let u=n/e,h=n%e,f=o-s*u,l=i-a*u;n=e,e=h,o=s,i=a,s=f,a=l}if(n!==dt)throw new Error("invert: does not exist");return at(o,t)}function qi(r,t,e){if(!r.eql(r.sqr(t),e))throw new Error("Cannot find square root")}function Uc(r,t){let e=(r.ORDER+dt)/Lc,n=r.pow(t,e);return qi(r,n,t),n}function yh(r,t){let e=(r.ORDER-Rc)/Oc,n=r.mul(t,Ke),o=r.pow(n,e),i=r.mul(t,o),s=r.mul(r.mul(i,Ke),o),a=r.mul(i,r.sub(s,r.ONE));return qi(r,a,t),a}function gh(r){let t=Nt(r),e=Mc(r),n=e(t,t.neg(t.ONE)),o=e(t,n),i=e(t,t.neg(n)),s=(r+ph)/Nc;return(a,c)=>{let u=a.pow(c,s),h=a.mul(u,n),f=a.mul(u,o),l=a.mul(u,i),d=a.eql(a.sqr(h),c),p=a.eql(a.sqr(f),c);u=a.cmov(u,h,d),h=a.cmov(l,f,p);let x=a.eql(a.sqr(h),c),S=a.cmov(u,h,x);return qi(a,S,c),S}}function Mc(r){if(r<Bc)throw new Error("sqrt is not defined for small field");let t=r-dt,e=0;for(;t%Ke===_t;)t/=Ke,e++;let n=Ke,o=Nt(r);for(;Pc(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(e===1)return Uc;let i=o.pow(n,t),s=(t+dt)/Ke;return function(c,u){if(c.is0(u))return u;if(Pc(c,u)!==1)throw new Error("Cannot find square root");let h=e,f=c.mul(c.ONE,i),l=c.pow(u,t),d=c.pow(u,s);for(;!c.eql(l,c.ONE);){if(c.is0(l))return c.ZERO;let p=1,x=c.sqr(l);for(;!c.eql(x,c.ONE);)if(p++,x=c.sqr(x),p===h)throw new Error("Cannot find square root");let S=dt<<BigInt(h-p-1),g=c.pow(f,S);h=p,f=c.sqr(g),l=c.mul(l,f),d=c.mul(d,g)}return d}}function bh(r){return r%Lc===Bc?Uc:r%Oc===Rc?yh:r%Nc===mh?gh(r):Mc(r)}var fe=(r,t)=>(at(r,t)&dt)===dt,xh=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Vi(r){let t={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},e=xh.reduce((n,o)=>(n[o]="function",n),t);return Te(r,e),r}function wh(r,t,e){if(e<_t)throw new Error("invalid exponent, negatives unsupported");if(e===_t)return r.ONE;if(e===dt)return t;let n=r.ONE,o=t;for(;e>_t;)e&dt&&(n=r.mul(n,o)),o=r.sqr(o),e>>=dt;return n}function Xr(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 Pc(r,t){let e=(r.ORDER-dt)/Ke,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 Vn(r,t){t!==void 0&&Hr(t);let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}function Nt(r,t,e=!1,n={}){if(r<=_t)throw new Error("invalid field: expected ORDER > 0, got "+r);let o,i,s=!1,a;if(typeof t=="object"&&t!=null){if(n.sqrt||e)throw new Error("cannot specify opts in two arguments");let l=t;l.BITS&&(o=l.BITS),l.sqrt&&(i=l.sqrt),typeof l.isLE=="boolean"&&(e=l.isLE),typeof l.modFromBytes=="boolean"&&(s=l.modFromBytes),a=l.allowedLengths}else typeof t=="number"&&(o=t),n.sqrt&&(i=n.sqrt);let{nBitLength:c,nByteLength:u}=Vn(r,o);if(u>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let h,f=Object.freeze({ORDER:r,isLE:e,BITS:c,BYTES:u,MASK:Ie(c),ZERO:_t,ONE:dt,allowedLengths:a,create:l=>at(l,r),isValid:l=>{if(typeof l!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof l);return _t<=l&&l<r},is0:l=>l===_t,isValidNot0:l=>!f.is0(l)&&f.isValid(l),isOdd:l=>(l&dt)===dt,neg:l=>at(-l,r),eql:(l,d)=>l===d,sqr:l=>at(l*l,r),add:(l,d)=>at(l+d,r),sub:(l,d)=>at(l-d,r),mul:(l,d)=>at(l*d,r),pow:(l,d)=>wh(f,l,d),div:(l,d)=>at(l*Dc(d,r),r),sqrN:l=>l*l,addN:(l,d)=>l+d,subN:(l,d)=>l-d,mulN:(l,d)=>l*d,inv:l=>Dc(l,r),sqrt:i||(l=>(h||(h=bh(r)),h(f,l))),toBytes:l=>e?Mi(l,u):Kn(l,u),fromBytes:(l,d=!0)=>{if(a){if(!a.includes(l.length)||l.length>u)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+l.length);let x=new Uint8Array(u);x.set(l,e?0:x.length-l.length),l=x}if(l.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+l.length);let p=e?le(l):ur(l);if(s&&(p=at(p,r)),!d&&!f.isValid(p))throw new Error("invalid field element: outside of range 0..ORDER");return p},invertBatch:l=>Xr(f,l),cmov:(l,d,p)=>p?d:l});return Object.freeze(f)}function kc(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 Fi(r){let t=kc(r);return t+Math.ceil(t/2)}function Hi(r,t,e=!1){let n=r.length,o=kc(t),i=Fi(t);if(n<16||n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);let s=e?le(r):ur(r),a=at(s,t-dt)+dt;return e?Mi(a,o):Kn(a,o)}var fr=BigInt(0),qe=BigInt(1);function jr(r,t){let e=t.negate();return r?e:t}function he(r,t){let e=Xr(r.Fp,t.map(n=>n.Z));return t.map((n,o)=>r.fromAffine(n.toAffine(e[o])))}function Fc(r,t){if(!Number.isSafeInteger(r)||r<=0||r>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+r)}function zi(r,t){Fc(r,t);let e=Math.ceil(t/r)+1,n=2**(r-1),o=2**r,i=Ie(r),s=BigInt(r);return{windows:e,windowSize:n,mask:i,maxNumber:o,shiftBy:s}}function Kc(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+=qe);let u=t*n,h=u+Math.abs(a)-1,f=a===0,l=a<0,d=t%2!==0;return{nextN:c,offset:h,isZero:f,isNeg:l,isNegF:d,offsetF:u}}function Eh(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 Sh(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,Hc=new WeakMap;function $i(r){return Hc.get(r)||1}function qc(r){if(r!==fr)throw new Error("invalid wNAF")}var hr=class{constructor(t,e){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=e}_unsafeLadder(t,e,n=this.ZERO){let o=t;for(;e>fr;)e&qe&&(n=n.add(o)),o=o.double(),e>>=qe;return n}precomputeWindow(t,e){let{windows:n,windowSize:o}=zi(e,this.bits),i=[],s=t,a=s;for(let c=0;c<n;c++){a=s,i.push(a);for(let u=1;u<o;u++)a=a.add(s),i.push(a);s=a.double()}return i}wNAF(t,e,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,i=this.BASE,s=zi(t,this.bits);for(let a=0;a<s.windows;a++){let{nextN:c,offset:u,isZero:h,isNeg:f,isNegF:l,offsetF:d}=Kc(n,a,s);n=c,h?i=i.add(jr(l,e[d])):o=o.add(jr(f,e[u]))}return qc(n),{p:o,f:i}}wNAFUnsafe(t,e,n,o=this.ZERO){let i=zi(t,this.bits);for(let s=0;s<i.windows&&n!==fr;s++){let{nextN:a,offset:c,isZero:u,isNeg:h}=Kc(n,s,i);if(n=a,!u){let f=e[c];o=o.add(h?f.negate():f)}}return qc(n),o}getPrecomputes(t,e,n){let o=Gi.get(e);return o||(o=this.precomputeWindow(e,t),t!==1&&(typeof n=="function"&&(o=n(o)),Gi.set(e,o))),o}cached(t,e,n){let o=$i(t);return this.wNAF(o,this.getPrecomputes(o,t,n),e)}unsafe(t,e,n,o){let i=$i(t);return i===1?this._unsafeLadder(t,e,o):this.wNAFUnsafe(i,this.getPrecomputes(i,t,n),e,o)}createCache(t,e){Fc(e,this.bits),Hc.set(t,e),Gi.delete(t)}hasCache(t){return $i(t)!==1}};function zc(r,t,e,n){let o=t,i=r.ZERO,s=r.ZERO;for(;e>fr||n>fr;)e&qe&&(i=i.add(o)),n&qe&&(s=s.add(o)),o=o.double(),e>>=qe,n>>=qe;return{p1:i,p2:s}}function dr(r,t,e,n){Eh(e,r),Sh(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=qn(BigInt(o)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let u=Ie(c),h=new Array(Number(u)+1).fill(s),f=Math.floor((t.BITS-1)/c)*c,l=s;for(let d=f;d>=0;d-=c){h.fill(s);for(let x=0;x<i;x++){let S=n[x],g=Number(S>>BigInt(d)&u);h[g]=h[g].add(e[x])}let p=s;for(let x=h.length-1,S=s;x>0;x--)S=S.add(h[x]),p=p.add(S);if(l=l.add(p),d!==0)for(let x=0;x<c;x++)l=l.double()}return l}function Vc(r,t,e){if(t){if(t.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Vi(t),t}else return Nt(r,{isLE:e})}function Fn(r,t,e={},n){if(n===void 0&&(n=r==="edwards"),!t||typeof t!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let u=t[c];if(!(typeof u=="bigint"&&u>fr))throw new Error(`CURVE.${c} must be positive bigint`)}let o=Vc(t.p,e.Fp,n),i=Vc(t.n,e.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(t[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:i}}var Ce=BigInt(0),pt=BigInt(1),Zi=BigInt(2),vh=BigInt(8);function _h(r,t,e,n){let o=r.sqr(e),i=r.sqr(n),s=r.add(r.mul(t.a,o),i),a=r.add(r.ONE,r.mul(t.d,r.mul(o,i)));return r.eql(s,a)}function Ah(r,t={}){let e=Fn("edwards",r,t,t.FpFnLE),{Fp:n,Fn:o}=e,i=e.CURVE,{h:s}=i;Te(t,{},{uvRatio:"function"});let a=Zi<<BigInt(o.BYTES*8)-pt,c=S=>n.create(S),u=t.uvRatio||((S,g)=>{try{return{isValid:!0,value:n.sqrt(n.div(S,g))}}catch{return{isValid:!1,value:Ce}}});if(!_h(n,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function h(S,g,_=!1){let w=_?pt:Ce;return Yr("coordinate "+S,g,w,a),g}function f(S){if(!(S instanceof p))throw new Error("ExtendedPoint expected")}let l=lr((S,g)=>{let{X:_,Y:w,Z:C}=S,R=S.is0();g==null&&(g=R?vh:n.inv(C));let V=c(_*g),q=c(w*g),N=n.mul(C,g);if(R)return{x:Ce,y:pt};if(N!==pt)throw new Error("invZ was invalid");return{x:V,y:q}}),d=lr(S=>{let{a:g,d:_}=i;if(S.is0())throw new Error("bad point: ZERO");let{X:w,Y:C,Z:R,T:V}=S,q=c(w*w),N=c(C*C),E=c(R*R),D=c(E*E),U=c(q*g),P=c(E*c(U+N)),b=c(D+c(_*c(q*N)));if(P!==b)throw new Error("bad point: equation left != right (1)");let m=c(w*C),y=c(R*V);if(m!==y)throw new Error("bad point: equation left != right (2)");return!0});class p{constructor(g,_,w,C){this.X=h("x",g),this.Y=h("y",_),this.Z=h("z",w,!0),this.T=h("t",C),Object.freeze(this)}static CURVE(){return i}static fromAffine(g){if(g instanceof p)throw new Error("extended point not allowed");let{x:_,y:w}=g||{};return h("x",_),h("y",w),new p(_,w,pt,c(_*w))}static fromBytes(g,_=!1){let w=n.BYTES,{a:C,d:R}=i;g=ki(Ot(g,w,"point")),ue(_,"zip215");let V=ki(g),q=g[w-1];V[w-1]=q&-129;let N=le(V),E=_?a:n.ORDER;Yr("point.y",N,Ce,E);let D=c(N*N),U=c(D-pt),P=c(R*D-C),{isValid:b,value:m}=u(U,P);if(!b)throw new Error("bad point: invalid y coordinate");let y=(m&pt)===pt,v=(q&128)!==0;if(!_&&m===Ce&&v)throw new Error("bad point: x=0 and x_0=1");return v!==y&&(m=c(-m)),p.fromAffine({x:m,y:N})}static fromHex(g,_=!1){return p.fromBytes(Y("point",g),_)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,_=!0){return x.createCache(this,g),_||this.multiply(Zi),this}assertValidity(){d(this)}equals(g){f(g);let{X:_,Y:w,Z:C}=this,{X:R,Y:V,Z:q}=g,N=c(_*q),E=c(R*C),D=c(w*q),U=c(V*C);return N===E&&D===U}is0(){return this.equals(p.ZERO)}negate(){return new p(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:g}=i,{X:_,Y:w,Z:C}=this,R=c(_*_),V=c(w*w),q=c(Zi*c(C*C)),N=c(g*R),E=_+w,D=c(c(E*E)-R-V),U=N+V,P=U-q,b=N-V,m=c(D*P),y=c(U*b),v=c(D*b),A=c(P*U);return new p(m,y,A,v)}add(g){f(g);let{a:_,d:w}=i,{X:C,Y:R,Z:V,T:q}=this,{X:N,Y:E,Z:D,T:U}=g,P=c(C*N),b=c(R*E),m=c(q*w*U),y=c(V*D),v=c((C+R)*(N+E)-P-b),A=y-m,B=y+m,I=c(b-_*P),T=c(v*A),O=c(B*I),M=c(v*I),rt=c(A*B);return new p(T,O,rt,M)}subtract(g){return this.add(g.negate())}multiply(g){if(!o.isValidNot0(g))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:_,f:w}=x.cached(this,g,C=>he(p,C));return he(p,[_,w])[0]}multiplyUnsafe(g,_=p.ZERO){if(!o.isValid(g))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return g===Ce?p.ZERO:this.is0()||g===pt?this:x.unsafe(this,g,w=>he(p,w),_)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}isTorsionFree(){return x.unsafe(this,i.n).is0()}toAffine(g){return l(this,g)}clearCofactor(){return s===pt?this:this.multiplyUnsafe(s)}toBytes(){let{x:g,y:_}=this.toAffine(),w=n.toBytes(_);return w[w.length-1]|=g&pt?128:0,w}toHex(){return qt(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(g){return he(p,g)}static msm(g,_){return dr(p,o,g,_)}_setWindowSize(g){this.precompute(g)}toRawBytes(){return this.toBytes()}}p.BASE=new p(i.Gx,i.Gy,pt,c(i.Gx*i.Gy)),p.ZERO=new p(Ce,pt,pt,Ce),p.Fp=n,p.Fn=o;let x=new hr(p,o.BITS);return p.BASE.precompute(8),p}var Hn=class{constructor(t){this.ep=t}static fromBytes(t){Ki()}static fromHex(t){Ki()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(t){return this.ep.toAffine(t)}toHex(){return qt(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(t){return this.assertSame(t),this.init(this.ep.add(t.ep))}subtract(t){return this.assertSame(t),this.init(this.ep.subtract(t.ep))}multiply(t){return this.init(this.ep.multiply(t))}multiplyUnsafe(t){return this.init(this.ep.multiplyUnsafe(t))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(t,e){return this.init(this.ep.precompute(t,e))}toRawBytes(){return this.toBytes()}};function Ih(r,t,e={}){if(typeof t!="function")throw new Error('"hash" function param is required');Te(e,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=e,{BASE:o,Fp:i,Fn:s}=r,a=e.randomBytes||cr,c=e.adjustScalarBytes||(E=>E),u=e.domain||((E,D,U)=>{if(ue(U,"phflag"),D.length||U)throw new Error("Contexts/pre-hash are not supported");return E});function h(E){return s.create(le(E))}function f(E){let D=w.secretKey;E=Y("private key",E,D);let U=Y("hashed private key",t(E),2*D),P=c(U.slice(0,D)),b=U.slice(D,2*D),m=h(P);return{head:P,prefix:b,scalar:m}}function l(E){let{head:D,prefix:U,scalar:P}=f(E),b=o.multiply(P),m=b.toBytes();return{head:D,prefix:U,scalar:P,point:b,pointBytes:m}}function d(E){return l(E).pointBytes}function p(E=Uint8Array.of(),...D){let U=vt(...D);return h(t(u(U,Y("context",E),!!n)))}function x(E,D,U={}){E=Y("message",E),n&&(E=n(E));let{prefix:P,scalar:b,pointBytes:m}=l(D),y=p(U.context,P,E),v=o.multiply(y).toBytes(),A=p(U.context,v,m,E),B=s.create(y+A*b);if(!s.isValid(B))throw new Error("sign failed: invalid s");let I=vt(v,s.toBytes(B));return Ot(I,w.signature,"result")}let S={zip215:!0};function g(E,D,U,P=S){let{context:b,zip215:m}=P,y=w.signature;E=Y("signature",E,y),D=Y("message",D),U=Y("publicKey",U,w.publicKey),m!==void 0&&ue(m,"zip215"),n&&(D=n(D));let v=y/2,A=E.subarray(0,v),B=le(E.subarray(v,y)),I,T,O;try{I=r.fromBytes(U,m),T=r.fromBytes(A,m),O=o.multiplyUnsafe(B)}catch{return!1}if(!m&&I.isSmallOrder())return!1;let M=p(b,T.toBytes(),I.toBytes(),D);return T.add(I.multiplyUnsafe(M)).subtract(O).clearCofactor().is0()}let _=i.BYTES,w={secretKey:_,publicKey:_,signature:2*_,seed:_};function C(E=a(w.seed)){return Ot(E,w.seed,"seed")}function R(E){let D=N.randomSecretKey(E);return{secretKey:D,publicKey:d(D)}}function V(E){return se(E)&&E.length===s.BYTES}function q(E,D){try{return!!r.fromBytes(E,D)}catch{return!1}}let N={getExtendedPublicKey:l,randomSecretKey:C,isValidSecretKey:V,isValidPublicKey:q,toMontgomery(E){let{y:D}=r.fromBytes(E),U=w.publicKey,P=U===32;if(!P&&U!==57)throw new Error("only defined for 25519 and 448");let b=P?i.div(pt+D,pt-D):i.div(D-pt,D+pt);return i.toBytes(b)},toMontgomerySecret(E){let D=w.secretKey;Ot(E,D);let U=t(E.subarray(0,D));return c(U).subarray(0,D)},randomPrivateKey:C,precompute(E=8,D=r.BASE){return D.precompute(E,!1)}};return Object.freeze({keygen:R,getPublicKey:d,sign:x,verify:g,utils:N,Point:r,lengths:w})}function Th(r){let t={a:r.a,d:r.d,p:r.Fp.ORDER,n:r.n,h:r.h,Gx:r.Gx,Gy:r.Gy},e=r.Fp,n=Nt(t.n,r.nBitLength,!0),o={Fp:e,Fn:n,uvRatio:r.uvRatio},i={randomBytes:r.randomBytes,adjustScalarBytes:r.adjustScalarBytes,domain:r.domain,prehash:r.prehash,mapToCurve:r.mapToCurve};return{CURVE:t,curveOpts:o,hash:r.hash,eddsaOpts:i}}function Ch(r,t){let e=t.Point;return Object.assign({},t,{ExtendedPoint:e,CURVE:r,nBitLength:e.Fn.BITS,nByteLength:e.Fn.BYTES})}function Gc(r){let{CURVE:t,curveOpts:e,hash:n,eddsaOpts:o}=Th(r),i=Ah(t,e),s=Ih(i,n,o);return Ch(r,s)}var Dh=BigInt(0),de=BigInt(1),$c=BigInt(2),py=BigInt(3),Ph=BigInt(5),Bh=BigInt(8),pr=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Qr={p:pr,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Bh,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Lh(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),i=pr,a=r*r%i*r%i,c=tt(a,$c,i)*a%i,u=tt(c,de,i)*r%i,h=tt(u,Ph,i)*u%i,f=tt(h,t,i)*h%i,l=tt(f,e,i)*f%i,d=tt(l,n,i)*l%i,p=tt(d,o,i)*d%i,x=tt(p,o,i)*d%i,S=tt(x,t,i)*h%i;return{pow_p_5_8:tt(S,$c,i)*r%i,b2:a}}function Rh(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var Wi=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function ji(r,t){let e=pr,n=at(t*t*t,e),o=at(n*n*t,e),i=Lh(r*o).pow_p_5_8,s=at(r*n*i,e),a=at(t*s*s,e),c=s,u=at(s*Wi,e),h=a===r,f=a===at(-r,e),l=a===at(-r*Wi,e);return h&&(s=c),(f||l)&&(s=u),fe(s,e)&&(s=at(-s,e)),{isValid:h||f,value:s}}var De=Nt(Qr.p,{isLE:!0}),Oh=Nt(Qr.n,{isLE:!0}),Nh={...Qr,Fp:De,hash:_c,adjustScalarBytes:Rh,uvRatio:ji},pe=Gc(Nh);var Yi=Wi,Uh=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Mh=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),kh=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),Kh=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),Zc=r=>ji(de,r),qh=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Xi=r=>pe.Point.Fp.create(le(r)&qh);function Wc(r){let{d:t}=Qr,e=pr,n=g=>De.create(g),o=n(Yi*r*r),i=n((o+de)*kh),s=BigInt(-1),a=n((s-t*o)*n(o+t)),{isValid:c,value:u}=ji(i,a),h=n(u*r);fe(h,e)||(h=n(-h)),c||(u=h),c||(s=o);let f=n(s*(o-de)*Kh-a),l=u*u,d=n((u+u)*a),p=n(f*Uh),x=n(de-l),S=n(de+l);return new pe.Point(n(d*S),n(x*p),n(p*S),n(d*x))}function Vh(r){Dt(r,64);let t=Xi(r.subarray(0,32)),e=Wc(t),n=Xi(r.subarray(32,64)),o=Wc(n);return new me(e.add(o))}var me=class r extends Hn{constructor(t){super(t)}static fromAffine(t){return new r(pe.Point.fromAffine(t))}assertSame(t){if(!(t instanceof r))throw new Error("RistrettoPoint expected")}init(t){return new r(t)}static hashToCurve(t){return Vh(Y("ristrettoHash",t,64))}static fromBytes(t){Dt(t,32);let{a:e,d:n}=Qr,o=pr,i=C=>De.create(C),s=Xi(t);if(!Ic(De.toBytes(s),t)||fe(s,o))throw new Error("invalid ristretto255 encoding 1");let a=i(s*s),c=i(de+e*a),u=i(de-e*a),h=i(c*c),f=i(u*u),l=i(e*n*h-f),{isValid:d,value:p}=Zc(i(l*f)),x=i(p*u),S=i(p*x*l),g=i((s+s)*x);fe(g,o)&&(g=i(-g));let _=i(c*S),w=i(g*_);if(!d||fe(w,o)||_===Dh)throw new Error("invalid ristretto255 encoding 2");return new r(new pe.Point(g,_,de,w))}static fromHex(t){return r.fromBytes(Y("ristrettoHex",t,32))}static msm(t,e){return dr(r,pe.Point.Fn,t,e)}toBytes(){let{X:t,Y:e,Z:n,T:o}=this.ep,i=pr,s=S=>De.create(S),a=s(s(n+e)*s(n-e)),c=s(t*e),u=s(c*c),{value:h}=Zc(s(a*u)),f=s(h*a),l=s(h*c),d=s(f*l*o),p;if(fe(o*d,i)){let S=s(e*Yi),g=s(t*Yi);t=S,e=g,p=s(f*Mh)}else p=l;fe(t*d,i)&&(e=s(-e));let x=s((n-e)*p);return fe(x,i)&&(x=s(-x)),De.toBytes(x)}equals(t){this.assertSame(t);let{X:e,Y:n}=this.ep,{X:o,Y:i}=t.ep,s=u=>De.create(u),a=s(e*i)===s(n*o),c=s(n*i)===s(e*o);return a||c}is0(){return this.equals(r.ZERO)}};me.BASE=new me(pe.Point.BASE);me.ZERO=new me(pe.Point.ZERO);me.Fp=De;me.Fn=Oh;var Jr=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},zn=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var Yc={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new zn("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return t}};var Vt=Yc;var Gn=32;var Qi,Fh=(async()=>{try{return await Vt.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function Hh(r,t,e){if(r.buffer instanceof ArrayBuffer){let n=await Vt.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await Vt.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 zh(r,t,e){return pe.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}async function Xc(r,t,e){return Qi==null&&(Qi=await Fh),Qi?Hh(r,t,e):zh(r,t,e)}function $n(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Zn=class{type="Ed25519";raw;constructor(t){this.raw=Ji(t,Gn)}toMultihash(){return Ht.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:ft(this.raw,t.raw)}verify(t,e,n){n?.signal?.throwIfAborted();let o=Xc(this.raw,e,t);return $n(o)?o.then(i=>(n?.signal?.throwIfAborted(),i)):o}};function ts(r){return r=Ji(r,Gn),new Zn(r)}function Ji(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new lt(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}var $h=Math.pow(2,7),Zh=Math.pow(2,14),Wh=Math.pow(2,21),es=Math.pow(2,28),rs=Math.pow(2,35),ns=Math.pow(2,42),os=Math.pow(2,49),Z=128,xt=127;function Pt(r){if(r<$h)return 1;if(r<Zh)return 2;if(r<Wh)return 3;if(r<es)return 4;if(r<rs)return 5;if(r<ns)return 6;if(r<os)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function mr(r,t,e=0){switch(Pt(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 Yh(r,t,e=0){switch(Pt(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 is(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)*es,e<Z)||(e=r[t+5],n+=(e&xt)*rs,e<Z)||(e=r[t+6],n+=(e&xt)*ns,e<Z)||(e=r[t+7],n+=(e&xt)*os,e<Z))return n;throw new RangeError("Could not decode varint")}function Xh(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)*es,e<Z)||(e=r.get(t+5),n+=(e&xt)*rs,e<Z)||(e=r.get(t+6),n+=(e&xt)*ns,e<Z)||(e=r.get(t+7),n+=(e&xt)*os,e<Z))return n;throw new RangeError("Could not decode varint")}function yr(r,t,e=0){return t==null&&(t=Tt(Pt(r))),t instanceof Uint8Array?mr(r,t,e):Yh(r,t,e)}function tn(r,t=0){return r instanceof Uint8Array?is(r,t):Xh(r,t)}var as=new Float32Array([-0]),Pe=new Uint8Array(as.buffer);function Qc(r,t,e){as[0]=r,t[e]=Pe[0],t[e+1]=Pe[1],t[e+2]=Pe[2],t[e+3]=Pe[3]}function Jc(r,t){return Pe[0]=r[t],Pe[1]=r[t+1],Pe[2]=r[t+2],Pe[3]=r[t+3],as[0]}var cs=new Float64Array([-0]),wt=new Uint8Array(cs.buffer);function tu(r,t,e){cs[0]=r,t[e]=wt[0],t[e+1]=wt[1],t[e+2]=wt[2],t[e+3]=wt[3],t[e+4]=wt[4],t[e+5]=wt[5],t[e+6]=wt[6],t[e+7]=wt[7]}function eu(r,t){return wt[0]=r[t],wt[1]=r[t+1],wt[2]=r[t+2],wt[3]=r[t+3],wt[4]=r[t+4],wt[5]=r[t+5],wt[6]=r[t+6],wt[7]=r[t+7],cs[0]}var jh=BigInt(Number.MAX_SAFE_INTEGER),Qh=BigInt(Number.MIN_SAFE_INTEGER),Ut=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 Ve;if(t<jh&&t>Qh)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>ru&&(o=0n,++n>ru&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return Ve;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):Ve}},Ve=new Ut(0,0);Ve.toBigInt=function(){return 0n};Ve.zzEncode=Ve.zzDecode=function(){return this};Ve.length=function(){return 1};var ru=4294967296n;function nu(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 ou(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 us(r,t,e){let n=e,o,i;for(let s=0;s<r.length;++s)o=r.charCodeAt(s),o<128?t[e++]=o:o<2048?(t[e++]=o>>6|192,t[e++]=o&63|128):(o&64512)===55296&&((i=r.charCodeAt(s+1))&64512)===56320?(o=65536+((o&1023)<<10)+(i&1023),++s,t[e++]=o>>18|240,t[e++]=o>>12&63|128,t[e++]=o>>6&63|128,t[e++]=o&63|128):(t[e++]=o>>12|224,t[e++]=o>>6&63|128,t[e++]=o&63|128);return e-n}function Gt(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function Wn(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var ls=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,Gt(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Gt(this,4);return Wn(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Gt(this,4);return Wn(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Gt(this,4);let t=Jc(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw Gt(this,4);let t=eu(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw Gt(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return ou(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw Gt(this,t);this.pos+=t}else do if(this.pos>=this.len)throw Gt(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new Ut(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw Gt(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw Gt(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Gt(this,8);let t=Wn(this.buf,this.pos+=4),e=Wn(this.buf,this.pos+=4);return new Ut(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=is(this.buf,this.pos);return this.pos+=Pt(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 fs(r){return new ls(r instanceof Uint8Array?r:r.subarray())}function Bt(r,t,e){let n=fs(r);return t.decode(n,void 0,e)}function hs(r){let t=r??8192,e=t>>>1,n,o=t;return function(s){if(s<1||s>e)return Tt(s);o+s>t&&(n=Tt(t),o=0);let a=n.subarray(o,o+=s);return(o&7)!==0&&(o=(o|7)+1),a}}var Fe=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function ds(){}var ms=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},Jh=hs();function td(r){return globalThis.Buffer!=null?Tt(r):Jh(r)}var rn=class{len;head;tail;states;constructor(){this.len=0,this.head=new Fe(ds,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new Fe(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new ys((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(Yn,10,Ut.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=Ut.fromBigInt(t);return this._push(Yn,e.length(),e)}uint64Number(t){return this._push(mr,Pt(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=Ut.fromBigInt(t).zzEncode();return this._push(Yn,e.length(),e)}sint64Number(t){let e=Ut.fromNumber(t).zzEncode();return this._push(Yn,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(ps,1,t?1:0)}fixed32(t){return this._push(en,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=Ut.fromBigInt(t);return this._push(en,4,e.lo)._push(en,4,e.hi)}fixed64Number(t){let e=Ut.fromNumber(t);return this._push(en,4,e.lo)._push(en,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(Qc,4,t)}double(t){return this._push(tu,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(ps,1,0):this.uint32(e)._push(rd,e,t)}string(t){let e=nu(t);return e!==0?this.uint32(e)._push(us,e,t):this._push(ps,1,0)}fork(){return this.states=new ms(this),this.head=this.tail=new Fe(ds,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 Fe(ds,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=td(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function ps(r,t,e){t[e]=r&255}function ed(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var ys=class extends Fe{next;constructor(t,e){super(ed,t,e),this.next=void 0}};function Yn(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 en(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 rd(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(rn.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(nd,t,r),this},rn.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(od,t,r),this});function nd(r,t,e){t.set(r,e)}function od(r,t,e){r.length<40?us(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(k(r),e)}function gs(){return new rn}function Lt(r,t){let e=gs();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var gr;(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"})(gr||(gr={}));function Xn(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function He(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 Xn("enum",gr.VARINT,e,n)}function Rt(r,t){return Xn("message",gr.LENGTH_DELIMITED,r,t)}var nn=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 bs;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(bs||(bs={}));(function(r){r.codec=()=>He(bs)})(ut||(ut={}));var Qt;(function(r){let t;r.codec=()=>(t==null&&(t=Rt((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=>Lt(e,r.codec()),r.decode=(e,n)=>Bt(e,r.codec(),n)})(Qt||(Qt={}));var xs;(function(r){let t;r.codec=()=>(t==null&&(t=Rt((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=>Lt(e,r.codec()),r.decode=(e,n)=>Bt(e,r.codec(),n)})(xs||(xs={}));var sn={};It(sn,{MAX_RSA_KEY_SIZE:()=>ws,generateRSAKeyPair:()=>lu,jwkToJWKKeyPair:()=>fu,jwkToPkcs1:()=>cd,jwkToPkix:()=>_s,jwkToRSAPrivateKey:()=>Cs,pkcs1MessageToJwk:()=>Ss,pkcs1MessageToRSAPrivateKey:()=>As,pkcs1ToJwk:()=>ad,pkcs1ToRSAPrivateKey:()=>uu,pkixMessageToJwk:()=>vs,pkixMessageToRSAPublicKey:()=>Ts,pkixToJwk:()=>ud,pkixToRSAPublicKey:()=>Is});var jn=kn;var br=class{type="RSA";jwk;_raw;_multihash;constructor(t,e){this.jwk=t,this._multihash=e}get raw(){return this._raw==null&&(this._raw=sn.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:ft(this.raw,t.raw)}verify(t,e,n){return cu(this.jwk,e,t,n)}},on=class{type="RSA";jwk;_raw;publicKey;constructor(t,e){this.jwk=t,this.publicKey=e}get raw(){return this._raw==null&&(this._raw=sn.jwkToPkcs1(this.jwk)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:ft(this.raw,t.raw)}sign(t,e){return au(this.jwk,t,e)}};var ws=8192,Es=18,id=1062,sd=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function ad(r){let t=oe(r);return Ss(t)}function Ss(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 cd(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 lt("JWK was missing components");return Se([Ct(Uint8Array.from([0])),Ct(k(r.n,"base64url")),Ct(k(r.e,"base64url")),Ct(k(r.d,"base64url")),Ct(k(r.p,"base64url")),Ct(k(r.q,"base64url")),Ct(k(r.dp,"base64url")),Ct(k(r.dq,"base64url")),Ct(k(r.qi,"base64url"))]).subarray()}function ud(r){let t=oe(r,{offset:0});return vs(t)}function vs(r){let t=oe(r[1],{offset:0});return{kty:"RSA",n:K(t[0],"base64url"),e:K(t[1],"base64url")}}function _s(r){if(r.n==null||r.e==null)throw new lt("JWK was missing components");return Se([sd,Rn(Se([Ct(k(r.n,"base64url")),Ct(k(r.e,"base64url"))]))]).subarray()}function uu(r){let t=oe(r);return As(t)}function As(r){let t=Ss(r);return Cs(t)}function Is(r,t){if(r.byteLength>=id)throw new Qe("Key size is too large");let e=oe(r,{offset:0});return Ts(e,r,t)}function Ts(r,t,e){let n=vs(r);if(e==null){let o=jn(Qt.encode({Type:ut.RSA,Data:t}));e=Wt(Es,o)}return new br(n,e)}function Cs(r){if(du(r)>ws)throw new lt("Key size is too large");let t=fu(r),e=jn(Qt.encode({Type:ut.RSA,Data:_s(t.publicKey)})),n=Wt(Es,e);return new on(t.privateKey,new br(t.publicKey,n))}async function lu(r){if(r>ws)throw new lt("Key size is too large");let t=await hu(r),e=jn(Qt.encode({Type:ut.RSA,Data:_s(t.publicKey)})),n=Wt(Es,e);return new on(t.privateKey,new br(t.publicKey,n))}function fu(r){if(r==null)throw new lt("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function hu(r,t){let e=await Vt.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 ld(e,t);return{privateKey:n[0],publicKey:n[1]}}async function au(r,t,e){let n=await Vt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);e?.signal?.throwIfAborted();let o=await Vt.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 cu(r,t,e,n){let o=await Vt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let i=await Vt.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,t,e instanceof Uint8Array?e:e.subarray());return n?.signal?.throwIfAborted(),i}async function ld(r,t){if(r.privateKey==null||r.publicKey==null)throw new lt("Private and public key are required");let e=await Promise.all([Vt.get().subtle.exportKey("jwk",r.privateKey),Vt.get().subtle.exportKey("jwk",r.publicKey)]);return t?.signal?.throwIfAborted(),e}function du(r){if(r.kty!=="RSA")throw new lt("invalid key type");if(r.n==null)throw new lt("invalid key modulus");return k(r.n,"base64url").length*8}var Qn=class extends sr{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,On(t);let n=zr(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 ar(this),this.iHash.update(t),this}digestInto(t){ar(this),Dt(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()}},Ds=(r,t,e)=>new Qn(r,t).update(e).digest();Ds.create=(r,t)=>new Qn(r,t);var pu=(r,t)=>(r+(r>=0?t:-t)/mu)/t;function fd(r,t,e){let[[n,o],[i,s]]=t,a=pu(s*r,e),c=pu(-o*r,e),u=r-a*n-c*i,h=-a*o-c*s,f=u<ge,l=h<ge;f&&(u=-u),l&&(h=-h);let d=Ie(Math.ceil(qn(e)/2))+wr;if(u<ge||u>=d||h<ge||h>=d)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:f,k1:u,k2neg:l,k2:h}}function Bs(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function Ps(r,t){let e={};for(let n of Object.keys(t))e[n]=r[n]===void 0?t[n]:r[n];return ue(e.lowS,"lowS"),ue(e.prehash,"prehash"),e.format!==void 0&&Bs(e.format),e}var Ls=class extends Error{constructor(t=""){super(t)}},ye={Err:Ls,_tlv:{encode:(r,t)=>{let{Err:e}=ye;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=Wr(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let i=n>127?Wr(o.length/2|128):"";return Wr(r)+i+o+t},decode(r,t){let{Err:e}=ye,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 u=t.subarray(n,n+c);if(u.length!==c)throw new e("tlv.decode: length bytes not complete");if(u[0]===0)throw new e("tlv.decode(long): zero leftmost byte");for(let h of u)s=s<<8|h;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}=ye;if(r<ge)throw new t("integer: negative integers are not allowed");let e=Wr(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}=ye;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 ur(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=ye,o=Y("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:u,l:h}=n.decode(2,c);if(h.length)throw new t("invalid signature: left bytes after parsing");return{r:e.decode(a),s:e.decode(u)}},hexFromSig(r){let{_tlv:t,_int:e}=ye,n=t.encode(2,e.encode(r.r)),o=t.encode(2,e.encode(r.s)),i=n+o;return t.encode(48,i)}},ge=BigInt(0),wr=BigInt(1),mu=BigInt(2),Jn=BigInt(3),hd=BigInt(4);function xr(r,t){let{BYTES:e}=r,n;if(typeof t=="bigint")n=t;else{let o=Y("private key",t);try{n=r.fromBytes(o)}catch{throw new Error(`invalid private key: expected ui8a of size ${e}, got ${typeof t}`)}}if(!r.isValidNot0(n))throw new Error("invalid private key: out of range [1..N-1]");return n}function dd(r,t={}){let e=Fn("weierstrass",r,t),{Fp:n,Fn:o}=e,i=e.CURVE,{h:s,n:a}=i;Te(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:c}=t;if(c&&(!n.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let u=gu(n,o);function h(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(P,b,m){let{x:y,y:v}=b.toAffine(),A=n.toBytes(y);if(ue(m,"isCompressed"),m){h();let B=!n.isOdd(v);return vt(yu(B),A)}else return vt(Uint8Array.of(4),A,n.toBytes(v))}function l(P){Ot(P,void 0,"Point");let{publicKey:b,publicKeyUncompressed:m}=u,y=P.length,v=P[0],A=P.subarray(1);if(y===b&&(v===2||v===3)){let B=n.fromBytes(A);if(!n.isValid(B))throw new Error("bad point: is not on curve, wrong x");let I=x(B),T;try{T=n.sqrt(I)}catch(rt){let Q=rt instanceof Error?": "+rt.message:"";throw new Error("bad point: is not on curve, sqrt error"+Q)}h();let O=n.isOdd(T);return(v&1)===1!==O&&(T=n.neg(T)),{x:B,y:T}}else if(y===m&&v===4){let B=n.BYTES,I=n.fromBytes(A.subarray(0,B)),T=n.fromBytes(A.subarray(B,B*2));if(!S(I,T))throw new Error("bad point: is not on curve");return{x:I,y:T}}else throw new Error(`bad point: got length ${y}, expected compressed=${b} or uncompressed=${m}`)}let d=t.toBytes||f,p=t.fromBytes||l;function x(P){let b=n.sqr(P),m=n.mul(b,P);return n.add(n.add(m,n.mul(P,i.a)),i.b)}function S(P,b){let m=n.sqr(b),y=x(P);return n.eql(m,y)}if(!S(i.Gx,i.Gy))throw new Error("bad curve params: generator point");let g=n.mul(n.pow(i.a,Jn),hd),_=n.mul(n.sqr(i.b),BigInt(27));if(n.is0(n.add(g,_)))throw new Error("bad curve params: a or b");function w(P,b,m=!1){if(!n.isValid(b)||m&&n.is0(b))throw new Error(`bad point coordinate ${P}`);return b}function C(P){if(!(P instanceof E))throw new Error("ProjectivePoint expected")}function R(P){if(!c||!c.basises)throw new Error("no endo");return fd(P,c.basises,o.ORDER)}let V=lr((P,b)=>{let{X:m,Y:y,Z:v}=P;if(n.eql(v,n.ONE))return{x:m,y};let A=P.is0();b==null&&(b=A?n.ONE:n.inv(v));let B=n.mul(m,b),I=n.mul(y,b),T=n.mul(v,b);if(A)return{x:n.ZERO,y:n.ZERO};if(!n.eql(T,n.ONE))throw new Error("invZ was invalid");return{x:B,y:I}}),q=lr(P=>{if(P.is0()){if(t.allowInfinityPoint&&!n.is0(P.Y))return;throw new Error("bad point: ZERO")}let{x:b,y:m}=P.toAffine();if(!n.isValid(b)||!n.isValid(m))throw new Error("bad point: x or y not field elements");if(!S(b,m))throw new Error("bad point: equation left != right");if(!P.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function N(P,b,m,y,v){return m=new E(n.mul(m.X,P),m.Y,m.Z),b=jr(y,b),m=jr(v,m),b.add(m)}class E{constructor(b,m,y){this.X=w("x",b),this.Y=w("y",m,!0),this.Z=w("z",y),Object.freeze(this)}static CURVE(){return i}static fromAffine(b){let{x:m,y}=b||{};if(!b||!n.isValid(m)||!n.isValid(y))throw new Error("invalid affine point");if(b instanceof E)throw new Error("projective point not allowed");return n.is0(m)&&n.is0(y)?E.ZERO:new E(m,y,n.ONE)}static fromBytes(b){let m=E.fromAffine(p(Ot(b,void 0,"point")));return m.assertValidity(),m}static fromHex(b){return E.fromBytes(Y("pointHex",b))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(b=8,m=!0){return U.createCache(this,b),m||this.multiply(Jn),this}assertValidity(){q(this)}hasEvenY(){let{y:b}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(b)}equals(b){C(b);let{X:m,Y:y,Z:v}=this,{X:A,Y:B,Z:I}=b,T=n.eql(n.mul(m,I),n.mul(A,v)),O=n.eql(n.mul(y,I),n.mul(B,v));return T&&O}negate(){return new E(this.X,n.neg(this.Y),this.Z)}double(){let{a:b,b:m}=i,y=n.mul(m,Jn),{X:v,Y:A,Z:B}=this,I=n.ZERO,T=n.ZERO,O=n.ZERO,M=n.mul(v,v),rt=n.mul(A,A),Q=n.mul(B,B),z=n.mul(v,A);return z=n.add(z,z),O=n.mul(v,B),O=n.add(O,O),I=n.mul(b,O),T=n.mul(y,Q),T=n.add(I,T),I=n.sub(rt,T),T=n.add(rt,T),T=n.mul(I,T),I=n.mul(z,I),O=n.mul(y,O),Q=n.mul(b,Q),z=n.sub(M,Q),z=n.mul(b,z),z=n.add(z,O),O=n.add(M,M),M=n.add(O,M),M=n.add(M,Q),M=n.mul(M,z),T=n.add(T,M),Q=n.mul(A,B),Q=n.add(Q,Q),M=n.mul(Q,z),I=n.sub(I,M),O=n.mul(Q,rt),O=n.add(O,O),O=n.add(O,O),new E(I,T,O)}add(b){C(b);let{X:m,Y:y,Z:v}=this,{X:A,Y:B,Z:I}=b,T=n.ZERO,O=n.ZERO,M=n.ZERO,rt=i.a,Q=n.mul(i.b,Jn),z=n.mul(m,A),nt=n.mul(y,B),ht=n.mul(v,I),At=n.add(m,y),ot=n.add(A,B);At=n.mul(At,ot),ot=n.add(z,nt),At=n.sub(At,ot),ot=n.add(m,v);let bt=n.add(A,I);return ot=n.mul(ot,bt),bt=n.add(z,ht),ot=n.sub(ot,bt),bt=n.add(y,v),T=n.add(B,I),bt=n.mul(bt,T),T=n.add(nt,ht),bt=n.sub(bt,T),M=n.mul(rt,ot),T=n.mul(Q,ht),M=n.add(T,M),T=n.sub(nt,M),M=n.add(nt,M),O=n.mul(T,M),nt=n.add(z,z),nt=n.add(nt,z),ht=n.mul(rt,ht),ot=n.mul(Q,ot),nt=n.add(nt,ht),ht=n.sub(z,ht),ht=n.mul(rt,ht),ot=n.add(ot,ht),z=n.mul(nt,ot),O=n.add(O,z),z=n.mul(bt,ot),T=n.mul(At,T),T=n.sub(T,z),z=n.mul(At,nt),M=n.mul(bt,M),M=n.add(M,z),new E(T,O,M)}subtract(b){return this.add(b.negate())}is0(){return this.equals(E.ZERO)}multiply(b){let{endo:m}=t;if(!o.isValidNot0(b))throw new Error("invalid scalar: out of range");let y,v,A=B=>U.cached(this,B,I=>he(E,I));if(m){let{k1neg:B,k1:I,k2neg:T,k2:O}=R(b),{p:M,f:rt}=A(I),{p:Q,f:z}=A(O);v=rt.add(z),y=N(m.beta,M,Q,B,T)}else{let{p:B,f:I}=A(b);y=B,v=I}return he(E,[y,v])[0]}multiplyUnsafe(b){let{endo:m}=t,y=this;if(!o.isValid(b))throw new Error("invalid scalar: out of range");if(b===ge||y.is0())return E.ZERO;if(b===wr)return y;if(U.hasCache(this))return this.multiply(b);if(m){let{k1neg:v,k1:A,k2neg:B,k2:I}=R(b),{p1:T,p2:O}=zc(E,y,A,I);return N(m.beta,T,O,v,B)}else return U.unsafe(y,b)}multiplyAndAddUnsafe(b,m,y){let v=this.multiplyUnsafe(m).add(b.multiplyUnsafe(y));return v.is0()?void 0:v}toAffine(b){return V(this,b)}isTorsionFree(){let{isTorsionFree:b}=t;return s===wr?!0:b?b(E,this):U.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:b}=t;return s===wr?this:b?b(E,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(b=!0){return ue(b,"isCompressed"),this.assertValidity(),d(E,this,b)}toHex(b=!0){return qt(this.toBytes(b))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(b=!0){return this.toBytes(b)}_setWindowSize(b){this.precompute(b)}static normalizeZ(b){return he(E,b)}static msm(b,m){return dr(E,o,b,m)}static fromPrivateKey(b){return E.BASE.multiply(xr(o,b))}}E.BASE=new E(i.Gx,i.Gy,n.ONE),E.ZERO=new E(n.ZERO,n.ONE,n.ZERO),E.Fp=n,E.Fn=o;let D=o.BITS,U=new hr(E,t.endo?Math.ceil(D/2):D);return E.BASE.precompute(8),E}function yu(r){return Uint8Array.of(r?2:3)}function gu(r,t){return{secretKey:t.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function pd(r,t={}){let{Fn:e}=r,n=t.randomBytes||cr,o=Object.assign(gu(r.Fp,e),{seed:Fi(e.ORDER)});function i(d){try{return!!xr(e,d)}catch{return!1}}function s(d,p){let{publicKey:x,publicKeyUncompressed:S}=o;try{let g=d.length;return p===!0&&g!==x||p===!1&&g!==S?!1:!!r.fromBytes(d)}catch{return!1}}function a(d=n(o.seed)){return Hi(Ot(d,o.seed,"seed"),e.ORDER)}function c(d,p=!0){return r.BASE.multiply(xr(e,d)).toBytes(p)}function u(d){let p=a(d);return{secretKey:p,publicKey:c(p)}}function h(d){if(typeof d=="bigint")return!1;if(d instanceof r)return!0;let{secretKey:p,publicKey:x,publicKeyUncompressed:S}=o;if(e.allowedLengths||p===x)return;let g=Y("key",d).length;return g===x||g===S}function f(d,p,x=!0){if(h(d)===!0)throw new Error("first arg must be private key");if(h(p)===!1)throw new Error("second arg must be public key");let S=xr(e,d);return r.fromHex(p).multiply(S).toBytes(x)}return Object.freeze({getPublicKey:c,getSharedSecret:f,keygen:u,Point:r,utils:{isValidSecretKey:i,isValidPublicKey:s,randomSecretKey:a,isValidPrivateKey:i,randomPrivateKey:a,normPrivateKeyToScalar:d=>xr(e,d),precompute(d=8,p=r.BASE){return p.precompute(d,!1)}},lengths:o})}function md(r,t,e={}){On(t),Te(e,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let n=e.randomBytes||cr,o=e.hmac||((m,...y)=>Ds(t,m,vt(...y))),{Fp:i,Fn:s}=r,{ORDER:a,BITS:c}=s,{keygen:u,getPublicKey:h,getSharedSecret:f,utils:l,lengths:d}=pd(r,e),p={prehash:!1,lowS:typeof e.lowS=="boolean"?e.lowS:!1,format:void 0,extraEntropy:!1},x="compact";function S(m){let y=a>>wr;return m>y}function g(m,y){if(!s.isValidNot0(y))throw new Error(`invalid signature ${m}: out of range 1..Point.Fn.ORDER`);return y}function _(m,y){Bs(y);let v=d.signature,A=y==="compact"?v:y==="recovered"?v+1:void 0;return Ot(m,A,`${y} signature`)}class w{constructor(y,v,A){this.r=g("r",y),this.s=g("s",v),A!=null&&(this.recovery=A),Object.freeze(this)}static fromBytes(y,v=x){_(y,v);let A;if(v==="der"){let{r:O,s:M}=ye.toSig(Ot(y));return new w(O,M)}v==="recovered"&&(A=y[0],v="compact",y=y.subarray(1));let B=s.BYTES,I=y.subarray(0,B),T=y.subarray(B,B*2);return new w(s.fromBytes(I),s.fromBytes(T),A)}static fromHex(y,v){return this.fromBytes(Ue(y),v)}addRecoveryBit(y){return new w(this.r,this.s,y)}recoverPublicKey(y){let v=i.ORDER,{r:A,s:B,recovery:I}=this;if(I==null||![0,1,2,3].includes(I))throw new Error("recovery id invalid");if(a*mu<v&&I>1)throw new Error("recovery id is ambiguous for h>1 curve");let O=I===2||I===3?A+a:A;if(!i.isValid(O))throw new Error("recovery id 2 or 3 invalid");let M=i.toBytes(O),rt=r.fromBytes(vt(yu((I&1)===0),M)),Q=s.inv(O),z=R(Y("msgHash",y)),nt=s.create(-z*Q),ht=s.create(B*Q),At=r.BASE.multiplyUnsafe(nt).add(rt.multiplyUnsafe(ht));if(At.is0())throw new Error("point at infinify");return At.assertValidity(),At}hasHighS(){return S(this.s)}toBytes(y=x){if(Bs(y),y==="der")return Ue(ye.hexFromSig(this));let v=s.toBytes(this.r),A=s.toBytes(this.s);if(y==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return vt(Uint8Array.of(this.recovery),v,A)}return vt(v,A)}toHex(y){return qt(this.toBytes(y))}assertValidity(){}static fromCompact(y){return w.fromBytes(Y("sig",y),"compact")}static fromDER(y){return w.fromBytes(Y("sig",y),"der")}normalizeS(){return this.hasHighS()?new w(this.r,s.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return qt(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return qt(this.toBytes("compact"))}}let C=e.bits2int||function(y){if(y.length>8192)throw new Error("input is too large");let v=ur(y),A=y.length*8-c;return A>0?v>>BigInt(A):v},R=e.bits2int_modN||function(y){return s.create(C(y))},V=Ie(c);function q(m){return Yr("num < 2^"+c,m,ge,V),s.toBytes(m)}function N(m,y){return Ot(m,void 0,"message"),y?Ot(t(m),void 0,"prehashed message"):m}function E(m,y,v){if(["recovered","canonical"].some(nt=>nt in v))throw new Error("sign() legacy options not supported");let{lowS:A,prehash:B,extraEntropy:I}=Ps(v,p);m=N(m,B);let T=R(m),O=xr(s,y),M=[q(O),q(T)];if(I!=null&&I!==!1){let nt=I===!0?n(d.secretKey):I;M.push(Y("extraEntropy",nt))}let rt=vt(...M),Q=T;function z(nt){let ht=C(nt);if(!s.isValidNot0(ht))return;let At=s.inv(ht),ot=r.BASE.multiply(ht).toAffine(),bt=s.create(ot.x);if(bt===ge)return;let In=s.create(At*s.create(Q+bt*O));if(In===ge)return;let Ca=(ot.x===bt?0:2)|Number(ot.y&wr),Da=In;return A&&S(In)&&(Da=s.neg(In),Ca^=1),new w(bt,Da,Ca)}return{seed:rt,k2sig:z}}function D(m,y,v={}){m=Y("message",m);let{seed:A,k2sig:B}=E(m,y,v);return Cc(t.outputLen,s.BYTES,o)(A,B)}function U(m){let y,v=typeof m=="string"||se(m),A=!v&&m!==null&&typeof m=="object"&&typeof m.r=="bigint"&&typeof m.s=="bigint";if(!v&&!A)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(A)y=new w(m.r,m.s);else if(v){try{y=w.fromBytes(Y("sig",m),"der")}catch(B){if(!(B instanceof ye.Err))throw B}if(!y)try{y=w.fromBytes(Y("sig",m),"compact")}catch{return!1}}return y||!1}function P(m,y,v,A={}){let{lowS:B,prehash:I,format:T}=Ps(A,p);if(v=Y("publicKey",v),y=N(Y("message",y),I),"strict"in A)throw new Error("options.strict was renamed to lowS");let O=T===void 0?U(m):w.fromBytes(Y("sig",m),T);if(O===!1)return!1;try{let M=r.fromBytes(v);if(B&&O.hasHighS())return!1;let{r:rt,s:Q}=O,z=R(y),nt=s.inv(Q),ht=s.create(z*nt),At=s.create(rt*nt),ot=r.BASE.multiplyUnsafe(ht).add(M.multiplyUnsafe(At));return ot.is0()?!1:s.create(ot.x)===rt}catch{return!1}}function b(m,y,v={}){let{prehash:A}=Ps(v,p);return y=N(y,A),w.fromBytes(m,"recovered").recoverPublicKey(y).toBytes()}return Object.freeze({keygen:u,getPublicKey:h,getSharedSecret:f,utils:l,lengths:d,Point:r,sign:D,verify:P,recoverPublicKey:b,Signature:w,hash:t})}function yd(r){let t={a:r.a,b:r.b,p:r.Fp.ORDER,n:r.n,h:r.h,Gx:r.Gx,Gy:r.Gy},e=r.Fp,n=r.allowedPrivateKeyLengths?Array.from(new Set(r.allowedPrivateKeyLengths.map(s=>Math.ceil(s/2)))):void 0,o=Nt(t.n,{BITS:r.nBitLength,allowedLengths:n,modFromBytes:r.wrapPrivateKey}),i={Fp:e,Fn:o,allowInfinityPoint:r.allowInfinityPoint,endo:r.endo,isTorsionFree:r.isTorsionFree,clearCofactor:r.clearCofactor,fromBytes:r.fromBytes,toBytes:r.toBytes};return{CURVE:t,curveOpts:i}}function gd(r){let{CURVE:t,curveOpts:e}=yd(r),n={hmac:r.hmac,randomBytes:r.randomBytes,lowS:r.lowS,bits2int:r.bits2int,bits2int_modN:r.bits2int_modN};return{CURVE:t,curveOpts:e,hash:r.hash,ecdsaOpts:n}}function bd(r,t){let e=t.Point;return Object.assign({},t,{ProjectivePoint:e,CURVE:Object.assign({},r,Vn(e.Fn.ORDER,e.Fn.BITS))})}function bu(r){let{CURVE:t,curveOpts:e,hash:n,ecdsaOpts:o}=gd(r),i=dd(t,e),s=md(i,n,o);return bd(r,s)}function xu(r,t){let e=n=>bu({...r,hash:n});return{...e(t),create:e}}var Os={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},xd={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var wu=BigInt(2);function wd(r){let t=Os.p,e=BigInt(3),n=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),u=r*r*r%t,h=u*u*r%t,f=tt(h,e,t)*h%t,l=tt(f,e,t)*h%t,d=tt(l,wu,t)*u%t,p=tt(d,o,t)*d%t,x=tt(p,i,t)*p%t,S=tt(x,a,t)*x%t,g=tt(S,c,t)*S%t,_=tt(g,a,t)*x%t,w=tt(_,e,t)*h%t,C=tt(w,s,t)*p%t,R=tt(C,n,t)*u%t,V=tt(R,wu,t);if(!Rs.eql(Rs.sqr(V),r))throw new Error("Cannot find square root");return V}var Rs=Nt(Os.p,{sqrt:wd}),Er=xu({...Os,Fp:Rs,lowS:!0,endo:xd},kn);function Eu(r,t,e,n){let o=or.digest(e instanceof Uint8Array?e:e.subarray());if($n(o))return o.then(({digest:i})=>(n?.signal?.throwIfAborted(),Er.verify(t,i,r))).catch(i=>{throw i.name==="AbortError"?i:new Jr(String(i))});try{return n?.signal?.throwIfAborted(),Er.verify(t,o.digest,r)}catch(i){throw new Jr(String(i))}}var to=class{type="secp256k1";raw;_key;constructor(t){this._key=vu(t),this.raw=Su(this._key)}toMultihash(){return Ht.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:ft(this.raw,t.raw)}verify(t,e,n){return Eu(this._key,e,t,n)}};function Ns(r){return new to(r)}function Su(r){return Er.ProjectivePoint.fromHex(r).toRawBytes(!0)}function vu(r){try{return Er.ProjectivePoint.fromHex(r),r}catch(t){throw new Qe(String(t))}}function _u(r,t){let{Type:e,Data:n}=Qt.decode(r),o=n??new Uint8Array;switch(e){case ut.RSA:return Is(o,t);case ut.Ed25519:return ts(o);case ut.secp256k1:return Ns(o);case ut.ECDSA:return Ci(o);default:throw new Je}}function Au(r){let{Type:t,Data:e}=Qt.decode(r.digest),n=e??new Uint8Array;switch(t){case ut.Ed25519:return ts(n);case ut.secp256k1:return Ns(n);case ut.ECDSA:return Ci(n);default:throw new Je}}function Xt(r){return Qt.encode({Type:ut[r.type],Data:r.raw})}var Iu=Symbol.for("nodejs.util.inspect.custom"),Ed=114,an=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()})`}[Jo]=!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(Ed,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return ft(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return ft(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[Iu](){return`PeerId(${this.toString()})`}},eo=class extends an{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},ro=class extends an{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},no=class extends an{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},Sd=2336,cn=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=Ht.digest(k(this.url))}[Iu](){return`PeerId(${this.url})`}[Jo]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return st.createV1(Sd,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=K(t)),t.toString()===this.toString())}};var vd=114,Tu=2336;function Us(r,t){let e;if(r.charAt(0)==="1"||r.charAt(0)==="Q")e=Yt(J.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return _d(st.parse(r));if(t==null)throw new lt('Please pass a multibase decoder for strings that do not start with "1" or "Q"');e=Yt(t.decode(r))}return Sr(e)}function Sr(r){if(Id(r))return new eo({multihash:r});if(Ad(r))try{let t=Au(r);if(t.type==="Ed25519")return new ro({multihash:r,publicKey:t});if(t.type==="secp256k1")return new no({multihash:r,publicKey:t})}catch{let e=K(r.digest);return new cn(new URL(e))}throw new Cn("Supplied PeerID Multihash is invalid")}function _d(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==vd&&r.code!==Tu)throw new Tn("Supplied PeerID CID is invalid");if(r.code===Tu){let t=K(r.multihash.digest);return new cn(new URL(t))}return Sr(r.multihash)}function Ad(r){return r.code===Ht.code}function Id(r){return r.code===or.code}var un;(function(r){let t;r.codec=()=>(t==null&&(t=Rt((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:et(0),payloadType:et(0),payload:et(0),signature:et(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=>Lt(e,r.codec()),r.decode=(e,n)=>Bt(e,r.codec(),n)})(un||(un={}));var oo=class extends Error{constructor(t="Invalid signature"){super(t),this.name="InvalidSignatureError"}};var ln=class r{static createFromProtobuf=t=>{let e=un.decode(t),n=_u(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=Cu(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 oo("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=un.encode({publicKey:Xt(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(t){return t==null?!1:ft(this.marshal(),t.marshal())}async validate(t,e){let n=Cu(t,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,e)}},Cu=(r,t,e)=>{let n=k(r),o=yr(n.byteLength),i=yr(t.length),s=yr(e.length);return new ct(o,n,i,t,s,e)};var gt=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},be=class extends Error{static name="ValidationError";name="ValidationError"},fn=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},io=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var so=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",u=2**(8*o)-1;for(;;){let h=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let l=Number.parseInt(f,t);if(!Number.isNaN(l))return l});if(h===void 0)break;if(i*=t,i+=h,i>u||(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 Td=45,Cd=15,ao=new so;function Ms(r){if(!(r.length>Cd))return ao.new(r).parseWith(()=>ao.readIPv4Addr())}function ks(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Td))return ao.new(r).parseWith(()=>ao.readIPv6Addr())}function co(r){return!!Ms(r)}function Pu(r){return!!ks(r)}function qs(r){return t=>K(t,r)}function Vs(r){return t=>k(t,r)}function vr(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function ze(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(t)}function Bu(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=k(t[0],"base32"),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=ze(n);return ne([e,o],e.length+o.length)}function Lu(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let e=Ee.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=ze(n);return ne([e,o],e.length+o.length)}function Fs(r){let t=r.subarray(0,r.length-2),e=r.subarray(r.length-2),n=K(t,"base32"),o=vr(e);return`${n}:${o}`}var Hs=function(r){r=r.toString().trim();let t=new Uint8Array(4);return r.split(/\./g).forEach((e,n)=>{let o=parseInt(e,10);if(isNaN(o)||o<0||o>255)throw new gt("Invalid byte value in IP address");t[n]=o}),t},Ru=function(r){let t=0;r=r.toString().trim();let e=r.split(":",8),n;for(n=0;n<e.length;n++){let i=co(e[n]),s;i&&(s=Hs(e[n]),e[n]=K(s.subarray(0,2),"base16")),s!=null&&++n<8&&e.splice(n,0,K(s.subarray(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++){e[n]===""&&(e[n]="0");let i=parseInt(e[n],16);if(isNaN(i)||i<0||i>65535)throw new gt("Invalid byte value in IP address");o[t++]=i>>8&255,o[t++]=i&255}return o},Ou=function(r){if(r.byteLength!==4)throw new gt("IPv4 address was incorrect length");let t=[];for(let e=0;e<r.byteLength;e++)t.push(r[e]);return t.join(".")},Nu=function(r){if(r.byteLength!==16)throw new gt("IPv6 address was incorrect length");let t=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],i=r[n+1],s=`${o.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`;t.push(s)}let e=t.join(":");try{let n=new URL(`http://[${e}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new gt(`Invalid IPv6 address "${e}"`)}};function Uu(r){try{let t=new URL(`http://[${r}]`);return t.hostname.substring(1,t.hostname.length-1)}catch{throw new gt(`Invalid IPv6 address "${r}"`)}}var Ks=Object.values(qr).map(r=>r.decoder),Dd=(function(){let r=Ks[0].or(Ks[1]);return Ks.slice(2).forEach(t=>r=r.or(t)),r})();function Mu(r){return Dd.decode(r)}function ku(r){return t=>r.encoder.encode(t)}function Pd(r){if(parseInt(r).toString()!==r)throw new be("Value must be an integer")}function Bd(r){if(r<0)throw new be("Value must be a positive integer, or zero")}function Ld(r){return t=>{if(t>r)throw new be(`Value must be smaller than or equal to ${r}`)}}function Rd(...r){return t=>{for(let e of r)e(t)}}var hn=Rd(Pd,Bd,Ld(65535));var mt=-1,zs=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(t){let e;if(typeof t=="string"?e=this.protocolsByName.get(t):e=this.protocolsByCode.get(t),e==null)throw new io(`Protocol ${t} was unknown`);return e}addProtocol(t){this.protocolsByCode.set(t.code,t),this.protocolsByName.set(t.name,t),t.aliases?.forEach(e=>{this.protocolsByName.set(e,t)})}removeProtocol(t){let e=this.protocolsByCode.get(t);e!=null&&(this.protocolsByCode.delete(e.code),this.protocolsByName.delete(e.name),e.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},Mt=new zs,Wd=[{code:4,name:"ip4",size:32,valueToBytes:Hs,bytesToValue:Ou,validate:r=>{if(!co(r))throw new be(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:ze,bytesToValue:vr,validate:hn},{code:273,name:"udp",size:16,valueToBytes:ze,bytesToValue:vr,validate:hn},{code:33,name:"dccp",size:16,valueToBytes:ze,bytesToValue:vr,validate:hn},{code:41,name:"ip6",size:128,valueToBytes:Ru,bytesToValue:Nu,stringToValue:Uu,validate:r=>{if(!Pu(r))throw new be(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:mt},{code:43,name:"ipcidr",size:8,bytesToValue:qs("base10"),valueToBytes:Vs("base10")},{code:53,name:"dns",size:mt,resolvable:!0},{code:54,name:"dns4",size:mt,resolvable:!0},{code:55,name:"dns6",size:mt,resolvable:!0},{code:56,name:"dnsaddr",size:mt,resolvable:!0},{code:132,name:"sctp",size:16,valueToBytes:ze,bytesToValue:vr,validate:hn},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:mt,path:!0,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:mt,bytesToValue:qs("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Vs("base58btc")(r):st.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Fs,valueToBytes:Bu},{code:445,name:"onion3",size:296,bytesToValue:Fs,valueToBytes:Lu},{code:446,name:"garlic64",size:mt},{code:447,name:"garlic32",size:mt},{code:448,name:"tls"},{code:449,name:"sni",size:mt},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:mt,bytesToValue:ku(mi),valueToBytes:Mu},{code:480,name:"http"},{code:481,name:"http-path",size:mt,stringToValue:r=>`/${decodeURIComponent(r)}`,valueToString:r=>encodeURIComponent(r.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:mt}];Wd.forEach(r=>{Mt.addProtocol(r)});function Ku(r){let t=[],e=0;for(;e<r.length;){let n=tn(r,e),o=Mt.getProtocol(n),i=Pt(n),s=Yd(o,r,e+i),a=0;s>0&&o.size===mt&&(a=Pt(s));let c=i+a+s,u={code:n,name:o.name,bytes:r.subarray(e,e+c)};if(s>0){let h=e+i+a,f=r.subarray(h,h+s);u.value=o.bytesToValue?.(f)??K(f)}t.push(u),e+=c}return t}function qu(r){let t=0,e=[];for(let n of r){if(n.bytes==null){let o=Mt.getProtocol(n.code),i=Pt(n.code),s,a=0,c=0;n.value!=null&&(s=o.valueToBytes?.(n.value)??k(n.value),a=s.byteLength,o.size===mt&&(c=Pt(a)));let u=new Uint8Array(i+c+a),h=0;mr(n.code,u,h),h+=i,s!=null&&(o.size===mt&&(mr(a,u,h),h+=c),u.set(s,h)),n.bytes=u}e.push(n.bytes),t+=n.bytes.byteLength}return ne(e,t)}function Vu(r){if(r.charAt(0)!=="/")throw new gt('String multiaddr must start with "/"');let t=[],e="protocol",n="",o="";for(let i=1;i<r.length;i++){let s=r.charAt(i);s!=="/"&&(e==="protocol"?o+=r.charAt(i):n+=r.charAt(i));let a=i===r.length-1;if(s==="/"||a){let c=Mt.getProtocol(o);if(e==="protocol"){if(c.size==null||c.size===0){t.push({code:c.code,name:c.name}),n="",o="",e="protocol";continue}else if(a)throw new gt(`Component ${o} was missing value`);e="value"}else if(e==="value"){let u={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new gt(`Component ${o} was missing value`);u.value=c.stringToValue?.(n)??n}t.push(u),n="",o="",e="protocol"}}}if(o!==""&&n!=="")throw new gt("Incomplete multiaddr");return t}function Fu(r){return`/${r.flatMap(t=>{if(t.value==null)return t.name;let e=Mt.getProtocol(t.code);if(e==null)throw new gt(`Unknown protocol code ${t.code}`);return[t.name,e.valueToString?.(t.value)??t.value]}).join("/")}`}function Yd(r,t,e){return r.size==null||r.size===0?0:r.size>0?r.size/8:tn(t,e)}var Xd=Symbol.for("nodejs.util.inspect.custom"),ta=Symbol.for("@multiformats/multiaddr"),jd=[53,54,55,56],Js=class extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}};function Qd(r){if(r==null&&(r="/"),zu(r))return r.getComponents();if(r instanceof Uint8Array)return Ku(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),Vu(r);if(Array.isArray(r))return r;throw new gt("Must be a string, Uint8Array, Component[], or another Multiaddr")}var ho=class r{[ta]=!0;#t;#e;#r;constructor(t="/",e={}){this.#t=Qd(t),e.validate!==!1&&Jd(this)}get bytes(){return this.#r==null&&(this.#r=qu(this.#t)),this.#r}toString(){return this.#e==null&&(this.#e=Fu(this.#t)),this.#e}toJSON(){return this.toString()}toOptions(){let t,e,n,o,i="";for(let{code:a,name:c,value:u}of this.#t)a===42&&(i=`%${u??""}`),jd.includes(a)&&(e="tcp",o=443,n=`${u??""}${i}`,t=a===55?6:4),(a===6||a===273)&&(e=c==="tcp"?"tcp":"udp",o=parseInt(u??"")),(a===4||a===41)&&(e="tcp",n=`${u??""}${i}`,t=a===41?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}}getComponents(){return[...this.#t]}protos(){return this.#t.map(({code:t,value:e})=>{let n=Mt.getProtocol(t);return{code:t,size:n.size??0,name:n.name,resolvable:!!n.resolvable,path:!!n.path}})}protoCodes(){return this.#t.map(({code:t})=>t)}protoNames(){return this.#t.map(({name:t})=>t)}tuples(){return this.#t.map(({code:t,value:e})=>{if(e==null)return[t];let n=Mt.getProtocol(t),o=[t];return e!=null&&o.push(n.valueToBytes?.(e)??k(e)),o})}stringTuples(){return this.#t.map(({code:t,value:e})=>e==null?[t]:[t,e])}encapsulate(t){let e=new r(t);return new r([...this.#t,...e.getComponents()],{validate:!1})}decapsulate(t){let e=t.toString(),n=this.toString(),o=n.lastIndexOf(e);if(o<0)throw new fn(`Address ${this.toString()} does not contain subaddress: ${t.toString()}`);return new r(n.slice(0,o),{validate:!1})}decapsulateCode(t){let e;for(let n=this.#t.length-1;n>-1;n--)if(this.#t[n].code===t){e=n;break}return new r(this.#t.slice(0,e),{validate:!1})}getPeerId(){try{let t=[];this.#t.forEach(({code:n,value:o})=>{n===421&&t.push([n,o]),n===290&&(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(){for(let t of this.#t)if(Mt.getProtocol(t.code).path)return t.value??null;return null}equals(t){return ft(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(i=>i.resolvable);if(e==null)return[this];let n=Hu.get(e.name);if(n==null)throw new Js(`no available resolver for ${e.name}`);return(await n(this,t)).map(i=>Et(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(){return!(this.#t.length!==2||this.#t[0].code!==4&&this.#t[0].code!==41||this.#t[1].code!==6&&this.#t[1].code!==273)}[Xd](){return`Multiaddr(${this.toString()})`}};function Jd(r){r.getComponents().forEach(t=>{let e=Mt.getProtocol(t.code);t.value!=null&&e.validate?.(t.value)})}var aw=parseInt("0xFFFF",16),cw=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);var Hu=new Map;function zu(r){return!!r?.[ta]}function Et(r){return new ho(r)}function $t(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var po=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 Ze(r,t,e){if(t==null)return r;if(t.aborted)return r.catch(()=>{}),Promise.reject(new po(e?.errorMessage,e?.errorCode,e?.errorName));let n,o=new po(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 ea=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=$t(),this.haveNext=$t()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let t=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=$t(),t}async throw(t){return this.ended=!0,this.error=t,t!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(t)),{done:!0,value:void 0}}async return(){let t={done:!0,value:void 0};return this.ended=!0,this.nextResult=t,this.haveNext.resolve(),t}async push(t,e){await this._push(t,e)}async end(t,e){t!=null?await this.throw(t):await this._push(void 0,e)}async _push(t,e){if(t!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;t!=null?this.nextResult={done:!1,value:t}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=$t(),await Ze(this.readNext.promise,e?.signal,e)}};function mo(){return new ea}var yo=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Zu(r,t){let e=mo();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:u}=await Ze(n.next(),s?.signal);return c===!0?null:u}for(;o.byteLength<s.bytes;){let{value:c,done:u}=await Ze(n.next(),s?.signal);if(u===!0)throw new yo("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 go=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},bo=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},xo=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Wu(r,t={}){let e=Zu(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=Pt(t.maxDataLength));let n=t?.lengthDecoder??tn,o=t?.lengthEncoder??yr;return{read:async s=>{let a=-1,c=new ct;for(;;){c.append(await e.read({...s,bytes:1}));try{a=n(c)}catch(u){if(u instanceof RangeError)continue;throw u}if(a<0)throw new go("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new xo("message length length too long");if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new bo("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(u=>[o(u.byteLength),u]));await e.write(c,a)},unwrap:()=>e.unwrap()}}function Be(r,t){let e=Wu(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 ra=1e3,Yu=60*ra,wo=290,Xu=15,ju=120*Yu,Qu=1,Eo=2e3,Ju=100,na="circuit-relay-source",bn=`${ti}-circuit-relay`,oa=`${ti}-circuit-relay-source`,tl=2*Yu,el=BigInt(1<<17),Ft="/libp2p/circuit/relay/0.2.0/hop",We="/libp2p/circuit/relay/0.2.0/stop",rl=30*ra,p2=30*ra,xn=300,nl=4096,ol=.001;var W;(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=()=>He(e)})(t=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Rt((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),Dr.codec().encode(o.peer,i)),o.reservation!=null&&(i.uint32(26),So.codec().encode(o.reservation,i)),o.limit!=null&&(i.uint32(34),Pr.codec().encode(o.limit,i)),o.status!=null&&(i.uint32(40),F.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 u=o.uint32();switch(u>>>3){case 1:{a.type=r.Type.codec().decode(o);break}case 2:{a.peer=Dr.codec().decode(o,o.uint32(),{limits:s.limits?.peer});break}case 3:{a.reservation=So.codec().decode(o,o.uint32(),{limits:s.limits?.reservation});break}case 4:{a.limit=Pr.codec().decode(o,o.uint32(),{limits:s.limits?.limit});break}case 5:{a.status=F.codec().decode(o);break}default:{o.skipType(u&7);break}}}return a})),n),r.encode=o=>Lt(o,r.codec()),r.decode=(o,i)=>Bt(o,r.codec(),i)})(W||(W={}));var kt;(function(r){let t;(function(o){o.CONNECT="CONNECT",o.STATUS="STATUS"})(t=r.Type||(r.Type={}));let e;(function(o){o[o.CONNECT=0]="CONNECT",o[o.STATUS=1]="STATUS"})(e||(e={})),(function(o){o.codec=()=>He(e)})(t=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Rt((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),Dr.codec().encode(o.peer,i)),o.limit!=null&&(i.uint32(26),Pr.codec().encode(o.limit,i)),o.status!=null&&(i.uint32(32),F.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 u=o.uint32();switch(u>>>3){case 1:{a.type=r.Type.codec().decode(o);break}case 2:{a.peer=Dr.codec().decode(o,o.uint32(),{limits:s.limits?.peer});break}case 3:{a.limit=Pr.codec().decode(o,o.uint32(),{limits:s.limits?.limit});break}case 4:{a.status=F.codec().decode(o);break}default:{o.skipType(u&7);break}}}return a})),n),r.encode=o=>Lt(o,r.codec()),r.decode=(o,i)=>Bt(o,r.codec(),i)})(kt||(kt={}));var Dr;(function(r){let t;r.codec=()=>(t==null&&(t=Rt((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:et(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 nn('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=>Lt(e,r.codec()),r.decode=(e,n)=>Bt(e,r.codec(),n)})(Dr||(Dr={}));var So;(function(r){let t;r.codec=()=>(t==null&&(t=Rt((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),vo.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 nn('Decode error - map field "addrs" had too many elements');i.addrs.push(e.bytes());break}case 3:{i.voucher=vo.codec().decode(e,e.uint32(),{limits:o.limits?.voucher});break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Lt(e,r.codec()),r.decode=(e,n)=>Bt(e,r.codec(),n)})(So||(So={}));var Pr;(function(r){let t;r.codec=()=>(t==null&&(t=Rt((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=>Lt(e,r.codec()),r.decode=(e,n)=>Bt(e,r.codec(),n)})(Pr||(Pr={}));var F;(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"})(F||(F={}));var ia;(function(r){r[r.UNUSED=0]="UNUSED",r[r.OK=100]="OK",r[r.RESERVATION_REFUSED=200]="RESERVATION_REFUSED",r[r.RESOURCE_LIMIT_EXCEEDED=201]="RESOURCE_LIMIT_EXCEEDED",r[r.PERMISSION_DENIED=202]="PERMISSION_DENIED",r[r.CONNECTION_FAILED=203]="CONNECTION_FAILED",r[r.NO_RESERVATION=204]="NO_RESERVATION",r[r.MALFORMED_MESSAGE=400]="MALFORMED_MESSAGE",r[r.UNEXPECTED_MESSAGE=401]="UNEXPECTED_MESSAGE"})(ia||(ia={}));(function(r){r.codec=()=>He(ia)})(F||(F={}));var Br;(function(r){let t;r.codec=()=>(t==null&&(t=Rt((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:et(0),peer:et(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=>Lt(e,r.codec()),r.decode=(e,n)=>Bt(e,r.codec(),n)})(Br||(Br={}));var vo;(function(r){let t;r.codec=()=>(t==null&&(t=Rt((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),Br.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:et(0),payloadType:et(0),signature:et(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=Br.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=>Lt(e,r.codec()),r.decode=(e,n)=>Bt(e,r.codec(),n)})(vo||(vo={}));var j=r=>({match:t=>{let e=t[0];return e==null||e.code!==r||e.value!=null?!1:t.slice(1)}}),L=(r,t)=>({match:e=>{let n=e[0];return n?.code!==r||n.value==null||t!=null&&n.value!==t?!1:e.slice(1)}}),H=r=>({match:t=>{let e=r.match(t);return e===!1?t:e}}),St=(...r)=>({match:t=>{let e;for(let n of r){let o=n.match(t);o!==!1&&(e==null||o.length<e.length)&&(e=o)}return e??!1}}),G=(...r)=>({match:t=>{for(let e of r){let n=e.match(t);if(n===!1)return!1;t=n}return t}});function X(...r){function t(o){if(o==null)return!1;let i=o.getComponents();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 op=L(421),S2=X(op),Ao=L(54),Io=L(55),To=L(56),aa=L(53),v2=X(Ao,H(L(421))),_2=X(Io,H(L(421))),A2=X(To,H(L(421))),I2=X(St(aa,To,Ao,Io),H(L(421))),il=G(L(4),H(L(43))),sl=G(H(L(42)),L(41),H(L(43))),ca=St(il,sl),Ye=St(ca,aa,Ao,Io,To),T2=X(St(ca,G(St(aa,To,Ao,Io),H(L(421))))),C2=X(il),D2=X(sl),P2=X(ca),ua=G(Ye,L(6)),wn=G(Ye,L(273)),B2=X(G(ua,H(L(421)))),L2=X(wn),la=G(wn,j(460),H(L(421))),Co=G(wn,j(461),H(L(421))),ip=St(la,Co),R2=X(la),O2=X(Co),sa=St(Ye,ua,wn,la,Co),al=St(G(sa,j(477),H(L(421)))),N2=X(al),cl=St(G(sa,j(478),H(L(421))),G(sa,j(448),H(L(449)),j(477),H(L(421)))),U2=X(cl),ul=G(wn,j(280),H(L(466)),H(L(466)),H(L(421))),M2=X(ul),ll=G(Co,j(465),H(L(466)),H(L(466)),H(L(421))),k2=X(ll),_o=St(al,cl,G(ua,H(L(421))),G(ip,H(L(421))),G(Ye,H(L(421))),ul,ll,L(421)),fl=X(_o),sp=G(_o,j(290),L(421)),Do=X(sp),ap=St(G(_o,j(290),j(281),H(L(421))),G(_o,j(281),H(L(421))),G(j(281),H(L(421)))),K2=X(ap),cp=St(G(Ye,L(6),j(480),H(L(421))),G(Ye,j(480),H(L(421)))),q2=X(cp),up=G(Ye,St(G(L(6,"443"),j(480)),G(L(6),j(443)),G(L(6),j(448),j(480)),G(j(448),j(480)),j(448),j(443)),H(L(421))),V2=X(up),lp=St(G(L(777),H(L(421)))),F2=X(lp),fp=St(G(L(400),H(L(421)))),H2=X(fp);function Po(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 Bo=class extends Error{constructor(t="Transfer limit error"){super(t),this.name="TransferLimitError"}},En=class extends Error{constructor(t="Duration limit error"){super(t),this.name="DurationLimitError"}},Sn=class extends Error{static name="HadEnoughRelaysError";name="HadEnoughRelaysError"},Lo=class extends Error{static name="DoubleRelayError";name="DoubleRelayError"},Ro=class extends Error{static name="RelayQueueFullError";name="RelayQueueFullError"};async function*hl(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 Bo(`data limit of ${n} bytes exceeded`)}t.remaining-=i,yield o}}function dl(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=Po(s),c=!1,u=!1,h;n.limit?.data!=null&&(h={remaining:n.limit.data}),queueMicrotask(()=>{let f=()=>{o.log("relayed connection reached time limit"),t.abort(new En(`duration limit of ${n.limit?.duration} ms exceeded`))};a.addEventListener("abort",f,{once:!0}),t.sink(h==null?r.source:hl(r.source,h,o)).catch(l=>{o.log.error("error while relaying streams src -> dst",l),i(l)}).finally(()=>{c=!0,u&&(a.removeEventListener("abort",f),a.clear())})}),queueMicrotask(()=>{let f=()=>{o.log("relayed connection reached time limit"),r.abort(new En(`duration limit of ${n.limit?.duration} ms exceeded`))};a.addEventListener("abort",f,{once:!0}),r.sink(h==null?t.source:hl(t.source,h,o)).catch(l=>{o.log.error("error while relaying streams dst -> src",l),i(l)}).finally(()=>{u=!0,c&&(a.removeEventListener("abort",f),a.clear())})})}function fa(r){let t=r*BigInt(1e3),e=new Date().getTime();return Number(t-BigInt(e))}var vn=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}},Oo=X(G(fl.matchers[0],j(290))),No=X(j(290));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 Le=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 ha={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},pl={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},ml=new globalThis.TextEncoder;function hp(r,t){let e=ha[t],n=pl[t];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(t,n*e);return n}function dp(r,t,e){if(e.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=ha[t],o=pl[t],i=r;for(;i.length>0;){let s=ml.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 da(r,{size:t=32,utf8Buffer:e}={}){if(!ha[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 dp(r,t,e);r=ml.encode(r)}return hp(r,t)}var _n={hash:r=>Number(da(r,{size:32})),hashV:(r,t)=>pp(_n.hash(r,t))};function pp(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),k(t,"base16")}var pa=64,Zt=class{fp;h;seed;constructor(t,e,n,o=2){if(o>pa)throw new TypeError("Invalid Fingerprint Size");let i=e.hashV(t,n),s=et(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?ft(this.fp,t.fp):!1}};function Xe(r,t){return Math.floor(Math.random()*(t-r))+r}var je=class{contents;constructor(t){this.contents=new Array(t).fill(null)}has(t){if(!(t instanceof Zt))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof Zt))throw new TypeError("Invalid Fingerprint");for(let e=0;e<this.contents.length;e++)if(this.contents[e]==null)return this.contents[e]=t,!0;return!0}swap(t){if(!(t instanceof Zt))throw new TypeError("Invalid Fingerprint");let e=Xe(0,this.contents.length-1),n=this.contents[e];return this.contents[e]=t,n}remove(t){if(!(t instanceof Zt))throw new TypeError("Invalid Fingerprint");let e=this.contents.findIndex(n=>t.equals(n));return e>-1?(this.contents[e]=null,!0):!1}};var mp=500,An=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??_n,this.seed=t.seed??Xe(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=k(t));let e=new Zt(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=(n^e.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new je(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new je(this.bucketSize)),this.buckets[n].add(e)||this.buckets[o].add(e))return this.count++,!0;let i=[n,o],s=i[Xe(0,i.length-1)];this.buckets[s]==null&&(this.buckets[s]=new je(this.bucketSize));for(let a=0;a<mp;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 je(this.bucketSize)),this.buckets[s].add(c)))return this.count++,!0}return!1}has(t){typeof t=="string"&&(t=k(t));let e=new Zt(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=this.buckets[n]?.has(e)??!1;if(o)return o;let i=(n^e.hash())%this.filterSize;return this.buckets[i]?.has(e)??!1}remove(t){typeof t=="string"&&(t=k(t));let e=new Zt(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=this.buckets[n]?.remove(e)??!1;if(o)return this.count--,o;let i=(n^e.hash())%this.filterSize,s=this.buckets[i]?.remove(e)??!1;return s&&this.count--,s}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},yp={1:.5,2:.84,4:.95,8:.98};function gp(r=.001){return r>.002?2:r>1e-5?4:8}function yl(r,t=.001){let e=gp(t),n=yp[e],o=Math.round(r/n),i=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),pa);return{filterSize:o,bucketSize:e,fingerprintSize:i}}var Mo=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??_n,this.seed=t.seed??Xe(0,Math.pow(2,10)),this.filterSeries=[new An({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(t){if(typeof t=="string"&&(t=k(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 An({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=k(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=k(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 Lr(r,t=.001,e){return new Mo({...yl(r,t),...e??{}})}var ko=class{filter;constructor(t,e){this.filter=Lr(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 ma(r,t=.001){return new ko(r,t)}var ya=class extends Le{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 ga(r){let{name:t,metrics:e}=r,n;return e!=null?n=new ya({name:t,metrics:e}):n=new Le,n}var ba=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 gl(r,t){let e=new ba(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 Ko=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??Xu,this.applyDefaultLimit=e.applyDefaultLimit!==!1,this.reservationTtl=e.reservationTtl??ju,this.defaultDurationLimit=e.defaultDurationLimit??tl,this.defaultDataLimit=e.defaultDataLimit??el,this.reservations=ga({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:F.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:gl(this.reservationTtl)}),this.reservations.set(t,o),o.signal.addEventListener("abort",()=>{this.reservations.delete(t)}),{status:F.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 qo=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 Br.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 bl=r=>r.protoCodes().includes(wo),bp={maxOutboundStopStreams:xn},xa=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??rl,this.maxInboundHopStreams=e.maxInboundHopStreams,this.maxOutboundHopStreams=e.maxOutboundHopStreams,this.maxOutboundStopStreams=e.maxOutboundStopStreams??bp.maxOutboundStopStreams,this.reservationStore=new Ko(t,e.reservations),this.shutdownController=new AbortController,this.shutdownController.signal}[Symbol.toStringTag]="@libp2p/circuit-relay-v2-server";isStarted(){return this.started}async start(){this.started||(await this.registrar.handle(Ft,t=>{this.onHop(t).catch(e=>{this.log.error(e)})},{maxInboundStreams:this.maxInboundHopStreams,maxOutboundStreams:this.maxOutboundHopStreams,runOnLimitedConnection:!0}),this.started=!0)}async stop(){this.reservationStore.clear(),this.shutdownController.abort(),await this.registrar.unhandle(Ft),this.started=!1}async onHop({connection:t,stream:e}){this.log("received circuit v2 hop protocol stream from %p",t.remotePeer);let n={signal:AbortSignal.timeout(this.hopTimeout)},o=Be(e);try{let i=await o.pb(W).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(W).write({type:W.Type.STATUS,status:F.MALFORMED_MESSAGE},n),e.abort(i)}}async handleHopProtocol({stream:t,request:e,connection:n},o){switch(this.log("received hop message"),e.type){case W.Type.RESERVE:await this.handleReserve({stream:t,request:e,connection:n},o);break;case W.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(W).write({type:W.Type.STATUS,status:F.UNEXPECTED_MESSAGE})}}async handleReserve({stream:t,connection:e},n){let o=t.pb(W);if(this.log("hop reserve request from %p",e.remotePeer),bl(e.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",e.remotePeer),await o.write({type:W.Type.STATUS,status:F.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:W.Type.STATUS,status:F.PERMISSION_DENIED},n);return}let i=this.reservationStore.reserve(e.remotePeer,e.remoteAddr);try{if(i.status!==F.OK){await o.write({type:W.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:{[na]:{value:1,ttl:s},[oa]:{value:1,ttl:s}}})}await o.write({type:W.Type.STATUS,status:F.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:{[na]:void 0,[oa]: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 ln.seal(new qo({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(W);if(bl(n.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",n.remotePeer),await i.write({type:W.Type.STATUS,status:F.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(Et),s=Sr(Yt(e.peer.id))}catch(l){this.log.error("invalid hop connect request via peer %p %s",n.remotePeer,l),await i.write({type:W.Type.STATUS,status:F.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,F.NO_RESERVATION),await i.write({type:W.Type.STATUS,status:F.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:W.Type.STATUS,status:F.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:W.Type.STATUS,status:F.NO_RESERVATION},o);return}let u=c[0],h=await this.stopHop({connection:u,request:{type:kt.Type.CONNECT,peer:{id:n.remotePeer.toMultihash().bytes,addrs:[]},limit:a?.limit}},o);if(h==null){this.log.error("failed to open stream to destination peer %p",u?.remotePeer),await i.write({type:W.Type.STATUS,status:F.CONNECTION_FAILED},o);return}await i.write({type:W.Type.STATUS,status:F.OK,limit:a?.limit},o);let f=t.unwrap();this.log("connection from %p to %p established - merging streams",n.remotePeer,s),dl(f,h,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([We],{maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0,...n}),i=Be(o),s=i.pb(kt);await s.write(e,n);let a;try{a=await s.read(n)}catch{this.log.error("error parsing stop message response from %p",t.remotePeer)}if(a==null){this.log.error("could not read response from %p",t.remotePeer),await o.close(n);return}if(a.status===F.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 xl(r={}){return t=>new xa(t,r)}function xp(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 wl=xp;function wp(r){return r[Symbol.asyncIterator]!=null}function El(r){return r?.then!=null}function Ep(r,t){let e=0;if(wp(r))return(async function*(){for await(let c of r){let u=t(c,e++);El(u)&&await u,yield c}})();let n=wl(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 u=t(c,e++);El(u)&&await u,yield c}})();let a=t;return(function*(){yield o;for(let c of n)a(c,e++),yield c})()}var Sl=Ep;var Vo=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}},Rr=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new Vo(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 Vo(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 Ea=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function Fo(r={}){return Sp(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 Sp(r,t){t=t??{};let e=t.onEnd,n=new Rr,o,i,s,a=$t(),c=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((S,g)=>{i=_=>{i=null,n.push(_);try{S(r(n))}catch(w){g(w)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=$t()})}},u=S=>i!=null?i(S):(n.push(S),o),h=S=>(n=new Rr,i!=null?i({error:S}):(n.push({error:S}),o)),f=S=>{if(s)return o;if(t?.objectMode!==!0&&S?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:S})},l=S=>s?o:(s=!0,S!=null?h(S):u({done:!0})),d=()=>(n=new Rr,l(),{done:!0}),p=S=>(l(S),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:d,throw:p,push:f,end:l,get readableLength(){return n.size},onEmpty:async S=>{let g=S?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let _,w;g!=null&&(_=new Promise((C,R)=>{w=()=>{R(new Ea)},g.addEventListener("abort",w)}));try{await Promise.race([a.promise,_])}finally{w!=null&&g!=null&&g?.removeEventListener("abort",w)}}},e==null)return o;let x=o;return o={[Symbol.asyncIterator](){return this},next(){return x.next()},throw(S){return x.throw(S),e!=null&&(e(S),e=void 0),{done:!0}},return(){return x.return(),e!=null&&(e(),e=void 0),{done:!0}},push:f,end(S){return x.end(S),e!=null&&(e(S),e=void 0),o},get readableLength(){return x.readableLength},onEmpty:S=>x.onEmpty(S)},o}function vp(r){return r[Symbol.asyncIterator]!=null}async function _p(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*Ap(r){let t=new AbortController,e=mo();_p(r,e,t.signal).catch(()=>{});try{yield*e}finally{t.abort()}}function*Ip(r){for(let t of r)yield*t}function Tp(...r){let t=[];for(let e of r)vp(e)||t.push(e);return t.length===r.length?Ip(t):Ap(r)}var vl=Tp;function _l(r,...t){if(r==null)throw new Error("Empty pipeline");if(Sa(r)){let n=r;r=()=>n.source}else if(Il(r)||Al(r)){let n=r;r=()=>n}let e=[r,...t];if(e.length>1&&Sa(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++)Sa(e[n])&&(e[n]=Dp(e[n]));return Cp(...e)}var Cp=(...r)=>{let t;for(;r.length>0;)t=r.shift()(t);return t},Al=r=>r?.[Symbol.asyncIterator]!=null,Il=r=>r?.[Symbol.iterator]!=null,Sa=r=>r==null?!1:r.sink!=null&&r.source!=null,Dp=r=>t=>{let e=r.sink(t);if(e?.then!=null){let n=Fo({objectMode:!0});e.then(()=>{n.end()},s=>{n.end(s)});let o,i=r.source;if(Al(i))o=async function*(){yield*i,n.end()};else if(Il(i))o=function*(){yield*i,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return vl(n,o())}return r.source};function va(r){let{stream:t,remoteAddr:e,log:n,onDataRead:o,onDataWrite:i}=r,s=!1,a=!1,c=t.close.bind(t);t.close=async d=>{await c(d),l(!0)};let u=t.abort.bind(t);t.abort=d=>{u(d),l(!0)};let h=t.sink.bind(t);t.sink=async d=>{try{await h(_l(d,p=>Sl(p,x=>i?.(x))))}catch(p){f.log.error("errored - %e",p),p.type!=="aborted"&&f.log.error("%s error in sink - %e",e,p)}finally{a=!0,l()}};let f={log:n.newScope("stream-to-maconn"),sink:t.sink,source:(async function*(){try{for await(let d of t.source)o?.(d),yield d}finally{s=!0,l()}})(),remoteAddr:e,timeline:{open:Date.now(),close:void 0},close:t.close,abort:t.abort};function l(d){d===!0&&(s=!0,a=!0),s&&a&&f.timeline.close==null&&(f.timeline.close=Date.now())}return f}var Re=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var Ho=class extends Error{static name="AbortError";name="AbortError";constructor(t="The operation was aborted",...e){super(t,...e)}};async function zo(r,t,e,n){let o=new Ho(n?.errorMessage);n?.errorCode!=null&&(o.code=n.errorCode);let i=n?.errorEvent??"error";return e?.aborted===!0?Promise.reject(o):new Promise((s,a)=>{function c(){Aa(e,"abort",f),Aa(r,t,u),Aa(r,i,h)}let u=l=>{try{if(n?.filter?.(l)===!1)return}catch(d){c(),a(d);return}c(),s(l)},h=l=>{if(c(),l instanceof Error){a(l);return}a(l.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},f=()=>{c(),a(o)};_a(e,"abort",f),_a(r,t,u),_a(r,i,h)})}function _a(r,t,e){r!=null&&(Tl(r)?r.addEventListener(t,e):r.addListener(t,e))}function Aa(r,t,e){r!=null&&(Tl(r)?r.removeEventListener(t,e):r.removeListener(t,e))}function Tl(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}function Ia(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 Go=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};var $o=class{deferred;signal;constructor(t){this.signal=t,this.deferred=$t(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new te)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Pp(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Zo=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=Pp(),this.status="queued",this.fn=t,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(t){this.controller.abort(t)}onAbort(){this.recipients.reduce((e,n)=>e&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new te),this.cleanup())}async join(t={}){let e=new $o(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 Ze(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 Wo=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=Ia(this.emitEmpty.bind(this),1),this.emitIdle=Ia(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 Go;let n=new Zo(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("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(t=>{t.abort(new te)}),this.clear()}async onEmpty(t){this.size!==0&&await zo(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await zo(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await zo(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=Fo({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.error)},s=()=>{n()},a=()=>{n(new te("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",i),this.addEventListener("idle",s),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",i),this.removeEventListener("idle",s),t?.signal?.removeEventListener("abort",a),n()}}};var Or=class extends Wo{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};var Yo=class extends Kt{components;started;running;topologyId;log;discoveryController;filter;queue;constructor(t,e={}){super(),this.log=t.logger.forComponent("libp2p:circuit-relay:discover-relays"),this.components=t,this.started=!1,this.running=!1,this.filter=e.filter,this.discoveryController=new AbortController,this.discoveryController.signal,this.dialPeer=this.dialPeer.bind(this),this.onPeer=this.onPeer.bind(this)}isStarted(){return this.started}async start(){this.topologyId=await this.components.registrar.register(Ft,{filter:this.filter,onConnect:t=>{this.log.trace("discovered relay %p queue (length: %d, active %d)",t,this.queue?.size,this.queue?.running),this.safeDispatchEvent("relay:discover",{detail:t})}}),this.started=!0}stop(){this.topologyId!=null&&this.components.registrar.unregister(this.topologyId),this.running&&this.stopDiscovery(),this.started=!1}startDiscovery(){this.running||(this.log("start discovery"),this.running=!0,this.discoveryController=new AbortController,this.discoveryController.signal,this.components.events.addEventListener("peer:discovery",this.onPeer),Promise.resolve().then(async()=>{this.log("searching peer store for relays");let t=await this.components.peerStore.all({filters:[n=>n.protocols.includes(Ft)],orders:[()=>Math.random()<.5?1:-1,(n,o)=>{let i=Cl(n),s=Cl(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 Or({concurrency:5});this.log("start random walk");for await(let n of this.components.randomWalk.walk({signal:this.discoveryController.signal})){if(this.log.trace("found random peer %p",n.id),e.has(n.id)){this.log.trace("random peer %p was already in queue",n.id);continue}if(this.components.connectionManager.getConnections(n.id)?.length>0){this.log.trace("random peer %p was already connected",n.id);continue}if(!await this.components.connectionManager.isDialable(n.multiaddrs)){this.log.trace("random peer %p was not dialable",n.id,n.multiaddrs.map(o=>o.toString()));continue}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(this.dialPeer,{peerId:n.id,signal:this.discoveryController.signal}).catch(o=>{this.log.error("error opening connection to random peer %p",n.id,o)})}this.log("stop random walk"),await 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(),this.queue?.clear(),this.components.events.removeEventListener("peer:discovery",this.onPeer)}onPeer(t){this.log.trace("maybe dialing discovered peer %p - %e",t.detail.id),this.maybeDialPeer(t).catch(e=>{this.log.trace("error dialing discovered peer %p - %e",t.detail.id,e)})}async maybeDialPeer(t){if(this.queue==null)return;let e=t.detail.id,n=t.detail.multiaddrs;if(this.queue.has(e)){this.log.trace("random peer %p was already in queue",e);return}if(this.components.connectionManager.getConnections(e)?.length>0){this.log.trace("random peer %p was already connected",e);return}if(!await this.components.connectionManager.isDialable(n)){this.log.trace("random peer %p was not dialable",e);return}this.queue?.add(this.dialPeer,{peerId:t.detail.id,signal:this.discoveryController.signal}).catch(o=>{this.log.error("error opening connection to discovered peer %p",t.detail.id,o)})}async dialPeer({peerId:t,signal:e}){let n=Po([AbortSignal.timeout(5e3),e]);try{await this.components.connectionManager.openConnection(t,{signal:n})}finally{n.clear()}}};function Cl(r){let t=r.metadata.get("last-dial-success");return t==null?0:new Date(K(t)).getTime()}var Ta=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??Eo,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(No.exactMatch(t))this.log("searching for circuit relay servers"),this.reservationId=this.reservationStore.reserveRelay();else if(Oo.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 Oe(`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=>Et(e).encapsulate("/p2p-circuit")),this.listeningAddrs.forEach(e=>{this.addressManager.confirmObservedAddr(e,{type:"transport"})}),queueMicrotask(()=>{this.safeDispatchEvent("listening")})}};function Dl(r){return new Ta(r)}var Pl="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Bl=(r=21)=>{let t="",e=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)t+=Pl[e[r]&63];return t};var Bp=60*1e3*10,Lp=60*1e3*5,Rp=30*1e3,Xo=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 Le,this.pendingReservations=[],this.maxReservationQueueLength=e?.maxReservationQueueLength??Ju,this.reservationCompletionTimeout=e?.reservationCompletionTimeout??Eo,this.started=!1,this.relayFilter=Lr(100),this.reserveQueue=new Or({concurrency:e?.reservationConcurrency??Qu,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(bn)]});this.log("removing tag from %d old relays",t.length),await Promise.all(t.map(async e=>{await this.peerStore.merge(e.id,{tags:{[bn]: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=Bl();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 Oe("Cannot use self as relay");if(this.reserveQueue.size>this.maxReservationQueueLength)throw new Ro("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 Oe("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 p=this.connectionManager.getConnections(t),x=!1;if(p.length===0&&this.log("already have relay reservation with %p but we are no longer connected",t),p.map(S=>S.id).includes(i.connection)&&(this.log("already have relay reservation with %p and the original connection is still open",t),x=!0),x&&fa(i.reservation.expire)>Bp)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 Sn("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(Do.matches(a.remoteAddr))throw new Lo("not creating reservation over relayed connection");let c=await this.#t(a,{signal:s}),u=fa(c.expire);this.log("created reservation on relay peer %p, expiry date is %s",t,new Date(Date.now()+u).toString());let h=Math.min(Math.max(u-Lp,Rp),Math.pow(2,31)-1),f=setTimeout(()=>{this.log("refresh reservation to relay %p",t),this.addRelay(t,e).catch(async p=>{this.log.error("could not refresh reservation to relay %p - %e",t,p),await this.#e(t)}).catch(p=>{this.log.error("could not remove expired reservation to relay %p - %e",t,p)})},h),l;if(e==="discovered"){let p=this.pendingReservations.pop();if(p==null)throw new Sn("Made reservation on relay but did not need any more discovered relays");l={timeout:f,reservation:c,type:e,connection:a.id,id:p}}else l={timeout:f,reservation:c,type:e,connection:a.id};this.reservations.set(t,l),await this.peerStore.merge(t,{tags:{[bn]:{value:1,ttl:u}}}),this.#r();let d={relay:t,details:l};return this.safeDispatchEvent("relay:created-reservation",{detail:d}),d}catch(i){throw e==="discovered"&&i.name==="HadEnoughRelaysError"||this.log.error("could not reserve slot on %p after %dms - %e",t,Date.now()-o,i),(i.name==="DialError"||i.name==="UnsupportedProtocolError")&&this.relayFilter.add(t.toMultihash().bytes),this.#e(t).catch(s=>{this.log.error("could not remove reservation on %p after reserving slot failed - %e",t,s)}),i}},{peerId:t})}hasReservation(t){return this.reservations.has(t)}getReservation(t){return this.reservations.get(t)?.reservation}reservationCount(t){return t==null?this.reservations.size:[...this.reservations.values()].reduce((e,n)=>(n.type===t&&e++,e),0)}cancelReservations(){[...this.reservations.values()].forEach(t=>{clearTimeout(t.timeout)}),this.reservations.clear()}async#t(t,e){e.signal?.throwIfAborted(),this.log("requesting reservation from %p",t.remotePeer);let n=await t.newStream(Ft,e),i=Be(n).pb(W);this.log.trace("send RESERVE to %p",t.remotePeer),await i.write({type:W.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===F.OK&&s.reservation!=null){let c=new Set;c.add(t.remoteAddr.toString());for(let u of s.reservation.addrs){let h=Et(u);h.getPeerId()==null&&(h=h.encapsulate(`/p2p/${t.remotePeer}`)),h=Et(h.toString().replace(`/p2p/${t.remotePeer}/p2p/${t.remotePeer}`,`/p2p/${t.remotePeer}`)),c.add(h.toString())}return s.reservation.addrs=[...c].map(u=>Et(u).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:{[bn]: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=Lr(100),this.log("not discovered enough relays %d/%d",this.reservations.size,this.pendingReservations.length),this.safeDispatchEvent("relay:not-enough-relays")}};var Op=r=>{if(r.peer==null)return!1;try{r.peer.addrs.forEach(Et)}catch{return!1}return!0},Ll={maxInboundStopStreams:xn,maxOutboundStopStreams:xn,stopTimeout:3e4},jo=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??Ll.maxInboundStopStreams,this.maxOutboundStopStreams=e.maxOutboundStopStreams??Ll.maxOutboundStopStreams,this.shutdownController=new AbortController,this.discovery=new Yo(t,{filter:e.discoveryFilter??ma(nl,ol)}),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 Xo(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";[Na]=["@libp2p/transport","@libp2p/circuit-relay-v2-transport"];get[Ua](){return this.discovery!=null?["@libp2p/identify"]:[]}[Ba]=!0;isStarted(){return this.started}async start(){this.shutdownController=new AbortController,this.shutdownController.signal,await this.registrar.handle(We,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 Ra(this.discovery,this.reservationStore),this.started=!0}async stop(){this.shutdownController.abort(),await Oa(this.discovery,this.reservationStore),await this.registrar.unhandle(We),this.started=!1}async dial(t,e){if(t.protoCodes().filter(d=>d===wo).length!==1){let d="Invalid circuit relay address";throw this.log.error(d,t),new Nr(d)}let n=t.toString().split("/p2p-circuit"),o=Et(n[0]),i=Et(n[n.length-1]),s=o.getPeerId(),a=i.getPeerId();if(s==null||a==null){let d=`ircuit relay dial to ${t.toString()} failed as address did not have both relay and destination PeerIDs`;throw this.log.error(`c${d}`),new Nr(`C${d}`)}let c=Us(s),u=Us(a),f=this.connectionManager.getConnections(c)[0];f==null?(await this.peerStore.merge(c,{multiaddrs:[o]}),e.onProgress?.(new Re("circuit-relay:open-connection")),f=await this.connectionManager.openConnection(c,e)):e.onProgress?.(new Re("circuit-relay:reuse-connection"));let l;try{e.onProgress?.(new Re("circuit-relay:open-hop-stream")),l=await f.newStream(Ft,e);let d=Be(l),p=d.pb(W);e.onProgress?.(new Re("circuit-relay:write-connect-message")),await p.write({type:W.Type.CONNECT,peer:{id:u.toMultihash().bytes,addrs:[Et(i).bytes]}},e),e.onProgress?.(new Re("circuit-relay:read-connect-response"));let x=await p.read(e);if(x.status!==F.OK)throw new Dn(`failed to connect via relay with status ${x?.status?.toString()??"undefined"}`);let S=new vn(x.limit),g=va({stream:d.unwrap(),remoteAddr:t,localAddr:o.encapsulate(`/p2p-circuit/p2p/${this.peerId.toString()}`),log:this.log,onDataRead:S.onData,onDataWrite:S.onData}),_=await this.upgrader.upgradeOutbound(g,{...e,limits:S.getLimits()});return _.log("outbound relayed connection established to %p with limits %o, over connection %s",_.remotePeer,x.limit??"none",f.id),_}catch(d){throw this.log.error("circuit relay dial to destination %p via relay %p failed",u,c,d),l?.abort(d),d}}createListener(t){return Dl({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=>Oo.exactMatch(e)||No.exactMatch(e))}dialFilter(t){return t=Array.isArray(t)?t:[t],t.filter(e=>Do.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=Be(e).pb(kt),i=await o.read({signal:n});if(this.log("new circuit relay v2 stop stream from %p with type %s",t.remotePeer,i.type),i?.type===void 0){this.log.error("type was missing from circuit v2 stop protocol request from %s",t.remotePeer),await o.write({type:kt.Type.STATUS,status:F.MALFORMED_MESSAGE},{signal:n}),await e.close();return}if(i.type!==kt.Type.CONNECT){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await o.write({type:kt.Type.STATUS,status:F.UNEXPECTED_MESSAGE},{signal:n}),await e.close();return}if(!Op(i)){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await o.write({type:kt.Type.STATUS,status:F.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}let s=Sr(Yt(i.peer.id));if(await this.connectionGater.denyInboundRelayedConnection?.(t.remotePeer,s)===!0){this.log.error("connection gater denied inbound relayed connection from %p",t.remotePeer),await o.write({type:kt.Type.STATUS,status:F.PERMISSION_DENIED},{signal:n}),await e.close({signal:n});return}this.log.trace("sending success response to %p",t.remotePeer),await o.write({type:kt.Type.STATUS,status:F.OK},{signal:n});let a=new vn(i.limit),c=t.remoteAddr.encapsulate(`/p2p-circuit/p2p/${s.toString()}`),u=this.addressManager.getAddresses()[0],h=va({stream:o.unwrap().unwrap(),remoteAddr:c,localAddr:u,log:this.log,onDataRead:a.onData,onDataWrite:a.onData});await this.upgrader.upgradeInbound(h,{limits:a.getLimits(),signal:n}),h.log("inbound relayed connection established to %p with limits %o, over connection %s",s,i.limit??"none",t.id)}};function Rl(r={}){return t=>new jo(t,r)}return kl(Np);})();
3
3
  /*! Bundled license information:
4
4
 
5
5
  @noble/hashes/esm/utils.js: