@libp2p/circuit-relay-v2 3.2.23 → 3.2.24-0f07e3df5
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 +1 -1
- package/dist/index.min.js.map +4 -4
- package/dist/src/constants.d.ts +0 -4
- package/dist/src/constants.d.ts.map +1 -1
- package/dist/src/constants.js +0 -4
- package/dist/src/constants.js.map +1 -1
- package/dist/src/index.d.ts +170 -7
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/index.js +12 -2
- package/dist/src/index.js.map +1 -1
- package/dist/src/server/index.d.ts +41 -45
- package/dist/src/server/index.d.ts.map +1 -1
- package/dist/src/server/index.js +30 -47
- package/dist/src/server/index.js.map +1 -1
- package/dist/src/server/reservation-store.d.ts +2 -36
- package/dist/src/server/reservation-store.d.ts.map +1 -1
- package/dist/src/server/reservation-store.js.map +1 -1
- package/dist/src/transport/discovery.d.ts +2 -17
- package/dist/src/transport/discovery.d.ts.map +1 -1
- package/dist/src/transport/discovery.js +2 -2
- package/dist/src/transport/discovery.js.map +1 -1
- package/dist/src/transport/index.d.ts +34 -42
- package/dist/src/transport/index.d.ts.map +1 -1
- package/dist/src/transport/index.js +291 -5
- package/dist/src/transport/index.js.map +1 -1
- package/dist/src/transport/reservation-store.d.ts +3 -37
- package/dist/src/transport/reservation-store.d.ts.map +1 -1
- package/dist/src/transport/reservation-store.js +4 -6
- package/dist/src/transport/reservation-store.js.map +1 -1
- package/dist/src/transport/stream-to-conn.d.ts +19 -0
- package/dist/src/transport/stream-to-conn.d.ts.map +1 -0
- package/dist/src/transport/stream-to-conn.js +60 -0
- package/dist/src/transport/stream-to-conn.js.map +1 -0
- package/dist/src/utils.d.ts.map +1 -1
- package/dist/src/utils.js +36 -59
- package/dist/src/utils.js.map +1 -1
- package/package.json +19 -24
- package/src/constants.ts +0 -5
- package/src/index.ts +207 -8
- package/src/server/index.ts +35 -100
- package/src/server/reservation-store.ts +2 -42
- package/src/transport/discovery.ts +4 -22
- package/src/transport/index.ts +338 -46
- package/src/transport/reservation-store.ts +8 -46
- package/src/transport/stream-to-conn.ts +91 -0
- package/src/utils.ts +37 -66
- package/dist/src/transport/transport.d.ts +0 -54
- package/dist/src/transport/transport.d.ts.map +0 -1
- package/dist/src/transport/transport.js +0 -314
- package/dist/src/transport/transport.js.map +0 -1
- package/dist/typedoc-urls.json +0 -23
- package/src/transport/transport.ts +0 -378
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 zo=Object.defineProperty;var al=Object.getOwnPropertyDescriptor;var cl=Object.getOwnPropertyNames;var ul=Object.prototype.hasOwnProperty;var St=(r,t)=>{for(var e in t)zo(r,e,{get:t[e],enumerable:!0})},ll=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of cl(t))!ul.call(r,o)&&o!==e&&zo(r,o,{get:()=>t[o],enumerable:!(n=al(t,o))||n.enumerable});return r};var fl=r=>ll(zo({},"__esModule",{value:!0}),r);var rp={};St(rp,{RELAY_V2_HOP_CODEC:()=>Nt,RELAY_V2_STOP_CODEC:()=>Ue,circuitRelayServer:()=>$u,circuitRelayTransport:()=>sl});var Bt=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 Ho=Symbol.for("@libp2p/peer-id");var Fo="keep-alive";var ia=Symbol.for("@libp2p/transport");var oa;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(oa||(oa={}));var jt=class extends Error{static name="AbortError";constructor(t="The operation was aborted"){super(t),this.name="AbortError"}};var st=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},He=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}};var mn=class extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}},yn=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}};var gn=class extends Error{static name="InvalidMessageError";constructor(t="Invalid message"){super(t),this.name="InvalidMessageError"}};var _r=class extends Error{static name="DialError";constructor(t="Dial error"){super(t),this.name="DialError"}},Ee=class extends Error{static name="ListenError";constructor(t="Listen error"){super(t),this.name="ListenError"}};var Fe=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};function sa(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function aa(...r){let t=[];for(let e of r)sa(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 ca(...r){let t=[];for(let e of r)sa(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 ua=Symbol.for("@libp2p/service-capabilities"),la=Symbol.for("@libp2p/service-dependencies");var Zo={};St(Zo,{base58btc:()=>Y,base58flickr:()=>bl});var Rp=new Uint8Array(0);function fa(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 Xt(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 ha(r){return new TextEncoder().encode(r)}function da(r){return new TextDecoder().decode(r)}function hl(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var o=0;o<r.length;o++){var i=r.charAt(o),s=i.charCodeAt(0);if(e[s]!==255)throw new TypeError(i+" is ambiguous");e[s]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function f(b){if(b instanceof Uint8Array||(ArrayBuffer.isView(b)?b=new Uint8Array(b.buffer,b.byteOffset,b.byteLength):Array.isArray(b)&&(b=Uint8Array.from(b))),!(b instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(b.length===0)return"";for(var x=0,h=0,S=0,C=b.length;S!==C&&b[S]===0;)S++,x++;for(var _=(C-S)*u+1>>>0,B=new Uint8Array(_);S!==C;){for(var g=b[S],R=0,P=_-1;(g!==0||R<h)&&P!==-1;P--,R++)g+=256*B[P]>>>0,B[P]=g%a>>>0,g=g/a>>>0;if(g!==0)throw new Error("Non-zero carry");h=R,S++}for(var I=_-h;I!==_&&B[I]===0;)I++;for(var d=c.repeat(x);I<_;++I)d+=r.charAt(B[I]);return d}function m(b){if(typeof b!="string")throw new TypeError("Expected String");if(b.length===0)return new Uint8Array;var x=0;if(b[x]!==" "){for(var h=0,S=0;b[x]===c;)h++,x++;for(var C=(b.length-x)*l+1>>>0,_=new Uint8Array(C);b[x];){var B=e[b.charCodeAt(x)];if(B===255)return;for(var g=0,R=C-1;(B!==0||g<S)&&R!==-1;R--,g++)B+=a*_[R]>>>0,_[R]=B%256>>>0,B=B/256>>>0;if(B!==0)throw new Error("Non-zero carry");S=g,x++}if(b[x]!==" "){for(var P=C-S;P!==C&&_[P]===0;)P++;for(var I=new Uint8Array(h+(C-P)),d=h;P!==C;)I[d++]=_[P++];return I}}}function p(b){var x=m(b);if(x)return x;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:m,decode:p}}var dl=hl,pl=dl,ma=pl;var Vo=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")}},Go=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 ya(this,t)}},Wo=class{decoders;constructor(t){this.decoders=t}or(t){return ya(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 ya(r,t){return new Wo({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var $o=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 Vo(t,e,n),this.decoder=new Go(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Ve({name:r,prefix:t,encode:e,decode:n}){return new $o(r,t,e,n)}function ce({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=ma(e,r);return Ve({prefix:t,name:r,encode:n,decode:i=>Xt(o(i))})}function ml(r,t,e,n){let o=r.length;for(;r[o-1]==="=";)--o;let i=new Uint8Array(o*e/8|0),s=0,a=0,c=0;for(let l=0;l<o;++l){let u=t[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<e|u,s+=e,s>=8&&(s-=8,i[c++]=255&a>>s)}if(s>=e||(255&a<<8-s)!==0)throw new SyntaxError("Unexpected end of data");return i}function yl(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 gl(r){let t={};for(let e=0;e<r.length;++e)t[r[e]]=e;return t}function tt({name:r,prefix:t,bitsPerChar:e,alphabet:n}){let o=gl(n);return Ve({prefix:t,name:r,encode(i){return yl(i,n,e)},decode(i){return ml(i,o,e,r)}})}var Y=ce({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),bl=ce({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Yo={};St(Yo,{base32:()=>ue,base32hex:()=>Sl,base32hexpad:()=>_l,base32hexpadupper:()=>Al,base32hexupper:()=>vl,base32pad:()=>wl,base32padupper:()=>El,base32upper:()=>xl,base32z:()=>Il});var ue=tt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),xl=tt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),wl=tt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),El=tt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Sl=tt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),vl=tt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),_l=tt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Al=tt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Il=tt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var jo={};St(jo,{base36:()=>Ar,base36upper:()=>Tl});var Ar=ce({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Tl=ce({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Cl=xa,ga=128,Dl=127,Pl=~Dl,Rl=Math.pow(2,31);function xa(r,t,e){t=t||[],e=e||0;for(var n=e;r>=Rl;)t[e++]=r&255|ga,r/=128;for(;r&Pl;)t[e++]=r&255|ga,r>>>=7;return t[e]=r|0,xa.bytes=e-n+1,t}var Ll=Xo,Bl=128,ba=127;function Xo(r,n){var e=0,n=n||0,o=0,i=n,s,a=r.length;do{if(i>=a)throw Xo.bytes=0,new RangeError("Could not decode varint");s=r[i++],e+=o<28?(s&ba)<<o:(s&ba)*Math.pow(2,o),o+=7}while(s>=Bl);return Xo.bytes=i-n,e}var Ol=Math.pow(2,7),Nl=Math.pow(2,14),Ul=Math.pow(2,21),kl=Math.pow(2,28),Ml=Math.pow(2,35),Kl=Math.pow(2,42),ql=Math.pow(2,49),zl=Math.pow(2,56),Hl=Math.pow(2,63),Fl=function(r){return r<Ol?1:r<Nl?2:r<Ul?3:r<kl?4:r<Ml?5:r<Kl?6:r<ql?7:r<zl?8:r<Hl?9:10},Vl={encode:Cl,decode:Ll,encodingLength:Fl},Gl=Vl,Ir=Gl;function Tr(r,t=0){return[Ir.decode(r,t),Ir.decode.bytes]}function Ge(r,t,e=0){return Ir.encode(r,t,e),t}function We(r){return Ir.encodingLength(r)}function Ut(r,t){let e=t.byteLength,n=We(r),o=n+We(e),i=new Uint8Array(o+e);return Ge(r,i,0),Ge(e,i,n),i.set(t,o),new $e(r,e,t,i)}function Ft(r){let t=Xt(r),[e,n]=Tr(t),[o,i]=Tr(t.subarray(n)),s=t.subarray(n+i);if(s.byteLength!==o)throw new Error("Incorrect length");return new $e(e,o,s,t)}function wa(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&fa(r.bytes,e.bytes)}}var $e=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};function Ea(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return $l(e,Qo(r),t??Y.encoder);default:return Zl(e,Qo(r),t??ue.encoder)}}var Sa=new WeakMap;function Qo(r){let t=Sa.get(r);if(t==null){let e=new Map;return Sa.set(r,e),e}return t}var et=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!==Cr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==Yl)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=Ut(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&&wa(t.multihash,n.multihash)}toString(t){return Ea(this,t)}toJSON(){return{"/":Ea(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??va(n,o,i.bytes))}else if(e[jl]===!0){let{version:n,multihash:o,code:i}=e,s=Ft(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!==Cr)throw new Error(`Version 0 CID must use dag-pb (code: ${Cr}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=va(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,Cr,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=Xt(t.subarray(n,n+e.multihashSize));if(o.byteLength!==e.multihashSize)throw new Error("Incorrect length");let i=o.subarray(e.multihashSize-e.digestSize),s=new $e(e.multihashCode,e.digestSize,i,o);return[e.version===0?r.createV0(s):r.createV1(e.codec,s),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[f,m]=Tr(t.subarray(e));return e+=m,f},o=n(),i=Cr;if(o===18?(o=0,e=0):i=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let s=e,a=n(),c=n(),l=e+c,u=l-s;return{version:o,codec:i,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(t,e){let[n,o]=Wl(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 Qo(i).set(n,t),i}};function Wl(r,t){switch(r[0]){case"Q":{let e=t??Y;return[Y.prefix,e.decode(`${Y.prefix}${r}`)]}case Y.prefix:{let e=t??Y;return[Y.prefix,e.decode(r)]}case ue.prefix:{let e=t??ue;return[ue.prefix,e.decode(r)]}case Ar.prefix:{let e=t??Ar;return[Ar.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 $l(r,t,e){let{prefix:n}=e;if(n!==Y.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let o=t.get(n);if(o==null){let i=e.encode(r).slice(1);return t.set(n,i),i}else return o}function Zl(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 Cr=112,Yl=18;function va(r,t,e){let n=We(r),o=n+We(t),i=new Uint8Array(o+e.byteLength);return Ge(r,i,0),Ge(t,i,n),i.set(e,o),i}var jl=Symbol.for("@ipld/js-cid/CID");var Jo={};St(Jo,{identity:()=>kt});var _a=0,Xl="identity",Aa=Xt;function Ql(r){return Ut(_a,Aa(r))}var kt={code:_a,name:Xl,encode:Aa,digest:Ql};function at(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 Q(r=0){return new Uint8Array(r)}function vt(r=0){return new Uint8Array(r)}function Jt(r,t){t==null&&(t=r.reduce((o,i)=>o+i.length,0));let e=vt(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}var Ta=Symbol.for("@achingbrain/uint8arraylist");function Ia(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 xn(r){return!!r?.[Ta]}var nt=class r{bufs;length;[Ta]=!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(xn(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(xn(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=Ia(this.bufs,t);return e.buf[e.index]}set(t,e){let n=Ia(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(xn(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 Jt(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:Jt(n,o)}sublist(t,e){let{bufs:n,length:o}=this._subList(t,e),i=new r;return i.length=o,i.bufs=[...n],i}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let i=0;i<this.bufs.length;i++){let s=this.bufs[i],a=o,c=a+s.byteLength;if(o=c,t>=c)continue;let l=t>=a&&t<c,u=e>a&&e<=c;if(l&&u){if(t===a&&e===c){n.push(s);break}let f=t-a;n.push(s.subarray(f,f+(e-t)));break}if(l){if(t===0){n.push(s);continue}n.push(s.subarray(t-a));continue}if(u){if(e===c){n.push(s);break}n.push(s.subarray(0,e-a));break}n.push(s)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!xn(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let i=256,s=new Int32Array(i);for(let f=0;f<i;f++)s[f]=-1;for(let f=0;f<o;f++)s[n[f]]=f;let a=s,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let f=e;f<=c;f+=u){u=0;for(let m=l;m>=0;m--){let p=this.get(f+m);if(n[m]!==p){u=Math.max(1,m-a[p]);break}}if(u===0)return f}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=vt(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=Q(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=Q(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=Q(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=vt(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=Q(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=Q(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=Q(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=Q(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=Q(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(!at(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 ti={};St(ti,{base10:()=>Jl});var Jl=ce({prefix:"9",name:"base10",alphabet:"0123456789"});var ei={};St(ei,{base16:()=>tf,base16upper:()=>ef});var tf=tt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),ef=tt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var ri={};St(ri,{base2:()=>rf});var rf=tt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var ni={};St(ni,{base256emoji:()=>cf});var Ca=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}"),nf=Ca.reduce((r,t,e)=>(r[e]=t,r),[]),of=Ca.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function sf(r){return r.reduce((t,e)=>(t+=nf[e],t),"")}function af(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=of[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var cf=Ve({prefix:"\u{1F680}",name:"base256emoji",encode:sf,decode:af});var ii={};St(ii,{base64:()=>uf,base64pad:()=>lf,base64url:()=>oi,base64urlpad:()=>ff});var uf=tt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),lf=tt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),oi=tt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ff=tt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var si={};St(si,{base8:()=>hf});var hf=tt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var ai={};St(ai,{identity:()=>df});var df=Ve({prefix:"\0",name:"identity",encode:r=>da(r),decode:r=>ha(r)});var pm=new TextEncoder,mm=new TextDecoder;var li={};St(li,{sha256:()=>Ze,sha512:()=>yf});function ui({name:r,code:t,encode:e}){return new ci(r,t,e)}var ci=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?Ut(this.code,e):e.then(n=>Ut(this.code,n))}else throw Error("Unknown type, must be binary type")}};function Pa(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var Ze=ui({name:"sha2-256",code:18,encode:Pa("SHA-256")}),yf=ui({name:"sha2-512",code:19,encode:Pa("SHA-512")});var Dr={...ai,...ri,...si,...ti,...ei,...Yo,...jo,...Zo,...ii,...ni},Tm={...li,...Jo};function La(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var Ra=La("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),fi=La("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=vt(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),gf={utf8:Ra,"utf-8":Ra,hex:Dr.base16,latin1:fi,ascii:fi,binary:fi,...Dr},wn=gf;function k(r,t="utf8"){let e=wn[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function M(r,t="utf8"){let e=wn[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var bf=parseInt("11111",2),hi=parseInt("10000000",2),xf=parseInt("01111111",2),Ba={0:Pr,1:Pr,2:wf,3:vf,4:_f,5:Sf,6:Ef,16:Pr,22:Pr,48:Pr};function te(r,t={offset:0}){let e=r[t.offset]&bf;if(t.offset++,Ba[e]!=null)return Ba[e](r,t);throw new Error("No decoder for tag "+e)}function Rr(r,t){let e=0;if((r[t.offset]&hi)===hi){let n=r[t.offset]&xf,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 Pr(r,t){Rr(r,t);let e=[];for(;!(t.offset>=r.byteLength);){let n=te(r,t);if(n===null)break;e.push(n)}return e}function wf(r,t){let e=Rr(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 Ef(r,t){let e=Rr(r,t),n=t.offset+e,o=r[t.offset];t.offset++;let i=0,s=0;o<40?(i=0,s=o):o<80?(i=1,s=o-40):(i=2,s=o-80);let a=`${i}.${s}`,c=[];for(;t.offset<n;){let l=r[t.offset];if(t.offset++,c.push(l&127),l<128){c.reverse();let u=0;for(let f=0;f<c.length;f++)u+=c[f]<<f*7;a+=`.${u}`,c=[]}}return a}function Sf(r,t){return t.offset++,null}function vf(r,t){let e=Rr(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 _f(r,t){let e=Rr(r,t),n=r.subarray(t.offset,t.offset+e);return t.offset+=e,n}function Af(r){let t=r.toString(16);t.length%2===1&&(t="0"+t);let e=new nt;for(let n=0;n<t.length;n+=2)e.append(Uint8Array.from([parseInt(`${t[n]}${t[n+1]}`,16)]));return e}function di(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let t=Af(r.byteLength);return new nt(Uint8Array.from([t.byteLength|hi]),t)}function _t(r){let t=new nt,e=128;return(r.subarray()[0]&e)===e&&t.append(Uint8Array.from([0])),t.append(r),new nt(Uint8Array.from([2]),di(t),t)}function En(r){let t=Uint8Array.from([0]),e=new nt(t,r);return new nt(Uint8Array.from([3]),di(e),e)}function le(r,t=48){let e=new nt;for(let n of r)e.append(n);return new nt(Uint8Array.from([t]),di(e),e)}async function Oa(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 If=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Tf=Uint8Array.from([6,5,43,129,4,0,34]),Cf=Uint8Array.from([6,5,43,129,4,0,35]),Df={ext:!0,kty:"EC",crv:"P-256"},Pf={ext:!0,kty:"EC",crv:"P-384"},Rf={ext:!0,kty:"EC",crv:"P-521"},pi=32,mi=48,yi=66;function gi(r){let t=te(r);return Na(t)}function Na(r){let t=r[1][1][0],e=1,n,o;if(t.byteLength===pi*2+1)return n=M(t.subarray(e,e+pi),"base64url"),o=M(t.subarray(e+pi),"base64url"),new Ye({...Df,key_ops:["verify"],x:n,y:o});if(t.byteLength===mi*2+1)return n=M(t.subarray(e,e+mi),"base64url"),o=M(t.subarray(e+mi),"base64url"),new Ye({...Pf,key_ops:["verify"],x:n,y:o});if(t.byteLength===yi*2+1)return n=M(t.subarray(e,e+yi),"base64url"),o=M(t.subarray(e+yi),"base64url"),new Ye({...Rf,key_ops:["verify"],x:n,y:o});throw new st(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function Ua(r){return le([_t(Uint8Array.from([1])),le([Lf(r.crv)],160),le([En(new nt(Uint8Array.from([4]),k(r.x??"","base64url"),k(r.y??"","base64url")))],161)]).subarray()}function Lf(r){if(r==="P-256")return If;if(r==="P-384")return Tf;if(r==="P-521")return Cf;throw new st(`Invalid curve ${r}`)}var Ye=class{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=Ua(this.jwk)),this._raw}toMultihash(){return kt.digest(Vt(this))}toCID(){return et.createV1(114,this.toMultihash())}toString(){return Y.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:at(this.raw,t.raw)}async verify(t,e,n){return Oa(this.jwk,e,t,n)}};var Se=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Xe(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Lr(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function pt(r,...t){if(!Xe(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 Ma(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Lr(r.outputLen),Lr(r.blockLen)}function Qe(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 Ka(r,t){pt(r);let e=t.outputLen;if(r.length<e)throw new Error("digestInto() expects output buffer of length at least "+e)}function re(...r){for(let t=0;t<r.length;t++)r[t].fill(0)}function Sn(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Mt(r,t){return r<<32-t|r>>>t}var qa=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Bf=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function Gt(r){if(pt(r),qa)return r.toHex();let t="";for(let e=0;e<r.length;e++)t+=Bf[r[e]];return t}var ee={_0:48,_9:57,A:65,F:70,a:97,f:102};function ka(r){if(r>=ee._0&&r<=ee._9)return r-ee._0;if(r>=ee.A&&r<=ee.F)return r-(ee.A-10);if(r>=ee.a&&r<=ee.f)return r-(ee.a-10)}function Je(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(qa)return Uint8Array.fromHex(r);let t=r.length,e=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(e);for(let o=0,i=0;o<e;o++,i+=2){let s=ka(r.charCodeAt(i)),a=ka(r.charCodeAt(i+1));if(s===void 0||a===void 0){let c=r[i]+r[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}n[o]=s*16+a}return n}function za(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function Br(r){return typeof r=="string"&&(r=za(r)),pt(r),r}function Dt(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];pt(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let i=r[n];e.set(i,o),o+=i.length}return e}var je=class{};function bi(r){let t=n=>r().update(Br(n)).digest(),e=r();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>r(),t}function Or(r=32){if(Se&&typeof Se.getRandomValues=="function")return Se.getRandomValues(new Uint8Array(r));if(Se&&typeof Se.randomBytes=="function")return Uint8Array.from(Se.randomBytes(r));throw new Error("crypto.getRandomValues must be defined")}function Of(r,t,e,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(t,e,n);let o=BigInt(32),i=BigInt(4294967295),s=Number(e>>o&i),a=Number(e&i),c=n?4:0,l=n?0:4;r.setUint32(t+c,s,n),r.setUint32(t+l,a,n)}function Ha(r,t,e){return r&t^~r&e}function Fa(r,t,e){return r&t^r&e^t&e}var Nr=class extends je{constructor(t,e,n,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(t),this.view=Sn(this.buffer)}update(t){Qe(this),t=Br(t),pt(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=Sn(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){Qe(this),Ka(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:o,isLE:i}=this,{pos:s}=this;e[s++]=128,re(this.buffer.subarray(s)),this.padOffset>o-s&&(this.process(n,0),s=0);for(let f=s;f<o;f++)e[f]=0;Of(n,o-8,BigInt(this.length*8),i),this.process(n,0);let a=Sn(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<l;f++)a.setUint32(4*f,u[f],i)}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:e,buffer:n,length:o,finished:i,destroyed:s,pos:a}=this;return t.destroyed=s,t.finished=i,t.length=o,t.pos=a,o%e&&t.buffer.set(n),t}clone(){return this._cloneInto()}},ne=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var ft=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var vn=BigInt(4294967295),Va=BigInt(32);function Nf(r,t=!1){return t?{h:Number(r&vn),l:Number(r>>Va&vn)}:{h:Number(r>>Va&vn)|0,l:Number(r&vn)|0}}function Ga(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}=Nf(r[i],t);[n[i],o[i]]=[s,a]}return[n,o]}var xi=(r,t,e)=>r>>>e,wi=(r,t,e)=>r<<32-e|t>>>e,ve=(r,t,e)=>r>>>e|t<<32-e,_e=(r,t,e)=>r<<32-e|t>>>e,Ur=(r,t,e)=>r<<64-e|t>>>e-32,kr=(r,t,e)=>r>>>e-32|t<<64-e;function Wt(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var Wa=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),$a=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,Za=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),Ya=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,ja=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),Xa=(r,t,e,n,o,i)=>t+e+n+o+i+(r/2**32|0)|0;var kf=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]),fe=new Uint32Array(64),_n=class extends Nr{constructor(t=32){super(64,t,8,!1),this.A=ne[0]|0,this.B=ne[1]|0,this.C=ne[2]|0,this.D=ne[3]|0,this.E=ne[4]|0,this.F=ne[5]|0,this.G=ne[6]|0,this.H=ne[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)fe[f]=t.getUint32(e,!1);for(let f=16;f<64;f++){let m=fe[f-15],p=fe[f-2],b=Mt(m,7)^Mt(m,18)^m>>>3,x=Mt(p,17)^Mt(p,19)^p>>>10;fe[f]=x+fe[f-7]+b+fe[f-16]|0}let{A:n,B:o,C:i,D:s,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){let m=Mt(a,6)^Mt(a,11)^Mt(a,25),p=u+m+Ha(a,c,l)+kf[f]+fe[f]|0,x=(Mt(n,2)^Mt(n,13)^Mt(n,22))+Fa(n,o,i)|0;u=l,l=c,c=a,a=s+p|0,s=i,i=o,o=n,n=p+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,l=l+this.G|0,u=u+this.H|0,this.set(n,o,i,s,a,c,l,u)}roundClean(){re(fe)}destroy(){this.set(0,0,0,0,0,0,0,0),re(this.buffer)}};var Qa=Ga(["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))),Mf=Qa[0],Kf=Qa[1],he=new Uint32Array(80),de=new Uint32Array(80),Ei=class extends Nr{constructor(t=64){super(128,t,16,!1),this.Ah=ft[0]|0,this.Al=ft[1]|0,this.Bh=ft[2]|0,this.Bl=ft[3]|0,this.Ch=ft[4]|0,this.Cl=ft[5]|0,this.Dh=ft[6]|0,this.Dl=ft[7]|0,this.Eh=ft[8]|0,this.El=ft[9]|0,this.Fh=ft[10]|0,this.Fl=ft[11]|0,this.Gh=ft[12]|0,this.Gl=ft[13]|0,this.Hh=ft[14]|0,this.Hl=ft[15]|0}get(){let{Ah:t,Al:e,Bh:n,Bl:o,Ch:i,Cl:s,Dh:a,Dl:c,Eh:l,El:u,Fh:f,Fl:m,Gh:p,Gl:b,Hh:x,Hl:h}=this;return[t,e,n,o,i,s,a,c,l,u,f,m,p,b,x,h]}set(t,e,n,o,i,s,a,c,l,u,f,m,p,b,x,h){this.Ah=t|0,this.Al=e|0,this.Bh=n|0,this.Bl=o|0,this.Ch=i|0,this.Cl=s|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=f|0,this.Fl=m|0,this.Gh=p|0,this.Gl=b|0,this.Hh=x|0,this.Hl=h|0}process(t,e){for(let _=0;_<16;_++,e+=4)he[_]=t.getUint32(e),de[_]=t.getUint32(e+=4);for(let _=16;_<80;_++){let B=he[_-15]|0,g=de[_-15]|0,R=ve(B,g,1)^ve(B,g,8)^xi(B,g,7),P=_e(B,g,1)^_e(B,g,8)^wi(B,g,7),I=he[_-2]|0,d=de[_-2]|0,E=ve(I,d,19)^Ur(I,d,61)^xi(I,d,6),y=_e(I,d,19)^kr(I,d,61)^wi(I,d,6),w=Za(P,y,de[_-7],de[_-16]),v=Ya(w,R,E,he[_-7],he[_-16]);he[_]=v|0,de[_]=w|0}let{Ah:n,Al:o,Bh:i,Bl:s,Ch:a,Cl:c,Dh:l,Dl:u,Eh:f,El:m,Fh:p,Fl:b,Gh:x,Gl:h,Hh:S,Hl:C}=this;for(let _=0;_<80;_++){let B=ve(f,m,14)^ve(f,m,18)^Ur(f,m,41),g=_e(f,m,14)^_e(f,m,18)^kr(f,m,41),R=f&p^~f&x,P=m&b^~m&h,I=ja(C,g,P,Kf[_],de[_]),d=Xa(I,S,B,R,Mf[_],he[_]),E=I|0,y=ve(n,o,28)^Ur(n,o,34)^Ur(n,o,39),w=_e(n,o,28)^kr(n,o,34)^kr(n,o,39),v=n&i^n&a^i&a,T=o&s^o&c^s&c;S=x|0,C=h|0,x=p|0,h=b|0,p=f|0,b=m|0,{h:f,l:m}=Wt(l|0,u|0,d|0,E|0),l=a|0,u=c|0,a=i|0,c=s|0,i=n|0,s=o|0;let A=Wa(E,w,T);n=$a(A,d,y,v),o=A|0}({h:n,l:o}=Wt(this.Ah|0,this.Al|0,n|0,o|0)),{h:i,l:s}=Wt(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=Wt(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=Wt(this.Dh|0,this.Dl|0,l|0,u|0),{h:f,l:m}=Wt(this.Eh|0,this.El|0,f|0,m|0),{h:p,l:b}=Wt(this.Fh|0,this.Fl|0,p|0,b|0),{h:x,l:h}=Wt(this.Gh|0,this.Gl|0,x|0,h|0),{h:S,l:C}=Wt(this.Hh|0,this.Hl|0,S|0,C|0),this.set(n,o,i,s,a,c,l,u,f,m,p,b,x,h,S,C)}roundClean(){re(he,de)}destroy(){re(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var An=bi(()=>new _n);var Ja=bi(()=>new Ei);var _i=BigInt(0),vi=BigInt(1);function oe(r,t){if(typeof t!="boolean")throw new Error(r+" boolean expected, got "+t)}function Mr(r){let t=r.toString(16);return t.length&1?"0"+t:t}function tc(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?_i:BigInt("0x"+r)}function tr(r){return tc(Gt(r))}function Ae(r){return pt(r),tc(Gt(Uint8Array.from(r).reverse()))}function In(r,t){return Je(r.toString(16).padStart(t*2,"0"))}function er(r,t){return In(r,t).reverse()}function j(r,t,e){let n;if(typeof t=="string")try{n=Je(t)}catch(i){throw new Error(r+" must be hex string or Uint8Array, cause: "+i)}else if(Xe(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}var Si=r=>typeof r=="bigint"&&_i<=r;function ec(r,t,e){return Si(r)&&Si(t)&&Si(e)&&t<=r&&r<e}function pe(r,t,e,n){if(!ec(t,e,n))throw new Error("expected valid "+r+": "+e+" <= n < "+n+", got "+t)}function rc(r){let t;for(t=0;r>_i;r>>=vi,t+=1);return t}var Ie=r=>(vi<<BigInt(r))-vi;function nc(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=p=>new Uint8Array(p),o=p=>Uint8Array.of(p),i=n(r),s=n(r),a=0,c=()=>{i.fill(1),s.fill(0),a=0},l=(...p)=>e(s,i,...p),u=(p=n(0))=>{s=l(o(0),p),i=l(),p.length!==0&&(s=l(o(1),p),i=l())},f=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let p=0,b=[];for(;p<t;){i=l();let x=i.slice();b.push(x),p+=i.length}return Dt(...b)};return(p,b)=>{c(),u(p);let x;for(;!(x=b(f()));)u();return c(),x}}function me(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))}function rr(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 wt=BigInt(0),ut=BigInt(1),Te=BigInt(2),qf=BigInt(3),sc=BigInt(4),ac=BigInt(5),cc=BigInt(8);function J(r,t){let e=r%t;return e>=wt?e:t+e}function X(r,t,e){let n=r;for(;t-- >wt;)n*=n,n%=e;return n}function oc(r,t){if(r===wt)throw new Error("invert: expected non-zero number");if(t<=wt)throw new Error("invert: expected positive modulus, got "+t);let e=J(r,t),n=t,o=wt,i=ut,s=ut,a=wt;for(;e!==wt;){let l=n/e,u=n%e,f=o-s*l,m=i-a*l;n=e,e=u,o=s,i=a,s=f,a=m}if(n!==ut)throw new Error("invert: does not exist");return J(o,t)}function uc(r,t){let e=(r.ORDER+ut)/sc,n=r.pow(t,e);if(!r.eql(r.sqr(n),t))throw new Error("Cannot find square root");return n}function zf(r,t){let e=(r.ORDER-ac)/cc,n=r.mul(t,Te),o=r.pow(n,e),i=r.mul(t,o),s=r.mul(r.mul(i,Te),o),a=r.mul(i,r.sub(s,r.ONE));if(!r.eql(r.sqr(a),t))throw new Error("Cannot find square root");return a}function Hf(r){if(r<BigInt(3))throw new Error("sqrt is not defined for small field");let t=r-ut,e=0;for(;t%Te===wt;)t/=Te,e++;let n=Te,o=Kt(r);for(;ic(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+ut)/Te;return function(c,l){if(c.is0(l))return l;if(ic(c,l)!==1)throw new Error("Cannot find square root");let u=e,f=c.mul(c.ONE,i),m=c.pow(l,t),p=c.pow(l,s);for(;!c.eql(m,c.ONE);){if(c.is0(m))return c.ZERO;let b=1,x=c.sqr(m);for(;!c.eql(x,c.ONE);)if(b++,x=c.sqr(x),b===u)throw new Error("Cannot find square root");let h=ut<<BigInt(u-b-1),S=c.pow(f,h);u=b,f=c.sqr(S),m=c.mul(m,f),p=c.mul(p,S)}return p}}function Ff(r){return r%sc===qf?uc:r%cc===ac?zf:Hf(r)}var lc=(r,t)=>(J(r,t)&ut)===ut,Vf=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ai(r){let t={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},e=Vf.reduce((n,o)=>(n[o]="function",n),t);return me(r,e),r}function Gf(r,t,e){if(e<wt)throw new Error("invalid exponent, negatives unsupported");if(e===wt)return r.ONE;if(e===ut)return t;let n=r.ONE,o=t;for(;e>wt;)e&ut&&(n=r.mul(n,o)),o=r.sqr(o),e>>=ut;return n}function Kr(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 ic(r,t){let e=(r.ORDER-ut)/Te,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 fc(r,t){t!==void 0&&Lr(t);let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}function Kt(r,t,e=!1,n={}){if(r<=wt)throw new Error("invalid field: expected ORDER > 0, got "+r);let o,i;if(typeof t=="object"&&t!=null){if(n.sqrt||e)throw new Error("cannot specify opts in two arguments");let u=t;u.BITS&&(o=u.BITS),u.sqrt&&(i=u.sqrt),typeof u.isLE=="boolean"&&(e=u.isLE)}else typeof t=="number"&&(o=t),n.sqrt&&(i=n.sqrt);let{nBitLength:s,nByteLength:a}=fc(r,o);if(a>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let c,l=Object.freeze({ORDER:r,isLE:e,BITS:s,BYTES:a,MASK:Ie(s),ZERO:wt,ONE:ut,create:u=>J(u,r),isValid:u=>{if(typeof u!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof u);return wt<=u&&u<r},is0:u=>u===wt,isValidNot0:u=>!l.is0(u)&&l.isValid(u),isOdd:u=>(u&ut)===ut,neg:u=>J(-u,r),eql:(u,f)=>u===f,sqr:u=>J(u*u,r),add:(u,f)=>J(u+f,r),sub:(u,f)=>J(u-f,r),mul:(u,f)=>J(u*f,r),pow:(u,f)=>Gf(l,u,f),div:(u,f)=>J(u*oc(f,r),r),sqrN:u=>u*u,addN:(u,f)=>u+f,subN:(u,f)=>u-f,mulN:(u,f)=>u*f,inv:u=>oc(u,r),sqrt:i||(u=>(c||(c=Ff(r)),c(l,u))),toBytes:u=>e?er(u,a):In(u,a),fromBytes:u=>{if(u.length!==a)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+u.length);return e?Ae(u):tr(u)},invertBatch:u=>Kr(l,u),cmov:(u,f,m)=>m?f:u});return Object.freeze(l)}function hc(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let t=r.toString(2).length;return Math.ceil(t/8)}function Ii(r){let t=hc(r);return t+Math.ceil(t/2)}function dc(r,t,e=!1){let n=r.length,o=hc(t),i=Ii(t);if(n<16||n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);let s=e?Ae(r):tr(r),a=J(s,t-ut)+ut;return e?er(a,o):In(a,o)}var or=BigInt(0),Ce=BigInt(1);function nr(r,t){let e=t.negate();return r?e:t}function Tn(r,t,e){let n=t==="pz"?s=>s.pz:s=>s.ez,o=Kr(r.Fp,e.map(n));return e.map((s,a)=>s.toAffine(o[a])).map(r.fromAffine)}function gc(r,t){if(!Number.isSafeInteger(r)||r<=0||r>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+r)}function Ti(r,t){gc(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 pc(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+=Ce);let l=t*n,u=l+Math.abs(a)-1,f=a===0,m=a<0,p=t%2!==0;return{nextN:c,offset:u,isZero:f,isNeg:m,isNegF:p,offsetF:l}}function Wf(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 $f(r,t){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((e,n)=>{if(!t.isValid(e))throw new Error("invalid scalar at index "+n)})}var Ci=new WeakMap,bc=new WeakMap;function Di(r){return bc.get(r)||1}function mc(r){if(r!==or)throw new Error("invalid wNAF")}function Cn(r,t){return{constTimeNegate:nr,hasPrecomputes(e){return Di(e)!==1},unsafeLadder(e,n,o=r.ZERO){let i=e;for(;n>or;)n&Ce&&(o=o.add(i)),i=i.double(),n>>=Ce;return o},precomputeWindow(e,n){let{windows:o,windowSize:i}=Ti(n,t),s=[],a=e,c=a;for(let l=0;l<o;l++){c=a,s.push(c);for(let u=1;u<i;u++)c=c.add(a),s.push(c);a=c.double()}return s},wNAF(e,n,o){let i=r.ZERO,s=r.BASE,a=Ti(e,t);for(let c=0;c<a.windows;c++){let{nextN:l,offset:u,isZero:f,isNeg:m,isNegF:p,offsetF:b}=pc(o,c,a);o=l,f?s=s.add(nr(p,n[b])):i=i.add(nr(m,n[u]))}return mc(o),{p:i,f:s}},wNAFUnsafe(e,n,o,i=r.ZERO){let s=Ti(e,t);for(let a=0;a<s.windows&&o!==or;a++){let{nextN:c,offset:l,isZero:u,isNeg:f}=pc(o,a,s);if(o=c,!u){let m=n[l];i=i.add(f?m.negate():m)}}return mc(o),i},getPrecomputes(e,n,o){let i=Ci.get(n);return i||(i=this.precomputeWindow(n,e),e!==1&&(typeof o=="function"&&(i=o(i)),Ci.set(n,i))),i},wNAFCached(e,n,o){let i=Di(e);return this.wNAF(i,this.getPrecomputes(i,e,o),n)},wNAFCachedUnsafe(e,n,o,i){let s=Di(e);return s===1?this.unsafeLadder(e,n,i):this.wNAFUnsafe(s,this.getPrecomputes(s,e,o),n,i)},setWindowSize(e,n){gc(n,t),bc.set(e,n),Ci.delete(e)}}}function xc(r,t,e,n){let o=t,i=r.ZERO,s=r.ZERO;for(;e>or||n>or;)e&Ce&&(i=i.add(o)),n&Ce&&(s=s.add(o)),o=o.double(),e>>=Ce,n>>=Ce;return{p1:i,p2:s}}function Dn(r,t,e,n){Wf(e,r),$f(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=rc(BigInt(o)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let l=Ie(c),u=new Array(Number(l)+1).fill(s),f=Math.floor((t.BITS-1)/c)*c,m=s;for(let p=f;p>=0;p-=c){u.fill(s);for(let x=0;x<i;x++){let h=n[x],S=Number(h>>BigInt(p)&l);u[S]=u[S].add(e[x])}let b=s;for(let x=u.length-1,h=s;x>0;x--)h=h.add(u[x]),b=b.add(h);if(m=m.add(b),p!==0)for(let x=0;x<c;x++)m=m.double()}return m}function yc(r,t){if(t){if(t.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Ai(t),t}else return Kt(r)}function Pn(r,t,e={}){if(!t||typeof t!="object")throw new Error(`expected valid ${r} CURVE object`);for(let a of["p","n","h"]){let c=t[a];if(!(typeof c=="bigint"&&c>or))throw new Error(`CURVE.${a} must be positive bigint`)}let n=yc(t.p,e.Fp),o=yc(t.n,e.Fn),s=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let a of s)if(!n.isValid(t[a]))throw new Error(`CURVE.${a} must be valid field element of CURVE.Fp`);return{Fp:n,Fn:o}}var $t=BigInt(0),Et=BigInt(1),Pi=BigInt(2),Zf=BigInt(8),Yf={zip215:!0};function jf(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 Xf(r,t={}){let{Fp:e,Fn:n}=Pn("edwards",r,t),{h:o,n:i}=r;me(t,{},{uvRatio:"function"});let s=Pi<<BigInt(n.BYTES*8)-Et,a=x=>e.create(x),c=t.uvRatio||((x,h)=>{try{return{isValid:!0,value:e.sqrt(e.div(x,h))}}catch{return{isValid:!1,value:$t}}});if(!jf(e,r,r.Gx,r.Gy))throw new Error("bad curve params: generator point");function l(x,h,S=!1){let C=S?Et:$t;return pe("coordinate "+x,h,C,s),h}function u(x){if(!(x instanceof p))throw new Error("ExtendedPoint expected")}let f=rr((x,h)=>{let{ex:S,ey:C,ez:_}=x,B=x.is0();h==null&&(h=B?Zf:e.inv(_));let g=a(S*h),R=a(C*h),P=a(_*h);if(B)return{x:$t,y:Et};if(P!==Et)throw new Error("invZ was invalid");return{x:g,y:R}}),m=rr(x=>{let{a:h,d:S}=r;if(x.is0())throw new Error("bad point: ZERO");let{ex:C,ey:_,ez:B,et:g}=x,R=a(C*C),P=a(_*_),I=a(B*B),d=a(I*I),E=a(R*h),y=a(I*a(E+P)),w=a(d+a(S*a(R*P)));if(y!==w)throw new Error("bad point: equation left != right (1)");let v=a(C*_),T=a(B*g);if(v!==T)throw new Error("bad point: equation left != right (2)");return!0});class p{constructor(h,S,C,_){this.ex=l("x",h),this.ey=l("y",S),this.ez=l("z",C,!0),this.et=l("t",_),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(h){if(h instanceof p)throw new Error("extended point not allowed");let{x:S,y:C}=h||{};return l("x",S),l("y",C),new p(S,C,Et,a(S*C))}static normalizeZ(h){return Tn(p,"ez",h)}static msm(h,S){return Dn(p,n,h,S)}_setWindowSize(h){this.precompute(h)}precompute(h=8,S=!0){return b.setWindowSize(this,h),S||this.multiply(Pi),this}assertValidity(){m(this)}equals(h){u(h);let{ex:S,ey:C,ez:_}=this,{ex:B,ey:g,ez:R}=h,P=a(S*R),I=a(B*_),d=a(C*R),E=a(g*_);return P===I&&d===E}is0(){return this.equals(p.ZERO)}negate(){return new p(a(-this.ex),this.ey,this.ez,a(-this.et))}double(){let{a:h}=r,{ex:S,ey:C,ez:_}=this,B=a(S*S),g=a(C*C),R=a(Pi*a(_*_)),P=a(h*B),I=S+C,d=a(a(I*I)-B-g),E=P+g,y=E-R,w=P-g,v=a(d*y),T=a(E*w),A=a(d*w),D=a(y*E);return new p(v,T,D,A)}add(h){u(h);let{a:S,d:C}=r,{ex:_,ey:B,ez:g,et:R}=this,{ex:P,ey:I,ez:d,et:E}=h,y=a(_*P),w=a(B*I),v=a(R*C*E),T=a(g*d),A=a((_+B)*(P+I)-y-w),D=T-v,N=T+v,O=a(w-S*y),rt=a(A*D),V=a(N*O),U=a(A*O),it=a(D*N);return new p(rt,V,it,U)}subtract(h){return this.add(h.negate())}multiply(h){let S=h;pe("scalar",S,Et,i);let{p:C,f:_}=b.wNAFCached(this,S,p.normalizeZ);return p.normalizeZ([C,_])[0]}multiplyUnsafe(h,S=p.ZERO){let C=h;return pe("scalar",C,$t,i),C===$t?p.ZERO:this.is0()||C===Et?this:b.wNAFCachedUnsafe(this,C,p.normalizeZ,S)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}isTorsionFree(){return b.wNAFCachedUnsafe(this,i).is0()}toAffine(h){return f(this,h)}clearCofactor(){return o===Et?this:this.multiplyUnsafe(o)}static fromBytes(h,S=!1){return pt(h),this.fromHex(h,S)}static fromHex(h,S=!1){let{d:C,a:_}=r,B=e.BYTES;h=j("pointHex",h,B),oe("zip215",S);let g=h.slice(),R=h[B-1];g[B-1]=R&-129;let P=Ae(g),I=S?s:e.ORDER;pe("pointHex.y",P,$t,I);let d=a(P*P),E=a(d-Et),y=a(C*d-_),{isValid:w,value:v}=c(E,y);if(!w)throw new Error("Point.fromHex: invalid y coordinate");let T=(v&Et)===Et,A=(R&128)!==0;if(!S&&v===$t&&A)throw new Error("Point.fromHex: x=0 and x_0=1");return A!==T&&(v=a(-v)),p.fromAffine({x:v,y:P})}static fromPrivateScalar(h){return p.BASE.multiply(h)}toBytes(){let{x:h,y:S}=this.toAffine(),C=er(S,e.BYTES);return C[C.length-1]|=h&Et?128:0,C}toRawBytes(){return this.toBytes()}toHex(){return Gt(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}p.BASE=new p(r.Gx,r.Gy,Et,a(r.Gx*r.Gy)),p.ZERO=new p($t,Et,Et,$t),p.Fp=e,p.Fn=n;let b=Cn(p,n.BYTES*8);return p}function Qf(r,t){me(t,{hash:"function"},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:e,hash:n}=t,{BASE:o,Fp:i,Fn:s}=r,a=s.ORDER,c=t.randomBytes||Or,l=t.adjustScalarBytes||(g=>g),u=t.domain||((g,R,P)=>{if(oe("phflag",P),R.length||P)throw new Error("Contexts/pre-hash are not supported");return g});function f(g){return s.create(g)}function m(g){return f(Ae(g))}function p(g){let R=i.BYTES;g=j("private key",g,R);let P=j("hashed private key",n(g),2*R),I=l(P.slice(0,R)),d=P.slice(R,2*R),E=m(I);return{head:I,prefix:d,scalar:E}}function b(g){let{head:R,prefix:P,scalar:I}=p(g),d=o.multiply(I),E=d.toBytes();return{head:R,prefix:P,scalar:I,point:d,pointBytes:E}}function x(g){return b(g).pointBytes}function h(g=Uint8Array.of(),...R){let P=Dt(...R);return m(n(u(P,j("context",g),!!e)))}function S(g,R,P={}){g=j("message",g),e&&(g=e(g));let{prefix:I,scalar:d,pointBytes:E}=b(R),y=h(P.context,I,g),w=o.multiply(y).toBytes(),v=h(P.context,w,E,g),T=f(y+v*d);pe("signature.s",T,$t,a);let A=i.BYTES,D=Dt(w,er(T,A));return j("result",D,A*2)}let C=Yf;function _(g,R,P,I=C){let{context:d,zip215:E}=I,y=i.BYTES;g=j("signature",g,2*y),R=j("message",R),P=j("publicKey",P,y),E!==void 0&&oe("zip215",E),e&&(R=e(R));let w=Ae(g.slice(y,2*y)),v,T,A;try{v=r.fromHex(P,E),T=r.fromHex(g.slice(0,y),E),A=o.multiplyUnsafe(w)}catch{return!1}if(!E&&v.isSmallOrder())return!1;let D=h(d,T.toBytes(),v.toBytes(),R);return T.add(v.multiplyUnsafe(D)).subtract(A).clearCofactor().is0()}return o.precompute(8),{getPublicKey:x,sign:S,verify:_,utils:{getExtendedPublicKey:b,randomPrivateKey:()=>c(i.BYTES),precompute(g=8,R=r.BASE){return R.precompute(g,!1)}},Point:r}}function Jf(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=Kt(t.n,r.nBitLength,!0),o={Fp:e,Fn:n,uvRatio:r.uvRatio},i={hash:r.hash,randomBytes:r.randomBytes,adjustScalarBytes:r.adjustScalarBytes,domain:r.domain,prehash:r.prehash,mapToCurve:r.mapToCurve};return{CURVE:t,curveOpts:o,eddsaOpts:i}}function th(r,t){return Object.assign({},t,{ExtendedPoint:t.Point,CURVE:r})}function wc(r){let{CURVE:t,curveOpts:e,eddsaOpts:n}=Jf(r),o=Xf(t,e),i=Qf(o,n);return th(r,i)}var L0=BigInt(0),eh=BigInt(1),Ec=BigInt(2),B0=BigInt(3),rh=BigInt(5),nh=BigInt(8),Rn={p:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:nh,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function oh(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),i=Rn.p,a=r*r%i*r%i,c=X(a,Ec,i)*a%i,l=X(c,eh,i)*r%i,u=X(l,rh,i)*l%i,f=X(u,t,i)*u%i,m=X(f,e,i)*f%i,p=X(m,n,i)*m%i,b=X(p,o,i)*p%i,x=X(b,o,i)*p%i,h=X(x,t,i)*u%i;return{pow_p_5_8:X(h,Ec,i)*r%i,b2:a}}function ih(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var Sc=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function sh(r,t){let e=Rn.p,n=J(t*t*t,e),o=J(n*n*t,e),i=oh(r*o).pow_p_5_8,s=J(r*n*i,e),a=J(t*s*s,e),c=s,l=J(s*Sc,e),u=a===r,f=a===J(-r,e),m=a===J(-r*Sc,e);return u&&(s=c),(f||m)&&(s=l),lc(s,e)&&(s=J(-s,e)),{isValid:u||f,value:s}}var ah=Kt(Rn.p,void 0,!0),ch={...Rn,Fp:ah,hash:Ja,adjustScalarBytes:ih,uvRatio:sh},vc=wc(ch);var qr=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},Ln=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var _c={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new Ln("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 Ot=_c;var Bn=32;var Ri,uh=(async()=>{try{return await Ot.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function lh(r,t,e){if(r.buffer instanceof ArrayBuffer){let n=await Ot.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await Ot.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 vc.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}async function Ac(r,t,e){return Ri==null&&(Ri=await uh),Ri?lh(r,t,e):fh(r,t,e)}function On(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Nn=class{type="Ed25519";raw;constructor(t){this.raw=Li(t,Bn)}toMultihash(){return kt.digest(Vt(this))}toCID(){return et.createV1(114,this.toMultihash())}toString(){return Y.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:at(this.raw,t.raw)}verify(t,e,n){n?.signal?.throwIfAborted();let o=Ac(this.raw,e,t);return On(o)?o.then(i=>(n?.signal?.throwIfAborted(),i)):o}};function Bi(r){return r=Li(r,Bn),new Nn(r)}function Li(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new st(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}var dh=Math.pow(2,7),ph=Math.pow(2,14),mh=Math.pow(2,21),Oi=Math.pow(2,28),Ni=Math.pow(2,35),Ui=Math.pow(2,42),ki=Math.pow(2,49),F=128,mt=127;function At(r){if(r<dh)return 1;if(r<ph)return 2;if(r<mh)return 3;if(r<Oi)return 4;if(r<Ni)return 5;if(r<Ui)return 6;if(r<ki)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function ir(r,t,e=0){switch(At(r)){case 8:t[e++]=r&255|F,r/=128;case 7:t[e++]=r&255|F,r/=128;case 6:t[e++]=r&255|F,r/=128;case 5:t[e++]=r&255|F,r/=128;case 4:t[e++]=r&255|F,r>>>=7;case 3:t[e++]=r&255|F,r>>>=7;case 2:t[e++]=r&255|F,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(At(r)){case 8:t.set(e++,r&255|F),r/=128;case 7:t.set(e++,r&255|F),r/=128;case 6:t.set(e++,r&255|F),r/=128;case 5:t.set(e++,r&255|F),r/=128;case 4:t.set(e++,r&255|F),r>>>=7;case 3:t.set(e++,r&255|F),r>>>=7;case 2:t.set(e++,r&255|F),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function Mi(r,t){let e=r[t],n=0;if(n+=e&mt,e<F||(e=r[t+1],n+=(e&mt)<<7,e<F)||(e=r[t+2],n+=(e&mt)<<14,e<F)||(e=r[t+3],n+=(e&mt)<<21,e<F)||(e=r[t+4],n+=(e&mt)*Oi,e<F)||(e=r[t+5],n+=(e&mt)*Ni,e<F)||(e=r[t+6],n+=(e&mt)*Ui,e<F)||(e=r[t+7],n+=(e&mt)*ki,e<F))return n;throw new RangeError("Could not decode varint")}function gh(r,t){let e=r.get(t),n=0;if(n+=e&mt,e<F||(e=r.get(t+1),n+=(e&mt)<<7,e<F)||(e=r.get(t+2),n+=(e&mt)<<14,e<F)||(e=r.get(t+3),n+=(e&mt)<<21,e<F)||(e=r.get(t+4),n+=(e&mt)*Oi,e<F)||(e=r.get(t+5),n+=(e&mt)*Ni,e<F)||(e=r.get(t+6),n+=(e&mt)*Ui,e<F)||(e=r.get(t+7),n+=(e&mt)*ki,e<F))return n;throw new RangeError("Could not decode varint")}function sr(r,t,e=0){return t==null&&(t=vt(At(r))),t instanceof Uint8Array?ir(r,t,e):yh(r,t,e)}function zr(r,t=0){return r instanceof Uint8Array?Mi(r,t):gh(r,t)}var qi=new Float32Array([-0]),ye=new Uint8Array(qi.buffer);function Tc(r,t,e){qi[0]=r,t[e]=ye[0],t[e+1]=ye[1],t[e+2]=ye[2],t[e+3]=ye[3]}function Cc(r,t){return ye[0]=r[t],ye[1]=r[t+1],ye[2]=r[t+2],ye[3]=r[t+3],qi[0]}var zi=new Float64Array([-0]),yt=new Uint8Array(zi.buffer);function Dc(r,t,e){zi[0]=r,t[e]=yt[0],t[e+1]=yt[1],t[e+2]=yt[2],t[e+3]=yt[3],t[e+4]=yt[4],t[e+5]=yt[5],t[e+6]=yt[6],t[e+7]=yt[7]}function Pc(r,t){return yt[0]=r[t],yt[1]=r[t+1],yt[2]=r[t+2],yt[3]=r[t+3],yt[4]=r[t+4],yt[5]=r[t+5],yt[6]=r[t+6],yt[7]=r[t+7],zi[0]}var bh=BigInt(Number.MAX_SAFE_INTEGER),xh=BigInt(Number.MIN_SAFE_INTEGER),Pt=class r{lo;hi;constructor(t,e){this.lo=t|0,this.hi=e|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(e+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(BigInt(e)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?e===0?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return De;if(t<bh&&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>Rc&&(o=0n,++n>Rc&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return De;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):De}},De=new Pt(0,0);De.toBigInt=function(){return 0n};De.zzEncode=De.zzDecode=function(){return this};De.length=function(){return 1};var Rc=4294967296n;function Lc(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 Bc(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 Hi(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 qt(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function Un(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var Fi=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,qt(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 qt(this,4);return Un(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw qt(this,4);return Un(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw qt(this,4);let t=Cc(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw qt(this,4);let t=Pc(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw qt(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return Bc(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw qt(this,t);this.pos+=t}else do if(this.pos>=this.len)throw qt(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new Pt(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw qt(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 qt(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 qt(this,8);let t=Un(this.buf,this.pos+=4),e=Un(this.buf,this.pos+=4);return new Pt(t,e)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=Mi(this.buf,this.pos);return this.pos+=At(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 Vi(r){return new Fi(r instanceof Uint8Array?r:r.subarray())}function It(r,t,e){let n=Vi(r);return t.decode(n,void 0,e)}function Gi(r){let t=r??8192,e=t>>>1,n,o=t;return function(s){if(s<1||s>e)return vt(s);o+s>t&&(n=vt(t),o=0);let a=n.subarray(o,o+=s);return(o&7)!==0&&(o=(o|7)+1),a}}var Pe=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function Wi(){}var Zi=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},wh=Gi();function Eh(r){return globalThis.Buffer!=null?vt(r):wh(r)}var Fr=class{len;head;tail;states;constructor(){this.len=0,this.head=new Pe(Wi,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new Pe(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new Yi((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(kn,10,Pt.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=Pt.fromBigInt(t);return this._push(kn,e.length(),e)}uint64Number(t){return this._push(ir,At(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let e=Pt.fromBigInt(t).zzEncode();return this._push(kn,e.length(),e)}sint64Number(t){let e=Pt.fromNumber(t).zzEncode();return this._push(kn,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push($i,1,t?1:0)}fixed32(t){return this._push(Hr,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=Pt.fromBigInt(t);return this._push(Hr,4,e.lo)._push(Hr,4,e.hi)}fixed64Number(t){let e=Pt.fromNumber(t);return this._push(Hr,4,e.lo)._push(Hr,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(Tc,4,t)}double(t){return this._push(Dc,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push($i,1,0):this.uint32(e)._push(vh,e,t)}string(t){let e=Lc(t);return e!==0?this.uint32(e)._push(Hi,e,t):this._push($i,1,0)}fork(){return this.states=new Zi(this),this.head=this.tail=new Pe(Wi,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Pe(Wi,0,0),this.len=0),this}ldelim(){let t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=e,this.len+=n),this}finish(){let t=this.head.next,e=Eh(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function $i(r,t,e){t[e]=r&255}function Sh(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var Yi=class extends Pe{next;constructor(t,e){super(Sh,t,e),this.next=void 0}};function kn(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 Hr(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 vh(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(Fr.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(_h,t,r),this},Fr.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(Ah,t,r),this});function _h(r,t,e){t.set(r,e)}function Ah(r,t,e){r.length<40?Hi(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(k(r),e)}function ji(){return new Fr}function Tt(r,t){let e=ji();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var ar;(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"})(ar||(ar={}));function Mn(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function Re(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 Mn("enum",ar.VARINT,e,n)}function Ct(r,t){return Mn("message",ar.LENGTH_DELIMITED,r,t)}var Vr=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var ot;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(ot||(ot={}));var Xi;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(Xi||(Xi={}));(function(r){r.codec=()=>Re(Xi)})(ot||(ot={}));var Zt;(function(r){let t;r.codec=()=>(t==null&&(t=Ct((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),ot.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=ot.codec().decode(e);break}case 2:{i.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Tt(e,r.codec()),r.decode=(e,n)=>It(e,r.codec(),n)})(Zt||(Zt={}));var Qi;(function(r){let t;r.codec=()=>(t==null&&(t=Ct((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),ot.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=ot.codec().decode(e);break}case 2:{i.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Tt(e,r.codec()),r.decode=(e,n)=>It(e,r.codec(),n)})(Qi||(Qi={}));var Wr={};St(Wr,{MAX_RSA_KEY_SIZE:()=>Ji,generateRSAKeyPair:()=>Kc,jwkToJWKKeyPair:()=>qc,jwkToPkcs1:()=>Dh,jwkToPkix:()=>ns,jwkToRSAPrivateKey:()=>as,pkcs1MessageToJwk:()=>es,pkcs1MessageToRSAPrivateKey:()=>os,pkcs1ToJwk:()=>Ch,pkcs1ToRSAPrivateKey:()=>Mc,pkixMessageToJwk:()=>rs,pkixMessageToRSAPublicKey:()=>ss,pkixToJwk:()=>Ph,pkixToRSAPublicKey:()=>is});var Kn=An;var cr=class{type="RSA";jwk;_raw;_multihash;constructor(t,e){this.jwk=t,this._multihash=e}get raw(){return this._raw==null&&(this._raw=Wr.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return et.createV1(114,this._multihash)}toString(){return Y.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:at(this.raw,t.raw)}verify(t,e,n){return kc(this.jwk,e,t,n)}},Gr=class{type="RSA";jwk;_raw;publicKey;constructor(t,e){this.jwk=t,this.publicKey=e}get raw(){return this._raw==null&&(this._raw=Wr.jwkToPkcs1(this.jwk)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:at(this.raw,t.raw)}sign(t,e){return Uc(this.jwk,t,e)}};var Ji=8192,ts=18,Ih=1062,Th=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function Ch(r){let t=te(r);return es(t)}function es(r){return{n:M(r[1],"base64url"),e:M(r[2],"base64url"),d:M(r[3],"base64url"),p:M(r[4],"base64url"),q:M(r[5],"base64url"),dp:M(r[6],"base64url"),dq:M(r[7],"base64url"),qi:M(r[8],"base64url"),kty:"RSA"}}function Dh(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 st("JWK was missing components");return le([_t(Uint8Array.from([0])),_t(k(r.n,"base64url")),_t(k(r.e,"base64url")),_t(k(r.d,"base64url")),_t(k(r.p,"base64url")),_t(k(r.q,"base64url")),_t(k(r.dp,"base64url")),_t(k(r.dq,"base64url")),_t(k(r.qi,"base64url"))]).subarray()}function Ph(r){let t=te(r,{offset:0});return rs(t)}function rs(r){let t=te(r[1],{offset:0});return{kty:"RSA",n:M(t[0],"base64url"),e:M(t[1],"base64url")}}function ns(r){if(r.n==null||r.e==null)throw new st("JWK was missing components");return le([Th,En(le([_t(k(r.n,"base64url")),_t(k(r.e,"base64url"))]))]).subarray()}function Mc(r){let t=te(r);return os(t)}function os(r){let t=es(r);return as(t)}function is(r,t){if(r.byteLength>=Ih)throw new He("Key size is too large");let e=te(r,{offset:0});return ss(e,r,t)}function ss(r,t,e){let n=rs(r);if(e==null){let o=Kn(Zt.encode({Type:ot.RSA,Data:t}));e=Ut(ts,o)}return new cr(n,e)}function as(r){if(Hc(r)>Ji)throw new st("Key size is too large");let t=qc(r),e=Kn(Zt.encode({Type:ot.RSA,Data:ns(t.publicKey)})),n=Ut(ts,e);return new Gr(t.privateKey,new cr(t.publicKey,n))}async function Kc(r){if(r>Ji)throw new st("Key size is too large");let t=await zc(r),e=Kn(Zt.encode({Type:ot.RSA,Data:ns(t.publicKey)})),n=Ut(ts,e);return new Gr(t.privateKey,new cr(t.publicKey,n))}function qc(r){if(r==null)throw new st("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function zc(r,t){let e=await Ot.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 Rh(e,t);return{privateKey:n[0],publicKey:n[1]}}async function Uc(r,t,e){let n=await Ot.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);e?.signal?.throwIfAborted();let o=await Ot.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 kc(r,t,e,n){let o=await Ot.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let i=await Ot.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,t,e instanceof Uint8Array?e:e.subarray());return n?.signal?.throwIfAborted(),i}async function Rh(r,t){if(r.privateKey==null||r.publicKey==null)throw new st("Private and public key are required");let e=await Promise.all([Ot.get().subtle.exportKey("jwk",r.privateKey),Ot.get().subtle.exportKey("jwk",r.publicKey)]);return t?.signal?.throwIfAborted(),e}function Hc(r){if(r.kty!=="RSA")throw new st("invalid key type");if(r.n==null)throw new st("invalid key modulus");return k(r.n,"base64url").length*8}var qn=class extends je{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,Ma(t);let n=Br(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),re(i)}update(t){return Qe(this),this.iHash.update(t),this}digestInto(t){Qe(this),pt(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()}},cs=(r,t,e)=>new qn(r,t).update(e).digest();cs.create=(r,t)=>new qn(r,t);function Fc(r){r.lowS!==void 0&&oe("lowS",r.lowS),r.prehash!==void 0&&oe("prehash",r.prehash)}var us=class extends Error{constructor(t=""){super(t)}},ie={Err:us,_tlv:{encode:(r,t)=>{let{Err:e}=ie;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=Mr(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let i=n>127?Mr(o.length/2|128):"";return Mr(r)+i+o+t},decode(r,t){let{Err:e}=ie,n=0;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length<2||t[n++]!==r)throw new e("tlv.decode: wrong tlv");let o=t[n++],i=!!(o&128),s=0;if(!i)s=o;else{let c=o&127;if(!c)throw new e("tlv.decode(long): indefinite length not supported");if(c>4)throw new e("tlv.decode(long): byte length is too big");let l=t.subarray(n,n+c);if(l.length!==c)throw new e("tlv.decode: length bytes not complete");if(l[0]===0)throw new e("tlv.decode(long): zero leftmost byte");for(let u of l)s=s<<8|u;if(n+=c,s<128)throw new e("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+s);if(a.length!==s)throw new e("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+s)}}},_int:{encode(r){let{Err:t}=ie;if(r<$r)throw new t("integer: negative integers are not allowed");let e=Mr(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}=ie;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 tr(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=ie,o=j("signature",r),{v:i,l:s}=n.decode(48,o);if(s.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,i),{v:l,l:u}=n.decode(2,c);if(u.length)throw new t("invalid signature: left bytes after parsing");return{r:e.decode(a),s:e.decode(l)}},hexFromSig(r){let{_tlv:t,_int:e}=ie,n=t.encode(2,e.encode(r.r)),o=t.encode(2,e.encode(r.s)),i=n+o;return t.encode(48,i)}},$r=BigInt(0),Zr=BigInt(1),Lh=BigInt(2),zn=BigInt(3),Bh=BigInt(4);function Oh(r,t,e){function n(o){let i=r.sqr(o),s=r.mul(i,o);return r.add(r.add(s,r.mul(o,t)),e)}return n}function Vc(r,t,e){let{BYTES:n}=r;function o(i){let s;if(typeof i=="bigint")s=i;else{let a=j("private key",i);if(t){if(!t.includes(a.length*2))throw new Error("invalid private key");let c=new Uint8Array(n);c.set(a,c.length-a.length),a=c}try{s=r.fromBytes(a)}catch{throw new Error(`invalid private key: expected ui8a of size ${n}, got ${typeof i}`)}}if(e&&(s=r.create(s)),!r.isValidNot0(s))throw new Error("invalid private key: out of range [1..N-1]");return s}return o}function Nh(r,t={}){let{Fp:e,Fn:n}=Pn("weierstrass",r,t),{h:o,n:i}=r;me(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:s}=t;if(s&&(!e.is0(r.a)||typeof s.beta!="bigint"||typeof s.splitScalar!="function"))throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function');function a(){if(!e.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function c(I,d,E){let{x:y,y:w}=d.toAffine(),v=e.toBytes(y);if(oe("isCompressed",E),E){a();let T=!e.isOdd(w);return Dt(Gc(T),v)}else return Dt(Uint8Array.of(4),v,e.toBytes(w))}function l(I){pt(I);let d=e.BYTES,E=d+1,y=2*d+1,w=I.length,v=I[0],T=I.subarray(1);if(w===E&&(v===2||v===3)){let A=e.fromBytes(T);if(!e.isValid(A))throw new Error("bad point: is not on curve, wrong x");let D=m(A),N;try{N=e.sqrt(D)}catch(V){let U=V instanceof Error?": "+V.message:"";throw new Error("bad point: is not on curve, sqrt error"+U)}a();let O=e.isOdd(N);return(v&1)===1!==O&&(N=e.neg(N)),{x:A,y:N}}else if(w===y&&v===4){let A=e.fromBytes(T.subarray(d*0,d*1)),D=e.fromBytes(T.subarray(d*1,d*2));if(!p(A,D))throw new Error("bad point: is not on curve");return{x:A,y:D}}else throw new Error(`bad point: got length ${w}, expected compressed=${E} or uncompressed=${y}`)}let u=t.toBytes||c,f=t.fromBytes||l,m=Oh(e,r.a,r.b);function p(I,d){let E=e.sqr(d),y=m(I);return e.eql(E,y)}if(!p(r.Gx,r.Gy))throw new Error("bad curve params: generator point");let b=e.mul(e.pow(r.a,zn),Bh),x=e.mul(e.sqr(r.b),BigInt(27));if(e.is0(e.add(b,x)))throw new Error("bad curve params: a or b");function h(I,d,E=!1){if(!e.isValid(d)||E&&e.is0(d))throw new Error(`bad point coordinate ${I}`);return d}function S(I){if(!(I instanceof g))throw new Error("ProjectivePoint expected")}let C=rr((I,d)=>{let{px:E,py:y,pz:w}=I;if(e.eql(w,e.ONE))return{x:E,y};let v=I.is0();d==null&&(d=v?e.ONE:e.inv(w));let T=e.mul(E,d),A=e.mul(y,d),D=e.mul(w,d);if(v)return{x:e.ZERO,y:e.ZERO};if(!e.eql(D,e.ONE))throw new Error("invZ was invalid");return{x:T,y:A}}),_=rr(I=>{if(I.is0()){if(t.allowInfinityPoint&&!e.is0(I.py))return;throw new Error("bad point: ZERO")}let{x:d,y:E}=I.toAffine();if(!e.isValid(d)||!e.isValid(E))throw new Error("bad point: x or y not field elements");if(!p(d,E))throw new Error("bad point: equation left != right");if(!I.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function B(I,d,E,y,w){return E=new g(e.mul(E.px,I),E.py,E.pz),d=nr(y,d),E=nr(w,E),d.add(E)}class g{constructor(d,E,y){this.px=h("x",d),this.py=h("y",E,!0),this.pz=h("z",y),Object.freeze(this)}static fromAffine(d){let{x:E,y}=d||{};if(!d||!e.isValid(E)||!e.isValid(y))throw new Error("invalid affine point");if(d instanceof g)throw new Error("projective point not allowed");return e.is0(E)&&e.is0(y)?g.ZERO:new g(E,y,e.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(d){return Tn(g,"pz",d)}static fromBytes(d){return pt(d),g.fromHex(d)}static fromHex(d){let E=g.fromAffine(f(j("pointHex",d)));return E.assertValidity(),E}static fromPrivateKey(d){let E=Vc(n,t.allowedPrivateKeyLengths,t.wrapPrivateKey);return g.BASE.multiply(E(d))}static msm(d,E){return Dn(g,n,d,E)}precompute(d=8,E=!0){return P.setWindowSize(this,d),E||this.multiply(zn),this}_setWindowSize(d){this.precompute(d)}assertValidity(){_(this)}hasEvenY(){let{y:d}=this.toAffine();if(!e.isOdd)throw new Error("Field doesn't support isOdd");return!e.isOdd(d)}equals(d){S(d);let{px:E,py:y,pz:w}=this,{px:v,py:T,pz:A}=d,D=e.eql(e.mul(E,A),e.mul(v,w)),N=e.eql(e.mul(y,A),e.mul(T,w));return D&&N}negate(){return new g(this.px,e.neg(this.py),this.pz)}double(){let{a:d,b:E}=r,y=e.mul(E,zn),{px:w,py:v,pz:T}=this,A=e.ZERO,D=e.ZERO,N=e.ZERO,O=e.mul(w,w),rt=e.mul(v,v),V=e.mul(T,T),U=e.mul(w,v);return U=e.add(U,U),N=e.mul(w,T),N=e.add(N,N),A=e.mul(d,N),D=e.mul(y,V),D=e.add(A,D),A=e.sub(rt,D),D=e.add(rt,D),D=e.mul(A,D),A=e.mul(U,A),N=e.mul(y,N),V=e.mul(d,V),U=e.sub(O,V),U=e.mul(d,U),U=e.add(U,N),N=e.add(O,O),O=e.add(N,O),O=e.add(O,V),O=e.mul(O,U),D=e.add(D,O),V=e.mul(v,T),V=e.add(V,V),O=e.mul(V,U),A=e.sub(A,O),N=e.mul(V,rt),N=e.add(N,N),N=e.add(N,N),new g(A,D,N)}add(d){S(d);let{px:E,py:y,pz:w}=this,{px:v,py:T,pz:A}=d,D=e.ZERO,N=e.ZERO,O=e.ZERO,rt=r.a,V=e.mul(r.b,zn),U=e.mul(E,v),it=e.mul(y,T),ct=e.mul(w,A),dt=e.add(E,y),Z=e.add(v,T);dt=e.mul(dt,Z),Z=e.add(U,it),dt=e.sub(dt,Z),Z=e.add(E,w);let xt=e.add(v,A);return Z=e.mul(Z,xt),xt=e.add(U,ct),Z=e.sub(Z,xt),xt=e.add(y,w),D=e.add(T,A),xt=e.mul(xt,D),D=e.add(it,ct),xt=e.sub(xt,D),O=e.mul(rt,Z),D=e.mul(V,ct),O=e.add(D,O),D=e.sub(it,O),O=e.add(it,O),N=e.mul(D,O),it=e.add(U,U),it=e.add(it,U),ct=e.mul(rt,ct),Z=e.mul(V,Z),it=e.add(it,ct),ct=e.sub(U,ct),ct=e.mul(rt,ct),Z=e.add(Z,ct),U=e.mul(it,Z),N=e.add(N,U),U=e.mul(xt,Z),D=e.mul(dt,D),D=e.sub(D,U),U=e.mul(dt,it),O=e.mul(xt,O),O=e.add(O,U),new g(D,N,O)}subtract(d){return this.add(d.negate())}is0(){return this.equals(g.ZERO)}multiply(d){let{endo:E}=t;if(!n.isValidNot0(d))throw new Error("invalid scalar: out of range");let y,w,v=T=>P.wNAFCached(this,T,g.normalizeZ);if(E){let{k1neg:T,k1:A,k2neg:D,k2:N}=E.splitScalar(d),{p:O,f:rt}=v(A),{p:V,f:U}=v(N);w=rt.add(U),y=B(E.beta,O,V,T,D)}else{let{p:T,f:A}=v(d);y=T,w=A}return g.normalizeZ([y,w])[0]}multiplyUnsafe(d){let{endo:E}=t,y=this;if(!n.isValid(d))throw new Error("invalid scalar: out of range");if(d===$r||y.is0())return g.ZERO;if(d===Zr)return y;if(P.hasPrecomputes(this))return this.multiply(d);if(E){let{k1neg:w,k1:v,k2neg:T,k2:A}=E.splitScalar(d),{p1:D,p2:N}=xc(g,y,v,A);return B(E.beta,D,N,w,T)}else return P.wNAFCachedUnsafe(y,d)}multiplyAndAddUnsafe(d,E,y){let w=this.multiplyUnsafe(E).add(d.multiplyUnsafe(y));return w.is0()?void 0:w}toAffine(d){return C(this,d)}isTorsionFree(){let{isTorsionFree:d}=t;return o===Zr?!0:d?d(g,this):P.wNAFCachedUnsafe(this,i).is0()}clearCofactor(){let{clearCofactor:d}=t;return o===Zr?this:d?d(g,this):this.multiplyUnsafe(o)}toBytes(d=!0){return oe("isCompressed",d),this.assertValidity(),u(g,this,d)}toRawBytes(d=!0){return this.toBytes(d)}toHex(d=!0){return Gt(this.toBytes(d))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}g.BASE=new g(r.Gx,r.Gy,e.ONE),g.ZERO=new g(e.ZERO,e.ONE,e.ZERO),g.Fp=e,g.Fn=n;let R=n.BITS,P=Cn(g,t.endo?Math.ceil(R/2):R);return g}function Gc(r){return Uint8Array.of(r?2:3)}function Uh(r,t,e={}){me(t,{hash:"function"},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let n=t.randomBytes||Or,o=t.hmac||((y,...w)=>cs(t.hash,y,Dt(...w))),{Fp:i,Fn:s}=r,{ORDER:a,BITS:c}=s;function l(y){let w=a>>Zr;return y>w}function u(y){return l(y)?s.neg(y):y}function f(y,w){if(!s.isValidNot0(w))throw new Error(`invalid signature ${y}: out of range 1..CURVE.n`)}class m{constructor(w,v,T){f("r",w),f("s",v),this.r=w,this.s=v,T!=null&&(this.recovery=T),Object.freeze(this)}static fromCompact(w){let v=s.BYTES,T=j("compactSignature",w,v*2);return new m(s.fromBytes(T.subarray(0,v)),s.fromBytes(T.subarray(v,v*2)))}static fromDER(w){let{r:v,s:T}=ie.toSig(j("DER",w));return new m(v,T)}assertValidity(){}addRecoveryBit(w){return new m(this.r,this.s,w)}recoverPublicKey(w){let v=i.ORDER,{r:T,s:A,recovery:D}=this;if(D==null||![0,1,2,3].includes(D))throw new Error("recovery id invalid");if(a*Lh<v&&D>1)throw new Error("recovery id is ambiguous for h>1 curve");let O=D===2||D===3?T+a:T;if(!i.isValid(O))throw new Error("recovery id 2 or 3 invalid");let rt=i.toBytes(O),V=r.fromHex(Dt(Gc((D&1)===0),rt)),U=s.inv(O),it=_(j("msgHash",w)),ct=s.create(-it*U),dt=s.create(A*U),Z=r.BASE.multiplyUnsafe(ct).add(V.multiplyUnsafe(dt));if(Z.is0())throw new Error("point at infinify");return Z.assertValidity(),Z}hasHighS(){return l(this.s)}normalizeS(){return this.hasHighS()?new m(this.r,s.neg(this.s),this.recovery):this}toBytes(w){if(w==="compact")return Dt(s.toBytes(this.r),s.toBytes(this.s));if(w==="der")return Je(ie.hexFromSig(this));throw new Error("invalid format")}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Gt(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Gt(this.toBytes("compact"))}}let p=Vc(s,e.allowedPrivateKeyLengths,e.wrapPrivateKey),b={isValidPrivateKey(y){try{return p(y),!0}catch{return!1}},normPrivateKeyToScalar:p,randomPrivateKey:()=>{let y=a;return dc(n(Ii(y)),y)},precompute(y=8,w=r.BASE){return w.precompute(y,!1)}};function x(y,w=!0){return r.fromPrivateKey(y).toBytes(w)}function h(y){if(typeof y=="bigint")return!1;if(y instanceof r)return!0;let v=j("key",y).length,T=i.BYTES,A=T+1,D=2*T+1;if(!(e.allowedPrivateKeyLengths||s.BYTES===A))return v===A||v===D}function S(y,w,v=!0){if(h(y)===!0)throw new Error("first arg must be private key");if(h(w)===!1)throw new Error("second arg must be public key");return r.fromHex(w).multiply(p(y)).toBytes(v)}let C=t.bits2int||function(y){if(y.length>8192)throw new Error("input is too large");let w=tr(y),v=y.length*8-c;return v>0?w>>BigInt(v):w},_=t.bits2int_modN||function(y){return s.create(C(y))},B=Ie(c);function g(y){return pe("num < 2^"+c,y,$r,B),s.toBytes(y)}function R(y,w,v=P){if(["recovered","canonical"].some(dt=>dt in v))throw new Error("sign() legacy options not supported");let{hash:T}=t,{lowS:A,prehash:D,extraEntropy:N}=v;A==null&&(A=!0),y=j("msgHash",y),Fc(v),D&&(y=j("prehashed msgHash",T(y)));let O=_(y),rt=p(w),V=[g(rt),g(O)];if(N!=null&&N!==!1){let dt=N===!0?n(i.BYTES):N;V.push(j("extraEntropy",dt))}let U=Dt(...V),it=O;function ct(dt){let Z=C(dt);if(!s.isValidNot0(Z))return;let xt=s.inv(Z),vr=r.BASE.multiply(Z).toAffine(),qe=s.create(vr.x);if(qe===$r)return;let we=s.create(xt*s.create(it+qe*rt));if(we===$r)return;let qo=(vr.x===qe?0:2)|Number(vr.y&Zr),ze=we;return A&&l(we)&&(ze=u(we),qo^=1),new m(qe,ze,qo)}return{seed:U,k2sig:ct}}let P={lowS:t.lowS,prehash:!1},I={lowS:t.lowS,prehash:!1};function d(y,w,v=P){let{seed:T,k2sig:A}=R(y,w,v);return nc(t.hash.outputLen,s.BYTES,o)(T,A)}r.BASE.precompute(8);function E(y,w,v,T=I){let A=y;w=j("msgHash",w),v=j("publicKey",v),Fc(T);let{lowS:D,prehash:N,format:O}=T;if("strict"in T)throw new Error("options.strict was renamed to lowS");if(O!==void 0&&!["compact","der","js"].includes(O))throw new Error('format must be "compact", "der" or "js"');let rt=typeof A=="string"||Xe(A),V=!rt&&!O&&typeof A=="object"&&A!==null&&typeof A.r=="bigint"&&typeof A.s=="bigint";if(!rt&&!V)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let U,it;try{if(V)if(O===void 0||O==="js")U=new m(A.r,A.s);else throw new Error("invalid format");if(rt){try{O!=="compact"&&(U=m.fromDER(A))}catch(ze){if(!(ze instanceof ie.Err))throw ze}!U&&O!=="der"&&(U=m.fromCompact(A))}it=r.fromHex(v)}catch{return!1}if(!U||D&&U.hasHighS())return!1;N&&(w=t.hash(w));let{r:ct,s:dt}=U,Z=_(w),xt=s.inv(dt),vr=s.create(Z*xt),qe=s.create(ct*xt),we=r.BASE.multiplyUnsafe(vr).add(it.multiplyUnsafe(qe));return we.is0()?!1:s.create(we.x)===ct}return Object.freeze({getPublicKey:x,getSharedSecret:S,sign:d,verify:E,utils:b,Point:r,Signature:m})}function kh(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=Kt(t.n,r.nBitLength),o={Fp:e,Fn:n,allowedPrivateKeyLengths:r.allowedPrivateKeyLengths,allowInfinityPoint:r.allowInfinityPoint,endo:r.endo,wrapPrivateKey:r.wrapPrivateKey,isTorsionFree:r.isTorsionFree,clearCofactor:r.clearCofactor,fromBytes:r.fromBytes,toBytes:r.toBytes};return{CURVE:t,curveOpts:o}}function Mh(r){let{CURVE:t,curveOpts:e}=kh(r),n={hash:r.hash,hmac:r.hmac,randomBytes:r.randomBytes,lowS:r.lowS,bits2int:r.bits2int,bits2int_modN:r.bits2int_modN};return{CURVE:t,curveOpts:e,ecdsaOpts:n}}function Kh(r,t){return Object.assign({},t,{ProjectivePoint:t.Point,CURVE:r})}function Wc(r){let{CURVE:t,curveOpts:e,ecdsaOpts:n}=Mh(r),o=Nh(t,e),i=Uh(o,n,e);return Kh(r,i)}function $c(r,t){let e=n=>Wc({...r,hash:n});return{...e(t),create:e}}var Hn={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},xg=BigInt(0),qh=BigInt(1),ls=BigInt(2),Zc=(r,t)=>(r+t/ls)/t;function zh(r){let t=Hn.p,e=BigInt(3),n=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%t,u=l*l*r%t,f=X(u,e,t)*u%t,m=X(f,e,t)*u%t,p=X(m,ls,t)*l%t,b=X(p,o,t)*p%t,x=X(b,i,t)*b%t,h=X(x,a,t)*x%t,S=X(h,c,t)*h%t,C=X(S,a,t)*x%t,_=X(C,e,t)*u%t,B=X(_,s,t)*b%t,g=X(B,n,t)*l%t,R=X(g,ls,t);if(!fs.eql(fs.sqr(R),r))throw new Error("Cannot find square root");return R}var fs=Kt(Hn.p,void 0,void 0,{sqrt:zh}),ur=$c({...Hn,Fp:fs,lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let t=Hn.n,e=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-qh*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=e,s=BigInt("0x100000000000000000000000000000000"),a=Zc(i*r,t),c=Zc(-n*r,t),l=J(r-a*e-c*o,t),u=J(-a*n-c*i,t),f=l>s,m=u>s;if(f&&(l=t-l),m&&(u=t-u),l>s||u>s)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:f,k1:l,k2neg:m,k2:u}}}},An);function Yc(r,t,e,n){let o=Ze.digest(e instanceof Uint8Array?e:e.subarray());if(On(o))return o.then(({digest:i})=>(n?.signal?.throwIfAborted(),ur.verify(t,i,r))).catch(i=>{throw i.name==="AbortError"?i:new qr(String(i))});try{return n?.signal?.throwIfAborted(),ur.verify(t,o.digest,r)}catch(i){throw new qr(String(i))}}var Fn=class{type="secp256k1";raw;_key;constructor(t){this._key=Xc(t),this.raw=jc(this._key)}toMultihash(){return kt.digest(Vt(this))}toCID(){return et.createV1(114,this.toMultihash())}toString(){return Y.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:at(this.raw,t.raw)}verify(t,e,n){return Yc(this._key,e,t,n)}};function hs(r){return new Fn(r)}function jc(r){return ur.ProjectivePoint.fromHex(r).toRawBytes(!0)}function Xc(r){try{return ur.ProjectivePoint.fromHex(r),r}catch(t){throw new He(String(t))}}function Qc(r,t){let{Type:e,Data:n}=Zt.decode(r),o=n??new Uint8Array;switch(e){case ot.RSA:return is(o,t);case ot.Ed25519:return Bi(o);case ot.secp256k1:return hs(o);case ot.ECDSA:return gi(o);default:throw new Fe}}function Jc(r){let{Type:t,Data:e}=Zt.decode(r.digest),n=e??new Uint8Array;switch(t){case ot.Ed25519:return Bi(n);case ot.secp256k1:return hs(n);case ot.ECDSA:return gi(n);default:throw new Fe}}function Vt(r){return Zt.encode({Type:ot[r.type],Data:r.raw})}var tu=Symbol.for("nodejs.util.inspect.custom"),Hh=114,Yr=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()})`}[Ho]=!0;toString(){return this.string==null&&(this.string=Y.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return et.createV1(Hh,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return at(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return at(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[tu](){return`PeerId(${this.toString()})`}},Vn=class extends Yr{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},Gn=class extends Yr{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},Wn=class extends Yr{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},Fh=2336,jr=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=kt.digest(k(this.url))}[tu](){return`PeerId(${this.url})`}[Ho]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return et.createV1(Fh,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=M(t)),t.toString()===this.toString())}};var Vh=114,eu=2336;function ds(r,t){let e;if(r.charAt(0)==="1"||r.charAt(0)==="Q")e=Ft(Y.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return Gh(et.parse(r));if(t==null)throw new st('Please pass a multibase decoder for strings that do not start with "1" or "Q"');e=Ft(t.decode(r))}return lr(e)}function lr(r){if($h(r))return new Vn({multihash:r});if(Wh(r))try{let t=Jc(r);if(t.type==="Ed25519")return new Gn({multihash:r,publicKey:t});if(t.type==="secp256k1")return new Wn({multihash:r,publicKey:t})}catch{let e=M(r.digest);return new jr(new URL(e))}throw new yn("Supplied PeerID Multihash is invalid")}function Gh(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==Vh&&r.code!==eu)throw new mn("Supplied PeerID CID is invalid");if(r.code===eu){let t=M(r.multihash.digest);return new jr(new URL(t))}return lr(r.multihash)}function Wh(r){return r.code===kt.code}function $h(r){return r.code===Ze.code}var Xr;(function(r){let t;r.codec=()=>(t==null&&(t=Ct((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:Q(0),payloadType:Q(0),payload:Q(0),signature:Q(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=>Tt(e,r.codec()),r.decode=(e,n)=>It(e,r.codec(),n)})(Xr||(Xr={}));var $n=class extends Error{constructor(t="Invalid signature"){super(t),this.name="InvalidSignatureError"}};var Qr=class r{static createFromProtobuf=t=>{let e=Xr.decode(t),n=Qc(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=ru(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 $n("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=Xr.encode({publicKey:Vt(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(t){return t==null?!1:at(this.marshal(),t.marshal())}async validate(t,e){let n=ru(t,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,e)}},ru=(r,t,e)=>{let n=k(r),o=sr(n.byteLength),i=sr(t.length),s=sr(e.length);return new nt(o,n,i,t,s,e)};var ht=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},se=class extends Error{static name="ValidationError";name="ValidationError"},Jr=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Zn=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var Yn=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let e=this.index,n=t();return n===void 0&&(this.index=e),n}parseWith(t){let e=t();if(this.index===this.input.length)return e}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(t){return this.readAtomically(()=>{let e=this.readChar();if(e===t)return e})}readSeparator(t,e,n){return this.readAtomically(()=>{if(!(e>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,e,n,o){return this.readAtomically(()=>{let i=0,s=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let u=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let m=Number.parseInt(f,t);if(!Number.isNaN(m))return m});if(u===void 0)break;if(i*=t,i+=u,i>l||(s+=1,e!==void 0&&s>e))return}if(s!==0)return!n&&c&&s>1?void 0:i})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let e=0;e<t.length;e++){let n=this.readSeparator(".",e,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[e]=n}return t})}readIPv6Addr(){let t=e=>{for(let n=0;n<e.length/2;n++){let o=n*2;if(n<e.length-3){let s=this.readSeparator(":",n,()=>this.readIPv4Addr());if(s!==void 0)return e[o]=s[0],e[o+1]=s[1],e[o+2]=s[2],e[o+3]=s[3],[o+4,!0]}let i=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(i===void 0)return[o,!1];e[o]=i>>8,e[o+1]=i&255}return[e.length,!1]};return this.readAtomically(()=>{let e=new Uint8Array(16),[n,o]=t(e);if(n===16)return e;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let i=new Uint8Array(14),s=16-(n+2),[a]=t(i.subarray(0,s));return e.set(i.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Zh=45,Yh=15,jn=new Yn;function ps(r){if(!(r.length>Yh))return jn.new(r).parseWith(()=>jn.readIPv4Addr())}function ms(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Zh))return jn.new(r).parseWith(()=>jn.readIPv6Addr())}function Xn(r){return!!ps(r)}function ou(r){return!!ms(r)}function gs(r){return t=>M(t,r)}function bs(r){return t=>k(t,r)}function fr(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Le(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(t)}function iu(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=Le(n);return Jt([e,o],e.length+o.length)}function su(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=ue.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=Le(n);return Jt([e,o],e.length+o.length)}function xs(r){let t=r.subarray(0,r.length-2),e=r.subarray(r.length-2),n=M(t,"base32"),o=fr(e);return`${n}:${o}`}var ws=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 ht("Invalid byte value in IP address");t[n]=o}),t},au=function(r){let t=0;r=r.toString().trim();let e=r.split(":",8),n;for(n=0;n<e.length;n++){let i=Xn(e[n]),s;i&&(s=ws(e[n]),e[n]=M(s.subarray(0,2),"base16")),s!=null&&++n<8&&e.splice(n,0,M(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 ht("Invalid byte value in IP address");o[t++]=i>>8&255,o[t++]=i&255}return o},cu=function(r){if(r.byteLength!==4)throw new ht("IPv4 address was incorrect length");let t=[];for(let e=0;e<r.byteLength;e++)t.push(r[e]);return t.join(".")},uu=function(r){if(r.byteLength!==16)throw new ht("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 ht(`Invalid IPv6 address "${e}"`)}};function lu(r){try{let t=new URL(`http://[${r}]`);return t.hostname.substring(1,t.hostname.length-1)}catch{throw new ht(`Invalid IPv6 address "${r}"`)}}var ys=Object.values(Dr).map(r=>r.decoder),jh=function(){let r=ys[0].or(ys[1]);return ys.slice(2).forEach(t=>r=r.or(t)),r}();function fu(r){return jh.decode(r)}function hu(r){return t=>r.encoder.encode(t)}function Xh(r){if(parseInt(r).toString()!==r)throw new se("Value must be an integer")}function Qh(r){if(r<0)throw new se("Value must be a positive integer, or zero")}function Jh(r){return t=>{if(t>r)throw new se(`Value must be smaller than or equal to ${r}`)}}function td(...r){return t=>{for(let e of r)e(t)}}var tn=td(Xh,Qh,Jh(65535));var lt=-1,Es=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 Zn(`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)}))}},Rt=new Es,md=[{code:4,name:"ip4",size:32,valueToBytes:ws,bytesToValue:cu,validate:r=>{if(!Xn(r))throw new se(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Le,bytesToValue:fr,validate:tn},{code:273,name:"udp",size:16,valueToBytes:Le,bytesToValue:fr,validate:tn},{code:33,name:"dccp",size:16,valueToBytes:Le,bytesToValue:fr,validate:tn},{code:41,name:"ip6",size:128,valueToBytes:au,bytesToValue:uu,stringToValue:lu,validate:r=>{if(!ou(r))throw new se(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:lt},{code:43,name:"ipcidr",size:8,bytesToValue:gs("base10"),valueToBytes:bs("base10")},{code:53,name:"dns",size:lt,resolvable:!0},{code:54,name:"dns4",size:lt,resolvable:!0},{code:55,name:"dns6",size:lt,resolvable:!0},{code:56,name:"dnsaddr",size:lt,resolvable:!0},{code:132,name:"sctp",size:16,valueToBytes:Le,bytesToValue:fr,validate:tn},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:lt,path:!0,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:lt,bytesToValue:gs("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?bs("base58btc")(r):et.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:xs,valueToBytes:iu},{code:445,name:"onion3",size:296,bytesToValue:xs,valueToBytes:su},{code:446,name:"garlic64",size:lt},{code:447,name:"garlic32",size:lt},{code:448,name:"tls"},{code:449,name:"sni",size:lt},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:lt,bytesToValue:hu(oi),valueToBytes:fu},{code:480,name:"http"},{code:481,name:"http-path",size:lt,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:lt}];md.forEach(r=>{Rt.addProtocol(r)});function du(r){let t=[],e=0;for(;e<r.length;){let n=zr(r,e),o=Rt.getProtocol(n),i=At(n),s=yd(o,r,e+i),a=0;s>0&&o.size===lt&&(a=At(s));let c=i+a+s,l={code:n,name:o.name,bytes:r.subarray(e,e+c)};if(s>0){let u=e+i+a,f=r.subarray(u,u+s);l.value=o.bytesToValue?.(f)??M(f)}t.push(l),e+=c}return t}function pu(r){let t=0,e=[];for(let n of r){if(n.bytes==null){let o=Rt.getProtocol(n.code),i=At(n.code),s,a=0,c=0;n.value!=null&&(s=o.valueToBytes?.(n.value)??k(n.value),a=s.byteLength,o.size===lt&&(c=At(a)));let l=new Uint8Array(i+c+a),u=0;ir(n.code,l,u),u+=i,s!=null&&(o.size===lt&&(ir(a,l,u),u+=c),l.set(s,u)),n.bytes=l}e.push(n.bytes),t+=n.bytes.byteLength}return Jt(e,t)}function mu(r){if(r.charAt(0)!=="/")throw new ht('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=Rt.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 ht(`Component ${o} was missing value`);e="value"}else if(e==="value"){let l={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new ht(`Component ${o} was missing value`);l.value=c.stringToValue?.(n)??n}t.push(l),n="",o="",e="protocol"}}}if(o!==""&&n!=="")throw new ht("Incomplete multiaddr");return t}function yu(r){return`/${r.flatMap(t=>{if(t.value==null)return t.name;let e=Rt.getProtocol(t.code);if(e==null)throw new ht(`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:zr(t,e)}var gd=Symbol.for("nodejs.util.inspect.custom"),Rs=Symbol.for("@multiformats/multiaddr"),bd=[53,54,55,56],Ps=class extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}};function xd(r){if(r==null&&(r="/"),bu(r))return r.getComponents();if(r instanceof Uint8Array)return du(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),mu(r);if(Array.isArray(r))return r;throw new ht("Must be a string, Uint8Array, Component[], or another Multiaddr")}var eo=class r{[Rs]=!0;#t;#e;#r;constructor(t="/",e={}){this.#t=xd(t),e.validate!==!1&&wd(this)}get bytes(){return this.#r==null&&(this.#r=pu(this.#t)),this.#r}toString(){return this.#e==null&&(this.#e=yu(this.#t)),this.#e}toJSON(){return this.toString()}toOptions(){let t,e,n,o,i="";for(let{code:a,name:c,value:l}of this.#t)a===42&&(i=`%${l??""}`),bd.includes(a)&&(e="tcp",o=443,n=`${l??""}${i}`,t=a===55?6:4),(a===6||a===273)&&(e=c==="tcp"?"tcp":"udp",o=parseInt(l??"")),(a===4||a===41)&&(e="tcp",n=`${l??""}${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=Rt.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=Rt.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 Jr(`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"?M(Y.decode(`z${n}`),"base58btc"):M(et.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){for(let t of this.#t)if(Rt.getProtocol(t.code).path)return t.value??null;return null}equals(t){return at(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(i=>i.resolvable);if(e==null)return[this];let n=gu.get(e.name);if(n==null)throw new Ps(`no available resolver for ${e.name}`);return(await n(this,t)).map(i=>gt(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)}[gd](){return`Multiaddr(${this.toString()})`}};function wd(r){r.getComponents().forEach(t=>{let e=Rt.getProtocol(t.code);t.value!=null&&e.validate?.(t.value)})}var Ix=parseInt("0xFFFF",16),Tx=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);var gu=new Map;function bu(r){return!!r?.[Rs]}function gt(r){return new eo(r)}function zt(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var ro=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 Ne(r,t,e){if(t==null)return r;if(t.aborted)return r.catch(()=>{}),Promise.reject(new ro(e?.errorMessage,e?.errorCode,e?.errorName));let n,o=new ro(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 Ls=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 Ne(this.readNext.promise,e?.signal,e)}};function no(){return new Ls}var oo=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Eu(r,t){let e=no();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 nt;return{read:async s=>{if(s?.signal?.throwIfAborted(),s?.bytes==null){let{done:c,value:l}=await Ne(n.next(),s?.signal);return c===!0?null:l}for(;o.byteLength<s.bytes;){let{value:c,done:l}=await Ne(n.next(),s?.signal);if(l===!0)throw new oo("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 io=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},so=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},ao=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Su(r,t={}){let e=Eu(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=At(t.maxDataLength));let n=t?.lengthDecoder??zr,o=t?.lengthEncoder??sr;return{read:async s=>{let a=-1,c=new nt;for(;;){c.append(await e.read({...s,bytes:1}));try{a=n(c)}catch(l){if(l instanceof RangeError)continue;throw l}if(a<0)throw new io("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new ao("message length length too long");if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new so("message length too long");return e.read({...s,bytes:a})},write:async(s,a)=>{await e.write(new nt(o(s.byteLength),s),a)},writeV:async(s,a)=>{let c=new nt(...s.flatMap(l=>[o(l.byteLength),l]));await e.write(c,a)},unwrap:()=>e.unwrap()}}function ge(r,t){let e=Su(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 Bs=1e3,vu=60*Bs,co=290,_u=15,Au=2*60*vu,Iu=1,uo=2e3,Tu=100,Os="circuit-relay-source",an=`${Fo}-circuit-relay`,Ns=`${Fo}-circuit-relay-source`,Cu=2*vu,Du=BigInt(1<<17),Nt="/libp2p/circuit/relay/0.2.0/hop",Ue="/libp2p/circuit/relay/0.2.0/stop",Pu=30*Bs,Bw=30*Bs,cn=300,Ru=4096,Lu=.001;var G;(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=()=>Re(e)}(t=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Ct((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),gr.codec().encode(o.peer,i)),o.reservation!=null&&(i.uint32(26),lo.codec().encode(o.reservation,i)),o.limit!=null&&(i.uint32(34),br.codec().encode(o.limit,i)),o.status!=null&&(i.uint32(40),K.codec().encode(o.status,i)),s.lengthDelimited!==!1&&i.ldelim()},(o,i,s={})=>{let a={},c=i==null?o.len:o.pos+i;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.type=r.Type.codec().decode(o);break}case 2:{a.peer=gr.codec().decode(o,o.uint32(),{limits:s.limits?.peer});break}case 3:{a.reservation=lo.codec().decode(o,o.uint32(),{limits:s.limits?.reservation});break}case 4:{a.limit=br.codec().decode(o,o.uint32(),{limits:s.limits?.limit});break}case 5:{a.status=K.codec().decode(o);break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>Tt(o,r.codec()),r.decode=(o,i)=>It(o,r.codec(),i)})(G||(G={}));var Lt;(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=()=>Re(e)}(t=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Ct((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),gr.codec().encode(o.peer,i)),o.limit!=null&&(i.uint32(26),br.codec().encode(o.limit,i)),o.status!=null&&(i.uint32(32),K.codec().encode(o.status,i)),s.lengthDelimited!==!1&&i.ldelim()},(o,i,s={})=>{let a={},c=i==null?o.len:o.pos+i;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.type=r.Type.codec().decode(o);break}case 2:{a.peer=gr.codec().decode(o,o.uint32(),{limits:s.limits?.peer});break}case 3:{a.limit=br.codec().decode(o,o.uint32(),{limits:s.limits?.limit});break}case 4:{a.status=K.codec().decode(o);break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>Tt(o,r.codec()),r.decode=(o,i)=>It(o,r.codec(),i)})(Lt||(Lt={}));var gr;(function(r){let t;r.codec=()=>(t==null&&(t=Ct((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:Q(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 Vr('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=>Tt(e,r.codec()),r.decode=(e,n)=>It(e,r.codec(),n)})(gr||(gr={}));var lo;(function(r){let t;r.codec=()=>(t==null&&(t=Ct((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),fo.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 Vr('Decode error - map field "addrs" had too many elements');i.addrs.push(e.bytes());break}case 3:{i.voucher=fo.codec().decode(e,e.uint32(),{limits:o.limits?.voucher});break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Tt(e,r.codec()),r.decode=(e,n)=>It(e,r.codec(),n)})(lo||(lo={}));var br;(function(r){let t;r.codec=()=>(t==null&&(t=Ct((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=>Tt(e,r.codec()),r.decode=(e,n)=>It(e,r.codec(),n)})(br||(br={}));var K;(function(r){r.UNUSED="UNUSED",r.OK="OK",r.RESERVATION_REFUSED="RESERVATION_REFUSED",r.RESOURCE_LIMIT_EXCEEDED="RESOURCE_LIMIT_EXCEEDED",r.PERMISSION_DENIED="PERMISSION_DENIED",r.CONNECTION_FAILED="CONNECTION_FAILED",r.NO_RESERVATION="NO_RESERVATION",r.MALFORMED_MESSAGE="MALFORMED_MESSAGE",r.UNEXPECTED_MESSAGE="UNEXPECTED_MESSAGE"})(K||(K={}));var Us;(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"})(Us||(Us={}));(function(r){r.codec=()=>Re(Us)})(K||(K={}));var xr;(function(r){let t;r.codec=()=>(t==null&&(t=Ct((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:Q(0),peer:Q(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=>Tt(e,r.codec()),r.decode=(e,n)=>It(e,r.codec(),n)})(xr||(xr={}));var fo;(function(r){let t;r.codec=()=>(t==null&&(t=Ct((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),xr.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:Q(0),payloadType:Q(0),signature:Q(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=xr.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=>Tt(e,r.codec()),r.decode=(e,n)=>It(e,r.codec(),n)})(fo||(fo={}));var $=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)}}),q=r=>({match:t=>{let e=r.match(t);return e===!1?t:e}}),bt=(...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}}),z=(...r)=>({match:t=>{for(let e of r){let n=e.match(t);if(n===!1)return!1;t=n}return t}});function W(...r){function t(o){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 Ad=L(421),zw=W(Ad),po=L(54),mo=L(55),yo=L(56),Ms=L(53),Hw=W(po,q(L(421))),Fw=W(mo,q(L(421))),Vw=W(yo,q(L(421))),Gw=W(bt(Ms,yo,po,mo),q(L(421))),Bu=z(L(4),q(L(43))),Ou=z(q(L(42)),L(41),q(L(43))),Ks=bt(Bu,Ou),ke=bt(Ks,Ms,po,mo,yo),Ww=W(bt(Ks,z(bt(Ms,yo,po,mo),q(L(421))))),$w=W(Bu),Zw=W(Ou),Yw=W(Ks),qs=z(ke,L(6)),un=z(ke,L(273)),jw=W(z(qs,q(L(421)))),Xw=W(un),zs=z(un,$(460),q(L(421))),go=z(un,$(461),q(L(421))),Id=bt(zs,go),Qw=W(zs),Jw=W(go),ks=bt(ke,qs,un,zs,go),Nu=bt(z(ks,$(477),q(L(421)))),t2=W(Nu),Uu=bt(z(ks,$(478),q(L(421))),z(ks,$(448),q(L(449)),$(477),q(L(421)))),e2=W(Uu),ku=z(un,$(280),q(L(466)),q(L(466)),q(L(421))),r2=W(ku),Mu=z(go,$(465),q(L(466)),q(L(466)),q(L(421))),n2=W(Mu),ho=bt(Nu,Uu,z(qs,q(L(421))),z(Id,q(L(421))),z(ke,q(L(421))),ku,Mu,L(421)),Ku=W(ho),Td=z(ho,$(290),L(421)),bo=W(Td),Cd=bt(z(ho,$(290),$(281),q(L(421))),z(ho,$(281),q(L(421))),z($(281),q(L(421)))),o2=W(Cd),Dd=bt(z(ke,L(6),$(480),q(L(421))),z(ke,$(480),q(L(421)))),i2=W(Dd),Pd=z(ke,bt(z(L(6,"443"),$(480)),z(L(6),$(443)),z(L(6),$(448),$(480)),z($(448),$(480)),$(448),$(443)),q(L(421))),s2=W(Pd),Rd=bt(z(L(777),q(L(421)))),a2=W(Rd),Ld=bt(z(L(400),q(L(421)))),c2=W(Ld);function xo(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 wo=class extends Error{constructor(t="Transfer limit error"){super(t),this.name="TransferLimitError"}},ln=class extends Error{constructor(t="Duration limit error"){super(t),this.name="DurationLimitError"}},fn=class extends Error{static name="HadEnoughRelaysError";name="HadEnoughRelaysError"},Eo=class extends Error{static name="DoubleRelayError";name="DoubleRelayError"},So=class extends Error{static name="RelayQueueFullError";name="RelayQueueFullError"};async function*qu(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 wo(`data limit of ${n} bytes exceeded`)}t.remaining-=i,yield o}}function zu(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=xo(s),c=!1,l=!1,u;n.limit?.data!=null&&(u={remaining:n.limit.data}),queueMicrotask(()=>{let f=()=>{o.log("relayed connection reached time limit"),t.abort(new ln(`duration limit of ${n.limit?.duration} ms exceeded`))};a.addEventListener("abort",f,{once:!0}),t.sink(u==null?r.source:qu(r.source,u,o)).catch(m=>{o.log.error("error while relaying streams src -> dst",m),i(m)}).finally(()=>{c=!0,l&&(a.removeEventListener("abort",f),a.clear())})}),queueMicrotask(()=>{let f=()=>{o.log("relayed connection reached time limit"),r.abort(new ln(`duration limit of ${n.limit?.duration} ms exceeded`))};a.addEventListener("abort",f,{once:!0}),r.sink(u==null?t.source:qu(t.source,u,o)).catch(m=>{o.log.error("error while relaying streams dst -> src",m),i(m)}).finally(()=>{l=!0,c&&(a.removeEventListener("abort",f),a.clear())})})}function Hs(r){let t=r*BigInt(1e3),e=new Date().getTime();return Number(t-BigInt(e))}var hn=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}},vo=W(z(Ku.matchers[0],$(290))),_o=W($(290));function Ao(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 be=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 Ao(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 Ao(this.map.values(),t=>t.key)}values(){return Ao(this.map.values(),t=>t.value)}get size(){return this.map.size}};var Fs={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Hu={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Fu=new globalThis.TextEncoder;function Bd(r,t){let e=Fs[t],n=Hu[t];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(t,n*e);return n}function Od(r,t,e){if(e.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Fs[t],o=Hu[t],i=r;for(;i.length>0;){let s=Fu.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 Vs(r,{size:t=32,utf8Buffer:e}={}){if(!Fs[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 Od(r,t,e);r=Fu.encode(r)}return Bd(r,t)}var dn={hash:r=>Number(Vs(r,{size:32})),hashV:(r,t)=>Nd(dn.hash(r,t))};function Nd(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),k(t,"base16")}var Gs=64,Ht=class{fp;h;seed;constructor(t,e,n,o=2){if(o>Gs)throw new TypeError("Invalid Fingerprint Size");let i=e.hashV(t,n),s=Q(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?at(this.fp,t.fp):!1}};function Me(r,t){return Math.floor(Math.random()*(t-r))+r}var Ke=class{contents;constructor(t){this.contents=new Array(t).fill(null)}has(t){if(!(t instanceof Ht))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof Ht))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 Ht))throw new TypeError("Invalid Fingerprint");let e=Me(0,this.contents.length-1),n=this.contents[e];return this.contents[e]=t,n}remove(t){if(!(t instanceof Ht))throw new TypeError("Invalid Fingerprint");let e=this.contents.findIndex(n=>t.equals(n));return e>-1?(this.contents[e]=null,!0):!1}};var Ud=500,pn=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??dn,this.seed=t.seed??Me(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=k(t));let e=new Ht(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 Ke(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new Ke(this.bucketSize)),this.buckets[n].add(e)||this.buckets[o].add(e))return this.count++,!0;let i=[n,o],s=i[Me(0,i.length-1)];this.buckets[s]==null&&(this.buckets[s]=new Ke(this.bucketSize));for(let a=0;a<Ud;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 Ke(this.bucketSize)),this.buckets[s].add(c)))return this.count++,!0}return!1}has(t){typeof t=="string"&&(t=k(t));let e=new Ht(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 Ht(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}},kd={1:.5,2:.84,4:.95,8:.98};function Md(r=.001){return r>.002?2:r>1e-5?4:8}function Vu(r,t=.001){let e=Md(t),n=kd[e],o=Math.round(r/n),i=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),Gs);return{filterSize:o,bucketSize:e,fingerprintSize:i}}var Io=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??dn,this.seed=t.seed??Me(0,Math.pow(2,10)),this.filterSeries=[new pn({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 pn({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 wr(r,t=.001,e){return new Io({...Vu(r,t),...e??{}})}var To=class{filter;constructor(t,e){this.filter=wr(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 Ws(r,t=.001){return new To(r,t)}var $s=class extends be{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 Zs(r){let{name:t,metrics:e}=r,n;return e!=null?n=new $s({name:t,metrics:e}):n=new be,n}var Ys=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 Gu(r,t){let e=new Ys(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 Co=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??_u,this.applyDefaultLimit=e.applyDefaultLimit!==!1,this.reservationTtl=e.reservationTtl??Au,this.defaultDurationLimit=e.defaultDurationLimit??Cu,this.defaultDataLimit=e.defaultDataLimit??Du,this.reservations=Zs({metrics:t.metrics,name:"libp2p_circuit_relay_server_reservations_total"})}reserve(t,e,n){let o=this.reservations.get(t);if(this.reservations.size>=this.maxReservations&&o==null)return{status:K.RESERVATION_REFUSED};let i=new Date(Date.now()+this.reservationTtl),s;return this.applyDefaultLimit&&(s=n??{data:this.defaultDataLimit,duration:this.defaultDurationLimit}),o!=null?(this.log("refreshing reservation for client %p",t),o.signal.reset(this.reservationTtl)):(this.log("creating new reservation for client %p",t),o={addr:e,expiry:i,limit:s,signal:Gu(this.reservationTtl)}),this.reservations.set(t,o),o.signal.addEventListener("abort",()=>{this.reservations.delete(t)}),{status:K.OK,expire:Math.round(i.getTime()/1e3)}}removeReservation(t){this.reservations.delete(t)}get(t){return this.reservations.get(t)}clear(){this.reservations.clear()}};var Do=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 xr.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 Wu=r=>r.protoCodes().includes(co),Kd={maxOutboundStopStreams:cn},js=class extends Bt{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??Pu,this.maxInboundHopStreams=e.maxInboundHopStreams,this.maxOutboundHopStreams=e.maxOutboundHopStreams,this.maxOutboundStopStreams=e.maxOutboundStopStreams??Kd.maxOutboundStopStreams,this.reservationStore=new Co(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(Nt,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(Nt),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=ge(e);try{let i=await o.pb(G).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(G).write({type:G.Type.STATUS,status:K.MALFORMED_MESSAGE},n),e.abort(i)}}async handleHopProtocol({stream:t,request:e,connection:n},o){switch(this.log("received hop message"),e.type){case G.Type.RESERVE:await this.handleReserve({stream:t,request:e,connection:n},o);break;case G.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(G).write({type:G.Type.STATUS,status:K.UNEXPECTED_MESSAGE})}}async handleReserve({stream:t,connection:e},n){let o=t.pb(G);if(this.log("hop reserve request from %p",e.remotePeer),Wu(e.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",e.remotePeer),await o.write({type:G.Type.STATUS,status:K.PERMISSION_DENIED},n);return}if(await this.connectionGater.denyInboundRelayReservation?.(e.remotePeer)===!0){this.log.error("reservation for %p denied by connection gater",e.remotePeer),await o.write({type:G.Type.STATUS,status:K.PERMISSION_DENIED},n);return}let i=this.reservationStore.reserve(e.remotePeer,e.remoteAddr);try{if(i.status!==K.OK){await o.write({type:G.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:{[Os]:{value:1,ttl:s},[Ns]:{value:1,ttl:s}}})}await o.write({type:G.Type.STATUS,status:K.OK,reservation:await this.makeReservation(e.remotePeer,BigInt(i.expire??0)),limit:this.reservationStore.get(e.remotePeer)?.limit},n),this.log("sent confirmation response to %s",e.remotePeer)}catch(s){this.log.error("failed to send confirmation response to %p - %e",e.remotePeer,s),this.reservationStore.removeReservation(e.remotePeer);try{await this.peerStore.merge(e.remotePeer,{tags:{[Os]:void 0,[Ns]: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 Qr.seal(new Do({peer:t,relay:this.peerId,expiration:e}),this.privateKey);return{addrs:n,expire:e,voucher:{publicKey:Vt(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(G);if(Wu(n.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",n.remotePeer),await i.write({type:G.Type.STATUS,status:K.PERMISSION_DENIED},o);return}this.log("hop connect request from %p",n.remotePeer);let s;try{if(e.peer==null)throw this.log.error("no peer info in hop connect request"),new Error("no peer info in request");e.peer.addrs.forEach(gt),s=lr(Ft(e.peer.id))}catch(m){this.log.error("invalid hop connect request via peer %p %s",n.remotePeer,m),await i.write({type:G.Type.STATUS,status:K.MALFORMED_MESSAGE},o);return}let a=this.reservationStore.get(s);if(a==null){this.log.error("hop connect denied for destination peer %p not having a reservation for %p with status %s",s,n.remotePeer,K.NO_RESERVATION),await i.write({type:G.Type.STATUS,status:K.NO_RESERVATION},o);return}if(await this.connectionGater.denyOutboundRelayedConnection?.(n.remotePeer,s)===!0){this.log.error("hop connect for %p to %p denied by connection gater",n.remotePeer,s),await i.write({type:G.Type.STATUS,status:K.PERMISSION_DENIED},o);return}let c=this.connectionManager.getConnections(s);if(c.length===0){this.log("hop connect denied for destination peer %p not having a connection for %p as there is no destination connection",s,n.remotePeer),await i.write({type:G.Type.STATUS,status:K.NO_RESERVATION},o);return}let l=c[0],u=await this.stopHop({connection:l,request:{type:Lt.Type.CONNECT,peer:{id:n.remotePeer.toMultihash().bytes,addrs:[]},limit:a?.limit}},o);if(u==null){this.log.error("failed to open stream to destination peer %p",l?.remotePeer),await i.write({type:G.Type.STATUS,status:K.CONNECTION_FAILED},o);return}await i.write({type:G.Type.STATUS,status:K.OK,limit:a?.limit},o);let f=t.unwrap();this.log("connection from %p to %p established - merging streams",n.remotePeer,s),zu(f,u,this.shutdownController.signal,a,{log:this.log})}async stopHop({connection:t,request:e},n){this.log("starting circuit relay v2 stop request to %s",t.remotePeer);let o=await t.newStream([Ue],{maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0,...n}),i=ge(o),s=i.pb(Lt);await s.write(e,n);let a;try{a=await s.read(n)}catch{this.log.error("error parsing stop message response from %p",t.remotePeer)}if(a==null){this.log.error("could not read response from %p",t.remotePeer),await o.close(n);return}if(a.status===K.OK)return this.log("stop request to %p was successful",t.remotePeer),i.unwrap();this.log("stop request failed with code %d",a.status),await o.close(n)}get reservations(){return this.reservationStore.reservations}};function $u(r={}){return t=>new js(t,r)}function qd(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 Zu=qd;function zd(r){return r[Symbol.asyncIterator]!=null}function Yu(r){return r?.then!=null}function Hd(r,t){let e=0;if(zd(r))return async function*(){for await(let c of r){let l=t(c,e++);Yu(l)&&await l,yield c}}();let n=Zu(r),{value:o,done:i}=n.next();if(i===!0)return function*(){}();if(typeof t(o,e++)?.then=="function")return async function*(){yield o;for(let c of n){let l=t(c,e++);Yu(l)&&await l,yield c}}();let a=t;return function*(){yield o;for(let c of n)a(c,e++),yield c}()}var ju=Hd;var Po=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}},Er=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new Po(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 Po(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let e=this.tail.next;this.tail.next=null,this.tail=e,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var Qs=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function Ro(r={}){return Fd(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 Fd(r,t){t=t??{};let e=t.onEnd,n=new Er,o,i,s,a=zt(),c=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((h,S)=>{i=C=>{i=null,n.push(C);try{h(r(n))}catch(_){S(_)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=zt()})}},l=h=>i!=null?i(h):(n.push(h),o),u=h=>(n=new Er,i!=null?i({error:h}):(n.push({error:h}),o)),f=h=>{if(s)return o;if(t?.objectMode!==!0&&h?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:h})},m=h=>s?o:(s=!0,h!=null?u(h):l({done:!0})),p=()=>(n=new Er,m(),{done:!0}),b=h=>(m(h),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:p,throw:b,push:f,end:m,get readableLength(){return n.size},onEmpty:async h=>{let S=h?.signal;if(S?.throwIfAborted(),n.isEmpty())return;let C,_;S!=null&&(C=new Promise((B,g)=>{_=()=>{g(new Qs)},S.addEventListener("abort",_)}));try{await Promise.race([a.promise,C])}finally{_!=null&&S!=null&&S?.removeEventListener("abort",_)}}},e==null)return o;let x=o;return o={[Symbol.asyncIterator](){return this},next(){return x.next()},throw(h){return x.throw(h),e!=null&&(e(h),e=void 0),{done:!0}},return(){return x.return(),e!=null&&(e(),e=void 0),{done:!0}},push:f,end(h){return x.end(h),e!=null&&(e(h),e=void 0),o},get readableLength(){return x.readableLength},onEmpty:h=>x.onEmpty(h)},o}function Vd(r){return r[Symbol.asyncIterator]!=null}async function Gd(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*Wd(r){let t=new AbortController,e=no();Gd(r,e,t.signal).catch(()=>{});try{yield*e}finally{t.abort()}}function*$d(r){for(let t of r)yield*t}function Zd(...r){let t=[];for(let e of r)Vd(e)||t.push(e);return t.length===r.length?$d(t):Wd(r)}var Xu=Zd;function Qu(r,...t){if(r==null)throw new Error("Empty pipeline");if(Js(r)){let n=r;r=()=>n.source}else if(tl(r)||Ju(r)){let n=r;r=()=>n}let e=[r,...t];if(e.length>1&&Js(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++)Js(e[n])&&(e[n]=jd(e[n]));return Yd(...e)}var Yd=(...r)=>{let t;for(;r.length>0;)t=r.shift()(t);return t},Ju=r=>r?.[Symbol.asyncIterator]!=null,tl=r=>r?.[Symbol.iterator]!=null,Js=r=>r==null?!1:r.sink!=null&&r.source!=null,jd=r=>t=>{let e=r.sink(t);if(e?.then!=null){let n=Ro({objectMode:!0});e.then(()=>{n.end()},s=>{n.end(s)});let o,i=r.source;if(Ju(i))o=async function*(){yield*i,n.end()};else if(tl(i))o=function*(){yield*i,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Xu(n,o())}return r.source};function ta(r){let{stream:t,remoteAddr:e,logger:n,onDataRead:o,onDataWrite:i}=r,s=n.forComponent("libp2p:stream:converter"),a=!1,c=!1,l=t.close.bind(t);t.close=async b=>{await l(b),p(!0)};let u=t.abort.bind(t);t.abort=b=>{u(b),p(!0)};let f=t.sink.bind(t);t.sink=async b=>{try{await f(Qu(b,x=>ju(x,h=>i?.(h))))}catch(x){x.type!=="aborted"&&s.error("%s error in sink",e,x)}finally{c=!0,p()}};let m={log:s,sink:t.sink,source:async function*(){try{for await(let b of t.source)o?.(b),yield b}finally{a=!0,p()}}(),remoteAddr:e,timeline:{open:Date.now(),close:void 0},close:t.close,abort:t.abort};function p(b){b===!0&&(a=!0,c=!0),a&&c&&m.timeline.close==null&&(m.timeline.close=Date.now())}return m}var xe=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var ea=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=e??"ABORT_ERR"}};async function Lo(r,t,e,n){let o=new ea(n?.errorMessage,n?.errorCode);return e?.aborted===!0?Promise.reject(o):new Promise((i,s)=>{function a(){e?.removeEventListener("abort",u),r.removeEventListener(t,c),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,l)}let c=f=>{try{if(n?.filter?.(f)===!1)return}catch(m){a(),s(m);return}a(),i(f)},l=f=>{a(),s(f.detail)},u=()=>{a(),s(o)};e?.addEventListener("abort",u),r.addEventListener(t,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,l)})}function ra(r,t){let e,n=function(){let o=function(){e=void 0,r()};clearTimeout(e),e=setTimeout(o,t)};return n.start=()=>{},n.stop=()=>{clearTimeout(e)},n}var Bo=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};var Oo=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 jt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Xd(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var No=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=Xd(),this.status="queued",this.fn=t,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(t){this.controller.abort(t)}onAbort(){this.recipients.reduce((e,n)=>e&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new jt),this.cleanup())}async join(t={}){let e=new Oo(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 Ne(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 Uo=class extends Bt{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=ra(this.emitEmpty.bind(this),1),this.emitIdle=ra(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let t;for(let e of this.queue)if(e.status==="queued"){t=e;break}return t==null?!1:(this.safeDispatchEvent("active"),this.pending++,t.run().finally(()=>{for(let e=0;e<this.queue.length;e++)if(this.queue[e]===t){this.queue.splice(e,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(t){this.queue.push(t),this.sort!=null&&this.queue.sort(this.sort)}async add(t,e){if(e?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Bo;let n=new No(t,e);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(e).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("error",{detail:o}),this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(t=>{t.abort(new jt)}),this.clear()}async onEmpty(t){this.size!==0&&await Lo(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await Lo(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await Lo(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=Ro({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),e.end(c)},o=c=>{c.detail!=null&&e.push(c.detail)},i=c=>{n(c.detail)},s=()=>{n()},a=()=>{n(new jt("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("error",i),this.addEventListener("idle",s),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("completed",o),this.removeEventListener("error",i),this.removeEventListener("idle",s),t?.signal?.removeEventListener("abort",a),n()}}};var Sr=class extends Uo{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};var ko=class extends Bt{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(Nt,{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(Nt)],orders:[()=>Math.random()<.5?1:-1,(n,o)=>{let i=el(n),s=el(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 Sr({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=xo([AbortSignal.timeout(5e3),e]);try{await this.components.connectionManager.openConnection(t,{signal:n})}finally{n.clear()}}};function el(r){let t=r.metadata.get("last-dial-success");return t==null?0:new Date(M(t)).getTime()}var na=class extends Bt{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??uo,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(_o.exactMatch(t))this.log("searching for circuit relay servers"),this.reservationId=this.reservationStore.reserveRelay();else if(vo.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 Ee(`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=>gt(e).encapsulate("/p2p-circuit")),this.listeningAddrs.forEach(e=>{this.addressManager.confirmObservedAddr(e,{type:"transport"})}),queueMicrotask(()=>{this.safeDispatchEvent("listening")})}};function rl(r){return new na(r)}var nl="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var ol=(r=21)=>{let t="",e=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)t+=nl[e[r]&63];return t};var Qd=60*1e3*10,Jd=60*1e3*5,tp=30*1e3,Mo=class extends Bt{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 be,this.pendingReservations=[],this.maxReservationQueueLength=e?.maxReservationQueueLength??Tu,this.reservationCompletionTimeout=e?.reservationCompletionTimeout??uo,this.started=!1,this.relayFilter=wr(100),this.reserveQueue=new Sr({concurrency:e?.reservationConcurrency??Iu,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(an)]});this.log("removing tag from %d old relays",t.length),await Promise.all(t.map(async e=>{await this.peerStore.merge(e.id,{tags:{[an]: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=ol();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 Ee("Cannot use self as relay");if(this.reserveQueue.size>this.maxReservationQueueLength)throw new So("The reservation queue is full");let n=this.reserveQueue.find(t);if(n!=null)return this.log.trace("potential relay peer %p is already in the reservation queue",t),n.join();if(this.relayFilter.has(t.toMultihash().bytes))throw new Ee("The relay was previously invalid");return this.log.trace("try to reserve relay slot with %p",t),this.reserveQueue.add(async()=>{let o=Date.now();try{let i=this.reservations.get(t);if(i!=null){let b=this.connectionManager.getConnections(t),x=!1;if(b.length===0&&this.log("already have relay reservation with %p but we are no longer connected",t),b.map(h=>h.id).includes(i.connection)&&(this.log("already have relay reservation with %p and the original connection is still open",t),x=!0),x&&Hs(i.reservation.expire)>Qd)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 fn("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(bo.matches(a.remoteAddr))throw new Eo("not creating reservation over relayed connection");let c=await this.#t(a,{signal:s}),l=Hs(c.expire);this.log("created reservation on relay peer %p, expiry date is %s",t,new Date(Date.now()+l).toString());let u=Math.min(Math.max(l-Jd,tp),Math.pow(2,31)-1),f=setTimeout(()=>{this.log("refresh reservation to relay %p",t),this.addRelay(t,e).catch(async b=>{this.log.error("could not refresh reservation to relay %p - %e",t,b),await this.#e(t)}).catch(b=>{this.log.error("could not remove expired reservation to relay %p - %e",t,b)})},u),m;if(e==="discovered"){let b=this.pendingReservations.pop();if(b==null)throw new fn("Made reservation on relay but did not need any more discovered relays");m={timeout:f,reservation:c,type:e,connection:a.id,id:b}}else m={timeout:f,reservation:c,type:e,connection:a.id};this.reservations.set(t,m),await this.peerStore.merge(t,{tags:{[an]:{value:1,ttl:l}}}),this.#r();let p={relay:t,details:m};return this.safeDispatchEvent("relay:created-reservation",{detail:p}),p}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(Nt,e),i=ge(n).pb(G);this.log.trace("send RESERVE to %p",t.remotePeer),await i.write({type:G.Type.RESERVE},e);let s;try{this.log.trace("reading response from %p",t.remotePeer),s=await i.read(e)}catch(c){throw n.abort(c),c}finally{n.status!=="closed"&&await n.close(e)}if(this.log.trace("read response %o",s),s.status===K.OK&&s.reservation!=null){let c=new Set;c.add(t.remoteAddr.toString());for(let l of s.reservation.addrs){let u=gt(l);u.getPeerId()==null&&(u=u.encapsulate(`/p2p/${t.remotePeer}`)),u=gt(u.toString().replace(`/p2p/${t.remotePeer}/p2p/${t.remotePeer}`,`/p2p/${t.remotePeer}`)),c.add(u.toString())}return s.reservation.addrs=[...c].map(l=>gt(l).bytes),s.reservation}let a=`reservation failed with status ${s.status??"undefined"}`;throw this.log.error(a),new Error(a)}async#e(t){let e=this.reservations.get(t);e!=null&&(this.log("removing relay reservation with %p from local store",t),clearTimeout(e.timeout),this.reservations.delete(t),e.type==="discovered"&&this.pendingReservations.push(e.id),await this.peerStore.merge(t,{tags:{[an]: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=wr(100),this.log("not discovered enough relays %d/%d",this.reservations.size,this.pendingReservations.length),this.safeDispatchEvent("relay:not-enough-relays")}};var ep=r=>{if(r.peer==null)return!1;try{r.peer.addrs.forEach(gt)}catch{return!1}return!0},il={maxInboundStopStreams:cn,maxOutboundStopStreams:cn,stopTimeout:3e4},Ko=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??il.maxInboundStopStreams,this.maxOutboundStopStreams=e.maxOutboundStopStreams??il.maxOutboundStopStreams,this.shutdownController=new AbortController,this.discovery=new ko(t,{filter:e.discoveryFilter??Ws(Ru,Lu)}),this.discovery.addEventListener("relay:discover",n=>{this.reservationStore.addRelay(n.detail,"discovered").catch(o=>{o.name!=="HadEnoughRelaysError"&&o.name!=="RelayQueueFullError"&&this.log.error("could not add discovered relay %p",n.detail,o)})}),this.reservationStore=new Mo(t,e),this.reservationStore.addEventListener("relay:not-enough-relays",()=>{this.discovery?.startDiscovery()}),this.reservationStore.addEventListener("relay:found-enough-relays",()=>{this.discovery?.stopDiscovery()}),this.started=!1}[Symbol.toStringTag]="@libp2p/circuit-relay-v2-transport";[ua]=["@libp2p/transport","@libp2p/circuit-relay-v2-transport"];get[la](){return this.discovery!=null?["@libp2p/identify"]:[]}[ia]=!0;isStarted(){return this.started}async start(){this.shutdownController=new AbortController,this.shutdownController.signal,await this.registrar.handle(Ue,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 aa(this.discovery,this.reservationStore),this.started=!0}async stop(){this.shutdownController.abort(),await ca(this.discovery,this.reservationStore),await this.registrar.unhandle(Ue),this.started=!1}async dial(t,e){if(t.protoCodes().filter(p=>p===co).length!==1){let p="Invalid circuit relay address";throw this.log.error(p,t),new _r(p)}let n=t.toString().split("/p2p-circuit"),o=gt(n[0]),i=gt(n[n.length-1]),s=o.getPeerId(),a=i.getPeerId();if(s==null||a==null){let p=`ircuit relay dial to ${t.toString()} failed as address did not have both relay and destination PeerIDs`;throw this.log.error(`c${p}`),new _r(`C${p}`)}let c=ds(s),l=ds(a),f=this.connectionManager.getConnections(c)[0];f==null?(await this.peerStore.merge(c,{multiaddrs:[o]}),e.onProgress?.(new xe("circuit-relay:open-connection")),f=await this.connectionManager.openConnection(c,e)):e.onProgress?.(new xe("circuit-relay:reuse-connection"));let m;try{e.onProgress?.(new xe("circuit-relay:open-hop-stream")),m=await f.newStream(Nt,e);let p=ge(m),b=p.pb(G);e.onProgress?.(new xe("circuit-relay:write-connect-message")),await b.write({type:G.Type.CONNECT,peer:{id:l.toMultihash().bytes,addrs:[gt(i).bytes]}},e),e.onProgress?.(new xe("circuit-relay:read-connect-response"));let x=await b.read(e);if(x.status!==K.OK)throw new gn(`failed to connect via relay with status ${x?.status?.toString()??"undefined"}`);let h=new hn(x.limit),S=ta({stream:p.unwrap(),remoteAddr:t,localAddr:o.encapsulate(`/p2p-circuit/p2p/${this.peerId.toString()}`),logger:this.logger,onDataRead:h.onData,onDataWrite:h.onData});return this.log("new outbound relayed connection %a",S.remoteAddr),await this.upgrader.upgradeOutbound(S,{...e,limits:h.getLimits()})}catch(p){throw this.log.error("circuit relay dial to destination %p via relay %p failed",l,c,p),m?.abort(p),p}}createListener(t){return rl({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=>vo.exactMatch(e)||_o.exactMatch(e))}dialFilter(t){return t=Array.isArray(t)?t:[t],t.filter(e=>bo.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=ge(e).pb(Lt),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:Lt.Type.STATUS,status:K.MALFORMED_MESSAGE},{signal:n}),await e.close();return}if(i.type!==Lt.Type.CONNECT){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await o.write({type:Lt.Type.STATUS,status:K.UNEXPECTED_MESSAGE},{signal:n}),await e.close();return}if(!ep(i)){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await o.write({type:Lt.Type.STATUS,status:K.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}let s=lr(Ft(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:Lt.Type.STATUS,status:K.PERMISSION_DENIED},{signal:n}),await e.close({signal:n});return}this.log.trace("sending success response to %p",t.remotePeer),await o.write({type:Lt.Type.STATUS,status:K.OK},{signal:n});let a=new hn(i.limit),c=t.remoteAddr.encapsulate(`/p2p-circuit/p2p/${s.toString()}`),l=this.addressManager.getAddresses()[0],u=ta({stream:o.unwrap().unwrap(),remoteAddr:c,localAddr:l,logger:this.logger,onDataRead:a.onData,onDataWrite:a.onData});this.log("new inbound relayed connection %a",u.remoteAddr),await this.upgrader.upgradeInbound(u,{limits:a.getLimits(),signal:n}),this.log("%s connection %a upgraded","inbound",u.remoteAddr)}};function sl(r={}){return t=>new Ko(t,r)}return fl(rp);})();
|
2
|
+
"use strict";var Libp2PCircuitRelayV2=(()=>{var Yo=Object.defineProperty;var Ul=Object.getOwnPropertyDescriptor;var Ml=Object.getOwnPropertyNames;var kl=Object.prototype.hasOwnProperty;var At=(r,t)=>{for(var e in t)Yo(r,e,{get:t[e],enumerable:!0})},Kl=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ml(t))!kl.call(r,o)&&o!==e&&Yo(r,o,{get:()=>t[o],enumerable:!(n=Ul(t,o))||n.enumerable});return r};var ql=r=>Kl(Yo({},"__esModule",{value:!0}),r);var Fp={};At(Fp,{RELAY_V2_HOP_CODEC:()=>Vt,RELAY_V2_STOP_CODEC:()=>tr,circuitRelayServer:()=>Vp,circuitRelayTransport:()=>Hp});var Tt=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:s})=>s!==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 Jt=class extends Error{static name="AbortError";constructor(t="The operation was aborted"){super(t),this.name="AbortError"}};var it=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},er=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}};var Sn=class extends Error{static name="StreamResetError";constructor(t="The stream has been reset"){super(t),this.name="StreamResetError"}};var Oe=class extends Error{static name="StreamStateError";constructor(t="The stream is in an invalid state"){super(t),this.name="StreamStateError"}},Mr=class extends Error{static name="StreamBufferError";constructor(t="The stream buffer was full"){super(t),this.name="StreamBufferError"}};var vn=class extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}},_n=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}};var An=class extends Error{static name="InvalidMessageError";constructor(t="Invalid message"){super(t),this.name="InvalidMessageError"}};var Tn=class extends Error{static name="DialError";constructor(t="Dial error"){super(t),this.name="DialError"}},Ne=class extends Error{static name="ListenError";constructor(t="Listen error"){super(t),this.name="ListenError"}};var rr=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var In=class extends Event{data;constructor(t,e){super("message",e),this.data=t}},nr=class extends Event{error;local;constructor(t,e,n){super("close",n),this.error=e,this.local=t}},Cn=class extends nr{constructor(t,e){super(!0,t,e)}},Dn=class extends nr{constructor(t,e){super(!1,t,e)}};var Xo=Symbol.for("@libp2p/peer-id");var jo="keep-alive";function Ma(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function ka(...r){let t=[];for(let e of r)Ma(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 Ka(...r){let t=[];for(let e of r)Ma(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 Va=Symbol.for("@libp2p/transport");var qa;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(qa||(qa={}));var Ha=Symbol.for("@libp2p/service-capabilities"),Fa=Symbol.for("@libp2p/service-dependencies");var rs={};At(rs,{base58btc:()=>et,base58flickr:()=>Wl});var _m=new Uint8Array(0);function za(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function te(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function Ga(r){return new TextEncoder().encode(r)}function $a(r){return new TextDecoder().decode(r)}function Vl(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 s=r.charAt(o),i=s.charCodeAt(0);if(e[i]!==255)throw new TypeError(s+" is ambiguous");e[i]=o}var a=r.length,c=r.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function h(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)*l+1>>>0,C=new Uint8Array(w);g!==_;){for(var P=p[g],q=0,K=w-1;(P!==0||q<S)&&K!==-1;K--,q++)P+=256*C[K]>>>0,C[K]=P%a>>>0,P=P/a>>>0;if(P!==0)throw new Error("Non-zero carry");S=q,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 f(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 P=0,q=_-1;(C!==0||P<g)&&q!==-1;q--,P++)C+=a*w[q]>>>0,w[q]=C%256>>>0,C=C/256>>>0;if(C!==0)throw new Error("Non-zero carry");g=P,x++}if(p[x]!==" "){for(var K=_-g;K!==_&&w[K]===0;)K++;for(var N=new Uint8Array(S+(_-K)),E=S;K!==_;)N[E++]=w[K++];return N}}}function d(p){var x=f(p);if(x)return x;throw new Error(`Non-${t} character`)}return{encode:h,decodeUnsafe:f,decode:d}}var Hl=Vl,Fl=Hl,Za=Fl;var Qo=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")}},Jo=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 Ya(this,t)}},ts=class{decoders;constructor(t){this.decoders=t}or(t){return Ya(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 Ya(r,t){return new ts({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var es=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 Qo(t,e,n),this.decoder=new Jo(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function or({name:r,prefix:t,encode:e,decode:n}){return new es(r,t,e,n)}function we({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=Za(e,r);return or({prefix:t,name:r,encode:n,decode:s=>te(o(s))})}function zl(r,t,e,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*e/8|0),i=0,a=0,c=0;for(let u=0;u<o;++u){let l=t[r[u]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<e|l,i+=e,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=e||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function Gl(r,t,e){let n=t[t.length-1]==="=",o=(1<<e)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>e;)i-=e,s+=t[o&a>>i];if(i!==0&&(s+=t[o&a<<e-i]),n)for(;(s.length*e&7)!==0;)s+="=";return s}function $l(r){let t={};for(let e=0;e<r.length;++e)t[r[e]]=e;return t}function at({name:r,prefix:t,bitsPerChar:e,alphabet:n}){let o=$l(n);return or({prefix:t,name:r,encode(s){return Gl(s,n,e)},decode(s){return zl(s,o,e,r)}})}var et=we({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Wl=we({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ns={};At(ns,{base32:()=>xe,base32hex:()=>jl,base32hexpad:()=>Jl,base32hexpadupper:()=>tf,base32hexupper:()=>Ql,base32pad:()=>Yl,base32padupper:()=>Xl,base32upper:()=>Zl,base32z:()=>ef});var xe=at({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Zl=at({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Yl=at({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Xl=at({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),jl=at({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Ql=at({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Jl=at({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),tf=at({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),ef=at({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var os={};At(os,{base36:()=>kr,base36upper:()=>rf});var kr=we({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),rf=we({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var nf=Qa,Xa=128,of=127,sf=~of,af=Math.pow(2,31);function Qa(r,t,e){t=t||[],e=e||0;for(var n=e;r>=af;)t[e++]=r&255|Xa,r/=128;for(;r&sf;)t[e++]=r&255|Xa,r>>>=7;return t[e]=r|0,Qa.bytes=e-n+1,t}var cf=ss,uf=128,ja=127;function ss(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw ss.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&ja)<<o:(i&ja)*Math.pow(2,o),o+=7}while(i>=uf);return ss.bytes=s-n,e}var lf=Math.pow(2,7),ff=Math.pow(2,14),hf=Math.pow(2,21),df=Math.pow(2,28),pf=Math.pow(2,35),mf=Math.pow(2,42),yf=Math.pow(2,49),gf=Math.pow(2,56),bf=Math.pow(2,63),wf=function(r){return r<lf?1:r<ff?2:r<hf?3:r<df?4:r<pf?5:r<mf?6:r<yf?7:r<gf?8:r<bf?9:10},xf={encode:nf,decode:cf,encodingLength:wf},Ef=xf,Kr=Ef;function qr(r,t=0){return[Kr.decode(r,t),Kr.decode.bytes]}function sr(r,t,e=0){return Kr.encode(r,t,e),t}function ir(r){return Kr.encodingLength(r)}function Wt(r,t){let e=t.byteLength,n=ir(r),o=n+ir(e),s=new Uint8Array(o+e);return sr(r,s,0),sr(e,s,n),s.set(t,o),new ar(r,e,t,s)}function Zt(r){let t=te(r),[e,n]=qr(t),[o,s]=qr(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new ar(e,o,i,t)}function Ja(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&za(r.bytes,e.bytes)}}var ar=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};function tc(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return vf(e,is(r),t??et.encoder);default:return _f(e,is(r),t??xe.encoder)}}var ec=new WeakMap;function is(r){let t=ec.get(r);if(t==null){let e=new Map;return ec.set(r,e),e}return t}var lt=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!==Vr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==Af)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&&Ja(t.multihash,n.multihash)}toString(t){return tc(this,t)}toJSON(){return{"/":tc(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:s,bytes:i}=e;return new r(n,o,s,i??rc(n,o,s.bytes))}else if(e[Tf]===!0){let{version:n,multihash:o,code:s}=e,i=Zt(o);return r.create(n,s,i)}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!==Vr)throw new Error(`Version 0 CID must use dag-pb (code: ${Vr}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=rc(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,Vr,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,o=te(t.subarray(n,n+e.multihashSize));if(o.byteLength!==e.multihashSize)throw new Error("Incorrect length");let s=o.subarray(e.multihashSize-e.digestSize),i=new ar(e.multihashCode,e.digestSize,s,o);return[e.version===0?r.createV0(i):r.createV1(e.codec,i),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[h,f]=qr(t.subarray(e));return e+=f,h},o=n(),s=Vr;if(o===18?(o=0,e=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=e,a=n(),c=n(),u=e+c,l=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(t,e){let[n,o]=Sf(t,e),s=r.decode(o);if(s.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return is(s).set(n,t),s}};function Sf(r,t){switch(r[0]){case"Q":{let e=t??et;return[et.prefix,e.decode(`${et.prefix}${r}`)]}case et.prefix:{let e=t??et;return[et.prefix,e.decode(r)]}case xe.prefix:{let e=t??xe;return[xe.prefix,e.decode(r)]}case kr.prefix:{let e=t??kr;return[kr.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 vf(r,t,e){let{prefix:n}=e;if(n!==et.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let o=t.get(n);if(o==null){let s=e.encode(r).slice(1);return t.set(n,s),s}else return o}function _f(r,t,e){let{prefix:n}=e,o=t.get(n);if(o==null){let s=e.encode(r);return t.set(n,s),s}else return o}var Vr=112,Af=18;function rc(r,t,e){let n=ir(r),o=n+ir(t),s=new Uint8Array(o+e.byteLength);return sr(r,s,0),sr(t,s,n),s.set(e,o),s}var Tf=Symbol.for("@ipld/js-cid/CID");var as={};At(as,{identity:()=>Ht});var nc=0,If="identity",oc=te;function Cf(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(nc,oc(r))}var Ht={code:nc,name:If,encode:oc,digest:Cf};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 rt(r=0){return new Uint8Array(r)}function It(r=0){return new Uint8Array(r)}function re(r,t){t==null&&(t=r.reduce((o,s)=>o+s.length,0));let e=It(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}var ic=Symbol.for("@achingbrain/uint8arraylist");function sc(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?.[ic]}var J=class r{bufs;length;[ic]=!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=sc(this.bufs,t);return e.buf[e.index]}set(t,e){let n=sc(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 re(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:re(n,o)}sublist(t,e){let{bufs:n,length:o}=this._subList(t,e),s=new r;return s.length=o,s.bufs=[...n],s}_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 s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,t>=c)continue;let u=t>=a&&t<c,l=e>a&&e<=c;if(u&&l){if(t===a&&e===c){n.push(i);break}let h=t-a;n.push(i.subarray(h,h+(e-t)));break}if(u){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(l){if(e===c){n.push(i);break}n.push(i.subarray(0,e-a));break}n.push(i)}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 s=256,i=new Int32Array(s);for(let h=0;h<s;h++)i[h]=-1;for(let h=0;h<o;h++)i[n[h]]=h;let a=i,c=this.byteLength-n.byteLength,u=n.byteLength-1,l;for(let h=e;h<=c;h+=l){l=0;for(let f=u;f>=0;f--){let d=this.get(h+f);if(n[f]!==d){l=Math.max(1,f-a[d]);break}}if(l===0)return h}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=It(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=rt(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=rt(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=rt(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=It(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=rt(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=rt(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=rt(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=rt(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=rt(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,s)=>o+s.byteLength,0)),n.length=e,n}};var cs={};At(cs,{base10:()=>Df});var Df=we({prefix:"9",name:"base10",alphabet:"0123456789"});var us={};At(us,{base16:()=>Lf,base16upper:()=>Bf});var Lf=at({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Bf=at({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var ls={};At(ls,{base2:()=>Rf});var Rf=at({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var fs={};At(fs,{base256emoji:()=>Mf});var ac=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=ac.reduce((r,t,e)=>(r[e]=t,r),[]),Of=ac.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function Nf(r){return r.reduce((t,e)=>(t+=Pf[e],t),"")}function Uf(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=Of[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var Mf=or({prefix:"\u{1F680}",name:"base256emoji",encode:Nf,decode:Uf});var ds={};At(ds,{base64:()=>kf,base64pad:()=>Kf,base64url:()=>hs,base64urlpad:()=>qf});var kf=at({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Kf=at({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),hs=at({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),qf=at({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ps={};At(ps,{base8:()=>Vf});var Vf=at({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var ms={};At(ms,{identity:()=>Hf});var Hf=or({prefix:"\0",name:"identity",encode:r=>$a(r),decode:r=>Ga(r)});var a0=new TextEncoder,c0=new TextDecoder;var bs={};At(bs,{sha256:()=>cr,sha512:()=>$f});var Gf=20;function gs({name:r,code:t,encode:e,minDigestLength:n,maxDigestLength:o}){return new ys(r,t,e,n,o)}var ys=class{name;code;encode;minDigestLength;maxDigestLength;constructor(t,e,n,o,s){this.name=t,this.code=e,this.encode=n,this.minDigestLength=o??Gf,this.maxDigestLength=s}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?cc(n,this.code,e?.truncate):n.then(o=>cc(o,this.code,e?.truncate))}else throw Error("Unknown type, must be binary type")}};function cc(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 lc(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var cr=gs({name:"sha2-256",code:18,encode:lc("SHA-256")}),$f=gs({name:"sha2-512",code:19,encode:lc("SHA-512")});var Hr={...ms,...ls,...ps,...cs,...us,...ns,...os,...rs,...ds,...fs},x0={...bs,...as};function hc(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var fc=hc("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),ws=hc("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=It(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),Wf={utf8:fc,"utf-8":fc,hex:Hr.base16,latin1:ws,ascii:ws,binary:ws,...Hr},Rn=Wf;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 z(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),xs=parseInt("10000000",2),Yf=parseInt("01111111",2),dc={0:Fr,1:Fr,2:Xf,3:Jf,4:th,5:Qf,6:jf,16:Fr,22:Fr,48:Fr};function ne(r,t={offset:0}){let e=r[t.offset]&Zf;if(t.offset++,dc[e]!=null)return dc[e](r,t);throw new Error("No decoder for tag "+e)}function zr(r,t){let e=0;if((r[t.offset]&xs)===xs){let n=r[t.offset]&Yf,o="0x";t.offset++;for(let s=0;s<n;s++,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 Fr(r,t){zr(r,t);let e=[];for(;!(t.offset>=r.byteLength);){let n=ne(r,t);if(n===null)break;e.push(n)}return e}function Xf(r,t){let e=zr(r,t),n=t.offset,o=t.offset+e,s=[];for(let i=n;i<o;i++)i===n&&r[i]===0||s.push(r[i]);return t.offset+=e,Uint8Array.from(s)}function jf(r,t){let e=zr(r,t),n=t.offset+e,o=r[t.offset];t.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,c=[];for(;t.offset<n;){let u=r[t.offset];if(t.offset++,c.push(u&127),u<128){c.reverse();let l=0;for(let h=0;h<c.length;h++)l+=c[h]<<h*7;a+=`.${l}`,c=[]}}return a}function Qf(r,t){return t.offset++,null}function Jf(r,t){let e=zr(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 th(r,t){let e=zr(r,t),n=r.subarray(t.offset,t.offset+e);return t.offset+=e,n}function eh(r){let t=r.toString(16);t.length%2===1&&(t="0"+t);let e=new J;for(let n=0;n<t.length;n+=2)e.append(Uint8Array.from([parseInt(`${t[n]}${t[n+1]}`,16)]));return e}function Es(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let t=eh(r.byteLength);return new J(Uint8Array.from([t.byteLength|xs]),t)}function Ct(r){let t=new J,e=128;return(r.subarray()[0]&e)===e&&t.append(Uint8Array.from([0])),t.append(r),new J(Uint8Array.from([2]),Es(t),t)}function Pn(r){let t=Uint8Array.from([0]),e=new J(t,r);return new J(Uint8Array.from([3]),Es(e),e)}function Ee(r,t=48){let e=new J;for(let n of r)e.append(n);return new J(Uint8Array.from([t]),Es(e),e)}async function pc(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 s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,t,e.subarray());return n?.signal?.throwIfAborted(),s}var rh=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),nh=Uint8Array.from([6,5,43,129,4,0,34]),oh=Uint8Array.from([6,5,43,129,4,0,35]),sh={ext:!0,kty:"EC",crv:"P-256"},ih={ext:!0,kty:"EC",crv:"P-384"},ah={ext:!0,kty:"EC",crv:"P-521"},Ss=32,vs=48,_s=66;function As(r){let t=ne(r);return mc(t)}function mc(r){let t=r[1][1][0],e=1,n,o;if(t.byteLength===Ss*2+1)return n=z(t.subarray(e,e+Ss),"base64url"),o=z(t.subarray(e+Ss),"base64url"),new ur({...sh,key_ops:["verify"],x:n,y:o});if(t.byteLength===vs*2+1)return n=z(t.subarray(e,e+vs),"base64url"),o=z(t.subarray(e+vs),"base64url"),new ur({...ih,key_ops:["verify"],x:n,y:o});if(t.byteLength===_s*2+1)return n=z(t.subarray(e,e+_s),"base64url"),o=z(t.subarray(e+_s),"base64url"),new ur({...ah,key_ops:["verify"],x:n,y:o});throw new it(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function yc(r){return Ee([Ct(Uint8Array.from([1])),Ee([ch(r.crv)],160),Ee([Pn(new J(Uint8Array.from([4]),k(r.x??"","base64url"),k(r.y??"","base64url")))],161)]).subarray()}function ch(r){if(r==="P-256")return rh;if(r==="P-384")return nh;if(r==="P-521")return oh;throw new it(`Invalid curve ${r}`)}var ur=class{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=yc(this.jwk)),this._raw}toMultihash(){return Ht.digest(Yt(this))}toCID(){return lt.createV1(114,this.toMultihash())}toString(){return et.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 pc(this.jwk,e,t,n)}};var Ue=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 Gr(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");Gr(r.outputLen),Gr(r.blockLen)}function fr(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 bc(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 ie(...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 Ft(r,t){return r<<32-t|r>>>t}var wc=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",uh=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function Kt(r){if(Dt(r),wc)return r.toHex();let t="";for(let e=0;e<r.length;e++)t+=uh[r[e]];return t}var oe={_0:48,_9:57,A:65,F:70,a:97,f:102};function gc(r){if(r>=oe._0&&r<=oe._9)return r-oe._0;if(r>=oe.A&&r<=oe.F)return r-(oe.A-10);if(r>=oe.a&&r<=oe.f)return r-(oe.a-10)}function Me(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(wc)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,s=0;o<e;o++,s+=2){let i=gc(r.charCodeAt(s)),a=gc(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function Ts(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function $r(r){return typeof r=="string"&&(r=Ts(r)),Dt(r),r}function St(...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 s=r[n];e.set(s,o),o+=s.length}return e}var lr=class{};function Is(r){let t=n=>r().update($r(n)).digest(),e=r();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>r(),t}function hr(r=32){if(Ue&&typeof Ue.getRandomValues=="function")return Ue.getRandomValues(new Uint8Array(r));if(Ue&&typeof Ue.randomBytes=="function")return Uint8Array.from(Ue.randomBytes(r));throw new Error("crypto.getRandomValues must be defined")}function lh(r,t,e,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(t,e,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(e>>o&s),a=Number(e&s),c=n?4:0,u=n?0:4;r.setUint32(t+c,i,n),r.setUint32(t+u,a,n)}function xc(r,t,e){return r&t^~r&e}function Ec(r,t,e){return r&t^r&e^t&e}var Wr=class extends lr{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){fr(this),t=$r(t),Dt(t);let{view:e,buffer:n,blockLen:o}=this,s=t.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=Nn(t);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(t.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){fr(this),bc(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;e[i++]=128,ie(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let h=i;h<o;h++)e[h]=0;lh(n,o-8,BigInt(this.length*8),s),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,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<u;h++)a.setUint32(4*h,l[h],s)}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:s,destroyed:i,pos:a}=this;return t.destroyed=i,t.finished=s,t.length=o,t.pos=a,o%e&&t.buffer.set(n),t}clone(){return this._cloneInto()}},ae=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var yt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Un=BigInt(4294967295),Sc=BigInt(32);function fh(r,t=!1){return t?{h:Number(r&Un),l:Number(r>>Sc&Un)}:{h:Number(r>>Sc&Un)|0,l:Number(r&Un)|0}}function vc(r,t=!1){let e=r.length,n=new Uint32Array(e),o=new Uint32Array(e);for(let s=0;s<e;s++){let{h:i,l:a}=fh(r[s],t);[n[s],o[s]]=[i,a]}return[n,o]}var Cs=(r,t,e)=>r>>>e,Ds=(r,t,e)=>r<<32-e|t>>>e,ke=(r,t,e)=>r>>>e|t<<32-e,Ke=(r,t,e)=>r<<32-e|t>>>e,Zr=(r,t,e)=>r<<64-e|t>>>e-32,Yr=(r,t,e)=>r>>>e-32|t<<64-e;function Xt(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var _c=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),Ac=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,Tc=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),Ic=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,Cc=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),Dc=(r,t,e,n,o,s)=>t+e+n+o+s+(r/2**32|0)|0;var dh=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]),Se=new Uint32Array(64),Mn=class extends Wr{constructor(t=32){super(64,t,8,!1),this.A=ae[0]|0,this.B=ae[1]|0,this.C=ae[2]|0,this.D=ae[3]|0,this.E=ae[4]|0,this.F=ae[5]|0,this.G=ae[6]|0,this.H=ae[7]|0}get(){let{A:t,B:e,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[t,e,n,o,s,i,a,c]}set(t,e,n,o,s,i,a,c){this.A=t|0,this.B=e|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,e){for(let h=0;h<16;h++,e+=4)Se[h]=t.getUint32(e,!1);for(let h=16;h<64;h++){let f=Se[h-15],d=Se[h-2],p=Ft(f,7)^Ft(f,18)^f>>>3,x=Ft(d,17)^Ft(d,19)^d>>>10;Se[h]=x+Se[h-7]+p+Se[h-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:l}=this;for(let h=0;h<64;h++){let f=Ft(a,6)^Ft(a,11)^Ft(a,25),d=l+f+xc(a,c,u)+dh[h]+Se[h]|0,x=(Ft(n,2)^Ft(n,13)^Ft(n,22))+Ec(n,o,s)|0;l=u,u=c,c=a,a=i+d|0,i=s,s=o,o=n,n=d+x|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(n,o,s,i,a,c,u,l)}roundClean(){ie(Se)}destroy(){this.set(0,0,0,0,0,0,0,0),ie(this.buffer)}};var Lc=vc(["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))),ph=Lc[0],mh=Lc[1],ve=new Uint32Array(80),_e=new Uint32Array(80),Ls=class extends Wr{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:s,Cl:i,Dh:a,Dl:c,Eh:u,El:l,Fh:h,Fl:f,Gh:d,Gl:p,Hh:x,Hl:S}=this;return[t,e,n,o,s,i,a,c,u,l,h,f,d,p,x,S]}set(t,e,n,o,s,i,a,c,u,l,h,f,d,p,x,S){this.Ah=t|0,this.Al=e|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=h|0,this.Fl=f|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)ve[w]=t.getUint32(e),_e[w]=t.getUint32(e+=4);for(let w=16;w<80;w++){let C=ve[w-15]|0,P=_e[w-15]|0,q=ke(C,P,1)^ke(C,P,8)^Cs(C,P,7),K=Ke(C,P,1)^Ke(C,P,8)^Ds(C,P,7),N=ve[w-2]|0,E=_e[w-2]|0,D=ke(N,E,19)^Zr(N,E,61)^Cs(N,E,6),U=Ke(N,E,19)^Yr(N,E,61)^Ds(N,E,6),L=Tc(K,U,_e[w-7],_e[w-16]),b=Ic(L,q,D,ve[w-7],ve[w-16]);ve[w]=b|0,_e[w]=L|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:l,Eh:h,El:f,Fh:d,Fl:p,Gh:x,Gl:S,Hh:g,Hl:_}=this;for(let w=0;w<80;w++){let C=ke(h,f,14)^ke(h,f,18)^Zr(h,f,41),P=Ke(h,f,14)^Ke(h,f,18)^Yr(h,f,41),q=h&d^~h&x,K=f&p^~f&S,N=Cc(_,P,K,mh[w],_e[w]),E=Dc(N,g,C,q,ph[w],ve[w]),D=N|0,U=ke(n,o,28)^Zr(n,o,34)^Zr(n,o,39),L=Ke(n,o,28)^Yr(n,o,34)^Yr(n,o,39),b=n&s^n&a^s&a,m=o&i^o&c^i&c;g=x|0,_=S|0,x=d|0,S=p|0,d=h|0,p=f|0,{h,l:f}=Xt(u|0,l|0,E|0,D|0),u=a|0,l=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let y=_c(D,L,m);n=Ac(y,E,U,b),o=y|0}({h:n,l:o}=Xt(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=Xt(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=Xt(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=Xt(this.Dh|0,this.Dl|0,u|0,l|0),{h,l:f}=Xt(this.Eh|0,this.El|0,h|0,f|0),{h:d,l:p}=Xt(this.Fh|0,this.Fl|0,d|0,p|0),{h:x,l:S}=Xt(this.Gh|0,this.Gl|0,x|0,S|0),{h:g,l:_}=Xt(this.Hh|0,this.Hl|0,g|0,_|0),this.set(n,o,s,i,a,c,u,l,h,f,d,p,x,S,g,_)}roundClean(){ie(ve,_e)}destroy(){ie(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var kn=Is(()=>new Mn);var Bc=Is(()=>new Ls);var Ps=BigInt(0),Rs=BigInt(1);function ce(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,s=t!==void 0;if(!n||s&&o!==t){let i=e&&`"${e}" `,a=s?` of length ${t}`:"",c=n?`length=${o}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function Xr(r){let t=r.toString(16);return t.length&1?"0"+t:t}function Rc(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?Ps:BigInt("0x"+r)}function dr(r){return Rc(Kt(r))}function ue(r){return Dt(r),Rc(Kt(Uint8Array.from(r).reverse()))}function Kn(r,t){return Me(r.toString(16).padStart(t*2,"0"))}function Os(r,t){return Kn(r,t).reverse()}function Y(r,t,e){let n;if(typeof t=="string")try{n=Me(t)}catch(s){throw new Error(r+" must be hex string or Uint8Array, cause: "+s)}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 Pc(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 Ns(r){return Uint8Array.from(r)}var Bs=r=>typeof r=="bigint"&&Ps<=r;function Oc(r,t,e){return Bs(r)&&Bs(t)&&Bs(e)&&t<=r&&r<e}function jr(r,t,e,n){if(!Oc(t,e,n))throw new Error("expected valid "+r+": "+e+" <= n < "+n+", got "+t)}function qn(r){let t;for(t=0;r>Ps;r>>=Rs,t+=1);return t}var Ae=r=>(Rs<<BigInt(r))-Rs;function Nc(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),s=n(r),i=n(r),a=0,c=()=>{s.fill(1),i.fill(0),a=0},u=(...d)=>e(i,s,...d),l=(d=n(0))=>{i=u(o(0),d),s=u(),d.length!==0&&(i=u(o(1),d),s=u())},h=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let d=0,p=[];for(;d<t;){s=u();let x=s.slice();p.push(x),d+=s.length}return St(...p)};return(d,p)=>{c(),l(d);let x;for(;!(x=p(h()));)l();return c(),x}}function Te(r,t,e={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function n(o,s,i){let a=r[o];if(i&&a===void 0)return;let c=typeof a;if(c!==s||a===null)throw new Error(`param "${o}" is invalid: expected ${s}, got ${c}`)}Object.entries(t).forEach(([o,s])=>n(o,s,!1)),Object.entries(e).forEach(([o,s])=>n(o,s,!0))}var Us=()=>{throw new Error("not implemented")};function pr(r){let t=new WeakMap;return(e,...n)=>{let o=t.get(e);if(o!==void 0)return o;let s=r(e,...n);return t.set(e,s),s}}var vt=BigInt(0),dt=BigInt(1),qe=BigInt(2),kc=BigInt(3),Kc=BigInt(4),qc=BigInt(5),yh=BigInt(7),Vc=BigInt(8),gh=BigInt(9),Hc=BigInt(16);function ct(r,t){let e=r%t;return e>=vt?e:t+e}function tt(r,t,e){let n=r;for(;t-- >vt;)n*=n,n%=e;return n}function Uc(r,t){if(r===vt)throw new Error("invert: expected non-zero number");if(t<=vt)throw new Error("invert: expected positive modulus, got "+t);let e=ct(r,t),n=t,o=vt,s=dt,i=dt,a=vt;for(;e!==vt;){let u=n/e,l=n%e,h=o-i*u,f=s-a*u;n=e,e=l,o=i,s=a,i=h,a=f}if(n!==dt)throw new Error("invert: does not exist");return ct(o,t)}function Ms(r,t,e){if(!r.eql(r.sqr(t),e))throw new Error("Cannot find square root")}function Fc(r,t){let e=(r.ORDER+dt)/Kc,n=r.pow(t,e);return Ms(r,n,t),n}function bh(r,t){let e=(r.ORDER-qc)/Vc,n=r.mul(t,qe),o=r.pow(n,e),s=r.mul(t,o),i=r.mul(r.mul(s,qe),o),a=r.mul(s,r.sub(i,r.ONE));return Ms(r,a,t),a}function wh(r){let t=Nt(r),e=zc(r),n=e(t,t.neg(t.ONE)),o=e(t,n),s=e(t,t.neg(n)),i=(r+yh)/Hc;return(a,c)=>{let u=a.pow(c,i),l=a.mul(u,n),h=a.mul(u,o),f=a.mul(u,s),d=a.eql(a.sqr(l),c),p=a.eql(a.sqr(h),c);u=a.cmov(u,l,d),l=a.cmov(f,h,p);let x=a.eql(a.sqr(l),c),S=a.cmov(u,l,x);return Ms(a,S,c),S}}function zc(r){if(r<kc)throw new Error("sqrt is not defined for small field");let t=r-dt,e=0;for(;t%qe===vt;)t/=qe,e++;let n=qe,o=Nt(r);for(;Mc(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(e===1)return Fc;let s=o.pow(n,t),i=(t+dt)/qe;return function(c,u){if(c.is0(u))return u;if(Mc(c,u)!==1)throw new Error("Cannot find square root");let l=e,h=c.mul(c.ONE,s),f=c.pow(u,t),d=c.pow(u,i);for(;!c.eql(f,c.ONE);){if(c.is0(f))return c.ZERO;let p=1,x=c.sqr(f);for(;!c.eql(x,c.ONE);)if(p++,x=c.sqr(x),p===l)throw new Error("Cannot find square root");let S=dt<<BigInt(l-p-1),g=c.pow(h,S);l=p,h=c.sqr(g),f=c.mul(f,h),d=c.mul(d,g)}return d}}function xh(r){return r%Kc===kc?Fc:r%Vc===qc?bh:r%Hc===gh?wh(r):zc(r)}var le=(r,t)=>(ct(r,t)&dt)===dt,Eh=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function ks(r){let t={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},e=Eh.reduce((n,o)=>(n[o]="function",n),t);return Te(r,e),r}function Sh(r,t,e){if(e<vt)throw new Error("invalid exponent, negatives unsupported");if(e===vt)return r.ONE;if(e===dt)return t;let n=r.ONE,o=t;for(;e>vt;)e&dt&&(n=r.mul(n,o)),o=r.sqr(o),e>>=dt;return n}function Qr(r,t,e=!1){let n=new Array(t.length).fill(e?r.ZERO:void 0),o=t.reduce((i,a,c)=>r.is0(a)?i:(n[c]=i,r.mul(i,a)),r.ONE),s=r.inv(o);return t.reduceRight((i,a,c)=>r.is0(a)?i:(n[c]=r.mul(i,n[c]),r.mul(i,a)),s),n}function Mc(r,t){let e=(r.ORDER-dt)/qe,n=r.pow(t,e),o=r.eql(n,r.ONE),s=r.eql(n,r.ZERO),i=r.eql(n,r.neg(r.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function Vn(r,t){t!==void 0&&Gr(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<=vt)throw new Error("invalid field: expected ORDER > 0, got "+r);let o,s,i=!1,a;if(typeof t=="object"&&t!=null){if(n.sqrt||e)throw new Error("cannot specify opts in two arguments");let f=t;f.BITS&&(o=f.BITS),f.sqrt&&(s=f.sqrt),typeof f.isLE=="boolean"&&(e=f.isLE),typeof f.modFromBytes=="boolean"&&(i=f.modFromBytes),a=f.allowedLengths}else typeof t=="number"&&(o=t),n.sqrt&&(s=n.sqrt);let{nBitLength:c,nByteLength:u}=Vn(r,o);if(u>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let l,h=Object.freeze({ORDER:r,isLE:e,BITS:c,BYTES:u,MASK:Ae(c),ZERO:vt,ONE:dt,allowedLengths:a,create:f=>ct(f,r),isValid:f=>{if(typeof f!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof f);return vt<=f&&f<r},is0:f=>f===vt,isValidNot0:f=>!h.is0(f)&&h.isValid(f),isOdd:f=>(f&dt)===dt,neg:f=>ct(-f,r),eql:(f,d)=>f===d,sqr:f=>ct(f*f,r),add:(f,d)=>ct(f+d,r),sub:(f,d)=>ct(f-d,r),mul:(f,d)=>ct(f*d,r),pow:(f,d)=>Sh(h,f,d),div:(f,d)=>ct(f*Uc(d,r),r),sqrN:f=>f*f,addN:(f,d)=>f+d,subN:(f,d)=>f-d,mulN:(f,d)=>f*d,inv:f=>Uc(f,r),sqrt:s||(f=>(l||(l=xh(r)),l(h,f))),toBytes:f=>e?Os(f,u):Kn(f,u),fromBytes:(f,d=!0)=>{if(a){if(!a.includes(f.length)||f.length>u)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+f.length);let x=new Uint8Array(u);x.set(f,e?0:x.length-f.length),f=x}if(f.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+f.length);let p=e?ue(f):dr(f);if(i&&(p=ct(p,r)),!d&&!h.isValid(p))throw new Error("invalid field element: outside of range 0..ORDER");return p},invertBatch:f=>Qr(h,f),cmov:(f,d,p)=>p?d:f});return Object.freeze(h)}function Gc(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 Ks(r){let t=Gc(r);return t+Math.ceil(t/2)}function qs(r,t,e=!1){let n=r.length,o=Gc(t),s=Ks(t);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=e?ue(r):dr(r),a=ct(i,t-dt)+dt;return e?Os(a,o):Kn(a,o)}var mr=BigInt(0),Ve=BigInt(1);function Jr(r,t){let e=t.negate();return r?e:t}function fe(r,t){let e=Qr(r.Fp,t.map(n=>n.Z));return t.map((n,o)=>r.fromAffine(n.toAffine(e[o])))}function Yc(r,t){if(!Number.isSafeInteger(r)||r<=0||r>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+r)}function Vs(r,t){Yc(r,t);let e=Math.ceil(t/r)+1,n=2**(r-1),o=2**r,s=Ae(r),i=BigInt(r);return{windows:e,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function $c(r,t,e){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=e,a=Number(r&o),c=r>>i;a>n&&(a-=s,c+=Ve);let u=t*n,l=u+Math.abs(a)-1,h=a===0,f=a<0,d=t%2!==0;return{nextN:c,offset:l,isZero:h,isNeg:f,isNegF:d,offsetF:u}}function vh(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 _h(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 Hs=new WeakMap,Xc=new WeakMap;function Fs(r){return Xc.get(r)||1}function Wc(r){if(r!==mr)throw new Error("invalid wNAF")}var yr=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>mr;)e&Ve&&(n=n.add(o)),o=o.double(),e>>=Ve;return n}precomputeWindow(t,e){let{windows:n,windowSize:o}=Vs(e,this.bits),s=[],i=t,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let u=1;u<o;u++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(t,e,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=Vs(t,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:u,isZero:l,isNeg:h,isNegF:f,offsetF:d}=$c(n,a,i);n=c,l?s=s.add(Jr(f,e[d])):o=o.add(Jr(h,e[u]))}return Wc(n),{p:o,f:s}}wNAFUnsafe(t,e,n,o=this.ZERO){let s=Vs(t,this.bits);for(let i=0;i<s.windows&&n!==mr;i++){let{nextN:a,offset:c,isZero:u,isNeg:l}=$c(n,i,s);if(n=a,!u){let h=e[c];o=o.add(l?h.negate():h)}}return Wc(n),o}getPrecomputes(t,e,n){let o=Hs.get(e);return o||(o=this.precomputeWindow(e,t),t!==1&&(typeof n=="function"&&(o=n(o)),Hs.set(e,o))),o}cached(t,e,n){let o=Fs(t);return this.wNAF(o,this.getPrecomputes(o,t,n),e)}unsafe(t,e,n,o){let s=Fs(t);return s===1?this._unsafeLadder(t,e,o):this.wNAFUnsafe(s,this.getPrecomputes(s,t,n),e,o)}createCache(t,e){Yc(e,this.bits),Xc.set(t,e),Hs.delete(t)}hasCache(t){return Fs(t)!==1}};function jc(r,t,e,n){let o=t,s=r.ZERO,i=r.ZERO;for(;e>mr||n>mr;)e&Ve&&(s=s.add(o)),n&Ve&&(i=i.add(o)),o=o.double(),e>>=Ve,n>>=Ve;return{p1:s,p2:i}}function gr(r,t,e,n){vh(e,r),_h(n,t);let o=e.length,s=n.length;if(o!==s)throw new Error("arrays of points and scalars must have equal length");let i=r.ZERO,a=qn(BigInt(o)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let u=Ae(c),l=new Array(Number(u)+1).fill(i),h=Math.floor((t.BITS-1)/c)*c,f=i;for(let d=h;d>=0;d-=c){l.fill(i);for(let x=0;x<s;x++){let S=n[x],g=Number(S>>BigInt(d)&u);l[g]=l[g].add(e[x])}let p=i;for(let x=l.length-1,S=i;x>0;x--)S=S.add(l[x]),p=p.add(S);if(f=f.add(p),d!==0)for(let x=0;x<c;x++)f=f.double()}return f}function Zc(r,t,e){if(t){if(t.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return ks(t),t}else return Nt(r,{isLE:e})}function Hn(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>mr))throw new Error(`CURVE.${c} must be positive bigint`)}let o=Zc(t.p,e.Fp,n),s=Zc(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:s}}var Ie=BigInt(0),pt=BigInt(1),zs=BigInt(2),Ah=BigInt(8);function Th(r,t,e,n){let o=r.sqr(e),s=r.sqr(n),i=r.add(r.mul(t.a,o),s),a=r.add(r.ONE,r.mul(t.d,r.mul(o,s)));return r.eql(i,a)}function Ih(r,t={}){let e=Hn("edwards",r,t,t.FpFnLE),{Fp:n,Fn:o}=e,s=e.CURVE,{h:i}=s;Te(t,{},{uvRatio:"function"});let a=zs<<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:Ie}}});if(!Th(n,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function l(S,g,_=!1){let w=_?pt:Ie;return jr("coordinate "+S,g,w,a),g}function h(S){if(!(S instanceof p))throw new Error("ExtendedPoint expected")}let f=pr((S,g)=>{let{X:_,Y:w,Z:C}=S,P=S.is0();g==null&&(g=P?Ah:n.inv(C));let q=c(_*g),K=c(w*g),N=n.mul(C,g);if(P)return{x:Ie,y:pt};if(N!==pt)throw new Error("invZ was invalid");return{x:q,y:K}}),d=pr(S=>{let{a:g,d:_}=s;if(S.is0())throw new Error("bad point: ZERO");let{X:w,Y:C,Z:P,T:q}=S,K=c(w*w),N=c(C*C),E=c(P*P),D=c(E*E),U=c(K*g),L=c(E*c(U+N)),b=c(D+c(_*c(K*N)));if(L!==b)throw new Error("bad point: equation left != right (1)");let m=c(w*C),y=c(P*q);if(m!==y)throw new Error("bad point: equation left != right (2)");return!0});class p{constructor(g,_,w,C){this.X=l("x",g),this.Y=l("y",_),this.Z=l("z",w,!0),this.T=l("t",C),Object.freeze(this)}static CURVE(){return s}static fromAffine(g){if(g instanceof p)throw new Error("extended point not allowed");let{x:_,y:w}=g||{};return l("x",_),l("y",w),new p(_,w,pt,c(_*w))}static fromBytes(g,_=!1){let w=n.BYTES,{a:C,d:P}=s;g=Ns(Ot(g,w,"point")),ce(_,"zip215");let q=Ns(g),K=g[w-1];q[w-1]=K&-129;let N=ue(q),E=_?a:n.ORDER;jr("point.y",N,Ie,E);let D=c(N*N),U=c(D-pt),L=c(P*D-C),{isValid:b,value:m}=u(U,L);if(!b)throw new Error("bad point: invalid y coordinate");let y=(m&pt)===pt,v=(K&128)!==0;if(!_&&m===Ie&&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(zs),this}assertValidity(){d(this)}equals(g){h(g);let{X:_,Y:w,Z:C}=this,{X:P,Y:q,Z:K}=g,N=c(_*K),E=c(P*C),D=c(w*K),U=c(q*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}=s,{X:_,Y:w,Z:C}=this,P=c(_*_),q=c(w*w),K=c(zs*c(C*C)),N=c(g*P),E=_+w,D=c(c(E*E)-P-q),U=N+q,L=U-K,b=N-q,m=c(D*L),y=c(U*b),v=c(D*b),A=c(L*U);return new p(m,y,A,v)}add(g){h(g);let{a:_,d:w}=s,{X:C,Y:P,Z:q,T:K}=this,{X:N,Y:E,Z:D,T:U}=g,L=c(C*N),b=c(P*E),m=c(K*w*U),y=c(q*D),v=c((C+P)*(N+E)-L-b),A=y-m,B=y+m,T=c(b-_*L),I=c(v*A),O=c(B*T),M=c(v*T),nt=c(A*B);return new p(I,O,nt,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=>fe(p,C));return fe(p,[_,w])[0]}multiplyUnsafe(g,_=p.ZERO){if(!o.isValid(g))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return g===Ie?p.ZERO:this.is0()||g===pt?this:x.unsafe(this,g,w=>fe(p,w),_)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return x.unsafe(this,s.n).is0()}toAffine(g){return f(this,g)}clearCofactor(){return i===pt?this:this.multiplyUnsafe(i)}toBytes(){let{x:g,y:_}=this.toAffine(),w=n.toBytes(_);return w[w.length-1]|=g&pt?128:0,w}toHex(){return Kt(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 fe(p,g)}static msm(g,_){return gr(p,o,g,_)}_setWindowSize(g){this.precompute(g)}toRawBytes(){return this.toBytes()}}p.BASE=new p(s.Gx,s.Gy,pt,c(s.Gx*s.Gy)),p.ZERO=new p(Ie,pt,pt,Ie),p.Fp=n,p.Fn=o;let x=new yr(p,o.BITS);return p.BASE.precompute(8),p}var Fn=class{constructor(t){this.ep=t}static fromBytes(t){Us()}static fromHex(t){Us()}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 Kt(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 Ch(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:s,Fn:i}=r,a=e.randomBytes||hr,c=e.adjustScalarBytes||(E=>E),u=e.domain||((E,D,U)=>{if(ce(U,"phflag"),D.length||U)throw new Error("Contexts/pre-hash are not supported");return E});function l(E){return i.create(ue(E))}function h(E){let D=w.secretKey;E=Y("private key",E,D);let U=Y("hashed private key",t(E),2*D),L=c(U.slice(0,D)),b=U.slice(D,2*D),m=l(L);return{head:L,prefix:b,scalar:m}}function f(E){let{head:D,prefix:U,scalar:L}=h(E),b=o.multiply(L),m=b.toBytes();return{head:D,prefix:U,scalar:L,point:b,pointBytes:m}}function d(E){return f(E).pointBytes}function p(E=Uint8Array.of(),...D){let U=St(...D);return l(t(u(U,Y("context",E),!!n)))}function x(E,D,U={}){E=Y("message",E),n&&(E=n(E));let{prefix:L,scalar:b,pointBytes:m}=f(D),y=p(U.context,L,E),v=o.multiply(y).toBytes(),A=p(U.context,v,m,E),B=i.create(y+A*b);if(!i.isValid(B))throw new Error("sign failed: invalid s");let T=St(v,i.toBytes(B));return Ot(T,w.signature,"result")}let S={zip215:!0};function g(E,D,U,L=S){let{context:b,zip215:m}=L,y=w.signature;E=Y("signature",E,y),D=Y("message",D),U=Y("publicKey",U,w.publicKey),m!==void 0&&ce(m,"zip215"),n&&(D=n(D));let v=y/2,A=E.subarray(0,v),B=ue(E.subarray(v,y)),T,I,O;try{T=r.fromBytes(U,m),I=r.fromBytes(A,m),O=o.multiplyUnsafe(B)}catch{return!1}if(!m&&T.isSmallOrder())return!1;let M=p(b,I.toBytes(),T.toBytes(),D);return I.add(T.multiplyUnsafe(M)).subtract(O).clearCofactor().is0()}let _=s.BYTES,w={secretKey:_,publicKey:_,signature:2*_,seed:_};function C(E=a(w.seed)){return Ot(E,w.seed,"seed")}function P(E){let D=N.randomSecretKey(E);return{secretKey:D,publicKey:d(D)}}function q(E){return se(E)&&E.length===i.BYTES}function K(E,D){try{return!!r.fromBytes(E,D)}catch{return!1}}let N={getExtendedPublicKey:f,randomSecretKey:C,isValidSecretKey:q,isValidPublicKey:K,toMontgomery(E){let{y:D}=r.fromBytes(E),U=w.publicKey,L=U===32;if(!L&&U!==57)throw new Error("only defined for 25519 and 448");let b=L?s.div(pt+D,pt-D):s.div(D-pt,D+pt);return s.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:P,getPublicKey:d,sign:x,verify:g,utils:N,Point:r,lengths:w})}function Dh(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},s={randomBytes:r.randomBytes,adjustScalarBytes:r.adjustScalarBytes,domain:r.domain,prehash:r.prehash,mapToCurve:r.mapToCurve};return{CURVE:t,curveOpts:o,hash:r.hash,eddsaOpts:s}}function Lh(r,t){let e=t.Point;return Object.assign({},t,{ExtendedPoint:e,CURVE:r,nBitLength:e.Fn.BITS,nByteLength:e.Fn.BYTES})}function Qc(r){let{CURVE:t,curveOpts:e,hash:n,eddsaOpts:o}=Dh(r),s=Ih(t,e),i=Ch(s,n,o);return Lh(r,i)}var Bh=BigInt(0),he=BigInt(1),Jc=BigInt(2),Cy=BigInt(3),Rh=BigInt(5),Ph=BigInt(8),br=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),tn={p:br,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Ph,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Oh(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),s=br,a=r*r%s*r%s,c=tt(a,Jc,s)*a%s,u=tt(c,he,s)*r%s,l=tt(u,Rh,s)*u%s,h=tt(l,t,s)*l%s,f=tt(h,e,s)*h%s,d=tt(f,n,s)*f%s,p=tt(d,o,s)*d%s,x=tt(p,o,s)*d%s,S=tt(x,t,s)*l%s;return{pow_p_5_8:tt(S,Jc,s)*r%s,b2:a}}function Nh(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var Gs=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Zs(r,t){let e=br,n=ct(t*t*t,e),o=ct(n*n*t,e),s=Oh(r*o).pow_p_5_8,i=ct(r*n*s,e),a=ct(t*i*i,e),c=i,u=ct(i*Gs,e),l=a===r,h=a===ct(-r,e),f=a===ct(-r*Gs,e);return l&&(i=c),(h||f)&&(i=u),le(i,e)&&(i=ct(-i,e)),{isValid:l||h,value:i}}var Ce=Nt(tn.p,{isLE:!0}),Uh=Nt(tn.n,{isLE:!0}),Mh={...tn,Fp:Ce,hash:Bc,adjustScalarBytes:Nh,uvRatio:Zs},de=Qc(Mh);var $s=Gs,kh=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Kh=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),qh=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),Vh=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),tu=r=>Zs(he,r),Hh=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Ws=r=>de.Point.Fp.create(ue(r)&Hh);function eu(r){let{d:t}=tn,e=br,n=g=>Ce.create(g),o=n($s*r*r),s=n((o+he)*qh),i=BigInt(-1),a=n((i-t*o)*n(o+t)),{isValid:c,value:u}=Zs(s,a),l=n(u*r);le(l,e)||(l=n(-l)),c||(u=l),c||(i=o);let h=n(i*(o-he)*Vh-a),f=u*u,d=n((u+u)*a),p=n(h*kh),x=n(he-f),S=n(he+f);return new de.Point(n(d*S),n(x*p),n(p*S),n(d*x))}function Fh(r){Dt(r,64);let t=Ws(r.subarray(0,32)),e=eu(t),n=Ws(r.subarray(32,64)),o=eu(n);return new pe(e.add(o))}var pe=class r extends Fn{constructor(t){super(t)}static fromAffine(t){return new r(de.Point.fromAffine(t))}assertSame(t){if(!(t instanceof r))throw new Error("RistrettoPoint expected")}init(t){return new r(t)}static hashToCurve(t){return Fh(Y("ristrettoHash",t,64))}static fromBytes(t){Dt(t,32);let{a:e,d:n}=tn,o=br,s=C=>Ce.create(C),i=Ws(t);if(!Pc(Ce.toBytes(i),t)||le(i,o))throw new Error("invalid ristretto255 encoding 1");let a=s(i*i),c=s(he+e*a),u=s(he-e*a),l=s(c*c),h=s(u*u),f=s(e*n*l-h),{isValid:d,value:p}=tu(s(f*h)),x=s(p*u),S=s(p*x*f),g=s((i+i)*x);le(g,o)&&(g=s(-g));let _=s(c*S),w=s(g*_);if(!d||le(w,o)||_===Bh)throw new Error("invalid ristretto255 encoding 2");return new r(new de.Point(g,_,he,w))}static fromHex(t){return r.fromBytes(Y("ristrettoHex",t,32))}static msm(t,e){return gr(r,de.Point.Fn,t,e)}toBytes(){let{X:t,Y:e,Z:n,T:o}=this.ep,s=br,i=S=>Ce.create(S),a=i(i(n+e)*i(n-e)),c=i(t*e),u=i(c*c),{value:l}=tu(i(a*u)),h=i(l*a),f=i(l*c),d=i(h*f*o),p;if(le(o*d,s)){let S=i(e*$s),g=i(t*$s);t=S,e=g,p=i(h*Kh)}else p=f;le(t*d,s)&&(e=i(-e));let x=i((n-e)*p);return le(x,s)&&(x=i(-x)),Ce.toBytes(x)}equals(t){this.assertSame(t);let{X:e,Y:n}=this.ep,{X:o,Y:s}=t.ep,i=u=>Ce.create(u),a=i(e*s)===i(n*o),c=i(n*s)===i(e*o);return a||c}is0(){return this.equals(r.ZERO)}};pe.BASE=new pe(de.Point.BASE);pe.ZERO=new pe(de.Point.ZERO);pe.Fp=Ce;pe.Fn=Uh;var en=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 ru={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 qt=ru;var Gn=32;var Ys,zh=(async()=>{try{return await qt.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function Gh(r,t,e){if(r.buffer instanceof ArrayBuffer){let n=await qt.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await qt.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 $h(r,t,e){return de.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}async function nu(r,t,e){return Ys==null&&(Ys=await zh),Ys?Gh(r,t,e):$h(r,t,e)}function $n(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Wn=class{type="Ed25519";raw;constructor(t){this.raw=Xs(t,Gn)}toMultihash(){return Ht.digest(Yt(this))}toCID(){return lt.createV1(114,this.toMultihash())}toString(){return et.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=nu(this.raw,e,t);return $n(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function js(r){return r=Xs(r,Gn),new Wn(r)}function Xs(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new it(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}var Zh=Math.pow(2,7),Yh=Math.pow(2,14),Xh=Math.pow(2,21),Qs=Math.pow(2,28),Js=Math.pow(2,35),ti=Math.pow(2,42),ei=Math.pow(2,49),W=128,wt=127;function Lt(r){if(r<Zh)return 1;if(r<Yh)return 2;if(r<Xh)return 3;if(r<Qs)return 4;if(r<Js)return 5;if(r<ti)return 6;if(r<ei)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function wr(r,t,e=0){switch(Lt(r)){case 8:t[e++]=r&255|W,r/=128;case 7:t[e++]=r&255|W,r/=128;case 6:t[e++]=r&255|W,r/=128;case 5:t[e++]=r&255|W,r/=128;case 4:t[e++]=r&255|W,r>>>=7;case 3:t[e++]=r&255|W,r>>>=7;case 2:t[e++]=r&255|W,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function jh(r,t,e=0){switch(Lt(r)){case 8:t.set(e++,r&255|W),r/=128;case 7:t.set(e++,r&255|W),r/=128;case 6:t.set(e++,r&255|W),r/=128;case 5:t.set(e++,r&255|W),r/=128;case 4:t.set(e++,r&255|W),r>>>=7;case 3:t.set(e++,r&255|W),r>>>=7;case 2:t.set(e++,r&255|W),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function ri(r,t){let e=r[t],n=0;if(n+=e&wt,e<W||(e=r[t+1],n+=(e&wt)<<7,e<W)||(e=r[t+2],n+=(e&wt)<<14,e<W)||(e=r[t+3],n+=(e&wt)<<21,e<W)||(e=r[t+4],n+=(e&wt)*Qs,e<W)||(e=r[t+5],n+=(e&wt)*Js,e<W)||(e=r[t+6],n+=(e&wt)*ti,e<W)||(e=r[t+7],n+=(e&wt)*ei,e<W))return n;throw new RangeError("Could not decode varint")}function Qh(r,t){let e=r.get(t),n=0;if(n+=e&wt,e<W||(e=r.get(t+1),n+=(e&wt)<<7,e<W)||(e=r.get(t+2),n+=(e&wt)<<14,e<W)||(e=r.get(t+3),n+=(e&wt)<<21,e<W)||(e=r.get(t+4),n+=(e&wt)*Qs,e<W)||(e=r.get(t+5),n+=(e&wt)*Js,e<W)||(e=r.get(t+6),n+=(e&wt)*ti,e<W)||(e=r.get(t+7),n+=(e&wt)*ei,e<W))return n;throw new RangeError("Could not decode varint")}function xr(r,t,e=0){return t==null&&(t=It(Lt(r))),t instanceof Uint8Array?wr(r,t,e):jh(r,t,e)}function rn(r,t=0){return r instanceof Uint8Array?ri(r,t):Qh(r,t)}var oi=new Float32Array([-0]),De=new Uint8Array(oi.buffer);function su(r,t,e){oi[0]=r,t[e]=De[0],t[e+1]=De[1],t[e+2]=De[2],t[e+3]=De[3]}function iu(r,t){return De[0]=r[t],De[1]=r[t+1],De[2]=r[t+2],De[3]=r[t+3],oi[0]}var si=new Float64Array([-0]),xt=new Uint8Array(si.buffer);function au(r,t,e){si[0]=r,t[e]=xt[0],t[e+1]=xt[1],t[e+2]=xt[2],t[e+3]=xt[3],t[e+4]=xt[4],t[e+5]=xt[5],t[e+6]=xt[6],t[e+7]=xt[7]}function cu(r,t){return xt[0]=r[t],xt[1]=r[t+1],xt[2]=r[t+2],xt[3]=r[t+3],xt[4]=r[t+4],xt[5]=r[t+5],xt[6]=r[t+6],xt[7]=r[t+7],si[0]}var Jh=BigInt(Number.MAX_SAFE_INTEGER),td=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 He;if(t<Jh&&t>td)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>uu&&(o=0n,++n>uu&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return He;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):He}},He=new Ut(0,0);He.toBigInt=function(){return 0n};He.zzEncode=He.zzDecode=function(){return this};He.length=function(){return 1};var uu=4294967296n;function lu(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 fu(r,t,e){if(e-t<1)return"";let o,s=[],i=0,a;for(;t<e;)a=r[t++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(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,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[t++]&63)<<6|r[t++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function ii(r,t,e){let n=e,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?t[e++]=o:o<2048?(t[e++]=o>>6|192,t[e++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,t[e++]=o>>18|240,t[e++]=o>>12&63|128,t[e++]=o>>6&63|128,t[e++]=o&63|128):(t[e++]=o>>12|224,t[e++]=o>>6&63|128,t[e++]=o&63|128);return e-n}function zt(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function Zn(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var ai=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,zt(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw zt(this,4);return Zn(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw zt(this,4);return Zn(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw zt(this,4);let t=iu(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw zt(this,4);let t=cu(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw zt(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return fu(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw zt(this,t);this.pos+=t}else do if(this.pos>=this.len)throw zt(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new 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 zt(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw zt(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw zt(this,8);let t=Zn(this.buf,this.pos+=4),e=Zn(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=ri(this.buf,this.pos);return this.pos+=Lt(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 ci(r){return new ai(r instanceof Uint8Array?r:r.subarray())}function Bt(r,t,e){let n=ci(r);return t.decode(n,void 0,e)}function ui(r){let t=r??8192,e=t>>>1,n,o=t;return function(i){if(i<1||i>e)return It(i);o+i>t&&(n=It(t),o=0);let a=n.subarray(o,o+=i);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 li(){}var hi=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},ed=ui();function rd(r){return globalThis.Buffer!=null?It(r):ed(r)}var on=class{len;head;tail;states;constructor(){this.len=0,this.head=new Fe(li,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 di((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(wr,Lt(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(fi,1,t?1:0)}fixed32(t){return this._push(nn,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=Ut.fromBigInt(t);return this._push(nn,4,e.lo)._push(nn,4,e.hi)}fixed64Number(t){let e=Ut.fromNumber(t);return this._push(nn,4,e.lo)._push(nn,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(su,4,t)}double(t){return this._push(au,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(fi,1,0):this.uint32(e)._push(od,e,t)}string(t){let e=lu(t);return e!==0?this.uint32(e)._push(ii,e,t):this._push(fi,1,0)}fork(){return this.states=new hi(this),this.head=this.tail=new Fe(li,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(li,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=rd(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function fi(r,t,e){t[e]=r&255}function nd(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var di=class extends Fe{next;constructor(t,e){super(nd,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 nn(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 od(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(on.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(sd,t,r),this},on.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(id,t,r),this});function sd(r,t,e){t.set(r,e)}function id(r,t,e){r.length<40?ii(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(k(r),e)}function pi(){return new on}function Rt(r,t){let e=pi();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var Er;(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"})(Er||(Er={}));function Xn(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function ze(r){function t(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let e=function(s,i){let a=t(s);i.int32(a)},n=function(s){let i=s.int32();return t(i)};return Xn("enum",Er.VARINT,e,n)}function Pt(r,t){return Xn("message",Er.LENGTH_DELIMITED,r,t)}var sn=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 mi;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(mi||(mi={}));(function(r){r.codec=()=>ze(mi)})(ut||(ut={}));var jt;(function(r){let t;r.codec=()=>(t==null&&(t=Pt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),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 s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.Type=ut.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Rt(e,r.codec()),r.decode=(e,n)=>Bt(e,r.codec(),n)})(jt||(jt={}));var yi;(function(r){let t;r.codec=()=>(t==null&&(t=Pt((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 s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.Type=ut.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Rt(e,r.codec()),r.decode=(e,n)=>Bt(e,r.codec(),n)})(yi||(yi={}));var cn={};At(cn,{MAX_RSA_KEY_SIZE:()=>gi,generateRSAKeyPair:()=>gu,jwkToJWKKeyPair:()=>bu,jwkToPkcs1:()=>ld,jwkToPkix:()=>Ei,jwkToRSAPrivateKey:()=>Ai,pkcs1MessageToJwk:()=>wi,pkcs1MessageToRSAPrivateKey:()=>Si,pkcs1ToJwk:()=>ud,pkcs1ToRSAPrivateKey:()=>yu,pkixMessageToJwk:()=>xi,pkixMessageToRSAPublicKey:()=>_i,pkixToJwk:()=>fd,pkixToRSAPublicKey:()=>vi});var jn=kn;var Sr=class{type="RSA";jwk;_raw;_multihash;constructor(t,e){this.jwk=t,this._multihash=e}get raw(){return this._raw==null&&(this._raw=cn.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return lt.createV1(114,this._multihash)}toString(){return et.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 mu(this.jwk,e,t,n)}},an=class{type="RSA";jwk;_raw;publicKey;constructor(t,e){this.jwk=t,this.publicKey=e}get raw(){return this._raw==null&&(this._raw=cn.jwkToPkcs1(this.jwk)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:ft(this.raw,t.raw)}sign(t,e){return pu(this.jwk,t,e)}};var gi=8192,bi=18,ad=1062,cd=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function ud(r){let t=ne(r);return wi(t)}function wi(r){return{n:z(r[1],"base64url"),e:z(r[2],"base64url"),d:z(r[3],"base64url"),p:z(r[4],"base64url"),q:z(r[5],"base64url"),dp:z(r[6],"base64url"),dq:z(r[7],"base64url"),qi:z(r[8],"base64url"),kty:"RSA"}}function ld(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 it("JWK was missing components");return Ee([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 fd(r){let t=ne(r,{offset:0});return xi(t)}function xi(r){let t=ne(r[1],{offset:0});return{kty:"RSA",n:z(t[0],"base64url"),e:z(t[1],"base64url")}}function Ei(r){if(r.n==null||r.e==null)throw new it("JWK was missing components");return Ee([cd,Pn(Ee([Ct(k(r.n,"base64url")),Ct(k(r.e,"base64url"))]))]).subarray()}function yu(r){let t=ne(r);return Si(t)}function Si(r){let t=wi(r);return Ai(t)}function vi(r,t){if(r.byteLength>=ad)throw new er("Key size is too large");let e=ne(r,{offset:0});return _i(e,r,t)}function _i(r,t,e){let n=xi(r);if(e==null){let o=jn(jt.encode({Type:ut.RSA,Data:t}));e=Wt(bi,o)}return new Sr(n,e)}function Ai(r){if(xu(r)>gi)throw new it("Key size is too large");let t=bu(r),e=jn(jt.encode({Type:ut.RSA,Data:Ei(t.publicKey)})),n=Wt(bi,e);return new an(t.privateKey,new Sr(t.publicKey,n))}async function gu(r){if(r>gi)throw new it("Key size is too large");let t=await wu(r),e=jn(jt.encode({Type:ut.RSA,Data:Ei(t.publicKey)})),n=Wt(bi,e);return new an(t.privateKey,new Sr(t.publicKey,n))}function bu(r){if(r==null)throw new it("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function wu(r,t){let e=await qt.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 hd(e,t);return{privateKey:n[0],publicKey:n[1]}}async function pu(r,t,e){let n=await qt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);e?.signal?.throwIfAborted();let o=await qt.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 mu(r,t,e,n){let o=await qt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let s=await qt.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,t,e instanceof Uint8Array?e:e.subarray());return n?.signal?.throwIfAborted(),s}async function hd(r,t){if(r.privateKey==null||r.publicKey==null)throw new it("Private and public key are required");let e=await Promise.all([qt.get().subtle.exportKey("jwk",r.privateKey),qt.get().subtle.exportKey("jwk",r.publicKey)]);return t?.signal?.throwIfAborted(),e}function xu(r){if(r.kty!=="RSA")throw new it("invalid key type");if(r.n==null)throw new it("invalid key modulus");return k(r.n,"base64url").length*8}var Qn=class extends lr{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,On(t);let n=$r(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,s=new Uint8Array(o);s.set(n.length>o?t.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=t.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),ie(s)}update(t){return fr(this),this.iHash.update(t),this}digestInto(t){fr(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:s,blockLen:i,outputLen:a}=this;return t=t,t.finished=o,t.destroyed=s,t.blockLen=i,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()}},Ti=(r,t,e)=>new Qn(r,t).update(e).digest();Ti.create=(r,t)=>new Qn(r,t);var Eu=(r,t)=>(r+(r>=0?t:-t)/Su)/t;function dd(r,t,e){let[[n,o],[s,i]]=t,a=Eu(i*r,e),c=Eu(-o*r,e),u=r-a*n-c*s,l=-a*o-c*i,h=u<ye,f=l<ye;h&&(u=-u),f&&(l=-l);let d=Ae(Math.ceil(qn(e)/2))+_r;if(u<ye||u>=d||l<ye||l>=d)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:h,k1:u,k2neg:f,k2:l}}function Ci(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function Ii(r,t){let e={};for(let n of Object.keys(t))e[n]=r[n]===void 0?t[n]:r[n];return ce(e.lowS,"lowS"),ce(e.prehash,"prehash"),e.format!==void 0&&Ci(e.format),e}var Di=class extends Error{constructor(t=""){super(t)}},me={Err:Di,_tlv:{encode:(r,t)=>{let{Err:e}=me;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=Xr(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let s=n>127?Xr(o.length/2|128):"";return Xr(r)+s+o+t},decode(r,t){let{Err:e}=me,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++],s=!!(o&128),i=0;if(!s)i=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 l of u)i=i<<8|l;if(n+=c,i<128)throw new e("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new e("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(r){let{Err:t}=me;if(r<ye)throw new t("integer: negative integers are not allowed");let e=Xr(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}=me;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 dr(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=me,o=Y("signature",r),{v:s,l:i}=n.decode(48,o);if(i.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:u,l}=n.decode(2,c);if(l.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}=me,n=t.encode(2,e.encode(r.r)),o=t.encode(2,e.encode(r.s)),s=n+o;return t.encode(48,s)}},ye=BigInt(0),_r=BigInt(1),Su=BigInt(2),Jn=BigInt(3),pd=BigInt(4);function vr(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 md(r,t={}){let e=Hn("weierstrass",r,t),{Fp:n,Fn:o}=e,s=e.CURVE,{h:i,n:a}=s;Te(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:c}=t;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let u=_u(n,o);function l(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function h(L,b,m){let{x:y,y:v}=b.toAffine(),A=n.toBytes(y);if(ce(m,"isCompressed"),m){l();let B=!n.isOdd(v);return St(vu(B),A)}else return St(Uint8Array.of(4),A,n.toBytes(v))}function f(L){Ot(L,void 0,"Point");let{publicKey:b,publicKeyUncompressed:m}=u,y=L.length,v=L[0],A=L.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 T=x(B),I;try{I=n.sqrt(T)}catch(nt){let Q=nt instanceof Error?": "+nt.message:"";throw new Error("bad point: is not on curve, sqrt error"+Q)}l();let O=n.isOdd(I);return(v&1)===1!==O&&(I=n.neg(I)),{x:B,y:I}}else if(y===m&&v===4){let B=n.BYTES,T=n.fromBytes(A.subarray(0,B)),I=n.fromBytes(A.subarray(B,B*2));if(!S(T,I))throw new Error("bad point: is not on curve");return{x:T,y:I}}else throw new Error(`bad point: got length ${y}, expected compressed=${b} or uncompressed=${m}`)}let d=t.toBytes||h,p=t.fromBytes||f;function x(L){let b=n.sqr(L),m=n.mul(b,L);return n.add(n.add(m,n.mul(L,s.a)),s.b)}function S(L,b){let m=n.sqr(b),y=x(L);return n.eql(m,y)}if(!S(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let g=n.mul(n.pow(s.a,Jn),pd),_=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(g,_)))throw new Error("bad curve params: a or b");function w(L,b,m=!1){if(!n.isValid(b)||m&&n.is0(b))throw new Error(`bad point coordinate ${L}`);return b}function C(L){if(!(L instanceof E))throw new Error("ProjectivePoint expected")}function P(L){if(!c||!c.basises)throw new Error("no endo");return dd(L,c.basises,o.ORDER)}let q=pr((L,b)=>{let{X:m,Y:y,Z:v}=L;if(n.eql(v,n.ONE))return{x:m,y};let A=L.is0();b==null&&(b=A?n.ONE:n.inv(v));let B=n.mul(m,b),T=n.mul(y,b),I=n.mul(v,b);if(A)return{x:n.ZERO,y:n.ZERO};if(!n.eql(I,n.ONE))throw new Error("invZ was invalid");return{x:B,y:T}}),K=pr(L=>{if(L.is0()){if(t.allowInfinityPoint&&!n.is0(L.Y))return;throw new Error("bad point: ZERO")}let{x:b,y:m}=L.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(!L.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function N(L,b,m,y,v){return m=new E(n.mul(m.X,L),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 s}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(){K(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:T}=b,I=n.eql(n.mul(m,T),n.mul(A,v)),O=n.eql(n.mul(y,T),n.mul(B,v));return I&&O}negate(){return new E(this.X,n.neg(this.Y),this.Z)}double(){let{a:b,b:m}=s,y=n.mul(m,Jn),{X:v,Y:A,Z:B}=this,T=n.ZERO,I=n.ZERO,O=n.ZERO,M=n.mul(v,v),nt=n.mul(A,A),Q=n.mul(B,B),G=n.mul(v,A);return G=n.add(G,G),O=n.mul(v,B),O=n.add(O,O),T=n.mul(b,O),I=n.mul(y,Q),I=n.add(T,I),T=n.sub(nt,I),I=n.add(nt,I),I=n.mul(T,I),T=n.mul(G,T),O=n.mul(y,O),Q=n.mul(b,Q),G=n.sub(M,Q),G=n.mul(b,G),G=n.add(G,O),O=n.add(M,M),M=n.add(O,M),M=n.add(M,Q),M=n.mul(M,G),I=n.add(I,M),Q=n.mul(A,B),Q=n.add(Q,Q),M=n.mul(Q,G),T=n.sub(T,M),O=n.mul(Q,nt),O=n.add(O,O),O=n.add(O,O),new E(T,I,O)}add(b){C(b);let{X:m,Y:y,Z:v}=this,{X:A,Y:B,Z:T}=b,I=n.ZERO,O=n.ZERO,M=n.ZERO,nt=s.a,Q=n.mul(s.b,Jn),G=n.mul(m,A),ot=n.mul(y,B),ht=n.mul(v,T),_t=n.add(m,y),st=n.add(A,B);_t=n.mul(_t,st),st=n.add(G,ot),_t=n.sub(_t,st),st=n.add(m,v);let bt=n.add(A,T);return st=n.mul(st,bt),bt=n.add(G,ht),st=n.sub(st,bt),bt=n.add(y,v),I=n.add(B,T),bt=n.mul(bt,I),I=n.add(ot,ht),bt=n.sub(bt,I),M=n.mul(nt,st),I=n.mul(Q,ht),M=n.add(I,M),I=n.sub(ot,M),M=n.add(ot,M),O=n.mul(I,M),ot=n.add(G,G),ot=n.add(ot,G),ht=n.mul(nt,ht),st=n.mul(Q,st),ot=n.add(ot,ht),ht=n.sub(G,ht),ht=n.mul(nt,ht),st=n.add(st,ht),G=n.mul(ot,st),O=n.add(O,G),G=n.mul(bt,st),I=n.mul(_t,I),I=n.sub(I,G),G=n.mul(_t,ot),M=n.mul(bt,M),M=n.add(M,G),new E(I,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,T=>fe(E,T));if(m){let{k1neg:B,k1:T,k2neg:I,k2:O}=P(b),{p:M,f:nt}=A(T),{p:Q,f:G}=A(O);v=nt.add(G),y=N(m.beta,M,Q,B,I)}else{let{p:B,f:T}=A(b);y=B,v=T}return fe(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===ye||y.is0())return E.ZERO;if(b===_r)return y;if(U.hasCache(this))return this.multiply(b);if(m){let{k1neg:v,k1:A,k2neg:B,k2:T}=P(b),{p1:I,p2:O}=jc(E,y,A,T);return N(m.beta,I,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 q(this,b)}isTorsionFree(){let{isTorsionFree:b}=t;return i===_r?!0:b?b(E,this):U.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:b}=t;return i===_r?this:b?b(E,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(b=!0){return ce(b,"isCompressed"),this.assertValidity(),d(E,this,b)}toHex(b=!0){return Kt(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 fe(E,b)}static msm(b,m){return gr(E,o,b,m)}static fromPrivateKey(b){return E.BASE.multiply(vr(o,b))}}E.BASE=new E(s.Gx,s.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 yr(E,t.endo?Math.ceil(D/2):D);return E.BASE.precompute(8),E}function vu(r){return Uint8Array.of(r?2:3)}function _u(r,t){return{secretKey:t.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function yd(r,t={}){let{Fn:e}=r,n=t.randomBytes||hr,o=Object.assign(_u(r.Fp,e),{seed:Ks(e.ORDER)});function s(d){try{return!!vr(e,d)}catch{return!1}}function i(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 qs(Ot(d,o.seed,"seed"),e.ORDER)}function c(d,p=!0){return r.BASE.multiply(vr(e,d)).toBytes(p)}function u(d){let p=a(d);return{secretKey:p,publicKey:c(p)}}function l(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 h(d,p,x=!0){if(l(d)===!0)throw new Error("first arg must be private key");if(l(p)===!1)throw new Error("second arg must be public key");let S=vr(e,d);return r.fromHex(p).multiply(S).toBytes(x)}return Object.freeze({getPublicKey:c,getSharedSecret:h,keygen:u,Point:r,utils:{isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a,isValidPrivateKey:s,randomPrivateKey:a,normPrivateKeyToScalar:d=>vr(e,d),precompute(d=8,p=r.BASE){return p.precompute(d,!1)}},lengths:o})}function gd(r,t,e={}){On(t),Te(e,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let n=e.randomBytes||hr,o=e.hmac||((m,...y)=>Ti(t,m,St(...y))),{Fp:s,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:u,getPublicKey:l,getSharedSecret:h,utils:f,lengths:d}=yd(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>>_r;return m>y}function g(m,y){if(!i.isValidNot0(y))throw new Error(`invalid signature ${m}: out of range 1..Point.Fn.ORDER`);return y}function _(m,y){Ci(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}=me.toSig(Ot(y));return new w(O,M)}v==="recovered"&&(A=y[0],v="compact",y=y.subarray(1));let B=i.BYTES,T=y.subarray(0,B),I=y.subarray(B,B*2);return new w(i.fromBytes(T),i.fromBytes(I),A)}static fromHex(y,v){return this.fromBytes(Me(y),v)}addRecoveryBit(y){return new w(this.r,this.s,y)}recoverPublicKey(y){let v=s.ORDER,{r:A,s:B,recovery:T}=this;if(T==null||![0,1,2,3].includes(T))throw new Error("recovery id invalid");if(a*Su<v&&T>1)throw new Error("recovery id is ambiguous for h>1 curve");let O=T===2||T===3?A+a:A;if(!s.isValid(O))throw new Error("recovery id 2 or 3 invalid");let M=s.toBytes(O),nt=r.fromBytes(St(vu((T&1)===0),M)),Q=i.inv(O),G=P(Y("msgHash",y)),ot=i.create(-G*Q),ht=i.create(B*Q),_t=r.BASE.multiplyUnsafe(ot).add(nt.multiplyUnsafe(ht));if(_t.is0())throw new Error("point at infinify");return _t.assertValidity(),_t}hasHighS(){return S(this.s)}toBytes(y=x){if(Ci(y),y==="der")return Me(me.hexFromSig(this));let v=i.toBytes(this.r),A=i.toBytes(this.s);if(y==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return St(Uint8Array.of(this.recovery),v,A)}return St(v,A)}toHex(y){return Kt(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,i.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Kt(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Kt(this.toBytes("compact"))}}let C=e.bits2int||function(y){if(y.length>8192)throw new Error("input is too large");let v=dr(y),A=y.length*8-c;return A>0?v>>BigInt(A):v},P=e.bits2int_modN||function(y){return i.create(C(y))},q=Ae(c);function K(m){return jr("num < 2^"+c,m,ye,q),i.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(ot=>ot in v))throw new Error("sign() legacy options not supported");let{lowS:A,prehash:B,extraEntropy:T}=Ii(v,p);m=N(m,B);let I=P(m),O=vr(i,y),M=[K(O),K(I)];if(T!=null&&T!==!1){let ot=T===!0?n(d.secretKey):T;M.push(Y("extraEntropy",ot))}let nt=St(...M),Q=I;function G(ot){let ht=C(ot);if(!i.isValidNot0(ht))return;let _t=i.inv(ht),st=r.BASE.multiply(ht).toAffine(),bt=i.create(st.x);if(bt===ye)return;let En=i.create(_t*i.create(Q+bt*O));if(En===ye)return;let Na=(st.x===bt?0:2)|Number(st.y&_r),Ua=En;return A&&S(En)&&(Ua=i.neg(En),Na^=1),new w(bt,Ua,Na)}return{seed:nt,k2sig:G}}function D(m,y,v={}){m=Y("message",m);let{seed:A,k2sig:B}=E(m,y,v);return Nc(t.outputLen,i.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 me.Err))throw B}if(!y)try{y=w.fromBytes(Y("sig",m),"compact")}catch{return!1}}return y||!1}function L(m,y,v,A={}){let{lowS:B,prehash:T,format:I}=Ii(A,p);if(v=Y("publicKey",v),y=N(Y("message",y),T),"strict"in A)throw new Error("options.strict was renamed to lowS");let O=I===void 0?U(m):w.fromBytes(Y("sig",m),I);if(O===!1)return!1;try{let M=r.fromBytes(v);if(B&&O.hasHighS())return!1;let{r:nt,s:Q}=O,G=P(y),ot=i.inv(Q),ht=i.create(G*ot),_t=i.create(nt*ot),st=r.BASE.multiplyUnsafe(ht).add(M.multiplyUnsafe(_t));return st.is0()?!1:i.create(st.x)===nt}catch{return!1}}function b(m,y,v={}){let{prehash:A}=Ii(v,p);return y=N(y,A),w.fromBytes(m,"recovered").recoverPublicKey(y).toBytes()}return Object.freeze({keygen:u,getPublicKey:l,getSharedSecret:h,utils:f,lengths:d,Point:r,sign:D,verify:L,recoverPublicKey:b,Signature:w,hash:t})}function bd(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(i=>Math.ceil(i/2)))):void 0,o=Nt(t.n,{BITS:r.nBitLength,allowedLengths:n,modFromBytes:r.wrapPrivateKey}),s={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:s}}function wd(r){let{CURVE:t,curveOpts:e}=bd(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 xd(r,t){let e=t.Point;return Object.assign({},t,{ProjectivePoint:e,CURVE:Object.assign({},r,Vn(e.Fn.ORDER,e.Fn.BITS))})}function Au(r){let{CURVE:t,curveOpts:e,hash:n,ecdsaOpts:o}=wd(r),s=md(t,e),i=gd(s,n,o);return xd(r,i)}function Tu(r,t){let e=n=>Au({...r,hash:n});return{...e(t),create:e}}var Bi={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Ed={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Iu=BigInt(2);function Sd(r){let t=Bi.p,e=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=r*r*r%t,l=u*u*r%t,h=tt(l,e,t)*l%t,f=tt(h,e,t)*l%t,d=tt(f,Iu,t)*u%t,p=tt(d,o,t)*d%t,x=tt(p,s,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)*l%t,C=tt(w,i,t)*p%t,P=tt(C,n,t)*u%t,q=tt(P,Iu,t);if(!Li.eql(Li.sqr(q),r))throw new Error("Cannot find square root");return q}var Li=Nt(Bi.p,{sqrt:Sd}),Ar=Tu({...Bi,Fp:Li,lowS:!0,endo:Ed},kn);function Cu(r,t,e,n){let o=cr.digest(e instanceof Uint8Array?e:e.subarray());if($n(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),Ar.verify(t,s,r))).catch(s=>{throw s.name==="AbortError"?s:new en(String(s))});try{return n?.signal?.throwIfAborted(),Ar.verify(t,o.digest,r)}catch(s){throw new en(String(s))}}var to=class{type="secp256k1";raw;_key;constructor(t){this._key=Lu(t),this.raw=Du(this._key)}toMultihash(){return Ht.digest(Yt(this))}toCID(){return lt.createV1(114,this.toMultihash())}toString(){return et.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._key,e,t,n)}};function Ri(r){return new to(r)}function Du(r){return Ar.ProjectivePoint.fromHex(r).toRawBytes(!0)}function Lu(r){try{return Ar.ProjectivePoint.fromHex(r),r}catch(t){throw new er(String(t))}}function Bu(r,t){let{Type:e,Data:n}=jt.decode(r),o=n??new Uint8Array;switch(e){case ut.RSA:return vi(o,t);case ut.Ed25519:return js(o);case ut.secp256k1:return Ri(o);case ut.ECDSA:return As(o);default:throw new rr}}function Ru(r){let{Type:t,Data:e}=jt.decode(r.digest),n=e??new Uint8Array;switch(t){case ut.Ed25519:return js(n);case ut.secp256k1:return Ri(n);case ut.ECDSA:return As(n);default:throw new rr}}function Yt(r){return jt.encode({Type:ut[r.type],Data:r.raw})}var Pu=Symbol.for("nodejs.util.inspect.custom"),vd=114,un=class{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Xo]=!0;toString(){return this.string==null&&(this.string=et.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return lt.createV1(vd,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")}[Pu](){return`PeerId(${this.toString()})`}},eo=class extends un{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},ro=class extends un{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},no=class extends un{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},_d=2336,ln=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=Ht.digest(k(this.url))}[Pu](){return`PeerId(${this.url})`}[Xo]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return lt.createV1(_d,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=z(t)),t.toString()===this.toString())}};var Ad=114,Ou=2336;function Pi(r,t){let e;if(r.charAt(0)==="1"||r.charAt(0)==="Q")e=Zt(et.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return Td(lt.parse(r));if(t==null)throw new it('Please pass a multibase decoder for strings that do not start with "1" or "Q"');e=Zt(t.decode(r))}return Tr(e)}function Tr(r){if(Cd(r))return new eo({multihash:r});if(Id(r))try{let t=Ru(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=z(r.digest);return new ln(new URL(e))}throw new _n("Supplied PeerID Multihash is invalid")}function Td(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==Ad&&r.code!==Ou)throw new vn("Supplied PeerID CID is invalid");if(r.code===Ou){let t=z(r.multihash.digest);return new ln(new URL(t))}return Tr(r.multihash)}function Id(r){return r.code===Ht.code}function Cd(r){return r.code===cr.code}var fn;(function(r){let t;r.codec=()=>(t==null&&(t=Pt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.publicKey!=null&&e.publicKey.byteLength>0&&(n.uint32(10),n.bytes(e.publicKey)),e.payloadType!=null&&e.payloadType.byteLength>0&&(n.uint32(18),n.bytes(e.payloadType)),e.payload!=null&&e.payload.byteLength>0&&(n.uint32(26),n.bytes(e.payload)),e.signature!=null&&e.signature.byteLength>0&&(n.uint32(42),n.bytes(e.signature)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={publicKey:rt(0),payloadType:rt(0),payload:rt(0),signature:rt(0)},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.publicKey=e.bytes();break}case 2:{s.payloadType=e.bytes();break}case 3:{s.payload=e.bytes();break}case 5:{s.signature=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Rt(e,r.codec()),r.decode=(e,n)=>Bt(e,r.codec(),n)})(fn||(fn={}));var oo=class extends Error{constructor(t="Invalid signature"){super(t),this.name="InvalidSignatureError"}};var hn=class r{static createFromProtobuf=t=>{let e=fn.decode(t),n=Bu(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,s=t.codec,i=t.marshal(),a=Nu(o,s,i),c=await e.sign(a.subarray(),n);return new r({publicKey:e.publicKey,payloadType:s,payload:i,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:s}=t;this.publicKey=e,this.payloadType=n,this.payload=o,this.signature=s}marshal(){return this.marshaled==null&&(this.marshaled=fn.encode({publicKey:Yt(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=Nu(t,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,e)}},Nu=(r,t,e)=>{let n=k(r),o=xr(n.byteLength),s=xr(t.length),i=xr(e.length);return new J(o,n,s,t,i,e)};var gt=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},ge=class extends Error{static name="ValidationError";name="ValidationError"},so=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},io=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var ao=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 s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*o)-1;for(;;){let l=this.readAtomically(()=>{let h=this.readChar();if(h===void 0)return;let f=Number.parseInt(h,t);if(!Number.isNaN(f))return f});if(l===void 0)break;if(s*=t,s+=l,s>u||(i+=1,e!==void 0&&i>e))return}if(i!==0)return!n&&c&&i>1?void 0:s})}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 i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return e[o]=i[0],e[o+1]=i[1],e[o+2]=i[2],e[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];e[o]=s>>8,e[o+1]=s&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 s=new Uint8Array(14),i=16-(n+2),[a]=t(s.subarray(0,i));return e.set(s.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Dd=45,Ld=15,co=new ao;function Uu(r){if(!(r.length>Ld))return co.new(r).parseWith(()=>co.readIPv4Addr())}function Mu(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Dd))return co.new(r).parseWith(()=>co.readIPv6Addr())}function uo(r){return!!Uu(r)}function ku(r){return!!Mu(r)}function Ni(r){return t=>z(t,r)}function Ui(r){return t=>k(t,r)}function Ir(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Ge(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(t)}function Ku(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=Ge(n);return re([e,o],e.length+o.length)}function qu(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=xe.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=Ge(n);return re([e,o],e.length+o.length)}function Mi(r){let t=r.subarray(0,r.length-2),e=r.subarray(r.length-2),n=z(t,"base32"),o=Ir(e);return`${n}:${o}`}var ki=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},Vu=function(r){let t=0;r=r.toString().trim();let e=r.split(":",8),n;for(n=0;n<e.length;n++){let s=uo(e[n]),i;s&&(i=ki(e[n]),e[n]=z(i.subarray(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,z(i.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 s=[n,1];for(n=9-e.length;n>0;n--)s.push("0");e.splice.apply(e,s)}let o=new Uint8Array(t+16);for(n=0;n<e.length;n++){e[n]===""&&(e[n]="0");let s=parseInt(e[n],16);if(isNaN(s)||s<0||s>65535)throw new gt("Invalid byte value in IP address");o[t++]=s>>8&255,o[t++]=s&255}return o},Hu=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(".")},Fu=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],s=r[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;t.push(i)}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 zu(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 Oi=Object.values(Hr).map(r=>r.decoder),Bd=(function(){let r=Oi[0].or(Oi[1]);return Oi.slice(2).forEach(t=>r=r.or(t)),r})();function Gu(r){return Bd.decode(r)}function $u(r){return t=>r.encoder.encode(t)}function Rd(r){if(parseInt(r).toString()!==r)throw new ge("Value must be an integer")}function Pd(r){if(r<0)throw new ge("Value must be a positive integer, or zero")}function Od(r){return t=>{if(t>r)throw new ge(`Value must be smaller than or equal to ${r}`)}}function Nd(...r){return t=>{for(let e of r)e(t)}}var dn=Nd(Rd,Pd,Od(65535));var mt=-1,Ki=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)}))}},be=new Ki,Xd=[{code:4,name:"ip4",size:32,valueToBytes:ki,bytesToValue:Hu,validate:r=>{if(!uo(r))throw new ge(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Ge,bytesToValue:Ir,validate:dn},{code:273,name:"udp",size:16,valueToBytes:Ge,bytesToValue:Ir,validate:dn},{code:33,name:"dccp",size:16,valueToBytes:Ge,bytesToValue:Ir,validate:dn},{code:41,name:"ip6",size:128,valueToBytes:Vu,bytesToValue:Fu,stringToValue:zu,validate:r=>{if(!ku(r))throw new ge(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:mt},{code:43,name:"ipcidr",size:8,bytesToValue:Ni("base10"),valueToBytes:Ui("base10")},{code:53,name:"dns",size:mt},{code:54,name:"dns4",size:mt},{code:55,name:"dns6",size:mt},{code:56,name:"dnsaddr",size:mt},{code:132,name:"sctp",size:16,valueToBytes:Ge,bytesToValue:Ir,validate:dn},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:mt,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:mt,bytesToValue:Ni("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Ui("base58btc")(r):lt.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Mi,valueToBytes:Ku},{code:445,name:"onion3",size:296,bytesToValue:Mi,valueToBytes:qu},{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:$u(hs),valueToBytes:Gu},{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}];Xd.forEach(r=>{be.addProtocol(r)});function Wu(r){let t=[],e=0;for(;e<r.length;){let n=rn(r,e),o=be.getProtocol(n),s=Lt(n),i=jd(o,r,e+s),a=0;i>0&&o.size===mt&&(a=Lt(i));let c=s+a+i,u={code:n,name:o.name,bytes:r.subarray(e,e+c)};if(i>0){let l=e+s+a,h=r.subarray(l,l+i);u.value=o.bytesToValue?.(h)??z(h)}t.push(u),e+=c}return t}function Zu(r){let t=0,e=[];for(let n of r){if(n.bytes==null){let o=be.getProtocol(n.code),s=Lt(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??k(n.value),a=i.byteLength,o.size===mt&&(c=Lt(a)));let u=new Uint8Array(s+c+a),l=0;wr(n.code,u,l),l+=s,i!=null&&(o.size===mt&&(wr(a,u,l),l+=c),u.set(i,l)),n.bytes=u}e.push(n.bytes),t+=n.bytes.byteLength}return re(e,t)}function Yu(r){if(r.charAt(0)!=="/")throw new gt('String multiaddr must start with "/"');let t=[],e="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(e==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=be.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 Xu(r){return`/${r.flatMap(t=>{if(t.value==null)return t.name;let e=be.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 jd(r,t,e){return r.size==null||r.size===0?0:r.size>0?r.size/8:rn(t,e)}var Qd=Symbol.for("nodejs.util.inspect.custom"),ra=Symbol.for("@multiformats/multiaddr");function Jd(r){if(r==null&&(r="/"),ju(r))return r.getComponents();if(r instanceof Uint8Array)return Wu(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),Yu(r);if(Array.isArray(r))return r;throw new gt("Must be a string, Uint8Array, Component[], or another Multiaddr")}var po=class r{[ra]=!0;#t;#e;#r;constructor(t="/",e={}){this.#t=Jd(t),e.validate!==!1&&tp(this)}get bytes(){return this.#r==null&&(this.#r=Zu(this.#t)),this.#r}toString(){return this.#e==null&&(this.#e=Xu(this.#t)),this.#e}toJSON(){return this.toString()}getComponents(){return[...this.#t.map(t=>({...t}))]}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 so(`Address ${this.toString()} does not contain subaddress: ${e}`);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})}equals(t){return ft(this.bytes,t.bytes)}[Qd](){return`Multiaddr(${this.toString()})`}};function tp(r){r.getComponents().forEach(t=>{let e=be.getProtocol(t.code);t.value!=null&&e.validate?.(t.value)})}function ju(r){return!!r?.[ra]}function Mt(r){return new po(r)}var na={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Qu={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Ju=new globalThis.TextEncoder;function ep(r,t){let e=na[t],n=Qu[t];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(t,n*e);return n}function rp(r,t,e){if(e.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=na[t],o=Qu[t],s=r;for(;s.length>0;){let i=Ju.encodeInto(s,e);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(e[a]),o=BigInt.asUintN(t,o*n)}return o}function oa(r,{size:t=32,utf8Buffer:e}={}){if(!na[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 rp(r,t,e);r=Ju.encode(r)}return ep(r,t)}var pn={hash:r=>Number(oa(r,{size:32})),hashV:(r,t)=>np(pn.hash(r,t))};function np(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),k(t,"base16")}var sa=64,Gt=class{fp;h;seed;constructor(t,e,n,o=2){if(o>sa)throw new TypeError("Invalid Fingerprint Size");let s=e.hashV(t,n),i=rt(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,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 Ye(r,t){return Math.floor(Math.random()*(t-r))+r}var Xe=class{contents;constructor(t){this.contents=new Array(t).fill(null)}has(t){if(!(t instanceof Gt))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof Gt))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 Gt))throw new TypeError("Invalid Fingerprint");let e=Ye(0,this.contents.length-1),n=this.contents[e];return this.contents[e]=t,n}remove(t){if(!(t instanceof Gt))throw new TypeError("Invalid Fingerprint");let e=this.contents.findIndex(n=>t.equals(n));return e>-1?(this.contents[e]=null,!0):!1}};var op=500,mn=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??pn,this.seed=t.seed??Ye(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=k(t));let e=new Gt(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 Xe(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new Xe(this.bucketSize)),this.buckets[n].add(e)||this.buckets[o].add(e))return this.count++,!0;let s=[n,o],i=s[Ye(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new Xe(this.bucketSize));for(let a=0;a<op;a++){let c=this.buckets[i].swap(e);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new Xe(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(t){typeof t=="string"&&(t=k(t));let e=new Gt(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 s=(n^e.hash())%this.filterSize;return this.buckets[s]?.has(e)??!1}remove(t){typeof t=="string"&&(t=k(t));let e=new Gt(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 s=(n^e.hash())%this.filterSize,i=this.buckets[s]?.remove(e)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},sp={1:.5,2:.84,4:.95,8:.98};function ip(r=.001){return r>.002?2:r>1e-5?4:8}function tl(r,t=.001){let e=ip(t),n=sp[e],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),sa);return{filterSize:o,bucketSize:e,fingerprintSize:s}}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??pn,this.seed=t.seed??Ye(0,Math.pow(2,10)),this.filterSeries=[new mn({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 mn({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 Br(r,t=.001,e){return new mo({...tl(r,t),...e??{}})}function $t(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var yo=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 yo(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 yo(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 ia=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function Le(r={}){return ap(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 ap(r,t){t=t??{};let e=t.onEnd,n=new Rr,o,s,i,a=$t(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((S,g)=>{s=_=>{s=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=>s!=null?s(S):(n.push(S),o),l=S=>(n=new Rr,s!=null?s({error:S}):(n.push({error:S}),o)),h=S=>{if(i)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})},f=S=>i?o:(i=!0,S!=null?l(S):u({done:!0})),d=()=>(n=new Rr,f(),{done:!0}),p=S=>(f(S),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:d,throw:p,push:h,end:f,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,P)=>{w=()=>{P(new ia)},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:h,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}var aa=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},ca=class extends Error{constructor(t){super(),this.name="AbortError",this.message=t}},el=r=>globalThis.DOMException===void 0?new ca(r):new DOMException(r),rl=r=>{let t=r.reason===void 0?el("This operation was aborted."):r.reason;return t instanceof Error?t:el(t)};function ua(r,t){let{milliseconds:e,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=t,i,a,u=new Promise((l,h)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(t.signal){let{signal:d}=t;d.aborted&&h(rl(d)),a=()=>{h(rl(d))},d.addEventListener("abort",a,{once:!0})}if(e===Number.POSITIVE_INFINITY){r.then(l,h);return}let f=new aa;i=s.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(d){h(d)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?l():o instanceof Error?h(o):(f.message=o??`Promise timed out after ${e} milliseconds`,h(f))},e),(async()=>{try{l(await r)}catch(d){h(d)}})()}).finally(()=>{u.clear(),a&&t.signal&&t.signal.removeEventListener("abort",a)});return u.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},u}var cp=r=>{let t=r.addEventListener||r.on||r.addListener,e=r.removeEventListener||r.off||r.removeListener;if(!t||!e)throw new TypeError("Emitter is not compatible");return{addListener:t.bind(r),removeListener:e.bind(r)}};function up(r,t,e){let n,o=new Promise((s,i)=>{if(e={rejectionEvents:["error"],multiArgs:!1,resolveImmediately:!1,...e},!(e.count>=0&&(e.count===Number.POSITIVE_INFINITY||Number.isInteger(e.count))))throw new TypeError("The `count` option should be at least 0 or more");e.signal?.throwIfAborted();let a=[t].flat(),c=[],{addListener:u,removeListener:l}=cp(r),h=(...d)=>{let p=e.multiArgs?d:d[0];e.filter&&!e.filter(p)||(c.push(p),e.count===c.length&&(n(),s(c)))},f=d=>{n(),i(d)};n=()=>{for(let d of a)l(d,h);for(let d of e.rejectionEvents)l(d,f)};for(let d of a)u(d,h);for(let d of e.rejectionEvents)u(d,f);e.signal&&e.signal.addEventListener("abort",()=>{f(e.signal.reason)},{once:!0}),e.resolveImmediately&&s(c)});if(o.cancel=n,typeof e.timeout=="number"){let s=ua(o,{milliseconds:e.timeout});return s.cancel=n,s}return o}function Qt(r,t,e){typeof e=="function"&&(e={filter:e}),e={...e,count:1,resolveImmediately:!1};let n=up(r,t,e),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function la(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"}},je=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"};function lp(r){return r.reason}async function bo(r,t,e){if(t==null)return r;let n=e?.translateError??lp;if(t.aborted)return r.catch(()=>{}),Promise.reject(n(t));let o;try{return await Promise.race([r,new Promise((s,i)=>{o=()=>{i(n(t))},t.addEventListener("abort",o)})])}finally{o!=null&&t.removeEventListener("abort",o)}}var wo=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 Jt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function fp(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var xo=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=fp(),this.status="queued",this.fn=t,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(t){this.controller.abort(t)}onAbort(){this.recipients.reduce((e,n)=>e&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Jt),this.cleanup())}async join(t={}){let e=new wo(t.signal);return this.recipients.push(e),t.signal?.addEventListener("abort",this.onAbort),e.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let t=await bo(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(e=>{e.deferred.resolve(t)}),this.status="complete"}catch(t){this.recipients.forEach(e=>{e.deferred.reject(t)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(t=>{t.cleanup(),t.signal?.removeEventListener("abort",this.onAbort)})}};var Eo=class extends Tt{concurrency;maxSize;queue;pending;sort;paused;constructor(t={}){super(),this.concurrency=t.concurrency??Number.POSITIVE_INFINITY,this.maxSize=t.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,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=la(this.emitEmpty.bind(this),1),this.emitIdle=la(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let 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 xo(t,e);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(e).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,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 Jt)}),this.clear()}async onEmpty(t){this.size!==0&&await Qt(this,"empty",t)}async onSizeLessThan(t,e){this.size<t||await Qt(this,"next",{...e,filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await Qt(this,"idle",t)}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=Le({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),e.end(c)},o=c=>{c.detail!=null&&e.push(c.detail)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new Jt("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",s),this.addEventListener("idle",i),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),t?.signal?.removeEventListener("abort",a),n()}}};var hp=Math.pow(2,20)*4,So=class extends Tt{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;constructor(t){super(),this.status="open",this.log=t.log,this.direction=t.direction??"outbound",this.inactivityTimeout=t.inactivityTimeout??12e4,this.maxReadBufferLength=t.maxReadBufferLength??hp,this.maxWriteBufferLength=t.maxWriteBufferLength,this.maxMessageSize=t.maxMessageSize,this.readBuffer=new J,this.writeBuffer=new J,this.readStatus="readable",this.remoteReadStatus="readable",this.writeStatus="writable",this.remoteWriteStatus="writable",this.sendingData=!1,this.writableNeedsDrain=!1,this.timeline={open:Date.now()},this.processSendQueue=this.processSendQueue.bind(this);let e=()=>{this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,this.processSendQueue()};this.addEventListener("drain",e)}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let t=Le(),e=s=>{t.push(s.data)};this.addEventListener("message",e);let n=s=>{t.end(s.error)};this.addEventListener("close",n);let o=()=>{t.end()};this.addEventListener("remoteCloseWrite",o);try{yield*t}finally{this.removeEventListener("message",e),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",o)}}isReadable(){return this.status==="open"}send(t){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new Oe(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",t.byteLength),this.writeBuffer.append(t),this.processSendQueue()}abort(t){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",t),this.status="aborted",this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle")),this.writeStatus="closed",this.remoteWriteStatus="closed",this.readStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now();try{this.sendReset(t)}catch(e){this.log("failed to send reset to remote - %e",e)}this.dispatchEvent(new Cn(t))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Oe("Cannot pause a stream that is closing/closed");this.readStatus!=="paused"&&(this.readStatus="paused",this.sendPause())}resume(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Oe("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(t){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Oe(`Cannot push data onto a stream that is ${this.readStatus}`);if(t.byteLength!==0){if(this.readBuffer.append(t),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(t){if(t.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(t),this.dispatchReadBuffer()}}addEventListener(...t){super.addEventListener.apply(this,t),t[0]==="message"&&this.readBuffer.byteLength>0&&queueMicrotask(()=>{this.dispatchReadBuffer()})}onRemoteReset(){this.log("remote reset"),this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.readBuffer.byteLength===0&&(this.readStatus="closed");let t=new Sn;this.dispatchEvent(new Dn(t))}onTransportClosed(t){this.log("transport closed"),this.readStatus==="readable"&&this.readBuffer.byteLength===0&&(this.readStatus="closed"),this.remoteReadStatus!=="closed"&&(this.remoteReadStatus="closed"),this.remoteWriteStatus!=="closed"&&(this.remoteWriteStatus="closed"),this.writeStatus!=="closed"&&(this.writeStatus="closed"),t!=null?this.abort(t):(this.status==="open"||this.status==="closing")&&(this.timeline.close=Date.now(),this.status="closed",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.dispatchEvent(new nr))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.writeStatus==="closed"&&this.onTransportClosed())}onRemoteCloseRead(){this.log.trace("on remote close read"),this.remoteReadStatus="closed",this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle"))}processSendQueue(){if(this.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(this.writeBuffer.byteLength===0)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let t=!0,e=this.writeBuffer.byteLength,n=0;for(;this.writeBuffer.byteLength>0;){let o=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(o===0){t=!1;break}let s=this.writeBuffer.sublist(0,o),i=new J(s);this.writeBuffer.consume(s.byteLength);let a=this.sendData(s);if(t=a.canSendMore,n+=a.sentBytes,a.sentBytes!==i.byteLength&&(i.consume(a.sentBytes),this.writeBuffer.prepend(i)),!t)break}return t||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",n,e,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),t}finally{this.sendingData=!1}}dispatchReadBuffer(){try{if(this.listenerCount("message")===0){this.log.trace("not dispatching pause buffer as there are no listeners for the message event");return}if(this.readBuffer.byteLength===0){this.log.trace("not dispatching pause buffer as there is no data to dispatch");return}if(this.readStatus==="paused"){this.log.trace("not dispatching pause buffer we are paused");return}if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("dropping %d bytes because the readable end is %s",this.readBuffer.byteLength,this.readStatus),this.readBuffer.consume(this.readBuffer.byteLength);return}let t=this.readBuffer.sublist();this.readBuffer.consume(t.byteLength),this.dispatchEvent(new In(t))}finally{this.remoteWriteStatus==="closed"&&(this.readStatus="closed"),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new Mr(`Read buffer length of ${this.readBuffer.byteLength} exceeded limit of ${this.maxReadBufferLength}, read status is ${this.readStatus}`))}checkWriteBufferLength(){this.maxWriteBufferLength!=null&&this.writeBuffer.byteLength>this.maxWriteBufferLength&&this.abort(new Mr(`Write buffer length of ${this.writeBuffer.byteLength} exceeded limit of ${this.maxWriteBufferLength}, write status is ${this.writeStatus}`))}onMuxerNeedsDrain(){this.writableNeedsDrain=!0}onMuxerDrain(){this.safeDispatchEvent("drain")}};var vo=class extends So{remoteAddr;metricPrefix;metrics;constructor(t){super(t),this.metricPrefix=t.metricPrefix??"",this.metrics=t.metrics,this.remoteAddr=t.remoteAddr,this.addEventListener("close",e=>{this.metrics?.increment({[`${this.metricPrefix}end`]:!0}),e.error!=null?e.local?this.metrics?.increment({[`${this.metricPrefix}abort`]:!0}):this.metrics?.increment({[`${this.metricPrefix}reset`]:!0}):e.local?this.metrics?.increment({[`${this.metricPrefix}_local_close`]:!0}):this.metrics?.increment({[`${this.metricPrefix}_remote_close`]:!0})})}async close(t){this.status==="open"&&(this.status="closing",this.writeStatus="closing",this.remoteWriteStatus="closing",this.remoteReadStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Qt(this,"idle",{...t,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Qt(this,"drain",{...t,rejectionEvents:["close"]})),await this.sendClose(t),this.onTransportClosed())}};function _o(r){let t=new globalThis.AbortController;function e(){t.abort();for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",e)}for(let s of r){if(s?.aborted===!0){e();break}s?.addEventListener!=null&&s.addEventListener("abort",e)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",e)}let o=t.signal;return o.clear=n,o}var Ao=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 nl(r,t,e){if(t==null)return r;if(t.aborted)return r.catch(()=>{}),Promise.reject(new Ao(e?.errorMessage,e?.errorCode,e?.errorName));let n,o=new Ao(e?.errorMessage,e?.errorCode,e?.errorName);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},t.addEventListener("abort",n)})])}finally{n!=null&&t.removeEventListener("abort",n)}}var fa=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 nl(this.readNext.promise,e?.signal,e)}};function ol(){return new fa}function dp(r){return r[Symbol.asyncIterator]!=null}async function pp(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*mp(r){let t=new AbortController,e=ol();pp(r,e,t.signal).catch(()=>{});try{yield*e}finally{t.abort()}}function*yp(r){for(let t of r)yield*t}function gp(...r){let t=[];for(let e of r)dp(e)||t.push(e);return t.length===r.length?yp(t):mp(r)}var sl=gp;function il(r,...t){if(r==null)throw new Error("Empty pipeline");if(ha(r)){let n=r;r=()=>n.source}else if(cl(r)||al(r)){let n=r;r=()=>n}let e=[r,...t];if(e.length>1&&ha(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++)ha(e[n])&&(e[n]=wp(e[n]));return bp(...e)}var bp=(...r)=>{let t;for(;r.length>0;)t=r.shift()(t);return t},al=r=>r?.[Symbol.asyncIterator]!=null,cl=r=>r?.[Symbol.iterator]!=null,ha=r=>r==null?!1:r.sink!=null&&r.source!=null,wp=r=>t=>{let e=r.sink(t);if(e?.then!=null){let n=Le({objectMode:!0});e.then(()=>{n.end()},i=>{n.end(i)});let o,s=r.source;if(al(s))o=async function*(){yield*s,n.end()};else if(cl(s))o=function*(){yield*s,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return sl(n,o())}return r.source};var xp=4194304,To=class extends Error{static name="UnwrappedError";name="UnwrappedError"},pa=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},ma=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},ya=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Ep(r){return typeof r?.closeRead=="function"}function Sp(r){return typeof r?.close=="function"}function da(r){return Ep(r)?r.readStatus==="closing"||r.readStatus==="closed":Sp(r)?r.status!=="open":!1}function vp(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function _p(r,t){let e=t?.maxBufferSize??xp,n=new J,o=Promise.withResolvers(),s=!1;if(!vp(r))throw new it("Argument should be a Stream or a Multiaddr");let i=l=>{if(t?.stopPropagation,n.append(l.data),n.byteLength>e){let h=n.byteLength;n.consume(n.byteLength),o.reject(new Error(`Read buffer overflow - ${h} > ${e}`))}o.resolve()};r.addEventListener("message",i);let a=l=>{l.error!=null?o.reject(l.error):o.resolve()};r.addEventListener("close",a);let c=()=>{o.resolve()};r.addEventListener("remoteCloseWrite",c);let u={readBuffer:n,async read(l){if(s===!0)throw new To("Stream was unwrapped");if(da(r)){if(l?.bytes==null)return null;if(n.byteLength<l.bytes)throw new je(`Unexpected EOF - stream closed after reading ${n.byteLength}/${l.bytes} bytes`)}let h=l?.bytes??1;for(;;){if(n.byteLength>=h){o.resolve();break}if(await bo(o.promise,l?.signal),da(r)){if(n.byteLength===0&&l?.bytes==null)return null;break}o=Promise.withResolvers()}let f=l?.bytes??n.byteLength;if(n.byteLength<f){if(da(r))throw new je(`Unexpected EOF - stream closed while reading ${n.byteLength}/${f} bytes`);return u.read(l)}let d=n.sublist(0,f);return n.consume(f),d},async write(l,h){if(s===!0)throw new To("Stream was unwrapped");r.send(l)||await Qt(r,"drain",{signal:h?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,r.removeEventListener("message",i),r.removeEventListener("close",a),r.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.push(n))),r}};return u}function Ap(r,t={}){let e=_p(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=Lt(t.maxDataLength));let n=t?.lengthDecoder??rn,o=t?.lengthEncoder??xr;return{async read(i){let a=-1,c=new J;for(;;){let l=await e.read({...i,bytes:1});if(l==null)break;c.append(l);try{a=n(c)}catch(h){if(h instanceof RangeError)continue;throw h}if(a<0)throw new pa("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new ya(`Message length length too long - ${c.byteLength} > ${t.maxLengthLength}`);if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new ma(`Message length too long - ${a} > ${t.maxDataLength}`);let u=await e.read({...i,bytes:a});if(u==null)throw new je(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(u.byteLength!==a)throw new je(`Unexpected EOF - read ${u.byteLength}/${a} bytes before the stream closed`);return u},async write(i,a){await e.write(new J(o(i.byteLength),i),a)},async writeV(i,a){let c=new J(...i.flatMap(u=>[o(u.byteLength),u]));await e.write(c,a)},unwrap(){return e.unwrap()}}}function Be(r,t){let e=Ap(r,t),n={read:async(o,s)=>{let i=await e.read(s);return o.decode(i)},write:async(o,s,i)=>{await e.write(s.encode(o),i)},writeV:async(o,s,i)=>{await e.writeV(o.map(a=>s.encode(a)),i)},pb:o=>({read:async s=>n.read(o,s),write:async(s,i)=>n.write(s,o,i),writeV:async(s,i)=>n.writeV(s,o,i),unwrap:()=>n}),unwrap:()=>e.unwrap()};return n}function Tp(r){return r?.addEventListener!=null}function Ip(r){let t=Le(),e,n=i=>{t.push(i.data)},o=()=>{t.end(),r.removeEventListener("message",n),r.removeEventListener("close",s),r.removeEventListener("remoteCloseWrite",o)},s=i=>{t.end(i.error),i.error!=null&&e?.reject(i.error),r.removeEventListener("message",n),r.removeEventListener("close",s),r.removeEventListener("remoteCloseWrite",o)};return r.addEventListener("message",n),r.addEventListener("close",s,{once:!0}),r.addEventListener("remoteCloseWrite",o,{once:!0}),{source:t,async sink(i){async function*a(){yield*i}let c=a();for(;;){e=Promise.withResolvers();let{done:u,value:l}=await Promise.race([c.next(),e.promise]);if(r.writeStatus==="closing"||r.writeStatus==="closed"||(l!=null&&(r.send(l)||await Promise.race([Qt(r,"drain",{rejectionEvents:["close"]})])),u===!0))break}await r.close()}}}function ul(...r){let t=r.map(e=>Tp(e)?Ip(e):e);return il(...t)}var Pr=class extends Eo{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};var X=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)}}),ll=r=>({match:t=>r.match(t)===!1?t:!1}),H=r=>({match:t=>{let e=r.match(t);return e===!1?t:e}}),Et=(...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}}),$=(...r)=>({match:t=>{for(let e of r){let n=e.match(t);if(n===!1)return!1;t=n}return t}});function j(...r){function t(o){if(o==null)return!1;let s=o.getComponents();for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function e(o){return t(o)!==!1}function n(o){let s=t(o);return s===!1?!1:s.length===0}return{matchers:r,matches:e,exactMatch:n}}var Cp=R(421),GE=j(Cp),Co=R(54),Do=R(55),Lo=R(56),ba=R(53),$E=j(Co,H(R(421))),WE=j(Do,H(R(421))),ZE=j(Lo,H(R(421))),YE=j(Et(ba,Lo,Co,Do),H(R(421))),fl=$(R(4),H(R(43))),hl=$(H(R(42)),R(41),H(R(43))),wa=Et(fl,hl),Qe=Et(wa,ba,Co,Do,Lo),XE=j(Et(wa,$(Et(ba,Lo,Co,Do),H(R(421))))),jE=j(fl),QE=j(hl),JE=j(wa),xa=$(Qe,R(6)),yn=$(Qe,R(273)),t2=j($(xa,H(R(421)))),e2=j(yn),Ea=$(yn,X(460),H(R(421))),Bo=$(yn,X(461),H(R(421))),Dp=Et(Ea,Bo),r2=j(Ea),n2=j(Bo),ga=Et(Qe,xa,yn,Ea,Bo),dl=Et($(ga,X(477),H(R(421)))),o2=j(dl),pl=Et($(ga,X(478),H(R(421))),$(ga,X(448),H(R(449)),X(477),H(R(421)))),s2=j(pl),ml=$(yn,X(280),H(R(466)),H(R(466)),H(R(421))),i2=j(ml),yl=$(Bo,X(465),H(R(466)),H(R(466)),H(R(421))),a2=j(yl),Io=Et(dl,pl,$(xa,H(R(421))),$(Dp,H(R(421))),$(Qe,H(R(421))),ml,yl,R(421)),gl=j(Io),Lp=$(H(Io),X(290),ll(X(281)),H(R(421))),Je=j(Lp),Bp=Et($(Io,X(290),X(281),H(R(421))),$(Io,X(281),H(R(421))),$(X(281),H(R(421)))),c2=j(Bp),Rp=Et($(Qe,R(6),X(480),H(R(421))),$(Qe,X(480),H(R(421)))),u2=j(Rp),Pp=$(Qe,Et($(R(6,"443"),X(480)),$(R(6),X(443)),$(R(6),X(448),X(480)),$(X(448),X(480)),X(448),X(443)),H(R(421))),l2=j(Pp),Op=Et($(R(777),H(R(421)))),f2=j(Op),Np=Et($(R(400),H(R(421)))),h2=j(Np);var Sa=1e3,bl=60*Sa,wl=15,xl=120*bl,El=1,Ro=2e3,Sl=100,va="circuit-relay-source",gn=`${jo}-circuit-relay`,_a=`${jo}-circuit-relay-source`,vl=2*bl,_l=BigInt(1<<17),Vt="/libp2p/circuit/relay/0.2.0/hop",tr="/libp2p/circuit/relay/0.2.0/stop",Al=30*Sa,m2=30*Sa,bn=300,Tl=4096,Il=.001;var Z;(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=()=>ze(e)})(t=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Pt((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.type!=null&&(s.uint32(8),r.Type.codec().encode(o.type,s)),o.peer!=null&&(s.uint32(18),Or.codec().encode(o.peer,s)),o.reservation!=null&&(s.uint32(26),Po.codec().encode(o.reservation,s)),o.limit!=null&&(s.uint32(34),Nr.codec().encode(o.limit,s)),o.status!=null&&(s.uint32(40),V.codec().encode(o.status,s)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={},c=s==null?o.len:o.pos+s;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=Or.codec().decode(o,o.uint32(),{limits:i.limits?.peer});break}case 3:{a.reservation=Po.codec().decode(o,o.uint32(),{limits:i.limits?.reservation});break}case 4:{a.limit=Nr.codec().decode(o,o.uint32(),{limits:i.limits?.limit});break}case 5:{a.status=V.codec().decode(o);break}default:{o.skipType(u&7);break}}}return a})),n),r.encode=o=>Rt(o,r.codec()),r.decode=(o,s)=>Bt(o,r.codec(),s)})(Z||(Z={}));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=()=>ze(e)})(t=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Pt((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.type!=null&&(s.uint32(8),r.Type.codec().encode(o.type,s)),o.peer!=null&&(s.uint32(18),Or.codec().encode(o.peer,s)),o.limit!=null&&(s.uint32(26),Nr.codec().encode(o.limit,s)),o.status!=null&&(s.uint32(32),V.codec().encode(o.status,s)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={},c=s==null?o.len:o.pos+s;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=Or.codec().decode(o,o.uint32(),{limits:i.limits?.peer});break}case 3:{a.limit=Nr.codec().decode(o,o.uint32(),{limits:i.limits?.limit});break}case 4:{a.status=V.codec().decode(o);break}default:{o.skipType(u&7);break}}}return a})),n),r.encode=o=>Rt(o,r.codec()),r.decode=(o,s)=>Bt(o,r.codec(),s)})(kt||(kt={}));var Or;(function(r){let t;r.codec=()=>(t==null&&(t=Pt((e,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),e.id!=null&&e.id.byteLength>0&&(n.uint32(10),n.bytes(e.id)),e.addrs!=null)for(let s of e.addrs)n.uint32(18),n.bytes(s);o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={id:rt(0),addrs:[]},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.id=e.bytes();break}case 2:{if(o.limits?.addrs!=null&&s.addrs.length===o.limits.addrs)throw new sn('Decode error - map field "addrs" had too many elements');s.addrs.push(e.bytes());break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Rt(e,r.codec()),r.decode=(e,n)=>Bt(e,r.codec(),n)})(Or||(Or={}));var Po;(function(r){let t;r.codec=()=>(t==null&&(t=Pt((e,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),e.expire!=null&&e.expire!==0n&&(n.uint32(8),n.uint64(e.expire)),e.addrs!=null)for(let s of e.addrs)n.uint32(18),n.bytes(s);e.voucher!=null&&(n.uint32(26),Oo.codec().encode(e.voucher,n)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={expire:0n,addrs:[]},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.expire=e.uint64();break}case 2:{if(o.limits?.addrs!=null&&s.addrs.length===o.limits.addrs)throw new sn('Decode error - map field "addrs" had too many elements');s.addrs.push(e.bytes());break}case 3:{s.voucher=Oo.codec().decode(e,e.uint32(),{limits:o.limits?.voucher});break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Rt(e,r.codec()),r.decode=(e,n)=>Bt(e,r.codec(),n)})(Po||(Po={}));var Nr;(function(r){let t;r.codec=()=>(t==null&&(t=Pt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.duration!=null&&(n.uint32(8),n.uint32(e.duration)),e.data!=null&&(n.uint32(16),n.uint64(e.data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.duration=e.uint32();break}case 2:{s.data=e.uint64();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Rt(e,r.codec()),r.decode=(e,n)=>Bt(e,r.codec(),n)})(Nr||(Nr={}));var V;(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"})(V||(V={}));var Aa;(function(r){r[r.UNUSED=0]="UNUSED",r[r.OK=100]="OK",r[r.RESERVATION_REFUSED=200]="RESERVATION_REFUSED",r[r.RESOURCE_LIMIT_EXCEEDED=201]="RESOURCE_LIMIT_EXCEEDED",r[r.PERMISSION_DENIED=202]="PERMISSION_DENIED",r[r.CONNECTION_FAILED=203]="CONNECTION_FAILED",r[r.NO_RESERVATION=204]="NO_RESERVATION",r[r.MALFORMED_MESSAGE=400]="MALFORMED_MESSAGE",r[r.UNEXPECTED_MESSAGE=401]="UNEXPECTED_MESSAGE"})(Aa||(Aa={}));(function(r){r.codec=()=>ze(Aa)})(V||(V={}));var Ur;(function(r){let t;r.codec=()=>(t==null&&(t=Pt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.relay!=null&&e.relay.byteLength>0&&(n.uint32(10),n.bytes(e.relay)),e.peer!=null&&e.peer.byteLength>0&&(n.uint32(18),n.bytes(e.peer)),e.expiration!=null&&e.expiration!==0n&&(n.uint32(24),n.uint64(e.expiration)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={relay:rt(0),peer:rt(0),expiration:0n},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.relay=e.bytes();break}case 2:{s.peer=e.bytes();break}case 3:{s.expiration=e.uint64();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Rt(e,r.codec()),r.decode=(e,n)=>Bt(e,r.codec(),n)})(Ur||(Ur={}));var Oo;(function(r){let t;r.codec=()=>(t==null&&(t=Pt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.publicKey!=null&&e.publicKey.byteLength>0&&(n.uint32(10),n.bytes(e.publicKey)),e.payloadType!=null&&e.payloadType.byteLength>0&&(n.uint32(18),n.bytes(e.payloadType)),e.payload!=null&&(n.uint32(26),Ur.codec().encode(e.payload,n)),e.signature!=null&&e.signature.byteLength>0&&(n.uint32(42),n.bytes(e.signature)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={publicKey:rt(0),payloadType:rt(0),signature:rt(0)},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.publicKey=e.bytes();break}case 2:{s.payloadType=e.bytes();break}case 3:{s.payload=Ur.codec().decode(e,e.uint32(),{limits:o.limits?.payload});break}case 5:{s.signature=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Rt(e,r.codec()),r.decode=(e,n)=>Bt(e,r.codec(),n)})(Oo||(Oo={}));var No=class extends Error{constructor(t="Transfer limit error"){super(t),this.name="TransferLimitError"}},Uo=class extends Error{constructor(t="Duration limit error"){super(t),this.name="DurationLimitError"}},wn=class extends Error{static name="HadEnoughRelaysError";name="HadEnoughRelaysError"},Mo=class extends Error{static name="DoubleRelayError";name="DoubleRelayError"},ko=class extends Error{static name="RelayQueueFullError";name="RelayQueueFullError"};function Cl(r,t,e){let n=t.remaining,o=s=>{let i=BigInt(s.data.byteLength);t.remaining-=i,t.remaining<0&&r.abort(new No(`data limit of ${n} bytes exceeded`))};r.addEventListener("message",o)}function Dl(r,t,e,n,o){function s(l){r.abort(l),t.abort(l)}let i=[e,n.signal];if(n.limit?.duration!=null){o.log("limiting relayed connection duration to %dms",n.limit.duration);let l=AbortSignal.timeout(n.limit.duration);i.push(l)}let a=_o(i);let c;n.limit?.data!=null&&(c={remaining:n.limit.data});let u=()=>{let l;e.aborted?l=e.reason:l=new Uo(`duration limit of ${n.limit?.duration} ms exceeded`),s(l)};a.addEventListener("abort",u,{once:!0}),c!=null&&(Cl(t,c,o),Cl(r,c,o)),ul(r,t,r).catch(l=>{s(l)}).finally(()=>{a.clear()})}function Ta(r){let t=r*BigInt(1e3),e=new Date().getTime();return Number(t-BigInt(e))}var xn=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}},Ko=j($(gl.matchers[0],X(290))),qo=j(X(290));function Vo(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 Vo(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 Vo(this.map.values(),t=>t.key)}values(){return Vo(this.map.values(),t=>t.value)}get size(){return this.map.size}};var Ho=class{filter;constructor(t,e){this.filter=Br(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 Ia(r,t=.001){return new Ho(r,t)}var Ca=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 Da(r){let{name:t,metrics:e}=r,n;return e!=null?n=new Ca({name:t,metrics:e}):n=new Re,n}var La=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 Ll(r,t){let e=new La(t?.errorMessage,t?.errorCode,t?.errorName),n=new AbortController,o=()=>{n.abort(e)},s=AbortSignal.timeout(r);s.addEventListener("abort",o);let i=n.signal;return i.reset=a=>{s?.removeEventListener("abort",o),s=AbortSignal.timeout(a??r),s.addEventListener("abort",()=>{n.abort(e)})},i.clear=()=>{s?.removeEventListener("abort",o),s=void 0},i}var Fo=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??wl,this.applyDefaultLimit=e.applyDefaultLimit!==!1,this.reservationTtl=e.reservationTtl??xl,this.defaultDurationLimit=e.defaultDurationLimit??vl,this.defaultDataLimit=e.defaultDataLimit??_l,this.reservations=Da({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:V.RESERVATION_REFUSED};let s=new Date(Date.now()+this.reservationTtl),i;return this.applyDefaultLimit&&(i=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:s,limit:i,signal:Ll(this.reservationTtl)}),this.reservations.set(t,o),o.signal.addEventListener("abort",()=>{this.reservations.delete(t)}),{status:V.OK,expire:Math.round(s.getTime()/1e3)}}removeReservation(t){this.reservations.delete(t)}get(t){return this.reservations.get(t)}clear(){this.reservations.clear()}};var zo=class r{domain="libp2p-relay-rsvp";codec=new Uint8Array([3,2]);relay;peer;expiration;constructor({relay:t,peer:e,expiration:n}){this.relay=t,this.peer=e,this.expiration=n}marshal(){return Ur.encode({relay:this.relay.toMultihash().bytes,peer:this.peer.toMultihash().bytes,expiration:BigInt(this.expiration)})}equals(t){return!(!(t instanceof r)||!this.peer.equals(t.peer)||!this.relay.equals(t.relay)||this.expiration!==t.expiration)}};var Up={maxOutboundStopStreams:bn},Go=class extends Tt{components;reservationStore;started;hopTimeout;shutdownController;maxInboundHopStreams;maxOutboundHopStreams;maxOutboundStopStreams;log;constructor(t,e={}){super(),this.log=t.logger.forComponent("libp2p:circuit-relay:server"),this.components=t,this.started=!1,this.hopTimeout=e?.hopTimeout??Al,this.maxInboundHopStreams=e.maxInboundHopStreams,this.maxOutboundHopStreams=e.maxOutboundHopStreams,this.maxOutboundStopStreams=e.maxOutboundStopStreams??Up.maxOutboundStopStreams,this.reservationStore=new Fo(t,e.reservations),this.shutdownController=new AbortController,this.shutdownController.signal,this.onHop=this.onHop.bind(this)}[Symbol.toStringTag]="@libp2p/circuit-relay-v2-server";isStarted(){return this.started}async start(){this.started||(await this.components.registrar.handle(Vt,this.onHop,{maxInboundStreams:this.maxInboundHopStreams,maxOutboundStreams:this.maxOutboundHopStreams,runOnLimitedConnection:!0}),this.started=!0)}async stop(){this.reservationStore.clear(),this.shutdownController.abort(),await this.components.registrar.unhandle(Vt),this.started=!1}async onHop(t,e){this.log("received circuit v2 hop protocol stream from %p",e.remotePeer);let n=AbortSignal.timeout(this.hopTimeout);let o={signal:n},s=Be(t);try{let i=await s.pb(Z).read(o);if(i?.type==null)throw new Error("request was invalid, could not read from stream");this.log("received",i.type),await this.handleHopProtocol({connection:e,stream:s,request:i},o)}catch(i){this.log.error("error while handling hop",i),await s.pb(Z).write({type:Z.Type.STATUS,status:V.MALFORMED_MESSAGE},o),t.abort(i)}}async handleHopProtocol({stream:t,request:e,connection:n},o){switch(this.log("received hop message"),e.type){case Z.Type.RESERVE:await this.handleReserve({stream:t,request:e,connection:n},o);break;case Z.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(Z).write({type:Z.Type.STATUS,status:V.UNEXPECTED_MESSAGE})}}async handleReserve({stream:t,connection:e},n){let o=t.pb(Z);if(this.log("hop reserve request from %p",e.remotePeer),Je.exactMatch(e.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",e.remotePeer),await o.write({type:Z.Type.STATUS,status:V.PERMISSION_DENIED},n);return}if(await this.components.connectionGater.denyInboundRelayReservation?.(e.remotePeer)===!0){this.log.error("reservation for %p denied by connection gater",e.remotePeer),await o.write({type:Z.Type.STATUS,status:V.PERMISSION_DENIED},n);return}let s=this.reservationStore.reserve(e.remotePeer,e.remoteAddr);try{if(s.status!==V.OK){await o.write({type:Z.Type.STATUS,status:s.status},n);return}if(s.expire!=null){let i=s.expire*1e3-Date.now();await this.components.peerStore.merge(e.remotePeer,{tags:{[va]:{value:1,ttl:i},[_a]:{value:1,ttl:i}}},n)}await o.write({type:Z.Type.STATUS,status:V.OK,reservation:await this.makeReservation(e.remotePeer,BigInt(s.expire??0)),limit:this.reservationStore.get(e.remotePeer)?.limit},n),this.log("sent confirmation response to %s",e.remotePeer),await o.unwrap().unwrap().close(n)}catch(i){this.log.error("failed to send confirmation response to %p - %e",e.remotePeer,i),this.reservationStore.removeReservation(e.remotePeer);try{await this.components.peerStore.merge(e.remotePeer,{tags:{[va]:void 0,[_a]:void 0}},n)}catch(a){this.log.error("failed to untag relay source peer %p - %e",e.remotePeer,a)}}}async makeReservation(t,e){let n=[];for(let s of this.components.addressManager.getAddresses())s.toString().includes("/p2p-circuit")||n.push(s.bytes);let o=await hn.seal(new zo({peer:t,relay:this.components.peerId,expiration:e}),this.components.privateKey);return{addrs:n,expire:e,voucher:{publicKey:Yt(o.publicKey),payloadType:o.payloadType,payload:{peer:t.toMultihash().bytes,relay:this.components.peerId.toMultihash().bytes,expiration:e},signature:o.signature}}}async handleConnect({stream:t,request:e,connection:n},o){let s=t.pb(Z);if(Je.matches(n.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",n.remotePeer),await s.write({type:Z.Type.STATUS,status:V.PERMISSION_DENIED},o);return}this.log("hop connect request from %p",n.remotePeer);let i;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(Mt),i=Tr(Zt(e.peer.id))}catch(h){this.log.error("invalid hop connect request via peer %p %s",n.remotePeer,h),await s.write({type:Z.Type.STATUS,status:V.MALFORMED_MESSAGE},o);return}let a=this.reservationStore.get(i);if(a==null){this.log.error("hop connect denied for destination peer %p not having a reservation for %p with status %s",i,n.remotePeer,V.NO_RESERVATION),await s.write({type:Z.Type.STATUS,status:V.NO_RESERVATION},o);return}if(await this.components.connectionGater.denyOutboundRelayedConnection?.(n.remotePeer,i)===!0){this.log.error("hop connect for %p to %p denied by connection gater",n.remotePeer,i),await s.write({type:Z.Type.STATUS,status:V.PERMISSION_DENIED},o);return}let c=this.components.connectionManager.getConnections(i);if(c.length===0){this.log("hop connect denied for destination peer %p not having a connection for %p as there is no destination connection",i,n.remotePeer),await s.write({type:Z.Type.STATUS,status:V.NO_RESERVATION},o);return}let u=c[0],l=await this.stopHop({connection:u,request:{type:kt.Type.CONNECT,peer:{id:n.remotePeer.toMultihash().bytes,addrs:[]},limit:a?.limit}},o);if(l==null){this.log.error("failed to open stream to destination peer %p",u?.remotePeer),await s.write({type:Z.Type.STATUS,status:V.CONNECTION_FAILED},o);return}await s.write({type:Z.Type.STATUS,status:V.OK,limit:a?.limit},o),this.log("connection from %p to %p established - merging streams",n.remotePeer,i),Dl(t.unwrap(),l,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(tr,{maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0,...n}),s=Be(o),i=s.pb(kt);await i.write(e,n);let a;try{a=await i.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===V.OK)return this.log("stop request to %p was successful",t.remotePeer),s.unwrap();this.log("stop request failed with code %d",a.status),await o.close(n)}get reservations(){return this.reservationStore.reservations}};var Pe=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var $o=class extends Tt{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(Vt,{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(Vt)],orders:[()=>Math.random()<.5?1:-1,(n,o)=>{let s=Bl(n),i=Bl(o);return s>i?-1:i>s?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 Pr({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",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=_o([AbortSignal.timeout(5e3),e]);try{await this.components.connectionManager.openConnection(t,{signal:n})}finally{n.clear()}}};function Bl(r){let t=r.metadata.get("last-dial-success");return t==null?0:new Date(z(t)).getTime()}var Ra=class extends Tt{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??Ro,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(qo.exactMatch(t))this.log("searching for circuit relay servers"),this.reservationId=this.reservationStore.reserveRelay();else if(Ko.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 s=await this.reservationStore.addRelay(o.remotePeer,"configured");this.addedRelay(s)}}else throw new Ne(`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=>Mt(e).encapsulate("/p2p-circuit")),this.listeningAddrs.forEach(e=>{this.addressManager.confirmObservedAddr(e,{type:"transport"})}),queueMicrotask(()=>{this.safeDispatchEvent("listening")})}};function Rl(r){return new Ra(r)}var Pl="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Ol=(r=21)=>{let t="",e=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)t+=Pl[e[r]&63];return t};var Mp=60*1e3*10,kp=60*1e3*5,Kp=30*1e3,Wo=class extends Tt{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??Sl,this.reservationCompletionTimeout=e?.reservationCompletionTimeout??Ro,this.started=!1,this.relayFilter=Br(100),this.reserveQueue=new Pr({concurrency:e?.reservationConcurrency??El,metricName:"libp2p_relay_reservation_queue",metrics:t.metrics}),this.events.addEventListener("connection:close",n=>{[...this.reservations.values()].find(s=>s.connection===n.detail.id)!=null&&this.#e(n.detail.remotePeer).catch(s=>{this.log("could not remove relay %p - %e",n.detail,s)})})}isStarted(){return this.started}start(){this.started=!0}afterStart(){Promise.resolve().then(async()=>{let t=await this.peerStore.all({filters:[e=>e.tags.has(gn)]});this.log("removing tag from %d old relays",t.length),await Promise.all(t.map(async e=>{await this.peerStore.merge(e.id,{tags:{[gn]: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=Ol();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 Ne("Cannot use self as relay");if(this.reserveQueue.size>this.maxReservationQueueLength)throw new ko("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 Ne("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 s=this.reservations.get(t);if(s!=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(s.connection)&&(this.log("already have relay reservation with %p and the original connection is still open",t),x=!0),x&&Ta(s.reservation.expire)>Mp)return this.log("already have relay reservation with %p but we are still connected and it does not expire soon",t),{relay:t,details:s};await this.#e(t)}if(e==="discovered"&&this.pendingReservations.length===0)throw new wn("Not making reservation on discovered relay because we do not need any more relays");let i=AbortSignal.timeout(this.reservationCompletionTimeout);let a=await this.connectionManager.openConnection(t,{signal:i});if(Je.matches(a.remoteAddr))throw new Mo("not creating reservation over relayed connection");let c=await this.#t(a,{signal:i}),u=Ta(c.expire);this.log("created reservation on relay peer %p, expiry date is %s",t,new Date(Date.now()+u).toString());let l=Math.min(Math.max(u-kp,Kp),Math.pow(2,31)-1),h=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)})},l),f;if(e==="discovered"){let p=this.pendingReservations.pop();if(p==null)throw new wn("Made reservation on relay but did not need any more discovered relays");f={timeout:h,reservation:c,type:e,connection:a.id,id:p}}else f={timeout:h,reservation:c,type:e,connection:a.id};this.reservations.set(t,f),await this.peerStore.merge(t,{tags:{[gn]:{value:1,ttl:u}}}),this.#r();let d={relay:t,details:f};return this.safeDispatchEvent("relay:created-reservation",{detail:d}),d}catch(s){throw e==="discovered"&&s.name==="HadEnoughRelaysError"||this.log.error("could not reserve slot on %p after %dms - %e",t,Date.now()-o,s),(s.name==="DialError"||s.name==="UnsupportedProtocolError")&&this.relayFilter.add(t.toMultihash().bytes),this.#e(t).catch(i=>{this.log.error("could not remove reservation on %p after reserving slot failed - %e",t,i)}),s}},{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(Vt,e),s=Be(n).pb(Z);this.log.trace("send RESERVE to %p",t.remotePeer),await s.write({type:Z.Type.RESERVE},e);let i;try{this.log.trace("reading response from %p",t.remotePeer),i=await s.read(e)}catch(c){throw n.abort(c),c}finally{n.status!=="closed"&&await n.close(e)}if(this.log.trace("read response %s",i.status),i.status===V.OK&&i.reservation!=null){let c=new Set;c.add(t.remoteAddr.toString());for(let u of i.reservation.addrs){let l=Mt(u);l.getComponents().find(h=>h.code===421)==null&&(l=l.encapsulate(`/p2p/${t.remotePeer}`)),l=Mt(l.toString().replace(`/p2p/${t.remotePeer}/p2p/${t.remotePeer}`,`/p2p/${t.remotePeer}`)),c.add(l.toString())}return i.reservation.addrs=[...c].map(u=>Mt(u).bytes),i.reservation}let a=`reservation failed with status ${i.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:{[gn]: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=Br(100),this.log("not discovered enough relays %d/%d",this.reservations.size,this.pendingReservations.length),this.safeDispatchEvent("relay:not-enough-relays")}};var Pa=class extends vo{stream;init;constructor(t){super({...t,direction:t.stream.direction}),this.init=t,this.stream=t.stream,this.stream.addEventListener("close",e=>{this.onTransportClosed(e.error)}),this.stream.addEventListener("remoteCloseWrite",e=>{this.onRemoteCloseWrite(),this.close().catch(n=>{this.abort(n)})}),this.stream.addEventListener("message",e=>{t.onDataRead?.(e.data),this.onData(e.data)}),this.stream.addEventListener("drain",()=>{this.safeDispatchEvent("drain")})}sendData(t){return this.init.onDataWrite?.(t),{sentBytes:t.byteLength,canSendMore:this.stream.send(t)}}async sendClose(t){await this.stream.close(t)}sendReset(){this.stream.abort(new Error("An error occurred"))}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}};function Oa(r){return new Pa(r)}var qp=r=>{if(r.peer==null)return!1;try{r.peer.addrs.forEach(Mt)}catch{return!1}return!0},Nl={maxInboundStopStreams:bn,maxOutboundStopStreams:bn,stopTimeout:3e4},Zo=class{components;discovery;reservationStore;maxInboundStopStreams;maxOutboundStopStreams;started;log;shutdownController;constructor(t,e={}){this.components=t,this.log=t.logger.forComponent("libp2p:circuit-relay:transport"),this.maxInboundStopStreams=e.maxInboundStopStreams??Nl.maxInboundStopStreams,this.maxOutboundStopStreams=e.maxOutboundStopStreams??Nl.maxOutboundStopStreams,this.shutdownController=new AbortController,this.discovery=new $o(t,{filter:e.discoveryFilter??Ia(Tl,Il)}),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 Wo(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,this.onStop=this.onStop.bind(this)}[Symbol.toStringTag]="@libp2p/circuit-relay-v2-transport";[Ha]=["@libp2p/transport","@libp2p/circuit-relay-v2-transport"];get[Fa](){return this.discovery!=null?["@libp2p/identify"]:[]}[Va]=!0;isStarted(){return this.started}async start(){this.shutdownController=new AbortController,this.shutdownController.signal,await this.components.registrar.handle(tr,this.onStop,{maxInboundStreams:this.maxInboundStopStreams,maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0}),await ka(this.discovery,this.reservationStore),this.started=!0}async stop(){this.shutdownController.abort(),await Ka(this.discovery,this.reservationStore),await this.components.registrar.unhandle(tr),this.started=!1}async dial(t,e){let n=t.toString().split("/p2p-circuit"),o=Mt(n[0]),s=Mt(n[n.length-1]),i=o.getComponents().find(d=>d.code===421)?.value,a=s.getComponents().find(d=>d.code===421)?.value;if(i==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 Tn(`C${d}`)}let c=Pi(i),u=Pi(a),h=this.components.connectionManager.getConnections(c)[0];h==null?(await this.components.peerStore.merge(c,{multiaddrs:[o]}),e.onProgress?.(new Pe("circuit-relay:open-connection")),h=await this.components.connectionManager.openConnection(c,e)):e.onProgress?.(new Pe("circuit-relay:reuse-connection"));let f;try{e.onProgress?.(new Pe("circuit-relay:open-hop-stream")),f=await h.newStream(Vt,e);let d=Be(f).pb(Z);e.onProgress?.(new Pe("circuit-relay:write-connect-message")),await d.write({type:Z.Type.CONNECT,peer:{id:u.toMultihash().bytes,addrs:[Mt(s).bytes]}},e),e.onProgress?.(new Pe("circuit-relay:read-connect-response"));let p=await d.read(e);if(p.status!==V.OK)throw new An(`failed to connect via relay with status ${p?.status?.toString()??"undefined"}`);let x=new xn(p.limit),S=Oa({stream:d.unwrap().unwrap(),remoteAddr:t,localAddr:o.encapsulate(`/p2p-circuit/p2p/${this.components.peerId.toString()}`),onDataRead:x.onData,onDataWrite:x.onData,log:f.log.newScope("circuit-relay:connection")}),g=await this.components.upgrader.upgradeOutbound(S,{...e,limits:x.getLimits()});return g.log("outbound relayed connection established to %p with limits %o, over connection %s",g.remotePeer,p.limit??"none",h.id),g}catch(d){throw this.log.error("circuit relay dial to destination %p via relay %p failed",u,c,d),f?.abort(d),d}}createListener(t){return Rl({peerId:this.components.peerId,connectionManager:this.components.connectionManager,addressManager:this.components.addressManager,reservationStore:this.reservationStore,logger:this.components.logger})}listenFilter(t){return t=Array.isArray(t)?t:[t],t.filter(e=>Ko.exactMatch(e)||qo.exactMatch(e))}dialFilter(t){return t=Array.isArray(t)?t:[t],t.filter(e=>Je.exactMatch(e))}async onStop(t,e){let n=this.components.upgrader.createInboundAbortSignal(this.shutdownController.signal);try{if(!this.reservationStore.hasReservation(e.remotePeer))try{this.log("dialed via relay we did not have a reservation on, start listening on that relay address"),await this.components.transportManager.listen([e.remoteAddr.encapsulate("/p2p-circuit")])}catch(h){this.log.error("failed to listen on a relay peer we were dialed via but did not have a reservation on",h)}let o=Be(t).pb(kt),s=await o.read({signal:n});if(this.log("new circuit relay v2 stop stream from %p with type %s",e.remotePeer,s.type),s?.type===void 0){this.log.error("type was missing from circuit v2 stop protocol request from %s",e.remotePeer),await o.write({type:kt.Type.STATUS,status:V.MALFORMED_MESSAGE},{signal:n}),await t.close({signal:n});return}if(s.type!==kt.Type.CONNECT){this.log.error("invalid stop connect request via peer %p",e.remotePeer),await o.write({type:kt.Type.STATUS,status:V.UNEXPECTED_MESSAGE},{signal:n}),await t.close({signal:n});return}if(!qp(s)){this.log.error("invalid stop connect request via peer %p",e.remotePeer),await o.write({type:kt.Type.STATUS,status:V.MALFORMED_MESSAGE},{signal:n}),await t.close({signal:n});return}let i=Tr(Zt(s.peer.id));if(await this.components.connectionGater.denyInboundRelayedConnection?.(e.remotePeer,i)===!0){this.log.error("connection gater denied inbound relayed connection from %p",e.remotePeer),await o.write({type:kt.Type.STATUS,status:V.PERMISSION_DENIED},{signal:n}),await t.close({signal:n});return}this.log.trace("sending success response to %p",e.remotePeer),await o.write({type:kt.Type.STATUS,status:V.OK},{signal:n});let a=new xn(s.limit),c=e.remoteAddr.encapsulate(`/p2p-circuit/p2p/${i.toString()}`),u=this.components.addressManager.getAddresses()[0],l=Oa({stream:o.unwrap().unwrap(),remoteAddr:c,localAddr:u,onDataRead:a.onData,onDataWrite:a.onData,log:t.log.newScope("circuit-relay:connection")});await this.components.upgrader.upgradeInbound(l,{limits:a.getLimits(),signal:n}),l.log("inbound relayed connection established to %p with limits %o, over connection %s",i,s.limit??"none",e.id)}finally{n?.clear()}}};function Vp(r={}){return t=>new Go(t,r)}function Hp(r={}){return t=>new Zo(t,r)}return ql(Fp);})();
|
3
3
|
/*! Bundled license information:
|
4
4
|
|
5
5
|
@noble/hashes/esm/utils.js:
|