@libp2p/webrtc 6.0.27 → 6.0.28

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.
Files changed (54) hide show
  1. package/dist/index.min.js +6 -6
  2. package/dist/index.min.js.map +3 -3
  3. package/dist/src/constants.d.ts +28 -0
  4. package/dist/src/constants.d.ts.map +1 -1
  5. package/dist/src/constants.js +28 -0
  6. package/dist/src/constants.js.map +1 -1
  7. package/dist/src/muxer.d.ts +36 -4
  8. package/dist/src/muxer.d.ts.map +1 -1
  9. package/dist/src/muxer.js +115 -8
  10. package/dist/src/muxer.js.map +1 -1
  11. package/dist/src/private-to-private/initiate-connection.d.ts +2 -1
  12. package/dist/src/private-to-private/initiate-connection.d.ts.map +1 -1
  13. package/dist/src/private-to-private/initiate-connection.js +6 -2
  14. package/dist/src/private-to-private/initiate-connection.js.map +1 -1
  15. package/dist/src/private-to-private/transport.d.ts +7 -0
  16. package/dist/src/private-to-private/transport.d.ts.map +1 -1
  17. package/dist/src/private-to-private/transport.js +25 -9
  18. package/dist/src/private-to-private/transport.js.map +1 -1
  19. package/dist/src/private-to-public/listener.d.ts +1 -0
  20. package/dist/src/private-to-public/listener.d.ts.map +1 -1
  21. package/dist/src/private-to-public/listener.js +3 -1
  22. package/dist/src/private-to-public/listener.js.map +1 -1
  23. package/dist/src/private-to-public/transport.browser.d.ts +7 -0
  24. package/dist/src/private-to-public/transport.browser.d.ts.map +1 -1
  25. package/dist/src/private-to-public/transport.browser.js +4 -1
  26. package/dist/src/private-to-public/transport.browser.js.map +1 -1
  27. package/dist/src/private-to-public/utils/connect.js +2 -0
  28. package/dist/src/private-to-public/utils/connect.js.map +1 -1
  29. package/dist/src/private-to-public/utils/get-rtcpeerconnection.browser.d.ts.map +1 -1
  30. package/dist/src/private-to-public/utils/get-rtcpeerconnection.browser.js +3 -1
  31. package/dist/src/private-to-public/utils/get-rtcpeerconnection.browser.js.map +1 -1
  32. package/dist/src/private-to-public/utils/get-rtcpeerconnection.d.ts +4 -1
  33. package/dist/src/private-to-public/utils/get-rtcpeerconnection.d.ts.map +1 -1
  34. package/dist/src/private-to-public/utils/get-rtcpeerconnection.js +21 -13
  35. package/dist/src/private-to-public/utils/get-rtcpeerconnection.js.map +1 -1
  36. package/dist/src/private-to-public/utils/stun-listener.d.ts.map +1 -1
  37. package/dist/src/private-to-public/utils/stun-listener.js +2 -5
  38. package/dist/src/private-to-public/utils/stun-listener.js.map +1 -1
  39. package/dist/src/util.d.ts +4 -2
  40. package/dist/src/util.d.ts.map +1 -1
  41. package/dist/src/util.js +21 -0
  42. package/dist/src/util.js.map +1 -1
  43. package/package.json +8 -8
  44. package/src/constants.ts +31 -0
  45. package/src/muxer.ts +160 -13
  46. package/src/private-to-private/initiate-connection.ts +7 -2
  47. package/src/private-to-private/transport.ts +33 -9
  48. package/src/private-to-public/listener.ts +4 -1
  49. package/src/private-to-public/transport.browser.ts +12 -1
  50. package/src/private-to-public/utils/connect.ts +2 -0
  51. package/src/private-to-public/utils/get-rtcpeerconnection.browser.ts +3 -1
  52. package/src/private-to-public/utils/get-rtcpeerconnection.ts +27 -14
  53. package/src/private-to-public/utils/stun-listener.ts +2 -7
  54. package/src/util.ts +29 -2
package/dist/index.min.js CHANGED
@@ -1,5 +1,5 @@
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 wi=Object.defineProperty;var Jd=Object.getOwnPropertyDescriptor;var Qd=Object.getOwnPropertyNames;var ep=Object.prototype.hasOwnProperty;var re=(r,e)=>{for(var t in e)wi(r,t,{get:e[t],enumerable:!0})},tp=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Qd(e))!ep.call(r,o)&&o!==t&&wi(r,o,{get:()=>e[o],enumerable:!(n=Jd(e,o))||n.enumerable});return r};var rp=r=>tp(wi({},"__esModule",{value:!0}),r);var Bb={};re(Bb,{webRTC:()=>Ib,webRTCDirect:()=>_b});var Do=class extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}},Ro=class extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}},$=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Tr=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var Oo=class extends Error{static name="ConnectionFailedError";constructor(e="Connection failed"){super(e),this.name="ConnectionFailedError"}},Po=class extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}},Dr=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}};var ot=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},Ln=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}};var Uo=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},No=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Fo=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var ko=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var nr=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var Mo=class extends Event{data;constructor(e,t){super("message",t),this.data=e}},Rr=class extends Event{error;local;constructor(e,t,n){super("close",n),this.error=t,this.local=e}},Ko=class extends Rr{constructor(e,t){super(!0,e,t)}},Ho=class extends Rr{constructor(e,t){super(!1,e,t)}};var xi=Symbol.for("@libp2p/peer-id");var Vo=Symbol.for("@libp2p/transport");var Jf;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Jf||(Jf={}));function np(r){return typeof r?.handleEvent=="function"}function op(r){return(r!==!0&&r!==!1&&r?.once)??!1}var Tt=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=op(n);super.addEventListener(e,i=>{if(o){let a=this.#e.get(i.type);a!=null&&(a=a.filter(({callback:c})=>c!==t),this.#e.set(i.type,a))}np(t)?t.handleEvent(i):t(i)},n);let s=this.#e.get(e);s==null&&(s=[],this.#e.set(e,s)),s.push({callback:t,once:o})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==t),this.#e.set(e,o))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var Or=Symbol.for("@libp2p/service-capabilities"),Qf=Symbol.for("@libp2p/service-dependencies");var Ci={};re(Ci,{base58btc:()=>he,base58flickr:()=>lp});var aw=new Uint8Array(0);function tu(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 qe(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return or(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return or(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function ru(r){let e=new Uint8Array(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}var eu=4096;function nu(r){let e=r.length;if(e<=eu)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.subarray(n,n+=eu));return t}function sp(r){return r?.buffer instanceof ArrayBuffer}function or(r){return sp(r)?r:r.slice()}function ip(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),p=Math.log(u)/Math.log(256),d=Math.log(256)/Math.log(u);function y(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 v=0,L=0,R=0,D=m.length;R!==D&&m[R]===0;)R++,v++;for(var O=(D-R)*d+1>>>0,B=new Uint8Array(O);R!==D;){for(var I=m[R],U=0,F=O-1;(I!==0||U<L)&&F!==-1;F--,U++)I+=256*B[F]>>>0,B[F]=I%u>>>0,I=I/u>>>0;if(I!==0)throw new Error("Non-zero carry");L=U,R++}for(var N=O-L;N!==O&&B[N]===0;)N++;for(var g=h.repeat(v);N<O;++N)g+=r.charAt(B[N]);return g}function x(m){if(typeof m!="string")throw new TypeError("Expected String");if(m.length===0)return new Uint8Array;var v=0;if(m[v]!==" "){for(var L=0,R=0;m[v]===h;)L++,v++;for(var D=(m.length-v)*p+1>>>0,O=new Uint8Array(D);m[v];){var B=n[m.charCodeAt(v)];if(B===255)return;for(var I=0,U=D-1;(B!==0||I<R)&&U!==-1;U--,I++)B+=u*O[U]>>>0,O[U]=B%256>>>0,B=B/256>>>0;if(B!==0)throw new Error("Non-zero carry");R=I,v++}if(m[v]!==" "){for(var F=D-R;F!==D&&O[F]===0;)F++;for(var N=new Uint8Array(L+(D-F)),g=L;F!==D;)N[g++]=O[F++];return N}}}function l(m){var v=x(m);if(v)return v;throw new Error(`Non-${e} character`)}return{encode:y,decodeUnsafe:x,decode:l}}var ap=ip,cp=ap,su=cp;var Ei=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")}},Si=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 iu(this,e)}},Ai=class{decoders;constructor(e){this.decoders=e}or(e){return iu(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 iu(r,e){return new Ai({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var vi=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 Ei(e,t,n),this.decoder=new Si(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Pr({name:r,prefix:e,encode:t,decode:n}){return new vi(r,e,t,n)}function Dt({name:r,prefix:e,alphabet:t,caseInsensitive:n=!1}){let{encode:o,decode:s}=su(t,r,n);return Pr({prefix:e,name:r,encode:o,decode:i=>qe(s(i))})}function fp(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 up(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 hp(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 ue({name:r,prefix:e,bitsPerChar:t,alphabet:n,caseInsensitive:o=!1}){let s=hp(n,o);return Pr({prefix:e,name:r,encode(i){return up(i,n,t)},decode(i){return fp(i,s,t,r)}})}var he=Dt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),lp=Dt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Li={};re(Li,{base32:()=>Rt,base32hex:()=>gp,base32hexpad:()=>bp,base32hexpadupper:()=>wp,base32hexupper:()=>yp,base32pad:()=>pp,base32padupper:()=>mp,base32upper:()=>dp,base32z:()=>xp});var Rt=ue({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5,caseInsensitive:!0}),dp=ue({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5,caseInsensitive:!0}),pp=ue({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5,caseInsensitive:!0}),mp=ue({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5,caseInsensitive:!0}),gp=ue({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5,caseInsensitive:!0}),yp=ue({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5,caseInsensitive:!0}),bp=ue({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5,caseInsensitive:!0}),wp=ue({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5,caseInsensitive:!0}),xp=ue({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var _i={};re(_i,{base36:()=>_n,base36upper:()=>Ep});var _n=Dt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz",caseInsensitive:!0}),Ep=Dt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",caseInsensitive:!0});var We={};re(We,{Digest:()=>sr,create:()=>Ue,decode:()=>Fr,equals:()=>Bi,hasCode:()=>Kp});var Sp=fu,au=128,Ap=127,vp=~Ap,Cp=Math.pow(2,31);function fu(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Cp;)e[t++]=r&255|au,r/=128;for(;r&vp;)e[t++]=r&255|au,r>>>=7;return e[t]=r|0,fu.bytes=t-n+1,e}var Lp=Ii,_p=128,cu=127;function Ii(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw Ii.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&cu)<<o:(i&cu)*Math.pow(2,o),o+=7}while(i>=_p);return Ii.bytes=s-n,t}var Ip=Math.pow(2,7),Bp=Math.pow(2,14),Tp=Math.pow(2,21),Dp=Math.pow(2,28),Rp=Math.pow(2,35),Op=Math.pow(2,42),Pp=Math.pow(2,49),Up=Math.pow(2,56),Np=Math.pow(2,63),Fp=function(r){return r<Ip?1:r<Bp?2:r<Tp?3:r<Dp?4:r<Rp?5:r<Op?6:r<Pp?7:r<Up?8:r<Np?9:10},kp={encode:Sp,decode:Lp,encodingLength:Fp},Mp=kp,In=Mp;function Bn(r,e=0){return[In.decode(r,e),In.decode.bytes]}function Ur(r,e,t=0){return In.encode(r,e,t),e}function Nr(r){return In.encodingLength(r)}function Ue(r,e){let t=e.byteLength,n=Nr(r),o=n+Nr(t),s=new Uint8Array(o+t);return Ur(r,s,0),Ur(t,s,n),s.set(e,o),new sr(r,t,e,s)}function Fr(r){let e=qe(r),[t,n]=Bn(e),[o,s]=Bn(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new sr(t,o,i,e)}function Bi(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&tu(r.bytes,t.bytes)}}var sr=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=or(n),this.bytes=or(o)}};function Kp(r,e){return r.code===e}function uu(r,e){let{bytes:t,version:n}=r;return n===0?Vp(t,Ti(r),e??he.encoder):zp(t,Ti(r),e??Rt.encoder)}var hu=new WeakMap;function Ti(r){let e=hu.get(r);if(e==null){let t=new Map;return hu.set(r,t),t}return e}var pe=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=or(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!==Tn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==$p)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=Ue(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&&Bi(e.multihash,n.multihash)}toString(e){return uu(this,e)}toJSON(){return{"/":uu(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??lu(n,o,s.bytes))}else if(t[qp]===!0){let{version:n,multihash:o,code:s}=t,i=Fr(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!==Tn)throw new Error(`Version 0 CID must use dag-pb (code: ${Tn}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=lu(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Tn,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=qe(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 sr(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,p]=Bn(e.subarray(t));return t+=p,h},o=n(),s=Tn;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]=Hp(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 Ti(s).set(n,e),s}};function Hp(r,e){switch(r[0]){case"Q":{let t=e??he;return[he.prefix,t.decode(`${he.prefix}${r}`)]}case he.prefix:{let t=e??he;return[he.prefix,t.decode(r)]}case Rt.prefix:{let t=e??Rt;return[Rt.prefix,t.decode(r)]}case _n.prefix:{let t=e??_n;return[_n.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 Vp(r,e,t){let{prefix:n}=t;if(n!==he.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 zp(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 Tn=112,$p=18;function lu(r,e,t){let n=Nr(r),o=n+Nr(e),s=new Uint8Array(o+t.byteLength);return Ur(r,s,0),Ur(e,s,n),s.set(t,o),s}var qp=Symbol.for("@ipld/js-cid/CID");var Di={};re(Di,{identity:()=>Xe});var du=0,jp="identity",pu=qe;function Gp(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 Ue(du,pu(r))}var Xe={code:du,name:jp,encode:pu,digest:Gp};function Ee(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 Wp(r){return r.buffer instanceof ArrayBuffer}function Se(r){return Wp(r)?r:r.slice()}async function mu(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,Se(e),Se(t.subarray()));return n?.signal?.throwIfAborted(),s}function st(r=0){return new Uint8Array(r)}function be(r=0){return new Uint8Array(r)}function Xp(r){return r?.buffer instanceof ArrayBuffer}function Ri(r){if(Xp(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function Me(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=be(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return Ri(t)}var yu=Symbol.for("@achingbrain/uint8arraylist");function gu(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 $o(r){return!!r?.[yu]}var X=class r{bufs;length;[yu]=!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($o(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($o(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=gu(this.bufs,e);return t.buf[t.index]}set(e,t){let n=gu(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($o(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 Me(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:Me(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(!$o(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 p=f;p>=0;p--){let d=this.get(h+p);if(n[p]!==d){u=Math.max(1,p-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=be(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=st(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=st(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=st(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=be(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=st(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=st(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=st(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=st(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=st(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(!Ee(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 Oi={};re(Oi,{base10:()=>Yp});var Yp=Dt({prefix:"9",name:"base10",alphabet:"0123456789"});var Pi={};re(Pi,{base16:()=>Zp,base16upper:()=>Jp});var Zp=ue({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4,caseInsensitive:!0}),Jp=ue({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4,caseInsensitive:!0});var Ui={};re(Ui,{base2:()=>Qp});var Qp=ue({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Ni={};re(Ni,{base256emoji:()=>om});var bu=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}"),em=bu.reduce((r,e,t)=>(r[t]=e,r),[]),tm=bu.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function rm(r){return r.reduce((e,t)=>(e+=em[t],e),"")}function nm(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=tm[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var om=Pr({prefix:"\u{1F680}",name:"base256emoji",encode:rm,decode:nm});var Fi={};re(Fi,{base64:()=>sm,base64pad:()=>im,base64url:()=>Dn,base64urlpad:()=>am});var sm=ue({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),im=ue({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Dn=ue({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),am=ue({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ki={};re(ki,{base8:()=>cm});var cm=ue({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Mi={};re(Mi,{identity:()=>fm});var fm=Pr({prefix:"\0",name:"identity",encode:r=>nu(qe(r)),decode:r=>qe(ru(r))});var jw=new TextEncoder,Gw=new TextDecoder;var Vi={};re(Vi,{sha256:()=>gt,sha512:()=>dm});var lm=20;function Hi({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new Ki(r,e,t,n,o)}var Ki=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??lm,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?wu(n,this.code,t?.truncate):n.then(o=>wu(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function wu(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 Ue(e,r)}function Eu(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var gt=Hi({name:"sha2-256",code:18,encode:Eu("SHA-256")}),dm=Hi({name:"sha2-512",code:19,encode:Eu("SHA-512")});var ir={...Mi,...Ui,...ki,...Oi,...Pi,...Li,..._i,...Ci,...Fi,...Ni},sx={...Vi,...Di};function Au(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Su=Au("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),zi=Au("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=be(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),pm={utf8:Su,"utf-8":Su,hex:ir.base16,latin1:zi,ascii:zi,binary:zi,...ir},qo=pm;function Y(r,e="utf8"){let t=qo[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function G(r,e="utf8"){let t=qo[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var mm=parseInt("11111",2),$i=parseInt("10000000",2),gm=parseInt("01111111",2),vu={0:Rn,1:Rn,2:ym,3:xm,4:Em,5:wm,6:bm,16:Rn,22:Rn,48:Rn};function yt(r,e={offset:0}){let t=r[e.offset]&mm;if(e.offset++,vu[t]!=null)return vu[t](r,e);throw new Error("No decoder for tag "+t)}function On(r,e){let t=0;if((r[e.offset]&$i)===$i){let n=r[e.offset]&gm,o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++)o+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(o,16)}else t=r[e.offset],e.offset++;return t}function Rn(r,e){On(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=yt(r,e);if(n===null)break;t.push(n)}return t}function ym(r,e){let t=On(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 bm(r,e){let t=On(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 wm(r,e){return e.offset++,null}function xm(r,e){let t=On(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 Em(r,e){let t=On(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function Sm(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new X;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function qi(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=Sm(r.byteLength);return new X(Uint8Array.from([e.byteLength|$i]),e)}function Fe(r){let e=new X,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new X(Uint8Array.from([2]),qi(e),e)}function jo(r){let e=Uint8Array.from([0]),t=new X(e,r);return new X(Uint8Array.from([3]),qi(t),t)}function Ot(r,e=48){let t=new X;for(let n of r)t.append(n);return new X(Uint8Array.from([e]),qi(t),t)}var Am=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),vm=Uint8Array.from([6,5,43,129,4,0,34]),Cm=Uint8Array.from([6,5,43,129,4,0,35]),Lm={ext:!0,kty:"EC",crv:"P-256"},_m={ext:!0,kty:"EC",crv:"P-384"},Im={ext:!0,kty:"EC",crv:"P-521"},ji=32,Gi=48,Wi=66;function Xi(r){let e=yt(r);return Cu(e)}function Cu(r){let e=r[1][1][0],t=1,n,o;if(e.byteLength===ji*2+1)return n=G(e.subarray(t,t+ji),"base64url"),o=G(e.subarray(t+ji),"base64url"),new kr({...Lm,key_ops:["verify"],x:n,y:o});if(e.byteLength===Gi*2+1)return n=G(e.subarray(t,t+Gi),"base64url"),o=G(e.subarray(t+Gi),"base64url"),new kr({..._m,key_ops:["verify"],x:n,y:o});if(e.byteLength===Wi*2+1)return n=G(e.subarray(t,t+Wi),"base64url"),o=G(e.subarray(t+Wi),"base64url"),new kr({...Im,key_ops:["verify"],x:n,y:o});throw new $(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function Lu(r){return Ot([Fe(Uint8Array.from([1])),Ot([Bm(r.crv)],160),Ot([jo(new X(Uint8Array.from([4]),Y(r.x??"","base64url"),Y(r.y??"","base64url")))],161)]).subarray()}function Bm(r){if(r==="P-256")return Am;if(r==="P-384")return vm;if(r==="P-521")return Cm;throw new $(`Invalid curve ${r}`)}var kr=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=Lu(this.jwk)),this._raw}toMultihash(){return Xe.digest(Pt(this))}toCID(){return pe.createV1(114,this.toMultihash())}toString(){return he.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ee(this.raw,e.raw)}async verify(e,t,n){return mu(this.jwk,t,e,n)}};function Yi(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}function it(r,e=""){if(typeof r!="number"){let t=e&&`"${e}" `;throw new TypeError(`${t}expected number, got ${typeof r}`)}if(!Number.isSafeInteger(r)||r<0){let t=e&&`"${e}" `;throw new RangeError(`${t}expected integer >= 0, got ${r}`)}}function Ie(r,e,t=""){let n=Yi(r),o=r?.length,s=e!==void 0;if(!n||s&&o!==e){let i=t&&`"${t}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof r}`,f=i+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(f):new TypeError(f)}return r}function ar(r){if(typeof r!="function"||typeof r.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(it(r.outputLen),it(r.blockLen),r.outputLen<1)throw new Error('"outputLen" must be >= 1');if(r.blockLen<1)throw new Error('"blockLen" must be >= 1')}function Mr(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function Go(r,e){Ie(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length<t)throw new RangeError('"digestInto() output" expected to be of length >='+t)}function Ye(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function Wo(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Ze(r,e){return r<<32-e|r>>>e}var Iu=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Tm=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Xo(r){if(Ie(r),Iu)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=Tm[r[t]];return e}var bt={_0:48,_9:57,A:65,F:70,a:97,f:102};function _u(r){if(r>=bt._0&&r<=bt._9)return r-bt._0;if(r>=bt.A&&r<=bt.F)return r-(bt.A-10);if(r>=bt.a&&r<=bt.f)return r-(bt.a-10)}function Pn(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);if(Iu)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=_u(r.charCodeAt(s)),a=_u(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 Zi(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];Ie(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 Ji(r,e={}){let t=(o,s)=>r(s).update(o).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.canXOF=n.canXOF,t.create=o=>r(o),Object.assign(t,e),Object.freeze(t)}function Bu(r=32){it(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 Qi=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function Tu(r,e,t){return r&e^~r&t}function Du(r,e,t){return r&e^r&t^e&t}var Un=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=Wo(this.buffer)}update(e){Mr(this),Ie(e);let{view:t,buffer:n,blockLen:o}=this,s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=Wo(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Mr(this),Go(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,Ye(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let h=i;h<o;h++)t[h]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=Wo(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let f=c/4,u=this.get();if(f>u.length)throw new Error("_sha2: outputLen bigger than state");for(let 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}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},wt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Ae=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Yo=BigInt(4294967295),Ru=BigInt(32);function Dm(r,e=!1){return e?{h:Number(r&Yo),l:Number(r>>Ru&Yo)}:{h:Number(r>>Ru&Yo)|0,l:Number(r&Yo)|0}}function Ou(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}=Dm(r[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var ea=(r,e,t)=>r>>>t,ta=(r,e,t)=>r<<32-t|e>>>t,cr=(r,e,t)=>r>>>t|e<<32-t,fr=(r,e,t)=>r<<32-t|e>>>t,Nn=(r,e,t)=>r<<64-t|e>>>t-32,Fn=(r,e,t)=>r>>>t-32|e<<64-t;function at(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var Pu=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),Uu=(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),Fu=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,ku=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),Mu=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var Om=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]),Ut=new Uint32Array(64),ra=class extends Un{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,t,n,o,s,i,a,c]}set(e,t,n,o,s,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let h=0;h<16;h++,t+=4)Ut[h]=e.getUint32(t,!1);for(let h=16;h<64;h++){let p=Ut[h-15],d=Ut[h-2],y=Ze(p,7)^Ze(p,18)^p>>>3,x=Ze(d,17)^Ze(d,19)^d>>>10;Ut[h]=x+Ut[h-7]+y+Ut[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 p=Ze(a,6)^Ze(a,11)^Ze(a,25),d=u+p+Tu(a,c,f)+Om[h]+Ut[h]|0,x=(Ze(n,2)^Ze(n,13)^Ze(n,22))+Du(n,o,s)|0;u=f,f=c,c=a,a=i+d|0,i=s,s=o,o=n,n=d+x|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,f=f+this.G|0,u=u+this.H|0,this.set(n,o,s,i,a,c,f,u)}roundClean(){Ye(Ut)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Ye(this.buffer)}},na=class extends ra{A=wt[0]|0;B=wt[1]|0;C=wt[2]|0;D=wt[3]|0;E=wt[4]|0;F=wt[5]|0;G=wt[6]|0;H=wt[7]|0;constructor(){super(32)}};var Ku=Ou(["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))),Pm=Ku[0],Um=Ku[1],Nt=new Uint32Array(80),Ft=new Uint32Array(80),oa=class extends Un{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:f,El:u,Fh:h,Fl:p,Gh:d,Gl:y,Hh:x,Hl:l}=this;return[e,t,n,o,s,i,a,c,f,u,h,p,d,y,x,l]}set(e,t,n,o,s,i,a,c,f,u,h,p,d,y,x,l){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=p|0,this.Gh=d|0,this.Gl=y|0,this.Hh=x|0,this.Hl=l|0}process(e,t){for(let L=0;L<16;L++,t+=4)Nt[L]=e.getUint32(t),Ft[L]=e.getUint32(t+=4);for(let L=16;L<80;L++){let R=Nt[L-15]|0,D=Ft[L-15]|0,O=cr(R,D,1)^cr(R,D,8)^ea(R,D,7),B=fr(R,D,1)^fr(R,D,8)^ta(R,D,7),I=Nt[L-2]|0,U=Ft[L-2]|0,F=cr(I,U,19)^Nn(I,U,61)^ea(I,U,6),N=fr(I,U,19)^Fn(I,U,61)^ta(I,U,6),g=Nu(B,N,Ft[L-7],Ft[L-16]),A=Fu(g,O,F,Nt[L-7],Nt[L-16]);Nt[L]=A|0,Ft[L]=g|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:f,Dl:u,Eh:h,El:p,Fh:d,Fl:y,Gh:x,Gl:l,Hh:m,Hl:v}=this;for(let L=0;L<80;L++){let R=cr(h,p,14)^cr(h,p,18)^Nn(h,p,41),D=fr(h,p,14)^fr(h,p,18)^Fn(h,p,41),O=h&d^~h&x,B=p&y^~p&l,I=ku(v,D,B,Um[L],Ft[L]),U=Mu(I,m,R,O,Pm[L],Nt[L]),F=I|0,N=cr(n,o,28)^Nn(n,o,34)^Nn(n,o,39),g=fr(n,o,28)^Fn(n,o,34)^Fn(n,o,39),A=n&s^n&a^s&a,S=o&i^o&c^i&c;m=x|0,v=l|0,x=d|0,l=y|0,d=h|0,y=p|0,{h,l:p}=at(f|0,u|0,U|0,F|0),f=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let w=Pu(F,g,S);n=Uu(w,U,N,A),o=w|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:p}=at(this.Eh|0,this.El|0,h|0,p|0),{h:d,l:y}=at(this.Fh|0,this.Fl|0,d|0,y|0),{h:x,l}=at(this.Gh|0,this.Gl|0,x|0,l|0),{h:m,l:v}=at(this.Hh|0,this.Hl|0,m|0,v|0),this.set(n,o,s,i,a,c,f,u,h,p,d,y,x,l,m,v)}roundClean(){Ye(Nt,Ft)}destroy(){this.destroyed=!0,Ye(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},sa=class extends oa{Ah=Ae[0]|0;Al=Ae[1]|0;Bh=Ae[2]|0;Bl=Ae[3]|0;Ch=Ae[4]|0;Cl=Ae[5]|0;Dh=Ae[6]|0;Dl=Ae[7]|0;Eh=Ae[8]|0;El=Ae[9]|0;Fh=Ae[10]|0;Fl=Ae[11]|0;Gh=Ae[12]|0;Gl=Ae[13]|0;Hh=Ae[14]|0;Hl=Ae[15]|0;constructor(){super(64)}};var ct=Ji(()=>new na,Qi(1));var Zo=Ji(()=>new sa,Qi(3));var V=(r,e,t)=>Ie(r,e,t),aa=it,Kr=Xo,me=(...r)=>Zi(...r),Hr=r=>Pn(r),ur=Yi,hr=r=>Bu(r),Qo=BigInt(0),ia=BigInt(1);function Je(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}" `;throw new TypeError(t+"expected boolean, got type="+typeof r)}return r}function es(r){if(typeof r=="bigint"){if(!Jo(r))throw new RangeError("positive bigint expected, got "+r)}else aa(r);return r}function Qe(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 kn(r){let e=es(r).toString(16);return e.length&1?"0"+e:e}function Hu(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);return r===""?Qo:BigInt("0x"+r)}function lr(r){return Hu(Xo(r))}function Ke(r){return Hu(Xo(kt(Ie(r)).reverse()))}function ts(r,e){if(it(e),e===0)throw new RangeError("zero length");r=es(r);let t=r.toString(16);if(t.length>e*2)throw new RangeError("number too large");return Pn(t.padStart(e*2,"0"))}function Mn(r,e){return ts(r,e).reverse()}function Vu(r,e){if(r=V(r),e=V(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 kt(r){return Uint8Array.from(V(r))}function rs(r){if(typeof r!="string")throw new TypeError("ascii string expected, got "+typeof r);return Uint8Array.from(r,(e,t)=>{let n=e.charCodeAt(0);if(e.length!==1||n>127)throw new RangeError(`string contains non-ASCII character "${r[t]}" with code ${n} at position ${t}`);return n})}var Jo=r=>typeof r=="bigint"&&Qo<=r;function Nm(r,e,t){return Jo(r)&&Jo(e)&&Jo(t)&&e<=r&&r<t}function xt(r,e,t,n){if(!Nm(e,t,n))throw new RangeError("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function Vr(r){if(r<Qo)throw new Error("expected non-negative bigint, got "+r);let e;for(e=0;r>Qo;r>>=ia,e+=1);return e}var Kn=r=>(ia<<BigInt(r))-ia;function zu(r,e,t){if(it(r,"hashLen"),it(e,"qByteLen"),typeof t!="function")throw new TypeError("hmacFn must be a function");let n=l=>new Uint8Array(l),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},p=(...l)=>t(f,me(c,...l)),d=(l=o)=>{f=p(s,l),c=p(),l.length!==0&&(f=p(i,l),c=p())},y=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let l=0,m=[];for(;l<e;){c=p();let v=c.slice();m.push(v),l+=c.length}return me(...m)};return(l,m)=>{h(),d(l);let v;for(;(v=m(y()))===void 0;)d();return h(),v}}function He(r,e={},t={}){if(Object.prototype.toString.call(r)!=="[object Object]")throw new TypeError("expected valid options object");function n(s,i,a){if(!a&&i!=="function"&&!Object.hasOwn(r,s))throw new TypeError(`param "${s}" is invalid: expected own property`);let c=r[s];if(a&&c===void 0)return;let f=typeof c;if(f!==i||c===null)throw new TypeError(`param "${s}" is invalid: expected ${i}, got ${f}`)}let o=(s,i)=>Object.entries(s).forEach(([a,c])=>n(a,c,i));o(e,!1),o(t,!0)}var ca=()=>{throw new Error("not implemented")};var ve=BigInt(0),le=BigInt(1),dr=BigInt(2),Gu=BigInt(3),Wu=BigInt(4),Xu=BigInt(5),Fm=BigInt(7),Yu=BigInt(8),km=BigInt(9),Zu=BigInt(16);function ce(r,e){if(e<=ve)throw new Error("mod: expected positive modulus, got "+e);let t=r%e;return t>=ve?t:e+t}function se(r,e,t){if(e<ve)throw new Error("pow2: expected non-negative exponent, got "+e);let n=r;for(;e-- >ve;)n*=n,n%=t;return n}function $u(r,e){if(r===ve)throw new Error("invert: expected non-zero number");if(e<=ve)throw new Error("invert: expected positive modulus, got "+e);let t=ce(r,e),n=e,o=ve,s=le,i=le,a=ve;for(;t!==ve;){let f=n/t,u=n-t*f,h=o-i*f,p=s-a*f;n=t,t=u,o=i,s=a,i=h,a=p}if(n!==le)throw new Error("invert: does not exist");return ce(o,e)}function fa(r,e,t){let n=r;if(!n.eql(n.sqr(e),t))throw new Error("Cannot find square root")}function Ju(r,e){let t=r,n=(t.ORDER+le)/Wu,o=t.pow(e,n);return fa(t,o,e),o}function Mm(r,e){let t=r,n=(t.ORDER-Xu)/Yu,o=t.mul(e,dr),s=t.pow(o,n),i=t.mul(e,s),a=t.mul(t.mul(i,dr),s),c=t.mul(i,t.sub(a,t.ONE));return fa(t,c,e),c}function Km(r){let e=zr(r),t=Qu(r),n=t(e,e.neg(e.ONE)),o=t(e,n),s=t(e,e.neg(n)),i=(r+Fm)/Zu;return((a,c)=>{let f=a,u=f.pow(c,i),h=f.mul(u,n),p=f.mul(u,o),d=f.mul(u,s),y=f.eql(f.sqr(h),c),x=f.eql(f.sqr(p),c);u=f.cmov(u,h,y),h=f.cmov(d,p,x);let l=f.eql(f.sqr(h),c),m=f.cmov(u,h,l);return fa(f,m,c),m})}function Qu(r){if(r<Gu)throw new Error("sqrt is not defined for small field");let e=r-le,t=0;for(;e%dr===ve;)e/=dr,t++;let n=dr,o=zr(r);for(;qu(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return Ju;let s=o.pow(n,e),i=(e+le)/dr;return function(c,f){let u=c;if(u.is0(f))return f;if(qu(u,f)!==1)throw new Error("Cannot find square root");let h=t,p=u.mul(u.ONE,s),d=u.pow(f,e),y=u.pow(f,i);for(;!u.eql(d,u.ONE);){if(u.is0(d))return u.ZERO;let x=1,l=u.sqr(d);for(;!u.eql(l,u.ONE);)if(x++,l=u.sqr(l),x===h)throw new Error("Cannot find square root");let m=le<<BigInt(h-x-1),v=u.pow(p,m);h=x,p=u.sqr(v),d=u.mul(d,p),y=u.mul(y,v)}return y}}function Hm(r){return r%Wu===Gu?Ju:r%Yu===Xu?Mm:r%Zu===km?Km(r):Qu(r)}var Et=(r,e)=>(ce(r,e)&le)===le,Vm=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function ua(r){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=Vm.reduce((n,o)=>(n[o]="function",n),e);if(He(r,t),Qe(r.BYTES,"BYTES"),Qe(r.BITS,"BITS"),r.BYTES<1||r.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(r.ORDER<=le)throw new Error("invalid field: expected ORDER > 1, got "+r.ORDER);return r}function zm(r,e,t){let n=r;if(t<ve)throw new Error("invalid exponent, negatives unsupported");if(t===ve)return n.ONE;if(t===le)return e;let o=n.ONE,s=e;for(;t>ve;)t&le&&(o=n.mul(o,s)),s=n.sqr(s),t>>=le;return o}function Hn(r,e,t=!1){let n=r,o=new Array(e.length).fill(t?n.ZERO:void 0),s=e.reduce((a,c,f)=>n.is0(c)?a:(o[f]=a,n.mul(a,c)),n.ONE),i=n.inv(s);return e.reduceRight((a,c,f)=>n.is0(c)?a:(o[f]=n.mul(a,o[f]),n.mul(a,c)),i),o}function qu(r,e){let t=r,n=(t.ORDER-le)/dr,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 $m(r,e){if(e!==void 0&&aa(e),r<=ve)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=Vr(r);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected bit length (${t}) >= n.length (${e})`);let n=e!==void 0?e:t,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}var ju=new WeakMap,ns=class{ORDER;BITS;BYTES;isLE;ZERO=ve;ONE=le;_lengths;_mod;constructor(e,t={}){if(e<=le)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}=$m(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 ce(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return ve<=e&&e<this.ORDER}is0(e){return e===ve}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&le)===le}neg(e){return ce(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return ce(e*e,this.ORDER)}add(e,t){return ce(e+t,this.ORDER)}sub(e,t){return ce(e-t,this.ORDER)}mul(e,t){return ce(e*t,this.ORDER)}pow(e,t){return zm(this,e,t)}div(e,t){return ce(e*$u(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 $u(e,this.ORDER)}sqrt(e){let t=ju.get(this);return t||ju.set(this,t=Hm(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?Mn(e,this.BYTES):ts(e,this.BYTES)}fromBytes(e,t=!1){V(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?Ke(e):lr(e);if(a&&(c=ce(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Hn(this,e)}cmov(e,t,n){return Je(n,"condition"),n?t:e}};Object.freeze(ns.prototype);function zr(r,e={}){return new ns(r,e)}function eh(r){if(typeof r!="bigint")throw new Error("field order must be bigint");if(r<=le)throw new Error("field order must be greater than 1");let e=Vr(r-le);return Math.ceil(e/8)}function ha(r){let e=eh(r);return e+Math.ceil(e/2)}function la(r,e,t=!1){V(r);let n=r.length,o=eh(e),s=Math.max(ha(e),16);if(n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=t?Ke(r):lr(r),a=ce(i,e-le)+le;return t?Mn(a,o):ts(a,o)}var $r=BigInt(0),pr=BigInt(1);function Vn(r,e){let t=e.negate();return r?t:e}function mr(r,e){let t=Hn(r.Fp,e.map(n=>n.Z));return e.map((n,o)=>r.fromAffine(n.toAffine(t[o])))}function oh(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function da(r,e){oh(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1),o=2**r,s=Kn(r),i=BigInt(r);return{windows:t,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function th(r,e,t){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=t,a=Number(r&o),c=r>>i;a>n&&(a-=s,c+=pr);let f=e*n,u=f+Math.abs(a)-1,h=a===0,p=a<0,d=e%2!==0;return{nextN:c,offset:u,isZero:h,isNeg:p,isNegF:d,offsetF:f}}var pa=new WeakMap,sh=new WeakMap;function ma(r){return sh.get(r)||1}function rh(r){if(r!==$r)throw new Error("invalid wNAF")}var qr=class{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let o=e;for(;t>$r;)t&pr&&(n=n.add(o)),o=o.double(),t>>=pr;return n}precomputeWindow(e,t){let{windows:n,windowSize:o}=da(t,this.bits),s=[],i=e,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let f=1;f<o;f++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=da(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:f,isZero:u,isNeg:h,isNegF:p,offsetF:d}=th(n,a,i);n=c,u?s=s.add(Vn(p,t[d])):o=o.add(Vn(h,t[f]))}return rh(n),{p:o,f:s}}wNAFUnsafe(e,t,n,o=this.ZERO){let s=da(e,this.bits);for(let i=0;i<s.windows&&n!==$r;i++){let{nextN:a,offset:c,isZero:f,isNeg:u}=th(n,i,s);if(n=a,!f){let h=t[c];o=o.add(u?h.negate():h)}}return rh(n),o}getPrecomputes(e,t,n){let o=pa.get(t);return o||(o=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(o=n(o)),pa.set(t,o))),o}cached(e,t,n){let o=ma(e);return this.wNAF(o,this.getPrecomputes(o,e,n),t)}unsafe(e,t,n,o){let s=ma(e);return s===1?this._unsafeLadder(e,t,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),t,o)}createCache(e,t){oh(t,this.bits),sh.set(e,t),pa.delete(e)}hasCache(e){return ma(e)!==1}};function ih(r,e,t,n){let o=e,s=r.ZERO,i=r.ZERO;for(;t>$r||n>$r;)t&pr&&(s=s.add(o)),n&pr&&(i=i.add(o)),o=o.double(),t>>=pr,n>>=pr;return{p1:s,p2:i}}function nh(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return ua(e),e}else return zr(r,{isLE:t})}function os(r,e,t={},n){if(n===void 0&&(n=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let f=e[c];if(!(typeof f=="bigint"&&f>$r))throw new Error(`CURVE.${c} must be positive bigint`)}let o=nh(e.p,t.Fp,n),s=nh(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 Mt=BigInt(0),we=BigInt(1),ga=BigInt(2),qm=BigInt(8);function jm(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 ah(r,e={}){let t=e,n=os("edwards",r,t,t.FpFnLE),{Fp:o,Fn:s}=n,i=n.CURVE,{h:a}=i;He(t,{},{uvRatio:"function"});let c=ga<<BigInt(s.BYTES*8)-we,f=x=>o.create(x),u=t.uvRatio===void 0?(x,l)=>{try{return{isValid:!0,value:o.sqrt(o.div(x,l))}}catch{return{isValid:!1,value:Mt}}}:t.uvRatio;if(!jm(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function h(x,l,m=!1){let v=m?we:Mt;return xt("coordinate "+x,l,v,c),l}function p(x){if(!(x instanceof d))throw new Error("EdwardsPoint expected")}class d{static BASE=new d(i.Gx,i.Gy,we,f(i.Gx*i.Gy));static ZERO=new d(Mt,we,we,Mt);static Fp=o;static Fn=s;X;Y;Z;T;constructor(l,m,v,L){this.X=h("x",l),this.Y=h("y",m),this.Z=h("z",v,!0),this.T=h("t",L),Object.freeze(this)}static CURVE(){return i}static fromAffine(l){if(l instanceof d)throw new Error("extended point not allowed");let{x:m,y:v}=l||{};return h("x",m),h("y",v),new d(m,v,we,f(m*v))}static fromBytes(l,m=!1){let v=o.BYTES,{a:L,d:R}=i;l=kt(V(l,v,"point")),Je(m,"zip215");let D=kt(l),O=l[v-1];D[v-1]=O&-129;let B=Ke(D),I=m?c:o.ORDER;xt("point.y",B,Mt,I);let U=f(B*B),F=f(U-we),N=f(R*U-L),{isValid:g,value:A}=u(F,N);if(!g)throw new Error("bad point: invalid y coordinate");let S=(A&we)===we,w=(O&128)!==0;if(!m&&A===Mt&&w)throw new Error("bad point: x=0 and x_0=1");return w!==S&&(A=f(-A)),d.fromAffine({x:A,y:B})}static fromHex(l,m=!1){return d.fromBytes(Hr(l),m)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(l=8,m=!0){return y.createCache(this,l),m||this.multiply(ga),this}assertValidity(){let l=this,{a:m,d:v}=i;if(l.is0())throw new Error("bad point: ZERO");let{X:L,Y:R,Z:D,T:O}=l,B=f(L*L),I=f(R*R),U=f(D*D),F=f(U*U),N=f(B*m),g=f(U*f(N+I)),A=f(F+f(v*f(B*I)));if(g!==A)throw new Error("bad point: equation left != right (1)");let S=f(L*R),w=f(D*O);if(S!==w)throw new Error("bad point: equation left != right (2)")}equals(l){p(l);let{X:m,Y:v,Z:L}=this,{X:R,Y:D,Z:O}=l,B=f(m*O),I=f(R*L),U=f(v*O),F=f(D*L);return B===I&&U===F}is0(){return this.equals(d.ZERO)}negate(){return new d(f(-this.X),this.Y,this.Z,f(-this.T))}double(){let{a:l}=i,{X:m,Y:v,Z:L}=this,R=f(m*m),D=f(v*v),O=f(ga*f(L*L)),B=f(l*R),I=m+v,U=f(f(I*I)-R-D),F=B+D,N=F-O,g=B-D,A=f(U*N),S=f(F*g),w=f(U*g),b=f(N*F);return new d(A,S,b,w)}add(l){p(l);let{a:m,d:v}=i,{X:L,Y:R,Z:D,T:O}=this,{X:B,Y:I,Z:U,T:F}=l,N=f(L*B),g=f(R*I),A=f(O*v*F),S=f(D*U),w=f((L+R)*(B+I)-N-g),b=S-A,C=S+A,_=f(g-m*N),E=f(w*b),T=f(C*_),P=f(w*_),k=f(b*C);return new d(E,T,k,P)}subtract(l){return p(l),this.add(l.negate())}multiply(l){if(!s.isValidNot0(l))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:m,f:v}=y.cached(this,l,L=>mr(d,L));return mr(d,[m,v])[0]}multiplyUnsafe(l){if(!s.isValid(l))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return l===Mt?d.ZERO:this.is0()||l===we?this:y.unsafe(this,l,m=>mr(d,m))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return y.unsafe(this,i.n).is0()}toAffine(l){let m=this,v=l,{X:L,Y:R,Z:D}=m,O=m.is0();v==null&&(v=O?qm:o.inv(D));let B=f(L*v),I=f(R*v),U=o.mul(D,v);if(O)return{x:Mt,y:we};if(U!==we)throw new Error("invZ was invalid");return{x:B,y:I}}clearCofactor(){return a===we?this:this.multiplyUnsafe(a)}toBytes(){let{x:l,y:m}=this.toAffine(),v=o.toBytes(m);return v[v.length-1]|=l&we?128:0,v}toHex(){return Kr(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let y=new qr(d,s.BITS);return s.BITS>=8&&d.BASE.precompute(8),Object.freeze(d.prototype),Object.freeze(d),d}var ss=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e}static fromBytes(e){ca()}static fromHex(e){ca()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return Kr(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.ep.precompute(e,t),this}};function ch(r,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');let n=e,o=t;He(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:s}=o,{BASE:i,Fp:a,Fn:c}=r,f=n.outputLen,u=2*a.BYTES;if(f!==void 0&&(Qe(f,"hash.outputLen"),f!==u))throw new Error(`hash.outputLen must be ${u}, got ${f}`);let h=o.randomBytes===void 0?hr:o.randomBytes,p=o.adjustScalarBytes===void 0?g=>g:o.adjustScalarBytes,d=o.domain===void 0?(g,A,S)=>{if(Je(S,"phflag"),A.length||S)throw new Error("Contexts/pre-hash are not supported");return g}:o.domain;function y(g){return c.create(Ke(g))}function x(g){let A=B.secretKey;V(g,B.secretKey,"secretKey");let S=V(n(g),2*A,"hashedSecretKey"),w=p(S.slice(0,A)),b=S.slice(A,2*A),C=y(w);return{head:w,prefix:b,scalar:C}}function l(g){let{head:A,prefix:S,scalar:w}=x(g),b=i.multiply(w),C=b.toBytes();return{head:A,prefix:S,scalar:w,point:b,pointBytes:C}}function m(g){return l(g).pointBytes}function v(g=Uint8Array.of(),...A){let S=me(...A);return y(n(d(S,V(g,void 0,"context"),!!s)))}function L(g,A,S={}){g=V(g,void 0,"message"),s&&(g=s(g));let{prefix:w,scalar:b,pointBytes:C}=l(A),_=v(S.context,w,g),E=i.multiply(_).toBytes(),T=v(S.context,E,C,g),P=c.create(_+T*b);if(!c.isValid(P))throw new Error("sign failed: invalid s");let k=me(E,c.toBytes(P));return V(k,B.signature,"result")}let R={zip215:o.zip215};function D(g,A,S,w=R){let{context:b}=w,C=w.zip215===void 0?!!R.zip215:w.zip215,_=B.signature;g=V(g,_,"signature"),A=V(A,void 0,"message"),S=V(S,B.publicKey,"publicKey"),C!==void 0&&Je(C,"zip215"),s&&(A=s(A));let E=_/2,T=g.subarray(0,E),P=Ke(g.subarray(E,_)),k,H,K;try{k=r.fromBytes(S,C),H=r.fromBytes(T,C),K=i.multiplyUnsafe(P)}catch{return!1}if(!C&&k.isSmallOrder())return!1;let Q=v(b,T,S,A);return H.add(k.multiplyUnsafe(Q)).subtract(K).clearCofactor().is0()}let O=a.BYTES,B={secretKey:O,publicKey:O,signature:2*O,seed:O};function I(g){return g=g===void 0?h(B.seed):g,V(g,B.seed,"seed")}function U(g){return ur(g)&&g.length===B.secretKey}function F(g,A){try{return!!r.fromBytes(g,A===void 0?R.zip215:A)}catch{return!1}}let N={getExtendedPublicKey:l,randomSecretKey:I,isValidSecretKey:U,isValidPublicKey:F,toMontgomery(g){let{y:A}=r.fromBytes(g),S=B.publicKey,w=S===32;if(!w&&S!==57)throw new Error("only defined for 25519 and 448");let b=w?a.div(we+A,we-A):a.div(A-we,A+we);return a.toBytes(b)},toMontgomerySecret(g){let A=B.secretKey;V(g,A);let S=n(g.subarray(0,A));return p(S).subarray(0,A)}};return Object.freeze(B),Object.freeze(N),Object.freeze({keygen:jr(I,m),getPublicKey:m,sign:L,verify:D,utils:N,Point:r,lengths:B})}function zn(r,e){if(Qe(r),Qe(e),e<0||e>4)throw new Error("invalid I2OSP length: "+e);if(r<0||r>2**(8*e)-1)throw new Error("invalid I2OSP input: "+r);let t=Array.from({length:e}).fill(0);for(let n=e-1;n>=0;n--)t[n]=r&255,r>>>=8;return new Uint8Array(t)}function Gm(r,e){let t=new Uint8Array(r.length);for(let n=0;n<r.length;n++)t[n]=r[n]^e[n];return t}function Wm(r){if(!ur(r)&&typeof r!="string")throw new Error("DST must be Uint8Array or ascii string");let e=typeof r=="string"?rs(r):r;if(e.length===0)throw new Error("DST must be non-empty");return e}function ya(r,e,t,n){V(r),Qe(t),e=Wm(e),e.length>255&&(e=n(me(rs("H2C-OVERSIZE-DST-"),e)));let{outputLen:o,blockLen:s}=n,i=Math.ceil(t/o);if(t>65535||i>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=me(e,zn(e.length,1)),c=new Uint8Array(s),f=zn(t,2),u=new Array(i),h=n(me(c,r,f,zn(0,1),a));u[0]=n(me(h,zn(1,1),a));for(let d=1;d<i;d++){let y=[Gm(h,u[d-1]),zn(d+1,1),a];u[d]=n(me(...y))}return me(...u).slice(0,t)}var fh="HashToScalar-";var $n=BigInt(0),Gr=BigInt(1),is=BigInt(2);function Xm(r){return He(r,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function"}),Object.freeze({...r})}function uh(r){let e=Xm(r),{P:t,type:n,adjustScalarBytes:o,powPminus2:s,randomBytes:i}=e,a=n==="x25519";if(!a&&n!=="x448")throw new Error("invalid type");let c=i===void 0?hr:i,f=a?255:448,u=a?32:56,h=BigInt(a?9:5),p=BigInt(a?121665:39081),d=a?is**BigInt(254):is**BigInt(447),y=a?BigInt(8)*is**BigInt(251)-Gr:BigInt(4)*is**BigInt(445)-Gr,x=d+y+Gr,l=S=>ce(S,t),m=v(h);function v(S){return Mn(l(S),u)}function L(S){let w=kt(V(S,u,"uCoordinate"));return a&&(w[31]&=127),l(Ke(w))}function R(S){return Ke(o(kt(V(S,u,"scalar"))))}function D(S,w){let b=F(L(w),R(S));if(b===$n)throw new Error("invalid private or public key received");return v(b)}function O(S){return D(S,m)}let B=O,I=D;function U(S,w,b){let C=l(S*(w-b));return w=l(w-C),b=l(b+C),{x_2:w,x_3:b}}function F(S,w){xt("u",S,$n,t),xt("scalar",w,d,x);let b=w,C=S,_=Gr,E=$n,T=S,P=Gr,k=$n;for(let K=BigInt(f-1);K>=$n;K--){let Q=b>>K&Gr;k^=Q,{x_2:_,x_3:T}=U(k,_,T),{x_2:E,x_3:P}=U(k,E,P),k=Q;let ee=_+E,te=l(ee*ee),j=_-E,ae=l(j*j),mt=te-ae,rr=T+P,Br=T-P,vn=l(Br*ee),Cn=l(rr*j),Yf=vn+Cn,Zf=vn-Cn;T=l(Yf*Yf),P=l(C*l(Zf*Zf)),_=l(te*ae),E=l(mt*(te+l(p*mt)))}({x_2:_,x_3:T}=U(k,_,T)),{x_2:E,x_3:P}=U(k,E,P);let H=s(E);return l(_*H)}let N={secretKey:u,publicKey:u,seed:u},g=S=>(S=S===void 0?c(u):S,V(S,N.seed,"seed"),S),A={randomSecretKey:g};return Object.freeze(N),Object.freeze(A),Object.freeze({keygen:jr(g,B),getSharedSecret:I,getPublicKey:B,scalarMult:D,scalarMultBase:O,utils:A,GuBytes:m.slice(),lengths:N})}var Ym=BigInt(0),St=BigInt(1),hh=BigInt(2),Zm=BigInt(3),Jm=BigInt(5),Qm=BigInt(8),gr=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Ea={p:gr,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Qm,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function ph(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=gr,a=r*r%s*r%s,c=se(a,hh,s)*a%s,f=se(c,St,s)*r%s,u=se(f,Jm,s)*f%s,h=se(u,e,s)*u%s,p=se(h,t,s)*h%s,d=se(p,n,s)*p%s,y=se(d,o,s)*d%s,x=se(y,o,s)*d%s,l=se(x,e,s)*u%s;return{pow_p_5_8:se(l,hh,s)*r%s,b2:a}}function mh(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var ba=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Sa(r,e){let t=gr,n=ce(e*e*e,t),o=ce(n*n*e,t),s=ph(r*o).pow_p_5_8,i=ce(r*n*s,t),a=ce(e*i*i,t),c=i,f=ce(i*ba,t),u=a===r,h=a===ce(-r,t),p=a===ce(-r*ba,t);return u&&(i=c),(h||p)&&(i=f),Et(i,t)&&(i=ce(-i,t)),{isValid:u||h,value:i}}var Ht=ah(Ea,{uvRatio:Sa}),Kt=Ht.Fp,gh=Ht.Fn;function e0(r){return ch(Ht,Zo,Object.assign({adjustScalarBytes:mh,zip215:!0},r))}var yh=e0({});var qn=(()=>{let r=gr;return uh({P:r,type:"x25519",powPminus2:e=>{let{pow_p_5_8:t,b2:n}=ph(e);return ce(se(t,Zm,r)*n,r)},adjustScalarBytes:mh})})();var wa=ba,t0=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),r0=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),n0=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),o0=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),lh=r=>Sa(St,r),s0=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),xa=r=>Kt.create(Ke(r)&s0);function dh(r){let{d:e}=Ea,t=gr,n=m=>Kt.create(m),o=n(wa*r*r),s=n((o+St)*n0),i=BigInt(-1),a=n((i-e*o)*n(o+e)),{isValid:c,value:f}=Sa(s,a),u=n(f*r);Et(u,t)||(u=n(-u)),c||(f=u),c||(i=o);let h=n(i*(o-St)*o0-a),p=f*f,d=n((f+f)*a),y=n(h*t0),x=n(St-p),l=n(St+p);return new Ht(n(d*l),n(x*y),n(y*l),n(d*x))}var Vt=class r extends ss{static BASE=new r(Ht.BASE);static ZERO=new r(Ht.ZERO);static Fp=Kt;static Fn=gh;constructor(e){super(e)}static fromAffine(e){return new r(Ht.fromAffine(e))}assertSame(e){if(!(e instanceof r))throw new Error("RistrettoPoint expected")}init(e){return new r(e)}static fromBytes(e){Ie(e,32);let{a:t,d:n}=Ea,o=gr,s=R=>Kt.create(R),i=xa(e);if(!Vu(Kt.toBytes(i),e)||Et(i,o))throw new Error("invalid ristretto255 encoding 1");let a=s(i*i),c=s(St+t*a),f=s(St-t*a),u=s(c*c),h=s(f*f),p=s(t*n*u-h),{isValid:d,value:y}=lh(s(p*h)),x=s(y*f),l=s(y*x*p),m=s((i+i)*x);Et(m,o)&&(m=s(-m));let v=s(c*l),L=s(m*v);if(!d||Et(L,o)||v===Ym)throw new Error("invalid ristretto255 encoding 2");return new r(new Ht(m,v,St,L))}static fromHex(e){return r.fromBytes(Pn(e))}toBytes(){let{X:e,Y:t,Z:n,T:o}=this.ep,s=gr,i=l=>Kt.create(l),a=i(i(n+t)*i(n-t)),c=i(e*t),f=i(c*c),{value:u}=lh(i(a*f)),h=i(u*a),p=i(u*c),d=i(h*p*o),y;if(Et(o*d,s)){let l=i(t*wa),m=i(e*wa);e=l,t=m,y=i(h*r0)}else y=p;Et(e*d,s)&&(t=i(-t));let x=i((n-t)*y);return Et(x,s)&&(x=i(-x)),Kt.toBytes(x)}equals(e){this.assertSame(e);let{X:t,Y:n}=this.ep,{X:o,Y:s}=e.ep,i=f=>Kt.create(f),a=i(t*s)===i(n*o),c=i(n*s)===i(t*o);return a||c}is0(){return this.equals(r.ZERO)}};Object.freeze(Vt.BASE);Object.freeze(Vt.ZERO);Object.freeze(Vt.prototype);Object.freeze(Vt);var i0=Object.freeze({Point:Vt,hashToCurve(r,e){let t=e?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":e.DST,n=ya(r,t,64,Zo);return i0.deriveToCurve(n)},hashToScalar(r,e={DST:fh}){let t=ya(r,e.DST,64,Zo);return gh.create(Ke(t))},deriveToCurve(r){Ie(r,64);let e=xa(r.subarray(0,32)),t=dh(e),n=xa(r.subarray(32,64)),o=dh(n);return new Vt(t.add(o))}});var jn=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},as=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var je={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new as("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 cs=32;var Aa,a0=(async()=>{try{return await je.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function c0(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await je.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await je.get().subtle.verify({name:"Ed25519"},n,Se(e),Se(t instanceof Uint8Array?t:t.subarray()))}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function f0(r,e,t){return yh.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function bh(r,e,t){return Aa==null&&(Aa=await a0),Aa?c0(r,e,t):f0(r,e,t)}function fs(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var us=class{type="Ed25519";raw;constructor(e){this.raw=va(e,cs)}toMultihash(){return Xe.digest(Pt(this))}toCID(){return pe.createV1(114,this.toMultihash())}toString(){return he.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ee(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let o=bh(this.raw,t,e);return fs(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function Ca(r){return r=va(r,cs),new us(r)}function va(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new $(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var h0=Math.pow(2,7),l0=Math.pow(2,14),d0=Math.pow(2,21),La=Math.pow(2,28),_a=Math.pow(2,35),Ia=Math.pow(2,42),Ba=Math.pow(2,49),Z=128,Be=127;function ie(r){if(r<h0)return 1;if(r<l0)return 2;if(r<d0)return 3;if(r<La)return 4;if(r<_a)return 5;if(r<Ia)return 6;if(r<Ba)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(ie(r)){case 8:e[t++]=r&255|Z,r/=128;case 7:e[t++]=r&255|Z,r/=128;case 6:e[t++]=r&255|Z,r/=128;case 5:e[t++]=r&255|Z,r/=128;case 4:e[t++]=r&255|Z,r>>>=7;case 3:e[t++]=r&255|Z,r>>>=7;case 2:e[t++]=r&255|Z,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function p0(r,e,t=0){switch(ie(r)){case 8:e.set(t++,r&255|Z),r/=128;case 7:e.set(t++,r&255|Z),r/=128;case 6:e.set(t++,r&255|Z),r/=128;case 5:e.set(t++,r&255|Z),r/=128;case 4:e.set(t++,r&255|Z),r>>>=7;case 3:e.set(t++,r&255|Z),r>>>=7;case 2:e.set(t++,r&255|Z),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function Ta(r,e){let t=r[e],n=0;if(n+=t&Be,t<Z||(t=r[e+1],n+=(t&Be)<<7,t<Z)||(t=r[e+2],n+=(t&Be)<<14,t<Z)||(t=r[e+3],n+=(t&Be)<<21,t<Z)||(t=r[e+4],n+=(t&Be)*La,t<Z)||(t=r[e+5],n+=(t&Be)*_a,t<Z)||(t=r[e+6],n+=(t&Be)*Ia,t<Z)||(t=r[e+7],n+=(t&Be)*Ba,t<Z))return n;throw new RangeError("Could not decode varint")}function m0(r,e){let t=r.get(e),n=0;if(n+=t&Be,t<Z||(t=r.get(e+1),n+=(t&Be)<<7,t<Z)||(t=r.get(e+2),n+=(t&Be)<<14,t<Z)||(t=r.get(e+3),n+=(t&Be)<<21,t<Z)||(t=r.get(e+4),n+=(t&Be)*La,t<Z)||(t=r.get(e+5),n+=(t&Be)*_a,t<Z)||(t=r.get(e+6),n+=(t&Be)*Ia,t<Z)||(t=r.get(e+7),n+=(t&Be)*Ba,t<Z))return n;throw new RangeError("Could not decode varint")}function hs(r,e,t=0){return e==null&&(e=be(ie(r))),e instanceof Uint8Array?Wr(r,e,t):p0(r,e,t)}function At(r,e=0){return r instanceof Uint8Array?Ta(r,e):m0(r,e)}var Da=new Float32Array([-0]),zt=new Uint8Array(Da.buffer);function xh(r,e,t){Da[0]=r,e[t]=zt[0],e[t+1]=zt[1],e[t+2]=zt[2],e[t+3]=zt[3]}function Eh(r,e){return zt[0]=r[e],zt[1]=r[e+1],zt[2]=r[e+2],zt[3]=r[e+3],Da[0]}var Ra=new Float64Array([-0]),Te=new Uint8Array(Ra.buffer);function Sh(r,e,t){Ra[0]=r,e[t]=Te[0],e[t+1]=Te[1],e[t+2]=Te[2],e[t+3]=Te[3],e[t+4]=Te[4],e[t+5]=Te[5],e[t+6]=Te[6],e[t+7]=Te[7]}function Ah(r,e){return Te[0]=r[e],Te[1]=r[e+1],Te[2]=r[e+2],Te[3]=r[e+3],Te[4]=r[e+4],Te[5]=r[e+5],Te[6]=r[e+6],Te[7]=r[e+7],Ra[0]}var g0=BigInt(Number.MAX_SAFE_INTEGER),y0=BigInt(Number.MIN_SAFE_INTEGER),Ve=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 yr;if(e<g0&&e>y0)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>vh&&(o=0n,++n>vh&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return yr;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):yr}},yr=new Ve(0,0);yr.toBigInt=function(){return 0n};yr.zzEncode=yr.zzDecode=function(){return this};yr.length=function(){return 1};var vh=4294967296n;function Ch(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 Lh(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 et(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function ls(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=Se(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 ls(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw et(this,4);return ls(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw et(this,4);let e=Eh(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw et(this,4);let e=Ah(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 et(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Lh(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 Ve(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 et(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 et(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 et(this,8);let e=ls(this.buf,this.pos+=4),t=ls(this.buf,this.pos+=4);return new Ve(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=Ta(this.buf,this.pos);return this.pos+=ie(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(r){return new Pa(r instanceof Uint8Array?r:r.subarray())}function $t(r,e,t){let n=Wn(r);return e.decode(n,void 0,t)}function Ua(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return be(i);o+i>e&&(n=be(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var br=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function Na(){}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}},b0=Ua();function w0(r){return globalThis.Buffer!=null?be(r):b0(r)}var Yn=class{len;head;tail;states;constructor(){this.len=0,this.head=new br(Na,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new br(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(ds,10,Ve.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Ve.fromBigInt(e);return this._push(ds,t.length(),t)}uint64Number(e){return this._push(Wr,ie(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=Ve.fromBigInt(e).zzEncode();return this._push(ds,t.length(),t)}sint64Number(e){let t=Ve.fromNumber(e).zzEncode();return this._push(ds,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(Xn,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Ve.fromBigInt(e);return this._push(Xn,4,t.lo)._push(Xn,4,t.hi)}fixed64Number(e){let t=Ve.fromNumber(e);return this._push(Xn,4,t.lo)._push(Xn,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(xh,4,e)}double(e){return this._push(Sh,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(Fa,1,0):this.uint32(t)._push(E0,t,e)}string(e){let t=Ch(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 br(Na,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 br(Na,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=w0(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 x0(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var Ma=class extends br{next;constructor(e,t){super(x0,e,t),this.next=void 0}};function ds(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 Xn(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 E0(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(Yn.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(S0,e,r),this},Yn.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(A0,e,r),this});function S0(r,e,t){e.set(r,t)}function A0(r,e,t){r.length<40?Oa(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(Y(r),t)}function Ka(){return new Yn}function qt(r,e){let t=Ka();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}function*jt(r,e,t){let n=Wn(r);yield*e.stream(n,void 0,"$",t)}var ps={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function ms(r,e,t,n,o){return{name:r,type:e,encode:t,decode:n,stream:o}}function wr(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 ms("enum",ps.VARINT,t,n,o)}function Gt(r,e,t){return ms("message",ps.LENGTH_DELIMITED,r,e,t)}var fe;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(fe||(fe={}));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=()=>wr(Ha)})(fe||(fe={}));var ft;(function(r){let e;r.codec=()=>(e==null&&(e=Gt((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),fe.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=fe.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:fe.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 qt(s,r.codec())}r.encode=t;function n(s,i){return $t(s,r.codec(),i)}r.decode=n;function o(s,i){return jt(s,r.codec(),i)}r.stream=o})(ft||(ft={}));var Va;(function(r){let e;r.codec=()=>(e==null&&(e=Gt((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),fe.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=fe.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:fe.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 qt(s,r.codec())}r.encode=t;function n(s,i){return $t(s,r.codec(),i)}r.decode=n;function o(s,i){return jt(s,r.codec(),i)}r.stream=o})(Va||(Va={}));var Jn={};re(Jn,{MAX_RSA_KEY_SIZE:()=>za,generateRSAKeyPair:()=>Rh,jwkToJWKKeyPair:()=>Oh,jwkToPkcs1:()=>_0,jwkToPkix:()=>Ga,jwkToRSAPrivateKey:()=>Za,pkcs1MessageToJwk:()=>qa,pkcs1MessageToRSAPrivateKey:()=>Wa,pkcs1ToJwk:()=>L0,pkcs1ToRSAPrivateKey:()=>Dh,pkixMessageToJwk:()=>ja,pkixMessageToRSAPublicKey:()=>Ya,pkixToJwk:()=>I0,pkixToRSAPublicKey:()=>Xa});var Xr=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 pe.createV1(114,this._multihash)}toString(){return he.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ee(this.raw,e.raw)}verify(e,t,n){return Th(this.jwk,t,e,n)}},Zn=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:Ee(this.raw,e.raw)}sign(e,t){return Bh(this.jwk,e,t)}};var za=8192,$a=18,v0=1062,C0=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function L0(r){let e=yt(r);return qa(e)}function qa(r){return{n:G(r[1],"base64url"),e:G(r[2],"base64url"),d:G(r[3],"base64url"),p:G(r[4],"base64url"),q:G(r[5],"base64url"),dp:G(r[6],"base64url"),dq:G(r[7],"base64url"),qi:G(r[8],"base64url"),kty:"RSA"}}function _0(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 $("JWK was missing components");return Ot([Fe(Uint8Array.from([0])),Fe(Y(r.n,"base64url")),Fe(Y(r.e,"base64url")),Fe(Y(r.d,"base64url")),Fe(Y(r.p,"base64url")),Fe(Y(r.q,"base64url")),Fe(Y(r.dp,"base64url")),Fe(Y(r.dq,"base64url")),Fe(Y(r.qi,"base64url"))]).subarray()}function I0(r){let e=yt(r,{offset:0});return ja(e)}function ja(r){let e=yt(r[1],{offset:0});return{kty:"RSA",n:G(e[0],"base64url"),e:G(e[1],"base64url")}}function Ga(r){if(r.n==null||r.e==null)throw new $("JWK was missing components");return Ot([C0,jo(Ot([Fe(Y(r.n,"base64url")),Fe(Y(r.e,"base64url"))]))]).subarray()}function Dh(r){let e=yt(r);return Wa(e)}function Wa(r){let e=qa(r);return Za(e)}function Xa(r,e){if(r.byteLength>=v0)throw new Tr("Key size is too large");let t=yt(r,{offset:0});return Ya(t,r,e)}function Ya(r,e,t){let n=ja(r);if(t==null){let o=ct(ft.encode({Type:fe.RSA,Data:e}));t=Ue($a,o)}return new Xr(n,t)}function Za(r){if(Uh(r)>za)throw new $("Key size is too large");let e=Oh(r),t=ct(ft.encode({Type:fe.RSA,Data:Ga(e.publicKey)})),n=Ue($a,t);return new Zn(e.privateKey,new Xr(e.publicKey,n))}async function Rh(r){if(r>za)throw new $("Key size is too large");let e=await Ph(r),t=ct(ft.encode({Type:fe.RSA,Data:Ga(e.publicKey)})),n=Ue($a,t);return new Zn(e.privateKey,new Xr(e.publicKey,n))}function Oh(r){if(r==null)throw new $("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function Ph(r,e){let t=await je.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 B0(t,e);return{privateKey:n[0],publicKey:n[1]}}async function Bh(r,e,t){let n=await je.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let o=await je.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,Se(e instanceof Uint8Array?e:e.subarray()));return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function Th(r,e,t,n){let o=await je.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let s=await je.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,Se(e),Se(t instanceof Uint8Array?t:t.subarray()));return n?.signal?.throwIfAborted(),s}async function B0(r,e){if(r.privateKey==null||r.publicKey==null)throw new $("Private and public key are required");let t=await Promise.all([je.get().subtle.exportKey("jwk",r.privateKey),je.get().subtle.exportKey("jwk",r.publicKey)]);return e?.signal?.throwIfAborted(),t}function Uh(r){if(r.kty!=="RSA")throw new $("invalid key type");if(r.n==null)throw new $("invalid key modulus");return Y(r.n,"base64url").length*8}var gs=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(ar(e),Ie(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(t.length>n?e.create().update(t).digest():t);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),Ye(o)}update(e){return Mr(this),this.iHash.update(e),this}digestInto(e){Mr(this),Go(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Qn=(()=>{let r=((e,t,n)=>new gs(e,t).update(n).digest());return r.create=(e,t)=>new gs(e,t),r})();var Nh=(r,e)=>(r+(r>=0?e:-e)/Fh)/e;function T0(r,e,t){xt("scalar",r,ut,t);let[[n,o],[s,i]]=e,a=Nh(i*r,t),c=Nh(-o*r,t),f=r-a*n-c*s,u=-a*o-c*i,h=f<ut,p=u<ut;h&&(f=-f),p&&(u=-u);let d=Kn(Math.ceil(Vr(t)/2))+Wt;if(f<ut||f>=d||u<ut||u>=d)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:h,k1:f,k2neg:p,k2:u}}function Qa(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function Ja(r,e){He(r);let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return Je(t.lowS,"lowS"),Je(t.prehash,"prehash"),t.format!==void 0&&Qa(t.format),t}var ec=class extends Error{constructor(e=""){super(e)}},tt={Err:ec,_tlv:{encode:(r,e)=>{let{Err:t}=tt;if(Qe(r,"tag"),r<0||r>255)throw new t("tlv.encode: wrong tag");if(typeof e!="string")throw new TypeError('"data" expected string, got type='+typeof e);if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,o=kn(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let s=n>127?kn(o.length/2|128):"";return kn(r)+s+o+e},decode(r,e){let{Err:t}=tt;e=V(e,void 0,"DER data");let n=0;if(r<0||r>255)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let o=e[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let f=e.subarray(n,n+c);if(f.length!==c)throw new t("tlv.decode: length bytes not complete");if(f[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let u of f)i=i<<8|u;if(n+=c,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(r){let{Err:e}=tt;if(es(r),r<ut)throw new e("integer: negative integers are not allowed");let t=kn(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}=tt;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 lr(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=tt,o=V(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}=tt,n=e.encode(2,t.encode(r.r)),o=e.encode(2,t.encode(r.s)),s=n+o;return e.encode(48,s)}};Object.freeze(tt._tlv);Object.freeze(tt._int);Object.freeze(tt);var ut=BigInt(0),Wt=BigInt(1),Fh=BigInt(2),ys=BigInt(3),D0=BigInt(4);function kh(r,e={}){let t=os("weierstrass",r,e),n=t.Fp,o=t.Fn,s=t.CURVE,{h:i,n:a}=s;He(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c,allowInfinityPoint:f}=e;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let u=Kh(n,o);function h(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function p(N,g,A){if(f&&g.is0())return Uint8Array.of(0);let{x:S,y:w}=g.toAffine(),b=n.toBytes(S);if(Je(A,"isCompressed"),A){h();let C=!n.isOdd(w);return me(Mh(C),b)}else return me(Uint8Array.of(4),b,n.toBytes(w))}function d(N){V(N,void 0,"Point");let{publicKey:g,publicKeyUncompressed:A}=u,S=N.length,w=N[0],b=N.subarray(1);if(f&&S===1&&w===0)return{x:n.ZERO,y:n.ZERO};if(S===g&&(w===2||w===3)){let C=n.fromBytes(b);if(!n.isValid(C))throw new Error("bad point: is not on curve, wrong x");let _=l(C),E;try{E=n.sqrt(_)}catch(k){let H=k instanceof Error?": "+k.message:"";throw new Error("bad point: is not on curve, sqrt error"+H)}h();let T=n.isOdd(E);return(w&1)===1!==T&&(E=n.neg(E)),{x:C,y:E}}else if(S===A&&w===4){let C=n.BYTES,_=n.fromBytes(b.subarray(0,C)),E=n.fromBytes(b.subarray(C,C*2));if(!m(_,E))throw new Error("bad point: is not on curve");return{x:_,y:E}}else throw new Error(`bad point: got length ${S}, expected compressed=${g} or uncompressed=${A}`)}let y=e.toBytes===void 0?p:e.toBytes,x=e.fromBytes===void 0?d:e.fromBytes;function l(N){let g=n.sqr(N),A=n.mul(g,N);return n.add(n.add(A,n.mul(N,s.a)),s.b)}function m(N,g){let A=n.sqr(g),S=l(N);return n.eql(A,S)}if(!m(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let v=n.mul(n.pow(s.a,ys),D0),L=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(v,L)))throw new Error("bad curve params: a or b");function R(N,g,A=!1){if(!n.isValid(g)||A&&n.is0(g))throw new Error(`bad point coordinate ${N}`);return g}function D(N){if(!(N instanceof I))throw new Error("Weierstrass Point expected")}function O(N){if(!c||!c.basises)throw new Error("no endo");return T0(N,c.basises,o.ORDER)}function B(N,g,A,S,w){return A=new I(n.mul(A.X,N),A.Y,A.Z),g=Vn(S,g),A=Vn(w,A),g.add(A)}class I{static BASE=new I(s.Gx,s.Gy,n.ONE);static ZERO=new I(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(g,A,S){this.X=R("x",g),this.Y=R("y",A,!0),this.Z=R("z",S),Object.freeze(this)}static CURVE(){return s}static fromAffine(g){let{x:A,y:S}=g||{};if(!g||!n.isValid(A)||!n.isValid(S))throw new Error("invalid affine point");if(g instanceof I)throw new Error("projective point not allowed");return n.is0(A)&&n.is0(S)?I.ZERO:new I(A,S,n.ONE)}static fromBytes(g){let A=I.fromAffine(x(V(g,void 0,"point")));return A.assertValidity(),A}static fromHex(g){return I.fromBytes(Hr(g))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,A=!0){return F.createCache(this,g),A||this.multiply(ys),this}assertValidity(){let g=this;if(g.is0()){if(e.allowInfinityPoint&&n.is0(g.X)&&n.eql(g.Y,n.ONE)&&n.is0(g.Z))return;throw new Error("bad point: ZERO")}let{x:A,y:S}=g.toAffine();if(!n.isValid(A)||!n.isValid(S))throw new Error("bad point: x or y not field elements");if(!m(A,S))throw new Error("bad point: equation left != right");if(!g.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:g}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(g)}equals(g){D(g);let{X:A,Y:S,Z:w}=this,{X:b,Y:C,Z:_}=g,E=n.eql(n.mul(A,_),n.mul(b,w)),T=n.eql(n.mul(S,_),n.mul(C,w));return E&&T}negate(){return new I(this.X,n.neg(this.Y),this.Z)}double(){let{a:g,b:A}=s,S=n.mul(A,ys),{X:w,Y:b,Z:C}=this,_=n.ZERO,E=n.ZERO,T=n.ZERO,P=n.mul(w,w),k=n.mul(b,b),H=n.mul(C,C),K=n.mul(w,b);return K=n.add(K,K),T=n.mul(w,C),T=n.add(T,T),_=n.mul(g,T),E=n.mul(S,H),E=n.add(_,E),_=n.sub(k,E),E=n.add(k,E),E=n.mul(_,E),_=n.mul(K,_),T=n.mul(S,T),H=n.mul(g,H),K=n.sub(P,H),K=n.mul(g,K),K=n.add(K,T),T=n.add(P,P),P=n.add(T,P),P=n.add(P,H),P=n.mul(P,K),E=n.add(E,P),H=n.mul(b,C),H=n.add(H,H),P=n.mul(H,K),_=n.sub(_,P),T=n.mul(H,k),T=n.add(T,T),T=n.add(T,T),new I(_,E,T)}add(g){D(g);let{X:A,Y:S,Z:w}=this,{X:b,Y:C,Z:_}=g,E=n.ZERO,T=n.ZERO,P=n.ZERO,k=s.a,H=n.mul(s.b,ys),K=n.mul(A,b),Q=n.mul(S,C),ee=n.mul(w,_),te=n.add(A,S),j=n.add(b,C);te=n.mul(te,j),j=n.add(K,Q),te=n.sub(te,j),j=n.add(A,w);let ae=n.add(b,_);return j=n.mul(j,ae),ae=n.add(K,ee),j=n.sub(j,ae),ae=n.add(S,w),E=n.add(C,_),ae=n.mul(ae,E),E=n.add(Q,ee),ae=n.sub(ae,E),P=n.mul(k,j),E=n.mul(H,ee),P=n.add(E,P),E=n.sub(Q,P),P=n.add(Q,P),T=n.mul(E,P),Q=n.add(K,K),Q=n.add(Q,K),ee=n.mul(k,ee),j=n.mul(H,j),Q=n.add(Q,ee),ee=n.sub(K,ee),ee=n.mul(k,ee),j=n.add(j,ee),K=n.mul(Q,j),T=n.add(T,K),K=n.mul(ae,j),E=n.mul(te,E),E=n.sub(E,K),K=n.mul(te,Q),P=n.mul(ae,P),P=n.add(P,K),new I(E,T,P)}subtract(g){return D(g),this.add(g.negate())}is0(){return this.equals(I.ZERO)}multiply(g){let{endo:A}=e;if(!o.isValidNot0(g))throw new RangeError("invalid scalar: out of range");let S,w,b=C=>F.cached(this,C,_=>mr(I,_));if(A){let{k1neg:C,k1:_,k2neg:E,k2:T}=O(g),{p:P,f:k}=b(_),{p:H,f:K}=b(T);w=k.add(K),S=B(A.beta,P,H,C,E)}else{let{p:C,f:_}=b(g);S=C,w=_}return mr(I,[S,w])[0]}multiplyUnsafe(g){let{endo:A}=e,S=this,w=g;if(!o.isValid(w))throw new RangeError("invalid scalar: out of range");if(w===ut||S.is0())return I.ZERO;if(w===Wt)return S;if(F.hasCache(this))return this.multiply(w);if(A){let{k1neg:b,k1:C,k2neg:_,k2:E}=O(w),{p1:T,p2:P}=ih(I,S,C,E);return B(A.beta,T,P,b,_)}else return F.unsafe(S,w)}toAffine(g){let A=this,S=g,{X:w,Y:b,Z:C}=A;if(n.eql(C,n.ONE))return{x:w,y:b};let _=A.is0();S==null&&(S=_?n.ONE:n.inv(C));let E=n.mul(w,S),T=n.mul(b,S),P=n.mul(C,S);if(_)return{x:n.ZERO,y:n.ZERO};if(!n.eql(P,n.ONE))throw new Error("invZ was invalid");return{x:E,y:T}}isTorsionFree(){let{isTorsionFree:g}=e;return i===Wt?!0:g?g(I,this):F.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:g}=e;return i===Wt?this:g?g(I,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===Wt?this.is0():this.clearCofactor().is0()}toBytes(g=!0){return Je(g,"isCompressed"),this.assertValidity(),y(I,this,g)}toHex(g=!0){return Kr(this.toBytes(g))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let U=o.BITS,F=new qr(I,e.endo?Math.ceil(U/2):U);return U>=8&&I.BASE.precompute(8),Object.freeze(I.prototype),Object.freeze(I),I}function Mh(r){return Uint8Array.of(r?2:3)}function Kh(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function R0(r,e={}){let{Fn:t}=r,n=e.randomBytes===void 0?hr:e.randomBytes,o=Object.assign(Kh(r.Fp,t),{seed:Math.max(ha(t.ORDER),16)});function s(d){try{let y=t.fromBytes(d);return t.isValidNot0(y)}catch{return!1}}function i(d,y){let{publicKey:x,publicKeyUncompressed:l}=o;try{let m=d.length;return y===!0&&m!==x||y===!1&&m!==l?!1:!!r.fromBytes(d)}catch{return!1}}function a(d){return d=d===void 0?n(o.seed):d,la(V(d,o.seed,"seed"),t.ORDER)}function c(d,y=!0){return r.BASE.multiply(t.fromBytes(d)).toBytes(y)}function f(d){let{secretKey:y,publicKey:x,publicKeyUncompressed:l}=o,m=t._lengths;if(!ur(d))return;let v=V(d,void 0,"key").length,L=v===x||v===l,R=v===y||!!m?.includes(v);if(!(L&&R))return L}function u(d,y,x=!0){if(f(d)===!0)throw new Error("first arg must be private key");if(f(y)===!1)throw new Error("second arg must be public key");let l=t.fromBytes(d);return r.fromBytes(y).multiply(l).toBytes(x)}let h={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},p=jr(a,c);return Object.freeze(h),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:p,Point:r,utils:h,lengths:o})}function Hh(r,e,t={}){let n=e;ar(n),He(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let o=t.randomBytes===void 0?hr:t.randomBytes,s=t.hmac===void 0?(w,b)=>Qn(n,w,b):t.hmac,{Fp:i,Fn:a}=r,{ORDER:c,BITS:f}=a,{keygen:u,getPublicKey:h,getSharedSecret:p,utils:d,lengths:y}=R0(r,t),x={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},l=c*Fh+Wt<i.ORDER;function m(w){let b=c>>Wt;return w>b}function v(w,b){if(!a.isValidNot0(b))throw new Error(`invalid signature ${w}: out of range 1..Point.Fn.ORDER`);return b}function L(){if(l)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function R(w,b){Qa(b);let C=y.signature,_=b==="compact"?C:b==="recovered"?C+1:void 0;return V(w,_)}class D{r;s;recovery;constructor(b,C,_){if(this.r=v("r",b),this.s=v("s",C),_!=null){if(L(),![0,1,2,3].includes(_))throw new Error("invalid recovery id");this.recovery=_}Object.freeze(this)}static fromBytes(b,C=x.format){R(b,C);let _;if(C==="der"){let{r:k,s:H}=tt.toSig(V(b));return new D(k,H)}C==="recovered"&&(_=b[0],C="compact",b=b.subarray(1));let E=y.signature/2,T=b.subarray(0,E),P=b.subarray(E,E*2);return new D(a.fromBytes(T),a.fromBytes(P),_)}static fromHex(b,C){return this.fromBytes(Hr(b),C)}assertRecovery(){let{recovery:b}=this;if(b==null)throw new Error("invalid recovery id: must be present");return b}addRecoveryBit(b){return new D(this.r,this.s,b)}recoverPublicKey(b){let{r:C,s:_}=this,E=this.assertRecovery(),T=E===2||E===3?C+c:C;if(!i.isValid(T))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let P=i.toBytes(T),k=r.fromBytes(me(Mh((E&1)===0),P)),H=a.inv(T),K=B(V(b,void 0,"msgHash")),Q=a.create(-K*H),ee=a.create(_*H),te=r.BASE.multiplyUnsafe(Q).add(k.multiplyUnsafe(ee));if(te.is0())throw new Error("invalid recovery: point at infinify");return te.assertValidity(),te}hasHighS(){return m(this.s)}toBytes(b=x.format){if(Qa(b),b==="der")return Hr(tt.hexFromSig(this));let{r:C,s:_}=this,E=a.toBytes(C),T=a.toBytes(_);return b==="recovered"?(L(),me(Uint8Array.of(this.assertRecovery()),E,T)):me(E,T)}toHex(b){return Kr(this.toBytes(b))}}Object.freeze(D.prototype),Object.freeze(D);let O=t.bits2int===void 0?function(b){if(b.length>8192)throw new Error("input is too large");let C=lr(b),_=b.length*8-f;return _>0?C>>BigInt(_):C}:t.bits2int,B=t.bits2int_modN===void 0?function(b){return a.create(O(b))}:t.bits2int_modN,I=Kn(f);function U(w){return xt("num < 2^"+f,w,ut,I),a.toBytes(w)}function F(w,b){return V(w,void 0,"message"),b?V(n(w),void 0,"prehashed message"):w}function N(w,b,C){let{lowS:_,prehash:E,extraEntropy:T}=Ja(C,x);w=F(w,E);let P=B(w),k=a.fromBytes(b);if(!a.isValidNot0(k))throw new Error("invalid private key");let H=[U(k),U(P)];if(T!=null&&T!==!1){let te=T===!0?o(y.secretKey):T;H.push(V(te,void 0,"extraEntropy"))}let K=me(...H),Q=P;function ee(te){let j=O(te);if(!a.isValidNot0(j))return;let ae=a.inv(j),mt=r.BASE.multiply(j).toAffine(),rr=a.create(mt.x);if(rr===ut)return;let Br=a.create(ae*a.create(Q+rr*k));if(Br===ut)return;let vn=(mt.x===rr?0:2)|Number(mt.y&Wt),Cn=Br;return _&&m(Br)&&(Cn=a.neg(Br),vn^=1),new D(rr,Cn,l?void 0:vn)}return{seed:K,k2sig:ee}}function g(w,b,C={}){let{seed:_,k2sig:E}=N(w,b,C);return zu(n.outputLen,a.BYTES,s)(_,E).toBytes(C.format)}function A(w,b,C,_={}){let{lowS:E,prehash:T,format:P}=Ja(_,x);if(C=V(C,void 0,"publicKey"),b=F(b,T),!ur(w)){let k=w instanceof D?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+k)}R(w,P);try{let k=D.fromBytes(w,P),H=r.fromBytes(C);if(E&&k.hasHighS())return!1;let{r:K,s:Q}=k,ee=B(b),te=a.inv(Q),j=a.create(ee*te),ae=a.create(K*te),mt=r.BASE.multiplyUnsafe(j).add(H.multiplyUnsafe(ae));return mt.is0()?!1:a.create(mt.x)===K}catch{return!1}}function S(w,b,C={}){let{prehash:_}=Ja(C,x);return b=F(b,_),D.fromBytes(w,"recovered").recoverPublicKey(b).toBytes()}return Object.freeze({keygen:u,getPublicKey:h,getSharedSecret:p,utils:d,lengths:y,Point:r,sign:g,verify:A,recoverPublicKey:S,Signature:D,hash:n})}var rc={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},O0={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Vh=BigInt(2);function P0(r){let e=rc.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=se(u,t,e)*u%e,p=se(h,t,e)*u%e,d=se(p,Vh,e)*f%e,y=se(d,o,e)*d%e,x=se(y,s,e)*y%e,l=se(x,a,e)*x%e,m=se(l,c,e)*l%e,v=se(m,a,e)*x%e,L=se(v,t,e)*u%e,R=se(L,i,e)*y%e,D=se(R,n,e)*f%e,O=se(D,Vh,e);if(!tc.eql(tc.sqr(O),r))throw new Error("Cannot find square root");return O}var tc=zr(rc.p,{sqrt:P0}),U0=kh(rc,{Fp:tc,endo:O0}),Yr=Hh(U0,ct);function zh(r,e,t,n){let o=gt.digest(t instanceof Uint8Array?t:t.subarray());if(fs(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),Yr.verify(e,s,r,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new jn(String(s))});try{return n?.signal?.throwIfAborted(),Yr.verify(e,o.digest,r,{prehash:!1,format:"der"})}catch(s){throw new jn(String(s))}}var bs=class{type="secp256k1";raw;_key;constructor(e){this._key=qh(e),this.raw=$h(this._key)}toMultihash(){return Xe.digest(Pt(this))}toCID(){return pe.createV1(114,this.toMultihash())}toString(){return he.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ee(this.raw,e.raw)}verify(e,t,n){return zh(this._key,t,e,n)}};function nc(r){return new bs(r)}function $h(r){return Yr.Point.fromBytes(r).toBytes()}function qh(r){try{return Yr.Point.fromBytes(r),r}catch(e){throw new Tr(String(e))}}function eo(r,e){let{Type:t,Data:n}=ft.decode(r),o=n??new Uint8Array;switch(t){case fe.RSA:return Xa(o,e);case fe.Ed25519:return Ca(o);case fe.secp256k1:return nc(o);case fe.ECDSA:return Xi(o);default:throw new nr}}function jh(r){let{Type:e,Data:t}=ft.decode(r.digest),n=t??new Uint8Array;switch(e){case fe.Ed25519:return Ca(n);case fe.secp256k1:return nc(n);case fe.ECDSA:return Xi(n);default:throw new nr}}function Pt(r){return ft.encode({Type:fe[r.type],Data:r.raw})}var Gh=Symbol.for("nodejs.util.inspect.custom"),N0=114,to=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()})`}[xi]=!0;toString(){return this.string==null&&(this.string=he.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return pe.createV1(N0,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return Ee(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return Ee(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Gh](){return`PeerId(${this.toString()})`}},ro=class extends to{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},no=class extends to{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},oo=class extends to{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},F0=2336,so=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Xe.digest(Y(this.url))}[Gh](){return`PeerId(${this.url})`}[xi]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return pe.createV1(F0,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=G(e)),e.toString()===this.toString())}};var k0=114,Wh=2336;function Zr(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=Fr(he.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return M0(pe.parse(r));if(e==null)throw new $('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=Fr(e.decode(r))}return Xh(t)}function oc(r){if(r.type==="Ed25519")return new no({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new oo({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new ro({multihash:r.toCID().multihash,publicKey:r});throw new nr}function Xh(r){if(H0(r))return new ro({multihash:r});if(K0(r))try{let e=jh(r);if(e.type==="Ed25519")return new no({multihash:r,publicKey:e});if(e.type==="secp256k1")return new oo({multihash:r,publicKey:e})}catch{let t=G(r.digest);return new so(new URL(t))}throw new Fo("Supplied PeerID Multihash is invalid")}function M0(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==k0&&r.code!==Wh)throw new No("Supplied PeerID CID is invalid");if(r.code===Wh){let e=G(r.multihash.digest);return new so(new URL(e))}return Xh(r.multihash)}function K0(r){return r.code===Xe.code}function H0(r){return r.code===gt.code}var Ce=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},vt=class extends Error{static name="ValidationError";name="ValidationError"},ws=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},xs=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var Es=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 p=Number.parseInt(h,e);if(!Number.isNaN(p))return p});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 V0=45,z0=15,Ss=new Es;function Yh(r){if(!(r.length>z0))return Ss.new(r).parseWith(()=>Ss.readIPv4Addr())}function Zh(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>V0))return Ss.new(r).parseWith(()=>Ss.readIPv6Addr())}function As(r){return!!Yh(r)}function Jh(r){return!!Zh(r)}function ic(r){return e=>G(e,r)}function ac(r){return e=>Y(e,r)}function Jr(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 Qh(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=Y(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 Me([t,o],t.length+o.length)}function el(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=Rt.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 Me([t,o],t.length+o.length)}function cc(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=G(e,"base32"),o=Jr(t);return`${n}:${o}`}var fc=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 Ce("Invalid byte value in IP address");e[n]=o}),e},tl=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=As(t[n]),i;s&&(i=fc(t[n]),t[n]=G(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,G(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 Ce("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},rl=function(r){if(r.byteLength!==4)throw new Ce("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},nl=function(r){if(r.byteLength!==16)throw new Ce("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 Ce(`Invalid IPv6 address "${t}"`)}};function ol(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Ce(`Invalid IPv6 address "${r}"`)}}var sc=Object.values(ir).map(r=>r.decoder),$0=(function(){let r=sc[0].or(sc[1]);return sc.slice(2).forEach(e=>r=r.or(e)),r})();function sl(r){return $0.decode(r)}function il(r){return e=>r.encoder.encode(e)}function q0(r){if(parseInt(r).toString()!==r)throw new vt("Value must be an integer")}function j0(r){if(r<0)throw new vt("Value must be a positive integer, or zero")}function G0(r){return e=>{if(e>r)throw new vt(`Value must be smaller than or equal to ${r}`)}}function W0(...r){return e=>{for(let t of r)t(e)}}var io=W0(q0,j0,G0(65535));var xe=-1,uc=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 xs(`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)}))}},Lt=new uc,cg=[{code:4,name:"ip4",size:32,valueToBytes:fc,bytesToValue:rl,validate:r=>{if(!As(r))throw new vt(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:xr,bytesToValue:Jr,validate:io},{code:273,name:"udp",size:16,valueToBytes:xr,bytesToValue:Jr,validate:io},{code:33,name:"dccp",size:16,valueToBytes:xr,bytesToValue:Jr,validate:io},{code:41,name:"ip6",size:128,valueToBytes:tl,bytesToValue:nl,stringToValue:ol,validate:r=>{if(!Jh(r))throw new vt(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:xe},{code:43,name:"ipcidr",size:8,bytesToValue:ic("base10"),valueToBytes:ac("base10")},{code:53,name:"dns",size:xe},{code:54,name:"dns4",size:xe},{code:55,name:"dns6",size:xe},{code:56,name:"dnsaddr",size:xe},{code:132,name:"sctp",size:16,valueToBytes:xr,bytesToValue:Jr,validate:io},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:xe,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:xe,bytesToValue:ic("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?ac("base58btc")(r):pe.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:cc,valueToBytes:Qh},{code:445,name:"onion3",size:296,bytesToValue:cc,valueToBytes:el},{code:446,name:"garlic64",size:xe},{code:447,name:"garlic32",size:xe},{code:448,name:"tls"},{code:449,name:"sni",size:xe},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:xe,bytesToValue:il(Dn),valueToBytes:sl},{code:480,name:"http"},{code:481,name:"http-path",size:xe,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:xe}];cg.forEach(r=>{Lt.addProtocol(r)});function al(r){let e=[],t=0;for(;t<r.length;){let n=At(r,t),o=Lt.getProtocol(n),s=ie(n),i=fg(o,r,t+s),a=0;i>0&&o.size===xe&&(a=ie(i));let c=s+a+i,f={code:n,name:o.name,bytes:Se(r.subarray(t,t+c))};if(i>0){let u=t+s+a,h=r.subarray(u,u+i);f.value=o.bytesToValue?.(h)??G(h)}e.push(f),t+=c}return e}function cl(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=Lt.getProtocol(n.code),s=ie(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??Y(n.value),a=i.byteLength,o.size===xe&&(c=ie(a)));let f=new Uint8Array(s+c+a),u=0;Wr(n.code,f,u),u+=s,i!=null&&(o.size===xe&&(Wr(a,f,u),u+=c),f.set(i,u)),n.bytes=f}t.push(n.bytes),e+=n.bytes.byteLength}return Me(t,e)}function fl(r){if(r.charAt(0)!=="/")throw new Ce('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=Lt.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 Ce(`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 Ce(`Component ${o} was missing value`);f.value=c.stringToValue?.(n)??n}e.push(f),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new Ce("Incomplete multiaddr");return e}function ul(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=Lt.getProtocol(e.code);if(t==null)throw new Ce(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function fg(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:At(e,t)}var ug=Symbol.for("nodejs.util.inspect.custom"),_c=Symbol.for("@multiformats/multiaddr");function hg(r){if(r==null&&(r="/"),hl(r))return r.getComponents();if(r instanceof Uint8Array)return al(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),fl(r);if(Array.isArray(r))return r;throw new Ce("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Is=class r{[_c]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=hg(e),t.validate!==!1&&lg(this)}get bytes(){return this.#r==null&&(this.#r=cl(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=ul(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 ws(`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 Ee(this.bytes,e.bytes)}[ug](){return`Multiaddr(${this.toString()})`}};function lg(r){r.getComponents().forEach(e=>{let t=Lt.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function hl(r){return!!r?.[_c]}function rn(r){return new Is(r)}var ne=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),M=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),ll=r=>({match:e=>r.match(e)===!1?e:!1}),z=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),De=(...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}}),W=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e}});function oe(...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 dg=M(421),h6=oe(dg),Ts=M(54),Ds=M(55),Rs=M(56),Bc=M(53),l6=oe(Ts,z(M(421))),d6=oe(Ds,z(M(421))),p6=oe(Rs,z(M(421))),m6=oe(De(Bc,Rs,Ts,Ds),z(M(421))),dl=W(M(4),z(M(43))),pl=W(z(M(42)),M(41),z(M(43))),Tc=De(dl,pl),nn=De(Tc,Bc,Ts,Ds,Rs),g6=oe(De(Tc,W(De(Bc,Rs,Ts,Ds),z(M(421))))),y6=oe(dl),b6=oe(pl),w6=oe(Tc),Dc=W(nn,M(6)),ao=W(nn,M(273)),x6=oe(W(Dc,z(M(421)))),E6=oe(ao),Rc=W(ao,ne(460),z(M(421))),Os=W(ao,ne(461),z(M(421))),pg=De(Rc,Os),S6=oe(Rc),A6=oe(Os),Ic=De(nn,Dc,ao,Rc,Os),ml=De(W(Ic,ne(477),z(M(421)))),v6=oe(ml),gl=De(W(Ic,ne(478),z(M(421))),W(Ic,ne(448),z(M(449)),ne(477),z(M(421)))),C6=oe(gl),yl=W(ao,ne(280),z(M(466)),z(M(466)),z(M(421))),bl=oe(yl),wl=W(Os,ne(465),z(M(466)),z(M(466)),z(M(421))),L6=oe(wl),Bs=De(ml,gl,W(Dc,z(M(421))),W(pg,z(M(421))),W(nn,z(M(421))),yl,wl,M(421)),xl=oe(Bs),mg=W(z(Bs),ne(290),ll(ne(281)),z(M(421))),_6=oe(mg),gg=De(W(Bs,ne(290),ne(281),z(M(421))),W(Bs,ne(281),z(M(421))),W(ne(281),z(M(421)))),El=oe(gg),yg=W(nn,De(W(M(6,"80")),W(M(6),ne(480)),ne(480)),z(M(481)),z(M(421))),I6=oe(yg),bg=W(nn,De(W(M(6,"443")),W(M(6,"443"),ne(480)),W(M(6),ne(443)),W(M(6),ne(448),ne(480)),W(ne(448),ne(480)),ne(448),ne(443)),z(M(481)),z(M(421))),B6=oe(bg),wg=De(W(M(777),z(M(421)))),T6=oe(wg),xg=De(W(M(400),z(M(421)))),D6=oe(xg);var Re;(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=()=>wr(t)})(e=r.Flag||(r.Flag={}));let n;r.codec=()=>(n==null&&(n=Gt((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 p=a.uint32();switch(p>>>3){case 1:{u.flag=r.Flag.codec().decode(a);break}case 2:{u.message=a.bytes();break}default:{a.skipType(p&7);break}}}return u},function*(a,c,f,u={}){let h=c==null?a.len:a.pos+c;for(;a.pos<h;){let p=a.uint32();switch(p>>>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(p&7);break}}}})),n);function o(a){return qt(a,r.codec())}r.encode=o;function s(a,c){return $t(a,r.codec(),c)}r.decode=s;function i(a,c){return jt(a,r.codec(),c)}r.stream=i})(Re||(Re={}));var Sl=["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478","stun:stun.cloudflare.com:3478","stun:stun.services.mozilla.com:3478"],Oc=Array.from("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"),Al="libp2p+webrtc+v1/",vl=2*1024*1024,on=16*1024;function Eg(r=on){let e=ie(r-ie(r)),t=1+ie(Object.keys(Re.Flag).length-1),n=1,o=r-e-t-n,s=ie(o);return e+t+n+s}var Cl=Eg();var Ll=1e4,Pc="/webrtc",co="/webrtc-signaling/0.0.1";function Sg(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 Uc(r){let e=Sg(r);if(e==null)throw new $(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e}function Ps(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Us=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}},sn=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Us(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 Us(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 Nc=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function an(r={}){return Ag(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 Ag(r,e){e=e??{};let t=e.onEnd,n=new sn,o,s,i,a=Ps(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((l,m)=>{s=v=>{s=null,n.push(v);try{l(r(n))}catch(L){m(L)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Ps()})}},f=l=>s!=null?s(l):(n.push(l),o),u=l=>(n=new sn,s!=null?s({error:l}):(n.push({error:l}),o)),h=l=>{if(i)return o;if(e?.objectMode!==!0&&l?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return f({done:!1,value:l})},p=l=>i?o:(i=!0,l!=null?u(l):f({done:!0})),d=()=>(n=new sn,p(),{done:!0}),y=l=>(p(l),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:d,throw:y,push:h,end:p,get readableLength(){return n.size},onEmpty:async l=>{let m=l?.signal;if(m?.throwIfAborted(),n.isEmpty())return;let v,L;m!=null&&(v=new Promise((R,D)=>{L=()=>{D(new Nc)},m.addEventListener("abort",L)}));try{await Promise.race([a.promise,v])}finally{L!=null&&m!=null&&m?.removeEventListener("abort",L)}}},t==null)return o;let x=o;return o={[Symbol.asyncIterator](){return this},next(){return x.next()},throw(l){return x.throw(l),t!=null&&(t(l),t=void 0),{done:!0}},return(){return x.return(),t!=null&&(t(),t=void 0),{done:!0}},push:h,end(l){return x.end(l),t!=null&&(t(l),t=void 0),o},get readableLength(){return x.readableLength},onEmpty:l=>x.onEmpty(l)},o}var Fc=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},_l=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,p)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(i?.aborted){p(_l(i));return}if(i&&(c=()=>{p(_l(i))},i.addEventListener("abort",c,{once:!0})),r.then(h,p),t===Number.POSITIVE_INFINITY)return;let d=new Fc;a=s.setTimeout.call(void 0,()=>{if(n){try{h(n())}catch(y){p(y)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?h():o instanceof Error?p(o):(d.message=o??`Promise timed out after ${t} milliseconds`,p(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 vg=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 Cg(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}=vg(r),h=async(...d)=>{let y=t.multiArgs?d:d[0];if(t.filter)try{if(!await t.filter(y))return}catch(x){n(),i(x);return}c.push(y),t.count===c.length&&(n(),s(c))},p=(...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,p)};for(let d of a)f(d,h);for(let d of t.rejectionEvents)a.includes(d)||f(d,p);t.signal&&t.signal.addEventListener("abort",()=>{p(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 Le(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=Cg(r,e,t),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}var Sr=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"},Ns=class extends Error{static name="MaxEarlyStreamsError";name="MaxEarlyStreamsError"},Fs=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function Lg(r){return r.reason}async function _t(r,e,t){if(e==null)return r;let n=t?.translateError??Lg;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let o;try{return await Promise.race([r,new Promise((s,i)=>{o=()=>{i(n(e))},e.addEventListener("abort",o)})])}finally{o!=null&&e.removeEventListener("abort",o)}}var _g=Math.pow(2,20)*4,Yt=class extends Tt{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;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??_g,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new X,this.writeBuffer=new X,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 Fs)};this.addEventListener("close",n)}get readBufferLength(){return this.readBuffer.byteLength}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),_t(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let e=an(),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 ot(`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();try{this.sendReset(e)}catch(t){this.log("failed to send reset to remote - %e",t)}this.dispatchEvent(new Ko(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new ot("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 ot("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 ot(`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 ot(`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");let e=new Dr;this.dispatchEvent(new Ho(e))}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.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.dispatchEvent(new Rr))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.writeStatus==="closed"&&this.onTransportClosed())}onRemoteCloseRead(){this.log.trace("on remote close read"),this.remoteReadStatus="closed",this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle"))}processSendQueue(){if(this.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(this.writeBuffer.byteLength===0)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;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 X(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}}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 Mo(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.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new Ln(`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 Ln(`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 ks=class extends Yt{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 Le(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 Le(this,"drain",{...e,rejectionEvents:["close"]})),await this.sendClose(e),this.onTransportClosed())}};function Il(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Ms=class extends Tt{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 _t(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 Po;let t=this.onCreateStream({...this.streamOptions,...e});return Il(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 Ns(`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 Ks=class extends Yt{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 Le(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 Le(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.log("closed readable end gracefully"))}};var Ig=4194304,Hs=class extends Error{static name="UnwrappedError";name="UnwrappedError"},fo=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Kc=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Hc=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Bg(r){return typeof r?.closeRead=="function"}function Tg(r){return typeof r?.close=="function"}function Mc(r){return Bg(r)?r.remoteWriteStatus!=="writable"&&r.readBufferLength===0:Tg(r)?r.status!=="open":!1}function Dg(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function Rg(r,e){let t=e?.maxBufferSize??Ig,n=new X,o,s=!1;if(!Dg(r))throw new $("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 Hs("Stream was unwrapped");if(Mc(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 Sr(`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 _t(o.promise,u?.signal),Mc(r)){if(n.byteLength===0&&u?.bytes==null)return null;break}o=Promise.withResolvers()}let p=u?.bytes??n.byteLength;if(n.byteLength<p){if(Mc(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,p),new Sr(`Unexpected EOF - stream closed while reading ${n.byteLength}/${p} bytes`);return f.read(u)}let d=n.sublist(0,p);return n.consume(p),d},async write(u,h){if(s===!0)throw new Hs("Stream was unwrapped");r.send(u)||await Le(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 Vs(r,e={}){let t=Rg(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=ie(e.maxDataLength));let n=e?.lengthDecoder??At,o=e?.lengthEncoder??hs;return{async read(i){let a=-1,c=new X;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 fo("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new Hc(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new Kc(`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 Sr(`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 Sr(`Unexpected EOF - read ${f.byteLength}/${a} bytes before the stream closed`);return f},async write(i,a){await t.write(new X(o(i.byteLength),i),a)},async writeV(i,a){let c=new X(...i.flatMap(f=>[o(f.byteLength),f]));await t.write(c,a)},unwrap(){return t.unwrap()}}}function zs(r,e){let t=Vs(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 Og=1024*1024*4,Pg=1024*1024*4,$s=class{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(e={}){this.buffer=new X,this.maxBufferSize=e.maxBufferSize??Og,this.maxDataLength=e.maxDataLength??Pg,this.lengthDecoder=e.lengthDecoder??At,this.encodingLength=e.encodingLength??ie}*decode(e){if(this.buffer.append(e),this.buffer.byteLength>this.maxBufferSize)throw new $(`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 fo("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 qs=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},cn=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},js=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},uo=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Gs(r){return r[Symbol.asyncIterator]!=null}function Bl(r,e){if(r.byteLength>e)throw new cn("Message length too long")}var Xs=r=>{let e=ie(r),t=be(e);return hs(r,t),Xs.bytes=e,t};Xs.bytes=0;function ho(r,e){e=e??{};let t=e.lengthEncoder??Xs,n=e?.maxDataLength??4194304;function*o(s){Bl(s,n);let i=t(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return Gs(r)?(async function*(){for await(let s of r)yield*o(s)})():(function*(){for(let s of r)yield*o(s)})()}ho.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Xs,n=e?.maxDataLength??4194304;return Bl(r,n),new X(t(r.byteLength),r)};var Ar;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Ar||(Ar={}));var Vc=r=>{let e=At(r);return Vc.bytes=ie(e),e};Vc.bytes=0;function lo(r,e){let t=new X,n=Ar.LENGTH,o=-1,s=e?.lengthDecoder??Vc,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===Ar.LENGTH)try{if(o=s(t),o<0)throw new qs("Invalid message length");if(o>a)throw new cn("Message length too long");let f=s.bytes;t.consume(f),e?.onLength!=null&&e.onLength(o),n=Ar.DATA}catch(f){if(f instanceof RangeError){if(t.byteLength>i)throw new js("Message length length too long");break}throw f}if(n===Ar.DATA){if(t.byteLength<o)break;let f=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(f),yield f,n=Ar.LENGTH}}}return Gs(r)?(async function*(){for await(let f of r)t.append(f),yield*c();if(t.byteLength>0)throw new uo("Unexpected end of input")})():(function*(){for(let f of r)t.append(f),yield*c();if(t.byteLength>0)throw new uo("Unexpected end of input")})()}lo.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 lo(n,{...e??{},onLength:s=>{t=s}})};var zc=class extends Ks{channel;incomingData;maxBufferedAmount;receivedFinAck;finAckTimeout;constructor(e){super({...e,maxMessageSize:(e.maxMessageSize??on)-Cl}),this.channel=e.channel,this.channel.binaryType="arraybuffer",this.incomingData=an(),this.maxBufferedAmount=e.maxBufferedAmount??vl,this.finAckTimeout=e.finAckTimeout??Ll,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 lo(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),Le(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 ot(`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(Se(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(ho.single(Re.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(Re.Flag.RESET),this.receivedFinAck?.reject(e)}catch(t){this.log.error("failed to send reset - %e",t)}}async sendCloseWrite(e){this._sendFlag(Re.Flag.FIN),e?.signal?.throwIfAborted(),this.receivedFinAck=Promise.withResolvers();let t=e?.signal??AbortSignal.timeout(this.finAckTimeout),n=[Le(this.channel,"close",{signal:t}),Le(this.channel,"error",{signal:t})];await Promise.any([_t(this.receivedFinAck.promise,t),...n]).finally(()=>{n.forEach(o=>o.cancel())})}async sendCloseRead(e){this._sendFlag(Re.Flag.STOP_SENDING),e?.signal?.throwIfAborted()}processIncomingProtobuf(e){let t=Re.decode(e);t.message!=null&&(this.readStatus==="readable"||this.readStatus==="paused")&&this.onData(new X(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===Re.Flag.FIN&&(this._sendFlag(Re.Flag.FIN_ACK),this.onRemoteCloseWrite()),t.flag===Re.Flag.RESET&&(this.receivedFinAck?.reject(new Dr("The stream was reset")),this.onRemoteReset()),t.flag===Re.Flag.STOP_SENDING&&this.onRemoteCloseRead(),t.flag===Re.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=Re.encode({flag:e}),n=ho.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 po(r){let{channel:e,direction:t,isHandshake:n}=r;return new zc({...r,id:`${e.id}`,log:r.log.newScope(`${n===!0?"handshake":t}:${e.id}`),protocol:""})}var Zt=class{protocol;peerConnection;metrics;dataChannelOptions;earlyDataChannels;constructor(e){this.onEarlyDataChannel=this.onEarlyDataChannel.bind(this),this.peerConnection=e.peerConnection,this.metrics=e.metrics,this.protocol=e.protocol??Pc,this.dataChannelOptions=e.dataChannelOptions??{},this.peerConnection.addEventListener("datachannel",this.onEarlyDataChannel),this.earlyDataChannels=[]}onEarlyDataChannel(e){this.earlyDataChannels.push(e.channel)}createStreamMuxer(e){return this.peerConnection.removeEventListener("datachannel",this.onEarlyDataChannel),new $c(e,{peerConnection:this.peerConnection,dataChannelOptions:this.dataChannelOptions,metrics:this.metrics,protocol:this.protocol,earlyDataChannels:this.earlyDataChannels})}},$c=class extends Ms{peerConnection;dataChannelOptions;constructor(e,t){super(e,{...t,name:"muxer"}),this.peerConnection=t.peerConnection,this.protocol=t.protocol??Pc,this.dataChannelOptions=t.dataChannelOptions??{},this.peerConnection.ondatachannel=({channel:n})=>{this.onDataChannel(n)},queueMicrotask(()=>{if(this.status!=="open"){t.earlyDataChannels.forEach(n=>{n.close()});return}t.earlyDataChannels.forEach(n=>{this.onDataChannel(n)})})}onDataChannel(e){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),e.close();return}let t=po({...this.streamOptions,...this.dataChannelOptions,channel:e,direction:"inbound",log:this.log});this.onRemoteStream(t)}async onCreateStream(e){let t=this.peerConnection.createDataChannel("",{});return this.log("open channel %d for protocol %s",t.id,e?.protocol),po({...e,...this.dataChannelOptions,channel:t,direction:"outbound",log:this.log})}onData(){}};var qc=class extends ks{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(){}},mo=r=>new qc(r);async function jc(r){return r=r??{},typeof r=="function"&&(r=await r()),r.iceServers=r.iceServers??Sl.map(e=>({urls:[e]})),r}var Tl=(r=32)=>Al+[...Array(r)].map(()=>Oc.at(Math.floor(Math.random()*Oc.length))).join("");var Ys=globalThis.RTCPeerConnection,Zs=globalThis.RTCSessionDescription,Dl=globalThis.RTCIceCandidate;var ze=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var Jt=class extends Error{constructor(e){super(`WebRTC transport error: ${e}`),this.name="WebRTCTransportError"}},Ge=class extends Jt{constructor(e="SDP handshake failed"){super(e),this.name="SDPHandshakeFailedError"}};var Js=class extends Jt{constructor(e,t){super(`Invalid fingerprint "${e}" within ${t}`),this.name="WebRTC/InvalidFingerprintError"}};var Qs=class extends Jt{constructor(e){super(`A method (${e}) was called though it has been intentionally left unimplemented.`),this.name="WebRTC/UnimplementedError"}},ei=class extends Jt{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 ke;(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=()=>wr(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Gt((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 p=a.uint32();switch(p>>>3){case 1:{u.type=r.Type.codec().decode(a);break}case 2:{u.data=a.string();break}default:{a.skipType(p&7);break}}}return u},function*(a,c,f,u={}){let h=c==null?a.len:a.pos+c;for(;a.pos<h;){let p=a.uint32();switch(p>>>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(p&7);break}}}})),n);function o(a){return qt(a,r.codec())}r.encode=o;function s(a,c){return $t(a,r.codec(),c)}r.decode=s;function i(a,c){return jt(a,r.codec(),c)}r.stream=i})(ke||(ke={}));var ti=async(r,e,t)=>{try{let n=Promise.withResolvers();for(Fg(r,n);;){let o=await Promise.race([n.promise,e.read({signal:t.signal})]);if(o==null){t.signal?.throwIfAborted();break}if(o.type!==ke.Type.ICE_CANDIDATE)throw new ko("ICE candidate message expected");let s=JSON.parse(o.data??"null");if(s===""||s===null){t.onProgress?.(new ze("webrtc:end-of-ice-candidates")),t.log.trace("end-of-candidates received");continue}let i=new Dl(s);t.log.trace("%s received new ICE candidate %o",t.direction,s);try{t.onProgress?.(new ze("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 Fg(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 Oo(`RTCPeerConnection connection state became "${r.connectionState}"`));break;default:break}}}function ri(r){let e;for(let t of r.getComponents())t.name==="p2p"&&(e=Zr(t.value??""));if(e==null)throw new Uo("Remote peerId must be present in multiaddr");return e}async function Rl({rtcConfiguration:r,dataChannel:e,signal:t,metrics:n,multiaddr:o,connectionManager:s,transportManager:i,log:a,logger:c,onProgress:f}){let{circuitAddress:u,targetPeer:h}=Ol(o);n?.dialerEvents.increment({open:!0}),a.trace("dialing circuit address: %a",u);let p=s.getConnections(h),d;p.length===0?(f?.(new ze("webrtc:dial-relay")),d=await i.dial(u,{signal:t,onProgress:f})):(f?.(new ze("webrtc:reuse-relay-connection")),d=p[0]),f?.(new ze("webrtc:open-signaling-stream"));let y=await d.newStream(co,{signal:t,runOnLimitedConnection:!0}),x=zs(y).pb(ke),l=new Ys(r);l.addEventListener("connectionstatechange",()=>{l.connectionState==="closed"&&l.close()});let m=new Zt({peerConnection:l,dataChannelOptions:e});try{let v=l.createDataChannel("init");l.onicecandidate=({candidate:O})=>{if(l.connectionState==="connected"){a.trace("ignore new ice candidate as peer connection is already connected");return}if(O==null||O?.candidate===""){a.trace("initiator detected end of ICE candidates");return}let B=JSON.stringify(O?.toJSON()??null);a.trace("initiator sending ICE candidate %o",O),x.write({type:ke.Type.ICE_CANDIDATE,data:B},{signal:t}).catch(I=>{a.error("error sending ICE candidate - %e",I)})},l.onicecandidateerror=O=>{a.error("initiator ICE candidate error",O)};let L=await l.createOffer().catch(O=>{throw a.error("could not execute createOffer - %e",O),new Ge("Failed to set createOffer")});a.trace("initiator send SDP offer %s",L.sdp),f?.(new ze("webrtc:send-sdp-offer")),await x.write({type:ke.Type.SDP_OFFER,data:L.sdp},{signal:t}),await l.setLocalDescription(L).catch(O=>{throw a.error("could not execute setLocalDescription - %e",O),new Ge("Failed to set localDescription")}),f?.(new ze("webrtc:read-sdp-answer")),a.trace("initiator read SDP answer");let R=await x.read({signal:t});if(R.type!==ke.Type.SDP_ANSWER)throw new Ge("Remote should send an SDP answer");a.trace("initiator received SDP answer %s",R.data);let D=new Zs({type:"answer",sdp:R.data});return await l.setRemoteDescription(D).catch(O=>{throw a.error("could not execute setRemoteDescription - %e",O),new Ge("Failed to set remoteDescription")}),a.trace("initiator read candidates until connected"),f?.(new ze("webrtc:read-ice-candidates")),await ti(l,x,{direction:"initiator",signal:t,log:a,onProgress:f}),a.trace("initiator connected"),v.readyState!=="open"&&(a.trace("wait for init channel to open"),await Le(v,"open",{signal:t})),a.trace("closing init channel"),v.close(),a.trace("waiting for init channel to close"),await Le(v,"close",{signal:t}),f?.(new ze("webrtc:close-signaling-stream")),a.trace("closing signaling channel"),await y.close({signal:t}),a.trace("initiator connected to remote address %s",o),{remoteAddress:o,peerConnection:l,muxerFactory:m}}catch(v){throw a.error("outgoing signaling error - %e",v),l.close(),y.abort(v),v}finally{l.onicecandidate=null,l.onicecandidateerror=null}}var Pl=oe(xl.matchers[0],ne(290)),ni=class r extends Tt{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=>Pl.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=>Pl.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 Ul(r,e,{peerConnection:t,signal:n,log:o}){o.trace("new inbound signaling stream");let s=zs(r).pb(ke);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 p=JSON.stringify(h?.toJSON()??null);o.trace("recipient sending ICE candidate %s",p),s.write({type:ke.Type.ICE_CANDIDATE,data:p},{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!==ke.Type.SDP_OFFER)throw new Ge(`expected message type SDP_OFFER, received: ${c.type??"undefined"} `);o.trace("recipient received SDP offer %s",c.data);let f=new Zs({type:"offer",sdp:c.data});await t.setRemoteDescription(f).catch(h=>{throw o.error("could not execute setRemoteDescription - %e",h),new Ge("Failed to set remoteDescription")});let u=await t.createAnswer().catch(h=>{throw o.error("could not execute createAnswer - %e",h),new Ge("Failed to create answer")});o.trace("recipient send SDP answer %s",u.sdp),await s.write({type:ke.Type.SDP_ANSWER,data:u.sdp},{signal:n}),await t.setLocalDescription(u).catch(h=>{throw o.error("could not execute setLocalDescription - %e",h),new Ge("Failed to set localDescription")}),o.trace("recipient read candidates until connected"),await ti(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=ri(e.remoteAddr),a=rn(`/webrtc/p2p/${i}`);return o.trace("recipient connected to remote address %s",a),{remoteAddress:a,remotePeer:i}}var oi=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"})})}[Vo]=!0;[Symbol.toStringTag]="@libp2p/webrtc";[Or]=["@libp2p/transport"];[Qf]=["@libp2p/identify","@libp2p/circuit-relay-v2-transport"];isStarted(){return this._started}async start(){await this.components.registrar.handle(co,(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(co),this._started=!1}createListener(e){return new ni(this.components,{shutdownController:this.shutdownController})}listenFilter(e){return e.filter(El.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 Rl({rtcConfiguration:await jc(this.init.rtcConfiguration),dataChannel:this.init.dataChannel,multiaddr:e,dataChannelOptions:this.init.dataChannel,signal:t.signal,connectionManager:this.components.connectionManager,transportManager:this.components.transportManager,log:this.log,logger:this.components.logger,onProgress:t.onProgress}),i=mo({peerConnection:o,remoteAddr:n,metrics:this.metrics?.dialerEvents,direction:"outbound",log:this.components.logger.forComponent("libp2p:webrtc:connection")}),a=await t.upgrader.upgradeOutbound(i,{skipProtection:!0,skipEncryption:!0,remotePeer:ri(e),muxerFactory:s,onProgress:t.onProgress,signal:t.signal});return this._closeOnShutdown(o,i),a}async _onProtocol(e,t,n){let o=new Ys(await jc(this.init.rtcConfiguration));o.addEventListener("connectionstatechange",()=>{o.connectionState==="closed"&&o.close()});let s=new Zt({peerConnection:o,dataChannelOptions:this.init.dataChannel});try{let{remoteAddress:i,remotePeer:a}=await Ul(e,t,{peerConnection:o,signal:n,log:this.log});await e.close({signal:n});let c=mo({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),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 Ol(r){let e=r.getComponents().filter(({name:n})=>n==="p2p").map(({value:n})=>n).pop();if(e==null)throw new $("Destination peer id was missing");return{circuitAddress:rn(r.getComponents().filter(({name:n})=>n!=="webrtc")),targetPeer:Zr(e)}}function ge(r=0){return new Uint8Array(r)}function Oe(r=0){return new Uint8Array(r)}var fn=!!globalThis.process?.env?.DUMP_SESSION_KEYS,Gc=16;function kg(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}function si(r){if(typeof r!="boolean")throw new TypeError(`boolean expected, not ${r}`)}function un(r){if(typeof r!="number")throw new TypeError("number expected, got "+typeof r);if(!Number.isSafeInteger(r)||r<0)throw new RangeError("positive integer expected, got "+r)}function ye(r,e,t=""){let n=kg(r),o=r?.length,s=e!==void 0;if(!n||s&&o!==e){let i=t&&`"${t}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof r}`,f=i+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(f):new TypeError(f)}return r}function Wc(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function Nl(r,e,t=!1){ye(r,void 0,"output");let n=e.outputLen;if(r.length<n)throw new RangeError("digestInto() expects output buffer of length at least "+n);if(t&&!hn(r))throw new Error("invalid output, must be aligned")}function ht(r){return new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4))}function rt(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function Mg(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}var vr=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68,Kg=r=>r<<24&4278190080|r<<8&16711680|r>>>8&65280|r>>>24&255;var Hg=r=>{for(let e=0;e<r.length;e++)r[e]=Kg(r[e]);return r},It=vr?r=>r:Hg;function Fl(r,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(r,e)}function kl(r,e){if(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 Ml(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 Kl=(r,e)=>{function t(n,...o){if(ye(n,void 0,"key"),r.nonceLength!==void 0){let u=o[0];ye(u,r.varSizeNonce?void 0:r.nonceLength,"nonce")}let s=r.tagLength;s&&o[1]!==void 0&&ye(o[1],void 0,"AAD");let i=e(n,...o),a=(u,h)=>{if(h!==void 0){if(u!==2)throw new Error("cipher output not supported");ye(h,void 0,"output")}},c=!1;return{encrypt(u,h){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,ye(u),a(i.encrypt.length,h),i.encrypt(u,h)},decrypt(u,h){if(ye(u),s&&u.length<s)throw new Error('"ciphertext" expected length bigger than tagLength='+s);return a(i.decrypt.length,h),i.decrypt(u,h)}}}return Object.assign(t,r),t};function go(r,e,t=!0){if(e===void 0)return new Uint8Array(r);if(ye(e,void 0,"output"),e.length!==r)throw new Error('"output" expected Uint8Array of length '+r+", got: "+e.length);if(t&&!hn(e))throw new Error("invalid output, must be aligned");return e}function Hl(r,e,t){un(r),un(e),si(t);let n=new Uint8Array(16),o=Mg(n);return o.setBigUint64(0,BigInt(e),t),o.setBigUint64(8,BigInt(r),t),n}function hn(r){return r.byteOffset%4===0}function ln(r){return Uint8Array.from(ye(r))}var zl=r=>Uint8Array.from(r.split(""),e=>e.charCodeAt(0)),Vg=It(ht(zl("expand 16-byte k"))),zg=It(ht(zl("expand 32-byte k")));function q(r,e){return r<<e|r>>>32-e}var yo=64,$g=16,Xc=2**32-1,Vl=Uint32Array.of();function qg(r,e,t,n,o,s,i,a){let c=o.length,f=new Uint8Array(yo),u=ht(f),h=vr&&hn(o)&&hn(s),p=h?ht(o):Vl,d=h?ht(s):Vl;if(!vr){for(let y=0;y<c;i++){if(r(e,t,n,u,i,a),It(u),i>=Xc)throw new Error("arx: counter overflow");let x=Math.min(yo,c-y);for(let l=0,m;l<x;l++)m=y+l,s[m]=o[m]^f[l];y+=x}return}for(let y=0;y<c;i++){if(r(e,t,n,u,i,a),i>=Xc)throw new Error("arx: counter overflow");let x=Math.min(yo,c-y);if(h&&x===yo){let l=y/4;if(y%4!==0)throw new Error("arx: invalid block position");for(let m=0,v;m<$g;m++)v=l+m,d[v]=p[v]^u[m];y+=yo;continue}for(let l=0,m;l<x;l++)m=y+l,s[m]=o[m]^f[l];y+=x}}function $l(r,e){let{allowShortKeys:t,extendNonceFn:n,counterLength:o,counterRight:s,rounds:i}=Fl({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof r!="function")throw new Error("core must be a function");return un(o),un(i),si(s),si(t),(a,c,f,u,h=0)=>{ye(a,void 0,"key"),ye(c,void 0,"nonce"),ye(f,void 0,"data");let p=f.length;if(u=go(p,u,!1),un(h),h<0||h>=Xc)throw new Error("arx: counter overflow");let d=[],y=a.length,x,l;if(y===32)d.push(x=ln(a)),l=zg;else if(y===16&&t)x=new Uint8Array(32),x.set(a),x.set(a,16),l=Vg,d.push(x);else throw ye(a,32,"arx key"),new Error("invalid key size");(!vr||!hn(c))&&d.push(c=ln(c));let m=ht(x);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");let R=c.subarray(0,16);if(vr)n(l,m,ht(R),m);else{let D=It(Uint32Array.from(l));n(D,m,ht(R),m),rt(D),It(m)}c=c.subarray(16)}else vr||It(m);let v=16-o;if(v!==c.length)throw new Error(`arx: nonce must be ${v} or 16 bytes`);if(v!==12){let R=new Uint8Array(12);R.set(c,s?0:12-c.length),c=R,d.push(c)}let L=It(ht(c));try{return qg(r,l,m,L,f,u,h,i),u}finally{rt(...d)}}}function _e(r,e){return r[e++]&255|(r[e++]&255)<<8}var Yc=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=ln(ye(e,32,"key"));let t=_e(e,0),n=_e(e,2),o=_e(e,4),s=_e(e,6),i=_e(e,8),a=_e(e,10),c=_e(e,12),f=_e(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]=_e(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],p=i[5],d=i[6],y=i[7],x=i[8],l=i[9],m=_e(e,t+0),v=_e(e,t+2),L=_e(e,t+4),R=_e(e,t+6),D=_e(e,t+8),O=_e(e,t+10),B=_e(e,t+12),I=_e(e,t+14),U=s[0]+(m&8191),F=s[1]+((m>>>13|v<<3)&8191),N=s[2]+((v>>>10|L<<6)&8191),g=s[3]+((L>>>7|R<<9)&8191),A=s[4]+((R>>>4|D<<12)&8191),S=s[5]+(D>>>1&8191),w=s[6]+((D>>>14|O<<2)&8191),b=s[7]+((O>>>11|B<<5)&8191),C=s[8]+((B>>>8|I<<8)&8191),_=s[9]+(I>>>5|o),E=0,T=E+U*a+F*(5*l)+N*(5*x)+g*(5*y)+A*(5*d);E=T>>>13,T&=8191,T+=S*(5*p)+w*(5*h)+b*(5*u)+C*(5*f)+_*(5*c),E+=T>>>13,T&=8191;let P=E+U*c+F*a+N*(5*l)+g*(5*x)+A*(5*y);E=P>>>13,P&=8191,P+=S*(5*d)+w*(5*p)+b*(5*h)+C*(5*u)+_*(5*f),E+=P>>>13,P&=8191;let k=E+U*f+F*c+N*a+g*(5*l)+A*(5*x);E=k>>>13,k&=8191,k+=S*(5*y)+w*(5*d)+b*(5*p)+C*(5*h)+_*(5*u),E+=k>>>13,k&=8191;let H=E+U*u+F*f+N*c+g*a+A*(5*l);E=H>>>13,H&=8191,H+=S*(5*x)+w*(5*y)+b*(5*d)+C*(5*p)+_*(5*h),E+=H>>>13,H&=8191;let K=E+U*h+F*u+N*f+g*c+A*a;E=K>>>13,K&=8191,K+=S*(5*l)+w*(5*x)+b*(5*y)+C*(5*d)+_*(5*p),E+=K>>>13,K&=8191;let Q=E+U*p+F*h+N*u+g*f+A*c;E=Q>>>13,Q&=8191,Q+=S*a+w*(5*l)+b*(5*x)+C*(5*y)+_*(5*d),E+=Q>>>13,Q&=8191;let ee=E+U*d+F*p+N*h+g*u+A*f;E=ee>>>13,ee&=8191,ee+=S*c+w*a+b*(5*l)+C*(5*x)+_*(5*y),E+=ee>>>13,ee&=8191;let te=E+U*y+F*d+N*p+g*h+A*u;E=te>>>13,te&=8191,te+=S*f+w*c+b*a+C*(5*l)+_*(5*x),E+=te>>>13,te&=8191;let j=E+U*x+F*y+N*d+g*p+A*h;E=j>>>13,j&=8191,j+=S*u+w*f+b*c+C*a+_*(5*l),E+=j>>>13,j&=8191;let ae=E+U*l+F*x+N*y+g*d+A*p;E=ae>>>13,ae&=8191,ae+=S*h+w*u+b*f+C*c+_*a,E+=ae>>>13,ae&=8191,E=(E<<2)+E|0,E=E+T|0,T=E&8191,E=E>>>13,P+=E,s[0]=T,s[1]=P,s[2]=k,s[3]=H,s[4]=K,s[5]=Q,s[6]=ee,s[7]=te,s[8]=j,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;rt(n)}update(e){Wc(this),ye(e),e=ln(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,rt(this.h,this.r,this.buffer,this.pad)}digestInto(e){Wc(this),Nl(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}},ql=Ml(32,r=>new Yc(r));function jg(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],p=e[2],d=e[3],y=e[4],x=e[5],l=e[6],m=e[7],v=o,L=t[0],R=t[1],D=t[2],O=i,B=a,I=c,U=f,F=u,N=h,g=p,A=d,S=y,w=x,b=l,C=m,_=v,E=L,T=R,P=D;for(let H=0;H<s;H+=2)O=O+F|0,_=q(_^O,16),S=S+_|0,F=q(F^S,12),O=O+F|0,_=q(_^O,8),S=S+_|0,F=q(F^S,7),B=B+N|0,E=q(E^B,16),w=w+E|0,N=q(N^w,12),B=B+N|0,E=q(E^B,8),w=w+E|0,N=q(N^w,7),I=I+g|0,T=q(T^I,16),b=b+T|0,g=q(g^b,12),I=I+g|0,T=q(T^I,8),b=b+T|0,g=q(g^b,7),U=U+A|0,P=q(P^U,16),C=C+P|0,A=q(A^C,12),U=U+A|0,P=q(P^U,8),C=C+P|0,A=q(A^C,7),O=O+N|0,P=q(P^O,16),b=b+P|0,N=q(N^b,12),O=O+N|0,P=q(P^O,8),b=b+P|0,N=q(N^b,7),B=B+g|0,_=q(_^B,16),C=C+_|0,g=q(g^C,12),B=B+g|0,_=q(_^B,8),C=C+_|0,g=q(g^C,7),I=I+A|0,E=q(E^I,16),S=S+E|0,A=q(A^S,12),I=I+A|0,E=q(E^I,8),S=S+E|0,A=q(A^S,7),U=U+F|0,T=q(T^U,16),w=w+T|0,F=q(F^w,12),U=U+F|0,T=q(T^U,8),w=w+T|0,F=q(F^w,7);let k=0;n[k++]=i+O|0,n[k++]=a+B|0,n[k++]=c+I|0,n[k++]=f+U|0,n[k++]=u+F|0,n[k++]=h+N|0,n[k++]=p+g|0,n[k++]=d+A|0,n[k++]=y+S|0,n[k++]=x+w|0,n[k++]=l+b|0,n[k++]=m+C|0,n[k++]=v+_|0,n[k++]=L+E|0,n[k++]=R+T|0,n[k++]=D+P|0}var Gg=$l(jg,{counterRight:!1,counterLength:4,allowShortKeys:!1});var Wg=new Uint8Array(16),jl=(r,e)=>{r.update(e);let t=e.length%16;t&&r.update(Wg.subarray(t))},Xg=new Uint8Array(32);function Gl(r,e,t,n,o){o!==void 0&&ye(o,void 0,"AAD");let s=r(e,t,Xg),i=Hl(n.length,o?o.length:0,!0),a=ql.create(s);o&&jl(a,o),jl(a,n),a.update(i);let c=a.digest();return rt(s,i),c}var Yg=r=>(e,t,n)=>({encrypt(s,i){let a=s.length;i=go(a+16,i,!1),i.set(s);let c=i.subarray(0,-16);r(e,t,c,c,1);let f=Gl(r,e,t,c,n);return i.set(f,a),rt(f),i},decrypt(s,i){i=go(s.length-16,i,!1);let a=s.subarray(0,-16),c=s.subarray(-16),f=Gl(r,e,t,a,n);if(!kl(c,f))throw rt(f),new Error("invalid tag");return i.set(s.subarray(0,-16)),r(e,t,i,i,1),rt(f),i}}),Zc=Kl({blockSize:64,nonceLength:12,tagLength:16},Yg(Gg));function Xl(r,e,t){return ar(r),t===void 0&&(t=new Uint8Array(r.outputLen)),Qn(r,t,e)}var Jc=Uint8Array.of(0),Wl=Uint8Array.of();function Yl(r,e,t,n=32){ar(r),it(n,"length"),Ie(e,void 0,"prk");let o=r.outputLen;if(e.length<o)throw new Error('"prk" must be at least HashLen octets');if(n>255*o)throw new Error("Length must be <= 255*HashLen");let s=Math.ceil(n/o);t===void 0?t=Wl:Ie(t,void 0,"info");let i=new Uint8Array(s*o),a=Qn.create(r,e),c=a._cloneInto(),f=new Uint8Array(a.outputLen);for(let u=0;u<s;u++)Jc[0]=u+1,c.update(u===0?Wl:f).update(t).update(Jc).digestInto(f),i.set(f,o*u),a._cloneInto(c);return a.destroy(),c.destroy(),Ye(f,Jc),i.slice(0,n)}var Qc={hashSHA256(r){return ct(r.subarray())},getHKDF(r,e){let t=Xl(ct,e,r),o=Yl(ct,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=qn.utils.randomSecretKey();return{publicKey:qn.getPublicKey(r),privateKey:r}},generateX25519KeyPairFromSeed(r){return{publicKey:qn.getPublicKey(r),privateKey:r}},generateX25519SharedKey(r,e){return qn.getSharedSecret(r.subarray(),e.subarray())},chaCha20Poly1305Encrypt(r,e,t,n){return Zc(n,e,t).encrypt(r.subarray())},chaCha20Poly1305Decrypt(r,e,t,n,o){return Zc(n,e,t).decrypt(r.subarray(),o)}};var Zl=Qc;function Jl(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 dn=r=>{let e=Oe(2);return e[0]=r>>8,e[1]=r,e};dn.bytes=2;var pn=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)};pn.bytes=2;function Ql(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 of={};re(of,{base10:()=>ny});var jv=new Uint8Array(0);function ed(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 Bt(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 td(r){return new TextEncoder().encode(r)}function rd(r){return new TextDecoder().decode(r)}function Zg(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(y){if(y instanceof Uint8Array||(ArrayBuffer.isView(y)?y=new Uint8Array(y.buffer,y.byteOffset,y.byteLength):Array.isArray(y)&&(y=Uint8Array.from(y))),!(y instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(y.length===0)return"";for(var x=0,l=0,m=0,v=y.length;m!==v&&y[m]===0;)m++,x++;for(var L=(v-m)*u+1>>>0,R=new Uint8Array(L);m!==v;){for(var D=y[m],O=0,B=L-1;(D!==0||O<l)&&B!==-1;B--,O++)D+=256*R[B]>>>0,R[B]=D%a>>>0,D=D/a>>>0;if(D!==0)throw new Error("Non-zero carry");l=O,m++}for(var I=L-l;I!==L&&R[I]===0;)I++;for(var U=c.repeat(x);I<L;++I)U+=r.charAt(R[I]);return U}function p(y){if(typeof y!="string")throw new TypeError("Expected String");if(y.length===0)return new Uint8Array;var x=0;if(y[x]!==" "){for(var l=0,m=0;y[x]===c;)l++,x++;for(var v=(y.length-x)*f+1>>>0,L=new Uint8Array(v);y[x];){var R=t[y.charCodeAt(x)];if(R===255)return;for(var D=0,O=v-1;(R!==0||D<m)&&O!==-1;O--,D++)R+=a*L[O]>>>0,L[O]=R%256>>>0,R=R/256>>>0;if(R!==0)throw new Error("Non-zero carry");m=D,x++}if(y[x]!==" "){for(var B=v-m;B!==v&&L[B]===0;)B++;for(var I=new Uint8Array(l+(v-B)),U=l;B!==v;)I[U++]=L[B++];return I}}}function d(y){var x=p(y);if(x)return x;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:p,decode:d}}var Jg=Zg,Qg=Jg,od=Qg;var ef=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")}},tf=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 sd(this,e)}},rf=class{decoders;constructor(e){this.decoders=e}or(e){return sd(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 sd(r,e){return new rf({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var nf=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 ef(e,t,n),this.decoder=new tf(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function mn({name:r,prefix:e,encode:t,decode:n}){return new nf(r,e,t,n)}function Qt({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=od(t,r);return mn({prefix:e,name:r,encode:n,decode:s=>Bt(o(s))})}function ey(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 ty(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 ry(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function de({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=ry(n);return mn({prefix:e,name:r,encode(s){return ty(s,n,t)},decode(s){return ey(s,o,t,r)}})}var ny=Qt({prefix:"9",name:"base10",alphabet:"0123456789"});var sf={};re(sf,{base16:()=>oy,base16upper:()=>sy});var oy=de({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),sy=de({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var af={};re(af,{base2:()=>iy});var iy=de({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var cf={};re(cf,{base256emoji:()=>hy});var id=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}"),ay=id.reduce((r,e,t)=>(r[t]=e,r),[]),cy=id.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function fy(r){return r.reduce((e,t)=>(e+=ay[t],e),"")}function uy(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=cy[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var hy=mn({prefix:"\u{1F680}",name:"base256emoji",encode:fy,decode:uy});var ff={};re(ff,{base32:()=>gn,base32hex:()=>my,base32hexpad:()=>yy,base32hexpadupper:()=>by,base32hexupper:()=>gy,base32pad:()=>dy,base32padupper:()=>py,base32upper:()=>ly,base32z:()=>wy});var gn=de({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),ly=de({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),dy=de({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),py=de({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),my=de({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),gy=de({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),yy=de({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),by=de({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),wy=de({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var uf={};re(uf,{base36:()=>bo,base36upper:()=>xy});var bo=Qt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),xy=Qt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var hf={};re(hf,{base58btc:()=>lt,base58flickr:()=>Ey});var lt=Qt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Ey=Qt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var lf={};re(lf,{base64:()=>Sy,base64pad:()=>Ay,base64url:()=>vy,base64urlpad:()=>Cy});var Sy=de({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Ay=de({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),vy=de({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Cy=de({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var df={};re(df,{base8:()=>Ly});var Ly=de({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var pf={};re(pf,{identity:()=>_y});var _y=mn({prefix:"\0",name:"identity",encode:r=>rd(r),decode:r=>td(r)});var c4=new TextEncoder,f4=new TextDecoder;var gf={};re(gf,{identity:()=>Yy});var Ty=fd,ad=128,Dy=127,Ry=~Dy,Oy=Math.pow(2,31);function fd(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Oy;)e[t++]=r&255|ad,r/=128;for(;r&Ry;)e[t++]=r&255|ad,r>>>=7;return e[t]=r|0,fd.bytes=t-n+1,e}var Py=mf,Uy=128,cd=127;function mf(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw mf.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&cd)<<o:(i&cd)*Math.pow(2,o),o+=7}while(i>=Uy);return mf.bytes=s-n,t}var Ny=Math.pow(2,7),Fy=Math.pow(2,14),ky=Math.pow(2,21),My=Math.pow(2,28),Ky=Math.pow(2,35),Hy=Math.pow(2,42),Vy=Math.pow(2,49),zy=Math.pow(2,56),$y=Math.pow(2,63),qy=function(r){return r<Ny?1:r<Fy?2:r<ky?3:r<My?4:r<Ky?5:r<Hy?6:r<Vy?7:r<zy?8:r<$y?9:10},jy={encode:Ty,decode:Py,encodingLength:qy},Gy=jy,wo=Gy;function xo(r,e=0){return[wo.decode(r,e),wo.decode.bytes]}function yn(r,e,t=0){return wo.encode(r,e,t),e}function bn(r){return wo.encodingLength(r)}function xn(r,e){let t=e.byteLength,n=bn(r),o=n+bn(t),s=new Uint8Array(o+t);return yn(r,s,0),yn(t,s,n),s.set(e,o),new wn(r,t,e,s)}function ud(r){let e=Bt(r),[t,n]=xo(e),[o,s]=xo(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new wn(t,o,i,e)}function hd(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&ed(r.bytes,t.bytes)}}var wn=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var ld=0,Wy="identity",dd=Bt;function Xy(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 xn(ld,dd(r))}var Yy={code:ld,name:Wy,encode:dd,digest:Xy};var wf={};re(wf,{sha256:()=>Jy,sha512:()=>Qy});var Zy=20;function bf({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new yf(r,e,t,n,o)}var yf=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??Zy,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?pd(n,this.code,t?.truncate):n.then(o=>pd(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function pd(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 xn(e,r)}function gd(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Jy=bf({name:"sha2-256",code:18,encode:gd("SHA-256")}),Qy=bf({name:"sha2-512",code:19,encode:gd("SHA-512")});function yd(r,e){let{bytes:t,version:n}=r;return n===0?tb(t,xf(r),e??lt.encoder):rb(t,xf(r),e??gn.encoder)}var bd=new WeakMap;function xf(r){let e=bd.get(r);if(e==null){let t=new Map;return bd.set(r,t),t}return e}var ai=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!==So)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==nb)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=xn(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&&hd(e.multihash,n.multihash)}toString(e){return yd(this,e)}toJSON(){return{"/":yd(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??wd(n,o,s.bytes))}else if(t[ob]===!0){let{version:n,multihash:o,code:s}=t,i=ud(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!==So)throw new Error(`Version 0 CID must use dag-pb (code: ${So}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=wd(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,So,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=Bt(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 wn(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,p]=xo(e.subarray(t));return t+=p,h},o=n(),s=So;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]=eb(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 xf(s).set(n,e),s}};function eb(r,e){switch(r[0]){case"Q":{let t=e??lt;return[lt.prefix,t.decode(`${lt.prefix}${r}`)]}case lt.prefix:{let t=e??lt;return[lt.prefix,t.decode(r)]}case gn.prefix:{let t=e??gn;return[gn.prefix,t.decode(r)]}case bo.prefix:{let t=e??bo;return[bo.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 tb(r,e,t){let{prefix:n}=t;if(n!==lt.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 rb(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 So=112,nb=18;function wd(r,e,t){let n=bn(r),o=n+bn(e),s=new Uint8Array(o+t.byteLength);return yn(r,s,0),yn(e,s,n),s.set(t,o),s}var ob=Symbol.for("@ipld/js-cid/CID");var Ef={...pf,...af,...df,...of,...sf,...ff,...uf,...hf,...lf,...cf},D4={...wf,...gf};function Ed(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var xd=Ed("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Sf=Ed("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=Oe(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),sb={utf8:xd,"utf-8":xd,hex:Ef.base16,latin1:Sf,ascii:Sf,binary:Sf,...Ef},ci=sb;function dt(r,e="utf8"){let t=ci[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}function Af(r,e){!e.enabled||!fn||(r?(e(`LOCAL_STATIC_PUBLIC_KEY ${dt(r.publicKey,"hex")}`),e(`LOCAL_STATIC_PRIVATE_KEY ${dt(r.privateKey,"hex")}`)):e("Missing local static keys."))}function vf(r,e){!e.enabled||!fn||(r?(e(`LOCAL_PUBLIC_EPHEMERAL_KEY ${dt(r.publicKey,"hex")}`),e(`LOCAL_PRIVATE_EPHEMERAL_KEY ${dt(r.privateKey,"hex")}`)):e("Missing local ephemeral keys."))}function Sd(r,e){!e.enabled||!fn||e(r?`REMOTE_STATIC_PUBLIC_KEY ${dt(r.subarray(),"hex")}`:"Missing remote static public key.")}function Cf(r,e){!e.enabled||!fn||e(r?`REMOTE_EPHEMERAL_PUBLIC_KEY ${dt(r.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function Lf(r,e,t){!t.enabled||!fn||(t(`CIPHER_STATE_1 ${r.n.getUint64()} ${r.k&&dt(r.k,"hex")}`),t(`CIPHER_STATE_2 ${e.n.getUint64()} ${e.k&&dt(e.k,"hex")}`))}function En(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=Oe(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}function _f(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 vd=Symbol.for("@achingbrain/uint8arraylist");function Ad(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 fi(r){return!!r?.[vd]}var pt=class r{bufs;length;[vd]=!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(fi(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(fi(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=Ad(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Ad(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(fi(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 En(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:En(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(!fi(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 p=f;p>=0;p--){let d=this.get(h+p);if(n[p]!==d){u=Math.max(1,p-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=Oe(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=ge(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=ge(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=ge(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=Oe(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=ge(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=ge(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=ge(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=ge(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=ge(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(!_f(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 Cr(r,e="utf8"){let t=ci[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}var Sn=class r extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=r.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};var ab=0,cb=4294967295,fb="Cipherstate has reached maximum n, a new handshake must be performed",ui=class{n;bytes;view;constructor(e=ab){this.n=e,this.bytes=ge(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>cb)throw new Error(fb)}};var Lr=ge(0),An=class{k;n;crypto;constructor(e,t=void 0,n=0){this.crypto=e,this.k=t,this.n=new ui(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}},If=class{cs;ck;h;crypto;constructor(e,t){this.crypto=e;let n=Cr(t,"utf-8");this.h=ub(e,n),this.ck=this.h,this.cs=new An(e)}mixKey(e){let[t,n]=this.crypto.hkdf(this.ck,e);this.ck=t,this.cs=new An(this.crypto,n)}mixHash(e){this.h=this.crypto.hash(new pt(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,Lr);return[new An(this.crypto,e),new An(this.crypto,t)]}},Bf=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 If(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()}},Ao=class extends Bf{writeMessageA(e){return new pt(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){let t=this.writeE();this.writeEE();let n=this.writeS();return this.writeES(),new pt(t,n,this.ss.encryptAndHash(e))}writeMessageC(e){let t=this.writeS();return this.writeSE(),new pt(t,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(t){throw new Sn(`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 Sn(`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 Sn(`handshake stage 2 validation fail: ${t.message}`)}}};function ub(r,e){if(e.length<=32){let t=ge(32);return t.set(e),t}else return r.hash(e)}var hb=Math.pow(2,7),lb=Math.pow(2,14),db=Math.pow(2,21),Cd=Math.pow(2,28),Ld=Math.pow(2,35),_d=Math.pow(2,42),Id=Math.pow(2,49),Ne=128,er=127;function vo(r){if(r<hb)return 1;if(r<lb)return 2;if(r<db)return 3;if(r<Cd)return 4;if(r<Ld)return 5;if(r<_d)return 6;if(r<Id)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Bd(r,e,t=0){switch(vo(r)){case 8:e[t++]=r&255|Ne,r/=128;case 7:e[t++]=r&255|Ne,r/=128;case 6:e[t++]=r&255|Ne,r/=128;case 5:e[t++]=r&255|Ne,r/=128;case 4:e[t++]=r&255|Ne,r>>>=7;case 3:e[t++]=r&255|Ne,r>>>=7;case 2:e[t++]=r&255|Ne,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function Td(r,e){let t=r[e],n=0;if(n+=t&er,t<Ne||(t=r[e+1],n+=(t&er)<<7,t<Ne)||(t=r[e+2],n+=(t&er)<<14,t<Ne)||(t=r[e+3],n+=(t&er)<<21,t<Ne)||(t=r[e+4],n+=(t&er)*Cd,t<Ne)||(t=r[e+5],n+=(t&er)*Ld,t<Ne)||(t=r[e+6],n+=(t&er)*_d,t<Ne)||(t=r[e+7],n+=(t&er)*Id,t<Ne))return n;throw new RangeError("Could not decode varint")}var Tf=new Float32Array([-0]),tr=new Uint8Array(Tf.buffer);function Dd(r,e,t){Tf[0]=r,e[t]=tr[0],e[t+1]=tr[1],e[t+2]=tr[2],e[t+3]=tr[3]}function Rd(r,e){return tr[0]=r[e],tr[1]=r[e+1],tr[2]=r[e+2],tr[3]=r[e+3],Tf[0]}var Df=new Float64Array([-0]),Pe=new Uint8Array(Df.buffer);function Od(r,e,t){Df[0]=r,e[t]=Pe[0],e[t+1]=Pe[1],e[t+2]=Pe[2],e[t+3]=Pe[3],e[t+4]=Pe[4],e[t+5]=Pe[5],e[t+6]=Pe[6],e[t+7]=Pe[7]}function Pd(r,e){return Pe[0]=r[e],Pe[1]=r[e+1],Pe[2]=r[e+2],Pe[3]=r[e+3],Pe[4]=r[e+4],Pe[5]=r[e+5],Pe[6]=r[e+6],Pe[7]=r[e+7],Df[0]}var pb=BigInt(Number.MAX_SAFE_INTEGER),mb=BigInt(Number.MIN_SAFE_INTEGER),$e=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 _r;if(e<pb&&e>mb)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>Ud&&(o=0n,++n>Ud&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return _r;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):_r}},_r=new $e(0,0);_r.toBigInt=function(){return 0n};_r.zzEncode=_r.zzDecode=function(){return this};_r.length=function(){return 1};var Ud=4294967296n;function Nd(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 Fd(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 Rf(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 nt(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function hi(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var Of=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,nt(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 nt(this,4);return hi(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw nt(this,4);return hi(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw nt(this,4);let e=Rd(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw nt(this,4);let e=Pd(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 nt(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Fd(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw nt(this,e);this.pos+=e}else do if(this.pos>=this.len)throw nt(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),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 nt(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 nt(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 nt(this,8);let e=hi(this.buf,this.pos+=4),t=hi(this.buf,this.pos+=4);return new $e(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=Td(this.buf,this.pos);return this.pos+=vo(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 Pf(r){return new Of(r instanceof Uint8Array?r:r.subarray())}function li(r,e,t){let n=Pf(r);return e.decode(n,void 0,t)}function Uf(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return Oe(i);o+i>e&&(n=Oe(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var Ir=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function Nf(){}var kf=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},gb=Uf();function yb(r){return globalThis.Buffer!=null?Oe(r):gb(r)}var Lo=class{len;head;tail;states;constructor(){this.len=0,this.head=new Ir(Nf,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new Ir(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Mf((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(di,10,$e.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=$e.fromBigInt(e);return this._push(di,t.length(),t)}uint64Number(e){return this._push(Bd,vo(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=$e.fromBigInt(e).zzEncode();return this._push(di,t.length(),t)}sint64Number(e){let t=$e.fromNumber(e).zzEncode();return this._push(di,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Ff,1,e?1:0)}fixed32(e){return this._push(Co,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=$e.fromBigInt(e);return this._push(Co,4,t.lo)._push(Co,4,t.hi)}fixed64Number(e){let t=$e.fromNumber(e);return this._push(Co,4,t.lo)._push(Co,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(Dd,4,e)}double(e){return this._push(Od,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(Ff,1,0):this.uint32(t)._push(wb,t,e)}string(e){let t=Nd(e);return t!==0?this.uint32(t)._push(Rf,t,e):this._push(Ff,1,0)}fork(){return this.states=new kf(this),this.head=this.tail=new Ir(Nf,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 Ir(Nf,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=yb(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function Ff(r,e,t){e[t]=r&255}function bb(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var Mf=class extends Ir{next;constructor(e,t){super(bb,e,t),this.next=void 0}};function di(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 Co(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 wb(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(Lo.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(xb,e,r),this},Lo.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(Eb,e,r),this});function xb(r,e,t){e.set(r,t)}function Eb(r,e,t){r.length<40?Rf(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(Cr(r),t)}function Kf(){return new Lo}function pi(r,e){let t=Kf();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var _o;(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"})(_o||(_o={}));function Hf(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function mi(r,e){return Hf("message",_o.LENGTH_DELIMITED,r,e)}var Io=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var gi;(function(r){let e;r.codec=()=>(e==null&&(e=mi((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 Io('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 Io('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=>pi(t,r.codec()),r.decode=(t,n)=>li(t,r.codec(),n)})(gi||(gi={}));var Bo;(function(r){let e;r.codec=()=>(e==null&&(e=mi((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),gi.codec().encode(t.extensions,n)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={identityKey:ge(0),identitySig:ge(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=gi.codec().decode(t,t.uint32(),{limits:o.limits?.extensions});break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>pi(t,r.codec()),r.decode=(t,n)=>li(t,r.codec(),n)})(Bo||(Bo={}));async function zf(r,e,t){let n=await r.sign(Kd(e));return Bo.encode({identityKey:Pt(r.publicKey),identitySig:n,extensions:t})}async function $f(r,e,t){try{let n=Bo.decode(r),o=eo(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=Kd(e);if(!await o.verify(s,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new Do(n.message)}}function Kd(r){let e=Cr("noise-libp2p-static-key:");return r instanceof Uint8Array?En([e,r],e.length+r.length):(r.prepend(e),r)}var Vf=class extends Yt{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 $s({lengthDecoder:pn,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 pt;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(dn(s.byteLength)),t.append(s)}return t}decrypt(e){let t=new pt;for(let n=0;n<e.byteLength;n+=65535){let o=n+65535;if(o>e.byteLength&&(o=e.byteLength),o-Gc<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-Gc);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 qf(r,e,t){return new Vf(r,e,t)}async function Hd(r,e){let{log:t,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:f}=r,u=await zf(s,a.publicKey,f),h=new Ao({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});Af(h.s,t),t.trace("Stage 0 - Initiator starting to send first message."),await n.write(h.writeMessageA(Lr),e),t.trace("Stage 0 - Initiator finished sending first message."),vf(h.e,t),t.trace("Stage 1 - Initiator waiting to receive first message from responder...");let p=h.readMessageB(await n.read(e));t.trace("Stage 1 - Initiator received the message."),Cf(h.re,t),Sd(h.rs,t),t.trace("Initiator going to check remote's signature...");let d=await $f(p,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[y,x]=h.ss.split();return Lf(y,x,t),{payload:d,encrypt:l=>y.encryptWithAd(Lr,l),decrypt:(l,m)=>x.decryptWithAd(Lr,l,m)}}async function Vd(r,e){let{log:t,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:f}=r,u=await zf(s,a.publicKey,f),h=new Ao({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});Af(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."),Cf(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."),vf(h.e,t),t.trace("Stage 2 - Responder waiting for third handshake message...");let p=h.readMessageC(await n.read(e));t.trace("Stage 2 - Responder received the message, finished handshake.");let d=await $f(p,h.rs,c),[y,x]=h.ss.split();return Lf(y,x,t),{payload:d,encrypt:l=>x.encryptWithAd(Lr,l),decrypt:(l,m)=>y.decryptWithAd(Lr,l,m)}}var yi=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??Zl;this.crypto=Jl(c),this.extensions={webtransportCerthashes:[],...o},this.metrics=a?Ql(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??ge(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[Or]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(e,t){let n=e.log?.newScope("noise")??this.log,o=Vs(e,{lengthEncoder:dn,lengthDecoder:pn,maxDataLength:65535}),s=await this.performHandshakeInitiator(o,this.components.privateKey,n,t?.remotePeer?.publicKey,t),i=eo(s.payload.identityKey);return{connection:qf(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:oc(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 Ro("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=Vs(e,{lengthEncoder:dn,lengthDecoder:pn,maxDataLength:65535}),s=await this.performHandshakeResponder(o,this.components.privateKey,n,t?.remotePeer?.publicKey,t),i=eo(s.payload.identityKey);return{connection:qf(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:oc(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 Hd({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 Vd({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 zd(r={}){return e=>new yi(e,r)}var jf=Object.values(ir).map(r=>r.decoder).reduce((r,e)=>r.or(e)),Sb=/^a=fingerprint:(?:\w+-[0-9]+)\s(?<fingerprint>(:?[0-9a-fA-F]{2})+)$/m;function $d(r){return r?.match(Sb)?.groups?.fingerprint}function Gf(r){let t=r.getComponents().find(n=>n.code===466)?.value;if(t===void 0||t==="")throw new $(`Couldn't find a certhash component of multiaddr: ${r.toString()}`);return t}function Ab(r){return We.decode(jf.decode(r))}function vb(r){let e=Ab(Gf(r)),t=Cb(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 Js(n,r.toString());return`${t} ${o.join(":").toUpperCase()}`}function qd(r){let e=r.split(":").map(o=>parseInt(o,16)),t=Uint8Array.from(e),n=Ue(gt.code,t);return rn(`/certhash/${Dn.encode(n.bytes)}`)}function Cb(r){switch(r){case 17:return"sha-1";case 18:return"sha-256";case 19:return"sha-512";default:throw new ei(r)}}function jd(r,e){let{host:t,port:n,type:o}=Uc(r);if(o!=="ip4"&&o!=="ip6")throw new $(`Multiaddr ${r} was not an IPv4 or IPv6 address`);let s=vb(r);return{type:"answer",sdp:`v=0
2
+ "use strict";var Libp2PWebrtc=(()=>{var wi=Object.defineProperty;var np=Object.getOwnPropertyDescriptor;var op=Object.getOwnPropertyNames;var sp=Object.prototype.hasOwnProperty;var re=(r,e)=>{for(var t in e)wi(r,t,{get:e[t],enumerable:!0})},ip=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of op(e))!sp.call(r,o)&&o!==t&&wi(r,o,{get:()=>e[o],enumerable:!(n=np(e,o))||n.enumerable});return r};var ap=r=>ip(wi({},"__esModule",{value:!0}),r);var Pb={};re(Pb,{webRTC:()=>Ob,webRTCDirect:()=>Rb});var Do=class extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}},Ro=class extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}},$=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Dr=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var Oo=class extends Error{static name="ConnectionFailedError";constructor(e="Connection failed"){super(e),this.name="ConnectionFailedError"}},Po=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 ot=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},Ln=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}};var No=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},Uo=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Fo=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var ko=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var nr=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var Mo=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}},Ko=class extends Or{constructor(e,t){super(!0,e,t)}},Ho=class extends Or{constructor(e,t){super(!1,e,t)}};var xi=Symbol.for("@libp2p/peer-id");var Vo=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 cp(r){return typeof r?.handleEvent=="function"}function fp(r){return(r!==!0&&r!==!1&&r?.once)??!1}var Bt=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=fp(n);super.addEventListener(e,i=>{if(o){let a=this.#e.get(i.type);a!=null&&(a=a.filter(({callback:c})=>c!==t),this.#e.set(i.type,a))}cp(t)?t.handleEvent(i):t(i)},n);let s=this.#e.get(e);s==null&&(s=[],this.#e.set(e,s)),s.push({callback:t,once:o})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==t),this.#e.set(e,o))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var Pr=Symbol.for("@libp2p/service-capabilities"),tu=Symbol.for("@libp2p/service-dependencies");var Ci={};re(Ci,{base58btc:()=>he,base58flickr:()=>yp});var lw=new Uint8Array(0);function nu(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 qe(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return or(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return or(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function ou(r){let e=new Uint8Array(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}var ru=4096;function su(r){let e=r.length;if(e<=ru)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.subarray(n,n+=ru));return t}function up(r){return r?.buffer instanceof ArrayBuffer}function or(r){return up(r)?r:r.slice()}function hp(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),m=Math.log(u)/Math.log(256),p=Math.log(256)/Math.log(u);function y(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var v=0,L=0,R=0,B=d.length;R!==B&&d[R]===0;)R++,v++;for(var U=(B-R)*p+1>>>0,I=new Uint8Array(U);R!==B;){for(var T=d[R],O=0,F=U-1;(T!==0||O<L)&&F!==-1;F--,O++)T+=256*I[F]>>>0,I[F]=T%u>>>0,T=T/u>>>0;if(T!==0)throw new Error("Non-zero carry");L=O,R++}for(var N=U-L;N!==U&&I[N]===0;)N++;for(var g=h.repeat(v);N<U;++N)g+=r.charAt(I[N]);return g}function x(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var v=0;if(d[v]!==" "){for(var L=0,R=0;d[v]===h;)L++,v++;for(var B=(d.length-v)*m+1>>>0,U=new Uint8Array(B);d[v];){var I=n[d.charCodeAt(v)];if(I===255)return;for(var T=0,O=B-1;(I!==0||T<R)&&O!==-1;O--,T++)I+=u*U[O]>>>0,U[O]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");R=T,v++}if(d[v]!==" "){for(var F=B-R;F!==B&&U[F]===0;)F++;for(var N=new Uint8Array(L+(B-F)),g=L;F!==B;)N[g++]=U[F++];return N}}}function l(d){var v=x(d);if(v)return v;throw new Error(`Non-${e} character`)}return{encode:y,decodeUnsafe:x,decode:l}}var lp=hp,dp=lp,au=dp;var Ei=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")}},Si=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 cu(this,e)}},Ai=class{decoders;constructor(e){this.decoders=e}or(e){return cu(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 cu(r,e){return new Ai({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var vi=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 Ei(e,t,n),this.decoder=new Si(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 vi(r,e,t,n)}function Dt({name:r,prefix:e,alphabet:t,caseInsensitive:n=!1}){let{encode:o,decode:s}=au(t,r,n);return Nr({prefix:e,name:r,encode:o,decode:i=>qe(s(i))})}function pp(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 mp(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 gp(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 ue({name:r,prefix:e,bitsPerChar:t,alphabet:n,caseInsensitive:o=!1}){let s=gp(n,o);return Nr({prefix:e,name:r,encode(i){return mp(i,n,t)},decode(i){return pp(i,s,t,r)}})}var he=Dt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),yp=Dt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Li={};re(Li,{base32:()=>Rt,base32hex:()=>Ep,base32hexpad:()=>Ap,base32hexpadupper:()=>vp,base32hexupper:()=>Sp,base32pad:()=>wp,base32padupper:()=>xp,base32upper:()=>bp,base32z:()=>Cp});var Rt=ue({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5,caseInsensitive:!0}),bp=ue({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5,caseInsensitive:!0}),wp=ue({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5,caseInsensitive:!0}),xp=ue({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5,caseInsensitive:!0}),Ep=ue({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5,caseInsensitive:!0}),Sp=ue({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5,caseInsensitive:!0}),Ap=ue({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5,caseInsensitive:!0}),vp=ue({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5,caseInsensitive:!0}),Cp=ue({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var _i={};re(_i,{base36:()=>_n,base36upper:()=>Lp});var _n=Dt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz",caseInsensitive:!0}),Lp=Dt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",caseInsensitive:!0});var We={};re(We,{Digest:()=>sr,create:()=>Ne,decode:()=>kr,equals:()=>Ti,hasCode:()=>qp});var _p=hu,fu=128,Ip=127,Tp=~Ip,Bp=Math.pow(2,31);function hu(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Bp;)e[t++]=r&255|fu,r/=128;for(;r&Tp;)e[t++]=r&255|fu,r>>>=7;return e[t]=r|0,hu.bytes=t-n+1,e}var Dp=Ii,Rp=128,uu=127;function Ii(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw Ii.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&uu)<<o:(i&uu)*Math.pow(2,o),o+=7}while(i>=Rp);return Ii.bytes=s-n,t}var Op=Math.pow(2,7),Pp=Math.pow(2,14),Np=Math.pow(2,21),Up=Math.pow(2,28),Fp=Math.pow(2,35),kp=Math.pow(2,42),Mp=Math.pow(2,49),Kp=Math.pow(2,56),Hp=Math.pow(2,63),Vp=function(r){return r<Op?1:r<Pp?2:r<Np?3:r<Up?4:r<Fp?5:r<kp?6:r<Mp?7:r<Kp?8:r<Hp?9:10},zp={encode:_p,decode:Dp,encodingLength:Vp},$p=zp,In=$p;function Tn(r,e=0){let t=In.decode(r,e),n=In.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 In.encode(r,e,t),e}function Fr(r){return In.encodingLength(r)}function Ne(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 sr(r,t,e,s)}function kr(r){let e=qe(r),[t,n]=Tn(e),[o,s]=Tn(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new sr(t,o,i,e)}function Ti(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&nu(r.bytes,t.bytes)}}var sr=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=or(n),this.bytes=or(o)}};function qp(r,e){return r.code===e}function lu(r,e){let{bytes:t,version:n}=r;return n===0?Gp(t,Bi(r),e??he.encoder):Wp(t,Bi(r),e??Rt.encoder)}var du=new WeakMap;function Bi(r){let e=du.get(r);if(e==null){let t=new Map;return du.set(r,t),t}return e}var pe=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=or(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!==Bn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Xp)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=Ne(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&&Ti(e.multihash,n.multihash)}toString(e){return lu(this,e)}toJSON(){return{"/":lu(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??pu(n,o,s.bytes))}else if(t[Yp]===!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!==Bn)throw new Error(`Version 0 CID must use dag-pb (code: ${Bn}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=pu(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Bn,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=qe(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 sr(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,m]=Tn(e.subarray(t));return t+=m,h},o=n(),s=Bn;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]=jp(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 Bi(s).set(n,e),s}};function jp(r,e){switch(r[0]){case"Q":{let t=e??he;return[he.prefix,t.decode(`${he.prefix}${r}`)]}case he.prefix:{let t=e??he;return[he.prefix,t.decode(r)]}case Rt.prefix:{let t=e??Rt;return[Rt.prefix,t.decode(r)]}case _n.prefix:{let t=e??_n;return[_n.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 Gp(r,e,t){let{prefix:n}=t;if(n!==he.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 Wp(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 Bn=112,Xp=18;function pu(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 Yp=Symbol.for("@ipld/js-cid/CID");var Di={};re(Di,{identity:()=>Xe});var mu=0,Zp="identity",gu=qe;function Jp(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 Ne(mu,gu(r))}var Xe={code:mu,name:Zp,encode:gu,digest:Jp};function Ee(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 Qp(r){return r.buffer instanceof ArrayBuffer}function Se(r){return Qp(r)?r:r.slice()}async function yu(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,Se(e),Se(t.subarray()));return n?.signal?.throwIfAborted(),s}function st(r=0){return new Uint8Array(r)}function be(r=0){return new Uint8Array(r)}function em(r){return r?.buffer instanceof ArrayBuffer}function Ri(r){if(em(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function Me(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=be(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return Ri(t)}var wu=Symbol.for("@achingbrain/uint8arraylist");function bu(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 $o(r){return!!r?.[wu]}var X=class r{bufs;length;[wu]=!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($o(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($o(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=bu(this.bufs,e);return t.buf[t.index]}set(e,t){let n=bu(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($o(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 Me(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:Me(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(!$o(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 m=f;m>=0;m--){let p=this.get(h+m);if(n[m]!==p){u=Math.max(1,m-a[p]);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=be(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=st(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=st(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=st(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=be(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=st(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=st(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=st(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=st(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=st(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(!Ee(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 Oi={};re(Oi,{base10:()=>tm});var tm=Dt({prefix:"9",name:"base10",alphabet:"0123456789"});var Pi={};re(Pi,{base16:()=>rm,base16upper:()=>nm});var rm=ue({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4,caseInsensitive:!0}),nm=ue({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4,caseInsensitive:!0});var Ni={};re(Ni,{base2:()=>om});var om=ue({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Ui={};re(Ui,{base256emoji:()=>fm});var xu=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}"),sm=xu.reduce((r,e,t)=>(r[t]=e,r),[]),im=xu.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function am(r){return r.reduce((e,t)=>(e+=sm[t],e),"")}function cm(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=im[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var fm=Nr({prefix:"\u{1F680}",name:"base256emoji",encode:am,decode:cm});var Fi={};re(Fi,{base64:()=>um,base64pad:()=>hm,base64url:()=>Dn,base64urlpad:()=>lm});var um=ue({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),hm=ue({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Dn=ue({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),lm=ue({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ki={};re(ki,{base8:()=>dm});var dm=ue({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Mi={};re(Mi,{identity:()=>pm});var pm=Nr({prefix:"\0",name:"identity",encode:r=>su(qe(r)),decode:r=>qe(ou(r))});var Zw=new TextEncoder,Jw=new TextDecoder;var Vi={};re(Vi,{sha256:()=>gt,sha512:()=>bm});var ym=20;function Hi({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new Ki(r,e,t,n,o)}var Ki=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??ym,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?Eu(n,this.code,t?.truncate):n.then(o=>Eu(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Eu(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 Ne(e,r)}function Au(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var gt=Hi({name:"sha2-256",code:18,encode:Au("SHA-256")}),bm=Hi({name:"sha2-512",code:19,encode:Au("SHA-512")});var ir={...Mi,...Ni,...ki,...Oi,...Pi,...Li,..._i,...Ci,...Fi,...Ui},ux={...Vi,...Di};function Cu(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var vu=Cu("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),zi=Cu("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=be(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),wm={utf8:vu,"utf-8":vu,hex:ir.base16,latin1:zi,ascii:zi,binary:zi,...ir},qo=wm;function Y(r,e="utf8"){let t=qo[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function G(r,e="utf8"){let t=qo[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var xm=parseInt("11111",2),$i=parseInt("10000000",2),Em=parseInt("01111111",2),Lu={0:Rn,1:Rn,2:Sm,3:Cm,4:Lm,5:vm,6:Am,16:Rn,22:Rn,48:Rn};function yt(r,e={offset:0}){let t=r[e.offset]&xm;if(e.offset++,Lu[t]!=null)return Lu[t](r,e);throw new Error("No decoder for tag "+t)}function On(r,e){let t=0;if((r[e.offset]&$i)===$i){let n=r[e.offset]&Em,o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++)o+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(o,16)}else t=r[e.offset],e.offset++;return t}function Rn(r,e){On(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=yt(r,e);if(n===null)break;t.push(n)}return t}function Sm(r,e){let t=On(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 Am(r,e){let t=On(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 vm(r,e){return e.offset++,null}function Cm(r,e){let t=On(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 Lm(r,e){let t=On(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function _m(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new X;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function qi(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=_m(r.byteLength);return new X(Uint8Array.from([e.byteLength|$i]),e)}function Fe(r){let e=new X,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new X(Uint8Array.from([2]),qi(e),e)}function jo(r){let e=Uint8Array.from([0]),t=new X(e,r);return new X(Uint8Array.from([3]),qi(t),t)}function Ot(r,e=48){let t=new X;for(let n of r)t.append(n);return new X(Uint8Array.from([e]),qi(t),t)}var Im=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Tm=Uint8Array.from([6,5,43,129,4,0,34]),Bm=Uint8Array.from([6,5,43,129,4,0,35]),Dm={ext:!0,kty:"EC",crv:"P-256"},Rm={ext:!0,kty:"EC",crv:"P-384"},Om={ext:!0,kty:"EC",crv:"P-521"},ji=32,Gi=48,Wi=66;function Xi(r){let e=yt(r);return _u(e)}function _u(r){let e=r[1][1][0],t=1,n,o;if(e.byteLength===ji*2+1)return n=G(e.subarray(t,t+ji),"base64url"),o=G(e.subarray(t+ji),"base64url"),new Mr({...Dm,key_ops:["verify"],x:n,y:o});if(e.byteLength===Gi*2+1)return n=G(e.subarray(t,t+Gi),"base64url"),o=G(e.subarray(t+Gi),"base64url"),new Mr({...Rm,key_ops:["verify"],x:n,y:o});if(e.byteLength===Wi*2+1)return n=G(e.subarray(t,t+Wi),"base64url"),o=G(e.subarray(t+Wi),"base64url"),new Mr({...Om,key_ops:["verify"],x:n,y:o});throw new $(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function Iu(r){return Ot([Fe(Uint8Array.from([1])),Ot([Pm(r.crv)],160),Ot([jo(new X(Uint8Array.from([4]),Y(r.x??"","base64url"),Y(r.y??"","base64url")))],161)]).subarray()}function Pm(r){if(r==="P-256")return Im;if(r==="P-384")return Tm;if(r==="P-521")return Bm;throw new $(`Invalid curve ${r}`)}var Mr=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=Iu(this.jwk)),this._raw}toMultihash(){return Xe.digest(Pt(this))}toCID(){return pe.createV1(114,this.toMultihash())}toString(){return he.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ee(this.raw,e.raw)}async verify(e,t,n){return yu(this.jwk,t,e,n)}};function Yi(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}function it(r,e=""){if(typeof r!="number"){let t=e&&`"${e}" `;throw new TypeError(`${t}expected number, got ${typeof r}`)}if(!Number.isSafeInteger(r)||r<0){let t=e&&`"${e}" `;throw new RangeError(`${t}expected integer >= 0, got ${r}`)}}function Ie(r,e,t=""){let n=Yi(r),o=r?.length,s=e!==void 0;if(!n||s&&o!==e){let i=t&&`"${t}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof r}`,f=i+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(f):new TypeError(f)}return r}function ar(r){if(typeof r!="function"||typeof r.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(it(r.outputLen),it(r.blockLen),r.outputLen<1)throw new Error('"outputLen" must be >= 1');if(r.blockLen<1)throw new Error('"blockLen" must be >= 1')}function Kr(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function Go(r,e){Ie(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length<t)throw new RangeError('"digestInto() output" expected to be of length >='+t)}function Ye(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function Wo(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Ze(r,e){return r<<32-e|r>>>e}var Bu=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Nm=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Xo(r){if(Ie(r),Bu)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=Nm[r[t]];return e}var bt={_0:48,_9:57,A:65,F:70,a:97,f:102};function Tu(r){if(r>=bt._0&&r<=bt._9)return r-bt._0;if(r>=bt.A&&r<=bt.F)return r-(bt.A-10);if(r>=bt.a&&r<=bt.f)return r-(bt.a-10)}function Pn(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);if(Bu)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=Tu(r.charCodeAt(s)),a=Tu(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 Zi(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];Ie(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 Ji(r,e={}){let t=(o,s)=>r(s).update(o).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.canXOF=n.canXOF,t.create=o=>r(o),Object.assign(t,e),Object.freeze(t)}function Du(r=32){it(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 Qi=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function Ru(r,e,t){return r&e^~r&t}function Ou(r,e,t){return r&e^r&t^e&t}var Nn=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=Wo(this.buffer)}update(e){Kr(this),Ie(e);let{view:t,buffer:n,blockLen:o}=this,s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=Wo(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Kr(this),Go(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,Ye(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let h=i;h<o;h++)t[h]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=Wo(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let f=c/4,u=this.get();if(f>u.length)throw new Error("_sha2: outputLen bigger than state");for(let 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}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},wt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Ae=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Yo=BigInt(4294967295),Pu=BigInt(32);function Um(r,e=!1){return e?{h:Number(r&Yo),l:Number(r>>Pu&Yo)}:{h:Number(r>>Pu&Yo)|0,l:Number(r&Yo)|0}}function Nu(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}=Um(r[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var ea=(r,e,t)=>r>>>t,ta=(r,e,t)=>r<<32-t|e>>>t,cr=(r,e,t)=>r>>>t|e<<32-t,fr=(r,e,t)=>r<<32-t|e>>>t,Un=(r,e,t)=>r<<64-t|e>>>t-32,Fn=(r,e,t)=>r>>>t-32|e<<64-t;function at(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var Uu=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),Fu=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,ku=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),Mu=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,Ku=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),Hu=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var km=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]),Nt=new Uint32Array(64),ra=class extends Nn{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,t,n,o,s,i,a,c]}set(e,t,n,o,s,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let h=0;h<16;h++,t+=4)Nt[h]=e.getUint32(t,!1);for(let h=16;h<64;h++){let m=Nt[h-15],p=Nt[h-2],y=Ze(m,7)^Ze(m,18)^m>>>3,x=Ze(p,17)^Ze(p,19)^p>>>10;Nt[h]=x+Nt[h-7]+y+Nt[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 m=Ze(a,6)^Ze(a,11)^Ze(a,25),p=u+m+Ru(a,c,f)+km[h]+Nt[h]|0,x=(Ze(n,2)^Ze(n,13)^Ze(n,22))+Ou(n,o,s)|0;u=f,f=c,c=a,a=i+p|0,i=s,s=o,o=n,n=p+x|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,f=f+this.G|0,u=u+this.H|0,this.set(n,o,s,i,a,c,f,u)}roundClean(){Ye(Nt)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Ye(this.buffer)}},na=class extends ra{A=wt[0]|0;B=wt[1]|0;C=wt[2]|0;D=wt[3]|0;E=wt[4]|0;F=wt[5]|0;G=wt[6]|0;H=wt[7]|0;constructor(){super(32)}};var Vu=Nu(["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))),Mm=Vu[0],Km=Vu[1],Ut=new Uint32Array(80),Ft=new Uint32Array(80),oa=class extends Nn{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:f,El:u,Fh:h,Fl:m,Gh:p,Gl:y,Hh:x,Hl:l}=this;return[e,t,n,o,s,i,a,c,f,u,h,m,p,y,x,l]}set(e,t,n,o,s,i,a,c,f,u,h,m,p,y,x,l){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=m|0,this.Gh=p|0,this.Gl=y|0,this.Hh=x|0,this.Hl=l|0}process(e,t){for(let L=0;L<16;L++,t+=4)Ut[L]=e.getUint32(t),Ft[L]=e.getUint32(t+=4);for(let L=16;L<80;L++){let R=Ut[L-15]|0,B=Ft[L-15]|0,U=cr(R,B,1)^cr(R,B,8)^ea(R,B,7),I=fr(R,B,1)^fr(R,B,8)^ta(R,B,7),T=Ut[L-2]|0,O=Ft[L-2]|0,F=cr(T,O,19)^Un(T,O,61)^ea(T,O,6),N=fr(T,O,19)^Fn(T,O,61)^ta(T,O,6),g=ku(I,N,Ft[L-7],Ft[L-16]),A=Mu(g,U,F,Ut[L-7],Ut[L-16]);Ut[L]=A|0,Ft[L]=g|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:f,Dl:u,Eh:h,El:m,Fh:p,Fl:y,Gh:x,Gl:l,Hh:d,Hl:v}=this;for(let L=0;L<80;L++){let R=cr(h,m,14)^cr(h,m,18)^Un(h,m,41),B=fr(h,m,14)^fr(h,m,18)^Fn(h,m,41),U=h&p^~h&x,I=m&y^~m&l,T=Ku(v,B,I,Km[L],Ft[L]),O=Hu(T,d,R,U,Mm[L],Ut[L]),F=T|0,N=cr(n,o,28)^Un(n,o,34)^Un(n,o,39),g=fr(n,o,28)^Fn(n,o,34)^Fn(n,o,39),A=n&s^n&a^s&a,S=o&i^o&c^i&c;d=x|0,v=l|0,x=p|0,l=y|0,p=h|0,y=m|0,{h,l:m}=at(f|0,u|0,O|0,F|0),f=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let w=Uu(F,g,S);n=Fu(w,O,N,A),o=w|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:m}=at(this.Eh|0,this.El|0,h|0,m|0),{h:p,l:y}=at(this.Fh|0,this.Fl|0,p|0,y|0),{h:x,l}=at(this.Gh|0,this.Gl|0,x|0,l|0),{h:d,l:v}=at(this.Hh|0,this.Hl|0,d|0,v|0),this.set(n,o,s,i,a,c,f,u,h,m,p,y,x,l,d,v)}roundClean(){Ye(Ut,Ft)}destroy(){this.destroyed=!0,Ye(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},sa=class extends oa{Ah=Ae[0]|0;Al=Ae[1]|0;Bh=Ae[2]|0;Bl=Ae[3]|0;Ch=Ae[4]|0;Cl=Ae[5]|0;Dh=Ae[6]|0;Dl=Ae[7]|0;Eh=Ae[8]|0;El=Ae[9]|0;Fh=Ae[10]|0;Fl=Ae[11]|0;Gh=Ae[12]|0;Gl=Ae[13]|0;Hh=Ae[14]|0;Hl=Ae[15]|0;constructor(){super(64)}};var ct=Ji(()=>new na,Qi(1));var Zo=Ji(()=>new sa,Qi(3));var V=(r,e,t)=>Ie(r,e,t),aa=it,Hr=Xo,me=(...r)=>Zi(...r),Vr=r=>Pn(r),ur=Yi,hr=r=>Du(r),Qo=BigInt(0),ia=BigInt(1);function Je(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}" `;throw new TypeError(t+"expected boolean, got type="+typeof r)}return r}function es(r){if(typeof r=="bigint"){if(!Jo(r))throw new RangeError("positive bigint expected, got "+r)}else aa(r);return r}function Qe(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 kn(r){let e=es(r).toString(16);return e.length&1?"0"+e:e}function zu(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);return r===""?Qo:BigInt("0x"+r)}function lr(r){return zu(Xo(r))}function Ke(r){return zu(Xo(kt(Ie(r)).reverse()))}function ts(r,e){if(it(e),e===0)throw new RangeError("zero length");r=es(r);let t=r.toString(16);if(t.length>e*2)throw new RangeError("number too large");return Pn(t.padStart(e*2,"0"))}function Mn(r,e){return ts(r,e).reverse()}function $u(r,e){if(r=V(r),e=V(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 kt(r){return Uint8Array.from(V(r))}function rs(r){if(typeof r!="string")throw new TypeError("ascii string expected, got "+typeof r);return Uint8Array.from(r,(e,t)=>{let n=e.charCodeAt(0);if(e.length!==1||n>127)throw new RangeError(`string contains non-ASCII character "${r[t]}" with code ${n} at position ${t}`);return n})}var Jo=r=>typeof r=="bigint"&&Qo<=r;function Hm(r,e,t){return Jo(r)&&Jo(e)&&Jo(t)&&e<=r&&r<t}function xt(r,e,t,n){if(!Hm(e,t,n))throw new RangeError("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function zr(r){if(r<Qo)throw new Error("expected non-negative bigint, got "+r);let e;for(e=0;r>Qo;r>>=ia,e+=1);return e}var Kn=r=>(ia<<BigInt(r))-ia;function qu(r,e,t){if(it(r,"hashLen"),it(e,"qByteLen"),typeof t!="function")throw new TypeError("hmacFn must be a function");let n=l=>new Uint8Array(l),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},m=(...l)=>t(f,me(c,...l)),p=(l=o)=>{f=m(s,l),c=m(),l.length!==0&&(f=m(i,l),c=m())},y=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let l=0,d=[];for(;l<e;){c=m();let v=c.slice();d.push(v),l+=c.length}return me(...d)};return(l,d)=>{h(),p(l);let v;for(;(v=d(y()))===void 0;)p();return h(),v}}function He(r,e={},t={}){if(Object.prototype.toString.call(r)!=="[object Object]")throw new TypeError("expected valid options object");function n(s,i,a){if(!a&&i!=="function"&&!Object.hasOwn(r,s))throw new TypeError(`param "${s}" is invalid: expected own property`);let c=r[s];if(a&&c===void 0)return;let f=typeof c;if(f!==i||c===null)throw new TypeError(`param "${s}" is invalid: expected ${i}, got ${f}`)}let o=(s,i)=>Object.entries(s).forEach(([a,c])=>n(a,c,i));o(e,!1),o(t,!0)}var ca=()=>{throw new Error("not implemented")};var ve=BigInt(0),le=BigInt(1),dr=BigInt(2),Xu=BigInt(3),Yu=BigInt(4),Zu=BigInt(5),Vm=BigInt(7),Ju=BigInt(8),zm=BigInt(9),Qu=BigInt(16);function ce(r,e){if(e<=ve)throw new Error("mod: expected positive modulus, got "+e);let t=r%e;return t>=ve?t:e+t}function se(r,e,t){if(e<ve)throw new Error("pow2: expected non-negative exponent, got "+e);let n=r;for(;e-- >ve;)n*=n,n%=t;return n}function ju(r,e){if(r===ve)throw new Error("invert: expected non-zero number");if(e<=ve)throw new Error("invert: expected positive modulus, got "+e);let t=ce(r,e),n=e,o=ve,s=le,i=le,a=ve;for(;t!==ve;){let f=n/t,u=n-t*f,h=o-i*f,m=s-a*f;n=t,t=u,o=i,s=a,i=h,a=m}if(n!==le)throw new Error("invert: does not exist");return ce(o,e)}function fa(r,e,t){let n=r;if(!n.eql(n.sqr(e),t))throw new Error("Cannot find square root")}function eh(r,e){let t=r,n=(t.ORDER+le)/Yu,o=t.pow(e,n);return fa(t,o,e),o}function $m(r,e){let t=r,n=(t.ORDER-Zu)/Ju,o=t.mul(e,dr),s=t.pow(o,n),i=t.mul(e,s),a=t.mul(t.mul(i,dr),s),c=t.mul(i,t.sub(a,t.ONE));return fa(t,c,e),c}function qm(r){let e=$r(r),t=th(r),n=t(e,e.neg(e.ONE)),o=t(e,n),s=t(e,e.neg(n)),i=(r+Vm)/Qu;return((a,c)=>{let f=a,u=f.pow(c,i),h=f.mul(u,n),m=f.mul(u,o),p=f.mul(u,s),y=f.eql(f.sqr(h),c),x=f.eql(f.sqr(m),c);u=f.cmov(u,h,y),h=f.cmov(p,m,x);let l=f.eql(f.sqr(h),c),d=f.cmov(u,h,l);return fa(f,d,c),d})}function th(r){if(r<Xu)throw new Error("sqrt is not defined for small field");let e=r-le,t=0;for(;e%dr===ve;)e/=dr,t++;let n=dr,o=$r(r);for(;Gu(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return eh;let s=o.pow(n,e),i=(e+le)/dr;return function(c,f){let u=c;if(u.is0(f))return f;if(Gu(u,f)!==1)throw new Error("Cannot find square root");let h=t,m=u.mul(u.ONE,s),p=u.pow(f,e),y=u.pow(f,i);for(;!u.eql(p,u.ONE);){if(u.is0(p))return u.ZERO;let x=1,l=u.sqr(p);for(;!u.eql(l,u.ONE);)if(x++,l=u.sqr(l),x===h)throw new Error("Cannot find square root");let d=le<<BigInt(h-x-1),v=u.pow(m,d);h=x,m=u.sqr(v),p=u.mul(p,m),y=u.mul(y,v)}return y}}function jm(r){return r%Yu===Xu?eh:r%Ju===Zu?$m:r%Qu===zm?qm(r):th(r)}var Et=(r,e)=>(ce(r,e)&le)===le,Gm=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function ua(r){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=Gm.reduce((n,o)=>(n[o]="function",n),e);if(He(r,t),Qe(r.BYTES,"BYTES"),Qe(r.BITS,"BITS"),r.BYTES<1||r.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(r.ORDER<=le)throw new Error("invalid field: expected ORDER > 1, got "+r.ORDER);return r}function Wm(r,e,t){let n=r;if(t<ve)throw new Error("invalid exponent, negatives unsupported");if(t===ve)return n.ONE;if(t===le)return e;let o=n.ONE,s=e;for(;t>ve;)t&le&&(o=n.mul(o,s)),s=n.sqr(s),t>>=le;return o}function Hn(r,e,t=!1){let n=r,o=new Array(e.length).fill(t?n.ZERO:void 0),s=e.reduce((a,c,f)=>n.is0(c)?a:(o[f]=a,n.mul(a,c)),n.ONE),i=n.inv(s);return e.reduceRight((a,c,f)=>n.is0(c)?a:(o[f]=n.mul(a,o[f]),n.mul(a,c)),i),o}function Gu(r,e){let t=r,n=(t.ORDER-le)/dr,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 Xm(r,e){if(e!==void 0&&aa(e),r<=ve)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=zr(r);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected bit length (${t}) >= n.length (${e})`);let n=e!==void 0?e:t,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}var Wu=new WeakMap,ns=class{ORDER;BITS;BYTES;isLE;ZERO=ve;ONE=le;_lengths;_mod;constructor(e,t={}){if(e<=le)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}=Xm(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 ce(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return ve<=e&&e<this.ORDER}is0(e){return e===ve}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&le)===le}neg(e){return ce(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return ce(e*e,this.ORDER)}add(e,t){return ce(e+t,this.ORDER)}sub(e,t){return ce(e-t,this.ORDER)}mul(e,t){return ce(e*t,this.ORDER)}pow(e,t){return Wm(this,e,t)}div(e,t){return ce(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=Wu.get(this);return t||Wu.set(this,t=jm(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?Mn(e,this.BYTES):ts(e,this.BYTES)}fromBytes(e,t=!1){V(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?Ke(e):lr(e);if(a&&(c=ce(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Hn(this,e)}cmov(e,t,n){return Je(n,"condition"),n?t:e}};Object.freeze(ns.prototype);function $r(r,e={}){return new ns(r,e)}function rh(r){if(typeof r!="bigint")throw new Error("field order must be bigint");if(r<=le)throw new Error("field order must be greater than 1");let e=zr(r-le);return Math.ceil(e/8)}function ha(r){let e=rh(r);return e+Math.ceil(e/2)}function la(r,e,t=!1){V(r);let n=r.length,o=rh(e),s=Math.max(ha(e),16);if(n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=t?Ke(r):lr(r),a=ce(i,e-le)+le;return t?Mn(a,o):ts(a,o)}var qr=BigInt(0),pr=BigInt(1);function Vn(r,e){let t=e.negate();return r?t:e}function mr(r,e){let t=Hn(r.Fp,e.map(n=>n.Z));return e.map((n,o)=>r.fromAffine(n.toAffine(t[o])))}function ih(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function da(r,e){ih(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1),o=2**r,s=Kn(r),i=BigInt(r);return{windows:t,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function nh(r,e,t){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=t,a=Number(r&o),c=r>>i;a>n&&(a-=s,c+=pr);let f=e*n,u=f+Math.abs(a)-1,h=a===0,m=a<0,p=e%2!==0;return{nextN:c,offset:u,isZero:h,isNeg:m,isNegF:p,offsetF:f}}var pa=new WeakMap,ah=new WeakMap;function ma(r){return ah.get(r)||1}function oh(r){if(r!==qr)throw new Error("invalid wNAF")}var jr=class{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let o=e;for(;t>qr;)t&pr&&(n=n.add(o)),o=o.double(),t>>=pr;return n}precomputeWindow(e,t){let{windows:n,windowSize:o}=da(t,this.bits),s=[],i=e,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let f=1;f<o;f++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=da(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:f,isZero:u,isNeg:h,isNegF:m,offsetF:p}=nh(n,a,i);n=c,u?s=s.add(Vn(m,t[p])):o=o.add(Vn(h,t[f]))}return oh(n),{p:o,f:s}}wNAFUnsafe(e,t,n,o=this.ZERO){let s=da(e,this.bits);for(let i=0;i<s.windows&&n!==qr;i++){let{nextN:a,offset:c,isZero:f,isNeg:u}=nh(n,i,s);if(n=a,!f){let h=t[c];o=o.add(u?h.negate():h)}}return oh(n),o}getPrecomputes(e,t,n){let o=pa.get(t);return o||(o=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(o=n(o)),pa.set(t,o))),o}cached(e,t,n){let o=ma(e);return this.wNAF(o,this.getPrecomputes(o,e,n),t)}unsafe(e,t,n,o){let s=ma(e);return s===1?this._unsafeLadder(e,t,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),t,o)}createCache(e,t){ih(t,this.bits),ah.set(e,t),pa.delete(e)}hasCache(e){return ma(e)!==1}};function ch(r,e,t,n){let o=e,s=r.ZERO,i=r.ZERO;for(;t>qr||n>qr;)t&pr&&(s=s.add(o)),n&pr&&(i=i.add(o)),o=o.double(),t>>=pr,n>>=pr;return{p1:s,p2:i}}function sh(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return ua(e),e}else return $r(r,{isLE:t})}function os(r,e,t={},n){if(n===void 0&&(n=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let f=e[c];if(!(typeof f=="bigint"&&f>qr))throw new Error(`CURVE.${c} must be positive bigint`)}let o=sh(e.p,t.Fp,n),s=sh(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 Gr(r,e){return function(n){let o=r(n);return{secretKey:o,publicKey:e(o)}}}var Mt=BigInt(0),we=BigInt(1),ga=BigInt(2),Ym=BigInt(8);function Zm(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 fh(r,e={}){let t=e,n=os("edwards",r,t,t.FpFnLE),{Fp:o,Fn:s}=n,i=n.CURVE,{h:a}=i;He(t,{},{uvRatio:"function"});let c=ga<<BigInt(s.BYTES*8)-we,f=x=>o.create(x),u=t.uvRatio===void 0?(x,l)=>{try{return{isValid:!0,value:o.sqrt(o.div(x,l))}}catch{return{isValid:!1,value:Mt}}}:t.uvRatio;if(!Zm(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function h(x,l,d=!1){let v=d?we:Mt;return xt("coordinate "+x,l,v,c),l}function m(x){if(!(x instanceof p))throw new Error("EdwardsPoint expected")}class p{static BASE=new p(i.Gx,i.Gy,we,f(i.Gx*i.Gy));static ZERO=new p(Mt,we,we,Mt);static Fp=o;static Fn=s;X;Y;Z;T;constructor(l,d,v,L){this.X=h("x",l),this.Y=h("y",d),this.Z=h("z",v,!0),this.T=h("t",L),Object.freeze(this)}static CURVE(){return i}static fromAffine(l){if(l instanceof p)throw new Error("extended point not allowed");let{x:d,y:v}=l||{};return h("x",d),h("y",v),new p(d,v,we,f(d*v))}static fromBytes(l,d=!1){let v=o.BYTES,{a:L,d:R}=i;l=kt(V(l,v,"point")),Je(d,"zip215");let B=kt(l),U=l[v-1];B[v-1]=U&-129;let I=Ke(B),T=d?c:o.ORDER;xt("point.y",I,Mt,T);let O=f(I*I),F=f(O-we),N=f(R*O-L),{isValid:g,value:A}=u(F,N);if(!g)throw new Error("bad point: invalid y coordinate");let S=(A&we)===we,w=(U&128)!==0;if(!d&&A===Mt&&w)throw new Error("bad point: x=0 and x_0=1");return w!==S&&(A=f(-A)),p.fromAffine({x:A,y:I})}static fromHex(l,d=!1){return p.fromBytes(Vr(l),d)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(l=8,d=!0){return y.createCache(this,l),d||this.multiply(ga),this}assertValidity(){let l=this,{a:d,d:v}=i;if(l.is0())throw new Error("bad point: ZERO");let{X:L,Y:R,Z:B,T:U}=l,I=f(L*L),T=f(R*R),O=f(B*B),F=f(O*O),N=f(I*d),g=f(O*f(N+T)),A=f(F+f(v*f(I*T)));if(g!==A)throw new Error("bad point: equation left != right (1)");let S=f(L*R),w=f(B*U);if(S!==w)throw new Error("bad point: equation left != right (2)")}equals(l){m(l);let{X:d,Y:v,Z:L}=this,{X:R,Y:B,Z:U}=l,I=f(d*U),T=f(R*L),O=f(v*U),F=f(B*L);return I===T&&O===F}is0(){return this.equals(p.ZERO)}negate(){return new p(f(-this.X),this.Y,this.Z,f(-this.T))}double(){let{a:l}=i,{X:d,Y:v,Z:L}=this,R=f(d*d),B=f(v*v),U=f(ga*f(L*L)),I=f(l*R),T=d+v,O=f(f(T*T)-R-B),F=I+B,N=F-U,g=I-B,A=f(O*N),S=f(F*g),w=f(O*g),b=f(N*F);return new p(A,S,b,w)}add(l){m(l);let{a:d,d:v}=i,{X:L,Y:R,Z:B,T:U}=this,{X:I,Y:T,Z:O,T:F}=l,N=f(L*I),g=f(R*T),A=f(U*v*F),S=f(B*O),w=f((L+R)*(I+T)-N-g),b=S-A,C=S+A,_=f(g-d*N),E=f(w*b),D=f(C*_),P=f(w*_),k=f(b*C);return new p(E,D,k,P)}subtract(l){return m(l),this.add(l.negate())}multiply(l){if(!s.isValidNot0(l))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:d,f:v}=y.cached(this,l,L=>mr(p,L));return mr(p,[d,v])[0]}multiplyUnsafe(l){if(!s.isValid(l))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return l===Mt?p.ZERO:this.is0()||l===we?this:y.unsafe(this,l,d=>mr(p,d))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return y.unsafe(this,i.n).is0()}toAffine(l){let d=this,v=l,{X:L,Y:R,Z:B}=d,U=d.is0();v==null&&(v=U?Ym:o.inv(B));let I=f(L*v),T=f(R*v),O=o.mul(B,v);if(U)return{x:Mt,y:we};if(O!==we)throw new Error("invZ was invalid");return{x:I,y:T}}clearCofactor(){return a===we?this:this.multiplyUnsafe(a)}toBytes(){let{x:l,y:d}=this.toAffine(),v=o.toBytes(d);return v[v.length-1]|=l&we?128:0,v}toHex(){return Hr(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let y=new jr(p,s.BITS);return s.BITS>=8&&p.BASE.precompute(8),Object.freeze(p.prototype),Object.freeze(p),p}var ss=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e}static fromBytes(e){ca()}static fromHex(e){ca()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return Hr(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.ep.precompute(e,t),this}};function uh(r,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');let n=e,o=t;He(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:s}=o,{BASE:i,Fp:a,Fn:c}=r,f=n.outputLen,u=2*a.BYTES;if(f!==void 0&&(Qe(f,"hash.outputLen"),f!==u))throw new Error(`hash.outputLen must be ${u}, got ${f}`);let h=o.randomBytes===void 0?hr:o.randomBytes,m=o.adjustScalarBytes===void 0?g=>g:o.adjustScalarBytes,p=o.domain===void 0?(g,A,S)=>{if(Je(S,"phflag"),A.length||S)throw new Error("Contexts/pre-hash are not supported");return g}:o.domain;function y(g){return c.create(Ke(g))}function x(g){let A=I.secretKey;V(g,I.secretKey,"secretKey");let S=V(n(g),2*A,"hashedSecretKey"),w=m(S.slice(0,A)),b=S.slice(A,2*A),C=y(w);return{head:w,prefix:b,scalar:C}}function l(g){let{head:A,prefix:S,scalar:w}=x(g),b=i.multiply(w),C=b.toBytes();return{head:A,prefix:S,scalar:w,point:b,pointBytes:C}}function d(g){return l(g).pointBytes}function v(g=Uint8Array.of(),...A){let S=me(...A);return y(n(p(S,V(g,void 0,"context"),!!s)))}function L(g,A,S={}){g=V(g,void 0,"message"),s&&(g=s(g));let{prefix:w,scalar:b,pointBytes:C}=l(A),_=v(S.context,w,g),E=i.multiply(_).toBytes(),D=v(S.context,E,C,g),P=c.create(_+D*b);if(!c.isValid(P))throw new Error("sign failed: invalid s");let k=me(E,c.toBytes(P));return V(k,I.signature,"result")}let R={zip215:o.zip215};function B(g,A,S,w=R){let{context:b}=w,C=w.zip215===void 0?!!R.zip215:w.zip215,_=I.signature;g=V(g,_,"signature"),A=V(A,void 0,"message"),S=V(S,I.publicKey,"publicKey"),C!==void 0&&Je(C,"zip215"),s&&(A=s(A));let E=_/2,D=g.subarray(0,E),P=Ke(g.subarray(E,_)),k,H,K;try{k=r.fromBytes(S,C),H=r.fromBytes(D,C),K=i.multiplyUnsafe(P)}catch{return!1}if(!C&&k.isSmallOrder())return!1;let Q=v(b,D,S,A);return H.add(k.multiplyUnsafe(Q)).subtract(K).clearCofactor().is0()}let U=a.BYTES,I={secretKey:U,publicKey:U,signature:2*U,seed:U};function T(g){return g=g===void 0?h(I.seed):g,V(g,I.seed,"seed")}function O(g){return ur(g)&&g.length===I.secretKey}function F(g,A){try{return!!r.fromBytes(g,A===void 0?R.zip215:A)}catch{return!1}}let N={getExtendedPublicKey:l,randomSecretKey:T,isValidSecretKey:O,isValidPublicKey:F,toMontgomery(g){let{y:A}=r.fromBytes(g),S=I.publicKey,w=S===32;if(!w&&S!==57)throw new Error("only defined for 25519 and 448");let b=w?a.div(we+A,we-A):a.div(A-we,A+we);return a.toBytes(b)},toMontgomerySecret(g){let A=I.secretKey;V(g,A);let S=n(g.subarray(0,A));return m(S).subarray(0,A)}};return Object.freeze(I),Object.freeze(N),Object.freeze({keygen:Gr(T,d),getPublicKey:d,sign:L,verify:B,utils:N,Point:r,lengths:I})}function zn(r,e){if(Qe(r),Qe(e),e<0||e>4)throw new Error("invalid I2OSP length: "+e);if(r<0||r>2**(8*e)-1)throw new Error("invalid I2OSP input: "+r);let t=Array.from({length:e}).fill(0);for(let n=e-1;n>=0;n--)t[n]=r&255,r>>>=8;return new Uint8Array(t)}function Jm(r,e){let t=new Uint8Array(r.length);for(let n=0;n<r.length;n++)t[n]=r[n]^e[n];return t}function Qm(r){if(!ur(r)&&typeof r!="string")throw new Error("DST must be Uint8Array or ascii string");let e=typeof r=="string"?rs(r):r;if(e.length===0)throw new Error("DST must be non-empty");return e}function ya(r,e,t,n){V(r),Qe(t),e=Qm(e),e.length>255&&(e=n(me(rs("H2C-OVERSIZE-DST-"),e)));let{outputLen:o,blockLen:s}=n,i=Math.ceil(t/o);if(t>65535||i>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=me(e,zn(e.length,1)),c=new Uint8Array(s),f=zn(t,2),u=new Array(i),h=n(me(c,r,f,zn(0,1),a));u[0]=n(me(h,zn(1,1),a));for(let p=1;p<i;p++){let y=[Jm(h,u[p-1]),zn(p+1,1),a];u[p]=n(me(...y))}return me(...u).slice(0,t)}var hh="HashToScalar-";var $n=BigInt(0),Wr=BigInt(1),is=BigInt(2);function e0(r){return He(r,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function"}),Object.freeze({...r})}function lh(r){let e=e0(r),{P:t,type:n,adjustScalarBytes:o,powPminus2:s,randomBytes:i}=e,a=n==="x25519";if(!a&&n!=="x448")throw new Error("invalid type");let c=i===void 0?hr:i,f=a?255:448,u=a?32:56,h=BigInt(a?9:5),m=BigInt(a?121665:39081),p=a?is**BigInt(254):is**BigInt(447),y=a?BigInt(8)*is**BigInt(251)-Wr:BigInt(4)*is**BigInt(445)-Wr,x=p+y+Wr,l=S=>ce(S,t),d=v(h);function v(S){return Mn(l(S),u)}function L(S){let w=kt(V(S,u,"uCoordinate"));return a&&(w[31]&=127),l(Ke(w))}function R(S){return Ke(o(kt(V(S,u,"scalar"))))}function B(S,w){let b=F(L(w),R(S));if(b===$n)throw new Error("invalid private or public key received");return v(b)}function U(S){return B(S,d)}let I=U,T=B;function O(S,w,b){let C=l(S*(w-b));return w=l(w-C),b=l(b+C),{x_2:w,x_3:b}}function F(S,w){xt("u",S,$n,t),xt("scalar",w,p,x);let b=w,C=S,_=Wr,E=$n,D=S,P=Wr,k=$n;for(let K=BigInt(f-1);K>=$n;K--){let Q=b>>K&Wr;k^=Q,{x_2:_,x_3:D}=O(k,_,D),{x_2:E,x_3:P}=O(k,E,P),k=Q;let ee=_+E,te=l(ee*ee),j=_-E,ae=l(j*j),mt=te-ae,rr=D+P,Br=D-P,vn=l(Br*ee),Cn=l(rr*j),Jf=vn+Cn,Qf=vn-Cn;D=l(Jf*Jf),P=l(C*l(Qf*Qf)),_=l(te*ae),E=l(mt*(te+l(m*mt)))}({x_2:_,x_3:D}=O(k,_,D)),{x_2:E,x_3:P}=O(k,E,P);let H=s(E);return l(_*H)}let N={secretKey:u,publicKey:u,seed:u},g=S=>(S=S===void 0?c(u):S,V(S,N.seed,"seed"),S),A={randomSecretKey:g};return Object.freeze(N),Object.freeze(A),Object.freeze({keygen:Gr(g,I),getSharedSecret:T,getPublicKey:I,scalarMult:B,scalarMultBase:U,utils:A,GuBytes:d.slice(),lengths:N})}var t0=BigInt(0),St=BigInt(1),dh=BigInt(2),r0=BigInt(3),n0=BigInt(5),o0=BigInt(8),gr=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Ea={p:gr,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:o0,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function gh(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=gr,a=r*r%s*r%s,c=se(a,dh,s)*a%s,f=se(c,St,s)*r%s,u=se(f,n0,s)*f%s,h=se(u,e,s)*u%s,m=se(h,t,s)*h%s,p=se(m,n,s)*m%s,y=se(p,o,s)*p%s,x=se(y,o,s)*p%s,l=se(x,e,s)*u%s;return{pow_p_5_8:se(l,dh,s)*r%s,b2:a}}function yh(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var ba=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Sa(r,e){let t=gr,n=ce(e*e*e,t),o=ce(n*n*e,t),s=gh(r*o).pow_p_5_8,i=ce(r*n*s,t),a=ce(e*i*i,t),c=i,f=ce(i*ba,t),u=a===r,h=a===ce(-r,t),m=a===ce(-r*ba,t);return u&&(i=c),(h||m)&&(i=f),Et(i,t)&&(i=ce(-i,t)),{isValid:u||h,value:i}}var Ht=fh(Ea,{uvRatio:Sa}),Kt=Ht.Fp,bh=Ht.Fn;function s0(r){return uh(Ht,Zo,Object.assign({adjustScalarBytes:yh,zip215:!0},r))}var wh=s0({});var qn=(()=>{let r=gr;return lh({P:r,type:"x25519",powPminus2:e=>{let{pow_p_5_8:t,b2:n}=gh(e);return ce(se(t,r0,r)*n,r)},adjustScalarBytes:yh})})();var wa=ba,i0=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),a0=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),c0=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),f0=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),ph=r=>Sa(St,r),u0=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),xa=r=>Kt.create(Ke(r)&u0);function mh(r){let{d:e}=Ea,t=gr,n=d=>Kt.create(d),o=n(wa*r*r),s=n((o+St)*c0),i=BigInt(-1),a=n((i-e*o)*n(o+e)),{isValid:c,value:f}=Sa(s,a),u=n(f*r);Et(u,t)||(u=n(-u)),c||(f=u),c||(i=o);let h=n(i*(o-St)*f0-a),m=f*f,p=n((f+f)*a),y=n(h*i0),x=n(St-m),l=n(St+m);return new Ht(n(p*l),n(x*y),n(y*l),n(p*x))}var Vt=class r extends ss{static BASE=new r(Ht.BASE);static ZERO=new r(Ht.ZERO);static Fp=Kt;static Fn=bh;constructor(e){super(e)}static fromAffine(e){return new r(Ht.fromAffine(e))}assertSame(e){if(!(e instanceof r))throw new Error("RistrettoPoint expected")}init(e){return new r(e)}static fromBytes(e){Ie(e,32);let{a:t,d:n}=Ea,o=gr,s=R=>Kt.create(R),i=xa(e);if(!$u(Kt.toBytes(i),e)||Et(i,o))throw new Error("invalid ristretto255 encoding 1");let a=s(i*i),c=s(St+t*a),f=s(St-t*a),u=s(c*c),h=s(f*f),m=s(t*n*u-h),{isValid:p,value:y}=ph(s(m*h)),x=s(y*f),l=s(y*x*m),d=s((i+i)*x);Et(d,o)&&(d=s(-d));let v=s(c*l),L=s(d*v);if(!p||Et(L,o)||v===t0)throw new Error("invalid ristretto255 encoding 2");return new r(new Ht(d,v,St,L))}static fromHex(e){return r.fromBytes(Pn(e))}toBytes(){let{X:e,Y:t,Z:n,T:o}=this.ep,s=gr,i=l=>Kt.create(l),a=i(i(n+t)*i(n-t)),c=i(e*t),f=i(c*c),{value:u}=ph(i(a*f)),h=i(u*a),m=i(u*c),p=i(h*m*o),y;if(Et(o*p,s)){let l=i(t*wa),d=i(e*wa);e=l,t=d,y=i(h*a0)}else y=m;Et(e*p,s)&&(t=i(-t));let x=i((n-t)*y);return Et(x,s)&&(x=i(-x)),Kt.toBytes(x)}equals(e){this.assertSame(e);let{X:t,Y:n}=this.ep,{X:o,Y:s}=e.ep,i=f=>Kt.create(f),a=i(t*s)===i(n*o),c=i(n*s)===i(t*o);return a||c}is0(){return this.equals(r.ZERO)}};Object.freeze(Vt.BASE);Object.freeze(Vt.ZERO);Object.freeze(Vt.prototype);Object.freeze(Vt);var h0=Object.freeze({Point:Vt,hashToCurve(r,e){let t=e?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":e.DST,n=ya(r,t,64,Zo);return h0.deriveToCurve(n)},hashToScalar(r,e={DST:hh}){let t=ya(r,e.DST,64,Zo);return bh.create(Ke(t))},deriveToCurve(r){Ie(r,64);let e=xa(r.subarray(0,32)),t=mh(e),n=xa(r.subarray(32,64)),o=mh(n);return new Vt(t.add(o))}});var jn=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},as=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var je={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new as("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 cs=32;var Aa,l0=(async()=>{try{return await je.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function d0(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await je.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await je.get().subtle.verify({name:"Ed25519"},n,Se(e),Se(t instanceof Uint8Array?t:t.subarray()))}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function p0(r,e,t){return wh.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function xh(r,e,t){return Aa==null&&(Aa=await l0),Aa?d0(r,e,t):p0(r,e,t)}function fs(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var us=class{type="Ed25519";raw;constructor(e){this.raw=va(e,cs)}toMultihash(){return Xe.digest(Pt(this))}toCID(){return pe.createV1(114,this.toMultihash())}toString(){return he.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ee(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let o=xh(this.raw,t,e);return fs(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function Ca(r){return r=va(r,cs),new us(r)}function va(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new $(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var g0=Math.pow(2,7),y0=Math.pow(2,14),b0=Math.pow(2,21),La=Math.pow(2,28),_a=Math.pow(2,35),Ia=Math.pow(2,42),Ta=Math.pow(2,49),Z=128,Te=127;function ie(r){if(r<g0)return 1;if(r<y0)return 2;if(r<b0)return 3;if(r<La)return 4;if(r<_a)return 5;if(r<Ia)return 6;if(r<Ta)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Xr(r,e,t=0){switch(ie(r)){case 8:e[t++]=r&255|Z,r/=128;case 7:e[t++]=r&255|Z,r/=128;case 6:e[t++]=r&255|Z,r/=128;case 5:e[t++]=r&255|Z,r/=128;case 4:e[t++]=r&255|Z,r>>>=7;case 3:e[t++]=r&255|Z,r>>>=7;case 2:e[t++]=r&255|Z,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function w0(r,e,t=0){switch(ie(r)){case 8:e.set(t++,r&255|Z),r/=128;case 7:e.set(t++,r&255|Z),r/=128;case 6:e.set(t++,r&255|Z),r/=128;case 5:e.set(t++,r&255|Z),r/=128;case 4:e.set(t++,r&255|Z),r>>>=7;case 3:e.set(t++,r&255|Z),r>>>=7;case 2:e.set(t++,r&255|Z),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function Ba(r,e){let t=r[e],n=0;if(n+=t&Te,t<Z||(t=r[e+1],n+=(t&Te)<<7,t<Z)||(t=r[e+2],n+=(t&Te)<<14,t<Z)||(t=r[e+3],n+=(t&Te)<<21,t<Z)||(t=r[e+4],n+=(t&Te)*La,t<Z)||(t=r[e+5],n+=(t&Te)*_a,t<Z)||(t=r[e+6],n+=(t&Te)*Ia,t<Z)||(t=r[e+7],n+=(t&Te)*Ta,t<Z))return n;throw new RangeError("Could not decode varint")}function x0(r,e){let t=r.get(e),n=0;if(n+=t&Te,t<Z||(t=r.get(e+1),n+=(t&Te)<<7,t<Z)||(t=r.get(e+2),n+=(t&Te)<<14,t<Z)||(t=r.get(e+3),n+=(t&Te)<<21,t<Z)||(t=r.get(e+4),n+=(t&Te)*La,t<Z)||(t=r.get(e+5),n+=(t&Te)*_a,t<Z)||(t=r.get(e+6),n+=(t&Te)*Ia,t<Z)||(t=r.get(e+7),n+=(t&Te)*Ta,t<Z))return n;throw new RangeError("Could not decode varint")}function hs(r,e,t=0){return e==null&&(e=be(ie(r))),e instanceof Uint8Array?Xr(r,e,t):w0(r,e,t)}function At(r,e=0){return r instanceof Uint8Array?Ba(r,e):x0(r,e)}var Da=new Float32Array([-0]),zt=new Uint8Array(Da.buffer);function Sh(r,e,t){Da[0]=r,e[t]=zt[0],e[t+1]=zt[1],e[t+2]=zt[2],e[t+3]=zt[3]}function Ah(r,e){return zt[0]=r[e],zt[1]=r[e+1],zt[2]=r[e+2],zt[3]=r[e+3],Da[0]}var Ra=new Float64Array([-0]),Be=new Uint8Array(Ra.buffer);function vh(r,e,t){Ra[0]=r,e[t]=Be[0],e[t+1]=Be[1],e[t+2]=Be[2],e[t+3]=Be[3],e[t+4]=Be[4],e[t+5]=Be[5],e[t+6]=Be[6],e[t+7]=Be[7]}function Ch(r,e){return Be[0]=r[e],Be[1]=r[e+1],Be[2]=r[e+2],Be[3]=r[e+3],Be[4]=r[e+4],Be[5]=r[e+5],Be[6]=r[e+6],Be[7]=r[e+7],Ra[0]}var E0=BigInt(Number.MAX_SAFE_INTEGER),S0=BigInt(Number.MIN_SAFE_INTEGER),Ve=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 yr;if(e<E0&&e>S0)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>Lh&&(o=0n,++n>Lh&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return yr;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):yr}},yr=new Ve(0,0);yr.toBigInt=function(){return 0n};yr.zzEncode=yr.zzDecode=function(){return this};yr.length=function(){return 1};var Lh=4294967296n;function _h(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 Ih(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 et(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function ls(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=Se(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 ls(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw et(this,4);return ls(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw et(this,4);let e=Ah(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw et(this,4);let e=Ch(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 et(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Ih(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 Ve(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 et(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 et(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 et(this,8);let e=ls(this.buf,this.pos+=4),t=ls(this.buf,this.pos+=4);return new Ve(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=Ba(this.buf,this.pos);return this.pos+=ie(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(r){return new Pa(r instanceof Uint8Array?r:r.subarray())}function $t(r,e,t){let n=Wn(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 be(i);o+i>e&&(n=be(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var br=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}},A0=Na();function v0(r){return globalThis.Buffer!=null?be(r):A0(r)}var Yn=class{len;head;tail;states;constructor(){this.len=0,this.head=new br(Ua,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new br(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(ds,10,Ve.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Ve.fromBigInt(e);return this._push(ds,t.length(),t)}uint64Number(e){return this._push(Xr,ie(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=Ve.fromBigInt(e).zzEncode();return this._push(ds,t.length(),t)}sint64Number(e){let t=Ve.fromNumber(e).zzEncode();return this._push(ds,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(Xn,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Ve.fromBigInt(e);return this._push(Xn,4,t.lo)._push(Xn,4,t.hi)}fixed64Number(e){let t=Ve.fromNumber(e);return this._push(Xn,4,t.lo)._push(Xn,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(Sh,4,e)}double(e){return this._push(vh,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(Fa,1,0):this.uint32(t)._push(L0,t,e)}string(e){let t=_h(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 br(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 br(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=v0(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 C0(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var Ma=class extends br{next;constructor(e,t){super(C0,e,t),this.next=void 0}};function ds(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 Xn(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 L0(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(Yn.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(_0,e,r),this},Yn.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(I0,e,r),this});function _0(r,e,t){e.set(r,t)}function I0(r,e,t){r.length<40?Oa(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(Y(r),t)}function Ka(){return new Yn}function qt(r,e){let t=Ka();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}function*jt(r,e,t){let n=Wn(r);yield*e.stream(n,void 0,"$",t)}var ps={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function ms(r,e,t,n,o){return{name:r,type:e,encode:t,decode:n,stream:o}}function wr(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 ms("enum",ps.VARINT,t,n,o)}function Gt(r,e,t){return ms("message",ps.LENGTH_DELIMITED,r,e,t)}var fe;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(fe||(fe={}));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=()=>wr(Ha)})(fe||(fe={}));var ft;(function(r){let e;r.codec=()=>(e==null&&(e=Gt((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),fe.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=fe.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:fe.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 qt(s,r.codec())}r.encode=t;function n(s,i){return $t(s,r.codec(),i)}r.decode=n;function o(s,i){return jt(s,r.codec(),i)}r.stream=o})(ft||(ft={}));var Va;(function(r){let e;r.codec=()=>(e==null&&(e=Gt((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),fe.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=fe.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:fe.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 qt(s,r.codec())}r.encode=t;function n(s,i){return $t(s,r.codec(),i)}r.decode=n;function o(s,i){return jt(s,r.codec(),i)}r.stream=o})(Va||(Va={}));var Jn={};re(Jn,{MAX_RSA_KEY_SIZE:()=>za,generateRSAKeyPair:()=>Ph,jwkToJWKKeyPair:()=>Nh,jwkToPkcs1:()=>R0,jwkToPkix:()=>Ga,jwkToRSAPrivateKey:()=>Za,pkcs1MessageToJwk:()=>qa,pkcs1MessageToRSAPrivateKey:()=>Wa,pkcs1ToJwk:()=>D0,pkcs1ToRSAPrivateKey:()=>Oh,pkixMessageToJwk:()=>ja,pkixMessageToRSAPublicKey:()=>Ya,pkixToJwk:()=>O0,pkixToRSAPublicKey:()=>Xa});var Yr=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 pe.createV1(114,this._multihash)}toString(){return he.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ee(this.raw,e.raw)}verify(e,t,n){return Rh(this.jwk,t,e,n)}},Zn=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:Ee(this.raw,e.raw)}sign(e,t){return Dh(this.jwk,e,t)}};var za=8192,$a=18,T0=1062,B0=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function D0(r){let e=yt(r);return qa(e)}function qa(r){return{n:G(r[1],"base64url"),e:G(r[2],"base64url"),d:G(r[3],"base64url"),p:G(r[4],"base64url"),q:G(r[5],"base64url"),dp:G(r[6],"base64url"),dq:G(r[7],"base64url"),qi:G(r[8],"base64url"),kty:"RSA"}}function R0(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 $("JWK was missing components");return Ot([Fe(Uint8Array.from([0])),Fe(Y(r.n,"base64url")),Fe(Y(r.e,"base64url")),Fe(Y(r.d,"base64url")),Fe(Y(r.p,"base64url")),Fe(Y(r.q,"base64url")),Fe(Y(r.dp,"base64url")),Fe(Y(r.dq,"base64url")),Fe(Y(r.qi,"base64url"))]).subarray()}function O0(r){let e=yt(r,{offset:0});return ja(e)}function ja(r){let e=yt(r[1],{offset:0});return{kty:"RSA",n:G(e[0],"base64url"),e:G(e[1],"base64url")}}function Ga(r){if(r.n==null||r.e==null)throw new $("JWK was missing components");return Ot([B0,jo(Ot([Fe(Y(r.n,"base64url")),Fe(Y(r.e,"base64url"))]))]).subarray()}function Oh(r){let e=yt(r);return Wa(e)}function Wa(r){let e=qa(r);return Za(e)}function Xa(r,e){if(r.byteLength>=T0)throw new Dr("Key size is too large");let t=yt(r,{offset:0});return Ya(t,r,e)}function Ya(r,e,t){let n=ja(r);if(t==null){let o=ct(ft.encode({Type:fe.RSA,Data:e}));t=Ne($a,o)}return new Yr(n,t)}function Za(r){if(Fh(r)>za)throw new $("Key size is too large");let e=Nh(r),t=ct(ft.encode({Type:fe.RSA,Data:Ga(e.publicKey)})),n=Ne($a,t);return new Zn(e.privateKey,new Yr(e.publicKey,n))}async function Ph(r){if(r>za)throw new $("Key size is too large");let e=await Uh(r),t=ct(ft.encode({Type:fe.RSA,Data:Ga(e.publicKey)})),n=Ne($a,t);return new Zn(e.privateKey,new Yr(e.publicKey,n))}function Nh(r){if(r==null)throw new $("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function Uh(r,e){let t=await je.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 P0(t,e);return{privateKey:n[0],publicKey:n[1]}}async function Dh(r,e,t){let n=await je.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let o=await je.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,Se(e instanceof Uint8Array?e:e.subarray()));return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function Rh(r,e,t,n){let o=await je.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let s=await je.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,Se(e),Se(t instanceof Uint8Array?t:t.subarray()));return n?.signal?.throwIfAborted(),s}async function P0(r,e){if(r.privateKey==null||r.publicKey==null)throw new $("Private and public key are required");let t=await Promise.all([je.get().subtle.exportKey("jwk",r.privateKey),je.get().subtle.exportKey("jwk",r.publicKey)]);return e?.signal?.throwIfAborted(),t}function Fh(r){if(r.kty!=="RSA")throw new $("invalid key type");if(r.n==null)throw new $("invalid key modulus");return Y(r.n,"base64url").length*8}var gs=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(ar(e),Ie(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(t.length>n?e.create().update(t).digest():t);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),Ye(o)}update(e){return Kr(this),this.iHash.update(e),this}digestInto(e){Kr(this),Go(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Qn=(()=>{let r=((e,t,n)=>new gs(e,t).update(n).digest());return r.create=(e,t)=>new gs(e,t),r})();var kh=(r,e)=>(r+(r>=0?e:-e)/Mh)/e;function N0(r,e,t){xt("scalar",r,ut,t);let[[n,o],[s,i]]=e,a=kh(i*r,t),c=kh(-o*r,t),f=r-a*n-c*s,u=-a*o-c*i,h=f<ut,m=u<ut;h&&(f=-f),m&&(u=-u);let p=Kn(Math.ceil(zr(t)/2))+Wt;if(f<ut||f>=p||u<ut||u>=p)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:h,k1:f,k2neg:m,k2:u}}function Qa(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function Ja(r,e){He(r);let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return Je(t.lowS,"lowS"),Je(t.prehash,"prehash"),t.format!==void 0&&Qa(t.format),t}var ec=class extends Error{constructor(e=""){super(e)}},tt={Err:ec,_tlv:{encode:(r,e)=>{let{Err:t}=tt;if(Qe(r,"tag"),r<0||r>255)throw new t("tlv.encode: wrong tag");if(typeof e!="string")throw new TypeError('"data" expected string, got type='+typeof e);if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,o=kn(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let s=n>127?kn(o.length/2|128):"";return kn(r)+s+o+e},decode(r,e){let{Err:t}=tt;e=V(e,void 0,"DER data");let n=0;if(r<0||r>255)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let o=e[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let f=e.subarray(n,n+c);if(f.length!==c)throw new t("tlv.decode: length bytes not complete");if(f[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let u of f)i=i<<8|u;if(n+=c,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(r){let{Err:e}=tt;if(es(r),r<ut)throw new e("integer: negative integers are not allowed");let t=kn(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}=tt;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 lr(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=tt,o=V(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}=tt,n=e.encode(2,t.encode(r.r)),o=e.encode(2,t.encode(r.s)),s=n+o;return e.encode(48,s)}};Object.freeze(tt._tlv);Object.freeze(tt._int);Object.freeze(tt);var ut=BigInt(0),Wt=BigInt(1),Mh=BigInt(2),ys=BigInt(3),U0=BigInt(4);function Kh(r,e={}){let t=os("weierstrass",r,e),n=t.Fp,o=t.Fn,s=t.CURVE,{h:i,n:a}=s;He(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c,allowInfinityPoint:f}=e;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let u=Vh(n,o);function h(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function m(N,g,A){if(f&&g.is0())return Uint8Array.of(0);let{x:S,y:w}=g.toAffine(),b=n.toBytes(S);if(Je(A,"isCompressed"),A){h();let C=!n.isOdd(w);return me(Hh(C),b)}else return me(Uint8Array.of(4),b,n.toBytes(w))}function p(N){V(N,void 0,"Point");let{publicKey:g,publicKeyUncompressed:A}=u,S=N.length,w=N[0],b=N.subarray(1);if(f&&S===1&&w===0)return{x:n.ZERO,y:n.ZERO};if(S===g&&(w===2||w===3)){let C=n.fromBytes(b);if(!n.isValid(C))throw new Error("bad point: is not on curve, wrong x");let _=l(C),E;try{E=n.sqrt(_)}catch(k){let H=k instanceof Error?": "+k.message:"";throw new Error("bad point: is not on curve, sqrt error"+H)}h();let D=n.isOdd(E);return(w&1)===1!==D&&(E=n.neg(E)),{x:C,y:E}}else if(S===A&&w===4){let C=n.BYTES,_=n.fromBytes(b.subarray(0,C)),E=n.fromBytes(b.subarray(C,C*2));if(!d(_,E))throw new Error("bad point: is not on curve");return{x:_,y:E}}else throw new Error(`bad point: got length ${S}, expected compressed=${g} or uncompressed=${A}`)}let y=e.toBytes===void 0?m:e.toBytes,x=e.fromBytes===void 0?p:e.fromBytes;function l(N){let g=n.sqr(N),A=n.mul(g,N);return n.add(n.add(A,n.mul(N,s.a)),s.b)}function d(N,g){let A=n.sqr(g),S=l(N);return n.eql(A,S)}if(!d(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let v=n.mul(n.pow(s.a,ys),U0),L=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(v,L)))throw new Error("bad curve params: a or b");function R(N,g,A=!1){if(!n.isValid(g)||A&&n.is0(g))throw new Error(`bad point coordinate ${N}`);return g}function B(N){if(!(N instanceof T))throw new Error("Weierstrass Point expected")}function U(N){if(!c||!c.basises)throw new Error("no endo");return N0(N,c.basises,o.ORDER)}function I(N,g,A,S,w){return A=new T(n.mul(A.X,N),A.Y,A.Z),g=Vn(S,g),A=Vn(w,A),g.add(A)}class T{static BASE=new T(s.Gx,s.Gy,n.ONE);static ZERO=new T(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(g,A,S){this.X=R("x",g),this.Y=R("y",A,!0),this.Z=R("z",S),Object.freeze(this)}static CURVE(){return s}static fromAffine(g){let{x:A,y:S}=g||{};if(!g||!n.isValid(A)||!n.isValid(S))throw new Error("invalid affine point");if(g instanceof T)throw new Error("projective point not allowed");return n.is0(A)&&n.is0(S)?T.ZERO:new T(A,S,n.ONE)}static fromBytes(g){let A=T.fromAffine(x(V(g,void 0,"point")));return A.assertValidity(),A}static fromHex(g){return T.fromBytes(Vr(g))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,A=!0){return F.createCache(this,g),A||this.multiply(ys),this}assertValidity(){let g=this;if(g.is0()){if(e.allowInfinityPoint&&n.is0(g.X)&&n.eql(g.Y,n.ONE)&&n.is0(g.Z))return;throw new Error("bad point: ZERO")}let{x:A,y:S}=g.toAffine();if(!n.isValid(A)||!n.isValid(S))throw new Error("bad point: x or y not field elements");if(!d(A,S))throw new Error("bad point: equation left != right");if(!g.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:g}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(g)}equals(g){B(g);let{X:A,Y:S,Z:w}=this,{X:b,Y:C,Z:_}=g,E=n.eql(n.mul(A,_),n.mul(b,w)),D=n.eql(n.mul(S,_),n.mul(C,w));return E&&D}negate(){return new T(this.X,n.neg(this.Y),this.Z)}double(){let{a:g,b:A}=s,S=n.mul(A,ys),{X:w,Y:b,Z:C}=this,_=n.ZERO,E=n.ZERO,D=n.ZERO,P=n.mul(w,w),k=n.mul(b,b),H=n.mul(C,C),K=n.mul(w,b);return K=n.add(K,K),D=n.mul(w,C),D=n.add(D,D),_=n.mul(g,D),E=n.mul(S,H),E=n.add(_,E),_=n.sub(k,E),E=n.add(k,E),E=n.mul(_,E),_=n.mul(K,_),D=n.mul(S,D),H=n.mul(g,H),K=n.sub(P,H),K=n.mul(g,K),K=n.add(K,D),D=n.add(P,P),P=n.add(D,P),P=n.add(P,H),P=n.mul(P,K),E=n.add(E,P),H=n.mul(b,C),H=n.add(H,H),P=n.mul(H,K),_=n.sub(_,P),D=n.mul(H,k),D=n.add(D,D),D=n.add(D,D),new T(_,E,D)}add(g){B(g);let{X:A,Y:S,Z:w}=this,{X:b,Y:C,Z:_}=g,E=n.ZERO,D=n.ZERO,P=n.ZERO,k=s.a,H=n.mul(s.b,ys),K=n.mul(A,b),Q=n.mul(S,C),ee=n.mul(w,_),te=n.add(A,S),j=n.add(b,C);te=n.mul(te,j),j=n.add(K,Q),te=n.sub(te,j),j=n.add(A,w);let ae=n.add(b,_);return j=n.mul(j,ae),ae=n.add(K,ee),j=n.sub(j,ae),ae=n.add(S,w),E=n.add(C,_),ae=n.mul(ae,E),E=n.add(Q,ee),ae=n.sub(ae,E),P=n.mul(k,j),E=n.mul(H,ee),P=n.add(E,P),E=n.sub(Q,P),P=n.add(Q,P),D=n.mul(E,P),Q=n.add(K,K),Q=n.add(Q,K),ee=n.mul(k,ee),j=n.mul(H,j),Q=n.add(Q,ee),ee=n.sub(K,ee),ee=n.mul(k,ee),j=n.add(j,ee),K=n.mul(Q,j),D=n.add(D,K),K=n.mul(ae,j),E=n.mul(te,E),E=n.sub(E,K),K=n.mul(te,Q),P=n.mul(ae,P),P=n.add(P,K),new T(E,D,P)}subtract(g){return B(g),this.add(g.negate())}is0(){return this.equals(T.ZERO)}multiply(g){let{endo:A}=e;if(!o.isValidNot0(g))throw new RangeError("invalid scalar: out of range");let S,w,b=C=>F.cached(this,C,_=>mr(T,_));if(A){let{k1neg:C,k1:_,k2neg:E,k2:D}=U(g),{p:P,f:k}=b(_),{p:H,f:K}=b(D);w=k.add(K),S=I(A.beta,P,H,C,E)}else{let{p:C,f:_}=b(g);S=C,w=_}return mr(T,[S,w])[0]}multiplyUnsafe(g){let{endo:A}=e,S=this,w=g;if(!o.isValid(w))throw new RangeError("invalid scalar: out of range");if(w===ut||S.is0())return T.ZERO;if(w===Wt)return S;if(F.hasCache(this))return this.multiply(w);if(A){let{k1neg:b,k1:C,k2neg:_,k2:E}=U(w),{p1:D,p2:P}=ch(T,S,C,E);return I(A.beta,D,P,b,_)}else return F.unsafe(S,w)}toAffine(g){let A=this,S=g,{X:w,Y:b,Z:C}=A;if(n.eql(C,n.ONE))return{x:w,y:b};let _=A.is0();S==null&&(S=_?n.ONE:n.inv(C));let E=n.mul(w,S),D=n.mul(b,S),P=n.mul(C,S);if(_)return{x:n.ZERO,y:n.ZERO};if(!n.eql(P,n.ONE))throw new Error("invZ was invalid");return{x:E,y:D}}isTorsionFree(){let{isTorsionFree:g}=e;return i===Wt?!0:g?g(T,this):F.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:g}=e;return i===Wt?this:g?g(T,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===Wt?this.is0():this.clearCofactor().is0()}toBytes(g=!0){return Je(g,"isCompressed"),this.assertValidity(),y(T,this,g)}toHex(g=!0){return Hr(this.toBytes(g))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let O=o.BITS,F=new jr(T,e.endo?Math.ceil(O/2):O);return O>=8&&T.BASE.precompute(8),Object.freeze(T.prototype),Object.freeze(T),T}function Hh(r){return Uint8Array.of(r?2:3)}function Vh(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function F0(r,e={}){let{Fn:t}=r,n=e.randomBytes===void 0?hr:e.randomBytes,o=Object.assign(Vh(r.Fp,t),{seed:Math.max(ha(t.ORDER),16)});function s(p){try{let y=t.fromBytes(p);return t.isValidNot0(y)}catch{return!1}}function i(p,y){let{publicKey:x,publicKeyUncompressed:l}=o;try{let d=p.length;return y===!0&&d!==x||y===!1&&d!==l?!1:!!r.fromBytes(p)}catch{return!1}}function a(p){return p=p===void 0?n(o.seed):p,la(V(p,o.seed,"seed"),t.ORDER)}function c(p,y=!0){return r.BASE.multiply(t.fromBytes(p)).toBytes(y)}function f(p){let{secretKey:y,publicKey:x,publicKeyUncompressed:l}=o,d=t._lengths;if(!ur(p))return;let v=V(p,void 0,"key").length,L=v===x||v===l,R=v===y||!!d?.includes(v);if(!(L&&R))return L}function u(p,y,x=!0){if(f(p)===!0)throw new Error("first arg must be private key");if(f(y)===!1)throw new Error("second arg must be public key");let l=t.fromBytes(p);return r.fromBytes(y).multiply(l).toBytes(x)}let h={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},m=Gr(a,c);return Object.freeze(h),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:m,Point:r,utils:h,lengths:o})}function zh(r,e,t={}){let n=e;ar(n),He(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let o=t.randomBytes===void 0?hr:t.randomBytes,s=t.hmac===void 0?(w,b)=>Qn(n,w,b):t.hmac,{Fp:i,Fn:a}=r,{ORDER:c,BITS:f}=a,{keygen:u,getPublicKey:h,getSharedSecret:m,utils:p,lengths:y}=F0(r,t),x={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},l=c*Mh+Wt<i.ORDER;function d(w){let b=c>>Wt;return w>b}function v(w,b){if(!a.isValidNot0(b))throw new Error(`invalid signature ${w}: out of range 1..Point.Fn.ORDER`);return b}function L(){if(l)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function R(w,b){Qa(b);let C=y.signature,_=b==="compact"?C:b==="recovered"?C+1:void 0;return V(w,_)}class B{r;s;recovery;constructor(b,C,_){if(this.r=v("r",b),this.s=v("s",C),_!=null){if(L(),![0,1,2,3].includes(_))throw new Error("invalid recovery id");this.recovery=_}Object.freeze(this)}static fromBytes(b,C=x.format){R(b,C);let _;if(C==="der"){let{r:k,s:H}=tt.toSig(V(b));return new B(k,H)}C==="recovered"&&(_=b[0],C="compact",b=b.subarray(1));let E=y.signature/2,D=b.subarray(0,E),P=b.subarray(E,E*2);return new B(a.fromBytes(D),a.fromBytes(P),_)}static fromHex(b,C){return this.fromBytes(Vr(b),C)}assertRecovery(){let{recovery:b}=this;if(b==null)throw new Error("invalid recovery id: must be present");return b}addRecoveryBit(b){return new B(this.r,this.s,b)}recoverPublicKey(b){let{r:C,s:_}=this,E=this.assertRecovery(),D=E===2||E===3?C+c:C;if(!i.isValid(D))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let P=i.toBytes(D),k=r.fromBytes(me(Hh((E&1)===0),P)),H=a.inv(D),K=I(V(b,void 0,"msgHash")),Q=a.create(-K*H),ee=a.create(_*H),te=r.BASE.multiplyUnsafe(Q).add(k.multiplyUnsafe(ee));if(te.is0())throw new Error("invalid recovery: point at infinify");return te.assertValidity(),te}hasHighS(){return d(this.s)}toBytes(b=x.format){if(Qa(b),b==="der")return Vr(tt.hexFromSig(this));let{r:C,s:_}=this,E=a.toBytes(C),D=a.toBytes(_);return b==="recovered"?(L(),me(Uint8Array.of(this.assertRecovery()),E,D)):me(E,D)}toHex(b){return Hr(this.toBytes(b))}}Object.freeze(B.prototype),Object.freeze(B);let U=t.bits2int===void 0?function(b){if(b.length>8192)throw new Error("input is too large");let C=lr(b),_=b.length*8-f;return _>0?C>>BigInt(_):C}:t.bits2int,I=t.bits2int_modN===void 0?function(b){return a.create(U(b))}:t.bits2int_modN,T=Kn(f);function O(w){return xt("num < 2^"+f,w,ut,T),a.toBytes(w)}function F(w,b){return V(w,void 0,"message"),b?V(n(w),void 0,"prehashed message"):w}function N(w,b,C){let{lowS:_,prehash:E,extraEntropy:D}=Ja(C,x);w=F(w,E);let P=I(w),k=a.fromBytes(b);if(!a.isValidNot0(k))throw new Error("invalid private key");let H=[O(k),O(P)];if(D!=null&&D!==!1){let te=D===!0?o(y.secretKey):D;H.push(V(te,void 0,"extraEntropy"))}let K=me(...H),Q=P;function ee(te){let j=U(te);if(!a.isValidNot0(j))return;let ae=a.inv(j),mt=r.BASE.multiply(j).toAffine(),rr=a.create(mt.x);if(rr===ut)return;let Br=a.create(ae*a.create(Q+rr*k));if(Br===ut)return;let vn=(mt.x===rr?0:2)|Number(mt.y&Wt),Cn=Br;return _&&d(Br)&&(Cn=a.neg(Br),vn^=1),new B(rr,Cn,l?void 0:vn)}return{seed:K,k2sig:ee}}function g(w,b,C={}){let{seed:_,k2sig:E}=N(w,b,C);return qu(n.outputLen,a.BYTES,s)(_,E).toBytes(C.format)}function A(w,b,C,_={}){let{lowS:E,prehash:D,format:P}=Ja(_,x);if(C=V(C,void 0,"publicKey"),b=F(b,D),!ur(w)){let k=w instanceof B?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+k)}R(w,P);try{let k=B.fromBytes(w,P),H=r.fromBytes(C);if(E&&k.hasHighS())return!1;let{r:K,s:Q}=k,ee=I(b),te=a.inv(Q),j=a.create(ee*te),ae=a.create(K*te),mt=r.BASE.multiplyUnsafe(j).add(H.multiplyUnsafe(ae));return mt.is0()?!1:a.create(mt.x)===K}catch{return!1}}function S(w,b,C={}){let{prehash:_}=Ja(C,x);return b=F(b,_),B.fromBytes(w,"recovered").recoverPublicKey(b).toBytes()}return Object.freeze({keygen:u,getPublicKey:h,getSharedSecret:m,utils:p,lengths:y,Point:r,sign:g,verify:A,recoverPublicKey:S,Signature:B,hash:n})}var rc={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},k0={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var $h=BigInt(2);function M0(r){let e=rc.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=se(u,t,e)*u%e,m=se(h,t,e)*u%e,p=se(m,$h,e)*f%e,y=se(p,o,e)*p%e,x=se(y,s,e)*y%e,l=se(x,a,e)*x%e,d=se(l,c,e)*l%e,v=se(d,a,e)*x%e,L=se(v,t,e)*u%e,R=se(L,i,e)*y%e,B=se(R,n,e)*f%e,U=se(B,$h,e);if(!tc.eql(tc.sqr(U),r))throw new Error("Cannot find square root");return U}var tc=$r(rc.p,{sqrt:M0}),K0=Kh(rc,{Fp:tc,endo:k0}),Zr=zh(K0,ct);function qh(r,e,t,n){let o=gt.digest(t instanceof Uint8Array?t:t.subarray());if(fs(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),Zr.verify(e,s,r,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new jn(String(s))});try{return n?.signal?.throwIfAborted(),Zr.verify(e,o.digest,r,{prehash:!1,format:"der"})}catch(s){throw new jn(String(s))}}var bs=class{type="secp256k1";raw;_key;constructor(e){this._key=Gh(e),this.raw=jh(this._key)}toMultihash(){return Xe.digest(Pt(this))}toCID(){return pe.createV1(114,this.toMultihash())}toString(){return he.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ee(this.raw,e.raw)}verify(e,t,n){return qh(this._key,t,e,n)}};function nc(r){return new bs(r)}function jh(r){return Zr.Point.fromBytes(r).toBytes()}function Gh(r){try{return Zr.Point.fromBytes(r),r}catch(e){throw new Dr(String(e))}}function eo(r,e){let{Type:t,Data:n}=ft.decode(r),o=n??new Uint8Array;switch(t){case fe.RSA:return Xa(o,e);case fe.Ed25519:return Ca(o);case fe.secp256k1:return nc(o);case fe.ECDSA:return Xi(o);default:throw new nr}}function Wh(r){let{Type:e,Data:t}=ft.decode(r.digest),n=t??new Uint8Array;switch(e){case fe.Ed25519:return Ca(n);case fe.secp256k1:return nc(n);case fe.ECDSA:return Xi(n);default:throw new nr}}function Pt(r){return ft.encode({Type:fe[r.type],Data:r.raw})}var Xh=Symbol.for("nodejs.util.inspect.custom"),H0=114,to=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()})`}[xi]=!0;toString(){return this.string==null&&(this.string=he.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return pe.createV1(H0,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return Ee(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return Ee(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Xh](){return`PeerId(${this.toString()})`}},ro=class extends to{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},no=class extends to{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},oo=class extends to{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},V0=2336,so=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Xe.digest(Y(this.url))}[Xh](){return`PeerId(${this.url})`}[xi]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return pe.createV1(V0,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=G(e)),e.toString()===this.toString())}};var z0=114,Yh=2336;function Jr(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=kr(he.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return $0(pe.parse(r));if(e==null)throw new $('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=kr(e.decode(r))}return Zh(t)}function oc(r){if(r.type==="Ed25519")return new no({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new oo({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new ro({multihash:r.toCID().multihash,publicKey:r});throw new nr}function Zh(r){if(j0(r))return new ro({multihash:r});if(q0(r))try{let e=Wh(r);if(e.type==="Ed25519")return new no({multihash:r,publicKey:e});if(e.type==="secp256k1")return new oo({multihash:r,publicKey:e})}catch{let t=G(r.digest);return new so(new URL(t))}throw new Fo("Supplied PeerID Multihash is invalid")}function $0(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==z0&&r.code!==Yh)throw new Uo("Supplied PeerID CID is invalid");if(r.code===Yh){let e=G(r.multihash.digest);return new so(new URL(e))}return Zh(r.multihash)}function q0(r){return r.code===Xe.code}function j0(r){return r.code===gt.code}var Ce=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},vt=class extends Error{static name="ValidationError";name="ValidationError"},ws=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},xs=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var Es=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 m=Number.parseInt(h,e);if(!Number.isNaN(m))return m});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 G0=45,W0=15,Ss=new Es;function Jh(r){if(!(r.length>W0))return Ss.new(r).parseWith(()=>Ss.readIPv4Addr())}function Qh(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>G0))return Ss.new(r).parseWith(()=>Ss.readIPv6Addr())}function As(r){return!!Jh(r)}function el(r){return!!Qh(r)}function ic(r){return e=>G(e,r)}function ac(r){return e=>Y(e,r)}function Qr(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 tl(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=Y(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 Me([t,o],t.length+o.length)}function rl(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=Rt.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 Me([t,o],t.length+o.length)}function cc(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=G(e,"base32"),o=Qr(t);return`${n}:${o}`}var fc=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 Ce("Invalid byte value in IP address");e[n]=o}),e},nl=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=As(t[n]),i;s&&(i=fc(t[n]),t[n]=G(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,G(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 Ce("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},ol=function(r){if(r.byteLength!==4)throw new Ce("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},sl=function(r){if(r.byteLength!==16)throw new Ce("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 Ce(`Invalid IPv6 address "${t}"`)}};function il(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Ce(`Invalid IPv6 address "${r}"`)}}var sc=Object.values(ir).map(r=>r.decoder),X0=(function(){let r=sc[0].or(sc[1]);return sc.slice(2).forEach(e=>r=r.or(e)),r})();function al(r){return X0.decode(r)}function cl(r){return e=>r.encoder.encode(e)}function Y0(r){if(parseInt(r).toString()!==r)throw new vt("Value must be an integer")}function Z0(r){if(r<0)throw new vt("Value must be a positive integer, or zero")}function J0(r){return e=>{if(e>r)throw new vt(`Value must be smaller than or equal to ${r}`)}}function Q0(...r){return e=>{for(let t of r)t(e)}}var io=Q0(Y0,Z0,J0(65535));var xe=-1,uc=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 xs(`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)}))}},Lt=new uc,dg=[{code:4,name:"ip4",size:32,valueToBytes:fc,bytesToValue:ol,validate:r=>{if(!As(r))throw new vt(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:xr,bytesToValue:Qr,validate:io},{code:273,name:"udp",size:16,valueToBytes:xr,bytesToValue:Qr,validate:io},{code:33,name:"dccp",size:16,valueToBytes:xr,bytesToValue:Qr,validate:io},{code:41,name:"ip6",size:128,valueToBytes:nl,bytesToValue:sl,stringToValue:il,validate:r=>{if(!el(r))throw new vt(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:xe},{code:43,name:"ipcidr",size:8,bytesToValue:ic("base10"),valueToBytes:ac("base10")},{code:53,name:"dns",size:xe},{code:54,name:"dns4",size:xe},{code:55,name:"dns6",size:xe},{code:56,name:"dnsaddr",size:xe},{code:132,name:"sctp",size:16,valueToBytes:xr,bytesToValue:Qr,validate:io},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:xe,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:xe,bytesToValue:ic("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?ac("base58btc")(r):pe.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:cc,valueToBytes:tl},{code:445,name:"onion3",size:296,bytesToValue:cc,valueToBytes:rl},{code:446,name:"garlic64",size:xe},{code:447,name:"garlic32",size:xe},{code:448,name:"tls"},{code:449,name:"sni",size:xe},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:xe,bytesToValue:cl(Dn),valueToBytes:al},{code:480,name:"http"},{code:481,name:"http-path",size:xe,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:xe}];dg.forEach(r=>{Lt.addProtocol(r)});function fl(r){let e=[],t=0;for(;t<r.length;){let n=At(r,t),o=Lt.getProtocol(n),s=ie(n),i=pg(o,r,t+s),a=0;i>0&&o.size===xe&&(a=ie(i));let c=s+a+i,f={code:n,name:o.name,bytes:Se(r.subarray(t,t+c))};if(i>0){let u=t+s+a,h=r.subarray(u,u+i);f.value=o.bytesToValue?.(h)??G(h)}e.push(f),t+=c}return e}function ul(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=Lt.getProtocol(n.code),s=ie(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??Y(n.value),a=i.byteLength,o.size===xe&&(c=ie(a)));let f=new Uint8Array(s+c+a),u=0;Xr(n.code,f,u),u+=s,i!=null&&(o.size===xe&&(Xr(a,f,u),u+=c),f.set(i,u)),n.bytes=f}t.push(n.bytes),e+=n.bytes.byteLength}return Me(t,e)}function hl(r){if(r.charAt(0)!=="/")throw new Ce('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=Lt.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 Ce(`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 Ce(`Component ${o} was missing value`);f.value=c.stringToValue?.(n)??n}e.push(f),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new Ce("Incomplete multiaddr");return e}function ll(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=Lt.getProtocol(e.code);if(t==null)throw new Ce(`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:At(e,t)}var mg=Symbol.for("nodejs.util.inspect.custom"),_c=Symbol.for("@multiformats/multiaddr");function gg(r){if(r==null&&(r="/"),dl(r))return r.getComponents();if(r instanceof Uint8Array)return fl(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),hl(r);if(Array.isArray(r))return r;throw new Ce("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Is=class r{[_c]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=gg(e),t.validate!==!1&&yg(this)}get bytes(){return this.#r==null&&(this.#r=ul(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=ll(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 ws(`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 Ee(this.bytes,e.bytes)}[mg](){return`Multiaddr(${this.toString()})`}};function yg(r){r.getComponents().forEach(e=>{let t=Lt.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function dl(r){return!!r?.[_c]}function nn(r){return new Is(r)}var ne=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),M=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),pl=r=>({match:e=>r.match(e)===!1?e:!1}),z=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),De=(...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}}),W=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e}});function oe(...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 bg=M(421),g6=oe(bg),Bs=M(54),Ds=M(55),Rs=M(56),Tc=M(53),y6=oe(Bs,z(M(421))),b6=oe(Ds,z(M(421))),w6=oe(Rs,z(M(421))),x6=oe(De(Tc,Rs,Bs,Ds),z(M(421))),ml=W(M(4),z(M(43))),gl=W(z(M(42)),M(41),z(M(43))),Bc=De(ml,gl),on=De(Bc,Tc,Bs,Ds,Rs),E6=oe(De(Bc,W(De(Tc,Rs,Bs,Ds),z(M(421))))),S6=oe(ml),A6=oe(gl),v6=oe(Bc),Dc=W(on,M(6)),ao=W(on,M(273)),C6=oe(W(Dc,z(M(421)))),L6=oe(ao),Rc=W(ao,ne(460),z(M(421))),Os=W(ao,ne(461),z(M(421))),wg=De(Rc,Os),_6=oe(Rc),I6=oe(Os),Ic=De(on,Dc,ao,Rc,Os),yl=De(W(Ic,ne(477),z(M(421)))),T6=oe(yl),bl=De(W(Ic,ne(478),z(M(421))),W(Ic,ne(448),z(M(449)),ne(477),z(M(421)))),B6=oe(bl),wl=W(ao,ne(280),z(M(466)),z(M(466)),z(M(421))),xl=oe(wl),El=W(Os,ne(465),z(M(466)),z(M(466)),z(M(421))),D6=oe(El),Ts=De(yl,bl,W(Dc,z(M(421))),W(wg,z(M(421))),W(on,z(M(421))),wl,El,M(421)),Sl=oe(Ts),xg=W(z(Ts),ne(290),pl(ne(281)),z(M(421))),R6=oe(xg),Eg=De(W(Ts,ne(290),ne(281),z(M(421))),W(Ts,ne(281),z(M(421))),W(ne(281),z(M(421)))),Al=oe(Eg),Sg=W(on,De(W(M(6,"80")),W(M(6),ne(480)),ne(480)),z(M(481)),z(M(421))),O6=oe(Sg),Ag=W(on,De(W(M(6,"443")),W(M(6,"443"),ne(480)),W(M(6),ne(443)),W(M(6),ne(448),ne(480)),W(ne(448),ne(480)),ne(448),ne(443)),z(M(481)),z(M(421))),P6=oe(Ag),vg=De(W(M(777),z(M(421)))),N6=oe(vg),Cg=De(W(M(400),z(M(421)))),U6=oe(Cg);var Re;(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=()=>wr(t)})(e=r.Flag||(r.Flag={}));let n;r.codec=()=>(n==null&&(n=Gt((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 m=a.uint32();switch(m>>>3){case 1:{u.flag=r.Flag.codec().decode(a);break}case 2:{u.message=a.bytes();break}default:{a.skipType(m&7);break}}}return u},function*(a,c,f,u={}){let h=c==null?a.len:a.pos+c;for(;a.pos<h;){let m=a.uint32();switch(m>>>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(m&7);break}}}})),n);function o(a){return qt(a,r.codec())}r.encode=o;function s(a,c){return $t(a,r.codec(),c)}r.decode=s;function i(a,c){return jt(a,r.codec(),c)}r.stream=i})(Re||(Re={}));var vl=["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478","stun:stun.cloudflare.com:3478","stun:stun.services.mozilla.com:3478"],Oc=Array.from("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"),Cl="libp2p+webrtc+v1/",Ll=2*1024*1024,Sr=16*1024,_l=Sr,Il=10,Tl=8;function Lg(r=Sr){let e=ie(r-ie(r)),t=1+ie(Object.keys(Re.Flag).length-1),n=1,o=r-e-t-n,s=ie(o);return e+t+n+s}var Bl=Lg();var Dl=1e4,Pc="/webrtc",co="/webrtc-signaling/0.0.1";function _g(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 Nc(r){let e=_g(r);if(e==null)throw new $(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e}function Ps(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Ns=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}},sn=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Ns(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 Ns(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 Uc=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function an(r={}){return Ig(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 Ig(r,e){e=e??{};let t=e.onEnd,n=new sn,o,s,i,a=Ps(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((l,d)=>{s=v=>{s=null,n.push(v);try{l(r(n))}catch(L){d(L)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Ps()})}},f=l=>s!=null?s(l):(n.push(l),o),u=l=>(n=new sn,s!=null?s({error:l}):(n.push({error:l}),o)),h=l=>{if(i)return o;if(e?.objectMode!==!0&&l?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return f({done:!1,value:l})},m=l=>i?o:(i=!0,l!=null?u(l):f({done:!0})),p=()=>(n=new sn,m(),{done:!0}),y=l=>(m(l),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:p,throw:y,push:h,end:m,get readableLength(){return n.size},onEmpty:async l=>{let d=l?.signal;if(d?.throwIfAborted(),n.isEmpty())return;let v,L;d!=null&&(v=new Promise((R,B)=>{L=()=>{B(new Uc)},d.addEventListener("abort",L)}));try{await Promise.race([a.promise,v])}finally{L!=null&&d!=null&&d?.removeEventListener("abort",L)}}},t==null)return o;let x=o;return o={[Symbol.asyncIterator](){return this},next(){return x.next()},throw(l){return x.throw(l),t!=null&&(t(l),t=void 0),{done:!0}},return(){return x.return(),t!=null&&(t(),t=void 0),{done:!0}},push:h,end(l){return x.end(l),t!=null&&(t(l),t=void 0),o},get readableLength(){return x.readableLength},onEmpty:l=>x.onEmpty(l)},o}var Fc=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},Rl=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,m)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(i?.aborted){m(Rl(i));return}if(i&&(c=()=>{m(Rl(i))},i.addEventListener("abort",c,{once:!0})),r.then(h,m),t===Number.POSITIVE_INFINITY)return;let p=new Fc;a=s.setTimeout.call(void 0,()=>{if(n){try{h(n())}catch(y){m(y)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?h():o instanceof Error?m(o):(p.message=o??`Promise timed out after ${t} milliseconds`,m(p))},t)}).finally(()=>{u.clear(),c&&i&&i.removeEventListener("abort",c)});return u.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},u}var Tg=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 Bg(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}=Tg(r),h=async(...p)=>{let y=t.multiArgs?p:p[0];if(t.filter)try{if(!await t.filter(y))return}catch(x){n(),i(x);return}c.push(y),t.count===c.length&&(n(),s(c))},m=(...p)=>{n(),i(t.rejectionMultiArgs?p:p[0])};n=()=>{for(let p of a)u(p,h);for(let p of t.rejectionEvents)a.includes(p)||u(p,m)};for(let p of a)f(p,h);for(let p of t.rejectionEvents)a.includes(p)||f(p,m);t.signal&&t.signal.addEventListener("abort",()=>{m(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 Le(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=Bg(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"},Us=class extends Error{static name="MaxEarlyStreamsError";name="MaxEarlyStreamsError"},Fs=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function Dg(r){return r.reason}async function _t(r,e,t){if(e==null)return r;let n=t?.translateError??Dg;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let o;try{return await Promise.race([r,new Promise((s,i)=>{o=()=>{i(n(e))},e.addEventListener("abort",o)})])}finally{o!=null&&e.removeEventListener("abort",o)}}var Rg=Math.pow(2,20)*4,Yt=class extends Bt{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;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??Rg,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new X,this.writeBuffer=new X,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 Fs)};this.addEventListener("close",n)}get readBufferLength(){return this.readBuffer.byteLength}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),_t(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let e=an(),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 ot(`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();try{this.sendReset(e)}catch(t){this.log("failed to send reset to remote - %e",t)}this.dispatchEvent(new Ko(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new ot("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 ot("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 ot(`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 ot(`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");let e=new Rr;this.dispatchEvent(new Ho(e))}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.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.dispatchEvent(new Or))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.writeStatus==="closed"&&this.onTransportClosed())}onRemoteCloseRead(){this.log.trace("on remote close read"),this.remoteReadStatus="closed",this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle"))}processSendQueue(){if(this.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(this.writeBuffer.byteLength===0)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;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 X(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}}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 Mo(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.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new Ln(`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 Ln(`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 ks=class extends Yt{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 Le(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 Le(this,"drain",{...e,rejectionEvents:["close"]})),await this.sendClose(e),this.onTransportClosed())}};function Ol(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Ms=class extends Bt{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 _t(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 Po;let t=this.onCreateStream({...this.streamOptions,...e});return Ol(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 Us(`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 Ks=class extends Yt{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 Le(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 Le(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.log("closed readable end gracefully"))}};var Og=4194304,Hs=class extends Error{static name="UnwrappedError";name="UnwrappedError"},fo=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Kc=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Hc=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Pg(r){return typeof r?.closeRead=="function"}function Ng(r){return typeof r?.close=="function"}function Mc(r){return Pg(r)?r.remoteWriteStatus!=="writable"&&r.readBufferLength===0:Ng(r)?r.status!=="open":!1}function Ug(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function Fg(r,e){let t=e?.maxBufferSize??Og,n=new X,o,s=!1;if(!Ug(r))throw new $("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 Hs("Stream was unwrapped");if(Mc(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 _t(o.promise,u?.signal),Mc(r)){if(n.byteLength===0&&u?.bytes==null)return null;break}o=Promise.withResolvers()}let m=u?.bytes??n.byteLength;if(n.byteLength<m){if(Mc(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,m),new Ar(`Unexpected EOF - stream closed while reading ${n.byteLength}/${m} bytes`);return f.read(u)}let p=n.sublist(0,m);return n.consume(m),p},async write(u,h){if(s===!0)throw new Hs("Stream was unwrapped");r.send(u)||await Le(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 Vs(r,e={}){let t=Fg(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=ie(e.maxDataLength));let n=e?.lengthDecoder??At,o=e?.lengthEncoder??hs;return{async read(i){let a=-1,c=new X;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 fo("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new Hc(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new Kc(`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 X(o(i.byteLength),i),a)},async writeV(i,a){let c=new X(...i.flatMap(f=>[o(f.byteLength),f]));await t.write(c,a)},unwrap(){return t.unwrap()}}}function zs(r,e){let t=Vs(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 kg=1024*1024*4,Mg=1024*1024*4,$s=class{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(e={}){this.buffer=new X,this.maxBufferSize=e.maxBufferSize??kg,this.maxDataLength=e.maxDataLength??Mg,this.lengthDecoder=e.lengthDecoder??At,this.encodingLength=e.encodingLength??ie}*decode(e){if(this.buffer.append(e),this.buffer.byteLength>this.maxBufferSize)throw new $(`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 fo("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 qs=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},cn=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},js=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},uo=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Gs(r){return r[Symbol.asyncIterator]!=null}function Pl(r,e){if(r.byteLength>e)throw new cn("Message length too long")}var Xs=r=>{let e=ie(r),t=be(e);return hs(r,t),Xs.bytes=e,t};Xs.bytes=0;function ho(r,e){e=e??{};let t=e.lengthEncoder??Xs,n=e?.maxDataLength??4194304;function*o(s){Pl(s,n);let i=t(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return Gs(r)?(async function*(){for await(let s of r)yield*o(s)})():(function*(){for(let s of r)yield*o(s)})()}ho.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Xs,n=e?.maxDataLength??4194304;return Pl(r,n),new X(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=At(r);return Vc.bytes=ie(e),e};Vc.bytes=0;function lo(r,e){let t=new X,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 qs("Invalid message length");if(o>a)throw new cn("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 js("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 Gs(r)?(async function*(){for await(let f of r)t.append(f),yield*c();if(t.byteLength>0)throw new uo("Unexpected end of input")})():(function*(){for(let f of r)t.append(f),yield*c();if(t.byteLength>0)throw new uo("Unexpected end of input")})()}lo.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 lo(n,{...e??{},onLength:s=>{t=s}})};var zc=class extends Ks{channel;incomingData;maxBufferedAmount;receivedFinAck;finAckTimeout;constructor(e){super({...e,maxMessageSize:(e.maxMessageSize??Sr)-Bl}),this.channel=e.channel,this.channel.binaryType="arraybuffer",this.incomingData=an(),this.maxBufferedAmount=e.maxBufferedAmount??Ll,this.finAckTimeout=e.finAckTimeout??Dl,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 lo(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),Le(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 ot(`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(Se(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(ho.single(Re.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(Re.Flag.RESET),this.receivedFinAck?.reject(e)}catch(t){this.log.error("failed to send reset - %e",t)}}async sendCloseWrite(e){this._sendFlag(Re.Flag.FIN),e?.signal?.throwIfAborted(),this.receivedFinAck=Promise.withResolvers();let t=e?.signal??AbortSignal.timeout(this.finAckTimeout),n=[Le(this.channel,"close",{signal:t}),Le(this.channel,"error",{signal:t})];await Promise.any([_t(this.receivedFinAck.promise,t),...n]).finally(()=>{n.forEach(o=>o.cancel())})}async sendCloseRead(e){this._sendFlag(Re.Flag.STOP_SENDING),e?.signal?.throwIfAborted()}processIncomingProtobuf(e){let t=Re.decode(e);t.message!=null&&(this.readStatus==="readable"||this.readStatus==="paused")&&this.onData(new X(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===Re.Flag.FIN&&(this._sendFlag(Re.Flag.FIN_ACK),this.onRemoteCloseWrite()),t.flag===Re.Flag.RESET&&(this.receivedFinAck?.reject(new Rr("The stream was reset")),this.onRemoteReset()),t.flag===Re.Flag.STOP_SENDING&&this.onRemoteCloseRead(),t.flag===Re.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=Re.encode({flag:e}),n=ho.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 po(r){let{channel:e,direction:t,isHandshake:n}=r;return new zc({...r,id:`${e.id}`,log:r.log.newScope(`${n===!0?"handshake":t}:${e.id}`),protocol:""})}function jc(r,e){try{r.close()}catch(t){e?.trace("error closing early data channel - %e",t)}}function $c(r,e){r.channel.onmessage=null,r.messages.length=0,jc(r.channel,e)}var Zt=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??Pc,this.dataChannelOptions=e.dataChannelOptions??{},this.maxEarlyStreams=e.maxEarlyStreams??Il,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}),jc(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>=Tl){this.closeEarlyDataChannel(n,"message_count_exceeded");return}if(n.messages.reduce((a,c)=>a+c.data.byteLength,0)+s.byteLength>_l){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}),$c(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 qc(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)$c(e,this.log);this.earlyDataChannels.length=0}}},qc=class extends Ms{peerConnection;dataChannelOptions;constructor(e,t){super(e,{...t,name:"muxer"}),this.peerConnection=t.peerConnection,this.protocol=t.protocol??Pc,this.dataChannelOptions=t.dataChannelOptions??{},this.peerConnection.ondatachannel=({channel:n})=>{this.onDataChannel(n)},queueMicrotask(()=>{if(this.status!=="open"){t.earlyDataChannels.forEach(n=>{$c(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),jc(e,this.log);return}let n=po({...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),po({...e,...this.dataChannelOptions,channel:t,direction:"outbound",log:this.log})}onData(){}};var Gc=class extends ks{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(){}},mo=r=>new Gc(r);async function Wc(r){return r=r??{},typeof r=="function"&&(r=await r()),r.iceServers=r.iceServers??vl.map(e=>({urls:[e]})),r}var Nl=(r=32)=>Cl+[...Array(r)].map(()=>Oc.at(Math.floor(Math.random()*Oc.length))).join("");var Ys=globalThis.RTCPeerConnection,Zs=globalThis.RTCSessionDescription,Ul=globalThis.RTCIceCandidate;var ze=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var Jt=class extends Error{constructor(e){super(`WebRTC transport error: ${e}`),this.name="WebRTCTransportError"}},Ge=class extends Jt{constructor(e="SDP handshake failed"){super(e),this.name="SDPHandshakeFailedError"}};var Js=class extends Jt{constructor(e,t){super(`Invalid fingerprint "${e}" within ${t}`),this.name="WebRTC/InvalidFingerprintError"}};var Qs=class extends Jt{constructor(e){super(`A method (${e}) was called though it has been intentionally left unimplemented.`),this.name="WebRTC/UnimplementedError"}},ei=class extends Jt{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 ke;(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=()=>wr(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Gt((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 m=a.uint32();switch(m>>>3){case 1:{u.type=r.Type.codec().decode(a);break}case 2:{u.data=a.string();break}default:{a.skipType(m&7);break}}}return u},function*(a,c,f,u={}){let h=c==null?a.len:a.pos+c;for(;a.pos<h;){let m=a.uint32();switch(m>>>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(m&7);break}}}})),n);function o(a){return qt(a,r.codec())}r.encode=o;function s(a,c){return $t(a,r.codec(),c)}r.decode=s;function i(a,c){return jt(a,r.codec(),c)}r.stream=i})(ke||(ke={}));var ti=async(r,e,t)=>{try{let n=Promise.withResolvers();for(Vg(r,n);;){let o=await Promise.race([n.promise,e.read({signal:t.signal})]);if(o==null){t.signal?.throwIfAborted();break}if(o.type!==ke.Type.ICE_CANDIDATE)throw new ko("ICE candidate message expected");let s=JSON.parse(o.data??"null");if(s===""||s===null){t.onProgress?.(new ze("webrtc:end-of-ice-candidates")),t.log.trace("end-of-candidates received");continue}let i=new Ul(s);t.log.trace("%s received new ICE candidate %o",t.direction,s);try{t.onProgress?.(new ze("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 Vg(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 Oo(`RTCPeerConnection connection state became "${r.connectionState}"`));break;default:break}}}function ri(r){let e;for(let t of r.getComponents())t.name==="p2p"&&(e=Jr(t.value??""));if(e==null)throw new No("Remote peerId must be present in multiaddr");return e}async function Fl({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:m}=kl(s);o?.dialerEvents.increment({open:!0}),c.trace("dialing circuit address: %a",h);let p=i.getConnections(m),y;p.length===0?(u?.(new ze("webrtc:dial-relay")),y=await a.dial(h,{signal:n,onProgress:u})):(u?.(new ze("webrtc:reuse-relay-connection")),y=p[0]),u?.(new ze("webrtc:open-signaling-stream"));let x=await y.newStream(co,{signal:n,runOnLimitedConnection:!0}),l=zs(x).pb(ke),d=new Ys(r);d.addEventListener("connectionstatechange",()=>{d.connectionState==="closed"&&d.close()});let v=new Zt({peerConnection:d,dataChannelOptions:e,maxEarlyStreams:t,metrics:o?.dialerEvents,log:c});try{let L=d.createDataChannel("init");d.onicecandidate=({candidate:I})=>{if(d.connectionState==="connected"){c.trace("ignore new ice candidate as peer connection is already connected");return}if(I==null||I?.candidate===""){c.trace("initiator detected end of ICE candidates");return}let T=JSON.stringify(I?.toJSON()??null);c.trace("initiator sending ICE candidate %o",I),l.write({type:ke.Type.ICE_CANDIDATE,data:T},{signal:n}).catch(O=>{c.error("error sending ICE candidate - %e",O)})},d.onicecandidateerror=I=>{c.error("initiator ICE candidate error",I)};let R=await d.createOffer().catch(I=>{throw c.error("could not execute createOffer - %e",I),new Ge("Failed to set createOffer")});c.trace("initiator send SDP offer %s",R.sdp),u?.(new ze("webrtc:send-sdp-offer")),await l.write({type:ke.Type.SDP_OFFER,data:R.sdp},{signal:n}),await d.setLocalDescription(R).catch(I=>{throw c.error("could not execute setLocalDescription - %e",I),new Ge("Failed to set localDescription")}),u?.(new ze("webrtc:read-sdp-answer")),c.trace("initiator read SDP answer");let B=await l.read({signal:n});if(B.type!==ke.Type.SDP_ANSWER)throw new Ge("Remote should send an SDP answer");c.trace("initiator received SDP answer %s",B.data);let U=new Zs({type:"answer",sdp:B.data});return await d.setRemoteDescription(U).catch(I=>{throw c.error("could not execute setRemoteDescription - %e",I),new Ge("Failed to set remoteDescription")}),c.trace("initiator read candidates until connected"),u?.(new ze("webrtc:read-ice-candidates")),await ti(d,l,{direction:"initiator",signal:n,log:c,onProgress:u}),c.trace("initiator connected"),L.readyState!=="open"&&(c.trace("wait for init channel to open"),await Le(L,"open",{signal:n})),c.trace("closing init channel"),L.close(),c.trace("waiting for init channel to close"),await Le(L,"close",{signal:n}),u?.(new ze("webrtc:close-signaling-stream")),c.trace("closing signaling channel"),await x.close({signal:n}),c.trace("initiator connected to remote address %s",s),{remoteAddress:s,peerConnection:d,muxerFactory:v}}catch(L){throw c.error("outgoing signaling error - %e",L),v.close(),d.close(),x.abort(L),L}finally{d.onicecandidate=null,d.onicecandidateerror=null}}var Ml=oe(Sl.matchers[0],ne(290)),ni=class r extends Bt{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=>Ml.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=>Ml.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 Kl(r,e,{peerConnection:t,signal:n,log:o}){o.trace("new inbound signaling stream");let s=zs(r).pb(ke);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 m=JSON.stringify(h?.toJSON()??null);o.trace("recipient sending ICE candidate %s",m),s.write({type:ke.Type.ICE_CANDIDATE,data:m},{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!==ke.Type.SDP_OFFER)throw new Ge(`expected message type SDP_OFFER, received: ${c.type??"undefined"} `);o.trace("recipient received SDP offer %s",c.data);let f=new Zs({type:"offer",sdp:c.data});await t.setRemoteDescription(f).catch(h=>{throw o.error("could not execute setRemoteDescription - %e",h),new Ge("Failed to set remoteDescription")});let u=await t.createAnswer().catch(h=>{throw o.error("could not execute createAnswer - %e",h),new Ge("Failed to create answer")});o.trace("recipient send SDP answer %s",u.sdp),await s.write({type:ke.Type.SDP_ANSWER,data:u.sdp},{signal:n}),await t.setLocalDescription(u).catch(h=>{throw o.error("could not execute setLocalDescription - %e",h),new Ge("Failed to set localDescription")}),o.trace("recipient read candidates until connected"),await ti(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=ri(e.remoteAddr),a=nn(`/webrtc/p2p/${i}`);return o.trace("recipient connected to remote address %s",a),{remoteAddress:a,remotePeer:i}}var oi=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"})})}[Vo]=!0;[Symbol.toStringTag]="@libp2p/webrtc";[Pr]=["@libp2p/transport"];[tu]=["@libp2p/identify","@libp2p/circuit-relay-v2-transport"];isStarted(){return this._started}async start(){await this.components.registrar.handle(co,(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(co),this._started=!1}createListener(e){return new ni(this.components,{shutdownController:this.shutdownController})}listenFilter(e){return e.filter(Al.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 Fl({rtcConfiguration:await Wc(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=mo({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:ri(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 Ys(await Wc(this.init.rtcConfiguration));o.addEventListener("connectionstatechange",()=>{o.connectionState==="closed"&&o.close()});let s=new Zt({peerConnection:o,dataChannelOptions:this.init.dataChannel,maxEarlyStreams:this.init.maxEarlyStreams,metrics:this.metrics?.listenerEvents,log:this.log});try{let{remoteAddress:i,remotePeer:a}=await Kl(e,t,{peerConnection:o,signal:n,log:this.log});await e.close({signal:n});let c=mo({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 kl(r){let e=r.getComponents().filter(({name:n})=>n==="p2p").map(({value:n})=>n).pop();if(e==null)throw new $("Destination peer id was missing");return{circuitAddress:nn(r.getComponents().filter(({name:n})=>n!=="webrtc")),targetPeer:Jr(e)}}function ge(r=0){return new Uint8Array(r)}function Oe(r=0){return new Uint8Array(r)}var fn=!!globalThis.process?.env?.DUMP_SESSION_KEYS,Xc=16;function zg(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}function si(r){if(typeof r!="boolean")throw new TypeError(`boolean expected, not ${r}`)}function un(r){if(typeof r!="number")throw new TypeError("number expected, got "+typeof r);if(!Number.isSafeInteger(r)||r<0)throw new RangeError("positive integer expected, got "+r)}function ye(r,e,t=""){let n=zg(r),o=r?.length,s=e!==void 0;if(!n||s&&o!==e){let i=t&&`"${t}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof r}`,f=i+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(f):new TypeError(f)}return r}function Yc(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function Hl(r,e,t=!1){ye(r,void 0,"output");let n=e.outputLen;if(r.length<n)throw new RangeError("digestInto() expects output buffer of length at least "+n);if(t&&!hn(r))throw new Error("invalid output, must be aligned")}function ht(r){return new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4))}function rt(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function $g(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}var Cr=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68,qg=r=>r<<24&4278190080|r<<8&16711680|r>>>8&65280|r>>>24&255;var jg=r=>{for(let e=0;e<r.length;e++)r[e]=qg(r[e]);return r},It=Cr?r=>r:jg;function Vl(r,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(r,e)}function zl(r,e){if(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 $l(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 ql=(r,e)=>{function t(n,...o){if(ye(n,void 0,"key"),r.nonceLength!==void 0){let u=o[0];ye(u,r.varSizeNonce?void 0:r.nonceLength,"nonce")}let s=r.tagLength;s&&o[1]!==void 0&&ye(o[1],void 0,"AAD");let i=e(n,...o),a=(u,h)=>{if(h!==void 0){if(u!==2)throw new Error("cipher output not supported");ye(h,void 0,"output")}},c=!1;return{encrypt(u,h){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,ye(u),a(i.encrypt.length,h),i.encrypt(u,h)},decrypt(u,h){if(ye(u),s&&u.length<s)throw new Error('"ciphertext" expected length bigger than tagLength='+s);return a(i.decrypt.length,h),i.decrypt(u,h)}}}return Object.assign(t,r),t};function go(r,e,t=!0){if(e===void 0)return new Uint8Array(r);if(ye(e,void 0,"output"),e.length!==r)throw new Error('"output" expected Uint8Array of length '+r+", got: "+e.length);if(t&&!hn(e))throw new Error("invalid output, must be aligned");return e}function jl(r,e,t){un(r),un(e),si(t);let n=new Uint8Array(16),o=$g(n);return o.setBigUint64(0,BigInt(e),t),o.setBigUint64(8,BigInt(r),t),n}function hn(r){return r.byteOffset%4===0}function ln(r){return Uint8Array.from(ye(r))}var Wl=r=>Uint8Array.from(r.split(""),e=>e.charCodeAt(0)),Gg=It(ht(Wl("expand 16-byte k"))),Wg=It(ht(Wl("expand 32-byte k")));function q(r,e){return r<<e|r>>>32-e}var yo=64,Xg=16,Zc=2**32-1,Gl=Uint32Array.of();function Yg(r,e,t,n,o,s,i,a){let c=o.length,f=new Uint8Array(yo),u=ht(f),h=Cr&&hn(o)&&hn(s),m=h?ht(o):Gl,p=h?ht(s):Gl;if(!Cr){for(let y=0;y<c;i++){if(r(e,t,n,u,i,a),It(u),i>=Zc)throw new Error("arx: counter overflow");let x=Math.min(yo,c-y);for(let l=0,d;l<x;l++)d=y+l,s[d]=o[d]^f[l];y+=x}return}for(let y=0;y<c;i++){if(r(e,t,n,u,i,a),i>=Zc)throw new Error("arx: counter overflow");let x=Math.min(yo,c-y);if(h&&x===yo){let l=y/4;if(y%4!==0)throw new Error("arx: invalid block position");for(let d=0,v;d<Xg;d++)v=l+d,p[v]=m[v]^u[d];y+=yo;continue}for(let l=0,d;l<x;l++)d=y+l,s[d]=o[d]^f[l];y+=x}}function Xl(r,e){let{allowShortKeys:t,extendNonceFn:n,counterLength:o,counterRight:s,rounds:i}=Vl({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof r!="function")throw new Error("core must be a function");return un(o),un(i),si(s),si(t),(a,c,f,u,h=0)=>{ye(a,void 0,"key"),ye(c,void 0,"nonce"),ye(f,void 0,"data");let m=f.length;if(u=go(m,u,!1),un(h),h<0||h>=Zc)throw new Error("arx: counter overflow");let p=[],y=a.length,x,l;if(y===32)p.push(x=ln(a)),l=Wg;else if(y===16&&t)x=new Uint8Array(32),x.set(a),x.set(a,16),l=Gg,p.push(x);else throw ye(a,32,"arx key"),new Error("invalid key size");(!Cr||!hn(c))&&p.push(c=ln(c));let d=ht(x);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");let R=c.subarray(0,16);if(Cr)n(l,d,ht(R),d);else{let B=It(Uint32Array.from(l));n(B,d,ht(R),d),rt(B),It(d)}c=c.subarray(16)}else Cr||It(d);let v=16-o;if(v!==c.length)throw new Error(`arx: nonce must be ${v} or 16 bytes`);if(v!==12){let R=new Uint8Array(12);R.set(c,s?0:12-c.length),c=R,p.push(c)}let L=It(ht(c));try{return Yg(r,l,d,L,f,u,h,i),u}finally{rt(...p)}}}function _e(r,e){return r[e++]&255|(r[e++]&255)<<8}var Jc=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=ln(ye(e,32,"key"));let t=_e(e,0),n=_e(e,2),o=_e(e,4),s=_e(e,6),i=_e(e,8),a=_e(e,10),c=_e(e,12),f=_e(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]=_e(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],m=i[5],p=i[6],y=i[7],x=i[8],l=i[9],d=_e(e,t+0),v=_e(e,t+2),L=_e(e,t+4),R=_e(e,t+6),B=_e(e,t+8),U=_e(e,t+10),I=_e(e,t+12),T=_e(e,t+14),O=s[0]+(d&8191),F=s[1]+((d>>>13|v<<3)&8191),N=s[2]+((v>>>10|L<<6)&8191),g=s[3]+((L>>>7|R<<9)&8191),A=s[4]+((R>>>4|B<<12)&8191),S=s[5]+(B>>>1&8191),w=s[6]+((B>>>14|U<<2)&8191),b=s[7]+((U>>>11|I<<5)&8191),C=s[8]+((I>>>8|T<<8)&8191),_=s[9]+(T>>>5|o),E=0,D=E+O*a+F*(5*l)+N*(5*x)+g*(5*y)+A*(5*p);E=D>>>13,D&=8191,D+=S*(5*m)+w*(5*h)+b*(5*u)+C*(5*f)+_*(5*c),E+=D>>>13,D&=8191;let P=E+O*c+F*a+N*(5*l)+g*(5*x)+A*(5*y);E=P>>>13,P&=8191,P+=S*(5*p)+w*(5*m)+b*(5*h)+C*(5*u)+_*(5*f),E+=P>>>13,P&=8191;let k=E+O*f+F*c+N*a+g*(5*l)+A*(5*x);E=k>>>13,k&=8191,k+=S*(5*y)+w*(5*p)+b*(5*m)+C*(5*h)+_*(5*u),E+=k>>>13,k&=8191;let H=E+O*u+F*f+N*c+g*a+A*(5*l);E=H>>>13,H&=8191,H+=S*(5*x)+w*(5*y)+b*(5*p)+C*(5*m)+_*(5*h),E+=H>>>13,H&=8191;let K=E+O*h+F*u+N*f+g*c+A*a;E=K>>>13,K&=8191,K+=S*(5*l)+w*(5*x)+b*(5*y)+C*(5*p)+_*(5*m),E+=K>>>13,K&=8191;let Q=E+O*m+F*h+N*u+g*f+A*c;E=Q>>>13,Q&=8191,Q+=S*a+w*(5*l)+b*(5*x)+C*(5*y)+_*(5*p),E+=Q>>>13,Q&=8191;let ee=E+O*p+F*m+N*h+g*u+A*f;E=ee>>>13,ee&=8191,ee+=S*c+w*a+b*(5*l)+C*(5*x)+_*(5*y),E+=ee>>>13,ee&=8191;let te=E+O*y+F*p+N*m+g*h+A*u;E=te>>>13,te&=8191,te+=S*f+w*c+b*a+C*(5*l)+_*(5*x),E+=te>>>13,te&=8191;let j=E+O*x+F*y+N*p+g*m+A*h;E=j>>>13,j&=8191,j+=S*u+w*f+b*c+C*a+_*(5*l),E+=j>>>13,j&=8191;let ae=E+O*l+F*x+N*y+g*p+A*m;E=ae>>>13,ae&=8191,ae+=S*h+w*u+b*f+C*c+_*a,E+=ae>>>13,ae&=8191,E=(E<<2)+E|0,E=E+D|0,D=E&8191,E=E>>>13,P+=E,s[0]=D,s[1]=P,s[2]=k,s[3]=H,s[4]=K,s[5]=Q,s[6]=ee,s[7]=te,s[8]=j,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;rt(n)}update(e){Yc(this),ye(e),e=ln(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,rt(this.h,this.r,this.buffer,this.pad)}digestInto(e){Yc(this),Hl(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}},Yl=$l(32,r=>new Jc(r));function Zg(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],m=e[2],p=e[3],y=e[4],x=e[5],l=e[6],d=e[7],v=o,L=t[0],R=t[1],B=t[2],U=i,I=a,T=c,O=f,F=u,N=h,g=m,A=p,S=y,w=x,b=l,C=d,_=v,E=L,D=R,P=B;for(let H=0;H<s;H+=2)U=U+F|0,_=q(_^U,16),S=S+_|0,F=q(F^S,12),U=U+F|0,_=q(_^U,8),S=S+_|0,F=q(F^S,7),I=I+N|0,E=q(E^I,16),w=w+E|0,N=q(N^w,12),I=I+N|0,E=q(E^I,8),w=w+E|0,N=q(N^w,7),T=T+g|0,D=q(D^T,16),b=b+D|0,g=q(g^b,12),T=T+g|0,D=q(D^T,8),b=b+D|0,g=q(g^b,7),O=O+A|0,P=q(P^O,16),C=C+P|0,A=q(A^C,12),O=O+A|0,P=q(P^O,8),C=C+P|0,A=q(A^C,7),U=U+N|0,P=q(P^U,16),b=b+P|0,N=q(N^b,12),U=U+N|0,P=q(P^U,8),b=b+P|0,N=q(N^b,7),I=I+g|0,_=q(_^I,16),C=C+_|0,g=q(g^C,12),I=I+g|0,_=q(_^I,8),C=C+_|0,g=q(g^C,7),T=T+A|0,E=q(E^T,16),S=S+E|0,A=q(A^S,12),T=T+A|0,E=q(E^T,8),S=S+E|0,A=q(A^S,7),O=O+F|0,D=q(D^O,16),w=w+D|0,F=q(F^w,12),O=O+F|0,D=q(D^O,8),w=w+D|0,F=q(F^w,7);let k=0;n[k++]=i+U|0,n[k++]=a+I|0,n[k++]=c+T|0,n[k++]=f+O|0,n[k++]=u+F|0,n[k++]=h+N|0,n[k++]=m+g|0,n[k++]=p+A|0,n[k++]=y+S|0,n[k++]=x+w|0,n[k++]=l+b|0,n[k++]=d+C|0,n[k++]=v+_|0,n[k++]=L+E|0,n[k++]=R+D|0,n[k++]=B+P|0}var Jg=Xl(Zg,{counterRight:!1,counterLength:4,allowShortKeys:!1});var Qg=new Uint8Array(16),Zl=(r,e)=>{r.update(e);let t=e.length%16;t&&r.update(Qg.subarray(t))},ey=new Uint8Array(32);function Jl(r,e,t,n,o){o!==void 0&&ye(o,void 0,"AAD");let s=r(e,t,ey),i=jl(n.length,o?o.length:0,!0),a=Yl.create(s);o&&Zl(a,o),Zl(a,n),a.update(i);let c=a.digest();return rt(s,i),c}var ty=r=>(e,t,n)=>({encrypt(s,i){let a=s.length;i=go(a+16,i,!1),i.set(s);let c=i.subarray(0,-16);r(e,t,c,c,1);let f=Jl(r,e,t,c,n);return i.set(f,a),rt(f),i},decrypt(s,i){i=go(s.length-16,i,!1);let a=s.subarray(0,-16),c=s.subarray(-16),f=Jl(r,e,t,a,n);if(!zl(c,f))throw rt(f),new Error("invalid tag");return i.set(s.subarray(0,-16)),r(e,t,i,i,1),rt(f),i}}),Qc=ql({blockSize:64,nonceLength:12,tagLength:16},ty(Jg));function ed(r,e,t){return ar(r),t===void 0&&(t=new Uint8Array(r.outputLen)),Qn(r,t,e)}var ef=Uint8Array.of(0),Ql=Uint8Array.of();function td(r,e,t,n=32){ar(r),it(n,"length"),Ie(e,void 0,"prk");let o=r.outputLen;if(e.length<o)throw new Error('"prk" must be at least HashLen octets');if(n>255*o)throw new Error("Length must be <= 255*HashLen");let s=Math.ceil(n/o);t===void 0?t=Ql:Ie(t,void 0,"info");let i=new Uint8Array(s*o),a=Qn.create(r,e),c=a._cloneInto(),f=new Uint8Array(a.outputLen);for(let u=0;u<s;u++)ef[0]=u+1,c.update(u===0?Ql:f).update(t).update(ef).digestInto(f),i.set(f,o*u),a._cloneInto(c);return a.destroy(),c.destroy(),Ye(f,ef),i.slice(0,n)}var tf={hashSHA256(r){return ct(r.subarray())},getHKDF(r,e){let t=ed(ct,e,r),o=td(ct,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=qn.utils.randomSecretKey();return{publicKey:qn.getPublicKey(r),privateKey:r}},generateX25519KeyPairFromSeed(r){return{publicKey:qn.getPublicKey(r),privateKey:r}},generateX25519SharedKey(r,e){return qn.getSharedSecret(r.subarray(),e.subarray())},chaCha20Poly1305Encrypt(r,e,t,n){return Qc(n,e,t).encrypt(r.subarray())},chaCha20Poly1305Decrypt(r,e,t,n,o){return Qc(n,e,t).decrypt(r.subarray(),o)}};var rd=tf;function nd(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 dn=r=>{let e=Oe(2);return e[0]=r>>8,e[1]=r,e};dn.bytes=2;var pn=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)};pn.bytes=2;function od(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 af={};re(af,{base10:()=>cy});var Zv=new Uint8Array(0);function sd(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 Tt(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 id(r){return new TextEncoder().encode(r)}function ad(r){return new TextDecoder().decode(r)}function ry(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(y){if(y instanceof Uint8Array||(ArrayBuffer.isView(y)?y=new Uint8Array(y.buffer,y.byteOffset,y.byteLength):Array.isArray(y)&&(y=Uint8Array.from(y))),!(y instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(y.length===0)return"";for(var x=0,l=0,d=0,v=y.length;d!==v&&y[d]===0;)d++,x++;for(var L=(v-d)*u+1>>>0,R=new Uint8Array(L);d!==v;){for(var B=y[d],U=0,I=L-1;(B!==0||U<l)&&I!==-1;I--,U++)B+=256*R[I]>>>0,R[I]=B%a>>>0,B=B/a>>>0;if(B!==0)throw new Error("Non-zero carry");l=U,d++}for(var T=L-l;T!==L&&R[T]===0;)T++;for(var O=c.repeat(x);T<L;++T)O+=r.charAt(R[T]);return O}function m(y){if(typeof y!="string")throw new TypeError("Expected String");if(y.length===0)return new Uint8Array;var x=0;if(y[x]!==" "){for(var l=0,d=0;y[x]===c;)l++,x++;for(var v=(y.length-x)*f+1>>>0,L=new Uint8Array(v);y[x];){var R=t[y.charCodeAt(x)];if(R===255)return;for(var B=0,U=v-1;(R!==0||B<d)&&U!==-1;U--,B++)R+=a*L[U]>>>0,L[U]=R%256>>>0,R=R/256>>>0;if(R!==0)throw new Error("Non-zero carry");d=B,x++}if(y[x]!==" "){for(var I=v-d;I!==v&&L[I]===0;)I++;for(var T=new Uint8Array(l+(v-I)),O=l;I!==v;)T[O++]=L[I++];return T}}}function p(y){var x=m(y);if(x)return x;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:m,decode:p}}var ny=ry,oy=ny,fd=oy;var rf=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")}},nf=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 ud(this,e)}},of=class{decoders;constructor(e){this.decoders=e}or(e){return ud(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 ud(r,e){return new of({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var sf=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 rf(e,t,n),this.decoder=new nf(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function mn({name:r,prefix:e,encode:t,decode:n}){return new sf(r,e,t,n)}function Qt({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=fd(t,r);return mn({prefix:e,name:r,encode:n,decode:s=>Tt(o(s))})}function sy(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 iy(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 ay(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function de({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=ay(n);return mn({prefix:e,name:r,encode(s){return iy(s,n,t)},decode(s){return sy(s,o,t,r)}})}var cy=Qt({prefix:"9",name:"base10",alphabet:"0123456789"});var cf={};re(cf,{base16:()=>fy,base16upper:()=>uy});var fy=de({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),uy=de({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var ff={};re(ff,{base2:()=>hy});var hy=de({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var uf={};re(uf,{base256emoji:()=>gy});var hd=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}"),ly=hd.reduce((r,e,t)=>(r[t]=e,r),[]),dy=hd.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+=ly[t],e),"")}function my(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=dy[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var gy=mn({prefix:"\u{1F680}",name:"base256emoji",encode:py,decode:my});var hf={};re(hf,{base32:()=>gn,base32hex:()=>xy,base32hexpad:()=>Sy,base32hexpadupper:()=>Ay,base32hexupper:()=>Ey,base32pad:()=>by,base32padupper:()=>wy,base32upper:()=>yy,base32z:()=>vy});var gn=de({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),yy=de({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),by=de({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),wy=de({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),xy=de({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Ey=de({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Sy=de({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Ay=de({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),vy=de({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var lf={};re(lf,{base36:()=>bo,base36upper:()=>Cy});var bo=Qt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Cy=Qt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var df={};re(df,{base58btc:()=>lt,base58flickr:()=>Ly});var lt=Qt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Ly=Qt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var pf={};re(pf,{base64:()=>_y,base64pad:()=>Iy,base64url:()=>Ty,base64urlpad:()=>By});var _y=de({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Iy=de({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ty=de({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),By=de({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var mf={};re(mf,{base8:()=>Dy});var Dy=de({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var gf={};re(gf,{identity:()=>Ry});var Ry=mn({prefix:"\0",name:"identity",encode:r=>ad(r),decode:r=>id(r)});var d4=new TextEncoder,p4=new TextDecoder;var bf={};re(bf,{identity:()=>tb});var Ny=pd,ld=128,Uy=127,Fy=~Uy,ky=Math.pow(2,31);function pd(r,e,t){e=e||[],t=t||0;for(var n=t;r>=ky;)e[t++]=r&255|ld,r/=128;for(;r&Fy;)e[t++]=r&255|ld,r>>>=7;return e[t]=r|0,pd.bytes=t-n+1,e}var My=yf,Ky=128,dd=127;function yf(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw yf.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&dd)<<o:(i&dd)*Math.pow(2,o),o+=7}while(i>=Ky);return yf.bytes=s-n,t}var Hy=Math.pow(2,7),Vy=Math.pow(2,14),zy=Math.pow(2,21),$y=Math.pow(2,28),qy=Math.pow(2,35),jy=Math.pow(2,42),Gy=Math.pow(2,49),Wy=Math.pow(2,56),Xy=Math.pow(2,63),Yy=function(r){return r<Hy?1:r<Vy?2:r<zy?3:r<$y?4:r<qy?5:r<jy?6:r<Gy?7:r<Wy?8:r<Xy?9:10},Zy={encode:Ny,decode:My,encodingLength:Yy},Jy=Zy,wo=Jy;function xo(r,e=0){return[wo.decode(r,e),wo.decode.bytes]}function yn(r,e,t=0){return wo.encode(r,e,t),e}function bn(r){return wo.encodingLength(r)}function xn(r,e){let t=e.byteLength,n=bn(r),o=n+bn(t),s=new Uint8Array(o+t);return yn(r,s,0),yn(t,s,n),s.set(e,o),new wn(r,t,e,s)}function md(r){let e=Tt(r),[t,n]=xo(e),[o,s]=xo(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new wn(t,o,i,e)}function gd(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&sd(r.bytes,t.bytes)}}var wn=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var yd=0,Qy="identity",bd=Tt;function eb(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 xn(yd,bd(r))}var tb={code:yd,name:Qy,encode:bd,digest:eb};var Ef={};re(Ef,{sha256:()=>nb,sha512:()=>ob});var rb=20;function xf({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new wf(r,e,t,n,o)}var wf=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??rb,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?wd(n,this.code,t?.truncate):n.then(o=>wd(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function wd(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 xn(e,r)}function Ed(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var nb=xf({name:"sha2-256",code:18,encode:Ed("SHA-256")}),ob=xf({name:"sha2-512",code:19,encode:Ed("SHA-512")});function Sd(r,e){let{bytes:t,version:n}=r;return n===0?ib(t,Sf(r),e??lt.encoder):ab(t,Sf(r),e??gn.encoder)}var Ad=new WeakMap;function Sf(r){let e=Ad.get(r);if(e==null){let t=new Map;return Ad.set(r,t),t}return e}var ai=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!==So)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==cb)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=xn(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&&gd(e.multihash,n.multihash)}toString(e){return Sd(this,e)}toJSON(){return{"/":Sd(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??vd(n,o,s.bytes))}else if(t[fb]===!0){let{version:n,multihash:o,code:s}=t,i=md(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!==So)throw new Error(`Version 0 CID must use dag-pb (code: ${So}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=vd(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,So,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=Tt(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 wn(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,m]=xo(e.subarray(t));return t+=m,h},o=n(),s=So;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]=sb(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 Sf(s).set(n,e),s}};function sb(r,e){switch(r[0]){case"Q":{let t=e??lt;return[lt.prefix,t.decode(`${lt.prefix}${r}`)]}case lt.prefix:{let t=e??lt;return[lt.prefix,t.decode(r)]}case gn.prefix:{let t=e??gn;return[gn.prefix,t.decode(r)]}case bo.prefix:{let t=e??bo;return[bo.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 ib(r,e,t){let{prefix:n}=t;if(n!==lt.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 ab(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 So=112,cb=18;function vd(r,e,t){let n=bn(r),o=n+bn(e),s=new Uint8Array(o+t.byteLength);return yn(r,s,0),yn(e,s,n),s.set(t,o),s}var fb=Symbol.for("@ipld/js-cid/CID");var Af={...gf,...ff,...mf,...af,...cf,...hf,...lf,...df,...pf,...uf},U4={...Ef,...bf};function Ld(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Cd=Ld("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),vf=Ld("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=Oe(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),ub={utf8:Cd,"utf-8":Cd,hex:Af.base16,latin1:vf,ascii:vf,binary:vf,...Af},ci=ub;function dt(r,e="utf8"){let t=ci[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}function Cf(r,e){!e.enabled||!fn||(r?(e(`LOCAL_STATIC_PUBLIC_KEY ${dt(r.publicKey,"hex")}`),e(`LOCAL_STATIC_PRIVATE_KEY ${dt(r.privateKey,"hex")}`)):e("Missing local static keys."))}function Lf(r,e){!e.enabled||!fn||(r?(e(`LOCAL_PUBLIC_EPHEMERAL_KEY ${dt(r.publicKey,"hex")}`),e(`LOCAL_PRIVATE_EPHEMERAL_KEY ${dt(r.privateKey,"hex")}`)):e("Missing local ephemeral keys."))}function _d(r,e){!e.enabled||!fn||e(r?`REMOTE_STATIC_PUBLIC_KEY ${dt(r.subarray(),"hex")}`:"Missing remote static public key.")}function _f(r,e){!e.enabled||!fn||e(r?`REMOTE_EPHEMERAL_PUBLIC_KEY ${dt(r.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function If(r,e,t){!t.enabled||!fn||(t(`CIPHER_STATE_1 ${r.n.getUint64()} ${r.k&&dt(r.k,"hex")}`),t(`CIPHER_STATE_2 ${e.n.getUint64()} ${e.k&&dt(e.k,"hex")}`))}function En(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=Oe(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}function Tf(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 Td=Symbol.for("@achingbrain/uint8arraylist");function Id(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 fi(r){return!!r?.[Td]}var pt=class r{bufs;length;[Td]=!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(fi(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(fi(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=Id(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Id(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(fi(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 En(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:En(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(!fi(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 m=f;m>=0;m--){let p=this.get(h+m);if(n[m]!==p){u=Math.max(1,m-a[p]);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=Oe(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=ge(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=ge(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=ge(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=Oe(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=ge(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=ge(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=ge(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=ge(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=ge(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(!Tf(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=ci[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}var Sn=class r extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=r.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};var lb=0,db=4294967295,pb="Cipherstate has reached maximum n, a new handshake must be performed",ui=class{n;bytes;view;constructor(e=lb){this.n=e,this.bytes=ge(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>db)throw new Error(pb)}};var _r=ge(0),An=class{k;n;crypto;constructor(e,t=void 0,n=0){this.crypto=e,this.k=t,this.n=new ui(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}},Bf=class{cs;ck;h;crypto;constructor(e,t){this.crypto=e;let n=Lr(t,"utf-8");this.h=mb(e,n),this.ck=this.h,this.cs=new An(e)}mixKey(e){let[t,n]=this.crypto.hkdf(this.ck,e);this.ck=t,this.cs=new An(this.crypto,n)}mixHash(e){this.h=this.crypto.hash(new pt(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,_r);return[new An(this.crypto,e),new An(this.crypto,t)]}},Df=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 Bf(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()}},Ao=class extends Df{writeMessageA(e){return new pt(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){let t=this.writeE();this.writeEE();let n=this.writeS();return this.writeES(),new pt(t,n,this.ss.encryptAndHash(e))}writeMessageC(e){let t=this.writeS();return this.writeSE(),new pt(t,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(t){throw new Sn(`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 Sn(`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 Sn(`handshake stage 2 validation fail: ${t.message}`)}}};function mb(r,e){if(e.length<=32){let t=ge(32);return t.set(e),t}else return r.hash(e)}var gb=Math.pow(2,7),yb=Math.pow(2,14),bb=Math.pow(2,21),Bd=Math.pow(2,28),Dd=Math.pow(2,35),Rd=Math.pow(2,42),Od=Math.pow(2,49),Ue=128,er=127;function vo(r){if(r<gb)return 1;if(r<yb)return 2;if(r<bb)return 3;if(r<Bd)return 4;if(r<Dd)return 5;if(r<Rd)return 6;if(r<Od)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Pd(r,e,t=0){switch(vo(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 Nd(r,e){let t=r[e],n=0;if(n+=t&er,t<Ue||(t=r[e+1],n+=(t&er)<<7,t<Ue)||(t=r[e+2],n+=(t&er)<<14,t<Ue)||(t=r[e+3],n+=(t&er)<<21,t<Ue)||(t=r[e+4],n+=(t&er)*Bd,t<Ue)||(t=r[e+5],n+=(t&er)*Dd,t<Ue)||(t=r[e+6],n+=(t&er)*Rd,t<Ue)||(t=r[e+7],n+=(t&er)*Od,t<Ue))return n;throw new RangeError("Could not decode varint")}var Rf=new Float32Array([-0]),tr=new Uint8Array(Rf.buffer);function Ud(r,e,t){Rf[0]=r,e[t]=tr[0],e[t+1]=tr[1],e[t+2]=tr[2],e[t+3]=tr[3]}function Fd(r,e){return tr[0]=r[e],tr[1]=r[e+1],tr[2]=r[e+2],tr[3]=r[e+3],Rf[0]}var Of=new Float64Array([-0]),Pe=new Uint8Array(Of.buffer);function kd(r,e,t){Of[0]=r,e[t]=Pe[0],e[t+1]=Pe[1],e[t+2]=Pe[2],e[t+3]=Pe[3],e[t+4]=Pe[4],e[t+5]=Pe[5],e[t+6]=Pe[6],e[t+7]=Pe[7]}function Md(r,e){return Pe[0]=r[e],Pe[1]=r[e+1],Pe[2]=r[e+2],Pe[3]=r[e+3],Pe[4]=r[e+4],Pe[5]=r[e+5],Pe[6]=r[e+6],Pe[7]=r[e+7],Of[0]}var wb=BigInt(Number.MAX_SAFE_INTEGER),xb=BigInt(Number.MIN_SAFE_INTEGER),$e=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 Ir;if(e<wb&&e>xb)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>Kd&&(o=0n,++n>Kd&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return Ir;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):Ir}},Ir=new $e(0,0);Ir.toBigInt=function(){return 0n};Ir.zzEncode=Ir.zzDecode=function(){return this};Ir.length=function(){return 1};var Kd=4294967296n;function Hd(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 Vd(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 Pf(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 nt(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function hi(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var Nf=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,nt(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 nt(this,4);return hi(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw nt(this,4);return hi(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw nt(this,4);let e=Fd(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw nt(this,4);let e=Md(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 nt(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Vd(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw nt(this,e);this.pos+=e}else do if(this.pos>=this.len)throw nt(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),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 nt(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 nt(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 nt(this,8);let e=hi(this.buf,this.pos+=4),t=hi(this.buf,this.pos+=4);return new $e(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=Nd(this.buf,this.pos);return this.pos+=vo(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 Uf(r){return new Nf(r instanceof Uint8Array?r:r.subarray())}function li(r,e,t){let n=Uf(r);return e.decode(n,void 0,t)}function Ff(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return Oe(i);o+i>e&&(n=Oe(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var Tr=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 Kf=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},Eb=Ff();function Sb(r){return globalThis.Buffer!=null?Oe(r):Eb(r)}var Lo=class{len;head;tail;states;constructor(){this.len=0,this.head=new Tr(kf,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new Tr(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Hf((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(di,10,$e.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=$e.fromBigInt(e);return this._push(di,t.length(),t)}uint64Number(e){return this._push(Pd,vo(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=$e.fromBigInt(e).zzEncode();return this._push(di,t.length(),t)}sint64Number(e){let t=$e.fromNumber(e).zzEncode();return this._push(di,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Mf,1,e?1:0)}fixed32(e){return this._push(Co,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=$e.fromBigInt(e);return this._push(Co,4,t.lo)._push(Co,4,t.hi)}fixed64Number(e){let t=$e.fromNumber(e);return this._push(Co,4,t.lo)._push(Co,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(Ud,4,e)}double(e){return this._push(kd,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(Mf,1,0):this.uint32(t)._push(vb,t,e)}string(e){let t=Hd(e);return t!==0?this.uint32(t)._push(Pf,t,e):this._push(Mf,1,0)}fork(){return this.states=new Kf(this),this.head=this.tail=new Tr(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 Tr(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=Sb(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function Mf(r,e,t){e[t]=r&255}function Ab(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var Hf=class extends Tr{next;constructor(e,t){super(Ab,e,t),this.next=void 0}};function di(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 Co(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&&(Lo.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(Cb,e,r),this},Lo.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(Lb,e,r),this});function Cb(r,e,t){e.set(r,t)}function Lb(r,e,t){r.length<40?Pf(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(Lr(r),t)}function Vf(){return new Lo}function pi(r,e){let t=Vf();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var _o;(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"})(_o||(_o={}));function zf(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function mi(r,e){return zf("message",_o.LENGTH_DELIMITED,r,e)}var Io=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var gi;(function(r){let e;r.codec=()=>(e==null&&(e=mi((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 Io('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 Io('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=>pi(t,r.codec()),r.decode=(t,n)=>li(t,r.codec(),n)})(gi||(gi={}));var To;(function(r){let e;r.codec=()=>(e==null&&(e=mi((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),gi.codec().encode(t.extensions,n)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={identityKey:ge(0),identitySig:ge(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=gi.codec().decode(t,t.uint32(),{limits:o.limits?.extensions});break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>pi(t,r.codec()),r.decode=(t,n)=>li(t,r.codec(),n)})(To||(To={}));async function qf(r,e,t){let n=await r.sign(qd(e));return To.encode({identityKey:Pt(r.publicKey),identitySig:n,extensions:t})}async function jf(r,e,t){try{let n=To.decode(r),o=eo(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=qd(e);if(!await o.verify(s,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new Do(n.message)}}function qd(r){let e=Lr("noise-libp2p-static-key:");return r instanceof Uint8Array?En([e,r],e.length+r.length):(r.prepend(e),r)}var $f=class extends Yt{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 $s({lengthDecoder:pn,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 pt;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(dn(s.byteLength)),t.append(s)}return t}decrypt(e){let t=new pt;for(let n=0;n<e.byteLength;n+=65535){let o=n+65535;if(o>e.byteLength&&(o=e.byteLength),o-Xc<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-Xc);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 Gf(r,e,t){return new $f(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 qf(s,a.publicKey,f),h=new Ao({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});Cf(h.s,t),t.trace("Stage 0 - Initiator starting to send first message."),await n.write(h.writeMessageA(_r),e),t.trace("Stage 0 - Initiator finished sending first message."),Lf(h.e,t),t.trace("Stage 1 - Initiator waiting to receive first message from responder...");let m=h.readMessageB(await n.read(e));t.trace("Stage 1 - Initiator received the message."),_f(h.re,t),_d(h.rs,t),t.trace("Initiator going to check remote's signature...");let p=await jf(m,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[y,x]=h.ss.split();return If(y,x,t),{payload:p,encrypt:l=>y.encryptWithAd(_r,l),decrypt:(l,d)=>x.decryptWithAd(_r,l,d)}}async function Gd(r,e){let{log:t,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:f}=r,u=await qf(s,a.publicKey,f),h=new Ao({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});Cf(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."),_f(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."),Lf(h.e,t),t.trace("Stage 2 - Responder waiting for third handshake message...");let m=h.readMessageC(await n.read(e));t.trace("Stage 2 - Responder received the message, finished handshake.");let p=await jf(m,h.rs,c),[y,x]=h.ss.split();return If(y,x,t),{payload:p,encrypt:l=>x.encryptWithAd(_r,l),decrypt:(l,d)=>y.decryptWithAd(_r,l,d)}}var yi=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??rd;this.crypto=nd(c),this.extensions={webtransportCerthashes:[],...o},this.metrics=a?od(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??ge(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=Vs(e,{lengthEncoder:dn,lengthDecoder:pn,maxDataLength:65535}),s=await this.performHandshakeInitiator(o,this.components.privateKey,n,t?.remotePeer?.publicKey,t),i=eo(s.payload.identityKey);return{connection:Gf(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:oc(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 Ro("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=Vs(e,{lengthEncoder:dn,lengthDecoder:pn,maxDataLength:65535}),s=await this.performHandshakeResponder(o,this.components.privateKey,n,t?.remotePeer?.publicKey,t),i=eo(s.payload.identityKey);return{connection:Gf(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:oc(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 Gd({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 Wd(r={}){return e=>new yi(e,r)}var Wf=Object.values(ir).map(r=>r.decoder).reduce((r,e)=>r.or(e)),_b=/^a=fingerprint:(?:\w+-[0-9]+)\s(?<fingerprint>(:?[0-9a-fA-F]{2})+)$/m;function Xd(r){return r?.match(_b)?.groups?.fingerprint}function Xf(r){let t=r.getComponents().find(n=>n.code===466)?.value;if(t===void 0||t==="")throw new $(`Couldn't find a certhash component of multiaddr: ${r.toString()}`);return t}function Ib(r){return We.decode(Wf.decode(r))}function Tb(r){let e=Ib(Xf(r)),t=Bb(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 Js(n,r.toString());return`${t} ${o.join(":").toUpperCase()}`}function Yd(r){let e=r.split(":").map(o=>parseInt(o,16)),t=Uint8Array.from(e),n=Ne(gt.code,t);return nn(`/certhash/${Dn.encode(n.bytes)}`)}function Bb(r){switch(r){case 17:return"sha-1";case 18:return"sha-256";case 19:return"sha-512";default:throw new ei(r)}}function Zd(r,e){let{host:t,port:n,type:o}=Nc(r);if(o!=="ip4"&&o!=="ip6")throw new $(`Multiaddr ${r} was not an IPv4 or IPv6 address`);let s=Tb(r);return{type:"answer",sdp:`v=0
3
3
  o=- 0 0 IN IP${o==="ip4"?4:6} ${t}
4
4
  s=-
5
5
  t=0 0
@@ -13,10 +13,10 @@ 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:${on}
16
+ a=max-message-size:${Sr}
17
17
  a=candidate:1467250027 1 UDP 1467250027 ${t} ${n} typ host
18
18
  a=end-of-candidates
19
- `}}function Gd(r,e){let{host:t,port:n,type:o}=Uc(r);if(o!=="ip4"&&o!=="ip6")throw new $(`Multiaddr ${r} was not an IPv4 or IPv6 address`);return{type:"offer",sdp:`v=0
19
+ `}}function Jd(r,e){let{host:t,port:n,type:o}=Nc(r);if(o!=="ip4"&&o!=="ip6")throw new $(`Multiaddr ${r} was not an IPv4 or IPv6 address`);return{type:"offer",sdp:`v=0
20
20
  o=- 0 0 IN IP${o==="ip4"?4:6} ${t}
21
21
  s=-
22
22
  c=IN IP${o==="ip4"?4:6} ${t}
@@ -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:${on}
32
+ a=max-message-size:${Sr}
33
33
  a=candidate:1467250027 1 UDP 1467250027 ${t} ${n} typ host
34
34
  a=end-of-candidates
35
- `}}function Wf(r,e){if(r.sdp===void 0)throw new $("Can't munge a missing SDP");let t=r.sdp.includes(`\r
35
+ `}}function Yf(r,e){if(r.sdp===void 0)throw new $("Can't munge a missing SDP");let t=r.sdp.includes(`\r
36
36
  `)?`\r
37
37
  `:`
38
38
  `;try{r.sdp=r.sdp.replace(/\na=ice-ufrag:[^\n]*\n/,`
39
39
  a=ice-ufrag:`+e+t).replace(/\na=ice-pwd:[^\n]*\n/,`
40
- a=ice-pwd:`+e+t)}catch{}return r}var Xf=Y("libp2p-webrtc-noise:");function Xd(r,e,t){let n=r.trim().toLowerCase().replaceAll(":",""),o=Y(n,"hex"),s=Ue(gt.code,o),i=jf.decode(Gf(e)),a=Xf.byteLength+s.bytes.byteLength+i.byteLength;return t==="server"?Me([Xf,i,s.bytes],a):Me([Xf,s.bytes,i],a)}function Lb(r,e){return r.role==="server"}async function Yd(r,e,t,n){let o=r.createDataChannel("",{negotiated:!0,id:0});try{if(n.role==="client"){n.log.trace("client creating local offer");let h=await r.createOffer();n.log.trace("client created local offer %s",h.sdp);let p=Wf(h,t);n.log.trace("client setting local offer %s",p.sdp),await r.setLocalDescription(p);let d=jd(n.remoteAddr,t);n.log.trace("client setting server description %s",d.sdp),await r.setRemoteDescription(d)}else{let h=Gd(n.remoteAddr,t);n.log.trace("server setting client %s %s",h.type,h.sdp),await r.setRemoteDescription(h),n.log.trace("server creating local answer");let p=await r.createAnswer();n.log.trace("server created local answer");let d=Wf(p,t);n.log.trace("server setting local description %s",p.sdp),await r.setLocalDescription(d)}if(o.readyState!=="open"&&(n.log.trace("%s wait for handshake channel to open, starting status %s",n.role,o.readyState),await Le(o,"open",n)),n.log.trace("%s handshake channel opened",n.role),Lb(n,r)){let h=r.remoteFingerprint()?.value??"";n.remoteAddr=n.remoteAddr.encapsulate(qd(h))}let s=$d(r.localDescription?.sdp);if(s==null)throw new Jt("Could not get fingerprint from local description sdp");n.log.trace("%s performing noise handshake",n.role);let i=Xd(s,n.remoteAddr,n.role),a=zd({prologueBytes:i})(n),c=po({channel:o,direction:"outbound",isHandshake:!0,log:n.log,...n.dataChannel??{}}),f=mo({peerConnection:r,remoteAddr:n.remoteAddr,metrics:n.events,direction:n.role==="client"?"outbound":"inbound",log:n.logger.forComponent("libp2p:webrtc-direct:connection")});if(r.addEventListener("connectionstatechange",()=>{switch(r.connectionState){case"failed":case"disconnected":case"closed":f.close().catch(h=>{n.log.error("error closing connection - %e",h),f.abort(h)});break;default:break}}),n.events?.increment({peer_connection:!0}),n.role==="client"){n.log.trace("%s secure inbound",n.role);let h=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:h.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 o.close(),r.close(),s}}async function Zd(r,e,t={}){let n=t.certificate;n==null&&(n=await RTCPeerConnection.generateCertificate({name:"ECDSA",namedCurve:"P-256"}));let o=typeof t.rtcConfiguration=="function"?await t.rtcConfiguration():t.rtcConfiguration,s=new RTCPeerConnection({...o??{},certificates:[n]}),i=new Zt({peerConnection:s,metrics:t.events,dataChannelOptions:t.dataChannel});return{peerConnection:s,muxerFactory:i}}var bi=class{log;metrics;components;init;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:webrtc-direct"),this.components=e,this.init=t,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"})})}[Vo]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[Or]=["@libp2p/transport"];async dial(e,t){this.log("dial %a",e),t.signal.throwIfAborted();let n,o=e.getComponents().findLast(c=>c.code===421)?.value;o!=null&&(n=Zr(o));let s=Tl(),{peerConnection:i,muxerFactory:a}=await Zd("client",s,{rtcConfiguration:typeof this.init.rtcConfiguration=="function"?await this.init.rtcConfiguration():this.init.rtcConfiguration??{},dataChannel:this.init.dataChannel});try{return await Yd(i,a,s,{role:"client",log:this.log,logger:this.components.logger,events:this.metrics?.dialerEvents,signal:t.signal,remoteAddr:e,dataChannel:this.init.dataChannel,upgrader:t.upgrader,peerId:this.components.peerId,remotePeer:n,privateKey:this.components.privateKey})}catch(c){throw i.close(),c}}createListener(e){throw new Qs("WebRTCDirectTransport.createListener")}listenFilter(e){return[]}dialFilter(e){return e.filter(bl.exactMatch)}};function _b(r){return e=>new bi(e,r)}function Ib(r){return e=>new oi(e,r)}return rp(Bb);})();
40
+ a=ice-pwd:`+e+t)}catch{}return r}var Zf=Y("libp2p-webrtc-noise:");function ep(r,e,t){let n=r.trim().toLowerCase().replaceAll(":",""),o=Y(n,"hex"),s=Ne(gt.code,o),i=Wf.decode(Xf(e)),a=Zf.byteLength+s.bytes.byteLength+i.byteLength;return t==="server"?Me([Zf,i,s.bytes],a):Me([Zf,s.bytes,i],a)}function Db(r,e){return r.role==="server"}async function tp(r,e,t,n){let o=r.createDataChannel("",{negotiated:!0,id:0});try{if(n.role==="client"){n.log.trace("client creating local offer");let h=await r.createOffer();n.log.trace("client created local offer %s",h.sdp);let m=Yf(h,t);n.log.trace("client setting local offer %s",m.sdp),await r.setLocalDescription(m);let p=Zd(n.remoteAddr,t);n.log.trace("client setting server description %s",p.sdp),await r.setRemoteDescription(p)}else{let h=Jd(n.remoteAddr,t);n.log.trace("server setting client %s %s",h.type,h.sdp),await r.setRemoteDescription(h),n.log.trace("server creating local answer");let m=await r.createAnswer();n.log.trace("server created local answer");let p=Yf(m,t);n.log.trace("server setting local description %s",m.sdp),await r.setLocalDescription(p)}if(o.readyState!=="open"&&(n.log.trace("%s wait for handshake channel to open, starting status %s",n.role,o.readyState),await Le(o,"open",n)),n.log.trace("%s handshake channel opened",n.role),Db(n,r)){let h=r.remoteFingerprint()?.value??"";n.remoteAddr=n.remoteAddr.encapsulate(Yd(h))}let s=Xd(r.localDescription?.sdp);if(s==null)throw new Jt("Could not get fingerprint from local description sdp");n.log.trace("%s performing noise handshake",n.role);let i=ep(s,n.remoteAddr,n.role),a=Wd({prologueBytes:i})(n),c=po({channel:o,direction:"outbound",isHandshake:!0,log:n.log,...n.dataChannel??{}}),f=mo({peerConnection:r,remoteAddr:n.remoteAddr,metrics:n.events,direction:n.role==="client"?"outbound":"inbound",log:n.logger.forComponent("libp2p:webrtc-direct:connection")});if(r.addEventListener("connectionstatechange",()=>{switch(r.connectionState){case"failed":case"disconnected":case"closed":f.close().catch(h=>{n.log.error("error closing connection - %e",h),f.abort(h)});break;default:break}}),n.events?.increment({peer_connection:!0}),n.role==="client"){n.log.trace("%s secure inbound",n.role);let h=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:h.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(),r.close(),s}}async function rp(r,e,t={}){let n=t.certificate;n==null&&(n=await RTCPeerConnection.generateCertificate({name:"ECDSA",namedCurve:"P-256"}));let o=typeof t.rtcConfiguration=="function"?await t.rtcConfiguration():t.rtcConfiguration,s=new RTCPeerConnection({...o??{},certificates:[n]}),i=new Zt({peerConnection:s,metrics:t.events,log:t.log,dataChannelOptions:t.dataChannel,maxEarlyStreams:t.maxEarlyStreams});return{peerConnection:s,muxerFactory:i}}var bi=class{log;metrics;components;init;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:webrtc-direct"),this.components=e,this.init=t,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"})})}[Vo]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[Pr]=["@libp2p/transport"];async dial(e,t){this.log("dial %a",e),t.signal.throwIfAborted();let n,o=e.getComponents().findLast(c=>c.code===421)?.value;o!=null&&(n=Jr(o));let s=Nl(),{peerConnection:i,muxerFactory:a}=await rp("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 tp(i,a,s,{role:"client",log:this.log,logger:this.components.logger,events:this.metrics?.dialerEvents,signal:t.signal,remoteAddr:e,dataChannel:this.init.dataChannel,upgrader:t.upgrader,peerId:this.components.peerId,remotePeer:n,privateKey:this.components.privateKey})}catch(c){throw i.close(),c}}createListener(e){throw new Qs("WebRTCDirectTransport.createListener")}listenFilter(e){return[]}dialFilter(e){return e.filter(xl.exactMatch)}};function Rb(r){return e=>new bi(e,r)}function Ob(r){return e=>new oi(e,r)}return ap(Pb);})();
41
41
  /*! Bundled license information:
42
42
 
43
43
  @noble/curves/utils.js: