@libp2p/webtransport 5.0.51-da78fa851 → 5.0.51-e8398d97e

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.min.js CHANGED
@@ -1,5 +1,5 @@
1
1
  (function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Libp2PWebtransport = factory()}(typeof self !== 'undefined' ? self : this, function () {
2
- "use strict";var Libp2PWebtransport=(()=>{var Rs=Object.defineProperty;var Pf=Object.getOwnPropertyDescriptor;var Rf=Object.getOwnPropertyNames;var Of=Object.prototype.hasOwnProperty;var It=(e,t)=>{for(var r in t)Rs(e,r,{get:t[r],enumerable:!0})},Uf=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Rf(t))!Of.call(e,s)&&s!==r&&Rs(e,s,{get:()=>t[s],enumerable:!(n=Pf(t,s))||n.enumerable});return e};var Kf=e=>Uf(Rs({},"__esModule",{value:!0}),e);var Vp={};It(Vp,{webTransport:()=>Hp});var En=class extends Error{static name="UnexpectedPeerError";constructor(t="Unexpected Peer"){super(t),this.name="UnexpectedPeerError"}},tr=class extends Error{static name="InvalidCryptoExchangeError";constructor(t="Invalid crypto exchange"){super(t),this.name="InvalidCryptoExchangeError"}},et=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},er=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}};var Sn=class extends Error{static name="MuxerClosedError";constructor(t="The muxer is closed"){super(t),this.name="MuxerClosedError"}};var vn=class extends Error{static name="StreamResetError";constructor(t="The stream has been reset"){super(t),this.name="StreamResetError"}};var Ce=class extends Error{static name="StreamStateError";constructor(t="The stream is in an invalid state"){super(t),this.name="StreamStateError"}},Nr=class extends Error{static name="StreamBufferError";constructor(t="The stream buffer was full"){super(t),this.name="StreamBufferError"}};var Mr=class extends Error{static name="InvalidMultiaddrError";constructor(t="Invalid multiaddr"){super(t),this.name="InvalidMultiaddrError"}},An=class extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}},Bn=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}};var Le=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var _n=class extends Event{data;constructor(t,r){super("message",r),this.data=t}},rr=class extends Event{error;local;constructor(t,r,n){super("close",n),this.error=r,this.local=t}},In=class extends rr{constructor(t,r){super(!0,t,r)}},Cn=class extends rr{constructor(t,r){super(!1,t,r)}};var Os=Symbol.for("@libp2p/peer-id");var Da=Symbol.for("@libp2p/transport");var Ta;(function(e){e[e.FATAL_ALL=0]="FATAL_ALL",e[e.NO_FATAL=1]="NO_FATAL"})(Ta||(Ta={}));var nr=class extends EventTarget{#t=new Map;constructor(){super()}listenerCount(t){let r=this.#t.get(t);return r==null?0:r.length}addEventListener(t,r,n){super.addEventListener(t,r,n);let s=this.#t.get(t);s==null&&(s=[],this.#t.set(t,s)),s.push({callback:r,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(t,r,n){super.removeEventListener(t.toString(),r??null,n);let s=this.#t.get(t);s!=null&&(s=s.filter(({callback:o})=>o!==r),this.#t.set(t,s))}dispatchEvent(t){let r=super.dispatchEvent(t),n=this.#t.get(t.type);return n==null||(n=n.filter(({once:s})=>!s),this.#t.set(t.type,n)),r}safeDispatchEvent(t,r={}){return this.dispatchEvent(new CustomEvent(t,r))}};var Ln=Symbol.for("@libp2p/service-capabilities"),jp=Symbol.for("@libp2p/service-dependencies");var ks={};It(ks,{base58btc:()=>ct,base58flickr:()=>zf});var Em=new Uint8Array(0);function Pa(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0}function Gt(e){if(e instanceof Uint8Array&&e.constructor.name==="Uint8Array")return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")}function Ra(e){return new TextEncoder().encode(e)}function Oa(e){return new TextDecoder().decode(e)}function Nf(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var s=0;s<e.length;s++){var o=e.charAt(s),i=o.charCodeAt(0);if(r[i]!==255)throw new TypeError(o+" is ambiguous");r[i]=s}var a=e.length,c=e.charAt(0),f=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function l(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var w=0,g=0,x=0,B=p.length;x!==B&&p[x]===0;)x++,w++;for(var E=(B-x)*u+1>>>0,P=new Uint8Array(E);x!==B;){for(var N=p[x],k=0,M=E-1;(N!==0||k<g)&&M!==-1;M--,k++)N+=256*P[M]>>>0,P[M]=N%a>>>0,N=N/a>>>0;if(N!==0)throw new Error("Non-zero carry");g=k,x++}for(var U=E-g;U!==E&&P[U]===0;)U++;for(var S=c.repeat(w);U<E;++U)S+=e.charAt(P[U]);return S}function h(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var w=0;if(p[w]!==" "){for(var g=0,x=0;p[w]===c;)g++,w++;for(var B=(p.length-w)*f+1>>>0,E=new Uint8Array(B);p[w];){var P=r[p.charCodeAt(w)];if(P===255)return;for(var N=0,k=B-1;(P!==0||N<x)&&k!==-1;k--,N++)P+=a*E[k]>>>0,E[k]=P%256>>>0,P=P/256>>>0;if(P!==0)throw new Error("Non-zero carry");x=N,w++}if(p[w]!==" "){for(var M=B-x;M!==B&&E[M]===0;)M++;for(var U=new Uint8Array(g+(B-M)),S=g;M!==B;)U[S++]=E[M++];return U}}}function d(p){var w=h(p);if(w)return w;throw new Error(`Non-${t} character`)}return{encode:l,decodeUnsafe:h,decode:d}}var Mf=Nf,kf=Mf,Ka=kf;var Us=class{name;prefix;baseEncode;constructor(t,r,n){this.name=t,this.prefix=r,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},Ks=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,r,n){this.name=t,this.prefix=r;let s=r.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return Na(this,t)}},Ns=class{decoders;constructor(t){this.decoders=t}or(t){return Na(this,t)}decode(t){let r=t[0],n=this.decoders[r];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Na(e,t){return new Ns({...e.decoders??{[e.prefix]:e},...t.decoders??{[t.prefix]:t}})}var Ms=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,r,n,s){this.name=t,this.prefix=r,this.baseEncode=n,this.baseDecode=s,this.encoder=new Us(t,r,n),this.decoder=new Ks(t,r,s)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function sr({name:e,prefix:t,encode:r,decode:n}){return new Ms(e,t,r,n)}function de({name:e,prefix:t,alphabet:r}){let{encode:n,decode:s}=Ka(r,e);return sr({prefix:t,name:e,encode:n,decode:o=>Gt(s(o))})}function Hf(e,t,r,n){let s=e.length;for(;e[s-1]==="=";)--s;let o=new Uint8Array(s*r/8|0),i=0,a=0,c=0;for(let f=0;f<s;++f){let u=t[e[f]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<r|u,i+=r,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=r||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function Vf(e,t,r){let n=t[t.length-1]==="=",s=(1<<r)-1,o="",i=0,a=0;for(let c=0;c<e.length;++c)for(a=a<<8|e[c],i+=8;i>r;)i-=r,o+=t[s&a>>i];if(i!==0&&(o+=t[s&a<<r-i]),n)for(;(o.length*r&7)!==0;)o+="=";return o}function qf(e){let t={};for(let r=0;r<e.length;++r)t[e[r]]=r;return t}function at({name:e,prefix:t,bitsPerChar:r,alphabet:n}){let s=qf(n);return sr({prefix:t,name:e,encode(o){return Vf(o,n,r)},decode(o){return Hf(o,s,r,e)}})}var ct=de({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),zf=de({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Hs={};It(Hs,{base32:()=>pe,base32hex:()=>Gf,base32hexpad:()=>Zf,base32hexpadupper:()=>Yf,base32hexupper:()=>jf,base32pad:()=>Wf,base32padupper:()=>$f,base32upper:()=>Ff,base32z:()=>Xf});var pe=at({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Ff=at({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Wf=at({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),$f=at({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Gf=at({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),jf=at({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Zf=at({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Yf=at({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Xf=at({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Vs={};It(Vs,{base36:()=>kr,base36upper:()=>Qf});var kr=de({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Qf=de({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var jt={};It(jt,{Digest:()=>Te,create:()=>Mt,decode:()=>ar,equals:()=>zs,hasCode:()=>gl});var Jf=Ha,Ma=128,tl=127,el=~tl,rl=Math.pow(2,31);function Ha(e,t,r){t=t||[],r=r||0;for(var n=r;e>=rl;)t[r++]=e&255|Ma,e/=128;for(;e&el;)t[r++]=e&255|Ma,e>>>=7;return t[r]=e|0,Ha.bytes=r-n+1,t}var nl=qs,sl=128,ka=127;function qs(e,n){var r=0,n=n||0,s=0,o=n,i,a=e.length;do{if(o>=a)throw qs.bytes=0,new RangeError("Could not decode varint");i=e[o++],r+=s<28?(i&ka)<<s:(i&ka)*Math.pow(2,s),s+=7}while(i>=sl);return qs.bytes=o-n,r}var ol=Math.pow(2,7),il=Math.pow(2,14),al=Math.pow(2,21),cl=Math.pow(2,28),ul=Math.pow(2,35),fl=Math.pow(2,42),ll=Math.pow(2,49),hl=Math.pow(2,56),dl=Math.pow(2,63),pl=function(e){return e<ol?1:e<il?2:e<al?3:e<cl?4:e<ul?5:e<fl?6:e<ll?7:e<hl?8:e<dl?9:10},ml={encode:Jf,decode:nl,encodingLength:pl},yl=ml,Hr=yl;function Vr(e,t=0){return[Hr.decode(e,t),Hr.decode.bytes]}function or(e,t,r=0){return Hr.encode(e,t,r),t}function ir(e){return Hr.encodingLength(e)}function Mt(e,t){let r=t.byteLength,n=ir(e),s=n+ir(r),o=new Uint8Array(s+r);return or(e,o,0),or(r,o,n),o.set(t,s),new Te(e,r,t,o)}function ar(e){let t=Gt(e),[r,n]=Vr(t),[s,o]=Vr(t.subarray(n)),i=t.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new Te(r,s,i,t)}function zs(e,t){if(e===t)return!0;{let r=t;return e.code===r.code&&e.size===r.size&&r.bytes instanceof Uint8Array&&Pa(e.bytes,r.bytes)}}var Te=class{code;size;digest;bytes;constructor(t,r,n,s){this.code=t,this.size=r,this.digest=n,this.bytes=s}};function gl(e,t){return e.code===t}function Va(e,t){let{bytes:r,version:n}=e;switch(n){case 0:return xl(r,Fs(e),t??ct.encoder);default:return wl(r,Fs(e),t??pe.encoder)}}var qa=new WeakMap;function Fs(e){let t=qa.get(e);if(t==null){let r=new Map;return qa.set(e,r),r}return t}var ft=class e{code;version;multihash;bytes;"/";constructor(t,r,n,s){this.code=r,this.version=t,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:t,multihash:r}=this;if(t!==qr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==El)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return e.createV0(r)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:t,digest:r}=this.multihash,n=Mt(t,r);return e.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return e.equals(this,t)}static equals(t,r){let n=r;return n!=null&&t.code===n.code&&t.version===n.version&&zs(t.multihash,n.multihash)}toString(t){return Va(this,t)}toJSON(){return{"/":Va(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let r=t;if(r instanceof e)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){let{version:n,code:s,multihash:o,bytes:i}=r;return new e(n,s,o,i??za(n,s,o.bytes))}else if(r[Sl]===!0){let{version:n,multihash:s,code:o}=r,i=ar(s);return e.create(n,o,i)}else return null}static create(t,r,n){if(typeof r!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(r!==qr)throw new Error(`Version 0 CID must use dag-pb (code: ${qr}) block encoding`);return new e(t,r,n,n.bytes)}case 1:{let s=za(t,r,n.bytes);return new e(t,r,n,s)}default:throw new Error("Invalid version")}}static createV0(t){return e.create(0,qr,t)}static createV1(t,r){return e.create(1,t,r)}static decode(t){let[r,n]=e.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return r}static decodeFirst(t){let r=e.inspectBytes(t),n=r.size-r.multihashSize,s=Gt(t.subarray(n,n+r.multihashSize));if(s.byteLength!==r.multihashSize)throw new Error("Incorrect length");let o=s.subarray(r.multihashSize-r.digestSize),i=new Te(r.multihashCode,r.digestSize,o,s);return[r.version===0?e.createV0(i):e.createV1(r.codec,i),t.subarray(r.size)]}static inspectBytes(t){let r=0,n=()=>{let[l,h]=Vr(t.subarray(r));return r+=h,l},s=n(),o=qr;if(s===18?(s=0,r=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=r,a=n(),c=n(),f=r+c,u=f-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:f}}static parse(t,r){let[n,s]=bl(t,r),o=e.decode(s);if(o.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Fs(o).set(n,t),o}};function bl(e,t){switch(e[0]){case"Q":{let r=t??ct;return[ct.prefix,r.decode(`${ct.prefix}${e}`)]}case ct.prefix:{let r=t??ct;return[ct.prefix,r.decode(e)]}case pe.prefix:{let r=t??pe;return[pe.prefix,r.decode(e)]}case kr.prefix:{let r=t??kr;return[kr.prefix,r.decode(e)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[e[0],t.decode(e)]}}}function xl(e,t,r){let{prefix:n}=r;if(n!==ct.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let s=t.get(n);if(s==null){let o=r.encode(e).slice(1);return t.set(n,o),o}else return s}function wl(e,t,r){let{prefix:n}=r,s=t.get(n);if(s==null){let o=r.encode(e);return t.set(n,o),o}else return s}var qr=112,El=18;function za(e,t,r){let n=ir(e),s=n+ir(t),o=new Uint8Array(s+r.byteLength);return or(e,o,0),or(t,o,n),o.set(r,s),o}var Sl=Symbol.for("@ipld/js-cid/CID");var Ws={};It(Ws,{identity:()=>kt});var Fa=0,vl="identity",Wa=Gt;function Al(e,t){if(t?.truncate!=null&&t.truncate!==e.byteLength){if(t.truncate<0||t.truncate>e.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${e.byteLength}`);e=e.subarray(0,t.truncate)}return Mt(Fa,Wa(e))}var kt={code:Fa,name:vl,encode:Wa,digest:Al};function lt(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0}function ht(e=0){return new Uint8Array(e)}function gt(e=0){return new Uint8Array(e)}function Ot(e,t){t==null&&(t=e.reduce((s,o)=>s+o.length,0));let r=gt(t),n=0;for(let s of e)r.set(s,n),n+=s.length;return r}var Ga=Symbol.for("@achingbrain/uint8arraylist");function $a(e,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let r=0;for(let n of e){let s=r+n.byteLength;if(t<s)return{buf:n,index:t-r};r=s}throw new RangeError("index is out of bounds")}function Dn(e){return!!e?.[Ga]}var j=class e{bufs;length;[Ga]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let r=0;for(let n of t)if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.push(n);else if(Dn(n))r+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=r}prepend(...t){this.prependAll(t)}prependAll(t){let r=0;for(let n of t.reverse())if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.unshift(n);else if(Dn(n))r+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=r}get(t){let r=$a(this.bufs,t);return r.buf[r.index]}set(t,r){let n=$a(this.bufs,t);n.buf[n.index]=r}write(t,r=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(r+n,t[n]);else if(Dn(t))for(let n=0;n<t.length;n++)this.set(r+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,r){let{bufs:n,length:s}=this._subList(t,r);return Ot(n,s)}subarray(t,r){let{bufs:n,length:s}=this._subList(t,r);return n.length===1?n[0]:Ot(n,s)}sublist(t,r){let{bufs:n,length:s}=this._subList(t,r),o=new e;return o.length=s,o.bufs=[...n],o}_subList(t,r){if(t=t??0,r=r??this.length,t<0&&(t=this.length+t),r<0&&(r=this.length+r),t<0||r>this.length)throw new RangeError("index is out of bounds");if(t===r)return{bufs:[],length:0};if(t===0&&r===this.length)return{bufs:this.bufs,length:this.length};let n=[],s=0;for(let o=0;o<this.bufs.length;o++){let i=this.bufs[o],a=s,c=a+i.byteLength;if(s=c,t>=c)continue;let f=t>=a&&t<c,u=r>a&&r<=c;if(f&&u){if(t===a&&r===c){n.push(i);break}let l=t-a;n.push(i.subarray(l,l+(r-t)));break}if(f){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(u){if(r===c){n.push(i);break}n.push(i.subarray(0,r-a));break}n.push(i)}return{bufs:n,length:r-t}}indexOf(t,r=0){if(!Dn(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(r=Number(r??0),isNaN(r)&&(r=0),r<0&&(r=this.length+r),r<0&&(r=0),t.length===0)return r>this.length?this.length:r;let s=n.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let o=256,i=new Int32Array(o);for(let l=0;l<o;l++)i[l]=-1;for(let l=0;l<s;l++)i[n[l]]=l;let a=i,c=this.byteLength-n.byteLength,f=n.byteLength-1,u;for(let l=r;l<=c;l+=u){u=0;for(let h=f;h>=0;h--){let d=this.get(l+h);if(n[h]!==d){u=Math.max(1,h-a[d]);break}}if(u===0)return l}return-1}getInt8(t){let r=this.subarray(t,t+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt8(0)}setInt8(t,r){let n=gt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,r),this.write(n,t)}getInt16(t,r){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,r)}setInt16(t,r,n){let s=ht(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,r,n),this.write(s,t)}getInt32(t,r){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,r)}setInt32(t,r,n){let s=ht(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,r,n),this.write(s,t)}getBigInt64(t,r){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,r)}setBigInt64(t,r,n){let s=ht(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,r,n),this.write(s,t)}getUint8(t){let r=this.subarray(t,t+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint8(0)}setUint8(t,r){let n=gt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,r),this.write(n,t)}getUint16(t,r){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,r)}setUint16(t,r,n){let s=ht(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,r,n),this.write(s,t)}getUint32(t,r){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,r)}setUint32(t,r,n){let s=ht(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,r,n),this.write(s,t)}getBigUint64(t,r){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,r)}setBigUint64(t,r,n){let s=ht(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,r,n),this.write(s,t)}getFloat32(t,r){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,r)}setFloat32(t,r,n){let s=ht(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,r,n),this.write(s,t)}getFloat64(t,r){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,r)}setFloat64(t,r,n){let s=ht(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,r,n),this.write(s,t)}equals(t){if(t==null||!(t instanceof e)||t.bufs.length!==this.bufs.length)return!1;for(let r=0;r<this.bufs.length;r++)if(!lt(this.bufs[r],t.bufs[r]))return!1;return!0}static fromUint8Arrays(t,r){let n=new e;return n.bufs=t,r==null&&(r=t.reduce((s,o)=>s+o.byteLength,0)),n.length=r,n}};var $s={};It($s,{base10:()=>_l});var _l=de({prefix:"9",name:"base10",alphabet:"0123456789"});var Gs={};It(Gs,{base16:()=>Il,base16upper:()=>Cl});var Il=at({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Cl=at({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var js={};It(js,{base2:()=>Ll});var Ll=at({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Zs={};It(Zs,{base256emoji:()=>Ol});var ja=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}"),Tl=ja.reduce((e,t,r)=>(e[r]=t,e),[]),Dl=ja.reduce((e,t,r)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return e[n]=r,e},[]);function Pl(e){return e.reduce((t,r)=>(t+=Tl[r],t),"")}function Rl(e){let t=[];for(let r of e){let n=r.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${r}`);let s=Dl[n];if(s==null)throw new Error(`Non-base256emoji character: ${r}`);t.push(s)}return new Uint8Array(t)}var Ol=sr({prefix:"\u{1F680}",name:"base256emoji",encode:Pl,decode:Rl});var Xs={};It(Xs,{base64:()=>Ul,base64pad:()=>Kl,base64url:()=>Ys,base64urlpad:()=>Nl});var Ul=at({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Kl=at({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ys=at({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Nl=at({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Qs={};It(Qs,{base8:()=>Ml});var Ml=at({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Js={};It(Js,{identity:()=>kl});var kl=sr({prefix:"\0",name:"identity",encode:e=>Oa(e),decode:e=>Ra(e)});var n0=new TextEncoder,s0=new TextDecoder;var ro={};It(ro,{sha256:()=>zr,sha512:()=>zl});var ql=20;function eo({name:e,code:t,encode:r,minDigestLength:n,maxDigestLength:s}){return new to(e,t,r,n,s)}var to=class{name;code;encode;minDigestLength;maxDigestLength;constructor(t,r,n,s,o){this.name=t,this.code=r,this.encode=n,this.minDigestLength=s??ql,this.maxDigestLength=o}digest(t,r){if(r?.truncate!=null){if(r.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&r.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(t instanceof Uint8Array){let n=this.encode(t);return n instanceof Uint8Array?Za(n,this.code,r?.truncate):n.then(s=>Za(s,this.code,r?.truncate))}else throw Error("Unknown type, must be binary type")}};function Za(e,t,r){if(r!=null&&r!==e.byteLength){if(r>e.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${e.byteLength}`);e=e.subarray(0,r)}return Mt(t,e)}function Xa(e){return async t=>new Uint8Array(await crypto.subtle.digest(e,t))}var zr=eo({name:"sha2-256",code:18,encode:Xa("SHA-256")}),zl=eo({name:"sha2-512",code:19,encode:Xa("SHA-512")});var De={...Js,...js,...Qs,...$s,...Gs,...Hs,...Vs,...ks,...Xs,...Zs},y0={...ro,...Ws};function Ja(e,t,r,n){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:r},decoder:{decode:n}}}var Qa=Ja("utf8","u",e=>"u"+new TextDecoder("utf8").decode(e),e=>new TextEncoder().encode(e.substring(1))),no=Ja("ascii","a",e=>{let t="a";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return t},e=>{e=e.substring(1);let t=gt(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}),Fl={utf8:Qa,"utf-8":Qa,hex:De.base16,latin1:no,ascii:no,binary:no,...De},Pn=Fl;function Z(e,t="utf8"){let r=Pn[t];if(r==null)throw new Error(`Unsupported encoding "${t}"`);return r.decoder.decode(`${r.prefix}${e}`)}function q(e,t="utf8"){let r=Pn[t];if(r==null)throw new Error(`Unsupported encoding "${t}"`);return r.encoder.encode(e).substring(1)}var Wl=parseInt("11111",2),so=parseInt("10000000",2),$l=parseInt("01111111",2),tc={0:Fr,1:Fr,2:Gl,3:Yl,4:Xl,5:Zl,6:jl,16:Fr,22:Fr,48:Fr};function Zt(e,t={offset:0}){let r=e[t.offset]&Wl;if(t.offset++,tc[r]!=null)return tc[r](e,t);throw new Error("No decoder for tag "+r)}function Wr(e,t){let r=0;if((e[t.offset]&so)===so){let n=e[t.offset]&$l,s="0x";t.offset++;for(let o=0;o<n;o++,t.offset++)s+=e[t.offset].toString(16).padStart(2,"0");r=parseInt(s,16)}else r=e[t.offset],t.offset++;return r}function Fr(e,t){Wr(e,t);let r=[];for(;!(t.offset>=e.byteLength);){let n=Zt(e,t);if(n===null)break;r.push(n)}return r}function Gl(e,t){let r=Wr(e,t),n=t.offset,s=t.offset+r,o=[];for(let i=n;i<s;i++)i===n&&e[i]===0||o.push(e[i]);return t.offset+=r,Uint8Array.from(o)}function jl(e,t){let r=Wr(e,t),n=t.offset+r,s=e[t.offset];t.offset++;let o=0,i=0;s<40?(o=0,i=s):s<80?(o=1,i=s-40):(o=2,i=s-80);let a=`${o}.${i}`,c=[];for(;t.offset<n;){let f=e[t.offset];if(t.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 Zl(e,t){return t.offset++,null}function Yl(e,t){let r=Wr(e,t),n=e[t.offset];t.offset++;let s=e.subarray(t.offset,t.offset+r-1);if(t.offset+=r,n!==0)throw new Error("Unused bits in bit string is unimplemented");return s}function Xl(e,t){let r=Wr(e,t),n=e.subarray(t.offset,t.offset+r);return t.offset+=r,n}function Ql(e){let t=e.toString(16);t.length%2===1&&(t="0"+t);let r=new j;for(let n=0;n<t.length;n+=2)r.append(Uint8Array.from([parseInt(`${t[n]}${t[n+1]}`,16)]));return r}function oo(e){if(e.byteLength<128)return Uint8Array.from([e.byteLength]);let t=Ql(e.byteLength);return new j(Uint8Array.from([t.byteLength|so]),t)}function Tt(e){let t=new j,r=128;return(e.subarray()[0]&r)===r&&t.append(Uint8Array.from([0])),t.append(e),new j(Uint8Array.from([2]),oo(t),t)}function Rn(e){let t=Uint8Array.from([0]),r=new j(t,e);return new j(Uint8Array.from([3]),oo(r),r)}function me(e,t=48){let r=new j;for(let n of e)r.append(n);return new j(Uint8Array.from([t]),oo(r),r)}async function ec(e,t,r,n){let s=await crypto.subtle.importKey("jwk",e,{name:"ECDSA",namedCurve:e.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let o=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},s,t,r.subarray());return n?.signal?.throwIfAborted(),o}var Jl=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),th=Uint8Array.from([6,5,43,129,4,0,34]),eh=Uint8Array.from([6,5,43,129,4,0,35]),rh={ext:!0,kty:"EC",crv:"P-256"},nh={ext:!0,kty:"EC",crv:"P-384"},sh={ext:!0,kty:"EC",crv:"P-521"},io=32,ao=48,co=66;function uo(e){let t=Zt(e);return rc(t)}function rc(e){let t=e[1][1][0],r=1,n,s;if(t.byteLength===io*2+1)return n=q(t.subarray(r,r+io),"base64url"),s=q(t.subarray(r+io),"base64url"),new cr({...rh,key_ops:["verify"],x:n,y:s});if(t.byteLength===ao*2+1)return n=q(t.subarray(r,r+ao),"base64url"),s=q(t.subarray(r+ao),"base64url"),new cr({...nh,key_ops:["verify"],x:n,y:s});if(t.byteLength===co*2+1)return n=q(t.subarray(r,r+co),"base64url"),s=q(t.subarray(r+co),"base64url"),new cr({...sh,key_ops:["verify"],x:n,y:s});throw new et(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function nc(e){return me([Tt(Uint8Array.from([1])),me([oh(e.crv)],160),me([Rn(new j(Uint8Array.from([4]),Z(e.x??"","base64url"),Z(e.y??"","base64url")))],161)]).subarray()}function oh(e){if(e==="P-256")return Jl;if(e==="P-384")return th;if(e==="P-521")return eh;throw new et(`Invalid curve ${e}`)}var cr=class{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=nc(this.jwk)),this._raw}toMultihash(){return kt.digest(ye(this))}toCID(){return ft.createV1(114,this.toMultihash())}toString(){return ct.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:lt(this.raw,t.raw)}async verify(t,r,n){return ec(this.jwk,r,t,n)}};var Pe=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Xt(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Re(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Et(e,...t){if(!Xt(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function Oe(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Re(e.outputLen),Re(e.blockLen)}function fr(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function oc(e,t){Et(e);let r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function Ht(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function On(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Vt(e,t){return e<<32-t|e>>>t}var ic=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",ih=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Ut(e){if(Et(e),ic)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=ih[e[r]];return t}var Yt={_0:48,_9:57,A:65,F:70,a:97,f:102};function sc(e){if(e>=Yt._0&&e<=Yt._9)return e-Yt._0;if(e>=Yt.A&&e<=Yt.F)return e-(Yt.A-10);if(e>=Yt.a&&e<=Yt.f)return e-(Yt.a-10)}function Ue(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(ic)return Uint8Array.fromHex(e);let t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let s=0,o=0;s<r;s++,o+=2){let i=sc(e.charCodeAt(o)),a=sc(e.charCodeAt(o+1));if(i===void 0||a===void 0){let c=e[o]+e[o+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+o)}n[s]=i*16+a}return n}function fo(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function ge(e){return typeof e=="string"&&(e=fo(e)),Et(e),e}function Ct(...e){let t=0;for(let n=0;n<e.length;n++){let s=e[n];Et(s),t+=s.length}let r=new Uint8Array(t);for(let n=0,s=0;n<e.length;n++){let o=e[n];r.set(o,s),s+=o.length}return r}var ur=class{};function lo(e){let t=n=>e().update(ge(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function be(e=32){if(Pe&&typeof Pe.getRandomValues=="function")return Pe.getRandomValues(new Uint8Array(e));if(Pe&&typeof Pe.randomBytes=="function")return Uint8Array.from(Pe.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function ah(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);let s=BigInt(32),o=BigInt(4294967295),i=Number(r>>s&o),a=Number(r&o),c=n?4:0,f=n?0:4;e.setUint32(t+c,i,n),e.setUint32(t+f,a,n)}function ac(e,t,r){return e&t^~e&r}function cc(e,t,r){return e&t^e&r^t&r}var $r=class extends ur{constructor(t,r,n,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(t),this.view=On(this.buffer)}update(t){fr(this),t=ge(t),Et(t);let{view:r,buffer:n,blockLen:s}=this,o=t.length;for(let i=0;i<o;){let a=Math.min(s-this.pos,o-i);if(a===s){let c=On(t);for(;s<=o-i;i+=s)this.process(c,i);continue}n.set(t.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===s&&(this.process(r,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){fr(this),oc(t,this),this.finished=!0;let{buffer:r,view:n,blockLen:s,isLE:o}=this,{pos:i}=this;r[i++]=128,Ht(this.buffer.subarray(i)),this.padOffset>s-i&&(this.process(n,0),i=0);for(let l=i;l<s;l++)r[l]=0;ah(n,s-8,BigInt(this.length*8),o),this.process(n,0);let a=On(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should 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],o)}digest(){let{buffer:t,outputLen:r}=this;this.digestInto(t);let n=t.slice(0,r);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:r,buffer:n,length:s,finished:o,destroyed:i,pos:a}=this;return t.destroyed=i,t.finished=o,t.length=s,t.pos=a,s%r&&t.buffer.set(n),t}clone(){return this._cloneInto()}},Qt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var bt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Un=BigInt(4294967295),uc=BigInt(32);function ch(e,t=!1){return t?{h:Number(e&Un),l:Number(e>>uc&Un)}:{h:Number(e>>uc&Un)|0,l:Number(e&Un)|0}}function fc(e,t=!1){let r=e.length,n=new Uint32Array(r),s=new Uint32Array(r);for(let o=0;o<r;o++){let{h:i,l:a}=ch(e[o],t);[n[o],s[o]]=[i,a]}return[n,s]}var ho=(e,t,r)=>e>>>r,po=(e,t,r)=>e<<32-r|t>>>r,Ke=(e,t,r)=>e>>>r|t<<32-r,Ne=(e,t,r)=>e<<32-r|t>>>r,Gr=(e,t,r)=>e<<64-r|t>>>r-32,jr=(e,t,r)=>e>>>r-32|t<<64-r;function zt(e,t,r,n){let s=(t>>>0)+(n>>>0);return{h:e+r+(s/2**32|0)|0,l:s|0}}var lc=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),hc=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,dc=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),pc=(e,t,r,n,s)=>t+r+n+s+(e/2**32|0)|0,mc=(e,t,r,n,s)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(s>>>0),yc=(e,t,r,n,s,o)=>t+r+n+s+o+(e/2**32|0)|0;var fh=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),xe=new Uint32Array(64),Kn=class extends $r{constructor(t=32){super(64,t,8,!1),this.A=Qt[0]|0,this.B=Qt[1]|0,this.C=Qt[2]|0,this.D=Qt[3]|0,this.E=Qt[4]|0,this.F=Qt[5]|0,this.G=Qt[6]|0,this.H=Qt[7]|0}get(){let{A:t,B:r,C:n,D:s,E:o,F:i,G:a,H:c}=this;return[t,r,n,s,o,i,a,c]}set(t,r,n,s,o,i,a,c){this.A=t|0,this.B=r|0,this.C=n|0,this.D=s|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,r){for(let l=0;l<16;l++,r+=4)xe[l]=t.getUint32(r,!1);for(let l=16;l<64;l++){let h=xe[l-15],d=xe[l-2],p=Vt(h,7)^Vt(h,18)^h>>>3,w=Vt(d,17)^Vt(d,19)^d>>>10;xe[l]=w+xe[l-7]+p+xe[l-16]|0}let{A:n,B:s,C:o,D:i,E:a,F:c,G:f,H:u}=this;for(let l=0;l<64;l++){let h=Vt(a,6)^Vt(a,11)^Vt(a,25),d=u+h+ac(a,c,f)+fh[l]+xe[l]|0,w=(Vt(n,2)^Vt(n,13)^Vt(n,22))+cc(n,s,o)|0;u=f,f=c,c=a,a=i+d|0,i=o,o=s,s=n,n=d+w|0}n=n+this.A|0,s=s+this.B|0,o=o+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,s,o,i,a,c,f,u)}roundClean(){Ht(xe)}destroy(){this.set(0,0,0,0,0,0,0,0),Ht(this.buffer)}};var gc=fc(["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(e=>BigInt(e))),lh=gc[0],hh=gc[1],we=new Uint32Array(80),Ee=new Uint32Array(80),mo=class extends $r{constructor(t=64){super(128,t,16,!1),this.Ah=bt[0]|0,this.Al=bt[1]|0,this.Bh=bt[2]|0,this.Bl=bt[3]|0,this.Ch=bt[4]|0,this.Cl=bt[5]|0,this.Dh=bt[6]|0,this.Dl=bt[7]|0,this.Eh=bt[8]|0,this.El=bt[9]|0,this.Fh=bt[10]|0,this.Fl=bt[11]|0,this.Gh=bt[12]|0,this.Gl=bt[13]|0,this.Hh=bt[14]|0,this.Hl=bt[15]|0}get(){let{Ah:t,Al:r,Bh:n,Bl:s,Ch:o,Cl:i,Dh:a,Dl:c,Eh:f,El:u,Fh:l,Fl:h,Gh:d,Gl:p,Hh:w,Hl:g}=this;return[t,r,n,s,o,i,a,c,f,u,l,h,d,p,w,g]}set(t,r,n,s,o,i,a,c,f,u,l,h,d,p,w,g){this.Ah=t|0,this.Al=r|0,this.Bh=n|0,this.Bl=s|0,this.Ch=o|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=h|0,this.Gh=d|0,this.Gl=p|0,this.Hh=w|0,this.Hl=g|0}process(t,r){for(let E=0;E<16;E++,r+=4)we[E]=t.getUint32(r),Ee[E]=t.getUint32(r+=4);for(let E=16;E<80;E++){let P=we[E-15]|0,N=Ee[E-15]|0,k=Ke(P,N,1)^Ke(P,N,8)^ho(P,N,7),M=Ne(P,N,1)^Ne(P,N,8)^po(P,N,7),U=we[E-2]|0,S=Ee[E-2]|0,L=Ke(U,S,19)^Gr(U,S,61)^ho(U,S,6),R=Ne(U,S,19)^jr(U,S,61)^po(U,S,6),T=dc(M,R,Ee[E-7],Ee[E-16]),m=pc(T,k,L,we[E-7],we[E-16]);we[E]=m|0,Ee[E]=T|0}let{Ah:n,Al:s,Bh:o,Bl:i,Ch:a,Cl:c,Dh:f,Dl:u,Eh:l,El:h,Fh:d,Fl:p,Gh:w,Gl:g,Hh:x,Hl:B}=this;for(let E=0;E<80;E++){let P=Ke(l,h,14)^Ke(l,h,18)^Gr(l,h,41),N=Ne(l,h,14)^Ne(l,h,18)^jr(l,h,41),k=l&d^~l&w,M=h&p^~h&g,U=mc(B,N,M,hh[E],Ee[E]),S=yc(U,x,P,k,lh[E],we[E]),L=U|0,R=Ke(n,s,28)^Gr(n,s,34)^Gr(n,s,39),T=Ne(n,s,28)^jr(n,s,34)^jr(n,s,39),m=n&o^n&a^o&a,y=s&i^s&c^i&c;x=w|0,B=g|0,w=d|0,g=p|0,d=l|0,p=h|0,{h:l,l:h}=zt(f|0,u|0,S|0,L|0),f=a|0,u=c|0,a=o|0,c=i|0,o=n|0,i=s|0;let b=lc(L,T,y);n=hc(b,S,R,m),s=b|0}({h:n,l:s}=zt(this.Ah|0,this.Al|0,n|0,s|0)),{h:o,l:i}=zt(this.Bh|0,this.Bl|0,o|0,i|0),{h:a,l:c}=zt(this.Ch|0,this.Cl|0,a|0,c|0),{h:f,l:u}=zt(this.Dh|0,this.Dl|0,f|0,u|0),{h:l,l:h}=zt(this.Eh|0,this.El|0,l|0,h|0),{h:d,l:p}=zt(this.Fh|0,this.Fl|0,d|0,p|0),{h:w,l:g}=zt(this.Gh|0,this.Gl|0,w|0,g|0),{h:x,l:B}=zt(this.Hh|0,this.Hl|0,x|0,B|0),this.set(n,s,o,i,a,c,f,u,l,h,d,p,w,g,x,B)}roundClean(){Ht(we,Ee)}destroy(){Ht(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var Se=lo(()=>new Kn);var bc=lo(()=>new mo);var bo=BigInt(0),go=BigInt(1);function Jt(e,t=""){if(typeof e!="boolean"){let r=t&&`"${t}"`;throw new Error(r+"expected boolean, got type="+typeof e)}return e}function Dt(e,t,r=""){let n=Xt(e),s=e?.length,o=t!==void 0;if(!n||o&&s!==t){let i=r&&`"${r}" `,a=o?` of length ${t}`:"",c=n?`length=${s}`:`type=${typeof e}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return e}function Zr(e){let t=e.toString(16);return t.length&1?"0"+t:t}function xc(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?bo:BigInt("0x"+e)}function lr(e){return xc(Ut(e))}function Kt(e){return Et(e),xc(Ut(Uint8Array.from(e).reverse()))}function Nn(e,t){return Ue(e.toString(16).padStart(t*2,"0"))}function Yr(e,t){return Nn(e,t).reverse()}function Y(e,t,r){let n;if(typeof t=="string")try{n=Ue(t)}catch(o){throw new Error(e+" must be hex string or Uint8Array, cause: "+o)}else if(Xt(t))n=Uint8Array.from(t);else throw new Error(e+" must be hex string or Uint8Array");let s=n.length;if(typeof r=="number"&&s!==r)throw new Error(e+" of length "+r+" expected, got "+s);return n}function wc(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return r===0}function xo(e){return Uint8Array.from(e)}var yo=e=>typeof e=="bigint"&&bo<=e;function Ec(e,t,r){return yo(e)&&yo(t)&&yo(r)&&t<=e&&e<r}function ve(e,t,r,n){if(!Ec(t,r,n))throw new Error("expected valid "+e+": "+r+" <= n < "+n+", got "+t)}function Mn(e){let t;for(t=0;e>bo;e>>=go,t+=1);return t}var Ae=e=>(go<<BigInt(e))-go;function Sc(e,t,r){if(typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");let n=d=>new Uint8Array(d),s=d=>Uint8Array.of(d),o=n(e),i=n(e),a=0,c=()=>{o.fill(1),i.fill(0),a=0},f=(...d)=>r(i,o,...d),u=(d=n(0))=>{i=f(s(0),d),o=f(),d.length!==0&&(i=f(s(1),d),o=f())},l=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let d=0,p=[];for(;d<t;){o=f();let w=o.slice();p.push(w),d+=o.length}return Ct(...p)};return(d,p)=>{c(),u(d);let w;for(;!(w=p(l()));)u();return c(),w}}function Ft(e,t,r={}){if(!e||typeof e!="object")throw new Error("expected valid options object");function n(s,o,i){let a=e[s];if(i&&a===void 0)return;let c=typeof a;if(c!==o||a===null)throw new Error(`param "${s}" is invalid: expected ${o}, got ${c}`)}Object.entries(t).forEach(([s,o])=>n(s,o,!1)),Object.entries(r).forEach(([s,o])=>n(s,o,!0))}var wo=()=>{throw new Error("not implemented")};function hr(e){let t=new WeakMap;return(r,...n)=>{let s=t.get(r);if(s!==void 0)return s;let o=e(r,...n);return t.set(r,o),o}}var Lt=BigInt(0),pt=BigInt(1),Me=BigInt(2),Bc=BigInt(3),_c=BigInt(4),Ic=BigInt(5),dh=BigInt(7),Cc=BigInt(8),ph=BigInt(9),Lc=BigInt(16);function rt(e,t){let r=e%t;return r>=Lt?r:t+r}function nt(e,t,r){let n=e;for(;t-- >Lt;)n*=n,n%=r;return n}function vc(e,t){if(e===Lt)throw new Error("invert: expected non-zero number");if(t<=Lt)throw new Error("invert: expected positive modulus, got "+t);let r=rt(e,t),n=t,s=Lt,o=pt,i=pt,a=Lt;for(;r!==Lt;){let f=n/r,u=n%r,l=s-i*f,h=o-a*f;n=r,r=u,s=i,o=a,i=l,a=h}if(n!==pt)throw new Error("invert: does not exist");return rt(s,t)}function Eo(e,t,r){if(!e.eql(e.sqr(t),r))throw new Error("Cannot find square root")}function Tc(e,t){let r=(e.ORDER+pt)/_c,n=e.pow(t,r);return Eo(e,n,t),n}function mh(e,t){let r=(e.ORDER-Ic)/Cc,n=e.mul(t,Me),s=e.pow(n,r),o=e.mul(t,s),i=e.mul(e.mul(o,Me),s),a=e.mul(o,e.sub(i,e.ONE));return Eo(e,a,t),a}function yh(e){let t=Pt(e),r=Dc(e),n=r(t,t.neg(t.ONE)),s=r(t,n),o=r(t,t.neg(n)),i=(e+dh)/Lc;return(a,c)=>{let f=a.pow(c,i),u=a.mul(f,n),l=a.mul(f,s),h=a.mul(f,o),d=a.eql(a.sqr(u),c),p=a.eql(a.sqr(l),c);f=a.cmov(f,u,d),u=a.cmov(h,l,p);let w=a.eql(a.sqr(u),c),g=a.cmov(f,u,w);return Eo(a,g,c),g}}function Dc(e){if(e<Bc)throw new Error("sqrt is not defined for small field");let t=e-pt,r=0;for(;t%Me===Lt;)t/=Me,r++;let n=Me,s=Pt(e);for(;Ac(s,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return Tc;let o=s.pow(n,t),i=(t+pt)/Me;return function(c,f){if(c.is0(f))return f;if(Ac(c,f)!==1)throw new Error("Cannot find square root");let u=r,l=c.mul(c.ONE,o),h=c.pow(f,t),d=c.pow(f,i);for(;!c.eql(h,c.ONE);){if(c.is0(h))return c.ZERO;let p=1,w=c.sqr(h);for(;!c.eql(w,c.ONE);)if(p++,w=c.sqr(w),p===u)throw new Error("Cannot find square root");let g=pt<<BigInt(u-p-1),x=c.pow(l,g);u=p,l=c.sqr(x),h=c.mul(h,l),d=c.mul(d,x)}return d}}function gh(e){return e%_c===Bc?Tc:e%Cc===Ic?mh:e%Lc===ph?yh(e):Dc(e)}var te=(e,t)=>(rt(e,t)&pt)===pt,bh=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function So(e){let t={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},r=bh.reduce((n,s)=>(n[s]="function",n),t);return Ft(e,r),e}function xh(e,t,r){if(r<Lt)throw new Error("invalid exponent, negatives unsupported");if(r===Lt)return e.ONE;if(r===pt)return t;let n=e.ONE,s=t;for(;r>Lt;)r&pt&&(n=e.mul(n,s)),s=e.sqr(s),r>>=pt;return n}function Xr(e,t,r=!1){let n=new Array(t.length).fill(r?e.ZERO:void 0),s=t.reduce((i,a,c)=>e.is0(a)?i:(n[c]=i,e.mul(i,a)),e.ONE),o=e.inv(s);return t.reduceRight((i,a,c)=>e.is0(a)?i:(n[c]=e.mul(i,n[c]),e.mul(i,a)),o),n}function Ac(e,t){let r=(e.ORDER-pt)/Me,n=e.pow(t,r),s=e.eql(n,e.ONE),o=e.eql(n,e.ZERO),i=e.eql(n,e.neg(e.ONE));if(!s&&!o&&!i)throw new Error("invalid Legendre symbol result");return s?1:o?0:-1}function kn(e,t){t!==void 0&&Re(t);let r=t!==void 0?t:e.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function Pt(e,t,r=!1,n={}){if(e<=Lt)throw new Error("invalid field: expected ORDER > 0, got "+e);let s,o,i=!1,a;if(typeof t=="object"&&t!=null){if(n.sqrt||r)throw new Error("cannot specify opts in two arguments");let h=t;h.BITS&&(s=h.BITS),h.sqrt&&(o=h.sqrt),typeof h.isLE=="boolean"&&(r=h.isLE),typeof h.modFromBytes=="boolean"&&(i=h.modFromBytes),a=h.allowedLengths}else typeof t=="number"&&(s=t),n.sqrt&&(o=n.sqrt);let{nBitLength:c,nByteLength:f}=kn(e,s);if(f>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let u,l=Object.freeze({ORDER:e,isLE:r,BITS:c,BYTES:f,MASK:Ae(c),ZERO:Lt,ONE:pt,allowedLengths:a,create:h=>rt(h,e),isValid:h=>{if(typeof h!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof h);return Lt<=h&&h<e},is0:h=>h===Lt,isValidNot0:h=>!l.is0(h)&&l.isValid(h),isOdd:h=>(h&pt)===pt,neg:h=>rt(-h,e),eql:(h,d)=>h===d,sqr:h=>rt(h*h,e),add:(h,d)=>rt(h+d,e),sub:(h,d)=>rt(h-d,e),mul:(h,d)=>rt(h*d,e),pow:(h,d)=>xh(l,h,d),div:(h,d)=>rt(h*vc(d,e),e),sqrN:h=>h*h,addN:(h,d)=>h+d,subN:(h,d)=>h-d,mulN:(h,d)=>h*d,inv:h=>vc(h,e),sqrt:o||(h=>(u||(u=gh(e)),u(l,h))),toBytes:h=>r?Yr(h,f):Nn(h,f),fromBytes:(h,d=!0)=>{if(a){if(!a.includes(h.length)||h.length>f)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+h.length);let w=new Uint8Array(f);w.set(h,r?0:w.length-h.length),h=w}if(h.length!==f)throw new Error("Field.fromBytes: expected "+f+" bytes, got "+h.length);let p=r?Kt(h):lr(h);if(i&&(p=rt(p,e)),!d&&!l.isValid(p))throw new Error("invalid field element: outside of range 0..ORDER");return p},invertBatch:h=>Xr(l,h),cmov:(h,d,p)=>p?d:h});return Object.freeze(l)}function Pc(e){if(typeof e!="bigint")throw new Error("field order must be bigint");let t=e.toString(2).length;return Math.ceil(t/8)}function vo(e){let t=Pc(e);return t+Math.ceil(t/2)}function Ao(e,t,r=!1){let n=e.length,s=Pc(t),o=vo(t);if(n<16||n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);let i=r?Kt(e):lr(e),a=rt(i,t-pt)+pt;return r?Yr(a,s):Nn(a,s)}var dr=BigInt(0),ke=BigInt(1);function Qr(e,t){let r=t.negate();return e?r:t}function ee(e,t){let r=Xr(e.Fp,t.map(n=>n.Z));return t.map((n,s)=>e.fromAffine(n.toAffine(r[s])))}function Kc(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function Bo(e,t){Kc(e,t);let r=Math.ceil(t/e)+1,n=2**(e-1),s=2**e,o=Ae(e),i=BigInt(e);return{windows:r,windowSize:n,mask:o,maxNumber:s,shiftBy:i}}function Rc(e,t,r){let{windowSize:n,mask:s,maxNumber:o,shiftBy:i}=r,a=Number(e&s),c=e>>i;a>n&&(a-=o,c+=ke);let f=t*n,u=f+Math.abs(a)-1,l=a===0,h=a<0,d=t%2!==0;return{nextN:c,offset:u,isZero:l,isNeg:h,isNegF:d,offsetF:f}}function wh(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((r,n)=>{if(!(r instanceof t))throw new Error("invalid point at index "+n)})}function Eh(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((r,n)=>{if(!t.isValid(r))throw new Error("invalid scalar at index "+n)})}var _o=new WeakMap,Nc=new WeakMap;function Io(e){return Nc.get(e)||1}function Oc(e){if(e!==dr)throw new Error("invalid wNAF")}var pr=class{constructor(t,r){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=r}_unsafeLadder(t,r,n=this.ZERO){let s=t;for(;r>dr;)r&ke&&(n=n.add(s)),s=s.double(),r>>=ke;return n}precomputeWindow(t,r){let{windows:n,windowSize:s}=Bo(r,this.bits),o=[],i=t,a=i;for(let c=0;c<n;c++){a=i,o.push(a);for(let f=1;f<s;f++)a=a.add(i),o.push(a);i=a.double()}return o}wNAF(t,r,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let s=this.ZERO,o=this.BASE,i=Bo(t,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:f,isZero:u,isNeg:l,isNegF:h,offsetF:d}=Rc(n,a,i);n=c,u?o=o.add(Qr(h,r[d])):s=s.add(Qr(l,r[f]))}return Oc(n),{p:s,f:o}}wNAFUnsafe(t,r,n,s=this.ZERO){let o=Bo(t,this.bits);for(let i=0;i<o.windows&&n!==dr;i++){let{nextN:a,offset:c,isZero:f,isNeg:u}=Rc(n,i,o);if(n=a,!f){let l=r[c];s=s.add(u?l.negate():l)}}return Oc(n),s}getPrecomputes(t,r,n){let s=_o.get(r);return s||(s=this.precomputeWindow(r,t),t!==1&&(typeof n=="function"&&(s=n(s)),_o.set(r,s))),s}cached(t,r,n){let s=Io(t);return this.wNAF(s,this.getPrecomputes(s,t,n),r)}unsafe(t,r,n,s){let o=Io(t);return o===1?this._unsafeLadder(t,r,s):this.wNAFUnsafe(o,this.getPrecomputes(o,t,n),r,s)}createCache(t,r){Kc(r,this.bits),Nc.set(t,r),_o.delete(t)}hasCache(t){return Io(t)!==1}};function Mc(e,t,r,n){let s=t,o=e.ZERO,i=e.ZERO;for(;r>dr||n>dr;)r&ke&&(o=o.add(s)),n&ke&&(i=i.add(s)),s=s.double(),r>>=ke,n>>=ke;return{p1:o,p2:i}}function mr(e,t,r,n){wh(r,e),Eh(n,t);let s=r.length,o=n.length;if(s!==o)throw new Error("arrays of points and scalars must have equal length");let i=e.ZERO,a=Mn(BigInt(s)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let f=Ae(c),u=new Array(Number(f)+1).fill(i),l=Math.floor((t.BITS-1)/c)*c,h=i;for(let d=l;d>=0;d-=c){u.fill(i);for(let w=0;w<o;w++){let g=n[w],x=Number(g>>BigInt(d)&f);u[x]=u[x].add(r[w])}let p=i;for(let w=u.length-1,g=i;w>0;w--)g=g.add(u[w]),p=p.add(g);if(h=h.add(p),d!==0)for(let w=0;w<c;w++)h=h.double()}return h}function Uc(e,t,r){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return So(t),t}else return Pt(e,{isLE:r})}function Hn(e,t,r={},n){if(n===void 0&&(n=e==="edwards"),!t||typeof t!="object")throw new Error(`expected valid ${e} CURVE object`);for(let c of["p","n","h"]){let f=t[c];if(!(typeof f=="bigint"&&f>dr))throw new Error(`CURVE.${c} must be positive bigint`)}let s=Uc(t.p,r.Fp,n),o=Uc(t.n,r.Fn,n),a=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(let c of a)if(!s.isValid(t[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:s,Fn:o}}var Be=BigInt(0),mt=BigInt(1),Co=BigInt(2),Sh=BigInt(8);function vh(e,t,r,n){let s=e.sqr(r),o=e.sqr(n),i=e.add(e.mul(t.a,s),o),a=e.add(e.ONE,e.mul(t.d,e.mul(s,o)));return e.eql(i,a)}function Ah(e,t={}){let r=Hn("edwards",e,t,t.FpFnLE),{Fp:n,Fn:s}=r,o=r.CURVE,{h:i}=o;Ft(t,{},{uvRatio:"function"});let a=Co<<BigInt(s.BYTES*8)-mt,c=g=>n.create(g),f=t.uvRatio||((g,x)=>{try{return{isValid:!0,value:n.sqrt(n.div(g,x))}}catch{return{isValid:!1,value:Be}}});if(!vh(n,o,o.Gx,o.Gy))throw new Error("bad curve params: generator point");function u(g,x,B=!1){let E=B?mt:Be;return ve("coordinate "+g,x,E,a),x}function l(g){if(!(g instanceof p))throw new Error("ExtendedPoint expected")}let h=hr((g,x)=>{let{X:B,Y:E,Z:P}=g,N=g.is0();x==null&&(x=N?Sh:n.inv(P));let k=c(B*x),M=c(E*x),U=n.mul(P,x);if(N)return{x:Be,y:mt};if(U!==mt)throw new Error("invZ was invalid");return{x:k,y:M}}),d=hr(g=>{let{a:x,d:B}=o;if(g.is0())throw new Error("bad point: ZERO");let{X:E,Y:P,Z:N,T:k}=g,M=c(E*E),U=c(P*P),S=c(N*N),L=c(S*S),R=c(M*x),T=c(S*c(R+U)),m=c(L+c(B*c(M*U)));if(T!==m)throw new Error("bad point: equation left != right (1)");let y=c(E*P),b=c(N*k);if(y!==b)throw new Error("bad point: equation left != right (2)");return!0});class p{constructor(x,B,E,P){this.X=u("x",x),this.Y=u("y",B),this.Z=u("z",E,!0),this.T=u("t",P),Object.freeze(this)}static CURVE(){return o}static fromAffine(x){if(x instanceof p)throw new Error("extended point not allowed");let{x:B,y:E}=x||{};return u("x",B),u("y",E),new p(B,E,mt,c(B*E))}static fromBytes(x,B=!1){let E=n.BYTES,{a:P,d:N}=o;x=xo(Dt(x,E,"point")),Jt(B,"zip215");let k=xo(x),M=x[E-1];k[E-1]=M&-129;let U=Kt(k),S=B?a:n.ORDER;ve("point.y",U,Be,S);let L=c(U*U),R=c(L-mt),T=c(N*L-P),{isValid:m,value:y}=f(R,T);if(!m)throw new Error("bad point: invalid y coordinate");let b=(y&mt)===mt,A=(M&128)!==0;if(!B&&y===Be&&A)throw new Error("bad point: x=0 and x_0=1");return A!==b&&(y=c(-y)),p.fromAffine({x:y,y:U})}static fromHex(x,B=!1){return p.fromBytes(Y("point",x),B)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(x=8,B=!0){return w.createCache(this,x),B||this.multiply(Co),this}assertValidity(){d(this)}equals(x){l(x);let{X:B,Y:E,Z:P}=this,{X:N,Y:k,Z:M}=x,U=c(B*M),S=c(N*P),L=c(E*M),R=c(k*P);return U===S&&L===R}is0(){return this.equals(p.ZERO)}negate(){return new p(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:x}=o,{X:B,Y:E,Z:P}=this,N=c(B*B),k=c(E*E),M=c(Co*c(P*P)),U=c(x*N),S=B+E,L=c(c(S*S)-N-k),R=U+k,T=R-M,m=U-k,y=c(L*T),b=c(R*m),A=c(L*m),_=c(T*R);return new p(y,b,_,A)}add(x){l(x);let{a:B,d:E}=o,{X:P,Y:N,Z:k,T:M}=this,{X:U,Y:S,Z:L,T:R}=x,T=c(P*U),m=c(N*S),y=c(M*E*R),b=c(k*L),A=c((P+N)*(U+S)-T-m),_=b-y,C=b+y,v=c(m-B*T),I=c(A*_),D=c(C*v),O=c(A*v),z=c(_*C);return new p(I,D,z,O)}subtract(x){return this.add(x.negate())}multiply(x){if(!s.isValidNot0(x))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:B,f:E}=w.cached(this,x,P=>ee(p,P));return ee(p,[B,E])[0]}multiplyUnsafe(x,B=p.ZERO){if(!s.isValid(x))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return x===Be?p.ZERO:this.is0()||x===mt?this:w.unsafe(this,x,E=>ee(p,E),B)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return w.unsafe(this,o.n).is0()}toAffine(x){return h(this,x)}clearCofactor(){return i===mt?this:this.multiplyUnsafe(i)}toBytes(){let{x,y:B}=this.toAffine(),E=n.toBytes(B);return E[E.length-1]|=x&mt?128:0,E}toHex(){return Ut(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(x){return ee(p,x)}static msm(x,B){return mr(p,s,x,B)}_setWindowSize(x){this.precompute(x)}toRawBytes(){return this.toBytes()}}p.BASE=new p(o.Gx,o.Gy,mt,c(o.Gx*o.Gy)),p.ZERO=new p(Be,mt,mt,Be),p.Fp=n,p.Fn=s;let w=new pr(p,s.BITS);return p.BASE.precompute(8),p}var Vn=class{constructor(t){this.ep=t}static fromBytes(t){wo()}static fromHex(t){wo()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(t){return this.ep.toAffine(t)}toHex(){return Ut(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(t){return this.assertSame(t),this.init(this.ep.add(t.ep))}subtract(t){return this.assertSame(t),this.init(this.ep.subtract(t.ep))}multiply(t){return this.init(this.ep.multiply(t))}multiplyUnsafe(t){return this.init(this.ep.multiplyUnsafe(t))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(t,r){return this.init(this.ep.precompute(t,r))}toRawBytes(){return this.toBytes()}};function Bh(e,t,r={}){if(typeof t!="function")throw new Error('"hash" function param is required');Ft(r,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=r,{BASE:s,Fp:o,Fn:i}=e,a=r.randomBytes||be,c=r.adjustScalarBytes||(S=>S),f=r.domain||((S,L,R)=>{if(Jt(R,"phflag"),L.length||R)throw new Error("Contexts/pre-hash are not supported");return S});function u(S){return i.create(Kt(S))}function l(S){let L=E.secretKey;S=Y("private key",S,L);let R=Y("hashed private key",t(S),2*L),T=c(R.slice(0,L)),m=R.slice(L,2*L),y=u(T);return{head:T,prefix:m,scalar:y}}function h(S){let{head:L,prefix:R,scalar:T}=l(S),m=s.multiply(T),y=m.toBytes();return{head:L,prefix:R,scalar:T,point:m,pointBytes:y}}function d(S){return h(S).pointBytes}function p(S=Uint8Array.of(),...L){let R=Ct(...L);return u(t(f(R,Y("context",S),!!n)))}function w(S,L,R={}){S=Y("message",S),n&&(S=n(S));let{prefix:T,scalar:m,pointBytes:y}=h(L),b=p(R.context,T,S),A=s.multiply(b).toBytes(),_=p(R.context,A,y,S),C=i.create(b+_*m);if(!i.isValid(C))throw new Error("sign failed: invalid s");let v=Ct(A,i.toBytes(C));return Dt(v,E.signature,"result")}let g={zip215:!0};function x(S,L,R,T=g){let{context:m,zip215:y}=T,b=E.signature;S=Y("signature",S,b),L=Y("message",L),R=Y("publicKey",R,E.publicKey),y!==void 0&&Jt(y,"zip215"),n&&(L=n(L));let A=b/2,_=S.subarray(0,A),C=Kt(S.subarray(A,b)),v,I,D;try{v=e.fromBytes(R,y),I=e.fromBytes(_,y),D=s.multiplyUnsafe(C)}catch{return!1}if(!y&&v.isSmallOrder())return!1;let O=p(m,I.toBytes(),v.toBytes(),L);return I.add(v.multiplyUnsafe(O)).subtract(D).clearCofactor().is0()}let B=o.BYTES,E={secretKey:B,publicKey:B,signature:2*B,seed:B};function P(S=a(E.seed)){return Dt(S,E.seed,"seed")}function N(S){let L=U.randomSecretKey(S);return{secretKey:L,publicKey:d(L)}}function k(S){return Xt(S)&&S.length===i.BYTES}function M(S,L){try{return!!e.fromBytes(S,L)}catch{return!1}}let U={getExtendedPublicKey:h,randomSecretKey:P,isValidSecretKey:k,isValidPublicKey:M,toMontgomery(S){let{y:L}=e.fromBytes(S),R=E.publicKey,T=R===32;if(!T&&R!==57)throw new Error("only defined for 25519 and 448");let m=T?o.div(mt+L,mt-L):o.div(L-mt,L+mt);return o.toBytes(m)},toMontgomerySecret(S){let L=E.secretKey;Dt(S,L);let R=t(S.subarray(0,L));return c(R).subarray(0,L)},randomPrivateKey:P,precompute(S=8,L=e.BASE){return L.precompute(S,!1)}};return Object.freeze({keygen:N,getPublicKey:d,sign:w,verify:x,utils:U,Point:e,lengths:E})}function _h(e){let t={a:e.a,d:e.d,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},r=e.Fp,n=Pt(t.n,e.nBitLength,!0),s={Fp:r,Fn:n,uvRatio:e.uvRatio},o={randomBytes:e.randomBytes,adjustScalarBytes:e.adjustScalarBytes,domain:e.domain,prehash:e.prehash,mapToCurve:e.mapToCurve};return{CURVE:t,curveOpts:s,hash:e.hash,eddsaOpts:o}}function Ih(e,t){let r=t.Point;return Object.assign({},t,{ExtendedPoint:r,CURVE:e,nBitLength:r.Fn.BITS,nByteLength:r.Fn.BYTES})}function kc(e){let{CURVE:t,curveOpts:r,hash:n,eddsaOpts:s}=_h(e),o=Ah(t,r),i=Bh(o,n,s);return Ih(e,i)}var Jr=BigInt(0),yr=BigInt(1),qn=BigInt(2);function Ch(e){return Ft(e,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...e})}function Hc(e){let t=Ch(e),{P:r,type:n,adjustScalarBytes:s,powPminus2:o,randomBytes:i}=t,a=n==="x25519";if(!a&&n!=="x448")throw new Error("invalid type");let c=i||be,f=a?255:448,u=a?32:56,l=BigInt(a?9:5),h=BigInt(a?121665:39081),d=a?qn**BigInt(254):qn**BigInt(447),p=a?BigInt(8)*qn**BigInt(251)-yr:BigInt(4)*qn**BigInt(445)-yr,w=d+p+yr,g=m=>rt(m,r),x=B(l);function B(m){return Yr(g(m),u)}function E(m){let y=Y("u coordinate",m,u);return a&&(y[31]&=127),g(Kt(y))}function P(m){return Kt(s(Y("scalar",m,u)))}function N(m,y){let b=U(E(y),P(m));if(b===Jr)throw new Error("invalid private or public key received");return B(b)}function k(m){return N(m,x)}function M(m,y,b){let A=g(m*(y-b));return y=g(y-A),b=g(b+A),{x_2:y,x_3:b}}function U(m,y){ve("u",m,Jr,r),ve("scalar",y,d,w);let b=y,A=m,_=yr,C=Jr,v=m,I=yr,D=Jr;for(let z=BigInt(f-1);z>=Jr;z--){let F=b>>z&yr;D^=F,{x_2:_,x_3:v}=M(D,_,v),{x_2:C,x_3:I}=M(D,C,I),D=F;let V=_+C,$=g(V*V),X=_-C,it=g(X*X),G=$-it,dt=v+I,Je=v-I,Ur=g(Je*V),Kr=g(dt*X),Ca=Ur+Kr,La=Ur-Kr;v=g(Ca*Ca),I=g(A*g(La*La)),_=g($*it),C=g(G*($+g(h*G)))}({x_2:_,x_3:v}=M(D,_,v)),{x_2:C,x_3:I}=M(D,C,I);let O=o(C);return g(_*O)}let S={secretKey:u,publicKey:u,seed:u},L=(m=c(u))=>(Et(m,S.seed),m);function R(m){let y=L(m);return{secretKey:y,publicKey:k(y)}}return{keygen:R,getSharedSecret:(m,y)=>N(m,y),getPublicKey:m=>k(m),scalarMult:N,scalarMultBase:k,utils:{randomSecretKey:L,randomPrivateKey:L},GuBytes:x.slice(),lengths:S}}var Lh=BigInt(0),ne=BigInt(1),Vc=BigInt(2),Th=BigInt(3),Dh=BigInt(5),Ph=BigInt(8),gr=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),tn={p:gr,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Ph,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Fc(e){let t=BigInt(10),r=BigInt(20),n=BigInt(40),s=BigInt(80),o=gr,a=e*e%o*e%o,c=nt(a,Vc,o)*a%o,f=nt(c,ne,o)*e%o,u=nt(f,Dh,o)*f%o,l=nt(u,t,o)*u%o,h=nt(l,r,o)*l%o,d=nt(h,n,o)*h%o,p=nt(d,s,o)*d%o,w=nt(p,s,o)*d%o,g=nt(w,t,o)*u%o;return{pow_p_5_8:nt(g,Vc,o)*e%o,b2:a}}function Wc(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var Lo=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Po(e,t){let r=gr,n=rt(t*t*t,r),s=rt(n*n*t,r),o=Fc(e*s).pow_p_5_8,i=rt(e*n*o,r),a=rt(t*i*i,r),c=i,f=rt(i*Lo,r),u=a===e,l=a===rt(-e,r),h=a===rt(-e*Lo,r);return u&&(i=c),(l||h)&&(i=f),te(i,r)&&(i=rt(-i,r)),{isValid:u||l,value:i}}var re=Pt(tn.p,{isLE:!0}),Rh=Pt(tn.n,{isLE:!0}),Oh={...tn,Fp:re,hash:bc,adjustScalarBytes:Wc,uvRatio:Po},se=kc(Oh);var en=(()=>{let e=re.ORDER;return Hc({P:e,type:"x25519",powPminus2:t=>{let{pow_p_5_8:r,b2:n}=Fc(t);return rt(nt(r,Th,e)*n,e)},adjustScalarBytes:Wc})})();var To=Lo,Uh=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Kh=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),Nh=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),Mh=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),qc=e=>Po(ne,e),kh=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Do=e=>se.Point.Fp.create(Kt(e)&kh);function zc(e){let{d:t}=tn,r=gr,n=x=>re.create(x),s=n(To*e*e),o=n((s+ne)*Nh),i=BigInt(-1),a=n((i-t*s)*n(s+t)),{isValid:c,value:f}=Po(o,a),u=n(f*e);te(u,r)||(u=n(-u)),c||(f=u),c||(i=s);let l=n(i*(s-ne)*Mh-a),h=f*f,d=n((f+f)*a),p=n(l*Uh),w=n(ne-h),g=n(ne+h);return new se.Point(n(d*g),n(w*p),n(p*g),n(d*w))}function Hh(e){Et(e,64);let t=Do(e.subarray(0,32)),r=zc(t),n=Do(e.subarray(32,64)),s=zc(n);return new oe(r.add(s))}var oe=class e extends Vn{constructor(t){super(t)}static fromAffine(t){return new e(se.Point.fromAffine(t))}assertSame(t){if(!(t instanceof e))throw new Error("RistrettoPoint expected")}init(t){return new e(t)}static hashToCurve(t){return Hh(Y("ristrettoHash",t,64))}static fromBytes(t){Et(t,32);let{a:r,d:n}=tn,s=gr,o=P=>re.create(P),i=Do(t);if(!wc(re.toBytes(i),t)||te(i,s))throw new Error("invalid ristretto255 encoding 1");let a=o(i*i),c=o(ne+r*a),f=o(ne-r*a),u=o(c*c),l=o(f*f),h=o(r*n*u-l),{isValid:d,value:p}=qc(o(h*l)),w=o(p*f),g=o(p*w*h),x=o((i+i)*w);te(x,s)&&(x=o(-x));let B=o(c*g),E=o(x*B);if(!d||te(E,s)||B===Lh)throw new Error("invalid ristretto255 encoding 2");return new e(new se.Point(x,B,ne,E))}static fromHex(t){return e.fromBytes(Y("ristrettoHex",t,32))}static msm(t,r){return mr(e,se.Point.Fn,t,r)}toBytes(){let{X:t,Y:r,Z:n,T:s}=this.ep,o=gr,i=g=>re.create(g),a=i(i(n+r)*i(n-r)),c=i(t*r),f=i(c*c),{value:u}=qc(i(a*f)),l=i(u*a),h=i(u*c),d=i(l*h*s),p;if(te(s*d,o)){let g=i(r*To),x=i(t*To);t=g,r=x,p=i(l*Kh)}else p=h;te(t*d,o)&&(r=i(-r));let w=i((n-r)*p);return te(w,o)&&(w=i(-w)),re.toBytes(w)}equals(t){this.assertSame(t);let{X:r,Y:n}=this.ep,{X:s,Y:o}=t.ep,i=f=>re.create(f),a=i(r*o)===i(n*s),c=i(n*o)===i(r*s);return a||c}is0(){return this.equals(e.ZERO)}};oe.BASE=new oe(se.Point.BASE);oe.ZERO=new oe(se.Point.ZERO);oe.Fp=re;oe.Fn=Rh;var rn=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},zn=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var $c={get(e=globalThis){let t=e.crypto;if(t?.subtle==null)throw new zn("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return t}};var Nt=$c;var Fn=32;var Ro,Vh=(async()=>{try{return await Nt.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function qh(e,t,r){if(e.buffer instanceof ArrayBuffer){let n=await Nt.get().subtle.importKey("raw",e.buffer,{name:"Ed25519"},!1,["verify"]);return await Nt.get().subtle.verify({name:"Ed25519"},n,t,r instanceof Uint8Array?r:r.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function zh(e,t,r){return se.verify(t,r instanceof Uint8Array?r:r.subarray(),e)}async function Gc(e,t,r){return Ro==null&&(Ro=await Vh),Ro?qh(e,t,r):zh(e,t,r)}function Wn(e){return e==null?!1:typeof e.then=="function"&&typeof e.catch=="function"&&typeof e.finally=="function"}var $n=class{type="Ed25519";raw;constructor(t){this.raw=Oo(t,Fn)}toMultihash(){return kt.digest(ye(this))}toCID(){return ft.createV1(114,this.toMultihash())}toString(){return ct.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:lt(this.raw,t.raw)}verify(t,r,n){n?.signal?.throwIfAborted();let s=Gc(this.raw,r,t);return Wn(s)?s.then(o=>(n?.signal?.throwIfAborted(),o)):s}};function Uo(e){return e=Oo(e,Fn),new $n(e)}function Oo(e,t){if(e=Uint8Array.from(e??[]),e.length!==t)throw new et(`Key must be a Uint8Array of length ${t}, got ${e.length}`);return e}var Wh=Math.pow(2,7),$h=Math.pow(2,14),Gh=Math.pow(2,21),Ko=Math.pow(2,28),No=Math.pow(2,35),Mo=Math.pow(2,42),ko=Math.pow(2,49),Q=128,St=127;function vt(e){if(e<Wh)return 1;if(e<$h)return 2;if(e<Gh)return 3;if(e<Ko)return 4;if(e<No)return 5;if(e<Mo)return 6;if(e<ko)return 7;if(Number.MAX_SAFE_INTEGER!=null&&e>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function br(e,t,r=0){switch(vt(e)){case 8:t[r++]=e&255|Q,e/=128;case 7:t[r++]=e&255|Q,e/=128;case 6:t[r++]=e&255|Q,e/=128;case 5:t[r++]=e&255|Q,e/=128;case 4:t[r++]=e&255|Q,e>>>=7;case 3:t[r++]=e&255|Q,e>>>=7;case 2:t[r++]=e&255|Q,e>>>=7;case 1:{t[r++]=e&255,e>>>=7;break}default:throw new Error("unreachable")}return t}function jh(e,t,r=0){switch(vt(e)){case 8:t.set(r++,e&255|Q),e/=128;case 7:t.set(r++,e&255|Q),e/=128;case 6:t.set(r++,e&255|Q),e/=128;case 5:t.set(r++,e&255|Q),e/=128;case 4:t.set(r++,e&255|Q),e>>>=7;case 3:t.set(r++,e&255|Q),e>>>=7;case 2:t.set(r++,e&255|Q),e>>>=7;case 1:{t.set(r++,e&255),e>>>=7;break}default:throw new Error("unreachable")}return t}function Ho(e,t){let r=e[t],n=0;if(n+=r&St,r<Q||(r=e[t+1],n+=(r&St)<<7,r<Q)||(r=e[t+2],n+=(r&St)<<14,r<Q)||(r=e[t+3],n+=(r&St)<<21,r<Q)||(r=e[t+4],n+=(r&St)*Ko,r<Q)||(r=e[t+5],n+=(r&St)*No,r<Q)||(r=e[t+6],n+=(r&St)*Mo,r<Q)||(r=e[t+7],n+=(r&St)*ko,r<Q))return n;throw new RangeError("Could not decode varint")}function Zh(e,t){let r=e.get(t),n=0;if(n+=r&St,r<Q||(r=e.get(t+1),n+=(r&St)<<7,r<Q)||(r=e.get(t+2),n+=(r&St)<<14,r<Q)||(r=e.get(t+3),n+=(r&St)<<21,r<Q)||(r=e.get(t+4),n+=(r&St)*Ko,r<Q)||(r=e.get(t+5),n+=(r&St)*No,r<Q)||(r=e.get(t+6),n+=(r&St)*Mo,r<Q)||(r=e.get(t+7),n+=(r&St)*ko,r<Q))return n;throw new RangeError("Could not decode varint")}function Zc(e,t,r=0){return t==null&&(t=gt(vt(e))),t instanceof Uint8Array?br(e,t,r):jh(e,t,r)}function He(e,t=0){return e instanceof Uint8Array?Ho(e,t):Zh(e,t)}var qo=new Float32Array([-0]),_e=new Uint8Array(qo.buffer);function Yc(e,t,r){qo[0]=e,t[r]=_e[0],t[r+1]=_e[1],t[r+2]=_e[2],t[r+3]=_e[3]}function Xc(e,t){return _e[0]=e[t],_e[1]=e[t+1],_e[2]=e[t+2],_e[3]=e[t+3],qo[0]}var zo=new Float64Array([-0]),At=new Uint8Array(zo.buffer);function Qc(e,t,r){zo[0]=e,t[r]=At[0],t[r+1]=At[1],t[r+2]=At[2],t[r+3]=At[3],t[r+4]=At[4],t[r+5]=At[5],t[r+6]=At[6],t[r+7]=At[7]}function Jc(e,t){return At[0]=e[t],At[1]=e[t+1],At[2]=e[t+2],At[3]=e[t+3],At[4]=e[t+4],At[5]=e[t+5],At[6]=e[t+6],At[7]=e[t+7],zo[0]}var Yh=BigInt(Number.MAX_SAFE_INTEGER),Xh=BigInt(Number.MIN_SAFE_INTEGER),Rt=class e{lo;hi;constructor(t,r){this.lo=t|0,this.hi=r|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let r=~this.lo+1>>>0,n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(r+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let r=~this.lo+1>>>0,n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(BigInt(r)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,r=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?r===0?t<16384?t<128?1:2:t<2097152?3:4:r<16384?r<128?5:6:r<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return Ve;if(t<Yh&&t>Xh)return this.fromNumber(Number(t));let r=t<0n;r&&(t=-t);let n=t>>32n,s=t-(n<<32n);return r&&(n=~n|0n,s=~s|0n,++s>tu&&(s=0n,++n>tu&&(n=0n))),new e(Number(s),Number(n))}static fromNumber(t){if(t===0)return Ve;let r=t<0;r&&(t=-t);let n=t>>>0,s=(t-n)/4294967296>>>0;return r&&(s=~s>>>0,n=~n>>>0,++n>4294967295&&(n=0,++s>4294967295&&(s=0))),new e(n,s)}static from(t){return typeof t=="number"?e.fromNumber(t):typeof t=="bigint"?e.fromBigInt(t):typeof t=="string"?e.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new e(t.low>>>0,t.high>>>0):Ve}},Ve=new Rt(0,0);Ve.toBigInt=function(){return 0n};Ve.zzEncode=Ve.zzDecode=function(){return this};Ve.length=function(){return 1};var tu=4294967296n;function eu(e){let t=0,r=0;for(let n=0;n<e.length;++n)r=e.charCodeAt(n),r<128?t+=1:r<2048?t+=2:(r&64512)===55296&&(e.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function ru(e,t,r){if(r-t<1)return"";let s,o=[],i=0,a;for(;t<r;)a=e[t++],a<128?o[i++]=a:a>191&&a<224?o[i++]=(a&31)<<6|e[t++]&63:a>239&&a<365?(a=((a&7)<<18|(e[t++]&63)<<12|(e[t++]&63)<<6|e[t++]&63)-65536,o[i++]=55296+(a>>10),o[i++]=56320+(a&1023)):o[i++]=(a&15)<<12|(e[t++]&63)<<6|e[t++]&63,i>8191&&((s??(s=[])).push(String.fromCharCode.apply(String,o)),i=0);return s!=null?(i>0&&s.push(String.fromCharCode.apply(String,o.slice(0,i))),s.join("")):String.fromCharCode.apply(String,o.slice(0,i))}function Fo(e,t,r){let n=r,s,o;for(let i=0;i<e.length;++i)s=e.charCodeAt(i),s<128?t[r++]=s:s<2048?(t[r++]=s>>6|192,t[r++]=s&63|128):(s&64512)===55296&&((o=e.charCodeAt(i+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++i,t[r++]=s>>18|240,t[r++]=s>>12&63|128,t[r++]=s>>6&63|128,t[r++]=s&63|128):(t[r++]=s>>12|224,t[r++]=s>>6&63|128,t[r++]=s&63|128);return r-n}function qt(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function Gn(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}var Wo=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,qt(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw qt(this,4);return Gn(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw qt(this,4);return Gn(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw qt(this,4);let t=Xc(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw qt(this,4);let t=Jc(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),r=this.pos,n=this.pos+t;if(n>this.len)throw qt(this,t);return this.pos+=t,r===n?new Uint8Array(0):this.buf.subarray(r,n)}string(){let t=this.bytes();return ru(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw qt(this,t);this.pos+=t}else do if(this.pos>=this.len)throw qt(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new Rt(0,0),r=0;if(this.len-this.pos>4){for(;r<4;++r)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;r=0}else{for(;r<3;++r){if(this.pos>=this.len)throw qt(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<r*7)>>>0,t}if(this.len-this.pos>4){for(;r<5;++r)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;r<5;++r){if(this.pos>=this.len)throw qt(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw qt(this,8);let t=Gn(this.buf,this.pos+=4),r=Gn(this.buf,this.pos+=4);return new Rt(t,r)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=Ho(this.buf,this.pos);return this.pos+=vt(t),t}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function $o(e){return new Wo(e instanceof Uint8Array?e:e.subarray())}function qe(e,t,r){let n=$o(e);return t.decode(n,void 0,r)}function Go(e){let t=e??8192,r=t>>>1,n,s=t;return function(i){if(i<1||i>r)return gt(i);s+i>t&&(n=gt(t),s=0);let a=n.subarray(s,s+=i);return(s&7)!==0&&(s=(s|7)+1),a}}var ze=class{fn;len;next;val;constructor(t,r,n){this.fn=t,this.len=r,this.next=void 0,this.val=n}};function jo(){}var Yo=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},Qh=Go();function Jh(e){return globalThis.Buffer!=null?gt(e):Qh(e)}var sn=class{len;head;tail;states;constructor(){this.len=0,this.head=new ze(jo,0,0),this.tail=this.head,this.states=null}_push(t,r,n){return this.tail=this.tail.next=new ze(t,r,n),this.len+=r,this}uint32(t){return this.len+=(this.tail=this.tail.next=new Xo((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(jn,10,Rt.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let r=Rt.fromBigInt(t);return this._push(jn,r.length(),r)}uint64Number(t){return this._push(br,vt(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let r=Rt.fromBigInt(t).zzEncode();return this._push(jn,r.length(),r)}sint64Number(t){let r=Rt.fromNumber(t).zzEncode();return this._push(jn,r.length(),r)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(Zo,1,t?1:0)}fixed32(t){return this._push(nn,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let r=Rt.fromBigInt(t);return this._push(nn,4,r.lo)._push(nn,4,r.hi)}fixed64Number(t){let r=Rt.fromNumber(t);return this._push(nn,4,r.lo)._push(nn,4,r.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(Yc,4,t)}double(t){return this._push(Qc,8,t)}bytes(t){let r=t.length>>>0;return r===0?this._push(Zo,1,0):this.uint32(r)._push(ed,r,t)}string(t){let r=eu(t);return r!==0?this.uint32(r)._push(Fo,r,t):this._push(Zo,1,0)}fork(){return this.states=new Yo(this),this.head=this.tail=new ze(jo,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 ze(jo,0,0),this.len=0),this}ldelim(){let t=this.head,r=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=r,this.len+=n),this}finish(){let t=this.head.next,r=Jh(this.len),n=0;for(;t!=null;)t.fn(t.val,r,n),n+=t.len,t=t.next;return r}};function Zo(e,t,r){t[r]=e&255}function td(e,t,r){for(;e>127;)t[r++]=e&127|128,e>>>=7;t[r]=e}var Xo=class extends ze{next;constructor(t,r){super(td,t,r),this.next=void 0}};function jn(e,t,r){for(;e.hi!==0;)t[r++]=e.lo&127|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[r++]=e.lo&127|128,e.lo=e.lo>>>7;t[r++]=e.lo}function nn(e,t,r){t[r]=e&255,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}function ed(e,t,r){t.set(e,r)}globalThis.Buffer!=null&&(sn.prototype.bytes=function(e){let t=e.length>>>0;return this.uint32(t),t>0&&this._push(rd,t,e),this},sn.prototype.string=function(e){let t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(nd,t,e),this});function rd(e,t,r){t.set(e,r)}function nd(e,t,r){e.length<40?Fo(e,t,r):t.utf8Write!=null?t.utf8Write(e,r):t.set(Z(e),r)}function Qo(){return new sn}function Fe(e,t){let r=Qo();return t.encode(e,r,{lengthDelimited:!1}),r.finish()}var xr;(function(e){e[e.VARINT=0]="VARINT",e[e.BIT64=1]="BIT64",e[e.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",e[e.START_GROUP=3]="START_GROUP",e[e.END_GROUP=4]="END_GROUP",e[e.BIT32=5]="BIT32"})(xr||(xr={}));function Zn(e,t,r,n){return{name:e,type:t,encode:r,decode:n}}function Jo(e){function t(s){if(e[s.toString()]==null)throw new Error("Invalid enum value");return e[s]}let r=function(o,i){let a=t(o);i.int32(a)},n=function(o){let i=o.int32();return t(i)};return Zn("enum",xr.VARINT,r,n)}function We(e,t){return Zn("message",xr.LENGTH_DELIMITED,e,t)}var on=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var ut;(function(e){e.RSA="RSA",e.Ed25519="Ed25519",e.secp256k1="secp256k1",e.ECDSA="ECDSA"})(ut||(ut={}));var ti;(function(e){e[e.RSA=0]="RSA",e[e.Ed25519=1]="Ed25519",e[e.secp256k1=2]="secp256k1",e[e.ECDSA=3]="ECDSA"})(ti||(ti={}));(function(e){e.codec=()=>Jo(ti)})(ut||(ut={}));var Wt;(function(e){let t;e.codec=()=>(t==null&&(t=We((r,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),r.Type!=null&&(n.uint32(8),ut.codec().encode(r.Type,n)),r.Data!=null&&(n.uint32(18),n.bytes(r.Data)),s.lengthDelimited!==!1&&n.ldelim()},(r,n,s={})=>{let o={},i=n==null?r.len:r.pos+n;for(;r.pos<i;){let a=r.uint32();switch(a>>>3){case 1:{o.Type=ut.codec().decode(r);break}case 2:{o.Data=r.bytes();break}default:{r.skipType(a&7);break}}}return o})),t),e.encode=r=>Fe(r,e.codec()),e.decode=(r,n)=>qe(r,e.codec(),n)})(Wt||(Wt={}));var ei;(function(e){let t;e.codec=()=>(t==null&&(t=We((r,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),r.Type!=null&&(n.uint32(8),ut.codec().encode(r.Type,n)),r.Data!=null&&(n.uint32(18),n.bytes(r.Data)),s.lengthDelimited!==!1&&n.ldelim()},(r,n,s={})=>{let o={},i=n==null?r.len:r.pos+n;for(;r.pos<i;){let a=r.uint32();switch(a>>>3){case 1:{o.Type=ut.codec().decode(r);break}case 2:{o.Data=r.bytes();break}default:{r.skipType(a&7);break}}}return o})),t),e.encode=r=>Fe(r,e.codec()),e.decode=(r,n)=>qe(r,e.codec(),n)})(ei||(ei={}));var cn={};It(cn,{MAX_RSA_KEY_SIZE:()=>ri,generateRSAKeyPair:()=>cu,jwkToJWKKeyPair:()=>uu,jwkToPkcs1:()=>ad,jwkToPkix:()=>ii,jwkToRSAPrivateKey:()=>fi,pkcs1MessageToJwk:()=>si,pkcs1MessageToRSAPrivateKey:()=>ai,pkcs1ToJwk:()=>id,pkcs1ToRSAPrivateKey:()=>au,pkixMessageToJwk:()=>oi,pkixMessageToRSAPublicKey:()=>ui,pkixToJwk:()=>cd,pkixToRSAPublicKey:()=>ci});var Yn=Se;var wr=class{type="RSA";jwk;_raw;_multihash;constructor(t,r){this.jwk=t,this._multihash=r}get raw(){return this._raw==null&&(this._raw=cn.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return ft.createV1(114,this._multihash)}toString(){return ct.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:lt(this.raw,t.raw)}verify(t,r,n){return iu(this.jwk,r,t,n)}},an=class{type="RSA";jwk;_raw;publicKey;constructor(t,r){this.jwk=t,this.publicKey=r}get raw(){return this._raw==null&&(this._raw=cn.jwkToPkcs1(this.jwk)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:lt(this.raw,t.raw)}sign(t,r){return ou(this.jwk,t,r)}};var ri=8192,ni=18,sd=1062,od=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function id(e){let t=Zt(e);return si(t)}function si(e){return{n:q(e[1],"base64url"),e:q(e[2],"base64url"),d:q(e[3],"base64url"),p:q(e[4],"base64url"),q:q(e[5],"base64url"),dp:q(e[6],"base64url"),dq:q(e[7],"base64url"),qi:q(e[8],"base64url"),kty:"RSA"}}function ad(e){if(e.n==null||e.e==null||e.d==null||e.p==null||e.q==null||e.dp==null||e.dq==null||e.qi==null)throw new et("JWK was missing components");return me([Tt(Uint8Array.from([0])),Tt(Z(e.n,"base64url")),Tt(Z(e.e,"base64url")),Tt(Z(e.d,"base64url")),Tt(Z(e.p,"base64url")),Tt(Z(e.q,"base64url")),Tt(Z(e.dp,"base64url")),Tt(Z(e.dq,"base64url")),Tt(Z(e.qi,"base64url"))]).subarray()}function cd(e){let t=Zt(e,{offset:0});return oi(t)}function oi(e){let t=Zt(e[1],{offset:0});return{kty:"RSA",n:q(t[0],"base64url"),e:q(t[1],"base64url")}}function ii(e){if(e.n==null||e.e==null)throw new et("JWK was missing components");return me([od,Rn(me([Tt(Z(e.n,"base64url")),Tt(Z(e.e,"base64url"))]))]).subarray()}function au(e){let t=Zt(e);return ai(t)}function ai(e){let t=si(e);return fi(t)}function ci(e,t){if(e.byteLength>=sd)throw new er("Key size is too large");let r=Zt(e,{offset:0});return ui(r,e,t)}function ui(e,t,r){let n=oi(e);if(r==null){let s=Yn(Wt.encode({Type:ut.RSA,Data:t}));r=Mt(ni,s)}return new wr(n,r)}function fi(e){if(lu(e)>ri)throw new et("Key size is too large");let t=uu(e),r=Yn(Wt.encode({Type:ut.RSA,Data:ii(t.publicKey)})),n=Mt(ni,r);return new an(t.privateKey,new wr(t.publicKey,n))}async function cu(e){if(e>ri)throw new et("Key size is too large");let t=await fu(e),r=Yn(Wt.encode({Type:ut.RSA,Data:ii(t.publicKey)})),n=Mt(ni,r);return new an(t.privateKey,new wr(t.publicKey,n))}function uu(e){if(e==null)throw new et("Missing key parameter");return{privateKey:e,publicKey:{kty:e.kty,n:e.n,e:e.e}}}async function fu(e,t){let r=await Nt.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);t?.signal?.throwIfAborted();let n=await ud(r,t);return{privateKey:n[0],publicKey:n[1]}}async function ou(e,t,r){let n=await Nt.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);r?.signal?.throwIfAborted();let s=await Nt.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,t instanceof Uint8Array?t:t.subarray());return r?.signal?.throwIfAborted(),new Uint8Array(s,0,s.byteLength)}async function iu(e,t,r,n){let s=await Nt.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let o=await Nt.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},s,t,r instanceof Uint8Array?r:r.subarray());return n?.signal?.throwIfAborted(),o}async function ud(e,t){if(e.privateKey==null||e.publicKey==null)throw new et("Private and public key are required");let r=await Promise.all([Nt.get().subtle.exportKey("jwk",e.privateKey),Nt.get().subtle.exportKey("jwk",e.publicKey)]);return t?.signal?.throwIfAborted(),r}function lu(e){if(e.kty!=="RSA")throw new et("invalid key type");if(e.n==null)throw new et("invalid key modulus");return Z(e.n,"base64url").length*8}var Xn=class extends ur{constructor(t,r){super(),this.finished=!1,this.destroyed=!1,Oe(t);let n=ge(r);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let s=this.blockLen,o=new Uint8Array(s);o.set(n.length>s?t.create().update(n).digest():n);for(let i=0;i<o.length;i++)o[i]^=54;this.iHash.update(o),this.oHash=t.create();for(let i=0;i<o.length;i++)o[i]^=106;this.oHash.update(o),Ht(o)}update(t){return fr(this),this.iHash.update(t),this}digestInto(t){fr(this),Et(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));let{oHash:r,iHash:n,finished:s,destroyed:o,blockLen:i,outputLen:a}=this;return t=t,t.finished=s,t.destroyed=o,t.blockLen=i,t.outputLen=a,t.oHash=r._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Er=(e,t,r)=>new Xn(e,t).update(r).digest();Er.create=(e,t)=>new Xn(e,t);var hu=(e,t)=>(e+(e>=0?t:-t)/du)/t;function fd(e,t,r){let[[n,s],[o,i]]=t,a=hu(i*e,r),c=hu(-s*e,r),f=e-a*n-c*o,u=-a*s-c*i,l=f<ae,h=u<ae;l&&(f=-f),h&&(u=-u);let d=Ae(Math.ceil(Mn(r)/2))+vr;if(f<ae||f>=d||u<ae||u>=d)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:l,k1:f,k2neg:h,k2:u}}function hi(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function li(e,t){let r={};for(let n of Object.keys(t))r[n]=e[n]===void 0?t[n]:e[n];return Jt(r.lowS,"lowS"),Jt(r.prehash,"prehash"),r.format!==void 0&&hi(r.format),r}var di=class extends Error{constructor(t=""){super(t)}},ie={Err:di,_tlv:{encode:(e,t)=>{let{Err:r}=ie;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length&1)throw new r("tlv.encode: unpadded data");let n=t.length/2,s=Zr(n);if(s.length/2&128)throw new r("tlv.encode: long form length too big");let o=n>127?Zr(s.length/2|128):"";return Zr(e)+o+s+t},decode(e,t){let{Err:r}=ie,n=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");let s=t[n++],o=!!(s&128),i=0;if(!o)i=s;else{let c=s&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let f=t.subarray(n,n+c);if(f.length!==c)throw new r("tlv.decode: length bytes not complete");if(f[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let u of f)i=i<<8|u;if(n+=c,i<128)throw new r("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(e){let{Err:t}=ie;if(e<ae)throw new t("integer: negative integers are not allowed");let r=Zr(e);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return r},decode(e){let{Err:t}=ie;if(e[0]&128)throw new t("invalid signature integer: negative");if(e[0]===0&&!(e[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return lr(e)}},toSig(e){let{Err:t,_int:r,_tlv:n}=ie,s=Y("signature",e),{v:o,l:i}=n.decode(48,s);if(i.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,o),{v:f,l:u}=n.decode(2,c);if(u.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(f)}},hexFromSig(e){let{_tlv:t,_int:r}=ie,n=t.encode(2,r.encode(e.r)),s=t.encode(2,r.encode(e.s)),o=n+s;return t.encode(48,o)}},ae=BigInt(0),vr=BigInt(1),du=BigInt(2),Qn=BigInt(3),ld=BigInt(4);function Sr(e,t){let{BYTES:r}=e,n;if(typeof t=="bigint")n=t;else{let s=Y("private key",t);try{n=e.fromBytes(s)}catch{throw new Error(`invalid private key: expected ui8a of size ${r}, got ${typeof t}`)}}if(!e.isValidNot0(n))throw new Error("invalid private key: out of range [1..N-1]");return n}function hd(e,t={}){let r=Hn("weierstrass",e,t),{Fp:n,Fn:s}=r,o=r.CURVE,{h:i,n:a}=o;Ft(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:c}=t;if(c&&(!n.is0(o.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let f=mu(n,s);function u(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function l(T,m,y){let{x:b,y:A}=m.toAffine(),_=n.toBytes(b);if(Jt(y,"isCompressed"),y){u();let C=!n.isOdd(A);return Ct(pu(C),_)}else return Ct(Uint8Array.of(4),_,n.toBytes(A))}function h(T){Dt(T,void 0,"Point");let{publicKey:m,publicKeyUncompressed:y}=f,b=T.length,A=T[0],_=T.subarray(1);if(b===m&&(A===2||A===3)){let C=n.fromBytes(_);if(!n.isValid(C))throw new Error("bad point: is not on curve, wrong x");let v=w(C),I;try{I=n.sqrt(v)}catch(z){let F=z instanceof Error?": "+z.message:"";throw new Error("bad point: is not on curve, sqrt error"+F)}u();let D=n.isOdd(I);return(A&1)===1!==D&&(I=n.neg(I)),{x:C,y:I}}else if(b===y&&A===4){let C=n.BYTES,v=n.fromBytes(_.subarray(0,C)),I=n.fromBytes(_.subarray(C,C*2));if(!g(v,I))throw new Error("bad point: is not on curve");return{x:v,y:I}}else throw new Error(`bad point: got length ${b}, expected compressed=${m} or uncompressed=${y}`)}let d=t.toBytes||l,p=t.fromBytes||h;function w(T){let m=n.sqr(T),y=n.mul(m,T);return n.add(n.add(y,n.mul(T,o.a)),o.b)}function g(T,m){let y=n.sqr(m),b=w(T);return n.eql(y,b)}if(!g(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let x=n.mul(n.pow(o.a,Qn),ld),B=n.mul(n.sqr(o.b),BigInt(27));if(n.is0(n.add(x,B)))throw new Error("bad curve params: a or b");function E(T,m,y=!1){if(!n.isValid(m)||y&&n.is0(m))throw new Error(`bad point coordinate ${T}`);return m}function P(T){if(!(T instanceof S))throw new Error("ProjectivePoint expected")}function N(T){if(!c||!c.basises)throw new Error("no endo");return fd(T,c.basises,s.ORDER)}let k=hr((T,m)=>{let{X:y,Y:b,Z:A}=T;if(n.eql(A,n.ONE))return{x:y,y:b};let _=T.is0();m==null&&(m=_?n.ONE:n.inv(A));let C=n.mul(y,m),v=n.mul(b,m),I=n.mul(A,m);if(_)return{x:n.ZERO,y:n.ZERO};if(!n.eql(I,n.ONE))throw new Error("invZ was invalid");return{x:C,y:v}}),M=hr(T=>{if(T.is0()){if(t.allowInfinityPoint&&!n.is0(T.Y))return;throw new Error("bad point: ZERO")}let{x:m,y}=T.toAffine();if(!n.isValid(m)||!n.isValid(y))throw new Error("bad point: x or y not field elements");if(!g(m,y))throw new Error("bad point: equation left != right");if(!T.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function U(T,m,y,b,A){return y=new S(n.mul(y.X,T),y.Y,y.Z),m=Qr(b,m),y=Qr(A,y),m.add(y)}class S{constructor(m,y,b){this.X=E("x",m),this.Y=E("y",y,!0),this.Z=E("z",b),Object.freeze(this)}static CURVE(){return o}static fromAffine(m){let{x:y,y:b}=m||{};if(!m||!n.isValid(y)||!n.isValid(b))throw new Error("invalid affine point");if(m instanceof S)throw new Error("projective point not allowed");return n.is0(y)&&n.is0(b)?S.ZERO:new S(y,b,n.ONE)}static fromBytes(m){let y=S.fromAffine(p(Dt(m,void 0,"point")));return y.assertValidity(),y}static fromHex(m){return S.fromBytes(Y("pointHex",m))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(m=8,y=!0){return R.createCache(this,m),y||this.multiply(Qn),this}assertValidity(){M(this)}hasEvenY(){let{y:m}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(m)}equals(m){P(m);let{X:y,Y:b,Z:A}=this,{X:_,Y:C,Z:v}=m,I=n.eql(n.mul(y,v),n.mul(_,A)),D=n.eql(n.mul(b,v),n.mul(C,A));return I&&D}negate(){return new S(this.X,n.neg(this.Y),this.Z)}double(){let{a:m,b:y}=o,b=n.mul(y,Qn),{X:A,Y:_,Z:C}=this,v=n.ZERO,I=n.ZERO,D=n.ZERO,O=n.mul(A,A),z=n.mul(_,_),F=n.mul(C,C),V=n.mul(A,_);return V=n.add(V,V),D=n.mul(A,C),D=n.add(D,D),v=n.mul(m,D),I=n.mul(b,F),I=n.add(v,I),v=n.sub(z,I),I=n.add(z,I),I=n.mul(v,I),v=n.mul(V,v),D=n.mul(b,D),F=n.mul(m,F),V=n.sub(O,F),V=n.mul(m,V),V=n.add(V,D),D=n.add(O,O),O=n.add(D,O),O=n.add(O,F),O=n.mul(O,V),I=n.add(I,O),F=n.mul(_,C),F=n.add(F,F),O=n.mul(F,V),v=n.sub(v,O),D=n.mul(F,z),D=n.add(D,D),D=n.add(D,D),new S(v,I,D)}add(m){P(m);let{X:y,Y:b,Z:A}=this,{X:_,Y:C,Z:v}=m,I=n.ZERO,D=n.ZERO,O=n.ZERO,z=o.a,F=n.mul(o.b,Qn),V=n.mul(y,_),$=n.mul(b,C),X=n.mul(A,v),it=n.add(y,b),G=n.add(_,C);it=n.mul(it,G),G=n.add(V,$),it=n.sub(it,G),G=n.add(y,A);let dt=n.add(_,v);return G=n.mul(G,dt),dt=n.add(V,X),G=n.sub(G,dt),dt=n.add(b,A),I=n.add(C,v),dt=n.mul(dt,I),I=n.add($,X),dt=n.sub(dt,I),O=n.mul(z,G),I=n.mul(F,X),O=n.add(I,O),I=n.sub($,O),O=n.add($,O),D=n.mul(I,O),$=n.add(V,V),$=n.add($,V),X=n.mul(z,X),G=n.mul(F,G),$=n.add($,X),X=n.sub(V,X),X=n.mul(z,X),G=n.add(G,X),V=n.mul($,G),D=n.add(D,V),V=n.mul(dt,G),I=n.mul(it,I),I=n.sub(I,V),V=n.mul(it,$),O=n.mul(dt,O),O=n.add(O,V),new S(I,D,O)}subtract(m){return this.add(m.negate())}is0(){return this.equals(S.ZERO)}multiply(m){let{endo:y}=t;if(!s.isValidNot0(m))throw new Error("invalid scalar: out of range");let b,A,_=C=>R.cached(this,C,v=>ee(S,v));if(y){let{k1neg:C,k1:v,k2neg:I,k2:D}=N(m),{p:O,f:z}=_(v),{p:F,f:V}=_(D);A=z.add(V),b=U(y.beta,O,F,C,I)}else{let{p:C,f:v}=_(m);b=C,A=v}return ee(S,[b,A])[0]}multiplyUnsafe(m){let{endo:y}=t,b=this;if(!s.isValid(m))throw new Error("invalid scalar: out of range");if(m===ae||b.is0())return S.ZERO;if(m===vr)return b;if(R.hasCache(this))return this.multiply(m);if(y){let{k1neg:A,k1:_,k2neg:C,k2:v}=N(m),{p1:I,p2:D}=Mc(S,b,_,v);return U(y.beta,I,D,A,C)}else return R.unsafe(b,m)}multiplyAndAddUnsafe(m,y,b){let A=this.multiplyUnsafe(y).add(m.multiplyUnsafe(b));return A.is0()?void 0:A}toAffine(m){return k(this,m)}isTorsionFree(){let{isTorsionFree:m}=t;return i===vr?!0:m?m(S,this):R.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:m}=t;return i===vr?this:m?m(S,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(m=!0){return Jt(m,"isCompressed"),this.assertValidity(),d(S,this,m)}toHex(m=!0){return Ut(this.toBytes(m))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(m=!0){return this.toBytes(m)}_setWindowSize(m){this.precompute(m)}static normalizeZ(m){return ee(S,m)}static msm(m,y){return mr(S,s,m,y)}static fromPrivateKey(m){return S.BASE.multiply(Sr(s,m))}}S.BASE=new S(o.Gx,o.Gy,n.ONE),S.ZERO=new S(n.ZERO,n.ONE,n.ZERO),S.Fp=n,S.Fn=s;let L=s.BITS,R=new pr(S,t.endo?Math.ceil(L/2):L);return S.BASE.precompute(8),S}function pu(e){return Uint8Array.of(e?2:3)}function mu(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function dd(e,t={}){let{Fn:r}=e,n=t.randomBytes||be,s=Object.assign(mu(e.Fp,r),{seed:vo(r.ORDER)});function o(d){try{return!!Sr(r,d)}catch{return!1}}function i(d,p){let{publicKey:w,publicKeyUncompressed:g}=s;try{let x=d.length;return p===!0&&x!==w||p===!1&&x!==g?!1:!!e.fromBytes(d)}catch{return!1}}function a(d=n(s.seed)){return Ao(Dt(d,s.seed,"seed"),r.ORDER)}function c(d,p=!0){return e.BASE.multiply(Sr(r,d)).toBytes(p)}function f(d){let p=a(d);return{secretKey:p,publicKey:c(p)}}function u(d){if(typeof d=="bigint")return!1;if(d instanceof e)return!0;let{secretKey:p,publicKey:w,publicKeyUncompressed:g}=s;if(r.allowedLengths||p===w)return;let x=Y("key",d).length;return x===w||x===g}function l(d,p,w=!0){if(u(d)===!0)throw new Error("first arg must be private key");if(u(p)===!1)throw new Error("second arg must be public key");let g=Sr(r,d);return e.fromHex(p).multiply(g).toBytes(w)}return Object.freeze({getPublicKey:c,getSharedSecret:l,keygen:f,Point:e,utils:{isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a,isValidPrivateKey:o,randomPrivateKey:a,normPrivateKeyToScalar:d=>Sr(r,d),precompute(d=8,p=e.BASE){return p.precompute(d,!1)}},lengths:s})}function pd(e,t,r={}){Oe(t),Ft(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let n=r.randomBytes||be,s=r.hmac||((y,...b)=>Er(t,y,Ct(...b))),{Fp:o,Fn:i}=e,{ORDER:a,BITS:c}=i,{keygen:f,getPublicKey:u,getSharedSecret:l,utils:h,lengths:d}=dd(e,r),p={prehash:!1,lowS:typeof r.lowS=="boolean"?r.lowS:!1,format:void 0,extraEntropy:!1},w="compact";function g(y){let b=a>>vr;return y>b}function x(y,b){if(!i.isValidNot0(b))throw new Error(`invalid signature ${y}: out of range 1..Point.Fn.ORDER`);return b}function B(y,b){hi(b);let A=d.signature,_=b==="compact"?A:b==="recovered"?A+1:void 0;return Dt(y,_,`${b} signature`)}class E{constructor(b,A,_){this.r=x("r",b),this.s=x("s",A),_!=null&&(this.recovery=_),Object.freeze(this)}static fromBytes(b,A=w){B(b,A);let _;if(A==="der"){let{r:D,s:O}=ie.toSig(Dt(b));return new E(D,O)}A==="recovered"&&(_=b[0],A="compact",b=b.subarray(1));let C=i.BYTES,v=b.subarray(0,C),I=b.subarray(C,C*2);return new E(i.fromBytes(v),i.fromBytes(I),_)}static fromHex(b,A){return this.fromBytes(Ue(b),A)}addRecoveryBit(b){return new E(this.r,this.s,b)}recoverPublicKey(b){let A=o.ORDER,{r:_,s:C,recovery:v}=this;if(v==null||![0,1,2,3].includes(v))throw new Error("recovery id invalid");if(a*du<A&&v>1)throw new Error("recovery id is ambiguous for h>1 curve");let D=v===2||v===3?_+a:_;if(!o.isValid(D))throw new Error("recovery id 2 or 3 invalid");let O=o.toBytes(D),z=e.fromBytes(Ct(pu((v&1)===0),O)),F=i.inv(D),V=N(Y("msgHash",b)),$=i.create(-V*F),X=i.create(C*F),it=e.BASE.multiplyUnsafe($).add(z.multiplyUnsafe(X));if(it.is0())throw new Error("point at infinify");return it.assertValidity(),it}hasHighS(){return g(this.s)}toBytes(b=w){if(hi(b),b==="der")return Ue(ie.hexFromSig(this));let A=i.toBytes(this.r),_=i.toBytes(this.s);if(b==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return Ct(Uint8Array.of(this.recovery),A,_)}return Ct(A,_)}toHex(b){return Ut(this.toBytes(b))}assertValidity(){}static fromCompact(b){return E.fromBytes(Y("sig",b),"compact")}static fromDER(b){return E.fromBytes(Y("sig",b),"der")}normalizeS(){return this.hasHighS()?new E(this.r,i.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Ut(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Ut(this.toBytes("compact"))}}let P=r.bits2int||function(b){if(b.length>8192)throw new Error("input is too large");let A=lr(b),_=b.length*8-c;return _>0?A>>BigInt(_):A},N=r.bits2int_modN||function(b){return i.create(P(b))},k=Ae(c);function M(y){return ve("num < 2^"+c,y,ae,k),i.toBytes(y)}function U(y,b){return Dt(y,void 0,"message"),b?Dt(t(y),void 0,"prehashed message"):y}function S(y,b,A){if(["recovered","canonical"].some($=>$ in A))throw new Error("sign() legacy options not supported");let{lowS:_,prehash:C,extraEntropy:v}=li(A,p);y=U(y,C);let I=N(y),D=Sr(i,b),O=[M(D),M(I)];if(v!=null&&v!==!1){let $=v===!0?n(d.secretKey):v;O.push(Y("extraEntropy",$))}let z=Ct(...O),F=I;function V($){let X=P($);if(!i.isValidNot0(X))return;let it=i.inv(X),G=e.BASE.multiply(X).toAffine(),dt=i.create(G.x);if(dt===ae)return;let Je=i.create(it*i.create(F+dt*D));if(Je===ae)return;let Ur=(G.x===dt?0:2)|Number(G.y&vr),Kr=Je;return _&&g(Je)&&(Kr=i.neg(Je),Ur^=1),new E(dt,Kr,Ur)}return{seed:z,k2sig:V}}function L(y,b,A={}){y=Y("message",y);let{seed:_,k2sig:C}=S(y,b,A);return Sc(t.outputLen,i.BYTES,s)(_,C)}function R(y){let b,A=typeof y=="string"||Xt(y),_=!A&&y!==null&&typeof y=="object"&&typeof y.r=="bigint"&&typeof y.s=="bigint";if(!A&&!_)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(_)b=new E(y.r,y.s);else if(A){try{b=E.fromBytes(Y("sig",y),"der")}catch(C){if(!(C instanceof ie.Err))throw C}if(!b)try{b=E.fromBytes(Y("sig",y),"compact")}catch{return!1}}return b||!1}function T(y,b,A,_={}){let{lowS:C,prehash:v,format:I}=li(_,p);if(A=Y("publicKey",A),b=U(Y("message",b),v),"strict"in _)throw new Error("options.strict was renamed to lowS");let D=I===void 0?R(y):E.fromBytes(Y("sig",y),I);if(D===!1)return!1;try{let O=e.fromBytes(A);if(C&&D.hasHighS())return!1;let{r:z,s:F}=D,V=N(b),$=i.inv(F),X=i.create(V*$),it=i.create(z*$),G=e.BASE.multiplyUnsafe(X).add(O.multiplyUnsafe(it));return G.is0()?!1:i.create(G.x)===z}catch{return!1}}function m(y,b,A={}){let{prehash:_}=li(A,p);return b=U(b,_),E.fromBytes(y,"recovered").recoverPublicKey(b).toBytes()}return Object.freeze({keygen:f,getPublicKey:u,getSharedSecret:l,utils:h,lengths:d,Point:e,sign:L,verify:T,recoverPublicKey:m,Signature:E,hash:t})}function md(e){let t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},r=e.Fp,n=e.allowedPrivateKeyLengths?Array.from(new Set(e.allowedPrivateKeyLengths.map(i=>Math.ceil(i/2)))):void 0,s=Pt(t.n,{BITS:e.nBitLength,allowedLengths:n,modFromBytes:e.wrapPrivateKey}),o={Fp:r,Fn:s,allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes};return{CURVE:t,curveOpts:o}}function yd(e){let{CURVE:t,curveOpts:r}=md(e),n={hmac:e.hmac,randomBytes:e.randomBytes,lowS:e.lowS,bits2int:e.bits2int,bits2int_modN:e.bits2int_modN};return{CURVE:t,curveOpts:r,hash:e.hash,ecdsaOpts:n}}function gd(e,t){let r=t.Point;return Object.assign({},t,{ProjectivePoint:r,CURVE:Object.assign({},e,kn(r.Fn.ORDER,r.Fn.BITS))})}function yu(e){let{CURVE:t,curveOpts:r,hash:n,ecdsaOpts:s}=yd(e),o=hd(t,r),i=pd(o,n,s);return gd(e,i)}function gu(e,t){let r=n=>yu({...e,hash:n});return{...r(t),create:r}}var mi={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},bd={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var bu=BigInt(2);function xd(e){let t=mi.p,r=BigInt(3),n=BigInt(6),s=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),f=e*e*e%t,u=f*f*e%t,l=nt(u,r,t)*u%t,h=nt(l,r,t)*u%t,d=nt(h,bu,t)*f%t,p=nt(d,s,t)*d%t,w=nt(p,o,t)*p%t,g=nt(w,a,t)*w%t,x=nt(g,c,t)*g%t,B=nt(x,a,t)*w%t,E=nt(B,r,t)*u%t,P=nt(E,i,t)*p%t,N=nt(P,n,t)*f%t,k=nt(N,bu,t);if(!pi.eql(pi.sqr(k),e))throw new Error("Cannot find square root");return k}var pi=Pt(mi.p,{sqrt:xd}),Ar=gu({...mi,Fp:pi,lowS:!0,endo:bd},Se);function xu(e,t,r,n){let s=zr.digest(r instanceof Uint8Array?r:r.subarray());if(Wn(s))return s.then(({digest:o})=>(n?.signal?.throwIfAborted(),Ar.verify(t,o,e))).catch(o=>{throw o.name==="AbortError"?o:new rn(String(o))});try{return n?.signal?.throwIfAborted(),Ar.verify(t,s.digest,e)}catch(o){throw new rn(String(o))}}var Jn=class{type="secp256k1";raw;_key;constructor(t){this._key=Eu(t),this.raw=wu(this._key)}toMultihash(){return kt.digest(ye(this))}toCID(){return ft.createV1(114,this.toMultihash())}toString(){return ct.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:lt(this.raw,t.raw)}verify(t,r,n){return xu(this._key,r,t,n)}};function yi(e){return new Jn(e)}function wu(e){return Ar.ProjectivePoint.fromHex(e).toRawBytes(!0)}function Eu(e){try{return Ar.ProjectivePoint.fromHex(e),e}catch(t){throw new er(String(t))}}function un(e,t){let{Type:r,Data:n}=Wt.decode(e),s=n??new Uint8Array;switch(r){case ut.RSA:return ci(s,t);case ut.Ed25519:return Uo(s);case ut.secp256k1:return yi(s);case ut.ECDSA:return uo(s);default:throw new Le}}function Su(e){let{Type:t,Data:r}=Wt.decode(e.digest),n=r??new Uint8Array;switch(t){case ut.Ed25519:return Uo(n);case ut.secp256k1:return yi(n);case ut.ECDSA:return uo(n);default:throw new Le}}function ye(e){return Wt.encode({Type:ut[e.type],Data:e.raw})}var vu=Symbol.for("nodejs.util.inspect.custom"),wd=114,fn=class{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Os]=!0;toString(){return this.string==null&&(this.string=ct.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return ft.createV1(wd,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return lt(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return lt(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[vu](){return`PeerId(${this.toString()})`}},ln=class extends fn{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},hn=class extends fn{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},dn=class extends fn{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},Ed=2336,pn=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=kt.digest(Z(this.url))}[vu](){return`PeerId(${this.url})`}[Os]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return ft.createV1(Ed,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=q(t)),t.toString()===this.toString())}};var Sd=114,Au=2336;function Bu(e,t){let r;if(e.charAt(0)==="1"||e.charAt(0)==="Q")r=ar(ct.decode(`z${e}`));else{if(e.startsWith("k51qzi5uqu5")||e.startsWith("kzwfwjn5ji4")||e.startsWith("k2k4r8")||e.startsWith("bafz"))return vd(ft.parse(e));if(t==null)throw new et('Please pass a multibase decoder for strings that do not start with "1" or "Q"');r=ar(t.decode(e))}return _u(r)}function gi(e){if(e.type==="Ed25519")return new hn({multihash:e.toCID().multihash,publicKey:e});if(e.type==="secp256k1")return new dn({multihash:e.toCID().multihash,publicKey:e});if(e.type==="RSA")return new ln({multihash:e.toCID().multihash,publicKey:e});throw new Le}function _u(e){if(Bd(e))return new ln({multihash:e});if(Ad(e))try{let t=Su(e);if(t.type==="Ed25519")return new hn({multihash:e,publicKey:t});if(t.type==="secp256k1")return new dn({multihash:e,publicKey:t})}catch{let r=q(e.digest);return new pn(new URL(r))}throw new Bn("Supplied PeerID Multihash is invalid")}function vd(e){if(e?.multihash==null||e.version==null||e.version===1&&e.code!==Sd&&e.code!==Au)throw new An("Supplied PeerID CID is invalid");if(e.code===Au){let t=q(e.multihash.digest);return new pn(new URL(t))}return _u(e.multihash)}function Ad(e){return e.code===kt.code}function Bd(e){return e.code===zr.code}function Iu(e){let t=e.getComponents(),r={},n=0;if(t[n]?.name==="ip6zone"&&(r.zone=`${t[n].value}`,n++),t[n].name==="ip4"||t[n].name==="ip6"||t[n].name==="dns"||t[n].name==="dns4"||t[n].name==="dns6"?(r.type=t[n].name,r.host=t[n].value,n++):t[n].name==="dnsaddr"&&(r.type=t[n].name,r.host=`_dnsaddr.${t[n].value}`,n++),(t[n]?.name==="tcp"||t[n]?.name==="udp")&&(r.protocol=t[n].name==="tcp"?"tcp":"udp",r.port=parseInt(`${t[n].value}`),n++),t[n]?.name==="ipcidr"&&(r.type==="ip4"?r.cidr=parseInt(`${t[n].value}`):r.type==="ip6"&&(r.cidr=`${t[n].value}`),n++),r.type==null||r.host==null)throw new et(`Multiaddr ${e} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return t[n]?.name==="tls"&&t[n+1]?.name==="sni"&&(r.sni=t[n+1].value,n+=2),r}var ts=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let r=this.index,n=t();return n===void 0&&(this.index=r),n}parseWith(t){let r=t();if(this.index===this.input.length)return r}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(t){return this.readAtomically(()=>{let r=this.readChar();if(r===t)return r})}readSeparator(t,r,n){return this.readAtomically(()=>{if(!(r>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,r,n,s){return this.readAtomically(()=>{let o=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",f=2**(8*s)-1;for(;;){let u=this.readAtomically(()=>{let l=this.readChar();if(l===void 0)return;let h=Number.parseInt(l,t);if(!Number.isNaN(h))return h});if(u===void 0)break;if(o*=t,o+=u,o>f||(i+=1,r!==void 0&&i>r))return}if(i!==0)return!n&&c&&i>1?void 0:o})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let r=0;r<t.length;r++){let n=this.readSeparator(".",r,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[r]=n}return t})}readIPv6Addr(){let t=r=>{for(let n=0;n<r.length/2;n++){let s=n*2;if(n<r.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return r[s]=i[0],r[s+1]=i[1],r[s+2]=i[2],r[s+3]=i[3],[s+4,!0]}let o=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(o===void 0)return[s,!1];r[s]=o>>8,r[s+1]=o&255}return[r.length,!1]};return this.readAtomically(()=>{let r=new Uint8Array(16),[n,s]=t(r);if(n===16)return r;if(s||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let o=new Uint8Array(14),i=16-(n+2),[a]=t(o.subarray(0,i));return r.set(o.subarray(0,a),16-a),r})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var _d=45,Id=15,es=new ts;function Cu(e){if(!(e.length>Id))return es.new(e).parseWith(()=>es.readIPv4Addr())}function Lu(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>_d))return es.new(e).parseWith(()=>es.readIPv6Addr())}function rs(e){return!!Cu(e)}function Tu(e){return!!Lu(e)}function ns(){let e={};return e.promise=new Promise((t,r)=>{e.resolve=t,e.reject=r}),e}var ss=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||(t-1&t)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},Br=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new ss(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){let r=this.head;this.head=r.next=new ss(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let r=this.tail.next;this.tail.next=null,this.tail=r,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var bi=class extends Error{type;code;constructor(t,r){super(t??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function os(e={}){return Cd(r=>{let n=r.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},e)}function Cd(e,t){t=t??{};let r=t.onEnd,n=new Br,s,o,i,a=ns(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((g,x)=>{o=B=>{o=null,n.push(B);try{g(e(n))}catch(E){x(E)}return s}}):e(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=ns()})}},f=g=>o!=null?o(g):(n.push(g),s),u=g=>(n=new Br,o!=null?o({error:g}):(n.push({error:g}),s)),l=g=>{if(i)return s;if(t?.objectMode!==!0&&g?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return f({done:!1,value:g})},h=g=>i?s:(i=!0,g!=null?u(g):f({done:!0})),d=()=>(n=new Br,h(),{done:!0}),p=g=>(h(g),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:d,throw:p,push:l,end:h,get readableLength(){return n.size},onEmpty:async g=>{let x=g?.signal;if(x?.throwIfAborted(),n.isEmpty())return;let B,E;x!=null&&(B=new Promise((P,N)=>{E=()=>{N(new bi)},x.addEventListener("abort",E)}));try{await Promise.race([a.promise,B])}finally{E!=null&&x!=null&&x?.removeEventListener("abort",E)}}},r==null)return s;let w=s;return s={[Symbol.asyncIterator](){return this},next(){return w.next()},throw(g){return w.throw(g),r!=null&&(r(g),r=void 0),{done:!0}},return(){return w.return(),r!=null&&(r(),r=void 0),{done:!0}},push:l,end(g){return w.end(g),r!=null&&(r(g),r=void 0),s},get readableLength(){return w.readableLength},onEmpty:g=>w.onEmpty(g)},s}var xi=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},wi=class extends Error{constructor(t){super(),this.name="AbortError",this.message=t}},Du=e=>globalThis.DOMException===void 0?new wi(e):new DOMException(e),Pu=e=>{let t=e.reason===void 0?Du("This operation was aborted."):e.reason;return t instanceof Error?t:Du(t)};function Ei(e,t){let{milliseconds:r,fallback:n,message:s,customTimers:o={setTimeout,clearTimeout}}=t,i,a,f=new Promise((u,l)=>{if(typeof r!="number"||Math.sign(r)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(t.signal){let{signal:d}=t;d.aborted&&l(Pu(d)),a=()=>{l(Pu(d))},d.addEventListener("abort",a,{once:!0})}if(r===Number.POSITIVE_INFINITY){e.then(u,l);return}let h=new xi;i=o.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(d){l(d)}return}typeof e.cancel=="function"&&e.cancel(),s===!1?u():s instanceof Error?l(s):(h.message=s??`Promise timed out after ${r} milliseconds`,l(h))},r),(async()=>{try{u(await e)}catch(d){l(d)}})()}).finally(()=>{f.clear(),a&&t.signal&&t.signal.removeEventListener("abort",a)});return f.clear=()=>{o.clearTimeout.call(void 0,i),i=void 0},f}var Ld=e=>{let t=e.addEventListener||e.on||e.addListener,r=e.removeEventListener||e.off||e.removeListener;if(!t||!r)throw new TypeError("Emitter is not compatible");return{addListener:t.bind(e),removeListener:r.bind(e)}};function Td(e,t,r){let n,s=new Promise((o,i)=>{if(r={rejectionEvents:["error"],multiArgs:!1,resolveImmediately:!1,...r},!(r.count>=0&&(r.count===Number.POSITIVE_INFINITY||Number.isInteger(r.count))))throw new TypeError("The `count` option should be at least 0 or more");r.signal?.throwIfAborted();let a=[t].flat(),c=[],{addListener:f,removeListener:u}=Ld(e),l=(...d)=>{let p=r.multiArgs?d:d[0];r.filter&&!r.filter(p)||(c.push(p),r.count===c.length&&(n(),o(c)))},h=d=>{n(),i(d)};n=()=>{for(let d of a)u(d,l);for(let d of r.rejectionEvents)u(d,h)};for(let d of a)f(d,l);for(let d of r.rejectionEvents)f(d,h);r.signal&&r.signal.addEventListener("abort",()=>{h(r.signal.reason)},{once:!0}),r.resolveImmediately&&o(c)});if(s.cancel=n,typeof r.timeout=="number"){let o=Ei(s,{milliseconds:r.timeout});return o.cancel=n,o}return s}function Ie(e,t,r){typeof r=="function"&&(r={filter:r}),r={...r,count:1,resolveImmediately:!1};let n=Td(e,t,r),s=n.then(o=>o[0]);return s.cancel=n.cancel,s}var $e=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"},is=class extends Error{static name="MaxEarlyStreamsError";name="MaxEarlyStreamsError"};function Dd(e){return e.reason}async function ce(e,t,r){if(t==null)return e;let n=r?.translateError??Dd;if(t.aborted)return e.catch(()=>{}),Promise.reject(n(t));let s;try{return await Promise.race([e,new Promise((o,i)=>{s=()=>{i(n(t))},t.addEventListener("abort",s)})])}finally{s!=null&&t.removeEventListener("abort",s)}}var Pd=Math.pow(2,20)*4,$t=class extends nr{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;constructor(t){super(),this.status="open",this.log=t.log,this.direction=t.direction??"outbound",this.inactivityTimeout=t.inactivityTimeout??12e4,this.maxReadBufferLength=t.maxReadBufferLength??Pd,this.maxWriteBufferLength=t.maxWriteBufferLength,this.maxMessageSize=t.maxMessageSize,this.readBuffer=new j,this.writeBuffer=new j,this.readStatus="readable",this.remoteReadStatus="readable",this.writeStatus="writable",this.remoteWriteStatus="writable",this.sendingData=!1,this.writableNeedsDrain=!1,this.timeline={open:Date.now()},this.processSendQueue=this.processSendQueue.bind(this);let r=()=>{this.writableNeedsDrain&&(this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,this.processSendQueue())};this.addEventListener("drain",r)}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let t=os(),r=o=>{t.push(o.data)};this.addEventListener("message",r);let n=o=>{t.end(o.error)};this.addEventListener("close",n);let s=()=>{t.end()};this.addEventListener("remoteCloseWrite",s);try{yield*t}finally{this.removeEventListener("message",r),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",s)}}isReadable(){return this.status==="open"}send(t){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new Ce(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",t.byteLength),this.writeBuffer.append(t),this.processSendQueue()}abort(t){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",t),this.status="aborted",this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle")),this.writeStatus="closed",this.remoteWriteStatus="closed",this.readStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now();try{this.sendReset(t)}catch(r){this.log("failed to send reset to remote - %e",r)}this.dispatchEvent(new In(t))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Ce("Cannot pause a stream that is closing/closed");this.readStatus!=="paused"&&(this.readStatus="paused",this.sendPause())}resume(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Ce("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(t){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Ce(`Cannot push data onto a stream that is ${this.readStatus}`);if(t.byteLength!==0){if(this.readBuffer.append(t),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(t){if(t.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(t),this.dispatchReadBuffer()}}addEventListener(...t){super.addEventListener.apply(this,t),t[0]==="message"&&this.readBuffer.byteLength>0&&queueMicrotask(()=>{this.dispatchReadBuffer()})}onRemoteReset(){this.log("remote reset"),this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.readBuffer.byteLength===0&&(this.readStatus="closed");let t=new vn;this.dispatchEvent(new Cn(t))}onTransportClosed(t){this.log("transport closed"),this.readStatus==="readable"&&this.readBuffer.byteLength===0&&(this.log("close readable end after transport closed and read buffer is empty"),this.readStatus="closed"),this.remoteReadStatus!=="closed"&&(this.remoteReadStatus="closed"),this.remoteWriteStatus!=="closed"&&(this.remoteWriteStatus="closed"),this.writeStatus!=="closed"&&(this.writeStatus="closed"),t!=null?this.abort(t):(this.status==="open"||this.status==="closing")&&(this.timeline.close=Date.now(),this.status="closed",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.dispatchEvent(new rr))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.writeStatus==="closed"&&this.onTransportClosed())}onRemoteCloseRead(){this.log.trace("on remote close read"),this.remoteReadStatus="closed",this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle"))}processSendQueue(){if(this.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(this.writeBuffer.byteLength===0)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let t=!0,r=this.writeBuffer.byteLength,n=0;for(;this.writeBuffer.byteLength>0;){let s=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(s===0){t=!1;break}let o=this.writeBuffer.sublist(0,s),i=new j(o);this.writeBuffer.consume(o.byteLength);let a=this.sendData(o);if(t=a.canSendMore,n+=a.sentBytes,a.sentBytes!==i.byteLength&&(i.consume(a.sentBytes),this.writeBuffer.prepend(i)),!t)break}return t||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",n,r,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),t}finally{this.sendingData=!1}}dispatchReadBuffer(){try{if(this.listenerCount("message")===0){this.log.trace("not dispatching pause buffer as there are no listeners for the message event");return}if(this.readBuffer.byteLength===0){this.log.trace("not dispatching pause buffer as there is no data to dispatch");return}if(this.readStatus==="paused"){this.log.trace("not dispatching pause buffer we are paused");return}if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("dropping %d bytes because the readable end is %s",this.readBuffer.byteLength,this.readStatus),this.readBuffer.consume(this.readBuffer.byteLength);return}let t=this.readBuffer.sublist();this.readBuffer.consume(t.byteLength),this.dispatchEvent(new _n(t))}finally{this.readBuffer.byteLength===0&&this.remoteWriteStatus==="closed"&&(this.log("close readable end after dispatching read buffer and remote writable end is closed"),this.readStatus="closed"),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new Nr(`Read buffer length of ${this.readBuffer.byteLength} exceeded limit of ${this.maxReadBufferLength}, read status is ${this.readStatus}`))}checkWriteBufferLength(){this.maxWriteBufferLength!=null&&this.writeBuffer.byteLength>this.maxWriteBufferLength&&this.abort(new Nr(`Write buffer length of ${this.writeBuffer.byteLength} exceeded limit of ${this.maxWriteBufferLength}, write status is ${this.writeStatus}`))}onMuxerNeedsDrain(){this.writableNeedsDrain=!0}onMuxerDrain(){this.safeDispatchEvent("drain")}};var as=class extends $t{remoteAddr;metricPrefix;metrics;constructor(t){super(t),this.metricPrefix=t.metricPrefix??"",this.metrics=t.metrics,this.remoteAddr=t.remoteAddr,this.addEventListener("close",r=>{this.metrics?.increment({[`${this.metricPrefix}end`]:!0}),r.error!=null?r.local?this.metrics?.increment({[`${this.metricPrefix}abort`]:!0}):this.metrics?.increment({[`${this.metricPrefix}reset`]:!0}):r.local?this.metrics?.increment({[`${this.metricPrefix}_local_close`]:!0}):this.metrics?.increment({[`${this.metricPrefix}_remote_close`]:!0})})}async close(t){this.status==="open"&&(this.status="closing",this.writeStatus="closing",this.remoteWriteStatus="closing",this.remoteReadStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Ie(this,"idle",{...t,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Ie(this,"drain",{...t,rejectionEvents:["close"]})),await this.sendClose(t),this.onTransportClosed())}};function Ru(e){return e==null?!1:typeof e.then=="function"&&typeof e.catch=="function"&&typeof e.finally=="function"}var cs=class extends nr{streams;protocol;status;log;maConn;streamOptions;earlyStreams;maxEarlyStreams;metrics;constructor(t,r){super(),this.maConn=t,this.protocol=r.protocol,this.streams=[],this.earlyStreams=[],this.status="open",this.log=t.log.newScope(r.name),this.streamOptions=r.streamOptions,this.maxEarlyStreams=r.maxEarlyStreams??10,this.metrics=r.metrics;let n=i=>{try{this.onData(i.data)}catch(a){this.abort(a),this.maConn.abort(a)}};this.maConn.addEventListener("message",n);let s=()=>{this.log("underlying stream drained, signal %d streams to continue writing",this.streams.length),this.streams.forEach(i=>{i.onMuxerDrain()})};this.maConn.addEventListener("drain",s);let o=()=>{this.log("underlying stream closed with status %s and %d streams",this.status,this.streams.length),this.onTransportClosed()};this.maConn.addEventListener("close",o)}send(t){let r=this.maConn.send(t);return r===!1&&(this.log("underlying stream saturated, signal %d streams to pause writing",this.streams.length),this.streams.forEach(n=>{n.onMuxerNeedsDrain()})),r}async close(t){this.status==="closed"||this.status==="closing"||(this.status="closing",await ce(Promise.all([...this.streams].map(async r=>{await r.close(t)})),t?.signal),this.status="closed")}abort(t){this.status!=="closed"&&(this.status="closing",[...this.streams].forEach(r=>{r.abort(t)}),this.status="closed")}onTransportClosed(t){this.status="closing";try{[...this.streams].forEach(r=>{r.onTransportClosed(t)})}catch(r){this.abort(r)}this.status="closed"}async createStream(t){if(this.status!=="open")throw new Sn;let r=this.onCreateStream({...this.streamOptions,...t});return Ru(r)&&(r=await r),this.streams.push(r),this.cleanUpStream(r),r}onRemoteStream(t){if(this.streams.push(t),this.cleanUpStream(t),this.listenerCount("stream")===0){this.earlyStreams.push(t),this.earlyStreams.length>this.maxEarlyStreams&&this.abort(new is(`Too many early streams were opened - ${this.earlyStreams.length}/${this.maxEarlyStreams}`));return}this.safeDispatchEvent("stream",{detail:t})}cleanUpStream(t){let r=n=>{let s=this.streams.findIndex(o=>o===t);s!==-1&&this.streams.splice(s,1),n.error!=null?n.local?this.metrics?.increment({[`${t.direction}_stream_reset`]:!0}):this.metrics?.increment({[`${t.direction}_stream_abort`]:!0}):this.metrics?.increment({[`${t.direction}_stream_end`]:!0})};t.addEventListener("close",r),this.metrics?.increment({[`${t.direction}_stream`]:!0})}addEventListener(...t){super.addEventListener.apply(this,t),t[0]==="stream"&&this.earlyStreams.length>0&&queueMicrotask(()=>{this.earlyStreams.forEach(r=>{this.safeDispatchEvent("stream",{detail:r})}),this.earlyStreams=[]})}};var us=class extends $t{id;protocol;constructor(t){super(t),this.id=t.id,this.protocol=t.protocol??""}async close(t){this.writeStatus==="closing"||this.writeStatus==="closed"||(this.writeStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Ie(this,"idle",{...t,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData),await Ie(this,"drain",{...t,rejectionEvents:["close"]}),this.log("write queue drained, closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData)),await this.sendCloseWrite(t),this.writeStatus="closed",this.log("closed writable end gracefully"),this.remoteWriteStatus==="closed"&&this.onTransportClosed())}async closeRead(t){this.readStatus==="closing"||this.readStatus==="closed"||(this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.readStatus="closing",await this.sendCloseRead(t),this.readStatus="closed",this.log("closed readable end gracefully"))}};var xt=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},ue=class extends Error{static name="ValidationError";name="ValidationError"},fs=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},ls=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function vi(e){return t=>q(t,e)}function Ai(e){return t=>Z(t,e)}function _r(e){return new DataView(e.buffer).getUint16(e.byteOffset).toString()}function Ge(e){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,typeof e=="string"?parseInt(e):e),new Uint8Array(t)}function Ou(e){let t=e.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==16)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);let r=Z(t[0],"base32"),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=Ge(n);return Ot([r,s],r.length+s.length)}function Uu(e){let t=e.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let r=pe.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=Ge(n);return Ot([r,s],r.length+s.length)}function Bi(e){let t=e.subarray(0,e.length-2),r=e.subarray(e.length-2),n=q(t,"base32"),s=_r(r);return`${n}:${s}`}var _i=function(e){e=e.toString().trim();let t=new Uint8Array(4);return e.split(/\./g).forEach((r,n)=>{let s=parseInt(r,10);if(isNaN(s)||s<0||s>255)throw new xt("Invalid byte value in IP address");t[n]=s}),t},Ku=function(e){let t=0;e=e.toString().trim();let r=e.split(":",8),n;for(n=0;n<r.length;n++){let o=rs(r[n]),i;o&&(i=_i(r[n]),r[n]=q(i.subarray(0,2),"base16")),i!=null&&++n<8&&r.splice(n,0,q(i.subarray(2,4),"base16"))}if(r[0]==="")for(;r.length<8;)r.unshift("0");else if(r[r.length-1]==="")for(;r.length<8;)r.push("0");else if(r.length<8){for(n=0;n<r.length&&r[n]!=="";n++);let o=[n,1];for(n=9-r.length;n>0;n--)o.push("0");r.splice.apply(r,o)}let s=new Uint8Array(t+16);for(n=0;n<r.length;n++){r[n]===""&&(r[n]="0");let o=parseInt(r[n],16);if(isNaN(o)||o<0||o>65535)throw new xt("Invalid byte value in IP address");s[t++]=o>>8&255,s[t++]=o&255}return s},Nu=function(e){if(e.byteLength!==4)throw new xt("IPv4 address was incorrect length");let t=[];for(let r=0;r<e.byteLength;r++)t.push(e[r]);return t.join(".")},Mu=function(e){if(e.byteLength!==16)throw new xt("IPv6 address was incorrect length");let t=[];for(let n=0;n<e.byteLength;n+=2){let s=e[n],o=e[n+1],i=`${s.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}`;t.push(i)}let r=t.join(":");try{let n=new URL(`http://[${r}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new xt(`Invalid IPv6 address "${r}"`)}};function ku(e){try{let t=new URL(`http://[${e}]`);return t.hostname.substring(1,t.hostname.length-1)}catch{throw new xt(`Invalid IPv6 address "${e}"`)}}var Si=Object.values(De).map(e=>e.decoder),Rd=(function(){let e=Si[0].or(Si[1]);return Si.slice(2).forEach(t=>e=e.or(t)),e})();function Hu(e){return Rd.decode(e)}function Vu(e){return t=>e.encoder.encode(t)}function Od(e){if(parseInt(e).toString()!==e)throw new ue("Value must be an integer")}function Ud(e){if(e<0)throw new ue("Value must be a positive integer, or zero")}function Kd(e){return t=>{if(t>e)throw new ue(`Value must be smaller than or equal to ${e}`)}}function Nd(...e){return t=>{for(let r of e)r(t)}}var mn=Nd(Od,Ud,Kd(65535));var yt=-1,Ii=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(t){let r;if(typeof t=="string"?r=this.protocolsByName.get(t):r=this.protocolsByCode.get(t),r==null)throw new ls(`Protocol ${t} was unknown`);return r}addProtocol(t){this.protocolsByCode.set(t.code,t),this.protocolsByName.set(t.name,t),t.aliases?.forEach(r=>{this.protocolsByName.set(r,t)})}removeProtocol(t){let r=this.protocolsByCode.get(t);r!=null&&(this.protocolsByCode.delete(r.code),this.protocolsByName.delete(r.name),r.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},fe=new Ii,Qd=[{code:4,name:"ip4",size:32,valueToBytes:_i,bytesToValue:Nu,validate:e=>{if(!rs(e))throw new ue(`Invalid IPv4 address "${e}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Ge,bytesToValue:_r,validate:mn},{code:273,name:"udp",size:16,valueToBytes:Ge,bytesToValue:_r,validate:mn},{code:33,name:"dccp",size:16,valueToBytes:Ge,bytesToValue:_r,validate:mn},{code:41,name:"ip6",size:128,valueToBytes:Ku,bytesToValue:Mu,stringToValue:ku,validate:e=>{if(!Tu(e))throw new ue(`Invalid IPv6 address "${e}"`)}},{code:42,name:"ip6zone",size:yt},{code:43,name:"ipcidr",size:8,bytesToValue:vi("base10"),valueToBytes:Ai("base10")},{code:53,name:"dns",size:yt},{code:54,name:"dns4",size:yt},{code:55,name:"dns6",size:yt},{code:56,name:"dnsaddr",size:yt},{code:132,name:"sctp",size:16,valueToBytes:Ge,bytesToValue:_r,validate:mn},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:yt,stringToValue:e=>decodeURIComponent(e),valueToString:e=>encodeURIComponent(e)},{code:421,name:"p2p",aliases:["ipfs"],size:yt,bytesToValue:vi("base58btc"),valueToBytes:e=>e.startsWith("Q")||e.startsWith("1")?Ai("base58btc")(e):ft.parse(e).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Bi,valueToBytes:Ou},{code:445,name:"onion3",size:296,bytesToValue:Bi,valueToBytes:Uu},{code:446,name:"garlic64",size:yt},{code:447,name:"garlic32",size:yt},{code:448,name:"tls"},{code:449,name:"sni",size:yt},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:yt,bytesToValue:Vu(Ys),valueToBytes:Hu},{code:480,name:"http"},{code:481,name:"http-path",size:yt,stringToValue:e=>`/${decodeURIComponent(e)}`,valueToString:e=>encodeURIComponent(e.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:yt}];Qd.forEach(e=>{fe.addProtocol(e)});function qu(e){let t=[],r=0;for(;r<e.length;){let n=He(e,r),s=fe.getProtocol(n),o=vt(n),i=Jd(s,e,r+o),a=0;i>0&&s.size===yt&&(a=vt(i));let c=o+a+i,f={code:n,name:s.name,bytes:e.subarray(r,r+c)};if(i>0){let u=r+o+a,l=e.subarray(u,u+i);f.value=s.bytesToValue?.(l)??q(l)}t.push(f),r+=c}return t}function zu(e){let t=0,r=[];for(let n of e){if(n.bytes==null){let s=fe.getProtocol(n.code),o=vt(n.code),i,a=0,c=0;n.value!=null&&(i=s.valueToBytes?.(n.value)??Z(n.value),a=i.byteLength,s.size===yt&&(c=vt(a)));let f=new Uint8Array(o+c+a),u=0;br(n.code,f,u),u+=o,i!=null&&(s.size===yt&&(br(a,f,u),u+=c),f.set(i,u)),n.bytes=f}r.push(n.bytes),t+=n.bytes.byteLength}return Ot(r,t)}function Fu(e){if(e.charAt(0)!=="/")throw new xt('String multiaddr must start with "/"');let t=[],r="protocol",n="",s="";for(let o=1;o<e.length;o++){let i=e.charAt(o);i!=="/"&&(r==="protocol"?s+=e.charAt(o):n+=e.charAt(o));let a=o===e.length-1;if(i==="/"||a){let c=fe.getProtocol(s);if(r==="protocol"){if(c.size==null||c.size===0){t.push({code:c.code,name:c.name}),n="",s="",r="protocol";continue}else if(a)throw new xt(`Component ${s} was missing value`);r="value"}else if(r==="value"){let f={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new xt(`Component ${s} was missing value`);f.value=c.stringToValue?.(n)??n}t.push(f),n="",s="",r="protocol"}}}if(s!==""&&n!=="")throw new xt("Incomplete multiaddr");return t}function Wu(e){return`/${e.flatMap(t=>{if(t.value==null)return t.name;let r=fe.getProtocol(t.code);if(r==null)throw new xt(`Unknown protocol code ${t.code}`);return[t.name,r.valueToString?.(t.value)??t.value]}).join("/")}`}function Jd(e,t,r){return e.size==null||e.size===0?0:e.size>0?e.size/8:He(t,r)}var tp=Symbol.for("nodejs.util.inspect.custom"),Wi=Symbol.for("@multiformats/multiaddr");function ep(e){if(e==null&&(e="/"),$u(e))return e.getComponents();if(e instanceof Uint8Array)return qu(e);if(typeof e=="string")return e=e.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),e===""&&(e="/"),Fu(e);if(Array.isArray(e))return e;throw new xt("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Fi=class e{[Wi]=!0;#t;#e;#r;constructor(t="/",r={}){this.#t=ep(t),r.validate!==!1&&rp(this)}get bytes(){return this.#r==null&&(this.#r=zu(this.#t)),this.#r}toString(){return this.#e==null&&(this.#e=Wu(this.#t)),this.#e}toJSON(){return this.toString()}getComponents(){return[...this.#t.map(t=>({...t}))]}encapsulate(t){let r=new e(t);return new e([...this.#t,...r.getComponents()],{validate:!1})}decapsulate(t){let r=t.toString(),n=this.toString(),s=n.lastIndexOf(r);if(s<0)throw new fs(`Address ${this.toString()} does not contain subaddress: ${r}`);return new e(n.slice(0,s),{validate:!1})}decapsulateCode(t){let r;for(let n=this.#t.length-1;n>-1;n--)if(this.#t[n].code===t){r=n;break}return new e(this.#t.slice(0,r),{validate:!1})}equals(t){return lt(this.bytes,t.bytes)}[tp](){return`Multiaddr(${this.toString()})`}};function rp(e){e.getComponents().forEach(t=>{let r=fe.getProtocol(t.code);t.value!=null&&r.validate?.(t.value)})}function $u(e){return!!e?.[Wi]}var np=4194304,ys=class extends Error{static name="UnwrappedError";name="UnwrappedError"},yn=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Gi=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},ji=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function sp(e){return typeof e?.closeRead=="function"}function op(e){return typeof e?.close=="function"}function $i(e){return sp(e)?e.readStatus==="closing"||e.readStatus==="closed":op(e)?e.status!=="open":!1}function ip(e){return e?.addEventListener!=null&&e?.removeEventListener!=null&&e?.send!=null&&e?.push!=null&&e?.log!=null}function ap(e,t){let r=t?.maxBufferSize??np,n=new j,s=Promise.withResolvers(),o=!1;if(!ip(e))throw new et("Argument should be a Stream or a Multiaddr");let i=u=>{if(n.append(u.data),n.byteLength>r){let l=n.byteLength;n.consume(n.byteLength),s.reject(new Error(`Read buffer overflow - ${l} > ${r}`))}s.resolve()};e.addEventListener("message",i);let a=u=>{u.error!=null?s.reject(u.error):s.resolve()};e.addEventListener("close",a);let c=()=>{s.resolve()};e.addEventListener("remoteCloseWrite",c);let f={readBuffer:n,async read(u){if(o===!0)throw new ys("Stream was unwrapped");if($i(e)){if(u?.bytes==null)return null;if(n.byteLength<u.bytes)throw e.log.error("closed after reading %d/%d bytes",n.byteLength,u.bytes),new $e(`Unexpected EOF - stream closed after reading ${n.byteLength}/${u.bytes} bytes`)}let l=u?.bytes??1;for(;;){if(n.byteLength>=l){s.resolve();break}if(await ce(s.promise,u?.signal),$i(e)){if(n.byteLength===0&&u?.bytes==null)return null;break}s=Promise.withResolvers()}let h=u?.bytes??n.byteLength;if(n.byteLength<h){if($i(e))throw e.log.error("closed while reading %d/%d bytes",n.byteLength,h),new $e(`Unexpected EOF - stream closed while reading ${n.byteLength}/${h} bytes`);return f.read(u)}let d=n.sublist(0,h);return n.consume(h),d},async write(u,l){if(o===!0)throw new ys("Stream was unwrapped");e.send(u)||await Ie(e,"drain",{signal:l?.signal,rejectionEvents:["close"]})},unwrap(){return o||(o=!0,e.removeEventListener("message",i),e.removeEventListener("close",a),e.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(e.log("stream unwrapped with %d unread bytes",n.byteLength),e.push(n))),e}};return f}function Zi(e,t={}){let r=ap(e,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=vt(t.maxDataLength));let n=t?.lengthDecoder??He,s=t?.lengthEncoder??Zc;return{async read(i){let a=-1,c=new j;for(;;){let u=await r.read({...i,bytes:1});if(u==null)break;c.append(u);try{a=n(c)}catch(l){if(l instanceof RangeError)continue;throw l}if(a<0)throw new yn("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new ji(`Message length length too long - ${c.byteLength} > ${t.maxLengthLength}`);if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new Gi(`Message length too long - ${a} > ${t.maxDataLength}`);let f=await r.read({...i,bytes:a});if(f==null)throw e.log.error("tried to read %d bytes but the stream closed",a),new $e(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(f.byteLength!==a)throw e.log.error("read %d/%d bytes before the stream closed",f.byteLength,a),new $e(`Unexpected EOF - read ${f.byteLength}/${a} bytes before the stream closed`);return f},async write(i,a){await r.write(new j(s(i.byteLength),i),a)},async writeV(i,a){let c=new j(...i.flatMap(f=>[s(f.byteLength),f]));await r.write(c,a)},unwrap(){return r.unwrap()}}}var cp=1024*1024*4,up=1024*1024*4,gs=class{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(t={}){this.buffer=new j,this.maxBufferSize=t.maxBufferSize??cp,this.maxDataLength=t.maxDataLength??up,this.lengthDecoder=t.lengthDecoder??He,this.encodingLength=t.encodingLength??vt}*decode(t){if(this.buffer.append(t),this.buffer.byteLength>this.maxBufferSize)throw new et(`Buffer length limit exceeded - ${this.buffer.byteLength}/${this.maxBufferSize}`);for(;;){let r;try{r=this.lengthDecoder(this.buffer)}catch(o){if(o instanceof RangeError)break;throw o}if(r<0||r>this.maxDataLength)throw new yn("Invalid message length");let n=this.encodingLength(r),s=n+r;if(this.buffer.byteLength>=s){let o=this.buffer.sublist(n,s);this.buffer.consume(s),o.byteLength>0&&(yield o)}else break}}};var Tr=!!globalThis.process?.env?.DUMP_SESSION_KEYS,Yi=16;function ju(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function bs(e){if(typeof e!="boolean")throw new Error(`boolean expected, not ${e}`)}function xs(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Bt(e,...t){if(!ju(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function Xi(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Zu(e,t){Bt(e);let r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function le(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function he(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function fp(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}var lp=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function hp(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function ws(e){if(typeof e=="string")e=hp(e);else if(ju(e))e=Es(e);else throw new Error("Uint8Array expected, got "+typeof e);return e}function Yu(e,t){if(t==null||typeof t!="object")throw new Error("options must be defined");return Object.assign(e,t)}function Xu(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return r===0}var Qi=(e,t)=>{function r(n,...s){if(Bt(n),!lp)throw new Error("Non little-endian hardware is not yet supported");if(e.nonceLength!==void 0){let u=s[0];if(!u)throw new Error("nonce / iv required");e.varSizeNonce?Bt(u):Bt(u,e.nonceLength)}let o=e.tagLength;o&&s[1]!==void 0&&Bt(s[1]);let i=t(n,...s),a=(u,l)=>{if(l!==void 0){if(u!==2)throw new Error("cipher output not supported");Bt(l)}},c=!1;return{encrypt(u,l){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,Bt(u),a(i.encrypt.length,l),i.encrypt(u,l)},decrypt(u,l){if(Bt(u),o&&u.length<o)throw new Error("invalid ciphertext length: smaller than tagLength="+o);return a(i.decrypt.length,l),i.decrypt(u,l)}}}return Object.assign(r,e),r};function Ji(e,t,r=!0){if(t===void 0)return new Uint8Array(e);if(t.length!==e)throw new Error("invalid output length, expected "+e+", got: "+t.length);if(r&&!dp(t))throw new Error("invalid output, must be aligned");return t}function Gu(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);let s=BigInt(32),o=BigInt(4294967295),i=Number(r>>s&o),a=Number(r&o),c=n?4:0,f=n?0:4;e.setUint32(t+c,i,n),e.setUint32(t+f,a,n)}function Qu(e,t,r){bs(r);let n=new Uint8Array(16),s=fp(n);return Gu(s,0,BigInt(t),r),Gu(s,8,BigInt(e),r),n}function dp(e){return e.byteOffset%4===0}function Es(e){return Uint8Array.from(e)}var tf=e=>Uint8Array.from(e.split("").map(t=>t.charCodeAt(0))),pp=tf("expand 16-byte k"),mp=tf("expand 32-byte k"),yp=le(pp),gp=le(mp);function K(e,t){return e<<t|e>>>32-t}function ta(e){return e.byteOffset%4===0}var Ss=64,bp=16,ef=2**32-1,Ju=new Uint32Array;function xp(e,t,r,n,s,o,i,a){let c=s.length,f=new Uint8Array(Ss),u=le(f),l=ta(s)&&ta(o),h=l?le(s):Ju,d=l?le(o):Ju;for(let p=0;p<c;i++){if(e(t,r,n,u,i,a),i>=ef)throw new Error("arx: counter overflow");let w=Math.min(Ss,c-p);if(l&&w===Ss){let g=p/4;if(p%4!==0)throw new Error("arx: invalid block position");for(let x=0,B;x<bp;x++)B=g+x,d[B]=h[B]^u[x];p+=Ss;continue}for(let g=0,x;g<w;g++)x=p+g,o[x]=s[x]^f[g];p+=w}}function ea(e,t){let{allowShortKeys:r,extendNonceFn:n,counterLength:s,counterRight:o,rounds:i}=Yu({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!="function")throw new Error("core must be a function");return xs(s),xs(i),bs(o),bs(r),(a,c,f,u,l=0)=>{Bt(a),Bt(c),Bt(f);let h=f.length;if(u===void 0&&(u=new Uint8Array(h)),Bt(u),xs(l),l<0||l>=ef)throw new Error("arx: counter overflow");if(u.length<h)throw new Error(`arx: output (${u.length}) is shorter than data (${h})`);let d=[],p=a.length,w,g;if(p===32)d.push(w=Es(a)),g=gp;else if(p===16&&r)w=new Uint8Array(32),w.set(a),w.set(a,16),g=yp,d.push(w);else throw new Error(`arx: invalid 32-byte key, got length=${p}`);ta(c)||d.push(c=Es(c));let x=le(w);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(g,x,le(c.subarray(0,16)),x),c=c.subarray(16)}let B=16-s;if(B!==c.length)throw new Error(`arx: nonce must be ${B} or 16 bytes`);if(B!==12){let P=new Uint8Array(12);P.set(c,o?0:12-c.length),c=P,d.push(c)}let E=le(c);return xp(e,g,x,E,f,u,l,i),he(...d),u}}var wt=(e,t)=>e[t++]&255|(e[t++]&255)<<8,ra=class{constructor(t){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,t=ws(t),Bt(t,32);let r=wt(t,0),n=wt(t,2),s=wt(t,4),o=wt(t,6),i=wt(t,8),a=wt(t,10),c=wt(t,12),f=wt(t,14);this.r[0]=r&8191,this.r[1]=(r>>>13|n<<3)&8191,this.r[2]=(n>>>10|s<<6)&7939,this.r[3]=(s>>>7|o<<9)&8191,this.r[4]=(o>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|f<<8)&8191,this.r[9]=f>>>5&127;for(let u=0;u<8;u++)this.pad[u]=wt(t,16+2*u)}process(t,r,n=!1){let s=n?0:2048,{h:o,r:i}=this,a=i[0],c=i[1],f=i[2],u=i[3],l=i[4],h=i[5],d=i[6],p=i[7],w=i[8],g=i[9],x=wt(t,r+0),B=wt(t,r+2),E=wt(t,r+4),P=wt(t,r+6),N=wt(t,r+8),k=wt(t,r+10),M=wt(t,r+12),U=wt(t,r+14),S=o[0]+(x&8191),L=o[1]+((x>>>13|B<<3)&8191),R=o[2]+((B>>>10|E<<6)&8191),T=o[3]+((E>>>7|P<<9)&8191),m=o[4]+((P>>>4|N<<12)&8191),y=o[5]+(N>>>1&8191),b=o[6]+((N>>>14|k<<2)&8191),A=o[7]+((k>>>11|M<<5)&8191),_=o[8]+((M>>>8|U<<8)&8191),C=o[9]+(U>>>5|s),v=0,I=v+S*a+L*(5*g)+R*(5*w)+T*(5*p)+m*(5*d);v=I>>>13,I&=8191,I+=y*(5*h)+b*(5*l)+A*(5*u)+_*(5*f)+C*(5*c),v+=I>>>13,I&=8191;let D=v+S*c+L*a+R*(5*g)+T*(5*w)+m*(5*p);v=D>>>13,D&=8191,D+=y*(5*d)+b*(5*h)+A*(5*l)+_*(5*u)+C*(5*f),v+=D>>>13,D&=8191;let O=v+S*f+L*c+R*a+T*(5*g)+m*(5*w);v=O>>>13,O&=8191,O+=y*(5*p)+b*(5*d)+A*(5*h)+_*(5*l)+C*(5*u),v+=O>>>13,O&=8191;let z=v+S*u+L*f+R*c+T*a+m*(5*g);v=z>>>13,z&=8191,z+=y*(5*w)+b*(5*p)+A*(5*d)+_*(5*h)+C*(5*l),v+=z>>>13,z&=8191;let F=v+S*l+L*u+R*f+T*c+m*a;v=F>>>13,F&=8191,F+=y*(5*g)+b*(5*w)+A*(5*p)+_*(5*d)+C*(5*h),v+=F>>>13,F&=8191;let V=v+S*h+L*l+R*u+T*f+m*c;v=V>>>13,V&=8191,V+=y*a+b*(5*g)+A*(5*w)+_*(5*p)+C*(5*d),v+=V>>>13,V&=8191;let $=v+S*d+L*h+R*l+T*u+m*f;v=$>>>13,$&=8191,$+=y*c+b*a+A*(5*g)+_*(5*w)+C*(5*p),v+=$>>>13,$&=8191;let X=v+S*p+L*d+R*h+T*l+m*u;v=X>>>13,X&=8191,X+=y*f+b*c+A*a+_*(5*g)+C*(5*w),v+=X>>>13,X&=8191;let it=v+S*w+L*p+R*d+T*h+m*l;v=it>>>13,it&=8191,it+=y*u+b*f+A*c+_*a+C*(5*g),v+=it>>>13,it&=8191;let G=v+S*g+L*w+R*p+T*d+m*h;v=G>>>13,G&=8191,G+=y*l+b*u+A*f+_*c+C*a,v+=G>>>13,G&=8191,v=(v<<2)+v|0,v=v+I|0,I=v&8191,v=v>>>13,D+=v,o[0]=I,o[1]=D,o[2]=O,o[3]=z,o[4]=F,o[5]=V,o[6]=$,o[7]=X,o[8]=it,o[9]=G}finalize(){let{h:t,pad:r}=this,n=new Uint16Array(10),s=t[1]>>>13;t[1]&=8191;for(let a=2;a<10;a++)t[a]+=s,s=t[a]>>>13,t[a]&=8191;t[0]+=s*5,s=t[0]>>>13,t[0]&=8191,t[1]+=s,s=t[1]>>>13,t[1]&=8191,t[2]+=s,n[0]=t[0]+5,s=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=t[a]+s,s=n[a]>>>13,n[a]&=8191;n[9]-=8192;let o=(s^1)-1;for(let a=0;a<10;a++)n[a]&=o;o=~o;for(let a=0;a<10;a++)t[a]=t[a]&o|n[a];t[0]=(t[0]|t[1]<<13)&65535,t[1]=(t[1]>>>3|t[2]<<10)&65535,t[2]=(t[2]>>>6|t[3]<<7)&65535,t[3]=(t[3]>>>9|t[4]<<4)&65535,t[4]=(t[4]>>>12|t[5]<<1|t[6]<<14)&65535,t[5]=(t[6]>>>2|t[7]<<11)&65535,t[6]=(t[7]>>>5|t[8]<<8)&65535,t[7]=(t[8]>>>8|t[9]<<5)&65535;let i=t[0]+r[0];t[0]=i&65535;for(let a=1;a<8;a++)i=(t[a]+r[a]|0)+(i>>>16)|0,t[a]=i&65535;he(n)}update(t){Xi(this),t=ws(t),Bt(t);let{buffer:r,blockLen:n}=this,s=t.length;for(let o=0;o<s;){let i=Math.min(n-this.pos,s-o);if(i===n){for(;n<=s-o;o+=n)this.process(t,o);continue}r.set(t.subarray(o,o+i),this.pos),this.pos+=i,o+=i,this.pos===n&&(this.process(r,0,!1),this.pos=0)}return this}destroy(){he(this.h,this.r,this.buffer,this.pad)}digestInto(t){Xi(this),Zu(t,this),this.finished=!0;let{buffer:r,h:n}=this,{pos:s}=this;if(s){for(r[s++]=1;s<16;s++)r[s]=0;this.process(r,0,!0)}this.finalize();let o=0;for(let i=0;i<8;i++)t[o++]=n[i]>>>0,t[o++]=n[i]>>>8;return t}digest(){let{buffer:t,outputLen:r}=this;this.digestInto(t);let n=t.slice(0,r);return this.destroy(),n}};function wp(e){let t=(n,s)=>e(s).update(ws(n)).digest(),r=e(new Uint8Array(32));return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=n=>e(n),t}var rf=wp(e=>new ra(e));function of(e,t,r,n,s,o=20){let i=e[0],a=e[1],c=e[2],f=e[3],u=t[0],l=t[1],h=t[2],d=t[3],p=t[4],w=t[5],g=t[6],x=t[7],B=s,E=r[0],P=r[1],N=r[2],k=i,M=a,U=c,S=f,L=u,R=l,T=h,m=d,y=p,b=w,A=g,_=x,C=B,v=E,I=P,D=N;for(let z=0;z<o;z+=2)k=k+L|0,C=K(C^k,16),y=y+C|0,L=K(L^y,12),k=k+L|0,C=K(C^k,8),y=y+C|0,L=K(L^y,7),M=M+R|0,v=K(v^M,16),b=b+v|0,R=K(R^b,12),M=M+R|0,v=K(v^M,8),b=b+v|0,R=K(R^b,7),U=U+T|0,I=K(I^U,16),A=A+I|0,T=K(T^A,12),U=U+T|0,I=K(I^U,8),A=A+I|0,T=K(T^A,7),S=S+m|0,D=K(D^S,16),_=_+D|0,m=K(m^_,12),S=S+m|0,D=K(D^S,8),_=_+D|0,m=K(m^_,7),k=k+R|0,D=K(D^k,16),A=A+D|0,R=K(R^A,12),k=k+R|0,D=K(D^k,8),A=A+D|0,R=K(R^A,7),M=M+T|0,C=K(C^M,16),_=_+C|0,T=K(T^_,12),M=M+T|0,C=K(C^M,8),_=_+C|0,T=K(T^_,7),U=U+m|0,v=K(v^U,16),y=y+v|0,m=K(m^y,12),U=U+m|0,v=K(v^U,8),y=y+v|0,m=K(m^y,7),S=S+L|0,I=K(I^S,16),b=b+I|0,L=K(L^b,12),S=S+L|0,I=K(I^S,8),b=b+I|0,L=K(L^b,7);let O=0;n[O++]=i+k|0,n[O++]=a+M|0,n[O++]=c+U|0,n[O++]=f+S|0,n[O++]=u+L|0,n[O++]=l+R|0,n[O++]=h+T|0,n[O++]=d+m|0,n[O++]=p+y|0,n[O++]=w+b|0,n[O++]=g+A|0,n[O++]=x+_|0,n[O++]=B+C|0,n[O++]=E+v|0,n[O++]=P+I|0,n[O++]=N+D|0}function Ep(e,t,r,n){let s=e[0],o=e[1],i=e[2],a=e[3],c=t[0],f=t[1],u=t[2],l=t[3],h=t[4],d=t[5],p=t[6],w=t[7],g=r[0],x=r[1],B=r[2],E=r[3];for(let N=0;N<20;N+=2)s=s+c|0,g=K(g^s,16),h=h+g|0,c=K(c^h,12),s=s+c|0,g=K(g^s,8),h=h+g|0,c=K(c^h,7),o=o+f|0,x=K(x^o,16),d=d+x|0,f=K(f^d,12),o=o+f|0,x=K(x^o,8),d=d+x|0,f=K(f^d,7),i=i+u|0,B=K(B^i,16),p=p+B|0,u=K(u^p,12),i=i+u|0,B=K(B^i,8),p=p+B|0,u=K(u^p,7),a=a+l|0,E=K(E^a,16),w=w+E|0,l=K(l^w,12),a=a+l|0,E=K(E^a,8),w=w+E|0,l=K(l^w,7),s=s+f|0,E=K(E^s,16),p=p+E|0,f=K(f^p,12),s=s+f|0,E=K(E^s,8),p=p+E|0,f=K(f^p,7),o=o+u|0,g=K(g^o,16),w=w+g|0,u=K(u^w,12),o=o+u|0,g=K(g^o,8),w=w+g|0,u=K(u^w,7),i=i+l|0,x=K(x^i,16),h=h+x|0,l=K(l^h,12),i=i+l|0,x=K(x^i,8),h=h+x|0,l=K(l^h,7),a=a+c|0,B=K(B^a,16),d=d+B|0,c=K(c^d,12),a=a+c|0,B=K(B^a,8),d=d+B|0,c=K(c^d,7);let P=0;n[P++]=s,n[P++]=o,n[P++]=i,n[P++]=a,n[P++]=g,n[P++]=x,n[P++]=B,n[P++]=E}var Sp=ea(of,{counterRight:!1,counterLength:4,allowShortKeys:!1}),vp=ea(of,{counterRight:!1,counterLength:8,extendNonceFn:Ep,allowShortKeys:!1});var Ap=new Uint8Array(16),nf=(e,t)=>{e.update(t);let r=t.length%16;r&&e.update(Ap.subarray(r))},Bp=new Uint8Array(32);function sf(e,t,r,n,s){let o=e(t,r,Bp),i=rf.create(o);s&&nf(i,s),nf(i,n);let a=Qu(n.length,s?s.length:0,!0);i.update(a);let c=i.digest();return he(o,a),c}var af=e=>(t,r,n)=>({encrypt(o,i){let a=o.length;i=Ji(a+16,i,!1),i.set(o);let c=i.subarray(0,-16);e(t,r,c,c,1);let f=sf(e,t,r,c,n);return i.set(f,a),he(f),i},decrypt(o,i){i=Ji(o.length-16,i,!1);let a=o.subarray(0,-16),c=o.subarray(-16),f=sf(e,t,r,a,n);if(!Xu(c,f))throw new Error("invalid tag");return i.set(o.subarray(0,-16)),e(t,r,i,i,1),he(f),i}}),na=Qi({blockSize:64,nonceLength:12,tagLength:16},af(Sp)),d1=Qi({blockSize:64,nonceLength:24,tagLength:16},af(vp));function uf(e,t,r){return Oe(e),r===void 0&&(r=new Uint8Array(e.outputLen)),Er(e,ge(r),ge(t))}var sa=Uint8Array.from([0]),cf=Uint8Array.of();function ff(e,t,r,n=32){Oe(e),Re(n);let s=e.outputLen;if(n>255*s)throw new Error("Length should be <= 255*HashLen");let o=Math.ceil(n/s);r===void 0&&(r=cf);let i=new Uint8Array(o*s),a=Er.create(e,t),c=a._cloneInto(),f=new Uint8Array(a.outputLen);for(let u=0;u<o;u++)sa[0]=u+1,c.update(u===0?cf:f).update(r).update(sa).digestInto(f),i.set(f,s*u),a._cloneInto(c);return a.destroy(),c.destroy(),Ht(f,sa),i.slice(0,n)}var oa={hashSHA256(e){return Se(e.subarray())},getHKDF(e,t){let r=uf(Se,t,e),s=ff(Se,r,void 0,96),o=s.subarray(0,32),i=s.subarray(32,64),a=s.subarray(64,96);return[o,i,a]},generateX25519KeyPair(){let e=en.utils.randomSecretKey();return{publicKey:en.getPublicKey(e),privateKey:e}},generateX25519KeyPairFromSeed(e){return{publicKey:en.getPublicKey(e),privateKey:e}},generateX25519SharedKey(e,t){return en.getSharedSecret(e.subarray(),t.subarray())},chaCha20Poly1305Encrypt(e,t,r,n){return na(n,t,r).encrypt(e.subarray())},chaCha20Poly1305Decrypt(e,t,r,n,s){return na(n,t,r).decrypt(e.subarray(),s)}};var lf=oa;function hf(e){return{generateKeypair:e.generateX25519KeyPair,dh:(t,r)=>e.generateX25519SharedKey(t.privateKey,r).subarray(0,32),encrypt:e.chaCha20Poly1305Encrypt,decrypt:e.chaCha20Poly1305Decrypt,hash:e.hashSHA256,hkdf:e.getHKDF}}var Dr=e=>{let t=gt(2);return t[0]=e>>8,t[1]=e,t};Dr.bytes=2;var Pr=e=>{if(e.length<2)throw RangeError("Could not decode int16BE");if(e instanceof Uint8Array){let t=0;return t+=e[0]<<8,t+=e[1],t}return e.getUint16(0)};Pr.bytes=2;function df(e){return{xxHandshakeSuccesses:e.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:e.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:e.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:e.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:e.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}function ia(e,t){!t.enabled||!Tr||(e?(t(`LOCAL_STATIC_PUBLIC_KEY ${q(e.publicKey,"hex")}`),t(`LOCAL_STATIC_PRIVATE_KEY ${q(e.privateKey,"hex")}`)):t("Missing local static keys."))}function aa(e,t){!t.enabled||!Tr||(e?(t(`LOCAL_PUBLIC_EPHEMERAL_KEY ${q(e.publicKey,"hex")}`),t(`LOCAL_PRIVATE_EPHEMERAL_KEY ${q(e.privateKey,"hex")}`)):t("Missing local ephemeral keys."))}function pf(e,t){!t.enabled||!Tr||t(e?`REMOTE_STATIC_PUBLIC_KEY ${q(e.subarray(),"hex")}`:"Missing remote static public key.")}function ca(e,t){!t.enabled||!Tr||t(e?`REMOTE_EPHEMERAL_PUBLIC_KEY ${q(e.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function ua(e,t,r){!r.enabled||!Tr||(r(`CIPHER_STATE_1 ${e.n.getUint64()} ${e.k&&q(e.k,"hex")}`),r(`CIPHER_STATE_2 ${t.n.getUint64()} ${t.k&&q(t.k,"hex")}`))}var Rr=class e extends Error{code;constructor(t="Invalid crypto exchange"){super(t),this.code=e.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};var _p=0,Ip=4294967295,Cp="Cipher state has reached maximum n, a new handshake must be performed",vs=class{n;bytes;view;constructor(t=_p){this.n=t,this.bytes=ht(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,t,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>Ip)throw new Error(Cp)}};var Ye=ht(0),Or=class{k;n;crypto;constructor(t,r=void 0,n=0){this.crypto=t,this.k=r,this.n=new vs(n)}hasKey(){return!!this.k}encryptWithAd(t,r){if(!this.hasKey())return r;this.n.assertValue();let n=this.crypto.encrypt(r,this.n.getBytes(),t,this.k);return this.n.increment(),n}decryptWithAd(t,r,n){if(!this.hasKey())return r;this.n.assertValue();let s=this.crypto.decrypt(r,this.n.getBytes(),t,this.k,n);return this.n.increment(),s}},fa=class{cs;ck;h;crypto;constructor(t,r){this.crypto=t;let n=Z(r,"utf-8");this.h=Lp(t,n),this.ck=this.h,this.cs=new Or(t)}mixKey(t){let[r,n]=this.crypto.hkdf(this.ck,t);this.ck=r,this.cs=new Or(this.crypto,n)}mixHash(t){this.h=this.crypto.hash(new j(this.h,t))}encryptAndHash(t){let r=this.cs.encryptWithAd(this.h,t);return this.mixHash(r),r}decryptAndHash(t){let r=this.cs.decryptWithAd(this.h,t);return this.mixHash(t),r}split(){let[t,r]=this.crypto.hkdf(this.ck,Ye);return[new Or(this.crypto,t),new Or(this.crypto,r)]}},la=class{ss;s;e;rs;re;initiator;crypto;constructor(t){let{crypto:r,protocolName:n,prologue:s,initiator:o,s:i,e:a,rs:c,re:f}=t;this.crypto=r,this.ss=new fa(r,n),this.ss.mixHash(s),this.initiator=o,this.s=i,this.e=a,this.rs=c,this.re=f}writeE(){if(this.e)throw new Error("ephemeral keypair is already set");let t=this.crypto.generateKeypair();return this.ss.mixHash(t.publicKey),this.e=t,t.publicKey}writeS(){if(!this.s)throw new Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.re))}writeES(){if(this.initiator){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}}writeSE(){if(this.initiator){if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(t,r=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(t.byteLength<r+32)throw new Error("message is not long enough");this.re=t.sublist(r,r+32),this.ss.mixHash(this.re)}readS(t,r=0){if(this.rs)throw new Error("remote static public key is already set");let n=32+(this.ss.cs.hasKey()?16:0);if(t.byteLength<r+n)throw new Error("message is not long enough");let s=t.sublist(r,r+n);return this.rs=this.ss.decryptAndHash(s),n}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}},gn=class extends la{writeMessageA(t){return new j(this.writeE(),this.ss.encryptAndHash(t))}writeMessageB(t){let r=this.writeE();this.writeEE();let n=this.writeS();return this.writeES(),new j(r,n,this.ss.encryptAndHash(t))}writeMessageC(t){let r=this.writeS();return this.writeSE(),new j(r,this.ss.encryptAndHash(t))}readMessageA(t){try{return this.readE(t),this.ss.decryptAndHash(t.sublist(32))}catch(r){throw new Rr(`handshake stage 0 validation fail: ${r.message}`)}}readMessageB(t){try{this.readE(t),this.readEE();let r=this.readS(t,32);return this.readES(),this.ss.decryptAndHash(t.sublist(32+r))}catch(r){throw new Rr(`handshake stage 1 validation fail: ${r.message}`)}}readMessageC(t){try{let r=this.readS(t);return this.readSE(),this.ss.decryptAndHash(t.sublist(r))}catch(r){throw new Rr(`handshake stage 2 validation fail: ${r.message}`)}}};function Lp(e,t){if(t.length<=32){let r=ht(32);return r.set(t),r}else return e.hash(t)}var As;(function(e){let t;e.codec=()=>(t==null&&(t=We((r,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),r.webtransportCerthashes!=null)for(let o of r.webtransportCerthashes)n.uint32(10),n.bytes(o);if(r.streamMuxers!=null)for(let o of r.streamMuxers)n.uint32(18),n.string(o);s.lengthDelimited!==!1&&n.ldelim()},(r,n,s={})=>{let o={webtransportCerthashes:[],streamMuxers:[]},i=n==null?r.len:r.pos+n;for(;r.pos<i;){let a=r.uint32();switch(a>>>3){case 1:{if(s.limits?.webtransportCerthashes!=null&&o.webtransportCerthashes.length===s.limits.webtransportCerthashes)throw new on('Decode error - map field "webtransportCerthashes" had too many elements');o.webtransportCerthashes.push(r.bytes());break}case 2:{if(s.limits?.streamMuxers!=null&&o.streamMuxers.length===s.limits.streamMuxers)throw new on('Decode error - map field "streamMuxers" had too many elements');o.streamMuxers.push(r.string());break}default:{r.skipType(a&7);break}}}return o})),t),e.encode=r=>Fe(r,e.codec()),e.decode=(r,n)=>qe(r,e.codec(),n)})(As||(As={}));var bn;(function(e){let t;e.codec=()=>(t==null&&(t=We((r,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),r.identityKey!=null&&r.identityKey.byteLength>0&&(n.uint32(10),n.bytes(r.identityKey)),r.identitySig!=null&&r.identitySig.byteLength>0&&(n.uint32(18),n.bytes(r.identitySig)),r.extensions!=null&&(n.uint32(34),As.codec().encode(r.extensions,n)),s.lengthDelimited!==!1&&n.ldelim()},(r,n,s={})=>{let o={identityKey:ht(0),identitySig:ht(0)},i=n==null?r.len:r.pos+n;for(;r.pos<i;){let a=r.uint32();switch(a>>>3){case 1:{o.identityKey=r.bytes();break}case 2:{o.identitySig=r.bytes();break}case 4:{o.extensions=As.codec().decode(r,r.uint32(),{limits:s.limits?.extensions});break}default:{r.skipType(a&7);break}}}return o})),t),e.encode=r=>Fe(r,e.codec()),e.decode=(r,n)=>qe(r,e.codec(),n)})(bn||(bn={}));async function da(e,t,r){let n=await e.sign(yf(t));return bn.encode({identityKey:ye(e.publicKey),identitySig:n,extensions:r})}async function pa(e,t,r){try{let n=bn.decode(e),s=un(n.identityKey);if(r?.equals(s)===!1)throw new Error(`Payload identity key ${s} does not match expected remote identity key ${r}`);if(!t)throw new Error("Remote static does not exist");let o=yf(t);if(!await s.verify(o,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new En(n.message)}}function yf(e){let t=Z("noise-libp2p-static-key:");return e instanceof Uint8Array?Ot([t,e],t.length+e.length):(e.prepend(t),e)}var ha=class extends $t{stream;handshake;metrics;decoder;constructor(t,r,n){super({log:t.log,inactivityTimeout:t.inactivityTimeout,maxReadBufferLength:t.maxReadBufferLength,direction:t.direction}),this.stream=t,this.handshake=r,this.metrics=n,this.decoder=new gs({lengthDecoder:Pr,maxBufferSize:16*1024*1024,encodingLength:()=>2});let s=c=>{try{for(let f of this.decoder.decode(c.data))this.onData(this.decrypt(f))}catch(f){this.abort(f)}};this.stream.addEventListener("message",s);let o=c=>{c.error!=null?c.local===!0?this.abort(c.error):this.onRemoteReset():this.onTransportClosed()};this.stream.addEventListener("close",o);let i=()=>{this.safeDispatchEvent("drain")};this.stream.addEventListener("drain",i);let a=()=>{this.onRemoteCloseWrite()};this.stream.addEventListener("remoteCloseWrite",a)}encrypt(t){let r=new j;for(let n=0;n<t.byteLength;n+=65519){let s=n+65519;s>t.byteLength&&(s=t.byteLength);let o;t instanceof Uint8Array?o=this.handshake.encrypt(t.subarray(n,s)):o=this.handshake.encrypt(t.sublist(n,s)),this.metrics?.encryptedPackets.increment(),r.append(Dr(o.byteLength)),r.append(o)}return r}decrypt(t){let r=new j;for(let n=0;n<t.byteLength;n+=65535){let s=n+65535;if(s>t.byteLength&&(s=t.byteLength),s-Yi<n)throw new Error("Invalid chunk");let o;t instanceof Uint8Array?o=t.subarray(n,s):o=t.sublist(n,s);let i=t.subarray(n,s-Yi);try{let a=this.handshake.decrypt(o,i);this.metrics?.decryptedPackets.increment(),r.append(a)}catch(a){throw this.metrics?.decryptErrors.increment(),a}}return r}close(t){return this.stream.close(t)}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}sendReset(t){this.stream.abort(t)}sendData(t){return{sentBytes:t.byteLength,canSendMore:this.stream.send(this.encrypt(t))}}};function ma(e,t,r){return new ha(e,t,r)}async function gf(e,t){let{log:r,connection:n,crypto:s,privateKey:o,prologue:i,s:a,remoteIdentityKey:c,extensions:f}=e,u=await da(o,a.publicKey,f),l=new gn({crypto:s,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});ia(l.s,r),r.trace("Stage 0 - Initiator starting to send first message."),await n.write(l.writeMessageA(Ye),t),r.trace("Stage 0 - Initiator finished sending first message."),aa(l.e,r),r.trace("Stage 1 - Initiator waiting to receive first message from responder...");let h=l.readMessageB(await n.read(t));r.trace("Stage 1 - Initiator received the message."),ca(l.re,r),pf(l.rs,r),r.trace("Initiator going to check remote's signature...");let d=await pa(h,l.rs,c);r.trace("All good with the signature!"),r.trace("Stage 2 - Initiator sending third handshake message."),await n.write(l.writeMessageC(u),t),r.trace("Stage 2 - Initiator sent message with signed payload.");let[p,w]=l.ss.split();return ua(p,w,r),{payload:d,encrypt:g=>p.encryptWithAd(Ye,g),decrypt:(g,x)=>w.decryptWithAd(Ye,g,x)}}async function bf(e,t){let{log:r,connection:n,crypto:s,privateKey:o,prologue:i,s:a,remoteIdentityKey:c,extensions:f}=e,u=await da(o,a.publicKey,f),l=new gn({crypto:s,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});ia(l.s,r),r.trace("Stage 0 - Responder waiting to receive first message."),l.readMessageA(await n.read(t)),r.trace("Stage 0 - Responder received first message."),ca(l.re,r),r.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(l.writeMessageB(u),t),r.trace("Stage 1 - Responder sent the second handshake message with signed payload."),aa(l.e,r),r.trace("Stage 2 - Responder waiting for third handshake message...");let h=l.readMessageC(await n.read(t));r.trace("Stage 2 - Responder received the message, finished handshake.");let d=await pa(h,l.rs,c),[p,w]=l.ss.split();return ua(p,w,r),{payload:d,encrypt:g=>w.encryptWithAd(Ye,g),decrypt:(g,x)=>p.decryptWithAd(Ye,g,x)}}var Bs=class{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;log;constructor(t,r={}){let{staticNoiseKey:n,extensions:s,crypto:o,prologueBytes:i}=r,{metrics:a}=t;this.components=t,this.log=t.logger.forComponent("libp2p:noise");let c=o??lf;this.crypto=hf(c),this.extensions={webtransportCerthashes:[],...s},this.metrics=a?df(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??ht(0)}[Symbol.toStringTag]="@libp2p/noise";[Ln]=["@libp2p/connection-encryption","@libp2p/noise"];async secureOutbound(t,r){let n=t.log?.newScope("noise")??this.log,s=Zi(t,{lengthEncoder:Dr,lengthDecoder:Pr,maxDataLength:65535}),o=await this.performHandshakeInitiator(s,this.components.privateKey,n,r?.remotePeer?.publicKey,r),i=un(o.payload.identityKey);return{connection:ma(s.unwrap(),o,this.metrics),remoteExtensions:o.payload.extensions,remotePeer:gi(i),streamMuxer:r?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(o.payload.extensions?.streamMuxers)}}getStreamMuxer(t){if(t==null||t.length===0)return;let r=this.components.upgrader.getStreamMuxers();if(r!=null)for(let n of t){let s=r.get(n);if(s!=null)return s}if(t.length)throw new tr("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(t,r){let n=t.log?.newScope("noise")??this.log,s=Zi(t,{lengthEncoder:Dr,lengthDecoder:Pr,maxDataLength:65535}),o=await this.performHandshakeResponder(s,this.components.privateKey,n,r?.remotePeer?.publicKey,r),i=un(o.payload.identityKey);return{connection:ma(s.unwrap(),o,this.metrics),remoteExtensions:o.payload.extensions,remotePeer:gi(i),streamMuxer:r?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(o.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(t,r,n,s,o){let i,a=o?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await gf({connection:t,privateKey:r,remoteIdentityKey:s,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},o),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}async performHandshakeResponder(t,r,n,s,o){let i,a=o?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await bf({connection:t,privateKey:r,remoteIdentityKey:s,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},o),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}};function xf(e={}){return t=>new Bs(t,e)}var st=e=>({match:t=>{let r=t[0];return r==null||r.code!==e||r.value!=null?!1:t.slice(1)}}),H=(e,t)=>({match:r=>{let n=r[0];return n?.code!==e||n.value==null||t!=null&&n.value!==t?!1:r.slice(1)}}),wf=e=>({match:t=>e.match(t)===!1?t:!1}),W=e=>({match:t=>{let r=e.match(t);return r===!1?t:r}}),_t=(...e)=>({match:t=>{let r;for(let n of e){let s=n.match(t);s!==!1&&(r==null||s.length<r.length)&&(r=s)}return r??!1}}),J=(...e)=>({match:t=>{for(let r of e){let n=r.match(t);if(n===!1)return!1;t=n}return t}});function ot(...e){function t(s){if(s==null)return!1;let o=s.getComponents();for(let i of e){let a=i.match(o);if(a===!1)return!1;o=a}return o}function r(s){return t(s)!==!1}function n(s){let o=t(s);return o===!1?!1:o.length===0}return{matchers:e,matches:r,exactMatch:n}}var Tp=H(421),N2=ot(Tp),Is=H(54),Cs=H(55),Ls=H(56),ga=H(53),M2=ot(Is,W(H(421))),k2=ot(Cs,W(H(421))),H2=ot(Ls,W(H(421))),V2=ot(_t(ga,Ls,Is,Cs),W(H(421))),Ef=J(H(4),W(H(43))),Sf=J(W(H(42)),H(41),W(H(43))),ba=_t(Ef,Sf),Xe=_t(ba,ga,Is,Cs,Ls),q2=ot(_t(ba,J(_t(ga,Ls,Is,Cs),W(H(421))))),z2=ot(Ef),F2=ot(Sf),W2=ot(ba),xa=J(Xe,H(6)),wn=J(Xe,H(273)),$2=ot(J(xa,W(H(421)))),G2=ot(wn),wa=J(wn,st(460),W(H(421))),Ts=J(wn,st(461),W(H(421))),Dp=_t(wa,Ts),j2=ot(wa),Z2=ot(Ts),ya=_t(Xe,xa,wn,wa,Ts),vf=_t(J(ya,st(477),W(H(421)))),Y2=ot(vf),Af=_t(J(ya,st(478),W(H(421))),J(ya,st(448),W(H(449)),st(477),W(H(421)))),X2=ot(Af),Bf=J(wn,st(280),W(H(466)),W(H(466)),W(H(421))),Q2=ot(Bf),_f=J(Ts,st(465),W(H(466)),W(H(466)),W(H(421))),Ds=ot(_f),_s=_t(vf,Af,J(xa,W(H(421))),J(Dp,W(H(421))),J(Xe,W(H(421))),Bf,_f,H(421)),J2=ot(_s),Pp=J(W(_s),st(290),wf(st(281)),W(H(421))),tE=ot(Pp),Rp=_t(J(_s,st(290),st(281),W(H(421))),J(_s,st(281),W(H(421))),J(st(281),W(H(421)))),eE=ot(Rp),Op=_t(J(Xe,H(6),st(480),W(H(421))),J(Xe,st(480),W(H(421)))),rE=ot(Op),Up=J(Xe,_t(J(H(6,"443"),st(480)),J(H(6),st(443)),J(H(6),st(448),st(480)),J(st(448),st(480)),st(448),st(443)),W(H(421))),nE=ot(Up),Kp=_t(J(H(777),W(H(421)))),sE=ot(Kp),Np=_t(J(H(400),W(H(421)))),oE=ot(Np);var Qe=class extends Event{type;detail;constructor(t,r){super(t),this.type=t,this.detail=r}};function Ea(e){throw new Error("Not implemented")}var Sa=class extends us{writer;reader;constructor(t){super(t),this.writer=t.stream.writable.getWriter(),this.reader=t.stream.readable.getReader(),this.writer.closed.then(()=>{this.log("writer closed gracefully")}).catch(r=>{r.message.includes("STOP_SENDING")||r.message.includes("StopSending")?this.onRemoteCloseRead():r.message.includes("RESET_STREAM")||r.message.includes("Reset")?this.onRemoteReset():this.log("writer close promise rejected - %e",r)}),this.readData()}readData(){Promise.resolve().then(async()=>{for(;;){let t=await this.reader.read();if(t.value!=null&&this.onData(t.value),t.done){this.log("remote closed write"),this.onRemoteCloseWrite();return}if(this.readStatus==="paused")break}}).catch(t=>{this.abort(t)}).finally(()=>{this.reader.releaseLock()})}sendData(t){for(let n of t)this.writer.write(n).catch(s=>{this.abort(s)});if(this.log.trace("desired size after sending %d bytes is %d bytes",t.byteLength,this.writer.desiredSize),this.writer.desiredSize==null)return{sentBytes:t.byteLength,canSendMore:!1};let r=this.writer.desiredSize>0;return r||this.writer.ready.then(()=>{this.safeDispatchEvent("drain")},n=>{this.abort(n)}),{sentBytes:t.byteLength,canSendMore:r}}sendReset(t){this.writer.abort(t).catch(r=>{this.log.error("error aborting writer - %e",r)})}async sendCloseWrite(t){this.log("sendCloseWrite closing writer"),await ce(this.writer.close().catch(()=>{}),t?.signal),this.log("sendCloseWrite closed writer")}async sendCloseRead(t){this.log("sendCloseRead cancelling reader"),await ce(this.reader.cancel(),t?.signal),this.log("sendCloseRead cancelled reader")}sendPause(){}sendResume(){this.readData()}};function va(e,t,r,n,s){return new Sa({...s,stream:e,id:t,direction:r,log:n.newScope(`${r}:${t}`),protocol:""})}var If="/webtransport",Aa=class extends cs{webTransport;streamIDCounter;reader;constructor(t,r){super(r,{protocol:If,name:"muxer"}),this.webTransport=t,this.streamIDCounter=0,this.reader=this.webTransport.incomingBidirectionalStreams.getReader(),Promise.resolve().then(async()=>{for(;;){let{done:n,value:s}=await this.reader.read();if(n||s==null)break;this.onRemoteStream(va(s,String(this.streamIDCounter++),"inbound",this.log,this.streamOptions))}}).catch(n=>{this.log.error("could not create a new stream - %e",n)})}async onCreateStream(t){let r=await this.webTransport.createBidirectionalStream();return t?.signal?.throwIfAborted(),va(r,String(this.streamIDCounter++),"outbound",this.log,t)}onData(){}sendReset(){this.webTransport.close()}};function Cf(e){return{protocol:If,createStreamMuxer(t){return new Aa(e,t)}}}var Ba=class extends as{cleanUpWTSession;constructor(t){super(t),this.cleanUpWTSession=t.cleanUpWTSession}sendData(t){return{sentBytes:t.byteLength,canSendMore:!0}}sendReset(){this.cleanUpWTSession("abort")}async sendClose(t){this.cleanUpWTSession("close"),t?.signal?.throwIfAborted()}sendPause(){}sendResume(){}},Lf=e=>new Ba(e);function Tf(e,t){return t.filter(n=>!!e.find(s=>lt(n,s))).length===t.length}var Mp=Object.values(De).map(e=>e.decoder).reduce((e,t)=>e.or(t));function kp(e){return jt.decode(Mp.decode(e))}function _a(e){if(!Ds.matches(e))throw new Mr("Invalid multiaddr, was not a WebTransport address");let t=[],r;for(let o of e.getComponents())o.name==="certhash"&&t.push(kp(o.value??"")),o.name==="p2p"&&r==null&&(r=Bu(o.value??""));if(r==null)throw new Mr("Remote peer must be present in multiaddr");let n=Iu(e),s=n.host;return n.type==="ip6"&&s.includes(":")&&(s=`[${s}]`),{url:`https://${s}:${n.port}`,certhashes:t,remotePeer:r}}var Ps=class extends $t{writer;reader;constructor(t){super(t),this.writer=t.stream.writable.getWriter(),this.reader=t.stream.readable.getReader(),Promise.resolve().then(async()=>{for(;;){let{done:r,value:n}=await this.reader.read();if(n!=null&&this.onData(n),r)break}}).catch(r=>{this.abort(r)})}async close(t){await ce(this.writer.close(),t?.signal)}sendData(t){return this.writer.write(t.subarray()).catch(r=>{this.abort(r)}),{sentBytes:t.byteLength,canSendMore:!0}}sendReset(t){this.writer.abort(t).catch(r=>{this.log.error("could not send reset - %e",r)})}sendPause(){}sendResume(){}};var Df=globalThis.WebTransport;var Ia=class{log;components;config;metrics;constructor(t,r={}){this.log=t.logger.forComponent("libp2p:webtransport"),this.components=t,this.config={...r,certificates:r.certificates??[]},t.metrics!=null&&(this.metrics={dialerEvents:t.metrics.registerCounterGroup("libp2p_webtransport_dialer_events_total",{label:"event",help:"Total count of WebTransport dialer events by type"})})}[Symbol.toStringTag]="@libp2p/webtransport";[Da]=!0;[Ln]=["@libp2p/transport"];async dial(t,r){r.signal.throwIfAborted(),this.log("dialing %s",t),r=r??{};let{url:n,certhashes:s,remotePeer:o}=_a(t),i,a,c=()=>{},f=!1,u=!1,l=!1;try{this.metrics?.dialerEvents.increment({pending:!0});let h=new Df(`${n}/.well-known/libp2p-webtransport?type=noise`,{serverCertificateHashes:s.map(d=>({algorithm:"sha-256",value:d.digest}))});if(c=d=>{if(!f)try{this.metrics?.dialerEvents.increment({[d]:!0}),h.close()}catch(p){this.log.error("error closing wt session",p)}finally{a!=null&&(a.timeline.close=Date.now()),f=!0}},i=()=>{c(u?"noise_timeout":"ready_timeout")},r.signal.addEventListener("abort",i,{once:!0}),this.log("wait for session to be ready"),r.onProgress?.(new Qe("webtransport:wait-for-session")),await Promise.race([h.closed,h.ready]),this.log("session became ready"),u=!0,this.metrics?.dialerEvents.increment({ready:!0}),h.closed.catch(d=>{this.log.error("error on remote wt session close",d)}).finally(()=>{c("remote_close")}),this.metrics?.dialerEvents.increment({open:!0}),a=Lf({remoteAddr:t,cleanUpWTSession:c,direction:"outbound",log:this.components.logger.forComponent("libp2p:webtransport:connection")}),l=await this.authenticateWebTransport({wt:h,maConn:a,remotePeer:o,certhashes:s,...r}),!l)throw new tr("Failed to authenticate webtransport");return await r.upgrader.upgradeOutbound(a,{...r,skipEncryption:!0,remotePeer:o,muxerFactory:Cf(h),skipProtection:!0})}catch(h){throw this.log.error("caught wt session err",h),c(l?"upgrade_error":u?"noise_error":"ready_error"),h}finally{i!=null&&r.signal?.removeEventListener("abort",i)}}async authenticateWebTransport({wt:t,maConn:r,remotePeer:n,certhashes:s,onProgress:o,signal:i}){o?.(new Qe("webtransport:open-authentication-stream"));let a=await t.createBidirectionalStream();i?.throwIfAborted();let c=new Ps({stream:a,log:r.log.newScope("muxer")}),f=xf()(this.components);o?.(new Qe("webtransport:secure-outbound-connection"));let{remoteExtensions:u}=await f.secureOutbound(c,{signal:i,remotePeer:n,skipStreamMuxerNegotiation:!0});if(o?.(new Qe("webtransport:close-authentication-stream")),await c.close({signal:i}),!Tf(u?.webtransportCerthashes??[],s.map(l=>l.bytes)))throw new et("Our certhashes are not a subset of the remote's reported certhashes");return!0}createListener(t){return Ea(this.components,{...t,certificates:this.config.certificates})}listenFilter(){return[]}dialFilter(t){return globalThis.WebTransport==null?[]:t.filter(r=>{if(!Ds.exactMatch(r))return!1;let{url:n,certhashes:s}=_a(r);return n!=null&&s.length>0})}};function Hp(e={}){return t=>new Ia(t,e)}return Kf(Vp);})();
2
+ "use strict";var Libp2PWebtransport=(()=>{var Rs=Object.defineProperty;var Pf=Object.getOwnPropertyDescriptor;var Rf=Object.getOwnPropertyNames;var Of=Object.prototype.hasOwnProperty;var It=(e,t)=>{for(var r in t)Rs(e,r,{get:t[r],enumerable:!0})},Uf=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Rf(t))!Of.call(e,s)&&s!==r&&Rs(e,s,{get:()=>t[s],enumerable:!(n=Pf(t,s))||n.enumerable});return e};var Kf=e=>Uf(Rs({},"__esModule",{value:!0}),e);var Vp={};It(Vp,{webTransport:()=>Hp});var En=class extends Error{static name="UnexpectedPeerError";constructor(t="Unexpected Peer"){super(t),this.name="UnexpectedPeerError"}},tr=class extends Error{static name="InvalidCryptoExchangeError";constructor(t="Invalid crypto exchange"){super(t),this.name="InvalidCryptoExchangeError"}},et=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},er=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}};var Sn=class extends Error{static name="MuxerClosedError";constructor(t="The muxer is closed"){super(t),this.name="MuxerClosedError"}},vn=class extends Error{static name="StreamResetError";constructor(t="The stream has been reset"){super(t),this.name="StreamResetError"}};var Ce=class extends Error{static name="StreamStateError";constructor(t="The stream is in an invalid state"){super(t),this.name="StreamStateError"}},Nr=class extends Error{static name="StreamBufferError";constructor(t="The stream buffer was full"){super(t),this.name="StreamBufferError"}};var Mr=class extends Error{static name="InvalidMultiaddrError";constructor(t="Invalid multiaddr"){super(t),this.name="InvalidMultiaddrError"}},An=class extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}},Bn=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}};var Le=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var _n=class extends Event{data;constructor(t,r){super("message",r),this.data=t}},rr=class extends Event{error;local;constructor(t,r,n){super("close",n),this.error=r,this.local=t}},In=class extends rr{constructor(t,r){super(!0,t,r)}},Cn=class extends rr{constructor(t,r){super(!1,t,r)}};var Os=Symbol.for("@libp2p/peer-id");var Da=Symbol.for("@libp2p/transport");var Ta;(function(e){e[e.FATAL_ALL=0]="FATAL_ALL",e[e.NO_FATAL=1]="NO_FATAL"})(Ta||(Ta={}));var nr=class extends EventTarget{#t=new Map;constructor(){super()}listenerCount(t){let r=this.#t.get(t);return r==null?0:r.length}addEventListener(t,r,n){super.addEventListener(t,r,n);let s=this.#t.get(t);s==null&&(s=[],this.#t.set(t,s)),s.push({callback:r,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(t,r,n){super.removeEventListener(t.toString(),r??null,n);let s=this.#t.get(t);s!=null&&(s=s.filter(({callback:o})=>o!==r),this.#t.set(t,s))}dispatchEvent(t){let r=super.dispatchEvent(t),n=this.#t.get(t.type);return n==null||(n=n.filter(({once:s})=>!s),this.#t.set(t.type,n)),r}safeDispatchEvent(t,r={}){return this.dispatchEvent(new CustomEvent(t,r))}};var Ln=Symbol.for("@libp2p/service-capabilities"),jp=Symbol.for("@libp2p/service-dependencies");var ks={};It(ks,{base58btc:()=>ct,base58flickr:()=>zf});var wm=new Uint8Array(0);function Pa(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0}function Gt(e){if(e instanceof Uint8Array&&e.constructor.name==="Uint8Array")return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")}function Ra(e){return new TextEncoder().encode(e)}function Oa(e){return new TextDecoder().decode(e)}function Nf(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var s=0;s<e.length;s++){var o=e.charAt(s),i=o.charCodeAt(0);if(r[i]!==255)throw new TypeError(o+" is ambiguous");r[i]=s}var a=e.length,c=e.charAt(0),f=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function l(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var w=0,g=0,x=0,B=p.length;x!==B&&p[x]===0;)x++,w++;for(var E=(B-x)*u+1>>>0,P=new Uint8Array(E);x!==B;){for(var N=p[x],k=0,M=E-1;(N!==0||k<g)&&M!==-1;M--,k++)N+=256*P[M]>>>0,P[M]=N%a>>>0,N=N/a>>>0;if(N!==0)throw new Error("Non-zero carry");g=k,x++}for(var U=E-g;U!==E&&P[U]===0;)U++;for(var S=c.repeat(w);U<E;++U)S+=e.charAt(P[U]);return S}function h(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var w=0;if(p[w]!==" "){for(var g=0,x=0;p[w]===c;)g++,w++;for(var B=(p.length-w)*f+1>>>0,E=new Uint8Array(B);p[w];){var P=r[p.charCodeAt(w)];if(P===255)return;for(var N=0,k=B-1;(P!==0||N<x)&&k!==-1;k--,N++)P+=a*E[k]>>>0,E[k]=P%256>>>0,P=P/256>>>0;if(P!==0)throw new Error("Non-zero carry");x=N,w++}if(p[w]!==" "){for(var M=B-x;M!==B&&E[M]===0;)M++;for(var U=new Uint8Array(g+(B-M)),S=g;M!==B;)U[S++]=E[M++];return U}}}function d(p){var w=h(p);if(w)return w;throw new Error(`Non-${t} character`)}return{encode:l,decodeUnsafe:h,decode:d}}var Mf=Nf,kf=Mf,Ka=kf;var Us=class{name;prefix;baseEncode;constructor(t,r,n){this.name=t,this.prefix=r,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},Ks=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,r,n){this.name=t,this.prefix=r;let s=r.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return Na(this,t)}},Ns=class{decoders;constructor(t){this.decoders=t}or(t){return Na(this,t)}decode(t){let r=t[0],n=this.decoders[r];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Na(e,t){return new Ns({...e.decoders??{[e.prefix]:e},...t.decoders??{[t.prefix]:t}})}var Ms=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,r,n,s){this.name=t,this.prefix=r,this.baseEncode=n,this.baseDecode=s,this.encoder=new Us(t,r,n),this.decoder=new Ks(t,r,s)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function sr({name:e,prefix:t,encode:r,decode:n}){return new Ms(e,t,r,n)}function de({name:e,prefix:t,alphabet:r}){let{encode:n,decode:s}=Ka(r,e);return sr({prefix:t,name:e,encode:n,decode:o=>Gt(s(o))})}function Hf(e,t,r,n){let s=e.length;for(;e[s-1]==="=";)--s;let o=new Uint8Array(s*r/8|0),i=0,a=0,c=0;for(let f=0;f<s;++f){let u=t[e[f]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<r|u,i+=r,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=r||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function Vf(e,t,r){let n=t[t.length-1]==="=",s=(1<<r)-1,o="",i=0,a=0;for(let c=0;c<e.length;++c)for(a=a<<8|e[c],i+=8;i>r;)i-=r,o+=t[s&a>>i];if(i!==0&&(o+=t[s&a<<r-i]),n)for(;(o.length*r&7)!==0;)o+="=";return o}function qf(e){let t={};for(let r=0;r<e.length;++r)t[e[r]]=r;return t}function at({name:e,prefix:t,bitsPerChar:r,alphabet:n}){let s=qf(n);return sr({prefix:t,name:e,encode(o){return Vf(o,n,r)},decode(o){return Hf(o,s,r,e)}})}var ct=de({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),zf=de({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Hs={};It(Hs,{base32:()=>pe,base32hex:()=>Gf,base32hexpad:()=>Zf,base32hexpadupper:()=>Yf,base32hexupper:()=>jf,base32pad:()=>Wf,base32padupper:()=>$f,base32upper:()=>Ff,base32z:()=>Xf});var pe=at({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Ff=at({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Wf=at({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),$f=at({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Gf=at({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),jf=at({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Zf=at({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Yf=at({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Xf=at({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Vs={};It(Vs,{base36:()=>kr,base36upper:()=>Qf});var kr=de({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Qf=de({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var jt={};It(jt,{Digest:()=>Te,create:()=>Mt,decode:()=>ar,equals:()=>zs,hasCode:()=>gl});var Jf=Ha,Ma=128,tl=127,el=~tl,rl=Math.pow(2,31);function Ha(e,t,r){t=t||[],r=r||0;for(var n=r;e>=rl;)t[r++]=e&255|Ma,e/=128;for(;e&el;)t[r++]=e&255|Ma,e>>>=7;return t[r]=e|0,Ha.bytes=r-n+1,t}var nl=qs,sl=128,ka=127;function qs(e,n){var r=0,n=n||0,s=0,o=n,i,a=e.length;do{if(o>=a)throw qs.bytes=0,new RangeError("Could not decode varint");i=e[o++],r+=s<28?(i&ka)<<s:(i&ka)*Math.pow(2,s),s+=7}while(i>=sl);return qs.bytes=o-n,r}var ol=Math.pow(2,7),il=Math.pow(2,14),al=Math.pow(2,21),cl=Math.pow(2,28),ul=Math.pow(2,35),fl=Math.pow(2,42),ll=Math.pow(2,49),hl=Math.pow(2,56),dl=Math.pow(2,63),pl=function(e){return e<ol?1:e<il?2:e<al?3:e<cl?4:e<ul?5:e<fl?6:e<ll?7:e<hl?8:e<dl?9:10},ml={encode:Jf,decode:nl,encodingLength:pl},yl=ml,Hr=yl;function Vr(e,t=0){return[Hr.decode(e,t),Hr.decode.bytes]}function or(e,t,r=0){return Hr.encode(e,t,r),t}function ir(e){return Hr.encodingLength(e)}function Mt(e,t){let r=t.byteLength,n=ir(e),s=n+ir(r),o=new Uint8Array(s+r);return or(e,o,0),or(r,o,n),o.set(t,s),new Te(e,r,t,o)}function ar(e){let t=Gt(e),[r,n]=Vr(t),[s,o]=Vr(t.subarray(n)),i=t.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new Te(r,s,i,t)}function zs(e,t){if(e===t)return!0;{let r=t;return e.code===r.code&&e.size===r.size&&r.bytes instanceof Uint8Array&&Pa(e.bytes,r.bytes)}}var Te=class{code;size;digest;bytes;constructor(t,r,n,s){this.code=t,this.size=r,this.digest=n,this.bytes=s}};function gl(e,t){return e.code===t}function Va(e,t){let{bytes:r,version:n}=e;switch(n){case 0:return xl(r,Fs(e),t??ct.encoder);default:return wl(r,Fs(e),t??pe.encoder)}}var qa=new WeakMap;function Fs(e){let t=qa.get(e);if(t==null){let r=new Map;return qa.set(e,r),r}return t}var ft=class e{code;version;multihash;bytes;"/";constructor(t,r,n,s){this.code=r,this.version=t,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:t,multihash:r}=this;if(t!==qr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==El)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return e.createV0(r)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:t,digest:r}=this.multihash,n=Mt(t,r);return e.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return e.equals(this,t)}static equals(t,r){let n=r;return n!=null&&t.code===n.code&&t.version===n.version&&zs(t.multihash,n.multihash)}toString(t){return Va(this,t)}toJSON(){return{"/":Va(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let r=t;if(r instanceof e)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){let{version:n,code:s,multihash:o,bytes:i}=r;return new e(n,s,o,i??za(n,s,o.bytes))}else if(r[Sl]===!0){let{version:n,multihash:s,code:o}=r,i=ar(s);return e.create(n,o,i)}else return null}static create(t,r,n){if(typeof r!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(r!==qr)throw new Error(`Version 0 CID must use dag-pb (code: ${qr}) block encoding`);return new e(t,r,n,n.bytes)}case 1:{let s=za(t,r,n.bytes);return new e(t,r,n,s)}default:throw new Error("Invalid version")}}static createV0(t){return e.create(0,qr,t)}static createV1(t,r){return e.create(1,t,r)}static decode(t){let[r,n]=e.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return r}static decodeFirst(t){let r=e.inspectBytes(t),n=r.size-r.multihashSize,s=Gt(t.subarray(n,n+r.multihashSize));if(s.byteLength!==r.multihashSize)throw new Error("Incorrect length");let o=s.subarray(r.multihashSize-r.digestSize),i=new Te(r.multihashCode,r.digestSize,o,s);return[r.version===0?e.createV0(i):e.createV1(r.codec,i),t.subarray(r.size)]}static inspectBytes(t){let r=0,n=()=>{let[l,h]=Vr(t.subarray(r));return r+=h,l},s=n(),o=qr;if(s===18?(s=0,r=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=r,a=n(),c=n(),f=r+c,u=f-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:f}}static parse(t,r){let[n,s]=bl(t,r),o=e.decode(s);if(o.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Fs(o).set(n,t),o}};function bl(e,t){switch(e[0]){case"Q":{let r=t??ct;return[ct.prefix,r.decode(`${ct.prefix}${e}`)]}case ct.prefix:{let r=t??ct;return[ct.prefix,r.decode(e)]}case pe.prefix:{let r=t??pe;return[pe.prefix,r.decode(e)]}case kr.prefix:{let r=t??kr;return[kr.prefix,r.decode(e)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[e[0],t.decode(e)]}}}function xl(e,t,r){let{prefix:n}=r;if(n!==ct.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let s=t.get(n);if(s==null){let o=r.encode(e).slice(1);return t.set(n,o),o}else return s}function wl(e,t,r){let{prefix:n}=r,s=t.get(n);if(s==null){let o=r.encode(e);return t.set(n,o),o}else return s}var qr=112,El=18;function za(e,t,r){let n=ir(e),s=n+ir(t),o=new Uint8Array(s+r.byteLength);return or(e,o,0),or(t,o,n),o.set(r,s),o}var Sl=Symbol.for("@ipld/js-cid/CID");var Ws={};It(Ws,{identity:()=>kt});var Fa=0,vl="identity",Wa=Gt;function Al(e,t){if(t?.truncate!=null&&t.truncate!==e.byteLength){if(t.truncate<0||t.truncate>e.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${e.byteLength}`);e=e.subarray(0,t.truncate)}return Mt(Fa,Wa(e))}var kt={code:Fa,name:vl,encode:Wa,digest:Al};function lt(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0}function ht(e=0){return new Uint8Array(e)}function gt(e=0){return new Uint8Array(e)}function Ot(e,t){t==null&&(t=e.reduce((s,o)=>s+o.length,0));let r=gt(t),n=0;for(let s of e)r.set(s,n),n+=s.length;return r}var Ga=Symbol.for("@achingbrain/uint8arraylist");function $a(e,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let r=0;for(let n of e){let s=r+n.byteLength;if(t<s)return{buf:n,index:t-r};r=s}throw new RangeError("index is out of bounds")}function Dn(e){return!!e?.[Ga]}var j=class e{bufs;length;[Ga]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let r=0;for(let n of t)if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.push(n);else if(Dn(n))r+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=r}prepend(...t){this.prependAll(t)}prependAll(t){let r=0;for(let n of t.reverse())if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.unshift(n);else if(Dn(n))r+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=r}get(t){let r=$a(this.bufs,t);return r.buf[r.index]}set(t,r){let n=$a(this.bufs,t);n.buf[n.index]=r}write(t,r=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(r+n,t[n]);else if(Dn(t))for(let n=0;n<t.length;n++)this.set(r+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,r){let{bufs:n,length:s}=this._subList(t,r);return Ot(n,s)}subarray(t,r){let{bufs:n,length:s}=this._subList(t,r);return n.length===1?n[0]:Ot(n,s)}sublist(t,r){let{bufs:n,length:s}=this._subList(t,r),o=new e;return o.length=s,o.bufs=[...n],o}_subList(t,r){if(t=t??0,r=r??this.length,t<0&&(t=this.length+t),r<0&&(r=this.length+r),t<0||r>this.length)throw new RangeError("index is out of bounds");if(t===r)return{bufs:[],length:0};if(t===0&&r===this.length)return{bufs:this.bufs,length:this.length};let n=[],s=0;for(let o=0;o<this.bufs.length;o++){let i=this.bufs[o],a=s,c=a+i.byteLength;if(s=c,t>=c)continue;let f=t>=a&&t<c,u=r>a&&r<=c;if(f&&u){if(t===a&&r===c){n.push(i);break}let l=t-a;n.push(i.subarray(l,l+(r-t)));break}if(f){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(u){if(r===c){n.push(i);break}n.push(i.subarray(0,r-a));break}n.push(i)}return{bufs:n,length:r-t}}indexOf(t,r=0){if(!Dn(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(r=Number(r??0),isNaN(r)&&(r=0),r<0&&(r=this.length+r),r<0&&(r=0),t.length===0)return r>this.length?this.length:r;let s=n.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let o=256,i=new Int32Array(o);for(let l=0;l<o;l++)i[l]=-1;for(let l=0;l<s;l++)i[n[l]]=l;let a=i,c=this.byteLength-n.byteLength,f=n.byteLength-1,u;for(let l=r;l<=c;l+=u){u=0;for(let h=f;h>=0;h--){let d=this.get(l+h);if(n[h]!==d){u=Math.max(1,h-a[d]);break}}if(u===0)return l}return-1}getInt8(t){let r=this.subarray(t,t+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt8(0)}setInt8(t,r){let n=gt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,r),this.write(n,t)}getInt16(t,r){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,r)}setInt16(t,r,n){let s=ht(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,r,n),this.write(s,t)}getInt32(t,r){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,r)}setInt32(t,r,n){let s=ht(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,r,n),this.write(s,t)}getBigInt64(t,r){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,r)}setBigInt64(t,r,n){let s=ht(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,r,n),this.write(s,t)}getUint8(t){let r=this.subarray(t,t+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint8(0)}setUint8(t,r){let n=gt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,r),this.write(n,t)}getUint16(t,r){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,r)}setUint16(t,r,n){let s=ht(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,r,n),this.write(s,t)}getUint32(t,r){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,r)}setUint32(t,r,n){let s=ht(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,r,n),this.write(s,t)}getBigUint64(t,r){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,r)}setBigUint64(t,r,n){let s=ht(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,r,n),this.write(s,t)}getFloat32(t,r){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,r)}setFloat32(t,r,n){let s=ht(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,r,n),this.write(s,t)}getFloat64(t,r){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,r)}setFloat64(t,r,n){let s=ht(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,r,n),this.write(s,t)}equals(t){if(t==null||!(t instanceof e)||t.bufs.length!==this.bufs.length)return!1;for(let r=0;r<this.bufs.length;r++)if(!lt(this.bufs[r],t.bufs[r]))return!1;return!0}static fromUint8Arrays(t,r){let n=new e;return n.bufs=t,r==null&&(r=t.reduce((s,o)=>s+o.byteLength,0)),n.length=r,n}};var $s={};It($s,{base10:()=>_l});var _l=de({prefix:"9",name:"base10",alphabet:"0123456789"});var Gs={};It(Gs,{base16:()=>Il,base16upper:()=>Cl});var Il=at({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Cl=at({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var js={};It(js,{base2:()=>Ll});var Ll=at({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Zs={};It(Zs,{base256emoji:()=>Ol});var ja=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}"),Tl=ja.reduce((e,t,r)=>(e[r]=t,e),[]),Dl=ja.reduce((e,t,r)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return e[n]=r,e},[]);function Pl(e){return e.reduce((t,r)=>(t+=Tl[r],t),"")}function Rl(e){let t=[];for(let r of e){let n=r.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${r}`);let s=Dl[n];if(s==null)throw new Error(`Non-base256emoji character: ${r}`);t.push(s)}return new Uint8Array(t)}var Ol=sr({prefix:"\u{1F680}",name:"base256emoji",encode:Pl,decode:Rl});var Xs={};It(Xs,{base64:()=>Ul,base64pad:()=>Kl,base64url:()=>Ys,base64urlpad:()=>Nl});var Ul=at({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Kl=at({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ys=at({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Nl=at({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Qs={};It(Qs,{base8:()=>Ml});var Ml=at({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Js={};It(Js,{identity:()=>kl});var kl=sr({prefix:"\0",name:"identity",encode:e=>Oa(e),decode:e=>Ra(e)});var r0=new TextEncoder,n0=new TextDecoder;var ro={};It(ro,{sha256:()=>zr,sha512:()=>zl});var ql=20;function eo({name:e,code:t,encode:r,minDigestLength:n,maxDigestLength:s}){return new to(e,t,r,n,s)}var to=class{name;code;encode;minDigestLength;maxDigestLength;constructor(t,r,n,s,o){this.name=t,this.code=r,this.encode=n,this.minDigestLength=s??ql,this.maxDigestLength=o}digest(t,r){if(r?.truncate!=null){if(r.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&r.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(t instanceof Uint8Array){let n=this.encode(t);return n instanceof Uint8Array?Za(n,this.code,r?.truncate):n.then(s=>Za(s,this.code,r?.truncate))}else throw Error("Unknown type, must be binary type")}};function Za(e,t,r){if(r!=null&&r!==e.byteLength){if(r>e.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${e.byteLength}`);e=e.subarray(0,r)}return Mt(t,e)}function Xa(e){return async t=>new Uint8Array(await crypto.subtle.digest(e,t))}var zr=eo({name:"sha2-256",code:18,encode:Xa("SHA-256")}),zl=eo({name:"sha2-512",code:19,encode:Xa("SHA-512")});var De={...Js,...js,...Qs,...$s,...Gs,...Hs,...Vs,...ks,...Xs,...Zs},m0={...ro,...Ws};function Ja(e,t,r,n){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:r},decoder:{decode:n}}}var Qa=Ja("utf8","u",e=>"u"+new TextDecoder("utf8").decode(e),e=>new TextEncoder().encode(e.substring(1))),no=Ja("ascii","a",e=>{let t="a";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return t},e=>{e=e.substring(1);let t=gt(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}),Fl={utf8:Qa,"utf-8":Qa,hex:De.base16,latin1:no,ascii:no,binary:no,...De},Pn=Fl;function Z(e,t="utf8"){let r=Pn[t];if(r==null)throw new Error(`Unsupported encoding "${t}"`);return r.decoder.decode(`${r.prefix}${e}`)}function q(e,t="utf8"){let r=Pn[t];if(r==null)throw new Error(`Unsupported encoding "${t}"`);return r.encoder.encode(e).substring(1)}var Wl=parseInt("11111",2),so=parseInt("10000000",2),$l=parseInt("01111111",2),tc={0:Fr,1:Fr,2:Gl,3:Yl,4:Xl,5:Zl,6:jl,16:Fr,22:Fr,48:Fr};function Zt(e,t={offset:0}){let r=e[t.offset]&Wl;if(t.offset++,tc[r]!=null)return tc[r](e,t);throw new Error("No decoder for tag "+r)}function Wr(e,t){let r=0;if((e[t.offset]&so)===so){let n=e[t.offset]&$l,s="0x";t.offset++;for(let o=0;o<n;o++,t.offset++)s+=e[t.offset].toString(16).padStart(2,"0");r=parseInt(s,16)}else r=e[t.offset],t.offset++;return r}function Fr(e,t){Wr(e,t);let r=[];for(;!(t.offset>=e.byteLength);){let n=Zt(e,t);if(n===null)break;r.push(n)}return r}function Gl(e,t){let r=Wr(e,t),n=t.offset,s=t.offset+r,o=[];for(let i=n;i<s;i++)i===n&&e[i]===0||o.push(e[i]);return t.offset+=r,Uint8Array.from(o)}function jl(e,t){let r=Wr(e,t),n=t.offset+r,s=e[t.offset];t.offset++;let o=0,i=0;s<40?(o=0,i=s):s<80?(o=1,i=s-40):(o=2,i=s-80);let a=`${o}.${i}`,c=[];for(;t.offset<n;){let f=e[t.offset];if(t.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 Zl(e,t){return t.offset++,null}function Yl(e,t){let r=Wr(e,t),n=e[t.offset];t.offset++;let s=e.subarray(t.offset,t.offset+r-1);if(t.offset+=r,n!==0)throw new Error("Unused bits in bit string is unimplemented");return s}function Xl(e,t){let r=Wr(e,t),n=e.subarray(t.offset,t.offset+r);return t.offset+=r,n}function Ql(e){let t=e.toString(16);t.length%2===1&&(t="0"+t);let r=new j;for(let n=0;n<t.length;n+=2)r.append(Uint8Array.from([parseInt(`${t[n]}${t[n+1]}`,16)]));return r}function oo(e){if(e.byteLength<128)return Uint8Array.from([e.byteLength]);let t=Ql(e.byteLength);return new j(Uint8Array.from([t.byteLength|so]),t)}function Tt(e){let t=new j,r=128;return(e.subarray()[0]&r)===r&&t.append(Uint8Array.from([0])),t.append(e),new j(Uint8Array.from([2]),oo(t),t)}function Rn(e){let t=Uint8Array.from([0]),r=new j(t,e);return new j(Uint8Array.from([3]),oo(r),r)}function me(e,t=48){let r=new j;for(let n of e)r.append(n);return new j(Uint8Array.from([t]),oo(r),r)}async function ec(e,t,r,n){let s=await crypto.subtle.importKey("jwk",e,{name:"ECDSA",namedCurve:e.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let o=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},s,t,r.subarray());return n?.signal?.throwIfAborted(),o}var Jl=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),th=Uint8Array.from([6,5,43,129,4,0,34]),eh=Uint8Array.from([6,5,43,129,4,0,35]),rh={ext:!0,kty:"EC",crv:"P-256"},nh={ext:!0,kty:"EC",crv:"P-384"},sh={ext:!0,kty:"EC",crv:"P-521"},io=32,ao=48,co=66;function uo(e){let t=Zt(e);return rc(t)}function rc(e){let t=e[1][1][0],r=1,n,s;if(t.byteLength===io*2+1)return n=q(t.subarray(r,r+io),"base64url"),s=q(t.subarray(r+io),"base64url"),new cr({...rh,key_ops:["verify"],x:n,y:s});if(t.byteLength===ao*2+1)return n=q(t.subarray(r,r+ao),"base64url"),s=q(t.subarray(r+ao),"base64url"),new cr({...nh,key_ops:["verify"],x:n,y:s});if(t.byteLength===co*2+1)return n=q(t.subarray(r,r+co),"base64url"),s=q(t.subarray(r+co),"base64url"),new cr({...sh,key_ops:["verify"],x:n,y:s});throw new et(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function nc(e){return me([Tt(Uint8Array.from([1])),me([oh(e.crv)],160),me([Rn(new j(Uint8Array.from([4]),Z(e.x??"","base64url"),Z(e.y??"","base64url")))],161)]).subarray()}function oh(e){if(e==="P-256")return Jl;if(e==="P-384")return th;if(e==="P-521")return eh;throw new et(`Invalid curve ${e}`)}var cr=class{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=nc(this.jwk)),this._raw}toMultihash(){return kt.digest(ye(this))}toCID(){return ft.createV1(114,this.toMultihash())}toString(){return ct.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:lt(this.raw,t.raw)}async verify(t,r,n){return ec(this.jwk,r,t,n)}};var Pe=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Xt(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Re(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Et(e,...t){if(!Xt(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function Oe(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Re(e.outputLen),Re(e.blockLen)}function fr(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function oc(e,t){Et(e);let r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function Ht(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function On(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Vt(e,t){return e<<32-t|e>>>t}var ic=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",ih=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Ut(e){if(Et(e),ic)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=ih[e[r]];return t}var Yt={_0:48,_9:57,A:65,F:70,a:97,f:102};function sc(e){if(e>=Yt._0&&e<=Yt._9)return e-Yt._0;if(e>=Yt.A&&e<=Yt.F)return e-(Yt.A-10);if(e>=Yt.a&&e<=Yt.f)return e-(Yt.a-10)}function Ue(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(ic)return Uint8Array.fromHex(e);let t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let s=0,o=0;s<r;s++,o+=2){let i=sc(e.charCodeAt(o)),a=sc(e.charCodeAt(o+1));if(i===void 0||a===void 0){let c=e[o]+e[o+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+o)}n[s]=i*16+a}return n}function fo(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function ge(e){return typeof e=="string"&&(e=fo(e)),Et(e),e}function Ct(...e){let t=0;for(let n=0;n<e.length;n++){let s=e[n];Et(s),t+=s.length}let r=new Uint8Array(t);for(let n=0,s=0;n<e.length;n++){let o=e[n];r.set(o,s),s+=o.length}return r}var ur=class{};function lo(e){let t=n=>e().update(ge(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function be(e=32){if(Pe&&typeof Pe.getRandomValues=="function")return Pe.getRandomValues(new Uint8Array(e));if(Pe&&typeof Pe.randomBytes=="function")return Uint8Array.from(Pe.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function ah(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);let s=BigInt(32),o=BigInt(4294967295),i=Number(r>>s&o),a=Number(r&o),c=n?4:0,f=n?0:4;e.setUint32(t+c,i,n),e.setUint32(t+f,a,n)}function ac(e,t,r){return e&t^~e&r}function cc(e,t,r){return e&t^e&r^t&r}var $r=class extends ur{constructor(t,r,n,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(t),this.view=On(this.buffer)}update(t){fr(this),t=ge(t),Et(t);let{view:r,buffer:n,blockLen:s}=this,o=t.length;for(let i=0;i<o;){let a=Math.min(s-this.pos,o-i);if(a===s){let c=On(t);for(;s<=o-i;i+=s)this.process(c,i);continue}n.set(t.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===s&&(this.process(r,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){fr(this),oc(t,this),this.finished=!0;let{buffer:r,view:n,blockLen:s,isLE:o}=this,{pos:i}=this;r[i++]=128,Ht(this.buffer.subarray(i)),this.padOffset>s-i&&(this.process(n,0),i=0);for(let l=i;l<s;l++)r[l]=0;ah(n,s-8,BigInt(this.length*8),o),this.process(n,0);let a=On(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should 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],o)}digest(){let{buffer:t,outputLen:r}=this;this.digestInto(t);let n=t.slice(0,r);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:r,buffer:n,length:s,finished:o,destroyed:i,pos:a}=this;return t.destroyed=i,t.finished=o,t.length=s,t.pos=a,s%r&&t.buffer.set(n),t}clone(){return this._cloneInto()}},Qt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var bt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Un=BigInt(4294967295),uc=BigInt(32);function ch(e,t=!1){return t?{h:Number(e&Un),l:Number(e>>uc&Un)}:{h:Number(e>>uc&Un)|0,l:Number(e&Un)|0}}function fc(e,t=!1){let r=e.length,n=new Uint32Array(r),s=new Uint32Array(r);for(let o=0;o<r;o++){let{h:i,l:a}=ch(e[o],t);[n[o],s[o]]=[i,a]}return[n,s]}var ho=(e,t,r)=>e>>>r,po=(e,t,r)=>e<<32-r|t>>>r,Ke=(e,t,r)=>e>>>r|t<<32-r,Ne=(e,t,r)=>e<<32-r|t>>>r,Gr=(e,t,r)=>e<<64-r|t>>>r-32,jr=(e,t,r)=>e>>>r-32|t<<64-r;function zt(e,t,r,n){let s=(t>>>0)+(n>>>0);return{h:e+r+(s/2**32|0)|0,l:s|0}}var lc=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),hc=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,dc=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),pc=(e,t,r,n,s)=>t+r+n+s+(e/2**32|0)|0,mc=(e,t,r,n,s)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(s>>>0),yc=(e,t,r,n,s,o)=>t+r+n+s+o+(e/2**32|0)|0;var fh=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),xe=new Uint32Array(64),Kn=class extends $r{constructor(t=32){super(64,t,8,!1),this.A=Qt[0]|0,this.B=Qt[1]|0,this.C=Qt[2]|0,this.D=Qt[3]|0,this.E=Qt[4]|0,this.F=Qt[5]|0,this.G=Qt[6]|0,this.H=Qt[7]|0}get(){let{A:t,B:r,C:n,D:s,E:o,F:i,G:a,H:c}=this;return[t,r,n,s,o,i,a,c]}set(t,r,n,s,o,i,a,c){this.A=t|0,this.B=r|0,this.C=n|0,this.D=s|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,r){for(let l=0;l<16;l++,r+=4)xe[l]=t.getUint32(r,!1);for(let l=16;l<64;l++){let h=xe[l-15],d=xe[l-2],p=Vt(h,7)^Vt(h,18)^h>>>3,w=Vt(d,17)^Vt(d,19)^d>>>10;xe[l]=w+xe[l-7]+p+xe[l-16]|0}let{A:n,B:s,C:o,D:i,E:a,F:c,G:f,H:u}=this;for(let l=0;l<64;l++){let h=Vt(a,6)^Vt(a,11)^Vt(a,25),d=u+h+ac(a,c,f)+fh[l]+xe[l]|0,w=(Vt(n,2)^Vt(n,13)^Vt(n,22))+cc(n,s,o)|0;u=f,f=c,c=a,a=i+d|0,i=o,o=s,s=n,n=d+w|0}n=n+this.A|0,s=s+this.B|0,o=o+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,s,o,i,a,c,f,u)}roundClean(){Ht(xe)}destroy(){this.set(0,0,0,0,0,0,0,0),Ht(this.buffer)}};var gc=fc(["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(e=>BigInt(e))),lh=gc[0],hh=gc[1],we=new Uint32Array(80),Ee=new Uint32Array(80),mo=class extends $r{constructor(t=64){super(128,t,16,!1),this.Ah=bt[0]|0,this.Al=bt[1]|0,this.Bh=bt[2]|0,this.Bl=bt[3]|0,this.Ch=bt[4]|0,this.Cl=bt[5]|0,this.Dh=bt[6]|0,this.Dl=bt[7]|0,this.Eh=bt[8]|0,this.El=bt[9]|0,this.Fh=bt[10]|0,this.Fl=bt[11]|0,this.Gh=bt[12]|0,this.Gl=bt[13]|0,this.Hh=bt[14]|0,this.Hl=bt[15]|0}get(){let{Ah:t,Al:r,Bh:n,Bl:s,Ch:o,Cl:i,Dh:a,Dl:c,Eh:f,El:u,Fh:l,Fl:h,Gh:d,Gl:p,Hh:w,Hl:g}=this;return[t,r,n,s,o,i,a,c,f,u,l,h,d,p,w,g]}set(t,r,n,s,o,i,a,c,f,u,l,h,d,p,w,g){this.Ah=t|0,this.Al=r|0,this.Bh=n|0,this.Bl=s|0,this.Ch=o|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=h|0,this.Gh=d|0,this.Gl=p|0,this.Hh=w|0,this.Hl=g|0}process(t,r){for(let E=0;E<16;E++,r+=4)we[E]=t.getUint32(r),Ee[E]=t.getUint32(r+=4);for(let E=16;E<80;E++){let P=we[E-15]|0,N=Ee[E-15]|0,k=Ke(P,N,1)^Ke(P,N,8)^ho(P,N,7),M=Ne(P,N,1)^Ne(P,N,8)^po(P,N,7),U=we[E-2]|0,S=Ee[E-2]|0,L=Ke(U,S,19)^Gr(U,S,61)^ho(U,S,6),R=Ne(U,S,19)^jr(U,S,61)^po(U,S,6),T=dc(M,R,Ee[E-7],Ee[E-16]),m=pc(T,k,L,we[E-7],we[E-16]);we[E]=m|0,Ee[E]=T|0}let{Ah:n,Al:s,Bh:o,Bl:i,Ch:a,Cl:c,Dh:f,Dl:u,Eh:l,El:h,Fh:d,Fl:p,Gh:w,Gl:g,Hh:x,Hl:B}=this;for(let E=0;E<80;E++){let P=Ke(l,h,14)^Ke(l,h,18)^Gr(l,h,41),N=Ne(l,h,14)^Ne(l,h,18)^jr(l,h,41),k=l&d^~l&w,M=h&p^~h&g,U=mc(B,N,M,hh[E],Ee[E]),S=yc(U,x,P,k,lh[E],we[E]),L=U|0,R=Ke(n,s,28)^Gr(n,s,34)^Gr(n,s,39),T=Ne(n,s,28)^jr(n,s,34)^jr(n,s,39),m=n&o^n&a^o&a,y=s&i^s&c^i&c;x=w|0,B=g|0,w=d|0,g=p|0,d=l|0,p=h|0,{h:l,l:h}=zt(f|0,u|0,S|0,L|0),f=a|0,u=c|0,a=o|0,c=i|0,o=n|0,i=s|0;let b=lc(L,T,y);n=hc(b,S,R,m),s=b|0}({h:n,l:s}=zt(this.Ah|0,this.Al|0,n|0,s|0)),{h:o,l:i}=zt(this.Bh|0,this.Bl|0,o|0,i|0),{h:a,l:c}=zt(this.Ch|0,this.Cl|0,a|0,c|0),{h:f,l:u}=zt(this.Dh|0,this.Dl|0,f|0,u|0),{h:l,l:h}=zt(this.Eh|0,this.El|0,l|0,h|0),{h:d,l:p}=zt(this.Fh|0,this.Fl|0,d|0,p|0),{h:w,l:g}=zt(this.Gh|0,this.Gl|0,w|0,g|0),{h:x,l:B}=zt(this.Hh|0,this.Hl|0,x|0,B|0),this.set(n,s,o,i,a,c,f,u,l,h,d,p,w,g,x,B)}roundClean(){Ht(we,Ee)}destroy(){Ht(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var Se=lo(()=>new Kn);var bc=lo(()=>new mo);var bo=BigInt(0),go=BigInt(1);function Jt(e,t=""){if(typeof e!="boolean"){let r=t&&`"${t}"`;throw new Error(r+"expected boolean, got type="+typeof e)}return e}function Dt(e,t,r=""){let n=Xt(e),s=e?.length,o=t!==void 0;if(!n||o&&s!==t){let i=r&&`"${r}" `,a=o?` of length ${t}`:"",c=n?`length=${s}`:`type=${typeof e}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return e}function Zr(e){let t=e.toString(16);return t.length&1?"0"+t:t}function xc(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?bo:BigInt("0x"+e)}function lr(e){return xc(Ut(e))}function Kt(e){return Et(e),xc(Ut(Uint8Array.from(e).reverse()))}function Nn(e,t){return Ue(e.toString(16).padStart(t*2,"0"))}function Yr(e,t){return Nn(e,t).reverse()}function Y(e,t,r){let n;if(typeof t=="string")try{n=Ue(t)}catch(o){throw new Error(e+" must be hex string or Uint8Array, cause: "+o)}else if(Xt(t))n=Uint8Array.from(t);else throw new Error(e+" must be hex string or Uint8Array");let s=n.length;if(typeof r=="number"&&s!==r)throw new Error(e+" of length "+r+" expected, got "+s);return n}function wc(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return r===0}function xo(e){return Uint8Array.from(e)}var yo=e=>typeof e=="bigint"&&bo<=e;function Ec(e,t,r){return yo(e)&&yo(t)&&yo(r)&&t<=e&&e<r}function ve(e,t,r,n){if(!Ec(t,r,n))throw new Error("expected valid "+e+": "+r+" <= n < "+n+", got "+t)}function Mn(e){let t;for(t=0;e>bo;e>>=go,t+=1);return t}var Ae=e=>(go<<BigInt(e))-go;function Sc(e,t,r){if(typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");let n=d=>new Uint8Array(d),s=d=>Uint8Array.of(d),o=n(e),i=n(e),a=0,c=()=>{o.fill(1),i.fill(0),a=0},f=(...d)=>r(i,o,...d),u=(d=n(0))=>{i=f(s(0),d),o=f(),d.length!==0&&(i=f(s(1),d),o=f())},l=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let d=0,p=[];for(;d<t;){o=f();let w=o.slice();p.push(w),d+=o.length}return Ct(...p)};return(d,p)=>{c(),u(d);let w;for(;!(w=p(l()));)u();return c(),w}}function Ft(e,t,r={}){if(!e||typeof e!="object")throw new Error("expected valid options object");function n(s,o,i){let a=e[s];if(i&&a===void 0)return;let c=typeof a;if(c!==o||a===null)throw new Error(`param "${s}" is invalid: expected ${o}, got ${c}`)}Object.entries(t).forEach(([s,o])=>n(s,o,!1)),Object.entries(r).forEach(([s,o])=>n(s,o,!0))}var wo=()=>{throw new Error("not implemented")};function hr(e){let t=new WeakMap;return(r,...n)=>{let s=t.get(r);if(s!==void 0)return s;let o=e(r,...n);return t.set(r,o),o}}var Lt=BigInt(0),pt=BigInt(1),Me=BigInt(2),Bc=BigInt(3),_c=BigInt(4),Ic=BigInt(5),dh=BigInt(7),Cc=BigInt(8),ph=BigInt(9),Lc=BigInt(16);function rt(e,t){let r=e%t;return r>=Lt?r:t+r}function nt(e,t,r){let n=e;for(;t-- >Lt;)n*=n,n%=r;return n}function vc(e,t){if(e===Lt)throw new Error("invert: expected non-zero number");if(t<=Lt)throw new Error("invert: expected positive modulus, got "+t);let r=rt(e,t),n=t,s=Lt,o=pt,i=pt,a=Lt;for(;r!==Lt;){let f=n/r,u=n%r,l=s-i*f,h=o-a*f;n=r,r=u,s=i,o=a,i=l,a=h}if(n!==pt)throw new Error("invert: does not exist");return rt(s,t)}function Eo(e,t,r){if(!e.eql(e.sqr(t),r))throw new Error("Cannot find square root")}function Tc(e,t){let r=(e.ORDER+pt)/_c,n=e.pow(t,r);return Eo(e,n,t),n}function mh(e,t){let r=(e.ORDER-Ic)/Cc,n=e.mul(t,Me),s=e.pow(n,r),o=e.mul(t,s),i=e.mul(e.mul(o,Me),s),a=e.mul(o,e.sub(i,e.ONE));return Eo(e,a,t),a}function yh(e){let t=Pt(e),r=Dc(e),n=r(t,t.neg(t.ONE)),s=r(t,n),o=r(t,t.neg(n)),i=(e+dh)/Lc;return(a,c)=>{let f=a.pow(c,i),u=a.mul(f,n),l=a.mul(f,s),h=a.mul(f,o),d=a.eql(a.sqr(u),c),p=a.eql(a.sqr(l),c);f=a.cmov(f,u,d),u=a.cmov(h,l,p);let w=a.eql(a.sqr(u),c),g=a.cmov(f,u,w);return Eo(a,g,c),g}}function Dc(e){if(e<Bc)throw new Error("sqrt is not defined for small field");let t=e-pt,r=0;for(;t%Me===Lt;)t/=Me,r++;let n=Me,s=Pt(e);for(;Ac(s,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return Tc;let o=s.pow(n,t),i=(t+pt)/Me;return function(c,f){if(c.is0(f))return f;if(Ac(c,f)!==1)throw new Error("Cannot find square root");let u=r,l=c.mul(c.ONE,o),h=c.pow(f,t),d=c.pow(f,i);for(;!c.eql(h,c.ONE);){if(c.is0(h))return c.ZERO;let p=1,w=c.sqr(h);for(;!c.eql(w,c.ONE);)if(p++,w=c.sqr(w),p===u)throw new Error("Cannot find square root");let g=pt<<BigInt(u-p-1),x=c.pow(l,g);u=p,l=c.sqr(x),h=c.mul(h,l),d=c.mul(d,x)}return d}}function gh(e){return e%_c===Bc?Tc:e%Cc===Ic?mh:e%Lc===ph?yh(e):Dc(e)}var te=(e,t)=>(rt(e,t)&pt)===pt,bh=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function So(e){let t={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},r=bh.reduce((n,s)=>(n[s]="function",n),t);return Ft(e,r),e}function xh(e,t,r){if(r<Lt)throw new Error("invalid exponent, negatives unsupported");if(r===Lt)return e.ONE;if(r===pt)return t;let n=e.ONE,s=t;for(;r>Lt;)r&pt&&(n=e.mul(n,s)),s=e.sqr(s),r>>=pt;return n}function Xr(e,t,r=!1){let n=new Array(t.length).fill(r?e.ZERO:void 0),s=t.reduce((i,a,c)=>e.is0(a)?i:(n[c]=i,e.mul(i,a)),e.ONE),o=e.inv(s);return t.reduceRight((i,a,c)=>e.is0(a)?i:(n[c]=e.mul(i,n[c]),e.mul(i,a)),o),n}function Ac(e,t){let r=(e.ORDER-pt)/Me,n=e.pow(t,r),s=e.eql(n,e.ONE),o=e.eql(n,e.ZERO),i=e.eql(n,e.neg(e.ONE));if(!s&&!o&&!i)throw new Error("invalid Legendre symbol result");return s?1:o?0:-1}function kn(e,t){t!==void 0&&Re(t);let r=t!==void 0?t:e.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function Pt(e,t,r=!1,n={}){if(e<=Lt)throw new Error("invalid field: expected ORDER > 0, got "+e);let s,o,i=!1,a;if(typeof t=="object"&&t!=null){if(n.sqrt||r)throw new Error("cannot specify opts in two arguments");let h=t;h.BITS&&(s=h.BITS),h.sqrt&&(o=h.sqrt),typeof h.isLE=="boolean"&&(r=h.isLE),typeof h.modFromBytes=="boolean"&&(i=h.modFromBytes),a=h.allowedLengths}else typeof t=="number"&&(s=t),n.sqrt&&(o=n.sqrt);let{nBitLength:c,nByteLength:f}=kn(e,s);if(f>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let u,l=Object.freeze({ORDER:e,isLE:r,BITS:c,BYTES:f,MASK:Ae(c),ZERO:Lt,ONE:pt,allowedLengths:a,create:h=>rt(h,e),isValid:h=>{if(typeof h!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof h);return Lt<=h&&h<e},is0:h=>h===Lt,isValidNot0:h=>!l.is0(h)&&l.isValid(h),isOdd:h=>(h&pt)===pt,neg:h=>rt(-h,e),eql:(h,d)=>h===d,sqr:h=>rt(h*h,e),add:(h,d)=>rt(h+d,e),sub:(h,d)=>rt(h-d,e),mul:(h,d)=>rt(h*d,e),pow:(h,d)=>xh(l,h,d),div:(h,d)=>rt(h*vc(d,e),e),sqrN:h=>h*h,addN:(h,d)=>h+d,subN:(h,d)=>h-d,mulN:(h,d)=>h*d,inv:h=>vc(h,e),sqrt:o||(h=>(u||(u=gh(e)),u(l,h))),toBytes:h=>r?Yr(h,f):Nn(h,f),fromBytes:(h,d=!0)=>{if(a){if(!a.includes(h.length)||h.length>f)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+h.length);let w=new Uint8Array(f);w.set(h,r?0:w.length-h.length),h=w}if(h.length!==f)throw new Error("Field.fromBytes: expected "+f+" bytes, got "+h.length);let p=r?Kt(h):lr(h);if(i&&(p=rt(p,e)),!d&&!l.isValid(p))throw new Error("invalid field element: outside of range 0..ORDER");return p},invertBatch:h=>Xr(l,h),cmov:(h,d,p)=>p?d:h});return Object.freeze(l)}function Pc(e){if(typeof e!="bigint")throw new Error("field order must be bigint");let t=e.toString(2).length;return Math.ceil(t/8)}function vo(e){let t=Pc(e);return t+Math.ceil(t/2)}function Ao(e,t,r=!1){let n=e.length,s=Pc(t),o=vo(t);if(n<16||n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);let i=r?Kt(e):lr(e),a=rt(i,t-pt)+pt;return r?Yr(a,s):Nn(a,s)}var dr=BigInt(0),ke=BigInt(1);function Qr(e,t){let r=t.negate();return e?r:t}function ee(e,t){let r=Xr(e.Fp,t.map(n=>n.Z));return t.map((n,s)=>e.fromAffine(n.toAffine(r[s])))}function Kc(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function Bo(e,t){Kc(e,t);let r=Math.ceil(t/e)+1,n=2**(e-1),s=2**e,o=Ae(e),i=BigInt(e);return{windows:r,windowSize:n,mask:o,maxNumber:s,shiftBy:i}}function Rc(e,t,r){let{windowSize:n,mask:s,maxNumber:o,shiftBy:i}=r,a=Number(e&s),c=e>>i;a>n&&(a-=o,c+=ke);let f=t*n,u=f+Math.abs(a)-1,l=a===0,h=a<0,d=t%2!==0;return{nextN:c,offset:u,isZero:l,isNeg:h,isNegF:d,offsetF:f}}function wh(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((r,n)=>{if(!(r instanceof t))throw new Error("invalid point at index "+n)})}function Eh(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((r,n)=>{if(!t.isValid(r))throw new Error("invalid scalar at index "+n)})}var _o=new WeakMap,Nc=new WeakMap;function Io(e){return Nc.get(e)||1}function Oc(e){if(e!==dr)throw new Error("invalid wNAF")}var pr=class{constructor(t,r){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=r}_unsafeLadder(t,r,n=this.ZERO){let s=t;for(;r>dr;)r&ke&&(n=n.add(s)),s=s.double(),r>>=ke;return n}precomputeWindow(t,r){let{windows:n,windowSize:s}=Bo(r,this.bits),o=[],i=t,a=i;for(let c=0;c<n;c++){a=i,o.push(a);for(let f=1;f<s;f++)a=a.add(i),o.push(a);i=a.double()}return o}wNAF(t,r,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let s=this.ZERO,o=this.BASE,i=Bo(t,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:f,isZero:u,isNeg:l,isNegF:h,offsetF:d}=Rc(n,a,i);n=c,u?o=o.add(Qr(h,r[d])):s=s.add(Qr(l,r[f]))}return Oc(n),{p:s,f:o}}wNAFUnsafe(t,r,n,s=this.ZERO){let o=Bo(t,this.bits);for(let i=0;i<o.windows&&n!==dr;i++){let{nextN:a,offset:c,isZero:f,isNeg:u}=Rc(n,i,o);if(n=a,!f){let l=r[c];s=s.add(u?l.negate():l)}}return Oc(n),s}getPrecomputes(t,r,n){let s=_o.get(r);return s||(s=this.precomputeWindow(r,t),t!==1&&(typeof n=="function"&&(s=n(s)),_o.set(r,s))),s}cached(t,r,n){let s=Io(t);return this.wNAF(s,this.getPrecomputes(s,t,n),r)}unsafe(t,r,n,s){let o=Io(t);return o===1?this._unsafeLadder(t,r,s):this.wNAFUnsafe(o,this.getPrecomputes(o,t,n),r,s)}createCache(t,r){Kc(r,this.bits),Nc.set(t,r),_o.delete(t)}hasCache(t){return Io(t)!==1}};function Mc(e,t,r,n){let s=t,o=e.ZERO,i=e.ZERO;for(;r>dr||n>dr;)r&ke&&(o=o.add(s)),n&ke&&(i=i.add(s)),s=s.double(),r>>=ke,n>>=ke;return{p1:o,p2:i}}function mr(e,t,r,n){wh(r,e),Eh(n,t);let s=r.length,o=n.length;if(s!==o)throw new Error("arrays of points and scalars must have equal length");let i=e.ZERO,a=Mn(BigInt(s)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let f=Ae(c),u=new Array(Number(f)+1).fill(i),l=Math.floor((t.BITS-1)/c)*c,h=i;for(let d=l;d>=0;d-=c){u.fill(i);for(let w=0;w<o;w++){let g=n[w],x=Number(g>>BigInt(d)&f);u[x]=u[x].add(r[w])}let p=i;for(let w=u.length-1,g=i;w>0;w--)g=g.add(u[w]),p=p.add(g);if(h=h.add(p),d!==0)for(let w=0;w<c;w++)h=h.double()}return h}function Uc(e,t,r){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return So(t),t}else return Pt(e,{isLE:r})}function Hn(e,t,r={},n){if(n===void 0&&(n=e==="edwards"),!t||typeof t!="object")throw new Error(`expected valid ${e} CURVE object`);for(let c of["p","n","h"]){let f=t[c];if(!(typeof f=="bigint"&&f>dr))throw new Error(`CURVE.${c} must be positive bigint`)}let s=Uc(t.p,r.Fp,n),o=Uc(t.n,r.Fn,n),a=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(let c of a)if(!s.isValid(t[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:s,Fn:o}}var Be=BigInt(0),mt=BigInt(1),Co=BigInt(2),Sh=BigInt(8);function vh(e,t,r,n){let s=e.sqr(r),o=e.sqr(n),i=e.add(e.mul(t.a,s),o),a=e.add(e.ONE,e.mul(t.d,e.mul(s,o)));return e.eql(i,a)}function Ah(e,t={}){let r=Hn("edwards",e,t,t.FpFnLE),{Fp:n,Fn:s}=r,o=r.CURVE,{h:i}=o;Ft(t,{},{uvRatio:"function"});let a=Co<<BigInt(s.BYTES*8)-mt,c=g=>n.create(g),f=t.uvRatio||((g,x)=>{try{return{isValid:!0,value:n.sqrt(n.div(g,x))}}catch{return{isValid:!1,value:Be}}});if(!vh(n,o,o.Gx,o.Gy))throw new Error("bad curve params: generator point");function u(g,x,B=!1){let E=B?mt:Be;return ve("coordinate "+g,x,E,a),x}function l(g){if(!(g instanceof p))throw new Error("ExtendedPoint expected")}let h=hr((g,x)=>{let{X:B,Y:E,Z:P}=g,N=g.is0();x==null&&(x=N?Sh:n.inv(P));let k=c(B*x),M=c(E*x),U=n.mul(P,x);if(N)return{x:Be,y:mt};if(U!==mt)throw new Error("invZ was invalid");return{x:k,y:M}}),d=hr(g=>{let{a:x,d:B}=o;if(g.is0())throw new Error("bad point: ZERO");let{X:E,Y:P,Z:N,T:k}=g,M=c(E*E),U=c(P*P),S=c(N*N),L=c(S*S),R=c(M*x),T=c(S*c(R+U)),m=c(L+c(B*c(M*U)));if(T!==m)throw new Error("bad point: equation left != right (1)");let y=c(E*P),b=c(N*k);if(y!==b)throw new Error("bad point: equation left != right (2)");return!0});class p{constructor(x,B,E,P){this.X=u("x",x),this.Y=u("y",B),this.Z=u("z",E,!0),this.T=u("t",P),Object.freeze(this)}static CURVE(){return o}static fromAffine(x){if(x instanceof p)throw new Error("extended point not allowed");let{x:B,y:E}=x||{};return u("x",B),u("y",E),new p(B,E,mt,c(B*E))}static fromBytes(x,B=!1){let E=n.BYTES,{a:P,d:N}=o;x=xo(Dt(x,E,"point")),Jt(B,"zip215");let k=xo(x),M=x[E-1];k[E-1]=M&-129;let U=Kt(k),S=B?a:n.ORDER;ve("point.y",U,Be,S);let L=c(U*U),R=c(L-mt),T=c(N*L-P),{isValid:m,value:y}=f(R,T);if(!m)throw new Error("bad point: invalid y coordinate");let b=(y&mt)===mt,A=(M&128)!==0;if(!B&&y===Be&&A)throw new Error("bad point: x=0 and x_0=1");return A!==b&&(y=c(-y)),p.fromAffine({x:y,y:U})}static fromHex(x,B=!1){return p.fromBytes(Y("point",x),B)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(x=8,B=!0){return w.createCache(this,x),B||this.multiply(Co),this}assertValidity(){d(this)}equals(x){l(x);let{X:B,Y:E,Z:P}=this,{X:N,Y:k,Z:M}=x,U=c(B*M),S=c(N*P),L=c(E*M),R=c(k*P);return U===S&&L===R}is0(){return this.equals(p.ZERO)}negate(){return new p(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:x}=o,{X:B,Y:E,Z:P}=this,N=c(B*B),k=c(E*E),M=c(Co*c(P*P)),U=c(x*N),S=B+E,L=c(c(S*S)-N-k),R=U+k,T=R-M,m=U-k,y=c(L*T),b=c(R*m),A=c(L*m),_=c(T*R);return new p(y,b,_,A)}add(x){l(x);let{a:B,d:E}=o,{X:P,Y:N,Z:k,T:M}=this,{X:U,Y:S,Z:L,T:R}=x,T=c(P*U),m=c(N*S),y=c(M*E*R),b=c(k*L),A=c((P+N)*(U+S)-T-m),_=b-y,C=b+y,v=c(m-B*T),I=c(A*_),D=c(C*v),O=c(A*v),z=c(_*C);return new p(I,D,z,O)}subtract(x){return this.add(x.negate())}multiply(x){if(!s.isValidNot0(x))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:B,f:E}=w.cached(this,x,P=>ee(p,P));return ee(p,[B,E])[0]}multiplyUnsafe(x,B=p.ZERO){if(!s.isValid(x))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return x===Be?p.ZERO:this.is0()||x===mt?this:w.unsafe(this,x,E=>ee(p,E),B)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return w.unsafe(this,o.n).is0()}toAffine(x){return h(this,x)}clearCofactor(){return i===mt?this:this.multiplyUnsafe(i)}toBytes(){let{x,y:B}=this.toAffine(),E=n.toBytes(B);return E[E.length-1]|=x&mt?128:0,E}toHex(){return Ut(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(x){return ee(p,x)}static msm(x,B){return mr(p,s,x,B)}_setWindowSize(x){this.precompute(x)}toRawBytes(){return this.toBytes()}}p.BASE=new p(o.Gx,o.Gy,mt,c(o.Gx*o.Gy)),p.ZERO=new p(Be,mt,mt,Be),p.Fp=n,p.Fn=s;let w=new pr(p,s.BITS);return p.BASE.precompute(8),p}var Vn=class{constructor(t){this.ep=t}static fromBytes(t){wo()}static fromHex(t){wo()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(t){return this.ep.toAffine(t)}toHex(){return Ut(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(t){return this.assertSame(t),this.init(this.ep.add(t.ep))}subtract(t){return this.assertSame(t),this.init(this.ep.subtract(t.ep))}multiply(t){return this.init(this.ep.multiply(t))}multiplyUnsafe(t){return this.init(this.ep.multiplyUnsafe(t))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(t,r){return this.init(this.ep.precompute(t,r))}toRawBytes(){return this.toBytes()}};function Bh(e,t,r={}){if(typeof t!="function")throw new Error('"hash" function param is required');Ft(r,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=r,{BASE:s,Fp:o,Fn:i}=e,a=r.randomBytes||be,c=r.adjustScalarBytes||(S=>S),f=r.domain||((S,L,R)=>{if(Jt(R,"phflag"),L.length||R)throw new Error("Contexts/pre-hash are not supported");return S});function u(S){return i.create(Kt(S))}function l(S){let L=E.secretKey;S=Y("private key",S,L);let R=Y("hashed private key",t(S),2*L),T=c(R.slice(0,L)),m=R.slice(L,2*L),y=u(T);return{head:T,prefix:m,scalar:y}}function h(S){let{head:L,prefix:R,scalar:T}=l(S),m=s.multiply(T),y=m.toBytes();return{head:L,prefix:R,scalar:T,point:m,pointBytes:y}}function d(S){return h(S).pointBytes}function p(S=Uint8Array.of(),...L){let R=Ct(...L);return u(t(f(R,Y("context",S),!!n)))}function w(S,L,R={}){S=Y("message",S),n&&(S=n(S));let{prefix:T,scalar:m,pointBytes:y}=h(L),b=p(R.context,T,S),A=s.multiply(b).toBytes(),_=p(R.context,A,y,S),C=i.create(b+_*m);if(!i.isValid(C))throw new Error("sign failed: invalid s");let v=Ct(A,i.toBytes(C));return Dt(v,E.signature,"result")}let g={zip215:!0};function x(S,L,R,T=g){let{context:m,zip215:y}=T,b=E.signature;S=Y("signature",S,b),L=Y("message",L),R=Y("publicKey",R,E.publicKey),y!==void 0&&Jt(y,"zip215"),n&&(L=n(L));let A=b/2,_=S.subarray(0,A),C=Kt(S.subarray(A,b)),v,I,D;try{v=e.fromBytes(R,y),I=e.fromBytes(_,y),D=s.multiplyUnsafe(C)}catch{return!1}if(!y&&v.isSmallOrder())return!1;let O=p(m,I.toBytes(),v.toBytes(),L);return I.add(v.multiplyUnsafe(O)).subtract(D).clearCofactor().is0()}let B=o.BYTES,E={secretKey:B,publicKey:B,signature:2*B,seed:B};function P(S=a(E.seed)){return Dt(S,E.seed,"seed")}function N(S){let L=U.randomSecretKey(S);return{secretKey:L,publicKey:d(L)}}function k(S){return Xt(S)&&S.length===i.BYTES}function M(S,L){try{return!!e.fromBytes(S,L)}catch{return!1}}let U={getExtendedPublicKey:h,randomSecretKey:P,isValidSecretKey:k,isValidPublicKey:M,toMontgomery(S){let{y:L}=e.fromBytes(S),R=E.publicKey,T=R===32;if(!T&&R!==57)throw new Error("only defined for 25519 and 448");let m=T?o.div(mt+L,mt-L):o.div(L-mt,L+mt);return o.toBytes(m)},toMontgomerySecret(S){let L=E.secretKey;Dt(S,L);let R=t(S.subarray(0,L));return c(R).subarray(0,L)},randomPrivateKey:P,precompute(S=8,L=e.BASE){return L.precompute(S,!1)}};return Object.freeze({keygen:N,getPublicKey:d,sign:w,verify:x,utils:U,Point:e,lengths:E})}function _h(e){let t={a:e.a,d:e.d,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},r=e.Fp,n=Pt(t.n,e.nBitLength,!0),s={Fp:r,Fn:n,uvRatio:e.uvRatio},o={randomBytes:e.randomBytes,adjustScalarBytes:e.adjustScalarBytes,domain:e.domain,prehash:e.prehash,mapToCurve:e.mapToCurve};return{CURVE:t,curveOpts:s,hash:e.hash,eddsaOpts:o}}function Ih(e,t){let r=t.Point;return Object.assign({},t,{ExtendedPoint:r,CURVE:e,nBitLength:r.Fn.BITS,nByteLength:r.Fn.BYTES})}function kc(e){let{CURVE:t,curveOpts:r,hash:n,eddsaOpts:s}=_h(e),o=Ah(t,r),i=Bh(o,n,s);return Ih(e,i)}var Jr=BigInt(0),yr=BigInt(1),qn=BigInt(2);function Ch(e){return Ft(e,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...e})}function Hc(e){let t=Ch(e),{P:r,type:n,adjustScalarBytes:s,powPminus2:o,randomBytes:i}=t,a=n==="x25519";if(!a&&n!=="x448")throw new Error("invalid type");let c=i||be,f=a?255:448,u=a?32:56,l=BigInt(a?9:5),h=BigInt(a?121665:39081),d=a?qn**BigInt(254):qn**BigInt(447),p=a?BigInt(8)*qn**BigInt(251)-yr:BigInt(4)*qn**BigInt(445)-yr,w=d+p+yr,g=m=>rt(m,r),x=B(l);function B(m){return Yr(g(m),u)}function E(m){let y=Y("u coordinate",m,u);return a&&(y[31]&=127),g(Kt(y))}function P(m){return Kt(s(Y("scalar",m,u)))}function N(m,y){let b=U(E(y),P(m));if(b===Jr)throw new Error("invalid private or public key received");return B(b)}function k(m){return N(m,x)}function M(m,y,b){let A=g(m*(y-b));return y=g(y-A),b=g(b+A),{x_2:y,x_3:b}}function U(m,y){ve("u",m,Jr,r),ve("scalar",y,d,w);let b=y,A=m,_=yr,C=Jr,v=m,I=yr,D=Jr;for(let z=BigInt(f-1);z>=Jr;z--){let F=b>>z&yr;D^=F,{x_2:_,x_3:v}=M(D,_,v),{x_2:C,x_3:I}=M(D,C,I),D=F;let V=_+C,$=g(V*V),X=_-C,it=g(X*X),G=$-it,dt=v+I,Je=v-I,Ur=g(Je*V),Kr=g(dt*X),Ca=Ur+Kr,La=Ur-Kr;v=g(Ca*Ca),I=g(A*g(La*La)),_=g($*it),C=g(G*($+g(h*G)))}({x_2:_,x_3:v}=M(D,_,v)),{x_2:C,x_3:I}=M(D,C,I);let O=o(C);return g(_*O)}let S={secretKey:u,publicKey:u,seed:u},L=(m=c(u))=>(Et(m,S.seed),m);function R(m){let y=L(m);return{secretKey:y,publicKey:k(y)}}return{keygen:R,getSharedSecret:(m,y)=>N(m,y),getPublicKey:m=>k(m),scalarMult:N,scalarMultBase:k,utils:{randomSecretKey:L,randomPrivateKey:L},GuBytes:x.slice(),lengths:S}}var Lh=BigInt(0),ne=BigInt(1),Vc=BigInt(2),Th=BigInt(3),Dh=BigInt(5),Ph=BigInt(8),gr=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),tn={p:gr,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Ph,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Fc(e){let t=BigInt(10),r=BigInt(20),n=BigInt(40),s=BigInt(80),o=gr,a=e*e%o*e%o,c=nt(a,Vc,o)*a%o,f=nt(c,ne,o)*e%o,u=nt(f,Dh,o)*f%o,l=nt(u,t,o)*u%o,h=nt(l,r,o)*l%o,d=nt(h,n,o)*h%o,p=nt(d,s,o)*d%o,w=nt(p,s,o)*d%o,g=nt(w,t,o)*u%o;return{pow_p_5_8:nt(g,Vc,o)*e%o,b2:a}}function Wc(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var Lo=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Po(e,t){let r=gr,n=rt(t*t*t,r),s=rt(n*n*t,r),o=Fc(e*s).pow_p_5_8,i=rt(e*n*o,r),a=rt(t*i*i,r),c=i,f=rt(i*Lo,r),u=a===e,l=a===rt(-e,r),h=a===rt(-e*Lo,r);return u&&(i=c),(l||h)&&(i=f),te(i,r)&&(i=rt(-i,r)),{isValid:u||l,value:i}}var re=Pt(tn.p,{isLE:!0}),Rh=Pt(tn.n,{isLE:!0}),Oh={...tn,Fp:re,hash:bc,adjustScalarBytes:Wc,uvRatio:Po},se=kc(Oh);var en=(()=>{let e=re.ORDER;return Hc({P:e,type:"x25519",powPminus2:t=>{let{pow_p_5_8:r,b2:n}=Fc(t);return rt(nt(r,Th,e)*n,e)},adjustScalarBytes:Wc})})();var To=Lo,Uh=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Kh=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),Nh=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),Mh=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),qc=e=>Po(ne,e),kh=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Do=e=>se.Point.Fp.create(Kt(e)&kh);function zc(e){let{d:t}=tn,r=gr,n=x=>re.create(x),s=n(To*e*e),o=n((s+ne)*Nh),i=BigInt(-1),a=n((i-t*s)*n(s+t)),{isValid:c,value:f}=Po(o,a),u=n(f*e);te(u,r)||(u=n(-u)),c||(f=u),c||(i=s);let l=n(i*(s-ne)*Mh-a),h=f*f,d=n((f+f)*a),p=n(l*Uh),w=n(ne-h),g=n(ne+h);return new se.Point(n(d*g),n(w*p),n(p*g),n(d*w))}function Hh(e){Et(e,64);let t=Do(e.subarray(0,32)),r=zc(t),n=Do(e.subarray(32,64)),s=zc(n);return new oe(r.add(s))}var oe=class e extends Vn{constructor(t){super(t)}static fromAffine(t){return new e(se.Point.fromAffine(t))}assertSame(t){if(!(t instanceof e))throw new Error("RistrettoPoint expected")}init(t){return new e(t)}static hashToCurve(t){return Hh(Y("ristrettoHash",t,64))}static fromBytes(t){Et(t,32);let{a:r,d:n}=tn,s=gr,o=P=>re.create(P),i=Do(t);if(!wc(re.toBytes(i),t)||te(i,s))throw new Error("invalid ristretto255 encoding 1");let a=o(i*i),c=o(ne+r*a),f=o(ne-r*a),u=o(c*c),l=o(f*f),h=o(r*n*u-l),{isValid:d,value:p}=qc(o(h*l)),w=o(p*f),g=o(p*w*h),x=o((i+i)*w);te(x,s)&&(x=o(-x));let B=o(c*g),E=o(x*B);if(!d||te(E,s)||B===Lh)throw new Error("invalid ristretto255 encoding 2");return new e(new se.Point(x,B,ne,E))}static fromHex(t){return e.fromBytes(Y("ristrettoHex",t,32))}static msm(t,r){return mr(e,se.Point.Fn,t,r)}toBytes(){let{X:t,Y:r,Z:n,T:s}=this.ep,o=gr,i=g=>re.create(g),a=i(i(n+r)*i(n-r)),c=i(t*r),f=i(c*c),{value:u}=qc(i(a*f)),l=i(u*a),h=i(u*c),d=i(l*h*s),p;if(te(s*d,o)){let g=i(r*To),x=i(t*To);t=g,r=x,p=i(l*Kh)}else p=h;te(t*d,o)&&(r=i(-r));let w=i((n-r)*p);return te(w,o)&&(w=i(-w)),re.toBytes(w)}equals(t){this.assertSame(t);let{X:r,Y:n}=this.ep,{X:s,Y:o}=t.ep,i=f=>re.create(f),a=i(r*o)===i(n*s),c=i(n*o)===i(r*s);return a||c}is0(){return this.equals(e.ZERO)}};oe.BASE=new oe(se.Point.BASE);oe.ZERO=new oe(se.Point.ZERO);oe.Fp=re;oe.Fn=Rh;var rn=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},zn=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var $c={get(e=globalThis){let t=e.crypto;if(t?.subtle==null)throw new zn("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return t}};var Nt=$c;var Fn=32;var Ro,Vh=(async()=>{try{return await Nt.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function qh(e,t,r){if(e.buffer instanceof ArrayBuffer){let n=await Nt.get().subtle.importKey("raw",e.buffer,{name:"Ed25519"},!1,["verify"]);return await Nt.get().subtle.verify({name:"Ed25519"},n,t,r instanceof Uint8Array?r:r.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function zh(e,t,r){return se.verify(t,r instanceof Uint8Array?r:r.subarray(),e)}async function Gc(e,t,r){return Ro==null&&(Ro=await Vh),Ro?qh(e,t,r):zh(e,t,r)}function Wn(e){return e==null?!1:typeof e.then=="function"&&typeof e.catch=="function"&&typeof e.finally=="function"}var $n=class{type="Ed25519";raw;constructor(t){this.raw=Oo(t,Fn)}toMultihash(){return kt.digest(ye(this))}toCID(){return ft.createV1(114,this.toMultihash())}toString(){return ct.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:lt(this.raw,t.raw)}verify(t,r,n){n?.signal?.throwIfAborted();let s=Gc(this.raw,r,t);return Wn(s)?s.then(o=>(n?.signal?.throwIfAborted(),o)):s}};function Uo(e){return e=Oo(e,Fn),new $n(e)}function Oo(e,t){if(e=Uint8Array.from(e??[]),e.length!==t)throw new et(`Key must be a Uint8Array of length ${t}, got ${e.length}`);return e}var Wh=Math.pow(2,7),$h=Math.pow(2,14),Gh=Math.pow(2,21),Ko=Math.pow(2,28),No=Math.pow(2,35),Mo=Math.pow(2,42),ko=Math.pow(2,49),Q=128,St=127;function vt(e){if(e<Wh)return 1;if(e<$h)return 2;if(e<Gh)return 3;if(e<Ko)return 4;if(e<No)return 5;if(e<Mo)return 6;if(e<ko)return 7;if(Number.MAX_SAFE_INTEGER!=null&&e>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function br(e,t,r=0){switch(vt(e)){case 8:t[r++]=e&255|Q,e/=128;case 7:t[r++]=e&255|Q,e/=128;case 6:t[r++]=e&255|Q,e/=128;case 5:t[r++]=e&255|Q,e/=128;case 4:t[r++]=e&255|Q,e>>>=7;case 3:t[r++]=e&255|Q,e>>>=7;case 2:t[r++]=e&255|Q,e>>>=7;case 1:{t[r++]=e&255,e>>>=7;break}default:throw new Error("unreachable")}return t}function jh(e,t,r=0){switch(vt(e)){case 8:t.set(r++,e&255|Q),e/=128;case 7:t.set(r++,e&255|Q),e/=128;case 6:t.set(r++,e&255|Q),e/=128;case 5:t.set(r++,e&255|Q),e/=128;case 4:t.set(r++,e&255|Q),e>>>=7;case 3:t.set(r++,e&255|Q),e>>>=7;case 2:t.set(r++,e&255|Q),e>>>=7;case 1:{t.set(r++,e&255),e>>>=7;break}default:throw new Error("unreachable")}return t}function Ho(e,t){let r=e[t],n=0;if(n+=r&St,r<Q||(r=e[t+1],n+=(r&St)<<7,r<Q)||(r=e[t+2],n+=(r&St)<<14,r<Q)||(r=e[t+3],n+=(r&St)<<21,r<Q)||(r=e[t+4],n+=(r&St)*Ko,r<Q)||(r=e[t+5],n+=(r&St)*No,r<Q)||(r=e[t+6],n+=(r&St)*Mo,r<Q)||(r=e[t+7],n+=(r&St)*ko,r<Q))return n;throw new RangeError("Could not decode varint")}function Zh(e,t){let r=e.get(t),n=0;if(n+=r&St,r<Q||(r=e.get(t+1),n+=(r&St)<<7,r<Q)||(r=e.get(t+2),n+=(r&St)<<14,r<Q)||(r=e.get(t+3),n+=(r&St)<<21,r<Q)||(r=e.get(t+4),n+=(r&St)*Ko,r<Q)||(r=e.get(t+5),n+=(r&St)*No,r<Q)||(r=e.get(t+6),n+=(r&St)*Mo,r<Q)||(r=e.get(t+7),n+=(r&St)*ko,r<Q))return n;throw new RangeError("Could not decode varint")}function Zc(e,t,r=0){return t==null&&(t=gt(vt(e))),t instanceof Uint8Array?br(e,t,r):jh(e,t,r)}function He(e,t=0){return e instanceof Uint8Array?Ho(e,t):Zh(e,t)}var qo=new Float32Array([-0]),_e=new Uint8Array(qo.buffer);function Yc(e,t,r){qo[0]=e,t[r]=_e[0],t[r+1]=_e[1],t[r+2]=_e[2],t[r+3]=_e[3]}function Xc(e,t){return _e[0]=e[t],_e[1]=e[t+1],_e[2]=e[t+2],_e[3]=e[t+3],qo[0]}var zo=new Float64Array([-0]),At=new Uint8Array(zo.buffer);function Qc(e,t,r){zo[0]=e,t[r]=At[0],t[r+1]=At[1],t[r+2]=At[2],t[r+3]=At[3],t[r+4]=At[4],t[r+5]=At[5],t[r+6]=At[6],t[r+7]=At[7]}function Jc(e,t){return At[0]=e[t],At[1]=e[t+1],At[2]=e[t+2],At[3]=e[t+3],At[4]=e[t+4],At[5]=e[t+5],At[6]=e[t+6],At[7]=e[t+7],zo[0]}var Yh=BigInt(Number.MAX_SAFE_INTEGER),Xh=BigInt(Number.MIN_SAFE_INTEGER),Rt=class e{lo;hi;constructor(t,r){this.lo=t|0,this.hi=r|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let r=~this.lo+1>>>0,n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(r+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let r=~this.lo+1>>>0,n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(BigInt(r)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,r=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?r===0?t<16384?t<128?1:2:t<2097152?3:4:r<16384?r<128?5:6:r<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return Ve;if(t<Yh&&t>Xh)return this.fromNumber(Number(t));let r=t<0n;r&&(t=-t);let n=t>>32n,s=t-(n<<32n);return r&&(n=~n|0n,s=~s|0n,++s>tu&&(s=0n,++n>tu&&(n=0n))),new e(Number(s),Number(n))}static fromNumber(t){if(t===0)return Ve;let r=t<0;r&&(t=-t);let n=t>>>0,s=(t-n)/4294967296>>>0;return r&&(s=~s>>>0,n=~n>>>0,++n>4294967295&&(n=0,++s>4294967295&&(s=0))),new e(n,s)}static from(t){return typeof t=="number"?e.fromNumber(t):typeof t=="bigint"?e.fromBigInt(t):typeof t=="string"?e.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new e(t.low>>>0,t.high>>>0):Ve}},Ve=new Rt(0,0);Ve.toBigInt=function(){return 0n};Ve.zzEncode=Ve.zzDecode=function(){return this};Ve.length=function(){return 1};var tu=4294967296n;function eu(e){let t=0,r=0;for(let n=0;n<e.length;++n)r=e.charCodeAt(n),r<128?t+=1:r<2048?t+=2:(r&64512)===55296&&(e.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function ru(e,t,r){if(r-t<1)return"";let s,o=[],i=0,a;for(;t<r;)a=e[t++],a<128?o[i++]=a:a>191&&a<224?o[i++]=(a&31)<<6|e[t++]&63:a>239&&a<365?(a=((a&7)<<18|(e[t++]&63)<<12|(e[t++]&63)<<6|e[t++]&63)-65536,o[i++]=55296+(a>>10),o[i++]=56320+(a&1023)):o[i++]=(a&15)<<12|(e[t++]&63)<<6|e[t++]&63,i>8191&&((s??(s=[])).push(String.fromCharCode.apply(String,o)),i=0);return s!=null?(i>0&&s.push(String.fromCharCode.apply(String,o.slice(0,i))),s.join("")):String.fromCharCode.apply(String,o.slice(0,i))}function Fo(e,t,r){let n=r,s,o;for(let i=0;i<e.length;++i)s=e.charCodeAt(i),s<128?t[r++]=s:s<2048?(t[r++]=s>>6|192,t[r++]=s&63|128):(s&64512)===55296&&((o=e.charCodeAt(i+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++i,t[r++]=s>>18|240,t[r++]=s>>12&63|128,t[r++]=s>>6&63|128,t[r++]=s&63|128):(t[r++]=s>>12|224,t[r++]=s>>6&63|128,t[r++]=s&63|128);return r-n}function qt(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function Gn(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}var Wo=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,qt(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw qt(this,4);return Gn(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw qt(this,4);return Gn(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw qt(this,4);let t=Xc(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw qt(this,4);let t=Jc(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),r=this.pos,n=this.pos+t;if(n>this.len)throw qt(this,t);return this.pos+=t,r===n?new Uint8Array(0):this.buf.subarray(r,n)}string(){let t=this.bytes();return ru(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw qt(this,t);this.pos+=t}else do if(this.pos>=this.len)throw qt(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new Rt(0,0),r=0;if(this.len-this.pos>4){for(;r<4;++r)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;r=0}else{for(;r<3;++r){if(this.pos>=this.len)throw qt(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<r*7)>>>0,t}if(this.len-this.pos>4){for(;r<5;++r)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;r<5;++r){if(this.pos>=this.len)throw qt(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw qt(this,8);let t=Gn(this.buf,this.pos+=4),r=Gn(this.buf,this.pos+=4);return new Rt(t,r)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=Ho(this.buf,this.pos);return this.pos+=vt(t),t}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function $o(e){return new Wo(e instanceof Uint8Array?e:e.subarray())}function qe(e,t,r){let n=$o(e);return t.decode(n,void 0,r)}function Go(e){let t=e??8192,r=t>>>1,n,s=t;return function(i){if(i<1||i>r)return gt(i);s+i>t&&(n=gt(t),s=0);let a=n.subarray(s,s+=i);return(s&7)!==0&&(s=(s|7)+1),a}}var ze=class{fn;len;next;val;constructor(t,r,n){this.fn=t,this.len=r,this.next=void 0,this.val=n}};function jo(){}var Yo=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},Qh=Go();function Jh(e){return globalThis.Buffer!=null?gt(e):Qh(e)}var sn=class{len;head;tail;states;constructor(){this.len=0,this.head=new ze(jo,0,0),this.tail=this.head,this.states=null}_push(t,r,n){return this.tail=this.tail.next=new ze(t,r,n),this.len+=r,this}uint32(t){return this.len+=(this.tail=this.tail.next=new Xo((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(jn,10,Rt.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let r=Rt.fromBigInt(t);return this._push(jn,r.length(),r)}uint64Number(t){return this._push(br,vt(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let r=Rt.fromBigInt(t).zzEncode();return this._push(jn,r.length(),r)}sint64Number(t){let r=Rt.fromNumber(t).zzEncode();return this._push(jn,r.length(),r)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(Zo,1,t?1:0)}fixed32(t){return this._push(nn,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let r=Rt.fromBigInt(t);return this._push(nn,4,r.lo)._push(nn,4,r.hi)}fixed64Number(t){let r=Rt.fromNumber(t);return this._push(nn,4,r.lo)._push(nn,4,r.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(Yc,4,t)}double(t){return this._push(Qc,8,t)}bytes(t){let r=t.length>>>0;return r===0?this._push(Zo,1,0):this.uint32(r)._push(ed,r,t)}string(t){let r=eu(t);return r!==0?this.uint32(r)._push(Fo,r,t):this._push(Zo,1,0)}fork(){return this.states=new Yo(this),this.head=this.tail=new ze(jo,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 ze(jo,0,0),this.len=0),this}ldelim(){let t=this.head,r=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=r,this.len+=n),this}finish(){let t=this.head.next,r=Jh(this.len),n=0;for(;t!=null;)t.fn(t.val,r,n),n+=t.len,t=t.next;return r}};function Zo(e,t,r){t[r]=e&255}function td(e,t,r){for(;e>127;)t[r++]=e&127|128,e>>>=7;t[r]=e}var Xo=class extends ze{next;constructor(t,r){super(td,t,r),this.next=void 0}};function jn(e,t,r){for(;e.hi!==0;)t[r++]=e.lo&127|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[r++]=e.lo&127|128,e.lo=e.lo>>>7;t[r++]=e.lo}function nn(e,t,r){t[r]=e&255,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}function ed(e,t,r){t.set(e,r)}globalThis.Buffer!=null&&(sn.prototype.bytes=function(e){let t=e.length>>>0;return this.uint32(t),t>0&&this._push(rd,t,e),this},sn.prototype.string=function(e){let t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(nd,t,e),this});function rd(e,t,r){t.set(e,r)}function nd(e,t,r){e.length<40?Fo(e,t,r):t.utf8Write!=null?t.utf8Write(e,r):t.set(Z(e),r)}function Qo(){return new sn}function Fe(e,t){let r=Qo();return t.encode(e,r,{lengthDelimited:!1}),r.finish()}var xr;(function(e){e[e.VARINT=0]="VARINT",e[e.BIT64=1]="BIT64",e[e.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",e[e.START_GROUP=3]="START_GROUP",e[e.END_GROUP=4]="END_GROUP",e[e.BIT32=5]="BIT32"})(xr||(xr={}));function Zn(e,t,r,n){return{name:e,type:t,encode:r,decode:n}}function Jo(e){function t(s){if(e[s.toString()]==null)throw new Error("Invalid enum value");return e[s]}let r=function(o,i){let a=t(o);i.int32(a)},n=function(o){let i=o.int32();return t(i)};return Zn("enum",xr.VARINT,r,n)}function We(e,t){return Zn("message",xr.LENGTH_DELIMITED,e,t)}var on=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var ut;(function(e){e.RSA="RSA",e.Ed25519="Ed25519",e.secp256k1="secp256k1",e.ECDSA="ECDSA"})(ut||(ut={}));var ti;(function(e){e[e.RSA=0]="RSA",e[e.Ed25519=1]="Ed25519",e[e.secp256k1=2]="secp256k1",e[e.ECDSA=3]="ECDSA"})(ti||(ti={}));(function(e){e.codec=()=>Jo(ti)})(ut||(ut={}));var Wt;(function(e){let t;e.codec=()=>(t==null&&(t=We((r,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),r.Type!=null&&(n.uint32(8),ut.codec().encode(r.Type,n)),r.Data!=null&&(n.uint32(18),n.bytes(r.Data)),s.lengthDelimited!==!1&&n.ldelim()},(r,n,s={})=>{let o={},i=n==null?r.len:r.pos+n;for(;r.pos<i;){let a=r.uint32();switch(a>>>3){case 1:{o.Type=ut.codec().decode(r);break}case 2:{o.Data=r.bytes();break}default:{r.skipType(a&7);break}}}return o})),t),e.encode=r=>Fe(r,e.codec()),e.decode=(r,n)=>qe(r,e.codec(),n)})(Wt||(Wt={}));var ei;(function(e){let t;e.codec=()=>(t==null&&(t=We((r,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),r.Type!=null&&(n.uint32(8),ut.codec().encode(r.Type,n)),r.Data!=null&&(n.uint32(18),n.bytes(r.Data)),s.lengthDelimited!==!1&&n.ldelim()},(r,n,s={})=>{let o={},i=n==null?r.len:r.pos+n;for(;r.pos<i;){let a=r.uint32();switch(a>>>3){case 1:{o.Type=ut.codec().decode(r);break}case 2:{o.Data=r.bytes();break}default:{r.skipType(a&7);break}}}return o})),t),e.encode=r=>Fe(r,e.codec()),e.decode=(r,n)=>qe(r,e.codec(),n)})(ei||(ei={}));var cn={};It(cn,{MAX_RSA_KEY_SIZE:()=>ri,generateRSAKeyPair:()=>cu,jwkToJWKKeyPair:()=>uu,jwkToPkcs1:()=>ad,jwkToPkix:()=>ii,jwkToRSAPrivateKey:()=>fi,pkcs1MessageToJwk:()=>si,pkcs1MessageToRSAPrivateKey:()=>ai,pkcs1ToJwk:()=>id,pkcs1ToRSAPrivateKey:()=>au,pkixMessageToJwk:()=>oi,pkixMessageToRSAPublicKey:()=>ui,pkixToJwk:()=>cd,pkixToRSAPublicKey:()=>ci});var Yn=Se;var wr=class{type="RSA";jwk;_raw;_multihash;constructor(t,r){this.jwk=t,this._multihash=r}get raw(){return this._raw==null&&(this._raw=cn.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return ft.createV1(114,this._multihash)}toString(){return ct.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:lt(this.raw,t.raw)}verify(t,r,n){return iu(this.jwk,r,t,n)}},an=class{type="RSA";jwk;_raw;publicKey;constructor(t,r){this.jwk=t,this.publicKey=r}get raw(){return this._raw==null&&(this._raw=cn.jwkToPkcs1(this.jwk)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:lt(this.raw,t.raw)}sign(t,r){return ou(this.jwk,t,r)}};var ri=8192,ni=18,sd=1062,od=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function id(e){let t=Zt(e);return si(t)}function si(e){return{n:q(e[1],"base64url"),e:q(e[2],"base64url"),d:q(e[3],"base64url"),p:q(e[4],"base64url"),q:q(e[5],"base64url"),dp:q(e[6],"base64url"),dq:q(e[7],"base64url"),qi:q(e[8],"base64url"),kty:"RSA"}}function ad(e){if(e.n==null||e.e==null||e.d==null||e.p==null||e.q==null||e.dp==null||e.dq==null||e.qi==null)throw new et("JWK was missing components");return me([Tt(Uint8Array.from([0])),Tt(Z(e.n,"base64url")),Tt(Z(e.e,"base64url")),Tt(Z(e.d,"base64url")),Tt(Z(e.p,"base64url")),Tt(Z(e.q,"base64url")),Tt(Z(e.dp,"base64url")),Tt(Z(e.dq,"base64url")),Tt(Z(e.qi,"base64url"))]).subarray()}function cd(e){let t=Zt(e,{offset:0});return oi(t)}function oi(e){let t=Zt(e[1],{offset:0});return{kty:"RSA",n:q(t[0],"base64url"),e:q(t[1],"base64url")}}function ii(e){if(e.n==null||e.e==null)throw new et("JWK was missing components");return me([od,Rn(me([Tt(Z(e.n,"base64url")),Tt(Z(e.e,"base64url"))]))]).subarray()}function au(e){let t=Zt(e);return ai(t)}function ai(e){let t=si(e);return fi(t)}function ci(e,t){if(e.byteLength>=sd)throw new er("Key size is too large");let r=Zt(e,{offset:0});return ui(r,e,t)}function ui(e,t,r){let n=oi(e);if(r==null){let s=Yn(Wt.encode({Type:ut.RSA,Data:t}));r=Mt(ni,s)}return new wr(n,r)}function fi(e){if(lu(e)>ri)throw new et("Key size is too large");let t=uu(e),r=Yn(Wt.encode({Type:ut.RSA,Data:ii(t.publicKey)})),n=Mt(ni,r);return new an(t.privateKey,new wr(t.publicKey,n))}async function cu(e){if(e>ri)throw new et("Key size is too large");let t=await fu(e),r=Yn(Wt.encode({Type:ut.RSA,Data:ii(t.publicKey)})),n=Mt(ni,r);return new an(t.privateKey,new wr(t.publicKey,n))}function uu(e){if(e==null)throw new et("Missing key parameter");return{privateKey:e,publicKey:{kty:e.kty,n:e.n,e:e.e}}}async function fu(e,t){let r=await Nt.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);t?.signal?.throwIfAborted();let n=await ud(r,t);return{privateKey:n[0],publicKey:n[1]}}async function ou(e,t,r){let n=await Nt.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);r?.signal?.throwIfAborted();let s=await Nt.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,t instanceof Uint8Array?t:t.subarray());return r?.signal?.throwIfAborted(),new Uint8Array(s,0,s.byteLength)}async function iu(e,t,r,n){let s=await Nt.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let o=await Nt.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},s,t,r instanceof Uint8Array?r:r.subarray());return n?.signal?.throwIfAborted(),o}async function ud(e,t){if(e.privateKey==null||e.publicKey==null)throw new et("Private and public key are required");let r=await Promise.all([Nt.get().subtle.exportKey("jwk",e.privateKey),Nt.get().subtle.exportKey("jwk",e.publicKey)]);return t?.signal?.throwIfAborted(),r}function lu(e){if(e.kty!=="RSA")throw new et("invalid key type");if(e.n==null)throw new et("invalid key modulus");return Z(e.n,"base64url").length*8}var Xn=class extends ur{constructor(t,r){super(),this.finished=!1,this.destroyed=!1,Oe(t);let n=ge(r);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let s=this.blockLen,o=new Uint8Array(s);o.set(n.length>s?t.create().update(n).digest():n);for(let i=0;i<o.length;i++)o[i]^=54;this.iHash.update(o),this.oHash=t.create();for(let i=0;i<o.length;i++)o[i]^=106;this.oHash.update(o),Ht(o)}update(t){return fr(this),this.iHash.update(t),this}digestInto(t){fr(this),Et(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));let{oHash:r,iHash:n,finished:s,destroyed:o,blockLen:i,outputLen:a}=this;return t=t,t.finished=s,t.destroyed=o,t.blockLen=i,t.outputLen=a,t.oHash=r._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Er=(e,t,r)=>new Xn(e,t).update(r).digest();Er.create=(e,t)=>new Xn(e,t);var hu=(e,t)=>(e+(e>=0?t:-t)/du)/t;function fd(e,t,r){let[[n,s],[o,i]]=t,a=hu(i*e,r),c=hu(-s*e,r),f=e-a*n-c*o,u=-a*s-c*i,l=f<ae,h=u<ae;l&&(f=-f),h&&(u=-u);let d=Ae(Math.ceil(Mn(r)/2))+vr;if(f<ae||f>=d||u<ae||u>=d)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:l,k1:f,k2neg:h,k2:u}}function hi(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function li(e,t){let r={};for(let n of Object.keys(t))r[n]=e[n]===void 0?t[n]:e[n];return Jt(r.lowS,"lowS"),Jt(r.prehash,"prehash"),r.format!==void 0&&hi(r.format),r}var di=class extends Error{constructor(t=""){super(t)}},ie={Err:di,_tlv:{encode:(e,t)=>{let{Err:r}=ie;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length&1)throw new r("tlv.encode: unpadded data");let n=t.length/2,s=Zr(n);if(s.length/2&128)throw new r("tlv.encode: long form length too big");let o=n>127?Zr(s.length/2|128):"";return Zr(e)+o+s+t},decode(e,t){let{Err:r}=ie,n=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");let s=t[n++],o=!!(s&128),i=0;if(!o)i=s;else{let c=s&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let f=t.subarray(n,n+c);if(f.length!==c)throw new r("tlv.decode: length bytes not complete");if(f[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let u of f)i=i<<8|u;if(n+=c,i<128)throw new r("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(e){let{Err:t}=ie;if(e<ae)throw new t("integer: negative integers are not allowed");let r=Zr(e);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return r},decode(e){let{Err:t}=ie;if(e[0]&128)throw new t("invalid signature integer: negative");if(e[0]===0&&!(e[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return lr(e)}},toSig(e){let{Err:t,_int:r,_tlv:n}=ie,s=Y("signature",e),{v:o,l:i}=n.decode(48,s);if(i.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,o),{v:f,l:u}=n.decode(2,c);if(u.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(f)}},hexFromSig(e){let{_tlv:t,_int:r}=ie,n=t.encode(2,r.encode(e.r)),s=t.encode(2,r.encode(e.s)),o=n+s;return t.encode(48,o)}},ae=BigInt(0),vr=BigInt(1),du=BigInt(2),Qn=BigInt(3),ld=BigInt(4);function Sr(e,t){let{BYTES:r}=e,n;if(typeof t=="bigint")n=t;else{let s=Y("private key",t);try{n=e.fromBytes(s)}catch{throw new Error(`invalid private key: expected ui8a of size ${r}, got ${typeof t}`)}}if(!e.isValidNot0(n))throw new Error("invalid private key: out of range [1..N-1]");return n}function hd(e,t={}){let r=Hn("weierstrass",e,t),{Fp:n,Fn:s}=r,o=r.CURVE,{h:i,n:a}=o;Ft(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:c}=t;if(c&&(!n.is0(o.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let f=mu(n,s);function u(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function l(T,m,y){let{x:b,y:A}=m.toAffine(),_=n.toBytes(b);if(Jt(y,"isCompressed"),y){u();let C=!n.isOdd(A);return Ct(pu(C),_)}else return Ct(Uint8Array.of(4),_,n.toBytes(A))}function h(T){Dt(T,void 0,"Point");let{publicKey:m,publicKeyUncompressed:y}=f,b=T.length,A=T[0],_=T.subarray(1);if(b===m&&(A===2||A===3)){let C=n.fromBytes(_);if(!n.isValid(C))throw new Error("bad point: is not on curve, wrong x");let v=w(C),I;try{I=n.sqrt(v)}catch(z){let F=z instanceof Error?": "+z.message:"";throw new Error("bad point: is not on curve, sqrt error"+F)}u();let D=n.isOdd(I);return(A&1)===1!==D&&(I=n.neg(I)),{x:C,y:I}}else if(b===y&&A===4){let C=n.BYTES,v=n.fromBytes(_.subarray(0,C)),I=n.fromBytes(_.subarray(C,C*2));if(!g(v,I))throw new Error("bad point: is not on curve");return{x:v,y:I}}else throw new Error(`bad point: got length ${b}, expected compressed=${m} or uncompressed=${y}`)}let d=t.toBytes||l,p=t.fromBytes||h;function w(T){let m=n.sqr(T),y=n.mul(m,T);return n.add(n.add(y,n.mul(T,o.a)),o.b)}function g(T,m){let y=n.sqr(m),b=w(T);return n.eql(y,b)}if(!g(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let x=n.mul(n.pow(o.a,Qn),ld),B=n.mul(n.sqr(o.b),BigInt(27));if(n.is0(n.add(x,B)))throw new Error("bad curve params: a or b");function E(T,m,y=!1){if(!n.isValid(m)||y&&n.is0(m))throw new Error(`bad point coordinate ${T}`);return m}function P(T){if(!(T instanceof S))throw new Error("ProjectivePoint expected")}function N(T){if(!c||!c.basises)throw new Error("no endo");return fd(T,c.basises,s.ORDER)}let k=hr((T,m)=>{let{X:y,Y:b,Z:A}=T;if(n.eql(A,n.ONE))return{x:y,y:b};let _=T.is0();m==null&&(m=_?n.ONE:n.inv(A));let C=n.mul(y,m),v=n.mul(b,m),I=n.mul(A,m);if(_)return{x:n.ZERO,y:n.ZERO};if(!n.eql(I,n.ONE))throw new Error("invZ was invalid");return{x:C,y:v}}),M=hr(T=>{if(T.is0()){if(t.allowInfinityPoint&&!n.is0(T.Y))return;throw new Error("bad point: ZERO")}let{x:m,y}=T.toAffine();if(!n.isValid(m)||!n.isValid(y))throw new Error("bad point: x or y not field elements");if(!g(m,y))throw new Error("bad point: equation left != right");if(!T.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function U(T,m,y,b,A){return y=new S(n.mul(y.X,T),y.Y,y.Z),m=Qr(b,m),y=Qr(A,y),m.add(y)}class S{constructor(m,y,b){this.X=E("x",m),this.Y=E("y",y,!0),this.Z=E("z",b),Object.freeze(this)}static CURVE(){return o}static fromAffine(m){let{x:y,y:b}=m||{};if(!m||!n.isValid(y)||!n.isValid(b))throw new Error("invalid affine point");if(m instanceof S)throw new Error("projective point not allowed");return n.is0(y)&&n.is0(b)?S.ZERO:new S(y,b,n.ONE)}static fromBytes(m){let y=S.fromAffine(p(Dt(m,void 0,"point")));return y.assertValidity(),y}static fromHex(m){return S.fromBytes(Y("pointHex",m))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(m=8,y=!0){return R.createCache(this,m),y||this.multiply(Qn),this}assertValidity(){M(this)}hasEvenY(){let{y:m}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(m)}equals(m){P(m);let{X:y,Y:b,Z:A}=this,{X:_,Y:C,Z:v}=m,I=n.eql(n.mul(y,v),n.mul(_,A)),D=n.eql(n.mul(b,v),n.mul(C,A));return I&&D}negate(){return new S(this.X,n.neg(this.Y),this.Z)}double(){let{a:m,b:y}=o,b=n.mul(y,Qn),{X:A,Y:_,Z:C}=this,v=n.ZERO,I=n.ZERO,D=n.ZERO,O=n.mul(A,A),z=n.mul(_,_),F=n.mul(C,C),V=n.mul(A,_);return V=n.add(V,V),D=n.mul(A,C),D=n.add(D,D),v=n.mul(m,D),I=n.mul(b,F),I=n.add(v,I),v=n.sub(z,I),I=n.add(z,I),I=n.mul(v,I),v=n.mul(V,v),D=n.mul(b,D),F=n.mul(m,F),V=n.sub(O,F),V=n.mul(m,V),V=n.add(V,D),D=n.add(O,O),O=n.add(D,O),O=n.add(O,F),O=n.mul(O,V),I=n.add(I,O),F=n.mul(_,C),F=n.add(F,F),O=n.mul(F,V),v=n.sub(v,O),D=n.mul(F,z),D=n.add(D,D),D=n.add(D,D),new S(v,I,D)}add(m){P(m);let{X:y,Y:b,Z:A}=this,{X:_,Y:C,Z:v}=m,I=n.ZERO,D=n.ZERO,O=n.ZERO,z=o.a,F=n.mul(o.b,Qn),V=n.mul(y,_),$=n.mul(b,C),X=n.mul(A,v),it=n.add(y,b),G=n.add(_,C);it=n.mul(it,G),G=n.add(V,$),it=n.sub(it,G),G=n.add(y,A);let dt=n.add(_,v);return G=n.mul(G,dt),dt=n.add(V,X),G=n.sub(G,dt),dt=n.add(b,A),I=n.add(C,v),dt=n.mul(dt,I),I=n.add($,X),dt=n.sub(dt,I),O=n.mul(z,G),I=n.mul(F,X),O=n.add(I,O),I=n.sub($,O),O=n.add($,O),D=n.mul(I,O),$=n.add(V,V),$=n.add($,V),X=n.mul(z,X),G=n.mul(F,G),$=n.add($,X),X=n.sub(V,X),X=n.mul(z,X),G=n.add(G,X),V=n.mul($,G),D=n.add(D,V),V=n.mul(dt,G),I=n.mul(it,I),I=n.sub(I,V),V=n.mul(it,$),O=n.mul(dt,O),O=n.add(O,V),new S(I,D,O)}subtract(m){return this.add(m.negate())}is0(){return this.equals(S.ZERO)}multiply(m){let{endo:y}=t;if(!s.isValidNot0(m))throw new Error("invalid scalar: out of range");let b,A,_=C=>R.cached(this,C,v=>ee(S,v));if(y){let{k1neg:C,k1:v,k2neg:I,k2:D}=N(m),{p:O,f:z}=_(v),{p:F,f:V}=_(D);A=z.add(V),b=U(y.beta,O,F,C,I)}else{let{p:C,f:v}=_(m);b=C,A=v}return ee(S,[b,A])[0]}multiplyUnsafe(m){let{endo:y}=t,b=this;if(!s.isValid(m))throw new Error("invalid scalar: out of range");if(m===ae||b.is0())return S.ZERO;if(m===vr)return b;if(R.hasCache(this))return this.multiply(m);if(y){let{k1neg:A,k1:_,k2neg:C,k2:v}=N(m),{p1:I,p2:D}=Mc(S,b,_,v);return U(y.beta,I,D,A,C)}else return R.unsafe(b,m)}multiplyAndAddUnsafe(m,y,b){let A=this.multiplyUnsafe(y).add(m.multiplyUnsafe(b));return A.is0()?void 0:A}toAffine(m){return k(this,m)}isTorsionFree(){let{isTorsionFree:m}=t;return i===vr?!0:m?m(S,this):R.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:m}=t;return i===vr?this:m?m(S,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(m=!0){return Jt(m,"isCompressed"),this.assertValidity(),d(S,this,m)}toHex(m=!0){return Ut(this.toBytes(m))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(m=!0){return this.toBytes(m)}_setWindowSize(m){this.precompute(m)}static normalizeZ(m){return ee(S,m)}static msm(m,y){return mr(S,s,m,y)}static fromPrivateKey(m){return S.BASE.multiply(Sr(s,m))}}S.BASE=new S(o.Gx,o.Gy,n.ONE),S.ZERO=new S(n.ZERO,n.ONE,n.ZERO),S.Fp=n,S.Fn=s;let L=s.BITS,R=new pr(S,t.endo?Math.ceil(L/2):L);return S.BASE.precompute(8),S}function pu(e){return Uint8Array.of(e?2:3)}function mu(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function dd(e,t={}){let{Fn:r}=e,n=t.randomBytes||be,s=Object.assign(mu(e.Fp,r),{seed:vo(r.ORDER)});function o(d){try{return!!Sr(r,d)}catch{return!1}}function i(d,p){let{publicKey:w,publicKeyUncompressed:g}=s;try{let x=d.length;return p===!0&&x!==w||p===!1&&x!==g?!1:!!e.fromBytes(d)}catch{return!1}}function a(d=n(s.seed)){return Ao(Dt(d,s.seed,"seed"),r.ORDER)}function c(d,p=!0){return e.BASE.multiply(Sr(r,d)).toBytes(p)}function f(d){let p=a(d);return{secretKey:p,publicKey:c(p)}}function u(d){if(typeof d=="bigint")return!1;if(d instanceof e)return!0;let{secretKey:p,publicKey:w,publicKeyUncompressed:g}=s;if(r.allowedLengths||p===w)return;let x=Y("key",d).length;return x===w||x===g}function l(d,p,w=!0){if(u(d)===!0)throw new Error("first arg must be private key");if(u(p)===!1)throw new Error("second arg must be public key");let g=Sr(r,d);return e.fromHex(p).multiply(g).toBytes(w)}return Object.freeze({getPublicKey:c,getSharedSecret:l,keygen:f,Point:e,utils:{isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a,isValidPrivateKey:o,randomPrivateKey:a,normPrivateKeyToScalar:d=>Sr(r,d),precompute(d=8,p=e.BASE){return p.precompute(d,!1)}},lengths:s})}function pd(e,t,r={}){Oe(t),Ft(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let n=r.randomBytes||be,s=r.hmac||((y,...b)=>Er(t,y,Ct(...b))),{Fp:o,Fn:i}=e,{ORDER:a,BITS:c}=i,{keygen:f,getPublicKey:u,getSharedSecret:l,utils:h,lengths:d}=dd(e,r),p={prehash:!1,lowS:typeof r.lowS=="boolean"?r.lowS:!1,format:void 0,extraEntropy:!1},w="compact";function g(y){let b=a>>vr;return y>b}function x(y,b){if(!i.isValidNot0(b))throw new Error(`invalid signature ${y}: out of range 1..Point.Fn.ORDER`);return b}function B(y,b){hi(b);let A=d.signature,_=b==="compact"?A:b==="recovered"?A+1:void 0;return Dt(y,_,`${b} signature`)}class E{constructor(b,A,_){this.r=x("r",b),this.s=x("s",A),_!=null&&(this.recovery=_),Object.freeze(this)}static fromBytes(b,A=w){B(b,A);let _;if(A==="der"){let{r:D,s:O}=ie.toSig(Dt(b));return new E(D,O)}A==="recovered"&&(_=b[0],A="compact",b=b.subarray(1));let C=i.BYTES,v=b.subarray(0,C),I=b.subarray(C,C*2);return new E(i.fromBytes(v),i.fromBytes(I),_)}static fromHex(b,A){return this.fromBytes(Ue(b),A)}addRecoveryBit(b){return new E(this.r,this.s,b)}recoverPublicKey(b){let A=o.ORDER,{r:_,s:C,recovery:v}=this;if(v==null||![0,1,2,3].includes(v))throw new Error("recovery id invalid");if(a*du<A&&v>1)throw new Error("recovery id is ambiguous for h>1 curve");let D=v===2||v===3?_+a:_;if(!o.isValid(D))throw new Error("recovery id 2 or 3 invalid");let O=o.toBytes(D),z=e.fromBytes(Ct(pu((v&1)===0),O)),F=i.inv(D),V=N(Y("msgHash",b)),$=i.create(-V*F),X=i.create(C*F),it=e.BASE.multiplyUnsafe($).add(z.multiplyUnsafe(X));if(it.is0())throw new Error("point at infinify");return it.assertValidity(),it}hasHighS(){return g(this.s)}toBytes(b=w){if(hi(b),b==="der")return Ue(ie.hexFromSig(this));let A=i.toBytes(this.r),_=i.toBytes(this.s);if(b==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return Ct(Uint8Array.of(this.recovery),A,_)}return Ct(A,_)}toHex(b){return Ut(this.toBytes(b))}assertValidity(){}static fromCompact(b){return E.fromBytes(Y("sig",b),"compact")}static fromDER(b){return E.fromBytes(Y("sig",b),"der")}normalizeS(){return this.hasHighS()?new E(this.r,i.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Ut(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Ut(this.toBytes("compact"))}}let P=r.bits2int||function(b){if(b.length>8192)throw new Error("input is too large");let A=lr(b),_=b.length*8-c;return _>0?A>>BigInt(_):A},N=r.bits2int_modN||function(b){return i.create(P(b))},k=Ae(c);function M(y){return ve("num < 2^"+c,y,ae,k),i.toBytes(y)}function U(y,b){return Dt(y,void 0,"message"),b?Dt(t(y),void 0,"prehashed message"):y}function S(y,b,A){if(["recovered","canonical"].some($=>$ in A))throw new Error("sign() legacy options not supported");let{lowS:_,prehash:C,extraEntropy:v}=li(A,p);y=U(y,C);let I=N(y),D=Sr(i,b),O=[M(D),M(I)];if(v!=null&&v!==!1){let $=v===!0?n(d.secretKey):v;O.push(Y("extraEntropy",$))}let z=Ct(...O),F=I;function V($){let X=P($);if(!i.isValidNot0(X))return;let it=i.inv(X),G=e.BASE.multiply(X).toAffine(),dt=i.create(G.x);if(dt===ae)return;let Je=i.create(it*i.create(F+dt*D));if(Je===ae)return;let Ur=(G.x===dt?0:2)|Number(G.y&vr),Kr=Je;return _&&g(Je)&&(Kr=i.neg(Je),Ur^=1),new E(dt,Kr,Ur)}return{seed:z,k2sig:V}}function L(y,b,A={}){y=Y("message",y);let{seed:_,k2sig:C}=S(y,b,A);return Sc(t.outputLen,i.BYTES,s)(_,C)}function R(y){let b,A=typeof y=="string"||Xt(y),_=!A&&y!==null&&typeof y=="object"&&typeof y.r=="bigint"&&typeof y.s=="bigint";if(!A&&!_)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(_)b=new E(y.r,y.s);else if(A){try{b=E.fromBytes(Y("sig",y),"der")}catch(C){if(!(C instanceof ie.Err))throw C}if(!b)try{b=E.fromBytes(Y("sig",y),"compact")}catch{return!1}}return b||!1}function T(y,b,A,_={}){let{lowS:C,prehash:v,format:I}=li(_,p);if(A=Y("publicKey",A),b=U(Y("message",b),v),"strict"in _)throw new Error("options.strict was renamed to lowS");let D=I===void 0?R(y):E.fromBytes(Y("sig",y),I);if(D===!1)return!1;try{let O=e.fromBytes(A);if(C&&D.hasHighS())return!1;let{r:z,s:F}=D,V=N(b),$=i.inv(F),X=i.create(V*$),it=i.create(z*$),G=e.BASE.multiplyUnsafe(X).add(O.multiplyUnsafe(it));return G.is0()?!1:i.create(G.x)===z}catch{return!1}}function m(y,b,A={}){let{prehash:_}=li(A,p);return b=U(b,_),E.fromBytes(y,"recovered").recoverPublicKey(b).toBytes()}return Object.freeze({keygen:f,getPublicKey:u,getSharedSecret:l,utils:h,lengths:d,Point:e,sign:L,verify:T,recoverPublicKey:m,Signature:E,hash:t})}function md(e){let t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},r=e.Fp,n=e.allowedPrivateKeyLengths?Array.from(new Set(e.allowedPrivateKeyLengths.map(i=>Math.ceil(i/2)))):void 0,s=Pt(t.n,{BITS:e.nBitLength,allowedLengths:n,modFromBytes:e.wrapPrivateKey}),o={Fp:r,Fn:s,allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes};return{CURVE:t,curveOpts:o}}function yd(e){let{CURVE:t,curveOpts:r}=md(e),n={hmac:e.hmac,randomBytes:e.randomBytes,lowS:e.lowS,bits2int:e.bits2int,bits2int_modN:e.bits2int_modN};return{CURVE:t,curveOpts:r,hash:e.hash,ecdsaOpts:n}}function gd(e,t){let r=t.Point;return Object.assign({},t,{ProjectivePoint:r,CURVE:Object.assign({},e,kn(r.Fn.ORDER,r.Fn.BITS))})}function yu(e){let{CURVE:t,curveOpts:r,hash:n,ecdsaOpts:s}=yd(e),o=hd(t,r),i=pd(o,n,s);return gd(e,i)}function gu(e,t){let r=n=>yu({...e,hash:n});return{...r(t),create:r}}var mi={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},bd={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var bu=BigInt(2);function xd(e){let t=mi.p,r=BigInt(3),n=BigInt(6),s=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),f=e*e*e%t,u=f*f*e%t,l=nt(u,r,t)*u%t,h=nt(l,r,t)*u%t,d=nt(h,bu,t)*f%t,p=nt(d,s,t)*d%t,w=nt(p,o,t)*p%t,g=nt(w,a,t)*w%t,x=nt(g,c,t)*g%t,B=nt(x,a,t)*w%t,E=nt(B,r,t)*u%t,P=nt(E,i,t)*p%t,N=nt(P,n,t)*f%t,k=nt(N,bu,t);if(!pi.eql(pi.sqr(k),e))throw new Error("Cannot find square root");return k}var pi=Pt(mi.p,{sqrt:xd}),Ar=gu({...mi,Fp:pi,lowS:!0,endo:bd},Se);function xu(e,t,r,n){let s=zr.digest(r instanceof Uint8Array?r:r.subarray());if(Wn(s))return s.then(({digest:o})=>(n?.signal?.throwIfAborted(),Ar.verify(t,o,e))).catch(o=>{throw o.name==="AbortError"?o:new rn(String(o))});try{return n?.signal?.throwIfAborted(),Ar.verify(t,s.digest,e)}catch(o){throw new rn(String(o))}}var Jn=class{type="secp256k1";raw;_key;constructor(t){this._key=Eu(t),this.raw=wu(this._key)}toMultihash(){return kt.digest(ye(this))}toCID(){return ft.createV1(114,this.toMultihash())}toString(){return ct.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:lt(this.raw,t.raw)}verify(t,r,n){return xu(this._key,r,t,n)}};function yi(e){return new Jn(e)}function wu(e){return Ar.ProjectivePoint.fromHex(e).toRawBytes(!0)}function Eu(e){try{return Ar.ProjectivePoint.fromHex(e),e}catch(t){throw new er(String(t))}}function un(e,t){let{Type:r,Data:n}=Wt.decode(e),s=n??new Uint8Array;switch(r){case ut.RSA:return ci(s,t);case ut.Ed25519:return Uo(s);case ut.secp256k1:return yi(s);case ut.ECDSA:return uo(s);default:throw new Le}}function Su(e){let{Type:t,Data:r}=Wt.decode(e.digest),n=r??new Uint8Array;switch(t){case ut.Ed25519:return Uo(n);case ut.secp256k1:return yi(n);case ut.ECDSA:return uo(n);default:throw new Le}}function ye(e){return Wt.encode({Type:ut[e.type],Data:e.raw})}var vu=Symbol.for("nodejs.util.inspect.custom"),wd=114,fn=class{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Os]=!0;toString(){return this.string==null&&(this.string=ct.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return ft.createV1(wd,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return lt(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return lt(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[vu](){return`PeerId(${this.toString()})`}},ln=class extends fn{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},hn=class extends fn{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},dn=class extends fn{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},Ed=2336,pn=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=kt.digest(Z(this.url))}[vu](){return`PeerId(${this.url})`}[Os]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return ft.createV1(Ed,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=q(t)),t.toString()===this.toString())}};var Sd=114,Au=2336;function Bu(e,t){let r;if(e.charAt(0)==="1"||e.charAt(0)==="Q")r=ar(ct.decode(`z${e}`));else{if(e.startsWith("k51qzi5uqu5")||e.startsWith("kzwfwjn5ji4")||e.startsWith("k2k4r8")||e.startsWith("bafz"))return vd(ft.parse(e));if(t==null)throw new et('Please pass a multibase decoder for strings that do not start with "1" or "Q"');r=ar(t.decode(e))}return _u(r)}function gi(e){if(e.type==="Ed25519")return new hn({multihash:e.toCID().multihash,publicKey:e});if(e.type==="secp256k1")return new dn({multihash:e.toCID().multihash,publicKey:e});if(e.type==="RSA")return new ln({multihash:e.toCID().multihash,publicKey:e});throw new Le}function _u(e){if(Bd(e))return new ln({multihash:e});if(Ad(e))try{let t=Su(e);if(t.type==="Ed25519")return new hn({multihash:e,publicKey:t});if(t.type==="secp256k1")return new dn({multihash:e,publicKey:t})}catch{let r=q(e.digest);return new pn(new URL(r))}throw new Bn("Supplied PeerID Multihash is invalid")}function vd(e){if(e?.multihash==null||e.version==null||e.version===1&&e.code!==Sd&&e.code!==Au)throw new An("Supplied PeerID CID is invalid");if(e.code===Au){let t=q(e.multihash.digest);return new pn(new URL(t))}return _u(e.multihash)}function Ad(e){return e.code===kt.code}function Bd(e){return e.code===zr.code}function Iu(e){let t=e.getComponents(),r={},n=0;if(t[n]?.name==="ip6zone"&&(r.zone=`${t[n].value}`,n++),t[n].name==="ip4"||t[n].name==="ip6"||t[n].name==="dns"||t[n].name==="dns4"||t[n].name==="dns6"?(r.type=t[n].name,r.host=t[n].value,n++):t[n].name==="dnsaddr"&&(r.type=t[n].name,r.host=`_dnsaddr.${t[n].value}`,n++),(t[n]?.name==="tcp"||t[n]?.name==="udp")&&(r.protocol=t[n].name==="tcp"?"tcp":"udp",r.port=parseInt(`${t[n].value}`),n++),t[n]?.name==="ipcidr"&&(r.type==="ip4"?r.cidr=parseInt(`${t[n].value}`):r.type==="ip6"&&(r.cidr=`${t[n].value}`),n++),r.type==null||r.host==null)throw new et(`Multiaddr ${e} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return t[n]?.name==="tls"&&t[n+1]?.name==="sni"&&(r.sni=t[n+1].value,n+=2),r}var ts=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let r=this.index,n=t();return n===void 0&&(this.index=r),n}parseWith(t){let r=t();if(this.index===this.input.length)return r}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(t){return this.readAtomically(()=>{let r=this.readChar();if(r===t)return r})}readSeparator(t,r,n){return this.readAtomically(()=>{if(!(r>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,r,n,s){return this.readAtomically(()=>{let o=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",f=2**(8*s)-1;for(;;){let u=this.readAtomically(()=>{let l=this.readChar();if(l===void 0)return;let h=Number.parseInt(l,t);if(!Number.isNaN(h))return h});if(u===void 0)break;if(o*=t,o+=u,o>f||(i+=1,r!==void 0&&i>r))return}if(i!==0)return!n&&c&&i>1?void 0:o})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let r=0;r<t.length;r++){let n=this.readSeparator(".",r,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[r]=n}return t})}readIPv6Addr(){let t=r=>{for(let n=0;n<r.length/2;n++){let s=n*2;if(n<r.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return r[s]=i[0],r[s+1]=i[1],r[s+2]=i[2],r[s+3]=i[3],[s+4,!0]}let o=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(o===void 0)return[s,!1];r[s]=o>>8,r[s+1]=o&255}return[r.length,!1]};return this.readAtomically(()=>{let r=new Uint8Array(16),[n,s]=t(r);if(n===16)return r;if(s||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let o=new Uint8Array(14),i=16-(n+2),[a]=t(o.subarray(0,i));return r.set(o.subarray(0,a),16-a),r})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var _d=45,Id=15,es=new ts;function Cu(e){if(!(e.length>Id))return es.new(e).parseWith(()=>es.readIPv4Addr())}function Lu(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>_d))return es.new(e).parseWith(()=>es.readIPv6Addr())}function rs(e){return!!Cu(e)}function Tu(e){return!!Lu(e)}function ns(){let e={};return e.promise=new Promise((t,r)=>{e.resolve=t,e.reject=r}),e}var ss=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||(t-1&t)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},Br=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new ss(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){let r=this.head;this.head=r.next=new ss(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let r=this.tail.next;this.tail.next=null,this.tail=r,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var bi=class extends Error{type;code;constructor(t,r){super(t??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function os(e={}){return Cd(r=>{let n=r.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},e)}function Cd(e,t){t=t??{};let r=t.onEnd,n=new Br,s,o,i,a=ns(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((g,x)=>{o=B=>{o=null,n.push(B);try{g(e(n))}catch(E){x(E)}return s}}):e(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=ns()})}},f=g=>o!=null?o(g):(n.push(g),s),u=g=>(n=new Br,o!=null?o({error:g}):(n.push({error:g}),s)),l=g=>{if(i)return s;if(t?.objectMode!==!0&&g?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return f({done:!1,value:g})},h=g=>i?s:(i=!0,g!=null?u(g):f({done:!0})),d=()=>(n=new Br,h(),{done:!0}),p=g=>(h(g),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:d,throw:p,push:l,end:h,get readableLength(){return n.size},onEmpty:async g=>{let x=g?.signal;if(x?.throwIfAborted(),n.isEmpty())return;let B,E;x!=null&&(B=new Promise((P,N)=>{E=()=>{N(new bi)},x.addEventListener("abort",E)}));try{await Promise.race([a.promise,B])}finally{E!=null&&x!=null&&x?.removeEventListener("abort",E)}}},r==null)return s;let w=s;return s={[Symbol.asyncIterator](){return this},next(){return w.next()},throw(g){return w.throw(g),r!=null&&(r(g),r=void 0),{done:!0}},return(){return w.return(),r!=null&&(r(),r=void 0),{done:!0}},push:l,end(g){return w.end(g),r!=null&&(r(g),r=void 0),s},get readableLength(){return w.readableLength},onEmpty:g=>w.onEmpty(g)},s}var xi=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},wi=class extends Error{constructor(t){super(),this.name="AbortError",this.message=t}},Du=e=>globalThis.DOMException===void 0?new wi(e):new DOMException(e),Pu=e=>{let t=e.reason===void 0?Du("This operation was aborted."):e.reason;return t instanceof Error?t:Du(t)};function Ei(e,t){let{milliseconds:r,fallback:n,message:s,customTimers:o={setTimeout,clearTimeout}}=t,i,a,f=new Promise((u,l)=>{if(typeof r!="number"||Math.sign(r)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(t.signal){let{signal:d}=t;d.aborted&&l(Pu(d)),a=()=>{l(Pu(d))},d.addEventListener("abort",a,{once:!0})}if(r===Number.POSITIVE_INFINITY){e.then(u,l);return}let h=new xi;i=o.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(d){l(d)}return}typeof e.cancel=="function"&&e.cancel(),s===!1?u():s instanceof Error?l(s):(h.message=s??`Promise timed out after ${r} milliseconds`,l(h))},r),(async()=>{try{u(await e)}catch(d){l(d)}})()}).finally(()=>{f.clear(),a&&t.signal&&t.signal.removeEventListener("abort",a)});return f.clear=()=>{o.clearTimeout.call(void 0,i),i=void 0},f}var Ld=e=>{let t=e.addEventListener||e.on||e.addListener,r=e.removeEventListener||e.off||e.removeListener;if(!t||!r)throw new TypeError("Emitter is not compatible");return{addListener:t.bind(e),removeListener:r.bind(e)}};function Td(e,t,r){let n,s=new Promise((o,i)=>{if(r={rejectionEvents:["error"],multiArgs:!1,resolveImmediately:!1,...r},!(r.count>=0&&(r.count===Number.POSITIVE_INFINITY||Number.isInteger(r.count))))throw new TypeError("The `count` option should be at least 0 or more");r.signal?.throwIfAborted();let a=[t].flat(),c=[],{addListener:f,removeListener:u}=Ld(e),l=(...d)=>{let p=r.multiArgs?d:d[0];r.filter&&!r.filter(p)||(c.push(p),r.count===c.length&&(n(),o(c)))},h=d=>{n(),i(d)};n=()=>{for(let d of a)u(d,l);for(let d of r.rejectionEvents)u(d,h)};for(let d of a)f(d,l);for(let d of r.rejectionEvents)f(d,h);r.signal&&r.signal.addEventListener("abort",()=>{h(r.signal.reason)},{once:!0}),r.resolveImmediately&&o(c)});if(s.cancel=n,typeof r.timeout=="number"){let o=Ei(s,{milliseconds:r.timeout});return o.cancel=n,o}return s}function Ie(e,t,r){typeof r=="function"&&(r={filter:r}),r={...r,count:1,resolveImmediately:!1};let n=Td(e,t,r),s=n.then(o=>o[0]);return s.cancel=n.cancel,s}var $e=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"},is=class extends Error{static name="MaxEarlyStreamsError";name="MaxEarlyStreamsError"};function Dd(e){return e.reason}async function ce(e,t,r){if(t==null)return e;let n=r?.translateError??Dd;if(t.aborted)return e.catch(()=>{}),Promise.reject(n(t));let s;try{return await Promise.race([e,new Promise((o,i)=>{s=()=>{i(n(t))},t.addEventListener("abort",s)})])}finally{s!=null&&t.removeEventListener("abort",s)}}var Pd=Math.pow(2,20)*4,$t=class extends nr{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;constructor(t){super(),this.status="open",this.log=t.log,this.direction=t.direction??"outbound",this.inactivityTimeout=t.inactivityTimeout??12e4,this.maxReadBufferLength=t.maxReadBufferLength??Pd,this.maxWriteBufferLength=t.maxWriteBufferLength,this.maxMessageSize=t.maxMessageSize,this.readBuffer=new j,this.writeBuffer=new j,this.readStatus="readable",this.remoteReadStatus="readable",this.writeStatus="writable",this.remoteWriteStatus="writable",this.sendingData=!1,this.writableNeedsDrain=!1,this.timeline={open:Date.now()},this.processSendQueue=this.processSendQueue.bind(this);let r=()=>{this.writableNeedsDrain&&(this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,this.processSendQueue())};this.addEventListener("drain",r)}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let t=os(),r=o=>{t.push(o.data)};this.addEventListener("message",r);let n=o=>{t.end(o.error)};this.addEventListener("close",n);let s=()=>{t.end()};this.addEventListener("remoteCloseWrite",s);try{yield*t}finally{this.removeEventListener("message",r),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",s)}}isReadable(){return this.status==="open"}send(t){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new Ce(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",t.byteLength),this.writeBuffer.append(t),this.processSendQueue()}abort(t){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",t),this.status="aborted",this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle")),this.writeStatus="closed",this.remoteWriteStatus="closed",this.readStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now();try{this.sendReset(t)}catch(r){this.log("failed to send reset to remote - %e",r)}this.dispatchEvent(new In(t))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Ce("Cannot pause a stream that is closing/closed");this.readStatus!=="paused"&&(this.readStatus="paused",this.sendPause())}resume(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Ce("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(t){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Ce(`Cannot push data onto a stream that is ${this.readStatus}`);if(t.byteLength!==0){if(this.readBuffer.append(t),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(t){if(t.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(t),this.dispatchReadBuffer()}}addEventListener(...t){super.addEventListener.apply(this,t),t[0]==="message"&&this.readBuffer.byteLength>0&&queueMicrotask(()=>{this.dispatchReadBuffer()})}onRemoteReset(){this.log("remote reset"),this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.readBuffer.byteLength===0&&(this.readStatus="closed");let t=new vn;this.dispatchEvent(new Cn(t))}onTransportClosed(t){this.log("transport closed"),this.readStatus==="readable"&&this.readBuffer.byteLength===0&&(this.log("close readable end after transport closed and read buffer is empty"),this.readStatus="closed"),this.remoteReadStatus!=="closed"&&(this.remoteReadStatus="closed"),this.remoteWriteStatus!=="closed"&&(this.remoteWriteStatus="closed"),this.writeStatus!=="closed"&&(this.writeStatus="closed"),t!=null?this.abort(t):(this.status==="open"||this.status==="closing")&&(this.timeline.close=Date.now(),this.status="closed",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.dispatchEvent(new rr))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.writeStatus==="closed"&&this.onTransportClosed())}onRemoteCloseRead(){this.log.trace("on remote close read"),this.remoteReadStatus="closed",this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle"))}processSendQueue(){if(this.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(this.writeBuffer.byteLength===0)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let t=!0,r=this.writeBuffer.byteLength,n=0;for(;this.writeBuffer.byteLength>0;){let s=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(s===0){t=!1;break}let o=this.writeBuffer.sublist(0,s),i=new j(o);this.writeBuffer.consume(o.byteLength);let a=this.sendData(o);if(t=a.canSendMore,n+=a.sentBytes,a.sentBytes!==i.byteLength&&(i.consume(a.sentBytes),this.writeBuffer.prepend(i)),!t)break}return t||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",n,r,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),t}finally{this.sendingData=!1}}dispatchReadBuffer(){try{if(this.listenerCount("message")===0){this.log.trace("not dispatching pause buffer as there are no listeners for the message event");return}if(this.readBuffer.byteLength===0){this.log.trace("not dispatching pause buffer as there is no data to dispatch");return}if(this.readStatus==="paused"){this.log.trace("not dispatching pause buffer we are paused");return}if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("dropping %d bytes because the readable end is %s",this.readBuffer.byteLength,this.readStatus),this.readBuffer.consume(this.readBuffer.byteLength);return}let t=this.readBuffer.sublist();this.readBuffer.consume(t.byteLength),this.dispatchEvent(new _n(t))}finally{this.readBuffer.byteLength===0&&this.remoteWriteStatus==="closed"&&(this.log("close readable end after dispatching read buffer and remote writable end is closed"),this.readStatus="closed"),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new Nr(`Read buffer length of ${this.readBuffer.byteLength} exceeded limit of ${this.maxReadBufferLength}, read status is ${this.readStatus}`))}checkWriteBufferLength(){this.maxWriteBufferLength!=null&&this.writeBuffer.byteLength>this.maxWriteBufferLength&&this.abort(new Nr(`Write buffer length of ${this.writeBuffer.byteLength} exceeded limit of ${this.maxWriteBufferLength}, write status is ${this.writeStatus}`))}onMuxerNeedsDrain(){this.writableNeedsDrain=!0}onMuxerDrain(){this.safeDispatchEvent("drain")}};var as=class extends $t{remoteAddr;metricPrefix;metrics;constructor(t){super(t),this.metricPrefix=t.metricPrefix??"",this.metrics=t.metrics,this.remoteAddr=t.remoteAddr,this.addEventListener("close",r=>{this.metrics?.increment({[`${this.metricPrefix}end`]:!0}),r.error!=null?r.local?this.metrics?.increment({[`${this.metricPrefix}abort`]:!0}):this.metrics?.increment({[`${this.metricPrefix}reset`]:!0}):r.local?this.metrics?.increment({[`${this.metricPrefix}_local_close`]:!0}):this.metrics?.increment({[`${this.metricPrefix}_remote_close`]:!0})})}async close(t){this.status==="open"&&(this.status="closing",this.writeStatus="closing",this.remoteWriteStatus="closing",this.remoteReadStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Ie(this,"idle",{...t,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Ie(this,"drain",{...t,rejectionEvents:["close"]})),await this.sendClose(t),this.onTransportClosed())}};function Ru(e){return e==null?!1:typeof e.then=="function"&&typeof e.catch=="function"&&typeof e.finally=="function"}var cs=class extends nr{streams;protocol;status;log;maConn;streamOptions;earlyStreams;maxEarlyStreams;metrics;constructor(t,r){super(),this.maConn=t,this.protocol=r.protocol,this.streams=[],this.earlyStreams=[],this.status="open",this.log=t.log.newScope(r.name),this.streamOptions=r.streamOptions,this.maxEarlyStreams=r.maxEarlyStreams??10,this.metrics=r.metrics;let n=i=>{try{this.onData(i.data)}catch(a){this.abort(a),this.maConn.abort(a)}};this.maConn.addEventListener("message",n);let s=()=>{this.log("underlying stream drained, signal %d streams to continue writing",this.streams.length),this.streams.forEach(i=>{i.onMuxerDrain()})};this.maConn.addEventListener("drain",s);let o=()=>{this.log("underlying stream closed with status %s and %d streams",this.status,this.streams.length),this.onTransportClosed()};this.maConn.addEventListener("close",o)}send(t){let r=this.maConn.send(t);return r===!1&&(this.log("underlying stream saturated, signal %d streams to pause writing",this.streams.length),this.streams.forEach(n=>{n.onMuxerNeedsDrain()})),r}async close(t){this.status==="closed"||this.status==="closing"||(this.status="closing",await ce(Promise.all([...this.streams].map(async r=>{await r.close(t)})),t?.signal),this.status="closed")}abort(t){this.status!=="closed"&&(this.status="closing",[...this.streams].forEach(r=>{r.abort(t)}),this.status="closed")}onTransportClosed(t){this.status="closing";try{[...this.streams].forEach(r=>{r.onTransportClosed(t)})}catch(r){this.abort(r)}this.status="closed"}async createStream(t){if(this.status!=="open")throw new Sn;let r=this.onCreateStream({...this.streamOptions,...t});return Ru(r)&&(r=await r),this.streams.push(r),this.cleanUpStream(r),r}onRemoteStream(t){if(this.streams.push(t),this.cleanUpStream(t),this.listenerCount("stream")===0){this.earlyStreams.push(t),this.earlyStreams.length>this.maxEarlyStreams&&this.abort(new is(`Too many early streams were opened - ${this.earlyStreams.length}/${this.maxEarlyStreams}`));return}this.safeDispatchEvent("stream",{detail:t})}cleanUpStream(t){let r=n=>{let s=this.streams.findIndex(o=>o===t);s!==-1&&this.streams.splice(s,1),n.error!=null?n.local?this.metrics?.increment({[`${t.direction}_stream_reset`]:!0}):this.metrics?.increment({[`${t.direction}_stream_abort`]:!0}):this.metrics?.increment({[`${t.direction}_stream_end`]:!0})};t.addEventListener("close",r),this.metrics?.increment({[`${t.direction}_stream`]:!0})}addEventListener(...t){super.addEventListener.apply(this,t),t[0]==="stream"&&this.earlyStreams.length>0&&queueMicrotask(()=>{this.earlyStreams.forEach(r=>{this.safeDispatchEvent("stream",{detail:r})}),this.earlyStreams=[]})}};var us=class extends $t{id;protocol;constructor(t){super(t),this.id=t.id,this.protocol=t.protocol??""}async close(t){this.writeStatus==="closing"||this.writeStatus==="closed"||(this.writeStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Ie(this,"idle",{...t,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData),await Ie(this,"drain",{...t,rejectionEvents:["close"]}),this.log("write queue drained, closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData)),await this.sendCloseWrite(t),this.writeStatus="closed",this.log("closed writable end gracefully"),this.remoteWriteStatus==="closed"&&this.onTransportClosed())}async closeRead(t){this.readStatus==="closing"||this.readStatus==="closed"||(this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.readStatus="closing",await this.sendCloseRead(t),this.readStatus="closed",this.log("closed readable end gracefully"))}};var xt=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},ue=class extends Error{static name="ValidationError";name="ValidationError"},fs=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},ls=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function vi(e){return t=>q(t,e)}function Ai(e){return t=>Z(t,e)}function _r(e){return new DataView(e.buffer).getUint16(e.byteOffset).toString()}function Ge(e){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,typeof e=="string"?parseInt(e):e),new Uint8Array(t)}function Ou(e){let t=e.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==16)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);let r=Z(t[0],"base32"),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=Ge(n);return Ot([r,s],r.length+s.length)}function Uu(e){let t=e.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let r=pe.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=Ge(n);return Ot([r,s],r.length+s.length)}function Bi(e){let t=e.subarray(0,e.length-2),r=e.subarray(e.length-2),n=q(t,"base32"),s=_r(r);return`${n}:${s}`}var _i=function(e){e=e.toString().trim();let t=new Uint8Array(4);return e.split(/\./g).forEach((r,n)=>{let s=parseInt(r,10);if(isNaN(s)||s<0||s>255)throw new xt("Invalid byte value in IP address");t[n]=s}),t},Ku=function(e){let t=0;e=e.toString().trim();let r=e.split(":",8),n;for(n=0;n<r.length;n++){let o=rs(r[n]),i;o&&(i=_i(r[n]),r[n]=q(i.subarray(0,2),"base16")),i!=null&&++n<8&&r.splice(n,0,q(i.subarray(2,4),"base16"))}if(r[0]==="")for(;r.length<8;)r.unshift("0");else if(r[r.length-1]==="")for(;r.length<8;)r.push("0");else if(r.length<8){for(n=0;n<r.length&&r[n]!=="";n++);let o=[n,1];for(n=9-r.length;n>0;n--)o.push("0");r.splice.apply(r,o)}let s=new Uint8Array(t+16);for(n=0;n<r.length;n++){r[n]===""&&(r[n]="0");let o=parseInt(r[n],16);if(isNaN(o)||o<0||o>65535)throw new xt("Invalid byte value in IP address");s[t++]=o>>8&255,s[t++]=o&255}return s},Nu=function(e){if(e.byteLength!==4)throw new xt("IPv4 address was incorrect length");let t=[];for(let r=0;r<e.byteLength;r++)t.push(e[r]);return t.join(".")},Mu=function(e){if(e.byteLength!==16)throw new xt("IPv6 address was incorrect length");let t=[];for(let n=0;n<e.byteLength;n+=2){let s=e[n],o=e[n+1],i=`${s.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}`;t.push(i)}let r=t.join(":");try{let n=new URL(`http://[${r}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new xt(`Invalid IPv6 address "${r}"`)}};function ku(e){try{let t=new URL(`http://[${e}]`);return t.hostname.substring(1,t.hostname.length-1)}catch{throw new xt(`Invalid IPv6 address "${e}"`)}}var Si=Object.values(De).map(e=>e.decoder),Rd=(function(){let e=Si[0].or(Si[1]);return Si.slice(2).forEach(t=>e=e.or(t)),e})();function Hu(e){return Rd.decode(e)}function Vu(e){return t=>e.encoder.encode(t)}function Od(e){if(parseInt(e).toString()!==e)throw new ue("Value must be an integer")}function Ud(e){if(e<0)throw new ue("Value must be a positive integer, or zero")}function Kd(e){return t=>{if(t>e)throw new ue(`Value must be smaller than or equal to ${e}`)}}function Nd(...e){return t=>{for(let r of e)r(t)}}var mn=Nd(Od,Ud,Kd(65535));var yt=-1,Ii=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(t){let r;if(typeof t=="string"?r=this.protocolsByName.get(t):r=this.protocolsByCode.get(t),r==null)throw new ls(`Protocol ${t} was unknown`);return r}addProtocol(t){this.protocolsByCode.set(t.code,t),this.protocolsByName.set(t.name,t),t.aliases?.forEach(r=>{this.protocolsByName.set(r,t)})}removeProtocol(t){let r=this.protocolsByCode.get(t);r!=null&&(this.protocolsByCode.delete(r.code),this.protocolsByName.delete(r.name),r.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},fe=new Ii,Qd=[{code:4,name:"ip4",size:32,valueToBytes:_i,bytesToValue:Nu,validate:e=>{if(!rs(e))throw new ue(`Invalid IPv4 address "${e}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Ge,bytesToValue:_r,validate:mn},{code:273,name:"udp",size:16,valueToBytes:Ge,bytesToValue:_r,validate:mn},{code:33,name:"dccp",size:16,valueToBytes:Ge,bytesToValue:_r,validate:mn},{code:41,name:"ip6",size:128,valueToBytes:Ku,bytesToValue:Mu,stringToValue:ku,validate:e=>{if(!Tu(e))throw new ue(`Invalid IPv6 address "${e}"`)}},{code:42,name:"ip6zone",size:yt},{code:43,name:"ipcidr",size:8,bytesToValue:vi("base10"),valueToBytes:Ai("base10")},{code:53,name:"dns",size:yt},{code:54,name:"dns4",size:yt},{code:55,name:"dns6",size:yt},{code:56,name:"dnsaddr",size:yt},{code:132,name:"sctp",size:16,valueToBytes:Ge,bytesToValue:_r,validate:mn},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:yt,stringToValue:e=>decodeURIComponent(e),valueToString:e=>encodeURIComponent(e)},{code:421,name:"p2p",aliases:["ipfs"],size:yt,bytesToValue:vi("base58btc"),valueToBytes:e=>e.startsWith("Q")||e.startsWith("1")?Ai("base58btc")(e):ft.parse(e).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Bi,valueToBytes:Ou},{code:445,name:"onion3",size:296,bytesToValue:Bi,valueToBytes:Uu},{code:446,name:"garlic64",size:yt},{code:447,name:"garlic32",size:yt},{code:448,name:"tls"},{code:449,name:"sni",size:yt},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:yt,bytesToValue:Vu(Ys),valueToBytes:Hu},{code:480,name:"http"},{code:481,name:"http-path",size:yt,stringToValue:e=>`/${decodeURIComponent(e)}`,valueToString:e=>encodeURIComponent(e.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:yt}];Qd.forEach(e=>{fe.addProtocol(e)});function qu(e){let t=[],r=0;for(;r<e.length;){let n=He(e,r),s=fe.getProtocol(n),o=vt(n),i=Jd(s,e,r+o),a=0;i>0&&s.size===yt&&(a=vt(i));let c=o+a+i,f={code:n,name:s.name,bytes:e.subarray(r,r+c)};if(i>0){let u=r+o+a,l=e.subarray(u,u+i);f.value=s.bytesToValue?.(l)??q(l)}t.push(f),r+=c}return t}function zu(e){let t=0,r=[];for(let n of e){if(n.bytes==null){let s=fe.getProtocol(n.code),o=vt(n.code),i,a=0,c=0;n.value!=null&&(i=s.valueToBytes?.(n.value)??Z(n.value),a=i.byteLength,s.size===yt&&(c=vt(a)));let f=new Uint8Array(o+c+a),u=0;br(n.code,f,u),u+=o,i!=null&&(s.size===yt&&(br(a,f,u),u+=c),f.set(i,u)),n.bytes=f}r.push(n.bytes),t+=n.bytes.byteLength}return Ot(r,t)}function Fu(e){if(e.charAt(0)!=="/")throw new xt('String multiaddr must start with "/"');let t=[],r="protocol",n="",s="";for(let o=1;o<e.length;o++){let i=e.charAt(o);i!=="/"&&(r==="protocol"?s+=e.charAt(o):n+=e.charAt(o));let a=o===e.length-1;if(i==="/"||a){let c=fe.getProtocol(s);if(r==="protocol"){if(c.size==null||c.size===0){t.push({code:c.code,name:c.name}),n="",s="",r="protocol";continue}else if(a)throw new xt(`Component ${s} was missing value`);r="value"}else if(r==="value"){let f={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new xt(`Component ${s} was missing value`);f.value=c.stringToValue?.(n)??n}t.push(f),n="",s="",r="protocol"}}}if(s!==""&&n!=="")throw new xt("Incomplete multiaddr");return t}function Wu(e){return`/${e.flatMap(t=>{if(t.value==null)return t.name;let r=fe.getProtocol(t.code);if(r==null)throw new xt(`Unknown protocol code ${t.code}`);return[t.name,r.valueToString?.(t.value)??t.value]}).join("/")}`}function Jd(e,t,r){return e.size==null||e.size===0?0:e.size>0?e.size/8:He(t,r)}var tp=Symbol.for("nodejs.util.inspect.custom"),Wi=Symbol.for("@multiformats/multiaddr");function ep(e){if(e==null&&(e="/"),$u(e))return e.getComponents();if(e instanceof Uint8Array)return qu(e);if(typeof e=="string")return e=e.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),e===""&&(e="/"),Fu(e);if(Array.isArray(e))return e;throw new xt("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Fi=class e{[Wi]=!0;#t;#e;#r;constructor(t="/",r={}){this.#t=ep(t),r.validate!==!1&&rp(this)}get bytes(){return this.#r==null&&(this.#r=zu(this.#t)),this.#r}toString(){return this.#e==null&&(this.#e=Wu(this.#t)),this.#e}toJSON(){return this.toString()}getComponents(){return[...this.#t.map(t=>({...t}))]}encapsulate(t){let r=new e(t);return new e([...this.#t,...r.getComponents()],{validate:!1})}decapsulate(t){let r=t.toString(),n=this.toString(),s=n.lastIndexOf(r);if(s<0)throw new fs(`Address ${this.toString()} does not contain subaddress: ${r}`);return new e(n.slice(0,s),{validate:!1})}decapsulateCode(t){let r;for(let n=this.#t.length-1;n>-1;n--)if(this.#t[n].code===t){r=n;break}return new e(this.#t.slice(0,r),{validate:!1})}equals(t){return lt(this.bytes,t.bytes)}[tp](){return`Multiaddr(${this.toString()})`}};function rp(e){e.getComponents().forEach(t=>{let r=fe.getProtocol(t.code);t.value!=null&&r.validate?.(t.value)})}function $u(e){return!!e?.[Wi]}var np=4194304,ys=class extends Error{static name="UnwrappedError";name="UnwrappedError"},yn=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Gi=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},ji=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function sp(e){return typeof e?.closeRead=="function"}function op(e){return typeof e?.close=="function"}function $i(e){return sp(e)?e.readStatus==="closing"||e.readStatus==="closed":op(e)?e.status!=="open":!1}function ip(e){return e?.addEventListener!=null&&e?.removeEventListener!=null&&e?.send!=null&&e?.push!=null&&e?.log!=null}function ap(e,t){let r=t?.maxBufferSize??np,n=new j,s=Promise.withResolvers(),o=!1;if(!ip(e))throw new et("Argument should be a Stream or a Multiaddr");let i=u=>{if(n.append(u.data),n.byteLength>r){let l=n.byteLength;n.consume(n.byteLength),s.reject(new Error(`Read buffer overflow - ${l} > ${r}`))}s.resolve()};e.addEventListener("message",i);let a=u=>{u.error!=null?s.reject(u.error):s.resolve()};e.addEventListener("close",a);let c=()=>{s.resolve()};e.addEventListener("remoteCloseWrite",c);let f={readBuffer:n,async read(u){if(o===!0)throw new ys("Stream was unwrapped");if($i(e)){if(u?.bytes==null)return null;if(n.byteLength<u.bytes)throw e.log.error("closed after reading %d/%d bytes",n.byteLength,u.bytes),new $e(`Unexpected EOF - stream closed after reading ${n.byteLength}/${u.bytes} bytes`)}let l=u?.bytes??1;for(;;){if(n.byteLength>=l){s.resolve();break}if(await ce(s.promise,u?.signal),$i(e)){if(n.byteLength===0&&u?.bytes==null)return null;break}s=Promise.withResolvers()}let h=u?.bytes??n.byteLength;if(n.byteLength<h){if($i(e))throw e.log.error("closed while reading %d/%d bytes",n.byteLength,h),new $e(`Unexpected EOF - stream closed while reading ${n.byteLength}/${h} bytes`);return f.read(u)}let d=n.sublist(0,h);return n.consume(h),d},async write(u,l){if(o===!0)throw new ys("Stream was unwrapped");e.send(u)||await Ie(e,"drain",{signal:l?.signal,rejectionEvents:["close"]})},unwrap(){return o||(o=!0,e.removeEventListener("message",i),e.removeEventListener("close",a),e.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(e.log("stream unwrapped with %d unread bytes",n.byteLength),e.push(n))),e}};return f}function Zi(e,t={}){let r=ap(e,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=vt(t.maxDataLength));let n=t?.lengthDecoder??He,s=t?.lengthEncoder??Zc;return{async read(i){let a=-1,c=new j;for(;;){let u=await r.read({...i,bytes:1});if(u==null)break;c.append(u);try{a=n(c)}catch(l){if(l instanceof RangeError)continue;throw l}if(a<0)throw new yn("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new ji(`Message length length too long - ${c.byteLength} > ${t.maxLengthLength}`);if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new Gi(`Message length too long - ${a} > ${t.maxDataLength}`);let f=await r.read({...i,bytes:a});if(f==null)throw e.log.error("tried to read %d bytes but the stream closed",a),new $e(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(f.byteLength!==a)throw e.log.error("read %d/%d bytes before the stream closed",f.byteLength,a),new $e(`Unexpected EOF - read ${f.byteLength}/${a} bytes before the stream closed`);return f},async write(i,a){await r.write(new j(s(i.byteLength),i),a)},async writeV(i,a){let c=new j(...i.flatMap(f=>[s(f.byteLength),f]));await r.write(c,a)},unwrap(){return r.unwrap()}}}var cp=1024*1024*4,up=1024*1024*4,gs=class{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(t={}){this.buffer=new j,this.maxBufferSize=t.maxBufferSize??cp,this.maxDataLength=t.maxDataLength??up,this.lengthDecoder=t.lengthDecoder??He,this.encodingLength=t.encodingLength??vt}*decode(t){if(this.buffer.append(t),this.buffer.byteLength>this.maxBufferSize)throw new et(`Buffer length limit exceeded - ${this.buffer.byteLength}/${this.maxBufferSize}`);for(;;){let r;try{r=this.lengthDecoder(this.buffer)}catch(o){if(o instanceof RangeError)break;throw o}if(r<0||r>this.maxDataLength)throw new yn("Invalid message length");let n=this.encodingLength(r),s=n+r;if(this.buffer.byteLength>=s){let o=this.buffer.sublist(n,s);this.buffer.consume(s),o.byteLength>0&&(yield o)}else break}}};var Tr=!!globalThis.process?.env?.DUMP_SESSION_KEYS,Yi=16;function ju(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function bs(e){if(typeof e!="boolean")throw new Error(`boolean expected, not ${e}`)}function xs(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Bt(e,...t){if(!ju(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function Xi(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Zu(e,t){Bt(e);let r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function le(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function he(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function fp(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}var lp=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function hp(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function ws(e){if(typeof e=="string")e=hp(e);else if(ju(e))e=Es(e);else throw new Error("Uint8Array expected, got "+typeof e);return e}function Yu(e,t){if(t==null||typeof t!="object")throw new Error("options must be defined");return Object.assign(e,t)}function Xu(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return r===0}var Qi=(e,t)=>{function r(n,...s){if(Bt(n),!lp)throw new Error("Non little-endian hardware is not yet supported");if(e.nonceLength!==void 0){let u=s[0];if(!u)throw new Error("nonce / iv required");e.varSizeNonce?Bt(u):Bt(u,e.nonceLength)}let o=e.tagLength;o&&s[1]!==void 0&&Bt(s[1]);let i=t(n,...s),a=(u,l)=>{if(l!==void 0){if(u!==2)throw new Error("cipher output not supported");Bt(l)}},c=!1;return{encrypt(u,l){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,Bt(u),a(i.encrypt.length,l),i.encrypt(u,l)},decrypt(u,l){if(Bt(u),o&&u.length<o)throw new Error("invalid ciphertext length: smaller than tagLength="+o);return a(i.decrypt.length,l),i.decrypt(u,l)}}}return Object.assign(r,e),r};function Ji(e,t,r=!0){if(t===void 0)return new Uint8Array(e);if(t.length!==e)throw new Error("invalid output length, expected "+e+", got: "+t.length);if(r&&!dp(t))throw new Error("invalid output, must be aligned");return t}function Gu(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);let s=BigInt(32),o=BigInt(4294967295),i=Number(r>>s&o),a=Number(r&o),c=n?4:0,f=n?0:4;e.setUint32(t+c,i,n),e.setUint32(t+f,a,n)}function Qu(e,t,r){bs(r);let n=new Uint8Array(16),s=fp(n);return Gu(s,0,BigInt(t),r),Gu(s,8,BigInt(e),r),n}function dp(e){return e.byteOffset%4===0}function Es(e){return Uint8Array.from(e)}var tf=e=>Uint8Array.from(e.split("").map(t=>t.charCodeAt(0))),pp=tf("expand 16-byte k"),mp=tf("expand 32-byte k"),yp=le(pp),gp=le(mp);function K(e,t){return e<<t|e>>>32-t}function ta(e){return e.byteOffset%4===0}var Ss=64,bp=16,ef=2**32-1,Ju=new Uint32Array;function xp(e,t,r,n,s,o,i,a){let c=s.length,f=new Uint8Array(Ss),u=le(f),l=ta(s)&&ta(o),h=l?le(s):Ju,d=l?le(o):Ju;for(let p=0;p<c;i++){if(e(t,r,n,u,i,a),i>=ef)throw new Error("arx: counter overflow");let w=Math.min(Ss,c-p);if(l&&w===Ss){let g=p/4;if(p%4!==0)throw new Error("arx: invalid block position");for(let x=0,B;x<bp;x++)B=g+x,d[B]=h[B]^u[x];p+=Ss;continue}for(let g=0,x;g<w;g++)x=p+g,o[x]=s[x]^f[g];p+=w}}function ea(e,t){let{allowShortKeys:r,extendNonceFn:n,counterLength:s,counterRight:o,rounds:i}=Yu({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!="function")throw new Error("core must be a function");return xs(s),xs(i),bs(o),bs(r),(a,c,f,u,l=0)=>{Bt(a),Bt(c),Bt(f);let h=f.length;if(u===void 0&&(u=new Uint8Array(h)),Bt(u),xs(l),l<0||l>=ef)throw new Error("arx: counter overflow");if(u.length<h)throw new Error(`arx: output (${u.length}) is shorter than data (${h})`);let d=[],p=a.length,w,g;if(p===32)d.push(w=Es(a)),g=gp;else if(p===16&&r)w=new Uint8Array(32),w.set(a),w.set(a,16),g=yp,d.push(w);else throw new Error(`arx: invalid 32-byte key, got length=${p}`);ta(c)||d.push(c=Es(c));let x=le(w);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(g,x,le(c.subarray(0,16)),x),c=c.subarray(16)}let B=16-s;if(B!==c.length)throw new Error(`arx: nonce must be ${B} or 16 bytes`);if(B!==12){let P=new Uint8Array(12);P.set(c,o?0:12-c.length),c=P,d.push(c)}let E=le(c);return xp(e,g,x,E,f,u,l,i),he(...d),u}}var wt=(e,t)=>e[t++]&255|(e[t++]&255)<<8,ra=class{constructor(t){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,t=ws(t),Bt(t,32);let r=wt(t,0),n=wt(t,2),s=wt(t,4),o=wt(t,6),i=wt(t,8),a=wt(t,10),c=wt(t,12),f=wt(t,14);this.r[0]=r&8191,this.r[1]=(r>>>13|n<<3)&8191,this.r[2]=(n>>>10|s<<6)&7939,this.r[3]=(s>>>7|o<<9)&8191,this.r[4]=(o>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|f<<8)&8191,this.r[9]=f>>>5&127;for(let u=0;u<8;u++)this.pad[u]=wt(t,16+2*u)}process(t,r,n=!1){let s=n?0:2048,{h:o,r:i}=this,a=i[0],c=i[1],f=i[2],u=i[3],l=i[4],h=i[5],d=i[6],p=i[7],w=i[8],g=i[9],x=wt(t,r+0),B=wt(t,r+2),E=wt(t,r+4),P=wt(t,r+6),N=wt(t,r+8),k=wt(t,r+10),M=wt(t,r+12),U=wt(t,r+14),S=o[0]+(x&8191),L=o[1]+((x>>>13|B<<3)&8191),R=o[2]+((B>>>10|E<<6)&8191),T=o[3]+((E>>>7|P<<9)&8191),m=o[4]+((P>>>4|N<<12)&8191),y=o[5]+(N>>>1&8191),b=o[6]+((N>>>14|k<<2)&8191),A=o[7]+((k>>>11|M<<5)&8191),_=o[8]+((M>>>8|U<<8)&8191),C=o[9]+(U>>>5|s),v=0,I=v+S*a+L*(5*g)+R*(5*w)+T*(5*p)+m*(5*d);v=I>>>13,I&=8191,I+=y*(5*h)+b*(5*l)+A*(5*u)+_*(5*f)+C*(5*c),v+=I>>>13,I&=8191;let D=v+S*c+L*a+R*(5*g)+T*(5*w)+m*(5*p);v=D>>>13,D&=8191,D+=y*(5*d)+b*(5*h)+A*(5*l)+_*(5*u)+C*(5*f),v+=D>>>13,D&=8191;let O=v+S*f+L*c+R*a+T*(5*g)+m*(5*w);v=O>>>13,O&=8191,O+=y*(5*p)+b*(5*d)+A*(5*h)+_*(5*l)+C*(5*u),v+=O>>>13,O&=8191;let z=v+S*u+L*f+R*c+T*a+m*(5*g);v=z>>>13,z&=8191,z+=y*(5*w)+b*(5*p)+A*(5*d)+_*(5*h)+C*(5*l),v+=z>>>13,z&=8191;let F=v+S*l+L*u+R*f+T*c+m*a;v=F>>>13,F&=8191,F+=y*(5*g)+b*(5*w)+A*(5*p)+_*(5*d)+C*(5*h),v+=F>>>13,F&=8191;let V=v+S*h+L*l+R*u+T*f+m*c;v=V>>>13,V&=8191,V+=y*a+b*(5*g)+A*(5*w)+_*(5*p)+C*(5*d),v+=V>>>13,V&=8191;let $=v+S*d+L*h+R*l+T*u+m*f;v=$>>>13,$&=8191,$+=y*c+b*a+A*(5*g)+_*(5*w)+C*(5*p),v+=$>>>13,$&=8191;let X=v+S*p+L*d+R*h+T*l+m*u;v=X>>>13,X&=8191,X+=y*f+b*c+A*a+_*(5*g)+C*(5*w),v+=X>>>13,X&=8191;let it=v+S*w+L*p+R*d+T*h+m*l;v=it>>>13,it&=8191,it+=y*u+b*f+A*c+_*a+C*(5*g),v+=it>>>13,it&=8191;let G=v+S*g+L*w+R*p+T*d+m*h;v=G>>>13,G&=8191,G+=y*l+b*u+A*f+_*c+C*a,v+=G>>>13,G&=8191,v=(v<<2)+v|0,v=v+I|0,I=v&8191,v=v>>>13,D+=v,o[0]=I,o[1]=D,o[2]=O,o[3]=z,o[4]=F,o[5]=V,o[6]=$,o[7]=X,o[8]=it,o[9]=G}finalize(){let{h:t,pad:r}=this,n=new Uint16Array(10),s=t[1]>>>13;t[1]&=8191;for(let a=2;a<10;a++)t[a]+=s,s=t[a]>>>13,t[a]&=8191;t[0]+=s*5,s=t[0]>>>13,t[0]&=8191,t[1]+=s,s=t[1]>>>13,t[1]&=8191,t[2]+=s,n[0]=t[0]+5,s=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=t[a]+s,s=n[a]>>>13,n[a]&=8191;n[9]-=8192;let o=(s^1)-1;for(let a=0;a<10;a++)n[a]&=o;o=~o;for(let a=0;a<10;a++)t[a]=t[a]&o|n[a];t[0]=(t[0]|t[1]<<13)&65535,t[1]=(t[1]>>>3|t[2]<<10)&65535,t[2]=(t[2]>>>6|t[3]<<7)&65535,t[3]=(t[3]>>>9|t[4]<<4)&65535,t[4]=(t[4]>>>12|t[5]<<1|t[6]<<14)&65535,t[5]=(t[6]>>>2|t[7]<<11)&65535,t[6]=(t[7]>>>5|t[8]<<8)&65535,t[7]=(t[8]>>>8|t[9]<<5)&65535;let i=t[0]+r[0];t[0]=i&65535;for(let a=1;a<8;a++)i=(t[a]+r[a]|0)+(i>>>16)|0,t[a]=i&65535;he(n)}update(t){Xi(this),t=ws(t),Bt(t);let{buffer:r,blockLen:n}=this,s=t.length;for(let o=0;o<s;){let i=Math.min(n-this.pos,s-o);if(i===n){for(;n<=s-o;o+=n)this.process(t,o);continue}r.set(t.subarray(o,o+i),this.pos),this.pos+=i,o+=i,this.pos===n&&(this.process(r,0,!1),this.pos=0)}return this}destroy(){he(this.h,this.r,this.buffer,this.pad)}digestInto(t){Xi(this),Zu(t,this),this.finished=!0;let{buffer:r,h:n}=this,{pos:s}=this;if(s){for(r[s++]=1;s<16;s++)r[s]=0;this.process(r,0,!0)}this.finalize();let o=0;for(let i=0;i<8;i++)t[o++]=n[i]>>>0,t[o++]=n[i]>>>8;return t}digest(){let{buffer:t,outputLen:r}=this;this.digestInto(t);let n=t.slice(0,r);return this.destroy(),n}};function wp(e){let t=(n,s)=>e(s).update(ws(n)).digest(),r=e(new Uint8Array(32));return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=n=>e(n),t}var rf=wp(e=>new ra(e));function of(e,t,r,n,s,o=20){let i=e[0],a=e[1],c=e[2],f=e[3],u=t[0],l=t[1],h=t[2],d=t[3],p=t[4],w=t[5],g=t[6],x=t[7],B=s,E=r[0],P=r[1],N=r[2],k=i,M=a,U=c,S=f,L=u,R=l,T=h,m=d,y=p,b=w,A=g,_=x,C=B,v=E,I=P,D=N;for(let z=0;z<o;z+=2)k=k+L|0,C=K(C^k,16),y=y+C|0,L=K(L^y,12),k=k+L|0,C=K(C^k,8),y=y+C|0,L=K(L^y,7),M=M+R|0,v=K(v^M,16),b=b+v|0,R=K(R^b,12),M=M+R|0,v=K(v^M,8),b=b+v|0,R=K(R^b,7),U=U+T|0,I=K(I^U,16),A=A+I|0,T=K(T^A,12),U=U+T|0,I=K(I^U,8),A=A+I|0,T=K(T^A,7),S=S+m|0,D=K(D^S,16),_=_+D|0,m=K(m^_,12),S=S+m|0,D=K(D^S,8),_=_+D|0,m=K(m^_,7),k=k+R|0,D=K(D^k,16),A=A+D|0,R=K(R^A,12),k=k+R|0,D=K(D^k,8),A=A+D|0,R=K(R^A,7),M=M+T|0,C=K(C^M,16),_=_+C|0,T=K(T^_,12),M=M+T|0,C=K(C^M,8),_=_+C|0,T=K(T^_,7),U=U+m|0,v=K(v^U,16),y=y+v|0,m=K(m^y,12),U=U+m|0,v=K(v^U,8),y=y+v|0,m=K(m^y,7),S=S+L|0,I=K(I^S,16),b=b+I|0,L=K(L^b,12),S=S+L|0,I=K(I^S,8),b=b+I|0,L=K(L^b,7);let O=0;n[O++]=i+k|0,n[O++]=a+M|0,n[O++]=c+U|0,n[O++]=f+S|0,n[O++]=u+L|0,n[O++]=l+R|0,n[O++]=h+T|0,n[O++]=d+m|0,n[O++]=p+y|0,n[O++]=w+b|0,n[O++]=g+A|0,n[O++]=x+_|0,n[O++]=B+C|0,n[O++]=E+v|0,n[O++]=P+I|0,n[O++]=N+D|0}function Ep(e,t,r,n){let s=e[0],o=e[1],i=e[2],a=e[3],c=t[0],f=t[1],u=t[2],l=t[3],h=t[4],d=t[5],p=t[6],w=t[7],g=r[0],x=r[1],B=r[2],E=r[3];for(let N=0;N<20;N+=2)s=s+c|0,g=K(g^s,16),h=h+g|0,c=K(c^h,12),s=s+c|0,g=K(g^s,8),h=h+g|0,c=K(c^h,7),o=o+f|0,x=K(x^o,16),d=d+x|0,f=K(f^d,12),o=o+f|0,x=K(x^o,8),d=d+x|0,f=K(f^d,7),i=i+u|0,B=K(B^i,16),p=p+B|0,u=K(u^p,12),i=i+u|0,B=K(B^i,8),p=p+B|0,u=K(u^p,7),a=a+l|0,E=K(E^a,16),w=w+E|0,l=K(l^w,12),a=a+l|0,E=K(E^a,8),w=w+E|0,l=K(l^w,7),s=s+f|0,E=K(E^s,16),p=p+E|0,f=K(f^p,12),s=s+f|0,E=K(E^s,8),p=p+E|0,f=K(f^p,7),o=o+u|0,g=K(g^o,16),w=w+g|0,u=K(u^w,12),o=o+u|0,g=K(g^o,8),w=w+g|0,u=K(u^w,7),i=i+l|0,x=K(x^i,16),h=h+x|0,l=K(l^h,12),i=i+l|0,x=K(x^i,8),h=h+x|0,l=K(l^h,7),a=a+c|0,B=K(B^a,16),d=d+B|0,c=K(c^d,12),a=a+c|0,B=K(B^a,8),d=d+B|0,c=K(c^d,7);let P=0;n[P++]=s,n[P++]=o,n[P++]=i,n[P++]=a,n[P++]=g,n[P++]=x,n[P++]=B,n[P++]=E}var Sp=ea(of,{counterRight:!1,counterLength:4,allowShortKeys:!1}),vp=ea(of,{counterRight:!1,counterLength:8,extendNonceFn:Ep,allowShortKeys:!1});var Ap=new Uint8Array(16),nf=(e,t)=>{e.update(t);let r=t.length%16;r&&e.update(Ap.subarray(r))},Bp=new Uint8Array(32);function sf(e,t,r,n,s){let o=e(t,r,Bp),i=rf.create(o);s&&nf(i,s),nf(i,n);let a=Qu(n.length,s?s.length:0,!0);i.update(a);let c=i.digest();return he(o,a),c}var af=e=>(t,r,n)=>({encrypt(o,i){let a=o.length;i=Ji(a+16,i,!1),i.set(o);let c=i.subarray(0,-16);e(t,r,c,c,1);let f=sf(e,t,r,c,n);return i.set(f,a),he(f),i},decrypt(o,i){i=Ji(o.length-16,i,!1);let a=o.subarray(0,-16),c=o.subarray(-16),f=sf(e,t,r,a,n);if(!Xu(c,f))throw new Error("invalid tag");return i.set(o.subarray(0,-16)),e(t,r,i,i,1),he(f),i}}),na=Qi({blockSize:64,nonceLength:12,tagLength:16},af(Sp)),h1=Qi({blockSize:64,nonceLength:24,tagLength:16},af(vp));function uf(e,t,r){return Oe(e),r===void 0&&(r=new Uint8Array(e.outputLen)),Er(e,ge(r),ge(t))}var sa=Uint8Array.from([0]),cf=Uint8Array.of();function ff(e,t,r,n=32){Oe(e),Re(n);let s=e.outputLen;if(n>255*s)throw new Error("Length should be <= 255*HashLen");let o=Math.ceil(n/s);r===void 0&&(r=cf);let i=new Uint8Array(o*s),a=Er.create(e,t),c=a._cloneInto(),f=new Uint8Array(a.outputLen);for(let u=0;u<o;u++)sa[0]=u+1,c.update(u===0?cf:f).update(r).update(sa).digestInto(f),i.set(f,s*u),a._cloneInto(c);return a.destroy(),c.destroy(),Ht(f,sa),i.slice(0,n)}var oa={hashSHA256(e){return Se(e.subarray())},getHKDF(e,t){let r=uf(Se,t,e),s=ff(Se,r,void 0,96),o=s.subarray(0,32),i=s.subarray(32,64),a=s.subarray(64,96);return[o,i,a]},generateX25519KeyPair(){let e=en.utils.randomSecretKey();return{publicKey:en.getPublicKey(e),privateKey:e}},generateX25519KeyPairFromSeed(e){return{publicKey:en.getPublicKey(e),privateKey:e}},generateX25519SharedKey(e,t){return en.getSharedSecret(e.subarray(),t.subarray())},chaCha20Poly1305Encrypt(e,t,r,n){return na(n,t,r).encrypt(e.subarray())},chaCha20Poly1305Decrypt(e,t,r,n,s){return na(n,t,r).decrypt(e.subarray(),s)}};var lf=oa;function hf(e){return{generateKeypair:e.generateX25519KeyPair,dh:(t,r)=>e.generateX25519SharedKey(t.privateKey,r).subarray(0,32),encrypt:e.chaCha20Poly1305Encrypt,decrypt:e.chaCha20Poly1305Decrypt,hash:e.hashSHA256,hkdf:e.getHKDF}}var Dr=e=>{let t=gt(2);return t[0]=e>>8,t[1]=e,t};Dr.bytes=2;var Pr=e=>{if(e.length<2)throw RangeError("Could not decode int16BE");if(e instanceof Uint8Array){let t=0;return t+=e[0]<<8,t+=e[1],t}return e.getUint16(0)};Pr.bytes=2;function df(e){return{xxHandshakeSuccesses:e.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:e.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:e.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:e.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:e.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}function ia(e,t){!t.enabled||!Tr||(e?(t(`LOCAL_STATIC_PUBLIC_KEY ${q(e.publicKey,"hex")}`),t(`LOCAL_STATIC_PRIVATE_KEY ${q(e.privateKey,"hex")}`)):t("Missing local static keys."))}function aa(e,t){!t.enabled||!Tr||(e?(t(`LOCAL_PUBLIC_EPHEMERAL_KEY ${q(e.publicKey,"hex")}`),t(`LOCAL_PRIVATE_EPHEMERAL_KEY ${q(e.privateKey,"hex")}`)):t("Missing local ephemeral keys."))}function pf(e,t){!t.enabled||!Tr||t(e?`REMOTE_STATIC_PUBLIC_KEY ${q(e.subarray(),"hex")}`:"Missing remote static public key.")}function ca(e,t){!t.enabled||!Tr||t(e?`REMOTE_EPHEMERAL_PUBLIC_KEY ${q(e.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function ua(e,t,r){!r.enabled||!Tr||(r(`CIPHER_STATE_1 ${e.n.getUint64()} ${e.k&&q(e.k,"hex")}`),r(`CIPHER_STATE_2 ${t.n.getUint64()} ${t.k&&q(t.k,"hex")}`))}var Rr=class e extends Error{code;constructor(t="Invalid crypto exchange"){super(t),this.code=e.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};var _p=0,Ip=4294967295,Cp="Cipher state has reached maximum n, a new handshake must be performed",vs=class{n;bytes;view;constructor(t=_p){this.n=t,this.bytes=ht(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,t,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>Ip)throw new Error(Cp)}};var Ye=ht(0),Or=class{k;n;crypto;constructor(t,r=void 0,n=0){this.crypto=t,this.k=r,this.n=new vs(n)}hasKey(){return!!this.k}encryptWithAd(t,r){if(!this.hasKey())return r;this.n.assertValue();let n=this.crypto.encrypt(r,this.n.getBytes(),t,this.k);return this.n.increment(),n}decryptWithAd(t,r,n){if(!this.hasKey())return r;this.n.assertValue();let s=this.crypto.decrypt(r,this.n.getBytes(),t,this.k,n);return this.n.increment(),s}},fa=class{cs;ck;h;crypto;constructor(t,r){this.crypto=t;let n=Z(r,"utf-8");this.h=Lp(t,n),this.ck=this.h,this.cs=new Or(t)}mixKey(t){let[r,n]=this.crypto.hkdf(this.ck,t);this.ck=r,this.cs=new Or(this.crypto,n)}mixHash(t){this.h=this.crypto.hash(new j(this.h,t))}encryptAndHash(t){let r=this.cs.encryptWithAd(this.h,t);return this.mixHash(r),r}decryptAndHash(t){let r=this.cs.decryptWithAd(this.h,t);return this.mixHash(t),r}split(){let[t,r]=this.crypto.hkdf(this.ck,Ye);return[new Or(this.crypto,t),new Or(this.crypto,r)]}},la=class{ss;s;e;rs;re;initiator;crypto;constructor(t){let{crypto:r,protocolName:n,prologue:s,initiator:o,s:i,e:a,rs:c,re:f}=t;this.crypto=r,this.ss=new fa(r,n),this.ss.mixHash(s),this.initiator=o,this.s=i,this.e=a,this.rs=c,this.re=f}writeE(){if(this.e)throw new Error("ephemeral keypair is already set");let t=this.crypto.generateKeypair();return this.ss.mixHash(t.publicKey),this.e=t,t.publicKey}writeS(){if(!this.s)throw new Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.re))}writeES(){if(this.initiator){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}}writeSE(){if(this.initiator){if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(t,r=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(t.byteLength<r+32)throw new Error("message is not long enough");this.re=t.sublist(r,r+32),this.ss.mixHash(this.re)}readS(t,r=0){if(this.rs)throw new Error("remote static public key is already set");let n=32+(this.ss.cs.hasKey()?16:0);if(t.byteLength<r+n)throw new Error("message is not long enough");let s=t.sublist(r,r+n);return this.rs=this.ss.decryptAndHash(s),n}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}},gn=class extends la{writeMessageA(t){return new j(this.writeE(),this.ss.encryptAndHash(t))}writeMessageB(t){let r=this.writeE();this.writeEE();let n=this.writeS();return this.writeES(),new j(r,n,this.ss.encryptAndHash(t))}writeMessageC(t){let r=this.writeS();return this.writeSE(),new j(r,this.ss.encryptAndHash(t))}readMessageA(t){try{return this.readE(t),this.ss.decryptAndHash(t.sublist(32))}catch(r){throw new Rr(`handshake stage 0 validation fail: ${r.message}`)}}readMessageB(t){try{this.readE(t),this.readEE();let r=this.readS(t,32);return this.readES(),this.ss.decryptAndHash(t.sublist(32+r))}catch(r){throw new Rr(`handshake stage 1 validation fail: ${r.message}`)}}readMessageC(t){try{let r=this.readS(t);return this.readSE(),this.ss.decryptAndHash(t.sublist(r))}catch(r){throw new Rr(`handshake stage 2 validation fail: ${r.message}`)}}};function Lp(e,t){if(t.length<=32){let r=ht(32);return r.set(t),r}else return e.hash(t)}var As;(function(e){let t;e.codec=()=>(t==null&&(t=We((r,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),r.webtransportCerthashes!=null)for(let o of r.webtransportCerthashes)n.uint32(10),n.bytes(o);if(r.streamMuxers!=null)for(let o of r.streamMuxers)n.uint32(18),n.string(o);s.lengthDelimited!==!1&&n.ldelim()},(r,n,s={})=>{let o={webtransportCerthashes:[],streamMuxers:[]},i=n==null?r.len:r.pos+n;for(;r.pos<i;){let a=r.uint32();switch(a>>>3){case 1:{if(s.limits?.webtransportCerthashes!=null&&o.webtransportCerthashes.length===s.limits.webtransportCerthashes)throw new on('Decode error - map field "webtransportCerthashes" had too many elements');o.webtransportCerthashes.push(r.bytes());break}case 2:{if(s.limits?.streamMuxers!=null&&o.streamMuxers.length===s.limits.streamMuxers)throw new on('Decode error - map field "streamMuxers" had too many elements');o.streamMuxers.push(r.string());break}default:{r.skipType(a&7);break}}}return o})),t),e.encode=r=>Fe(r,e.codec()),e.decode=(r,n)=>qe(r,e.codec(),n)})(As||(As={}));var bn;(function(e){let t;e.codec=()=>(t==null&&(t=We((r,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),r.identityKey!=null&&r.identityKey.byteLength>0&&(n.uint32(10),n.bytes(r.identityKey)),r.identitySig!=null&&r.identitySig.byteLength>0&&(n.uint32(18),n.bytes(r.identitySig)),r.extensions!=null&&(n.uint32(34),As.codec().encode(r.extensions,n)),s.lengthDelimited!==!1&&n.ldelim()},(r,n,s={})=>{let o={identityKey:ht(0),identitySig:ht(0)},i=n==null?r.len:r.pos+n;for(;r.pos<i;){let a=r.uint32();switch(a>>>3){case 1:{o.identityKey=r.bytes();break}case 2:{o.identitySig=r.bytes();break}case 4:{o.extensions=As.codec().decode(r,r.uint32(),{limits:s.limits?.extensions});break}default:{r.skipType(a&7);break}}}return o})),t),e.encode=r=>Fe(r,e.codec()),e.decode=(r,n)=>qe(r,e.codec(),n)})(bn||(bn={}));async function da(e,t,r){let n=await e.sign(yf(t));return bn.encode({identityKey:ye(e.publicKey),identitySig:n,extensions:r})}async function pa(e,t,r){try{let n=bn.decode(e),s=un(n.identityKey);if(r?.equals(s)===!1)throw new Error(`Payload identity key ${s} does not match expected remote identity key ${r}`);if(!t)throw new Error("Remote static does not exist");let o=yf(t);if(!await s.verify(o,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new En(n.message)}}function yf(e){let t=Z("noise-libp2p-static-key:");return e instanceof Uint8Array?Ot([t,e],t.length+e.length):(e.prepend(t),e)}var ha=class extends $t{stream;handshake;metrics;decoder;constructor(t,r,n){super({log:t.log,inactivityTimeout:t.inactivityTimeout,maxReadBufferLength:t.maxReadBufferLength,direction:t.direction}),this.stream=t,this.handshake=r,this.metrics=n,this.decoder=new gs({lengthDecoder:Pr,maxBufferSize:16*1024*1024,encodingLength:()=>2});let s=c=>{try{for(let f of this.decoder.decode(c.data))this.onData(this.decrypt(f))}catch(f){this.abort(f)}};this.stream.addEventListener("message",s);let o=c=>{c.error!=null?c.local===!0?this.abort(c.error):this.onRemoteReset():this.onTransportClosed()};this.stream.addEventListener("close",o);let i=()=>{this.safeDispatchEvent("drain")};this.stream.addEventListener("drain",i);let a=()=>{this.onRemoteCloseWrite()};this.stream.addEventListener("remoteCloseWrite",a)}encrypt(t){let r=new j;for(let n=0;n<t.byteLength;n+=65519){let s=n+65519;s>t.byteLength&&(s=t.byteLength);let o;t instanceof Uint8Array?o=this.handshake.encrypt(t.subarray(n,s)):o=this.handshake.encrypt(t.sublist(n,s)),this.metrics?.encryptedPackets.increment(),r.append(Dr(o.byteLength)),r.append(o)}return r}decrypt(t){let r=new j;for(let n=0;n<t.byteLength;n+=65535){let s=n+65535;if(s>t.byteLength&&(s=t.byteLength),s-Yi<n)throw new Error("Invalid chunk");let o;t instanceof Uint8Array?o=t.subarray(n,s):o=t.sublist(n,s);let i=t.subarray(n,s-Yi);try{let a=this.handshake.decrypt(o,i);this.metrics?.decryptedPackets.increment(),r.append(a)}catch(a){throw this.metrics?.decryptErrors.increment(),a}}return r}close(t){return this.stream.close(t)}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}sendReset(t){this.stream.abort(t)}sendData(t){return{sentBytes:t.byteLength,canSendMore:this.stream.send(this.encrypt(t))}}};function ma(e,t,r){return new ha(e,t,r)}async function gf(e,t){let{log:r,connection:n,crypto:s,privateKey:o,prologue:i,s:a,remoteIdentityKey:c,extensions:f}=e,u=await da(o,a.publicKey,f),l=new gn({crypto:s,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});ia(l.s,r),r.trace("Stage 0 - Initiator starting to send first message."),await n.write(l.writeMessageA(Ye),t),r.trace("Stage 0 - Initiator finished sending first message."),aa(l.e,r),r.trace("Stage 1 - Initiator waiting to receive first message from responder...");let h=l.readMessageB(await n.read(t));r.trace("Stage 1 - Initiator received the message."),ca(l.re,r),pf(l.rs,r),r.trace("Initiator going to check remote's signature...");let d=await pa(h,l.rs,c);r.trace("All good with the signature!"),r.trace("Stage 2 - Initiator sending third handshake message."),await n.write(l.writeMessageC(u),t),r.trace("Stage 2 - Initiator sent message with signed payload.");let[p,w]=l.ss.split();return ua(p,w,r),{payload:d,encrypt:g=>p.encryptWithAd(Ye,g),decrypt:(g,x)=>w.decryptWithAd(Ye,g,x)}}async function bf(e,t){let{log:r,connection:n,crypto:s,privateKey:o,prologue:i,s:a,remoteIdentityKey:c,extensions:f}=e,u=await da(o,a.publicKey,f),l=new gn({crypto:s,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});ia(l.s,r),r.trace("Stage 0 - Responder waiting to receive first message."),l.readMessageA(await n.read(t)),r.trace("Stage 0 - Responder received first message."),ca(l.re,r),r.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(l.writeMessageB(u),t),r.trace("Stage 1 - Responder sent the second handshake message with signed payload."),aa(l.e,r),r.trace("Stage 2 - Responder waiting for third handshake message...");let h=l.readMessageC(await n.read(t));r.trace("Stage 2 - Responder received the message, finished handshake.");let d=await pa(h,l.rs,c),[p,w]=l.ss.split();return ua(p,w,r),{payload:d,encrypt:g=>w.encryptWithAd(Ye,g),decrypt:(g,x)=>p.decryptWithAd(Ye,g,x)}}var Bs=class{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;log;constructor(t,r={}){let{staticNoiseKey:n,extensions:s,crypto:o,prologueBytes:i}=r,{metrics:a}=t;this.components=t,this.log=t.logger.forComponent("libp2p:noise");let c=o??lf;this.crypto=hf(c),this.extensions={webtransportCerthashes:[],...s},this.metrics=a?df(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??ht(0)}[Symbol.toStringTag]="@libp2p/noise";[Ln]=["@libp2p/connection-encryption","@libp2p/noise"];async secureOutbound(t,r){let n=t.log?.newScope("noise")??this.log,s=Zi(t,{lengthEncoder:Dr,lengthDecoder:Pr,maxDataLength:65535}),o=await this.performHandshakeInitiator(s,this.components.privateKey,n,r?.remotePeer?.publicKey,r),i=un(o.payload.identityKey);return{connection:ma(s.unwrap(),o,this.metrics),remoteExtensions:o.payload.extensions,remotePeer:gi(i),streamMuxer:r?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(o.payload.extensions?.streamMuxers)}}getStreamMuxer(t){if(t==null||t.length===0)return;let r=this.components.upgrader.getStreamMuxers();if(r!=null)for(let n of t){let s=r.get(n);if(s!=null)return s}if(t.length)throw new tr("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(t,r){let n=t.log?.newScope("noise")??this.log,s=Zi(t,{lengthEncoder:Dr,lengthDecoder:Pr,maxDataLength:65535}),o=await this.performHandshakeResponder(s,this.components.privateKey,n,r?.remotePeer?.publicKey,r),i=un(o.payload.identityKey);return{connection:ma(s.unwrap(),o,this.metrics),remoteExtensions:o.payload.extensions,remotePeer:gi(i),streamMuxer:r?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(o.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(t,r,n,s,o){let i,a=o?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await gf({connection:t,privateKey:r,remoteIdentityKey:s,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},o),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}async performHandshakeResponder(t,r,n,s,o){let i,a=o?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await bf({connection:t,privateKey:r,remoteIdentityKey:s,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},o),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}};function xf(e={}){return t=>new Bs(t,e)}var st=e=>({match:t=>{let r=t[0];return r==null||r.code!==e||r.value!=null?!1:t.slice(1)}}),H=(e,t)=>({match:r=>{let n=r[0];return n?.code!==e||n.value==null||t!=null&&n.value!==t?!1:r.slice(1)}}),wf=e=>({match:t=>e.match(t)===!1?t:!1}),W=e=>({match:t=>{let r=e.match(t);return r===!1?t:r}}),_t=(...e)=>({match:t=>{let r;for(let n of e){let s=n.match(t);s!==!1&&(r==null||s.length<r.length)&&(r=s)}return r??!1}}),J=(...e)=>({match:t=>{for(let r of e){let n=r.match(t);if(n===!1)return!1;t=n}return t}});function ot(...e){function t(s){if(s==null)return!1;let o=s.getComponents();for(let i of e){let a=i.match(o);if(a===!1)return!1;o=a}return o}function r(s){return t(s)!==!1}function n(s){let o=t(s);return o===!1?!1:o.length===0}return{matchers:e,matches:r,exactMatch:n}}var Tp=H(421),K2=ot(Tp),Is=H(54),Cs=H(55),Ls=H(56),ga=H(53),N2=ot(Is,W(H(421))),M2=ot(Cs,W(H(421))),k2=ot(Ls,W(H(421))),H2=ot(_t(ga,Ls,Is,Cs),W(H(421))),Ef=J(H(4),W(H(43))),Sf=J(W(H(42)),H(41),W(H(43))),ba=_t(Ef,Sf),Xe=_t(ba,ga,Is,Cs,Ls),V2=ot(_t(ba,J(_t(ga,Ls,Is,Cs),W(H(421))))),q2=ot(Ef),z2=ot(Sf),F2=ot(ba),xa=J(Xe,H(6)),wn=J(Xe,H(273)),W2=ot(J(xa,W(H(421)))),$2=ot(wn),wa=J(wn,st(460),W(H(421))),Ts=J(wn,st(461),W(H(421))),Dp=_t(wa,Ts),G2=ot(wa),j2=ot(Ts),ya=_t(Xe,xa,wn,wa,Ts),vf=_t(J(ya,st(477),W(H(421)))),Z2=ot(vf),Af=_t(J(ya,st(478),W(H(421))),J(ya,st(448),W(H(449)),st(477),W(H(421)))),Y2=ot(Af),Bf=J(wn,st(280),W(H(466)),W(H(466)),W(H(421))),X2=ot(Bf),_f=J(Ts,st(465),W(H(466)),W(H(466)),W(H(421))),Ds=ot(_f),_s=_t(vf,Af,J(xa,W(H(421))),J(Dp,W(H(421))),J(Xe,W(H(421))),Bf,_f,H(421)),Q2=ot(_s),Pp=J(W(_s),st(290),wf(st(281)),W(H(421))),J2=ot(Pp),Rp=_t(J(_s,st(290),st(281),W(H(421))),J(_s,st(281),W(H(421))),J(st(281),W(H(421)))),tE=ot(Rp),Op=_t(J(Xe,H(6),st(480),W(H(421))),J(Xe,st(480),W(H(421)))),eE=ot(Op),Up=J(Xe,_t(J(H(6,"443"),st(480)),J(H(6),st(443)),J(H(6),st(448),st(480)),J(st(448),st(480)),st(448),st(443)),W(H(421))),rE=ot(Up),Kp=_t(J(H(777),W(H(421)))),nE=ot(Kp),Np=_t(J(H(400),W(H(421)))),sE=ot(Np);var Qe=class extends Event{type;detail;constructor(t,r){super(t),this.type=t,this.detail=r}};function Ea(e){throw new Error("Not implemented")}var Sa=class extends us{writer;reader;constructor(t){super(t),this.writer=t.stream.writable.getWriter(),this.reader=t.stream.readable.getReader(),this.writer.closed.then(()=>{this.log("writer closed gracefully")}).catch(r=>{r.message.includes("STOP_SENDING")||r.message.includes("StopSending")?this.onRemoteCloseRead():r.message.includes("RESET_STREAM")||r.message.includes("Reset")?this.onRemoteReset():this.log("writer close promise rejected - %e",r)}),this.readData()}readData(){Promise.resolve().then(async()=>{for(;;){let t=await this.reader.read();if(t.value!=null&&this.onData(t.value),t.done){this.log("remote closed write"),this.onRemoteCloseWrite();return}if(this.readStatus==="paused")break}}).catch(t=>{this.abort(t)}).finally(()=>{this.reader.releaseLock()})}sendData(t){for(let n of t)this.writer.write(n).catch(s=>{this.abort(s)});if(this.log.trace("desired size after sending %d bytes is %d bytes",t.byteLength,this.writer.desiredSize),this.writer.desiredSize==null)return{sentBytes:t.byteLength,canSendMore:!1};let r=this.writer.desiredSize>0;return r||this.writer.ready.then(()=>{this.safeDispatchEvent("drain")},n=>{this.abort(n)}),{sentBytes:t.byteLength,canSendMore:r}}sendReset(t){this.writer.abort(t).catch(r=>{this.log.error("error aborting writer - %e",r)})}async sendCloseWrite(t){this.log("sendCloseWrite closing writer"),await ce(this.writer.close().catch(()=>{}),t?.signal),this.log("sendCloseWrite closed writer")}async sendCloseRead(t){this.log("sendCloseRead cancelling reader"),await ce(this.reader.cancel(),t?.signal),this.log("sendCloseRead cancelled reader")}sendPause(){}sendResume(){this.readData()}};function va(e,t,r,n,s){return new Sa({...s,stream:e,id:t,direction:r,log:n.newScope(`${r}:${t}`),protocol:""})}var If="/webtransport",Aa=class extends cs{webTransport;streamIDCounter;reader;constructor(t,r){super(r,{protocol:If,name:"muxer"}),this.webTransport=t,this.streamIDCounter=0,this.reader=this.webTransport.incomingBidirectionalStreams.getReader(),Promise.resolve().then(async()=>{for(;;){let{done:n,value:s}=await this.reader.read();if(n||s==null)break;this.onRemoteStream(va(s,String(this.streamIDCounter++),"inbound",this.log,this.streamOptions))}}).catch(n=>{this.log.error("could not create a new stream - %e",n)})}async onCreateStream(t){let r=await this.webTransport.createBidirectionalStream();return t?.signal?.throwIfAborted(),va(r,String(this.streamIDCounter++),"outbound",this.log,t)}onData(){}sendReset(){this.webTransport.close()}};function Cf(e){return{protocol:If,createStreamMuxer(t){return new Aa(e,t)}}}var Ba=class extends as{cleanUpWTSession;constructor(t){super(t),this.cleanUpWTSession=t.cleanUpWTSession}sendData(t){return{sentBytes:t.byteLength,canSendMore:!0}}sendReset(){this.cleanUpWTSession("abort")}async sendClose(t){this.cleanUpWTSession("close"),t?.signal?.throwIfAborted()}sendPause(){}sendResume(){}},Lf=e=>new Ba(e);function Tf(e,t){return t.filter(n=>!!e.find(s=>lt(n,s))).length===t.length}var Mp=Object.values(De).map(e=>e.decoder).reduce((e,t)=>e.or(t));function kp(e){return jt.decode(Mp.decode(e))}function _a(e){if(!Ds.matches(e))throw new Mr("Invalid multiaddr, was not a WebTransport address");let t=[],r;for(let o of e.getComponents())o.name==="certhash"&&t.push(kp(o.value??"")),o.name==="p2p"&&r==null&&(r=Bu(o.value??""));if(r==null)throw new Mr("Remote peer must be present in multiaddr");let n=Iu(e),s=n.host;return n.type==="ip6"&&s.includes(":")&&(s=`[${s}]`),{url:`https://${s}:${n.port}`,certhashes:t,remotePeer:r}}var Ps=class extends $t{writer;reader;constructor(t){super(t),this.writer=t.stream.writable.getWriter(),this.reader=t.stream.readable.getReader(),Promise.resolve().then(async()=>{for(;;){let{done:r,value:n}=await this.reader.read();if(n!=null&&this.onData(n),r)break}}).catch(r=>{this.abort(r)})}async close(t){await ce(this.writer.close(),t?.signal)}sendData(t){return this.writer.write(t.subarray()).catch(r=>{this.abort(r)}),{sentBytes:t.byteLength,canSendMore:!0}}sendReset(t){this.writer.abort(t).catch(r=>{this.log.error("could not send reset - %e",r)})}sendPause(){}sendResume(){}};var Df=globalThis.WebTransport;var Ia=class{log;components;config;metrics;constructor(t,r={}){this.log=t.logger.forComponent("libp2p:webtransport"),this.components=t,this.config={...r,certificates:r.certificates??[]},t.metrics!=null&&(this.metrics={dialerEvents:t.metrics.registerCounterGroup("libp2p_webtransport_dialer_events_total",{label:"event",help:"Total count of WebTransport dialer events by type"})})}[Symbol.toStringTag]="@libp2p/webtransport";[Da]=!0;[Ln]=["@libp2p/transport"];async dial(t,r){r.signal.throwIfAborted(),this.log("dialing %s",t),r=r??{};let{url:n,certhashes:s,remotePeer:o}=_a(t),i,a,c=()=>{},f=!1,u=!1,l=!1;try{this.metrics?.dialerEvents.increment({pending:!0});let h=new Df(`${n}/.well-known/libp2p-webtransport?type=noise`,{serverCertificateHashes:s.map(d=>({algorithm:"sha-256",value:d.digest}))});if(c=d=>{if(!f)try{this.metrics?.dialerEvents.increment({[d]:!0}),h.close()}catch(p){this.log.error("error closing wt session",p)}finally{a!=null&&(a.timeline.close=Date.now()),f=!0}},i=()=>{c(u?"noise_timeout":"ready_timeout")},r.signal.addEventListener("abort",i,{once:!0}),this.log("wait for session to be ready"),r.onProgress?.(new Qe("webtransport:wait-for-session")),await Promise.race([h.closed,h.ready]),this.log("session became ready"),u=!0,this.metrics?.dialerEvents.increment({ready:!0}),h.closed.catch(d=>{this.log.error("error on remote wt session close",d)}).finally(()=>{c("remote_close")}),this.metrics?.dialerEvents.increment({open:!0}),a=Lf({remoteAddr:t,cleanUpWTSession:c,direction:"outbound",log:this.components.logger.forComponent("libp2p:webtransport:connection")}),l=await this.authenticateWebTransport({wt:h,maConn:a,remotePeer:o,certhashes:s,...r}),!l)throw new tr("Failed to authenticate webtransport");return await r.upgrader.upgradeOutbound(a,{...r,skipEncryption:!0,remotePeer:o,muxerFactory:Cf(h),skipProtection:!0})}catch(h){throw this.log.error("caught wt session err",h),c(l?"upgrade_error":u?"noise_error":"ready_error"),h}finally{i!=null&&r.signal?.removeEventListener("abort",i)}}async authenticateWebTransport({wt:t,maConn:r,remotePeer:n,certhashes:s,onProgress:o,signal:i}){o?.(new Qe("webtransport:open-authentication-stream"));let a=await t.createBidirectionalStream();i?.throwIfAborted();let c=new Ps({stream:a,log:r.log.newScope("muxer")}),f=xf()(this.components);o?.(new Qe("webtransport:secure-outbound-connection"));let{remoteExtensions:u}=await f.secureOutbound(c,{signal:i,remotePeer:n,skipStreamMuxerNegotiation:!0});if(o?.(new Qe("webtransport:close-authentication-stream")),await c.close({signal:i}),!Tf(u?.webtransportCerthashes??[],s.map(l=>l.bytes)))throw new et("Our certhashes are not a subset of the remote's reported certhashes");return!0}createListener(t){return Ea(this.components,{...t,certificates:this.config.certificates})}listenFilter(){return[]}dialFilter(t){return globalThis.WebTransport==null?[]:t.filter(r=>{if(!Ds.exactMatch(r))return!1;let{url:n,certhashes:s}=_a(r);return n!=null&&s.length>0})}};function Hp(e={}){return t=>new Ia(t,e)}return Kf(Vp);})();
3
3
  //! TODO unclear how to add backpressure here?
4
4
  /*! Bundled license information:
5
5