@libp2p/webrtc 6.0.30 → 6.0.31-5cb617ae2
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/README.md +2 -2
- package/dist/index.min.js +14 -14
- package/dist/index.min.js.map +4 -4
- package/dist/src/index.d.ts +2 -2
- package/dist/src/index.js +2 -2
- package/dist/src/private-to-public/utils/connect.js +1 -1
- package/dist/src/private-to-public/utils/connect.js.map +1 -1
- package/package.json +9 -9
- package/src/index.ts +2 -2
- package/src/private-to-public/utils/connect.ts +1 -1
- package/dist/typedoc-urls.json +0 -14
package/dist/index.min.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
(function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Libp2PWebrtc = factory()}(typeof self !== 'undefined' ? self : this, function () {
|
|
2
|
-
"use strict";var Libp2PWebrtc=(()=>{var Ai=Object.defineProperty;var lp=Object.getOwnPropertyDescriptor;var dp=Object.getOwnPropertyNames;var pp=Object.prototype.hasOwnProperty;var oe=(r,e)=>{for(var t in e)Ai(r,t,{get:e[t],enumerable:!0})},mp=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of dp(e))!pp.call(r,o)&&o!==t&&Ai(r,o,{get:()=>e[o],enumerable:!(n=lp(e,o))||n.enumerable});return r};var gp=r=>mp(Ai({},"__esModule",{value:!0}),r);var ew={};oe(ew,{webRTC:()=>Qb,webRTCDirect:()=>Jb});var Bo=class extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}},To=class extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}},W=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Ir=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var Do=class extends Error{static name="ConnectionFailedError";constructor(e="Connection failed"){super(e),this.name="ConnectionFailedError"}},_o=class extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}},Rr=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}};var it=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},En=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}};var Io=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},Ro=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Oo=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var Po=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var ir=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var No=class extends Event{data;constructor(e,t){super("message",t),this.data=e}},Or=class extends Event{error;local;constructor(e,t,n){super("close",n),this.error=t,this.local=e}},Uo=class extends Or{constructor(e,t){super(!0,e,t)}},Fo=class extends Or{constructor(e,t){super(!1,e,t)}};var vi=Symbol.for("@libp2p/peer-id");var ko=Symbol.for("@libp2p/transport");var eu;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(eu||(eu={}));function yp(r){return typeof r?.handleEvent=="function"}function bp(r){return r===!0||r===!1}function wp(r){return bp(r)?r:r?.capture??!1}function Ci(r){let e={capture:wp(r),once:!!r?.once};return r?.passive!=null&&(e.passive=r?.passive),r?.signal!=null&&(e.signal=r?.signal),e}function tu(r,e){return Ci(r).capture===Ci(e).capture}var Rt=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){let o=Ci(n);if(o?.signal?.aborted===!0)return;let s=f=>{o.once&&this.removeEventListener(e,t,o),yp(t)?t.handleEvent(f):t(f)},i=this.#e.get(e);if(i==null&&(i=[],this.#e.set(e,i)),i.some(f=>f.callback!==t?!1:tu(f.options,o)))return;super.addEventListener(e,s,o);let c=()=>{this.removeEventListener(e,t,o)};o.signal?.addEventListener("abort",c),i.push({callback:t,wrapper:s,options:o,onAbort:c})}removeEventListener(e,t,n){let o=this.#e.get(e);if(o==null){super.removeEventListener(e,t??null,n);return}this.#e.set(e,o.filter(s=>s.callback===t&&tu(s.options,n)?(super.removeEventListener(e,s.wrapper,n),s.options?.signal?.removeEventListener("abort",s.onAbort),!1):!0))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var Pr=Symbol.for("@libp2p/service-capabilities"),ru=Symbol.for("@libp2p/service-dependencies");var _i={};oe(_i,{base58btc:()=>de,base58flickr:()=>Bp});var Rw=new Uint8Array(0);function ou(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function je(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return ar(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return ar(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function su(r){let e=new Uint8Array(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}var nu=4096;function iu(r){let e=r.length;if(e<=nu)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.subarray(n,n+=nu));return t}function xp(r){return r?.buffer instanceof ArrayBuffer}function ar(r){return xp(r)?r:r.slice()}function Ep(r,e,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),o=0;o<n.length;o++)n[o]=255;for(var s=0;s<r.length;s++){var i=r.charAt(s),a=i.charCodeAt(0);if(n[a]!==255)throw new TypeError(i+" is ambiguous");if(n[a]=s,t){var c=i.toLowerCase().charCodeAt(0),f=i.toUpperCase().charCodeAt(0);c!==a&&(n[c]=s),f!==a&&(n[f]=s)}}var u=r.length,h=r.charAt(0),l=Math.log(u)/Math.log(256),d=Math.log(256)/Math.log(u);function b(m){if(m instanceof Uint8Array||(ArrayBuffer.isView(m)?m=new Uint8Array(m.buffer,m.byteOffset,m.byteLength):Array.isArray(m)&&(m=Uint8Array.from(m))),!(m instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(m.length===0)return"";for(var E=0,x=0,L=0,T=m.length;L!==T&&m[L]===0;)L++,E++;for(var F=(T-L)*d+1>>>0,O=new Uint8Array(F);L!==T;){for(var N=m[L],I=0,U=F-1;(N!==0||I<x)&&U!==-1;U--,I++)N+=256*O[U]>>>0,O[U]=N%u>>>0,N=N/u>>>0;if(N!==0)throw new Error("Non-zero carry");x=I,L++}for(var k=F-x;k!==F&&O[k]===0;)k++;for(var R=h.repeat(E);k<F;++k)R+=r.charAt(O[k]);return R}function w(m){if(typeof m!="string")throw new TypeError("Expected String");if(m.length===0)return new Uint8Array;var E=0;if(m[E]!==" "){for(var x=0,L=0;m[E]===h;)x++,E++;for(var T=(m.length-E)*l+1>>>0,F=new Uint8Array(T);m[E];){var O=n[m.charCodeAt(E)];if(O===255)return;for(var N=0,I=T-1;(O!==0||N<L)&&I!==-1;I--,N++)O+=u*F[I]>>>0,F[I]=O%256>>>0,O=O/256>>>0;if(O!==0)throw new Error("Non-zero carry");L=N,E++}if(m[E]!==" "){for(var U=T-L;U!==T&&F[U]===0;)U++;for(var k=new Uint8Array(x+(T-U)),R=x;U!==T;)k[R++]=F[U++];return k}}}function g(m){var E=w(m);if(E)return E;throw new Error(`Non-${e} character`)}return{encode:b,decodeUnsafe:w,decode:g}}var Sp=Ep,Ap=Sp,cu=Ap;var Li=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Bi=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return fu(this,e)}},Ti=class{decoders;constructor(e){this.decoders=e}or(e){return fu(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function fu(r,e){return new Ti({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Di=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new Li(e,t,n),this.decoder=new Bi(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Nr({name:r,prefix:e,encode:t,decode:n}){return new Di(r,e,t,n)}function Ot({name:r,prefix:e,alphabet:t,caseInsensitive:n=!1}){let{encode:o,decode:s}=cu(t,r,n);return Nr({prefix:e,name:r,encode:o,decode:i=>je(s(i))})}function vp(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let f=0;f<o;++f){let u=e[r[f]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function Cp(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function Lp(r,e){let t={};for(let n=0;n<r.length;++n)if(t[r[n]]=n,e){let o=r[n].toLowerCase(),s=r[n].toUpperCase();o!==r[n]&&(t[o]=n),s!==r[n]&&(t[s]=n)}return t}function le({name:r,prefix:e,bitsPerChar:t,alphabet:n,caseInsensitive:o=!1}){let s=Lp(n,o);return Nr({prefix:e,name:r,encode(i){return Cp(i,n,t)},decode(i){return vp(i,s,t,r)}})}var de=Ot({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Bp=Ot({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Ii={};oe(Ii,{base32:()=>Pt,base32hex:()=>Ip,base32hexpad:()=>Op,base32hexpadupper:()=>Pp,base32hexupper:()=>Rp,base32pad:()=>Dp,base32padupper:()=>_p,base32upper:()=>Tp,base32z:()=>Np});var Pt=le({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5,caseInsensitive:!0}),Tp=le({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5,caseInsensitive:!0}),Dp=le({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5,caseInsensitive:!0}),_p=le({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5,caseInsensitive:!0}),Ip=le({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5,caseInsensitive:!0}),Rp=le({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5,caseInsensitive:!0}),Op=le({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5,caseInsensitive:!0}),Pp=le({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5,caseInsensitive:!0}),Np=le({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Ri={};oe(Ri,{base36:()=>Sn,base36upper:()=>Up});var Sn=Ot({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz",caseInsensitive:!0}),Up=Ot({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",caseInsensitive:!0});var Je={};oe(Je,{Digest:()=>cr,create:()=>Pe,decode:()=>kr,equals:()=>Pi,hasCode:()=>tm});var Fp=lu,uu=128,kp=127,Mp=~kp,Kp=Math.pow(2,31);function lu(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Kp;)e[t++]=r&255|uu,r/=128;for(;r&Mp;)e[t++]=r&255|uu,r>>>=7;return e[t]=r|0,lu.bytes=t-n+1,e}var Hp=Oi,$p=128,hu=127;function Oi(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw Oi.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&hu)<<o:(i&hu)*Math.pow(2,o),o+=7}while(i>=$p);return Oi.bytes=s-n,t}var zp=Math.pow(2,7),Vp=Math.pow(2,14),qp=Math.pow(2,21),jp=Math.pow(2,28),Wp=Math.pow(2,35),Gp=Math.pow(2,42),Xp=Math.pow(2,49),Yp=Math.pow(2,56),Zp=Math.pow(2,63),Jp=function(r){return r<zp?1:r<Vp?2:r<qp?3:r<jp?4:r<Wp?5:r<Gp?6:r<Xp?7:r<Yp?8:r<Zp?9:10},Qp={encode:Fp,decode:Hp,encodingLength:Jp},em=Qp,An=em;function vn(r,e=0){let t=An.decode(r,e),n=An.decode.bytes;if(n>9)throw new RangeError("Invalid varint: too long");if(n>1&&r[e+n-1]===0)throw new RangeError("Invalid varint: not minimally encoded");return[t,n]}function Ur(r,e,t=0){return An.encode(r,e,t),e}function Fr(r){return An.encodingLength(r)}function Pe(r,e){let t=e.byteLength,n=Fr(r),o=n+Fr(t),s=new Uint8Array(o+t);return Ur(r,s,0),Ur(t,s,n),s.set(e,o),new cr(r,t,e,s)}function kr(r){let e=je(r),[t,n]=vn(e),[o,s]=vn(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new cr(t,o,i,e)}function Pi(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&ou(r.bytes,t.bytes)}}var cr=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=ar(n),this.bytes=ar(o)}};function tm(r,e){return r.code===e}function du(r,e){let{bytes:t,version:n}=r;return n===0?nm(t,Ni(r),e??de.encoder):om(t,Ni(r),e??Pt.encoder)}var pu=new WeakMap;function Ni(r){let e=pu.get(r);if(e==null){let t=new Map;return pu.set(r,t),t}return e}var ye=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=ar(o),this["/"]=this.bytes}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Cn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==sm)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=Pe(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&Pi(e.multihash,n.multihash)}toString(e){return du(this,e)}toJSON(){return{"/":du(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??mu(n,o,s.bytes))}else if(t[im]===!0){let{version:n,multihash:o,code:s}=t,i=kr(o);return r.create(n,s,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Cn)throw new Error(`Version 0 CID must use dag-pb (code: ${Cn}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=mu(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Cn,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=je(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new cr(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[h,l]=vn(e.subarray(t));return t+=l,h},o=n(),s=Cn;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),f=t+c,u=f-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:f}}static parse(e,t){let[n,o]=rm(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Ni(s).set(n,e),s}};function rm(r,e){switch(r[0]){case"Q":{let t=e??de;return[de.prefix,t.decode(`${de.prefix}${r}`)]}case de.prefix:{let t=e??de;return[de.prefix,t.decode(r)]}case Pt.prefix:{let t=e??Pt;return[Pt.prefix,t.decode(r)]}case Sn.prefix:{let t=e??Sn;return[Sn.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function nm(r,e,t){let{prefix:n}=t;if(n!==de.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function om(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var Cn=112,sm=18;function mu(r,e,t){let n=Fr(r),o=n+Fr(e),s=new Uint8Array(o+t.byteLength);return Ur(r,s,0),Ur(e,s,n),s.set(t,o),s}var im=Symbol.for("@ipld/js-cid/CID");var Ui={};oe(Ui,{identity:()=>Qe});var gu=0,am="identity",yu=je;function cm(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return Pe(gu,yu(r))}var Qe={code:gu,name:am,encode:yu,digest:cm};function Se(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function fm(r){return r.buffer instanceof ArrayBuffer}function Ae(r){return fm(r)?r:r.slice()}async function bu(r,e,t,n){let o=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,Ae(e),Ae(t.subarray()));return n?.signal?.throwIfAborted(),s}function at(r=0){return new Uint8Array(r)}function xe(r=0){return new Uint8Array(r)}function um(r){return r?.buffer instanceof ArrayBuffer}function Fi(r){if(um(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function $e(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=xe(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return Fi(t)}var xu=Symbol.for("@achingbrain/uint8arraylist");function wu(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function Ko(r){return!!r?.[xu]}var J=class r{bufs;length;[xu]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(Ko(n)){t+=n.byteLength;for(let o of n.bufs)this.bufs.push(o)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(Ko(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=wu(this.bufs,e);return t.buf[t.index]}set(e,t){let n=wu(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(Ko(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:o}=this._subList(e,t);return $e(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:$e(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=n,s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let f=e>=a&&e<c,u=t>a&&t<=c;if(f&&u){if(e===a&&t===c){n.push(i);break}let h=e-a;n.push(i.subarray(h,h+(t-e)));break}if(f){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(u){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!Ko(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let h=0;h<s;h++)i[h]=-1;for(let h=0;h<o;h++)i[n[h]]=h;let a=i,c=this.byteLength-n.byteLength,f=n.byteLength-1,u;for(let h=t;h<=c;h+=u){u=0;for(let l=f;l>=0;l--){let d=this.get(h+l);if(n[l]!==d){u=Math.max(1,l-a[d]);break}}if(u===0)return h}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=xe(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=at(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=at(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=at(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=xe(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=at(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=at(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=at(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=at(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=at(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!Se(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,s)=>o+s.byteLength,0)),n.length=t,n}};var ki={};oe(ki,{base10:()=>hm});var hm=Ot({prefix:"9",name:"base10",alphabet:"0123456789"});var Mi={};oe(Mi,{base16:()=>lm,base16upper:()=>dm});var lm=le({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4,caseInsensitive:!0}),dm=le({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4,caseInsensitive:!0});var Ki={};oe(Ki,{base2:()=>pm});var pm=le({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Hi={};oe(Hi,{base256emoji:()=>wm});var Eu=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}"),mm=Eu.reduce((r,e,t)=>(r[t]=e,r),[]),gm=Eu.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function ym(r){return r.reduce((e,t)=>(e+=mm[t],e),"")}function bm(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=gm[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var wm=Nr({prefix:"\u{1F680}",name:"base256emoji",encode:ym,decode:bm});var $i={};oe($i,{base64:()=>xm,base64pad:()=>Em,base64url:()=>Ln,base64urlpad:()=>Sm});var xm=le({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Em=le({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ln=le({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Sm=le({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var zi={};oe(zi,{base8:()=>Am});var Am=le({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Vi={};oe(Vi,{identity:()=>vm});var vm=Nr({prefix:"\0",name:"identity",encode:r=>iu(je(r)),decode:r=>je(su(r))});var yx=new TextEncoder,bx=new TextDecoder;var Wi={};oe(Wi,{sha256:()=>wt,sha512:()=>Tm});var Bm=20;function ji({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new qi(r,e,t,n,o)}var qi=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??Bm,this.maxDigestLength=s}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?Su(n,this.code,t?.truncate):n.then(o=>Su(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Su(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return Pe(e,r)}function vu(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var wt=ji({name:"sha2-256",code:18,encode:vu("SHA-256")}),Tm=ji({name:"sha2-512",code:19,encode:vu("SHA-512")});var fr={...Vi,...Ki,...zi,...ki,...Mi,...Ii,...Ri,..._i,...$i,...Hi},_x={...Wi,...Ui};function Lu(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Cu=Lu("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Gi=Lu("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=xe(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),Dm={utf8:Cu,"utf-8":Cu,hex:fr.base16,latin1:Gi,ascii:Gi,binary:Gi,...fr},Ho=Dm;function Q(r,e="utf8"){let t=Ho[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function Y(r,e="utf8"){let t=Ho[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var _m=parseInt("11111",2),Xi=parseInt("10000000",2),Im=parseInt("01111111",2),Bu={0:Bn,1:Bn,2:Rm,3:Nm,4:Um,5:Pm,6:Om,16:Bn,22:Bn,48:Bn};function xt(r,e={offset:0}){let t=r[e.offset]&_m;if(e.offset++,Bu[t]!=null)return Bu[t](r,e);throw new Error("No decoder for tag "+t)}function Tn(r,e){let t=0;if((r[e.offset]&Xi)===Xi){let n=r[e.offset]&Im,o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++){if(e.offset>=r.byteLength)throw new Error("invalid DER element length");o+=r[e.offset].toString(16).padStart(2,"0")}t=parseInt(o,16)}else t=r[e.offset],e.offset++;if(!Number.isInteger(t)||t<0||t>r.byteLength-e.offset)throw new Error("invalid DER element length");return t}function Bn(r,e){Tn(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=xt(r,e);if(n===null)break;t.push(n)}return t}function Rm(r,e){let t=Tn(r,e),n=e.offset,o=e.offset+t,s=[];for(let i=n;i<o;i++)i===n&&r[i]===0||s.push(r[i]);return e.offset+=t,Uint8Array.from(s)}function Om(r,e){let t=Tn(r,e),n=e.offset+t,o=r[e.offset];e.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,c=[];for(;e.offset<n;){let f=r[e.offset];if(e.offset++,c.push(f&127),f<128){c.reverse();let u=0;for(let h=0;h<c.length;h++)u+=c[h]<<h*7;a+=`.${u}`,c=[]}}return a}function Pm(r,e){return e.offset++,null}function Nm(r,e){let t=Tn(r,e),n=r[e.offset];e.offset++;let o=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function Um(r,e){let t=Tn(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function Fm(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new J;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function Yi(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=Fm(r.byteLength);return new J(Uint8Array.from([e.byteLength|Xi]),e)}function Fe(r){let e=new J,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new J(Uint8Array.from([2]),Yi(e),e)}function $o(r){let e=Uint8Array.from([0]),t=new J(e,r);return new J(Uint8Array.from([3]),Yi(t),t)}function Nt(r,e=48){let t=new J;for(let n of r)t.append(n);return new J(Uint8Array.from([e]),Yi(t),t)}var km=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Mm=Uint8Array.from([6,5,43,129,4,0,34]),Km=Uint8Array.from([6,5,43,129,4,0,35]),Hm={ext:!0,kty:"EC",crv:"P-256"},$m={ext:!0,kty:"EC",crv:"P-384"},zm={ext:!0,kty:"EC",crv:"P-521"},Zi=32,Ji=48,Qi=66;function ea(r){let e=xt(r);return Tu(e)}function Tu(r){let e=r[1][1][0],t=1,n,o;if(e.byteLength===Zi*2+1)return n=Y(e.subarray(t,t+Zi),"base64url"),o=Y(e.subarray(t+Zi),"base64url"),new Mr({...Hm,key_ops:["verify"],x:n,y:o});if(e.byteLength===Ji*2+1)return n=Y(e.subarray(t,t+Ji),"base64url"),o=Y(e.subarray(t+Ji),"base64url"),new Mr({...$m,key_ops:["verify"],x:n,y:o});if(e.byteLength===Qi*2+1)return n=Y(e.subarray(t,t+Qi),"base64url"),o=Y(e.subarray(t+Qi),"base64url"),new Mr({...zm,key_ops:["verify"],x:n,y:o});throw new W(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function Du(r){return Nt([Fe(Uint8Array.from([1])),Nt([Vm(r.crv)],160),Nt([$o(new J(Uint8Array.from([4]),Q(r.x??"","base64url"),Q(r.y??"","base64url")))],161)]).subarray()}function Vm(r){if(r==="P-256")return km;if(r==="P-384")return Mm;if(r==="P-521")return Km;throw new W(`Invalid curve ${r}`)}var Mr=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=Du(this.jwk)),this._raw}toMultihash(){return Qe.digest(Ut(this))}toCID(){return ye.createV1(114,this.toMultihash())}toString(){return de.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Se(this.raw,e.raw)}async verify(e,t,n){return bu(this.jwk,t,e,n)}};var zo=BigInt(4294967295),_u=BigInt(32);function qm(r,e=!1){return e?{h:Number(r&zo),l:Number(r>>_u&zo)}:{h:Number(r>>_u&zo)|0,l:Number(r&zo)|0}}function Iu(r,e=!1){let t=r.length,n=new Uint32Array(t),o=new Uint32Array(t);for(let s=0;s<t;s++){let{h:i,l:a}=qm(r[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var jm=r=>r/2**32|0,Wm=r=>r>>>0;function Ru(r,e,t,n){let o=jm(t),s=Wm(t);r.setUint32(e,n?s:o,n),r.setUint32(e+4,n?o:s,n)}var ta=(r,e,t)=>r>>>t,ra=(r,e,t)=>r<<32-t|e>>>t,ur=(r,e,t)=>r>>>t|e<<32-t,hr=(r,e,t)=>r<<32-t|e>>>t,Dn=(r,e,t)=>r<<64-t|e>>>t-32,_n=(r,e,t)=>r>>>t-32|e<<64-t;function ct(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var Ou=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),Pu=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,Nu=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),Uu=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,Fu=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),ku=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;function Vo(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}var na=r=>r?`"${r}" `:"";function et(r,e=""){if(typeof r!="number")throw new TypeError(na(e)+"expected number, got "+typeof r);if(!Number.isSafeInteger(r)||r<0)throw new RangeError(na(e)+"expected integer >= 0, got "+r);return r}function Ne(r,e,t=""){if(Vo(r)&&(e===void 0||r.length===e))return r;e!==void 0&&et(e,"length");let n=Vo(r),o=e!==void 0?` of length ${e}`:"",s=n?`length=${r.length}`:`type=${typeof r}`,i=na(t)+"expected Uint8Array"+o+", got "+s;throw n?new RangeError(i):new TypeError(i)}function lr(r){if(typeof r!="function"||typeof r.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(et(r.outputLen),et(r.blockLen),r.outputLen<1||r.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}var Mu=(r,e)=>{if(r===null||typeof r!="object"||Array.isArray(r))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof r)};function Kr(r,e=!0){if(r.destroyed)throw new Error("hash was destroyed");if(e&&r.finished)throw new Error("digest() was already called")}function qo(r,e){Ne(r,void 0,"output");let t=e.outputLen;if(!(r.length>=t))throw new RangeError('"output" expected length >= '+t)}function We(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function jo(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function tt(r,e){return r<<32-e|r>>>e}var Hu=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Xm=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Wo(r){if(Ne(r),Hu)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=Xm[r[t]];return e}function Ku(r){return r>=48&&r<=57?r-48:r>=65&&r<=70?r-55:r>=97&&r<=102?r-87:void 0}function Go(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);if(Hu)try{return Uint8Array.fromHex(r)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}let e=r.length,t=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let o=0,s=0;o<t;o++,s+=2){let i=Ku(r.charCodeAt(s)),a=Ku(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function oa(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];Ne(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let s=r[n];t.set(s,o),o+=s.length}return t}function Ym(r,e,t="opts"){return Mu(r,"defaults"),e!==void 0&&Mu(e,t),Object.assign(r,e)}function sa(r,e={}){if(typeof r!="function")throw new TypeError('"hashCons" expected function, got type='+typeof r);e=Ym({},e,"info");let t=(o,s)=>r(s).update(o).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.canXOF=n.canXOF,t.create=o=>r(o),Object.assign(t,e),Object.freeze(t)}function $u(r=32){et(r,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(r>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${r}`);return e.getRandomValues(new Uint8Array(r))}var ia=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function zu(r,e,t){return r&e^~r&t}function Vu(r,e,t){return r&e^r&t^e&t}var In=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,o){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=jo(this.buffer)}update(e){Kr(this),Ne(e);let{view:t,buffer:n,blockLen:o}=this,s=e.length,i=!1;for(let a=0;a<s;){let c=Math.min(o-this.pos,s-a);if(c===o){let f=jo(e);for(;o<=s-a;a+=o)this.process(f,a);i=!0;continue}n.set(a===0&&c===s?e:e.subarray(a,a+c),this.pos),this.pos+=c,a+=c,this.pos===o&&(this.process(t,0),this.pos=0,i=!0)}return this.length+=e.length,i&&this.roundClean(),this}digestInto(e){Kr(this),qo(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,t.fill(0,i),this.padOffset>o-i&&(this.process(n,0),t.fill(0)),Ru(n,o-8,this.length*8,s),this.process(n,0),this.roundClean();let a=e===t?n:jo(e),c=this.outputLen,f=c/4,u=this.get();if(c%4||f>u.length)throw new Error("invalid outputLen");for(let h=0;h<f;h++)a.setUint32(4*h,u[h],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneIntoMeta(e){let{buffer:t,length:n,finished:o,destroyed:s,pos:i}=this;return e.destroyed=s,e.finished=o,e.length=n,e.pos=i,i&&e.buffer.set(t),e}clone(){return this._cloneInto()}},qu=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var ju=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Zm=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]),Ft=new Uint32Array(64),aa=class extends In{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1),this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}get(){let{A:e,B:t,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,t,n,o,s,i,a,c]}set(e,t,n,o,s,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let h=0;h<16;h++,t+=4)Ft[h]=e.getUint32(t,!1);for(let h=16;h<64;h++){let l=Ft[h-15],d=Ft[h-2],b=tt(l,7)^tt(l,18)^l>>>3,w=tt(d,17)^tt(d,19)^d>>>10;Ft[h]=w+Ft[h-7]+b+Ft[h-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:f,H:u}=this;for(let h=0;h<64;h++){let l=tt(a,6)^tt(a,11)^tt(a,25),d=u+l+zu(a,c,f)+Zm[h]+Ft[h]|0,w=(tt(n,2)^tt(n,13)^tt(n,22))+Vu(n,o,s)|0;u=f,f=c,c=a,a=i+d|0,i=s,s=o,o=n,n=d+w|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,f=f+this.G|0,u=u+this.H|0,this.set(n,o,s,i,a,c,f,u)}roundClean(){We(Ft)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),We(this.buffer)}},ca=class extends aa{constructor(){super(32,qu)}};var Wu=Iu(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(r=>BigInt(r))),Jm=Wu[0],Qm=Wu[1],kt=new Uint32Array(80),Mt=new Uint32Array(80),fa=class extends In{Ah=0;Al=0;Bh=0;Bl=0;Ch=0;Cl=0;Dh=0;Dl=0;Eh=0;El=0;Fh=0;Fl=0;Gh=0;Gl=0;Hh=0;Hl=0;constructor(e,t){super(128,e,16,!1),this.Ah=t[0]|0,this.Al=t[1]|0,this.Bh=t[2]|0,this.Bl=t[3]|0,this.Ch=t[4]|0,this.Cl=t[5]|0,this.Dh=t[6]|0,this.Dl=t[7]|0,this.Eh=t[8]|0,this.El=t[9]|0,this.Fh=t[10]|0,this.Fl=t[11]|0,this.Gh=t[12]|0,this.Gl=t[13]|0,this.Hh=t[14]|0,this.Hl=t[15]|0}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:f,El:u,Fh:h,Fl:l,Gh:d,Gl:b,Hh:w,Hl:g}=this;return[e,t,n,o,s,i,a,c,f,u,h,l,d,b,w,g]}set(e,t,n,o,s,i,a,c,f,u,h,l,d,b,w,g){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=f|0,this.El=u|0,this.Fh=h|0,this.Fl=l|0,this.Gh=d|0,this.Gl=b|0,this.Hh=w|0,this.Hl=g|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let x=0;x<16;x++,t+=4)kt[x]=e.getUint32(t),Mt[x]=e.getUint32(t+=4);for(let x=16;x<80;x++){let L=kt[x-15]|0,T=Mt[x-15]|0,F=ur(L,T,1)^ur(L,T,8)^ta(L,T,7),O=hr(L,T,1)^hr(L,T,8)^ra(L,T,7),N=kt[x-2]|0,I=Mt[x-2]|0,U=ur(N,I,19)^Dn(N,I,61)^ta(N,I,6),k=hr(N,I,19)^_n(N,I,61)^ra(N,I,6),R=Nu(O,k,Mt[x-7],Mt[x-16]),H=Uu(R,F,U,kt[x-7],kt[x-16]);kt[x]=H|0,Mt[x]=R|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:f,Dl:u,Eh:h,El:l,Fh:d,Fl:b,Gh:w,Gl:g,Hh:m,Hl:E}=this;for(let x=0;x<80;x++){let L=ur(h,l,14)^ur(h,l,18)^Dn(h,l,41),T=hr(h,l,14)^hr(h,l,18)^_n(h,l,41),F=h&d^~h&w,O=l&b^~l&g,N=Fu(E,T,O,Qm[x],Mt[x]),I=ku(N,m,L,F,Jm[x],kt[x]),U=N|0,k=ur(n,o,28)^Dn(n,o,34)^Dn(n,o,39),R=hr(n,o,28)^_n(n,o,34)^_n(n,o,39),H=n&s^n&a^s&a,_=o&i^o&c^i&c;m=w|0,E=g|0,w=d|0,g=b|0,d=h|0,b=l|0,{h,l}=ct(f|0,u|0,I|0,U|0),f=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let D=Ou(U,R,_);n=Pu(D,I,k,H),o=D|0}({h:n,l:o}=ct(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=ct(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=ct(this.Ch|0,this.Cl|0,a|0,c|0),{h:f,l:u}=ct(this.Dh|0,this.Dl|0,f|0,u|0),{h,l}=ct(this.Eh|0,this.El|0,h|0,l|0),{h:d,l:b}=ct(this.Fh|0,this.Fl|0,d|0,b|0),{h:w,l:g}=ct(this.Gh|0,this.Gl|0,w|0,g|0),{h:m,l:E}=ct(this.Hh|0,this.Hl|0,m|0,E|0),this.set(n,o,s,i,a,c,f,u,h,l,d,b,w,g,m,E)}roundClean(){We(kt,Mt)}destroy(){this.destroyed=!0,We(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},ua=class extends fa{constructor(){super(64,ju)}};var ft=sa(()=>new ca,ia(1));var ha=sa(()=>new ua,ia(3));function Yo(r,e,t=()=>{}){if(!Array.isArray(r))throw new TypeError(`"${e}" expected array, got type=${typeof r}`);for(let n=0;n<r.length;n++)t(r[n],`${e}[${n}]`);return r}var j=(r,e,t)=>Ne(r,e,t),la=et;function Xu(r,e=""){if(typeof r!="string"){let t=e&&`"${e}" `;throw new TypeError(t+"expected string, got type="+typeof r)}return r}function Kt(r,e="object"){if(r===null||typeof r!="object"||Array.isArray(r))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof r}`);return r}function dr(r,e){if(typeof r!="function")throw new TypeError(`"${e}" is invalid: expected function, got ${typeof r}`);return r}var Rn=Wo,Ge=(...r)=>oa(...r),Hr=r=>Go(r),$t=Vo,Et=r=>$u(r),Xo=BigInt(0),Gu=BigInt(1),e0=r=>r?`"${r}" `:"";function ke(r,e=""){if(typeof r!="boolean")throw new TypeError(e0(e)+"expected boolean, got type="+typeof r);return r}function Zo(r){if(typeof r=="bigint"){if(!Ht(r))throw new RangeError("positive bigint expected, got "+r)}else la(r);return r}function zt(r,e=""){if(typeof r!="number"){let t=e&&`"${e}" `;throw new TypeError(t+"expected number, got type="+typeof r)}if(!Number.isSafeInteger(r)){let t=e&&`"${e}" `;throw new RangeError(t+"expected safe integer, got "+r)}}function On(r){let e=Zo(r).toString(16);return e.length&1?"0"+e:e}function Yu(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);return r===""?Xo:BigInt("0x"+r)}function ut(r){return Yu(Wo(r))}function ht(r){return Yu(Wo(pr(Ne(r)).reverse()))}function Jo(r,e){if(et(e),e===0)throw new Error("zero output length is invalid");r=Zo(r);let t=e*2,n=r.toString(16);if(n.length>t)throw new RangeError("number is too large");return Go(n.padStart(t,"0"))}function Pn(r,e){return Jo(r,e).reverse()}function pr(r){return Uint8Array.from(j(r))}function Ht(r){return typeof r=="bigint"&&Xo<=r}function da(r,e,t){return Ht(r)&&Ht(e)&&Ht(t)&&e<=r&&r<t}function lt(r,e,t,n){if(!da(e,t,n))throw new RangeError("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function $r(r){if(r<Xo)throw new Error("expected non-negative bigint, got "+r);return r===Xo?0:r.toString(2).length}var Nn=r=>(zt(r,"n"),(Gu<<BigInt(r))-Gu);function Zu(r,e,t){if(et(r,"hashLen"),et(e,"qByteLen"),typeof t!="function")throw new TypeError("hmacFn must be a function");let n=g=>new Uint8Array(g),o=Uint8Array.of(),s=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(r),f=n(r),u=0,h=()=>{c.fill(1),f.fill(0),u=0},l=(...g)=>t(f,Ge(c,...g)),d=(g=o)=>{f=l(s,g),c=l(),g.length!==0&&(f=l(i,g),c=l())},b=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let g=0,m=[];for(;g<e;){c=l();let E=c.slice();m.push(E),g+=c.length}return Ge(...m)};return(g,m)=>{h(),d(g);let E;for(;(E=m(b()))===void 0;)d();return h(),E}}function Be(r,e={},t={},n="object"){Kt(r,n),Kt(e,"fields"),Kt(t,"optFields");function o(i,a,c){let f=n==="object"?`param "${String(i)}"`:`"${n}.${String(i)}"`,u=r[i];if(!Object.hasOwn(r,i)&&(c?u!==void 0:a!=="function"))throw new TypeError(`${f} is invalid: expected own property`);if(c&&u===void 0)return;let h=typeof u;if(h!==a||u===null)throw new TypeError(`${f} is invalid: expected ${a}, got ${h}`)}let s=(i,a)=>Object.entries(i).forEach(([c,f])=>o(c,f,a));s(e,!1),s(t,!0)}var be=BigInt(0),ee=BigInt(1),Vt=BigInt(2),eh=BigInt(3),pa=BigInt(4),th=BigInt(5),t0=BigInt(7),rh=BigInt(8),r0=BigInt(9),n0=BigInt(15),nh=BigInt(16),o0=BigInt("0x10000000000000000");function ne(r,e){if(e<=be)throw new Error("mod: expected positive modulus, got "+e);let t=r%e;return t>=be?t:e+t}function oh(r,e,t){if(t<=ee)throw new Error("pow: expected modulus > 1, got "+t);if(typeof e!="bigint")throw new TypeError("invalid exponent: expected bigint, got "+typeof e);if(e<be)throw new Error("invalid exponent, negatives unsupported");if(e===be)return ee;if(e===ee)return r;let n=r%t;if(n<be&&(n+=t),e<o0){let a=ee;for(;e>be;)e&ee&&(a=a*n%t),n=n*n%t,e>>=ee;return a}let o=[];for(;e>be;)o.push(Number(e&n0)),e>>=pa;let s=new Array(16);s[0]=ee,s[1]=n;for(let a=2;a<16;a++)s[a]=s[a-1]*n%t;let i=s[o[o.length-1]];for(let a=o.length-2;a>=0;a--){i=i*i%t,i=i*i%t,i=i*i%t,i=i*i%t;let c=o[a];c!==0&&(i=i*s[c]%t)}return i}function fe(r,e,t){if(t<=ee)throw new Error("pow2: expected modulus > 1, got "+t);if(e<be)throw new Error("pow2: expected non-negative exponent, got "+e);let n=r;for(;e-- >be;)n*=n,n%=t;return n}function Ju(r,e){if(r===be)throw new Error("invert: expected non-zero number");if(e<=ee)throw new Error("invert: expected modulus > 1, got "+e);let t=ne(r,e),n=e,o=be,s=ee;for(;t!==be;){let a=n/t,c=n-t*a,f=o-s*a;n=t,t=c,o=s,s=f}if(n!==ee)throw new Error("invert: does not exist");return ne(o,e)}function sh(r,e){if(e<=ee)throw new Error("invertCt: expected prime modulus > 1, got "+e);let t=ne(r,e);if(t===be)throw new Error("invertCt: expected non-zero number");let n=oh(t,e-Vt,e);if(ne(t*n,e)!==ee)throw new Error("invertCt: does not exist");return n}function ma(r,e,t){let n=r;if(!n.eql(n.sqr(e),t))throw new Error("Cannot find square root")}function ga(r,e){if((r&ee)===be)throw new Error(e+": expected odd modulus, got "+r)}function ih(r,e){let t=r,n=(t.ORDER+ee)/pa,o=t.pow(e,n);return ma(t,o,e),o}function s0(r,e){let t=r,n=(t.ORDER-th)/rh,o=t.mul(e,Vt),s=t.pow(o,n),i=t.mul(e,s),a=t.mul(t.mul(i,Vt),s),c=t.mul(i,t.sub(a,t.ONE));return ma(t,c,e),c}function i0(r){let e=Vr(r),t=ah(r),n=t(e,e.neg(e.ONE)),o=t(e,n),s=t(e,e.neg(n)),i=(r+t0)/nh;return((a,c)=>{let f=a,u=f.pow(c,i),h=f.mul(u,n),l=f.mul(u,o),d=f.mul(u,s),b=f.eql(f.sqr(h),c),w=f.eql(f.sqr(l),c);u=f.cmov(u,h,b),h=f.cmov(d,l,w);let g=f.eql(f.sqr(h),c),m=f.cmov(u,h,g);return ma(f,m,c),m})}function ah(r){if(r<eh)throw new Error("sqrt is not defined for small field");ga(r,"tonelliShanks");let e=r-ee,t=0;for(;e%Vt===be;)e/=Vt,t++;let n=Vt,o=Vr(r);for(;Un(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return ih;let s=o.pow(n,e),i=(e+ee)/Vt;return function(c,f){let u=c;if(u.is0(f))return f;if(Un(u,f)!==1)throw new Error("Cannot find square root");let h=t,l=u.mul(u.ONE,s),d=u.pow(f,e),b=u.pow(f,i);for(;!u.eql(d,u.ONE);){if(u.is0(d))throw new Error("Cannot find square root: probably non-prime P");let w=1,g=u.sqr(d);for(;!u.eql(g,u.ONE);)if(w++,g=u.sqr(g),w===h)throw new Error("Cannot find square root");let m=ee<<BigInt(h-w-1),E=u.pow(l,m);h=w,l=u.sqr(E),d=u.mul(d,l),b=u.mul(b,E)}return b}}function a0(r){return ga(r,"Fp.sqrt"),r%pa===eh?ih:r%rh===th?s0:r%nh===r0?i0(r):ah(r)}var ch=(r,e)=>(ne(r,e)&ee)===ee,c0=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function zr(r){if(Kt(r,"field"),typeof r.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof r.ORDER);zt(r.BYTES,"BYTES"),zt(r.BITS,"BITS");for(let e of c0)dr(r[e],"field."+e);if(r.BYTES<1||r.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(r.ORDER<=ee)throw new Error("invalid field: expected ORDER > 1, got "+r.ORDER);return r}function es(r,e,t=!1){zr(r),Yo(e,"nums"),ke(t,"passZero");let n=r,o=new Array(e.length).fill(t?n.ZERO:void 0),s=e.reduce((a,c,f)=>n.is0(c)?a:(o[f]=a,n.mul(a,c)),n.ONE),i=n.inv(s);return e.reduceRight((a,c,f)=>n.is0(c)?a:(o[f]=n.mul(a,o[f]),n.mul(a,c)),i),o}function Un(r,e){zr(r);let t=r;ga(t.ORDER,"FpLegendre");let n=(t.ORDER-ee)/Vt,o=t.pow(e,n),s=t.eql(o,t.ONE),i=t.eql(o,t.ZERO),a=t.eql(o,t.neg(t.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function f0(r,e){if(e!==void 0&&la(e),r<=be)throw new Error("invalid n length: expected positive n, got "+r);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let t=$r(r);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected nBitLength (${e}) >= bitLen(n) (${t})`);let n=e!==void 0?e:t,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}var Qu=new WeakMap,Qo=class{ORDER;BITS;BYTES;isLE;ZERO=be;ONE=ee;_lengths;_mod;constructor(e,t={}){if(e<=ee)throw new Error("invalid field: expected ORDER > 1, got "+e);let n;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(n=t.BITS),typeof t.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0}),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=Object.freeze(t.allowedLengths.slice())),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:o,nByteLength:s}=f0(e,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,Object.freeze(this)}create(e){return ne(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return be<=e&&e<this.ORDER}is0(e){return e===be}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&ee)===ee}neg(e){return ne(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return ne(e*e,this.ORDER)}add(e,t){return ne(e+t,this.ORDER)}sub(e,t){return ne(e-t,this.ORDER)}mul(e,t){return ne(e*t,this.ORDER)}pow(e,t){return oh(e,t,this.ORDER)}div(e,t){return ne(e*Ju(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return Ju(e,this.ORDER)}sqrt(e){let t=Qu.get(this);return t||Qu.set(this,t=a0(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?Pn(e,this.BYTES):Jo(e,this.BYTES)}fromBytes(e,t=!1){j(e);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(e.length<1||!n.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let f=new Uint8Array(o);f.set(e,s?0:f.length-e.length),e=f}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?ht(e):ut(e);if(a&&(c=ne(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return es(this,e,!0)}cmov(e,t,n){return ke(n,"condition"),n?t:e}};function Vr(r,e={}){return Object.freeze(Qo.prototype),new Qo(r,e)}function fh(r){if(typeof r!="bigint")throw new Error("field order must be bigint");if(r<=ee)throw new Error("field order must be greater than 1");let e=$r(r-ee);return Math.ceil(e/8)}function ts(r){let e=fh(r);return e+Math.ceil(e/2)}function rs(r,e,t=!1){j(r);let n=r.length,o=fh(e),s=Math.max(ts(e),16);if(n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=t?ht(r):ut(r),a=ne(i,e-ee)+ee;return t?Pn(a,o):Jo(a,o)}var wa=BigInt(0),Fn=BigInt(1),u0=BigInt(4),ya=16,uh=128,h0=5,hh=2**31;function qt(r){let e=r;if(typeof e!="function")throw new TypeError('"Point" expected constructor, got type='+typeof r);dr(e.fromAffine,"Point.fromAffine"),dr(e.fromBytes,"Point.fromBytes"),dr(e.fromHex,"Point.fromHex"),Kt(e.BASE,"Point.BASE"),Kt(e.ZERO,"Point.ZERO"),zr(e.Fp),zr(e.Fn)}function ns(r,e){qt(r),dh(e,r);let t=es(r.Fp,e.map(n=>n.Z));return e.map((n,o)=>r.fromAffine(n.toAffine(t[o])))}function l0(r,e,t=1){if(!Number.isSafeInteger(r)||r<t||r>e)throw new Error("invalid window size, expected ["+t+".."+e+"], got W="+r)}function d0(r,e){let t=r*(4*e+128);if(t>hh)throw new Error("invalid window size: table would need ~"+Math.ceil(t/2**20)+" MiB, max "+hh/2**20+" MiB")}function xa(r,e){if(r!==void 0){dr(r,"randomBytes");try{let t=r(e);if(!$t(t)||t.length!==e)return}catch{return}return r}}function dh(r,e){Yo(r,"points"),r.forEach((t,n)=>{if(!(t instanceof e))throw new Error("invalid point at index "+n)})}function p0(r,e,t){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((n,o)=>{if(!(t===void 0?e.isValid(n):Ht(n)&&n<t))throw new Error("invalid scalar at index "+o)})}var ph=new WeakMap;function ba(r){return ph.get(r)||1}function m0(r,e){let t=r.double(),n=[r];for(let o=1;o<e;o++)n.push(n[o-1].add(t));return n}function g0(r,e){let t=2**e,n=t/2,o=BigInt(t-1),s=[];for(;r>wa;){let i=0;r&Fn&&(i=Number(r&o),i>=n&&(i-=t),r-=BigInt(i)),s.push(i),r>>=Fn}return s}function y0(r,e,t){let n=2**e,o=n/2,s=BigInt(n-1),i=BigInt(e),a=[];for(let c=0;c<t;c++){let f=Number(r&s);r>>=i,f>o&&(f-=n,r+=Fn),a.push(f)}if(r!==wa)throw new Error("invalid wnaf");return a}function b0(r,e,t){let n=0;for(let s of t)n=Math.max(n,s.length);let o=r;for(let s=n-1;s>=0;s--){s!==n-1&&(o=o.double());for(let i=0;i<t.length;i++){let a=t[i][s];if(a){let c=e[i][Math.abs(a)-1>>1];o=o.add(a<0?c.negate():c)}}}return o}var qr=class{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,t){qt(e),this.randomBytes=xa(t,ya),this.Point=e,this.BASE=e.BASE,this.ZERO=e.ZERO,this.bits=e.Fn.BITS}buildWnafTable(e,t,n){let o=Math.ceil(n/t)+1,s=2**(t-1),i=[],a=e;for(let c=0;c<o;c++){let f=a;for(let u=0;u<s;u++)i.push(f),f=f.add(a);a=i[i.length-1].double()}return{W:t,bits:n,windows:o,comp:i}}wnafCachedCT(e,t){let{W:n,windows:o,comp:s}=e,i=2**(n-1),a=y0(t,n,o),c=this.ZERO,f=this.BASE;for(let u=0;u<o;u++){let h=a[u],l=u*i,d=Math.abs(h)-1,b=s[l];for(let g=1;g<i;g++)b=g===d?s[l+g]:b;let w=b.negate();h===0?f=f.add(s[l]):c=c.add(h<0?w:b)}return{p:c,f}}getWnafPrecomputes(e,t,n,o){let s=this.wnafPrecomputes.get(t),i=s?.find(a=>a.W===e&&a.bits===n);return i||(i=this.buildWnafTable(t,e,n),typeof o=="function"&&(i={...i,comp:o(i.comp)}),s||(s=[],this.wnafPrecomputes.set(t,s)),s.push(i)),i}assertPoint(e){if(!(e instanceof this.Point))throw new TypeError('"point" expected Point instance, got type='+typeof e)}validateMulInput(e,t){if(this.assertPoint(e),!da(t,Fn,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(e,t,n,o){let s=ba(e);return s===1?this.fixedWindowCT(e,t,n):this.wnafCachedCT(this.getWnafPrecomputes(s,e,n,o),t)}mulCT(e,t,n){return this.validateMulInput(e,t),this.runCT(e,t,this.bits,n)}mulCTBlinded(e,t,n){if(this.validateMulInput(e,t),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");let o=this.Point.Fn.BITS+uh,s=this.randomBytes(ya);if(!$t(s)||s.length!==ya)throw new Error("randomBytes returned invalid byte array");s[0]=s[0]&63|128;let i=t+ut(s)*this.Point.Fn.ORDER;return this.runCT(e,i,o,n)}fixedWindowCT(e,t,n){let o=h0,s=1<<o,i=Nn(o),a=new Array(s);a[0]=this.ZERO;for(let u=1;u<s;u++)a[u]=a[u-1].add(e);let c=Math.ceil(n/o),f=this.ZERO;for(let u=c-1;u>=0;u--){if(u!==c-1)for(let d=0;d<o;d++)f=f.double();let h=Number(t>>BigInt(u*o)&i),l=a[0];for(let d=1;d<s;d++)l=d===h?a[d]:l;f=f.add(l)}return{p:f,f}}shouldBlind(e,t){return this.randomBytes===void 0?!1:t===Fn?!0:e!==this.BASE?!1:(this.baseCanBeBlinded===void 0&&(this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0()),this.baseCanBeBlinded)}mulSecret(e,t,n,o){return this.shouldBlind(e,n)?this.mulCTBlinded(e,t,o):this.mulCT(e,t,o)}mulUnsafe(e,t,n){if(this.assertPoint(e),!Ht(t))throw new Error("invalid scalar");let o=ba(e);if(o===1||t>=this.Point.Fn.ORDER)return os(this.Point,[e],[t],!0);let s=this.getWnafPrecomputes(o,e,this.bits,n);return this.wnafCachedCT(s,t).p}setWindowSize(e,t){this.assertPoint(e),l0(t,this.bits);let n=Math.ceil((this.bits+uh)/t)+1;d0(n*2**(t-1),this.Point.Fp.BYTES),ph.set(e,t),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return ba(e)!==1}};function os(r,e,t,n=!1){if(qt(r),dh(e,r),ke(n,"allowOversized"),p0(t,r.Fn,n?r.Fn.ORDER**u0:void 0),e.length!==t.length)throw new Error("arrays of points and scalars must have equal length");let o=e.map(i=>m0(i,4)),s=t.map(i=>g0(i,4));return b0(r.ZERO,o,s)}function lh(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return zr(e),e}else return Vr(r,{isLE:t})}function ss(r,e,t={},n){if(r!=="weierstrass"&&r!=="edwards")throw new Error('expected curve type "weierstrass" or "edwards"');if(n===void 0&&(n=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);Be(t);for(let c of["p","n","h"]){let f=e[c];if(!(Ht(f)&&f!==wa))throw new Error(`CURVE.${c} must be positive bigint`)}let o=lh(e.p,t.Fp,n),s=lh(e.n,t.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}function jr(r,e){return function(n){let o=r(n);return{secretKey:o,publicKey:e(o)}}}var is=BigInt(0),as=BigInt(1),cs=BigInt(2),w0=BigInt(4),mh=BigInt(8);function x0(r,e,t,n){let o=r.sqr(t),s=r.sqr(n),i=r.add(r.mul(e.a,o),s),a=r.add(r.ONE,r.mul(e.d,r.mul(o,s)));return r.eql(i,a)}function gh(r,e={}){Be(e,{},{},"extraOpts");let t=e,n=ss("edwards",r,t,t.FpFnLE),{Fp:o,Fn:s}=n,i=n.CURVE,{h:a}=i;if(Un(o,i.a)!==1)throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(Un(o,i.d)!==-1)throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");Be(t,{},{uvRatio:"function",randomBytes:"function"});let c=t.randomBytes===void 0?Et:t.randomBytes,f=cs<<BigInt(o.BYTES*8)-as;function u(E){if(!o.isOdd)throw new Error("Field does not have .isOdd()");return o.isOdd(E)}let h=t.uvRatio===void 0?(E,x)=>{try{return{isValid:!0,value:o.sqrt(o.div(E,x))}}catch{return{isValid:!1,value:is}}}:t.uvRatio;if(!x0(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");let l=o.eql(i.a,o.neg(o.ONE))?E=>o.neg(E):o.eql(i.a,o.ONE)?E=>E:E=>o.mul(i.a,E);function d(E,x,L=!1){let T=L?as:is;return lt("coordinate "+E,x,T,f),x}function b(E){if(!(E instanceof w))throw new Error("EdwardsPoint expected")}class w{static BASE=new w(i.Gx,i.Gy,o.ONE,o.mul(i.Gx,i.Gy));static ZERO=new w(o.ZERO,o.ONE,o.ONE,o.ZERO);static Fp=o;static Fn=s;X;Y;Z;T;constructor(x,L,T,F){this.X=d("x",x),this.Y=d("y",L),this.Z=d("z",T,!0),this.T=d("t",F),Object.freeze(this)}static CURVE(){return i}static fromAffine(x){if(x instanceof w)throw new Error("extended point not allowed");let{x:L,y:T}=x||{};return d("x",L),d("y",T),new w(L,T,o.ONE,o.mul(L,T))}static fromBytes(x,L=!1){let T=o.BYTES,{a:F,d:O}=i;x=pr(j(x,T,"point")),ke(L,"zip215");let N=pr(x),I=x[T-1];N[T-1]=I&-129;let U=ht(N),k=L?f:o.ORDER;lt("point.y",U,is,k);let R=o.sqr(U),H=o.sub(R,o.ONE),_=o.sub(o.mulN(O,R),F),{isValid:D,value:p}=h(H,_);if(!D)throw new Error("bad point: invalid y coordinate");let S=u(p),C=(I&128)!==0;if(!L&&o.is0(p)&&C)throw new Error("bad point: x=0 and x_0=1");return C!==S&&(p=o.neg(p)),w.fromAffine({x:p,y:U})}static fromHex(x,L=!1){return w.fromBytes(Hr(x),L)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(x=6,L=!0){return m.setWindowSize(this,x),L||this.multiply(cs),this}assertValidity(){let x=this,{a:L,d:T}=i;if(x.is0())throw new Error("bad point: ZERO");let{X:F,Y:O,Z:N,T:I}=x,U=o.sqr(F),k=o.sqr(O),R=o.sqr(N),H=o.sqr(R),_=o.mul(U,L),D=o.mul(o.add(_,k),R),p=o.add(H,o.mul(T,o.mul(U,k)));if(!o.eql(D,p))throw new Error("bad point: equation left != right (1)");let S=o.mul(F,O),C=o.mul(N,I);if(!o.eql(S,C))throw new Error("bad point: equation left != right (2)")}equals(x){b(x);let{X:L,Y:T,Z:F}=this,{X:O,Y:N,Z:I}=x,U=o.mul(L,I),k=o.mul(O,F),R=o.mul(T,I),H=o.mul(N,F);return o.eql(U,k)&&o.eql(R,H)}is0(){return this.equals(w.ZERO)}negate(){return new w(o.neg(this.X),this.Y,this.Z,o.neg(this.T))}double(){let{X:x,Y:L,Z:T}=this,F=o.sqr(x),O=o.sqr(L),N=o.mul(o.sqr(T),cs),I=l(F),U=o.addN(x,L),k=o.sub(o.subN(o.sqr(U),F),O),R=o.addN(I,O),H=o.subN(R,N),_=o.subN(I,O),D=o.mul(k,H),p=o.mul(R,_),S=o.mul(k,_),C=o.mul(H,R);return new w(D,p,C,S)}add(x){b(x);let{d:L}=i,{X:T,Y:F,Z:O,T:N}=this,{X:I,Y:U,Z:k,T:R}=x,H=o.mul(T,I),_=o.mul(F,U),D=o.mul(o.mulN(N,L),R),p=o.mul(O,k),S=o.sub(o.subN(o.mulN(o.addN(T,F),o.addN(I,U)),H),_),C=o.subN(p,D),A=o.addN(p,D),v=o.sub(_,l(H)),y=o.mul(S,C),B=o.mul(A,v),P=o.mul(S,v),K=o.mul(C,A);return new w(y,B,K,P)}subtract(x){return b(x),this.add(x.negate())}multiply(x){if(!s.isValidNot0(x))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:L,f:T}=m.mulSecret(this,x,a,g);return g([L,T])[0]}multiplyUnsafe(x){if(!s.isValid(x))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return x===is?w.ZERO:this.is0()||x===as?this:m.mulUnsafe(this,x,g)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return m.mulUnsafe(this,i.n).is0()}toAffine(x){let L=this,T=x;if(T!=null&&typeof T!="bigint")throw new TypeError('"invertedZ" expected bigint, got type='+typeof T);let{X:F,Y:O,Z:N}=L,I=L.is0();T==null&&(T=I?o.create(mh):o.inv(N));let U=o.mul(F,T),k=o.mul(O,T),R=o.mul(N,T);if(I)return{x:o.ZERO,y:o.ONE};if(!o.eql(R,o.ONE))throw new Error("invZ was invalid");return{x:U,y:k}}clearCofactor(){return a===as?this:a===cs?this.double():a===w0?this.double().double():a===mh?this.double().double().double():this.multiplyUnsafe(a)}toBytes(){let{x,y:L}=this.toAffine(),T=o.toBytes(L);return T[T.length-1]|=u(x)?128:0,T}toHex(){return Rn(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let g=E=>ns(w,E),m=new qr(w,c);return m.bits>=6&&w.BASE.precompute(6),Object.freeze(w.prototype),Object.freeze(w),w}function yh(r,e,t={}){if(qt(r),typeof e!="function")throw new Error('"hash" function param is required');let n=e,o=t;Be(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function",toMontgomery:"function",toMontgomerySecret:"function"});let{prehash:s}=o,{BASE:i,Fp:a,Fn:c}=r,f=n.outputLen,u=2*a.BYTES;if(f!==void 0&&(zt(f,"hash.outputLen"),f!==u))throw new Error(`hash.outputLen must be ${u}, got ${f}`);let h=o.randomBytes===void 0?Et:o.randomBytes,l=o.toMontgomery,d=o.toMontgomerySecret,b=o.adjustScalarBytes===void 0?_=>_:o.adjustScalarBytes,w=o.domain===void 0?(_,D,p)=>{if(ke(p,"phflag"),D.length||p)throw new Error("Contexts/pre-hash are not supported");return _}:o.domain;function g(_){return c.create(ht(_))}function m(_){let D=I.secretKey;j(_,I.secretKey,"secretKey");let p=j(n(_),2*D,"hashedSecretKey"),S=b(p.slice(0,D)),C=p.slice(D,2*D),A=g(S);return{head:S,prefix:C,scalar:A}}function E(_){let{head:D,prefix:p,scalar:S}=m(_),C=i.multiply(S),A=C.toBytes();return{head:D,prefix:p,scalar:S,point:C,pointBytes:A}}function x(_){return E(_).pointBytes}function L(_=Uint8Array.of(),...D){let p=Ge(...D);return g(n(w(p,j(_,void 0,"context"),!!s)))}function T(_,D,p={}){Be(p,{},{},"options"),_=j(_,void 0,"message"),s&&(_=s(_));let{prefix:S,scalar:C,pointBytes:A}=E(D),v=L(p.context,S,_),y=i.multiply(v).toBytes(),B=L(p.context,y,A,_),P=c.create(v+B*C);if(!c.isValid(P))throw new Error("sign failed: invalid s");let K=Ge(y,c.toBytes(P));return j(K,I.signature,"result")}let F={zip215:o.zip215};function O(_,D,p,S=F){Be(S);let{context:C}=S,A=S.zip215===void 0?!!F.zip215:S.zip215,v=I.signature;_=j(_,v,"signature"),D=j(D,void 0,"message"),p=j(p,I.publicKey,"publicKey"),A!==void 0&&ke(A,"zip215"),s&&(D=s(D));let y=v/2,B=_.subarray(0,y),P=ht(_.subarray(y,v)),K,M,V;try{K=r.fromBytes(p,A),M=r.fromBytes(B,A),V=i.multiplyUnsafe(P)}catch{return!1}if(!A&&K.isSmallOrder())return!1;let z=L(C,B,p,D);return M.add(K.multiplyUnsafe(z)).subtract(V).clearCofactor().is0()}let N=a.BYTES,I={secretKey:N,publicKey:N,signature:2*N,seed:N};function U(_){return _=_===void 0?h(I.seed):_,j(_,I.seed,"seed")}function k(_){return $t(_)&&_.length===I.secretKey}function R(_,D){try{return!!r.fromBytes(_,D===void 0?F.zip215:D)}catch{return!1}}let H={getExtendedPublicKey:E,randomSecretKey:U,isValidSecretKey:k,isValidPublicKey:R,toMontgomery(_){if(l===void 0)throw new Error("Montgomery conversion is not supported for this curve");return l(r.fromBytes(_))},toMontgomerySecret(_){if(d===void 0)throw new Error("Montgomery conversion is not supported for this curve");return d(_)}};return Object.freeze(I),Object.freeze(H),Object.freeze({keygen:jr(U,x),getPublicKey:x,sign:T,verify:O,utils:H,Point:r,lengths:I})}var mr=BigInt(0),Xe=BigInt(1),fs=BigInt(2);function bh(r,e){return r+e-(e>>Xe<<Xe)}function E0(r){let e=BigInt(6)*r;return(t,n,o)=>{let s=n+o,a=((e+o-n)*t+n)%r;return{x_2:a,x_3:s-a}}}function S0(r){return Be(r,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function",scalarMultBase:"function"}),Object.freeze({...r})}function wh(r){let e=S0(r),{P:t,type:n,adjustScalarBytes:o,powPminus2:s,randomBytes:i}=e,a=e.scalarMultBase,c=n==="x25519";if(!c&&n!=="x448")throw new Error("invalid type");let f=i===void 0?Et:i,u=c?255:448,h=E0(t),l=c?32:56,d=BigInt(c?9:5),b=BigInt(c?121665:39081),w=c?fs**BigInt(254):fs**BigInt(447),g=c?BigInt(8)*(fs**BigInt(251)-Xe):BigInt(4)*(fs**BigInt(445)-Xe),m=w+g+Xe,E=p=>ne(p,t),x=L(d);function L(p){return Pn(E(p),l)}function T(p){let S=pr(j(p,l,"uCoordinate"));return c&&(S[31]&=127),E(ht(S))}function F(p){return ht(o(pr(j(p,l,"scalar"))))}let O=new Set(c?[mr,Xe,t-Xe,BigInt("325606250916557431795983626356110631294008115727848805560023387167927233504"),BigInt("39382357235489614581723060781553021112529911719440698176882885853963445705823")]:[mr,Xe,t-Xe]);function N(p,S){let C=T(S);if(O.has(C))throw new Error("invalid private or public key received");let A=R(C,F(p));if(A===mr)throw new Error("invalid private or public key received");return L(A)}function I(p){if(a===void 0)return N(p,x);let S=F(p);lt("scalar",S,w,m);let C=E(a(S));if(C===mr)throw new Error("invalid private or public key received");return L(C)}let U=I,k=N;function R(p,S){lt("u",p,mr,t),lt("scalar",S,w,m);let C=S,A=p,v=Xe,y=mr,B=p,P=Xe,K=C^C>>Xe;for(let z=BigInt(u-1);z>=mr;z--){let X=bh(t,K>>z);({x_2:v,x_3:B}=h(X,v,B)),{x_2:y,x_3:P}=h(X,y,P);let ae=v+y,ce=E(ae*ae),ge=v-y,Ke=E(ge*ge),bt=ce-Ke,sr=B+P,st=B-P,He=E(st*ae),_r=E(sr*ge),xn=He+_r,It=He-_r;B=E(xn*xn),P=E(A*E(It*It)),v=E(ce*Ke),y=E(bt*(ce+E(b*bt)))}let M=bh(t,C);({x_2:v,x_3:B}=h(M,v,B)),{x_2:y,x_3:P}=h(M,y,P);let V=s(y);return E(v*V)}let H={secretKey:l,publicKey:l,seed:l},_=p=>(p=p===void 0?f(l):p,j(p,H.seed,"seed"),p),D={randomSecretKey:_};return Object.freeze(H),Object.freeze(D),Object.freeze({keygen:jr(_,U),getSharedSecret:k,getPublicKey:U,scalarMult:N,scalarMultBase:I,utils:D,GuBytes:x.slice(),lengths:H})}var xh=BigInt(0),Ea=BigInt(1),Eh=BigInt(2),A0=BigInt(3),v0=BigInt(5),C0=BigInt(8),us=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),L0={p:us,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:C0,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function vh(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=us,a=r*r%s*r%s,c=fe(a,Eh,s)*a%s,f=fe(c,Ea,s)*r%s,u=fe(f,v0,s)*f%s,h=fe(u,e,s)*u%s,l=fe(h,t,s)*h%s,d=fe(l,n,s)*l%s,b=fe(d,o,s)*d%s,w=fe(b,o,s)*d%s,g=fe(w,e,s)*u%s;return{pow_p_5_8:fe(g,Eh,s)*r%s,b2:a}}function Sa(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var Sh=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function B0(r,e){let t=us,n=ne(e*e*e,t),o=ne(n*n*e,t),s=vh(r*o).pow_p_5_8,i=ne(r*n*s,t),a=ne(e*i*i,t),c=i,f=ne(i*Sh,t),u=a===r,h=a===ne(-r,t),l=a===ne(-r*Sh,t);return u&&(i=c),(h||l)&&(i=f),ch(i,t)&&(i=ne(-i,t)),{isValid:u||h,value:i}}var kn=gh(L0,{uvRatio:B0}),Ah=kn.Fp;function T0(r){let{y:e}=r;return Ah.toBytes(Ah.div(Ea+e,Ea-e))}function D0(r){let e=kn.Fp.BYTES;return Ne(r,e),Sa(ha(r.subarray(0,e))).subarray(0,e)}function _0(r){return yh(kn,ha,Object.assign({adjustScalarBytes:Sa,toMontgomery:T0,toMontgomerySecret:D0,zip215:!0},r))}var Ch=_0({});var Mn=(()=>{let r=us,e=t=>{let{pow_p_5_8:n,b2:o}=vh(t);return ne(fe(n,A0,r)*o,r)};return wh({P:r,type:"x25519",powPminus2:e,adjustScalarBytes:Sa,scalarMultBase:t=>{let n=ne(t,kn.Fn.ORDER);if(n===xh)return xh;let o=kn.BASE.multiply(n);return ne((o.Z+o.Y)*e(ne(o.Z-o.Y,r)),r)}})})();var Kn=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},hs=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var Ye={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new hs("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return e}};var ls=32;var Aa,I0=(async()=>{try{return await Ye.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function R0(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await Ye.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await Ye.get().subtle.verify({name:"Ed25519"},n,Ae(e),Ae(t instanceof Uint8Array?t:t.subarray()))}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function O0(r,e,t){return Ch.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function Lh(r,e,t){return Aa==null&&(Aa=await I0),Aa?R0(r,e,t):O0(r,e,t)}function ds(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var ps=class{type="Ed25519";raw;constructor(e){this.raw=va(e,ls)}toMultihash(){return Qe.digest(Ut(this))}toCID(){return ye.createV1(114,this.toMultihash())}toString(){return de.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Se(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let o=Lh(this.raw,t,e);return ds(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function Ca(r){return r=va(r,ls),new ps(r)}function va(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new W(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var N0=Math.pow(2,7),U0=Math.pow(2,14),F0=Math.pow(2,21),La=Math.pow(2,28),Ba=Math.pow(2,35),Ta=Math.pow(2,42),Da=Math.pow(2,49),te=128,Te=127;function ue(r){if(r<N0)return 1;if(r<U0)return 2;if(r<F0)return 3;if(r<La)return 4;if(r<Ba)return 5;if(r<Ta)return 6;if(r<Da)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Wr(r,e,t=0){switch(ue(r)){case 8:e[t++]=r&255|te,r/=128;case 7:e[t++]=r&255|te,r/=128;case 6:e[t++]=r&255|te,r/=128;case 5:e[t++]=r&255|te,r/=128;case 4:e[t++]=r&255|te,r>>>=7;case 3:e[t++]=r&255|te,r>>>=7;case 2:e[t++]=r&255|te,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function k0(r,e,t=0){switch(ue(r)){case 8:e.set(t++,r&255|te),r/=128;case 7:e.set(t++,r&255|te),r/=128;case 6:e.set(t++,r&255|te),r/=128;case 5:e.set(t++,r&255|te),r/=128;case 4:e.set(t++,r&255|te),r>>>=7;case 3:e.set(t++,r&255|te),r>>>=7;case 2:e.set(t++,r&255|te),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function _a(r,e){let t=r[e],n=0;if(n+=t&Te,t<te||(t=r[e+1],n+=(t&Te)<<7,t<te)||(t=r[e+2],n+=(t&Te)<<14,t<te)||(t=r[e+3],n+=(t&Te)<<21,t<te)||(t=r[e+4],n+=(t&Te)*La,t<te)||(t=r[e+5],n+=(t&Te)*Ba,t<te)||(t=r[e+6],n+=(t&Te)*Ta,t<te)||(t=r[e+7],n+=(t&Te)*Da,t<te))return n;throw new RangeError("Could not decode varint")}function M0(r,e){let t=r.get(e),n=0;if(n+=t&Te,t<te||(t=r.get(e+1),n+=(t&Te)<<7,t<te)||(t=r.get(e+2),n+=(t&Te)<<14,t<te)||(t=r.get(e+3),n+=(t&Te)<<21,t<te)||(t=r.get(e+4),n+=(t&Te)*La,t<te)||(t=r.get(e+5),n+=(t&Te)*Ba,t<te)||(t=r.get(e+6),n+=(t&Te)*Ta,t<te)||(t=r.get(e+7),n+=(t&Te)*Da,t<te))return n;throw new RangeError("Could not decode varint")}function ms(r,e,t=0){return e==null&&(e=xe(ue(r))),e instanceof Uint8Array?Wr(r,e,t):k0(r,e,t)}function St(r,e=0){return r instanceof Uint8Array?_a(r,e):M0(r,e)}var Ia=new Float32Array([-0]),jt=new Uint8Array(Ia.buffer);function Th(r,e,t){Ia[0]=r,e[t]=jt[0],e[t+1]=jt[1],e[t+2]=jt[2],e[t+3]=jt[3]}function Dh(r,e){return jt[0]=r[e],jt[1]=r[e+1],jt[2]=r[e+2],jt[3]=r[e+3],Ia[0]}var Ra=new Float64Array([-0]),De=new Uint8Array(Ra.buffer);function _h(r,e,t){Ra[0]=r,e[t]=De[0],e[t+1]=De[1],e[t+2]=De[2],e[t+3]=De[3],e[t+4]=De[4],e[t+5]=De[5],e[t+6]=De[6],e[t+7]=De[7]}function Ih(r,e){return De[0]=r[e],De[1]=r[e+1],De[2]=r[e+2],De[3]=r[e+3],De[4]=r[e+4],De[5]=r[e+5],De[6]=r[e+6],De[7]=r[e+7],Ra[0]}var K0=BigInt(Number.MAX_SAFE_INTEGER),H0=BigInt(Number.MIN_SAFE_INTEGER),ze=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return gr;if(e<K0&&e>H0)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>Rh&&(o=0n,++n>Rh&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return gr;let t=e<0;t&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):gr}},gr=new ze(0,0);gr.toBigInt=function(){return 0n};gr.zzEncode=gr.zzDecode=function(){return this};gr.length=function(){return 1};var Rh=4294967296n;function Oh(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function Ph(r,e,t){if(t-e<1)return"";let o,s=[],i=0,a;for(;e<t;)a=r[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function Oa(r,e,t){let n=t,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function rt(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function gs(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var Pa=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=Ae(e),this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,rt(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw rt(this,4);return gs(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw rt(this,4);return gs(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw rt(this,4);let e=Dh(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw rt(this,4);let e=Ih(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw rt(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Ph(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw rt(this,e);this.pos+=e}else do if(this.pos>=this.len)throw rt(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new ze(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw rt(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw rt(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw rt(this,8);let e=gs(this.buf,this.pos+=4),t=gs(this.buf,this.pos+=4);return new ze(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=_a(this.buf,this.pos);return this.pos+=ue(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function $n(r){return new Pa(r instanceof Uint8Array?r:r.subarray())}function Wt(r,e,t){let n=$n(r);return e.decode(n,void 0,t)}function Na(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return xe(i);o+i>e&&(n=xe(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var yr=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function Ua(){}var ka=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},$0=Na();function z0(r){return globalThis.Buffer!=null?xe(r):$0(r)}var Vn=class{len;head;tail;states;constructor(){this.len=0,this.head=new yr(Ua,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new yr(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Ma((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(ys,10,ze.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=ze.fromBigInt(e);return this._push(ys,t.length(),t)}uint64Number(e){return this._push(Wr,ue(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=ze.fromBigInt(e).zzEncode();return this._push(ys,t.length(),t)}sint64Number(e){let t=ze.fromNumber(e).zzEncode();return this._push(ys,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Fa,1,e?1:0)}fixed32(e){return this._push(zn,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=ze.fromBigInt(e);return this._push(zn,4,t.lo)._push(zn,4,t.hi)}fixed64Number(e){let t=ze.fromNumber(e);return this._push(zn,4,t.lo)._push(zn,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(Th,4,e)}double(e){return this._push(_h,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(Fa,1,0):this.uint32(t)._push(q0,t,e)}string(e){let t=Oh(e);return t!==0?this.uint32(t)._push(Oa,t,e):this._push(Fa,1,0)}fork(){return this.states=new ka(this),this.head=this.tail=new yr(Ua,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 yr(Ua,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=z0(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function Fa(r,e,t){e[t]=r&255}function V0(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var Ma=class extends yr{next;constructor(e,t){super(V0,e,t),this.next=void 0}};function ys(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function zn(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function q0(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(Vn.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(j0,e,r),this},Vn.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(W0,e,r),this});function j0(r,e,t){e.set(r,t)}function W0(r,e,t){r.length<40?Oa(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(Q(r),t)}function Ka(){return new Vn}function Gt(r,e){let t=Ka();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}function*Xt(r,e,t){let n=$n(r);yield*e.stream(n,void 0,"$",t)}var bs={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function ws(r,e,t,n,o){return{name:r,type:e,encode:t,decode:n,stream:o}}function br(r){function e(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let t=function(i,a){let c=e(i);a.int32(c)},n=function(i){let a=i.int32();return e(a)},o=function*(i){let a=i.int32();yield e(a)};return ws("enum",bs.VARINT,t,n,o)}function Yt(r,e,t){return ws("message",bs.LENGTH_DELIMITED,r,e,t)}var he;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(he||(he={}));var Ha;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(Ha||(Ha={}));(function(r){r.codec=()=>br(Ha)})(he||(he={}));var dt;(function(r){let e;r.codec=()=>(e==null&&(e=Yt((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),he.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{c.Type=he.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:he.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return Gt(s,r.codec())}r.encode=t;function n(s,i){return Wt(s,r.codec(),i)}r.decode=n;function o(s,i){return Xt(s,r.codec(),i)}r.stream=o})(dt||(dt={}));var $a;(function(r){let e;r.codec=()=>(e==null&&(e=Yt((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),he.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{c.Type=he.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:he.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return Gt(s,r.codec())}r.encode=t;function n(s,i){return Wt(s,r.codec(),i)}r.decode=n;function o(s,i){return Xt(s,r.codec(),i)}r.stream=o})($a||($a={}));var jn={};oe(jn,{MAX_RSA_KEY_SIZE:()=>za,generateRSAKeyPair:()=>Kh,jwkToJWKKeyPair:()=>Hh,jwkToPkcs1:()=>Z0,jwkToPkix:()=>Wa,jwkToRSAPrivateKey:()=>Za,pkcs1MessageToJwk:()=>qa,pkcs1MessageToRSAPrivateKey:()=>Ga,pkcs1ToJwk:()=>Y0,pkcs1ToRSAPrivateKey:()=>Mh,pkixMessageToJwk:()=>ja,pkixMessageToRSAPublicKey:()=>Ya,pkixToJwk:()=>J0,pkixToRSAPublicKey:()=>Xa});var Gr=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=jn.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return ye.createV1(114,this._multihash)}toString(){return de.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Se(this.raw,e.raw)}verify(e,t,n){return kh(this.jwk,t,e,n)}},qn=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=jn.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Se(this.raw,e.raw)}sign(e,t){return Fh(this.jwk,e,t)}};var za=8192,Va=18,G0=1062,X0=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function Y0(r){let e=xt(r);return qa(e)}function qa(r){return{n:Y(r[1],"base64url"),e:Y(r[2],"base64url"),d:Y(r[3],"base64url"),p:Y(r[4],"base64url"),q:Y(r[5],"base64url"),dp:Y(r[6],"base64url"),dq:Y(r[7],"base64url"),qi:Y(r[8],"base64url"),kty:"RSA"}}function Z0(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new W("JWK was missing components");return Nt([Fe(Uint8Array.from([0])),Fe(Q(r.n,"base64url")),Fe(Q(r.e,"base64url")),Fe(Q(r.d,"base64url")),Fe(Q(r.p,"base64url")),Fe(Q(r.q,"base64url")),Fe(Q(r.dp,"base64url")),Fe(Q(r.dq,"base64url")),Fe(Q(r.qi,"base64url"))]).subarray()}function J0(r){let e=xt(r,{offset:0});return ja(e)}function ja(r){let e=xt(r[1],{offset:0});return{kty:"RSA",n:Y(e[0],"base64url"),e:Y(e[1],"base64url")}}function Wa(r){if(r.n==null||r.e==null)throw new W("JWK was missing components");return Nt([X0,$o(Nt([Fe(Q(r.n,"base64url")),Fe(Q(r.e,"base64url"))]))]).subarray()}function Mh(r){let e=xt(r);return Ga(e)}function Ga(r){let e=qa(r);return Za(e)}function Xa(r,e){if(r.byteLength>=G0)throw new Ir("Key size is too large");let t=xt(r,{offset:0});return Ya(t,r,e)}function Ya(r,e,t){let n=ja(r);if(t==null){let o=ft(dt.encode({Type:he.RSA,Data:e}));t=Pe(Va,o)}return new Gr(n,t)}function Za(r){if(zh(r)>za)throw new W("Key size is too large");let e=Hh(r),t=ft(dt.encode({Type:he.RSA,Data:Wa(e.publicKey)})),n=Pe(Va,t);return new qn(e.privateKey,new Gr(e.publicKey,n))}async function Kh(r){if(r>za)throw new W("Key size is too large");let e=await $h(r),t=ft(dt.encode({Type:he.RSA,Data:Wa(e.publicKey)})),n=Pe(Va,t);return new qn(e.privateKey,new Gr(e.publicKey,n))}function Hh(r){if(r==null)throw new W("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function $h(r,e){let t=await Ye.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);e?.signal?.throwIfAborted();let n=await Q0(t,e);return{privateKey:n[0],publicKey:n[1]}}async function Fh(r,e,t){let n=await Ye.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let o=await Ye.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,Ae(e instanceof Uint8Array?e:e.subarray()));return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function kh(r,e,t,n){let o=await Ye.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let s=await Ye.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,Ae(e),Ae(t instanceof Uint8Array?t:t.subarray()));return n?.signal?.throwIfAborted(),s}async function Q0(r,e){if(r.privateKey==null||r.publicKey==null)throw new W("Private and public key are required");let t=await Promise.all([Ye.get().subtle.exportKey("jwk",r.privateKey),Ye.get().subtle.exportKey("jwk",r.publicKey)]);return e?.signal?.throwIfAborted(),t}function zh(r){if(r.kty!=="RSA")throw new W("invalid key type");if(r.n==null)throw new W("invalid key modulus");return Q(r.n,"base64url").length*8}var xs=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(lr(e),Ne(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("expected Hash instance");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(t.length>n?e.create().update(t).digest():t);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),We(o)}update(e){return Kr(this),this.iHash.update(e),this}digestInto(e){Kr(this),qo(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a,canXOF:c}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.canXOF=c,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Wn=(()=>{let r=((e,t,n)=>new xs(e,t).update(n).digest());return r.create=(e,t)=>new xs(e,t),r})();var eg=BigInt(0),Ja=class extends Error{constructor(e=""){super(e)}},At={Err:Ja,_tlv:{encode:(r,e)=>{let{Err:t}=At;if(zt(r,"tag"),r<0||r>255)throw new t("tlv.encode: wrong tag");if(Xu(e,"data"),e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,o=On(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let s=n>127?On(o.length/2|128):"";return On(r)+s+o+e},decode(r,e){let{Err:t}=At;e=j(e,void 0,"DER data");let n=0;if(r<0||r>255)throw new t("tlv.decode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let o=e[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let f=e.subarray(n,n+c);if(f.length!==c)throw new t("tlv.decode: length bytes not complete");if(f[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let u of f)i=i<<8|u;if(n+=c,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(r){let{Err:e}=At;if(Zo(r),r<eg)throw new e("integer: negative integers are not allowed");let t=On(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(r){let{Err:e}=At;if(r.length<1)throw new e("invalid signature integer: empty");if(r[0]&128)throw new e("invalid signature integer: negative");if(r.length>1&&r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return ut(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=At,o=j(r,void 0,"signature"),{v:s,l:i}=n.decode(48,o);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:f,l:u}=n.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(f)}},hexFromSig(r){let{_tlv:e,_int:t}=At;Be(r,{r:"bigint",s:"bigint"},{},"sig");let n=e.encode(2,t.encode(r.r)),o=e.encode(2,t.encode(r.s)),s=n+o;return e.encode(48,s)}},Qa=(Object.freeze(At._tlv),Object.freeze(At._int),Object.freeze(At));var Vh=(r,e)=>(r+(r>=0?e:-e)/qh)/e;function tg(r,e,t){lt("scalar",r,vt,t);let[[n,o],[s,i]]=e,a=Vh(i*r,t),c=Vh(-o*r,t),f=r-a*n-c*s,u=-a*o-c*i,h=f<vt,l=u<vt;h&&(f=-f),l&&(u=-u);let d=Nn(Math.ceil($r(t)/2))+wr;if(f<vt||f>=d||u<vt||u>=d)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:h,k1:f,k2neg:l,k2:u}}function rc(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function ec(r,e){Be(r);let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return ke(t.lowS,"lowS"),ke(t.prehash,"prehash"),t.format!==void 0&&rc(t.format),t}var vt=BigInt(0),wr=BigInt(1),qh=BigInt(2),tc=BigInt(3),rg=BigInt(4);function jh(r,e={}){let t=ss("weierstrass",r,e),n=t.Fp,o=t.Fn,s=t.CURVE,{h:i,n:a}=s;Be(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",randomBytes:"function"});let{endo:c,allowInfinityPoint:f}=e,u=e.randomBytes===void 0?Et:e.randomBytes;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let h=Gh(n,o);function l(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function d(D,p,S){if(f&&p.is0())return Uint8Array.of(0);let{x:C,y:A}=p.toAffine(),v=n.toBytes(C);if(ke(S,"isCompressed"),S){l();let y=!n.isOdd(A);return Ge(Wh(y),v)}else return Ge(Uint8Array.of(4),v,n.toBytes(A))}function b(D){j(D,void 0,"Point");let{publicKey:p,publicKeyUncompressed:S}=h,C=D.length,A=D[0],v=D.subarray(1);if(f&&C===1&&A===0)return{x:n.ZERO,y:n.ZERO};if(C===p&&(A===2||A===3)){let y=n.fromBytes(v);if(!n.isValid(y))throw new Error("bad point: is not on curve, wrong x");let B=x(y),P;try{P=n.sqrt(B)}catch(V){let z=V instanceof Error?": "+V.message:"";throw new Error("bad point: is not on curve, sqrt error"+z)}l();let K=n.isOdd(P);return(A&1)===1!==K&&(P=n.neg(P)),{x:y,y:P}}else if(C===S&&A===4){let y=n.BYTES,B=n.fromBytes(v.subarray(0,y)),P=n.fromBytes(v.subarray(y,y*2));if(!L(B,P))throw new Error("bad point: is not on curve");return{x:B,y:P}}else throw new Error(`bad point: got length ${C}, expected compressed=${p} or uncompressed=${S}`)}let w=e.toBytes===void 0?d:e.toBytes,g=e.fromBytes===void 0?b:e.fromBytes,m=n.mul(s.b,tc),E=n.is0(s.a)?D=>n.ZERO:D=>n.mul(s.a,D);function x(D){let p=n.sqr(D),S=n.mul(p,D);return n.add(n.add(S,n.mul(D,s.a)),s.b)}function L(D,p){let S=n.sqr(p),C=x(D);return n.eql(S,C)}if(!L(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let T=n.mul(n.pow(s.a,tc),rg),F=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(T,F)))throw new Error("bad curve params: a or b");function O(D,p,S=!1){if(!n.isValid(p)||S&&n.is0(p))throw new Error(`bad point coordinate ${D}`);return p}function N(D){if(!(D instanceof R))throw new Error("Weierstrass Point expected")}function I(D){if(!c||!c.basises)throw new Error("no endo");return tg(D,c.basises,o.ORDER)}function U(D,p,S,C){if(!o.isValid(C))throw new RangeError("invalid scalar: out of range");if(c){let{k1neg:A,k1:v,k2neg:y,k2:B}=I(C),P=new R(n.mul(S.X,c.beta),S.Y,S.Z);D.push(A?S.negate():S,y?P.negate():P),p.push(v,B)}else D.push(S),p.push(C)}let k=new WeakSet;class R{static BASE=new R(s.Gx,s.Gy,n.ONE);static ZERO=new R(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(p,S,C){this.X=O("x",p),this.Y=O("y",S,!0),this.Z=O("z",C),Object.freeze(this)}static CURVE(){return s}static fromAffine(p){let{x:S,y:C}=p||{};if(!p||!n.isValid(S)||!n.isValid(C))throw new Error("invalid affine point");if(p instanceof R)throw new Error("projective point not allowed");return n.is0(S)&&n.is0(C)?R.ZERO:new R(S,C,n.ONE)}static fromBytes(p){let S=R.fromAffine(g(j(p,void 0,"point")));return S.assertValidity(),S}static fromHex(p){return R.fromBytes(Hr(p))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(p=6,S=!0){return _.setWindowSize(this,p),S||this.multiply(tc),this}assertValidity(){let p=this;if(p.is0()){if(e.allowInfinityPoint&&n.is0(p.X)&&n.eql(p.Y,n.ONE)&&n.is0(p.Z))return;throw new Error("bad point: ZERO")}if(k.has(p))return;let{x:S,y:C}=p.toAffine();if(!n.isValid(S)||!n.isValid(C))throw new Error("bad point: x or y not field elements");if(!L(S,C))throw new Error("bad point: equation left != right");if(!p.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");k.add(p)}hasEvenY(){let{y:p}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(p)}equals(p){N(p);let{X:S,Y:C,Z:A}=this,{X:v,Y:y,Z:B}=p,P=n.eql(n.mul(S,B),n.mul(v,A)),K=n.eql(n.mul(C,B),n.mul(y,A));return P&&K}negate(){return new R(this.X,n.neg(this.Y),this.Z)}double(){let{X:p,Y:S,Z:C}=this,A=n.ZERO,v=n.ZERO,y=n.ZERO,B=n.mul(p,p),P=n.mul(S,S),K=n.mul(C,C),M=n.mul(p,S);return M=n.add(M,M),y=n.mul(p,C),y=n.add(y,y),A=E(y),v=n.mul(m,K),v=n.add(A,v),A=n.sub(P,v),v=n.add(P,v),v=n.mul(A,v),A=n.mul(M,A),y=n.mul(m,y),K=E(K),M=n.sub(B,K),M=E(M),M=n.add(M,y),y=n.add(B,B),B=n.add(y,B),B=n.add(B,K),B=n.mul(B,M),v=n.add(v,B),K=n.mul(S,C),K=n.add(K,K),B=n.mul(K,M),A=n.sub(A,B),y=n.mul(K,P),y=n.add(y,y),y=n.add(y,y),new R(A,v,y)}add(p){N(p);let{X:S,Y:C,Z:A}=this,{X:v,Y:y,Z:B}=p,P=n.ZERO,K=n.ZERO,M=n.ZERO,V=n.mul(S,v),z=n.mul(C,y),X=n.mul(A,B),ae=n.add(S,C),ce=n.add(v,y);ae=n.mul(ae,ce),ce=n.add(V,z),ae=n.sub(ae,ce),ce=n.add(S,A);let ge=n.add(v,B);return ce=n.mul(ce,ge),ge=n.add(V,X),ce=n.sub(ce,ge),ge=n.add(C,A),P=n.add(y,B),ge=n.mul(ge,P),P=n.add(z,X),ge=n.sub(ge,P),M=E(ce),P=n.mul(m,X),M=n.add(P,M),P=n.sub(z,M),M=n.add(z,M),K=n.mul(P,M),z=n.add(V,V),z=n.add(z,V),X=E(X),ce=n.mul(m,ce),z=n.add(z,X),X=n.sub(V,X),X=E(X),ce=n.add(ce,X),V=n.mul(z,ce),K=n.add(K,V),V=n.mul(ge,ce),P=n.mul(ae,P),P=n.sub(P,V),V=n.mul(ae,z),M=n.mul(ge,M),M=n.add(M,V),new R(P,K,M)}subtract(p){return N(p),this.add(p.negate())}is0(){return this.equals(R.ZERO)}multiply(p){if(!o.isValidNot0(p))throw new RangeError("invalid scalar: out of range");let{p:S,f:C}=_.mulSecret(this,p,i,H);return H([S,C])[0]}multiplyUnsafe(p){let S=this,C=p;if(!o.isValid(C))throw new RangeError("invalid scalar: out of range");if(C===vt||S.is0())return R.ZERO;if(C===wr)return S;if(_.hasWindowSize(this))return _.mulUnsafe(S,C,H);let A=[],v=[];return U(A,v,S,C),os(R,A,v)}mulAddUnsafe(p,S,C){N(S);let A=[],v=[];return U(A,v,this,p),U(A,v,S,C),os(R,A,v)}toAffine(p){let S=this,C=p;if(C!=null&&!n.isValid(C))throw new RangeError('"invertedZ" expected valid field element');let{X:A,Y:v,Z:y}=S;if(n.eql(y,n.ONE))return{x:A,y:v};let B=S.is0();C==null&&(C=B?n.ONE:n.inv(y));let P=n.mul(A,C),K=n.mul(v,C),M=n.mul(y,C);if(B)return{x:n.ZERO,y:n.ZERO};if(!n.eql(M,n.ONE))throw new Error("invZ was invalid");return{x:P,y:K}}isTorsionFree(){let{isTorsionFree:p}=e;return i===wr?!0:p?p(R,this):_.mulUnsafe(this,a).is0()}clearCofactor(){let{clearCofactor:p}=e;return i===wr?this:p?p(R,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===wr?this.is0():this.clearCofactor().is0()}toBytes(p=!0){return ke(p,"isCompressed"),this.assertValidity(),w(R,this,p)}toHex(p=!0){return Rn(this.toBytes(p))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let H=D=>ns(R,D),_=new qr(R,u);return _.bits>=6&&R.BASE.precompute(6),Object.freeze(R.prototype),Object.freeze(R),R}function Wh(r){return Uint8Array.of(r?2:3)}function Gh(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function ng(r,e={}){qt(r);let{Fn:t}=r,n=e.randomBytes===void 0?Et:e.randomBytes,o=Object.assign(Gh(r.Fp,t),{seed:Math.max(ts(t.ORDER),16)});function s(d){try{let b=t.fromBytes(d);return t.isValidNot0(b)}catch{return!1}}function i(d,b){let{publicKey:w,publicKeyUncompressed:g}=o;try{let m=d.length;return b===!0&&m!==w||b===!1&&m!==g?!1:!!r.fromBytes(d)}catch{return!1}}function a(d){return d=d===void 0?n(o.seed):d,rs(j(d,o.seed,"seed"),t.ORDER)}function c(d,b=!0){return r.BASE.multiply(t.fromBytes(d)).toBytes(b)}function f(d){let{secretKey:b,publicKey:w,publicKeyUncompressed:g}=o,m=t._lengths;if(!$t(d))return;let E=j(d,void 0,"key").length,x=E===w||E===g,L=E===b||!!m?.includes(E);if(!(x&&L))return x}function u(d,b,w=!0){if(f(d)===!0)throw new Error("first arg must be private key");if(f(b)===!1)throw new Error("second arg must be public key");let g=t.fromBytes(d);return r.fromBytes(b).multiply(g).toBytes(w)}let h={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},l=jr(a,c);return Object.freeze(h),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:l,Point:r,utils:h,lengths:o})}function Xh(r,e,t={}){qt(r);let n=e;lr(n),Be(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let o=Object.assign({},t),s=o.randomBytes===void 0?Et:o.randomBytes,i=o.hmac===void 0?(v,y)=>Wn(n,v,y):o.hmac,{Fp:a,Fn:c}=r,{ORDER:f,BITS:u}=c,h=ts(f),l=xa(s,h),{keygen:d,getPublicKey:b,getSharedSecret:w,utils:g,lengths:m}=ng(r,o),E={prehash:!0,lowS:typeof o.lowS=="boolean"?o.lowS:!0,format:"compact",extraEntropy:!1},x=f*qh+wr<a.ORDER;function L(v){let y=f>>wr;return v>y}function T(v,y){if(!c.isValidNot0(y))throw new Error(`invalid signature ${v}: out of range 1..Point.Fn.ORDER`);return y}function F(){if(!a.isOdd)throw new Error("Field doesn't support isOdd")}function O(v,y,B){return F(),(v===B?0:2)|Number(a.isOdd(y))}function N(){if(x)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function I(v,y){rc(y);let B=m.signature,P=y==="compact"?B:y==="recovered"?B+1:void 0;return j(v,P)}class U{r;s;recovery;constructor(y,B,P){if(this.r=T("r",y),this.s=T("s",B),P!=null){if(N(),![0,1,2,3].includes(P))throw new Error("invalid recovery id");this.recovery=P}Object.freeze(this)}static fromBytes(y,B=E.format){I(y,B);let P;if(B==="der"){let{r:z,s:X}=Qa.toSig(j(y));return new U(z,X)}B==="recovered"&&(P=y[0],B="compact",y=y.subarray(1));let K=m.signature/2,M=y.subarray(0,K),V=y.subarray(K,K*2);return new U(c.fromBytes(M),c.fromBytes(V),P)}static fromHex(y,B){return this.fromBytes(Hr(y),B)}assertRecovery(){let{recovery:y}=this;if(y==null)throw new Error("invalid recovery id: must be present");return y}addRecoveryBit(y){return new U(this.r,this.s,y)}recoverPublicKey(y){let{r:B,s:P}=this,K=this.assertRecovery(),M=K===2||K===3?B+f:B;if(!a.isValid(M))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let V=a.toBytes(M),z=r.fromBytes(Ge(Wh((K&1)===0),V)),X=c.inv(M),ae=R(j(y,void 0,"msgHash")),ce=c.create(-ae*X),ge=c.create(P*X),Ke=r.BASE.mulAddUnsafe(ce,z,ge);if(Ke.is0())throw new Error("invalid recovery: point at infinify");return Ke.assertValidity(),Ke}hasHighS(){return L(this.s)}toBytes(y=E.format){if(rc(y),y==="der")return Hr(Qa.hexFromSig(this));let{r:B,s:P}=this,K=c.toBytes(B),M=c.toBytes(P);return y==="recovered"?(N(),Ge(Uint8Array.of(this.assertRecovery()),K,M)):Ge(K,M)}toHex(y){return Rn(this.toBytes(y))}}Object.freeze(U.prototype),Object.freeze(U);let k=o.bits2int===void 0?function(y){if(y.length>8192)throw new Error("input is too large");let B=ut(y),P=y.length*8-u;return P>0?B>>BigInt(P):B}:o.bits2int,R=o.bits2int_modN===void 0?function(y){return c.create(k(y))}:o.bits2int_modN,H=Nn(u);function _(v){return lt("num < 2^"+u,v,vt,H),c.toBytes(v)}function D(v,y){return j(v,void 0,"message"),y?j(n(v),void 0,"prehashed message"):v}function p(v,y,B){let{lowS:P,prehash:K,extraEntropy:M}=ec(B,E);v=D(v,K);let V=R(v),z=c.fromBytes(y);if(!c.isValidNot0(z))throw new Error("invalid private key");let X=[_(z),_(V)];if(M!=null&&M!==!1){let Ke=M===!0?s(m.secretKey):M;X.push(j(Ke,void 0,"extraEntropy"))}let ae=Ge(...X),ce=V;function ge(Ke){let bt=k(Ke);if(!c.isValidNot0(bt))return;let sr=r.BASE.multiply(bt).toAffine(),st=c.create(sr.x);if(st===vt)return;let He;if(l!==void 0){let It=ut(rs(l(h),f)),fp=c.inv(c.mul(It,bt)),up=c.mul(It,ce),hp=c.mul(It,z);He=c.create(fp*c.create(up+hp*st))}else{let It=sh(bt,f);He=c.create(It*c.create(ce+st*z))}if(He===vt)return;let _r=O(sr.x,sr.y,st),xn=He;return P&&L(He)&&(xn=c.neg(He),_r^=1),new U(st,xn,x?void 0:_r)}return{seed:ae,k2sig:ge}}function S(v,y,B={}){let{seed:P,k2sig:K}=p(v,y,B);return Zu(n.outputLen,c.BYTES,i)(P,K).toBytes(B.format)}function C(v,y,B,P={}){let{lowS:K,prehash:M,format:V}=ec(P,E);if(B=j(B,void 0,"publicKey"),y=D(y,M),!$t(v)){let z=v instanceof U?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+z)}I(v,V);try{let z=U.fromBytes(v,V),X=r.fromBytes(B);if(K&&z.hasHighS())return!1;let{r:ae,s:ce}=z,ge=R(y),Ke=c.inv(ce),bt=c.create(ge*Ke),sr=c.create(ae*Ke),st=r.BASE.mulAddUnsafe(bt,X,sr);if(st.is0())return!1;let He=st.toAffine();return!(c.create(He.x)!==ae||V==="recovered"&&z.recovery!==O(He.x,He.y,ae))}catch{return!1}}function A(v,y,B={}){let{prehash:P}=ec(B,E);return y=D(y,P),U.fromBytes(v,"recovered").recoverPublicKey(y).toBytes()}return Object.freeze({keygen:d,getPublicKey:b,getSharedSecret:w,utils:g,lengths:m,Point:r,sign:S,verify:C,recoverPublicKey:A,Signature:U,hash:n})}var oc={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},og={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Yh=BigInt(2);function sg(r){let e=oc.p,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),f=r*r*r%e,u=f*f*r%e,h=fe(u,t,e)*u%e,l=fe(h,t,e)*u%e,d=fe(l,Yh,e)*f%e,b=fe(d,o,e)*d%e,w=fe(b,s,e)*b%e,g=fe(w,a,e)*w%e,m=fe(g,c,e)*g%e,E=fe(m,a,e)*w%e,x=fe(E,t,e)*u%e,L=fe(x,i,e)*b%e,T=fe(L,n,e)*f%e,F=fe(T,Yh,e);if(!nc.eql(nc.sqr(F),r))throw new Error("Cannot find square root");return F}var nc=Vr(oc.p,{sqrt:sg}),ig=jh(oc,{Fp:nc,endo:og}),Xr=Xh(ig,ft);function Zh(r,e,t,n){let o=wt.digest(t instanceof Uint8Array?t:t.subarray());if(ds(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),Xr.verify(e,s,r,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new Kn(String(s))});try{return n?.signal?.throwIfAborted(),Xr.verify(e,o.digest,r,{prehash:!1,format:"der"})}catch(s){throw new Kn(String(s))}}var Es=class{type="secp256k1";raw;_key;constructor(e){this._key=Qh(e),this.raw=Jh(this._key)}toMultihash(){return Qe.digest(Ut(this))}toCID(){return ye.createV1(114,this.toMultihash())}toString(){return de.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Se(this.raw,e.raw)}verify(e,t,n){return Zh(this._key,t,e,n)}};function sc(r){return new Es(r)}function Jh(r){return Xr.Point.fromBytes(r).toBytes()}function Qh(r){try{return Xr.Point.fromBytes(r),r}catch(e){throw new Ir(String(e))}}function Gn(r,e){let{Type:t,Data:n}=dt.decode(r),o=n??new Uint8Array;switch(t){case he.RSA:return Xa(o,e);case he.Ed25519:return Ca(o);case he.secp256k1:return sc(o);case he.ECDSA:return ea(o);default:throw new ir}}function el(r){let{Type:e,Data:t}=dt.decode(r.digest),n=t??new Uint8Array;switch(e){case he.Ed25519:return Ca(n);case he.secp256k1:return sc(n);case he.ECDSA:return ea(n);default:throw new ir}}function Ut(r){return dt.encode({Type:he[r.type],Data:r.raw})}var tl=Symbol.for("nodejs.util.inspect.custom"),ag=114,Xn=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[vi]=!0;toString(){return this.string==null&&(this.string=de.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return ye.createV1(ag,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return Se(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return Se(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[tl](){return`PeerId(${this.toString()})`}},Yn=class extends Xn{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Zn=class extends Xn{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},Jn=class extends Xn{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},cg=2336,Qn=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Qe.digest(Q(this.url))}[tl](){return`PeerId(${this.url})`}[vi]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return ye.createV1(cg,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=Y(e)),e.toString()===this.toString())}};var fg=114,rl=2336;function Yr(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=kr(de.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return ug(ye.parse(r));if(e==null)throw new W('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=kr(e.decode(r))}return nl(t)}function ic(r){if(r.type==="Ed25519")return new Zn({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new Jn({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new Yn({multihash:r.toCID().multihash,publicKey:r});throw new ir}function nl(r){if(lg(r))return new Yn({multihash:r});if(hg(r))try{let e=el(r);if(e.type==="Ed25519")return new Zn({multihash:r,publicKey:e});if(e.type==="secp256k1")return new Jn({multihash:r,publicKey:e})}catch{let t=Y(r.digest);return new Qn(new URL(t))}throw new Oo("Supplied PeerID Multihash is invalid")}function ug(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==fg&&r.code!==rl)throw new Ro("Supplied PeerID CID is invalid");if(r.code===rl){let e=Y(r.multihash.digest);return new Qn(new URL(e))}return nl(r.multihash)}function hg(r){return r.code===Qe.code}function lg(r){return r.code===wt.code}var ve=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Ct=class extends Error{static name="ValidationError";name="ValidationError"},Ss=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},As=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var vs=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",f=2**(8*o)-1;for(;;){let u=this.readAtomically(()=>{let h=this.readChar();if(h===void 0)return;let l=Number.parseInt(h,e);if(!Number.isNaN(l))return l});if(u===void 0)break;if(s*=e,s+=u,s>f||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var dg=45,pg=15,Cs=new vs;function ol(r){if(!(r.length>pg))return Cs.new(r).parseWith(()=>Cs.readIPv4Addr())}function sl(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>dg))return Cs.new(r).parseWith(()=>Cs.readIPv6Addr())}function Ls(r){return!!ol(r)}function il(r){return!!sl(r)}function cc(r){return e=>Y(e,r)}function fc(r){return e=>Q(e,r)}function Zr(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function xr(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function al(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=Q(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=xr(n);return $e([t,o],t.length+o.length)}function cl(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=Pt.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=xr(n);return $e([t,o],t.length+o.length)}function uc(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=Y(e,"base32"),o=Zr(t);return`${n}:${o}`}var hc=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let o=parseInt(t,10);if(isNaN(o)||o<0||o>255)throw new ve("Invalid byte value in IP address");e[n]=o}),e},fl=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=Ls(t[n]),i;s&&(i=hc(t[n]),t[n]=Y(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,Y(i.subarray(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let s=parseInt(t[n],16);if(isNaN(s)||s<0||s>65535)throw new ve("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},ul=function(r){if(r.byteLength!==4)throw new ve("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},hl=function(r){if(r.byteLength!==16)throw new ve("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],s=r[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new ve(`Invalid IPv6 address "${t}"`)}};function ll(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new ve(`Invalid IPv6 address "${r}"`)}}var ac=Object.values(fr).map(r=>r.decoder),mg=(function(){let r=ac[0].or(ac[1]);return ac.slice(2).forEach(e=>r=r.or(e)),r})();function dl(r){return mg.decode(r)}function pl(r){return e=>r.encoder.encode(e)}function gg(r){if(parseInt(r).toString()!==r)throw new Ct("Value must be an integer")}function yg(r){if(r<0)throw new Ct("Value must be a positive integer, or zero")}function bg(r){return e=>{if(e>r)throw new Ct(`Value must be smaller than or equal to ${r}`)}}function wg(...r){return e=>{for(let t of r)t(e)}}var eo=wg(gg,yg,bg(65535));var Ee=-1,lc=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(typeof e=="string"?t=this.protocolsByName.get(e):t=this.protocolsByCode.get(e),t==null)throw new As(`Protocol ${e} was unknown`);return t}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(t=>{this.protocolsByName.set(t,e)})}removeProtocol(e){let t=this.protocolsByCode.get(e);t!=null&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},Bt=new lc,Og=[{code:4,name:"ip4",size:32,valueToBytes:hc,bytesToValue:ul,validate:r=>{if(!Ls(r))throw new Ct(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:xr,bytesToValue:Zr,validate:eo},{code:273,name:"udp",size:16,valueToBytes:xr,bytesToValue:Zr,validate:eo},{code:33,name:"dccp",size:16,valueToBytes:xr,bytesToValue:Zr,validate:eo},{code:41,name:"ip6",size:128,valueToBytes:fl,bytesToValue:hl,stringToValue:ll,validate:r=>{if(!il(r))throw new Ct(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:Ee},{code:43,name:"ipcidr",size:8,bytesToValue:cc("base10"),valueToBytes:fc("base10")},{code:53,name:"dns",size:Ee},{code:54,name:"dns4",size:Ee},{code:55,name:"dns6",size:Ee},{code:56,name:"dnsaddr",size:Ee},{code:132,name:"sctp",size:16,valueToBytes:xr,bytesToValue:Zr,validate:eo},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:Ee,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:Ee,bytesToValue:cc("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?fc("base58btc")(r):ye.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:uc,valueToBytes:al},{code:445,name:"onion3",size:296,bytesToValue:uc,valueToBytes:cl},{code:446,name:"garlic64",size:Ee},{code:447,name:"garlic32",size:Ee},{code:448,name:"tls"},{code:449,name:"sni",size:Ee},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:Ee,bytesToValue:pl(Ln),valueToBytes:dl},{code:480,name:"http"},{code:481,name:"http-path",size:Ee,stringToValue:r=>`/${decodeURIComponent(r)}`,valueToString:r=>encodeURIComponent(r.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:Ee}];Og.forEach(r=>{Bt.addProtocol(r)});function ml(r){let e=[],t=0;for(;t<r.length;){let n=St(r,t),o=Bt.getProtocol(n),s=ue(n),i=Pg(o,r,t+s),a=0;i>0&&o.size===Ee&&(a=ue(i));let c=s+a+i,f={code:n,name:o.name,bytes:Ae(r.subarray(t,t+c))};if(i>0){let u=t+s+a,h=r.subarray(u,u+i);f.value=o.bytesToValue?.(h)??Y(h)}e.push(f),t+=c}return e}function gl(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=Bt.getProtocol(n.code),s=ue(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??Q(n.value),a=i.byteLength,o.size===Ee&&(c=ue(a)));let f=new Uint8Array(s+c+a),u=0;Wr(n.code,f,u),u+=s,i!=null&&(o.size===Ee&&(Wr(a,f,u),u+=c),f.set(i,u)),n.bytes=f}t.push(n.bytes),e+=n.bytes.byteLength}return $e(t,e)}function yl(r){if(r.charAt(0)!=="/")throw new ve('String multiaddr must start with "/"');let e=[],t="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(t==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=Bt.getProtocol(o);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",t="protocol";continue}else if(a)throw new ve(`Component ${o} was missing value`);t="value"}else if(t==="value"){let f={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new ve(`Component ${o} was missing value`);f.value=c.stringToValue?.(n)??n}e.push(f),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new ve("Incomplete multiaddr");return e}function bl(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=Bt.getProtocol(e.code);if(t==null)throw new ve(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function Pg(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:St(e,t)}var Ng=Symbol.for("nodejs.util.inspect.custom"),Dc=Symbol.for("@multiformats/multiaddr");function Ug(r){if(r==null&&(r="/"),wl(r))return r.getComponents();if(r instanceof Uint8Array)return ml(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),yl(r);if(Array.isArray(r))return r;throw new ve("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Is=class r{[Dc]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=Ug(e),t.validate!==!1&&Fg(this)}get bytes(){return this.#r==null&&(this.#r=gl(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=bl(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new Ss(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,o),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}equals(e){return Se(this.bytes,e.bytes)}[Ng](){return`Multiaddr(${this.toString()})`}};function Fg(r){r.getComponents().forEach(e=>{let t=Bt.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function wl(r){return!!r?.[Dc]}function tn(r){return new Is(r)}var se=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),$=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),xl=r=>({match:e=>r.match(e)===!1?e:!1}),q=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),_e=(...r)=>({match:e=>{let t;for(let n of r){let o=n.match(e);o!==!1&&(t==null||o.length<t.length)&&(t=o)}return t??!1}}),Z=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e}});function ie(...r){function e(o){if(o==null)return!1;let s=o.getComponents();for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function t(o){return e(o)!==!1}function n(o){let s=e(o);return s===!1?!1:s.length===0}return{matchers:r,matches:t,exactMatch:n}}var kg=$(421),U6=ie(kg),Os=$(54),Ps=$(55),Ns=$(56),Ic=$(53),F6=ie(Os,q($(421))),k6=ie(Ps,q($(421))),M6=ie(Ns,q($(421))),K6=ie(_e(Ic,Ns,Os,Ps),q($(421))),El=Z($(4),q($(43))),Sl=Z(q($(42)),$(41),q($(43))),Rc=_e(El,Sl),rn=_e(Rc,Ic,Os,Ps,Ns),H6=ie(_e(Rc,Z(_e(Ic,Ns,Os,Ps),q($(421))))),$6=ie(El),z6=ie(Sl),V6=ie(Rc),Oc=Z(rn,$(6)),to=Z(rn,$(273)),q6=ie(Z(Oc,q($(421)))),j6=ie(to),Pc=Z(to,se(460),q($(421))),Us=Z(to,se(461),q($(421))),Mg=_e(Pc,Us),W6=ie(Pc),G6=ie(Us),_c=_e(rn,Oc,to,Pc,Us),Al=_e(Z(_c,se(477),q($(421)))),X6=ie(Al),vl=_e(Z(_c,se(478),q($(421))),Z(_c,se(448),q($(449)),se(477),q($(421)))),Y6=ie(vl),Cl=Z(to,se(280),q($(466)),q($(466)),q($(421))),Ll=ie(Cl),Bl=Z(Us,se(465),q($(466)),q($(466)),q($(421))),Z6=ie(Bl),Rs=_e(Al,vl,Z(Oc,q($(421))),Z(Mg,q($(421))),Z(rn,q($(421))),Cl,Bl,$(421)),Tl=ie(Rs),Kg=Z(q(Rs),se(290),xl(se(281)),q($(421))),J6=ie(Kg),Hg=_e(Z(Rs,se(290),se(281),q($(421))),Z(Rs,se(281),q($(421))),Z(se(281),q($(421)))),Dl=ie(Hg),$g=Z(rn,_e(Z($(6,"80")),Z($(6),se(480)),se(480)),q($(481)),q($(421))),Q6=ie($g),zg=Z(rn,_e(Z($(6,"443")),Z($(6,"443"),se(480)),Z($(6),se(443)),Z($(6),se(448),se(480)),Z(se(448),se(480)),se(448),se(443)),q($(481)),q($(421))),eA=ie(zg),Vg=_e(Z($(777),q($(421)))),tA=ie(Vg),qg=_e(Z($(400),q($(421)))),rA=ie(qg);var Ie;(function(r){let e;(function(a){a.FIN="FIN",a.STOP_SENDING="STOP_SENDING",a.RESET="RESET",a.FIN_ACK="FIN_ACK"})(e=r.Flag||(r.Flag={}));let t;(function(a){a[a.FIN=0]="FIN",a[a.STOP_SENDING=1]="STOP_SENDING",a[a.RESET=2]="RESET",a[a.FIN_ACK=3]="FIN_ACK"})(t||(t={})),(function(a){a.codec=()=>br(t)})(e=r.Flag||(r.Flag={}));let n;r.codec=()=>(n==null&&(n=Yt((a,c,f={})=>{f.lengthDelimited!==!1&&c.fork(),a.flag!=null&&(c.uint32(8),r.Flag.codec().encode(a.flag,c)),a.message!=null&&(c.uint32(18),c.bytes(a.message)),f.lengthDelimited!==!1&&c.ldelim()},(a,c,f={})=>{let u={},h=c==null?a.len:a.pos+c;for(;a.pos<h;){let l=a.uint32();switch(l>>>3){case 1:{u.flag=r.Flag.codec().decode(a);break}case 2:{u.message=a.bytes();break}default:{a.skipType(l&7);break}}}return u},function*(a,c,f,u={}){let h=c==null?a.len:a.pos+c;for(;a.pos<h;){let l=a.uint32();switch(l>>>3){case 1:{yield{field:`${f}.flag`,value:r.Flag.codec().decode(a)};break}case 2:{yield{field:`${f}.message`,value:a.bytes()};break}default:{a.skipType(l&7);break}}}})),n);function o(a){return Gt(a,r.codec())}r.encode=o;function s(a,c){return Wt(a,r.codec(),c)}r.decode=s;function i(a,c){return Xt(a,r.codec(),c)}r.stream=i})(Ie||(Ie={}));var _l=["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478","stun:stun.cloudflare.com:3478","stun:stun.services.mozilla.com:3478"],Nc=Array.from("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"),Il="libp2p+webrtc+v1/",Rl=2*1024*1024,Sr=16*1024,Ol=Sr,Pl=10,Nl=8;function jg(r=Sr){let e=ue(r-ue(r)),t=1+ue(Object.keys(Ie.Flag).length-1),n=1,o=r-e-t-n,s=ue(o);return e+t+n+s}var Ul=jg();var Fl=1e4,Uc="/webrtc",ro="/webrtc-signaling/0.0.1";function Wg(r){let e=r.getComponents(),t={},n=0;return e[n]?.name==="ip6zone"&&(t.zone=`${e[n].value}`,n++),e[n]?.name==="ip4"||e[n]?.name==="ip6"||e[n]?.name==="dns"||e[n]?.name==="dns4"||e[n]?.name==="dns6"?(t.type=e[n].name,t.host=e[n].value,n++):e[n]?.name==="dnsaddr"&&(t.type=e[n].name,t.host=`_dnsaddr.${e[n].value}`,n++),(e[n]?.name==="tcp"||e[n]?.name==="udp")&&(t.protocol=e[n].name==="tcp"?"tcp":"udp",t.port=parseInt(`${e[n].value}`),n++),e[n]?.name==="ipcidr"&&(t.type==="ip4"?t.cidr=parseInt(`${e[n].value}`):t.type==="ip6"&&(t.cidr=`${e[n].value}`),n++),t.type==null||t.host==null?null:(e[n]?.name==="tls"&&e[n+1]?.name==="sni"&&(t.sni=e[n+1].value,n+=2),t)}function Fc(r){let e=Wg(r);if(e==null)throw new W(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e}function Fs(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var ks=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},nn=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new ks(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new ks(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var kc=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function on(r={}){return Gg(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function Gg(r,e){e=e??{};let t=e.onEnd,n=new nn,o,s,i,a=Fs(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((g,m)=>{s=E=>{s=null,n.push(E);try{g(r(n))}catch(x){m(x)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Fs()})}},f=g=>s!=null?s(g):(n.push(g),o),u=g=>(n=new nn,s!=null?s({error:g}):(n.push({error:g}),o)),h=g=>{if(i)return o;if(e?.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})},l=g=>i?o:(i=!0,g!=null?u(g):f({done:!0})),d=()=>(n=new nn,l(),{done:!0}),b=g=>(l(g),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:d,throw:b,push:h,end:l,get readableLength(){return n.size},onEmpty:async g=>{let m=g?.signal;if(m?.throwIfAborted(),n.isEmpty())return;let E,x;m!=null&&(E=new Promise((L,T)=>{x=()=>{T(new kc)},m.addEventListener("abort",x)}));try{await Promise.race([a.promise,E])}finally{x!=null&&m!=null&&m?.removeEventListener("abort",x)}}},t==null)return o;let w=o;return o={[Symbol.asyncIterator](){return this},next(){return w.next()},throw(g){return w.throw(g),t!=null&&(t(g),t=void 0),{done:!0}},return(){return w.return(),t!=null&&(t(),t=void 0),{done:!0}},push:h,end(g){return w.end(g),t!=null&&(t(g),t=void 0),o},get readableLength(){return w.readableLength},onEmpty:g=>w.onEmpty(g)},o}var Mc=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},kl=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function Kc(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e,a,c,u=new Promise((h,l)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(i?.aborted){l(kl(i));return}if(i&&(c=()=>{l(kl(i))},i.addEventListener("abort",c,{once:!0})),r.then(h,l),t===Number.POSITIVE_INFINITY)return;let d=new Mc;a=s.setTimeout.call(void 0,()=>{if(n){try{h(n())}catch(b){l(b)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?h():o instanceof Error?l(o):(d.message=o??`Promise timed out after ${t} milliseconds`,l(d))},t)}).finally(()=>{u.clear(),c&&i&&i.removeEventListener("abort",c)});return u.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},u}var Xg=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function Yg(r,e,t){let n,o=new Promise((s,i)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:f,removeListener:u}=Xg(r),h=async(...d)=>{let b=t.multiArgs?d:d[0];if(t.filter)try{if(!await t.filter(b))return}catch(w){n(),i(w);return}c.push(b),t.count===c.length&&(n(),s(c))},l=(...d)=>{n(),i(t.rejectionMultiArgs?d:d[0])};n=()=>{for(let d of a)u(d,h);for(let d of t.rejectionEvents)a.includes(d)||u(d,l)};for(let d of a)f(d,h);for(let d of t.rejectionEvents)a.includes(d)||f(d,l);t.signal&&t.signal.addEventListener("abort",()=>{l(t.signal.reason)},{once:!0}),t.resolveImmediately&&s(c)});if(o.cancel=n,typeof t.timeout=="number"){let s=Kc(o,{milliseconds:t.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function Ce(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=Yg(r,e,t),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}var Ar=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"},Ms=class extends Error{static name="MaxEarlyStreamsError";name="MaxEarlyStreamsError"},Ks=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function Zg(r){return r.reason}function Tt(r,e,t){if(e==null||r==null)return r;let n=t?.translateError??Zg;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let o;return Promise.race([r,new Promise((s,i)=>{o=()=>{i(n(e))},e.addEventListener("abort",o)})]).finally(()=>{o!=null&&e.removeEventListener("abort",o)})}var Jg=Math.pow(2,20)*4,Jt=class extends Rt{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;#e=!1;onDrainPromise;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??Jg,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.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 t=()=>{this.writableNeedsDrain&&(this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,queueMicrotask(()=>{try{this.processSendQueue()}catch(o){this.log.error("processSendQueue threw - %e",o)}})),this.onDrainPromise?.resolve()};this.addEventListener("drain",t);let n=o=>{this.onDrainPromise?.reject(o.error??new Ks)};this.addEventListener("close",n)}get readBufferLength(){return this.readBuffer.byteLength}get readableEnded(){return this.#e}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),Tt(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let e=on(),t=s=>{e.push(s.data)};this.addEventListener("message",t);let n=s=>{e.end(s.error)};this.addEventListener("close",n);let o=()=>{e.end()};this.addEventListener("remoteCloseWrite",o);try{yield*e}finally{this.removeEventListener("message",t),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",o)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new it(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",e.byteLength),this.writeBuffer.append(e),this.processSendQueue()}abort(e){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",e),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(),this.maybeDispatchEnd();try{this.sendReset(e)}catch(t){this.log.error("failed to send reset to remote - %e",t)}this.dispatchEvent(new Uo(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new it("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 it("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new it(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.append(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}unshift(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new it(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.prepend(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(e){if(e.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(e),this.dispatchReadBuffer()}}addEventListener(...e){super.addEventListener.apply(this,e),e[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",this.maybeDispatchEnd()),this.dispatchEvent(new Fo(new Rr))}onTransportClosed(e){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"),e!=null?this.abort(e):(this.status==="open"||this.status==="closing")&&(this.timeline.close=Date.now(),this.status="closed",this.maybeDispatchEnd(),this.dispatchEvent(new Or))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.maybeDispatchEnd(),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;if(this.writeStatus!=="writable"&&this.writeStatus!=="closing")return this.log.trace("not processing send queue as stream is %s",this.writeStatus),!1;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let e=!0,t=this.writeBuffer.byteLength,n=0;for(;this.writeBuffer.byteLength>0;){let o=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(o===0){e=!1;break}let s=this.writeBuffer.sublist(0,o),i=new J(s);this.writeBuffer.consume(s.byteLength);let a;try{a=this.sendData(s)}catch(c){throw this.writeBuffer.prepend(i),this.abort(c),c}if(e=a.canSendMore,n+=a.sentBytes,a.sentBytes!==i.byteLength&&(i.consume(a.sentBytes),this.writeBuffer.prepend(i)),!e)break}return e||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",n,t,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),e}finally{this.sendingData=!1}}maybeDispatchEnd(){this.#e||this.readBuffer.byteLength>0||this.remoteWriteStatus!=="closed"&&this.readStatus!=="closed"||(this.#e=!0,this.safeDispatchEvent("end"))}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 e=this.readBuffer.sublist();this.readBuffer.consume(e.byteLength),this.dispatchEvent(new No(e))}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.maybeDispatchEnd()),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new En(`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 En(`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 Hs=class extends Jt{remoteAddr;metricPrefix;metrics;constructor(e){super(e),this.metricPrefix=e.metricPrefix??"",this.metrics=e.metrics,this.remoteAddr=e.remoteAddr,this.addEventListener("close",t=>{this.metrics?.increment({[`${this.metricPrefix}end`]:!0}),t.error!=null?t.local?this.metrics?.increment({[`${this.metricPrefix}abort`]:!0}):this.metrics?.increment({[`${this.metricPrefix}reset`]:!0}):t.local?this.metrics?.increment({[`${this.metricPrefix}_local_close`]:!0}):this.metrics?.increment({[`${this.metricPrefix}_remote_close`]:!0})})}async close(e){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 Ce(this,"idle",{...e,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 Ce(this,"drain",{...e,rejectionEvents:["close"]})),await this.sendClose(e),this.onTransportClosed())}};function Ml(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var $s=class extends Rt{streams;protocol;status;log;maConn;streamOptions;earlyStreams;maxEarlyStreams;metrics;constructor(e,t){super(),this.maConn=e,this.protocol=t.protocol,this.streams=[],this.earlyStreams=[],this.status="open",this.log=e.log.newScope(t.name),this.streamOptions=t.streamOptions,this.maxEarlyStreams=t.maxEarlyStreams??10,this.metrics=t.metrics;let n=i=>{try{this.onData(i.data)}catch(a){this.abort(a),this.maConn.abort(a)}};this.maConn.addEventListener("message",n);let o=()=>{this.log("underlying stream drained, signal %d streams to continue writing",this.streams.length),this.streams.forEach(i=>{i.onMuxerDrain()})};this.maConn.addEventListener("drain",o);let s=()=>{this.log("underlying stream closed with status %s and %d streams",this.status,this.streams.length),this.onTransportClosed()};this.maConn.addEventListener("close",s)}send(e){let t=this.maConn.send(e);return t===!1&&(this.log("underlying stream saturated, signal %d streams to pause writing",this.streams.length),this.streams.forEach(n=>{n.onMuxerNeedsDrain()})),t}async close(e){this.status==="closed"||this.status==="closing"||(this.status="closing",await Tt(Promise.all([...this.streams].map(async t=>{await t.close(e)})),e?.signal),this.status="closed")}abort(e){this.status!=="closed"&&(this.status="closing",[...this.streams].forEach(t=>{t.abort(e)}),this.status="closed")}onTransportClosed(e){this.status="closing";try{[...this.streams].forEach(t=>{t.onTransportClosed(e)})}catch(t){this.abort(t)}this.status="closed"}async createStream(e){if(this.status!=="open")throw new _o;let t=this.onCreateStream({...this.streamOptions,...e});return Ml(t)&&(t=await t),this.streams.push(t),this.cleanUpStream(t),t}onRemoteStream(e){if(this.streams.push(e),this.cleanUpStream(e),this.listenerCount("stream")===0){this.earlyStreams.push(e),this.earlyStreams.length>this.maxEarlyStreams&&this.abort(new Ms(`Too many early streams were opened - ${this.earlyStreams.length}/${this.maxEarlyStreams}`));return}this.safeDispatchEvent("stream",{detail:e})}cleanUpStream(e){let t=n=>{let o=this.streams.findIndex(s=>s===e);o!==-1&&this.streams.splice(o,1),n.error!=null?n.local?this.metrics?.increment({[`${e.direction}_stream_reset`]:!0}):this.metrics?.increment({[`${e.direction}_stream_abort`]:!0}):this.metrics?.increment({[`${e.direction}_stream_end`]:!0})};e.addEventListener("close",t),this.metrics?.increment({[`${e.direction}_stream`]:!0})}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="stream"&&this.earlyStreams.length>0&&queueMicrotask(()=>{this.earlyStreams.forEach(t=>{this.safeDispatchEvent("stream",{detail:t})}),this.earlyStreams=[]})}};var zs=class extends Jt{id;protocol;constructor(e){super(e),this.id=e.id,this.protocol=e.protocol??""}async close(e){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 Ce(this,"idle",{...e,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 Ce(this,"drain",{...e,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(e),this.writeStatus="closed",this.log("closed writable end gracefully"),this.remoteWriteStatus==="closed"&&this.onTransportClosed())}async closeRead(e){this.readStatus==="closing"||this.readStatus==="closed"||(this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.readStatus="closing",await this.sendCloseRead(e),this.readStatus="closed",this.maybeDispatchEnd(),this.log("closed readable end gracefully"))}};var Qg=4194304,Vs=class extends Error{static name="UnwrappedError";name="UnwrappedError"},no=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},$c=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},zc=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function ey(r){return typeof r?.closeRead=="function"}function ty(r){return typeof r?.close=="function"}function Hc(r){return ey(r)?r.remoteWriteStatus!=="writable"&&r.readBufferLength===0:ty(r)?r.status!=="open":!1}function ry(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function ny(r,e){let t=e?.maxBufferSize??Qg,n=new J,o,s=!1;if(!ry(r))throw new W("Argument should be a Stream or a Multiaddr");let i=u=>{if(n.append(u.data),n.byteLength>t){let h=n.byteLength;n.consume(n.byteLength),o?.reject(new Error(`Read buffer overflow - ${h} > ${t}`))}o?.resolve()};r.addEventListener("message",i);let a=u=>{u.error!=null?o?.reject(u.error):o?.resolve()};r.addEventListener("close",a);let c=()=>{o?.resolve()};r.addEventListener("remoteCloseWrite",c);let f={readBuffer:n,async read(u){if(s===!0)throw new Vs("Stream was unwrapped");if(Hc(r)){if(n.byteLength===0&&u?.bytes==null)return null;if(u?.bytes!=null&&n.byteLength<u.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,u.bytes),new Ar(`Unexpected EOF - stream closed after reading ${n.byteLength}/${u.bytes} bytes`)}let h=u?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=h){o.resolve();break}if(await Tt(o.promise,u?.signal),Hc(r)){if(n.byteLength===0&&u?.bytes==null)return null;break}o=Promise.withResolvers()}let l=u?.bytes??n.byteLength;if(n.byteLength<l){if(Hc(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,l),new Ar(`Unexpected EOF - stream closed while reading ${n.byteLength}/${l} bytes`);return f.read(u)}let d=n.sublist(0,l);return n.consume(l),d},async write(u,h){if(s===!0)throw new Vs("Stream was unwrapped");r.send(u)||await Ce(r,"drain",{signal:h?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,r.removeEventListener("message",i),r.removeEventListener("close",a),r.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.unshift(n))),r}};return f}function qs(r,e={}){let t=ny(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=ue(e.maxDataLength));let n=e?.lengthDecoder??St,o=e?.lengthEncoder??ms;return{async read(i){let a=-1,c=new J;for(;;){let u=await t.read({...i,bytes:1});if(u==null)break;c.append(u);try{a=n(c)}catch(h){if(h instanceof RangeError)continue;throw h}if(a<0)throw new no("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new zc(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new $c(`Message length too long - ${a} > ${e.maxDataLength}`);let f=await t.read({...i,bytes:a});if(f==null)throw r.log.error("tried to read %d bytes but the stream closed",a),new Ar(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(f.byteLength!==a)throw r.log.error("read %d/%d bytes before the stream closed",f.byteLength,a),new Ar(`Unexpected EOF - read ${f.byteLength}/${a} bytes before the stream closed`);return f},async write(i,a){await t.write(new J(o(i.byteLength),i),a)},async writeV(i,a){let c=new J(...i.flatMap(f=>[o(f.byteLength),f]));await t.write(c,a)},unwrap(){return t.unwrap()}}}function js(r,e){let t=qs(r,e),n={read:async(o,s)=>{let i=await t.read(s);return o.decode(i,s)},write:async(o,s,i)=>{await t.write(s.encode(o),i)},writeV:async(o,s,i)=>{await t.writeV(o.map(a=>s.encode(a)),i)},pb:o=>({read:async s=>n.read(o,s),write:async(s,i)=>n.write(s,o,i),writeV:async(s,i)=>n.writeV(s,o,i),unwrap:()=>n}),unwrap:()=>t.unwrap()};return n}var oy=1024*1024*4,sy=1024*1024*4,Ws=class{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(e={}){this.buffer=new J,this.maxBufferSize=e.maxBufferSize??oy,this.maxDataLength=e.maxDataLength??sy,this.lengthDecoder=e.lengthDecoder??St,this.encodingLength=e.encodingLength??ue}*decode(e){if(this.buffer.append(e),this.buffer.byteLength>this.maxBufferSize)throw new W(`Buffer length limit exceeded - ${this.buffer.byteLength}/${this.maxBufferSize}`);for(;;){let t;try{t=this.lengthDecoder(this.buffer)}catch(s){if(s instanceof RangeError)break;throw s}if(t<0||t>this.maxDataLength)throw new no("Invalid message length");let n=this.encodingLength(t),o=n+t;if(this.buffer.byteLength>=o){let s=this.buffer.sublist(n,o);this.buffer.consume(o),s.byteLength>0&&(yield s)}else break}}};var Gs=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},sn=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Xs=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},oo=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Ys(r){return r[Symbol.asyncIterator]!=null}function Kl(r,e){if(r.byteLength>e)throw new sn("Message length too long")}var Js=r=>{let e=ue(r),t=xe(e);return ms(r,t),Js.bytes=e,t};Js.bytes=0;function so(r,e){e=e??{};let t=e.lengthEncoder??Js,n=e?.maxDataLength??4194304;function*o(s){Kl(s,n);let i=t(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return Ys(r)?(async function*(){for await(let s of r)yield*o(s)})():(function*(){for(let s of r)yield*o(s)})()}so.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Js,n=e?.maxDataLength??4194304;return Kl(r,n),new J(t(r.byteLength),r)};var vr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(vr||(vr={}));var Vc=r=>{let e=St(r);return Vc.bytes=ue(e),e};Vc.bytes=0;function io(r,e){let t=new J,n=vr.LENGTH,o=-1,s=e?.lengthDecoder??Vc,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===vr.LENGTH)try{if(o=s(t),o<0)throw new Gs("Invalid message length");if(o>a)throw new sn("Message length too long");let f=s.bytes;t.consume(f),e?.onLength!=null&&e.onLength(o),n=vr.DATA}catch(f){if(f instanceof RangeError){if(t.byteLength>i)throw new Xs("Message length length too long");break}throw f}if(n===vr.DATA){if(t.byteLength<o)break;let f=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(f),yield f,n=vr.LENGTH}}}return Ys(r)?(async function*(){for await(let f of r)t.append(f),yield*c();if(t.byteLength>0)throw new oo("Unexpected end of input")})():(function*(){for(let f of r)t.append(f),yield*c();if(t.byteLength>0)throw new oo("Unexpected end of input")})()}io.fromReader=(r,e)=>{let t=1,n=(async function*(){for(;;)try{let{done:s,value:i}=await r.next(t);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{t=1}})();return io(n,{...e??{},onLength:s=>{t=s}})};var qc=class extends zs{channel;incomingData;maxBufferedAmount;receivedFinAck;finAckTimeout;constructor(e){super({...e,maxMessageSize:(e.maxMessageSize??Sr)-Ul}),this.channel=e.channel,this.channel.binaryType="arraybuffer",this.incomingData=on(),this.maxBufferedAmount=e.maxBufferedAmount??Rl,this.finAckTimeout=e.finAckTimeout??Fl,this.channel.onclose=()=>{this.log.trace("received datachannel close event"),this.onRemoteCloseWrite(),this.onTransportClosed()},this.channel.onerror=n=>{let o=n.error;this.log.trace("received datachannel error event - %e",o),this.abort(o)},this.channel.onmessage=async n=>{this.log("incoming message %d bytes",n.data.byteLength);let{data:o}=n;o===null||o.byteLength===0||this.incomingData.push(new Uint8Array(o,0,o.byteLength))},this.channel.bufferedAmountLowThreshold=0,this.channel.onbufferedamountlow=()=>{this.writableNeedsDrain&&this.safeDispatchEvent("drain")},Promise.resolve().then(async()=>{for await(let n of io(this.incomingData))this.processIncomingProtobuf(n)}).catch(n=>{this.log.error("error processing incoming data channel messages - %e",n)});let t=()=>{this.channel.readyState==="open"&&(this.log.trace("stream closed, closing underlying datachannel"),this.channel.close())};this.addEventListener("close",t),this.channel.readyState!=="open"&&(this.log('channel ready state is "%s" and not "open", waiting for "open" event before sending data',this.channel.readyState),Ce(this.channel,"open",{rejectionEvents:["close","error"]}).then(()=>{this.log('channel ready state is now "%s", dispatching drain',this.channel.readyState),this.safeDispatchEvent("drain")}).catch(n=>{this.abort(n.error??n)}))}sendNewStream(){}_sendMessage(e){if(this.channel.readyState!=="open")throw new it(`Invalid datachannel state - ${this.channel.readyState}`);this.log.trace('sending message, channel state "%s"',this.channel.readyState);try{for(let t of e)this.channel.send(Ae(t))}catch(t){this.log.error("error sending datachannel message - %e",t),this.abort(t)}}sendData(e){return this.channel.readyState!=="open"?{sentBytes:0,canSendMore:!1}:(this._sendMessage(so.single(Ie.encode({message:e.subarray()}))),{sentBytes:e.byteLength,canSendMore:this.channel.bufferedAmount<this.maxBufferedAmount})}sendReset(e){try{this.log.error("sending reset - %e",e),this._sendFlag(Ie.Flag.RESET),this.receivedFinAck?.reject(e)}catch(t){this.log.error("failed to send reset - %e",t)}}async sendCloseWrite(e){this._sendFlag(Ie.Flag.FIN),e?.signal?.throwIfAborted(),this.receivedFinAck=Promise.withResolvers();let t=e?.signal??AbortSignal.timeout(this.finAckTimeout),n=[Ce(this.channel,"close",{signal:t}),Ce(this.channel,"error",{signal:t})];await Promise.any([Tt(this.receivedFinAck.promise,t),...n]).finally(()=>{n.forEach(o=>o.cancel())})}async sendCloseRead(e){this._sendFlag(Ie.Flag.STOP_SENDING),e?.signal?.throwIfAborted()}processIncomingProtobuf(e){let t=Ie.decode(e);t.message!=null&&(this.readStatus==="readable"||this.readStatus==="paused")&&this.onData(new J(t.message)),t.flag!==void 0&&(this.log.trace('incoming flag %s, write status "%s", read status "%s"',t.flag,this.writeStatus,this.readStatus),t.flag===Ie.Flag.FIN&&(this._sendFlag(Ie.Flag.FIN_ACK),this.onRemoteCloseWrite()),t.flag===Ie.Flag.RESET&&(this.receivedFinAck?.reject(new Rr("The stream was reset")),this.onRemoteReset()),t.flag===Ie.Flag.STOP_SENDING&&this.onRemoteCloseRead(),t.flag===Ie.Flag.FIN_ACK&&this.receivedFinAck?.resolve())}_sendFlag(e){if(this.channel.readyState!=="open")return this.log.trace('not sending flag %s because channel is "%s" and not "open"',e.toString(),this.channel.readyState),!1;this.log.trace("sending flag %s",e.toString());let t=Ie.encode({flag:e}),n=so.single(t);try{return this._sendMessage(n),!0}catch(o){this.log.error("could not send flag %s - %e",e.toString(),o)}return!1}sendPause(){}sendResume(){}};function ao(r){let{channel:e,direction:t,isHandshake:n}=r;return new qc({...r,id:`${e.id}`,log:r.log.newScope(`${n===!0?"handshake":t}:${e.id}`),protocol:""})}function Gc(r,e){try{r.close()}catch(t){e?.trace("error closing early data channel - %e",t)}}function jc(r,e){r.channel.onmessage=null,r.messages.length=0,Gc(r.channel,e)}var Qt=class{protocol;peerConnection;metrics;log;dataChannelOptions;maxEarlyStreams;earlyDataChannels;handedOff=!1;constructor(e){this.onEarlyDataChannel=this.onEarlyDataChannel.bind(this),this.peerConnection=e.peerConnection,this.metrics=e.metrics,this.log=e.log,this.protocol=e.protocol??Uc,this.dataChannelOptions=e.dataChannelOptions??{},this.maxEarlyStreams=e.maxEarlyStreams??Pl,this.peerConnection.addEventListener("datachannel",this.onEarlyDataChannel),this.earlyDataChannels=[]}onEarlyDataChannel(e){let t=e.channel;if(this.earlyDataChannels.length>=this.maxEarlyStreams){this.log?.("rejecting early data channel %d - too many early channels",t.id),this.metrics?.increment({early_data_channel_count_exceeded:!0}),Gc(t,this.log);return}t.binaryType="arraybuffer";let n={channel:t,messages:[]};t.onmessage=o=>{let{data:s}=o;if(!(s instanceof ArrayBuffer)){this.closeEarlyDataChannel(n,"invalid_message");return}if(n.messages.length>=Nl){this.closeEarlyDataChannel(n,"message_count_exceeded");return}if(n.messages.reduce((a,c)=>a+c.data.byteLength,0)+s.byteLength>Ol){this.closeEarlyDataChannel(n,"byte_count_exceeded");return}n.messages.push(o)},this.earlyDataChannels.push(n)}closeEarlyDataChannel(e,t){this.log?.("closing early data channel %d - %s",e.channel.id,t),this.metrics?.increment({[`early_data_channel_${t}`]:!0}),jc(e,this.log);let n=this.earlyDataChannels.indexOf(e);n!==-1&&this.earlyDataChannels.splice(n,1)}createStreamMuxer(e){return this.handedOff=!0,this.peerConnection.removeEventListener("datachannel",this.onEarlyDataChannel),new Wc(e,{peerConnection:this.peerConnection,dataChannelOptions:this.dataChannelOptions,metrics:this.metrics,protocol:this.protocol,maxEarlyStreams:this.maxEarlyStreams,earlyDataChannels:this.earlyDataChannels})}close(){if(!this.handedOff){this.peerConnection.removeEventListener("datachannel",this.onEarlyDataChannel);for(let e of this.earlyDataChannels)jc(e,this.log);this.earlyDataChannels.length=0}}},Wc=class extends $s{peerConnection;dataChannelOptions;constructor(e,t){super(e,{...t,name:"muxer"}),this.peerConnection=t.peerConnection,this.protocol=t.protocol??Uc,this.dataChannelOptions=t.dataChannelOptions??{},this.peerConnection.ondatachannel=({channel:n})=>{this.onDataChannel(n)},queueMicrotask(()=>{if(this.status!=="open"){t.earlyDataChannels.forEach(n=>{jc(n,this.log)});return}t.earlyDataChannels.forEach(({channel:n,messages:o})=>{try{this.onDataChannel(n,o)}catch(s){this.log.error("error adopting early data channel %d - %e",n.id,s)}})})}onDataChannel(e,t){if(this.log("incoming datachannel with channel id %d, protocol %s and status %s",e.id,e.protocol,e.readyState),e.label==="init"){this.log.trace("closing init channel %d",e.id),Gc(e,this.log);return}let n=ao({...this.streamOptions,...this.dataChannelOptions,channel:e,direction:"inbound",log:this.log});t?.forEach(o=>{e.onmessage?.(o)}),this.onRemoteStream(n)}async onCreateStream(e){let t=this.peerConnection.createDataChannel("",{});return this.log("open channel %d for protocol %s",t.id,e?.protocol),ao({...e,...this.dataChannelOptions,channel:t,direction:"outbound",log:this.log})}onData(){}};var Xc=class extends Hs{peerConnection;constructor(e){super(e),this.peerConnection=e.peerConnection;let t=e.peerConnection.connectionState;this.peerConnection.onconnectionstatechange=()=>{this.log.trace("peer connection state change %s initial state %s",this.peerConnection.connectionState,t),(this.peerConnection.connectionState==="failed"||this.peerConnection.connectionState==="closed")&&(this.onTransportClosed(),this.peerConnection.close())}}sendData(e){return{sentBytes:e.byteLength,canSendMore:!0}}async sendClose(e){this.peerConnection.close(),e?.signal?.throwIfAborted()}sendReset(){this.peerConnection.close()}sendPause(){}sendResume(){}},co=r=>new Xc(r);async function Yc(r){return r=r??{},typeof r=="function"&&(r=await r()),r.iceServers=r.iceServers??_l.map(e=>({urls:[e]})),r}var Hl=(r=32)=>Il+[...Array(r)].map(()=>Nc.at(Math.floor(Math.random()*Nc.length))).join("");var Qs=globalThis.RTCPeerConnection,ei=globalThis.RTCSessionDescription,$l=globalThis.RTCIceCandidate;var Ve=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var er=class extends Error{constructor(e){super(`WebRTC transport error: ${e}`),this.name="WebRTCTransportError"}},Ze=class extends er{constructor(e="SDP handshake failed"){super(e),this.name="SDPHandshakeFailedError"}};var ti=class extends er{constructor(e,t){super(`Invalid fingerprint "${e}" within ${t}`),this.name="WebRTC/InvalidFingerprintError"}};var ri=class extends er{constructor(e){super(`A method (${e}) was called though it has been intentionally left unimplemented.`),this.name="WebRTC/UnimplementedError"}},ni=class extends er{constructor(e){super(`unsupported hash algorithm code: ${e} please see the codes at https://github.com/multiformats/multicodec/blob/master/table.csv `),this.name="WebRTC/UnsupportedHashAlgorithmError"}};var Me;(function(r){let e;(function(a){a.SDP_OFFER="SDP_OFFER",a.SDP_ANSWER="SDP_ANSWER",a.ICE_CANDIDATE="ICE_CANDIDATE"})(e=r.Type||(r.Type={}));let t;(function(a){a[a.SDP_OFFER=0]="SDP_OFFER",a[a.SDP_ANSWER=1]="SDP_ANSWER",a[a.ICE_CANDIDATE=2]="ICE_CANDIDATE"})(t||(t={})),(function(a){a.codec=()=>br(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Yt((a,c,f={})=>{f.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),r.Type.codec().encode(a.type,c)),a.data!=null&&(c.uint32(18),c.string(a.data)),f.lengthDelimited!==!1&&c.ldelim()},(a,c,f={})=>{let u={},h=c==null?a.len:a.pos+c;for(;a.pos<h;){let l=a.uint32();switch(l>>>3){case 1:{u.type=r.Type.codec().decode(a);break}case 2:{u.data=a.string();break}default:{a.skipType(l&7);break}}}return u},function*(a,c,f,u={}){let h=c==null?a.len:a.pos+c;for(;a.pos<h;){let l=a.uint32();switch(l>>>3){case 1:{yield{field:`${f}.type`,value:r.Type.codec().decode(a)};break}case 2:{yield{field:`${f}.data`,value:a.string()};break}default:{a.skipType(l&7);break}}}})),n);function o(a){return Gt(a,r.codec())}r.encode=o;function s(a,c){return Wt(a,r.codec(),c)}r.decode=s;function i(a,c){return Xt(a,r.codec(),c)}r.stream=i})(Me||(Me={}));var oi=async(r,e,t)=>{try{let n=Promise.withResolvers();for(cy(r,n);;){let o=await Promise.race([n.promise,e.read({signal:t.signal})]);if(o==null){t.signal?.throwIfAborted();break}if(o.type!==Me.Type.ICE_CANDIDATE)throw new Po("ICE candidate message expected");let s=JSON.parse(o.data??"null");if(s===""||s===null){t.onProgress?.(new Ve("webrtc:end-of-ice-candidates")),t.log.trace("end-of-candidates received");continue}let i=new $l(s);t.log.trace("%s received new ICE candidate %o",t.direction,s);try{t.onProgress?.(new Ve("webrtc:add-ice-candidate",i.candidate)),await r.addIceCandidate(i)}catch(a){t.log.error("%s bad candidate received %o - %e",t.direction,s,a)}}}catch(n){if(t.log.error("%s error parsing ICE candidate - %e",t.direction,n),t.signal?.aborted===!0&&r.connectionState!=="connected")throw n}};function cy(r,e){if(r.connectionState==="connected"){e.resolve();return}r.onconnectionstatechange=t=>{switch(r.connectionState){case"connected":e.resolve();break;case"failed":case"closed":e.reject(new Do(`RTCPeerConnection connection state became "${r.connectionState}"`));break;default:break}}}function si(r){let e;for(let t of r.getComponents())t.name==="p2p"&&(e=Yr(t.value??""));if(e==null)throw new Io("Remote peerId must be present in multiaddr");return e}async function zl({rtcConfiguration:r,dataChannel:e,maxEarlyStreams:t,signal:n,metrics:o,multiaddr:s,connectionManager:i,transportManager:a,log:c,logger:f,onProgress:u}){let{circuitAddress:h,targetPeer:l}=Vl(s);o?.dialerEvents.increment({open:!0}),c.trace("dialing circuit address: %a",h);let d=i.getConnections(l),b;d.length===0?(u?.(new Ve("webrtc:dial-relay")),b=await a.dial(h,{signal:n,onProgress:u})):(u?.(new Ve("webrtc:reuse-relay-connection")),b=d[0]),u?.(new Ve("webrtc:open-signaling-stream"));let w=await b.newStream(ro,{signal:n,runOnLimitedConnection:!0}),g=js(w).pb(Me),m=new Qs(r);m.addEventListener("connectionstatechange",()=>{m.connectionState==="closed"&&m.close()});let E=new Qt({peerConnection:m,dataChannelOptions:e,maxEarlyStreams:t,metrics:o?.dialerEvents,log:c});try{let x=m.createDataChannel("init");m.onicecandidate=({candidate:O})=>{if(m.connectionState==="connected"){c.trace("ignore new ice candidate as peer connection is already connected");return}if(O==null||O?.candidate===""){c.trace("initiator detected end of ICE candidates");return}let N=JSON.stringify(O?.toJSON()??null);c.trace("initiator sending ICE candidate %o",O),g.write({type:Me.Type.ICE_CANDIDATE,data:N},{signal:n}).catch(I=>{c.error("error sending ICE candidate - %e",I)})},m.onicecandidateerror=O=>{c.error("initiator ICE candidate error",O)};let L=await m.createOffer().catch(O=>{throw c.error("could not execute createOffer - %e",O),new Ze("Failed to set createOffer")});c.trace("initiator send SDP offer %s",L.sdp),u?.(new Ve("webrtc:send-sdp-offer")),await g.write({type:Me.Type.SDP_OFFER,data:L.sdp},{signal:n}),await m.setLocalDescription(L).catch(O=>{throw c.error("could not execute setLocalDescription - %e",O),new Ze("Failed to set localDescription")}),u?.(new Ve("webrtc:read-sdp-answer")),c.trace("initiator read SDP answer");let T=await g.read({signal:n});if(T.type!==Me.Type.SDP_ANSWER)throw new Ze("Remote should send an SDP answer");c.trace("initiator received SDP answer %s",T.data);let F=new ei({type:"answer",sdp:T.data});return await m.setRemoteDescription(F).catch(O=>{throw c.error("could not execute setRemoteDescription - %e",O),new Ze("Failed to set remoteDescription")}),c.trace("initiator read candidates until connected"),u?.(new Ve("webrtc:read-ice-candidates")),await oi(m,g,{direction:"initiator",signal:n,log:c,onProgress:u}),c.trace("initiator connected"),x.readyState!=="open"&&(c.trace("wait for init channel to open"),await Ce(x,"open",{signal:n})),c.trace("closing init channel"),x.close(),c.trace("waiting for init channel to close"),await Ce(x,"close",{signal:n}),u?.(new Ve("webrtc:close-signaling-stream")),c.trace("closing signaling channel"),await w.close({signal:n}),c.trace("initiator connected to remote address %s",s),{remoteAddress:s,peerConnection:m,muxerFactory:E}}catch(x){throw c.error("outgoing signaling error - %e",x),E.close(),m.close(),w.abort(x),x}finally{m.onicecandidate=null,m.onicecandidateerror=null}}var ql=ie(Tl.matchers[0],se(290)),ii=class r extends Rt{transportManager;shutdownController;events;constructor(e,t){super(),this.transportManager=e.transportManager,this.events=e.events,this.shutdownController=t.shutdownController,this.onTransportListening=this.onTransportListening.bind(this)}async listen(){this.events.addEventListener("transport:listening",this.onTransportListening)}onTransportListening(e){e.detail.getAddrs().filter(n=>ql.exactMatch(n)).map(n=>n.encapsulate("/webrtc")).length>0&&this.safeDispatchEvent("listening")}getAddrs(){return this.transportManager.getListeners().filter(e=>!(e instanceof r)).map(e=>e.getAddrs().filter(t=>ql.exactMatch(t)).map(t=>t.encapsulate("/webrtc"))).flat()}updateAnnounceAddrs(){}async close(){this.events.removeEventListener("transport:listening",this.onTransportListening),this.shutdownController.abort(),queueMicrotask(()=>{this.safeDispatchEvent("close")})}};async function jl(r,e,{peerConnection:t,signal:n,log:o}){o.trace("new inbound signaling stream");let s=js(r).pb(Me);try{t.onicecandidate=({candidate:h})=>{if(t.connectionState==="connected"){o.trace("ignore new ice candidate as peer connection is already connected");return}if(h==null||h?.candidate===""){o.trace("recipient detected end of ICE candidates");return}let l=JSON.stringify(h?.toJSON()??null);o.trace("recipient sending ICE candidate %s",l),s.write({type:Me.Type.ICE_CANDIDATE,data:l},{signal:n}).catch(d=>{o.error("error sending ICE candidate - %e",d)})},o.trace("recipient read SDP offer");let c=await s.read({signal:n});if(c.type!==Me.Type.SDP_OFFER)throw new Ze(`expected message type SDP_OFFER, received: ${c.type??"undefined"} `);o.trace("recipient received SDP offer %s",c.data);let f=new ei({type:"offer",sdp:c.data});await t.setRemoteDescription(f).catch(h=>{throw o.error("could not execute setRemoteDescription - %e",h),new Ze("Failed to set remoteDescription")});let u=await t.createAnswer().catch(h=>{throw o.error("could not execute createAnswer - %e",h),new Ze("Failed to create answer")});o.trace("recipient send SDP answer %s",u.sdp),await s.write({type:Me.Type.SDP_ANSWER,data:u.sdp},{signal:n}),await t.setLocalDescription(u).catch(h=>{throw o.error("could not execute setLocalDescription - %e",h),new Ze("Failed to set localDescription")}),o.trace("recipient read candidates until connected"),await oi(t,s,{direction:"recipient",signal:n,log:o})}catch(c){if(t.connectionState!=="connected")throw o.error("error while handling signaling stream from peer %a - %e",e.remoteAddr,c),t.close(),c;o("error while handling signaling stream from peer %a, ignoring as the RTCPeerConnection is already connected",e.remoteAddr,c)}let i=si(e.remoteAddr),a=tn(`/webrtc/p2p/${i}`);return o.trace("recipient connected to remote address %s",a),{remoteAddress:a,remotePeer:i}}var ai=class{components;init;log;_started=!1;metrics;shutdownController;constructor(e,t={}){this.components=e,this.init=t,this.log=e.logger.forComponent("libp2p:webrtc"),this.shutdownController=new AbortController,this.shutdownController.signal,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc_dialer_events_total",{label:"event",help:"Total count of WebRTC dialer events by type"}),listenerEvents:e.metrics.registerCounterGroup("libp2p_webrtc_listener_events_total",{label:"event",help:"Total count of WebRTC listener events by type"})})}[ko]=!0;[Symbol.toStringTag]="@libp2p/webrtc";[Pr]=["@libp2p/transport"];[ru]=["@libp2p/identify","@libp2p/circuit-relay-v2-transport"];isStarted(){return this._started}async start(){await this.components.registrar.handle(ro,(e,t)=>{let n=this.components.upgrader.createInboundAbortSignal(this.shutdownController.signal);this._onProtocol(e,t,n).catch(o=>{this.log.error("failed to handle incoming connect from %p - %e",t.remotePeer,o)}).finally(()=>{n.clear()})},{runOnLimitedConnection:!0}),this._started=!0}async stop(){await this.components.registrar.unhandle(ro),this._started=!1}createListener(e){return new ii(this.components,{shutdownController:this.shutdownController})}listenFilter(e){return e.filter(Dl.exactMatch)}dialFilter(e){return this.listenFilter(e)}async dial(e,t){this.log.trace("dialing address: %a",e);let{remoteAddress:n,peerConnection:o,muxerFactory:s}=await zl({rtcConfiguration:await Yc(this.init.rtcConfiguration),dataChannel:this.init.dataChannel,maxEarlyStreams:this.init.maxEarlyStreams,multiaddr:e,dataChannelOptions:this.init.dataChannel,signal:t.signal,connectionManager:this.components.connectionManager,transportManager:this.components.transportManager,metrics:this.metrics,log:this.log,logger:this.components.logger,onProgress:t.onProgress}),i=co({peerConnection:o,remoteAddr:n,metrics:this.metrics?.dialerEvents,direction:"outbound",log:this.components.logger.forComponent("libp2p:webrtc:connection")}),a;try{a=await t.upgrader.upgradeOutbound(i,{skipProtection:!0,skipEncryption:!0,remotePeer:si(e),muxerFactory:s,onProgress:t.onProgress,signal:t.signal})}catch(c){throw s.close(),o.close(),c}return this._closeOnShutdown(o,i),a}async _onProtocol(e,t,n){let o=new Qs(await Yc(this.init.rtcConfiguration));o.addEventListener("connectionstatechange",()=>{o.connectionState==="closed"&&o.close()});let s=new Qt({peerConnection:o,dataChannelOptions:this.init.dataChannel,maxEarlyStreams:this.init.maxEarlyStreams,metrics:this.metrics?.listenerEvents,log:this.log});try{let{remoteAddress:i,remotePeer:a}=await jl(e,t,{peerConnection:o,signal:n,log:this.log});await e.close({signal:n});let c=co({peerConnection:o,remoteAddr:i,metrics:this.metrics?.listenerEvents,direction:"inbound",log:this.components.logger.forComponent("libp2p:webrtc:connection")});await this.components.upgrader.upgradeInbound(c,{skipEncryption:!0,skipProtection:!0,remotePeer:a,muxerFactory:s,signal:n}),this._closeOnShutdown(o,c)}catch(i){throw this.log.error("incoming signaling error - %e",i),s.close(),o.close(),e.abort(i),i}}_closeOnShutdown(e,t){let n=()=>{t.close().catch(o=>{this.log.error("could not close WebRTCMultiaddrConnection - %e",o)})};this.shutdownController.signal.addEventListener("abort",n),e.addEventListener("close",()=>{this.shutdownController.signal.removeEventListener("abort",n)})}};function Vl(r){let e=r.getComponents().filter(({name:n})=>n==="p2p").map(({value:n})=>n).pop();if(e==null)throw new W("Destination peer id was missing");return{circuitAddress:tn(r.getComponents().filter(({name:n})=>n!=="webrtc")),targetPeer:Yr(e)}}function we(r=0){return new Uint8Array(r)}function Re(r=0){return new Uint8Array(r)}var an=!!globalThis.process?.env?.DUMP_SESSION_KEYS,Zc=16;function Jc(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}var ci=r=>r?`"${r}" `:"";function fi(r,e=""){if(typeof r!="boolean")throw new TypeError(ci(e)+"expected boolean, got type="+typeof r);return r}function Cr(r,e=""){if(typeof r!="number")throw new TypeError(ci(e)+"expected number, got "+typeof r);if(!Number.isSafeInteger(r)||r<0)throw new RangeError(ci(e)+"expected integer >= 0, got "+r);return r}function me(r,e,t=""){if(Jc(r)&&(e===void 0||r.length===e))return r;e!==void 0&&Cr(e,"length");let n=Jc(r),o=e!==void 0?` of length ${e}`:"",s=n?`length=${r.length}`:`type=${typeof r}`,i=ci(t)+"expected Uint8Array"+o+", got "+s;throw n?new RangeError(i):new TypeError(i)}var Wl=(r,e)=>{if(r===null||typeof r!="object"||Array.isArray(r))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof r}`)};function Qc(r,e=!0){if(r.destroyed)throw new Error("hash was destroyed");if(e&&r.finished)throw new Error("digest() was already called")}function Gl(r,e){me(r,void 0,"output");let t=e.outputLen;if(!(r.length>=t))throw new RangeError('"output" expected length >= '+t)}function pt(r){return new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4))}function nt(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function fy(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}var tr=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function uy(r){return r<<24&4278190080|r<<8&16711680|r>>>8&65280|r>>>24&255}function hy(r){for(let e=0;e<r.length;e++)r[e]=uy(r[e]);return r}var Dt=tr?r=>r:hy;function Xl(r,e){return Wl(r,"defaults"),Wl(e,"opts"),Object.assign(r,e)}function Yl(r,e){if(r=me(r),e=me(e),r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}function Zl(r,e,t){let n=e,o=t||(()=>[]),s=(a,c)=>n(c,...o(a)).update(a).digest(),i=n(new Uint8Array(r),...o(new Uint8Array(0)));return s.outputLen=i.outputLen,s.blockLen=i.blockLen,s.create=(a,...c)=>n(a,...c),s}var Jl=(r,e)=>{function t(n,...o){if(me(n,void 0,"key"),r.nonceLength!==void 0){let h=o[0];me(h,r.varSizeNonce?void 0:r.nonceLength,"nonce")}let s=r.tagLength,i=r.nonceLength!==void 0?1:0;if(!r.withAAD){for(let h=i;h<o.length;h++)if(Jc(o[h]))throw new Error("AAD not supported")}r.withAAD&&o[i]!==void 0&&me(o[i],void 0,"AAD");let a=e(n,...o),c=(h,l)=>{if(l!==void 0){if(h!==2)throw new Error("cipher output not supported");me(l,void 0,"output")}},f=!1;return{encrypt(h,l){if(f)throw new Error("cannot encrypt() twice with same key + nonce");return f=!0,me(h,void 0,"data"),c(a.encrypt.length,l),a.encrypt(h,l)},decrypt(h,l){if(me(h,void 0,"data"),s&&h.length<s)throw new Error('"ciphertext" expected length >= tagLength='+s);return c(a.decrypt.length,l),a.decrypt(h,l)}}}return Object.assign(t,r),t};function fo(r,e,t=!0){if(e===void 0)return new Uint8Array(r);if(me(e,r,"output"),t&&!uo(e))throw new Error("invalid output, must be aligned");return e}function Ql(r,e,t){Cr(r),Cr(e),fi(t);let n=new Uint8Array(16),o=fy(n);return o.setBigUint64(0,BigInt(e),t),o.setBigUint64(8,BigInt(r),t),n}function uo(r){return r.byteOffset%4===0}function cn(r){return Uint8Array.from(me(r))}var td=r=>Uint8Array.from(r.split(""),e=>e.charCodeAt(0)),ly=Dt(pt(td("expand 16-byte k"))),dy=Dt(pt(td("expand 32-byte k")));function G(r,e){return r<<e|r>>>32-e}var ho=64,py=16,ef=2**32-1,ed=Uint32Array.of();function my(r,e,t,n,o,s,i,a){let c=o.length,f=new Uint8Array(ho),u=pt(f),h=tr&&uo(o)&&uo(s),l=h?pt(o):ed,d=h?pt(s):ed;if(!tr){for(let b=0;b<c;i++){if(r(e,t,n,u,i,a),Dt(u),i>=ef)throw new Error("arx: counter overflow");let w=Math.min(ho,c-b);for(let g=0,m;g<w;g++)m=b+g,s[m]=o[m]^f[g];b+=w}return}for(let b=0;b<c;i++){if(r(e,t,n,u,i,a),i>=ef)throw new Error("arx: counter overflow");let w=Math.min(ho,c-b);if(h&&w===ho){let g=b/4;if(b%4!==0)throw new Error("arx: invalid block position");for(let m=0,E;m<py;m++)E=g+m,d[E]=l[E]^u[m];b+=ho;continue}for(let g=0,m;g<w;g++)m=b+g,s[m]=o[m]^f[g];b+=w}}function rd(r,e){let{allowShortKeys:t,extendNonceFn:n,counterLength:o,counterRight:s,rounds:i}=Xl({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof r!="function")throw new Error("core must be a function");return Cr(o),Cr(i),fi(s),fi(t),(a,c,f,u,h=0)=>{me(a,void 0,"key"),me(c,void 0,"nonce"),me(f,void 0,"data");let l=f.length;if(u=fo(l,u,!1),Cr(h),h<0||h>=ef)throw new Error("arx: counter overflow");let d=[],b=a.length,w,g;if(b===32)d.push(w=cn(a)),g=dy;else if(b===16&&t)w=new Uint8Array(32),w.set(a),w.set(a,16),g=ly,d.push(w);else throw me(a,32,"arx key"),new Error("invalid key size");(!tr||!uo(c))&&d.push(c=cn(c));let m=pt(w);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");let L=c.subarray(0,16);if(tr)n(g,m,pt(L),m);else{let T=Dt(Uint32Array.from(g));n(T,m,pt(L),m),nt(T),Dt(m)}c=c.subarray(16)}else tr||Dt(m);let E=16-o;if(E!==c.length)throw new Error(`arx: nonce must be ${E} or 16 bytes`);if(E!==12){let L=new Uint8Array(12);L.set(c,s?0:12-c.length),c=L,d.push(c)}let x=Dt(pt(c));try{return my(r,g,m,x,f,u,h,i),u}finally{nt(...d)}}}function Le(r,e){return r[e++]&255|(r[e++]&255)<<8}var tf=class{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;destroyed=!1;constructor(e){e=cn(me(e,32,"key"));let t=Le(e,0),n=Le(e,2),o=Le(e,4),s=Le(e,6),i=Le(e,8),a=Le(e,10),c=Le(e,12),f=Le(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|n<<3)&8191,this.r[2]=(n>>>10|o<<6)&7939,this.r[3]=(o>>>7|s<<9)&8191,this.r[4]=(s>>>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]=Le(e,16+2*u)}process(e,t,n=!1){let o=n?0:2048,{h:s,r:i}=this,a=i[0],c=i[1],f=i[2],u=i[3],h=i[4],l=i[5],d=i[6],b=i[7],w=i[8],g=i[9],m=Le(e,t+0),E=Le(e,t+2),x=Le(e,t+4),L=Le(e,t+6),T=Le(e,t+8),F=Le(e,t+10),O=Le(e,t+12),N=Le(e,t+14),I=s[0]+(m&8191),U=s[1]+((m>>>13|E<<3)&8191),k=s[2]+((E>>>10|x<<6)&8191),R=s[3]+((x>>>7|L<<9)&8191),H=s[4]+((L>>>4|T<<12)&8191),_=s[5]+(T>>>1&8191),D=s[6]+((T>>>14|F<<2)&8191),p=s[7]+((F>>>11|O<<5)&8191),S=s[8]+((O>>>8|N<<8)&8191),C=s[9]+(N>>>5|o),A=0,v=A+I*a+U*(5*g)+k*(5*w)+R*(5*b)+H*(5*d);A=v>>>13,v&=8191,v+=_*(5*l)+D*(5*h)+p*(5*u)+S*(5*f)+C*(5*c),A+=v>>>13,v&=8191;let y=A+I*c+U*a+k*(5*g)+R*(5*w)+H*(5*b);A=y>>>13,y&=8191,y+=_*(5*d)+D*(5*l)+p*(5*h)+S*(5*u)+C*(5*f),A+=y>>>13,y&=8191;let B=A+I*f+U*c+k*a+R*(5*g)+H*(5*w);A=B>>>13,B&=8191,B+=_*(5*b)+D*(5*d)+p*(5*l)+S*(5*h)+C*(5*u),A+=B>>>13,B&=8191;let P=A+I*u+U*f+k*c+R*a+H*(5*g);A=P>>>13,P&=8191,P+=_*(5*w)+D*(5*b)+p*(5*d)+S*(5*l)+C*(5*h),A+=P>>>13,P&=8191;let K=A+I*h+U*u+k*f+R*c+H*a;A=K>>>13,K&=8191,K+=_*(5*g)+D*(5*w)+p*(5*b)+S*(5*d)+C*(5*l),A+=K>>>13,K&=8191;let M=A+I*l+U*h+k*u+R*f+H*c;A=M>>>13,M&=8191,M+=_*a+D*(5*g)+p*(5*w)+S*(5*b)+C*(5*d),A+=M>>>13,M&=8191;let V=A+I*d+U*l+k*h+R*u+H*f;A=V>>>13,V&=8191,V+=_*c+D*a+p*(5*g)+S*(5*w)+C*(5*b),A+=V>>>13,V&=8191;let z=A+I*b+U*d+k*l+R*h+H*u;A=z>>>13,z&=8191,z+=_*f+D*c+p*a+S*(5*g)+C*(5*w),A+=z>>>13,z&=8191;let X=A+I*w+U*b+k*d+R*l+H*h;A=X>>>13,X&=8191,X+=_*u+D*f+p*c+S*a+C*(5*g),A+=X>>>13,X&=8191;let ae=A+I*g+U*w+k*b+R*d+H*l;A=ae>>>13,ae&=8191,ae+=_*h+D*u+p*f+S*c+C*a,A+=ae>>>13,ae&=8191,A=(A<<2)+A|0,A=A+v|0,v=A&8191,A=A>>>13,y+=A,s[0]=v,s[1]=y,s[2]=B,s[3]=P,s[4]=K,s[5]=M,s[6]=V,s[7]=z,s[8]=X,s[9]=ae}finalize(){let{h:e,pad:t}=this,n=new Uint16Array(10),o=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=o,o=e[a]>>>13,e[a]&=8191;e[0]+=o*5,o=e[0]>>>13,e[0]&=8191,e[1]+=o,o=e[1]>>>13,e[1]&=8191,e[2]+=o,n[0]=e[0]+5,o=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=e[a]+o,o=n[a]>>>13,n[a]&=8191;n[9]-=8192;let s=(o^1)-1;for(let a=0;a<10;a++)n[a]&=s;s=~s;for(let a=0;a<10;a++)e[a]=e[a]&s|n[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let i=e[0]+t[0];e[0]=i&65535;for(let a=1;a<8;a++)i=(e[a]+t[a]|0)+(i>>>16)|0,e[a]=i&65535;nt(n)}update(e){Qc(this),me(e),e=cn(e);let{buffer:t,blockLen:n}=this,o=e.length;for(let s=0;s<o;){let i=Math.min(n-this.pos,o-s);if(i===n){for(;n<=o-s;s+=n)this.process(e,s);continue}t.set(e.subarray(s,s+i),this.pos),this.pos+=i,s+=i,this.pos===n&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,nt(this.h,this.r,this.buffer,this.pad)}digestInto(e){Qc(this),Gl(e,this),this.finished=!0;let{buffer:t,h:n}=this,{pos:o}=this;if(o){for(t[o++]=1;o<16;o++)t[o]=0;this.process(t,0,!0)}this.finalize();let s=0;for(let i=0;i<8;i++)e[s++]=n[i]>>>0,e[s++]=n[i]>>>8}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}},nd=Zl(32,r=>new tf(r));function gy(r,e,t,n,o,s=20){let i=r[0],a=r[1],c=r[2],f=r[3],u=e[0],h=e[1],l=e[2],d=e[3],b=e[4],w=e[5],g=e[6],m=e[7],E=o,x=t[0],L=t[1],T=t[2],F=i,O=a,N=c,I=f,U=u,k=h,R=l,H=d,_=b,D=w,p=g,S=m,C=E,A=x,v=L,y=T;for(let P=0;P<s;P+=2)F=F+U|0,C=G(C^F,16),_=_+C|0,U=G(U^_,12),F=F+U|0,C=G(C^F,8),_=_+C|0,U=G(U^_,7),O=O+k|0,A=G(A^O,16),D=D+A|0,k=G(k^D,12),O=O+k|0,A=G(A^O,8),D=D+A|0,k=G(k^D,7),N=N+R|0,v=G(v^N,16),p=p+v|0,R=G(R^p,12),N=N+R|0,v=G(v^N,8),p=p+v|0,R=G(R^p,7),I=I+H|0,y=G(y^I,16),S=S+y|0,H=G(H^S,12),I=I+H|0,y=G(y^I,8),S=S+y|0,H=G(H^S,7),F=F+k|0,y=G(y^F,16),p=p+y|0,k=G(k^p,12),F=F+k|0,y=G(y^F,8),p=p+y|0,k=G(k^p,7),O=O+R|0,C=G(C^O,16),S=S+C|0,R=G(R^S,12),O=O+R|0,C=G(C^O,8),S=S+C|0,R=G(R^S,7),N=N+H|0,A=G(A^N,16),_=_+A|0,H=G(H^_,12),N=N+H|0,A=G(A^N,8),_=_+A|0,H=G(H^_,7),I=I+U|0,v=G(v^I,16),D=D+v|0,U=G(U^D,12),I=I+U|0,v=G(v^I,8),D=D+v|0,U=G(U^D,7);let B=0;n[B++]=i+F|0,n[B++]=a+O|0,n[B++]=c+N|0,n[B++]=f+I|0,n[B++]=u+U|0,n[B++]=h+k|0,n[B++]=l+R|0,n[B++]=d+H|0,n[B++]=b+_|0,n[B++]=w+D|0,n[B++]=g+p|0,n[B++]=m+S|0,n[B++]=E+C|0,n[B++]=x+A|0,n[B++]=L+v|0,n[B++]=T+y|0}var yy=rd(gy,{counterRight:!1,counterLength:4,allowShortKeys:!1});var by=new Uint8Array(16),od=(r,e)=>{r.update(e);let t=e.length%16;t&&r.update(by.subarray(t))},wy=new Uint8Array(32);function sd(r,e,t,n,o){o!==void 0&&me(o,void 0,"AAD");let s=r(e,t,wy),i=Ql(n.length,o?o.length:0,!0),a=nd.create(s);o&&od(a,o),od(a,n),a.update(i);let c=a.digest();return nt(s,i),c}var xy=r=>(e,t,n)=>({encrypt(s,i){let a=s.length;i=fo(a+16,i,!1),i.set(s);let c=i.subarray(0,-16);r(e,t,c,c,1);let f=sd(r,e,t,c,n);return i.set(f,a),nt(f),i},decrypt(s,i){i=fo(s.length-16,i,!1);let a=s.subarray(0,-16),c=s.subarray(-16),f=sd(r,e,t,a,n);if(!Yl(c,f))throw nt(f),new Error("invalid tag");return i.set(s.subarray(0,-16)),r(e,t,i,i,1),nt(f),i}}),rf=Jl({blockSize:64,nonceLength:12,tagLength:16,withAAD:!0},xy(yy));function id(r,e,t){return lr(r),t===void 0&&(t=new Uint8Array(r.outputLen)),Wn(r,t,e)}var lo=Uint8Array.of(0),Ey=Uint8Array.of();function ad(r,e,t,n=32,o){lr(r),et(n,"length"),Ne(e,void 0,"prk");let s=r.outputLen;if(e.length<s)throw new Error('"prk" must be at least HashLen octets');if(n>255*s)throw new Error("Length must be <= 255*HashLen");let i=Math.ceil(n/s);if(t===void 0?t=Ey:Ne(t,void 0,"info"),!i)return o&&We(e),new Uint8Array;let a=o&&i===1?e:new Uint8Array(i*s),{iHash:c,oHash:f}=Wn.create(r,e),u=o?e:new Uint8Array(s),h=i>1?o?.iHash||r.create():void 0;for(let d=0;d<i-1;d++){lo[0]=d+1;let b=c._cloneInto(h);d&&b.update(u),b.update(t).update(lo).digestInto(u),f._cloneInto(h).update(u).digestInto(u),a.set(u,s*d)}if(lo[0]=i,i>1&&c.update(u),c.update(t).update(lo).digestInto(u),f.update(u).digestInto(u),a.set(u,s*(i-1)),c.destroy(),f.destroy(),h?.destroy(),u!==a&&We(u),We(lo),n===a.length)return a;let l=a.slice(0,n);return We(a),l}var nf={hashSHA256(r){return ft(r.subarray())},getHKDF(r,e){let t=id(ft,e,r),o=ad(ft,t,void 0,96),s=o.subarray(0,32),i=o.subarray(32,64),a=o.subarray(64,96);return[s,i,a]},generateX25519KeyPair(){let r=Mn.utils.randomSecretKey();return{publicKey:Mn.getPublicKey(r),privateKey:r}},generateX25519KeyPairFromSeed(r){return{publicKey:Mn.getPublicKey(r),privateKey:r}},generateX25519SharedKey(r,e){return Mn.getSharedSecret(r.subarray(),e.subarray())},chaCha20Poly1305Encrypt(r,e,t,n){return rf(n,e,t).encrypt(r.subarray())},chaCha20Poly1305Decrypt(r,e,t,n,o){return rf(n,e,t).decrypt(r.subarray(),o)}};var cd=nf;function fd(r){return{generateKeypair:r.generateX25519KeyPair,dh:(e,t)=>r.generateX25519SharedKey(e.privateKey,t).subarray(0,32),encrypt:r.chaCha20Poly1305Encrypt,decrypt:r.chaCha20Poly1305Decrypt,hash:r.hashSHA256,hkdf:r.getHKDF}}var fn=r=>{let e=Re(2);return e[0]=r>>8,e[1]=r,e};fn.bytes=2;var un=r=>{if(r.length<2)throw RangeError("Could not decode int16BE");if(r instanceof Uint8Array){let e=0;return e+=r[0]<<8,e+=r[1],e}return r.getUint16(0)};un.bytes=2;function ud(r){return{xxHandshakeSuccesses:r.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:r.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:r.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:r.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:r.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}var ff={};oe(ff,{base10:()=>Ty});var l4=new Uint8Array(0);function hd(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function _t(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function ld(r){return new TextEncoder().encode(r)}function dd(r){return new TextDecoder().decode(r)}function Sy(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),f=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(b){if(b instanceof Uint8Array||(ArrayBuffer.isView(b)?b=new Uint8Array(b.buffer,b.byteOffset,b.byteLength):Array.isArray(b)&&(b=Uint8Array.from(b))),!(b instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(b.length===0)return"";for(var w=0,g=0,m=0,E=b.length;m!==E&&b[m]===0;)m++,w++;for(var x=(E-m)*u+1>>>0,L=new Uint8Array(x);m!==E;){for(var T=b[m],F=0,O=x-1;(T!==0||F<g)&&O!==-1;O--,F++)T+=256*L[O]>>>0,L[O]=T%a>>>0,T=T/a>>>0;if(T!==0)throw new Error("Non-zero carry");g=F,m++}for(var N=x-g;N!==x&&L[N]===0;)N++;for(var I=c.repeat(w);N<x;++N)I+=r.charAt(L[N]);return I}function l(b){if(typeof b!="string")throw new TypeError("Expected String");if(b.length===0)return new Uint8Array;var w=0;if(b[w]!==" "){for(var g=0,m=0;b[w]===c;)g++,w++;for(var E=(b.length-w)*f+1>>>0,x=new Uint8Array(E);b[w];){var L=t[b.charCodeAt(w)];if(L===255)return;for(var T=0,F=E-1;(L!==0||T<m)&&F!==-1;F--,T++)L+=a*x[F]>>>0,x[F]=L%256>>>0,L=L/256>>>0;if(L!==0)throw new Error("Non-zero carry");m=T,w++}if(b[w]!==" "){for(var O=E-m;O!==E&&x[O]===0;)O++;for(var N=new Uint8Array(g+(E-O)),I=g;O!==E;)N[I++]=x[O++];return N}}}function d(b){var w=l(b);if(w)return w;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:l,decode:d}}var Ay=Sy,vy=Ay,md=vy;var of=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},sf=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return gd(this,e)}},af=class{decoders;constructor(e){this.decoders=e}or(e){return gd(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function gd(r,e){return new af({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var cf=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new of(e,t,n),this.decoder=new sf(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function hn({name:r,prefix:e,encode:t,decode:n}){return new cf(r,e,t,n)}function rr({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=md(t,r);return hn({prefix:e,name:r,encode:n,decode:s=>_t(o(s))})}function Cy(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let f=0;f<o;++f){let u=e[r[f]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function Ly(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function By(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function pe({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=By(n);return hn({prefix:e,name:r,encode(s){return Ly(s,n,t)},decode(s){return Cy(s,o,t,r)}})}var Ty=rr({prefix:"9",name:"base10",alphabet:"0123456789"});var uf={};oe(uf,{base16:()=>Dy,base16upper:()=>_y});var Dy=pe({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),_y=pe({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var hf={};oe(hf,{base2:()=>Iy});var Iy=pe({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var lf={};oe(lf,{base256emoji:()=>Uy});var yd=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}"),Ry=yd.reduce((r,e,t)=>(r[t]=e,r),[]),Oy=yd.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function Py(r){return r.reduce((e,t)=>(e+=Ry[t],e),"")}function Ny(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=Oy[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var Uy=hn({prefix:"\u{1F680}",name:"base256emoji",encode:Py,decode:Ny});var df={};oe(df,{base32:()=>ln,base32hex:()=>Ky,base32hexpad:()=>$y,base32hexpadupper:()=>zy,base32hexupper:()=>Hy,base32pad:()=>ky,base32padupper:()=>My,base32upper:()=>Fy,base32z:()=>Vy});var ln=pe({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Fy=pe({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ky=pe({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),My=pe({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Ky=pe({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Hy=pe({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),$y=pe({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),zy=pe({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Vy=pe({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var pf={};oe(pf,{base36:()=>po,base36upper:()=>qy});var po=rr({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),qy=rr({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var mf={};oe(mf,{base58btc:()=>mt,base58flickr:()=>jy});var mt=rr({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),jy=rr({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var gf={};oe(gf,{base64:()=>Wy,base64pad:()=>Gy,base64url:()=>Xy,base64urlpad:()=>Yy});var Wy=pe({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Gy=pe({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Xy=pe({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Yy=pe({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var yf={};oe(yf,{base8:()=>Zy});var Zy=pe({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var bf={};oe(bf,{identity:()=>Jy});var Jy=hn({prefix:"\0",name:"identity",encode:r=>dd(r),decode:r=>ld(r)});var T4=new TextEncoder,D4=new TextDecoder;var xf={};oe(xf,{identity:()=>Eb});var tb=xd,bd=128,rb=127,nb=~rb,ob=Math.pow(2,31);function xd(r,e,t){e=e||[],t=t||0;for(var n=t;r>=ob;)e[t++]=r&255|bd,r/=128;for(;r&nb;)e[t++]=r&255|bd,r>>>=7;return e[t]=r|0,xd.bytes=t-n+1,e}var sb=wf,ib=128,wd=127;function wf(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw wf.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&wd)<<o:(i&wd)*Math.pow(2,o),o+=7}while(i>=ib);return wf.bytes=s-n,t}var ab=Math.pow(2,7),cb=Math.pow(2,14),fb=Math.pow(2,21),ub=Math.pow(2,28),hb=Math.pow(2,35),lb=Math.pow(2,42),db=Math.pow(2,49),pb=Math.pow(2,56),mb=Math.pow(2,63),gb=function(r){return r<ab?1:r<cb?2:r<fb?3:r<ub?4:r<hb?5:r<lb?6:r<db?7:r<pb?8:r<mb?9:10},yb={encode:tb,decode:sb,encodingLength:gb},bb=yb,mo=bb;function go(r,e=0){return[mo.decode(r,e),mo.decode.bytes]}function dn(r,e,t=0){return mo.encode(r,e,t),e}function pn(r){return mo.encodingLength(r)}function gn(r,e){let t=e.byteLength,n=pn(r),o=n+pn(t),s=new Uint8Array(o+t);return dn(r,s,0),dn(t,s,n),s.set(e,o),new mn(r,t,e,s)}function Ed(r){let e=_t(r),[t,n]=go(e),[o,s]=go(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new mn(t,o,i,e)}function Sd(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&hd(r.bytes,t.bytes)}}var mn=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var Ad=0,wb="identity",vd=_t;function xb(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return gn(Ad,vd(r))}var Eb={code:Ad,name:wb,encode:vd,digest:xb};var Af={};oe(Af,{sha256:()=>Ab,sha512:()=>vb});var Sb=20;function Sf({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new Ef(r,e,t,n,o)}var Ef=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??Sb,this.maxDigestLength=s}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?Cd(n,this.code,t?.truncate):n.then(o=>Cd(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Cd(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return gn(e,r)}function Bd(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Ab=Sf({name:"sha2-256",code:18,encode:Bd("SHA-256")}),vb=Sf({name:"sha2-512",code:19,encode:Bd("SHA-512")});function Td(r,e){let{bytes:t,version:n}=r;return n===0?Lb(t,vf(r),e??mt.encoder):Bb(t,vf(r),e??ln.encoder)}var Dd=new WeakMap;function vf(r){let e=Dd.get(r);if(e==null){let t=new Map;return Dd.set(r,t),t}return e}var hi=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==bo)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Tb)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=gn(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&Sd(e.multihash,n.multihash)}toString(e){return Td(this,e)}toJSON(){return{"/":Td(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??_d(n,o,s.bytes))}else if(t[Db]===!0){let{version:n,multihash:o,code:s}=t,i=Ed(o);return r.create(n,s,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==bo)throw new Error(`Version 0 CID must use dag-pb (code: ${bo}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=_d(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,bo,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=_t(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new mn(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[h,l]=go(e.subarray(t));return t+=l,h},o=n(),s=bo;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),f=t+c,u=f-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:f}}static parse(e,t){let[n,o]=Cb(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return vf(s).set(n,e),s}};function Cb(r,e){switch(r[0]){case"Q":{let t=e??mt;return[mt.prefix,t.decode(`${mt.prefix}${r}`)]}case mt.prefix:{let t=e??mt;return[mt.prefix,t.decode(r)]}case ln.prefix:{let t=e??ln;return[ln.prefix,t.decode(r)]}case po.prefix:{let t=e??po;return[po.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function Lb(r,e,t){let{prefix:n}=t;if(n!==mt.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function Bb(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var bo=112,Tb=18;function _d(r,e,t){let n=pn(r),o=n+pn(e),s=new Uint8Array(o+t.byteLength);return dn(r,s,0),dn(e,s,n),s.set(t,o),s}var Db=Symbol.for("@ipld/js-cid/CID");var Cf={...bf,...hf,...yf,...ff,...uf,...df,...pf,...mf,...gf,...lf},Z4={...Af,...xf};function Rd(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Id=Rd("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Lf=Rd("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=Re(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),_b={utf8:Id,"utf-8":Id,hex:Cf.base16,latin1:Lf,ascii:Lf,binary:Lf,...Cf},li=_b;function gt(r,e="utf8"){let t=li[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}function Bf(r,e){!e.enabled||!an||(r?(e(`LOCAL_STATIC_PUBLIC_KEY ${gt(r.publicKey,"hex")}`),e(`LOCAL_STATIC_PRIVATE_KEY ${gt(r.privateKey,"hex")}`)):e("Missing local static keys."))}function Tf(r,e){!e.enabled||!an||(r?(e(`LOCAL_PUBLIC_EPHEMERAL_KEY ${gt(r.publicKey,"hex")}`),e(`LOCAL_PRIVATE_EPHEMERAL_KEY ${gt(r.privateKey,"hex")}`)):e("Missing local ephemeral keys."))}function Od(r,e){!e.enabled||!an||e(r?`REMOTE_STATIC_PUBLIC_KEY ${gt(r.subarray(),"hex")}`:"Missing remote static public key.")}function Df(r,e){!e.enabled||!an||e(r?`REMOTE_EPHEMERAL_PUBLIC_KEY ${gt(r.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function _f(r,e,t){!t.enabled||!an||(t(`CIPHER_STATE_1 ${r.n.getUint64()} ${r.k&>(r.k,"hex")}`),t(`CIPHER_STATE_2 ${e.n.getUint64()} ${e.k&>(e.k,"hex")}`))}function yn(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=Re(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}function If(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}var Nd=Symbol.for("@achingbrain/uint8arraylist");function Pd(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function di(r){return!!r?.[Nd]}var yt=class r{bufs;length;[Nd]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(di(n)){t+=n.byteLength;for(let o of n.bufs)this.bufs.push(o)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(di(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=Pd(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Pd(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(di(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:o}=this._subList(e,t);return yn(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:yn(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=n,s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let f=e>=a&&e<c,u=t>a&&t<=c;if(f&&u){if(e===a&&t===c){n.push(i);break}let h=e-a;n.push(i.subarray(h,h+(t-e)));break}if(f){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(u){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!di(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let h=0;h<s;h++)i[h]=-1;for(let h=0;h<o;h++)i[n[h]]=h;let a=i,c=this.byteLength-n.byteLength,f=n.byteLength-1,u;for(let h=t;h<=c;h+=u){u=0;for(let l=f;l>=0;l--){let d=this.get(h+l);if(n[l]!==d){u=Math.max(1,l-a[d]);break}}if(u===0)return h}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=Re(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=we(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=we(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=we(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=Re(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=we(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=we(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=we(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=we(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=we(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!If(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,s)=>o+s.byteLength,0)),n.length=t,n}};function Lr(r,e="utf8"){let t=li[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}var bn=class r extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=r.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};var Rb=0,Ob=4294967295,Pb="Cipherstate has reached maximum n, a new handshake must be performed",pi=class{n;bytes;view;constructor(e=Rb){this.n=e,this.bytes=we(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,e,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>Ob)throw new Error(Pb)}};var Br=we(0),wn=class{k;n;crypto;constructor(e,t=void 0,n=0){this.crypto=e,this.k=t,this.n=new pi(n)}hasKey(){return!!this.k}encryptWithAd(e,t){if(!this.hasKey())return t;this.n.assertValue();let n=this.crypto.encrypt(t,this.n.getBytes(),e,this.k);return this.n.increment(),n}decryptWithAd(e,t,n){if(!this.hasKey())return t;this.n.assertValue();let o=this.crypto.decrypt(t,this.n.getBytes(),e,this.k,n);return this.n.increment(),o}},Rf=class{cs;ck;h;crypto;constructor(e,t){this.crypto=e;let n=Lr(t,"utf-8");this.h=Nb(e,n),this.ck=this.h,this.cs=new wn(e)}mixKey(e){let[t,n]=this.crypto.hkdf(this.ck,e);this.ck=t,this.cs=new wn(this.crypto,n)}mixHash(e){this.h=this.crypto.hash(new yt(this.h,e))}encryptAndHash(e){let t=this.cs.encryptWithAd(this.h,e);return this.mixHash(t),t}decryptAndHash(e){let t=this.cs.decryptWithAd(this.h,e);return this.mixHash(e),t}split(){let[e,t]=this.crypto.hkdf(this.ck,Br);return[new wn(this.crypto,e),new wn(this.crypto,t)]}},Of=class{ss;s;e;rs;re;initiator;crypto;constructor(e){let{crypto:t,protocolName:n,prologue:o,initiator:s,s:i,e:a,rs:c,re:f}=e;this.crypto=t,this.ss=new Rf(t,n),this.ss.mixHash(o),this.initiator=s,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 e=this.crypto.generateKeypair();return this.ss.mixHash(e.publicKey),this.e=e,e.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(e,t=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(e.byteLength<t+32)throw new Error("message is not long enough");this.re=e.sublist(t,t+32),this.ss.mixHash(this.re)}readS(e,t=0){if(this.rs)throw new Error("remote static public key is already set");let n=32+(this.ss.cs.hasKey()?16:0);if(e.byteLength<t+n)throw new Error("message is not long enough");let o=e.sublist(t,t+n);return this.rs=this.ss.decryptAndHash(o),n}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}},wo=class extends Of{writeMessageA(e){return new yt(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){let t=this.writeE();this.writeEE();let n=this.writeS();return this.writeES(),new yt(t,n,this.ss.encryptAndHash(e))}writeMessageC(e){let t=this.writeS();return this.writeSE(),new yt(t,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(t){throw new bn(`handshake stage 0 validation fail: ${t.message}`)}}readMessageB(e){try{this.readE(e),this.readEE();let t=this.readS(e,32);return this.readES(),this.ss.decryptAndHash(e.sublist(32+t))}catch(t){throw new bn(`handshake stage 1 validation fail: ${t.message}`)}}readMessageC(e){try{let t=this.readS(e);return this.readSE(),this.ss.decryptAndHash(e.sublist(t))}catch(t){throw new bn(`handshake stage 2 validation fail: ${t.message}`)}}};function Nb(r,e){if(e.length<=32){let t=we(32);return t.set(e),t}else return r.hash(e)}var Ub=Math.pow(2,7),Fb=Math.pow(2,14),kb=Math.pow(2,21),Ud=Math.pow(2,28),Fd=Math.pow(2,35),kd=Math.pow(2,42),Md=Math.pow(2,49),Ue=128,nr=127;function xo(r){if(r<Ub)return 1;if(r<Fb)return 2;if(r<kb)return 3;if(r<Ud)return 4;if(r<Fd)return 5;if(r<kd)return 6;if(r<Md)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Kd(r,e,t=0){switch(xo(r)){case 8:e[t++]=r&255|Ue,r/=128;case 7:e[t++]=r&255|Ue,r/=128;case 6:e[t++]=r&255|Ue,r/=128;case 5:e[t++]=r&255|Ue,r/=128;case 4:e[t++]=r&255|Ue,r>>>=7;case 3:e[t++]=r&255|Ue,r>>>=7;case 2:e[t++]=r&255|Ue,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function Hd(r,e){let t=r[e],n=0;if(n+=t&nr,t<Ue||(t=r[e+1],n+=(t&nr)<<7,t<Ue)||(t=r[e+2],n+=(t&nr)<<14,t<Ue)||(t=r[e+3],n+=(t&nr)<<21,t<Ue)||(t=r[e+4],n+=(t&nr)*Ud,t<Ue)||(t=r[e+5],n+=(t&nr)*Fd,t<Ue)||(t=r[e+6],n+=(t&nr)*kd,t<Ue)||(t=r[e+7],n+=(t&nr)*Md,t<Ue))return n;throw new RangeError("Could not decode varint")}var Pf=new Float32Array([-0]),or=new Uint8Array(Pf.buffer);function $d(r,e,t){Pf[0]=r,e[t]=or[0],e[t+1]=or[1],e[t+2]=or[2],e[t+3]=or[3]}function zd(r,e){return or[0]=r[e],or[1]=r[e+1],or[2]=r[e+2],or[3]=r[e+3],Pf[0]}var Nf=new Float64Array([-0]),Oe=new Uint8Array(Nf.buffer);function Vd(r,e,t){Nf[0]=r,e[t]=Oe[0],e[t+1]=Oe[1],e[t+2]=Oe[2],e[t+3]=Oe[3],e[t+4]=Oe[4],e[t+5]=Oe[5],e[t+6]=Oe[6],e[t+7]=Oe[7]}function qd(r,e){return Oe[0]=r[e],Oe[1]=r[e+1],Oe[2]=r[e+2],Oe[3]=r[e+3],Oe[4]=r[e+4],Oe[5]=r[e+5],Oe[6]=r[e+6],Oe[7]=r[e+7],Nf[0]}var Mb=BigInt(Number.MAX_SAFE_INTEGER),Kb=BigInt(Number.MIN_SAFE_INTEGER),qe=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return Tr;if(e<Mb&&e>Kb)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>jd&&(o=0n,++n>jd&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return Tr;let t=e<0;t&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):Tr}},Tr=new qe(0,0);Tr.toBigInt=function(){return 0n};Tr.zzEncode=Tr.zzDecode=function(){return this};Tr.length=function(){return 1};var jd=4294967296n;function Wd(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function Gd(r,e,t){if(t-e<1)return"";let o,s=[],i=0,a;for(;e<t;)a=r[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function Uf(r,e,t){let n=t,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function ot(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function mi(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var Ff=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,ot(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw ot(this,4);return mi(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw ot(this,4);return mi(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw ot(this,4);let e=zd(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw ot(this,4);let e=qd(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw ot(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Gd(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw ot(this,e);this.pos+=e}else do if(this.pos>=this.len)throw ot(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new qe(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw ot(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw ot(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw ot(this,8);let e=mi(this.buf,this.pos+=4),t=mi(this.buf,this.pos+=4);return new qe(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=Hd(this.buf,this.pos);return this.pos+=xo(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function kf(r){return new Ff(r instanceof Uint8Array?r:r.subarray())}function gi(r,e,t){let n=kf(r);return e.decode(n,void 0,t)}function Mf(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return Re(i);o+i>e&&(n=Re(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var Dr=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function Kf(){}var $f=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},Hb=Mf();function $b(r){return globalThis.Buffer!=null?Re(r):Hb(r)}var So=class{len;head;tail;states;constructor(){this.len=0,this.head=new Dr(Kf,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new Dr(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new zf((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(yi,10,qe.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=qe.fromBigInt(e);return this._push(yi,t.length(),t)}uint64Number(e){return this._push(Kd,xo(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=qe.fromBigInt(e).zzEncode();return this._push(yi,t.length(),t)}sint64Number(e){let t=qe.fromNumber(e).zzEncode();return this._push(yi,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Hf,1,e?1:0)}fixed32(e){return this._push(Eo,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=qe.fromBigInt(e);return this._push(Eo,4,t.lo)._push(Eo,4,t.hi)}fixed64Number(e){let t=qe.fromNumber(e);return this._push(Eo,4,t.lo)._push(Eo,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push($d,4,e)}double(e){return this._push(Vd,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(Hf,1,0):this.uint32(t)._push(Vb,t,e)}string(e){let t=Wd(e);return t!==0?this.uint32(t)._push(Uf,t,e):this._push(Hf,1,0)}fork(){return this.states=new $f(this),this.head=this.tail=new Dr(Kf,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 Dr(Kf,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=$b(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function Hf(r,e,t){e[t]=r&255}function zb(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var zf=class extends Dr{next;constructor(e,t){super(zb,e,t),this.next=void 0}};function yi(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function Eo(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function Vb(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(So.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(qb,e,r),this},So.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(jb,e,r),this});function qb(r,e,t){e.set(r,t)}function jb(r,e,t){r.length<40?Uf(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(Lr(r),t)}function Vf(){return new So}function bi(r,e){let t=Vf();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var Ao;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(Ao||(Ao={}));function qf(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function wi(r,e){return qf("message",Ao.LENGTH_DELIMITED,r,e)}var vo=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var xi;(function(r){let e;r.codec=()=>(e==null&&(e=wi((t,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),t.webtransportCerthashes!=null)for(let s of t.webtransportCerthashes)n.uint32(10),n.bytes(s);if(t.streamMuxers!=null)for(let s of t.streamMuxers)n.uint32(18),n.string(s);o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={webtransportCerthashes:[],streamMuxers:[]},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{if(o.limits?.webtransportCerthashes!=null&&s.webtransportCerthashes.length===o.limits.webtransportCerthashes)throw new vo('Decode error - map field "webtransportCerthashes" had too many elements');s.webtransportCerthashes.push(t.bytes());break}case 2:{if(o.limits?.streamMuxers!=null&&s.streamMuxers.length===o.limits.streamMuxers)throw new vo('Decode error - map field "streamMuxers" had too many elements');s.streamMuxers.push(t.string());break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>bi(t,r.codec()),r.decode=(t,n)=>gi(t,r.codec(),n)})(xi||(xi={}));var Co;(function(r){let e;r.codec=()=>(e==null&&(e=wi((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.identityKey!=null&&t.identityKey.byteLength>0&&(n.uint32(10),n.bytes(t.identityKey)),t.identitySig!=null&&t.identitySig.byteLength>0&&(n.uint32(18),n.bytes(t.identitySig)),t.extensions!=null&&(n.uint32(34),xi.codec().encode(t.extensions,n)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={identityKey:we(0),identitySig:we(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.identityKey=t.bytes();break}case 2:{s.identitySig=t.bytes();break}case 4:{s.extensions=xi.codec().decode(t,t.uint32(),{limits:o.limits?.extensions});break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>bi(t,r.codec()),r.decode=(t,n)=>gi(t,r.codec(),n)})(Co||(Co={}));async function Wf(r,e,t){let n=await r.sign(Zd(e));return Co.encode({identityKey:Ut(r.publicKey),identitySig:n,extensions:t})}async function Gf(r,e,t){try{let n=Co.decode(r),o=Gn(n.identityKey);if(t?.equals(o)===!1)throw new Error(`Payload identity key ${o} does not match expected remote identity key ${t}`);if(!e)throw new Error("Remote static does not exist");let s=Zd(e);if(!await o.verify(s,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new Bo(n.message)}}function Zd(r){let e=Lr("noise-libp2p-static-key:");return r instanceof Uint8Array?yn([e,r],e.length+r.length):(r.prepend(e),r)}var jf=class extends Jt{stream;handshake;metrics;decoder;constructor(e,t,n){super({log:e.log,inactivityTimeout:e.inactivityTimeout,maxReadBufferLength:e.maxReadBufferLength,direction:e.direction}),this.stream=e,this.handshake=t,this.metrics=n,this.decoder=new Ws({lengthDecoder:un,maxBufferSize:16*1024*1024,encodingLength:()=>2});let o=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",o);let s=c=>{c.error!=null?c.local===!0?this.abort(c.error):this.onRemoteReset():this.onTransportClosed()};this.stream.addEventListener("close",s);let i=()=>{this.safeDispatchEvent("drain")};this.stream.addEventListener("drain",i);let a=()=>{this.onRemoteCloseWrite()};this.stream.addEventListener("remoteCloseWrite",a)}encrypt(e){let t=new yt;for(let n=0;n<e.byteLength;n+=65519){let o=n+65519;o>e.byteLength&&(o=e.byteLength);let s;e instanceof Uint8Array?s=this.handshake.encrypt(e.subarray(n,o)):s=this.handshake.encrypt(e.sublist(n,o)),this.metrics?.encryptedPackets.increment(),t.append(fn(s.byteLength)),t.append(s)}return t}decrypt(e){let t=new yt;for(let n=0;n<e.byteLength;n+=65535){let o=n+65535;if(o>e.byteLength&&(o=e.byteLength),o-Zc<n)throw new Error("Invalid chunk");let s;e instanceof Uint8Array?s=e.subarray(n,o):s=e.sublist(n,o);let i=e.subarray(n,o-Zc);try{let a=this.handshake.decrypt(s,i);this.metrics?.decryptedPackets.increment(),t.append(a)}catch(a){throw this.metrics?.decryptErrors.increment(),a}}return t}close(e){return this.stream.close(e)}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}sendReset(e){this.stream.abort(e)}sendData(e){return{sentBytes:e.byteLength,canSendMore:this.stream.send(this.encrypt(e))}}};function Xf(r,e,t){return new jf(r,e,t)}async function Jd(r,e){let{log:t,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:f}=r,u=await Wf(s,a.publicKey,f),h=new wo({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});Bf(h.s,t),t.trace("Stage 0 - Initiator starting to send first message."),await n.write(h.writeMessageA(Br),e),t.trace("Stage 0 - Initiator finished sending first message."),Tf(h.e,t),t.trace("Stage 1 - Initiator waiting to receive first message from responder...");let l=h.readMessageB(await n.read(e));t.trace("Stage 1 - Initiator received the message."),Df(h.re,t),Od(h.rs,t),t.trace("Initiator going to check remote's signature...");let d=await Gf(l,h.rs,c);t.trace("All good with the signature!"),t.trace("Stage 2 - Initiator sending third handshake message."),await n.write(h.writeMessageC(u),e),t.trace("Stage 2 - Initiator sent message with signed payload.");let[b,w]=h.ss.split();return _f(b,w,t),{payload:d,encrypt:g=>b.encryptWithAd(Br,g),decrypt:(g,m)=>w.decryptWithAd(Br,g,m)}}async function Qd(r,e){let{log:t,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:f}=r,u=await Wf(s,a.publicKey,f),h=new wo({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});Bf(h.s,t),t.trace("Stage 0 - Responder waiting to receive first message."),h.readMessageA(await n.read(e)),t.trace("Stage 0 - Responder received first message."),Df(h.re,t),t.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(h.writeMessageB(u),e),t.trace("Stage 1 - Responder sent the second handshake message with signed payload."),Tf(h.e,t),t.trace("Stage 2 - Responder waiting for third handshake message...");let l=h.readMessageC(await n.read(e));t.trace("Stage 2 - Responder received the message, finished handshake.");let d=await Gf(l,h.rs,c),[b,w]=h.ss.split();return _f(b,w,t),{payload:d,encrypt:g=>w.encryptWithAd(Br,g),decrypt:(g,m)=>b.decryptWithAd(Br,g,m)}}var Ei=class{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;log;constructor(e,t={}){let{staticNoiseKey:n,extensions:o,crypto:s,prologueBytes:i}=t,{metrics:a}=e;this.components=e,this.log=e.logger.forComponent("libp2p:noise");let c=s??cd;this.crypto=fd(c),this.extensions={webtransportCerthashes:[],...o},this.metrics=a?ud(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??we(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[Pr]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(e,t){let n=e.log?.newScope("noise")??this.log,o=qs(e,{lengthEncoder:fn,lengthDecoder:un,maxDataLength:65535}),s=await this.performHandshakeInitiator(o,this.components.privateKey,n,t?.remotePeer?.publicKey,t),i=Gn(s.payload.identityKey);return{connection:Xf(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:ic(i),streamMuxer:t?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}getStreamMuxer(e){if(e==null||e.length===0)return;let t=this.components.upgrader.getStreamMuxers();if(t!=null)for(let n of e){let o=t.get(n);if(o!=null)return o}if(e.length)throw new To("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(e,t){let n=e.log?.newScope("noise")??this.log,o=qs(e,{lengthEncoder:fn,lengthDecoder:un,maxDataLength:65535}),s=await this.performHandshakeResponder(o,this.components.privateKey,n,t?.remotePeer?.publicKey,t),i=Gn(s.payload.identityKey);return{connection:Xf(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:ic(i),streamMuxer:t?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(e,t,n,o,s){let i,a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await Jd({connection:e,privateKey:t,remoteIdentityKey:o,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},s),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}async performHandshakeResponder(e,t,n,o,s){let i,a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await Qd({connection:e,privateKey:t,remoteIdentityKey:o,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},s),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}};function ep(r={}){return e=>new Ei(e,r)}var Yf=Object.values(fr).map(r=>r.decoder).reduce((r,e)=>r.or(e)),Wb=/^a=fingerprint:(?:\w+-[0-9]+)\s(?<fingerprint>(:?[0-9a-fA-F]{2})+)$/m;function tp(r){return r?.match(Wb)?.groups?.fingerprint}function Zf(r){let t=r.getComponents().find(n=>n.code===466)?.value;if(t===void 0||t==="")throw new W(`Couldn't find a certhash component of multiaddr: ${r.toString()}`);return t}function Gb(r){return Je.decode(Yf.decode(r))}function Xb(r){let e=Gb(Zf(r)),t=Yb(e.code),n=e.digest.reduce((s,i)=>s+i.toString(16).padStart(2,"0"),""),o=n.match(/.{1,2}/g);if(o==null)throw new ti(n,r.toString());return`${t} ${o.join(":").toUpperCase()}`}function rp(r){let e=r.split(":").map(o=>parseInt(o,16)),t=Uint8Array.from(e),n=Pe(wt.code,t);return tn(`/certhash/${Ln.encode(n.bytes)}`)}function Yb(r){switch(r){case 17:return"sha-1";case 18:return"sha-256";case 19:return"sha-512";default:throw new ni(r)}}function np(r,e){let{host:t,port:n,type:o}=Fc(r);if(o!=="ip4"&&o!=="ip6")throw new W(`Multiaddr ${r} was not an IPv4 or IPv6 address`);let s=Xb(r);return{type:"answer",sdp:`v=0
|
|
3
|
-
o=- 0 0 IN IP${o==="ip4"?4:6} ${
|
|
2
|
+
"use strict";var Libp2PWebrtc=(()=>{var Us=Object.defineProperty;var id=Object.getOwnPropertyDescriptor;var ad=Object.getOwnPropertyNames;var cd=Object.prototype.hasOwnProperty;var Pe=(t,e)=>{for(var r in e)Us(t,r,{get:e[r],enumerable:!0})},fd=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ad(e))!cd.call(t,o)&&o!==r&&Us(t,o,{get:()=>e[o],enumerable:!(n=id(e,o))||n.enumerable});return t};var ud=t=>fd(Us({},"__esModule",{value:!0}),t);var By={};Pe(By,{webRTC:()=>Ly,webRTCDirect:()=>Ty});var Wn=class extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}},Gn=class extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}},J=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},yr=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var Yn=class extends Error{static name="ConnectionFailedError";constructor(e="Connection failed"){super(e),this.name="ConnectionFailedError"}},Xn=class extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}},gr=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}};var it=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},Wt=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}};var Zn=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},Qn=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Jn=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var eo=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var Gt=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var to=class extends Event{data;constructor(e,r){super("message",r),this.data=e}},br=class extends Event{error;local;constructor(e,r,n){super("close",n),this.error=r,this.local=e}},ro=class extends br{constructor(e,r){super(!0,e,r)}},no=class extends br{constructor(e,r){super(!1,e,r)}};var ks=Symbol.for("@libp2p/peer-id");var oo=Symbol.for("@libp2p/transport");var Bc;(function(t){t[t.FATAL_ALL=0]="FATAL_ALL",t[t.NO_FATAL=1]="NO_FATAL"})(Bc||(Bc={}));function ld(t){return typeof t?.handleEvent=="function"}function dd(t){return t===!0||t===!1}function hd(t){return dd(t)?t:t?.capture??!1}function Ms(t){let e={capture:hd(t),once:!!t?.once};return t?.passive!=null&&(e.passive=t?.passive),t?.signal!=null&&(e.signal=t?.signal),e}function Dc(t,e){return Ms(t).capture===Ms(e).capture}var Tt=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let r=this.#e.get(e);return r==null?0:r.length}addEventListener(e,r,n){let o=Ms(n);if(o?.signal?.aborted===!0)return;let s=f=>{o.once&&this.removeEventListener(e,r,o),ld(r)?r.handleEvent(f):r(f)},i=this.#e.get(e);if(i==null&&(i=[],this.#e.set(e,i)),i.some(f=>f.callback!==r?!1:Dc(f.options,o)))return;super.addEventListener(e,s,o);let c=()=>{this.removeEventListener(e,r,o)};o.signal?.addEventListener("abort",c),i.push({callback:r,wrapper:s,options:o,onAbort:c})}removeEventListener(e,r,n){let o=this.#e.get(e);if(o==null){super.removeEventListener(e,r??null,n);return}this.#e.set(e,o.filter(s=>s.callback===r&&Dc(s.options,n)?(super.removeEventListener(e,s.wrapper,n),s.options?.signal?.removeEventListener("abort",s.onAbort),!1):!0))}safeDispatchEvent(e,r={}){return this.dispatchEvent(new CustomEvent(e,r))}};var wr=Symbol.for("@libp2p/service-capabilities"),Ic=Symbol.for("@libp2p/service-dependencies");var zs={};Pe(zs,{base58btc:()=>ye,base58flickr:()=>Ed});var a0=new Uint8Array(0);function Oc(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}function qe(t){if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return Yt(t);if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return Yt(new Uint8Array(t.buffer,t.byteOffset,t.byteLength));throw new Error("Unknown type, must be binary type")}function Pc(t){let e=new Uint8Array(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}var Rc=4096;function Nc(t){let e=t.length;if(e<=Rc)return String.fromCharCode.apply(String,t);let r="",n=0;for(;n<e;)r+=String.fromCharCode.apply(String,t.subarray(n,n+=Rc));return r}function pd(t){return t?.buffer instanceof ArrayBuffer}function Yt(t){return pd(t)?t:t.slice()}function md(t,e,r){if(t.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),o=0;o<n.length;o++)n[o]=255;for(var s=0;s<t.length;s++){var i=t.charAt(s),a=i.charCodeAt(0);if(n[a]!==255)throw new TypeError(i+" is ambiguous");if(n[a]=s,r){var c=i.toLowerCase().charCodeAt(0),f=i.toUpperCase().charCodeAt(0);c!==a&&(n[c]=s),f!==a&&(n[f]=s)}}var u=t.length,l=t.charAt(0),h=Math.log(u)/Math.log(256),p=Math.log(256)/Math.log(u);function x(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var E=0,b=0,L=0,C=g.length;L!==C&&g[L]===0;)L++,E++;for(var O=(C-L)*p+1>>>0,R=new Uint8Array(O);L!==C;){for(var N=g[L],B=0,I=O-1;(N!==0||B<b)&&I!==-1;I--,B++)N+=256*R[I]>>>0,R[I]=N%u>>>0,N=N/u>>>0;if(N!==0)throw new Error("Non-zero carry");b=B,L++}for(var K=O-b;K!==O&&R[K]===0;)K++;for(var F=l.repeat(E);K<O;++K)F+=t.charAt(R[K]);return F}function w(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var E=0;if(g[E]!==" "){for(var b=0,L=0;g[E]===l;)b++,E++;for(var C=(g.length-E)*h+1>>>0,O=new Uint8Array(C);g[E];){var R=n[g.charCodeAt(E)];if(R===255)return;for(var N=0,B=C-1;(R!==0||N<L)&&B!==-1;B--,N++)R+=u*O[B]>>>0,O[B]=R%256>>>0,R=R/256>>>0;if(R!==0)throw new Error("Non-zero carry");L=N,E++}if(g[E]!==" "){for(var I=C-L;I!==C&&O[I]===0;)I++;for(var K=new Uint8Array(b+(C-I)),F=b;I!==C;)K[F++]=O[I++];return K}}}function m(g){var E=w(g);if(E)return E;throw new Error(`Non-${e} character`)}return{encode:x,decodeUnsafe:w,decode:m}}var yd=md,gd=yd,kc=gd;var Fs=class{name;prefix;baseEncode;constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Ks=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,r,n){this.name=e,this.prefix=r;let o=r.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Mc(this,e)}},Hs=class{decoders;constructor(e){this.decoders=e}or(e){return Mc(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Mc(t,e){return new Hs({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}var $s=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,r,n,o){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=o,this.encoder=new Fs(e,r,n),this.decoder=new Ks(e,r,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function xr({name:t,prefix:e,encode:r,decode:n}){return new $s(t,e,r,n)}function Lt({name:t,prefix:e,alphabet:r,caseInsensitive:n=!1}){let{encode:o,decode:s}=kc(r,t,n);return xr({prefix:e,name:t,encode:o,decode:i=>qe(s(i))})}function bd(t,e,r,n){let o=t.length;for(;t[o-1]==="=";)--o;let s=new Uint8Array(o*r/8|0),i=0,a=0,c=0;for(let f=0;f<o;++f){let u=e[t[f]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<r|u,i+=r,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=r||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function wd(t,e,r){let n=e[e.length-1]==="=",o=(1<<r)-1,s="",i=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],i+=8;i>r;)i-=r,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<r-i]),n)for(;(s.length*r&7)!==0;)s+="=";return s}function xd(t,e){let r={};for(let n=0;n<t.length;++n)if(r[t[n]]=n,e){let o=t[n].toLowerCase(),s=t[n].toUpperCase();o!==t[n]&&(r[o]=n),s!==t[n]&&(r[s]=n)}return r}function me({name:t,prefix:e,bitsPerChar:r,alphabet:n,caseInsensitive:o=!1}){let s=xd(n,o);return xr({prefix:e,name:t,encode(i){return wd(i,n,r)},decode(i){return bd(i,s,r,t)}})}var ye=Lt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Ed=Lt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var qs={};Pe(qs,{base32:()=>Bt,base32hex:()=>Cd,base32hexpad:()=>Td,base32hexpadupper:()=>Ld,base32hexupper:()=>_d,base32pad:()=>Ad,base32padupper:()=>vd,base32upper:()=>Sd,base32z:()=>Bd});var Bt=me({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5,caseInsensitive:!0}),Sd=me({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5,caseInsensitive:!0}),Ad=me({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5,caseInsensitive:!0}),vd=me({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5,caseInsensitive:!0}),Cd=me({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5,caseInsensitive:!0}),_d=me({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5,caseInsensitive:!0}),Td=me({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5,caseInsensitive:!0}),Ld=me({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5,caseInsensitive:!0}),Bd=me({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Vs={};Pe(Vs,{base36:()=>Qr,base36upper:()=>Dd});var Qr=Lt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz",caseInsensitive:!0}),Dd=Lt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",caseInsensitive:!0});var Xe={};Pe(Xe,{Digest:()=>Xt,create:()=>Ne,decode:()=>Ar,equals:()=>Ws,hasCode:()=>Yd});var Id=Hc,Fc=128,Rd=127,Od=~Rd,Pd=Math.pow(2,31);function Hc(t,e,r){e=e||[],r=r||0;for(var n=r;t>=Pd;)e[r++]=t&255|Fc,t/=128;for(;t&Od;)e[r++]=t&255|Fc,t>>>=7;return e[r]=t|0,Hc.bytes=r-n+1,e}var Nd=js,Ud=128,Kc=127;function js(t,n){var r=0,n=n||0,o=0,s=n,i,a=t.length;do{if(s>=a)throw js.bytes=0,new RangeError("Could not decode varint");i=t[s++],r+=o<28?(i&Kc)<<o:(i&Kc)*Math.pow(2,o),o+=7}while(i>=Ud);return js.bytes=s-n,r}var kd=Math.pow(2,7),Md=Math.pow(2,14),Fd=Math.pow(2,21),Kd=Math.pow(2,28),Hd=Math.pow(2,35),$d=Math.pow(2,42),zd=Math.pow(2,49),qd=Math.pow(2,56),Vd=Math.pow(2,63),jd=function(t){return t<kd?1:t<Md?2:t<Fd?3:t<Kd?4:t<Hd?5:t<$d?6:t<zd?7:t<qd?8:t<Vd?9:10},Wd={encode:Id,decode:Nd,encodingLength:jd},Gd=Wd,Jr=Gd;function en(t,e=0){let r=Jr.decode(t,e),n=Jr.decode.bytes;if(n>9)throw new RangeError("Invalid varint: too long");if(n>1&&t[e+n-1]===0)throw new RangeError("Invalid varint: not minimally encoded");return[r,n]}function Er(t,e,r=0){return Jr.encode(t,e,r),e}function Sr(t){return Jr.encodingLength(t)}function Ne(t,e){let r=e.byteLength,n=Sr(t),o=n+Sr(r),s=new Uint8Array(o+r);return Er(t,s,0),Er(r,s,n),s.set(e,o),new Xt(t,r,e,s)}function Ar(t){let e=qe(t),[r,n]=en(e),[o,s]=en(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Xt(r,o,i,e)}function Ws(t,e){if(t===e)return!0;{let r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&Oc(t.bytes,r.bytes)}}var Xt=class{code;size;digest;bytes;constructor(e,r,n,o){this.code=e,this.size=r,this.digest=Yt(n),this.bytes=Yt(o)}};function Yd(t,e){return t.code===e}function $c(t,e){let{bytes:r,version:n}=t;return n===0?Zd(r,Gs(t),e??ye.encoder):Qd(r,Gs(t),e??Bt.encoder)}var zc=new WeakMap;function Gs(t){let e=zc.get(t);if(e==null){let r=new Map;return zc.set(t,r),r}return e}var Ee=class t{code;version;multihash;bytes;"/";constructor(e,r,n,o){this.code=r,this.version=e,this.multihash=n,this.bytes=Yt(o),this["/"]=this.bytes}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:r}=this;if(e!==tn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==Jd)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return t.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:e,digest:r}=this.multihash,n=Ne(e,r);return t.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return t.equals(this,e)}static equals(e,r){let n=r;return n!=null&&e.code===n.code&&e.version===n.version&&Ws(e.multihash,n.multihash)}toString(e){return $c(this,e)}toJSON(){return{"/":$c(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let r=e;if(r instanceof t)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){let{version:n,code:o,multihash:s,bytes:i}=r;return new t(n,o,s,i??qc(n,o,s.bytes))}else if(r[eh]===!0){let{version:n,multihash:o,code:s}=r,i=Ar(o);return t.create(n,s,i)}else return null}static create(e,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(e){case 0:{if(r!==tn)throw new Error(`Version 0 CID must use dag-pb (code: ${tn}) block encoding`);return new t(e,r,n,n.bytes)}case 1:{let o=qc(e,r,n.bytes);return new t(e,r,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return t.create(0,tn,e)}static createV1(e,r){return t.create(1,e,r)}static decode(e){let[r,n]=t.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return r}static decodeFirst(e){let r=t.inspectBytes(e),n=r.size-r.multihashSize,o=qe(e.subarray(n,n+r.multihashSize));if(o.byteLength!==r.multihashSize)throw new Error("Incorrect length");let s=o.subarray(r.multihashSize-r.digestSize),i=new Xt(r.multihashCode,r.digestSize,s,o);return[r.version===0?t.createV0(i):t.createV1(r.codec,i),e.subarray(r.size)]}static inspectBytes(e){let r=0,n=()=>{let[l,h]=en(e.subarray(r));return r+=h,l},o=n(),s=tn;if(o===18?(o=0,r=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=r,a=n(),c=n(),f=r+c,u=f-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:f}}static parse(e,r){let[n,o]=Xd(e,r),s=t.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Gs(s).set(n,e),s}};function Xd(t,e){switch(t[0]){case"Q":{let r=e??ye;return[ye.prefix,r.decode(`${ye.prefix}${t}`)]}case ye.prefix:{let r=e??ye;return[ye.prefix,r.decode(t)]}case Bt.prefix:{let r=e??Bt;return[Bt.prefix,r.decode(t)]}case Qr.prefix:{let r=e??Qr;return[Qr.prefix,r.decode(t)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}}function Zd(t,e,r){let{prefix:n}=r;if(n!==ye.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let o=e.get(n);if(o==null){let s=r.encode(t).slice(1);return e.set(n,s),s}else return o}function Qd(t,e,r){let{prefix:n}=r,o=e.get(n);if(o==null){let s=r.encode(t);return e.set(n,s),s}else return o}var tn=112,Jd=18;function qc(t,e,r){let n=Sr(t),o=n+Sr(e),s=new Uint8Array(o+r.byteLength);return Er(t,s,0),Er(e,s,n),s.set(r,o),s}var eh=Symbol.for("@ipld/js-cid/CID");var Ys={};Pe(Ys,{identity:()=>Ze});var Vc=0,th="identity",jc=qe;function rh(t,e){if(e?.truncate!=null&&e.truncate!==t.byteLength){if(e.truncate<0||e.truncate>t.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,e.truncate)}return Ne(Vc,jc(t))}var Ze={code:Vc,name:th,encode:jc,digest:rh};function ve(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}function nh(t){return t.buffer instanceof ArrayBuffer}function Ce(t){return nh(t)?t:t.slice()}async function Wc(t,e,r,n){let o=await crypto.subtle.importKey("jwk",t,{name:"ECDSA",namedCurve:t.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,Ce(e),Ce(r.subarray()));return n?.signal?.throwIfAborted(),s}function we(t=0){return new Uint8Array(t)}function xe(t=0){return new Uint8Array(t)}function oh(t){return t?.buffer instanceof ArrayBuffer}function Xs(t){if(oh(t))return t;let e=t.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function Ue(t,e){e==null&&(e=t.reduce((o,s)=>o+s.length,0));let r=xe(e),n=0;for(let o of t)r.set(o,n),n+=o.length;return Xs(r)}var Yc=Symbol.for("@achingbrain/uint8arraylist");function Gc(t,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let r=0;for(let n of t){let o=r+n.byteLength;if(e<o)return{buf:n,index:e-r};r=o}throw new RangeError("index is out of bounds")}function io(t){return!!t?.[Yc]}var Y=class t{bufs;length;[Yc]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let r=0;for(let n of e)if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.push(n);else if(io(n)){r+=n.byteLength;for(let o of n.bufs)this.bufs.push(o)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=r}prepend(...e){this.prependAll(e)}prependAll(e){let r=0;for(let n of e.reverse())if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.unshift(n);else if(io(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(e){let r=Gc(this.bufs,e);return r.buf[r.index]}set(e,r){let n=Gc(this.bufs,e);n.buf[n.index]=r}write(e,r=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(r+n,e[n]);else if(io(e))for(let n=0;n<e.length;n++)this.set(r+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,r){let{bufs:n,length:o}=this._subList(e,r);return Ue(n,o)}subarray(e,r){let{bufs:n,length:o}=this._subList(e,r);return n.length===1?n[0]:Ue(n,o)}sublist(e,r){let{bufs:n,length:o}=this._subList(e,r),s=new t;return s.length=o,s.bufs=n,s}_subList(e,r){if(e=e??0,r=r??this.length,e<0&&(e=this.length+e),r<0&&(r=this.length+r),e<0||r>this.length)throw new RangeError("index is out of bounds");if(e===r)return{bufs:[],length:0};if(e===0&&r===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let f=e>=a&&e<c,u=r>a&&r<=c;if(f&&u){if(e===a&&r===c){n.push(i);break}let l=e-a;n.push(i.subarray(l,l+(r-e)));break}if(f){if(e===0){n.push(i);continue}n.push(i.subarray(e-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-e}}indexOf(e,r=0){if(!io(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(r=Number(r??0),isNaN(r)&&(r=0),r<0&&(r=this.length+r),r<0&&(r=0),e.length===0)return r>this.length?this.length:r;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let l=0;l<s;l++)i[l]=-1;for(let l=0;l<o;l++)i[n[l]]=l;let a=i,c=this.byteLength-n.byteLength,f=n.byteLength-1,u;for(let l=r;l<=c;l+=u){u=0;for(let h=f;h>=0;h--){let p=this.get(l+h);if(n[h]!==p){u=Math.max(1,h-a[p]);break}}if(u===0)return l}return-1}getInt8(e){let r=this.subarray(e,e+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt8(0)}setInt8(e,r){let n=xe(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,r),this.write(n,e)}getInt16(e,r){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,r)}setInt16(e,r,n){let o=we(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,r,n),this.write(o,e)}getInt32(e,r){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,r)}setInt32(e,r,n){let o=we(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,r,n),this.write(o,e)}getBigInt64(e,r){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,r)}setBigInt64(e,r,n){let o=we(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,r,n),this.write(o,e)}getUint8(e){let r=this.subarray(e,e+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint8(0)}setUint8(e,r){let n=xe(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,r),this.write(n,e)}getUint16(e,r){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,r)}setUint16(e,r,n){let o=we(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,r,n),this.write(o,e)}getUint32(e,r){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,r)}setUint32(e,r,n){let o=we(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,r,n),this.write(o,e)}getBigUint64(e,r){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,r)}setBigUint64(e,r,n){let o=we(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,r,n),this.write(o,e)}getFloat32(e,r){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,r)}setFloat32(e,r,n){let o=we(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,r,n),this.write(o,e)}getFloat64(e,r){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,r)}setFloat64(e,r,n){let o=we(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,r,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof t)||e.bufs.length!==this.bufs.length)return!1;for(let r=0;r<this.bufs.length;r++)if(!ve(this.bufs[r],e.bufs[r]))return!1;return!0}static fromUint8Arrays(e,r){let n=new t;return n.bufs=e,r==null&&(r=e.reduce((o,s)=>o+s.byteLength,0)),n.length=r,n}};var Zs={};Pe(Zs,{base10:()=>sh});var sh=Lt({prefix:"9",name:"base10",alphabet:"0123456789"});var Qs={};Pe(Qs,{base16:()=>ih,base16upper:()=>ah});var ih=me({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4,caseInsensitive:!0}),ah=me({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4,caseInsensitive:!0});var Js={};Pe(Js,{base2:()=>ch});var ch=me({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var ei={};Pe(ei,{base256emoji:()=>hh});var Xc=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}"),fh=Xc.reduce((t,e,r)=>(t[r]=e,t),[]),uh=Xc.reduce((t,e,r)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return t[n]=r,t},[]);function lh(t){return t.reduce((e,r)=>(e+=fh[r],e),"")}function dh(t){let e=[];for(let r of t){let n=r.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${r}`);let o=uh[n];if(o==null)throw new Error(`Non-base256emoji character: ${r}`);e.push(o)}return new Uint8Array(e)}var hh=xr({prefix:"\u{1F680}",name:"base256emoji",encode:lh,decode:dh});var ti={};Pe(ti,{base64:()=>ph,base64pad:()=>mh,base64url:()=>rn,base64urlpad:()=>yh});var ph=me({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),mh=me({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),rn=me({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),yh=me({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ri={};Pe(ri,{base8:()=>gh});var gh=me({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var ni={};Pe(ni,{identity:()=>bh});var bh=xr({prefix:"\0",name:"identity",encode:t=>Nc(qe(t)),decode:t=>qe(Pc(t))});var j0=new TextEncoder,W0=new TextDecoder;var ii={};Pe(ii,{sha256:()=>pt,sha512:()=>Sh});var Eh=20;function si({name:t,code:e,encode:r,minDigestLength:n,maxDigestLength:o}){return new oi(t,e,r,n,o)}var oi=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,r,n,o,s){this.name=e,this.code=r,this.encode=n,this.minDigestLength=o??Eh,this.maxDigestLength=s}digest(e,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(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?Zc(n,this.code,r?.truncate):n.then(o=>Zc(o,this.code,r?.truncate))}else throw Error("Unknown type, must be binary type")}};function Zc(t,e,r){if(r!=null&&r!==t.byteLength){if(r>t.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,r)}return Ne(e,t)}function Jc(t){return async e=>new Uint8Array(await crypto.subtle.digest(t,e))}var pt=si({name:"sha2-256",code:18,encode:Jc("SHA-256")}),Sh=si({name:"sha2-512",code:19,encode:Jc("SHA-512")});var Zt={...ni,...Js,...ri,...Zs,...Qs,...qs,...Vs,...zs,...ti,...ei},sg={...ii,...Ys};function tf(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var ef=tf("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),ai=tf("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);let e=xe(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),Ah={utf8:ef,"utf-8":ef,hex:Zt.base16,latin1:ai,ascii:ai,binary:ai,...Zt},ao=Ah;function Z(t,e="utf8"){let r=ao[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return r.decoder.decode(`${r.prefix}${t}`)}function W(t,e="utf8"){let r=ao[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return r.encoder.encode(t).substring(1)}var vh=parseInt("11111",2),ci=parseInt("10000000",2),Ch=parseInt("01111111",2),rf={0:nn,1:nn,2:_h,3:Bh,4:Dh,5:Lh,6:Th,16:nn,22:nn,48:nn};function mt(t,e={offset:0}){let r=t[e.offset]&vh;if(e.offset++,rf[r]!=null)return rf[r](t,e);throw new Error("No decoder for tag "+r)}function on(t,e){let r=0;if((t[e.offset]&ci)===ci){let n=t[e.offset]&Ch,o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++){if(e.offset>=t.byteLength)throw new Error("invalid DER element length");o+=t[e.offset].toString(16).padStart(2,"0")}r=parseInt(o,16)}else r=t[e.offset],e.offset++;if(!Number.isInteger(r)||r<0||r>t.byteLength-e.offset)throw new Error("invalid DER element length");return r}function nn(t,e){on(t,e);let r=[];for(;!(e.offset>=t.byteLength);){let n=mt(t,e);if(n===null)break;r.push(n)}return r}function _h(t,e){let r=on(t,e),n=e.offset,o=e.offset+r,s=[];for(let i=n;i<o;i++)i===n&&t[i]===0||s.push(t[i]);return e.offset+=r,Uint8Array.from(s)}function Th(t,e){let r=on(t,e),n=e.offset+r,o=t[e.offset];e.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,c=[];for(;e.offset<n;){let f=t[e.offset];if(e.offset++,c.push(f&127),f<128){c.reverse();let u=0;for(let l=0;l<c.length;l++)u+=c[l]<<l*7;a+=`.${u}`,c=[]}}return a}function Lh(t,e){return e.offset++,null}function Bh(t,e){let r=on(t,e),n=t[e.offset];e.offset++;let o=t.subarray(e.offset,e.offset+r-1);if(e.offset+=r,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function Dh(t,e){let r=on(t,e),n=t.subarray(e.offset,e.offset+r);return e.offset+=r,n}function Ih(t){let e=t.toString(16);e.length%2===1&&(e="0"+e);let r=new Y;for(let n=0;n<e.length;n+=2)r.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return r}function fi(t){if(t.byteLength<128)return Uint8Array.from([t.byteLength]);let e=Ih(t.byteLength);return new Y(Uint8Array.from([e.byteLength|ci]),e)}function Fe(t){let e=new Y,r=128;return(t.subarray()[0]&r)===r&&e.append(Uint8Array.from([0])),e.append(t),new Y(Uint8Array.from([2]),fi(e),e)}function co(t){let e=Uint8Array.from([0]),r=new Y(e,t);return new Y(Uint8Array.from([3]),fi(r),r)}function Dt(t,e=48){let r=new Y;for(let n of t)r.append(n);return new Y(Uint8Array.from([e]),fi(r),r)}var Rh=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Oh=Uint8Array.from([6,5,43,129,4,0,34]),Ph=Uint8Array.from([6,5,43,129,4,0,35]),Nh={ext:!0,kty:"EC",crv:"P-256"},Uh={ext:!0,kty:"EC",crv:"P-384"},kh={ext:!0,kty:"EC",crv:"P-521"},ui=32,li=48,di=66;function hi(t){let e=mt(t);return nf(e)}function nf(t){let e=t[1][1][0],r=1,n,o;if(e.byteLength===ui*2+1)return n=W(e.subarray(r,r+ui),"base64url"),o=W(e.subarray(r+ui),"base64url"),new vr({...Nh,key_ops:["verify"],x:n,y:o});if(e.byteLength===li*2+1)return n=W(e.subarray(r,r+li),"base64url"),o=W(e.subarray(r+li),"base64url"),new vr({...Uh,key_ops:["verify"],x:n,y:o});if(e.byteLength===di*2+1)return n=W(e.subarray(r,r+di),"base64url"),o=W(e.subarray(r+di),"base64url"),new vr({...kh,key_ops:["verify"],x:n,y:o});throw new J(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function of(t){return Dt([Fe(Uint8Array.from([1])),Dt([Mh(t.crv)],160),Dt([co(new Y(Uint8Array.from([4]),Z(t.x??"","base64url"),Z(t.y??"","base64url")))],161)]).subarray()}function Mh(t){if(t==="P-256")return Rh;if(t==="P-384")return Oh;if(t==="P-521")return Ph;throw new J(`Invalid curve ${t}`)}var vr=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=of(this.jwk)),this._raw}toMultihash(){return Ze.digest(It(this))}toCID(){return Ee.createV1(114,this.toMultihash())}toString(){return ye.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ve(this.raw,e.raw)}async verify(e,r,n){return Wc(this.jwk,r,e,n)}};var fo=BigInt(4294967295),sf=BigInt(32);function Fh(t,e=!1){return e?{h:Number(t&fo),l:Number(t>>sf&fo)}:{h:Number(t>>sf&fo)|0,l:Number(t&fo)|0}}function af(t,e=!1){let r=t.length,n=new Uint32Array(r),o=new Uint32Array(r);for(let s=0;s<r;s++){let{h:i,l:a}=Fh(t[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var Kh=t=>t/2**32|0,Hh=t=>t>>>0;function cf(t,e,r,n){let o=Kh(r),s=Hh(r);t.setUint32(e,n?s:o,n),t.setUint32(e+4,n?o:s,n)}var pi=(t,e,r)=>t>>>r,mi=(t,e,r)=>t<<32-r|e>>>r,Qt=(t,e,r)=>t>>>r|e<<32-r,Jt=(t,e,r)=>t<<32-r|e>>>r,sn=(t,e,r)=>t<<64-r|e>>>r-32,an=(t,e,r)=>t>>>r-32|e<<64-r;function at(t,e,r,n){let o=(e>>>0)+(n>>>0);return{h:t+r+(o/2**32|0)|0,l:o|0}}var ff=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),uf=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,lf=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),df=(t,e,r,n,o)=>e+r+n+o+(t/2**32|0)|0,hf=(t,e,r,n,o)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(o>>>0),pf=(t,e,r,n,o,s)=>e+r+n+o+s+(t/2**32|0)|0;function uo(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}var yi=t=>t?`"${t}" `:"";function Qe(t,e=""){if(typeof t!="number")throw new TypeError(yi(e)+"expected number, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw new RangeError(yi(e)+"expected integer >= 0, got "+t);return t}function ke(t,e,r=""){if(uo(t)&&(e===void 0||t.length===e))return t;e!==void 0&&Qe(e,"length");let n=uo(t),o=e!==void 0?` of length ${e}`:"",s=n?`length=${t.length}`:`type=${typeof t}`,i=yi(r)+"expected Uint8Array"+o+", got "+s;throw n?new RangeError(i):new TypeError(i)}function er(t){if(typeof t!="function"||typeof t.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(Qe(t.outputLen),Qe(t.blockLen),t.outputLen<1||t.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}var zh=(t,e)=>{if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof t)},mf=(t,e)=>{zh(t,e);let r=Object.getPrototypeOf(t);if(r!==Object.prototype&&r!==null)throw new TypeError(`"${e}" expected plain object`);if(Object.hasOwn(t,"__proto__"))throw new TypeError(`"${e}.__proto__" is not allowed`)};function Cr(t,e=!0){if(t.destroyed)throw new Error("hash was destroyed");if(e&&t.finished)throw new Error("digest() was already called")}function lo(t,e){ke(t,void 0,"output");let r=e.outputLen;if(!(t.length>=r))throw new RangeError('"output" expected length >= '+r)}function Ve(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function ho(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Je(t,e){return t<<32-e|t>>>e}var gf=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",qh=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function po(t){if(ke(t),gf)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=qh[t[r]];return e}function yf(t){return t>=48&&t<=57?t-48:t>=65&&t<=70?t-55:t>=97&&t<=102?t-87:void 0}function mo(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);if(gf)try{return Uint8Array.fromHex(t)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}let e=t.length,r=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(r);for(let o=0,s=0;o<r;o++,s+=2){let i=yf(t.charCodeAt(s)),a=yf(t.charCodeAt(s+1));if(i===void 0||a===void 0){let c=t[s]+t[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function gi(...t){let e=0;for(let n=0;n<t.length;n++){let o=t[n];ke(o),e+=o.length}let r=new Uint8Array(e);for(let n=0,o=0;n<t.length;n++){let s=t[n];r.set(s,o),o+=s.length}return r}function Vh(t,e,r="opts"){return mf(t,"defaults"),e!==void 0&&mf(e,r),Object.assign(Object.create(null),t,e)}function bi(t,e={}){if(typeof t!="function")throw new TypeError('"hashCons" expected function, got type='+typeof t);e=Vh({},e,"info");let r=(o,s)=>t(s).update(o).digest(),n=t(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=o=>t(o),Object.assign(r,e),Object.freeze(r)}function bf(t=32){Qe(t,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(t>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${t}`);return e.getRandomValues(new Uint8Array(t))}var wi=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});function wf(t,e,r){return t&e^~t&r}function xf(t,e,r){return t&e^t&r^e&r}var cn=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,r,n,o){this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=ho(this.buffer)}update(e){Cr(this),ke(e);let{view:r,buffer:n,blockLen:o}=this,s=e.length,i=!1;for(let a=0;a<s;){let c=Math.min(o-this.pos,s-a);if(c===o){let f=ho(e);for(;o<=s-a;a+=o)this.process(f,a);i=!0;continue}n.set(a===0&&c===s?e:e.subarray(a,a+c),this.pos),this.pos+=c,a+=c,this.pos===o&&(this.process(r,0),this.pos=0,i=!0)}return this.length+=e.length,i&&this.roundClean(),this}digestInto(e){Cr(this),lo(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;r[i++]=128,r.fill(0,i),this.padOffset>o-i&&(this.process(n,0),r.fill(0)),cf(n,o-8,this.length*8,s),this.process(n,0),this.roundClean();let a=e===r?n:ho(e),c=this.outputLen,f=c/4,u=this.get();if(c%4||f>u.length)throw new Error("invalid outputLen");for(let l=0;l<f;l++)a.setUint32(4*l,u[l],s)}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}_cloneIntoMeta(e){let{buffer:r,length:n,finished:o,destroyed:s,pos:i}=this;return e.destroyed=s,e.finished=o,e.length=n,e.pos=i,i&&e.buffer.set(r),e}clone(){return this._cloneInto()}},Ef=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Sf=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var jh=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]),Rt=new Uint32Array(64),xi=class extends cn{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,r){super(64,e,8,!1),this.A=r[0]|0,this.B=r[1]|0,this.C=r[2]|0,this.D=r[3]|0,this.E=r[4]|0,this.F=r[5]|0,this.G=r[6]|0,this.H=r[7]|0}get(){let{A:e,B:r,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,r,n,o,s,i,a,c]}set(e,r,n,o,s,i,a,c){this.A=e|0,this.B=r|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,r){for(let l=0;l<16;l++,r+=4)Rt[l]=e.getUint32(r,!1);for(let l=16;l<64;l++){let h=Rt[l-15],p=Rt[l-2],x=Je(h,7)^Je(h,18)^h>>>3,w=Je(p,17)^Je(p,19)^p>>>10;Rt[l]=w+Rt[l-7]+x+Rt[l-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:f,H:u}=this;for(let l=0;l<64;l++){let h=Je(a,6)^Je(a,11)^Je(a,25),p=u+h+wf(a,c,f)+jh[l]+Rt[l]|0,w=(Je(n,2)^Je(n,13)^Je(n,22))+xf(n,o,s)|0;u=f,f=c,c=a,a=i+p|0,i=s,s=o,o=n,n=p+w|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,f=f+this.G|0,u=u+this.H|0,this.set(n,o,s,i,a,c,f,u)}roundClean(){Ve(Rt)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Ve(this.buffer)}},Ei=class extends xi{constructor(){super(32,Ef)}};var Af=af(["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(t=>BigInt(t))),Wh=Af[0],Gh=Af[1],Ot=new Uint32Array(80),Pt=new Uint32Array(80),Si=class extends cn{Ah=0;Al=0;Bh=0;Bl=0;Ch=0;Cl=0;Dh=0;Dl=0;Eh=0;El=0;Fh=0;Fl=0;Gh=0;Gl=0;Hh=0;Hl=0;constructor(e,r){super(128,e,16,!1),this.Ah=r[0]|0,this.Al=r[1]|0,this.Bh=r[2]|0,this.Bl=r[3]|0,this.Ch=r[4]|0,this.Cl=r[5]|0,this.Dh=r[6]|0,this.Dl=r[7]|0,this.Eh=r[8]|0,this.El=r[9]|0,this.Fh=r[10]|0,this.Fl=r[11]|0,this.Gh=r[12]|0,this.Gl=r[13]|0,this.Hh=r[14]|0,this.Hl=r[15]|0}get(){let{Ah:e,Al:r,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:f,El:u,Fh:l,Fl:h,Gh:p,Gl:x,Hh:w,Hl:m}=this;return[e,r,n,o,s,i,a,c,f,u,l,h,p,x,w,m]}set(e,r,n,o,s,i,a,c,f,u,l,h,p,x,w,m){this.Ah=e|0,this.Al=r|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=f|0,this.El=u|0,this.Fh=l|0,this.Fl=h|0,this.Gh=p|0,this.Gl=x|0,this.Hh=w|0,this.Hl=m|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,r){for(let b=0;b<16;b++,r+=4)Ot[b]=e.getUint32(r),Pt[b]=e.getUint32(r+=4);for(let b=16;b<80;b++){let L=Ot[b-15]|0,C=Pt[b-15]|0,O=Qt(L,C,1)^Qt(L,C,8)^pi(L,C,7),R=Jt(L,C,1)^Jt(L,C,8)^mi(L,C,7),N=Ot[b-2]|0,B=Pt[b-2]|0,I=Qt(N,B,19)^sn(N,B,61)^pi(N,B,6),K=Jt(N,B,19)^an(N,B,61)^mi(N,B,6),F=lf(R,K,Pt[b-7],Pt[b-16]),q=df(F,O,I,Ot[b-7],Ot[b-16]);Ot[b]=q|0,Pt[b]=F|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:f,Dl:u,Eh:l,El:h,Fh:p,Fl:x,Gh:w,Gl:m,Hh:g,Hl:E}=this;for(let b=0;b<80;b++){let L=Qt(l,h,14)^Qt(l,h,18)^sn(l,h,41),C=Jt(l,h,14)^Jt(l,h,18)^an(l,h,41),O=l&p^~l&w,R=h&x^~h&m,N=hf(E,C,R,Gh[b],Pt[b]),B=pf(N,g,L,O,Wh[b],Ot[b]),I=N|0,K=Qt(n,o,28)^sn(n,o,34)^sn(n,o,39),F=Jt(n,o,28)^an(n,o,34)^an(n,o,39),q=n&s^n&a^s&a,_=o&i^o&c^i&c;g=w|0,E=m|0,w=p|0,m=x|0,p=l|0,x=h|0,{h:l,l:h}=at(f|0,u|0,B|0,I|0),f=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let U=ff(I,F,_);n=uf(U,B,K,q),o=U|0}({h:n,l:o}=at(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=at(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=at(this.Ch|0,this.Cl|0,a|0,c|0),{h:f,l:u}=at(this.Dh|0,this.Dl|0,f|0,u|0),{h:l,l:h}=at(this.Eh|0,this.El|0,l|0,h|0),{h:p,l:x}=at(this.Fh|0,this.Fl|0,p|0,x|0),{h:w,l:m}=at(this.Gh|0,this.Gl|0,w|0,m|0),{h:g,l:E}=at(this.Hh|0,this.Hl|0,g|0,E|0),this.set(n,o,s,i,a,c,f,u,l,h,p,x,w,m,g,E)}roundClean(){Ve(Ot,Pt)}destroy(){this.destroyed=!0,Ve(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Ai=class extends Si{constructor(){super(64,Sf)}};var ct=bi(()=>new Ei,wi(1));var vi=bi(()=>new Ai,wi(3));function go(t,e,r=()=>{}){if(!Array.isArray(t))throw new TypeError(`"${e}" expected array, got type=${typeof t}`);for(let n=0;n<t.length;n++)r(t[n],`${e}[${n}]`);return t}var Q=(t,e,r)=>ke(t,e,r),Ci=Qe;function Cf(t,e=""){if(typeof t!="string"){let r=e&&`"${e}" `;throw new TypeError(r+"expected string, got type="+typeof t)}return t}function Nt(t,e="object"){if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof t}`);return t}function tr(t,e){if(typeof t!="function")throw new TypeError(`"${e}" is invalid: expected function, got ${typeof t}`);return t}var fn=po,je=(...t)=>gi(...t),_r=t=>mo(t),kt=uo,yt=t=>bf(t),yo=BigInt(0),vf=BigInt(1),Yh=t=>t?`"${t}" `:"";function Ke(t,e=""){if(typeof t!="boolean")throw new TypeError(Yh(e)+"expected boolean, got type="+typeof t);return t}function bo(t){if(typeof t=="bigint"){if(!Ut(t))throw new RangeError("positive bigint expected, got "+t)}else Ci(t);return t}function gt(t,e=""){if(typeof t!="number"){let r=e&&`"${e}" `;throw new TypeError(r+"expected number, got type="+typeof t)}if(!Number.isSafeInteger(t)){let r=e&&`"${e}" `;throw new RangeError(r+"expected safe integer, got "+t)}}function un(t){let e=bo(t).toString(16);return e.length&1?"0"+e:e}function _f(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);return t===""?yo:BigInt("0x"+t)}function ft(t){return _f(po(t))}function ut(t){return _f(po(Mt(ke(t)).reverse()))}function wo(t,e){if(Qe(e),e===0)throw new Error("zero output length is invalid");t=bo(t);let r=e*2,n=t.toString(16);if(n.length>r)throw new RangeError("number is too large");return mo(n.padStart(r,"0"))}function ln(t,e){return wo(t,e).reverse()}function Mt(t){return Uint8Array.from(Q(t))}function Ut(t){return typeof t=="bigint"&&yo<=t}function _i(t,e,r){return Ut(t)&&Ut(e)&&Ut(r)&&e<=t&&t<r}function lt(t,e,r,n){if(!_i(e,r,n))throw new RangeError("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function Tr(t){if(t<yo)throw new Error("expected non-negative bigint, got "+t);return t===yo?0:t.toString(2).length}var dn=t=>(gt(t,"n"),(vf<<BigInt(t))-vf);function Tf(t,e,r){if(Qe(t,"hashLen"),Qe(e,"qByteLen"),typeof r!="function")throw new TypeError("hmacFn must be a function");let n=m=>new Uint8Array(m),o=Uint8Array.of(),s=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(t),f=n(t),u=0,l=()=>{c.fill(1),f.fill(0),u=0},h=(...m)=>r(f,je(c,...m)),p=(m=o)=>{f=h(s,m),c=h(),m.length!==0&&(f=h(i,m),c=h())},x=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let m=0,g=[];for(;m<e;){c=h();let E=c.slice();g.push(E),m+=c.length}return je(...g)};return(m,g)=>{l(),p(m);let E;for(;(E=g(x()))===void 0;)p();return l(),E}}function Be(t,e={},r={},n="object"){Nt(t,n),Nt(e,"fields"),Nt(r,"optFields");function o(i,a,c){let f=n==="object"?`param "${String(i)}"`:`"${n}.${String(i)}"`,u=t[i];if(!Object.hasOwn(t,i)&&(c?u!==void 0:a!=="function"))throw new TypeError(`${f} is invalid: expected own property`);if(c&&u===void 0)return;let l=typeof u;if(l!==a||u===null)throw new TypeError(`${f} is invalid: expected ${a}, got ${l}`)}let s=(i,a)=>Object.entries(i).forEach(([c,f])=>o(c,f,a));s(e,!1),s(r,!0)}var Se=BigInt(0),re=BigInt(1),Ft=BigInt(2),Df=BigInt(3),Ti=BigInt(4),If=BigInt(5),Xh=BigInt(7),Rf=BigInt(8),Zh=BigInt(9),Qh=BigInt(15),Of=BigInt(16),Jh=BigInt("0x10000000000000000");function se(t,e){if(e<=Se)throw new Error("mod: expected positive modulus, got "+e);let r=t%e;return r>=Se?r:e+r}function Pf(t,e,r){if(r<=re)throw new Error("pow: expected modulus > 1, got "+r);if(typeof e!="bigint")throw new TypeError("invalid exponent: expected bigint, got "+typeof e);if(e<Se)throw new Error("invalid exponent, negatives unsupported");if(e===Se)return re;if(e===re)return t;let n=t%r;if(n<Se&&(n+=r),e<Jh){let a=re;for(;e>Se;)e&re&&(a=a*n%r),n=n*n%r,e>>=re;return a}let o=[];for(;e>Se;)o.push(Number(e&Qh)),e>>=Ti;let s=new Array(16);s[0]=re,s[1]=n;for(let a=2;a<16;a++)s[a]=s[a-1]*n%r;let i=s[o[o.length-1]];for(let a=o.length-2;a>=0;a--){i=i*i%r,i=i*i%r,i=i*i%r,i=i*i%r;let c=o[a];c!==0&&(i=i*s[c]%r)}return i}function le(t,e,r){if(r<=re)throw new Error("pow2: expected modulus > 1, got "+r);if(e<Se)throw new Error("pow2: expected non-negative exponent, got "+e);let n=t;for(;e-- >Se;)n*=n,n%=r;return n}function Lf(t,e){if(t===Se)throw new Error("invert: expected non-zero number");if(e<=re)throw new Error("invert: expected modulus > 1, got "+e);let r=se(t,e),n=e,o=Se,s=re;for(;r!==Se;){let a=n/r,c=n-r*a,f=o-s*a;n=r,r=c,o=s,s=f}if(n!==re)throw new Error("invert: does not exist");return se(o,e)}function Nf(t,e){if(e<=re)throw new Error("invertCt: expected prime modulus > 1, got "+e);let r=se(t,e);if(r===Se)throw new Error("invertCt: expected non-zero number");let n=Pf(r,e-Ft,e);if(se(r*n,e)!==re)throw new Error("invertCt: does not exist");return n}function Li(t,e,r){let n=t;if(!n.eql(n.sqr(e),r))throw new Error("Cannot find square root")}function Bi(t,e){if((t&re)===Se)throw new Error(e+": expected odd modulus, got "+t)}function Uf(t,e){let r=t,n=(r.ORDER+re)/Ti,o=r.pow(e,n);return Li(r,o,e),o}function ep(t,e){let r=t,n=(r.ORDER-If)/Rf,o=r.mul(e,Ft),s=r.pow(o,n),i=r.mul(e,s),a=r.mul(r.mul(i,Ft),s),c=r.mul(i,r.sub(a,r.ONE));return Li(r,c,e),c}function tp(t){let e=Br(t),r=kf(t),n=r(e,e.neg(e.ONE)),o=r(e,n),s=r(e,e.neg(n)),i=(t+Xh)/Of;return((a,c)=>{let f=a,u=f.pow(c,i),l=f.mul(u,n),h=f.mul(u,o),p=f.mul(u,s),x=f.eql(f.sqr(l),c),w=f.eql(f.sqr(h),c);u=f.cmov(u,l,x),l=f.cmov(p,h,w);let m=f.eql(f.sqr(l),c),g=f.cmov(u,l,m);return Li(f,g,c),g})}function kf(t){if(t<Df)throw new Error("sqrt is not defined for small field");Bi(t,"tonelliShanks");let e=t-re,r=0;for(;e%Ft===Se;)e/=Ft,r++;let n=Ft,o=Br(t);for(;hn(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return Uf;let s=o.pow(n,e),i=(e+re)/Ft;return function(c,f){let u=c;if(u.is0(f))return f;if(hn(u,f)!==1)throw new Error("Cannot find square root");let l=r,h=u.mul(u.ONE,s),p=u.pow(f,e),x=u.pow(f,i);for(;!u.eql(p,u.ONE);){if(u.is0(p))throw new Error("Cannot find square root: probably non-prime P");let w=1,m=u.sqr(p);for(;!u.eql(m,u.ONE);)if(w++,m=u.sqr(m),w===l)throw new Error("Cannot find square root");let g=re<<BigInt(l-w-1),E=u.pow(h,g);l=w,h=u.sqr(E),p=u.mul(p,h),x=u.mul(x,E)}return x}}function rp(t){return Bi(t,"Fp.sqrt"),t%Ti===Df?Uf:t%Rf===If?ep:t%Of===Zh?tp(t):kf(t)}var Mf=(t,e)=>(se(t,e)&re)===re,np=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Lr(t){if(Nt(t,"field"),typeof t.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof t.ORDER);gt(t.BYTES,"BYTES"),gt(t.BITS,"BITS");for(let e of np)tr(t[e],"field."+e);if(t.BYTES<1||t.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(t.ORDER<=re)throw new Error("invalid field: expected ORDER > 1, got "+t.ORDER);return t}function Eo(t,e,r=!1){Lr(t),go(e,"nums"),Ke(r,"passZero");let n=t,o=new Array(e.length).fill(r?n.ZERO:void 0),s=e.reduce((a,c,f)=>n.is0(c)?a:(o[f]=a,n.mul(a,c)),n.ONE),i=n.inv(s);return e.reduceRight((a,c,f)=>n.is0(c)?a:(o[f]=n.mul(a,o[f]),n.mul(a,c)),i),o}function hn(t,e){Lr(t);let r=t;Bi(r.ORDER,"FpLegendre");let n=(r.ORDER-re)/Ft,o=r.pow(e,n),s=r.eql(o,r.ONE),i=r.eql(o,r.ZERO),a=r.eql(o,r.neg(r.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function op(t,e){if(e!==void 0&&Ci(e),t<=Se)throw new Error("invalid n length: expected positive n, got "+t);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let r=Tr(t);if(e!==void 0&&e<r)throw new Error(`invalid n length: expected nBitLength (${e}) >= bitLen(n) (${r})`);let n=e!==void 0?e:r,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}var Bf=new WeakMap,xo=class{ORDER;BITS;BYTES;isLE;ZERO=Se;ONE=re;_lengths;_mod;constructor(e,r={}){if(e<=re)throw new Error("invalid field: expected ORDER > 1, got "+e);let n;this.isLE=!1,r!=null&&typeof r=="object"&&(typeof r.BITS=="number"&&(n=r.BITS),typeof r.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:r.sqrt,enumerable:!0}),typeof r.isLE=="boolean"&&(this.isLE=r.isLE),r.allowedLengths&&(this._lengths=Object.freeze(r.allowedLengths.slice())),typeof r.modFromBytes=="boolean"&&(this._mod=r.modFromBytes));let{nBitLength:o,nByteLength:s}=op(e,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,Object.freeze(this)}create(e){return se(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return Se<=e&&e<this.ORDER}is0(e){return e===Se}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&re)===re}neg(e){return se(-e,this.ORDER)}eql(e,r){return e===r}sqr(e){return se(e*e,this.ORDER)}add(e,r){return se(e+r,this.ORDER)}sub(e,r){return se(e-r,this.ORDER)}mul(e,r){return se(e*r,this.ORDER)}pow(e,r){return Pf(e,r,this.ORDER)}div(e,r){return se(e*Lf(r,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,r){return e+r}subN(e,r){return e-r}mulN(e,r){return e*r}inv(e){return Lf(e,this.ORDER)}sqrt(e){let r=Bf.get(this);return r||Bf.set(this,r=rp(this.ORDER)),r(this,e)}toBytes(e){return this.isLE?ln(e,this.BYTES):wo(e,this.BYTES)}fromBytes(e,r=!1){Q(e);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(e.length<1||!n.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let f=new Uint8Array(o);f.set(e,s?0:f.length-e.length),e=f}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?ut(e):ft(e);if(a&&(c=se(c,i)),!r&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Eo(this,e,!0)}cmov(e,r,n){return Ke(n,"condition"),n?r:e}};function Br(t,e={}){return Object.freeze(xo.prototype),new xo(t,e)}function Ff(t){if(typeof t!="bigint")throw new Error("field order must be bigint");if(t<=re)throw new Error("field order must be greater than 1");let e=Tr(t-re);return Math.ceil(e/8)}function So(t){let e=Ff(t);return e+Math.ceil(e/2)}function Ao(t,e,r=!1){Q(t);let n=t.length,o=Ff(e),s=Math.max(So(e),16);if(n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=r?ut(t):ft(t),a=se(i,e-re)+re;return r?ln(a,o):wo(a,o)}var Ri=BigInt(0),pn=BigInt(1),sp=BigInt(4),Di=16,Kf=128,ip=5,Hf=2**31;function Kt(t){let e=t;if(typeof e!="function")throw new TypeError('"Point" expected constructor, got type='+typeof t);tr(e.fromAffine,"Point.fromAffine"),tr(e.fromBytes,"Point.fromBytes"),tr(e.fromHex,"Point.fromHex"),Nt(e.BASE,"Point.BASE"),Nt(e.ZERO,"Point.ZERO"),Lr(e.Fp),Lr(e.Fn)}function vo(t,e){Kt(t),zf(e,t);let r=Eo(t.Fp,e.map(n=>n.Z));return e.map((n,o)=>t.fromAffine(n.toAffine(r[o])))}function ap(t,e,r=1){if(!Number.isSafeInteger(t)||t<r||t>e)throw new Error("invalid window size, expected ["+r+".."+e+"], got W="+t)}function cp(t,e){let r=t*(4*e+128);if(r>Hf)throw new Error("invalid window size: table would need ~"+Math.ceil(r/2**20)+" MiB, max "+Hf/2**20+" MiB")}function Oi(t,e){if(t!==void 0){tr(t,"randomBytes");try{let r=t(e);if(!kt(r)||r.length!==e)return}catch{return}return t}}function zf(t,e){go(t,"points"),t.forEach((r,n)=>{if(!(r instanceof e))throw new Error("invalid point at index "+n)})}function fp(t,e,r){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((n,o)=>{if(!(r===void 0?e.isValid(n):Ut(n)&&n<r))throw new Error("invalid scalar at index "+o)})}var qf=new WeakMap;function Ii(t){return qf.get(t)||1}function up(t,e){let r=t.double(),n=[t];for(let o=1;o<e;o++)n.push(n[o-1].add(r));return n}function lp(t,e){let r=2**e,n=r/2,o=BigInt(r-1),s=[];for(;t>Ri;){let i=0;t&pn&&(i=Number(t&o),i>=n&&(i-=r),t-=BigInt(i)),s.push(i),t>>=pn}return s}function dp(t,e,r){let n=2**e,o=n/2,s=BigInt(n-1),i=BigInt(e),a=[];for(let c=0;c<r;c++){let f=Number(t&s);t>>=i,f>o&&(f-=n,t+=pn),a.push(f)}if(t!==Ri)throw new Error("invalid wnaf");return a}function hp(t,e,r){let n=0;for(let s of r)n=Math.max(n,s.length);let o=t;for(let s=n-1;s>=0;s--){s!==n-1&&(o=o.double());for(let i=0;i<r.length;i++){let a=r[i][s];if(a){let c=e[i][Math.abs(a)-1>>1];o=o.add(a<0?c.negate():c)}}}return o}var Dr=class{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,r){Kt(e),this.randomBytes=Oi(r,Di),this.Point=e,this.BASE=e.BASE,this.ZERO=e.ZERO,this.bits=e.Fn.BITS}buildWnafTable(e,r,n){let o=Math.ceil(n/r)+1,s=2**(r-1),i=[],a=e;for(let c=0;c<o;c++){let f=a;for(let u=0;u<s;u++)i.push(f),f=f.add(a);a=i[i.length-1].double()}return{W:r,bits:n,windows:o,comp:i}}wnafCachedCT(e,r){let{W:n,windows:o,comp:s}=e,i=2**(n-1),a=dp(r,n,o),c=this.ZERO,f=this.BASE;for(let u=0;u<o;u++){let l=a[u],h=u*i,p=Math.abs(l)-1,x=s[h];for(let m=1;m<i;m++)x=m===p?s[h+m]:x;let w=x.negate();l===0?f=f.add(s[h]):c=c.add(l<0?w:x)}return{p:c,f}}getWnafPrecomputes(e,r,n,o){let s=this.wnafPrecomputes.get(r),i=s?.find(a=>a.W===e&&a.bits===n);return i||(i=this.buildWnafTable(r,e,n),typeof o=="function"&&(i={...i,comp:o(i.comp)}),s||(s=[],this.wnafPrecomputes.set(r,s)),s.push(i)),i}assertPoint(e){if(!(e instanceof this.Point))throw new TypeError('"point" expected Point instance, got type='+typeof e)}validateMulInput(e,r){if(this.assertPoint(e),!_i(r,pn,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(e,r,n,o){let s=Ii(e);return s===1?this.fixedWindowCT(e,r,n):this.wnafCachedCT(this.getWnafPrecomputes(s,e,n,o),r)}mulCT(e,r,n){return this.validateMulInput(e,r),this.runCT(e,r,this.bits,n)}mulCTBlinded(e,r,n){if(this.validateMulInput(e,r),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");let o=this.Point.Fn.BITS+Kf,s=this.randomBytes(Di);if(!kt(s)||s.length!==Di)throw new Error("randomBytes returned invalid byte array");s[0]=s[0]&63|128;let i=r+ft(s)*this.Point.Fn.ORDER;return this.runCT(e,i,o,n)}fixedWindowCT(e,r,n){let o=ip,s=1<<o,i=dn(o),a=new Array(s);a[0]=this.ZERO;for(let u=1;u<s;u++)a[u]=a[u-1].add(e);let c=Math.ceil(n/o),f=this.ZERO;for(let u=c-1;u>=0;u--){if(u!==c-1)for(let p=0;p<o;p++)f=f.double();let l=Number(r>>BigInt(u*o)&i),h=a[0];for(let p=1;p<s;p++)h=p===l?a[p]:h;f=f.add(h)}return{p:f,f}}shouldBlind(e,r){return this.randomBytes===void 0?!1:r===pn?!0:e!==this.BASE?!1:(this.baseCanBeBlinded===void 0&&(this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0()),this.baseCanBeBlinded)}mulSecret(e,r,n,o){return this.shouldBlind(e,n)?this.mulCTBlinded(e,r,o):this.mulCT(e,r,o)}mulUnsafe(e,r,n){if(this.assertPoint(e),!Ut(r))throw new Error("invalid scalar");let o=Ii(e);if(o===1||r>=this.Point.Fn.ORDER)return Co(this.Point,[e],[r],!0);let s=this.getWnafPrecomputes(o,e,this.bits,n);return this.wnafCachedCT(s,r).p}setWindowSize(e,r){this.assertPoint(e),ap(r,this.bits);let n=Math.ceil((this.bits+Kf)/r)+1;cp(n*2**(r-1),this.Point.Fp.BYTES),qf.set(e,r),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return Ii(e)!==1}};function Co(t,e,r,n=!1){if(Kt(t),zf(e,t),Ke(n,"allowOversized"),fp(r,t.Fn,n?t.Fn.ORDER**sp:void 0),e.length!==r.length)throw new Error("arrays of points and scalars must have equal length");let o=e.map(i=>up(i,4)),s=r.map(i=>lp(i,4));return hp(t.ZERO,o,s)}function $f(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Lr(e),e}else return Br(t,{isLE:r})}function _o(t,e,r={},n){if(t!=="weierstrass"&&t!=="edwards")throw new Error('expected curve type "weierstrass" or "edwards"');if(n===void 0&&(n=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);Be(r);for(let c of["p","n","h"]){let f=e[c];if(!(Ut(f)&&f!==Ri))throw new Error(`CURVE.${c} must be positive bigint`)}let o=$f(e.p,r.Fp,n),s=$f(e.n,r.Fn,n),a=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}function Ir(t,e){return function(n){let o=t(n);return{secretKey:o,publicKey:e(o)}}}var To=BigInt(0),Lo=BigInt(1),Bo=BigInt(2),pp=BigInt(4),Vf=BigInt(8);function mp(t,e,r,n){let o=t.sqr(r),s=t.sqr(n),i=t.add(t.mul(e.a,o),s),a=t.add(t.ONE,t.mul(e.d,t.mul(o,s)));return t.eql(i,a)}function jf(t,e={}){Be(e,{},{},"extraOpts");let r=e,n=_o("edwards",t,r,r.FpFnLE),{Fp:o,Fn:s}=n,i=n.CURVE,{h:a}=i;if(hn(o,i.a)!==1)throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(hn(o,i.d)!==-1)throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");Be(r,{},{uvRatio:"function",randomBytes:"function"});let c=r.randomBytes===void 0?yt:r.randomBytes,f=Bo<<BigInt(o.BYTES*8)-Lo;function u(E){if(!o.isOdd)throw new Error("Field does not have .isOdd()");return o.isOdd(E)}let l=r.uvRatio===void 0?(E,b)=>{try{return{isValid:!0,value:o.sqrt(o.div(E,b))}}catch{return{isValid:!1,value:To}}}:r.uvRatio;if(!mp(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");let h=o.eql(i.a,o.neg(o.ONE))?E=>o.neg(E):o.eql(i.a,o.ONE)?E=>E:E=>o.mul(i.a,E);function p(E,b,L=!1){let C=L?Lo:To;return lt("coordinate "+E,b,C,f),b}function x(E){if(!(E instanceof w))throw new Error("EdwardsPoint expected")}class w{static BASE=new w(i.Gx,i.Gy,o.ONE,o.mul(i.Gx,i.Gy));static ZERO=new w(o.ZERO,o.ONE,o.ONE,o.ZERO);static Fp=o;static Fn=s;X;Y;Z;T;constructor(b,L,C,O){this.X=p("x",b),this.Y=p("y",L),this.Z=p("z",C,!0),this.T=p("t",O),Object.freeze(this)}static CURVE(){return i}static fromAffine(b){if(b instanceof w)throw new Error("extended point not allowed");let{x:L,y:C}=b||{};return p("x",L),p("y",C),new w(L,C,o.ONE,o.mul(L,C))}static fromBytes(b,L=!1){let C=o.BYTES,{a:O,d:R}=i;b=Mt(Q(b,C,"point")),Ke(L,"zip215");let N=Mt(b),B=b[C-1];N[C-1]=B&-129;let I=ut(N),K=L?f:o.ORDER;lt("point.y",I,To,K);let F=o.sqr(I),q=o.sub(F,o.ONE),_=o.sub(o.mulN(R,F),O),{isValid:U,value:T}=l(q,_);if(!U)throw new Error("bad point: invalid y coordinate");let v=u(T),H=(B&128)!==0;if(!L&&o.is0(T)&&H)throw new Error("bad point: x=0 and x_0=1");return H!==v&&(T=o.neg(T)),w.fromAffine({x:T,y:I})}static fromHex(b,L=!1){return w.fromBytes(_r(b),L)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(b=6,L=!0){return g.setWindowSize(this,b),L||this.multiply(Bo),this}assertValidity(){let b=this,{a:L,d:C}=i;if(b.is0())throw new Error("bad point: ZERO");let{X:O,Y:R,Z:N,T:B}=b,I=o.sqr(O),K=o.sqr(R),F=o.sqr(N),q=o.sqr(F),_=o.mul(I,L),U=o.mul(o.add(_,K),F),T=o.add(q,o.mul(C,o.mul(I,K)));if(!o.eql(U,T))throw new Error("bad point: equation left != right (1)");let v=o.mul(O,R),H=o.mul(N,B);if(!o.eql(v,H))throw new Error("bad point: equation left != right (2)")}equals(b){x(b);let{X:L,Y:C,Z:O}=this,{X:R,Y:N,Z:B}=b,I=o.mul(L,B),K=o.mul(R,O),F=o.mul(C,B),q=o.mul(N,O);return o.eql(I,K)&&o.eql(F,q)}is0(){return this.equals(w.ZERO)}negate(){return new w(o.neg(this.X),this.Y,this.Z,o.neg(this.T))}double(){let{X:b,Y:L,Z:C}=this,O=o.sqr(b),R=o.sqr(L),N=o.mul(o.sqr(C),Bo),B=h(O),I=o.addN(b,L),K=o.sub(o.subN(o.sqr(I),O),R),F=o.addN(B,R),q=o.subN(F,N),_=o.subN(B,R),U=o.mul(K,q),T=o.mul(F,_),v=o.mul(K,_),H=o.mul(q,F);return new w(U,T,H,v)}add(b){x(b);let{d:L}=i,{X:C,Y:O,Z:R,T:N}=this,{X:B,Y:I,Z:K,T:F}=b,q=o.mul(C,B),_=o.mul(O,I),U=o.mul(o.mulN(N,L),F),T=o.mul(R,K),v=o.sub(o.subN(o.mulN(o.addN(C,O),o.addN(B,I)),q),_),H=o.subN(T,U),D=o.addN(T,U),S=o.sub(_,h(q)),d=o.mul(v,H),y=o.mul(D,S),A=o.mul(v,S),P=o.mul(H,D);return new w(d,y,P,A)}subtract(b){return x(b),this.add(b.negate())}multiply(b){if(!s.isValidNot0(b))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:L,f:C}=g.mulSecret(this,b,a,m);return m([L,C])[0]}multiplyUnsafe(b){if(!s.isValid(b))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return b===To?w.ZERO:this.is0()||b===Lo?this:g.mulUnsafe(this,b,m)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return g.mulUnsafe(this,i.n).is0()}toAffine(b){let L=this,C=b;if(C!=null&&typeof C!="bigint")throw new TypeError('"invertedZ" expected bigint, got type='+typeof C);let{X:O,Y:R,Z:N}=L,B=L.is0();C==null&&(C=B?o.create(Vf):o.inv(N));let I=o.mul(O,C),K=o.mul(R,C),F=o.mul(N,C);if(B)return{x:o.ZERO,y:o.ONE};if(!o.eql(F,o.ONE))throw new Error("invZ was invalid");return{x:I,y:K}}clearCofactor(){return a===Lo?this:a===Bo?this.double():a===pp?this.double().double():a===Vf?this.double().double().double():this.multiplyUnsafe(a)}toBytes(){let{x:b,y:L}=this.toAffine(),C=o.toBytes(L);return C[C.length-1]|=u(b)?128:0,C}toHex(){return fn(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let m=E=>vo(w,E),g=new Dr(w,c);return g.bits>=6&&w.BASE.precompute(6),Object.freeze(w.prototype),Object.freeze(w),w}function Wf(t,e,r={}){if(Kt(t),typeof e!="function")throw new Error('"hash" function param is required');let n=e,o=r;Be(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function",toMontgomery:"function",toMontgomerySecret:"function"});let{prehash:s}=o,{BASE:i,Fp:a,Fn:c}=t,f=n.outputLen,u=2*a.BYTES;if(f!==void 0&&(gt(f,"hash.outputLen"),f!==u))throw new Error(`hash.outputLen must be ${u}, got ${f}`);let l=o.randomBytes===void 0?yt:o.randomBytes,h=o.toMontgomery,p=o.toMontgomerySecret,x=o.adjustScalarBytes===void 0?_=>_:o.adjustScalarBytes,w=o.domain===void 0?(_,U,T)=>{if(Ke(T,"phflag"),U.length||T)throw new Error("Contexts/pre-hash are not supported");return _}:o.domain;function m(_){return c.create(ut(_))}function g(_){let U=B.secretKey;Q(_,B.secretKey,"secretKey");let T=Q(n(_),2*U,"hashedSecretKey"),v=x(T.slice(0,U)),H=T.slice(U,2*U),D=m(v);return{head:v,prefix:H,scalar:D}}function E(_){let{head:U,prefix:T,scalar:v}=g(_),H=i.multiply(v),D=H.toBytes();return{head:U,prefix:T,scalar:v,point:H,pointBytes:D}}function b(_){return E(_).pointBytes}function L(_=Uint8Array.of(),...U){let T=je(...U);return m(n(w(T,Q(_,void 0,"context"),!!s)))}function C(_,U,T={}){Be(T,{},{},"options"),_=Mt(Q(_,void 0,"message")),s&&(_=s(_));let{prefix:v,scalar:H,pointBytes:D}=E(U),S=L(T.context,v,_),d=i.multiply(S).toBytes(),y=L(T.context,d,D,_),A=c.create(S+y*H);if(!c.isValid(A))throw new Error("sign failed: invalid s");let P=je(d,c.toBytes(A));return Q(P,B.signature,"result")}let O={zip215:o.zip215};function R(_,U,T,v=O){Be(v);let{context:H}=v,D=v.zip215===void 0?!!O.zip215:v.zip215,S=B.signature;_=Q(_,S,"signature"),U=Q(U,void 0,"message"),T=Q(T,B.publicKey,"publicKey"),D!==void 0&&Ke(D,"zip215"),s&&(U=s(U));let d=S/2,y=_.subarray(0,d),A=ut(_.subarray(d,S)),P,k,M;try{P=t.fromBytes(T,D),k=t.fromBytes(y,D),M=i.multiplyUnsafe(A)}catch{return!1}if(!D&&P.isSmallOrder())return!1;let $=L(H,y,T,U);return k.add(P.multiplyUnsafe($)).subtract(M).clearCofactor().is0()}let N=a.BYTES,B={secretKey:N,publicKey:N,signature:2*N,seed:N};function I(_){return _=_===void 0?l(B.seed):_,Q(_,B.seed,"seed")}function K(_){return kt(_)&&_.length===B.secretKey}function F(_,U){try{return!!t.fromBytes(_,U===void 0?O.zip215:U)}catch{return!1}}let q={getExtendedPublicKey:E,randomSecretKey:I,isValidSecretKey:K,isValidPublicKey:F,toMontgomery(_){if(h===void 0)throw new Error("Montgomery conversion is not supported for this curve");return h(t.fromBytes(_))},toMontgomerySecret(_){if(p===void 0)throw new Error("Montgomery conversion is not supported for this curve");return p(_)}};return Object.freeze(B),Object.freeze(q),Object.freeze({keygen:Ir(I,b),getPublicKey:b,sign:C,verify:R,utils:q,Point:t,lengths:B})}var rr=BigInt(0),We=BigInt(1),Do=BigInt(2);function Gf(t,e){return t+e-(e>>We<<We)}function yp(t){let e=BigInt(6)*t;return(r,n,o)=>{let s=n+o,a=((e+o-n)*r+n)%t;return{x_2:a,x_3:s-a}}}function gp(t){return Be(t,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function",scalarMultBase:"function"}),Object.freeze({...t})}function Yf(t){let e=gp(t),{P:r,type:n,adjustScalarBytes:o,powPminus2:s,randomBytes:i}=e,a=e.scalarMultBase,c=n==="x25519";if(!c&&n!=="x448")throw new Error("invalid type");let f=i===void 0?yt:i,u=c?255:448,l=yp(r),h=c?32:56,p=BigInt(c?9:5),x=BigInt(c?121665:39081),w=c?Do**BigInt(254):Do**BigInt(447),m=c?BigInt(8)*(Do**BigInt(251)-We):BigInt(4)*(Do**BigInt(445)-We),g=w+m+We,E=T=>se(T,r),b=L(p);function L(T){return ln(E(T),h)}function C(T){let v=Mt(Q(T,h,"uCoordinate"));return c&&(v[31]&=127),E(ut(v))}function O(T){return ut(o(Mt(Q(T,h,"scalar"))))}let R=new Set(c?[rr,We,r-We,BigInt("325606250916557431795983626356110631294008115727848805560023387167927233504"),BigInt("39382357235489614581723060781553021112529911719440698176882885853963445705823")]:[rr,We,r-We]);function N(T,v){let H=C(v);if(R.has(H))throw new Error("invalid private or public key received");let D=F(H,O(T));if(D===rr)throw new Error("invalid private or public key received");return L(D)}function B(T){if(a===void 0)return N(T,b);let v=O(T);lt("scalar",v,w,g);let H=E(a(v));if(H===rr)throw new Error("invalid private or public key received");return L(H)}let I=B,K=N;function F(T,v){lt("u",T,rr,r),lt("scalar",v,w,g);let H=v,D=T,S=We,d=rr,y=T,A=We,P=H^H>>We;for(let $=BigInt(u-1);$>=rr;$--){let z=Gf(r,P>>$);({x_2:S,x_3:y}=l(z,S,y)),{x_2:d,x_3:A}=l(z,d,A);let j=S+d,G=E(j*j),ue=S-d,ie=E(ue*ue),ge=G-ie,Me=y+A,fe=y-A,he=E(fe*j),mr=E(Me*ue),Zr=he+mr,_t=he-mr;y=E(Zr*Zr),A=E(D*E(_t*_t)),S=E(G*ie),d=E(ge*(G+E(x*ge)))}let k=Gf(r,H);({x_2:S,x_3:y}=l(k,S,y)),{x_2:d,x_3:A}=l(k,d,A);let M=s(d);return E(S*M)}let q={secretKey:h,publicKey:h,seed:h},_=T=>(T=T===void 0?f(h):T,Q(T,q.seed,"seed"),T),U={randomSecretKey:_};return Object.freeze(q),Object.freeze(U),Object.freeze({keygen:Ir(_,I),getSharedSecret:K,getPublicKey:I,scalarMult:N,scalarMultBase:B,utils:U,GuBytes:b.slice(),lengths:q})}var Xf=BigInt(0),Pi=BigInt(1),Zf=BigInt(2),bp=BigInt(3),wp=BigInt(5),xp=BigInt(8),Io=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Ep={p:Io,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:xp,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function eu(t){let e=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),s=Io,a=t*t%s*t%s,c=le(a,Zf,s)*a%s,f=le(c,Pi,s)*t%s,u=le(f,wp,s)*f%s,l=le(u,e,s)*u%s,h=le(l,r,s)*l%s,p=le(h,n,s)*h%s,x=le(p,o,s)*p%s,w=le(x,o,s)*p%s,m=le(w,e,s)*u%s;return{pow_p_5_8:le(m,Zf,s)*t%s,b2:a}}function Ni(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}var Qf=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Sp(t,e){let r=Io,n=se(e*e*e,r),o=se(n*n*e,r),s=eu(t*o).pow_p_5_8,i=se(t*n*s,r),a=se(e*i*i,r),c=i,f=se(i*Qf,r),u=a===t,l=a===se(-t,r),h=a===se(-t*Qf,r);return u&&(i=c),(l||h)&&(i=f),Mf(i,r)&&(i=se(-i,r)),{isValid:u||l,value:i}}var mn=jf(Ep,{uvRatio:Sp}),Jf=mn.Fp;function Ap(t){let{y:e}=t;return Jf.toBytes(Jf.div(Pi+e,Pi-e))}function vp(t){let e=mn.Fp.BYTES;return ke(t,e),Ni(vi(t.subarray(0,e))).subarray(0,e)}function Cp(t){return Wf(mn,vi,Object.assign({adjustScalarBytes:Ni,toMontgomery:Ap,toMontgomerySecret:vp,zip215:!0},t))}var tu=Cp({});var yn=(()=>{let t=Io,e=r=>{let{pow_p_5_8:n,b2:o}=eu(r);return se(le(n,bp,t)*o,t)};return Yf({P:t,type:"x25519",powPminus2:e,adjustScalarBytes:Ni,scalarMultBase:r=>{let n=se(r,mn.Fn.ORDER);if(n===Xf)return Xf;let o=mn.BASE.multiply(n);return se((o.Z+o.Y)*e(se(o.Z-o.Y,t)),t)}})})();var gn=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},Ro=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var Ge={get(t=globalThis){let e=t.crypto;if(e?.subtle==null)throw new Ro("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return e}};var Oo=32;var Ui,_p=(async()=>{try{return await Ge.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function Tp(t,e,r){if(t.buffer instanceof ArrayBuffer){let n=await Ge.get().subtle.importKey("raw",t.buffer,{name:"Ed25519"},!1,["verify"]);return await Ge.get().subtle.verify({name:"Ed25519"},n,Ce(e),Ce(r instanceof Uint8Array?r:r.subarray()))}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function Lp(t,e,r){return tu.verify(e,r instanceof Uint8Array?r:r.subarray(),t)}async function ru(t,e,r){return Ui==null&&(Ui=await _p),Ui?Tp(t,e,r):Lp(t,e,r)}function Po(t){return t==null?!1:typeof t.then=="function"&&typeof t.catch=="function"&&typeof t.finally=="function"}var No=class{type="Ed25519";raw;constructor(e){this.raw=ki(e,Oo)}toMultihash(){return Ze.digest(It(this))}toCID(){return Ee.createV1(114,this.toMultihash())}toString(){return ye.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ve(this.raw,e.raw)}verify(e,r,n){n?.signal?.throwIfAborted();let o=ru(this.raw,r,e);return Po(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function Mi(t){return t=ki(t,Oo),new No(t)}function ki(t,e){if(t=Uint8Array.from(t??[]),t.length!==e)throw new J(`Key must be a Uint8Array of length ${e}, got ${t.length}`);return t}var Dp=Math.pow(2,7),Ip=Math.pow(2,14),Rp=Math.pow(2,21),Fi=Math.pow(2,28),Ki=Math.pow(2,35),Hi=Math.pow(2,42),$i=Math.pow(2,49),ne=128,De=127;function de(t){if(t<Dp)return 1;if(t<Ip)return 2;if(t<Rp)return 3;if(t<Fi)return 4;if(t<Ki)return 5;if(t<Hi)return 6;if(t<$i)return 7;if(Number.MAX_SAFE_INTEGER!=null&&t>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Rr(t,e,r=0){switch(de(t)){case 8:e[r++]=t&255|ne,t/=128;case 7:e[r++]=t&255|ne,t/=128;case 6:e[r++]=t&255|ne,t/=128;case 5:e[r++]=t&255|ne,t/=128;case 4:e[r++]=t&255|ne,t>>>=7;case 3:e[r++]=t&255|ne,t>>>=7;case 2:e[r++]=t&255|ne,t>>>=7;case 1:{e[r++]=t&255,t>>>=7;break}default:throw new Error("unreachable")}return e}function Op(t,e,r=0){switch(de(t)){case 8:e.set(r++,t&255|ne),t/=128;case 7:e.set(r++,t&255|ne),t/=128;case 6:e.set(r++,t&255|ne),t/=128;case 5:e.set(r++,t&255|ne),t/=128;case 4:e.set(r++,t&255|ne),t>>>=7;case 3:e.set(r++,t&255|ne),t>>>=7;case 2:e.set(r++,t&255|ne),t>>>=7;case 1:{e.set(r++,t&255),t>>>=7;break}default:throw new Error("unreachable")}return e}function zi(t,e){let r=t[e],n=0;if(n+=r&De,r<ne||(r=t[e+1],n+=(r&De)<<7,r<ne)||(r=t[e+2],n+=(r&De)<<14,r<ne)||(r=t[e+3],n+=(r&De)<<21,r<ne)||(r=t[e+4],n+=(r&De)*Fi,r<ne)||(r=t[e+5],n+=(r&De)*Ki,r<ne)||(r=t[e+6],n+=(r&De)*Hi,r<ne)||(r=t[e+7],n+=(r&De)*$i,r<ne))return n;throw new RangeError("Could not decode varint")}function Pp(t,e){let r=t.get(e),n=0;if(n+=r&De,r<ne||(r=t.get(e+1),n+=(r&De)<<7,r<ne)||(r=t.get(e+2),n+=(r&De)<<14,r<ne)||(r=t.get(e+3),n+=(r&De)<<21,r<ne)||(r=t.get(e+4),n+=(r&De)*Fi,r<ne)||(r=t.get(e+5),n+=(r&De)*Ki,r<ne)||(r=t.get(e+6),n+=(r&De)*Hi,r<ne)||(r=t.get(e+7),n+=(r&De)*$i,r<ne))return n;throw new RangeError("Could not decode varint")}function Uo(t,e,r=0){return e==null&&(e=xe(de(t))),e instanceof Uint8Array?Rr(t,e,r):Op(t,e,r)}function bt(t,e=0){return t instanceof Uint8Array?zi(t,e):Pp(t,e)}var qi=new Float32Array([-0]),Ht=new Uint8Array(qi.buffer);function ou(t,e,r){qi[0]=t,e[r]=Ht[0],e[r+1]=Ht[1],e[r+2]=Ht[2],e[r+3]=Ht[3]}function su(t,e){return Ht[0]=t[e],Ht[1]=t[e+1],Ht[2]=t[e+2],Ht[3]=t[e+3],qi[0]}var Vi=new Float64Array([-0]),Ie=new Uint8Array(Vi.buffer);function iu(t,e,r){Vi[0]=t,e[r]=Ie[0],e[r+1]=Ie[1],e[r+2]=Ie[2],e[r+3]=Ie[3],e[r+4]=Ie[4],e[r+5]=Ie[5],e[r+6]=Ie[6],e[r+7]=Ie[7]}function au(t,e){return Ie[0]=t[e],Ie[1]=t[e+1],Ie[2]=t[e+2],Ie[3]=t[e+3],Ie[4]=t[e+4],Ie[5]=t[e+5],Ie[6]=t[e+6],Ie[7]=t[e+7],Vi[0]}var Np=BigInt(Number.MAX_SAFE_INTEGER),Up=BigInt(Number.MIN_SAFE_INTEGER),$e=class t{lo;hi;constructor(e,r){this.lo=e|0,this.hi=r|0}toNumber(e=!1){if(!e&&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(e=!1){if(e)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(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,r=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?r===0?e<16384?e<128?1:2:e<2097152?3:4:r<16384?r<128?5:6:r<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return nr;if(e<Np&&e>Up)return this.fromNumber(Number(e));let r=e<0n;r&&(e=-e);let n=e>>32n,o=e-(n<<32n);return r&&(n=~n|0n,o=~o|0n,++o>cu&&(o=0n,++n>cu&&(n=0n))),new t(Number(o),Number(n))}static fromNumber(e){if(e===0)return nr;let r=e<0;r&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return r&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new t(n,o)}static from(e){return typeof e=="number"?t.fromNumber(e):typeof e=="bigint"?t.fromBigInt(e):typeof e=="string"?t.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new t(e.low>>>0,e.high>>>0):nr}},nr=new $e(0,0);nr.toBigInt=function(){return 0n};nr.zzEncode=nr.zzDecode=function(){return this};nr.length=function(){return 1};var cu=4294967296n;function fu(t){let e=0,r=0;for(let n=0;n<t.length;++n)r=t.charCodeAt(n),r<128?e+=1:r<2048?e+=2:(r&64512)===55296&&(t.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function uu(t,e,r){if(r-e<1)return"";let o,s=[],i=0,a;for(;e<r;)a=t[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|t[e++]&63:a>239&&a<365?(a=((a&7)<<18|(t[e++]&63)<<12|(t[e++]&63)<<6|t[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(t[e++]&63)<<6|t[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function ji(t,e,r){let n=r,o,s;for(let i=0;i<t.length;++i)o=t.charCodeAt(i),o<128?e[r++]=o:o<2048?(e[r++]=o>>6|192,e[r++]=o&63|128):(o&64512)===55296&&((s=t.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[r++]=o>>18|240,e[r++]=o>>12&63|128,e[r++]=o>>6&63|128,e[r++]=o&63|128):(e[r++]=o>>12|224,e[r++]=o>>6&63|128,e[r++]=o&63|128);return r-n}function et(t,e){return RangeError(`index out of range: ${t.pos} + ${e??1} > ${t.len}`)}function ko(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}var Wi=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=Ce(e),this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,et(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw et(this,4);return ko(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw et(this,4);return ko(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw et(this,4);let e=su(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw et(this,4);let e=au(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),r=this.pos,n=this.pos+e;if(n>this.len)throw et(this,e);return this.pos+=e,r===n?new Uint8Array(0):this.buf.subarray(r,n)}string(){let e=this.bytes();return uu(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw et(this,e);this.pos+=e}else do if(this.pos>=this.len)throw et(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new $e(0,0),r=0;if(this.len-this.pos>4){for(;r<4;++r)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;r=0}else{for(;r<3;++r){if(this.pos>=this.len)throw et(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<r*7)>>>0,e}if(this.len-this.pos>4){for(;r<5;++r)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;r<5;++r){if(this.pos>=this.len)throw et(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw et(this,8);let e=ko(this.buf,this.pos+=4),r=ko(this.buf,this.pos+=4);return new $e(e,r)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=zi(this.buf,this.pos);return this.pos+=de(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function wn(t){return new Wi(t instanceof Uint8Array?t:t.subarray())}function tt(t,e,r){let n=wn(t);return e.decode(n,void 0,r)}function Gi(t){let e=t??8192,r=e>>>1,n,o=e;return function(i){if(i<1||i>r)return xe(i);o+i>e&&(n=xe(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var or=class{fn;len;next;val;constructor(e,r,n){this.fn=e,this.len=r,this.next=void 0,this.val=n}};function Yi(){}var Zi=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},kp=Gi();function Mp(t){return globalThis.Buffer!=null?xe(t):kp(t)}var En=class{len;head;tail;states;constructor(){this.len=0,this.head=new or(Yi,0,0),this.tail=this.head,this.states=null}_push(e,r,n){return this.tail=this.tail.next=new or(e,r,n),this.len+=r,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Qi((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(Mo,10,$e.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let r=$e.fromBigInt(e);return this._push(Mo,r.length(),r)}uint64Number(e){return this._push(Rr,de(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let r=$e.fromBigInt(e).zzEncode();return this._push(Mo,r.length(),r)}sint64Number(e){let r=$e.fromNumber(e).zzEncode();return this._push(Mo,r.length(),r)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Xi,1,e?1:0)}fixed32(e){return this._push(xn,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let r=$e.fromBigInt(e);return this._push(xn,4,r.lo)._push(xn,4,r.hi)}fixed64Number(e){let r=$e.fromNumber(e);return this._push(xn,4,r.lo)._push(xn,4,r.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(ou,4,e)}double(e){return this._push(iu,8,e)}bytes(e){let r=e.length>>>0;return r===0?this._push(Xi,1,0):this.uint32(r)._push(Kp,r,e)}string(e){let r=fu(e);return r!==0?this.uint32(r)._push(ji,r,e):this._push(Xi,1,0)}fork(){return this.states=new Zi(this),this.head=this.tail=new or(Yi,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 or(Yi,0,0),this.len=0),this}ldelim(){let e=this.head,r=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=r,this.len+=n),this}finish(){let e=this.head.next,r=Mp(this.len),n=0;for(;e!=null;)e.fn(e.val,r,n),n+=e.len,e=e.next;return r}};function Xi(t,e,r){e[r]=t&255}function Fp(t,e,r){for(;t>127;)e[r++]=t&127|128,t>>>=7;e[r]=t}var Qi=class extends or{next;constructor(e,r){super(Fp,e,r),this.next=void 0}};function Mo(t,e,r){for(;t.hi!==0;)e[r++]=t.lo&127|128,t.lo=(t.lo>>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;t.lo>127;)e[r++]=t.lo&127|128,t.lo=t.lo>>>7;e[r++]=t.lo}function xn(t,e,r){e[r]=t&255,e[r+1]=t>>>8&255,e[r+2]=t>>>16&255,e[r+3]=t>>>24}function Kp(t,e,r){e.set(t,r)}globalThis.Buffer!=null&&(En.prototype.bytes=function(t){let e=t.length>>>0;return this.uint32(e),e>0&&this._push(Hp,e,t),this},En.prototype.string=function(t){let e=globalThis.Buffer.byteLength(t);return this.uint32(e),e>0&&this._push($p,e,t),this});function Hp(t,e,r){e.set(t,r)}function $p(t,e,r){t.length<40?ji(t,e,r):e.utf8Write!=null?e.utf8Write(t,r):e.set(Z(t),r)}function Ji(){return new En}function rt(t,e){let r=Ji();return e.encode(t,r,{lengthDelimited:!1}),r.finish()}function*nt(t,e,r){let n=wn(t);yield*e.stream(n,void 0,"$",r)}var Fo={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function Ko(t,e,r,n,o){return{name:t,type:e,encode:r,decode:n,stream:o}}function sr(t){function e(s){if(t[s.toString()]==null)throw new Error("Invalid enum value");return t[s]}let r=function(i,a){let c=e(i);a.int32(c)},n=function(i){let a=i.int32();return e(a)},o=function*(i){let a=i.int32();yield e(a)};return Ko("enum",Fo.VARINT,r,n,o)}function ot(t,e,r){return Ko("message",Fo.LENGTH_DELIMITED,t,e,r)}var ir=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var pe;(function(t){t.RSA="RSA",t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.ECDSA="ECDSA"})(pe||(pe={}));var ea;(function(t){t[t.RSA=0]="RSA",t[t.Ed25519=1]="Ed25519",t[t.secp256k1=2]="secp256k1",t[t.ECDSA=3]="ECDSA"})(ea||(ea={}));(function(t){t.codec=()=>sr(ea)})(pe||(pe={}));var dt;(function(t){let e;t.codec=()=>(e==null&&(e=ot((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),pe.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{c.Type=pe.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:pe.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function r(s){return rt(s,t.codec())}t.encode=r;function n(s,i){return tt(s,t.codec(),i)}t.decode=n;function o(s,i){return nt(s,t.codec(),i)}t.stream=o})(dt||(dt={}));var ta;(function(t){let e;t.codec=()=>(e==null&&(e=ot((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),pe.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{c.Type=pe.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:pe.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function r(s){return rt(s,t.codec())}t.encode=r;function n(s,i){return tt(s,t.codec(),i)}t.decode=n;function o(s,i){return nt(s,t.codec(),i)}t.stream=o})(ta||(ta={}));var An={};Pe(An,{MAX_RSA_KEY_SIZE:()=>ra,generateRSAKeyPair:()=>yu,jwkToJWKKeyPair:()=>gu,jwkToPkcs1:()=>jp,jwkToPkix:()=>ia,jwkToRSAPrivateKey:()=>ua,pkcs1MessageToJwk:()=>oa,pkcs1MessageToRSAPrivateKey:()=>aa,pkcs1ToJwk:()=>Vp,pkcs1ToRSAPrivateKey:()=>mu,pkixMessageToJwk:()=>sa,pkixMessageToRSAPublicKey:()=>fa,pkixToJwk:()=>Wp,pkixToRSAPublicKey:()=>ca});var Or=class{type="RSA";jwk;_raw;_multihash;constructor(e,r){this.jwk=e,this._multihash=r}get raw(){return this._raw==null&&(this._raw=An.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return Ee.createV1(114,this._multihash)}toString(){return ye.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ve(this.raw,e.raw)}verify(e,r,n){return pu(this.jwk,r,e,n)}},Sn=class{type="RSA";jwk;_raw;publicKey;constructor(e,r){this.jwk=e,this.publicKey=r}get raw(){return this._raw==null&&(this._raw=An.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ve(this.raw,e.raw)}sign(e,r){return hu(this.jwk,e,r)}};var ra=8192,na=18,zp=1062,qp=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function Vp(t){let e=mt(t);return oa(e)}function oa(t){return{n:W(t[1],"base64url"),e:W(t[2],"base64url"),d:W(t[3],"base64url"),p:W(t[4],"base64url"),q:W(t[5],"base64url"),dp:W(t[6],"base64url"),dq:W(t[7],"base64url"),qi:W(t[8],"base64url"),kty:"RSA"}}function jp(t){if(t.n==null||t.e==null||t.d==null||t.p==null||t.q==null||t.dp==null||t.dq==null||t.qi==null)throw new J("JWK was missing components");return Dt([Fe(Uint8Array.from([0])),Fe(Z(t.n,"base64url")),Fe(Z(t.e,"base64url")),Fe(Z(t.d,"base64url")),Fe(Z(t.p,"base64url")),Fe(Z(t.q,"base64url")),Fe(Z(t.dp,"base64url")),Fe(Z(t.dq,"base64url")),Fe(Z(t.qi,"base64url"))]).subarray()}function Wp(t){let e=mt(t,{offset:0});return sa(e)}function sa(t){let e=mt(t[1],{offset:0});return{kty:"RSA",n:W(e[0],"base64url"),e:W(e[1],"base64url")}}function ia(t){if(t.n==null||t.e==null)throw new J("JWK was missing components");return Dt([qp,co(Dt([Fe(Z(t.n,"base64url")),Fe(Z(t.e,"base64url"))]))]).subarray()}function mu(t){let e=mt(t);return aa(e)}function aa(t){let e=oa(t);return ua(e)}function ca(t,e){if(t.byteLength>=zp)throw new yr("Key size is too large");let r=mt(t,{offset:0});return fa(r,t,e)}function fa(t,e,r){let n=sa(t);if(r==null){let o=ct(dt.encode({Type:pe.RSA,Data:e}));r=Ne(na,o)}return new Or(n,r)}function ua(t){if(wu(t)>ra)throw new J("Key size is too large");let e=gu(t),r=ct(dt.encode({Type:pe.RSA,Data:ia(e.publicKey)})),n=Ne(na,r);return new Sn(e.privateKey,new Or(e.publicKey,n))}async function yu(t){if(t>ra)throw new J("Key size is too large");let e=await bu(t),r=ct(dt.encode({Type:pe.RSA,Data:ia(e.publicKey)})),n=Ne(na,r);return new Sn(e.privateKey,new Or(e.publicKey,n))}function gu(t){if(t==null)throw new J("Missing key parameter");return{privateKey:t,publicKey:{kty:t.kty,n:t.n,e:t.e}}}async function bu(t,e){let r=await Ge.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:t,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);e?.signal?.throwIfAborted();let n=await Gp(r,e);return{privateKey:n[0],publicKey:n[1]}}async function hu(t,e,r){let n=await Ge.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);r?.signal?.throwIfAborted();let o=await Ge.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,Ce(e instanceof Uint8Array?e:e.subarray()));return r?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function pu(t,e,r,n){let o=await Ge.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let s=await Ge.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,Ce(e),Ce(r instanceof Uint8Array?r:r.subarray()));return n?.signal?.throwIfAborted(),s}async function Gp(t,e){if(t.privateKey==null||t.publicKey==null)throw new J("Private and public key are required");let r=await Promise.all([Ge.get().subtle.exportKey("jwk",t.privateKey),Ge.get().subtle.exportKey("jwk",t.publicKey)]);return e?.signal?.throwIfAborted(),r}function wu(t){if(t.kty!=="RSA")throw new J("invalid key type");if(t.n==null)throw new J("invalid key modulus");return Z(t.n,"base64url").length*8}var Ho=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,r){if(er(e),ke(r,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("expected Hash instance");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(r.length>n?e.create().update(r).digest():r);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),Ve(o)}update(e){return Cr(this),this.iHash.update(e),this}digestInto(e){Cr(this),lo(e,this),this.finished=!0;let r=e.subarray(0,this.outputLen);this.iHash.digestInto(r),this.oHash.update(r),this.oHash.digestInto(r),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:r,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a,canXOF:c}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.canXOF=c,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},vn=(()=>{let t=((e,r,n)=>new Ho(e,r).update(n).digest());return t.create=(e,r)=>new Ho(e,r),t})();var Yp=BigInt(0),la=class extends Error{constructor(e=""){super(e)}},wt={Err:la,_tlv:{encode:(t,e)=>{let{Err:r}=wt;if(gt(t,"tag"),t<0||t>255)throw new r("tlv.encode: wrong tag");if(Cf(e,"data"),e.length&1)throw new r("tlv.encode: unpadded data");let n=e.length/2,o=un(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");let s=n>127?un(o.length/2|128):"";return un(t)+s+o+e},decode(t,e){let{Err:r}=wt;e=Q(e,void 0,"DER data");let n=0;if(t<0||t>255)throw new r("tlv.decode: wrong tag");if(e.length<2||e[n++]!==t)throw new r("tlv.decode: wrong tlv");let o=e[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let f=e.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=e.subarray(n,n+i);if(a.length!==i)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(t){let{Err:e}=wt;if(bo(t),t<Yp)throw new e("integer: negative integers are not allowed");let r=un(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){let{Err:e}=wt;if(t.length<1)throw new e("invalid signature integer: empty");if(t[0]&128)throw new e("invalid signature integer: negative");if(t.length>1&&t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return ft(t)}},toSig(t,e){let{Err:r,_int:n,_tlv:o}=wt;if(e!==void 0&&(gt(e,"maxScalarBytes"),e<1))throw new r("invalid signature: maxScalarBytes must be positive");let s=Q(t,void 0,"signature"),{v:i,l:a}=o.decode(48,s);if(a.length)throw new r("invalid signature: left bytes after parsing");let{v:c,l:f}=o.decode(2,i),{v:u,l}=o.decode(2,f);if(l.length)throw new r("invalid signature: left bytes after parsing");if(e!==void 0&&(c.length>e||u.length>e))throw new r("invalid signature: integer too large");return{r:n.decode(c),s:n.decode(u)}},hexFromSig(t){let{_tlv:e,_int:r}=wt;Be(t,{r:"bigint",s:"bigint"},{},"sig");let n=e.encode(2,r.encode(t.r)),o=e.encode(2,r.encode(t.s)),s=n+o;return e.encode(48,s)}},$o=(Object.freeze(wt._tlv),Object.freeze(wt._int),Object.freeze(wt));var xu=(t,e)=>(t+(t>=0?e:-e)/Eu)/e;function Xp(t,e,r){lt("scalar",t,xt,r);let[[n,o],[s,i]]=e,a=xu(i*t,r),c=xu(-o*t,r),f=t-a*n-c*s,u=-a*o-c*i,l=f<xt,h=u<xt;l&&(f=-f),h&&(u=-u);let p=dn(Math.ceil(Tr(r)/2))+ar;if(f<xt||f>=p||u<xt||u>=p)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:l,k1:f,k2neg:h,k2:u}}function pa(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function da(t,e){Be(t);let r={};for(let n of Object.keys(e))r[n]=t[n]===void 0?e[n]:t[n];return Ke(r.lowS,"lowS"),Ke(r.prehash,"prehash"),r.format!==void 0&&pa(r.format),r}var xt=BigInt(0),ar=BigInt(1),Eu=BigInt(2),ha=BigInt(3),Zp=BigInt(4);function Su(t,e={}){let r=_o("weierstrass",t,e),n=r.Fp,o=r.Fn,s=r.CURVE,{h:i,n:a}=s;Be(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",randomBytes:"function"});let{endo:c,allowInfinityPoint:f,clearCofactor:u,isTorsionFree:l,fromBytes:h,toBytes:p}=e,x=e.randomBytes===void 0?yt:e.randomBytes;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let w=c?{beta:c.beta,basises:c.basises.map(S=>[...S])}:void 0,m=vu(n,o);function g(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function E(S,d,y){if(d.is0()){if(!f)throw new Error("bad point: ZERO");return Uint8Array.of(0)}let{x:A,y:P}=d.toAffine(),k=n.toBytes(A);if(Ke(y,"isCompressed"),y){g();let M=!n.isOdd(P);return je(Au(M),k)}else return je(Uint8Array.of(4),k,n.toBytes(P))}function b(S){Q(S,void 0,"Point");let{publicKey:d,publicKeyUncompressed:y}=m,A=S.length,P=S[0],k=S.subarray(1);if(f&&A===1&&P===0)return{x:n.ZERO,y:n.ZERO};if(A===d&&(P===2||P===3)){let M=n.fromBytes(k);if(!n.isValid(M))throw new Error("bad point: is not on curve, wrong x");let $=N(M),z;try{z=n.sqrt($)}catch(ue){let ie=ue instanceof Error?": "+ue.message:"";throw new Error("bad point: is not on curve, sqrt error"+ie)}g();let j=n.isOdd(z);return(P&1)===1!==j&&(z=n.neg(z)),{x:M,y:z}}else if(A===y&&P===4){let M=n.BYTES,$=n.fromBytes(k.subarray(0,M)),z=n.fromBytes(k.subarray(M,M*2));if(!B($,z))throw new Error("bad point: is not on curve");return{x:$,y:z}}else throw new Error(`bad point: got length ${A}, expected compressed=${d} or uncompressed=${y}`)}let L=p===void 0?E:p,C=h===void 0?b:h,O=n.mul(s.b,ha),R=n.is0(s.a)?S=>n.ZERO:S=>n.mul(s.a,S);function N(S){let d=n.sqr(S),y=n.mul(d,S);return n.add(n.add(y,n.mul(S,s.a)),s.b)}function B(S,d){let y=n.sqr(d),A=N(S);return n.eql(y,A)}if(!B(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let I=n.mul(n.pow(s.a,ha),Zp),K=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(I,K)))throw new Error("bad curve params: a or b");function F(S,d,y=!1){if(!n.isValid(d)||y&&n.is0(d))throw new Error(`bad point coordinate ${S}`);return typeof d=="object"&&d!==null?n.create(d):d}function q(S){if(!(S instanceof v))throw new Error("Weierstrass Point expected")}function _(S){if(!w||!w.basises)throw new Error("no endo");return Xp(S,w.basises,o.ORDER)}function U(S,d,y,A){if(!o.isValid(A))throw new RangeError("invalid scalar: out of range");if(w){let{k1neg:P,k1:k,k2neg:M,k2:$}=_(A),z=new v(n.mul(y.X,w.beta),y.Y,y.Z);S.push(P?y.negate():y,M?z.negate():z),d.push(k,$)}else S.push(y),d.push(A)}let T=new WeakSet;class v{static BASE=new v(s.Gx,s.Gy,n.ONE);static ZERO=new v(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(d,y,A){this.X=F("x",d),this.Y=F("y",y,!0),this.Z=F("z",A),Object.freeze(this)}static CURVE(){return s}static fromAffine(d){let{x:y,y:A}=d||{};if(!d||!n.isValid(y)||!n.isValid(A))throw new Error("invalid affine point");if(d instanceof v)throw new Error("projective point not allowed");return n.is0(y)&&n.is0(A)?v.ZERO:new v(y,A,n.ONE)}static fromBytes(d){let y=v.fromAffine(C(Q(d,void 0,"point")));return y.assertValidity(),y}static fromHex(d){return v.fromBytes(_r(d))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(d=6,y=!0){return D.setWindowSize(this,d),y||this.multiply(ha),this}assertValidity(){let d=this;if(d.is0()){if(f&&n.is0(d.X)&&n.eql(d.Y,n.ONE)&&n.is0(d.Z))return;throw new Error("bad point: ZERO")}if(T.has(d))return;let{x:y,y:A}=d.toAffine();if(!n.isValid(y)||!n.isValid(A))throw new Error("bad point: x or y not field elements");if(!B(y,A))throw new Error("bad point: equation left != right");if(!d.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");T.add(d)}hasEvenY(){let{y:d}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(d)}equals(d){q(d);let{X:y,Y:A,Z:P}=this,{X:k,Y:M,Z:$}=d,z=n.eql(n.mul(y,$),n.mul(k,P)),j=n.eql(n.mul(A,$),n.mul(M,P));return z&&j}negate(){return new v(this.X,n.neg(this.Y),this.Z)}double(){let{X:d,Y:y,Z:A}=this,P=n.ZERO,k=n.ZERO,M=n.ZERO,$=n.mul(d,d),z=n.mul(y,y),j=n.mul(A,A),G=n.mul(d,y);return G=n.add(G,G),M=n.mul(d,A),M=n.add(M,M),P=R(M),k=n.mul(O,j),k=n.add(P,k),P=n.sub(z,k),k=n.add(z,k),k=n.mul(P,k),P=n.mul(G,P),M=n.mul(O,M),j=R(j),G=n.sub($,j),G=R(G),G=n.add(G,M),M=n.add($,$),$=n.add(M,$),$=n.add($,j),$=n.mul($,G),k=n.add(k,$),j=n.mul(y,A),j=n.add(j,j),$=n.mul(j,G),P=n.sub(P,$),M=n.mul(j,z),M=n.add(M,M),M=n.add(M,M),new v(P,k,M)}add(d){q(d);let{X:y,Y:A,Z:P}=this,{X:k,Y:M,Z:$}=d,z=n.ZERO,j=n.ZERO,G=n.ZERO,ue=n.mul(y,k),ie=n.mul(A,M),ge=n.mul(P,$),Me=n.add(y,A),fe=n.add(k,M);Me=n.mul(Me,fe),fe=n.add(ue,ie),Me=n.sub(Me,fe),fe=n.add(y,P);let he=n.add(k,$);return fe=n.mul(fe,he),he=n.add(ue,ge),fe=n.sub(fe,he),he=n.add(A,P),z=n.add(M,$),he=n.mul(he,z),z=n.add(ie,ge),he=n.sub(he,z),G=R(fe),z=n.mul(O,ge),G=n.add(z,G),z=n.sub(ie,G),G=n.add(ie,G),j=n.mul(z,G),ie=n.add(ue,ue),ie=n.add(ie,ue),ge=R(ge),fe=n.mul(O,fe),ie=n.add(ie,ge),ge=n.sub(ue,ge),ge=R(ge),fe=n.add(fe,ge),ue=n.mul(ie,fe),j=n.add(j,ue),ue=n.mul(he,fe),z=n.mul(Me,z),z=n.sub(z,ue),ue=n.mul(Me,ie),G=n.mul(he,G),G=n.add(G,ue),new v(z,j,G)}subtract(d){return q(d),this.add(d.negate())}is0(){return this.equals(v.ZERO)}multiply(d){if(!o.isValidNot0(d))throw new RangeError("invalid scalar: out of range");let{p:y,f:A}=D.mulSecret(this,d,i,H);return H([y,A])[0]}multiplyUnsafe(d){let y=this,A=d;if(!o.isValid(A))throw new RangeError("invalid scalar: out of range");if(A===xt||y.is0())return v.ZERO;if(A===ar)return y;if(D.hasWindowSize(this))return D.mulUnsafe(y,A,H);let P=[],k=[];return U(P,k,y,A),Co(v,P,k)}mulAddUnsafe(d,y,A){q(y);let P=[],k=[];return U(P,k,this,d),U(P,k,y,A),Co(v,P,k)}toAffine(d){let y=this,A=d;if(A!=null&&!n.isValid(A))throw new RangeError('"invertedZ" expected valid field element');let{X:P,Y:k,Z:M}=y;if(n.eql(M,n.ONE))return{x:P,y:k};let $=y.is0();A==null&&(A=$?n.ONE:n.inv(M));let z=n.mul(P,A),j=n.mul(k,A),G=n.mul(M,A);if($)return{x:n.ZERO,y:n.ZERO};if(!n.eql(G,n.ONE))throw new Error("invZ was invalid");return{x:z,y:j}}isTorsionFree(){return i===ar?!0:l?l(v,this):D.mulUnsafe(this,a).is0()}clearCofactor(){return i===ar?this:u?u(v,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===ar?this.is0():this.clearCofactor().is0()}toBytes(d=!0){return Ke(d,"isCompressed"),this.assertValidity(),L(v,this,d)}toHex(d=!0){return fn(this.toBytes(d))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let H=S=>vo(v,S),D=new Dr(v,x);return D.bits>=6&&v.BASE.precompute(6),Object.freeze(v.prototype),Object.freeze(v),v}function Au(t){return Uint8Array.of(t?2:3)}function vu(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Qp(t,e={}){Kt(t);let{Fn:r}=t,n=e.randomBytes===void 0?yt:e.randomBytes,o=Object.assign(vu(t.Fp,r),{seed:Math.max(So(r.ORDER),16)});function s(p){try{let x=r.fromBytes(p);return r.isValidNot0(x)}catch{return!1}}function i(p,x){let{publicKey:w,publicKeyUncompressed:m}=o;try{let g=p.length;return x===!0&&g!==w||x===!1&&g!==m?!1:!t.fromBytes(p).is0()}catch{return!1}}function a(p){return p=p===void 0?n(o.seed):p,Ao(Q(p,o.seed,"seed"),r.ORDER)}function c(p,x=!0){return t.BASE.multiply(r.fromBytes(p)).toBytes(x)}function f(p){let{secretKey:x,publicKey:w,publicKeyUncompressed:m}=o,g=r._lengths;if(!kt(p))return;let E=Q(p,void 0,"key").length,b=E===w||E===m,L=E===x||!!g?.includes(E);if(!(b&&L))return b}function u(p,x,w=!0){if(f(p)===!0)throw new Error("first arg must be private key");if(f(x)===!1)throw new Error("second arg must be public key");let m=r.fromBytes(p),g=t.fromBytes(x);if(g.is0())throw new Error("invalid public key: point at infinity");return g.multiply(m).toBytes(w)}let l={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},h=Ir(a,c);return Object.freeze(l),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:h,Point:t,utils:l,lengths:o})}function Cu(t,e,r={}){Kt(t);let n=e;er(n),Be(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let o=Object.assign({},r),s=o.randomBytes===void 0?yt:o.randomBytes,i=o.hmac===void 0?(S,d)=>vn(n,S,d):o.hmac,{Fp:a,Fn:c}=t,{ORDER:f,BITS:u}=c,l=So(f),h=Oi(s,l),{keygen:p,getPublicKey:x,getSharedSecret:w,utils:m,lengths:g}=Qp(t,o),E={prehash:!0,lowS:typeof o.lowS=="boolean"?o.lowS:!0,format:"compact",extraEntropy:!1},b=f*Eu+ar<a.ORDER;function L(S){let d=f>>ar;return S>d}function C(S,d){if(!c.isValidNot0(d))throw new Error(`invalid signature ${S}: out of range 1..Point.Fn.ORDER`);return d}function O(){if(!a.isOdd)throw new Error("Field doesn't support isOdd")}function R(S,d,y){return O(),(S===y?0:2)|Number(a.isOdd(d))}function N(){if(b)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function B(S,d){pa(d);let y=g.signature,A=d==="compact"?y:d==="recovered"?y+1:void 0;return Q(S,A)}class I{r;s;recovery;constructor(d,y,A){if(this.r=C("r",d),this.s=C("s",y),A!=null){if(N(),![0,1,2,3].includes(A))throw new Error("invalid recovery id");this.recovery=A}Object.freeze(this)}static fromBytes(d,y=E.format){B(d,y);let A;if(y==="der"){if(d.length>2*c.BYTES+16)throw new $o.Err("invalid signature: DER signature too long");let{r:$,s:z}=$o.toSig(Q(d),c.BYTES+1);return new I($,z)}y==="recovered"&&(A=d[0],y="compact",d=d.subarray(1));let P=g.signature/2,k=d.subarray(0,P),M=d.subarray(P,P*2);return new I(c.fromBytes(k),c.fromBytes(M),A)}static fromHex(d,y){return this.fromBytes(_r(d),y)}assertRecovery(){let{recovery:d}=this;if(d==null)throw new Error("invalid recovery id: must be present");return d}addRecoveryBit(d){return new I(this.r,this.s,d)}recoverPublicKey(d){let{r:y,s:A}=this,P=this.assertRecovery(),k=P===2||P===3?y+f:y;if(!a.isValid(k))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let M=a.toBytes(k),$=t.fromBytes(je(Au((P&1)===0),M)),z=c.inv(k),j=F(Q(d,void 0,"msgHash")),G=c.create(-j*z),ue=c.create(A*z),ie=t.BASE.mulAddUnsafe(G,$,ue);if(ie.is0())throw new Error("invalid recovery: point at infinify");return ie.assertValidity(),ie}hasHighS(){return L(this.s)}toBytes(d=E.format){if(pa(d),d==="der")return _r($o.hexFromSig(this));let{r:y,s:A}=this,P=c.toBytes(y),k=c.toBytes(A);return d==="recovered"?(N(),je(Uint8Array.of(this.assertRecovery()),P,k)):je(P,k)}toHex(d){return fn(this.toBytes(d))}}Object.freeze(I.prototype),Object.freeze(I);let K=o.bits2int===void 0?function(d){if(d.length>8192)throw new Error("input is too large");let y=ft(d),A=d.length*8-u;return A>0?y>>BigInt(A):y}:o.bits2int,F=o.bits2int_modN===void 0?function(d){return c.create(K(d))}:o.bits2int_modN,q=dn(u);function _(S){return lt("num < 2^"+u,S,xt,q),c.toBytes(S)}function U(S,d){return Q(S,void 0,"message"),d?Q(n(S),void 0,"prehashed message"):S}function T(S,d,y){let{lowS:A,prehash:P,extraEntropy:k}=da(y,E);S=U(S,P);let M=F(S),$=c.fromBytes(d);if(!c.isValidNot0($))throw new Error("invalid private key");let z=[_($),_(M)];if(k!=null&&k!==!1){let ie=k===!0?s(g.secretKey):k;z.push(Q(ie,void 0,"extraEntropy"))}let j=je(...z),G=M;function ue(ie){let ge=K(ie);if(!c.isValidNot0(ge))return;let Me=t.BASE.multiply(ge).toAffine(),fe=c.create(Me.x);if(fe===xt)return;let he;if(h!==void 0){let _t=ft(Ao(h(l),f)),nd=c.inv(c.mul(_t,ge)),od=c.mul(_t,G),sd=c.mul(_t,$);he=c.create(nd*c.create(od+sd*fe))}else{let _t=Nf(ge,f);he=c.create(_t*c.create(G+fe*$))}if(he===xt)return;let mr=R(Me.x,Me.y,fe),Zr=he;return A&&L(he)&&(Zr=c.neg(he),mr^=1),new I(fe,Zr,b?void 0:mr)}return{seed:j,k2sig:ue}}function v(S,d,y={}){let{seed:A,k2sig:P}=T(S,d,y);return Tf(n.outputLen,c.BYTES,i)(A,P).toBytes(y.format)}function H(S,d,y,A={}){let{lowS:P,prehash:k,format:M}=da(A,E);if(y=Q(y,void 0,"publicKey"),d=U(d,k),!kt(S)){let $=S instanceof I?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+$)}B(S,M);try{let $=I.fromBytes(S,M),z=t.fromBytes(y);if(z.is0()||P&&$.hasHighS())return!1;let{r:j,s:G}=$,ue=F(d),ie=c.inv(G),ge=c.create(ue*ie),Me=c.create(j*ie),fe=t.BASE.mulAddUnsafe(ge,z,Me);if(fe.is0())return!1;let he=fe.toAffine();return!(c.create(he.x)!==j||M==="recovered"&&$.recovery!==R(he.x,he.y,j))}catch{return!1}}function D(S,d,y={}){let{prehash:A}=da(y,E);return d=U(d,A),I.fromBytes(S,"recovered").recoverPublicKey(d).toBytes()}return Object.freeze({keygen:p,getPublicKey:x,getSharedSecret:w,utils:m,lengths:g,Point:t,sign:v,verify:H,recoverPublicKey:D,Signature:I,hash:n})}var ya={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Jp={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var _u=BigInt(2);function em(t){let e=ya.p,r=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),f=t*t*t%e,u=f*f*t%e,l=le(u,r,e)*u%e,h=le(l,r,e)*u%e,p=le(h,_u,e)*f%e,x=le(p,o,e)*p%e,w=le(x,s,e)*x%e,m=le(w,a,e)*w%e,g=le(m,c,e)*m%e,E=le(g,a,e)*w%e,b=le(E,r,e)*u%e,L=le(b,i,e)*x%e,C=le(L,n,e)*f%e,O=le(C,_u,e);if(!ma.eql(ma.sqr(O),t))throw new Error("Cannot find square root");return O}var ma=Br(ya.p,{sqrt:em}),tm=Su(ya,{Fp:ma,endo:Jp}),Pr=Cu(tm,ct);function Tu(t,e,r,n){let o=pt.digest(r instanceof Uint8Array?r:r.subarray());if(Po(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),Pr.verify(e,s,t,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new gn(String(s))});try{return n?.signal?.throwIfAborted(),Pr.verify(e,o.digest,t,{prehash:!1,format:"der"})}catch(s){throw new gn(String(s))}}var zo=class{type="secp256k1";raw;_key;constructor(e){this._key=Bu(e),this.raw=Lu(this._key)}toMultihash(){return Ze.digest(It(this))}toCID(){return Ee.createV1(114,this.toMultihash())}toString(){return ye.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ve(this.raw,e.raw)}verify(e,r,n){return Tu(this._key,r,e,n)}};function ga(t){return new zo(t)}function Lu(t){return Pr.Point.fromBytes(t).toBytes()}function Bu(t){try{return Pr.Point.fromBytes(t),t}catch(e){throw new yr(String(e))}}function Cn(t,e){let{Type:r,Data:n}=dt.decode(t),o=n??new Uint8Array;switch(r){case pe.RSA:return ca(o,e);case pe.Ed25519:return Mi(o);case pe.secp256k1:return ga(o);case pe.ECDSA:return hi(o);default:throw new Gt}}function Du(t){let{Type:e,Data:r}=dt.decode(t.digest),n=r??new Uint8Array;switch(e){case pe.Ed25519:return Mi(n);case pe.secp256k1:return ga(n);case pe.ECDSA:return hi(n);default:throw new Gt}}function It(t){return dt.encode({Type:pe[t.type],Data:t.raw})}var Iu=Symbol.for("nodejs.util.inspect.custom"),rm=114,_n=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[ks]=!0;toString(){return this.string==null&&(this.string=ye.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return Ee.createV1(rm,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return ve(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return ve(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Iu](){return`PeerId(${this.toString()})`}},Tn=class extends _n{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Ln=class extends _n{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},Bn=class extends _n{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},nm=2336,Dn=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Ze.digest(Z(this.url))}[Iu](){return`PeerId(${this.url})`}[ks]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return Ee.createV1(nm,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=W(e)),e.toString()===this.toString())}};var om=114,Ru=2336;function Nr(t,e){let r;if(t.charAt(0)==="1"||t.charAt(0)==="Q")r=Ar(ye.decode(`z${t}`));else{if(t.startsWith("k51qzi5uqu5")||t.startsWith("kzwfwjn5ji4")||t.startsWith("k2k4r8")||t.startsWith("bafz"))return sm(Ee.parse(t));if(e==null)throw new J('Please pass a multibase decoder for strings that do not start with "1" or "Q"');r=Ar(e.decode(t))}return Ou(r)}function ba(t){if(t.type==="Ed25519")return new Ln({multihash:t.toCID().multihash,publicKey:t});if(t.type==="secp256k1")return new Bn({multihash:t.toCID().multihash,publicKey:t});if(t.type==="RSA")return new Tn({multihash:t.toCID().multihash,publicKey:t});throw new Gt}function Ou(t){if(am(t))return new Tn({multihash:t});if(im(t))try{let e=Du(t);if(e.type==="Ed25519")return new Ln({multihash:t,publicKey:e});if(e.type==="secp256k1")return new Bn({multihash:t,publicKey:e})}catch{let r=W(t.digest);return new Dn(new URL(r))}throw new Jn("Supplied PeerID Multihash is invalid")}function sm(t){if(t?.multihash==null||t.version==null||t.version===1&&t.code!==om&&t.code!==Ru)throw new Qn("Supplied PeerID CID is invalid");if(t.code===Ru){let e=W(t.multihash.digest);return new Dn(new URL(e))}return Ou(t.multihash)}function im(t){return t.code===Ze.code}function am(t){return t.code===pt.code}var _e=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Et=class extends Error{static name="ValidationError";name="ValidationError"},qo=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Vo=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var jo=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let r=this.index,n=e();return n===void 0&&(this.index=r),n}parseWith(e){let r=e();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(e){return this.readAtomically(()=>{let r=this.readChar();if(r===e)return r})}readSeparator(e,r,n){return this.readAtomically(()=>{if(!(r>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,r,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",f=2**(8*o)-1;for(;;){let u=this.readAtomically(()=>{let l=this.readChar();if(l===void 0)return;let h=Number.parseInt(l,e);if(!Number.isNaN(h))return h});if(u===void 0)break;if(s*=e,s+=u,s>f||(i+=1,r!==void 0&&i>r))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let r=0;r<e.length;r++){let n=this.readSeparator(".",r,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[r]=n}return e})}readIPv6Addr(){let e=r=>{for(let n=0;n<r.length/2;n++){let o=n*2;if(n<r.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return r[o]=i[0],r[o+1]=i[1],r[o+2]=i[2],r[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];r[o]=s>>8,r[o+1]=s&255}return[r.length,!1]};return this.readAtomically(()=>{let r=new Uint8Array(16),[n,o]=e(r);if(n===16)return r;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return r.set(s.subarray(0,a),16-a),r})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var cm=45,fm=15,Wo=new jo;function Pu(t){if(!(t.length>fm))return Wo.new(t).parseWith(()=>Wo.readIPv4Addr())}function Nu(t){if(t.includes("%")&&(t=t.split("%")[0]),!(t.length>cm))return Wo.new(t).parseWith(()=>Wo.readIPv6Addr())}function Go(t){return!!Pu(t)}function Uu(t){return!!Nu(t)}function xa(t){return e=>W(e,t)}function Ea(t){return e=>Z(e,t)}function Ur(t){return new DataView(t.buffer).getUint16(t.byteOffset).toString()}function cr(t){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof t=="string"?parseInt(t):t),new Uint8Array(e)}function ku(t){let e=t.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let r=Z(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=cr(n);return Ue([r,o],r.length+o.length)}function Mu(t){let e=t.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let r=Bt.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=cr(n);return Ue([r,o],r.length+o.length)}function Sa(t){let e=t.subarray(0,t.length-2),r=t.subarray(t.length-2),n=W(e,"base32"),o=Ur(r);return`${n}:${o}`}var Aa=function(t){t=t.toString().trim();let e=new Uint8Array(4);return t.split(/\./g).forEach((r,n)=>{let o=parseInt(r,10);if(isNaN(o)||o<0||o>255)throw new _e("Invalid byte value in IP address");e[n]=o}),e},Fu=function(t){let e=0;t=t.toString().trim();let r=t.split(":",8),n;for(n=0;n<r.length;n++){let s=Go(r[n]),i;s&&(i=Aa(r[n]),r[n]=W(i.subarray(0,2),"base16")),i!=null&&++n<8&&r.splice(n,0,W(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 s=[n,1];for(n=9-r.length;n>0;n--)s.push("0");r.splice.apply(r,s)}let o=new Uint8Array(e+16);for(n=0;n<r.length;n++){r[n]===""&&(r[n]="0");let s=parseInt(r[n],16);if(isNaN(s)||s<0||s>65535)throw new _e("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},Ku=function(t){if(t.byteLength!==4)throw new _e("IPv4 address was incorrect length");let e=[];for(let r=0;r<t.byteLength;r++)e.push(t[r]);return e.join(".")},Hu=function(t){if(t.byteLength!==16)throw new _e("IPv6 address was incorrect length");let e=[];for(let n=0;n<t.byteLength;n+=2){let o=t[n],s=t[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;e.push(i)}let r=e.join(":");try{let n=new URL(`http://[${r}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new _e(`Invalid IPv6 address "${r}"`)}};function $u(t){try{let e=new URL(`http://[${t}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new _e(`Invalid IPv6 address "${t}"`)}}var wa=Object.values(Zt).map(t=>t.decoder),um=(function(){let t=wa[0].or(wa[1]);return wa.slice(2).forEach(e=>t=t.or(e)),t})();function zu(t){return um.decode(t)}function qu(t){return e=>t.encoder.encode(e)}function lm(t){if(parseInt(t).toString()!==t)throw new Et("Value must be an integer")}function dm(t){if(t<0)throw new Et("Value must be a positive integer, or zero")}function hm(t){return e=>{if(e>t)throw new Et(`Value must be smaller than or equal to ${t}`)}}function pm(...t){return e=>{for(let r of t)r(e)}}var In=pm(lm,dm,hm(65535));var Ae=-1,va=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let r;if(typeof e=="string"?r=this.protocolsByName.get(e):r=this.protocolsByCode.get(e),r==null)throw new Vo(`Protocol ${e} was unknown`);return r}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(r=>{this.protocolsByName.set(r,e)})}removeProtocol(e){let r=this.protocolsByCode.get(e);r!=null&&(this.protocolsByCode.delete(r.code),this.protocolsByName.delete(r.name),r.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},At=new va,Lm=[{code:4,name:"ip4",size:32,valueToBytes:Aa,bytesToValue:Ku,validate:t=>{if(!Go(t))throw new Et(`Invalid IPv4 address "${t}"`)}},{code:6,name:"tcp",size:16,valueToBytes:cr,bytesToValue:Ur,validate:In},{code:273,name:"udp",size:16,valueToBytes:cr,bytesToValue:Ur,validate:In},{code:33,name:"dccp",size:16,valueToBytes:cr,bytesToValue:Ur,validate:In},{code:41,name:"ip6",size:128,valueToBytes:Fu,bytesToValue:Hu,stringToValue:$u,validate:t=>{if(!Uu(t))throw new Et(`Invalid IPv6 address "${t}"`)}},{code:42,name:"ip6zone",size:Ae},{code:43,name:"ipcidr",size:8,bytesToValue:xa("base10"),valueToBytes:Ea("base10")},{code:53,name:"dns",size:Ae},{code:54,name:"dns4",size:Ae},{code:55,name:"dns6",size:Ae},{code:56,name:"dnsaddr",size:Ae},{code:132,name:"sctp",size:16,valueToBytes:cr,bytesToValue:Ur,validate:In},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:Ae,stringToValue:t=>decodeURIComponent(t),valueToString:t=>encodeURIComponent(t)},{code:421,name:"p2p",aliases:["ipfs"],size:Ae,bytesToValue:xa("base58btc"),valueToBytes:t=>t.startsWith("Q")||t.startsWith("1")?Ea("base58btc")(t):Ee.parse(t).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Sa,valueToBytes:ku},{code:445,name:"onion3",size:296,bytesToValue:Sa,valueToBytes:Mu},{code:446,name:"garlic64",size:Ae},{code:447,name:"garlic32",size:Ae},{code:448,name:"tls"},{code:449,name:"sni",size:Ae},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:Ae,bytesToValue:qu(rn),valueToBytes:zu},{code:480,name:"http"},{code:481,name:"http-path",size:Ae,stringToValue:t=>`/${decodeURIComponent(t)}`,valueToString:t=>encodeURIComponent(t.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:Ae}];Lm.forEach(t=>{At.addProtocol(t)});function Vu(t){let e=[],r=0;for(;r<t.length;){let n=bt(t,r),o=At.getProtocol(n),s=de(n),i=Bm(o,t,r+s),a=0;i>0&&o.size===Ae&&(a=de(i));let c=s+a+i,f={code:n,name:o.name,bytes:Ce(t.subarray(r,r+c))};if(i>0){let u=r+s+a,l=t.subarray(u,u+i);f.value=o.bytesToValue?.(l)??W(l)}e.push(f),r+=c}return e}function ju(t){let e=0,r=[];for(let n of t){if(n.bytes==null){let o=At.getProtocol(n.code),s=de(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??Z(n.value),a=i.byteLength,o.size===Ae&&(c=de(a)));let f=new Uint8Array(s+c+a),u=0;Rr(n.code,f,u),u+=s,i!=null&&(o.size===Ae&&(Rr(a,f,u),u+=c),f.set(i,u)),n.bytes=f}r.push(n.bytes),e+=n.bytes.byteLength}return Ue(r,e)}function Wu(t){if(t.charAt(0)!=="/")throw new _e('String multiaddr must start with "/"');let e=[],r="protocol",n="",o="";for(let s=1;s<t.length;s++){let i=t.charAt(s);i!=="/"&&(r==="protocol"?o+=t.charAt(s):n+=t.charAt(s));let a=s===t.length-1;if(i==="/"||a){let c=At.getProtocol(o);if(r==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",r="protocol";continue}else if(a)throw new _e(`Component ${o} 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 _e(`Component ${o} was missing value`);f.value=c.stringToValue?.(n)??n}e.push(f),n="",o="",r="protocol"}}}if(o!==""&&n!=="")throw new _e("Incomplete multiaddr");return e}function Gu(t){return`/${t.flatMap(e=>{if(e.value==null)return e.name;let r=At.getProtocol(e.code);if(r==null)throw new _e(`Unknown protocol code ${e.code}`);return[e.name,r.valueToString?.(e.value)??e.value]}).join("/")}`}function Bm(t,e,r){return t.size==null||t.size===0?0:t.size>0?t.size/8:bt(e,r)}var Dm=Symbol.for("nodejs.util.inspect.custom"),Ha=Symbol.for("@multiformats/multiaddr");function Im(t){if(t==null&&(t="/"),Yu(t))return t.getComponents();if(t instanceof Uint8Array)return Vu(t);if(typeof t=="string")return t=t.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),t===""&&(t="/"),Wu(t);if(Array.isArray(t))return t;throw new _e("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Jo=class t{[Ha]=!0;#e;#t;#r;constructor(e="/",r={}){this.#e=Im(e),r.validate!==!1&&Rm(this)}get bytes(){return this.#r==null&&(this.#r=ju(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=Gu(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let r=new t(e);return new t([...this.#e,...r.getComponents()],{validate:!1})}decapsulate(e){let r=e.toString(),n=this.toString(),o=n.lastIndexOf(r);if(o<0)throw new qo(`Address ${this.toString()} does not contain subaddress: ${r}`);return new t(n.slice(0,o),{validate:!1})}decapsulateCode(e){let r;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){r=n;break}return new t(this.#e.slice(0,r),{validate:!1})}equals(e){return ve(this.bytes,e.bytes)}[Dm](){return`Multiaddr(${this.toString()})`}};function Rm(t){t.getComponents().forEach(e=>{let r=At.getProtocol(e.code);e.value!=null&&r.validate?.(e.value)})}function Yu(t){return!!t?.[Ha]}function Kr(t){return new Jo(t)}var ae=t=>({match:e=>{let r=e[0];return r==null||r.code!==t||r.value!=null?!1:e.slice(1)}}),V=(t,e)=>({match:r=>{let n=r[0];return n?.code!==t||n.value==null||e!=null&&n.value!==e?!1:r.slice(1)}}),Xu=t=>({match:e=>t.match(e)===!1?e:!1}),X=t=>({match:e=>{let r=t.match(e);return r===!1?e:r}}),Re=(...t)=>({match:e=>{let r;for(let n of t){let o=n.match(e);o!==!1&&(r==null||o.length<r.length)&&(r=o)}return r??!1}}),te=(...t)=>({match:e=>{for(let r of t){let n=r.match(e);if(n===!1)return!1;e=n}return e}});function ce(...t){function e(o){if(o==null)return!1;let s=o.getComponents();for(let i of t){let a=i.match(s);if(a===!1)return!1;s=a}return s}function r(o){return e(o)!==!1}function n(o){let s=e(o);return s===!1?!1:s.length===0}return{matchers:t,matches:r,exactMatch:n}}var Om=V(421),l1=ce(Om),ts=V(54),rs=V(55),ns=V(56),za=V(53),d1=ce(ts,X(V(421))),h1=ce(rs,X(V(421))),p1=ce(ns,X(V(421))),m1=ce(Re(za,ns,ts,rs),X(V(421))),Zu=te(V(4),X(V(43))),Qu=te(X(V(42)),V(41),X(V(43))),qa=Re(Zu,Qu),Hr=Re(qa,za,ts,rs,ns),y1=ce(Re(qa,te(Re(za,ns,ts,rs),X(V(421))))),g1=ce(Zu),b1=ce(Qu),w1=ce(qa),Va=te(Hr,V(6)),Rn=te(Hr,V(273)),x1=ce(te(Va,X(V(421)))),E1=ce(Rn),ja=te(Rn,ae(460),X(V(421))),os=te(Rn,ae(461),X(V(421))),Pm=Re(ja,os),S1=ce(ja),A1=ce(os),$a=Re(Hr,Va,Rn,ja,os),Ju=Re(te($a,ae(477),X(V(421)))),v1=ce(Ju),el=Re(te($a,ae(478),X(V(421))),te($a,ae(448),X(V(449)),ae(477),X(V(421)))),C1=ce(el),tl=te(Rn,ae(280),X(V(466)),X(V(466)),X(V(421))),rl=ce(tl),nl=te(os,ae(465),X(V(466)),X(V(466)),X(V(421))),_1=ce(nl),es=Re(Ju,el,te(Va,X(V(421))),te(Pm,X(V(421))),te(Hr,X(V(421))),tl,nl,V(421)),ol=ce(es),Nm=te(X(es),ae(290),Xu(ae(281)),X(V(421))),T1=ce(Nm),Um=Re(te(es,ae(290),ae(281),X(V(421))),te(es,ae(281),X(V(421))),te(ae(281),X(V(421)))),sl=ce(Um),km=te(Hr,Re(te(V(6,"80")),te(V(6),ae(480)),ae(480)),X(V(481)),X(V(421))),L1=ce(km),Mm=te(Hr,Re(te(V(6,"443")),te(V(6,"443"),ae(480)),te(V(6),ae(443)),te(V(6),ae(448),ae(480)),te(ae(448),ae(480)),ae(448),ae(443)),X(V(481)),X(V(421))),B1=ce(Mm),Fm=Re(te(V(777),X(V(421)))),D1=ce(Fm),Km=Re(te(V(400),X(V(421)))),I1=ce(Km);var Oe;(function(t){let e;(function(a){a.FIN="FIN",a.STOP_SENDING="STOP_SENDING",a.RESET="RESET",a.FIN_ACK="FIN_ACK"})(e=t.Flag||(t.Flag={}));let r;(function(a){a[a.FIN=0]="FIN",a[a.STOP_SENDING=1]="STOP_SENDING",a[a.RESET=2]="RESET",a[a.FIN_ACK=3]="FIN_ACK"})(r||(r={})),(function(a){a.codec=()=>sr(r)})(e=t.Flag||(t.Flag={}));let n;t.codec=()=>(n==null&&(n=ot((a,c,f={})=>{f.lengthDelimited!==!1&&c.fork(),a.flag!=null&&(c.uint32(8),t.Flag.codec().encode(a.flag,c)),a.message!=null&&(c.uint32(18),c.bytes(a.message)),f.lengthDelimited!==!1&&c.ldelim()},(a,c,f={})=>{let u={},l=c==null?a.len:a.pos+c;for(;a.pos<l;){let h=a.uint32();switch(h>>>3){case 1:{u.flag=t.Flag.codec().decode(a);break}case 2:{u.message=a.bytes();break}default:{a.skipType(h&7);break}}}return u},function*(a,c,f,u={}){let l=c==null?a.len:a.pos+c;for(;a.pos<l;){let h=a.uint32();switch(h>>>3){case 1:{yield{field:`${f}.flag`,value:t.Flag.codec().decode(a)};break}case 2:{yield{field:`${f}.message`,value:a.bytes()};break}default:{a.skipType(h&7);break}}}})),n);function o(a){return rt(a,t.codec())}t.encode=o;function s(a,c){return tt(a,t.codec(),c)}t.decode=s;function i(a,c){return nt(a,t.codec(),c)}t.stream=i})(Oe||(Oe={}));var il=["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478","stun:stun.cloudflare.com:3478","stun:stun.services.mozilla.com:3478"],Wa=Array.from("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"),al="libp2p+webrtc+v1/",cl=2*1024*1024,ur=16*1024,fl=ur,ul=10,ll=8;function Hm(t=ur){let e=de(t-de(t)),r=1+de(Object.keys(Oe.Flag).length-1),n=1,o=t-e-r-n,s=de(o);return e+r+n+s}var dl=Hm();var hl=1e4,Ga="/webrtc",On="/webrtc-signaling/0.0.1";function $m(t){let e=t.getComponents(),r={},n=0;return e[n]?.name==="ip6zone"&&(r.zone=`${e[n].value}`,n++),e[n]?.name==="ip4"||e[n]?.name==="ip6"||e[n]?.name==="dns"||e[n]?.name==="dns4"||e[n]?.name==="dns6"?(r.type=e[n].name,r.host=e[n].value,n++):e[n]?.name==="dnsaddr"&&(r.type=e[n].name,r.host=`_dnsaddr.${e[n].value}`,n++),(e[n]?.name==="tcp"||e[n]?.name==="udp")&&(r.protocol=e[n].name==="tcp"?"tcp":"udp",r.port=parseInt(`${e[n].value}`),n++),e[n]?.name==="ipcidr"&&(r.type==="ip4"?r.cidr=parseInt(`${e[n].value}`):r.type==="ip6"&&(r.cidr=`${e[n].value}`),n++),r.type==null||r.host==null?null:(e[n]?.name==="tls"&&e[n+1]?.name==="sni"&&(r.sni=e[n+1].value,n+=2),r)}function Ya(t){let e=$m(t);if(e==null)throw new J(`Multiaddr ${t} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e}function ss(){let t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}var is=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},$r=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new is(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let r=this.head;this.head=r.next=new is(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let r=this.tail.next;this.tail.next=null,this.tail=r,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var Xa=class extends Error{type;code;constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function zr(t={}){return zm(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}},t)}function zm(t,e){e=e??{};let r=e.onEnd,n=new $r,o,s,i,a=ss(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((m,g)=>{s=E=>{s=null,n.push(E);try{m(t(n))}catch(b){g(b)}return o}}):t(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=ss()})}},f=m=>s!=null?s(m):(n.push(m),o),u=m=>(n=new $r,s!=null?s({error:m}):(n.push({error:m}),o)),l=m=>{if(i)return o;if(e?.objectMode!==!0&&m?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return f({done:!1,value:m})},h=m=>i?o:(i=!0,m!=null?u(m):f({done:!0})),p=()=>(n=new $r,h(),{done:!0}),x=m=>(h(m),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:p,throw:x,push:l,end:h,get readableLength(){return n.size},onEmpty:async m=>{let g=m?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let E,b;g!=null&&(E=new Promise((L,C)=>{b=()=>{C(new Xa)},g.addEventListener("abort",b)}));try{await Promise.race([a.promise,E])}finally{b!=null&&g!=null&&g?.removeEventListener("abort",b)}}},r==null)return o;let w=o;return o={[Symbol.asyncIterator](){return this},next(){return w.next()},throw(m){return w.throw(m),r!=null&&(r(m),r=void 0),{done:!0}},return(){return w.return(),r!=null&&(r(),r=void 0),{done:!0}},push:l,end(m){return w.end(m),r!=null&&(r(m),r=void 0),o},get readableLength(){return w.readableLength},onEmpty:m=>w.onEmpty(m)},o}var Za=class t extends Error{name="TimeoutError";constructor(e,r){super(e,r),Error.captureStackTrace?.(this,t)}},pl=t=>t.reason??new DOMException("This operation was aborted.","AbortError");function Qa(t,e){let{milliseconds:r,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e,a,c,u=new Promise((l,h)=>{if(typeof r!="number"||Math.sign(r)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(i?.aborted){h(pl(i));return}if(i&&(c=()=>{h(pl(i))},i.addEventListener("abort",c,{once:!0})),t.then(l,h),r===Number.POSITIVE_INFINITY)return;let p=new Za;a=s.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(x){h(x)}return}typeof t.cancel=="function"&&t.cancel(),o===!1?l():o instanceof Error?h(o):(p.message=o??`Promise timed out after ${r} milliseconds`,h(p))},r)}).finally(()=>{u.clear(),c&&i&&i.removeEventListener("abort",c)});return u.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},u}var qm=t=>{let e=t.addEventListener||t.on||t.addListener,r=t.removeEventListener||t.off||t.removeListener;if(!e||!r)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(t),removeListener:r.bind(t)}};function Vm(t,e,r){let n,o=new Promise((s,i)=>{if(r={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!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=[e].flat(),c=[],{addListener:f,removeListener:u}=qm(t),l=async(...p)=>{let x=r.multiArgs?p:p[0];if(r.filter)try{if(!await r.filter(x))return}catch(w){n(),i(w);return}c.push(x),r.count===c.length&&(n(),s(c))},h=(...p)=>{n(),i(r.rejectionMultiArgs?p:p[0])};n=()=>{for(let p of a)u(p,l);for(let p of r.rejectionEvents)a.includes(p)||u(p,h)};for(let p of a)f(p,l);for(let p of r.rejectionEvents)a.includes(p)||f(p,h);r.signal&&r.signal.addEventListener("abort",()=>{h(r.signal.reason)},{once:!0}),r.resolveImmediately&&s(c)});if(o.cancel=n,typeof r.timeout=="number"){let s=Qa(o,{milliseconds:r.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function Te(t,e,r){typeof r=="function"&&(r={filter:r}),r={...r,count:1,resolveImmediately:!1};let n=Vm(t,e,r),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}var lr=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"},as=class extends Error{static name="MaxEarlyStreamsError";name="MaxEarlyStreamsError"},cs=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function jm(t){return t.reason}function vt(t,e,r){if(e==null||t==null)return t;let n=r?.translateError??jm;if(e.aborted)return t.catch(()=>{}),Promise.reject(n(e));let o;return Promise.race([t,new Promise((s,i)=>{o=()=>{i(n(e))},e.addEventListener("abort",o)})]).finally(()=>{o!=null&&e.removeEventListener("abort",o)})}var Wm=Math.pow(2,20)*4,zt=class extends Tt{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;#e=!1;onDrainPromise;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??Wm,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new Y,this.writeBuffer=new Y,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,queueMicrotask(()=>{try{this.processSendQueue()}catch(o){this.log.error("processSendQueue threw - %e",o)}})),this.onDrainPromise?.resolve()};this.addEventListener("drain",r);let n=o=>{this.onDrainPromise?.reject(o.error??new cs)};this.addEventListener("close",n)}get readBufferLength(){return this.readBuffer.byteLength}get readableEnded(){return this.#e}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),vt(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let e=zr(),r=s=>{e.push(s.data)};this.addEventListener("message",r);let n=s=>{e.end(s.error)};this.addEventListener("close",n);let o=()=>{e.end()};this.addEventListener("remoteCloseWrite",o);try{yield*e}finally{this.removeEventListener("message",r),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",o)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new it(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",e.byteLength),this.writeBuffer.append(e),this.processSendQueue()}abort(e){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",e),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(),this.maybeDispatchEnd();try{this.sendReset(e)}catch(r){this.log.error("failed to send reset to remote - %e",r)}this.dispatchEvent(new ro(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new it("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 it("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new it(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.append(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}unshift(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new it(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.prepend(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(e){if(e.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(e),this.dispatchReadBuffer()}}addEventListener(...e){super.addEventListener.apply(this,e),e[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",this.maybeDispatchEnd()),this.dispatchEvent(new no(new gr))}onTransportClosed(e){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"),e!=null?this.abort(e):(this.status==="open"||this.status==="closing")&&(this.timeline.close=Date.now(),this.status="closed",this.maybeDispatchEnd(),this.dispatchEvent(new br))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.maybeDispatchEnd(),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;if(this.writeStatus!=="writable"&&this.writeStatus!=="closing")return this.log.trace("not processing send queue as stream is %s",this.writeStatus),!1;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let e=!0,r=this.writeBuffer.byteLength,n=0;for(;this.writeBuffer.byteLength>0;){let o=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(o===0){e=!1;break}let s=this.writeBuffer.sublist(0,o),i=new Y(s);this.writeBuffer.consume(s.byteLength);let a;try{a=this.sendData(s)}catch(c){throw this.writeBuffer.prepend(i),this.abort(c),c}if(e=a.canSendMore,n+=a.sentBytes,a.sentBytes!==i.byteLength&&(i.consume(a.sentBytes),this.writeBuffer.prepend(i)),!e)break}return e||(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"),e}finally{this.sendingData=!1}}maybeDispatchEnd(){this.#e||this.readBuffer.byteLength>0||this.remoteWriteStatus!=="closed"&&this.readStatus!=="closed"||(this.#e=!0,this.safeDispatchEvent("end"))}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 e=this.readBuffer.sublist();this.readBuffer.consume(e.byteLength),this.dispatchEvent(new to(e))}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.maybeDispatchEnd()),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new Wt(`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 Wt(`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 fs=class extends zt{remoteAddr;metricPrefix;metrics;constructor(e){super(e),this.metricPrefix=e.metricPrefix??"",this.metrics=e.metrics,this.remoteAddr=e.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(e){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 Te(this,"idle",{...e,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 Te(this,"drain",{...e,rejectionEvents:["close"]})),await this.sendClose(e),this.onTransportClosed())}};function ml(t){return t==null?!1:typeof t.then=="function"&&typeof t.catch=="function"&&typeof t.finally=="function"}var us=class extends Tt{streams;protocol;status;log;maConn;streamOptions;earlyStreams;maxEarlyStreams;metrics;constructor(e,r){super(),this.maConn=e,this.protocol=r.protocol,this.streams=[],this.earlyStreams=[],this.status="open",this.log=e.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 o=()=>{this.log("underlying stream drained, signal %d streams to continue writing",this.streams.length),this.streams.forEach(i=>{i.onMuxerDrain()})};this.maConn.addEventListener("drain",o);let s=()=>{this.log("underlying stream closed with status %s and %d streams",this.status,this.streams.length),this.onTransportClosed()};this.maConn.addEventListener("close",s)}send(e){let r=this.maConn.send(e);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(e){this.status==="closed"||this.status==="closing"||(this.status="closing",await vt(Promise.all([...this.streams].map(async r=>{await r.close(e)})),e?.signal),this.status="closed")}abort(e){this.status!=="closed"&&(this.status="closing",[...this.streams].forEach(r=>{r.abort(e)}),this.status="closed")}onTransportClosed(e){this.status="closing";try{[...this.streams].forEach(r=>{r.onTransportClosed(e)})}catch(r){this.abort(r)}this.status="closed"}async createStream(e){if(this.status!=="open")throw new Xn;let r=this.onCreateStream({...this.streamOptions,...e});return ml(r)&&(r=await r),this.streams.push(r),this.cleanUpStream(r),r}onRemoteStream(e){if(this.streams.push(e),this.cleanUpStream(e),this.listenerCount("stream")===0){this.earlyStreams.push(e),this.earlyStreams.length>this.maxEarlyStreams&&this.abort(new as(`Too many early streams were opened - ${this.earlyStreams.length}/${this.maxEarlyStreams}`));return}this.safeDispatchEvent("stream",{detail:e})}cleanUpStream(e){let r=n=>{let o=this.streams.findIndex(s=>s===e);o!==-1&&this.streams.splice(o,1),n.error!=null?n.local?this.metrics?.increment({[`${e.direction}_stream_reset`]:!0}):this.metrics?.increment({[`${e.direction}_stream_abort`]:!0}):this.metrics?.increment({[`${e.direction}_stream_end`]:!0})};e.addEventListener("close",r),this.metrics?.increment({[`${e.direction}_stream`]:!0})}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="stream"&&this.earlyStreams.length>0&&queueMicrotask(()=>{this.earlyStreams.forEach(r=>{this.safeDispatchEvent("stream",{detail:r})}),this.earlyStreams=[]})}};var ls=class extends zt{id;protocol;constructor(e){super(e),this.id=e.id,this.protocol=e.protocol??""}async close(e){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 Te(this,"idle",{...e,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 Te(this,"drain",{...e,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(e),this.writeStatus="closed",this.log("closed writable end gracefully"),this.remoteWriteStatus==="closed"&&this.onTransportClosed())}async closeRead(e){this.readStatus==="closing"||this.readStatus==="closed"||(this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.readStatus="closing",await this.sendCloseRead(e),this.readStatus="closed",this.maybeDispatchEnd(),this.log("closed readable end gracefully"))}};var Gm=4194304,ds=class extends Error{static name="UnwrappedError";name="UnwrappedError"},Pn=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},ec=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},tc=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Ym(t){return typeof t?.closeRead=="function"}function Xm(t){return typeof t?.close=="function"}function Ja(t){return Ym(t)?t.remoteWriteStatus!=="writable"&&t.readBufferLength===0:Xm(t)?t.status!=="open":!1}function Zm(t){return t?.addEventListener!=null&&t?.removeEventListener!=null&&t?.send!=null&&t?.push!=null&&t?.log!=null}function Qm(t,e){let r=e?.maxBufferSize??Gm,n=new Y,o,s=!1,i;if(!Zm(t))throw new J("Argument should be a Stream or a Multiaddr");let a=l=>{if(i==null){if(n.append(l.data),n.byteLength>r){let h=n.byteLength;n.consume(h);let p=new Wt(`Read buffer overflow - ${h} > ${r}`);i=p,o?.reject(p),queueMicrotask(()=>{t.abort(p)});return}o?.resolve()}};t.addEventListener("message",a);let c=l=>{l.error!=null?o?.reject(l.error):o?.resolve()};t.addEventListener("close",c);let f=()=>{o?.resolve()};t.addEventListener("remoteCloseWrite",f);let u={readBuffer:n,async read(l){if(s===!0)throw new ds("Stream was unwrapped");if(i!=null)throw i;if(Ja(t)){if(n.byteLength===0&&l?.bytes==null)return null;if(l?.bytes!=null&&n.byteLength<l.bytes)throw t.log.error("closed after reading %d/%d bytes",n.byteLength,l.bytes),new lr(`Unexpected EOF - stream closed after reading ${n.byteLength}/${l.bytes} bytes`)}let h=l?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=h){o.resolve();break}if(await vt(o.promise,l?.signal),Ja(t)){if(n.byteLength===0&&l?.bytes==null)return null;break}o=Promise.withResolvers()}let p=l?.bytes??n.byteLength;if(n.byteLength<p){if(Ja(t))throw t.log.error("closed while reading %d/%d bytes",n.byteLength,p),new lr(`Unexpected EOF - stream closed while reading ${n.byteLength}/${p} bytes`);return u.read(l)}let x=n.sublist(0,p);return n.consume(p),x},async write(l,h){if(s===!0)throw new ds("Stream was unwrapped");t.send(l)||await Te(t,"drain",{signal:h?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,t.removeEventListener("message",a),t.removeEventListener("close",c),t.removeEventListener("remoteCloseWrite",f),n.byteLength>0&&(t.log("stream unwrapped with %d unread bytes",n.byteLength),t.unshift(n))),t}};return u}function hs(t,e={}){let r=Qm(t,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=de(e.maxDataLength));let n=e?.lengthDecoder??bt,o=e?.lengthEncoder??Uo;return{async read(i){let a=-1,c=new Y;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 Pn("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new tc(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new ec(`Message length too long - ${a} > ${e.maxDataLength}`);let f=await r.read({...i,bytes:a});if(f==null)throw t.log.error("tried to read %d bytes but the stream closed",a),new lr(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(f.byteLength!==a)throw t.log.error("read %d/%d bytes before the stream closed",f.byteLength,a),new lr(`Unexpected EOF - read ${f.byteLength}/${a} bytes before the stream closed`);return f},async write(i,a){await r.write(new Y(o(i.byteLength),i),a)},async writeV(i,a){let c=new Y(...i.flatMap(f=>[o(f.byteLength),f]));await r.write(c,a)},unwrap(){return r.unwrap()}}}function ps(t,e){let r=hs(t,e),n={read:async(o,s)=>{let i=await r.read(s);return o.decode(i,s)},write:async(o,s,i)=>{await r.write(s.encode(o),i)},writeV:async(o,s,i)=>{await r.writeV(o.map(a=>s.encode(a)),i)},pb:o=>({read:async s=>n.read(o,s),write:async(s,i)=>n.write(s,o,i),writeV:async(s,i)=>n.writeV(s,o,i),unwrap:()=>n}),unwrap:()=>r.unwrap()};return n}var Jm=1024*1024*4,ey=1024*1024*4,ms=class{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(e={}){this.buffer=new Y,this.maxBufferSize=e.maxBufferSize??Jm,this.maxDataLength=e.maxDataLength??ey,this.lengthDecoder=e.lengthDecoder??bt,this.encodingLength=e.encodingLength??de}*decode(e){if(this.buffer.append(e),this.buffer.byteLength>this.maxBufferSize)throw new J(`Buffer length limit exceeded - ${this.buffer.byteLength}/${this.maxBufferSize}`);for(;;){let r;try{r=this.lengthDecoder(this.buffer)}catch(s){if(s instanceof RangeError)break;throw s}if(r<0||r>this.maxDataLength)throw new Pn("Invalid message length");let n=this.encodingLength(r),o=n+r;if(this.buffer.byteLength>=o){let s=this.buffer.sublist(n,o);this.buffer.consume(o),s.byteLength>0&&(yield s)}else break}}};var ys=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},qr=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},gs=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Nn=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function bs(t){return t[Symbol.asyncIterator]!=null}function yl(t,e){if(t.byteLength>e)throw new qr("Message length too long")}var xs=t=>{let e=de(t),r=xe(e);return Uo(t,r),xs.bytes=e,r};xs.bytes=0;function Un(t,e){e=e??{};let r=e.lengthEncoder??xs,n=e?.maxDataLength??4194304;function*o(s){yl(s,n);let i=r(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return bs(t)?(async function*(){for await(let s of t)yield*o(s)})():(function*(){for(let s of t)yield*o(s)})()}Un.single=(t,e)=>{e=e??{};let r=e.lengthEncoder??xs,n=e?.maxDataLength??4194304;return yl(t,n),new Y(r(t.byteLength),t)};var dr;(function(t){t[t.LENGTH=0]="LENGTH",t[t.DATA=1]="DATA"})(dr||(dr={}));var rc=t=>{let e=bt(t);return rc.bytes=de(e),e};rc.bytes=0;function kn(t,e){let r=new Y,n=dr.LENGTH,o=-1,s=e?.lengthDecoder??rc,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;r.byteLength>0;){if(n===dr.LENGTH)try{if(o=s(r),o<0)throw new ys("Invalid message length");if(o>a)throw new qr("Message length too long");let f=s.bytes;r.consume(f),e?.onLength!=null&&e.onLength(o),n=dr.DATA}catch(f){if(f instanceof RangeError){if(r.byteLength>i)throw new gs("Message length length too long");break}throw f}if(n===dr.DATA){if(r.byteLength<o)break;let f=r.sublist(0,o);r.consume(o),e?.onData!=null&&e.onData(f),yield f,n=dr.LENGTH}}}return bs(t)?(async function*(){for await(let f of t)r.append(f),yield*c();if(r.byteLength>0)throw new Nn("Unexpected end of input")})():(function*(){for(let f of t)r.append(f),yield*c();if(r.byteLength>0)throw new Nn("Unexpected end of input")})()}kn.fromReader=(t,e)=>{let r=1,n=(async function*(){for(;;)try{let{done:s,value:i}=await t.next(r);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{r=1}})();return kn(n,{...e??{},onLength:s=>{r=s}})};var nc=class extends ls{channel;incomingData;maxBufferedAmount;receivedFinAck;finAckTimeout;constructor(e){super({...e,maxMessageSize:(e.maxMessageSize??ur)-dl}),this.channel=e.channel,this.channel.binaryType="arraybuffer",this.incomingData=zr(),this.maxBufferedAmount=e.maxBufferedAmount??cl,this.finAckTimeout=e.finAckTimeout??hl,this.channel.onclose=()=>{this.log.trace("received datachannel close event"),this.onRemoteCloseWrite(),this.onTransportClosed()},this.channel.onerror=n=>{let o=n.error;this.log.trace("received datachannel error event - %e",o),this.abort(o)},this.channel.onmessage=async n=>{this.log("incoming message %d bytes",n.data.byteLength);let{data:o}=n;o===null||o.byteLength===0||this.incomingData.push(new Uint8Array(o,0,o.byteLength))},this.channel.bufferedAmountLowThreshold=0,this.channel.onbufferedamountlow=()=>{this.writableNeedsDrain&&this.safeDispatchEvent("drain")},Promise.resolve().then(async()=>{for await(let n of kn(this.incomingData))this.processIncomingProtobuf(n)}).catch(n=>{this.log.error("error processing incoming data channel messages - %e",n)});let r=()=>{this.channel.readyState==="open"&&(this.log.trace("stream closed, closing underlying datachannel"),this.channel.close())};this.addEventListener("close",r),this.channel.readyState!=="open"&&(this.log('channel ready state is "%s" and not "open", waiting for "open" event before sending data',this.channel.readyState),Te(this.channel,"open",{rejectionEvents:["close","error"]}).then(()=>{this.log('channel ready state is now "%s", dispatching drain',this.channel.readyState),this.safeDispatchEvent("drain")}).catch(n=>{this.abort(n.error??n)}))}sendNewStream(){}_sendMessage(e){if(this.channel.readyState!=="open")throw new it(`Invalid datachannel state - ${this.channel.readyState}`);this.log.trace('sending message, channel state "%s"',this.channel.readyState);try{for(let r of e)this.channel.send(Ce(r))}catch(r){this.log.error("error sending datachannel message - %e",r),this.abort(r)}}sendData(e){return this.channel.readyState!=="open"?{sentBytes:0,canSendMore:!1}:(this._sendMessage(Un.single(Oe.encode({message:e.subarray()}))),{sentBytes:e.byteLength,canSendMore:this.channel.bufferedAmount<this.maxBufferedAmount})}sendReset(e){try{this.log.error("sending reset - %e",e),this._sendFlag(Oe.Flag.RESET),this.receivedFinAck?.reject(e)}catch(r){this.log.error("failed to send reset - %e",r)}}async sendCloseWrite(e){this._sendFlag(Oe.Flag.FIN),e?.signal?.throwIfAborted(),this.receivedFinAck=Promise.withResolvers();let r=e?.signal??AbortSignal.timeout(this.finAckTimeout),n=[Te(this.channel,"close",{signal:r}),Te(this.channel,"error",{signal:r})];await Promise.any([vt(this.receivedFinAck.promise,r),...n]).finally(()=>{n.forEach(o=>o.cancel())})}async sendCloseRead(e){this._sendFlag(Oe.Flag.STOP_SENDING),e?.signal?.throwIfAborted()}processIncomingProtobuf(e){let r=Oe.decode(e);r.message!=null&&(this.readStatus==="readable"||this.readStatus==="paused")&&this.onData(new Y(r.message)),r.flag!==void 0&&(this.log.trace('incoming flag %s, write status "%s", read status "%s"',r.flag,this.writeStatus,this.readStatus),r.flag===Oe.Flag.FIN&&(this._sendFlag(Oe.Flag.FIN_ACK),this.onRemoteCloseWrite()),r.flag===Oe.Flag.RESET&&(this.receivedFinAck?.reject(new gr("The stream was reset")),this.onRemoteReset()),r.flag===Oe.Flag.STOP_SENDING&&this.onRemoteCloseRead(),r.flag===Oe.Flag.FIN_ACK&&this.receivedFinAck?.resolve())}_sendFlag(e){if(this.channel.readyState!=="open")return this.log.trace('not sending flag %s because channel is "%s" and not "open"',e.toString(),this.channel.readyState),!1;this.log.trace("sending flag %s",e.toString());let r=Oe.encode({flag:e}),n=Un.single(r);try{return this._sendMessage(n),!0}catch(o){this.log.error("could not send flag %s - %e",e.toString(),o)}return!1}sendPause(){}sendResume(){}};function Mn(t){let{channel:e,direction:r,isHandshake:n}=t;return new nc({...t,id:`${e.id}`,log:t.log.newScope(`${n===!0?"handshake":r}:${e.id}`),protocol:""})}function ic(t,e){try{t.close()}catch(r){e?.trace("error closing early data channel - %e",r)}}function oc(t,e){t.channel.onmessage=null,t.messages.length=0,ic(t.channel,e)}var qt=class{protocol;peerConnection;metrics;log;dataChannelOptions;maxEarlyStreams;earlyDataChannels;handedOff=!1;constructor(e){this.onEarlyDataChannel=this.onEarlyDataChannel.bind(this),this.peerConnection=e.peerConnection,this.metrics=e.metrics,this.log=e.log,this.protocol=e.protocol??Ga,this.dataChannelOptions=e.dataChannelOptions??{},this.maxEarlyStreams=e.maxEarlyStreams??ul,this.peerConnection.addEventListener("datachannel",this.onEarlyDataChannel),this.earlyDataChannels=[]}onEarlyDataChannel(e){let r=e.channel;if(this.earlyDataChannels.length>=this.maxEarlyStreams){this.log?.("rejecting early data channel %d - too many early channels",r.id),this.metrics?.increment({early_data_channel_count_exceeded:!0}),ic(r,this.log);return}r.binaryType="arraybuffer";let n={channel:r,messages:[]};r.onmessage=o=>{let{data:s}=o;if(!(s instanceof ArrayBuffer)){this.closeEarlyDataChannel(n,"invalid_message");return}if(n.messages.length>=ll){this.closeEarlyDataChannel(n,"message_count_exceeded");return}if(n.messages.reduce((a,c)=>a+c.data.byteLength,0)+s.byteLength>fl){this.closeEarlyDataChannel(n,"byte_count_exceeded");return}n.messages.push(o)},this.earlyDataChannels.push(n)}closeEarlyDataChannel(e,r){this.log?.("closing early data channel %d - %s",e.channel.id,r),this.metrics?.increment({[`early_data_channel_${r}`]:!0}),oc(e,this.log);let n=this.earlyDataChannels.indexOf(e);n!==-1&&this.earlyDataChannels.splice(n,1)}createStreamMuxer(e){return this.handedOff=!0,this.peerConnection.removeEventListener("datachannel",this.onEarlyDataChannel),new sc(e,{peerConnection:this.peerConnection,dataChannelOptions:this.dataChannelOptions,metrics:this.metrics,protocol:this.protocol,maxEarlyStreams:this.maxEarlyStreams,earlyDataChannels:this.earlyDataChannels})}close(){if(!this.handedOff){this.peerConnection.removeEventListener("datachannel",this.onEarlyDataChannel);for(let e of this.earlyDataChannels)oc(e,this.log);this.earlyDataChannels.length=0}}},sc=class extends us{peerConnection;dataChannelOptions;constructor(e,r){super(e,{...r,name:"muxer"}),this.peerConnection=r.peerConnection,this.protocol=r.protocol??Ga,this.dataChannelOptions=r.dataChannelOptions??{},this.peerConnection.ondatachannel=({channel:n})=>{this.onDataChannel(n)},queueMicrotask(()=>{if(this.status!=="open"){r.earlyDataChannels.forEach(n=>{oc(n,this.log)});return}r.earlyDataChannels.forEach(({channel:n,messages:o})=>{try{this.onDataChannel(n,o)}catch(s){this.log.error("error adopting early data channel %d - %e",n.id,s)}})})}onDataChannel(e,r){if(this.log("incoming datachannel with channel id %d, protocol %s and status %s",e.id,e.protocol,e.readyState),e.label==="init"){this.log.trace("closing init channel %d",e.id),ic(e,this.log);return}let n=Mn({...this.streamOptions,...this.dataChannelOptions,channel:e,direction:"inbound",log:this.log});r?.forEach(o=>{e.onmessage?.(o)}),this.onRemoteStream(n)}async onCreateStream(e){let r=this.peerConnection.createDataChannel("",{});return this.log("open channel %d for protocol %s",r.id,e?.protocol),Mn({...e,...this.dataChannelOptions,channel:r,direction:"outbound",log:this.log})}onData(){}};var ac=class extends fs{peerConnection;constructor(e){super(e),this.peerConnection=e.peerConnection;let r=e.peerConnection.connectionState;this.peerConnection.onconnectionstatechange=()=>{this.log.trace("peer connection state change %s initial state %s",this.peerConnection.connectionState,r),(this.peerConnection.connectionState==="failed"||this.peerConnection.connectionState==="closed")&&(this.onTransportClosed(),this.peerConnection.close())}}sendData(e){return{sentBytes:e.byteLength,canSendMore:!0}}async sendClose(e){this.peerConnection.close(),e?.signal?.throwIfAborted()}sendReset(){this.peerConnection.close()}sendPause(){}sendResume(){}},Fn=t=>new ac(t);async function cc(t){return t=t??{},typeof t=="function"&&(t=await t()),t.iceServers=t.iceServers??il.map(e=>({urls:[e]})),t}var gl=(t=32)=>al+[...Array(t)].map(()=>Wa.at(Math.floor(Math.random()*Wa.length))).join("");var Es=globalThis.RTCPeerConnection,Ss=globalThis.RTCSessionDescription,bl=globalThis.RTCIceCandidate;var ze=class extends Event{type;detail;constructor(e,r){super(e),this.type=e,this.detail=r}};var Vt=class extends Error{constructor(e){super(`WebRTC transport error: ${e}`),this.name="WebRTCTransportError"}},Ye=class extends Vt{constructor(e="SDP handshake failed"){super(e),this.name="SDPHandshakeFailedError"}};var As=class extends Vt{constructor(e,r){super(`Invalid fingerprint "${e}" within ${r}`),this.name="WebRTC/InvalidFingerprintError"}};var vs=class extends Vt{constructor(e){super(`A method (${e}) was called though it has been intentionally left unimplemented.`),this.name="WebRTC/UnimplementedError"}},Cs=class extends Vt{constructor(e){super(`unsupported hash algorithm code: ${e} please see the codes at https://github.com/multiformats/multicodec/blob/master/table.csv `),this.name="WebRTC/UnsupportedHashAlgorithmError"}};var He;(function(t){let e;(function(a){a.SDP_OFFER="SDP_OFFER",a.SDP_ANSWER="SDP_ANSWER",a.ICE_CANDIDATE="ICE_CANDIDATE"})(e=t.Type||(t.Type={}));let r;(function(a){a[a.SDP_OFFER=0]="SDP_OFFER",a[a.SDP_ANSWER=1]="SDP_ANSWER",a[a.ICE_CANDIDATE=2]="ICE_CANDIDATE"})(r||(r={})),(function(a){a.codec=()=>sr(r)})(e=t.Type||(t.Type={}));let n;t.codec=()=>(n==null&&(n=ot((a,c,f={})=>{f.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),t.Type.codec().encode(a.type,c)),a.data!=null&&(c.uint32(18),c.string(a.data)),f.lengthDelimited!==!1&&c.ldelim()},(a,c,f={})=>{let u={},l=c==null?a.len:a.pos+c;for(;a.pos<l;){let h=a.uint32();switch(h>>>3){case 1:{u.type=t.Type.codec().decode(a);break}case 2:{u.data=a.string();break}default:{a.skipType(h&7);break}}}return u},function*(a,c,f,u={}){let l=c==null?a.len:a.pos+c;for(;a.pos<l;){let h=a.uint32();switch(h>>>3){case 1:{yield{field:`${f}.type`,value:t.Type.codec().decode(a)};break}case 2:{yield{field:`${f}.data`,value:a.string()};break}default:{a.skipType(h&7);break}}}})),n);function o(a){return rt(a,t.codec())}t.encode=o;function s(a,c){return tt(a,t.codec(),c)}t.decode=s;function i(a,c){return nt(a,t.codec(),c)}t.stream=i})(He||(He={}));var _s=async(t,e,r)=>{try{let n=Promise.withResolvers();for(ny(t,n);;){let o=await Promise.race([n.promise,e.read({signal:r.signal})]);if(o==null){r.signal?.throwIfAborted();break}if(o.type!==He.Type.ICE_CANDIDATE)throw new eo("ICE candidate message expected");let s=JSON.parse(o.data??"null");if(s===""||s===null){r.onProgress?.(new ze("webrtc:end-of-ice-candidates")),r.log.trace("end-of-candidates received");continue}let i=new bl(s);r.log.trace("%s received new ICE candidate %o",r.direction,s);try{r.onProgress?.(new ze("webrtc:add-ice-candidate",i.candidate)),await t.addIceCandidate(i)}catch(a){r.log.error("%s bad candidate received %o - %e",r.direction,s,a)}}}catch(n){if(r.log.error("%s error parsing ICE candidate - %e",r.direction,n),r.signal?.aborted===!0&&t.connectionState!=="connected")throw n}};function ny(t,e){if(t.connectionState==="connected"){e.resolve();return}t.onconnectionstatechange=r=>{switch(t.connectionState){case"connected":e.resolve();break;case"failed":case"closed":e.reject(new Yn(`RTCPeerConnection connection state became "${t.connectionState}"`));break;default:break}}}function Ts(t){let e;for(let r of t.getComponents())r.name==="p2p"&&(e=Nr(r.value??""));if(e==null)throw new Zn("Remote peerId must be present in multiaddr");return e}async function wl({rtcConfiguration:t,dataChannel:e,maxEarlyStreams:r,signal:n,metrics:o,multiaddr:s,connectionManager:i,transportManager:a,log:c,logger:f,onProgress:u}){let{circuitAddress:l,targetPeer:h}=xl(s);o?.dialerEvents.increment({open:!0}),c.trace("dialing circuit address: %a",l);let p=i.getConnections(h),x;p.length===0?(u?.(new ze("webrtc:dial-relay")),x=await a.dial(l,{signal:n,onProgress:u})):(u?.(new ze("webrtc:reuse-relay-connection")),x=p[0]),u?.(new ze("webrtc:open-signaling-stream"));let w=await x.newStream(On,{signal:n,runOnLimitedConnection:!0}),m=ps(w).pb(He),g=new Es(t);g.addEventListener("connectionstatechange",()=>{g.connectionState==="closed"&&g.close()});let E=new qt({peerConnection:g,dataChannelOptions:e,maxEarlyStreams:r,metrics:o?.dialerEvents,log:c});try{let b=g.createDataChannel("init");g.onicecandidate=({candidate:R})=>{if(g.connectionState==="connected"){c.trace("ignore new ice candidate as peer connection is already connected");return}if(R==null||R?.candidate===""){c.trace("initiator detected end of ICE candidates");return}let N=JSON.stringify(R?.toJSON()??null);c.trace("initiator sending ICE candidate %o",R),m.write({type:He.Type.ICE_CANDIDATE,data:N},{signal:n}).catch(B=>{c.error("error sending ICE candidate - %e",B)})},g.onicecandidateerror=R=>{c.error("initiator ICE candidate error",R)};let L=await g.createOffer().catch(R=>{throw c.error("could not execute createOffer - %e",R),new Ye("Failed to set createOffer")});c.trace("initiator send SDP offer %s",L.sdp),u?.(new ze("webrtc:send-sdp-offer")),await m.write({type:He.Type.SDP_OFFER,data:L.sdp},{signal:n}),await g.setLocalDescription(L).catch(R=>{throw c.error("could not execute setLocalDescription - %e",R),new Ye("Failed to set localDescription")}),u?.(new ze("webrtc:read-sdp-answer")),c.trace("initiator read SDP answer");let C=await m.read({signal:n});if(C.type!==He.Type.SDP_ANSWER)throw new Ye("Remote should send an SDP answer");c.trace("initiator received SDP answer %s",C.data);let O=new Ss({type:"answer",sdp:C.data});return await g.setRemoteDescription(O).catch(R=>{throw c.error("could not execute setRemoteDescription - %e",R),new Ye("Failed to set remoteDescription")}),c.trace("initiator read candidates until connected"),u?.(new ze("webrtc:read-ice-candidates")),await _s(g,m,{direction:"initiator",signal:n,log:c,onProgress:u}),c.trace("initiator connected"),b.readyState!=="open"&&(c.trace("wait for init channel to open"),await Te(b,"open",{signal:n})),c.trace("closing init channel"),b.close(),c.trace("waiting for init channel to close"),await Te(b,"close",{signal:n}),u?.(new ze("webrtc:close-signaling-stream")),c.trace("closing signaling channel"),await w.close({signal:n}),c.trace("initiator connected to remote address %s",s),{remoteAddress:s,peerConnection:g,muxerFactory:E}}catch(b){throw c.error("outgoing signaling error - %e",b),E.close(),g.close(),w.abort(b),b}finally{g.onicecandidate=null,g.onicecandidateerror=null}}var El=ce(ol.matchers[0],ae(290)),Ls=class t extends Tt{transportManager;shutdownController;events;constructor(e,r){super(),this.transportManager=e.transportManager,this.events=e.events,this.shutdownController=r.shutdownController,this.onTransportListening=this.onTransportListening.bind(this)}async listen(){this.events.addEventListener("transport:listening",this.onTransportListening)}onTransportListening(e){e.detail.getAddrs().filter(n=>El.exactMatch(n)).map(n=>n.encapsulate("/webrtc")).length>0&&this.safeDispatchEvent("listening")}getAddrs(){return this.transportManager.getListeners().filter(e=>!(e instanceof t)).map(e=>e.getAddrs().filter(r=>El.exactMatch(r)).map(r=>r.encapsulate("/webrtc"))).flat()}updateAnnounceAddrs(){}async close(){this.events.removeEventListener("transport:listening",this.onTransportListening),this.shutdownController.abort(),queueMicrotask(()=>{this.safeDispatchEvent("close")})}};async function Sl(t,e,{peerConnection:r,signal:n,log:o}){o.trace("new inbound signaling stream");let s=ps(t).pb(He);try{r.onicecandidate=({candidate:l})=>{if(r.connectionState==="connected"){o.trace("ignore new ice candidate as peer connection is already connected");return}if(l==null||l?.candidate===""){o.trace("recipient detected end of ICE candidates");return}let h=JSON.stringify(l?.toJSON()??null);o.trace("recipient sending ICE candidate %s",h),s.write({type:He.Type.ICE_CANDIDATE,data:h},{signal:n}).catch(p=>{o.error("error sending ICE candidate - %e",p)})},o.trace("recipient read SDP offer");let c=await s.read({signal:n});if(c.type!==He.Type.SDP_OFFER)throw new Ye(`expected message type SDP_OFFER, received: ${c.type??"undefined"} `);o.trace("recipient received SDP offer %s",c.data);let f=new Ss({type:"offer",sdp:c.data});await r.setRemoteDescription(f).catch(l=>{throw o.error("could not execute setRemoteDescription - %e",l),new Ye("Failed to set remoteDescription")});let u=await r.createAnswer().catch(l=>{throw o.error("could not execute createAnswer - %e",l),new Ye("Failed to create answer")});o.trace("recipient send SDP answer %s",u.sdp),await s.write({type:He.Type.SDP_ANSWER,data:u.sdp},{signal:n}),await r.setLocalDescription(u).catch(l=>{throw o.error("could not execute setLocalDescription - %e",l),new Ye("Failed to set localDescription")}),o.trace("recipient read candidates until connected"),await _s(r,s,{direction:"recipient",signal:n,log:o})}catch(c){if(r.connectionState!=="connected")throw o.error("error while handling signaling stream from peer %a - %e",e.remoteAddr,c),r.close(),c;o("error while handling signaling stream from peer %a, ignoring as the RTCPeerConnection is already connected",e.remoteAddr,c)}let i=Ts(e.remoteAddr),a=Kr(`/webrtc/p2p/${i}`);return o.trace("recipient connected to remote address %s",a),{remoteAddress:a,remotePeer:i}}var Bs=class{components;init;log;_started=!1;metrics;shutdownController;constructor(e,r={}){this.components=e,this.init=r,this.log=e.logger.forComponent("libp2p:webrtc"),this.shutdownController=new AbortController,this.shutdownController.signal,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc_dialer_events_total",{label:"event",help:"Total count of WebRTC dialer events by type"}),listenerEvents:e.metrics.registerCounterGroup("libp2p_webrtc_listener_events_total",{label:"event",help:"Total count of WebRTC listener events by type"})})}[oo]=!0;[Symbol.toStringTag]="@libp2p/webrtc";[wr]=["@libp2p/transport"];[Ic]=["@libp2p/identify","@libp2p/circuit-relay-v2-transport"];isStarted(){return this._started}async start(){await this.components.registrar.handle(On,(e,r)=>{let n=this.components.upgrader.createInboundAbortSignal(this.shutdownController.signal);this._onProtocol(e,r,n).catch(o=>{this.log.error("failed to handle incoming connect from %p - %e",r.remotePeer,o)}).finally(()=>{n.clear()})},{runOnLimitedConnection:!0}),this._started=!0}async stop(){await this.components.registrar.unhandle(On),this._started=!1}createListener(e){return new Ls(this.components,{shutdownController:this.shutdownController})}listenFilter(e){return e.filter(sl.exactMatch)}dialFilter(e){return this.listenFilter(e)}async dial(e,r){this.log.trace("dialing address: %a",e);let{remoteAddress:n,peerConnection:o,muxerFactory:s}=await wl({rtcConfiguration:await cc(this.init.rtcConfiguration),dataChannel:this.init.dataChannel,maxEarlyStreams:this.init.maxEarlyStreams,multiaddr:e,dataChannelOptions:this.init.dataChannel,signal:r.signal,connectionManager:this.components.connectionManager,transportManager:this.components.transportManager,metrics:this.metrics,log:this.log,logger:this.components.logger,onProgress:r.onProgress}),i=Fn({peerConnection:o,remoteAddr:n,metrics:this.metrics?.dialerEvents,direction:"outbound",log:this.components.logger.forComponent("libp2p:webrtc:connection")}),a;try{a=await r.upgrader.upgradeOutbound(i,{skipProtection:!0,skipEncryption:!0,remotePeer:Ts(e),muxerFactory:s,onProgress:r.onProgress,signal:r.signal})}catch(c){throw s.close(),o.close(),c}return this._closeOnShutdown(o,i),a}async _onProtocol(e,r,n){let o=new Es(await cc(this.init.rtcConfiguration));o.addEventListener("connectionstatechange",()=>{o.connectionState==="closed"&&o.close()});let s=new qt({peerConnection:o,dataChannelOptions:this.init.dataChannel,maxEarlyStreams:this.init.maxEarlyStreams,metrics:this.metrics?.listenerEvents,log:this.log});try{let{remoteAddress:i,remotePeer:a}=await Sl(e,r,{peerConnection:o,signal:n,log:this.log});await e.close({signal:n});let c=Fn({peerConnection:o,remoteAddr:i,metrics:this.metrics?.listenerEvents,direction:"inbound",log:this.components.logger.forComponent("libp2p:webrtc:connection")});await this.components.upgrader.upgradeInbound(c,{skipEncryption:!0,skipProtection:!0,remotePeer:a,muxerFactory:s,signal:n}),this._closeOnShutdown(o,c)}catch(i){throw this.log.error("incoming signaling error - %e",i),s.close(),o.close(),e.abort(i),i}}_closeOnShutdown(e,r){let n=()=>{r.close().catch(o=>{this.log.error("could not close WebRTCMultiaddrConnection - %e",o)})};this.shutdownController.signal.addEventListener("abort",n),e.addEventListener("close",()=>{this.shutdownController.signal.removeEventListener("abort",n)})}};function xl(t){let e=t.getComponents().filter(({name:n})=>n==="p2p").map(({value:n})=>n).pop();if(e==null)throw new J("Destination peer id was missing");return{circuitAddress:Kr(t.getComponents().filter(({name:n})=>n!=="webrtc")),targetPeer:Nr(e)}}var Vr=!!globalThis.process?.env?.DUMP_SESSION_KEYS,fc=16;function uc(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}var Ds=t=>t?`"${t}" `:"";function Is(t,e=""){if(typeof t!="boolean")throw new TypeError(Ds(e)+"expected boolean, got type="+typeof t);return t}function hr(t,e=""){if(typeof t!="number")throw new TypeError(Ds(e)+"expected number, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw new RangeError(Ds(e)+"expected integer >= 0, got "+t);return t}function be(t,e,r=""){if(uc(t)&&(e===void 0||t.length===e))return t;e!==void 0&&hr(e,"length");let n=uc(t),o=e!==void 0?` of length ${e}`:"",s=n?`length=${t.length}`:`type=${typeof t}`,i=Ds(r)+"expected Uint8Array"+o+", got "+s;throw n?new RangeError(i):new TypeError(i)}var Al=(t,e)=>{if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof t}`)};function lc(t,e=!0){if(t.destroyed)throw new Error("hash was destroyed");if(e&&t.finished)throw new Error("digest() was already called")}function vl(t,e){be(t,void 0,"output");let r=e.outputLen;if(!(t.length>=r))throw new RangeError('"output" expected length >= '+r)}function ht(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function st(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function oy(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}var jt=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function sy(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function iy(t){for(let e=0;e<t.length;e++)t[e]=sy(t[e]);return t}var Ct=jt?t=>t:iy;function ay(t,e){return!t.byteLength||!e.byteLength?!1:t.buffer===e.buffer&&t.byteOffset<e.byteOffset+e.byteLength&&e.byteOffset<t.byteOffset+t.byteLength}function Cl(t,e){if(ay(t,e)&&t.byteOffset<e.byteOffset)throw new Error("complex overlap of input and output is not supported")}function _l(t,e){return Al(t,"defaults"),Al(e,"opts"),Object.assign(t,e)}function Tl(t,e){if(t=be(t),e=be(e),t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}function Ll(t,e,r){let n=e,o=r||(()=>[]),s=(a,c)=>n(c,...o(a)).update(a).digest(),i=n(new Uint8Array(t),...o(new Uint8Array(0)));return s.outputLen=i.outputLen,s.blockLen=i.blockLen,s.create=(a,...c)=>n(a,...c),s}var Bl=(t,e)=>{function r(n,...o){if(be(n,void 0,"key"),t.nonceLength!==void 0){let l=o[0];be(l,t.varSizeNonce?void 0:t.nonceLength,"nonce")}let s=t.tagLength,i=t.nonceLength!==void 0?1:0;if(!t.withAAD){for(let l=i;l<o.length;l++)if(uc(o[l]))throw new Error("AAD not supported")}t.withAAD&&o[i]!==void 0&&be(o[i],void 0,"AAD");let a=e(n,...o),c=(l,h)=>{if(h!==void 0){if(l!==2)throw new Error("cipher output not supported");be(h,void 0,"output")}},f=!1;return{encrypt(l,h){if(f)throw new Error("cannot encrypt() twice with same key + nonce");return f=!0,be(l,void 0,"data"),c(a.encrypt.length,h),a.encrypt(l,h)},decrypt(l,h){if(be(l,void 0,"data"),s&&l.length<s)throw new Error('"ciphertext" expected length >= tagLength='+s);return c(a.decrypt.length,h),a.decrypt(l,h)}}}return Object.assign(r,t),r};function Kn(t,e,r=!0){if(e===void 0)return new Uint8Array(t);if(be(e,t,"output"),r&&!Hn(e))throw new Error("invalid output, must be aligned");return e}function Dl(t,e,r){hr(t),hr(e),Is(r);let n=new Uint8Array(16),o=oy(n);return o.setBigUint64(0,BigInt(e),r),o.setBigUint64(8,BigInt(t),r),n}function Hn(t){return t.byteOffset%4===0}function jr(t){return Uint8Array.from(be(t))}var Rl=t=>Uint8Array.from(t.split(""),e=>e.charCodeAt(0)),cy=Ct(ht(Rl("expand 16-byte k"))),fy=Ct(ht(Rl("expand 32-byte k")));function ee(t,e){return t<<e|t>>>32-e}var $n=64,uy=16,dc=2**32-1,Il=Uint32Array.of();function ly(t,e,r,n,o,s,i,a){let c=o.length,f=new Uint8Array($n),u=ht(f),l=jt&&Hn(o)&&Hn(s),h=l?ht(o):Il,p=l?ht(s):Il;if(!jt){for(let x=0;x<c;i++){if(t(e,r,n,u,i,a),Ct(u),i>=dc)throw new Error("arx: counter overflow");let w=Math.min($n,c-x);for(let m=0,g;m<w;m++)g=x+m,s[g]=o[g]^f[m];x+=w}return}for(let x=0;x<c;i++){if(t(e,r,n,u,i,a),i>=dc)throw new Error("arx: counter overflow");let w=Math.min($n,c-x);if(l&&w===$n){let m=x/4;if(x%4!==0)throw new Error("arx: invalid block position");for(let g=0,E;g<uy;g++)E=m+g,p[E]=h[E]^u[g];x+=$n;continue}for(let m=0,g;m<w;m++)g=x+m,s[g]=o[g]^f[m];x+=w}}function Ol(t,e){let{allowShortKeys:r,extendNonceFn:n,counterLength:o,counterRight:s,rounds:i}=_l({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return hr(o),hr(i),Is(s),Is(r),(a,c,f,u,l=0)=>{be(a,void 0,"key"),be(c,void 0,"nonce"),be(f,void 0,"data");let h=f.length,p=u!==void 0;if(u=Kn(h,u,!1),p&&Cl(f,u),hr(l),l<0||l>=dc)throw new Error("arx: counter overflow");let x=[],w=a.length,m,g;if(w===32)x.push(m=jr(a)),g=fy;else if(w===16&&r)m=new Uint8Array(32),m.set(a),m.set(a,16),g=cy,x.push(m);else throw be(a,32,"arx key"),new Error("invalid key size");(!jt||!Hn(c))&&x.push(c=jr(c));let E=ht(m);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");let C=c.subarray(0,16);if(jt)n(g,E,ht(C),E);else{let O=Ct(Uint32Array.from(g));n(O,E,ht(C),E),st(O),Ct(E)}c=c.subarray(16)}else jt||Ct(E);let b=16-o;if(b!==c.length)throw new Error(`arx: nonce must be ${b} or 16 bytes`);if(b!==12){let C=new Uint8Array(12);C.set(c,s?0:12-c.length),c=C,x.push(c)}let L=Ct(ht(c));try{return ly(t,g,E,L,f,u,l,i),u}finally{st(...x)}}}function Le(t,e){return t[e++]&255|(t[e++]&255)<<8}var hc=class{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;destroyed=!1;constructor(e){e=jr(be(e,32,"key"));let r=Le(e,0),n=Le(e,2),o=Le(e,4),s=Le(e,6),i=Le(e,8),a=Le(e,10),c=Le(e,12),f=Le(e,14);this.r[0]=r&8191,this.r[1]=(r>>>13|n<<3)&8191,this.r[2]=(n>>>10|o<<6)&7939,this.r[3]=(o>>>7|s<<9)&8191,this.r[4]=(s>>>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]=Le(e,16+2*u)}process(e,r,n=!1){let o=n?0:2048,{h:s,r:i}=this,a=i[0],c=i[1],f=i[2],u=i[3],l=i[4],h=i[5],p=i[6],x=i[7],w=i[8],m=i[9],g=Le(e,r+0),E=Le(e,r+2),b=Le(e,r+4),L=Le(e,r+6),C=Le(e,r+8),O=Le(e,r+10),R=Le(e,r+12),N=Le(e,r+14),B=s[0]+(g&8191),I=s[1]+((g>>>13|E<<3)&8191),K=s[2]+((E>>>10|b<<6)&8191),F=s[3]+((b>>>7|L<<9)&8191),q=s[4]+((L>>>4|C<<12)&8191),_=s[5]+(C>>>1&8191),U=s[6]+((C>>>14|O<<2)&8191),T=s[7]+((O>>>11|R<<5)&8191),v=s[8]+((R>>>8|N<<8)&8191),H=s[9]+(N>>>5|o),D=0,S=D+B*a+I*(5*m)+K*(5*w)+F*(5*x)+q*(5*p);D=S>>>13,S&=8191,S+=_*(5*h)+U*(5*l)+T*(5*u)+v*(5*f)+H*(5*c),D+=S>>>13,S&=8191;let d=D+B*c+I*a+K*(5*m)+F*(5*w)+q*(5*x);D=d>>>13,d&=8191,d+=_*(5*p)+U*(5*h)+T*(5*l)+v*(5*u)+H*(5*f),D+=d>>>13,d&=8191;let y=D+B*f+I*c+K*a+F*(5*m)+q*(5*w);D=y>>>13,y&=8191,y+=_*(5*x)+U*(5*p)+T*(5*h)+v*(5*l)+H*(5*u),D+=y>>>13,y&=8191;let A=D+B*u+I*f+K*c+F*a+q*(5*m);D=A>>>13,A&=8191,A+=_*(5*w)+U*(5*x)+T*(5*p)+v*(5*h)+H*(5*l),D+=A>>>13,A&=8191;let P=D+B*l+I*u+K*f+F*c+q*a;D=P>>>13,P&=8191,P+=_*(5*m)+U*(5*w)+T*(5*x)+v*(5*p)+H*(5*h),D+=P>>>13,P&=8191;let k=D+B*h+I*l+K*u+F*f+q*c;D=k>>>13,k&=8191,k+=_*a+U*(5*m)+T*(5*w)+v*(5*x)+H*(5*p),D+=k>>>13,k&=8191;let M=D+B*p+I*h+K*l+F*u+q*f;D=M>>>13,M&=8191,M+=_*c+U*a+T*(5*m)+v*(5*w)+H*(5*x),D+=M>>>13,M&=8191;let $=D+B*x+I*p+K*h+F*l+q*u;D=$>>>13,$&=8191,$+=_*f+U*c+T*a+v*(5*m)+H*(5*w),D+=$>>>13,$&=8191;let z=D+B*w+I*x+K*p+F*h+q*l;D=z>>>13,z&=8191,z+=_*u+U*f+T*c+v*a+H*(5*m),D+=z>>>13,z&=8191;let j=D+B*m+I*w+K*x+F*p+q*h;D=j>>>13,j&=8191,j+=_*l+U*u+T*f+v*c+H*a,D+=j>>>13,j&=8191,D=(D<<2)+D|0,D=D+S|0,S=D&8191,D=D>>>13,d+=D,s[0]=S,s[1]=d,s[2]=y,s[3]=A,s[4]=P,s[5]=k,s[6]=M,s[7]=$,s[8]=z,s[9]=j}finalize(){let{h:e,pad:r}=this,n=new Uint16Array(10),o=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=o,o=e[a]>>>13,e[a]&=8191;e[0]+=o*5,o=e[0]>>>13,e[0]&=8191,e[1]+=o,o=e[1]>>>13,e[1]&=8191,e[2]+=o,n[0]=e[0]+5,o=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=e[a]+o,o=n[a]>>>13,n[a]&=8191;n[9]-=8192;let s=(o^1)-1;for(let a=0;a<10;a++)n[a]&=s;s=~s;for(let a=0;a<10;a++)e[a]=e[a]&s|n[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let i=e[0]+r[0];e[0]=i&65535;for(let a=1;a<8;a++)i=(e[a]+r[a]|0)+(i>>>16)|0,e[a]=i&65535;st(n)}update(e){lc(this),be(e),e=jr(e);let{buffer:r,blockLen:n}=this,o=e.length;for(let s=0;s<o;){let i=Math.min(n-this.pos,o-s);if(i===n){for(;n<=o-s;s+=n)this.process(e,s);continue}r.set(e.subarray(s,s+i),this.pos),this.pos+=i,s+=i,this.pos===n&&(this.process(r,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,st(this.h,this.r,this.buffer,this.pad)}digestInto(e){lc(this),vl(e,this),this.finished=!0;let{buffer:r,h:n}=this,{pos:o}=this;if(o){for(r[o++]=1;o<16;o++)r[o]=0;this.process(r,0,!0)}this.finalize();let s=0;for(let i=0;i<8;i++)e[s++]=n[i]>>>0,e[s++]=n[i]>>>8}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}},Pl=Ll(32,t=>new hc(t));function dy(t,e,r,n,o,s=20){let i=t[0],a=t[1],c=t[2],f=t[3],u=e[0],l=e[1],h=e[2],p=e[3],x=e[4],w=e[5],m=e[6],g=e[7],E=o,b=r[0],L=r[1],C=r[2],O=i,R=a,N=c,B=f,I=u,K=l,F=h,q=p,_=x,U=w,T=m,v=g,H=E,D=b,S=L,d=C;for(let A=0;A<s;A+=2)O=O+I|0,H=ee(H^O,16),_=_+H|0,I=ee(I^_,12),O=O+I|0,H=ee(H^O,8),_=_+H|0,I=ee(I^_,7),R=R+K|0,D=ee(D^R,16),U=U+D|0,K=ee(K^U,12),R=R+K|0,D=ee(D^R,8),U=U+D|0,K=ee(K^U,7),N=N+F|0,S=ee(S^N,16),T=T+S|0,F=ee(F^T,12),N=N+F|0,S=ee(S^N,8),T=T+S|0,F=ee(F^T,7),B=B+q|0,d=ee(d^B,16),v=v+d|0,q=ee(q^v,12),B=B+q|0,d=ee(d^B,8),v=v+d|0,q=ee(q^v,7),O=O+K|0,d=ee(d^O,16),T=T+d|0,K=ee(K^T,12),O=O+K|0,d=ee(d^O,8),T=T+d|0,K=ee(K^T,7),R=R+F|0,H=ee(H^R,16),v=v+H|0,F=ee(F^v,12),R=R+F|0,H=ee(H^R,8),v=v+H|0,F=ee(F^v,7),N=N+q|0,D=ee(D^N,16),_=_+D|0,q=ee(q^_,12),N=N+q|0,D=ee(D^N,8),_=_+D|0,q=ee(q^_,7),B=B+I|0,S=ee(S^B,16),U=U+S|0,I=ee(I^U,12),B=B+I|0,S=ee(S^B,8),U=U+S|0,I=ee(I^U,7);let y=0;n[y++]=i+O|0,n[y++]=a+R|0,n[y++]=c+N|0,n[y++]=f+B|0,n[y++]=u+I|0,n[y++]=l+K|0,n[y++]=h+F|0,n[y++]=p+q|0,n[y++]=x+_|0,n[y++]=w+U|0,n[y++]=m+T|0,n[y++]=g+v|0,n[y++]=E+H|0,n[y++]=b+D|0,n[y++]=L+S|0,n[y++]=C+d|0}var hy=Ol(dy,{counterRight:!1,counterLength:4,allowShortKeys:!1});var py=new Uint8Array(16),Nl=(t,e)=>{t.update(e);let r=e.length%16;r&&t.update(py.subarray(r))},my=new Uint8Array(32);function Ul(t,e,r,n,o){o!==void 0&&be(o,void 0,"AAD");let s=t(e,r,my),i=Dl(n.length,o?o.length:0,!0),a=Pl.create(s);o&&Nl(a,o),Nl(a,n),a.update(i);let c=a.digest();return st(s,i),c}var yy=t=>(e,r,n)=>({encrypt(s,i){let a=s.length;i=Kn(a+16,i,!1),i.set(s);let c=i.subarray(0,-16);t(e,r,c,c,1);let f=Ul(t,e,r,c,n);return i.set(f,a),st(f),i},decrypt(s,i){i=Kn(s.length-16,i,!1);let a=s.subarray(0,-16),c=s.subarray(-16),f=Ul(t,e,r,a,n);if(!Tl(c,f))throw st(f),new Error("invalid tag");return i.set(s.subarray(0,-16)),t(e,r,i,i,1),st(f),i}}),pc=Bl({blockSize:64,nonceLength:12,tagLength:16,withAAD:!0},yy(hy));function kl(t,e,r){return er(t),r===void 0&&(r=new Uint8Array(t.outputLen)),vn(t,r,e)}var zn=Uint8Array.of(0),gy=Uint8Array.of();function Ml(t,e,r,n=32,o){er(t),Qe(n,"length"),ke(e,void 0,"prk");let s=t.outputLen;if(e.length<s)throw new Error('"prk" must be at least HashLen octets');if(n>255*s)throw new Error("Length must be <= 255*HashLen");let i=Math.ceil(n/s);if(r===void 0?r=gy:ke(r,void 0,"info"),!i)return o&&Ve(e),new Uint8Array;let a=o&&i===1?e:new Uint8Array(i*s),{iHash:c,oHash:f}=vn.create(t,e),u=o?e:new Uint8Array(s),l=i>1?o?.iHash||t.create():void 0;for(let p=0;p<i-1;p++){zn[0]=p+1;let x=c._cloneInto(l);p&&x.update(u),x.update(r).update(zn).digestInto(u),f._cloneInto(l).update(u).digestInto(u),a.set(u,s*p)}if(zn[0]=i,i>1&&c.update(u),c.update(r).update(zn).digestInto(u),f.update(u).digestInto(u),a.set(u,s*(i-1)),c.destroy(),f.destroy(),l?.destroy(),u!==a&&Ve(u),Ve(zn),n===a.length)return a;let h=a.slice(0,n);return Ve(a),h}var Fl={hashSHA256(t){return ct(t.subarray())},getHKDF(t,e){let r=kl(ct,e,t),o=Ml(ct,r,void 0,96),s=o.subarray(0,32),i=o.subarray(32,64),a=o.subarray(64,96);return[s,i,a]},generateX25519KeyPair(){let t=yn.utils.randomSecretKey();return{publicKey:yn.getPublicKey(t),privateKey:t}},generateX25519KeyPairFromSeed(t){return{publicKey:yn.getPublicKey(t),privateKey:t}},generateX25519SharedKey(t,e){return yn.getSharedSecret(t.subarray(),e.subarray())},chaCha20Poly1305Encrypt(t,e,r,n){return pc(n,e,r).encrypt(t.subarray())},chaCha20Poly1305Decrypt(t,e,r,n,o){return pc(n,e,r).decrypt(t.subarray(),o)}};var Kl=Fl;function Hl(t){return{generateKeypair:t.generateX25519KeyPair,dh:(e,r)=>t.generateX25519SharedKey(e.privateKey,r).subarray(0,32),encrypt:t.chaCha20Poly1305Encrypt,decrypt:t.chaCha20Poly1305Decrypt,hash:t.hashSHA256,hkdf:t.getHKDF}}var Wr=t=>{let e=xe(2);return e[0]=t>>8,e[1]=t,e};Wr.bytes=2;var Gr=t=>{if(t.length<2)throw RangeError("Could not decode int16BE");if(t instanceof Uint8Array){let e=0;return e+=t[0]<<8,e+=t[1],e}return t.getUint16(0)};Gr.bytes=2;function $l(t){return{xxHandshakeSuccesses:t.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:t.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:t.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:t.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:t.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}function mc(t,e){!e.enabled||!Vr||(t?(e(`LOCAL_STATIC_PUBLIC_KEY ${W(t.publicKey,"hex")}`),e(`LOCAL_STATIC_PRIVATE_KEY ${W(t.privateKey,"hex")}`)):e("Missing local static keys."))}function yc(t,e){!e.enabled||!Vr||(t?(e(`LOCAL_PUBLIC_EPHEMERAL_KEY ${W(t.publicKey,"hex")}`),e(`LOCAL_PRIVATE_EPHEMERAL_KEY ${W(t.privateKey,"hex")}`)):e("Missing local ephemeral keys."))}function zl(t,e){!e.enabled||!Vr||e(t?`REMOTE_STATIC_PUBLIC_KEY ${W(t.subarray(),"hex")}`:"Missing remote static public key.")}function gc(t,e){!e.enabled||!Vr||e(t?`REMOTE_EPHEMERAL_PUBLIC_KEY ${W(t.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function bc(t,e,r){!r.enabled||!Vr||(r(`CIPHER_STATE_1 ${t.n.getUint64()} ${t.k&&W(t.k,"hex")}`),r(`CIPHER_STATE_2 ${e.n.getUint64()} ${e.k&&W(e.k,"hex")}`))}var Yr=class t extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=t.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};var by=0,wy=4294967295,xy="Cipherstate has reached maximum n, a new handshake must be performed",Rs=class{n;bytes;view;constructor(e=by){this.n=e,this.bytes=we(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,e,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>wy)throw new Error(xy)}};var pr=we(0),Xr=class{k;n;crypto;constructor(e,r=void 0,n=0){this.crypto=e,this.k=r,this.n=new Rs(n)}hasKey(){return!!this.k}encryptWithAd(e,r){if(!this.hasKey())return r;this.n.assertValue();let n=this.crypto.encrypt(r,this.n.getBytes(),e,this.k);return this.n.increment(),n}decryptWithAd(e,r,n){if(!this.hasKey())return r;this.n.assertValue();let o=this.crypto.decrypt(r,this.n.getBytes(),e,this.k,n);return this.n.increment(),o}},wc=class{cs;ck;h;crypto;constructor(e,r){this.crypto=e;let n=Z(r,"utf-8");this.h=Ey(e,n),this.ck=this.h,this.cs=new Xr(e)}mixKey(e){let[r,n]=this.crypto.hkdf(this.ck,e);this.ck=r,this.cs=new Xr(this.crypto,n)}mixHash(e){this.h=this.crypto.hash(new Y(this.h,e))}encryptAndHash(e){let r=this.cs.encryptWithAd(this.h,e);return this.mixHash(r),r}decryptAndHash(e){let r=this.cs.decryptWithAd(this.h,e);return this.mixHash(e),r}split(){let[e,r]=this.crypto.hkdf(this.ck,pr);return[new Xr(this.crypto,e),new Xr(this.crypto,r)]}},xc=class{ss;s;e;rs;re;initiator;crypto;constructor(e){let{crypto:r,protocolName:n,prologue:o,initiator:s,s:i,e:a,rs:c,re:f}=e;this.crypto=r,this.ss=new wc(r,n),this.ss.mixHash(o),this.initiator=s,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 e=this.crypto.generateKeypair();return this.ss.mixHash(e.publicKey),this.e=e,e.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(e,r=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(e.byteLength<r+32)throw new Error("message is not long enough");this.re=e.sublist(r,r+32),this.ss.mixHash(this.re)}readS(e,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(e.byteLength<r+n)throw new Error("message is not long enough");let o=e.sublist(r,r+n);return this.rs=this.ss.decryptAndHash(o),n}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}},qn=class extends xc{writeMessageA(e){return new Y(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){let r=this.writeE();this.writeEE();let n=this.writeS();return this.writeES(),new Y(r,n,this.ss.encryptAndHash(e))}writeMessageC(e){let r=this.writeS();return this.writeSE(),new Y(r,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(r){throw new Yr(`handshake stage 0 validation fail: ${r.message}`)}}readMessageB(e){try{this.readE(e),this.readEE();let r=this.readS(e,32);return this.readES(),this.ss.decryptAndHash(e.sublist(32+r))}catch(r){throw new Yr(`handshake stage 1 validation fail: ${r.message}`)}}readMessageC(e){try{let r=this.readS(e);return this.readSE(),this.ss.decryptAndHash(e.sublist(r))}catch(r){throw new Yr(`handshake stage 2 validation fail: ${r.message}`)}}};function Ey(t,e){if(e.length<=32){let r=we(32);return r.set(e),r}else return t.hash(e)}var Vn;(function(t){let e;t.codec=()=>(e==null&&(e=ot((s,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),s.webtransportCerthashes!=null&&s.webtransportCerthashes.length>0)for(let c of s.webtransportCerthashes)i.uint32(10),i.bytes(c);if(s.streamMuxers!=null&&s.streamMuxers.length>0)for(let c of s.streamMuxers)i.uint32(18),i.string(c);a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={webtransportCerthashes:[],streamMuxers:[]},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{if(a.limits?.webtransportCerthashes!=null&&c.webtransportCerthashes.length===a.limits.webtransportCerthashes)throw new ir('Decode error - repeated field "webtransportCerthashes" had too many elements');c.webtransportCerthashes.push(s.bytes());break}case 2:{if(a.limits?.streamMuxers!=null&&c.streamMuxers.length===a.limits.streamMuxers)throw new ir('Decode error - repeated field "streamMuxers" had too many elements');c.streamMuxers.push(s.string());break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let f={webtransportCerthashes:0,streamMuxers:0},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{if(c.limits?.webtransportCerthashes!=null&&f.webtransportCerthashes===c.limits.webtransportCerthashes)throw new ir('Streaming decode error - repeated field "webtransportCerthashes" had too many elements');yield{field:`${a}.webtransportCerthashes[]`,index:f.webtransportCerthashes,value:s.bytes()},f.webtransportCerthashes++;break}case 2:{if(c.limits?.streamMuxers!=null&&f.streamMuxers===c.limits.streamMuxers)throw new ir('Streaming decode error - repeated field "streamMuxers" had too many elements');yield{field:`${a}.streamMuxers[]`,index:f.streamMuxers,value:s.string()},f.streamMuxers++;break}default:{s.skipType(l&7);break}}}})),e);function r(s){return rt(s,t.codec())}t.encode=r;function n(s,i){return tt(s,t.codec(),i)}t.decode=n;function o(s,i){return nt(s,t.codec(),i)}t.stream=o})(Vn||(Vn={}));var jn;(function(t){let e;t.codec=()=>(e==null&&(e=ot((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.identityKey!=null&&s.identityKey.byteLength>0&&(i.uint32(10),i.bytes(s.identityKey)),s.identitySig!=null&&s.identitySig.byteLength>0&&(i.uint32(18),i.bytes(s.identitySig)),s.extensions!=null&&(i.uint32(34),Vn.codec().encode(s.extensions,i)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={identityKey:we(0),identitySig:we(0)},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{c.identityKey=s.bytes();break}case 2:{c.identitySig=s.bytes();break}case 4:{c.extensions=Vn.codec().decode(s,s.uint32(),{limits:a.limits?.extensions});break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.identityKey`,value:s.bytes()};break}case 2:{yield{field:`${a}.identitySig`,value:s.bytes()};break}case 4:{yield*Vn.codec().stream(s,s.uint32(),`${a}.extensions`,{limits:c.limits?.extensions});break}default:{s.skipType(u&7);break}}}})),e);function r(s){return rt(s,t.codec())}t.encode=r;function n(s,i){return tt(s,t.codec(),i)}t.decode=n;function o(s,i){return nt(s,t.codec(),i)}t.stream=o})(jn||(jn={}));async function Sc(t,e,r){let n=await t.sign(Vl(e));return jn.encode({identityKey:It(t.publicKey),identitySig:n,extensions:r})}async function Ac(t,e,r){try{let n=jn.decode(t),o=Cn(n.identityKey);if(r?.equals(o)===!1)throw new Error(`Payload identity key ${o} does not match expected remote identity key ${r}`);if(!e)throw new Error("Remote static does not exist");let s=Vl(e);if(!await o.verify(s,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new Wn(n.message)}}function Vl(t){let e=Z("noise-libp2p-static-key:");return t instanceof Uint8Array?Ue([e,t],e.length+t.length):(t.prepend(e),t)}var Ec=class extends zt{stream;handshake;metrics;decoder;constructor(e,r,n){super({log:e.log,inactivityTimeout:e.inactivityTimeout,maxReadBufferLength:e.maxReadBufferLength,direction:e.direction}),this.stream=e,this.handshake=r,this.metrics=n,this.decoder=new ms({lengthDecoder:Gr,maxBufferSize:16*1024*1024,encodingLength:()=>2});let o=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",o);let s=c=>{c.error!=null?c.local===!0?this.abort(c.error):this.onRemoteReset():this.onTransportClosed()};this.stream.addEventListener("close",s);let i=()=>{this.safeDispatchEvent("drain")};this.stream.addEventListener("drain",i);let a=()=>{this.onRemoteCloseWrite()};this.stream.addEventListener("remoteCloseWrite",a)}encrypt(e){let r=new Y;for(let n=0;n<e.byteLength;n+=65519){let o=n+65519;o>e.byteLength&&(o=e.byteLength);let s;e instanceof Uint8Array?s=this.handshake.encrypt(e.subarray(n,o)):s=this.handshake.encrypt(e.sublist(n,o)),this.metrics?.encryptedPackets.increment(),r.append(Wr(s.byteLength)),r.append(s)}return r}decrypt(e){let r=new Y;for(let n=0;n<e.byteLength;n+=65535){let o=n+65535;if(o>e.byteLength&&(o=e.byteLength),o-fc<n)throw new Error("Invalid chunk");let s;e instanceof Uint8Array?s=e.subarray(n,o):s=e.sublist(n,o);let i=e.subarray(n,o-fc);try{let a=this.handshake.decrypt(s,i);this.metrics?.decryptedPackets.increment(),r.append(a)}catch(a){throw this.metrics?.decryptErrors.increment(),a}}return r}close(e){return this.stream.close(e)}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}sendReset(e){this.stream.abort(e)}sendData(e){return{sentBytes:e.byteLength,canSendMore:this.stream.send(this.encrypt(e))}}};function vc(t,e,r){return new Ec(t,e,r)}async function jl(t,e){let{log:r,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:f}=t,u=await Sc(s,a.publicKey,f),l=new qn({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});mc(l.s,r),r.trace("Stage 0 - Initiator starting to send first message."),await n.write(l.writeMessageA(pr),e),r.trace("Stage 0 - Initiator finished sending first message."),yc(l.e,r),r.trace("Stage 1 - Initiator waiting to receive first message from responder...");let h=l.readMessageB(await n.read(e));r.trace("Stage 1 - Initiator received the message."),gc(l.re,r),zl(l.rs,r),r.trace("Initiator going to check remote's signature...");let p=await Ac(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),e),r.trace("Stage 2 - Initiator sent message with signed payload.");let[x,w]=l.ss.split();return bc(x,w,r),{payload:p,encrypt:m=>x.encryptWithAd(pr,m),decrypt:(m,g)=>w.decryptWithAd(pr,m,g)}}async function Wl(t,e){let{log:r,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:f}=t,u=await Sc(s,a.publicKey,f),l=new qn({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});mc(l.s,r),r.trace("Stage 0 - Responder waiting to receive first message."),l.readMessageA(await n.read(e)),r.trace("Stage 0 - Responder received first message."),gc(l.re,r),r.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(l.writeMessageB(u),e),r.trace("Stage 1 - Responder sent the second handshake message with signed payload."),yc(l.e,r),r.trace("Stage 2 - Responder waiting for third handshake message...");let h=l.readMessageC(await n.read(e));r.trace("Stage 2 - Responder received the message, finished handshake.");let p=await Ac(h,l.rs,c),[x,w]=l.ss.split();return bc(x,w,r),{payload:p,encrypt:m=>w.encryptWithAd(pr,m),decrypt:(m,g)=>x.decryptWithAd(pr,m,g)}}var Ps=class{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;log;constructor(e,r={}){let{staticNoiseKey:n,extensions:o,crypto:s,prologueBytes:i}=r,{metrics:a}=e;this.components=e,this.log=e.logger.forComponent("libp2p:noise");let c=s??Kl;this.crypto=Hl(c),this.extensions={webtransportCerthashes:[],...o},this.metrics=a?$l(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??we(0)}[Symbol.toStringTag]="@libp2p/noise";[wr]=["@libp2p/connection-encryption","@libp2p/noise"];async secureOutbound(e,r){let n=e.log?.newScope("noise")??this.log,o=hs(e,{lengthEncoder:Wr,lengthDecoder:Gr,maxDataLength:65535}),s=await this.performHandshakeInitiator(o,this.components.privateKey,n,r?.remotePeer?.publicKey,r),i=Cn(s.payload.identityKey);return{connection:vc(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:ba(i),streamMuxer:r?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}getStreamMuxer(e){if(e==null||e.length===0)return;let r=this.components.upgrader.getStreamMuxers();if(r!=null)for(let n of e){let o=r.get(n);if(o!=null)return o}if(e.length)throw new Gn("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(e,r){let n=e.log?.newScope("noise")??this.log,o=hs(e,{lengthEncoder:Wr,lengthDecoder:Gr,maxDataLength:65535}),s=await this.performHandshakeResponder(o,this.components.privateKey,n,r?.remotePeer?.publicKey,r),i=Cn(s.payload.identityKey);return{connection:vc(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:ba(i),streamMuxer:r?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(e,r,n,o,s){let i,a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await jl({connection:e,privateKey:r,remoteIdentityKey:o,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},s),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}async performHandshakeResponder(e,r,n,o,s){let i,a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await Wl({connection:e,privateKey:r,remoteIdentityKey:o,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},s),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}};function Gl(t={}){return e=>new Ps(e,t)}var Cc=Object.values(Zt).map(t=>t.decoder).reduce((t,e)=>t.or(e)),Sy=/^a=fingerprint:(?:\w+-[0-9]+)\s(?<fingerprint>(:?[0-9a-fA-F]{2})+)$/m;function Yl(t){return t?.match(Sy)?.groups?.fingerprint}function _c(t){let r=t.getComponents().find(n=>n.code===466)?.value;if(r===void 0||r==="")throw new J(`Couldn't find a certhash component of multiaddr: ${t.toString()}`);return r}function Ay(t){return Xe.decode(Cc.decode(t))}function vy(t){let e=Ay(_c(t)),r=Cy(e.code),n=e.digest.reduce((s,i)=>s+i.toString(16).padStart(2,"0"),""),o=n.match(/.{1,2}/g);if(o==null)throw new As(n,t.toString());return`${r} ${o.join(":").toUpperCase()}`}function Xl(t){let e=t.split(":").map(o=>parseInt(o,16)),r=Uint8Array.from(e),n=Ne(pt.code,r);return Kr(`/certhash/${rn.encode(n.bytes)}`)}function Cy(t){switch(t){case 17:return"sha-1";case 18:return"sha-256";case 19:return"sha-512";default:throw new Cs(t)}}function Zl(t,e){let{host:r,port:n,type:o}=Ya(t);if(o!=="ip4"&&o!=="ip6")throw new J(`Multiaddr ${t} was not an IPv4 or IPv6 address`);let s=vy(t);return{type:"answer",sdp:`v=0
|
|
3
|
+
o=- 0 0 IN IP${o==="ip4"?4:6} ${r}
|
|
4
4
|
s=-
|
|
5
5
|
t=0 0
|
|
6
6
|
a=ice-lite
|
|
7
7
|
m=application ${n} UDP/DTLS/SCTP webrtc-datachannel
|
|
8
|
-
c=IN IP${o==="ip4"?4:6} ${
|
|
8
|
+
c=IN IP${o==="ip4"?4:6} ${r}
|
|
9
9
|
a=mid:0
|
|
10
10
|
a=ice-options:ice2
|
|
11
11
|
a=ice-ufrag:${e}
|
|
@@ -13,13 +13,13 @@ a=ice-pwd:${e}
|
|
|
13
13
|
a=fingerprint:${s}
|
|
14
14
|
a=setup:passive
|
|
15
15
|
a=sctp-port:5000
|
|
16
|
-
a=max-message-size:${
|
|
17
|
-
a=candidate:1467250027 1 UDP 1467250027 ${
|
|
16
|
+
a=max-message-size:${ur}
|
|
17
|
+
a=candidate:1467250027 1 UDP 1467250027 ${r} ${n} typ host
|
|
18
18
|
a=end-of-candidates
|
|
19
|
-
`}}function
|
|
20
|
-
o=- 0 0 IN IP${o==="ip4"?4:6} ${
|
|
19
|
+
`}}function Ql(t,e){let{host:r,port:n,type:o}=Ya(t);if(o!=="ip4"&&o!=="ip6")throw new J(`Multiaddr ${t} was not an IPv4 or IPv6 address`);return{type:"offer",sdp:`v=0
|
|
20
|
+
o=- 0 0 IN IP${o==="ip4"?4:6} ${r}
|
|
21
21
|
s=-
|
|
22
|
-
c=IN IP${o==="ip4"?4:6} ${
|
|
22
|
+
c=IN IP${o==="ip4"?4:6} ${r}
|
|
23
23
|
t=0 0
|
|
24
24
|
a=ice-options:ice2,trickle
|
|
25
25
|
m=application ${n} UDP/DTLS/SCTP webrtc-datachannel
|
|
@@ -29,15 +29,15 @@ a=ice-ufrag:${e}
|
|
|
29
29
|
a=ice-pwd:${e}
|
|
30
30
|
a=fingerprint:sha-256 00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00
|
|
31
31
|
a=sctp-port:5000
|
|
32
|
-
a=max-message-size:${
|
|
33
|
-
a=candidate:1467250027 1 UDP 1467250027 ${
|
|
32
|
+
a=max-message-size:${ur}
|
|
33
|
+
a=candidate:1467250027 1 UDP 1467250027 ${r} ${n} typ host
|
|
34
34
|
a=end-of-candidates
|
|
35
|
-
`}}function
|
|
35
|
+
`}}function Tc(t,e){if(t.sdp===void 0)throw new J("Can't munge a missing SDP");let r=t.sdp.includes(`\r
|
|
36
36
|
`)?`\r
|
|
37
37
|
`:`
|
|
38
|
-
`;try{
|
|
39
|
-
a=ice-ufrag:`+e+
|
|
40
|
-
a=ice-pwd:`+e+
|
|
38
|
+
`;try{t.sdp=t.sdp.replace(/\na=ice-ufrag:[^\n]*\n/,`
|
|
39
|
+
a=ice-ufrag:`+e+r).replace(/\na=ice-pwd:[^\n]*\n/,`
|
|
40
|
+
a=ice-pwd:`+e+r)}catch{}return t}var Lc=Z("libp2p-webrtc-noise:");function ed(t,e,r){let n=t.trim().toLowerCase().replaceAll(":",""),o=Z(n,"hex"),s=Ne(pt.code,o),i=Cc.decode(_c(e)),a=Lc.byteLength+s.bytes.byteLength+i.byteLength;return r==="server"?Ue([Lc,i,s.bytes],a):Ue([Lc,s.bytes,i],a)}function _y(t,e){return t.role==="server"}async function td(t,e,r,n){let o=t.createDataChannel("",{negotiated:!0,id:0});try{if(n.role==="client"){n.log.trace("client creating local offer");let l=await t.createOffer();n.log.trace("client created local offer %s",l.sdp);let h=Tc(l,r);n.log.trace("client setting local offer %s",h.sdp),await t.setLocalDescription(h);let p=Zl(n.remoteAddr,r);n.log.trace("client setting server description %s",p.sdp),await t.setRemoteDescription(p)}else{let l=Ql(n.remoteAddr,r);n.log.trace("server setting client %s %s",l.type,l.sdp),await t.setRemoteDescription(l),n.log.trace("server creating local answer");let h=await t.createAnswer();n.log.trace("server created local answer");let p=Tc(h,r);n.log.trace("server setting local description %s",h.sdp),await t.setLocalDescription(p)}if(o.readyState!=="open"&&(n.log.trace("%s wait for handshake channel to open, starting status %s",n.role,o.readyState),await Te(o,"open",n)),n.log.trace("%s handshake channel opened",n.role),_y(n,t)){let l=t.remoteFingerprint()?.value??"";n.remoteAddr=n.remoteAddr.encapsulate(Xl(l))}let s=Yl(t.localDescription?.sdp);if(s==null)throw new Vt("Could not get fingerprint from local description sdp");n.log.trace("%s performing noise handshake",n.role);let i=ed(s,n.remoteAddr,n.role),a=Gl({prologueBytes:i})(n),c=Mn({channel:o,direction:"outbound",isHandshake:!0,log:n.log,...n.dataChannel??{}}),f=Fn({peerConnection:t,remoteAddr:n.remoteAddr,metrics:n.events,direction:n.role==="client"?"outbound":"inbound",log:n.logger.forComponent("libp2p:webrtc-direct:connection")});if(t.addEventListener("connectionstatechange",()=>{switch(t.connectionState){case"failed":case"disconnected":case"closed":f.close().catch(l=>{n.log.error("error closing connection - %e",l),f.abort(l)});break;default:break}}),n.events?.increment({peer_connection:!0}),n.role==="client"){n.log.trace("%s secure inbound",n.role);let l=await a.secureInbound(c,{remotePeer:n.remotePeer,signal:n.signal,skipStreamMuxerNegotiation:!0});return n.log.trace("%s upgrade outbound",n.role),await n.upgrader.upgradeOutbound(f,{skipProtection:!0,skipEncryption:!0,remotePeer:l.remotePeer,muxerFactory:e,signal:n.signal})}n.log.trace("%s secure outbound",n.role);let u=await a.secureOutbound(c,{remotePeer:n.remotePeer,signal:n.signal,skipStreamMuxerNegotiation:!0});f.remoteAddr=f.remoteAddr.encapsulate(`/p2p/${u.remotePeer}`),n.log.trace("%s upgrade inbound",n.role),await n.upgrader.upgradeInbound(f,{skipProtection:!0,skipEncryption:!0,remotePeer:u.remotePeer,muxerFactory:e,signal:n.signal})}catch(s){throw e.close(),o.close(),t.close(),s}}async function rd(t,e,r={}){let n=r.certificate;n==null&&(n=await RTCPeerConnection.generateCertificate({name:"ECDSA",namedCurve:"P-256"}));let o=typeof r.rtcConfiguration=="function"?await r.rtcConfiguration():r.rtcConfiguration,s=new RTCPeerConnection({...o??{},certificates:[n]}),i=new qt({peerConnection:s,metrics:r.events,log:r.log,dataChannelOptions:r.dataChannel,maxEarlyStreams:r.maxEarlyStreams});return{peerConnection:s,muxerFactory:i}}var Ns=class{log;metrics;components;init;constructor(e,r={}){this.log=e.logger.forComponent("libp2p:webrtc-direct"),this.components=e,this.init=r,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc-direct_dialer_events_total",{label:"event",help:"Total count of WebRTC-direct dial events by type"})})}[oo]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[wr]=["@libp2p/transport"];async dial(e,r){this.log("dial %a",e),r.signal.throwIfAborted();let n,o=e.getComponents().findLast(c=>c.code===421)?.value;o!=null&&(n=Nr(o));let s=gl(),{peerConnection:i,muxerFactory:a}=await rd("client",s,{rtcConfiguration:typeof this.init.rtcConfiguration=="function"?await this.init.rtcConfiguration():this.init.rtcConfiguration??{},events:this.metrics?.dialerEvents,log:this.log,dataChannel:this.init.dataChannel,maxEarlyStreams:this.init.maxEarlyStreams});try{return await td(i,a,s,{role:"client",log:this.log,logger:this.components.logger,events:this.metrics?.dialerEvents,signal:r.signal,remoteAddr:e,dataChannel:this.init.dataChannel,upgrader:r.upgrader,peerId:this.components.peerId,remotePeer:n,privateKey:this.components.privateKey})}catch(c){throw i.close(),c}}createListener(e){throw new vs("WebRTCDirectTransport.createListener")}listenFilter(e){return[]}dialFilter(e){return e.filter(rl.exactMatch)}};function Ty(t){return e=>new Ns(e,t)}function Ly(t){return e=>new Bs(e,t)}return ud(By);})();
|
|
41
41
|
/*! Bundled license information:
|
|
42
42
|
|
|
43
43
|
@noble/curves/utils.js:
|