@helia/bitswap 4.0.5 → 4.0.6-f713369d
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 +3 -3
- package/dist/src/session.d.ts +1 -0
- package/dist/src/session.d.ts.map +1 -1
- package/dist/src/session.js +12 -4
- package/dist/src/session.js.map +1 -1
- package/package.json +4 -4
- package/src/session.ts +14 -4
- package/dist/typedoc-urls.json +0 -29
package/dist/index.min.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
(function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.HeliaBitswap = factory()}(typeof self !== 'undefined' ? self : this, function () {
|
|
2
|
-
"use strict";var HeliaBitswap=(()=>{var po=Object.defineProperty;var Vc=Object.getOwnPropertyDescriptor;var Wc=Object.getOwnPropertyNames;var $c=Object.prototype.hasOwnProperty;var be=(r,e)=>{for(var t in e)po(r,t,{get:e[t],enumerable:!0})},jc=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Wc(e))!$c.call(r,o)&&o!==t&&po(r,o,{get:()=>e[o],enumerable:!(n=Vc(e,o))||n.enumerable});return r};var Gc=r=>jc(po({},"__esModule",{value:!0}),r);var gh={};be(gh,{withBitswap:()=>mh});var Ae=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var Se=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},zr=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var Kr=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Hr=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var qr=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},Vr=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}};var or=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var Wr=Symbol.for("@libp2p/peer-id");function $r(r){return!!r?.[Wr]}function Zc(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function yi(...r){let e=[];for(let t of r)Zc(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStart!=null&&await t.beforeStart()})),await Promise.all(e.map(async t=>{await t.start()})),await Promise.all(e.map(async t=>{t.afterStart!=null&&await t.afterStart()}))}function Yc(r){return typeof r?.handleEvent=="function"}function Xc(r){return(r!==!0&&r!==!1&&r?.once)??!1}var Ne=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){let o=Xc(n);super.addEventListener(e,i=>{if(o){let a=this.#e.get(i.type);a!=null&&(a=a.filter(({callback:c})=>c!==t),this.#e.set(i.type,a))}Yc(t)?t.handleEvent(i):t(i)},n);let s=this.#e.get(e);s==null&&(s=[],this.#e.set(e,s)),s.push({callback:t,once:o})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==t),this.#e.set(e,o))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var ce=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};function bi(r){let e=new globalThis.AbortController;function t(){let s=r.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();e.abort(s);for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}for(let s of r){if(s?.aborted===!0){t();break}s?.addEventListener!=null&&s.addEventListener("abort",t)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}var _h=new Uint8Array(0);function xi(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function _e(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return dt(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return dt(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function Ei(r){let e=new Uint8Array(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}var wi=4096;function vi(r){let e=r.length;if(e<=wi)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.subarray(n,n+=wi));return t}function Qc(r){return r?.buffer instanceof ArrayBuffer}function dt(r){return Qc(r)?r:r.slice()}var wo={};be(wo,{base32:()=>et,base32hex:()=>cu,base32hexpad:()=>fu,base32hexpadupper:()=>lu,base32hexupper:()=>uu,base32pad:()=>iu,base32padupper:()=>au,base32upper:()=>su,base32z:()=>du});function Jc(r,e,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),o=0;o<n.length;o++)n[o]=255;for(var s=0;s<r.length;s++){var i=r.charAt(s),a=i.charCodeAt(0);if(n[a]!==255)throw new TypeError(i+" is ambiguous");if(n[a]=s,t){var c=i.toLowerCase().charCodeAt(0),u=i.toUpperCase().charCodeAt(0);c!==a&&(n[c]=s),u!==a&&(n[u]=s)}}var f=r.length,l=r.charAt(0),d=Math.log(f)/Math.log(256),h=Math.log(256)/Math.log(f);function x(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var E=0,A=0,k=0,D=g.length;k!==D&&g[k]===0;)k++,E++;for(var R=(D-k)*h+1>>>0,C=new Uint8Array(R);k!==D;){for(var I=g[k],N=0,U=R-1;(I!==0||N<A)&&U!==-1;U--,N++)I+=256*C[U]>>>0,C[U]=I%f>>>0,I=I/f>>>0;if(I!==0)throw new Error("Non-zero carry");A=N,k++}for(var O=R-A;O!==R&&C[O]===0;)O++;for(var p=l.repeat(E);O<R;++O)p+=r.charAt(C[O]);return p}function _(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var E=0;if(g[E]!==" "){for(var A=0,k=0;g[E]===l;)A++,E++;for(var D=(g.length-E)*d+1>>>0,R=new Uint8Array(D);g[E];){var C=n[g.charCodeAt(E)];if(C===255)return;for(var I=0,N=D-1;(C!==0||I<k)&&N!==-1;N--,I++)C+=f*R[N]>>>0,R[N]=C%256>>>0,C=C/256>>>0;if(C!==0)throw new Error("Non-zero carry");k=I,E++}if(g[E]!==" "){for(var U=D-k;U!==D&&R[U]===0;)U++;for(var O=new Uint8Array(A+(D-U)),p=A;U!==D;)O[p++]=R[U++];return O}}}function m(g){var E=_(g);if(E)return E;throw new Error(`Non-${e} character`)}return{encode:x,decodeUnsafe:_,decode:m}}var eu=Jc,tu=eu,_i=tu;var mo=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},go=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Ai(this,e)}},yo=class{decoders;constructor(e){this.decoders=e}or(e){return Ai(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Ai(r,e){return new yo({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var bo=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new mo(e,t,n),this.decoder=new go(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Ot({name:r,prefix:e,encode:t,decode:n}){return new bo(r,e,t,n)}function Je({name:r,prefix:e,alphabet:t,caseInsensitive:n=!1}){let{encode:o,decode:s}=_i(t,r,n);return Ot({prefix:e,name:r,encode:o,decode:i=>_e(s(i))})}function ru(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let u=0;u<o;++u){let f=e[r[u]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|f,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function nu(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function ou(r,e){let t={};for(let n=0;n<r.length;++n)if(t[r[n]]=n,e){let o=r[n].toLowerCase(),s=r[n].toUpperCase();o!==r[n]&&(t[o]=n),s!==r[n]&&(t[s]=n)}return t}function Z({name:r,prefix:e,bitsPerChar:t,alphabet:n,caseInsensitive:o=!1}){let s=ou(n,o);return Ot({prefix:e,name:r,encode(i){return nu(i,n,t)},decode(i){return ru(i,s,t,r)}})}var et=Z({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5,caseInsensitive:!0}),su=Z({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5,caseInsensitive:!0}),iu=Z({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5,caseInsensitive:!0}),au=Z({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5,caseInsensitive:!0}),cu=Z({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5,caseInsensitive:!0}),uu=Z({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5,caseInsensitive:!0}),fu=Z({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5,caseInsensitive:!0}),lu=Z({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5,caseInsensitive:!0}),du=Z({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var xo={};be(xo,{base36:()=>sr,base36upper:()=>hu});var sr=Je({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz",caseInsensitive:!0}),hu=Je({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",caseInsensitive:!0});var Eo={};be(Eo,{base58btc:()=>ee,base58flickr:()=>pu});var ee=Je({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),pu=Je({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var mu=Bi,Ii=128,gu=127,yu=~gu,bu=Math.pow(2,31);function Bi(r,e,t){e=e||[],t=t||0;for(var n=t;r>=bu;)e[t++]=r&255|Ii,r/=128;for(;r&yu;)e[t++]=r&255|Ii,r>>>=7;return e[t]=r|0,Bi.bytes=t-n+1,e}var wu=vo,xu=128,Ti=127;function vo(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw vo.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&Ti)<<o:(i&Ti)*Math.pow(2,o),o+=7}while(i>=xu);return vo.bytes=s-n,t}var Eu=Math.pow(2,7),vu=Math.pow(2,14),Su=Math.pow(2,21),_u=Math.pow(2,28),Au=Math.pow(2,35),Iu=Math.pow(2,42),Tu=Math.pow(2,49),Bu=Math.pow(2,56),Du=Math.pow(2,63),Lu=function(r){return r<Eu?1:r<vu?2:r<Su?3:r<_u?4:r<Au?5:r<Iu?6:r<Tu?7:r<Bu?8:r<Du?9:10},ku={encode:mu,decode:wu,encodingLength:Lu},Cu=ku,ir=Cu;function ar(r,e=0){return[ir.decode(r,e),ir.decode.bytes]}function Rt(r,e,t=0){return ir.encode(r,e,t),e}function Nt(r){return ir.encodingLength(r)}function Ft(r,e){let t=e.byteLength,n=Nt(r),o=n+Nt(t),s=new Uint8Array(o+t);return Rt(r,s,0),Rt(t,s,n),s.set(e,o),new Ut(r,t,e,s)}function Gr(r){let e=_e(r),[t,n]=ar(e),[o,s]=ar(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Ut(t,o,i,e)}function Di(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&xi(r.bytes,t.bytes)}}var Ut=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=dt(n),this.bytes=dt(o)}};function Li(r,e){let{bytes:t,version:n}=r;return n===0?Ou(t,So(r),e??ee.encoder):Ru(t,So(r),e??et.encoder)}var ki=new WeakMap;function So(r){let e=ki.get(r);if(e==null){let t=new Map;return ki.set(r,t),t}return e}var G=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=dt(o),this["/"]=this.bytes}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==cr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Nu)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=Ft(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&Di(e.multihash,n.multihash)}toString(e){return Li(this,e)}toJSON(){return{"/":Li(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??Ci(n,o,s.bytes))}else if(t[Uu]===!0){let{version:n,multihash:o,code:s}=t,i=Gr(o);return r.create(n,s,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==cr)throw new Error(`Version 0 CID must use dag-pb (code: ${cr}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=Ci(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,cr,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=_e(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new Ut(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[l,d]=ar(e.subarray(t));return t+=d,l},o=n(),s=cr;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),u=t+c,f=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:f,size:u}}static parse(e,t){let[n,o]=Pu(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return So(s).set(n,e),s}};function Pu(r,e){switch(r[0]){case"Q":{let t=e??ee;return[ee.prefix,t.decode(`${ee.prefix}${r}`)]}case ee.prefix:{let t=e??ee;return[ee.prefix,t.decode(r)]}case et.prefix:{let t=e??et;return[et.prefix,t.decode(r)]}case sr.prefix:{let t=e??sr;return[sr.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function Ou(r,e,t){let{prefix:n}=t;if(n!==ee.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function Ru(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var cr=112,Nu=18;function Ci(r,e,t){let n=Nt(r),o=n+Nt(e),s=new Uint8Array(o+t.byteLength);return Rt(r,s,0),Rt(e,s,n),s.set(t,o),s}var Uu=Symbol.for("@ipld/js-cid/CID");var Fu=20;function Ao({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new _o(r,e,t,n,o)}var _o=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??Fu,this.maxDigestLength=s}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?Pi(n,this.code,t?.truncate):n.then(o=>Pi(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Pi(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return Ft(e,r)}var To={};be(To,{base64:()=>pt,base64pad:()=>Mu,base64url:()=>Io,base64urlpad:()=>zu});var pt=Z({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Mu=Z({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Io=Z({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),zu=Z({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Bo={};be(Bo,{identity:()=>Ie});var Ri=0,Ku="identity",Ni=_e;function Hu(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return Ft(Ri,Ni(r))}var Ie={code:Ri,name:Ku,encode:Ni,digest:Hu};function ue(r=0){return new Uint8Array(r)}function se(r=0){return new Uint8Array(r)}function qu(r){return r?.buffer instanceof ArrayBuffer}function Do(r){if(qu(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function we(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=se(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return Do(t)}function Q(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}var Fi=Symbol.for("@achingbrain/uint8arraylist");function Ui(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function Zr(r){return!!r?.[Fi]}var fe=class r{bufs;length;[Fi]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(Zr(n)){t+=n.byteLength;for(let o of n.bufs)this.bufs.push(o)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(Zr(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=Ui(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Ui(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(Zr(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:o}=this._subList(e,t);return we(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:we(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=n,s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],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,e>=c)continue;let u=e>=a&&e<c,f=t>a&&t<=c;if(u&&f){if(e===a&&t===c){n.push(i);break}let l=e-a;n.push(i.subarray(l,l+(t-e)));break}if(u){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(f){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!Zr(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let 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 l=0;l<s;l++)i[l]=-1;for(let l=0;l<o;l++)i[n[l]]=l;let a=i,c=this.byteLength-n.byteLength,u=n.byteLength-1,f;for(let l=t;l<=c;l+=f){f=0;for(let d=u;d>=0;d--){let h=this.get(l+d);if(n[d]!==h){f=Math.max(1,d-a[h]);break}}if(f===0)return l}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=se(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=ue(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=ue(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=ue(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=se(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=ue(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=ue(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=ue(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=ue(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=ue(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!Q(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,s)=>o+s.byteLength,0)),n.length=t,n}};function Vu(r){return r.buffer instanceof ArrayBuffer}function Te(r){return Vu(r)?r:r.slice()}var Wu=Math.pow(2,7),$u=Math.pow(2,14),ju=Math.pow(2,21),Lo=Math.pow(2,28),ko=Math.pow(2,35),Co=Math.pow(2,42),Po=Math.pow(2,49),H=128,pe=127;function V(r){if(r<Wu)return 1;if(r<$u)return 2;if(r<ju)return 3;if(r<Lo)return 4;if(r<ko)return 5;if(r<Co)return 6;if(r<Po)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Mt(r,e,t=0){switch(V(r)){case 8:e[t++]=r&255|H,r/=128;case 7:e[t++]=r&255|H,r/=128;case 6:e[t++]=r&255|H,r/=128;case 5:e[t++]=r&255|H,r/=128;case 4:e[t++]=r&255|H,r>>>=7;case 3:e[t++]=r&255|H,r>>>=7;case 2:e[t++]=r&255|H,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function Gu(r,e,t=0){switch(V(r)){case 8:e.set(t++,r&255|H),r/=128;case 7:e.set(t++,r&255|H),r/=128;case 6:e.set(t++,r&255|H),r/=128;case 5:e.set(t++,r&255|H),r/=128;case 4:e.set(t++,r&255|H),r>>>=7;case 3:e.set(t++,r&255|H),r>>>=7;case 2:e.set(t++,r&255|H),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function Oo(r,e){let t=r[e],n=0;if(n+=t&pe,t<H||(t=r[e+1],n+=(t&pe)<<7,t<H)||(t=r[e+2],n+=(t&pe)<<14,t<H)||(t=r[e+3],n+=(t&pe)<<21,t<H)||(t=r[e+4],n+=(t&pe)*Lo,t<H)||(t=r[e+5],n+=(t&pe)*ko,t<H)||(t=r[e+6],n+=(t&pe)*Co,t<H)||(t=r[e+7],n+=(t&pe)*Po,t<H))return n;throw new RangeError("Could not decode varint")}function Zu(r,e){let t=r.get(e),n=0;if(n+=t&pe,t<H||(t=r.get(e+1),n+=(t&pe)<<7,t<H)||(t=r.get(e+2),n+=(t&pe)<<14,t<H)||(t=r.get(e+3),n+=(t&pe)<<21,t<H)||(t=r.get(e+4),n+=(t&pe)*Lo,t<H)||(t=r.get(e+5),n+=(t&pe)*ko,t<H)||(t=r.get(e+6),n+=(t&pe)*Co,t<H)||(t=r.get(e+7),n+=(t&pe)*Po,t<H))return n;throw new RangeError("Could not decode varint")}function Yr(r,e,t=0){return e==null&&(e=se(V(r))),e instanceof Uint8Array?Mt(r,e,t):Gu(r,e,t)}function mt(r,e=0){return r instanceof Uint8Array?Oo(r,e):Zu(r,e)}var No=new Float32Array([-0]),tt=new Uint8Array(No.buffer);function Mi(r,e,t){No[0]=r,e[t]=tt[0],e[t+1]=tt[1],e[t+2]=tt[2],e[t+3]=tt[3]}function zi(r,e){return tt[0]=r[e],tt[1]=r[e+1],tt[2]=r[e+2],tt[3]=r[e+3],No[0]}var Uo=new Float64Array([-0]),me=new Uint8Array(Uo.buffer);function Ki(r,e,t){Uo[0]=r,e[t]=me[0],e[t+1]=me[1],e[t+2]=me[2],e[t+3]=me[3],e[t+4]=me[4],e[t+5]=me[5],e[t+6]=me[6],e[t+7]=me[7]}function Hi(r,e){return me[0]=r[e],me[1]=r[e+1],me[2]=r[e+2],me[3]=r[e+3],me[4]=r[e+4],me[5]=r[e+5],me[6]=r[e+6],me[7]=r[e+7],Uo[0]}var Yu=BigInt(Number.MAX_SAFE_INTEGER),Xu=BigInt(Number.MIN_SAFE_INTEGER),xe=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return gt;if(e<Yu&&e>Xu)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>qi&&(o=0n,++n>qi&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return gt;let t=e<0;t&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):gt}},gt=new xe(0,0);gt.toBigInt=function(){return 0n};gt.zzEncode=gt.zzDecode=function(){return this};gt.length=function(){return 1};var qi=4294967296n;function Vi(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function Wi(r,e,t){if(t-e<1)return"";let o,s=[],i=0,a;for(;e<t;)a=r[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&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 Fo(r,e,t){let n=t,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function Be(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Xr(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var Mo=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=Te(e),this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,Be(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Be(this,4);return Xr(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Be(this,4);return Xr(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Be(this,4);let e=zi(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Be(this,4);let e=Hi(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw Be(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Wi(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Be(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Be(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new xe(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw Be(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw Be(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Be(this,8);let e=Xr(this.buf,this.pos+=4),t=Xr(this.buf,this.pos+=4);return new xe(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=Oo(this.buf,this.pos);return this.pos+=V(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function ur(r){return new Mo(r instanceof Uint8Array?r:r.subarray())}function Ue(r,e,t){let n=ur(r);return e.decode(n,void 0,t)}var zo={};be(zo,{base10:()=>Qu});var Qu=Je({prefix:"9",name:"base10",alphabet:"0123456789"});var Ko={};be(Ko,{base16:()=>Ju,base16upper:()=>ef});var Ju=Z({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4,caseInsensitive:!0}),ef=Z({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4,caseInsensitive:!0});var Ho={};be(Ho,{base2:()=>tf});var tf=Z({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var qo={};be(qo,{base256emoji:()=>af});var ji=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}"),rf=ji.reduce((r,e,t)=>(r[t]=e,r),[]),nf=ji.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function of(r){return r.reduce((e,t)=>(e+=rf[t],e),"")}function sf(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=nf[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var af=Ot({prefix:"\u{1F680}",name:"base256emoji",encode:of,decode:sf});var Vo={};be(Vo,{base8:()=>cf});var cf=Z({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Wo={};be(Wo,{identity:()=>uf});var uf=Ot({prefix:"\0",name:"identity",encode:r=>vi(_e(r)),decode:r=>_e(Ei(r))});var Ap=new TextEncoder,Ip=new TextDecoder;var $o={};be($o,{sha256:()=>rt,sha512:()=>df});function Gi(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var rt=Ao({name:"sha2-256",code:18,encode:Gi("SHA-256")}),df=Ao({name:"sha2-512",code:19,encode:Gi("SHA-512")});var fr={...Wo,...Ho,...Vo,...zo,...Ko,...wo,...xo,...Eo,...To,...qo},Lp={...$o,...Bo};function Yi(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Zi=Yi("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),jo=Yi("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=se(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),hf={utf8:Zi,"utf-8":Zi,hex:fr.base16,latin1:jo,ascii:jo,binary:jo,...fr},Qr=hf;function W(r,e="utf8"){let t=Qr[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function Go(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return se(i);o+i>e&&(n=se(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var yt=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function Zo(){}var Xo=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},pf=Go();function mf(r){return globalThis.Buffer!=null?se(r):pf(r)}var dr=class{len;head;tail;states;constructor(){this.len=0,this.head=new yt(Zo,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new yt(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Qo((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(Jr,10,xe.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=xe.fromBigInt(e);return this._push(Jr,t.length(),t)}uint64Number(e){return this._push(Mt,V(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=xe.fromBigInt(e).zzEncode();return this._push(Jr,t.length(),t)}sint64Number(e){let t=xe.fromNumber(e).zzEncode();return this._push(Jr,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Yo,1,e?1:0)}fixed32(e){return this._push(lr,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=xe.fromBigInt(e);return this._push(lr,4,t.lo)._push(lr,4,t.hi)}fixed64Number(e){let t=xe.fromNumber(e);return this._push(lr,4,t.lo)._push(lr,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(Mi,4,e)}double(e){return this._push(Ki,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(Yo,1,0):this.uint32(t)._push(yf,t,e)}string(e){let t=Vi(e);return t!==0?this.uint32(t)._push(Fo,t,e):this._push(Yo,1,0)}fork(){return this.states=new Xo(this),this.head=this.tail=new yt(Zo,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 yt(Zo,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=mf(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function Yo(r,e,t){e[t]=r&255}function gf(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var Qo=class extends yt{next;constructor(e,t){super(gf,e,t),this.next=void 0}};function Jr(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function lr(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function yf(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(dr.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(bf,e,r),this},dr.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(wf,e,r),this});function bf(r,e,t){e.set(r,t)}function wf(r,e,t){r.length<40?Fo(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(W(r),t)}function Jo(){return new dr}function Fe(r,e){let t=Jo();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}function*Me(r,e,t){let n=ur(r);yield*e.stream(n,void 0,"$",t)}var en={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function tn(r,e,t,n,o){return{name:r,type:e,encode:t,decode:n,stream:o}}function zt(r){function e(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let t=function(i,a){let c=e(i);a.int32(c)},n=function(i){let a=i.int32();return e(a)},o=function*(i){let a=i.int32();yield e(a)};return tn("enum",en.VARINT,t,n,o)}function ze(r,e,t){return tn("message",en.LENGTH_DELIMITED,r,e,t)}var Ve=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var rn=class extends Error{static name="InsufficientProvidersError";constructor(e="Insufficient providers found"){super(e),this.name="InsufficientProvidersError"}};var es={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Xi={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Qi=new globalThis.TextEncoder;function xf(r,e){let t=es[e],n=Xi[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function Ef(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=es[e],o=Xi[e],s=r;for(;s.length>0;){let i=Qi.encodeInto(s,t);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(t[a]),o=BigInt.asUintN(e,o*n)}return o}function ts(r,{size:e=32,utf8Buffer:t}={}){if(!es[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(t)return Ef(r,e,t);r=Qi.encode(r)}return xf(r,e)}var hr={hash:r=>Number(ts(r,{size:32})),hashV:(r,e)=>vf(hr.hash(r,e))};function vf(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),W(e,"base16")}var rs=64,De=class{fp;h;seed;constructor(e,t,n,o=2){if(o>rs)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),i=ue(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?Q(this.fp,e.fp):!1}};function bt(r,e){return Math.floor(Math.random()*(e-r))+r}var wt=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof De))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof De))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(this.contents[t]==null)return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof De))throw new TypeError("Invalid Fingerprint");let t=bt(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof De))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var Sf=500,pr=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??hr,this.seed=e.seed??bt(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=W(e));let t=new De(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new wt(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new wt(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let s=[n,o],i=s[bt(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new wt(this.bucketSize));for(let a=0;a<Sf;a++){let c=this.buckets[i].swap(t);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new wt(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=W(e));let t=new De(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let s=(n^t.hash())%this.filterSize;return this.buckets[s]?.has(t)??!1}remove(e){typeof e=="string"&&(e=W(e));let t=new De(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let s=(n^t.hash())%this.filterSize,i=this.buckets[s]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},_f={1:.5,2:.84,4:.95,8:.98};function Af(r=.001){return r>.002?2:r>1e-5?4:8}function Ji(r,e=.001){let t=Af(e),n=_f[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),rs);return{filterSize:o,bucketSize:t,fingerprintSize:s}}var nn=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??hr,this.seed=e.seed??bt(0,Math.pow(2,10)),this.filterSeries=[new pr({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=W(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new pr({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=W(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=W(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function on(r,e=.001,t){return new nn({...Ji(r,e),...t??{}})}var sn=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,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 f=this.readAtomically(()=>{let l=this.readChar();if(l===void 0)return;let d=Number.parseInt(l,e);if(!Number.isNaN(d))return d});if(f===void 0)break;if(s*=e,s+=f,s>u||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[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];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var If=45,Tf=15,an=new sn;function ea(r){if(!(r.length>Tf))return an.new(r).parseWith(()=>an.readIPv4Addr())}function ta(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>If))return an.new(r).parseWith(()=>an.readIPv6Addr())}function cn(r){return!!ea(r)}function ra(r){return!!ta(r)}function q(r,e="utf8"){let t=Qr[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var le=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},We=class extends Error{static name="ValidationError";name="ValidationError"},un=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},fn=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function os(r){return e=>q(e,r)}function ss(r){return e=>W(e,r)}function Kt(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function xt(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function na(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=W(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=xt(n);return we([t,o],t.length+o.length)}function oa(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=et.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=xt(n);return we([t,o],t.length+o.length)}function is(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=q(e,"base32"),o=Kt(t);return`${n}:${o}`}var as=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let o=parseInt(t,10);if(isNaN(o)||o<0||o>255)throw new le("Invalid byte value in IP address");e[n]=o}),e},sa=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=cn(t[n]),i;s&&(i=as(t[n]),t[n]=q(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,q(i.subarray(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let s=parseInt(t[n],16);if(isNaN(s)||s<0||s>65535)throw new le("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},ia=function(r){if(r.byteLength!==4)throw new le("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},aa=function(r){if(r.byteLength!==16)throw new le("IPv6 address was incorrect length");let e=[];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")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new le(`Invalid IPv6 address "${t}"`)}};function ca(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new le(`Invalid IPv6 address "${r}"`)}}var ns=Object.values(fr).map(r=>r.decoder),Bf=(function(){let r=ns[0].or(ns[1]);return ns.slice(2).forEach(e=>r=r.or(e)),r})();function ua(r){return Bf.decode(r)}function fa(r){return e=>r.encoder.encode(e)}function Df(r){if(parseInt(r).toString()!==r)throw new We("Value must be an integer")}function Lf(r){if(r<0)throw new We("Value must be a positive integer, or zero")}function kf(r){return e=>{if(e>r)throw new We(`Value must be smaller than or equal to ${r}`)}}function Cf(...r){return e=>{for(let t of r)t(e)}}var mr=Cf(Df,Lf,kf(65535));var ie=-1,cs=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(typeof e=="string"?t=this.protocolsByName.get(e):t=this.protocolsByCode.get(e),t==null)throw new fn(`Protocol ${e} was unknown`);return t}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(t=>{this.protocolsByName.set(t,e)})}removeProtocol(e){let t=this.protocolsByCode.get(e);t!=null&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},$e=new cs,wl=[{code:4,name:"ip4",size:32,valueToBytes:as,bytesToValue:ia,validate:r=>{if(!cn(r))throw new We(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:xt,bytesToValue:Kt,validate:mr},{code:273,name:"udp",size:16,valueToBytes:xt,bytesToValue:Kt,validate:mr},{code:33,name:"dccp",size:16,valueToBytes:xt,bytesToValue:Kt,validate:mr},{code:41,name:"ip6",size:128,valueToBytes:sa,bytesToValue:aa,stringToValue:ca,validate:r=>{if(!ra(r))throw new We(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:ie},{code:43,name:"ipcidr",size:8,bytesToValue:os("base10"),valueToBytes:ss("base10")},{code:53,name:"dns",size:ie},{code:54,name:"dns4",size:ie},{code:55,name:"dns6",size:ie},{code:56,name:"dnsaddr",size:ie},{code:132,name:"sctp",size:16,valueToBytes:xt,bytesToValue:Kt,validate:mr},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:ie,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:ie,bytesToValue:os("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?ss("base58btc")(r):G.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:is,valueToBytes:na},{code:445,name:"onion3",size:296,bytesToValue:is,valueToBytes:oa},{code:446,name:"garlic64",size:ie},{code:447,name:"garlic32",size:ie},{code:448,name:"tls"},{code:449,name:"sni",size:ie},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:ie,bytesToValue:fa(Io),valueToBytes:ua},{code:480,name:"http"},{code:481,name:"http-path",size:ie,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:ie}];wl.forEach(r=>{$e.addProtocol(r)});function la(r){let e=[],t=0;for(;t<r.length;){let n=mt(r,t),o=$e.getProtocol(n),s=V(n),i=xl(o,r,t+s),a=0;i>0&&o.size===ie&&(a=V(i));let c=s+a+i,u={code:n,name:o.name,bytes:Te(r.subarray(t,t+c))};if(i>0){let f=t+s+a,l=r.subarray(f,f+i);u.value=o.bytesToValue?.(l)??q(l)}e.push(u),t+=c}return e}function da(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=$e.getProtocol(n.code),s=V(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??W(n.value),a=i.byteLength,o.size===ie&&(c=V(a)));let u=new Uint8Array(s+c+a),f=0;Mt(n.code,u,f),f+=s,i!=null&&(o.size===ie&&(Mt(a,u,f),f+=c),u.set(i,f)),n.bytes=u}t.push(n.bytes),e+=n.bytes.byteLength}return we(t,e)}function ha(r){if(r.charAt(0)!=="/")throw new le('String multiaddr must start with "/"');let e=[],t="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(t==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=$e.getProtocol(o);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",t="protocol";continue}else if(a)throw new le(`Component ${o} was missing value`);t="value"}else if(t==="value"){let u={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new le(`Component ${o} was missing value`);u.value=c.stringToValue?.(n)??n}e.push(u),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new le("Incomplete multiaddr");return e}function pa(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=$e.getProtocol(e.code);if(t==null)throw new le(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function xl(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:mt(e,t)}var El=Symbol.for("nodejs.util.inspect.custom"),fs=Symbol.for("@multiformats/multiaddr");function vl(r){if(r==null&&(r="/"),ln(r))return r.getComponents();if(r instanceof Uint8Array)return la(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),ha(r);if(Array.isArray(r))return r;throw new le("Must be a string, Uint8Array, Component[], or another Multiaddr")}var us=class r{[fs]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=vl(e),t.validate!==!1&&Sl(this)}get bytes(){return this.#r==null&&(this.#r=da(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=pa(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new un(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,o),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}equals(e){return Q(this.bytes,e.bytes)}[El](){return`Multiaddr(${this.toString()})`}};function Sl(r){r.getComponents().forEach(e=>{let t=$e.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function ln(r){return!!r?.[fs]}function Le(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var dn=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},Ht=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new dn(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new dn(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var ls=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function hn(r={}){return _l(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function _l(r,e){e=e??{};let t=e.onEnd,n=new Ht,o,s,i,a=Le(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((m,g)=>{s=E=>{s=null,n.push(E);try{m(r(n))}catch(A){g(A)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Le()})}},u=m=>s!=null?s(m):(n.push(m),o),f=m=>(n=new Ht,s!=null?s({error:m}):(n.push({error:m}),o)),l=m=>{if(i)return o;if(e?.objectMode!==!0&&m?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:m})},d=m=>i?o:(i=!0,m!=null?f(m):u({done:!0})),h=()=>(n=new Ht,d(),{done:!0}),x=m=>(d(m),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:x,push:l,end:d,get readableLength(){return n.size},onEmpty:async m=>{let g=m?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let E,A;g!=null&&(E=new Promise((k,D)=>{A=()=>{D(new ls)},g.addEventListener("abort",A)}));try{await Promise.race([a.promise,E])}finally{A!=null&&g!=null&&g?.removeEventListener("abort",A)}}},t==null)return o;let _=o;return o={[Symbol.asyncIterator](){return this},next(){return _.next()},throw(m){return _.throw(m),t!=null&&(t(m),t=void 0),{done:!0}},return(){return _.return(),t!=null&&(t(),t=void 0),{done:!0}},push:l,end(m){return _.end(m),t!=null&&(t(m),t=void 0),o},get readableLength(){return _.readableLength},onEmpty:m=>_.onEmpty(m)},o}var ds=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},ma=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function hs(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e,a,c,f=new Promise((l,d)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(i?.aborted){d(ma(i));return}if(i&&(c=()=>{d(ma(i))},i.addEventListener("abort",c,{once:!0})),r.then(l,d),t===Number.POSITIVE_INFINITY)return;let h=new ds;a=s.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(x){d(x)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?l():o instanceof Error?d(o):(h.message=o??`Promise timed out after ${t} milliseconds`,d(h))},t)}).finally(()=>{f.clear(),c&&i&&i.removeEventListener("abort",c)});return f.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},f}var Al=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function Il(r,e,t){let n,o=new Promise((s,i)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:u,removeListener:f}=Al(r),l=async(...h)=>{let x=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(x))return}catch(_){n(),i(_);return}c.push(x),t.count===c.length&&(n(),s(c))},d=(...h)=>{n(),i(t.rejectionMultiArgs?h:h[0])};n=()=>{for(let h of a)f(h,l);for(let h of t.rejectionEvents)a.includes(h)||f(h,d)};for(let h of a)u(h,l);for(let h of t.rejectionEvents)a.includes(h)||u(h,d);t.signal&&t.signal.addEventListener("abort",()=>{d(t.signal.reason)},{once:!0}),t.resolveImmediately&&s(c)});if(o.cancel=n,typeof t.timeout=="number"){let s=hs(o,{milliseconds:t.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function pn(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=Il(r,e,t),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function ps(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var mn=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};function Tl(r){return r.reason}async function gn(r,e,t){if(e==null)return r;let n=t?.translateError??Tl;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let o;try{return await Promise.race([r,new Promise((s,i)=>{o=()=>{i(n(e))},e.addEventListener("abort",o)})])}finally{o!=null&&e.removeEventListener("abort",o)}}var yn=class{deferred;signal;onProgress;constructor(e){this.signal=e?.signal,this.onProgress=e?.onProgress,this.deferred=Le(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Ae)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Bl(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var bn=class{id;fn;options;recipients;status;timeline;controller;dispatchingProgress;constructor(e,t){this.id=Bl(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.dispatchingProgress=!1,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Ae),this.cleanup())}async join(e){let t=new yn(e);return this.recipients.push(t),e?.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await gn(this.fn({...this.options??{},signal:this.controller.signal,onProgress:t=>{if(!this.dispatchingProgress){this.dispatchingProgress=!0;try{this.recipients.forEach(n=>{n.onProgress?.(t)})}finally{this.dispatchingProgress=!1}}}}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var qt=class extends Ne{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=ps(this.emitEmpty.bind(this),1),this.emitIdle=ps(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new mn;let n=new bn(e,t);this.enqueue(n),this.safeDispatchEvent("add");let o=n.join(t).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s});return this.tryToStartAnother(),o}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Ae)}),this.clear()}async onEmpty(e){this.size!==0&&await pn(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await pn(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await pn(this,"idle",e)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=hn({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new Ae("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var wn=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Vt=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},xn=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},gr=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function En(r){return r[Symbol.asyncIterator]!=null}function ga(r,e){if(r.byteLength>e)throw new Vt("Message length too long")}var Sn=r=>{let e=V(r),t=se(e);return Yr(r,t),Sn.bytes=e,t};Sn.bytes=0;function _n(r,e){e=e??{};let t=e.lengthEncoder??Sn,n=e?.maxDataLength??4194304;function*o(s){ga(s,n);let i=t(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return En(r)?(async function*(){for await(let s of r)yield*o(s)})():(function*(){for(let s of r)yield*o(s)})()}_n.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Sn,n=e?.maxDataLength??4194304;return ga(r,n),new fe(t(r.byteLength),r)};var Et;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Et||(Et={}));var ms=r=>{let e=mt(r);return ms.bytes=V(e),e};ms.bytes=0;function yr(r,e){let t=new fe,n=Et.LENGTH,o=-1,s=e?.lengthDecoder??ms,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===Et.LENGTH)try{if(o=s(t),o<0)throw new wn("Invalid message length");if(o>a)throw new Vt("Message length too long");let u=s.bytes;t.consume(u),e?.onLength!=null&&e.onLength(o),n=Et.DATA}catch(u){if(u instanceof RangeError){if(t.byteLength>i)throw new xn("Message length length too long");break}throw u}if(n===Et.DATA){if(t.byteLength<o)break;let u=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(u),yield u,n=Et.LENGTH}}}return En(r)?(async function*(){for await(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw new gr("Unexpected end of input")})():(function*(){for(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw new gr("Unexpected end of input")})()}yr.fromReader=(r,e)=>{let t=1,n=(async function*(){for(;;)try{let{done:s,value:i}=await r.next(t);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{t=1}})();return yr(n,{...e??{},onLength:s=>{t=s}})};var An=class extends qt{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var gs=class extends Map{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function ya(r){let{name:e,metrics:t}=r,n;return t!=null?n=new gs({name:e,metrics:t}):n=new Map,n}var In=class extends Ne{initialPeerSearchComplete;requests;logName;log;logger;minProviders;maxProviders;providers;evictionFilter;initialProviders;cidPeerFilterSize;constructor(e,t){super(),this.logName=t.name,this.logger=e.logger,this.log=e.logger.forComponent(this.logName),this.requests=new Map,this.minProviders=t.minProviders??1,this.maxProviders=t.maxProviders??5,this.cidPeerFilterSize=t.cidPeerFilterSize??100,this.providers=[],this.evictionFilter=on(this.maxProviders),this.initialProviders=[...t.providers??[]]}async retrieve(e,t={}){let n=pt.encode(e.multihash.bytes),o=this.requests.get(n);if(o!=null)return this.log("join existing request for %c",e),o.observers++,o.promise;let s=Le(),i={promise:s.promise,observers:1,queryFilter:on(this.cidPeerFilterSize)};this.requests.set(n,i);let a=!1;this.initialPeerSearchComplete==null&&(a=!0,this.log=this.logger.forComponent(`${this.logName}:${e}`),this.initialPeerSearchComplete=this.findProviders(e,this.minProviders,t));let c=!1,u=new qt({concurrency:this.maxProviders});u.addEventListener("failure",d=>{this.log.error("error querying provider %s, evicting from session - %e",d.detail.job.options.provider,d.detail.error),this.evict(d.detail.job.options.provider)}),u.addEventListener("success",d=>{c=!0,s.resolve(d.detail.result)}),u.addEventListener("idle",()=>{if(c){this.log.trace("session idle, found block");return}if(t.signal?.aborted===!0){this.log.trace("session idle, signal aborted");return}Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",e);for(let d=0;d<this.minProviders&&this.providers.length!==0;d++){let h=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(h)}await this.findProviders(e,this.minProviders,t),this.log("found new providers re-retrieving %c",e),this.requests.delete(n),s.resolve(await this.retrieve(e,t))}).catch(d=>{this.log.error("could not find new providers for %c - %e",e,d),s.reject(d)})});let f=d=>{let h=this.toFilterKey(d.detail);i.queryFilter.has(h)||(i.queryFilter.add(h),this.emitFoundProviderProgressEvent(e,d.detail,t),u.add(async()=>this.queryProvider(e,d.detail,t),{provider:d.detail}).catch(x=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,x)}))};if(this.addEventListener("provider",f),a)try{await gn(this.initialPeerSearchComplete,t.signal),a&&this.log("found initial session peers for %c",e)}catch(d){throw a&&this.log("failed to find initial session peers for %c - %e",e,d),this.requests.delete(n),i.observers>1&&s.reject(d),d}Promise.all([...this.providers].filter(d=>{let h=this.toFilterKey(d),x=i.queryFilter.has(h);return x||i.queryFilter.add(this.toFilterKey(d)),!x}).map(async d=>u.add(async()=>this.queryProvider(e,d,t),{provider:d}))).catch(d=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,d)});let l=()=>{s.reject(new Ae(t.signal?.reason??"Session aborted")),u.abort()};t.signal?.addEventListener("abort",l);try{return await s.promise}finally{this.removeEventListener("provider",f),t.signal?.removeEventListener("abort",l),u.clear(),this.requests.delete(n)}}evict(e){this.evictionFilter.add(this.toFilterKey(e));let t=this.providers.findIndex(n=>this.equals(n,e));t!==-1&&this.providers.splice(t,1)}isEvicted(e){return this.evictionFilter.has(this.toFilterKey(e))}hasProvider(e){return!!(this.providers.find(t=>this.equals(t,e))!=null||this.isEvicted(e))}async addPeer(e,t){let n=await this.convertToProvider(e,"manually-added",t);n==null||this.hasProvider(n)||(this.providers.push(n),this.safeDispatchEvent("provider",{detail:n}))}async findProviders(e,t,n){let o=Le(),s=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c - %d initial providers",t,this.maxProviders,e,this.initialProviders.length);let i=this,a=async function*(){for(;i.initialProviders.length>0;){let u=i.initialProviders.pop();if(u==null)continue;let f=await i.convertToProvider(u,"manual",n);f!=null&&(yield f)}},c=async function*(){yield*a(),yield*i.findNewProviders(e,n)};for await(let u of c()){if(this.providers.length===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(u)&&(this.log("found %d providers, %d in session",s,this.providers.length),this.providers.push(u),this.safeDispatchEvent("provider",{detail:u}),s++,this.providers.length===t&&(this.log("session is ready with %d peer(s), new peers present",this.providers.length),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers %d",this.providers.length);break}}if(this.log("found %d new session peers while trying to find %d, %d in session",s,t,this.providers.length),this.providers.length<t)throw new rn(`Found ${s} of ${t} ${this.name} providers for ${e}, ${this.providers.length} in session after evictions`)}).catch(i=>{this.log.error("error searching routing for potential session peers for %c - %e",e,i),o.reject(i)}),o.promise}};function Ol(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var wa=Ol;function Rl(r){return r[Symbol.asyncIterator]!=null}function Nl(r){if(Rl(r))return(async()=>{let n=new Uint8Array(0);for await(let o of r)n=we([n,o],n.length+o.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return we(e,t)}var xa=Nl;function Tn(r){return r==null?!1:G.asCID(r)!=null}async function Ea(r,e,t,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,Te(e),Te(t.subarray()));return n?.signal?.throwIfAborted(),s}var Ul=parseInt("11111",2),ys=parseInt("10000000",2),Fl=parseInt("01111111",2),va={0:br,1:br,2:Ml,3:Hl,4:ql,5:Kl,6:zl,16:br,22:br,48:br};function bs(r,e={offset:0}){let t=r[e.offset]&Ul;if(e.offset++,va[t]!=null)return va[t](r,e);throw new Error("No decoder for tag "+t)}function wr(r,e){let t=0;if((r[e.offset]&ys)===ys){let n=r[e.offset]&Fl,o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++)o+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(o,16)}else t=r[e.offset],e.offset++;return t}function br(r,e){wr(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=bs(r,e);if(n===null)break;t.push(n)}return t}function Ml(r,e){let t=wr(r,e),n=e.offset,o=e.offset+t,s=[];for(let i=n;i<o;i++)i===n&&r[i]===0||s.push(r[i]);return e.offset+=t,Uint8Array.from(s)}function zl(r,e){let t=wr(r,e),n=e.offset+t,o=r[e.offset];e.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(;e.offset<n;){let u=r[e.offset];if(e.offset++,c.push(u&127),u<128){c.reverse();let f=0;for(let l=0;l<c.length;l++)f+=c[l]<<l*7;a+=`.${f}`,c=[]}}return a}function Kl(r,e){return e.offset++,null}function Hl(r,e){let t=wr(r,e),n=r[e.offset];e.offset++;let o=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function ql(r,e){let t=wr(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function Vl(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new fe;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function ws(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=Vl(r.byteLength);return new fe(Uint8Array.from([e.byteLength|ys]),e)}function Sa(r){let e=new fe,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new fe(Uint8Array.from([2]),ws(e),e)}function _a(r){let e=Uint8Array.from([0]),t=new fe(e,r);return new fe(Uint8Array.from([3]),ws(t),t)}function Bn(r,e=48){let t=new fe;for(let n of r)t.append(n);return new fe(Uint8Array.from([e]),ws(t),t)}var Wl=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),$l=Uint8Array.from([6,5,43,129,4,0,34]),jl=Uint8Array.from([6,5,43,129,4,0,35]),Gl={ext:!0,kty:"EC",crv:"P-256"},Zl={ext:!0,kty:"EC",crv:"P-384"},Yl={ext:!0,kty:"EC",crv:"P-521"},xs=32,Es=48,vs=66;function Aa(r){let e=bs(r);return Ia(e)}function Ia(r){let e=r[1][1][0],t=1,n,o;if(e.byteLength===xs*2+1)return n=q(e.subarray(t,t+xs),"base64url"),o=q(e.subarray(t+xs),"base64url"),new Wt({...Gl,key_ops:["verify"],x:n,y:o});if(e.byteLength===Es*2+1)return n=q(e.subarray(t,t+Es),"base64url"),o=q(e.subarray(t+Es),"base64url"),new Wt({...Zl,key_ops:["verify"],x:n,y:o});if(e.byteLength===vs*2+1)return n=q(e.subarray(t,t+vs),"base64url"),o=q(e.subarray(t+vs),"base64url"),new Wt({...Yl,key_ops:["verify"],x:n,y:o});throw new Se(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function Ta(r){return Bn([Sa(Uint8Array.from([1])),Bn([Xl(r.crv)],160),Bn([_a(new fe(Uint8Array.from([4]),W(r.x??"","base64url"),W(r.y??"","base64url")))],161)]).subarray()}function Xl(r){if(r==="P-256")return Wl;if(r==="P-384")return $l;if(r==="P-521")return jl;throw new Se(`Invalid curve ${r}`)}var Wt=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=Ta(this.jwk)),this._raw}toMultihash(){return Ie.digest($t(this))}toCID(){return G.createV1(114,this.toMultihash())}toString(){return ee.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Q(this.raw,e.raw)}async verify(e,t,n){return Ea(this.jwk,t,e,n)}};function Ss(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}function nt(r,e=""){if(typeof r!="number"){let t=e&&`"${e}" `;throw new TypeError(`${t}expected number, got ${typeof r}`)}if(!Number.isSafeInteger(r)||r<0){let t=e&&`"${e}" `;throw new RangeError(`${t}expected integer >= 0, got ${r}`)}}function Ee(r,e,t=""){let n=Ss(r),o=r?.length,s=e!==void 0;if(!n||s&&o!==e){let i=t&&`"${t}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof r}`,u=i+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(u):new TypeError(u)}return r}function Dn(r){if(typeof r!="function"||typeof r.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(nt(r.outputLen),nt(r.blockLen),r.outputLen<1)throw new Error('"outputLen" must be >= 1');if(r.blockLen<1)throw new Error('"blockLen" must be >= 1')}function jt(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function Ln(r,e){Ee(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length<t)throw new RangeError('"digestInto() output" expected to be of length >='+t)}function Ge(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function kn(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function ke(r,e){return r<<32-e|r>>>e}var Da=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Ql=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Cn(r){if(Ee(r),Da)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=Ql[r[t]];return e}var je={_0:48,_9:57,A:65,F:70,a:97,f:102};function Ba(r){if(r>=je._0&&r<=je._9)return r-je._0;if(r>=je.A&&r<=je.F)return r-(je.A-10);if(r>=je.a&&r<=je.f)return r-(je.a-10)}function xr(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);if(Da)try{return Uint8Array.fromHex(r)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}let e=r.length,t=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let o=0,s=0;o<t;o++,s+=2){let i=Ba(r.charCodeAt(s)),a=Ba(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function _s(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];Ee(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let s=r[n];t.set(s,o),o+=s.length}return t}function As(r,e={}){let t=(o,s)=>r(s).update(o).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.canXOF=n.canXOF,t.create=o=>r(o),Object.assign(t,e),Object.freeze(t)}function La(r=32){nt(r,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(r>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${r}`);return e.getRandomValues(new Uint8Array(r))}var Is=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function ka(r,e,t){return r&e^~r&t}function Ca(r,e,t){return r&e^r&t^e&t}var Er=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,o){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=kn(this.buffer)}update(e){jt(this),Ee(e);let{view:t,buffer:n,blockLen:o}=this,s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=kn(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){jt(this),Ln(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,Ge(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let l=i;l<o;l++)t[l]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=kn(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let u=c/4,f=this.get();if(u>f.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<u;l++)a.setUint32(4*l,f[l],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},Ze=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var de=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Pn=BigInt(4294967295),Pa=BigInt(32);function Jl(r,e=!1){return e?{h:Number(r&Pn),l:Number(r>>Pa&Pn)}:{h:Number(r>>Pa&Pn)|0,l:Number(r&Pn)|0}}function Oa(r,e=!1){let t=r.length,n=new Uint32Array(t),o=new Uint32Array(t);for(let s=0;s<t;s++){let{h:i,l:a}=Jl(r[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var Ts=(r,e,t)=>r>>>t,Bs=(r,e,t)=>r<<32-t|e>>>t,vt=(r,e,t)=>r>>>t|e<<32-t,St=(r,e,t)=>r<<32-t|e>>>t,vr=(r,e,t)=>r<<64-t|e>>>t-32,Sr=(r,e,t)=>r>>>t-32|e<<64-t;function Ke(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var Ra=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),Na=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,Ua=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),Fa=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,Ma=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),za=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var td=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]),ot=new Uint32Array(64),Ds=class extends Er{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,t,n,o,s,i,a,c]}set(e,t,n,o,s,i,a,c){this.A=e|0,this.B=t|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(e,t){for(let l=0;l<16;l++,t+=4)ot[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){let d=ot[l-15],h=ot[l-2],x=ke(d,7)^ke(d,18)^d>>>3,_=ke(h,17)^ke(h,19)^h>>>10;ot[l]=_+ot[l-7]+x+ot[l-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:f}=this;for(let l=0;l<64;l++){let d=ke(a,6)^ke(a,11)^ke(a,25),h=f+d+ka(a,c,u)+td[l]+ot[l]|0,_=(ke(n,2)^ke(n,13)^ke(n,22))+Ca(n,o,s)|0;f=u,u=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+_|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,f=f+this.H|0,this.set(n,o,s,i,a,c,u,f)}roundClean(){Ge(ot)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Ge(this.buffer)}},Ls=class extends Ds{A=Ze[0]|0;B=Ze[1]|0;C=Ze[2]|0;D=Ze[3]|0;E=Ze[4]|0;F=Ze[5]|0;G=Ze[6]|0;H=Ze[7]|0;constructor(){super(32)}};var Ka=Oa(["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))),rd=Ka[0],nd=Ka[1],st=new Uint32Array(80),it=new Uint32Array(80),ks=class extends Er{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:u,El:f,Fh:l,Fl:d,Gh:h,Gl:x,Hh:_,Hl:m}=this;return[e,t,n,o,s,i,a,c,u,f,l,d,h,x,_,m]}set(e,t,n,o,s,i,a,c,u,f,l,d,h,x,_,m){this.Ah=e|0,this.Al=t|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=f|0,this.Fh=l|0,this.Fl=d|0,this.Gh=h|0,this.Gl=x|0,this.Hh=_|0,this.Hl=m|0}process(e,t){for(let A=0;A<16;A++,t+=4)st[A]=e.getUint32(t),it[A]=e.getUint32(t+=4);for(let A=16;A<80;A++){let k=st[A-15]|0,D=it[A-15]|0,R=vt(k,D,1)^vt(k,D,8)^Ts(k,D,7),C=St(k,D,1)^St(k,D,8)^Bs(k,D,7),I=st[A-2]|0,N=it[A-2]|0,U=vt(I,N,19)^vr(I,N,61)^Ts(I,N,6),O=St(I,N,19)^Sr(I,N,61)^Bs(I,N,6),p=Ua(C,O,it[A-7],it[A-16]),y=Fa(p,R,U,st[A-7],st[A-16]);st[A]=y|0,it[A]=p|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:f,Eh:l,El:d,Fh:h,Fl:x,Gh:_,Gl:m,Hh:g,Hl:E}=this;for(let A=0;A<80;A++){let k=vt(l,d,14)^vt(l,d,18)^vr(l,d,41),D=St(l,d,14)^St(l,d,18)^Sr(l,d,41),R=l&h^~l&_,C=d&x^~d&m,I=Ma(E,D,C,nd[A],it[A]),N=za(I,g,k,R,rd[A],st[A]),U=I|0,O=vt(n,o,28)^vr(n,o,34)^vr(n,o,39),p=St(n,o,28)^Sr(n,o,34)^Sr(n,o,39),y=n&s^n&a^s&a,v=o&i^o&c^i&c;g=_|0,E=m|0,_=h|0,m=x|0,h=l|0,x=d|0,{h:l,l:d}=Ke(u|0,f|0,N|0,U|0),u=a|0,f=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let w=Ra(U,p,v);n=Na(w,N,O,y),o=w|0}({h:n,l:o}=Ke(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=Ke(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=Ke(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:f}=Ke(this.Dh|0,this.Dl|0,u|0,f|0),{h:l,l:d}=Ke(this.Eh|0,this.El|0,l|0,d|0),{h,l:x}=Ke(this.Fh|0,this.Fl|0,h|0,x|0),{h:_,l:m}=Ke(this.Gh|0,this.Gl|0,_|0,m|0),{h:g,l:E}=Ke(this.Hh|0,this.Hl|0,g|0,E|0),this.set(n,o,s,i,a,c,u,f,l,d,h,x,_,m,g,E)}roundClean(){Ge(st,it)}destroy(){this.destroyed=!0,Ge(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Cs=class extends ks{Ah=de[0]|0;Al=de[1]|0;Bh=de[2]|0;Bl=de[3]|0;Ch=de[4]|0;Cl=de[5]|0;Dh=de[6]|0;Dl=de[7]|0;Eh=de[8]|0;El=de[9]|0;Fh=de[10]|0;Fl=de[11]|0;Gh=de[12]|0;Gl=de[13]|0;Hh=de[14]|0;Hl=de[15]|0;constructor(){super(64)}};var Ha=As(()=>new Ls,Is(1));var On=As(()=>new Cs,Is(3));var z=(r,e,t)=>Ee(r,e,t),Os=nt,Gt=Cn,re=(...r)=>_s(...r),Zt=r=>xr(r),_t=Ss,_r=r=>La(r),Nn=BigInt(0),Ps=BigInt(1);function Ce(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}" `;throw new TypeError(t+"expected boolean, got type="+typeof r)}return r}function Un(r){if(typeof r=="bigint"){if(!Rn(r))throw new RangeError("positive bigint expected, got "+r)}else Os(r);return r}function Pe(r,e=""){if(typeof r!="number"){let t=e&&`"${e}" `;throw new TypeError(t+"expected number, got type="+typeof r)}if(!Number.isSafeInteger(r)){let t=e&&`"${e}" `;throw new RangeError(t+"expected safe integer, got "+r)}}function Ar(r){let e=Un(r).toString(16);return e.length&1?"0"+e:e}function qa(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);return r===""?Nn:BigInt("0x"+r)}function At(r){return qa(Cn(r))}function He(r){return qa(Cn(Ir(Ee(r)).reverse()))}function Fn(r,e){if(nt(e),e===0)throw new RangeError("zero length");r=Un(r);let t=r.toString(16);if(t.length>e*2)throw new RangeError("number too large");return xr(t.padStart(e*2,"0"))}function Rs(r,e){return Fn(r,e).reverse()}function Va(r,e){if(r=z(r),e=z(e),r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}function Ir(r){return Uint8Array.from(z(r))}function Mn(r){if(typeof r!="string")throw new TypeError("ascii string expected, got "+typeof r);return Uint8Array.from(r,(e,t)=>{let n=e.charCodeAt(0);if(e.length!==1||n>127)throw new RangeError(`string contains non-ASCII character "${r[t]}" with code ${n} at position ${t}`);return n})}var Rn=r=>typeof r=="bigint"&&Nn<=r;function od(r,e,t){return Rn(r)&&Rn(e)&&Rn(t)&&e<=r&&r<t}function Yt(r,e,t,n){if(!od(e,t,n))throw new RangeError("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function Xt(r){if(r<Nn)throw new Error("expected non-negative bigint, got "+r);let e;for(e=0;r>Nn;r>>=Ps,e+=1);return e}var Tr=r=>(Ps<<BigInt(r))-Ps;function Wa(r,e,t){if(nt(r,"hashLen"),nt(e,"qByteLen"),typeof t!="function")throw new TypeError("hmacFn must be a function");let n=m=>new Uint8Array(m),o=Uint8Array.of(),s=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(r),u=n(r),f=0,l=()=>{c.fill(1),u.fill(0),f=0},d=(...m)=>t(u,re(c,...m)),h=(m=o)=>{u=d(s,m),c=d(),m.length!==0&&(u=d(i,m),c=d())},x=()=>{if(f++>=a)throw new Error("drbg: tried max amount of iterations");let m=0,g=[];for(;m<e;){c=d();let E=c.slice();g.push(E),m+=c.length}return re(...g)};return(m,g)=>{l(),h(m);let E;for(;(E=g(x()))===void 0;)h();return l(),E}}function Oe(r,e={},t={}){if(Object.prototype.toString.call(r)!=="[object Object]")throw new TypeError("expected valid options object");function n(s,i,a){if(!a&&i!=="function"&&!Object.hasOwn(r,s))throw new TypeError(`param "${s}" is invalid: expected own property`);let c=r[s];if(a&&c===void 0)return;let u=typeof c;if(u!==i||c===null)throw new TypeError(`param "${s}" is invalid: expected ${i}, got ${u}`)}let o=(s,i)=>Object.entries(s).forEach(([a,c])=>n(a,c,i));o(e,!1),o(t,!0)}var Ns=()=>{throw new Error("not implemented")};var he=BigInt(0),Y=BigInt(1),It=BigInt(2),Za=BigInt(3),Ya=BigInt(4),Xa=BigInt(5),sd=BigInt(7),Qa=BigInt(8),id=BigInt(9),Ja=BigInt(16);function J(r,e){if(e<=he)throw new Error("mod: expected positive modulus, got "+e);let t=r%e;return t>=he?t:e+t}function $(r,e,t){if(e<he)throw new Error("pow2: expected non-negative exponent, got "+e);let n=r;for(;e-- >he;)n*=n,n%=t;return n}function $a(r,e){if(r===he)throw new Error("invert: expected non-zero number");if(e<=he)throw new Error("invert: expected positive modulus, got "+e);let t=J(r,e),n=e,o=he,s=Y,i=Y,a=he;for(;t!==he;){let u=n/t,f=n-t*u,l=o-i*u,d=s-a*u;n=t,t=f,o=i,s=a,i=l,a=d}if(n!==Y)throw new Error("invert: does not exist");return J(o,e)}function Us(r,e,t){let n=r;if(!n.eql(n.sqr(e),t))throw new Error("Cannot find square root")}function ec(r,e){let t=r,n=(t.ORDER+Y)/Ya,o=t.pow(e,n);return Us(t,o,e),o}function ad(r,e){let t=r,n=(t.ORDER-Xa)/Qa,o=t.mul(e,It),s=t.pow(o,n),i=t.mul(e,s),a=t.mul(t.mul(i,It),s),c=t.mul(i,t.sub(a,t.ONE));return Us(t,c,e),c}function cd(r){let e=Qt(r),t=tc(r),n=t(e,e.neg(e.ONE)),o=t(e,n),s=t(e,e.neg(n)),i=(r+sd)/Ja;return((a,c)=>{let u=a,f=u.pow(c,i),l=u.mul(f,n),d=u.mul(f,o),h=u.mul(f,s),x=u.eql(u.sqr(l),c),_=u.eql(u.sqr(d),c);f=u.cmov(f,l,x),l=u.cmov(h,d,_);let m=u.eql(u.sqr(l),c),g=u.cmov(f,l,m);return Us(u,g,c),g})}function tc(r){if(r<Za)throw new Error("sqrt is not defined for small field");let e=r-Y,t=0;for(;e%It===he;)e/=It,t++;let n=It,o=Qt(r);for(;ja(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return ec;let s=o.pow(n,e),i=(e+Y)/It;return function(c,u){let f=c;if(f.is0(u))return u;if(ja(f,u)!==1)throw new Error("Cannot find square root");let l=t,d=f.mul(f.ONE,s),h=f.pow(u,e),x=f.pow(u,i);for(;!f.eql(h,f.ONE);){if(f.is0(h))return f.ZERO;let _=1,m=f.sqr(h);for(;!f.eql(m,f.ONE);)if(_++,m=f.sqr(m),_===l)throw new Error("Cannot find square root");let g=Y<<BigInt(l-_-1),E=f.pow(d,g);l=_,d=f.sqr(E),h=f.mul(h,d),x=f.mul(x,E)}return x}}function ud(r){return r%Ya===Za?ec:r%Qa===Xa?ad:r%Ja===id?cd(r):tc(r)}var Ye=(r,e)=>(J(r,e)&Y)===Y,fd=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Fs(r){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=fd.reduce((n,o)=>(n[o]="function",n),e);if(Oe(r,t),Pe(r.BYTES,"BYTES"),Pe(r.BITS,"BITS"),r.BYTES<1||r.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(r.ORDER<=Y)throw new Error("invalid field: expected ORDER > 1, got "+r.ORDER);return r}function ld(r,e,t){let n=r;if(t<he)throw new Error("invalid exponent, negatives unsupported");if(t===he)return n.ONE;if(t===Y)return e;let o=n.ONE,s=e;for(;t>he;)t&Y&&(o=n.mul(o,s)),s=n.sqr(s),t>>=Y;return o}function Br(r,e,t=!1){let n=r,o=new Array(e.length).fill(t?n.ZERO:void 0),s=e.reduce((a,c,u)=>n.is0(c)?a:(o[u]=a,n.mul(a,c)),n.ONE),i=n.inv(s);return e.reduceRight((a,c,u)=>n.is0(c)?a:(o[u]=n.mul(a,o[u]),n.mul(a,c)),i),o}function ja(r,e){let t=r,n=(t.ORDER-Y)/It,o=t.pow(e,n),s=t.eql(o,t.ONE),i=t.eql(o,t.ZERO),a=t.eql(o,t.neg(t.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function dd(r,e){if(e!==void 0&&Os(e),r<=he)throw new Error("invalid n length: expected positive n, got "+r);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let t=Xt(r);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected bit length (${t}) >= n.length (${e})`);let n=e!==void 0?e:t,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}var Ga=new WeakMap,zn=class{ORDER;BITS;BYTES;isLE;ZERO=he;ONE=Y;_lengths;_mod;constructor(e,t={}){if(e<=Y)throw new Error("invalid field: expected ORDER > 1, got "+e);let n;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(n=t.BITS),typeof t.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0}),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=Object.freeze(t.allowedLengths.slice())),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:o,nByteLength:s}=dd(e,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,Object.freeze(this)}create(e){return J(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return he<=e&&e<this.ORDER}is0(e){return e===he}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&Y)===Y}neg(e){return J(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return J(e*e,this.ORDER)}add(e,t){return J(e+t,this.ORDER)}sub(e,t){return J(e-t,this.ORDER)}mul(e,t){return J(e*t,this.ORDER)}pow(e,t){return ld(this,e,t)}div(e,t){return J(e*$a(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return $a(e,this.ORDER)}sqrt(e){let t=Ga.get(this);return t||Ga.set(this,t=ud(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?Rs(e,this.BYTES):Fn(e,this.BYTES)}fromBytes(e,t=!1){z(e);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(e.length<1||!n.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let u=new Uint8Array(o);u.set(e,s?0:u.length-e.length),e=u}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?He(e):At(e);if(a&&(c=J(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Br(this,e)}cmov(e,t,n){return Ce(n,"condition"),n?t:e}};Object.freeze(zn.prototype);function Qt(r,e={}){return new zn(r,e)}function rc(r){if(typeof r!="bigint")throw new Error("field order must be bigint");if(r<=Y)throw new Error("field order must be greater than 1");let e=Xt(r-Y);return Math.ceil(e/8)}function Ms(r){let e=rc(r);return e+Math.ceil(e/2)}function zs(r,e,t=!1){z(r);let n=r.length,o=rc(e),s=Math.max(Ms(e),16);if(n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=t?He(r):At(r),a=J(i,e-Y)+Y;return t?Rs(a,o):Fn(a,o)}var Jt=BigInt(0),Tt=BigInt(1);function Dr(r,e){let t=e.negate();return r?t:e}function Bt(r,e){let t=Br(r.Fp,e.map(n=>n.Z));return e.map((n,o)=>r.fromAffine(n.toAffine(t[o])))}function ic(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function Ks(r,e){ic(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1),o=2**r,s=Tr(r),i=BigInt(r);return{windows:t,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function nc(r,e,t){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=t,a=Number(r&o),c=r>>i;a>n&&(a-=s,c+=Tt);let u=e*n,f=u+Math.abs(a)-1,l=a===0,d=a<0,h=e%2!==0;return{nextN:c,offset:f,isZero:l,isNeg:d,isNegF:h,offsetF:u}}var Hs=new WeakMap,ac=new WeakMap;function qs(r){return ac.get(r)||1}function oc(r){if(r!==Jt)throw new Error("invalid wNAF")}var er=class{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let o=e;for(;t>Jt;)t&Tt&&(n=n.add(o)),o=o.double(),t>>=Tt;return n}precomputeWindow(e,t){let{windows:n,windowSize:o}=Ks(t,this.bits),s=[],i=e,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(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=Ks(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:u,isZero:f,isNeg:l,isNegF:d,offsetF:h}=nc(n,a,i);n=c,f?s=s.add(Dr(d,t[h])):o=o.add(Dr(l,t[u]))}return oc(n),{p:o,f:s}}wNAFUnsafe(e,t,n,o=this.ZERO){let s=Ks(e,this.bits);for(let i=0;i<s.windows&&n!==Jt;i++){let{nextN:a,offset:c,isZero:u,isNeg:f}=nc(n,i,s);if(n=a,!u){let l=t[c];o=o.add(f?l.negate():l)}}return oc(n),o}getPrecomputes(e,t,n){let o=Hs.get(t);return o||(o=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(o=n(o)),Hs.set(t,o))),o}cached(e,t,n){let o=qs(e);return this.wNAF(o,this.getPrecomputes(o,e,n),t)}unsafe(e,t,n,o){let s=qs(e);return s===1?this._unsafeLadder(e,t,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),t,o)}createCache(e,t){ic(t,this.bits),ac.set(e,t),Hs.delete(e)}hasCache(e){return qs(e)!==1}};function cc(r,e,t,n){let o=e,s=r.ZERO,i=r.ZERO;for(;t>Jt||n>Jt;)t&Tt&&(s=s.add(o)),n&Tt&&(i=i.add(o)),o=o.double(),t>>=Tt,n>>=Tt;return{p1:s,p2:i}}function sc(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Fs(e),e}else return Qt(r,{isLE:t})}function Kn(r,e,t={},n){if(n===void 0&&(n=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let u=e[c];if(!(typeof u=="bigint"&&u>Jt))throw new Error(`CURVE.${c} must be positive bigint`)}let o=sc(e.p,t.Fp,n),s=sc(e.n,t.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}function Hn(r,e){return function(n){let o=r(n);return{secretKey:o,publicKey:e(o)}}}var at=BigInt(0),ae=BigInt(1),Vs=BigInt(2),hd=BigInt(8);function pd(r,e,t,n){let o=r.sqr(t),s=r.sqr(n),i=r.add(r.mul(e.a,o),s),a=r.add(r.ONE,r.mul(e.d,r.mul(o,s)));return r.eql(i,a)}function uc(r,e={}){let t=e,n=Kn("edwards",r,t,t.FpFnLE),{Fp:o,Fn:s}=n,i=n.CURVE,{h:a}=i;Oe(t,{},{uvRatio:"function"});let c=Vs<<BigInt(s.BYTES*8)-ae,u=_=>o.create(_),f=t.uvRatio===void 0?(_,m)=>{try{return{isValid:!0,value:o.sqrt(o.div(_,m))}}catch{return{isValid:!1,value:at}}}:t.uvRatio;if(!pd(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function l(_,m,g=!1){let E=g?ae:at;return Yt("coordinate "+_,m,E,c),m}function d(_){if(!(_ instanceof h))throw new Error("EdwardsPoint expected")}class h{static BASE=new h(i.Gx,i.Gy,ae,u(i.Gx*i.Gy));static ZERO=new h(at,ae,ae,at);static Fp=o;static Fn=s;X;Y;Z;T;constructor(m,g,E,A){this.X=l("x",m),this.Y=l("y",g),this.Z=l("z",E,!0),this.T=l("t",A),Object.freeze(this)}static CURVE(){return i}static fromAffine(m){if(m instanceof h)throw new Error("extended point not allowed");let{x:g,y:E}=m||{};return l("x",g),l("y",E),new h(g,E,ae,u(g*E))}static fromBytes(m,g=!1){let E=o.BYTES,{a:A,d:k}=i;m=Ir(z(m,E,"point")),Ce(g,"zip215");let D=Ir(m),R=m[E-1];D[E-1]=R&-129;let C=He(D),I=g?c:o.ORDER;Yt("point.y",C,at,I);let N=u(C*C),U=u(N-ae),O=u(k*N-A),{isValid:p,value:y}=f(U,O);if(!p)throw new Error("bad point: invalid y coordinate");let v=(y&ae)===ae,w=(R&128)!==0;if(!g&&y===at&&w)throw new Error("bad point: x=0 and x_0=1");return w!==v&&(y=u(-y)),h.fromAffine({x:y,y:C})}static fromHex(m,g=!1){return h.fromBytes(Zt(m),g)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(m=8,g=!0){return x.createCache(this,m),g||this.multiply(Vs),this}assertValidity(){let m=this,{a:g,d:E}=i;if(m.is0())throw new Error("bad point: ZERO");let{X:A,Y:k,Z:D,T:R}=m,C=u(A*A),I=u(k*k),N=u(D*D),U=u(N*N),O=u(C*g),p=u(N*u(O+I)),y=u(U+u(E*u(C*I)));if(p!==y)throw new Error("bad point: equation left != right (1)");let v=u(A*k),w=u(D*R);if(v!==w)throw new Error("bad point: equation left != right (2)")}equals(m){d(m);let{X:g,Y:E,Z:A}=this,{X:k,Y:D,Z:R}=m,C=u(g*R),I=u(k*A),N=u(E*R),U=u(D*A);return C===I&&N===U}is0(){return this.equals(h.ZERO)}negate(){return new h(u(-this.X),this.Y,this.Z,u(-this.T))}double(){let{a:m}=i,{X:g,Y:E,Z:A}=this,k=u(g*g),D=u(E*E),R=u(Vs*u(A*A)),C=u(m*k),I=g+E,N=u(u(I*I)-k-D),U=C+D,O=U-R,p=C-D,y=u(N*O),v=u(U*p),w=u(N*p),b=u(O*U);return new h(y,v,b,w)}add(m){d(m);let{a:g,d:E}=i,{X:A,Y:k,Z:D,T:R}=this,{X:C,Y:I,Z:N,T:U}=m,O=u(A*C),p=u(k*I),y=u(R*E*U),v=u(D*N),w=u((A+k)*(C+I)-O-p),b=v-y,S=v+y,B=u(p-g*O),T=u(w*b),L=u(S*B),P=u(w*B),M=u(b*S);return new h(T,L,M,P)}subtract(m){return d(m),this.add(m.negate())}multiply(m){if(!s.isValidNot0(m))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:g,f:E}=x.cached(this,m,A=>Bt(h,A));return Bt(h,[g,E])[0]}multiplyUnsafe(m){if(!s.isValid(m))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return m===at?h.ZERO:this.is0()||m===ae?this:x.unsafe(this,m,g=>Bt(h,g))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return x.unsafe(this,i.n).is0()}toAffine(m){let g=this,E=m,{X:A,Y:k,Z:D}=g,R=g.is0();E==null&&(E=R?hd:o.inv(D));let C=u(A*E),I=u(k*E),N=o.mul(D,E);if(R)return{x:at,y:ae};if(N!==ae)throw new Error("invZ was invalid");return{x:C,y:I}}clearCofactor(){return a===ae?this:this.multiplyUnsafe(a)}toBytes(){let{x:m,y:g}=this.toAffine(),E=o.toBytes(g);return E[E.length-1]|=m&ae?128:0,E}toHex(){return Gt(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let x=new er(h,s.BITS);return s.BITS>=8&&h.BASE.precompute(8),Object.freeze(h.prototype),Object.freeze(h),h}var qn=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e}static fromBytes(e){Ns()}static fromHex(e){Ns()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return Gt(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.ep.precompute(e,t),this}};function fc(r,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');let n=e,o=t;Oe(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:s}=o,{BASE:i,Fp:a,Fn:c}=r,u=n.outputLen,f=2*a.BYTES;if(u!==void 0&&(Pe(u,"hash.outputLen"),u!==f))throw new Error(`hash.outputLen must be ${f}, got ${u}`);let l=o.randomBytes===void 0?_r:o.randomBytes,d=o.adjustScalarBytes===void 0?p=>p:o.adjustScalarBytes,h=o.domain===void 0?(p,y,v)=>{if(Ce(v,"phflag"),y.length||v)throw new Error("Contexts/pre-hash are not supported");return p}:o.domain;function x(p){return c.create(He(p))}function _(p){let y=C.secretKey;z(p,C.secretKey,"secretKey");let v=z(n(p),2*y,"hashedSecretKey"),w=d(v.slice(0,y)),b=v.slice(y,2*y),S=x(w);return{head:w,prefix:b,scalar:S}}function m(p){let{head:y,prefix:v,scalar:w}=_(p),b=i.multiply(w),S=b.toBytes();return{head:y,prefix:v,scalar:w,point:b,pointBytes:S}}function g(p){return m(p).pointBytes}function E(p=Uint8Array.of(),...y){let v=re(...y);return x(n(h(v,z(p,void 0,"context"),!!s)))}function A(p,y,v={}){p=z(p,void 0,"message"),s&&(p=s(p));let{prefix:w,scalar:b,pointBytes:S}=m(y),B=E(v.context,w,p),T=i.multiply(B).toBytes(),L=E(v.context,T,S,p),P=c.create(B+L*b);if(!c.isValid(P))throw new Error("sign failed: invalid s");let M=re(T,c.toBytes(P));return z(M,C.signature,"result")}let k={zip215:o.zip215};function D(p,y,v,w=k){let{context:b}=w,S=w.zip215===void 0?!!k.zip215:w.zip215,B=C.signature;p=z(p,B,"signature"),y=z(y,void 0,"message"),v=z(v,C.publicKey,"publicKey"),S!==void 0&&Ce(S,"zip215"),s&&(y=s(y));let T=B/2,L=p.subarray(0,T),P=He(p.subarray(T,B)),M,K,F;try{M=r.fromBytes(v,S),K=r.fromBytes(L,S),F=i.multiplyUnsafe(P)}catch{return!1}if(!S&&M.isSmallOrder())return!1;let te=E(b,L,v,y);return K.add(M.multiplyUnsafe(te)).subtract(F).clearCofactor().is0()}let R=a.BYTES,C={secretKey:R,publicKey:R,signature:2*R,seed:R};function I(p){return p=p===void 0?l(C.seed):p,z(p,C.seed,"seed")}function N(p){return _t(p)&&p.length===C.secretKey}function U(p,y){try{return!!r.fromBytes(p,y===void 0?k.zip215:y)}catch{return!1}}let O={getExtendedPublicKey:m,randomSecretKey:I,isValidSecretKey:N,isValidPublicKey:U,toMontgomery(p){let{y}=r.fromBytes(p),v=C.publicKey,w=v===32;if(!w&&v!==57)throw new Error("only defined for 25519 and 448");let b=w?a.div(ae+y,ae-y):a.div(y-ae,y+ae);return a.toBytes(b)},toMontgomerySecret(p){let y=C.secretKey;z(p,y);let v=n(p.subarray(0,y));return d(v).subarray(0,y)}};return Object.freeze(C),Object.freeze(O),Object.freeze({keygen:Hn(I,g),getPublicKey:g,sign:A,verify:D,utils:O,Point:r,lengths:C})}function Lr(r,e){if(Pe(r),Pe(e),e<0||e>4)throw new Error("invalid I2OSP length: "+e);if(r<0||r>2**(8*e)-1)throw new Error("invalid I2OSP input: "+r);let t=Array.from({length:e}).fill(0);for(let n=e-1;n>=0;n--)t[n]=r&255,r>>>=8;return new Uint8Array(t)}function md(r,e){let t=new Uint8Array(r.length);for(let n=0;n<r.length;n++)t[n]=r[n]^e[n];return t}function gd(r){if(!_t(r)&&typeof r!="string")throw new Error("DST must be Uint8Array or ascii string");let e=typeof r=="string"?Mn(r):r;if(e.length===0)throw new Error("DST must be non-empty");return e}function Ws(r,e,t,n){z(r),Pe(t),e=gd(e),e.length>255&&(e=n(re(Mn("H2C-OVERSIZE-DST-"),e)));let{outputLen:o,blockLen:s}=n,i=Math.ceil(t/o);if(t>65535||i>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=re(e,Lr(e.length,1)),c=new Uint8Array(s),u=Lr(t,2),f=new Array(i),l=n(re(c,r,u,Lr(0,1),a));f[0]=n(re(l,Lr(1,1),a));for(let h=1;h<i;h++){let x=[md(l,f[h-1]),Lr(h+1,1),a];f[h]=n(re(...x))}return re(...f).slice(0,t)}var lc="HashToScalar-";var yd=BigInt(0),Xe=BigInt(1),dc=BigInt(2);var bd=BigInt(5),wd=BigInt(8),tr=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Zs={p:tr,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:wd,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function xd(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=tr,a=r*r%s*r%s,c=$(a,dc,s)*a%s,u=$(c,Xe,s)*r%s,f=$(u,bd,s)*u%s,l=$(f,e,s)*f%s,d=$(l,t,s)*l%s,h=$(d,n,s)*d%s,x=$(h,o,s)*h%s,_=$(x,o,s)*h%s,m=$(_,e,s)*f%s;return{pow_p_5_8:$(m,dc,s)*r%s,b2:a}}function Ed(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var $s=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Ys(r,e){let t=tr,n=J(e*e*e,t),o=J(n*n*e,t),s=xd(r*o).pow_p_5_8,i=J(r*n*s,t),a=J(e*i*i,t),c=i,u=J(i*$s,t),f=a===r,l=a===J(-r,t),d=a===J(-r*$s,t);return f&&(i=c),(l||d)&&(i=u),Ye(i,t)&&(i=J(-i,t)),{isValid:f||l,value:i}}var ut=uc(Zs,{uvRatio:Ys}),ct=ut.Fp,mc=ut.Fn;function vd(r){return fc(ut,On,Object.assign({adjustScalarBytes:Ed,zip215:!0},r))}var gc=vd({});var js=$s,Sd=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),_d=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),Ad=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),Id=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),hc=r=>Ys(Xe,r),Td=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Gs=r=>ct.create(He(r)&Td);function pc(r){let{d:e}=Zs,t=tr,n=g=>ct.create(g),o=n(js*r*r),s=n((o+Xe)*Ad),i=BigInt(-1),a=n((i-e*o)*n(o+e)),{isValid:c,value:u}=Ys(s,a),f=n(u*r);Ye(f,t)||(f=n(-f)),c||(u=f),c||(i=o);let l=n(i*(o-Xe)*Id-a),d=u*u,h=n((u+u)*a),x=n(l*Sd),_=n(Xe-d),m=n(Xe+d);return new ut(n(h*m),n(_*x),n(x*m),n(h*_))}var ft=class r extends qn{static BASE=new r(ut.BASE);static ZERO=new r(ut.ZERO);static Fp=ct;static Fn=mc;constructor(e){super(e)}static fromAffine(e){return new r(ut.fromAffine(e))}assertSame(e){if(!(e instanceof r))throw new Error("RistrettoPoint expected")}init(e){return new r(e)}static fromBytes(e){Ee(e,32);let{a:t,d:n}=Zs,o=tr,s=k=>ct.create(k),i=Gs(e);if(!Va(ct.toBytes(i),e)||Ye(i,o))throw new Error("invalid ristretto255 encoding 1");let a=s(i*i),c=s(Xe+t*a),u=s(Xe-t*a),f=s(c*c),l=s(u*u),d=s(t*n*f-l),{isValid:h,value:x}=hc(s(d*l)),_=s(x*u),m=s(x*_*d),g=s((i+i)*_);Ye(g,o)&&(g=s(-g));let E=s(c*m),A=s(g*E);if(!h||Ye(A,o)||E===yd)throw new Error("invalid ristretto255 encoding 2");return new r(new ut(g,E,Xe,A))}static fromHex(e){return r.fromBytes(xr(e))}toBytes(){let{X:e,Y:t,Z:n,T:o}=this.ep,s=tr,i=m=>ct.create(m),a=i(i(n+t)*i(n-t)),c=i(e*t),u=i(c*c),{value:f}=hc(i(a*u)),l=i(f*a),d=i(f*c),h=i(l*d*o),x;if(Ye(o*h,s)){let m=i(t*js),g=i(e*js);e=m,t=g,x=i(l*_d)}else x=d;Ye(e*h,s)&&(t=i(-t));let _=i((n-t)*x);return Ye(_,s)&&(_=i(-_)),ct.toBytes(_)}equals(e){this.assertSame(e);let{X:t,Y:n}=this.ep,{X:o,Y:s}=e.ep,i=u=>ct.create(u),a=i(t*s)===i(n*o),c=i(n*s)===i(t*o);return a||c}is0(){return this.equals(r.ZERO)}};Object.freeze(ft.BASE);Object.freeze(ft.ZERO);Object.freeze(ft.prototype);Object.freeze(ft);var Bd=Object.freeze({Point:ft,hashToCurve(r,e){let t=e?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":e.DST,n=Ws(r,t,64,On);return Bd.deriveToCurve(n)},hashToScalar(r,e={DST:lc}){let t=Ws(r,e.DST,64,On);return mc.create(He(t))},deriveToCurve(r){Ee(r,64);let e=Gs(r.subarray(0,32)),t=pc(e),n=Gs(r.subarray(32,64)),o=pc(n);return new ft(t.add(o))}});var kr=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},Vn=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var Wn={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new Vn("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return e}};var $n=32;var Xs,Dd=(async()=>{try{return await Wn.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function Ld(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await Wn.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await Wn.get().subtle.verify({name:"Ed25519"},n,Te(e),Te(t instanceof Uint8Array?t:t.subarray()))}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function kd(r,e,t){return gc.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function yc(r,e,t){return Xs==null&&(Xs=await Dd),Xs?Ld(r,e,t):kd(r,e,t)}function jn(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Gn=class{type="Ed25519";raw;constructor(e){this.raw=Qs(e,$n)}toMultihash(){return Ie.digest($t(this))}toCID(){return G.createV1(114,this.toMultihash())}toString(){return ee.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Q(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let o=yc(this.raw,t,e);return jn(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function wc(r){return r=Qs(r,$n),new Gn(r)}function Qs(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new Se(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var ge;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(ge||(ge={}));var Js;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(Js||(Js={}));(function(r){r.codec=()=>zt(Js)})(ge||(ge={}));var Cr;(function(r){let e;r.codec=()=>(e==null&&(e=ze((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),ge.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{c.Type=ge.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(f&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{yield{field:`${a}.Type`,value:ge.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(f&7);break}}}})),e);function t(s){return Fe(s,r.codec())}r.encode=t;function n(s,i){return Ue(s,r.codec(),i)}r.decode=n;function o(s,i){return Me(s,r.codec(),i)}r.stream=o})(Cr||(Cr={}));var ei;(function(r){let e;r.codec=()=>(e==null&&(e=ze((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),ge.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{c.Type=ge.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(f&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{yield{field:`${a}.Type`,value:ge.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(f&7);break}}}})),e);function t(s){return Fe(s,r.codec())}r.encode=t;function n(s,i){return Ue(s,r.codec(),i)}r.decode=n;function o(s,i){return Me(s,r.codec(),i)}r.stream=o})(ei||(ei={}));var Zn=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(Dn(e),Ee(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(t.length>n?e.create().update(t).digest():t);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),Ge(o)}update(e){return jt(this),this.iHash.update(e),this}digestInto(e){jt(this),Ln(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},xc=(()=>{let r=((e,t,n)=>new Zn(e,t).update(n).digest());return r.create=(e,t)=>new Zn(e,t),r})();var Ec=(r,e)=>(r+(r>=0?e:-e)/vc)/e;function Od(r,e,t){Yt("scalar",r,qe,t);let[[n,o],[s,i]]=e,a=Ec(i*r,t),c=Ec(-o*r,t),u=r-a*n-c*s,f=-a*o-c*i,l=u<qe,d=f<qe;l&&(u=-u),d&&(f=-f);let h=Tr(Math.ceil(Xt(t)/2))+lt;if(u<qe||u>=h||f<qe||f>=h)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:l,k1:u,k2neg:d,k2:f}}function ri(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function ti(r,e){Oe(r);let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return Ce(t.lowS,"lowS"),Ce(t.prehash,"prehash"),t.format!==void 0&&ri(t.format),t}var ni=class extends Error{constructor(e=""){super(e)}},Re={Err:ni,_tlv:{encode:(r,e)=>{let{Err:t}=Re;if(Pe(r,"tag"),r<0||r>255)throw new t("tlv.encode: wrong tag");if(typeof e!="string")throw new TypeError('"data" expected string, got type='+typeof e);if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,o=Ar(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let s=n>127?Ar(o.length/2|128):"";return Ar(r)+s+o+e},decode(r,e){let{Err:t}=Re;e=z(e,void 0,"DER data");let n=0;if(r<0||r>255)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let o=e[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let u=e.subarray(n,n+c);if(u.length!==c)throw new t("tlv.decode: length bytes not complete");if(u[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let f of u)i=i<<8|f;if(n+=c,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(r){let{Err:e}=Re;if(Un(r),r<qe)throw new e("integer: negative integers are not allowed");let t=Ar(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(r){let{Err:e}=Re;if(r.length<1)throw new e("invalid signature integer: empty");if(r[0]&128)throw new e("invalid signature integer: negative");if(r.length>1&&r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return At(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=Re,o=z(r,void 0,"signature"),{v:s,l:i}=n.decode(48,o);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:u,l:f}=n.decode(2,c);if(f.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(u)}},hexFromSig(r){let{_tlv:e,_int:t}=Re,n=e.encode(2,t.encode(r.r)),o=e.encode(2,t.encode(r.s)),s=n+o;return e.encode(48,s)}};Object.freeze(Re._tlv);Object.freeze(Re._int);Object.freeze(Re);var qe=BigInt(0),lt=BigInt(1),vc=BigInt(2),Yn=BigInt(3),Rd=BigInt(4);function Sc(r,e={}){let t=Kn("weierstrass",r,e),n=t.Fp,o=t.Fn,s=t.CURVE,{h:i,n:a}=s;Oe(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c,allowInfinityPoint:u}=e;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 f=Ac(n,o);function l(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function d(O,p,y){if(u&&p.is0())return Uint8Array.of(0);let{x:v,y:w}=p.toAffine(),b=n.toBytes(v);if(Ce(y,"isCompressed"),y){l();let S=!n.isOdd(w);return re(_c(S),b)}else return re(Uint8Array.of(4),b,n.toBytes(w))}function h(O){z(O,void 0,"Point");let{publicKey:p,publicKeyUncompressed:y}=f,v=O.length,w=O[0],b=O.subarray(1);if(u&&v===1&&w===0)return{x:n.ZERO,y:n.ZERO};if(v===p&&(w===2||w===3)){let S=n.fromBytes(b);if(!n.isValid(S))throw new Error("bad point: is not on curve, wrong x");let B=m(S),T;try{T=n.sqrt(B)}catch(M){let K=M instanceof Error?": "+M.message:"";throw new Error("bad point: is not on curve, sqrt error"+K)}l();let L=n.isOdd(T);return(w&1)===1!==L&&(T=n.neg(T)),{x:S,y:T}}else if(v===y&&w===4){let S=n.BYTES,B=n.fromBytes(b.subarray(0,S)),T=n.fromBytes(b.subarray(S,S*2));if(!g(B,T))throw new Error("bad point: is not on curve");return{x:B,y:T}}else throw new Error(`bad point: got length ${v}, expected compressed=${p} or uncompressed=${y}`)}let x=e.toBytes===void 0?d:e.toBytes,_=e.fromBytes===void 0?h:e.fromBytes;function m(O){let p=n.sqr(O),y=n.mul(p,O);return n.add(n.add(y,n.mul(O,s.a)),s.b)}function g(O,p){let y=n.sqr(p),v=m(O);return n.eql(y,v)}if(!g(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let E=n.mul(n.pow(s.a,Yn),Rd),A=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(E,A)))throw new Error("bad curve params: a or b");function k(O,p,y=!1){if(!n.isValid(p)||y&&n.is0(p))throw new Error(`bad point coordinate ${O}`);return p}function D(O){if(!(O instanceof I))throw new Error("Weierstrass Point expected")}function R(O){if(!c||!c.basises)throw new Error("no endo");return Od(O,c.basises,o.ORDER)}function C(O,p,y,v,w){return y=new I(n.mul(y.X,O),y.Y,y.Z),p=Dr(v,p),y=Dr(w,y),p.add(y)}class I{static BASE=new I(s.Gx,s.Gy,n.ONE);static ZERO=new I(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(p,y,v){this.X=k("x",p),this.Y=k("y",y,!0),this.Z=k("z",v),Object.freeze(this)}static CURVE(){return s}static fromAffine(p){let{x:y,y:v}=p||{};if(!p||!n.isValid(y)||!n.isValid(v))throw new Error("invalid affine point");if(p instanceof I)throw new Error("projective point not allowed");return n.is0(y)&&n.is0(v)?I.ZERO:new I(y,v,n.ONE)}static fromBytes(p){let y=I.fromAffine(_(z(p,void 0,"point")));return y.assertValidity(),y}static fromHex(p){return I.fromBytes(Zt(p))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(p=8,y=!0){return U.createCache(this,p),y||this.multiply(Yn),this}assertValidity(){let p=this;if(p.is0()){if(e.allowInfinityPoint&&n.is0(p.X)&&n.eql(p.Y,n.ONE)&&n.is0(p.Z))return;throw new Error("bad point: ZERO")}let{x:y,y:v}=p.toAffine();if(!n.isValid(y)||!n.isValid(v))throw new Error("bad point: x or y not field elements");if(!g(y,v))throw new Error("bad point: equation left != right");if(!p.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:p}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(p)}equals(p){D(p);let{X:y,Y:v,Z:w}=this,{X:b,Y:S,Z:B}=p,T=n.eql(n.mul(y,B),n.mul(b,w)),L=n.eql(n.mul(v,B),n.mul(S,w));return T&&L}negate(){return new I(this.X,n.neg(this.Y),this.Z)}double(){let{a:p,b:y}=s,v=n.mul(y,Yn),{X:w,Y:b,Z:S}=this,B=n.ZERO,T=n.ZERO,L=n.ZERO,P=n.mul(w,w),M=n.mul(b,b),K=n.mul(S,S),F=n.mul(w,b);return F=n.add(F,F),L=n.mul(w,S),L=n.add(L,L),B=n.mul(p,L),T=n.mul(v,K),T=n.add(B,T),B=n.sub(M,T),T=n.add(M,T),T=n.mul(B,T),B=n.mul(F,B),L=n.mul(v,L),K=n.mul(p,K),F=n.sub(P,K),F=n.mul(p,F),F=n.add(F,L),L=n.add(P,P),P=n.add(L,P),P=n.add(P,K),P=n.mul(P,F),T=n.add(T,P),K=n.mul(b,S),K=n.add(K,K),P=n.mul(K,F),B=n.sub(B,P),L=n.mul(K,M),L=n.add(L,L),L=n.add(L,L),new I(B,T,L)}add(p){D(p);let{X:y,Y:v,Z:w}=this,{X:b,Y:S,Z:B}=p,T=n.ZERO,L=n.ZERO,P=n.ZERO,M=s.a,K=n.mul(s.b,Yn),F=n.mul(y,b),te=n.mul(v,S),ne=n.mul(w,B),oe=n.add(y,v),X=n.add(b,S);oe=n.mul(oe,X),X=n.add(F,te),oe=n.sub(oe,X),X=n.add(y,w);let ye=n.add(b,B);return X=n.mul(X,ye),ye=n.add(F,ne),X=n.sub(X,ye),ye=n.add(v,w),T=n.add(S,B),ye=n.mul(ye,T),T=n.add(te,ne),ye=n.sub(ye,T),P=n.mul(M,X),T=n.mul(K,ne),P=n.add(T,P),T=n.sub(te,P),P=n.add(te,P),L=n.mul(T,P),te=n.add(F,F),te=n.add(te,F),ne=n.mul(M,ne),X=n.mul(K,X),te=n.add(te,ne),ne=n.sub(F,ne),ne=n.mul(M,ne),X=n.add(X,ne),F=n.mul(te,X),L=n.add(L,F),F=n.mul(ye,X),T=n.mul(oe,T),T=n.sub(T,F),F=n.mul(oe,te),P=n.mul(ye,P),P=n.add(P,F),new I(T,L,P)}subtract(p){return D(p),this.add(p.negate())}is0(){return this.equals(I.ZERO)}multiply(p){let{endo:y}=e;if(!o.isValidNot0(p))throw new RangeError("invalid scalar: out of range");let v,w,b=S=>U.cached(this,S,B=>Bt(I,B));if(y){let{k1neg:S,k1:B,k2neg:T,k2:L}=R(p),{p:P,f:M}=b(B),{p:K,f:F}=b(L);w=M.add(F),v=C(y.beta,P,K,S,T)}else{let{p:S,f:B}=b(p);v=S,w=B}return Bt(I,[v,w])[0]}multiplyUnsafe(p){let{endo:y}=e,v=this,w=p;if(!o.isValid(w))throw new RangeError("invalid scalar: out of range");if(w===qe||v.is0())return I.ZERO;if(w===lt)return v;if(U.hasCache(this))return this.multiply(w);if(y){let{k1neg:b,k1:S,k2neg:B,k2:T}=R(w),{p1:L,p2:P}=cc(I,v,S,T);return C(y.beta,L,P,b,B)}else return U.unsafe(v,w)}toAffine(p){let y=this,v=p,{X:w,Y:b,Z:S}=y;if(n.eql(S,n.ONE))return{x:w,y:b};let B=y.is0();v==null&&(v=B?n.ONE:n.inv(S));let T=n.mul(w,v),L=n.mul(b,v),P=n.mul(S,v);if(B)return{x:n.ZERO,y:n.ZERO};if(!n.eql(P,n.ONE))throw new Error("invZ was invalid");return{x:T,y:L}}isTorsionFree(){let{isTorsionFree:p}=e;return i===lt?!0:p?p(I,this):U.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:p}=e;return i===lt?this:p?p(I,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===lt?this.is0():this.clearCofactor().is0()}toBytes(p=!0){return Ce(p,"isCompressed"),this.assertValidity(),x(I,this,p)}toHex(p=!0){return Gt(this.toBytes(p))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let N=o.BITS,U=new er(I,e.endo?Math.ceil(N/2):N);return N>=8&&I.BASE.precompute(8),Object.freeze(I.prototype),Object.freeze(I),I}function _c(r){return Uint8Array.of(r?2:3)}function Ac(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Nd(r,e={}){let{Fn:t}=r,n=e.randomBytes===void 0?_r:e.randomBytes,o=Object.assign(Ac(r.Fp,t),{seed:Math.max(Ms(t.ORDER),16)});function s(h){try{let x=t.fromBytes(h);return t.isValidNot0(x)}catch{return!1}}function i(h,x){let{publicKey:_,publicKeyUncompressed:m}=o;try{let g=h.length;return x===!0&&g!==_||x===!1&&g!==m?!1:!!r.fromBytes(h)}catch{return!1}}function a(h){return h=h===void 0?n(o.seed):h,zs(z(h,o.seed,"seed"),t.ORDER)}function c(h,x=!0){return r.BASE.multiply(t.fromBytes(h)).toBytes(x)}function u(h){let{secretKey:x,publicKey:_,publicKeyUncompressed:m}=o,g=t._lengths;if(!_t(h))return;let E=z(h,void 0,"key").length,A=E===_||E===m,k=E===x||!!g?.includes(E);if(!(A&&k))return A}function f(h,x,_=!0){if(u(h)===!0)throw new Error("first arg must be private key");if(u(x)===!1)throw new Error("second arg must be public key");let m=t.fromBytes(h);return r.fromBytes(x).multiply(m).toBytes(_)}let l={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},d=Hn(a,c);return Object.freeze(l),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:f,keygen:d,Point:r,utils:l,lengths:o})}function Ic(r,e,t={}){let n=e;Dn(n),Oe(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let o=t.randomBytes===void 0?_r:t.randomBytes,s=t.hmac===void 0?(w,b)=>xc(n,w,b):t.hmac,{Fp:i,Fn:a}=r,{ORDER:c,BITS:u}=a,{keygen:f,getPublicKey:l,getSharedSecret:d,utils:h,lengths:x}=Nd(r,t),_={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},m=c*vc+lt<i.ORDER;function g(w){let b=c>>lt;return w>b}function E(w,b){if(!a.isValidNot0(b))throw new Error(`invalid signature ${w}: out of range 1..Point.Fn.ORDER`);return b}function A(){if(m)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function k(w,b){ri(b);let S=x.signature,B=b==="compact"?S:b==="recovered"?S+1:void 0;return z(w,B)}class D{r;s;recovery;constructor(b,S,B){if(this.r=E("r",b),this.s=E("s",S),B!=null){if(A(),![0,1,2,3].includes(B))throw new Error("invalid recovery id");this.recovery=B}Object.freeze(this)}static fromBytes(b,S=_.format){k(b,S);let B;if(S==="der"){let{r:M,s:K}=Re.toSig(z(b));return new D(M,K)}S==="recovered"&&(B=b[0],S="compact",b=b.subarray(1));let T=x.signature/2,L=b.subarray(0,T),P=b.subarray(T,T*2);return new D(a.fromBytes(L),a.fromBytes(P),B)}static fromHex(b,S){return this.fromBytes(Zt(b),S)}assertRecovery(){let{recovery:b}=this;if(b==null)throw new Error("invalid recovery id: must be present");return b}addRecoveryBit(b){return new D(this.r,this.s,b)}recoverPublicKey(b){let{r:S,s:B}=this,T=this.assertRecovery(),L=T===2||T===3?S+c:S;if(!i.isValid(L))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let P=i.toBytes(L),M=r.fromBytes(re(_c((T&1)===0),P)),K=a.inv(L),F=C(z(b,void 0,"msgHash")),te=a.create(-F*K),ne=a.create(B*K),oe=r.BASE.multiplyUnsafe(te).add(M.multiplyUnsafe(ne));if(oe.is0())throw new Error("invalid recovery: point at infinify");return oe.assertValidity(),oe}hasHighS(){return g(this.s)}toBytes(b=_.format){if(ri(b),b==="der")return Zt(Re.hexFromSig(this));let{r:S,s:B}=this,T=a.toBytes(S),L=a.toBytes(B);return b==="recovered"?(A(),re(Uint8Array.of(this.assertRecovery()),T,L)):re(T,L)}toHex(b){return Gt(this.toBytes(b))}}Object.freeze(D.prototype),Object.freeze(D);let R=t.bits2int===void 0?function(b){if(b.length>8192)throw new Error("input is too large");let S=At(b),B=b.length*8-u;return B>0?S>>BigInt(B):S}:t.bits2int,C=t.bits2int_modN===void 0?function(b){return a.create(R(b))}:t.bits2int_modN,I=Tr(u);function N(w){return Yt("num < 2^"+u,w,qe,I),a.toBytes(w)}function U(w,b){return z(w,void 0,"message"),b?z(n(w),void 0,"prehashed message"):w}function O(w,b,S){let{lowS:B,prehash:T,extraEntropy:L}=ti(S,_);w=U(w,T);let P=C(w),M=a.fromBytes(b);if(!a.isValidNot0(M))throw new Error("invalid private key");let K=[N(M),N(P)];if(L!=null&&L!==!1){let oe=L===!0?o(x.secretKey):L;K.push(z(oe,void 0,"extraEntropy"))}let F=re(...K),te=P;function ne(oe){let X=R(oe);if(!a.isValidNot0(X))return;let ye=a.inv(X),Pt=r.BASE.multiply(X).toAffine(),nr=a.create(Pt.x);if(nr===qe)return;let Mr=a.create(ye*a.create(te+nr*M));if(Mr===qe)return;let mi=(Pt.x===nr?0:2)|Number(Pt.y<),gi=Mr;return B&&g(Mr)&&(gi=a.neg(Mr),mi^=1),new D(nr,gi,m?void 0:mi)}return{seed:F,k2sig:ne}}function p(w,b,S={}){let{seed:B,k2sig:T}=O(w,b,S);return Wa(n.outputLen,a.BYTES,s)(B,T).toBytes(S.format)}function y(w,b,S,B={}){let{lowS:T,prehash:L,format:P}=ti(B,_);if(S=z(S,void 0,"publicKey"),b=U(b,L),!_t(w)){let M=w instanceof D?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+M)}k(w,P);try{let M=D.fromBytes(w,P),K=r.fromBytes(S);if(T&&M.hasHighS())return!1;let{r:F,s:te}=M,ne=C(b),oe=a.inv(te),X=a.create(ne*oe),ye=a.create(F*oe),Pt=r.BASE.multiplyUnsafe(X).add(K.multiplyUnsafe(ye));return Pt.is0()?!1:a.create(Pt.x)===F}catch{return!1}}function v(w,b,S={}){let{prehash:B}=ti(S,_);return b=U(b,B),D.fromBytes(w,"recovered").recoverPublicKey(b).toBytes()}return Object.freeze({keygen:f,getPublicKey:l,getSharedSecret:d,utils:h,lengths:x,Point:r,sign:p,verify:y,recoverPublicKey:v,Signature:D,hash:n})}var si={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Ud={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Tc=BigInt(2);function Fd(r){let e=si.p,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=r*r*r%e,f=u*u*r%e,l=$(f,t,e)*f%e,d=$(l,t,e)*f%e,h=$(d,Tc,e)*u%e,x=$(h,o,e)*h%e,_=$(x,s,e)*x%e,m=$(_,a,e)*_%e,g=$(m,c,e)*m%e,E=$(g,a,e)*_%e,A=$(E,t,e)*f%e,k=$(A,i,e)*x%e,D=$(k,n,e)*u%e,R=$(D,Tc,e);if(!oi.eql(oi.sqr(R),r))throw new Error("Cannot find square root");return R}var oi=Qt(si.p,{sqrt:Fd}),Md=Sc(si,{Fp:oi,endo:Ud}),rr=Ic(Md,Ha);function Bc(r,e,t,n){let o=rt.digest(t instanceof Uint8Array?t:t.subarray());if(jn(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),rr.verify(e,s,r,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new kr(String(s))});try{return n?.signal?.throwIfAborted(),rr.verify(e,o.digest,r,{prehash:!1,format:"der"})}catch(s){throw new kr(String(s))}}var Xn=class{type="secp256k1";raw;_key;constructor(e){this._key=Lc(e),this.raw=Dc(this._key)}toMultihash(){return Ie.digest($t(this))}toCID(){return G.createV1(114,this.toMultihash())}toString(){return ee.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Q(this.raw,e.raw)}verify(e,t,n){return Bc(this._key,t,e,n)}};function kc(r){return new Xn(r)}function Dc(r){return rr.Point.fromBytes(r).toBytes()}function Lc(r){try{return rr.Point.fromBytes(r),r}catch(e){throw new zr(String(e))}}function Cc(r){let{Type:e,Data:t}=Cr.decode(r.digest),n=t??new Uint8Array;switch(e){case ge.Ed25519:return wc(n);case ge.secp256k1:return kc(n);case ge.ECDSA:return Aa(n);default:throw new or}}function $t(r){return Cr.encode({Type:ge[r.type],Data:r.raw})}var Pc=Symbol.for("nodejs.util.inspect.custom"),zd=114,Pr=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Wr]=!0;toString(){return this.string==null&&(this.string=ee.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return G.createV1(zd,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return Q(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return Q(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Pc](){return`PeerId(${this.toString()})`}},Qn=class extends Pr{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Jn=class extends Pr{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},eo=class extends Pr{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},Kd=2336,Or=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Ie.digest(W(this.url))}[Pc](){return`PeerId(${this.url})`}[Wr]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return G.createV1(Kd,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=q(e)),e.toString()===this.toString())}};var Hd=114,Oc=2336;function qd(r){if(Wd(r))return new Qn({multihash:r});if(Vd(r))try{let e=Cc(r);if(e.type==="Ed25519")return new Jn({multihash:r,publicKey:e});if(e.type==="secp256k1")return new eo({multihash:r,publicKey:e})}catch{let t=q(r.digest);return new Or(new URL(t))}throw new Hr("Supplied PeerID Multihash is invalid")}function to(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==Hd&&r.code!==Oc)throw new Kr("Supplied PeerID CID is invalid");if(r.code===Oc){let e=q(r.multihash.digest);return new Or(new URL(e))}return qd(r.multihash)}function Vd(r){return r.code===Ie.code}function Wd(r){return r.code===rt.code}function $d(r){return r[Symbol.asyncIterator]!=null}function jd(r){if($d(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Rc=jd;function Gd(r){return r[Symbol.asyncIterator]!=null}function Zd(r,e){let t=0;if(Gd(r))return(async function*(){for await(let c of r)yield e(c,t++)})();let n=wa(r),{value:o,done:s}=n.next();if(s===!0)return(function*(){})();let i=e(o,t++);if(typeof i.then=="function")return(async function*(){yield await i;for(let c of n)yield e(c,t++)})();let a=e;return(function*(){yield i;for(let c of n)yield a(c,t++)})()}var Nc=Zd;function Yd(r){return r[Symbol.asyncIterator]!=null}function Xd(r,e){return Yd(r)?(async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}})():(function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}})()}var Uc=Xd;var ii="/ipfs/bitswap/1.2.0";var j;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(j||(j={}));var ai;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(ai||(ai={}));(function(r){r.codec=()=>zt(ai)})(j||(j={}));var Dt;(function(r){let e;r.codec=()=>(e==null&&(e=ze((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.cid!=null&&s.cid.byteLength>0&&(i.uint32(10),i.bytes(s.cid)),s.priority!=null&&s.priority!==0&&(i.uint32(16),i.int32(s.priority)),s.cancel!=null&&(i.uint32(24),i.bool(s.cancel)),s.wantType!=null&&(i.uint32(32),j.codec().encode(s.wantType,i)),s.sendDontHave!=null&&(i.uint32(40),i.bool(s.sendDontHave)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={cid:ue(0),priority:0},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{c.cid=s.bytes();break}case 2:{c.priority=s.int32();break}case 3:{c.cancel=s.bool();break}case 4:{c.wantType=j.codec().decode(s);break}case 5:{c.sendDontHave=s.bool();break}default:{s.skipType(f&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{yield{field:`${a}.cid`,value:s.bytes()};break}case 2:{yield{field:`${a}.priority`,value:s.int32()};break}case 3:{yield{field:`${a}.cancel`,value:s.bool()};break}case 4:{yield{field:`${a}.wantType`,value:j.codec().decode(s)};break}case 5:{yield{field:`${a}.sendDontHave`,value:s.bool()};break}default:{s.skipType(f&7);break}}}})),e);function t(s){return Fe(s,r.codec())}r.encode=t;function n(s,i){return Ue(s,r.codec(),i)}r.decode=n;function o(s,i){return Me(s,r.codec(),i)}r.stream=o})(Dt||(Dt={}));var Rr;(function(r){let e;r.codec=()=>(e==null&&(e=ze((s,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),s.entries!=null&&s.entries.length>0)for(let c of s.entries)i.uint32(10),Dt.codec().encode(c,i);s.full!=null&&(i.uint32(16),i.bool(s.full)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={entries:[]},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{if(a.limits?.entries!=null&&c.entries.length===a.limits.entries)throw new Ve('Decode error - repeated field "entries" had too many elements');c.entries.push(Dt.codec().decode(s,s.uint32(),{limits:a.limits?.entries$}));break}case 2:{c.full=s.bool();break}default:{s.skipType(f&7);break}}}return c},function*(s,i,a,c={}){let u={entries:0},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let l=s.uint32();switch(l>>>3){case 1:{if(c.limits?.entries!=null&&u.entries===c.limits.entries)throw new Ve('Streaming decode error - repeated field "entries" had too many elements');for(let d of Dt.codec().stream(s,s.uint32(),`${a}.entries[]`,{limits:c.limits?.entries$}))yield{...d,index:u.entries};u.entries++;break}case 2:{yield{field:`${a}.full`,value:s.bool()};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return Fe(s,r.codec())}r.encode=t;function n(s,i){return Ue(s,r.codec(),i)}r.decode=n;function o(s,i){return Me(s,r.codec(),i)}r.stream=o})(Rr||(Rr={}));var Lt;(function(r){let e;r.codec=()=>(e==null&&(e=ze((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.prefix!=null&&s.prefix.byteLength>0&&(i.uint32(10),i.bytes(s.prefix)),s.data!=null&&s.data.byteLength>0&&(i.uint32(18),i.bytes(s.data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={prefix:ue(0),data:ue(0)},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{c.prefix=s.bytes();break}case 2:{c.data=s.bytes();break}default:{s.skipType(f&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{yield{field:`${a}.prefix`,value:s.bytes()};break}case 2:{yield{field:`${a}.data`,value:s.bytes()};break}default:{s.skipType(f&7);break}}}})),e);function t(s){return Fe(s,r.codec())}r.encode=t;function n(s,i){return Ue(s,r.codec(),i)}r.decode=n;function o(s,i){return Me(s,r.codec(),i)}r.stream=o})(Lt||(Lt={}));var ve;(function(r){r.HaveBlock="HaveBlock",r.DoNotHaveBlock="DoNotHaveBlock"})(ve||(ve={}));var ro;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DoNotHaveBlock=1]="DoNotHaveBlock"})(ro||(ro={}));(function(r){r.codec=()=>zt(ro)})(ve||(ve={}));var kt;(function(r){let e;r.codec=()=>(e==null&&(e=ze((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.cid!=null&&s.cid.byteLength>0&&(i.uint32(10),i.bytes(s.cid)),s.type!=null&&ro[s.type]!==0&&(i.uint32(16),ve.codec().encode(s.type,i)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={cid:ue(0),type:ve.HaveBlock},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{c.cid=s.bytes();break}case 2:{c.type=ve.codec().decode(s);break}default:{s.skipType(f&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{yield{field:`${a}.cid`,value:s.bytes()};break}case 2:{yield{field:`${a}.type`,value:ve.codec().decode(s)};break}default:{s.skipType(f&7);break}}}})),e);function t(s){return Fe(s,r.codec())}r.encode=t;function n(s,i){return Ue(s,r.codec(),i)}r.decode=n;function o(s,i){return Me(s,r.codec(),i)}r.stream=o})(kt||(kt={}));var Ct;(function(r){let e;r.codec=()=>(e==null&&(e=ze((s,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),s.wantlist!=null&&(i.uint32(10),Rr.codec().encode(s.wantlist,i)),s.blocks!=null&&s.blocks.length>0)for(let c of s.blocks)i.uint32(26),Lt.codec().encode(c,i);if(s.blockPresences!=null&&s.blockPresences.length>0)for(let c of s.blockPresences)i.uint32(34),kt.codec().encode(c,i);s.pendingBytes!=null&&s.pendingBytes!==0&&(i.uint32(40),i.int32(s.pendingBytes)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={blocks:[],blockPresences:[],pendingBytes:0},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{c.wantlist=Rr.codec().decode(s,s.uint32(),{limits:a.limits?.wantlist});break}case 3:{if(a.limits?.blocks!=null&&c.blocks.length===a.limits.blocks)throw new Ve('Decode error - repeated field "blocks" had too many elements');c.blocks.push(Lt.codec().decode(s,s.uint32(),{limits:a.limits?.blocks$}));break}case 4:{if(a.limits?.blockPresences!=null&&c.blockPresences.length===a.limits.blockPresences)throw new Ve('Decode error - repeated field "blockPresences" had too many elements');c.blockPresences.push(kt.codec().decode(s,s.uint32(),{limits:a.limits?.blockPresences$}));break}case 5:{c.pendingBytes=s.int32();break}default:{s.skipType(f&7);break}}}return c},function*(s,i,a,c={}){let u={blocks:0,blockPresences:0},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let l=s.uint32();switch(l>>>3){case 1:{yield*Rr.codec().stream(s,s.uint32(),`${a}.wantlist`,{limits:c.limits?.wantlist});break}case 3:{if(c.limits?.blocks!=null&&u.blocks===c.limits.blocks)throw new Ve('Streaming decode error - repeated field "blocks" had too many elements');for(let d of Lt.codec().stream(s,s.uint32(),`${a}.blocks[]`,{limits:c.limits?.blocks$}))yield{...d,index:u.blocks};u.blocks++;break}case 4:{if(c.limits?.blockPresences!=null&&u.blockPresences===c.limits.blockPresences)throw new Ve('Streaming decode error - repeated field "blockPresences" had too many elements');for(let d of kt.codec().stream(s,s.uint32(),`${a}.blockPresences[]`,{limits:c.limits?.blockPresences$}))yield{...d,index:u.blockPresences};u.blockPresences++;break}case 5:{yield{field:`${a}.pendingBytes`,value:s.int32()};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return Fe(s,r.codec())}r.encode=t;function n(s,i){return Ue(s,r.codec(),i)}r.decode=n;function o(s,i){return Me(s,r.codec(),i)}r.stream=o})(Ct||(Ct={}));function Fc(r,e){for(let[t,n]of e.wantlist.entries()){let o=r.wantlist.get(t);o!=null&&(o.priority>n.priority&&(n.priority=o.priority),n.cancel=n.cancel??o.cancel,n.wantType=n.wantType??o.wantType,n.sendDontHave=n.sendDontHave??o.sendDontHave),r.wantlist.set(t,n)}for(let[t,n]of e.blockPresences.entries())r.blockPresences.set(t,n);for(let[t,n]of e.blocks.entries())r.blocks.set(t,n);return e.full&&!r.full&&(r.full=!0),r}var no=class extends Error{static name="BlockTooLargeError";constructor(e="Block too large"){super(e),this.name="BlockTooLargeError"}};var Qd=4193648,Jd=Qd+16;function*Mc(r,e){let t=[...r.wantlist.values()],n=[...r.blockPresences.values()],o=[...r.blocks.values()],s=0,i=0,a=0,c=!1;for(;;){let u={wantlist:{full:r.full??!1,entries:[]},blockPresences:[],blocks:[],pendingBytes:0},f=Ct.encode(u).byteLength,{added:l,hasMore:d,newSize:h}=ci(o,u.blocks,a,e,f,eh);a+=l,f=h;let x=d;({added:l,hasMore:d,newSize:h}=ci(n,u.blockPresences,i,e,f,th)),i+=l,f=h;let _=d;if({added:l,hasMore:d,newSize:h}=ci(t,u.wantlist.entries,s,e,f,rh),s+=l,f=h,c=!x&&!_&&!d,c||(u.wantlist.full=!1),yield Ct.encode(u),c)break}}function ci(r,e,t,n,o,s){let i=0,a=!1;for(let c=t;c<r.length;c++){let u=r[c],f=s(u);if(f>Jd)throw new no("Cannot send block as after encoding it is over the max message size");let l=o+f;if(l>n){a=!0;break}e.push(u),i++,o=l}return{hasMore:a,added:i,newSize:o}}function eh(r){return ui(3,Lt.encode(r))}function th(r){return ui(4,kt.encode(r))}function rh(r){return ui(1,Dt.encode(r))}function ui(r,e){let t=V(r),n=V(e.byteLength);return t+n+e.byteLength}function dh(r){if($r(r))return r;if(Tn(r))return to(r);if(ln(r)||Array.isArray(r))return r;throw new Se(`Peer ${r} was not a CID, a Multiaddr or a Multiaddr[]`)}var oo=class extends Ne{log;libp2p;routing;protocols;running;maxInboundStreams;maxOutboundStreams;messageReceiveTimeout;messageSendTimeout;registrarIds;metrics;sendQueue;runOnLimitedConnections;maxOutgoingMessageSize;maxIncomingMessageSize;constructor(e,t={}){super(),this.log=e.logger.forComponent("helia:bitswap:network"),this.libp2p=e.libp2p,this.routing=e.routing,this.protocols=t.protocols??[ii],this.registrarIds=[],this.running=!1,this._onStream=this._onStream.bind(this),this.maxInboundStreams=t.maxInboundStreams??1024,this.maxOutboundStreams=t.maxOutboundStreams??1024,this.messageReceiveTimeout=t.messageReceiveTimeout??1e4,this.messageSendTimeout=t.messageSendTimeout??1e4,this.runOnLimitedConnections=t.runOnLimitedConnections??!1,this.maxIncomingMessageSize=t.maxIncomingMessageSize??4194304,this.maxOutgoingMessageSize=t.maxOutgoingMessageSize??t.maxIncomingMessageSize??4194304,this.metrics={blocksSent:e.metrics?.registerCounter("helia_bitswap_sent_blocks_total"),dataSent:e.metrics?.registerCounter("helia_bitswap_sent_data_bytes_total")},this.sendQueue=new An({concurrency:t.messageSendConcurrency??50,metrics:e.metrics,metricName:"helia_bitswap_message_send_queue"})}async start(){if(this.running)return;this.running=!0,await this.libp2p.handle(this.protocols,this._onStream,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnections});let e={onConnect:t=>{this.safeDispatchEvent("peer:connected",{detail:t})},onDisconnect:t=>{this.safeDispatchEvent("peer:disconnected",{detail:t})}};this.registrarIds=[];for(let t of this.protocols)this.registrarIds.push(await this.libp2p.register(t,e));this.libp2p.getConnections().forEach(t=>{this.safeDispatchEvent("peer:connected",{detail:t.remotePeer})})}async stop(){if(this.running=!1,await this.libp2p.unhandle(this.protocols),this.registrarIds!=null){for(let e of this.registrarIds)this.libp2p.unregister(e);this.registrarIds=[]}}_onStream(e,t){this.running&&Promise.resolve().then(async()=>{this.log("incoming new bitswap %s stream from %p",e.protocol,t.remotePeer);let n=()=>{e.status==="open"?e.abort(new qr(`Incoming Bitswap stream timed out after ${this.messageReceiveTimeout}ms`)):this.log("stream aborted with status %s",e.status)},o=AbortSignal.timeout(this.messageReceiveTimeout);o.addEventListener("abort",n),await e.close({signal:o});let s=hn();e.addEventListener("message",i=>{s.push(i.data)}),e.addEventListener("remoteCloseWrite",()=>{s.end()}),e.addEventListener("close",i=>{i.error!=null&&s.end(i.error)});for await(let i of yr(s,{maxDataLength:this.maxIncomingMessageSize}))try{let a=Ct.decode(i);this.log("incoming new bitswap %s message from %p on stream",e.protocol,t.remotePeer,e.id),this.safeDispatchEvent("bitswap:message",{detail:{peer:t.remotePeer,message:a,connection:t}}),o.removeEventListener("abort",n),o=AbortSignal.timeout(this.messageReceiveTimeout),o.addEventListener("abort",n)}catch(a){this.log.error("error reading incoming bitswap message from %p on stream - %e",t.remotePeer,e.id,a),e.abort(a);break}}).catch(n=>{this.log.error("error handling incoming stream from %p - %e",t.remotePeer,n),e.abort(n)})}async*findProviders(e,t){t?.onProgress?.(new ce("bitswap:find-providers",e));for await(let n of this.routing.findProviders(e,t)){if(!await this.libp2p.isDialable(n.multiaddrs,{runOnLimitedConnection:this.runOnLimitedConnections})){this.log("skipping peer %p as they are not dialable - %a",n.id,n.multiaddrs);continue}t?.onProgress?.(new ce("bitswap:found-provider",{type:"bitswap",cid:e,provider:n,router:n.router})),yield n}}async findAndConnect(e,t){t?.providers!=null&&await Promise.all(t.providers.map(async n=>this.connectTo(n,t).catch(o=>{this.log.error("could not connect to supplied provider - %e",o)}))),await Rc(Nc(Uc(this.findProviders(e,t),t?.maxProviders??3),async n=>this.connectTo(n.id,t))).catch(n=>{this.log.error(n)})}async sendMessage(e,t,n){if(!this.running)throw new Error("network isn't running");let o=this.sendQueue.queue.find(s=>e.equals(s.options.peerId)&&s.status==="queued");if(o!=null){o.options.message=Fc(o.options.message,t),await o.join(n);return}await this.sendQueue.add(async s=>{let i=s.message;if(i==null)throw new Se("No message to send");this.log("sendMessage to %p",e),s.onProgress?.(new ce("bitswap:send-wantlist",e));let a=await this.libp2p.dialProtocol(e,ii,s);await a.closeRead(s);try{for(let c of Mc(i,this.maxOutgoingMessageSize))a.send(_n.single(c))||await a.onDrain(s);await a.close(s)}catch(c){this.log.error("error sending message to %p - %e",e,c),s?.onProgress?.(new ce("bitswap:send-wantlist:error",{peer:e,error:c})),a.abort(c)}this._updateSentStats(i.blocks)},{onProgress:n?.onProgress,peerId:e,signal:n?.signal??AbortSignal.timeout(this.messageSendTimeout),message:t})}async connectTo(e,t){if(!this.running)throw new Vr("Network isn't running");return e=dh(e),t?.onProgress?.(new ce("bitswap:dial",e)),this.libp2p.dial(e,t)}_updateSentStats(e){let t=0;for(let n of e.values())t+=n.data.byteLength;this.metrics.dataSent?.increment(t),this.metrics.blocksSent?.increment(e.size)}};function so(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}var Nr=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),{key:t,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return so(this.map.entries(),e=>[e[1].key,e[1].value])}forEach(e){this.map.forEach((t,n)=>{e(t.value,t.key,this)})}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),{key:e,value:t})}keys(){return so(this.map.values(),e=>e.key)}values(){return so(this.map.values(),e=>e.value)}get size(){return this.map.size}};var fi=class extends Nr{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Ur(r){let{name:e,metrics:t}=r,n;return t!=null?n=new fi({name:e,metrics:t}):n=new Nr,n}var Qe=class{full;pendingBytes;wantlist;blocks;blockPresences;constructor(e=!1,t=0){this.full=e,this.wantlist=new Map,this.blocks=new Map,this.blockPresences=new Map,this.pendingBytes=0}addWantlistEntry(e,t){let n=pt.encode(e.multihash.bytes);this.wantlist.set(n,t)}addBlockPresence(e,t){let n=pt.encode(e.multihash.bytes);this.blockPresences.set(n,t)}addBlock(e,t){let n=pt.encode(e.multihash.bytes);this.blocks.set(n,t)}};function hh(r){let e=new Uint8Array(r.reduce((n,o)=>n+V(o),0)),t=0;for(let n of r)e=Yr(n,e,t),t+=V(n);return e}var zc=hh;function li(r){return zc([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var io=class{peerId;blockstore;network;wants;exchangeCount;bytesSent;bytesReceived;lastExchange;maxSizeReplaceHasWithBlock;log;doNotResendBlockWindow;maxWantListSize;constructor(e,t){this.peerId=e.peerId,this.blockstore=e.blockstore,this.network=e.network,this.wants=new Map,this.log=e.logger.forComponent(`helia:bitswap:ledger:${e.peerId}`),this.exchangeCount=0,this.bytesSent=0,this.bytesReceived=0,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock??1024,this.doNotResendBlockWindow=t.doNotResendBlockWindow??5e3,this.maxWantListSize=t.maxWantListSize??1024}sentBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesSent+=e}receivedBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesReceived+=e}debtRatio(){return this.bytesSent/(this.bytesReceived+1)}removeExpiredWants(){this.wants.forEach((e,t)=>{e.expires!=null&&e.expires<Date.now()&&this.wants.delete(t)})}addWants(e){if(e==null)return;e.full===!0&&this.wants.forEach((n,o)=>{n.status==="want"&&this.wants.delete(o)});for(let n of e.entries){let o=G.decode(n.cid),s=q(o.multihash.bytes,"base64");if(n.cancel===!0)this.log("peer %p cancelled want of block for %c",this.peerId,o),this.wants.delete(s);else{n.wantType===j.WantHave?this.log("peer %p wanted block presence for %c",this.peerId,o):this.log("peer %p wanted block for %c",this.peerId,o);let i=this.wants.get(s);if(i!=null){let a=i.status==="sent"||i.status==="sending",c=i.wantType===j.WantHave&&(n.wantType==null||n.wantType===j.WantBlock);a&&c&&(i.status="want"),i.priority=n.priority,i.wantType=n.wantType??j.WantBlock,i.sendDontHave=n.sendDontHave??!1;continue}this.wants.set(s,{cid:o,priority:n.priority,wantType:n.wantType??j.WantBlock,sendDontHave:n.sendDontHave??!1,status:"want",created:Date.now()})}}let t=[...this.wants.entries()].filter(([n,o])=>o.status==="want");t.length>this.maxWantListSize&&this.truncateWants(t)}truncateWants(e){e=e.sort((n,o)=>n[1].created<o[1].created?-1:o[1].created<n[1].created?1:0).sort((n,o)=>n[1].haveBlock===!1?-1:o[1].haveBlock===!1?1:0).sort((n,o)=>n[1].priority<o[1].priority?-1:o[1].priority<n[1].priority?1:0);let t=e.length-this.maxWantListSize;for(let n=0;n<t;n++)this.wants.delete(e[n][0])}getWants(){return[...this.wants.values()]}hasWant(e){let t=q(e.multihash.bytes,"base64");return this.wants.has(t)}async sendBlocksToPeer(e){let t=new Qe,n=new Set;this.removeExpiredWants();let o=[...this.wants.entries()].filter(([s,i])=>i.status==="want");o.forEach(([s,i])=>{i.status="sending"});for(let[s,i]of o)try{let a=await xa(this.blockstore.get(i.cid,e));if(i.status!=="sending")continue;i.wantType===j.WantHave?a.byteLength<this.maxSizeReplaceHasWithBlock?(this.log("sending have and block for %c",i.cid),n.add(s),t.addBlock(i.cid,{data:a,prefix:li(i.cid)})):(this.log("sending have for %c",i.cid),t.addBlockPresence(i.cid,{cid:i.cid.bytes,type:ve.HaveBlock})):(this.log("sending block for %c",i.cid),n.add(s),t.addBlock(i.cid,{data:a,prefix:li(i.cid)})),i.status="sent",i.expires=Date.now()+this.doNotResendBlockWindow}catch(a){if(a.name!=="NotFoundError")throw a;if(i.status="want",i.haveBlock=!1,this.log("do not have block for %c",i.cid),!i.sendDontHave||i.sentDoNotHave===!0)continue;i.sentDoNotHave=!0,t.addBlockPresence(i.cid,{cid:i.cid.bytes,type:ve.DoNotHaveBlock})}(t.blocks.size>0||t.blockPresences.size>0)&&(this.log("sending message"),await this.network.sendMessage(this.peerId,t,e),this.log("sent message"),this.sentBytes([...t.blocks.values()].reduce((s,i)=>s+i.data.byteLength,0)))}};var ao=class{blockstore;network;ledgerMap;maxSizeReplaceHasWithBlock;doNotResendBlockWindow;maxWantListSize;log;logger;constructor(e,t={}){this.blockstore=e.blockstore,this.network=e.network,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock,this.doNotResendBlockWindow=t.doNotResendBlockWindow,this.maxWantListSize=t.maxWantListSize,this.log=e.logger.forComponent("helia:bitswap:peer-want-lists"),this.logger=e.logger,this.ledgerMap=Ur({name:"helia_bitswap_ledger_map",metrics:e.metrics}),this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.connection.remotePeer,n.detail.message).catch(o=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.connection.remotePeer,o)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}ledgerForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return{peer:t.peerId,value:t.debtRatio(),sent:t.bytesSent,received:t.bytesReceived,exchanged:t.exchangeCount}}wantListForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return t.removeExpiredWants(),t.getWants()}peers(){return Array.from(this.ledgerMap.values()).map(e=>e.peerId)}async receiveMessage(e,t){let n=this.ledgerMap.get(e);n==null&&(n=new io({peerId:e,blockstore:this.blockstore,network:this.network,logger:this.logger},{maxSizeReplaceHasWithBlock:this.maxSizeReplaceHasWithBlock,doNotResendBlockWindow:this.doNotResendBlockWindow,maxWantListSize:this.maxWantListSize}),this.ledgerMap.set(e,n)),n.receivedBytes(t.blocks?.reduce((o,s)=>o+s.data.byteLength,0)??0),n.removeExpiredWants(),n.addWants(t.wantlist),this.log("send blocks to peer"),await n.sendBlocksToPeer()}async receivedBlock(e,t){let n=[];for(let o of this.ledgerMap.values())o.hasWant(e)&&n.push(o);await Promise.all(n.map(async o=>o.sendBlocksToPeer(t)))}peerDisconnected(e){this.ledgerMap.delete(e)}};var di=class extends In{name="bitswap-session";wantList;network;libp2p;constructor(e,t){super(e,{...t,name:"helia:bitswap:session"}),this.wantList=e.wantList,this.network=e.network,this.libp2p=e.libp2p}async queryProvider(e,t,n){let o=to(t.peerId);this.log("sending WANT-BLOCK for %c to %p",e,o);let s=await this.wantList.wantSessionBlock(e,o,n);if(this.log("%p %s %c",t,s.has?"has":"does not have",e),s.has){if(s.block!=null)return s.block;throw new Error("Provider has block but did not send it to us")}throw new Error("Provider did not have block")}async*findNewProviders(e,t={}){for await(let n of this.network.findProviders(e,t))yield{peerId:n.id,router:n.router,toString:()=>`Bitswap(${n.id})`}}toFilterKey(e){return e.peerId.multihash.bytes}equals(e,t){return e.peerId.equals(t.peerId)}async convertToProvider(e,t,n){if(Tn(e))return{peerId:e,router:t,toString:()=>`Bitswap(${e})`};if(await this.libp2p.isDialable(e)!==!1)try{let o=await this.libp2p.dial(e,n);return{peerId:o.remotePeer.toCID(),router:t,toString:()=>`Bitswap(${o.remotePeer})`}}catch{}}emitFoundProviderProgressEvent(e,t,n){n?.onProgress?.(new ce("bitswap:found-provider",{type:"bitswap",cid:e,provider:{id:t.peerId,multiaddrs:[],router:t.router},router:t.router}))}};function Kc(r,e){return new di(r,e)}var co=class{blocksReceived;duplicateBlocksReceived;dataReceived;duplicateDataReceived;constructor(e){this.blocksReceived=e.metrics?.registerMetricGroup("helia_bitswap_received_blocks"),this.duplicateBlocksReceived=e.metrics?.registerMetricGroup("helia_bitswap_duplicate_received_blocks"),this.dataReceived=e.metrics?.registerMetricGroup("helia_bitswap_data_received_bytes"),this.duplicateDataReceived=e.metrics?.registerMetricGroup("helia_bitswap_duplicate_data_received_bytes")}updateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.blocksReceived?.increment(n)}updateDuplicateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateBlocksReceived?.increment(n)}updateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.dataReceived?.increment(n)}updateDuplicateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateDataReceived?.increment(n)}};var uo=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function Fr(r,e,t,n){let o=new uo(n?.errorMessage);n?.errorCode!=null&&(o.code=n.errorCode);let s=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(o):new Promise((i,a)=>{function c(){pi(t,"abort",l),pi(r,e,u),pi(r,s,f)}let u=d=>{try{if(n?.filter?.(d)===!1)return}catch(h){c(),a(h);return}c(),i(d)},f=d=>{if(c(),d instanceof Error){a(d);return}a(d.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},l=()=>{c(),a(o)};hi(t,"abort",l),hi(r,e,u),hi(r,s,f)})}function hi(r,e,t){r!=null&&(Hc(r)?r.addEventListener(e,t):r.addListener(e,t))}function pi(r,e,t){r!=null&&(Hc(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function Hc(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}function ph(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let e=[];for(;r.length>0;){let t=mt(r);e.push(t),r=r.slice(V(t))}return e}var qc=ph;var fo=class extends Ne{peers;wants;network;log;sendWantlistDebounce;sendMessagesTimeout;getHasher;sendingMessages;constructor(e,t={}){super(),this.peers=Ur({name:"helia_bitswap_peers",metrics:e.metrics}),this.wants=ya({name:"helia_bitswap_wantlist",metrics:e.metrics}),this.network=e.network,this.sendWantlistDebounce=t.sendWantlistDebounce??10,this.log=e.logger.forComponent("helia:bitswap:wantlist"),this.getHasher=e.getHasher,this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.connection,n.detail.message).catch(o=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.connection.remotePeer,o)})}),this.network.addEventListener("peer:connected",n=>{this.peerConnected(n.detail).catch(o=>{this.log.error("error processing newly connected bitswap peer %p - %e",n.detail,o)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}async addEntry(e,t){let n=q(e.multihash.bytes,"base64"),o=this.wants.get(n);o==null&&(o={cid:e,priority:t.priority??1,wantType:t.wantType??j.WantBlock,cancel:!1,sendDontHave:!0,onProgress:[]},this.wants.set(n,o)),t.onProgress!=null&&o.onProgress.push({onProgress:t.onProgress,signal:t.signal}),o.wantType===j.WantHave&&t.wantType===j.WantBlock&&(o.wantType=j.WantBlock),await this.sendMessagesDebounced();try{return t.wantType===j.WantBlock?(await Fr(this,"block",t?.signal,{filter:a=>Q(e.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await Fr(this,"presence",t?.signal,{filter:i=>Q(e.multihash.digest,i.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail}finally{t.signal?.aborted===!0&&(this.log("want for %c was aborted, cancelling want",e),o.cancel=!0,await this.sendMessagesDebounced())}}async sendMessagesDebounced(){await this.sendingMessages?.promise,clearTimeout(this.sendMessagesTimeout),this.sendMessagesTimeout=setTimeout(()=>{this.sendMessages().catch(e=>{this.log("error sending messages to peers - %e",e)})},this.sendWantlistDebounce)}async sendMessages(){this.sendingMessages=Le(),await Promise.all([...this.peers.entries()].map(async([e,t])=>{let n=new Set,o=new Qe;for(let[s,i]of this.wants.entries())t.has(s)||i.cancel||(n.add(s),o.addWantlistEntry(i.cid,{cid:i.cid.bytes,priority:i.priority,wantType:i.wantType,cancel:i.cancel,sendDontHave:i.sendDontHave}));if(o.wantlist.size!==0)try{await this.network.sendMessage(e,o,{onProgress:s=>{this.wants.forEach(({onProgress:i})=>{i.forEach(({onProgress:a})=>{a(s)})})}});for(let s of n)t.add(s)}catch(s){this.log.error("error sending full wantlist to new peer - %e",s)}})).catch(e=>{this.log.error("error sending messages - %e",e)});for(let[e,t]of this.wants)if(t.cancel){this.wants.delete(e);for(let n of this.peers.values())n.delete(e)}this.sendingMessages.resolve()}has(e){let t=q(e.multihash.bytes,"base64");return this.wants.has(t)}async wantSessionPresence(e,t,n={}){let o=new Qe;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:j.WantHave,priority:1}),await this.network.sendMessage(t,o,n),(await Fr(this,"presence",n.signal,{filter:i=>t.equals(i.detail.sender)&&Q(e.multihash.digest,i.detail.cid.multihash.digest)})).detail}async wantBlock(e,t={}){return this.addEntry(e,{...t,wantType:j.WantBlock})}async wantSessionBlock(e,t,n={}){let o=new Qe;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:j.WantBlock,priority:1}),await this.network.sendMessage(t,o,n),(await Fr(this,"presence",n.signal,{filter:i=>t.equals(i.detail.sender)&&Q(e.multihash.digest,i.detail.cid.multihash.digest)})).detail}async receivedBlock(e,t){let n=q(e.multihash.bytes,"base64"),o=this.wants.get(n);o!=null&&(o.cancel=!0,await this.sendMessagesDebounced())}async receiveMessage(e,t){this.log("received message from %p with %d blocks",e.remotePeer,t.blocks.length);let n=!1;for(let o of t.blocks){if(o.prefix==null||o.data==null)continue;let s=qc(o.prefix),i=s[0],a=s[1],c=s[2],u=s[3],f=c===rt.code?rt:await this.getHasher(c);if(f==null){this.log.error("unknown hash algorithm",c);continue}let l=f.digest(o.data,{truncate:u});l.then!=null&&(l=await l);let d=G.create(i===0?0:1,a,l);this.log("received block from %p for %c",e.remotePeer,d),this.safeDispatchEvent("block",{detail:{sender:e.remotePeer,cid:d,block:o.data,connection:e}}),this.safeDispatchEvent("presence",{detail:{sender:e.remotePeer,cid:d,has:!0,block:o.data}});let h=q(d.multihash.bytes,"base64"),x=this.wants.get(h);x!=null&&(x.cancel=!0,n=!0)}for(let{cid:o,type:s}of t.blockPresences){let i=G.decode(o);this.log("received %s from %p for %c",s,e.remotePeer,i),this.safeDispatchEvent("presence",{detail:{sender:e.remotePeer,cid:i,has:s===ve.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(e){let t=new Set,n=new Qe(!0);for(let[o,s]of this.wants.entries())s.cancel||(t.add(o),n.addWantlistEntry(s.cid,{cid:s.cid.bytes,priority:1,wantType:j.WantBlock,cancel:!1,sendDontHave:!1}));if(n.wantlist.size===0){this.peers.set(e,t);return}try{await this.network.sendMessage(e,n,{onProgress:o=>{this.wants.forEach(({onProgress:s})=>{s.forEach(({onProgress:i})=>{i(o)})})}}),this.peers.set(e,t)}catch(o){this.log.error("error sending full wantlist to new peer %p - %e",e,o)}}peerDisconnected(e){this.peers.delete(e)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}};var lo=class{log;logger;stats;network;blockstore;peerWantLists;wantList;libp2p;constructor(e,t={}){this.logger=e.logger,this.log=e.logger.forComponent("helia:bitswap"),this.blockstore=e.blockstore,this.libp2p=e.libp2p,this.stats=new co(e),this.network=new oo(e,t),this.peerWantLists=new ao({...e,network:this.network},t),this.wantList=new fo({...e,network:this.network},t)}createSession(e={}){return Kc({wantList:this.wantList,network:this.network,logger:this.logger,libp2p:this.libp2p},e)}async want(e,t={}){let n=new AbortController,o=bi([n.signal,t.signal]);n.signal,this.network.findAndConnect(e,{...t,signal:o}).catch(s=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c - %e",e,s)});try{let s=await this.wantList.wantBlock(e,{...t,signal:o});return t.onProgress?.(new ce("bitswap:block",{cid:e,sender:s.connection.remotePeer})),s.block}finally{n.abort(),o.clear()}}async notify(e,t={}){await Promise.all([this.peerWantLists.receivedBlock(e,t),this.wantList.receivedBlock(e,t)])}getWantlist(){return[...this.wantList.wants.values()].filter(e=>!e.cancel).map(e=>({cid:e.cid,priority:e.priority,wantType:e.wantType}))}getPeerWantlist(e){return this.peerWantLists.wantListForPeer(e)}async start(){this.wantList.start(),await this.network.start()}async stop(){this.wantList.stop(),await this.network.stop()}};var ho=class{name="bitswap";bitswap;started;constructor(e,t={}){this.bitswap=new lo(e,t),this.started=!1}isStarted(){return this.started}async start(){await this.bitswap.start(),this.started=!0}async stop(){await this.bitswap.stop(),this.started=!1}async announce(e,t){await this.bitswap.notify(e,t)}async retrieve(e,t={}){return this.bitswap.want(e,{...t,onProgress:function(o){if(t?.onProgress!=null)if(t.onProgress(o),o.type==="connection:open"){if(!$r(o.detail))return;t.onProgress(new ce("helia:block-broker:connect",{broker:"bitswap",type:"connect",provider:o.detail.toCID(),cid:e}))}else o.type==="connection:opened"?t.onProgress(new ce("helia:block-broker:connected",{broker:"bitswap",type:"connected",provider:o.detail.remotePeer.toCID(),address:o.detail.remoteAddr,cid:e})):o.type==="bitswap:send-wantlist"?t.onProgress(new ce("helia:block-broker:request-block",{broker:"bitswap",type:"request-block",provider:o.detail.toCID(),cid:e})):o.type==="bitswap:block"&&t.onProgress(new ce("helia:block-broker:receive-block",{broker:"bitswap",type:"receive-block",provider:o.detail.sender.toCID(),cid:e}))}})}createSession(e){let t=this.bitswap.createSession(e);return{name:"bitswap-session",addPeer:async(n,o)=>{await t.addPeer(n,o)},announce:async(n,o)=>{await this.bitswap.notify(n,o)},retrieve:async(n,o)=>t.retrieve(n,o)}}};function mh(r,e={}){let t={name:"bitswap",start:async n=>{if(n.status==="starting"&&!n.hasBlockBroker("bitswap")){let o=new ho(n,e);await yi(o),n.addBlockBroker(o)}}};return r.addMixin(t),r}return Gc(gh);})();
|
|
2
|
+
"use strict";var HeliaBitswap=(()=>{var mo=Object.defineProperty;var Wc=Object.getOwnPropertyDescriptor;var $c=Object.getOwnPropertyNames;var jc=Object.prototype.hasOwnProperty;var ye=(r,e)=>{for(var t in e)mo(r,t,{get:e[t],enumerable:!0})},Gc=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of $c(e))!jc.call(r,o)&&o!==t&&mo(r,o,{get:()=>e[o],enumerable:!(n=Wc(e,o))||n.enumerable});return r};var Zc=r=>Gc(mo({},"__esModule",{value:!0}),r);var bh={};ye(bh,{withBitswap:()=>gh});var Ae=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var Se=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},zr=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var Kr=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Hr=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var qr=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},Vr=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}};var or=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var Wr=Symbol.for("@libp2p/peer-id");function $r(r){return!!r?.[Wr]}function Yc(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function yi(...r){let e=[];for(let t of r)Yc(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStart!=null&&await t.beforeStart()})),await Promise.all(e.map(async t=>{await t.start()})),await Promise.all(e.map(async t=>{t.afterStart!=null&&await t.afterStart()}))}function Xc(r){return typeof r?.handleEvent=="function"}function Qc(r){return(r!==!0&&r!==!1&&r?.once)??!1}var Ne=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){let o=Qc(n);super.addEventListener(e,i=>{if(o){let a=this.#e.get(i.type);a!=null&&(a=a.filter(({callback:c})=>c!==t),this.#e.set(i.type,a))}Xc(t)?t.handleEvent(i):t(i)},n);let s=this.#e.get(e);s==null&&(s=[],this.#e.set(e,s)),s.push({callback:t,once:o})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==t),this.#e.set(e,o))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var ce=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};function wi(r){let e=new globalThis.AbortController;function t(){let s=r.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();e.abort(s);for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}for(let s of r){if(s?.aborted===!0){t();break}s?.addEventListener!=null&&s.addEventListener("abort",t)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}var Ah=new Uint8Array(0);function Ei(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function _e(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return dt(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return dt(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function vi(r){let e=new Uint8Array(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}var xi=4096;function Si(r){let e=r.length;if(e<=xi)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.subarray(n,n+=xi));return t}function Jc(r){return r?.buffer instanceof ArrayBuffer}function dt(r){return Jc(r)?r:r.slice()}var xo={};ye(xo,{base32:()=>et,base32hex:()=>uf,base32hexpad:()=>df,base32hexpadupper:()=>hf,base32hexupper:()=>lf,base32pad:()=>cf,base32padupper:()=>ff,base32upper:()=>af,base32z:()=>pf});function ef(r,e,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),o=0;o<n.length;o++)n[o]=255;for(var s=0;s<r.length;s++){var i=r.charAt(s),a=i.charCodeAt(0);if(n[a]!==255)throw new TypeError(i+" is ambiguous");if(n[a]=s,t){var c=i.toLowerCase().charCodeAt(0),f=i.toUpperCase().charCodeAt(0);c!==a&&(n[c]=s),f!==a&&(n[f]=s)}}var u=r.length,l=r.charAt(0),d=Math.log(u)/Math.log(256),h=Math.log(256)/Math.log(u);function x(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var E=0,A=0,L=0,k=g.length;L!==k&&g[L]===0;)L++,E++;for(var R=(k-L)*h+1>>>0,C=new Uint8Array(R);L!==k;){for(var I=g[L],N=0,U=R-1;(I!==0||N<A)&&U!==-1;U--,N++)I+=256*C[U]>>>0,C[U]=I%u>>>0,I=I/u>>>0;if(I!==0)throw new Error("Non-zero carry");A=N,L++}for(var O=R-A;O!==R&&C[O]===0;)O++;for(var p=l.repeat(E);O<R;++O)p+=r.charAt(C[O]);return p}function _(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var E=0;if(g[E]!==" "){for(var A=0,L=0;g[E]===l;)A++,E++;for(var k=(g.length-E)*d+1>>>0,R=new Uint8Array(k);g[E];){var C=n[g.charCodeAt(E)];if(C===255)return;for(var I=0,N=k-1;(C!==0||I<L)&&N!==-1;N--,I++)C+=u*R[N]>>>0,R[N]=C%256>>>0,C=C/256>>>0;if(C!==0)throw new Error("Non-zero carry");L=I,E++}if(g[E]!==" "){for(var U=k-L;U!==k&&R[U]===0;)U++;for(var O=new Uint8Array(A+(k-U)),p=A;U!==k;)O[p++]=R[U++];return O}}}function m(g){var E=_(g);if(E)return E;throw new Error(`Non-${e} character`)}return{encode:x,decodeUnsafe:_,decode:m}}var tf=ef,rf=tf,Ai=rf;var go=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},bo=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Ii(this,e)}},yo=class{decoders;constructor(e){this.decoders=e}or(e){return Ii(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Ii(r,e){return new yo({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var wo=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new go(e,t,n),this.decoder=new bo(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Ot({name:r,prefix:e,encode:t,decode:n}){return new wo(r,e,t,n)}function Je({name:r,prefix:e,alphabet:t,caseInsensitive:n=!1}){let{encode:o,decode:s}=Ai(t,r,n);return Ot({prefix:e,name:r,encode:o,decode:i=>_e(s(i))})}function nf(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let f=0;f<o;++f){let u=e[r[f]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function of(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function sf(r,e){let t={};for(let n=0;n<r.length;++n)if(t[r[n]]=n,e){let o=r[n].toLowerCase(),s=r[n].toUpperCase();o!==r[n]&&(t[o]=n),s!==r[n]&&(t[s]=n)}return t}function Z({name:r,prefix:e,bitsPerChar:t,alphabet:n,caseInsensitive:o=!1}){let s=sf(n,o);return Ot({prefix:e,name:r,encode(i){return of(i,n,t)},decode(i){return nf(i,s,t,r)}})}var et=Z({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5,caseInsensitive:!0}),af=Z({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5,caseInsensitive:!0}),cf=Z({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5,caseInsensitive:!0}),ff=Z({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5,caseInsensitive:!0}),uf=Z({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5,caseInsensitive:!0}),lf=Z({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5,caseInsensitive:!0}),df=Z({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5,caseInsensitive:!0}),hf=Z({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5,caseInsensitive:!0}),pf=Z({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Eo={};ye(Eo,{base36:()=>sr,base36upper:()=>mf});var sr=Je({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz",caseInsensitive:!0}),mf=Je({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",caseInsensitive:!0});var vo={};ye(vo,{base58btc:()=>ee,base58flickr:()=>gf});var ee=Je({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),gf=Je({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var bf=ki,Ti=128,yf=127,wf=~yf,xf=Math.pow(2,31);function ki(r,e,t){e=e||[],t=t||0;for(var n=t;r>=xf;)e[t++]=r&255|Ti,r/=128;for(;r&wf;)e[t++]=r&255|Ti,r>>>=7;return e[t]=r|0,ki.bytes=t-n+1,e}var Ef=So,vf=128,Bi=127;function So(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw So.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&Bi)<<o:(i&Bi)*Math.pow(2,o),o+=7}while(i>=vf);return So.bytes=s-n,t}var Sf=Math.pow(2,7),_f=Math.pow(2,14),Af=Math.pow(2,21),If=Math.pow(2,28),Tf=Math.pow(2,35),Bf=Math.pow(2,42),kf=Math.pow(2,49),Df=Math.pow(2,56),Lf=Math.pow(2,63),Cf=function(r){return r<Sf?1:r<_f?2:r<Af?3:r<If?4:r<Tf?5:r<Bf?6:r<kf?7:r<Df?8:r<Lf?9:10},Pf={encode:bf,decode:Ef,encodingLength:Cf},Of=Pf,ir=Of;function ar(r,e=0){let t=ir.decode(r,e),n=ir.decode.bytes;if(n>9)throw new RangeError("Invalid varint: too long");if(n>1&&r[e+n-1]===0)throw new RangeError("Invalid varint: not minimally encoded");return[t,n]}function Rt(r,e,t=0){return ir.encode(r,e,t),e}function Nt(r){return ir.encodingLength(r)}function Ft(r,e){let t=e.byteLength,n=Nt(r),o=n+Nt(t),s=new Uint8Array(o+t);return Rt(r,s,0),Rt(t,s,n),s.set(e,o),new Ut(r,t,e,s)}function Gr(r){let e=_e(r),[t,n]=ar(e),[o,s]=ar(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Ut(t,o,i,e)}function Di(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Ei(r.bytes,t.bytes)}}var Ut=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=dt(n),this.bytes=dt(o)}};function Li(r,e){let{bytes:t,version:n}=r;return n===0?Nf(t,_o(r),e??ee.encoder):Uf(t,_o(r),e??et.encoder)}var Ci=new WeakMap;function _o(r){let e=Ci.get(r);if(e==null){let t=new Map;return Ci.set(r,t),t}return e}var G=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=dt(o),this["/"]=this.bytes}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==cr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Ff)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=Ft(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&Di(e.multihash,n.multihash)}toString(e){return Li(this,e)}toJSON(){return{"/":Li(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??Pi(n,o,s.bytes))}else if(t[Mf]===!0){let{version:n,multihash:o,code:s}=t,i=Gr(o);return r.create(n,s,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==cr)throw new Error(`Version 0 CID must use dag-pb (code: ${cr}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=Pi(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,cr,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=_e(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new Ut(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[l,d]=ar(e.subarray(t));return t+=d,l},o=n(),s=cr;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),f=t+c,u=f-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:f}}static parse(e,t){let[n,o]=Rf(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return _o(s).set(n,e),s}};function Rf(r,e){switch(r[0]){case"Q":{let t=e??ee;return[ee.prefix,t.decode(`${ee.prefix}${r}`)]}case ee.prefix:{let t=e??ee;return[ee.prefix,t.decode(r)]}case et.prefix:{let t=e??et;return[et.prefix,t.decode(r)]}case sr.prefix:{let t=e??sr;return[sr.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function Nf(r,e,t){let{prefix:n}=t;if(n!==ee.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function Uf(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var cr=112,Ff=18;function Pi(r,e,t){let n=Nt(r),o=n+Nt(e),s=new Uint8Array(o+t.byteLength);return Rt(r,s,0),Rt(e,s,n),s.set(t,o),s}var Mf=Symbol.for("@ipld/js-cid/CID");var zf=20;function Io({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new Ao(r,e,t,n,o)}var Ao=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??zf,this.maxDigestLength=s}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?Oi(n,this.code,t?.truncate):n.then(o=>Oi(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Oi(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return Ft(e,r)}var Bo={};ye(Bo,{base64:()=>pt,base64pad:()=>Kf,base64url:()=>To,base64urlpad:()=>Hf});var pt=Z({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Kf=Z({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),To=Z({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Hf=Z({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ko={};ye(ko,{identity:()=>Ie});var Ni=0,qf="identity",Ui=_e;function Vf(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return Ft(Ni,Ui(r))}var Ie={code:Ni,name:qf,encode:Ui,digest:Vf};function fe(r=0){return new Uint8Array(r)}function se(r=0){return new Uint8Array(r)}function Wf(r){return r?.buffer instanceof ArrayBuffer}function Do(r){if(Wf(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function we(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=se(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return Do(t)}function Q(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}var Mi=Symbol.for("@achingbrain/uint8arraylist");function Fi(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function Zr(r){return!!r?.[Mi]}var ue=class r{bufs;length;[Mi]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(Zr(n)){t+=n.byteLength;for(let o of n.bufs)this.bufs.push(o)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(Zr(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=Fi(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Fi(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(Zr(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:o}=this._subList(e,t);return we(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:we(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=n,s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],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,e>=c)continue;let f=e>=a&&e<c,u=t>a&&t<=c;if(f&&u){if(e===a&&t===c){n.push(i);break}let l=e-a;n.push(i.subarray(l,l+(t-e)));break}if(f){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(u){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!Zr(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let 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 l=0;l<s;l++)i[l]=-1;for(let l=0;l<o;l++)i[n[l]]=l;let a=i,c=this.byteLength-n.byteLength,f=n.byteLength-1,u;for(let l=t;l<=c;l+=u){u=0;for(let d=f;d>=0;d--){let h=this.get(l+d);if(n[d]!==h){u=Math.max(1,d-a[h]);break}}if(u===0)return l}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=se(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=fe(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=fe(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=fe(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=se(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=fe(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=fe(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=fe(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=fe(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=fe(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!Q(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,s)=>o+s.byteLength,0)),n.length=t,n}};function $f(r){return r.buffer instanceof ArrayBuffer}function Te(r){return $f(r)?r:r.slice()}var jf=Math.pow(2,7),Gf=Math.pow(2,14),Zf=Math.pow(2,21),Lo=Math.pow(2,28),Co=Math.pow(2,35),Po=Math.pow(2,42),Oo=Math.pow(2,49),H=128,pe=127;function V(r){if(r<jf)return 1;if(r<Gf)return 2;if(r<Zf)return 3;if(r<Lo)return 4;if(r<Co)return 5;if(r<Po)return 6;if(r<Oo)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Mt(r,e,t=0){switch(V(r)){case 8:e[t++]=r&255|H,r/=128;case 7:e[t++]=r&255|H,r/=128;case 6:e[t++]=r&255|H,r/=128;case 5:e[t++]=r&255|H,r/=128;case 4:e[t++]=r&255|H,r>>>=7;case 3:e[t++]=r&255|H,r>>>=7;case 2:e[t++]=r&255|H,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function Yf(r,e,t=0){switch(V(r)){case 8:e.set(t++,r&255|H),r/=128;case 7:e.set(t++,r&255|H),r/=128;case 6:e.set(t++,r&255|H),r/=128;case 5:e.set(t++,r&255|H),r/=128;case 4:e.set(t++,r&255|H),r>>>=7;case 3:e.set(t++,r&255|H),r>>>=7;case 2:e.set(t++,r&255|H),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function Ro(r,e){let t=r[e],n=0;if(n+=t&pe,t<H||(t=r[e+1],n+=(t&pe)<<7,t<H)||(t=r[e+2],n+=(t&pe)<<14,t<H)||(t=r[e+3],n+=(t&pe)<<21,t<H)||(t=r[e+4],n+=(t&pe)*Lo,t<H)||(t=r[e+5],n+=(t&pe)*Co,t<H)||(t=r[e+6],n+=(t&pe)*Po,t<H)||(t=r[e+7],n+=(t&pe)*Oo,t<H))return n;throw new RangeError("Could not decode varint")}function Xf(r,e){let t=r.get(e),n=0;if(n+=t&pe,t<H||(t=r.get(e+1),n+=(t&pe)<<7,t<H)||(t=r.get(e+2),n+=(t&pe)<<14,t<H)||(t=r.get(e+3),n+=(t&pe)<<21,t<H)||(t=r.get(e+4),n+=(t&pe)*Lo,t<H)||(t=r.get(e+5),n+=(t&pe)*Co,t<H)||(t=r.get(e+6),n+=(t&pe)*Po,t<H)||(t=r.get(e+7),n+=(t&pe)*Oo,t<H))return n;throw new RangeError("Could not decode varint")}function Yr(r,e,t=0){return e==null&&(e=se(V(r))),e instanceof Uint8Array?Mt(r,e,t):Yf(r,e,t)}function mt(r,e=0){return r instanceof Uint8Array?Ro(r,e):Xf(r,e)}var Uo=new Float32Array([-0]),tt=new Uint8Array(Uo.buffer);function zi(r,e,t){Uo[0]=r,e[t]=tt[0],e[t+1]=tt[1],e[t+2]=tt[2],e[t+3]=tt[3]}function Ki(r,e){return tt[0]=r[e],tt[1]=r[e+1],tt[2]=r[e+2],tt[3]=r[e+3],Uo[0]}var Fo=new Float64Array([-0]),me=new Uint8Array(Fo.buffer);function Hi(r,e,t){Fo[0]=r,e[t]=me[0],e[t+1]=me[1],e[t+2]=me[2],e[t+3]=me[3],e[t+4]=me[4],e[t+5]=me[5],e[t+6]=me[6],e[t+7]=me[7]}function qi(r,e){return me[0]=r[e],me[1]=r[e+1],me[2]=r[e+2],me[3]=r[e+3],me[4]=r[e+4],me[5]=r[e+5],me[6]=r[e+6],me[7]=r[e+7],Fo[0]}var Qf=BigInt(Number.MAX_SAFE_INTEGER),Jf=BigInt(Number.MIN_SAFE_INTEGER),xe=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return gt;if(e<Qf&&e>Jf)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>Vi&&(o=0n,++n>Vi&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return gt;let t=e<0;t&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):gt}},gt=new xe(0,0);gt.toBigInt=function(){return 0n};gt.zzEncode=gt.zzDecode=function(){return this};gt.length=function(){return 1};var Vi=4294967296n;function Wi(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function $i(r,e,t){if(t-e<1)return"";let o,s=[],i=0,a;for(;e<t;)a=r[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&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 Mo(r,e,t){let n=t,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function Be(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Xr(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var zo=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=Te(e),this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,Be(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Be(this,4);return Xr(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Be(this,4);return Xr(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Be(this,4);let e=Ki(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Be(this,4);let e=qi(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw Be(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return $i(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Be(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Be(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new xe(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw Be(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw Be(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Be(this,8);let e=Xr(this.buf,this.pos+=4),t=Xr(this.buf,this.pos+=4);return new xe(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=Ro(this.buf,this.pos);return this.pos+=V(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function fr(r){return new zo(r instanceof Uint8Array?r:r.subarray())}function Ue(r,e,t){let n=fr(r);return e.decode(n,void 0,t)}var Ko={};ye(Ko,{base10:()=>eu});var eu=Je({prefix:"9",name:"base10",alphabet:"0123456789"});var Ho={};ye(Ho,{base16:()=>tu,base16upper:()=>ru});var tu=Z({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4,caseInsensitive:!0}),ru=Z({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4,caseInsensitive:!0});var qo={};ye(qo,{base2:()=>nu});var nu=Z({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Vo={};ye(Vo,{base256emoji:()=>cu});var Gi=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}"),ou=Gi.reduce((r,e,t)=>(r[t]=e,r),[]),su=Gi.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function iu(r){return r.reduce((e,t)=>(e+=ou[t],e),"")}function au(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=su[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var cu=Ot({prefix:"\u{1F680}",name:"base256emoji",encode:iu,decode:au});var Wo={};ye(Wo,{base8:()=>fu});var fu=Z({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var $o={};ye($o,{identity:()=>uu});var uu=Ot({prefix:"\0",name:"identity",encode:r=>Si(_e(r)),decode:r=>_e(vi(r))});var Ip=new TextEncoder,Tp=new TextDecoder;var jo={};ye(jo,{sha256:()=>rt,sha512:()=>hu});function Zi(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var rt=Io({name:"sha2-256",code:18,encode:Zi("SHA-256")}),hu=Io({name:"sha2-512",code:19,encode:Zi("SHA-512")});var ur={...$o,...qo,...Wo,...Ko,...Ho,...xo,...Eo,...vo,...Bo,...Vo},Lp={...jo,...ko};function Xi(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Yi=Xi("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Go=Xi("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=se(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),pu={utf8:Yi,"utf-8":Yi,hex:ur.base16,latin1:Go,ascii:Go,binary:Go,...ur},Qr=pu;function W(r,e="utf8"){let t=Qr[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function Zo(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return se(i);o+i>e&&(n=se(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var bt=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function Yo(){}var Qo=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},mu=Zo();function gu(r){return globalThis.Buffer!=null?se(r):mu(r)}var dr=class{len;head;tail;states;constructor(){this.len=0,this.head=new bt(Yo,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new bt(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Jo((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(Jr,10,xe.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=xe.fromBigInt(e);return this._push(Jr,t.length(),t)}uint64Number(e){return this._push(Mt,V(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=xe.fromBigInt(e).zzEncode();return this._push(Jr,t.length(),t)}sint64Number(e){let t=xe.fromNumber(e).zzEncode();return this._push(Jr,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Xo,1,e?1:0)}fixed32(e){return this._push(lr,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=xe.fromBigInt(e);return this._push(lr,4,t.lo)._push(lr,4,t.hi)}fixed64Number(e){let t=xe.fromNumber(e);return this._push(lr,4,t.lo)._push(lr,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(zi,4,e)}double(e){return this._push(Hi,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(Xo,1,0):this.uint32(t)._push(yu,t,e)}string(e){let t=Wi(e);return t!==0?this.uint32(t)._push(Mo,t,e):this._push(Xo,1,0)}fork(){return this.states=new Qo(this),this.head=this.tail=new bt(Yo,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 bt(Yo,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=gu(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function Xo(r,e,t){e[t]=r&255}function bu(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var Jo=class extends bt{next;constructor(e,t){super(bu,e,t),this.next=void 0}};function Jr(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function lr(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function yu(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(dr.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(wu,e,r),this},dr.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(xu,e,r),this});function wu(r,e,t){e.set(r,t)}function xu(r,e,t){r.length<40?Mo(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(W(r),t)}function es(){return new dr}function Fe(r,e){let t=es();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}function*Me(r,e,t){let n=fr(r);yield*e.stream(n,void 0,"$",t)}var en={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function tn(r,e,t,n,o){return{name:r,type:e,encode:t,decode:n,stream:o}}function zt(r){function e(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let t=function(i,a){let c=e(i);a.int32(c)},n=function(i){let a=i.int32();return e(a)},o=function*(i){let a=i.int32();yield e(a)};return tn("enum",en.VARINT,t,n,o)}function ze(r,e,t){return tn("message",en.LENGTH_DELIMITED,r,e,t)}var Ve=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var rn=class extends Error{static name="InsufficientProvidersError";constructor(e="Insufficient providers found"){super(e),this.name="InsufficientProvidersError"}};var nn=class extends Error{static name="NoEvictionError";name="NoEvictionError"};var ts={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Qi={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Ji=new globalThis.TextEncoder;function Eu(r,e){let t=ts[e],n=Qi[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function vu(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=ts[e],o=Qi[e],s=r;for(;s.length>0;){let i=Ji.encodeInto(s,t);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(t[a]),o=BigInt.asUintN(e,o*n)}return o}function rs(r,{size:e=32,utf8Buffer:t}={}){if(!ts[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(t)return vu(r,e,t);r=Ji.encode(r)}return Eu(r,e)}var hr={hash:r=>Number(rs(r,{size:32})),hashV:(r,e)=>Su(hr.hash(r,e))};function Su(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),W(e,"base16")}var ns=64,ke=class{fp;h;seed;constructor(e,t,n,o=2){if(o>ns)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),i=fe(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?Q(this.fp,e.fp):!1}};function yt(r,e){return Math.floor(Math.random()*(e-r))+r}var wt=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof ke))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof ke))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(this.contents[t]==null)return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof ke))throw new TypeError("Invalid Fingerprint");let t=yt(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof ke))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var _u=500,pr=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??hr,this.seed=e.seed??yt(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=W(e));let t=new ke(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new wt(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new wt(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let s=[n,o],i=s[yt(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new wt(this.bucketSize));for(let a=0;a<_u;a++){let c=this.buckets[i].swap(t);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new wt(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=W(e));let t=new ke(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let s=(n^t.hash())%this.filterSize;return this.buckets[s]?.has(t)??!1}remove(e){typeof e=="string"&&(e=W(e));let t=new ke(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let s=(n^t.hash())%this.filterSize,i=this.buckets[s]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},Au={1:.5,2:.84,4:.95,8:.98};function Iu(r=.001){return r>.002?2:r>1e-5?4:8}function ea(r,e=.001){let t=Iu(e),n=Au[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),ns);return{filterSize:o,bucketSize:t,fingerprintSize:s}}var on=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??hr,this.seed=e.seed??yt(0,Math.pow(2,10)),this.filterSeries=[new pr({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=W(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new pr({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=W(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=W(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function sn(r,e=.001,t){return new on({...ea(r,e),...t??{}})}var an=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",f=2**(8*o)-1;for(;;){let u=this.readAtomically(()=>{let l=this.readChar();if(l===void 0)return;let d=Number.parseInt(l,e);if(!Number.isNaN(d))return d});if(u===void 0)break;if(s*=e,s+=u,s>f||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[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];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Tu=45,Bu=15,cn=new an;function ta(r){if(!(r.length>Bu))return cn.new(r).parseWith(()=>cn.readIPv4Addr())}function ra(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Tu))return cn.new(r).parseWith(()=>cn.readIPv6Addr())}function fn(r){return!!ta(r)}function na(r){return!!ra(r)}function q(r,e="utf8"){let t=Qr[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var le=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},We=class extends Error{static name="ValidationError";name="ValidationError"},un=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},ln=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function ss(r){return e=>q(e,r)}function is(r){return e=>W(e,r)}function Kt(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function xt(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function oa(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=W(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=xt(n);return we([t,o],t.length+o.length)}function sa(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=et.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=xt(n);return we([t,o],t.length+o.length)}function as(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=q(e,"base32"),o=Kt(t);return`${n}:${o}`}var cs=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let o=parseInt(t,10);if(isNaN(o)||o<0||o>255)throw new le("Invalid byte value in IP address");e[n]=o}),e},ia=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=fn(t[n]),i;s&&(i=cs(t[n]),t[n]=q(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,q(i.subarray(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let s=parseInt(t[n],16);if(isNaN(s)||s<0||s>65535)throw new le("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},aa=function(r){if(r.byteLength!==4)throw new le("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},ca=function(r){if(r.byteLength!==16)throw new le("IPv6 address was incorrect length");let e=[];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")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new le(`Invalid IPv6 address "${t}"`)}};function fa(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new le(`Invalid IPv6 address "${r}"`)}}var os=Object.values(ur).map(r=>r.decoder),ku=(function(){let r=os[0].or(os[1]);return os.slice(2).forEach(e=>r=r.or(e)),r})();function ua(r){return ku.decode(r)}function la(r){return e=>r.encoder.encode(e)}function Du(r){if(parseInt(r).toString()!==r)throw new We("Value must be an integer")}function Lu(r){if(r<0)throw new We("Value must be a positive integer, or zero")}function Cu(r){return e=>{if(e>r)throw new We(`Value must be smaller than or equal to ${r}`)}}function Pu(...r){return e=>{for(let t of r)t(e)}}var mr=Pu(Du,Lu,Cu(65535));var ie=-1,fs=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(typeof e=="string"?t=this.protocolsByName.get(e):t=this.protocolsByCode.get(e),t==null)throw new ln(`Protocol ${e} was unknown`);return t}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(t=>{this.protocolsByName.set(t,e)})}removeProtocol(e){let t=this.protocolsByCode.get(e);t!=null&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},$e=new fs,xl=[{code:4,name:"ip4",size:32,valueToBytes:cs,bytesToValue:aa,validate:r=>{if(!fn(r))throw new We(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:xt,bytesToValue:Kt,validate:mr},{code:273,name:"udp",size:16,valueToBytes:xt,bytesToValue:Kt,validate:mr},{code:33,name:"dccp",size:16,valueToBytes:xt,bytesToValue:Kt,validate:mr},{code:41,name:"ip6",size:128,valueToBytes:ia,bytesToValue:ca,stringToValue:fa,validate:r=>{if(!na(r))throw new We(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:ie},{code:43,name:"ipcidr",size:8,bytesToValue:ss("base10"),valueToBytes:is("base10")},{code:53,name:"dns",size:ie},{code:54,name:"dns4",size:ie},{code:55,name:"dns6",size:ie},{code:56,name:"dnsaddr",size:ie},{code:132,name:"sctp",size:16,valueToBytes:xt,bytesToValue:Kt,validate:mr},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:ie,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:ie,bytesToValue:ss("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?is("base58btc")(r):G.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:as,valueToBytes:oa},{code:445,name:"onion3",size:296,bytesToValue:as,valueToBytes:sa},{code:446,name:"garlic64",size:ie},{code:447,name:"garlic32",size:ie},{code:448,name:"tls"},{code:449,name:"sni",size:ie},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:ie,bytesToValue:la(To),valueToBytes:ua},{code:480,name:"http"},{code:481,name:"http-path",size:ie,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:ie}];xl.forEach(r=>{$e.addProtocol(r)});function da(r){let e=[],t=0;for(;t<r.length;){let n=mt(r,t),o=$e.getProtocol(n),s=V(n),i=El(o,r,t+s),a=0;i>0&&o.size===ie&&(a=V(i));let c=s+a+i,f={code:n,name:o.name,bytes:Te(r.subarray(t,t+c))};if(i>0){let u=t+s+a,l=r.subarray(u,u+i);f.value=o.bytesToValue?.(l)??q(l)}e.push(f),t+=c}return e}function ha(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=$e.getProtocol(n.code),s=V(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??W(n.value),a=i.byteLength,o.size===ie&&(c=V(a)));let f=new Uint8Array(s+c+a),u=0;Mt(n.code,f,u),u+=s,i!=null&&(o.size===ie&&(Mt(a,f,u),u+=c),f.set(i,u)),n.bytes=f}t.push(n.bytes),e+=n.bytes.byteLength}return we(t,e)}function pa(r){if(r.charAt(0)!=="/")throw new le('String multiaddr must start with "/"');let e=[],t="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(t==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=$e.getProtocol(o);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",t="protocol";continue}else if(a)throw new le(`Component ${o} was missing value`);t="value"}else if(t==="value"){let f={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new le(`Component ${o} was missing value`);f.value=c.stringToValue?.(n)??n}e.push(f),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new le("Incomplete multiaddr");return e}function ma(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=$e.getProtocol(e.code);if(t==null)throw new le(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function El(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:mt(e,t)}var vl=Symbol.for("nodejs.util.inspect.custom"),ls=Symbol.for("@multiformats/multiaddr");function Sl(r){if(r==null&&(r="/"),dn(r))return r.getComponents();if(r instanceof Uint8Array)return da(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),pa(r);if(Array.isArray(r))return r;throw new le("Must be a string, Uint8Array, Component[], or another Multiaddr")}var us=class r{[ls]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=Sl(e),t.validate!==!1&&_l(this)}get bytes(){return this.#r==null&&(this.#r=ha(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=ma(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new un(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,o),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}equals(e){return Q(this.bytes,e.bytes)}[vl](){return`Multiaddr(${this.toString()})`}};function _l(r){r.getComponents().forEach(e=>{let t=$e.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function dn(r){return!!r?.[ls]}function De(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var hn=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},Ht=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new hn(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new hn(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var ds=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function pn(r={}){return Al(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function Al(r,e){e=e??{};let t=e.onEnd,n=new Ht,o,s,i,a=De(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((m,g)=>{s=E=>{s=null,n.push(E);try{m(r(n))}catch(A){g(A)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=De()})}},f=m=>s!=null?s(m):(n.push(m),o),u=m=>(n=new Ht,s!=null?s({error:m}):(n.push({error:m}),o)),l=m=>{if(i)return o;if(e?.objectMode!==!0&&m?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return f({done:!1,value:m})},d=m=>i?o:(i=!0,m!=null?u(m):f({done:!0})),h=()=>(n=new Ht,d(),{done:!0}),x=m=>(d(m),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:x,push:l,end:d,get readableLength(){return n.size},onEmpty:async m=>{let g=m?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let E,A;g!=null&&(E=new Promise((L,k)=>{A=()=>{k(new ds)},g.addEventListener("abort",A)}));try{await Promise.race([a.promise,E])}finally{A!=null&&g!=null&&g?.removeEventListener("abort",A)}}},t==null)return o;let _=o;return o={[Symbol.asyncIterator](){return this},next(){return _.next()},throw(m){return _.throw(m),t!=null&&(t(m),t=void 0),{done:!0}},return(){return _.return(),t!=null&&(t(),t=void 0),{done:!0}},push:l,end(m){return _.end(m),t!=null&&(t(m),t=void 0),o},get readableLength(){return _.readableLength},onEmpty:m=>_.onEmpty(m)},o}var hs=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},ga=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function ps(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e,a,c,u=new Promise((l,d)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(i?.aborted){d(ga(i));return}if(i&&(c=()=>{d(ga(i))},i.addEventListener("abort",c,{once:!0})),r.then(l,d),t===Number.POSITIVE_INFINITY)return;let h=new hs;a=s.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(x){d(x)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?l():o instanceof Error?d(o):(h.message=o??`Promise timed out after ${t} milliseconds`,d(h))},t)}).finally(()=>{u.clear(),c&&i&&i.removeEventListener("abort",c)});return u.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},u}var Il=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function Tl(r,e,t){let n,o=new Promise((s,i)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:f,removeListener:u}=Il(r),l=async(...h)=>{let x=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(x))return}catch(_){n(),i(_);return}c.push(x),t.count===c.length&&(n(),s(c))},d=(...h)=>{n(),i(t.rejectionMultiArgs?h:h[0])};n=()=>{for(let h of a)u(h,l);for(let h of t.rejectionEvents)a.includes(h)||u(h,d)};for(let h of a)f(h,l);for(let h of t.rejectionEvents)a.includes(h)||f(h,d);t.signal&&t.signal.addEventListener("abort",()=>{d(t.signal.reason)},{once:!0}),t.resolveImmediately&&s(c)});if(o.cancel=n,typeof t.timeout=="number"){let s=ps(o,{milliseconds:t.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function mn(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=Tl(r,e,t),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function ms(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var gn=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};function Bl(r){return r.reason}async function bn(r,e,t){if(e==null)return r;let n=t?.translateError??Bl;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let o;try{return await Promise.race([r,new Promise((s,i)=>{o=()=>{i(n(e))},e.addEventListener("abort",o)})])}finally{o!=null&&e.removeEventListener("abort",o)}}var yn=class{deferred;signal;onProgress;constructor(e){this.signal=e?.signal,this.onProgress=e?.onProgress,this.deferred=De(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Ae)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function kl(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var wn=class{id;fn;options;recipients;status;timeline;controller;dispatchingProgress;constructor(e,t){this.id=kl(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.dispatchingProgress=!1,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Ae),this.cleanup())}async join(e){let t=new yn(e);return this.recipients.push(t),e?.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await bn(this.fn({...this.options??{},signal:this.controller.signal,onProgress:t=>{if(!this.dispatchingProgress){this.dispatchingProgress=!0;try{this.recipients.forEach(n=>{n.onProgress?.(t)})}finally{this.dispatchingProgress=!1}}}}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var qt=class extends Ne{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=ms(this.emitEmpty.bind(this),1),this.emitIdle=ms(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new gn;let n=new wn(e,t);this.enqueue(n),this.safeDispatchEvent("add");let o=n.join(t).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s});return this.tryToStartAnother(),o}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Ae)}),this.clear()}async onEmpty(e){this.size!==0&&await mn(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await mn(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await mn(this,"idle",e)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=pn({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new Ae("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var xn=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Vt=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},En=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},gr=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function vn(r){return r[Symbol.asyncIterator]!=null}function ba(r,e){if(r.byteLength>e)throw new Vt("Message length too long")}var _n=r=>{let e=V(r),t=se(e);return Yr(r,t),_n.bytes=e,t};_n.bytes=0;function An(r,e){e=e??{};let t=e.lengthEncoder??_n,n=e?.maxDataLength??4194304;function*o(s){ba(s,n);let i=t(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return vn(r)?(async function*(){for await(let s of r)yield*o(s)})():(function*(){for(let s of r)yield*o(s)})()}An.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??_n,n=e?.maxDataLength??4194304;return ba(r,n),new ue(t(r.byteLength),r)};var Et;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Et||(Et={}));var gs=r=>{let e=mt(r);return gs.bytes=V(e),e};gs.bytes=0;function br(r,e){let t=new ue,n=Et.LENGTH,o=-1,s=e?.lengthDecoder??gs,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===Et.LENGTH)try{if(o=s(t),o<0)throw new xn("Invalid message length");if(o>a)throw new Vt("Message length too long");let f=s.bytes;t.consume(f),e?.onLength!=null&&e.onLength(o),n=Et.DATA}catch(f){if(f instanceof RangeError){if(t.byteLength>i)throw new En("Message length length too long");break}throw f}if(n===Et.DATA){if(t.byteLength<o)break;let f=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(f),yield f,n=Et.LENGTH}}}return vn(r)?(async function*(){for await(let f of r)t.append(f),yield*c();if(t.byteLength>0)throw new gr("Unexpected end of input")})():(function*(){for(let f of r)t.append(f),yield*c();if(t.byteLength>0)throw new gr("Unexpected end of input")})()}br.fromReader=(r,e)=>{let t=1,n=(async function*(){for(;;)try{let{done:s,value:i}=await r.next(t);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{t=1}})();return br(n,{...e??{},onLength:s=>{t=s}})};var In=class extends qt{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var bs=class extends Map{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function ya(r){let{name:e,metrics:t}=r,n;return t!=null?n=new bs({name:e,metrics:t}):n=new Map,n}var Tn=class extends Ne{initialPeerSearchComplete;requests;logName;log;logger;minProviders;maxProviders;providers;evictionFilter;initialProviders;cidPeerFilterSize;constructor(e,t){super(),this.logName=t.name,this.logger=e.logger,this.log=e.logger.forComponent(this.logName),this.requests=new Map,this.minProviders=t.minProviders??1,this.maxProviders=t.maxProviders??5,this.cidPeerFilterSize=t.cidPeerFilterSize??100,this.providers=[],this.evictionFilter=sn(this.maxProviders),this.initialProviders=[...t.providers??[]]}async retrieve(e,t={}){let n=pt.encode(e.multihash.bytes),o=this.requests.get(n);if(o!=null)return this.log("join existing request for %c",e),o.observers++,o.promise;let s=De(),i={promise:s.promise,observers:1,queryFilter:sn(this.cidPeerFilterSize)};this.requests.set(n,i);let a=!1;this.initialPeerSearchComplete==null&&(a=!0,this.log=this.logger.forComponent(`${this.logName}:${e}`),this.initialPeerSearchComplete=this.findProviders(e,this.minProviders,t));let c=!1,f=new qt({concurrency:this.maxProviders});f.addEventListener("failure",d=>{if(d.detail.job.options.provider.fallback){this.log.error("error querying fallback provider %s - %e",d.detail.job.options.provider,d.detail.error);return}if(d.detail.error.name==="NoEvictionError"){this.log.error("no-eviction error querying provider %s - %e",d.detail.job.options.provider,d.detail.error);return}this.log.error("error querying provider %s, evicting from session - %e",d.detail.job.options.provider,d.detail.error),this.evict(d.detail.job.options.provider)}),f.addEventListener("success",d=>{c=!0,s.resolve(d.detail.result)}),f.addEventListener("idle",()=>{if(c){this.log.trace("session idle, found block");return}if(t.signal?.aborted===!0){this.log.trace("session idle, signal aborted");return}Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",e);for(let d=0;d<this.minProviders&&this.providers.length!==0;d++){let h=this.providers[Math.floor(Math.random()*this.providers.length)];h.fallback||(this.log("evicting %s to make room for more providers",h),this.evict(h))}await this.findProviders(e,this.minProviders,t),this.log("found new providers re-retrieving %c",e),this.requests.delete(n),s.resolve(await this.retrieve(e,t))}).catch(d=>{this.log.error("could not find new providers for %c - %e",e,d),s.reject(d)})});let u=d=>{let h=this.toFilterKey(d.detail);i.queryFilter.has(h)||(i.queryFilter.add(h),this.emitFoundProviderProgressEvent(e,d.detail,t),f.add(async()=>this.queryProvider(e,d.detail,t),{provider:d.detail}).catch(x=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,x)}))};if(this.addEventListener("provider",u),a)try{await bn(this.initialPeerSearchComplete,t.signal),a&&this.log("found initial session peers for %c",e)}catch(d){throw a&&this.log("failed to find initial session peers for %c - %e",e,d),this.requests.delete(n),i.observers>1&&s.reject(d),d}Promise.all([...this.providers].filter(d=>{let h=this.toFilterKey(d),x=i.queryFilter.has(h);return x||i.queryFilter.add(this.toFilterKey(d)),!x}).map(async d=>f.add(async()=>this.queryProvider(e,d,t),{provider:d}))).catch(d=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,d)});let l=()=>{s.reject(new Ae(t.signal?.reason??"Session aborted")),f.abort()};t.signal?.addEventListener("abort",l);try{return await s.promise}finally{this.removeEventListener("provider",u),t.signal?.removeEventListener("abort",l),f.clear(),this.requests.delete(n)}}evict(e){this.evictionFilter.add(this.toFilterKey(e));let t=this.providers.findIndex(n=>this.equals(n,e));t!==-1&&this.providers.splice(t,1)}isEvicted(e){return this.evictionFilter.has(this.toFilterKey(e))}hasProvider(e){return!!(this.providers.find(t=>this.equals(t,e))!=null||this.isEvicted(e))}async addPeer(e,t){let n=await this.convertToProvider(e,"manually-added",t);n==null||this.hasProvider(n)||(this.providers.push(n),this.safeDispatchEvent("provider",{detail:n}))}async findProviders(e,t,n){let o=De(),s=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c - %d initial providers",t,this.maxProviders,e,this.initialProviders.length);let i=this,a=async function*(){for(;i.initialProviders.length>0;){let f=i.initialProviders.pop();if(f==null)continue;let u=await i.convertToProvider(f,"manual",n);u!=null&&(yield u)}},c=async function*(){yield*a(),yield*i.findNewProviders(e,n)};for await(let f of c()){if(this.providers.length===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(f)&&(this.log("found %d providers, %d in session",s,this.providers.length),this.providers.push(f),this.safeDispatchEvent("provider",{detail:f}),s++,this.providers.length===t&&(this.log("session is ready with %d peer(s), new peers present",this.providers.length),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers %d",this.providers.length);break}}if(this.log("found %d new session peers while trying to find %d, %d in session",s,t,this.providers.length),this.providers.length<t)throw new rn(`Found ${s} of ${t} ${this.name} providers for ${e}, ${this.providers.length} in session after evictions`)}).catch(i=>{this.log.error("error searching routing for potential session peers for %c - %e",e,i),o.reject(i)}),o.promise}};function Rl(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var xa=Rl;function Nl(r){return r[Symbol.asyncIterator]!=null}function Ul(r){if(Nl(r))return(async()=>{let n=new Uint8Array(0);for await(let o of r)n=we([n,o],n.length+o.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return we(e,t)}var Ea=Ul;function Bn(r){return r==null?!1:G.asCID(r)!=null}async function va(r,e,t,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,Te(e),Te(t.subarray()));return n?.signal?.throwIfAborted(),s}var Fl=parseInt("11111",2),ys=parseInt("10000000",2),Ml=parseInt("01111111",2),Sa={0:yr,1:yr,2:zl,3:ql,4:Vl,5:Hl,6:Kl,16:yr,22:yr,48:yr};function ws(r,e={offset:0}){let t=r[e.offset]&Fl;if(e.offset++,Sa[t]!=null)return Sa[t](r,e);throw new Error("No decoder for tag "+t)}function wr(r,e){let t=0;if((r[e.offset]&ys)===ys){let n=r[e.offset]&Ml,o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++)o+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(o,16)}else t=r[e.offset],e.offset++;return t}function yr(r,e){wr(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=ws(r,e);if(n===null)break;t.push(n)}return t}function zl(r,e){let t=wr(r,e),n=e.offset,o=e.offset+t,s=[];for(let i=n;i<o;i++)i===n&&r[i]===0||s.push(r[i]);return e.offset+=t,Uint8Array.from(s)}function Kl(r,e){let t=wr(r,e),n=e.offset+t,o=r[e.offset];e.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(;e.offset<n;){let f=r[e.offset];if(e.offset++,c.push(f&127),f<128){c.reverse();let u=0;for(let l=0;l<c.length;l++)u+=c[l]<<l*7;a+=`.${u}`,c=[]}}return a}function Hl(r,e){return e.offset++,null}function ql(r,e){let t=wr(r,e),n=r[e.offset];e.offset++;let o=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function Vl(r,e){let t=wr(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function Wl(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new ue;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function xs(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=Wl(r.byteLength);return new ue(Uint8Array.from([e.byteLength|ys]),e)}function _a(r){let e=new ue,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new ue(Uint8Array.from([2]),xs(e),e)}function Aa(r){let e=Uint8Array.from([0]),t=new ue(e,r);return new ue(Uint8Array.from([3]),xs(t),t)}function kn(r,e=48){let t=new ue;for(let n of r)t.append(n);return new ue(Uint8Array.from([e]),xs(t),t)}var $l=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),jl=Uint8Array.from([6,5,43,129,4,0,34]),Gl=Uint8Array.from([6,5,43,129,4,0,35]),Zl={ext:!0,kty:"EC",crv:"P-256"},Yl={ext:!0,kty:"EC",crv:"P-384"},Xl={ext:!0,kty:"EC",crv:"P-521"},Es=32,vs=48,Ss=66;function Ia(r){let e=ws(r);return Ta(e)}function Ta(r){let e=r[1][1][0],t=1,n,o;if(e.byteLength===Es*2+1)return n=q(e.subarray(t,t+Es),"base64url"),o=q(e.subarray(t+Es),"base64url"),new Wt({...Zl,key_ops:["verify"],x:n,y:o});if(e.byteLength===vs*2+1)return n=q(e.subarray(t,t+vs),"base64url"),o=q(e.subarray(t+vs),"base64url"),new Wt({...Yl,key_ops:["verify"],x:n,y:o});if(e.byteLength===Ss*2+1)return n=q(e.subarray(t,t+Ss),"base64url"),o=q(e.subarray(t+Ss),"base64url"),new Wt({...Xl,key_ops:["verify"],x:n,y:o});throw new Se(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function Ba(r){return kn([_a(Uint8Array.from([1])),kn([Ql(r.crv)],160),kn([Aa(new ue(Uint8Array.from([4]),W(r.x??"","base64url"),W(r.y??"","base64url")))],161)]).subarray()}function Ql(r){if(r==="P-256")return $l;if(r==="P-384")return jl;if(r==="P-521")return Gl;throw new Se(`Invalid curve ${r}`)}var Wt=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=Ba(this.jwk)),this._raw}toMultihash(){return Ie.digest($t(this))}toCID(){return G.createV1(114,this.toMultihash())}toString(){return ee.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Q(this.raw,e.raw)}async verify(e,t,n){return va(this.jwk,t,e,n)}};function _s(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}function nt(r,e=""){if(typeof r!="number"){let t=e&&`"${e}" `;throw new TypeError(`${t}expected number, got ${typeof r}`)}if(!Number.isSafeInteger(r)||r<0){let t=e&&`"${e}" `;throw new RangeError(`${t}expected integer >= 0, got ${r}`)}}function Ee(r,e,t=""){let n=_s(r),o=r?.length,s=e!==void 0;if(!n||s&&o!==e){let i=t&&`"${t}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof r}`,f=i+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(f):new TypeError(f)}return r}function Dn(r){if(typeof r!="function"||typeof r.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(nt(r.outputLen),nt(r.blockLen),r.outputLen<1)throw new Error('"outputLen" must be >= 1');if(r.blockLen<1)throw new Error('"blockLen" must be >= 1')}function jt(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function Ln(r,e){Ee(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length<t)throw new RangeError('"digestInto() output" expected to be of length >='+t)}function Ge(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function Cn(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Le(r,e){return r<<32-e|r>>>e}var Da=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Jl=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Pn(r){if(Ee(r),Da)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=Jl[r[t]];return e}var je={_0:48,_9:57,A:65,F:70,a:97,f:102};function ka(r){if(r>=je._0&&r<=je._9)return r-je._0;if(r>=je.A&&r<=je.F)return r-(je.A-10);if(r>=je.a&&r<=je.f)return r-(je.a-10)}function xr(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);if(Da)try{return Uint8Array.fromHex(r)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}let e=r.length,t=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let o=0,s=0;o<t;o++,s+=2){let i=ka(r.charCodeAt(s)),a=ka(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function As(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];Ee(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let s=r[n];t.set(s,o),o+=s.length}return t}function Is(r,e={}){let t=(o,s)=>r(s).update(o).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.canXOF=n.canXOF,t.create=o=>r(o),Object.assign(t,e),Object.freeze(t)}function La(r=32){nt(r,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(r>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${r}`);return e.getRandomValues(new Uint8Array(r))}var Ts=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function Ca(r,e,t){return r&e^~r&t}function Pa(r,e,t){return r&e^r&t^e&t}var Er=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,o){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=Cn(this.buffer)}update(e){jt(this),Ee(e);let{view:t,buffer:n,blockLen:o}=this,s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=Cn(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){jt(this),Ln(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,Ge(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let l=i;l<o;l++)t[l]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=Cn(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let f=c/4,u=this.get();if(f>u.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<f;l++)a.setUint32(4*l,u[l],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},Ze=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var de=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var On=BigInt(4294967295),Oa=BigInt(32);function ed(r,e=!1){return e?{h:Number(r&On),l:Number(r>>Oa&On)}:{h:Number(r>>Oa&On)|0,l:Number(r&On)|0}}function Ra(r,e=!1){let t=r.length,n=new Uint32Array(t),o=new Uint32Array(t);for(let s=0;s<t;s++){let{h:i,l:a}=ed(r[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var Bs=(r,e,t)=>r>>>t,ks=(r,e,t)=>r<<32-t|e>>>t,vt=(r,e,t)=>r>>>t|e<<32-t,St=(r,e,t)=>r<<32-t|e>>>t,vr=(r,e,t)=>r<<64-t|e>>>t-32,Sr=(r,e,t)=>r>>>t-32|e<<64-t;function Ke(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var Na=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),Ua=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,Fa=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),Ma=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,za=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),Ka=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var rd=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]),ot=new Uint32Array(64),Ds=class extends Er{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,t,n,o,s,i,a,c]}set(e,t,n,o,s,i,a,c){this.A=e|0,this.B=t|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(e,t){for(let l=0;l<16;l++,t+=4)ot[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){let d=ot[l-15],h=ot[l-2],x=Le(d,7)^Le(d,18)^d>>>3,_=Le(h,17)^Le(h,19)^h>>>10;ot[l]=_+ot[l-7]+x+ot[l-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:f,H:u}=this;for(let l=0;l<64;l++){let d=Le(a,6)^Le(a,11)^Le(a,25),h=u+d+Ca(a,c,f)+rd[l]+ot[l]|0,_=(Le(n,2)^Le(n,13)^Le(n,22))+Pa(n,o,s)|0;u=f,f=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+_|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,f=f+this.G|0,u=u+this.H|0,this.set(n,o,s,i,a,c,f,u)}roundClean(){Ge(ot)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Ge(this.buffer)}},Ls=class extends Ds{A=Ze[0]|0;B=Ze[1]|0;C=Ze[2]|0;D=Ze[3]|0;E=Ze[4]|0;F=Ze[5]|0;G=Ze[6]|0;H=Ze[7]|0;constructor(){super(32)}};var Ha=Ra(["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))),nd=Ha[0],od=Ha[1],st=new Uint32Array(80),it=new Uint32Array(80),Cs=class extends Er{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:f,El:u,Fh:l,Fl:d,Gh:h,Gl:x,Hh:_,Hl:m}=this;return[e,t,n,o,s,i,a,c,f,u,l,d,h,x,_,m]}set(e,t,n,o,s,i,a,c,f,u,l,d,h,x,_,m){this.Ah=e|0,this.Al=t|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=f|0,this.El=u|0,this.Fh=l|0,this.Fl=d|0,this.Gh=h|0,this.Gl=x|0,this.Hh=_|0,this.Hl=m|0}process(e,t){for(let A=0;A<16;A++,t+=4)st[A]=e.getUint32(t),it[A]=e.getUint32(t+=4);for(let A=16;A<80;A++){let L=st[A-15]|0,k=it[A-15]|0,R=vt(L,k,1)^vt(L,k,8)^Bs(L,k,7),C=St(L,k,1)^St(L,k,8)^ks(L,k,7),I=st[A-2]|0,N=it[A-2]|0,U=vt(I,N,19)^vr(I,N,61)^Bs(I,N,6),O=St(I,N,19)^Sr(I,N,61)^ks(I,N,6),p=Fa(C,O,it[A-7],it[A-16]),b=Ma(p,R,U,st[A-7],st[A-16]);st[A]=b|0,it[A]=p|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:f,Dl:u,Eh:l,El:d,Fh:h,Fl:x,Gh:_,Gl:m,Hh:g,Hl:E}=this;for(let A=0;A<80;A++){let L=vt(l,d,14)^vt(l,d,18)^vr(l,d,41),k=St(l,d,14)^St(l,d,18)^Sr(l,d,41),R=l&h^~l&_,C=d&x^~d&m,I=za(E,k,C,od[A],it[A]),N=Ka(I,g,L,R,nd[A],st[A]),U=I|0,O=vt(n,o,28)^vr(n,o,34)^vr(n,o,39),p=St(n,o,28)^Sr(n,o,34)^Sr(n,o,39),b=n&s^n&a^s&a,v=o&i^o&c^i&c;g=_|0,E=m|0,_=h|0,m=x|0,h=l|0,x=d|0,{h:l,l:d}=Ke(f|0,u|0,N|0,U|0),f=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let w=Na(U,p,v);n=Ua(w,N,O,b),o=w|0}({h:n,l:o}=Ke(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=Ke(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=Ke(this.Ch|0,this.Cl|0,a|0,c|0),{h:f,l:u}=Ke(this.Dh|0,this.Dl|0,f|0,u|0),{h:l,l:d}=Ke(this.Eh|0,this.El|0,l|0,d|0),{h,l:x}=Ke(this.Fh|0,this.Fl|0,h|0,x|0),{h:_,l:m}=Ke(this.Gh|0,this.Gl|0,_|0,m|0),{h:g,l:E}=Ke(this.Hh|0,this.Hl|0,g|0,E|0),this.set(n,o,s,i,a,c,f,u,l,d,h,x,_,m,g,E)}roundClean(){Ge(st,it)}destroy(){this.destroyed=!0,Ge(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Ps=class extends Cs{Ah=de[0]|0;Al=de[1]|0;Bh=de[2]|0;Bl=de[3]|0;Ch=de[4]|0;Cl=de[5]|0;Dh=de[6]|0;Dl=de[7]|0;Eh=de[8]|0;El=de[9]|0;Fh=de[10]|0;Fl=de[11]|0;Gh=de[12]|0;Gl=de[13]|0;Hh=de[14]|0;Hl=de[15]|0;constructor(){super(64)}};var qa=Is(()=>new Ls,Ts(1));var Rn=Is(()=>new Ps,Ts(3));var z=(r,e,t)=>Ee(r,e,t),Rs=nt,Gt=Pn,re=(...r)=>As(...r),Zt=r=>xr(r),_t=_s,_r=r=>La(r),Un=BigInt(0),Os=BigInt(1);function Ce(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}" `;throw new TypeError(t+"expected boolean, got type="+typeof r)}return r}function Fn(r){if(typeof r=="bigint"){if(!Nn(r))throw new RangeError("positive bigint expected, got "+r)}else Rs(r);return r}function Pe(r,e=""){if(typeof r!="number"){let t=e&&`"${e}" `;throw new TypeError(t+"expected number, got type="+typeof r)}if(!Number.isSafeInteger(r)){let t=e&&`"${e}" `;throw new RangeError(t+"expected safe integer, got "+r)}}function Ar(r){let e=Fn(r).toString(16);return e.length&1?"0"+e:e}function Va(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);return r===""?Un:BigInt("0x"+r)}function At(r){return Va(Pn(r))}function He(r){return Va(Pn(Ir(Ee(r)).reverse()))}function Mn(r,e){if(nt(e),e===0)throw new RangeError("zero length");r=Fn(r);let t=r.toString(16);if(t.length>e*2)throw new RangeError("number too large");return xr(t.padStart(e*2,"0"))}function Ns(r,e){return Mn(r,e).reverse()}function Wa(r,e){if(r=z(r),e=z(e),r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}function Ir(r){return Uint8Array.from(z(r))}function zn(r){if(typeof r!="string")throw new TypeError("ascii string expected, got "+typeof r);return Uint8Array.from(r,(e,t)=>{let n=e.charCodeAt(0);if(e.length!==1||n>127)throw new RangeError(`string contains non-ASCII character "${r[t]}" with code ${n} at position ${t}`);return n})}var Nn=r=>typeof r=="bigint"&&Un<=r;function sd(r,e,t){return Nn(r)&&Nn(e)&&Nn(t)&&e<=r&&r<t}function Yt(r,e,t,n){if(!sd(e,t,n))throw new RangeError("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function Xt(r){if(r<Un)throw new Error("expected non-negative bigint, got "+r);let e;for(e=0;r>Un;r>>=Os,e+=1);return e}var Tr=r=>(Os<<BigInt(r))-Os;function $a(r,e,t){if(nt(r,"hashLen"),nt(e,"qByteLen"),typeof t!="function")throw new TypeError("hmacFn must be a function");let n=m=>new Uint8Array(m),o=Uint8Array.of(),s=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(r),f=n(r),u=0,l=()=>{c.fill(1),f.fill(0),u=0},d=(...m)=>t(f,re(c,...m)),h=(m=o)=>{f=d(s,m),c=d(),m.length!==0&&(f=d(i,m),c=d())},x=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let m=0,g=[];for(;m<e;){c=d();let E=c.slice();g.push(E),m+=c.length}return re(...g)};return(m,g)=>{l(),h(m);let E;for(;(E=g(x()))===void 0;)h();return l(),E}}function Oe(r,e={},t={}){if(Object.prototype.toString.call(r)!=="[object Object]")throw new TypeError("expected valid options object");function n(s,i,a){if(!a&&i!=="function"&&!Object.hasOwn(r,s))throw new TypeError(`param "${s}" is invalid: expected own property`);let c=r[s];if(a&&c===void 0)return;let f=typeof c;if(f!==i||c===null)throw new TypeError(`param "${s}" is invalid: expected ${i}, got ${f}`)}let o=(s,i)=>Object.entries(s).forEach(([a,c])=>n(a,c,i));o(e,!1),o(t,!0)}var Us=()=>{throw new Error("not implemented")};var he=BigInt(0),Y=BigInt(1),It=BigInt(2),Ya=BigInt(3),Xa=BigInt(4),Qa=BigInt(5),id=BigInt(7),Ja=BigInt(8),ad=BigInt(9),ec=BigInt(16);function J(r,e){if(e<=he)throw new Error("mod: expected positive modulus, got "+e);let t=r%e;return t>=he?t:e+t}function $(r,e,t){if(e<he)throw new Error("pow2: expected non-negative exponent, got "+e);let n=r;for(;e-- >he;)n*=n,n%=t;return n}function ja(r,e){if(r===he)throw new Error("invert: expected non-zero number");if(e<=he)throw new Error("invert: expected positive modulus, got "+e);let t=J(r,e),n=e,o=he,s=Y,i=Y,a=he;for(;t!==he;){let f=n/t,u=n-t*f,l=o-i*f,d=s-a*f;n=t,t=u,o=i,s=a,i=l,a=d}if(n!==Y)throw new Error("invert: does not exist");return J(o,e)}function Fs(r,e,t){let n=r;if(!n.eql(n.sqr(e),t))throw new Error("Cannot find square root")}function tc(r,e){let t=r,n=(t.ORDER+Y)/Xa,o=t.pow(e,n);return Fs(t,o,e),o}function cd(r,e){let t=r,n=(t.ORDER-Qa)/Ja,o=t.mul(e,It),s=t.pow(o,n),i=t.mul(e,s),a=t.mul(t.mul(i,It),s),c=t.mul(i,t.sub(a,t.ONE));return Fs(t,c,e),c}function fd(r){let e=Qt(r),t=rc(r),n=t(e,e.neg(e.ONE)),o=t(e,n),s=t(e,e.neg(n)),i=(r+id)/ec;return((a,c)=>{let f=a,u=f.pow(c,i),l=f.mul(u,n),d=f.mul(u,o),h=f.mul(u,s),x=f.eql(f.sqr(l),c),_=f.eql(f.sqr(d),c);u=f.cmov(u,l,x),l=f.cmov(h,d,_);let m=f.eql(f.sqr(l),c),g=f.cmov(u,l,m);return Fs(f,g,c),g})}function rc(r){if(r<Ya)throw new Error("sqrt is not defined for small field");let e=r-Y,t=0;for(;e%It===he;)e/=It,t++;let n=It,o=Qt(r);for(;Ga(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return tc;let s=o.pow(n,e),i=(e+Y)/It;return function(c,f){let u=c;if(u.is0(f))return f;if(Ga(u,f)!==1)throw new Error("Cannot find square root");let l=t,d=u.mul(u.ONE,s),h=u.pow(f,e),x=u.pow(f,i);for(;!u.eql(h,u.ONE);){if(u.is0(h))return u.ZERO;let _=1,m=u.sqr(h);for(;!u.eql(m,u.ONE);)if(_++,m=u.sqr(m),_===l)throw new Error("Cannot find square root");let g=Y<<BigInt(l-_-1),E=u.pow(d,g);l=_,d=u.sqr(E),h=u.mul(h,d),x=u.mul(x,E)}return x}}function ud(r){return r%Xa===Ya?tc:r%Ja===Qa?cd:r%ec===ad?fd(r):rc(r)}var Ye=(r,e)=>(J(r,e)&Y)===Y,ld=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ms(r){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=ld.reduce((n,o)=>(n[o]="function",n),e);if(Oe(r,t),Pe(r.BYTES,"BYTES"),Pe(r.BITS,"BITS"),r.BYTES<1||r.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(r.ORDER<=Y)throw new Error("invalid field: expected ORDER > 1, got "+r.ORDER);return r}function dd(r,e,t){let n=r;if(t<he)throw new Error("invalid exponent, negatives unsupported");if(t===he)return n.ONE;if(t===Y)return e;let o=n.ONE,s=e;for(;t>he;)t&Y&&(o=n.mul(o,s)),s=n.sqr(s),t>>=Y;return o}function Br(r,e,t=!1){let n=r,o=new Array(e.length).fill(t?n.ZERO:void 0),s=e.reduce((a,c,f)=>n.is0(c)?a:(o[f]=a,n.mul(a,c)),n.ONE),i=n.inv(s);return e.reduceRight((a,c,f)=>n.is0(c)?a:(o[f]=n.mul(a,o[f]),n.mul(a,c)),i),o}function Ga(r,e){let t=r,n=(t.ORDER-Y)/It,o=t.pow(e,n),s=t.eql(o,t.ONE),i=t.eql(o,t.ZERO),a=t.eql(o,t.neg(t.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function hd(r,e){if(e!==void 0&&Rs(e),r<=he)throw new Error("invalid n length: expected positive n, got "+r);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let t=Xt(r);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected bit length (${t}) >= n.length (${e})`);let n=e!==void 0?e:t,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}var Za=new WeakMap,Kn=class{ORDER;BITS;BYTES;isLE;ZERO=he;ONE=Y;_lengths;_mod;constructor(e,t={}){if(e<=Y)throw new Error("invalid field: expected ORDER > 1, got "+e);let n;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(n=t.BITS),typeof t.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0}),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=Object.freeze(t.allowedLengths.slice())),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:o,nByteLength:s}=hd(e,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,Object.freeze(this)}create(e){return J(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return he<=e&&e<this.ORDER}is0(e){return e===he}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&Y)===Y}neg(e){return J(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return J(e*e,this.ORDER)}add(e,t){return J(e+t,this.ORDER)}sub(e,t){return J(e-t,this.ORDER)}mul(e,t){return J(e*t,this.ORDER)}pow(e,t){return dd(this,e,t)}div(e,t){return J(e*ja(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return ja(e,this.ORDER)}sqrt(e){let t=Za.get(this);return t||Za.set(this,t=ud(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?Ns(e,this.BYTES):Mn(e,this.BYTES)}fromBytes(e,t=!1){z(e);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(e.length<1||!n.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let f=new Uint8Array(o);f.set(e,s?0:f.length-e.length),e=f}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?He(e):At(e);if(a&&(c=J(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Br(this,e)}cmov(e,t,n){return Ce(n,"condition"),n?t:e}};Object.freeze(Kn.prototype);function Qt(r,e={}){return new Kn(r,e)}function nc(r){if(typeof r!="bigint")throw new Error("field order must be bigint");if(r<=Y)throw new Error("field order must be greater than 1");let e=Xt(r-Y);return Math.ceil(e/8)}function zs(r){let e=nc(r);return e+Math.ceil(e/2)}function Ks(r,e,t=!1){z(r);let n=r.length,o=nc(e),s=Math.max(zs(e),16);if(n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=t?He(r):At(r),a=J(i,e-Y)+Y;return t?Ns(a,o):Mn(a,o)}var Jt=BigInt(0),Tt=BigInt(1);function kr(r,e){let t=e.negate();return r?t:e}function Bt(r,e){let t=Br(r.Fp,e.map(n=>n.Z));return e.map((n,o)=>r.fromAffine(n.toAffine(t[o])))}function ac(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function Hs(r,e){ac(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1),o=2**r,s=Tr(r),i=BigInt(r);return{windows:t,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function oc(r,e,t){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=t,a=Number(r&o),c=r>>i;a>n&&(a-=s,c+=Tt);let f=e*n,u=f+Math.abs(a)-1,l=a===0,d=a<0,h=e%2!==0;return{nextN:c,offset:u,isZero:l,isNeg:d,isNegF:h,offsetF:f}}var qs=new WeakMap,cc=new WeakMap;function Vs(r){return cc.get(r)||1}function sc(r){if(r!==Jt)throw new Error("invalid wNAF")}var er=class{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let o=e;for(;t>Jt;)t&Tt&&(n=n.add(o)),o=o.double(),t>>=Tt;return n}precomputeWindow(e,t){let{windows:n,windowSize:o}=Hs(t,this.bits),s=[],i=e,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let f=1;f<o;f++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=Hs(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:f,isZero:u,isNeg:l,isNegF:d,offsetF:h}=oc(n,a,i);n=c,u?s=s.add(kr(d,t[h])):o=o.add(kr(l,t[f]))}return sc(n),{p:o,f:s}}wNAFUnsafe(e,t,n,o=this.ZERO){let s=Hs(e,this.bits);for(let i=0;i<s.windows&&n!==Jt;i++){let{nextN:a,offset:c,isZero:f,isNeg:u}=oc(n,i,s);if(n=a,!f){let l=t[c];o=o.add(u?l.negate():l)}}return sc(n),o}getPrecomputes(e,t,n){let o=qs.get(t);return o||(o=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(o=n(o)),qs.set(t,o))),o}cached(e,t,n){let o=Vs(e);return this.wNAF(o,this.getPrecomputes(o,e,n),t)}unsafe(e,t,n,o){let s=Vs(e);return s===1?this._unsafeLadder(e,t,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),t,o)}createCache(e,t){ac(t,this.bits),cc.set(e,t),qs.delete(e)}hasCache(e){return Vs(e)!==1}};function fc(r,e,t,n){let o=e,s=r.ZERO,i=r.ZERO;for(;t>Jt||n>Jt;)t&Tt&&(s=s.add(o)),n&Tt&&(i=i.add(o)),o=o.double(),t>>=Tt,n>>=Tt;return{p1:s,p2:i}}function ic(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Ms(e),e}else return Qt(r,{isLE:t})}function Hn(r,e,t={},n){if(n===void 0&&(n=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let f=e[c];if(!(typeof f=="bigint"&&f>Jt))throw new Error(`CURVE.${c} must be positive bigint`)}let o=ic(e.p,t.Fp,n),s=ic(e.n,t.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}function qn(r,e){return function(n){let o=r(n);return{secretKey:o,publicKey:e(o)}}}var at=BigInt(0),ae=BigInt(1),Ws=BigInt(2),pd=BigInt(8);function md(r,e,t,n){let o=r.sqr(t),s=r.sqr(n),i=r.add(r.mul(e.a,o),s),a=r.add(r.ONE,r.mul(e.d,r.mul(o,s)));return r.eql(i,a)}function uc(r,e={}){let t=e,n=Hn("edwards",r,t,t.FpFnLE),{Fp:o,Fn:s}=n,i=n.CURVE,{h:a}=i;Oe(t,{},{uvRatio:"function"});let c=Ws<<BigInt(s.BYTES*8)-ae,f=_=>o.create(_),u=t.uvRatio===void 0?(_,m)=>{try{return{isValid:!0,value:o.sqrt(o.div(_,m))}}catch{return{isValid:!1,value:at}}}:t.uvRatio;if(!md(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function l(_,m,g=!1){let E=g?ae:at;return Yt("coordinate "+_,m,E,c),m}function d(_){if(!(_ instanceof h))throw new Error("EdwardsPoint expected")}class h{static BASE=new h(i.Gx,i.Gy,ae,f(i.Gx*i.Gy));static ZERO=new h(at,ae,ae,at);static Fp=o;static Fn=s;X;Y;Z;T;constructor(m,g,E,A){this.X=l("x",m),this.Y=l("y",g),this.Z=l("z",E,!0),this.T=l("t",A),Object.freeze(this)}static CURVE(){return i}static fromAffine(m){if(m instanceof h)throw new Error("extended point not allowed");let{x:g,y:E}=m||{};return l("x",g),l("y",E),new h(g,E,ae,f(g*E))}static fromBytes(m,g=!1){let E=o.BYTES,{a:A,d:L}=i;m=Ir(z(m,E,"point")),Ce(g,"zip215");let k=Ir(m),R=m[E-1];k[E-1]=R&-129;let C=He(k),I=g?c:o.ORDER;Yt("point.y",C,at,I);let N=f(C*C),U=f(N-ae),O=f(L*N-A),{isValid:p,value:b}=u(U,O);if(!p)throw new Error("bad point: invalid y coordinate");let v=(b&ae)===ae,w=(R&128)!==0;if(!g&&b===at&&w)throw new Error("bad point: x=0 and x_0=1");return w!==v&&(b=f(-b)),h.fromAffine({x:b,y:C})}static fromHex(m,g=!1){return h.fromBytes(Zt(m),g)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(m=8,g=!0){return x.createCache(this,m),g||this.multiply(Ws),this}assertValidity(){let m=this,{a:g,d:E}=i;if(m.is0())throw new Error("bad point: ZERO");let{X:A,Y:L,Z:k,T:R}=m,C=f(A*A),I=f(L*L),N=f(k*k),U=f(N*N),O=f(C*g),p=f(N*f(O+I)),b=f(U+f(E*f(C*I)));if(p!==b)throw new Error("bad point: equation left != right (1)");let v=f(A*L),w=f(k*R);if(v!==w)throw new Error("bad point: equation left != right (2)")}equals(m){d(m);let{X:g,Y:E,Z:A}=this,{X:L,Y:k,Z:R}=m,C=f(g*R),I=f(L*A),N=f(E*R),U=f(k*A);return C===I&&N===U}is0(){return this.equals(h.ZERO)}negate(){return new h(f(-this.X),this.Y,this.Z,f(-this.T))}double(){let{a:m}=i,{X:g,Y:E,Z:A}=this,L=f(g*g),k=f(E*E),R=f(Ws*f(A*A)),C=f(m*L),I=g+E,N=f(f(I*I)-L-k),U=C+k,O=U-R,p=C-k,b=f(N*O),v=f(U*p),w=f(N*p),y=f(O*U);return new h(b,v,y,w)}add(m){d(m);let{a:g,d:E}=i,{X:A,Y:L,Z:k,T:R}=this,{X:C,Y:I,Z:N,T:U}=m,O=f(A*C),p=f(L*I),b=f(R*E*U),v=f(k*N),w=f((A+L)*(C+I)-O-p),y=v-b,S=v+b,B=f(p-g*O),T=f(w*y),D=f(S*B),P=f(w*B),M=f(y*S);return new h(T,D,M,P)}subtract(m){return d(m),this.add(m.negate())}multiply(m){if(!s.isValidNot0(m))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:g,f:E}=x.cached(this,m,A=>Bt(h,A));return Bt(h,[g,E])[0]}multiplyUnsafe(m){if(!s.isValid(m))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return m===at?h.ZERO:this.is0()||m===ae?this:x.unsafe(this,m,g=>Bt(h,g))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return x.unsafe(this,i.n).is0()}toAffine(m){let g=this,E=m,{X:A,Y:L,Z:k}=g,R=g.is0();E==null&&(E=R?pd:o.inv(k));let C=f(A*E),I=f(L*E),N=o.mul(k,E);if(R)return{x:at,y:ae};if(N!==ae)throw new Error("invZ was invalid");return{x:C,y:I}}clearCofactor(){return a===ae?this:this.multiplyUnsafe(a)}toBytes(){let{x:m,y:g}=this.toAffine(),E=o.toBytes(g);return E[E.length-1]|=m&ae?128:0,E}toHex(){return Gt(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let x=new er(h,s.BITS);return s.BITS>=8&&h.BASE.precompute(8),Object.freeze(h.prototype),Object.freeze(h),h}var Vn=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e}static fromBytes(e){Us()}static fromHex(e){Us()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return Gt(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.ep.precompute(e,t),this}};function lc(r,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');let n=e,o=t;Oe(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:s}=o,{BASE:i,Fp:a,Fn:c}=r,f=n.outputLen,u=2*a.BYTES;if(f!==void 0&&(Pe(f,"hash.outputLen"),f!==u))throw new Error(`hash.outputLen must be ${u}, got ${f}`);let l=o.randomBytes===void 0?_r:o.randomBytes,d=o.adjustScalarBytes===void 0?p=>p:o.adjustScalarBytes,h=o.domain===void 0?(p,b,v)=>{if(Ce(v,"phflag"),b.length||v)throw new Error("Contexts/pre-hash are not supported");return p}:o.domain;function x(p){return c.create(He(p))}function _(p){let b=C.secretKey;z(p,C.secretKey,"secretKey");let v=z(n(p),2*b,"hashedSecretKey"),w=d(v.slice(0,b)),y=v.slice(b,2*b),S=x(w);return{head:w,prefix:y,scalar:S}}function m(p){let{head:b,prefix:v,scalar:w}=_(p),y=i.multiply(w),S=y.toBytes();return{head:b,prefix:v,scalar:w,point:y,pointBytes:S}}function g(p){return m(p).pointBytes}function E(p=Uint8Array.of(),...b){let v=re(...b);return x(n(h(v,z(p,void 0,"context"),!!s)))}function A(p,b,v={}){p=z(p,void 0,"message"),s&&(p=s(p));let{prefix:w,scalar:y,pointBytes:S}=m(b),B=E(v.context,w,p),T=i.multiply(B).toBytes(),D=E(v.context,T,S,p),P=c.create(B+D*y);if(!c.isValid(P))throw new Error("sign failed: invalid s");let M=re(T,c.toBytes(P));return z(M,C.signature,"result")}let L={zip215:o.zip215};function k(p,b,v,w=L){let{context:y}=w,S=w.zip215===void 0?!!L.zip215:w.zip215,B=C.signature;p=z(p,B,"signature"),b=z(b,void 0,"message"),v=z(v,C.publicKey,"publicKey"),S!==void 0&&Ce(S,"zip215"),s&&(b=s(b));let T=B/2,D=p.subarray(0,T),P=He(p.subarray(T,B)),M,K,F;try{M=r.fromBytes(v,S),K=r.fromBytes(D,S),F=i.multiplyUnsafe(P)}catch{return!1}if(!S&&M.isSmallOrder())return!1;let te=E(y,D,v,b);return K.add(M.multiplyUnsafe(te)).subtract(F).clearCofactor().is0()}let R=a.BYTES,C={secretKey:R,publicKey:R,signature:2*R,seed:R};function I(p){return p=p===void 0?l(C.seed):p,z(p,C.seed,"seed")}function N(p){return _t(p)&&p.length===C.secretKey}function U(p,b){try{return!!r.fromBytes(p,b===void 0?L.zip215:b)}catch{return!1}}let O={getExtendedPublicKey:m,randomSecretKey:I,isValidSecretKey:N,isValidPublicKey:U,toMontgomery(p){let{y:b}=r.fromBytes(p),v=C.publicKey,w=v===32;if(!w&&v!==57)throw new Error("only defined for 25519 and 448");let y=w?a.div(ae+b,ae-b):a.div(b-ae,b+ae);return a.toBytes(y)},toMontgomerySecret(p){let b=C.secretKey;z(p,b);let v=n(p.subarray(0,b));return d(v).subarray(0,b)}};return Object.freeze(C),Object.freeze(O),Object.freeze({keygen:qn(I,g),getPublicKey:g,sign:A,verify:k,utils:O,Point:r,lengths:C})}function Dr(r,e){if(Pe(r),Pe(e),e<0||e>4)throw new Error("invalid I2OSP length: "+e);if(r<0||r>2**(8*e)-1)throw new Error("invalid I2OSP input: "+r);let t=Array.from({length:e}).fill(0);for(let n=e-1;n>=0;n--)t[n]=r&255,r>>>=8;return new Uint8Array(t)}function gd(r,e){let t=new Uint8Array(r.length);for(let n=0;n<r.length;n++)t[n]=r[n]^e[n];return t}function bd(r){if(!_t(r)&&typeof r!="string")throw new Error("DST must be Uint8Array or ascii string");let e=typeof r=="string"?zn(r):r;if(e.length===0)throw new Error("DST must be non-empty");return e}function $s(r,e,t,n){z(r),Pe(t),e=bd(e),e.length>255&&(e=n(re(zn("H2C-OVERSIZE-DST-"),e)));let{outputLen:o,blockLen:s}=n,i=Math.ceil(t/o);if(t>65535||i>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=re(e,Dr(e.length,1)),c=new Uint8Array(s),f=Dr(t,2),u=new Array(i),l=n(re(c,r,f,Dr(0,1),a));u[0]=n(re(l,Dr(1,1),a));for(let h=1;h<i;h++){let x=[gd(l,u[h-1]),Dr(h+1,1),a];u[h]=n(re(...x))}return re(...u).slice(0,t)}var dc="HashToScalar-";var yd=BigInt(0),Xe=BigInt(1),hc=BigInt(2);var wd=BigInt(5),xd=BigInt(8),tr=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Ys={p:tr,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:xd,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Ed(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=tr,a=r*r%s*r%s,c=$(a,hc,s)*a%s,f=$(c,Xe,s)*r%s,u=$(f,wd,s)*f%s,l=$(u,e,s)*u%s,d=$(l,t,s)*l%s,h=$(d,n,s)*d%s,x=$(h,o,s)*h%s,_=$(x,o,s)*h%s,m=$(_,e,s)*u%s;return{pow_p_5_8:$(m,hc,s)*r%s,b2:a}}function vd(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var js=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Xs(r,e){let t=tr,n=J(e*e*e,t),o=J(n*n*e,t),s=Ed(r*o).pow_p_5_8,i=J(r*n*s,t),a=J(e*i*i,t),c=i,f=J(i*js,t),u=a===r,l=a===J(-r,t),d=a===J(-r*js,t);return u&&(i=c),(l||d)&&(i=f),Ye(i,t)&&(i=J(-i,t)),{isValid:u||l,value:i}}var ft=uc(Ys,{uvRatio:Xs}),ct=ft.Fp,gc=ft.Fn;function Sd(r){return lc(ft,Rn,Object.assign({adjustScalarBytes:vd,zip215:!0},r))}var bc=Sd({});var Gs=js,_d=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Ad=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),Id=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),Td=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),pc=r=>Xs(Xe,r),Bd=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Zs=r=>ct.create(He(r)&Bd);function mc(r){let{d:e}=Ys,t=tr,n=g=>ct.create(g),o=n(Gs*r*r),s=n((o+Xe)*Id),i=BigInt(-1),a=n((i-e*o)*n(o+e)),{isValid:c,value:f}=Xs(s,a),u=n(f*r);Ye(u,t)||(u=n(-u)),c||(f=u),c||(i=o);let l=n(i*(o-Xe)*Td-a),d=f*f,h=n((f+f)*a),x=n(l*_d),_=n(Xe-d),m=n(Xe+d);return new ft(n(h*m),n(_*x),n(x*m),n(h*_))}var ut=class r extends Vn{static BASE=new r(ft.BASE);static ZERO=new r(ft.ZERO);static Fp=ct;static Fn=gc;constructor(e){super(e)}static fromAffine(e){return new r(ft.fromAffine(e))}assertSame(e){if(!(e instanceof r))throw new Error("RistrettoPoint expected")}init(e){return new r(e)}static fromBytes(e){Ee(e,32);let{a:t,d:n}=Ys,o=tr,s=L=>ct.create(L),i=Zs(e);if(!Wa(ct.toBytes(i),e)||Ye(i,o))throw new Error("invalid ristretto255 encoding 1");let a=s(i*i),c=s(Xe+t*a),f=s(Xe-t*a),u=s(c*c),l=s(f*f),d=s(t*n*u-l),{isValid:h,value:x}=pc(s(d*l)),_=s(x*f),m=s(x*_*d),g=s((i+i)*_);Ye(g,o)&&(g=s(-g));let E=s(c*m),A=s(g*E);if(!h||Ye(A,o)||E===yd)throw new Error("invalid ristretto255 encoding 2");return new r(new ft(g,E,Xe,A))}static fromHex(e){return r.fromBytes(xr(e))}toBytes(){let{X:e,Y:t,Z:n,T:o}=this.ep,s=tr,i=m=>ct.create(m),a=i(i(n+t)*i(n-t)),c=i(e*t),f=i(c*c),{value:u}=pc(i(a*f)),l=i(u*a),d=i(u*c),h=i(l*d*o),x;if(Ye(o*h,s)){let m=i(t*Gs),g=i(e*Gs);e=m,t=g,x=i(l*Ad)}else x=d;Ye(e*h,s)&&(t=i(-t));let _=i((n-t)*x);return Ye(_,s)&&(_=i(-_)),ct.toBytes(_)}equals(e){this.assertSame(e);let{X:t,Y:n}=this.ep,{X:o,Y:s}=e.ep,i=f=>ct.create(f),a=i(t*s)===i(n*o),c=i(n*s)===i(t*o);return a||c}is0(){return this.equals(r.ZERO)}};Object.freeze(ut.BASE);Object.freeze(ut.ZERO);Object.freeze(ut.prototype);Object.freeze(ut);var kd=Object.freeze({Point:ut,hashToCurve(r,e){let t=e?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":e.DST,n=$s(r,t,64,Rn);return kd.deriveToCurve(n)},hashToScalar(r,e={DST:dc}){let t=$s(r,e.DST,64,Rn);return gc.create(He(t))},deriveToCurve(r){Ee(r,64);let e=Zs(r.subarray(0,32)),t=mc(e),n=Zs(r.subarray(32,64)),o=mc(n);return new ut(t.add(o))}});var Lr=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},Wn=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var $n={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new Wn("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return e}};var jn=32;var Qs,Dd=(async()=>{try{return await $n.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function Ld(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await $n.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await $n.get().subtle.verify({name:"Ed25519"},n,Te(e),Te(t instanceof Uint8Array?t:t.subarray()))}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function Cd(r,e,t){return bc.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function yc(r,e,t){return Qs==null&&(Qs=await Dd),Qs?Ld(r,e,t):Cd(r,e,t)}function Gn(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Zn=class{type="Ed25519";raw;constructor(e){this.raw=Js(e,jn)}toMultihash(){return Ie.digest($t(this))}toCID(){return G.createV1(114,this.toMultihash())}toString(){return ee.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Q(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let o=yc(this.raw,t,e);return Gn(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function xc(r){return r=Js(r,jn),new Zn(r)}function Js(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new Se(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var ge;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(ge||(ge={}));var ei;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(ei||(ei={}));(function(r){r.codec=()=>zt(ei)})(ge||(ge={}));var Cr;(function(r){let e;r.codec=()=>(e==null&&(e=ze((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),ge.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{c.Type=ge.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:ge.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return Fe(s,r.codec())}r.encode=t;function n(s,i){return Ue(s,r.codec(),i)}r.decode=n;function o(s,i){return Me(s,r.codec(),i)}r.stream=o})(Cr||(Cr={}));var ti;(function(r){let e;r.codec=()=>(e==null&&(e=ze((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),ge.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{c.Type=ge.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:ge.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return Fe(s,r.codec())}r.encode=t;function n(s,i){return Ue(s,r.codec(),i)}r.decode=n;function o(s,i){return Me(s,r.codec(),i)}r.stream=o})(ti||(ti={}));var Yn=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(Dn(e),Ee(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(t.length>n?e.create().update(t).digest():t);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),Ge(o)}update(e){return jt(this),this.iHash.update(e),this}digestInto(e){jt(this),Ln(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Ec=(()=>{let r=((e,t,n)=>new Yn(e,t).update(n).digest());return r.create=(e,t)=>new Yn(e,t),r})();var vc=(r,e)=>(r+(r>=0?e:-e)/Sc)/e;function Rd(r,e,t){Yt("scalar",r,qe,t);let[[n,o],[s,i]]=e,a=vc(i*r,t),c=vc(-o*r,t),f=r-a*n-c*s,u=-a*o-c*i,l=f<qe,d=u<qe;l&&(f=-f),d&&(u=-u);let h=Tr(Math.ceil(Xt(t)/2))+lt;if(f<qe||f>=h||u<qe||u>=h)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:l,k1:f,k2neg:d,k2:u}}function ni(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function ri(r,e){Oe(r);let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return Ce(t.lowS,"lowS"),Ce(t.prehash,"prehash"),t.format!==void 0&&ni(t.format),t}var oi=class extends Error{constructor(e=""){super(e)}},Re={Err:oi,_tlv:{encode:(r,e)=>{let{Err:t}=Re;if(Pe(r,"tag"),r<0||r>255)throw new t("tlv.encode: wrong tag");if(typeof e!="string")throw new TypeError('"data" expected string, got type='+typeof e);if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,o=Ar(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let s=n>127?Ar(o.length/2|128):"";return Ar(r)+s+o+e},decode(r,e){let{Err:t}=Re;e=z(e,void 0,"DER data");let n=0;if(r<0||r>255)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let o=e[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let f=e.subarray(n,n+c);if(f.length!==c)throw new t("tlv.decode: length bytes not complete");if(f[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let u of f)i=i<<8|u;if(n+=c,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(r){let{Err:e}=Re;if(Fn(r),r<qe)throw new e("integer: negative integers are not allowed");let t=Ar(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(r){let{Err:e}=Re;if(r.length<1)throw new e("invalid signature integer: empty");if(r[0]&128)throw new e("invalid signature integer: negative");if(r.length>1&&r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return At(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=Re,o=z(r,void 0,"signature"),{v:s,l:i}=n.decode(48,o);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:f,l:u}=n.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(f)}},hexFromSig(r){let{_tlv:e,_int:t}=Re,n=e.encode(2,t.encode(r.r)),o=e.encode(2,t.encode(r.s)),s=n+o;return e.encode(48,s)}};Object.freeze(Re._tlv);Object.freeze(Re._int);Object.freeze(Re);var qe=BigInt(0),lt=BigInt(1),Sc=BigInt(2),Xn=BigInt(3),Nd=BigInt(4);function _c(r,e={}){let t=Hn("weierstrass",r,e),n=t.Fp,o=t.Fn,s=t.CURVE,{h:i,n:a}=s;Oe(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c,allowInfinityPoint:f}=e;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=Ic(n,o);function l(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function d(O,p,b){if(f&&p.is0())return Uint8Array.of(0);let{x:v,y:w}=p.toAffine(),y=n.toBytes(v);if(Ce(b,"isCompressed"),b){l();let S=!n.isOdd(w);return re(Ac(S),y)}else return re(Uint8Array.of(4),y,n.toBytes(w))}function h(O){z(O,void 0,"Point");let{publicKey:p,publicKeyUncompressed:b}=u,v=O.length,w=O[0],y=O.subarray(1);if(f&&v===1&&w===0)return{x:n.ZERO,y:n.ZERO};if(v===p&&(w===2||w===3)){let S=n.fromBytes(y);if(!n.isValid(S))throw new Error("bad point: is not on curve, wrong x");let B=m(S),T;try{T=n.sqrt(B)}catch(M){let K=M instanceof Error?": "+M.message:"";throw new Error("bad point: is not on curve, sqrt error"+K)}l();let D=n.isOdd(T);return(w&1)===1!==D&&(T=n.neg(T)),{x:S,y:T}}else if(v===b&&w===4){let S=n.BYTES,B=n.fromBytes(y.subarray(0,S)),T=n.fromBytes(y.subarray(S,S*2));if(!g(B,T))throw new Error("bad point: is not on curve");return{x:B,y:T}}else throw new Error(`bad point: got length ${v}, expected compressed=${p} or uncompressed=${b}`)}let x=e.toBytes===void 0?d:e.toBytes,_=e.fromBytes===void 0?h:e.fromBytes;function m(O){let p=n.sqr(O),b=n.mul(p,O);return n.add(n.add(b,n.mul(O,s.a)),s.b)}function g(O,p){let b=n.sqr(p),v=m(O);return n.eql(b,v)}if(!g(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let E=n.mul(n.pow(s.a,Xn),Nd),A=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(E,A)))throw new Error("bad curve params: a or b");function L(O,p,b=!1){if(!n.isValid(p)||b&&n.is0(p))throw new Error(`bad point coordinate ${O}`);return p}function k(O){if(!(O instanceof I))throw new Error("Weierstrass Point expected")}function R(O){if(!c||!c.basises)throw new Error("no endo");return Rd(O,c.basises,o.ORDER)}function C(O,p,b,v,w){return b=new I(n.mul(b.X,O),b.Y,b.Z),p=kr(v,p),b=kr(w,b),p.add(b)}class I{static BASE=new I(s.Gx,s.Gy,n.ONE);static ZERO=new I(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(p,b,v){this.X=L("x",p),this.Y=L("y",b,!0),this.Z=L("z",v),Object.freeze(this)}static CURVE(){return s}static fromAffine(p){let{x:b,y:v}=p||{};if(!p||!n.isValid(b)||!n.isValid(v))throw new Error("invalid affine point");if(p instanceof I)throw new Error("projective point not allowed");return n.is0(b)&&n.is0(v)?I.ZERO:new I(b,v,n.ONE)}static fromBytes(p){let b=I.fromAffine(_(z(p,void 0,"point")));return b.assertValidity(),b}static fromHex(p){return I.fromBytes(Zt(p))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(p=8,b=!0){return U.createCache(this,p),b||this.multiply(Xn),this}assertValidity(){let p=this;if(p.is0()){if(e.allowInfinityPoint&&n.is0(p.X)&&n.eql(p.Y,n.ONE)&&n.is0(p.Z))return;throw new Error("bad point: ZERO")}let{x:b,y:v}=p.toAffine();if(!n.isValid(b)||!n.isValid(v))throw new Error("bad point: x or y not field elements");if(!g(b,v))throw new Error("bad point: equation left != right");if(!p.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:p}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(p)}equals(p){k(p);let{X:b,Y:v,Z:w}=this,{X:y,Y:S,Z:B}=p,T=n.eql(n.mul(b,B),n.mul(y,w)),D=n.eql(n.mul(v,B),n.mul(S,w));return T&&D}negate(){return new I(this.X,n.neg(this.Y),this.Z)}double(){let{a:p,b}=s,v=n.mul(b,Xn),{X:w,Y:y,Z:S}=this,B=n.ZERO,T=n.ZERO,D=n.ZERO,P=n.mul(w,w),M=n.mul(y,y),K=n.mul(S,S),F=n.mul(w,y);return F=n.add(F,F),D=n.mul(w,S),D=n.add(D,D),B=n.mul(p,D),T=n.mul(v,K),T=n.add(B,T),B=n.sub(M,T),T=n.add(M,T),T=n.mul(B,T),B=n.mul(F,B),D=n.mul(v,D),K=n.mul(p,K),F=n.sub(P,K),F=n.mul(p,F),F=n.add(F,D),D=n.add(P,P),P=n.add(D,P),P=n.add(P,K),P=n.mul(P,F),T=n.add(T,P),K=n.mul(y,S),K=n.add(K,K),P=n.mul(K,F),B=n.sub(B,P),D=n.mul(K,M),D=n.add(D,D),D=n.add(D,D),new I(B,T,D)}add(p){k(p);let{X:b,Y:v,Z:w}=this,{X:y,Y:S,Z:B}=p,T=n.ZERO,D=n.ZERO,P=n.ZERO,M=s.a,K=n.mul(s.b,Xn),F=n.mul(b,y),te=n.mul(v,S),ne=n.mul(w,B),oe=n.add(b,v),X=n.add(y,S);oe=n.mul(oe,X),X=n.add(F,te),oe=n.sub(oe,X),X=n.add(b,w);let be=n.add(y,B);return X=n.mul(X,be),be=n.add(F,ne),X=n.sub(X,be),be=n.add(v,w),T=n.add(S,B),be=n.mul(be,T),T=n.add(te,ne),be=n.sub(be,T),P=n.mul(M,X),T=n.mul(K,ne),P=n.add(T,P),T=n.sub(te,P),P=n.add(te,P),D=n.mul(T,P),te=n.add(F,F),te=n.add(te,F),ne=n.mul(M,ne),X=n.mul(K,X),te=n.add(te,ne),ne=n.sub(F,ne),ne=n.mul(M,ne),X=n.add(X,ne),F=n.mul(te,X),D=n.add(D,F),F=n.mul(be,X),T=n.mul(oe,T),T=n.sub(T,F),F=n.mul(oe,te),P=n.mul(be,P),P=n.add(P,F),new I(T,D,P)}subtract(p){return k(p),this.add(p.negate())}is0(){return this.equals(I.ZERO)}multiply(p){let{endo:b}=e;if(!o.isValidNot0(p))throw new RangeError("invalid scalar: out of range");let v,w,y=S=>U.cached(this,S,B=>Bt(I,B));if(b){let{k1neg:S,k1:B,k2neg:T,k2:D}=R(p),{p:P,f:M}=y(B),{p:K,f:F}=y(D);w=M.add(F),v=C(b.beta,P,K,S,T)}else{let{p:S,f:B}=y(p);v=S,w=B}return Bt(I,[v,w])[0]}multiplyUnsafe(p){let{endo:b}=e,v=this,w=p;if(!o.isValid(w))throw new RangeError("invalid scalar: out of range");if(w===qe||v.is0())return I.ZERO;if(w===lt)return v;if(U.hasCache(this))return this.multiply(w);if(b){let{k1neg:y,k1:S,k2neg:B,k2:T}=R(w),{p1:D,p2:P}=fc(I,v,S,T);return C(b.beta,D,P,y,B)}else return U.unsafe(v,w)}toAffine(p){let b=this,v=p,{X:w,Y:y,Z:S}=b;if(n.eql(S,n.ONE))return{x:w,y};let B=b.is0();v==null&&(v=B?n.ONE:n.inv(S));let T=n.mul(w,v),D=n.mul(y,v),P=n.mul(S,v);if(B)return{x:n.ZERO,y:n.ZERO};if(!n.eql(P,n.ONE))throw new Error("invZ was invalid");return{x:T,y:D}}isTorsionFree(){let{isTorsionFree:p}=e;return i===lt?!0:p?p(I,this):U.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:p}=e;return i===lt?this:p?p(I,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===lt?this.is0():this.clearCofactor().is0()}toBytes(p=!0){return Ce(p,"isCompressed"),this.assertValidity(),x(I,this,p)}toHex(p=!0){return Gt(this.toBytes(p))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let N=o.BITS,U=new er(I,e.endo?Math.ceil(N/2):N);return N>=8&&I.BASE.precompute(8),Object.freeze(I.prototype),Object.freeze(I),I}function Ac(r){return Uint8Array.of(r?2:3)}function Ic(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Ud(r,e={}){let{Fn:t}=r,n=e.randomBytes===void 0?_r:e.randomBytes,o=Object.assign(Ic(r.Fp,t),{seed:Math.max(zs(t.ORDER),16)});function s(h){try{let x=t.fromBytes(h);return t.isValidNot0(x)}catch{return!1}}function i(h,x){let{publicKey:_,publicKeyUncompressed:m}=o;try{let g=h.length;return x===!0&&g!==_||x===!1&&g!==m?!1:!!r.fromBytes(h)}catch{return!1}}function a(h){return h=h===void 0?n(o.seed):h,Ks(z(h,o.seed,"seed"),t.ORDER)}function c(h,x=!0){return r.BASE.multiply(t.fromBytes(h)).toBytes(x)}function f(h){let{secretKey:x,publicKey:_,publicKeyUncompressed:m}=o,g=t._lengths;if(!_t(h))return;let E=z(h,void 0,"key").length,A=E===_||E===m,L=E===x||!!g?.includes(E);if(!(A&&L))return A}function u(h,x,_=!0){if(f(h)===!0)throw new Error("first arg must be private key");if(f(x)===!1)throw new Error("second arg must be public key");let m=t.fromBytes(h);return r.fromBytes(x).multiply(m).toBytes(_)}let l={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},d=qn(a,c);return Object.freeze(l),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:d,Point:r,utils:l,lengths:o})}function Tc(r,e,t={}){let n=e;Dn(n),Oe(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let o=t.randomBytes===void 0?_r:t.randomBytes,s=t.hmac===void 0?(w,y)=>Ec(n,w,y):t.hmac,{Fp:i,Fn:a}=r,{ORDER:c,BITS:f}=a,{keygen:u,getPublicKey:l,getSharedSecret:d,utils:h,lengths:x}=Ud(r,t),_={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},m=c*Sc+lt<i.ORDER;function g(w){let y=c>>lt;return w>y}function E(w,y){if(!a.isValidNot0(y))throw new Error(`invalid signature ${w}: out of range 1..Point.Fn.ORDER`);return y}function A(){if(m)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function L(w,y){ni(y);let S=x.signature,B=y==="compact"?S:y==="recovered"?S+1:void 0;return z(w,B)}class k{r;s;recovery;constructor(y,S,B){if(this.r=E("r",y),this.s=E("s",S),B!=null){if(A(),![0,1,2,3].includes(B))throw new Error("invalid recovery id");this.recovery=B}Object.freeze(this)}static fromBytes(y,S=_.format){L(y,S);let B;if(S==="der"){let{r:M,s:K}=Re.toSig(z(y));return new k(M,K)}S==="recovered"&&(B=y[0],S="compact",y=y.subarray(1));let T=x.signature/2,D=y.subarray(0,T),P=y.subarray(T,T*2);return new k(a.fromBytes(D),a.fromBytes(P),B)}static fromHex(y,S){return this.fromBytes(Zt(y),S)}assertRecovery(){let{recovery:y}=this;if(y==null)throw new Error("invalid recovery id: must be present");return y}addRecoveryBit(y){return new k(this.r,this.s,y)}recoverPublicKey(y){let{r:S,s:B}=this,T=this.assertRecovery(),D=T===2||T===3?S+c:S;if(!i.isValid(D))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let P=i.toBytes(D),M=r.fromBytes(re(Ac((T&1)===0),P)),K=a.inv(D),F=C(z(y,void 0,"msgHash")),te=a.create(-F*K),ne=a.create(B*K),oe=r.BASE.multiplyUnsafe(te).add(M.multiplyUnsafe(ne));if(oe.is0())throw new Error("invalid recovery: point at infinify");return oe.assertValidity(),oe}hasHighS(){return g(this.s)}toBytes(y=_.format){if(ni(y),y==="der")return Zt(Re.hexFromSig(this));let{r:S,s:B}=this,T=a.toBytes(S),D=a.toBytes(B);return y==="recovered"?(A(),re(Uint8Array.of(this.assertRecovery()),T,D)):re(T,D)}toHex(y){return Gt(this.toBytes(y))}}Object.freeze(k.prototype),Object.freeze(k);let R=t.bits2int===void 0?function(y){if(y.length>8192)throw new Error("input is too large");let S=At(y),B=y.length*8-f;return B>0?S>>BigInt(B):S}:t.bits2int,C=t.bits2int_modN===void 0?function(y){return a.create(R(y))}:t.bits2int_modN,I=Tr(f);function N(w){return Yt("num < 2^"+f,w,qe,I),a.toBytes(w)}function U(w,y){return z(w,void 0,"message"),y?z(n(w),void 0,"prehashed message"):w}function O(w,y,S){let{lowS:B,prehash:T,extraEntropy:D}=ri(S,_);w=U(w,T);let P=C(w),M=a.fromBytes(y);if(!a.isValidNot0(M))throw new Error("invalid private key");let K=[N(M),N(P)];if(D!=null&&D!==!1){let oe=D===!0?o(x.secretKey):D;K.push(z(oe,void 0,"extraEntropy"))}let F=re(...K),te=P;function ne(oe){let X=R(oe);if(!a.isValidNot0(X))return;let be=a.inv(X),Pt=r.BASE.multiply(X).toAffine(),nr=a.create(Pt.x);if(nr===qe)return;let Mr=a.create(be*a.create(te+nr*M));if(Mr===qe)return;let gi=(Pt.x===nr?0:2)|Number(Pt.y<),bi=Mr;return B&&g(Mr)&&(bi=a.neg(Mr),gi^=1),new k(nr,bi,m?void 0:gi)}return{seed:F,k2sig:ne}}function p(w,y,S={}){let{seed:B,k2sig:T}=O(w,y,S);return $a(n.outputLen,a.BYTES,s)(B,T).toBytes(S.format)}function b(w,y,S,B={}){let{lowS:T,prehash:D,format:P}=ri(B,_);if(S=z(S,void 0,"publicKey"),y=U(y,D),!_t(w)){let M=w instanceof k?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+M)}L(w,P);try{let M=k.fromBytes(w,P),K=r.fromBytes(S);if(T&&M.hasHighS())return!1;let{r:F,s:te}=M,ne=C(y),oe=a.inv(te),X=a.create(ne*oe),be=a.create(F*oe),Pt=r.BASE.multiplyUnsafe(X).add(K.multiplyUnsafe(be));return Pt.is0()?!1:a.create(Pt.x)===F}catch{return!1}}function v(w,y,S={}){let{prehash:B}=ri(S,_);return y=U(y,B),k.fromBytes(w,"recovered").recoverPublicKey(y).toBytes()}return Object.freeze({keygen:u,getPublicKey:l,getSharedSecret:d,utils:h,lengths:x,Point:r,sign:p,verify:b,recoverPublicKey:v,Signature:k,hash:n})}var ii={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Fd={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Bc=BigInt(2);function Md(r){let e=ii.p,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),f=r*r*r%e,u=f*f*r%e,l=$(u,t,e)*u%e,d=$(l,t,e)*u%e,h=$(d,Bc,e)*f%e,x=$(h,o,e)*h%e,_=$(x,s,e)*x%e,m=$(_,a,e)*_%e,g=$(m,c,e)*m%e,E=$(g,a,e)*_%e,A=$(E,t,e)*u%e,L=$(A,i,e)*x%e,k=$(L,n,e)*f%e,R=$(k,Bc,e);if(!si.eql(si.sqr(R),r))throw new Error("Cannot find square root");return R}var si=Qt(ii.p,{sqrt:Md}),zd=_c(ii,{Fp:si,endo:Fd}),rr=Tc(zd,qa);function kc(r,e,t,n){let o=rt.digest(t instanceof Uint8Array?t:t.subarray());if(Gn(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),rr.verify(e,s,r,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new Lr(String(s))});try{return n?.signal?.throwIfAborted(),rr.verify(e,o.digest,r,{prehash:!1,format:"der"})}catch(s){throw new Lr(String(s))}}var Qn=class{type="secp256k1";raw;_key;constructor(e){this._key=Lc(e),this.raw=Dc(this._key)}toMultihash(){return Ie.digest($t(this))}toCID(){return G.createV1(114,this.toMultihash())}toString(){return ee.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Q(this.raw,e.raw)}verify(e,t,n){return kc(this._key,t,e,n)}};function Cc(r){return new Qn(r)}function Dc(r){return rr.Point.fromBytes(r).toBytes()}function Lc(r){try{return rr.Point.fromBytes(r),r}catch(e){throw new zr(String(e))}}function Pc(r){let{Type:e,Data:t}=Cr.decode(r.digest),n=t??new Uint8Array;switch(e){case ge.Ed25519:return xc(n);case ge.secp256k1:return Cc(n);case ge.ECDSA:return Ia(n);default:throw new or}}function $t(r){return Cr.encode({Type:ge[r.type],Data:r.raw})}var Oc=Symbol.for("nodejs.util.inspect.custom"),Kd=114,Pr=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Wr]=!0;toString(){return this.string==null&&(this.string=ee.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return G.createV1(Kd,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return Q(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return Q(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Oc](){return`PeerId(${this.toString()})`}},Jn=class extends Pr{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},eo=class extends Pr{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},to=class extends Pr{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},Hd=2336,Or=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Ie.digest(W(this.url))}[Oc](){return`PeerId(${this.url})`}[Wr]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return G.createV1(Hd,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=q(e)),e.toString()===this.toString())}};var qd=114,Rc=2336;function Vd(r){if($d(r))return new Jn({multihash:r});if(Wd(r))try{let e=Pc(r);if(e.type==="Ed25519")return new eo({multihash:r,publicKey:e});if(e.type==="secp256k1")return new to({multihash:r,publicKey:e})}catch{let t=q(r.digest);return new Or(new URL(t))}throw new Hr("Supplied PeerID Multihash is invalid")}function ro(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==qd&&r.code!==Rc)throw new Kr("Supplied PeerID CID is invalid");if(r.code===Rc){let e=q(r.multihash.digest);return new Or(new URL(e))}return Vd(r.multihash)}function Wd(r){return r.code===Ie.code}function $d(r){return r.code===rt.code}function jd(r){return r[Symbol.asyncIterator]!=null}function Gd(r){if(jd(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Nc=Gd;function Zd(r){return r[Symbol.asyncIterator]!=null}function Yd(r,e){let t=0;if(Zd(r))return(async function*(){for await(let c of r)yield e(c,t++)})();let n=xa(r),{value:o,done:s}=n.next();if(s===!0)return(function*(){})();let i=e(o,t++);if(typeof i.then=="function")return(async function*(){yield await i;for(let c of n)yield e(c,t++)})();let a=e;return(function*(){yield i;for(let c of n)yield a(c,t++)})()}var Uc=Yd;function Xd(r){return r[Symbol.asyncIterator]!=null}function Qd(r,e){return Xd(r)?(async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}})():(function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}})()}var Fc=Qd;var ai="/ipfs/bitswap/1.2.0";var j;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(j||(j={}));var ci;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(ci||(ci={}));(function(r){r.codec=()=>zt(ci)})(j||(j={}));var kt;(function(r){let e;r.codec=()=>(e==null&&(e=ze((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.cid!=null&&s.cid.byteLength>0&&(i.uint32(10),i.bytes(s.cid)),s.priority!=null&&s.priority!==0&&(i.uint32(16),i.int32(s.priority)),s.cancel!=null&&(i.uint32(24),i.bool(s.cancel)),s.wantType!=null&&(i.uint32(32),j.codec().encode(s.wantType,i)),s.sendDontHave!=null&&(i.uint32(40),i.bool(s.sendDontHave)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={cid:fe(0),priority:0},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{c.cid=s.bytes();break}case 2:{c.priority=s.int32();break}case 3:{c.cancel=s.bool();break}case 4:{c.wantType=j.codec().decode(s);break}case 5:{c.sendDontHave=s.bool();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.cid`,value:s.bytes()};break}case 2:{yield{field:`${a}.priority`,value:s.int32()};break}case 3:{yield{field:`${a}.cancel`,value:s.bool()};break}case 4:{yield{field:`${a}.wantType`,value:j.codec().decode(s)};break}case 5:{yield{field:`${a}.sendDontHave`,value:s.bool()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return Fe(s,r.codec())}r.encode=t;function n(s,i){return Ue(s,r.codec(),i)}r.decode=n;function o(s,i){return Me(s,r.codec(),i)}r.stream=o})(kt||(kt={}));var Rr;(function(r){let e;r.codec=()=>(e==null&&(e=ze((s,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),s.entries!=null&&s.entries.length>0)for(let c of s.entries)i.uint32(10),kt.codec().encode(c,i);s.full!=null&&(i.uint32(16),i.bool(s.full)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={entries:[]},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{if(a.limits?.entries!=null&&c.entries.length===a.limits.entries)throw new Ve('Decode error - repeated field "entries" had too many elements');c.entries.push(kt.codec().decode(s,s.uint32(),{limits:a.limits?.entries$}));break}case 2:{c.full=s.bool();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let f={entries:0},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{if(c.limits?.entries!=null&&f.entries===c.limits.entries)throw new Ve('Streaming decode error - repeated field "entries" had too many elements');for(let d of kt.codec().stream(s,s.uint32(),`${a}.entries[]`,{limits:c.limits?.entries$}))yield{...d,index:f.entries};f.entries++;break}case 2:{yield{field:`${a}.full`,value:s.bool()};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return Fe(s,r.codec())}r.encode=t;function n(s,i){return Ue(s,r.codec(),i)}r.decode=n;function o(s,i){return Me(s,r.codec(),i)}r.stream=o})(Rr||(Rr={}));var Dt;(function(r){let e;r.codec=()=>(e==null&&(e=ze((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.prefix!=null&&s.prefix.byteLength>0&&(i.uint32(10),i.bytes(s.prefix)),s.data!=null&&s.data.byteLength>0&&(i.uint32(18),i.bytes(s.data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={prefix:fe(0),data:fe(0)},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{c.prefix=s.bytes();break}case 2:{c.data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.prefix`,value:s.bytes()};break}case 2:{yield{field:`${a}.data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return Fe(s,r.codec())}r.encode=t;function n(s,i){return Ue(s,r.codec(),i)}r.decode=n;function o(s,i){return Me(s,r.codec(),i)}r.stream=o})(Dt||(Dt={}));var ve;(function(r){r.HaveBlock="HaveBlock",r.DoNotHaveBlock="DoNotHaveBlock"})(ve||(ve={}));var no;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DoNotHaveBlock=1]="DoNotHaveBlock"})(no||(no={}));(function(r){r.codec=()=>zt(no)})(ve||(ve={}));var Lt;(function(r){let e;r.codec=()=>(e==null&&(e=ze((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.cid!=null&&s.cid.byteLength>0&&(i.uint32(10),i.bytes(s.cid)),s.type!=null&&no[s.type]!==0&&(i.uint32(16),ve.codec().encode(s.type,i)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={cid:fe(0),type:ve.HaveBlock},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{c.cid=s.bytes();break}case 2:{c.type=ve.codec().decode(s);break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.cid`,value:s.bytes()};break}case 2:{yield{field:`${a}.type`,value:ve.codec().decode(s)};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return Fe(s,r.codec())}r.encode=t;function n(s,i){return Ue(s,r.codec(),i)}r.decode=n;function o(s,i){return Me(s,r.codec(),i)}r.stream=o})(Lt||(Lt={}));var Ct;(function(r){let e;r.codec=()=>(e==null&&(e=ze((s,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),s.wantlist!=null&&(i.uint32(10),Rr.codec().encode(s.wantlist,i)),s.blocks!=null&&s.blocks.length>0)for(let c of s.blocks)i.uint32(26),Dt.codec().encode(c,i);if(s.blockPresences!=null&&s.blockPresences.length>0)for(let c of s.blockPresences)i.uint32(34),Lt.codec().encode(c,i);s.pendingBytes!=null&&s.pendingBytes!==0&&(i.uint32(40),i.int32(s.pendingBytes)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={blocks:[],blockPresences:[],pendingBytes:0},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{c.wantlist=Rr.codec().decode(s,s.uint32(),{limits:a.limits?.wantlist});break}case 3:{if(a.limits?.blocks!=null&&c.blocks.length===a.limits.blocks)throw new Ve('Decode error - repeated field "blocks" had too many elements');c.blocks.push(Dt.codec().decode(s,s.uint32(),{limits:a.limits?.blocks$}));break}case 4:{if(a.limits?.blockPresences!=null&&c.blockPresences.length===a.limits.blockPresences)throw new Ve('Decode error - repeated field "blockPresences" had too many elements');c.blockPresences.push(Lt.codec().decode(s,s.uint32(),{limits:a.limits?.blockPresences$}));break}case 5:{c.pendingBytes=s.int32();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let f={blocks:0,blockPresences:0},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield*Rr.codec().stream(s,s.uint32(),`${a}.wantlist`,{limits:c.limits?.wantlist});break}case 3:{if(c.limits?.blocks!=null&&f.blocks===c.limits.blocks)throw new Ve('Streaming decode error - repeated field "blocks" had too many elements');for(let d of Dt.codec().stream(s,s.uint32(),`${a}.blocks[]`,{limits:c.limits?.blocks$}))yield{...d,index:f.blocks};f.blocks++;break}case 4:{if(c.limits?.blockPresences!=null&&f.blockPresences===c.limits.blockPresences)throw new Ve('Streaming decode error - repeated field "blockPresences" had too many elements');for(let d of Lt.codec().stream(s,s.uint32(),`${a}.blockPresences[]`,{limits:c.limits?.blockPresences$}))yield{...d,index:f.blockPresences};f.blockPresences++;break}case 5:{yield{field:`${a}.pendingBytes`,value:s.int32()};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return Fe(s,r.codec())}r.encode=t;function n(s,i){return Ue(s,r.codec(),i)}r.decode=n;function o(s,i){return Me(s,r.codec(),i)}r.stream=o})(Ct||(Ct={}));function Mc(r,e){for(let[t,n]of e.wantlist.entries()){let o=r.wantlist.get(t);o!=null&&(o.priority>n.priority&&(n.priority=o.priority),n.cancel=n.cancel??o.cancel,n.wantType=n.wantType??o.wantType,n.sendDontHave=n.sendDontHave??o.sendDontHave),r.wantlist.set(t,n)}for(let[t,n]of e.blockPresences.entries())r.blockPresences.set(t,n);for(let[t,n]of e.blocks.entries())r.blocks.set(t,n);return e.full&&!r.full&&(r.full=!0),r}var oo=class extends Error{static name="BlockTooLargeError";constructor(e="Block too large"){super(e),this.name="BlockTooLargeError"}};var Jd=4193648,eh=Jd+16;function*zc(r,e){let t=[...r.wantlist.values()],n=[...r.blockPresences.values()],o=[...r.blocks.values()],s=0,i=0,a=0,c=!1;for(;;){let f={wantlist:{full:r.full??!1,entries:[]},blockPresences:[],blocks:[],pendingBytes:0},u=Ct.encode(f).byteLength,{added:l,hasMore:d,newSize:h}=fi(o,f.blocks,a,e,u,th);a+=l,u=h;let x=d;({added:l,hasMore:d,newSize:h}=fi(n,f.blockPresences,i,e,u,rh)),i+=l,u=h;let _=d;if({added:l,hasMore:d,newSize:h}=fi(t,f.wantlist.entries,s,e,u,nh),s+=l,u=h,c=!x&&!_&&!d,c||(f.wantlist.full=!1),yield Ct.encode(f),c)break}}function fi(r,e,t,n,o,s){let i=0,a=!1;for(let c=t;c<r.length;c++){let f=r[c],u=s(f);if(u>eh)throw new oo("Cannot send block as after encoding it is over the max message size");let l=o+u;if(l>n){a=!0;break}e.push(f),i++,o=l}return{hasMore:a,added:i,newSize:o}}function th(r){return ui(3,Dt.encode(r))}function rh(r){return ui(4,Lt.encode(r))}function nh(r){return ui(1,kt.encode(r))}function ui(r,e){let t=V(r),n=V(e.byteLength);return t+n+e.byteLength}function hh(r){if($r(r))return r;if(Bn(r))return ro(r);if(dn(r)||Array.isArray(r))return r;throw new Se(`Peer ${r} was not a CID, a Multiaddr or a Multiaddr[]`)}var so=class extends Ne{log;libp2p;routing;protocols;running;maxInboundStreams;maxOutboundStreams;messageReceiveTimeout;messageSendTimeout;registrarIds;metrics;sendQueue;runOnLimitedConnections;maxOutgoingMessageSize;maxIncomingMessageSize;constructor(e,t={}){super(),this.log=e.logger.forComponent("helia:bitswap:network"),this.libp2p=e.libp2p,this.routing=e.routing,this.protocols=t.protocols??[ai],this.registrarIds=[],this.running=!1,this._onStream=this._onStream.bind(this),this.maxInboundStreams=t.maxInboundStreams??1024,this.maxOutboundStreams=t.maxOutboundStreams??1024,this.messageReceiveTimeout=t.messageReceiveTimeout??1e4,this.messageSendTimeout=t.messageSendTimeout??1e4,this.runOnLimitedConnections=t.runOnLimitedConnections??!1,this.maxIncomingMessageSize=t.maxIncomingMessageSize??4194304,this.maxOutgoingMessageSize=t.maxOutgoingMessageSize??t.maxIncomingMessageSize??4194304,this.metrics={blocksSent:e.metrics?.registerCounter("helia_bitswap_sent_blocks_total"),dataSent:e.metrics?.registerCounter("helia_bitswap_sent_data_bytes_total")},this.sendQueue=new In({concurrency:t.messageSendConcurrency??50,metrics:e.metrics,metricName:"helia_bitswap_message_send_queue"})}async start(){if(this.running)return;this.running=!0,await this.libp2p.handle(this.protocols,this._onStream,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnections});let e={onConnect:t=>{this.safeDispatchEvent("peer:connected",{detail:t})},onDisconnect:t=>{this.safeDispatchEvent("peer:disconnected",{detail:t})}};this.registrarIds=[];for(let t of this.protocols)this.registrarIds.push(await this.libp2p.register(t,e));this.libp2p.getConnections().forEach(t=>{this.safeDispatchEvent("peer:connected",{detail:t.remotePeer})})}async stop(){if(this.running=!1,await this.libp2p.unhandle(this.protocols),this.registrarIds!=null){for(let e of this.registrarIds)this.libp2p.unregister(e);this.registrarIds=[]}}_onStream(e,t){this.running&&Promise.resolve().then(async()=>{this.log("incoming new bitswap %s stream from %p",e.protocol,t.remotePeer);let n=()=>{e.status==="open"?e.abort(new qr(`Incoming Bitswap stream timed out after ${this.messageReceiveTimeout}ms`)):this.log("stream aborted with status %s",e.status)},o=AbortSignal.timeout(this.messageReceiveTimeout);o.addEventListener("abort",n),await e.close({signal:o});let s=pn();e.addEventListener("message",i=>{s.push(i.data)}),e.addEventListener("remoteCloseWrite",()=>{s.end()}),e.addEventListener("close",i=>{i.error!=null&&s.end(i.error)});for await(let i of br(s,{maxDataLength:this.maxIncomingMessageSize}))try{let a=Ct.decode(i);this.log("incoming new bitswap %s message from %p on stream",e.protocol,t.remotePeer,e.id),this.safeDispatchEvent("bitswap:message",{detail:{peer:t.remotePeer,message:a,connection:t}}),o.removeEventListener("abort",n),o=AbortSignal.timeout(this.messageReceiveTimeout),o.addEventListener("abort",n)}catch(a){this.log.error("error reading incoming bitswap message from %p on stream - %e",t.remotePeer,e.id,a),e.abort(a);break}}).catch(n=>{this.log.error("error handling incoming stream from %p - %e",t.remotePeer,n),e.abort(n)})}async*findProviders(e,t){t?.onProgress?.(new ce("bitswap:find-providers",e));for await(let n of this.routing.findProviders(e,t)){if(!await this.libp2p.isDialable(n.multiaddrs,{runOnLimitedConnection:this.runOnLimitedConnections})){this.log("skipping peer %p as they are not dialable - %a",n.id,n.multiaddrs);continue}t?.onProgress?.(new ce("bitswap:found-provider",{type:"bitswap",cid:e,provider:n,router:n.router})),yield n}}async findAndConnect(e,t){t?.providers!=null&&await Promise.all(t.providers.map(async n=>this.connectTo(n,t).catch(o=>{this.log.error("could not connect to supplied provider - %e",o)}))),await Nc(Uc(Fc(this.findProviders(e,t),t?.maxProviders??3),async n=>this.connectTo(n.id,t))).catch(n=>{this.log.error(n)})}async sendMessage(e,t,n){if(!this.running)throw new Error("network isn't running");let o=this.sendQueue.queue.find(s=>e.equals(s.options.peerId)&&s.status==="queued");if(o!=null){o.options.message=Mc(o.options.message,t),await o.join(n);return}await this.sendQueue.add(async s=>{let i=s.message;if(i==null)throw new Se("No message to send");this.log("sendMessage to %p",e),s.onProgress?.(new ce("bitswap:send-wantlist",e));let a=await this.libp2p.dialProtocol(e,ai,s);await a.closeRead(s);try{for(let c of zc(i,this.maxOutgoingMessageSize))a.send(An.single(c))||await a.onDrain(s);await a.close(s)}catch(c){this.log.error("error sending message to %p - %e",e,c),s?.onProgress?.(new ce("bitswap:send-wantlist:error",{peer:e,error:c})),a.abort(c)}this._updateSentStats(i.blocks)},{onProgress:n?.onProgress,peerId:e,signal:n?.signal??AbortSignal.timeout(this.messageSendTimeout),message:t})}async connectTo(e,t){if(!this.running)throw new Vr("Network isn't running");return e=hh(e),t?.onProgress?.(new ce("bitswap:dial",e)),this.libp2p.dial(e,t)}_updateSentStats(e){let t=0;for(let n of e.values())t+=n.data.byteLength;this.metrics.dataSent?.increment(t),this.metrics.blocksSent?.increment(e.size)}};function io(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}var Nr=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),{key:t,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return io(this.map.entries(),e=>[e[1].key,e[1].value])}forEach(e){this.map.forEach((t,n)=>{e(t.value,t.key,this)})}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),{key:e,value:t})}keys(){return io(this.map.values(),e=>e.key)}values(){return io(this.map.values(),e=>e.value)}get size(){return this.map.size}};var li=class extends Nr{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Ur(r){let{name:e,metrics:t}=r,n;return t!=null?n=new li({name:e,metrics:t}):n=new Nr,n}var Qe=class{full;pendingBytes;wantlist;blocks;blockPresences;constructor(e=!1,t=0){this.full=e,this.wantlist=new Map,this.blocks=new Map,this.blockPresences=new Map,this.pendingBytes=0}addWantlistEntry(e,t){let n=pt.encode(e.multihash.bytes);this.wantlist.set(n,t)}addBlockPresence(e,t){let n=pt.encode(e.multihash.bytes);this.blockPresences.set(n,t)}addBlock(e,t){let n=pt.encode(e.multihash.bytes);this.blocks.set(n,t)}};function ph(r){let e=new Uint8Array(r.reduce((n,o)=>n+V(o),0)),t=0;for(let n of r)e=Yr(n,e,t),t+=V(n);return e}var Kc=ph;function di(r){return Kc([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var ao=class{peerId;blockstore;network;wants;exchangeCount;bytesSent;bytesReceived;lastExchange;maxSizeReplaceHasWithBlock;log;doNotResendBlockWindow;maxWantListSize;constructor(e,t){this.peerId=e.peerId,this.blockstore=e.blockstore,this.network=e.network,this.wants=new Map,this.log=e.logger.forComponent(`helia:bitswap:ledger:${e.peerId}`),this.exchangeCount=0,this.bytesSent=0,this.bytesReceived=0,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock??1024,this.doNotResendBlockWindow=t.doNotResendBlockWindow??5e3,this.maxWantListSize=t.maxWantListSize??1024}sentBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesSent+=e}receivedBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesReceived+=e}debtRatio(){return this.bytesSent/(this.bytesReceived+1)}removeExpiredWants(){this.wants.forEach((e,t)=>{e.expires!=null&&e.expires<Date.now()&&this.wants.delete(t)})}addWants(e){if(e==null)return;e.full===!0&&this.wants.forEach((n,o)=>{n.status==="want"&&this.wants.delete(o)});for(let n of e.entries){let o=G.decode(n.cid),s=q(o.multihash.bytes,"base64");if(n.cancel===!0)this.log("peer %p cancelled want of block for %c",this.peerId,o),this.wants.delete(s);else{n.wantType===j.WantHave?this.log("peer %p wanted block presence for %c",this.peerId,o):this.log("peer %p wanted block for %c",this.peerId,o);let i=this.wants.get(s);if(i!=null){let a=i.status==="sent"||i.status==="sending",c=i.wantType===j.WantHave&&(n.wantType==null||n.wantType===j.WantBlock);a&&c&&(i.status="want"),i.priority=n.priority,i.wantType=n.wantType??j.WantBlock,i.sendDontHave=n.sendDontHave??!1;continue}this.wants.set(s,{cid:o,priority:n.priority,wantType:n.wantType??j.WantBlock,sendDontHave:n.sendDontHave??!1,status:"want",created:Date.now()})}}let t=[...this.wants.entries()].filter(([n,o])=>o.status==="want");t.length>this.maxWantListSize&&this.truncateWants(t)}truncateWants(e){e=e.sort((n,o)=>n[1].created<o[1].created?-1:o[1].created<n[1].created?1:0).sort((n,o)=>n[1].haveBlock===!1?-1:o[1].haveBlock===!1?1:0).sort((n,o)=>n[1].priority<o[1].priority?-1:o[1].priority<n[1].priority?1:0);let t=e.length-this.maxWantListSize;for(let n=0;n<t;n++)this.wants.delete(e[n][0])}getWants(){return[...this.wants.values()]}hasWant(e){let t=q(e.multihash.bytes,"base64");return this.wants.has(t)}async sendBlocksToPeer(e){let t=new Qe,n=new Set;this.removeExpiredWants();let o=[...this.wants.entries()].filter(([s,i])=>i.status==="want");o.forEach(([s,i])=>{i.status="sending"});for(let[s,i]of o)try{let a=await Ea(this.blockstore.get(i.cid,e));if(i.status!=="sending")continue;i.wantType===j.WantHave?a.byteLength<this.maxSizeReplaceHasWithBlock?(this.log("sending have and block for %c",i.cid),n.add(s),t.addBlock(i.cid,{data:a,prefix:di(i.cid)})):(this.log("sending have for %c",i.cid),t.addBlockPresence(i.cid,{cid:i.cid.bytes,type:ve.HaveBlock})):(this.log("sending block for %c",i.cid),n.add(s),t.addBlock(i.cid,{data:a,prefix:di(i.cid)})),i.status="sent",i.expires=Date.now()+this.doNotResendBlockWindow}catch(a){if(a.name!=="NotFoundError")throw a;if(i.status="want",i.haveBlock=!1,this.log("do not have block for %c",i.cid),!i.sendDontHave||i.sentDoNotHave===!0)continue;i.sentDoNotHave=!0,t.addBlockPresence(i.cid,{cid:i.cid.bytes,type:ve.DoNotHaveBlock})}(t.blocks.size>0||t.blockPresences.size>0)&&(this.log("sending message"),await this.network.sendMessage(this.peerId,t,e),this.log("sent message"),this.sentBytes([...t.blocks.values()].reduce((s,i)=>s+i.data.byteLength,0)))}};var co=class{blockstore;network;ledgerMap;maxSizeReplaceHasWithBlock;doNotResendBlockWindow;maxWantListSize;log;logger;constructor(e,t={}){this.blockstore=e.blockstore,this.network=e.network,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock,this.doNotResendBlockWindow=t.doNotResendBlockWindow,this.maxWantListSize=t.maxWantListSize,this.log=e.logger.forComponent("helia:bitswap:peer-want-lists"),this.logger=e.logger,this.ledgerMap=Ur({name:"helia_bitswap_ledger_map",metrics:e.metrics}),this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.connection.remotePeer,n.detail.message).catch(o=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.connection.remotePeer,o)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}ledgerForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return{peer:t.peerId,value:t.debtRatio(),sent:t.bytesSent,received:t.bytesReceived,exchanged:t.exchangeCount}}wantListForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return t.removeExpiredWants(),t.getWants()}peers(){return Array.from(this.ledgerMap.values()).map(e=>e.peerId)}async receiveMessage(e,t){let n=this.ledgerMap.get(e);n==null&&(n=new ao({peerId:e,blockstore:this.blockstore,network:this.network,logger:this.logger},{maxSizeReplaceHasWithBlock:this.maxSizeReplaceHasWithBlock,doNotResendBlockWindow:this.doNotResendBlockWindow,maxWantListSize:this.maxWantListSize}),this.ledgerMap.set(e,n)),n.receivedBytes(t.blocks?.reduce((o,s)=>o+s.data.byteLength,0)??0),n.removeExpiredWants(),n.addWants(t.wantlist),this.log("send blocks to peer"),await n.sendBlocksToPeer()}async receivedBlock(e,t){let n=[];for(let o of this.ledgerMap.values())o.hasWant(e)&&n.push(o);await Promise.all(n.map(async o=>o.sendBlocksToPeer(t)))}peerDisconnected(e){this.ledgerMap.delete(e)}};var hi=class extends Tn{name="bitswap-session";wantList;network;libp2p;constructor(e,t){super(e,{...t,name:"helia:bitswap:session"}),this.wantList=e.wantList,this.network=e.network,this.libp2p=e.libp2p}async queryProvider(e,t,n){if(n.signal?.aborted===!0)throw new nn(`Signal to want session block for CID ${e} from peer ${t} was aborted prior to want`);let o=ro(t.peerId);this.log("sending WANT-BLOCK for %c to %p",e,o);let s=await this.wantList.wantSessionBlock(e,o,n);if(this.log("%p %s %c",t,s.has?"has":"does not have",e),s.has){if(s.block!=null)return s.block;throw new Error("Provider has block but did not send it to us")}throw new Error("Provider did not have block")}async*findNewProviders(e,t={}){for await(let n of this.network.findProviders(e,t))yield{peerId:n.id,router:n.router,toString:()=>`Bitswap(${n.id})`,fallback:n.fallback}}toFilterKey(e){return e.peerId.multihash.bytes}equals(e,t){return e.peerId.equals(t.peerId)}async convertToProvider(e,t,n){if(Bn(e))return{peerId:e,router:t,toString:()=>`Bitswap(${e})`,fallback:!1};if(await this.libp2p.isDialable(e)!==!1)try{let o=await this.libp2p.dial(e,n);return{peerId:o.remotePeer.toCID(),router:t,toString:()=>`Bitswap(${o.remotePeer})`,fallback:!1}}catch{}}emitFoundProviderProgressEvent(e,t,n){n?.onProgress?.(new ce("bitswap:found-provider",{type:"bitswap",cid:e,provider:{id:t.peerId,multiaddrs:[],router:t.router,fallback:t.fallback},router:t.router}))}};function Hc(r,e){return new hi(r,e)}var fo=class{blocksReceived;duplicateBlocksReceived;dataReceived;duplicateDataReceived;constructor(e){this.blocksReceived=e.metrics?.registerMetricGroup("helia_bitswap_received_blocks"),this.duplicateBlocksReceived=e.metrics?.registerMetricGroup("helia_bitswap_duplicate_received_blocks"),this.dataReceived=e.metrics?.registerMetricGroup("helia_bitswap_data_received_bytes"),this.duplicateDataReceived=e.metrics?.registerMetricGroup("helia_bitswap_duplicate_data_received_bytes")}updateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.blocksReceived?.increment(n)}updateDuplicateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateBlocksReceived?.increment(n)}updateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.dataReceived?.increment(n)}updateDuplicateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateDataReceived?.increment(n)}};var uo=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function Fr(r,e,t,n){let o=new uo(n?.errorMessage);n?.errorCode!=null&&(o.code=n.errorCode);let s=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(o):new Promise((i,a)=>{function c(){mi(t,"abort",l),mi(r,e,f),mi(r,s,u)}let f=d=>{try{if(n?.filter?.(d)===!1)return}catch(h){c(),a(h);return}c(),i(d)},u=d=>{if(c(),d instanceof Error){a(d);return}a(d.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},l=()=>{c(),a(o)};pi(t,"abort",l),pi(r,e,f),pi(r,s,u)})}function pi(r,e,t){r!=null&&(qc(r)?r.addEventListener(e,t):r.addListener(e,t))}function mi(r,e,t){r!=null&&(qc(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function qc(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}function mh(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let e=[];for(;r.length>0;){let t=mt(r);e.push(t),r=r.slice(V(t))}return e}var Vc=mh;var lo=class extends Ne{peers;wants;network;log;sendWantlistDebounce;sendMessagesTimeout;getHasher;sendingMessages;constructor(e,t={}){super(),this.peers=Ur({name:"helia_bitswap_peers",metrics:e.metrics}),this.wants=ya({name:"helia_bitswap_wantlist",metrics:e.metrics}),this.network=e.network,this.sendWantlistDebounce=t.sendWantlistDebounce??10,this.log=e.logger.forComponent("helia:bitswap:wantlist"),this.getHasher=e.getHasher,this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.connection,n.detail.message).catch(o=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.connection.remotePeer,o)})}),this.network.addEventListener("peer:connected",n=>{this.peerConnected(n.detail).catch(o=>{this.log.error("error processing newly connected bitswap peer %p - %e",n.detail,o)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}async addEntry(e,t){let n=q(e.multihash.bytes,"base64"),o=this.wants.get(n);o==null&&(o={cid:e,priority:t.priority??1,wantType:t.wantType??j.WantBlock,cancel:!1,sendDontHave:!0,onProgress:[]},this.wants.set(n,o)),t.onProgress!=null&&o.onProgress.push({onProgress:t.onProgress,signal:t.signal}),o.wantType===j.WantHave&&t.wantType===j.WantBlock&&(o.wantType=j.WantBlock),await this.sendMessagesDebounced();try{return t.wantType===j.WantBlock?(await Fr(this,"block",t?.signal,{filter:a=>Q(e.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await Fr(this,"presence",t?.signal,{filter:i=>Q(e.multihash.digest,i.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail}finally{t.signal?.aborted===!0&&(this.log("want for %c was aborted, cancelling want",e),o.cancel=!0,await this.sendMessagesDebounced())}}async sendMessagesDebounced(){await this.sendingMessages?.promise,clearTimeout(this.sendMessagesTimeout),this.sendMessagesTimeout=setTimeout(()=>{this.sendMessages().catch(e=>{this.log("error sending messages to peers - %e",e)})},this.sendWantlistDebounce)}async sendMessages(){this.sendingMessages=De(),await Promise.all([...this.peers.entries()].map(async([e,t])=>{let n=new Set,o=new Qe;for(let[s,i]of this.wants.entries())t.has(s)||i.cancel||(n.add(s),o.addWantlistEntry(i.cid,{cid:i.cid.bytes,priority:i.priority,wantType:i.wantType,cancel:i.cancel,sendDontHave:i.sendDontHave}));if(o.wantlist.size!==0)try{await this.network.sendMessage(e,o,{onProgress:s=>{this.wants.forEach(({onProgress:i})=>{i.forEach(({onProgress:a})=>{a(s)})})}});for(let s of n)t.add(s)}catch(s){this.log.error("error sending full wantlist to new peer - %e",s)}})).catch(e=>{this.log.error("error sending messages - %e",e)});for(let[e,t]of this.wants)if(t.cancel){this.wants.delete(e);for(let n of this.peers.values())n.delete(e)}this.sendingMessages.resolve()}has(e){let t=q(e.multihash.bytes,"base64");return this.wants.has(t)}async wantSessionPresence(e,t,n={}){let o=new Qe;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:j.WantHave,priority:1}),await this.network.sendMessage(t,o,n),(await Fr(this,"presence",n.signal,{filter:i=>t.equals(i.detail.sender)&&Q(e.multihash.digest,i.detail.cid.multihash.digest)})).detail}async wantBlock(e,t={}){return this.addEntry(e,{...t,wantType:j.WantBlock})}async wantSessionBlock(e,t,n={}){let o=new Qe;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:j.WantBlock,priority:1}),await this.network.sendMessage(t,o,n),(await Fr(this,"presence",n.signal,{filter:i=>t.equals(i.detail.sender)&&Q(e.multihash.digest,i.detail.cid.multihash.digest)})).detail}async receivedBlock(e,t){let n=q(e.multihash.bytes,"base64"),o=this.wants.get(n);o!=null&&(o.cancel=!0,await this.sendMessagesDebounced())}async receiveMessage(e,t){this.log("received message from %p with %d blocks",e.remotePeer,t.blocks.length);let n=!1;for(let o of t.blocks){if(o.prefix==null||o.data==null)continue;let s=Vc(o.prefix),i=s[0],a=s[1],c=s[2],f=s[3],u=c===rt.code?rt:await this.getHasher(c);if(u==null){this.log.error("unknown hash algorithm",c);continue}let l=u.digest(o.data,{truncate:f});l.then!=null&&(l=await l);let d=G.create(i===0?0:1,a,l);this.log("received block from %p for %c",e.remotePeer,d),this.safeDispatchEvent("block",{detail:{sender:e.remotePeer,cid:d,block:o.data,connection:e}}),this.safeDispatchEvent("presence",{detail:{sender:e.remotePeer,cid:d,has:!0,block:o.data}});let h=q(d.multihash.bytes,"base64"),x=this.wants.get(h);x!=null&&(x.cancel=!0,n=!0)}for(let{cid:o,type:s}of t.blockPresences){let i=G.decode(o);this.log("received %s from %p for %c",s,e.remotePeer,i),this.safeDispatchEvent("presence",{detail:{sender:e.remotePeer,cid:i,has:s===ve.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(e){let t=new Set,n=new Qe(!0);for(let[o,s]of this.wants.entries())s.cancel||(t.add(o),n.addWantlistEntry(s.cid,{cid:s.cid.bytes,priority:1,wantType:j.WantBlock,cancel:!1,sendDontHave:!1}));if(n.wantlist.size===0){this.peers.set(e,t);return}try{await this.network.sendMessage(e,n,{onProgress:o=>{this.wants.forEach(({onProgress:s})=>{s.forEach(({onProgress:i})=>{i(o)})})}}),this.peers.set(e,t)}catch(o){this.log.error("error sending full wantlist to new peer %p - %e",e,o)}}peerDisconnected(e){this.peers.delete(e)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}};var ho=class{log;logger;stats;network;blockstore;peerWantLists;wantList;libp2p;constructor(e,t={}){this.logger=e.logger,this.log=e.logger.forComponent("helia:bitswap"),this.blockstore=e.blockstore,this.libp2p=e.libp2p,this.stats=new fo(e),this.network=new so(e,t),this.peerWantLists=new co({...e,network:this.network},t),this.wantList=new lo({...e,network:this.network},t)}createSession(e={}){return Hc({wantList:this.wantList,network:this.network,logger:this.logger,libp2p:this.libp2p},e)}async want(e,t={}){let n=new AbortController,o=wi([n.signal,t.signal]);n.signal,this.network.findAndConnect(e,{...t,signal:o}).catch(s=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c - %e",e,s)});try{let s=await this.wantList.wantBlock(e,{...t,signal:o});return t.onProgress?.(new ce("bitswap:block",{cid:e,sender:s.connection.remotePeer})),s.block}finally{n.abort(),o.clear()}}async notify(e,t={}){await Promise.all([this.peerWantLists.receivedBlock(e,t),this.wantList.receivedBlock(e,t)])}getWantlist(){return[...this.wantList.wants.values()].filter(e=>!e.cancel).map(e=>({cid:e.cid,priority:e.priority,wantType:e.wantType}))}getPeerWantlist(e){return this.peerWantLists.wantListForPeer(e)}async start(){this.wantList.start(),await this.network.start()}async stop(){this.wantList.stop(),await this.network.stop()}};var po=class{name="bitswap";bitswap;started;constructor(e,t={}){this.bitswap=new ho(e,t),this.started=!1}isStarted(){return this.started}async start(){await this.bitswap.start(),this.started=!0}async stop(){await this.bitswap.stop(),this.started=!1}async announce(e,t){await this.bitswap.notify(e,t)}async retrieve(e,t={}){return this.bitswap.want(e,{...t,onProgress:function(o){if(t?.onProgress!=null)if(t.onProgress(o),o.type==="connection:open"){if(!$r(o.detail))return;t.onProgress(new ce("helia:block-broker:connect",{broker:"bitswap",type:"connect",provider:o.detail.toCID(),cid:e}))}else o.type==="connection:opened"?t.onProgress(new ce("helia:block-broker:connected",{broker:"bitswap",type:"connected",provider:o.detail.remotePeer.toCID(),address:o.detail.remoteAddr,cid:e})):o.type==="bitswap:send-wantlist"?t.onProgress(new ce("helia:block-broker:request-block",{broker:"bitswap",type:"request-block",provider:o.detail.toCID(),cid:e})):o.type==="bitswap:block"&&t.onProgress(new ce("helia:block-broker:receive-block",{broker:"bitswap",type:"receive-block",provider:o.detail.sender.toCID(),cid:e}))}})}createSession(e){let t=this.bitswap.createSession(e);return{name:"bitswap-session",addPeer:async(n,o)=>{await t.addPeer(n,o)},announce:async(n,o)=>{await this.bitswap.notify(n,o)},retrieve:async(n,o)=>t.retrieve(n,o)}}};function gh(r,e={}){let t={name:"bitswap",start:async n=>{if(n.status==="starting"&&!n.hasBlockBroker("bitswap")){let o=new po(n,e);await yi(o),n.addBlockBroker(o)}}};return r.addMixin(t),r}return Zc(bh);})();
|
|
3
3
|
/*! Bundled license information:
|
|
4
4
|
|
|
5
5
|
@noble/curves/utils.js:
|