libp2p 1.9.3 → 1.9.4-df330695a
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.min.js +15 -16
- package/dist/src/components.d.ts.map +1 -1
- package/dist/src/components.js +4 -3
- package/dist/src/components.js.map +1 -1
- package/dist/src/config.d.ts +1 -1
- package/dist/src/config.d.ts.map +1 -1
- package/dist/src/config.js +2 -7
- package/dist/src/config.js.map +1 -1
- package/dist/src/connection/index.d.ts +3 -3
- package/dist/src/connection/index.d.ts.map +1 -1
- package/dist/src/connection/index.js +7 -7
- package/dist/src/connection/index.js.map +1 -1
- package/dist/src/connection-manager/connection-pruner.js +1 -1
- package/dist/src/connection-manager/constants.browser.d.ts +0 -8
- package/dist/src/connection-manager/constants.browser.d.ts.map +1 -1
- package/dist/src/connection-manager/constants.browser.js +0 -8
- package/dist/src/connection-manager/constants.browser.js.map +1 -1
- package/dist/src/connection-manager/constants.d.ts +0 -8
- package/dist/src/connection-manager/constants.d.ts.map +1 -1
- package/dist/src/connection-manager/constants.defaults.d.ts +12 -22
- package/dist/src/connection-manager/constants.defaults.d.ts.map +1 -1
- package/dist/src/connection-manager/constants.defaults.js +12 -22
- package/dist/src/connection-manager/constants.defaults.js.map +1 -1
- package/dist/src/connection-manager/constants.js +0 -8
- package/dist/src/connection-manager/constants.js.map +1 -1
- package/dist/src/connection-manager/dial-queue.d.ts.map +1 -1
- package/dist/src/connection-manager/dial-queue.js +29 -15
- package/dist/src/connection-manager/dial-queue.js.map +1 -1
- package/dist/src/connection-manager/index.d.ts +47 -50
- package/dist/src/connection-manager/index.d.ts.map +1 -1
- package/dist/src/connection-manager/index.js +23 -57
- package/dist/src/connection-manager/index.js.map +1 -1
- package/dist/src/connection-manager/reconnect-queue.d.ts +35 -0
- package/dist/src/connection-manager/reconnect-queue.d.ts.map +1 -0
- package/dist/src/connection-manager/reconnect-queue.js +104 -0
- package/dist/src/connection-manager/reconnect-queue.js.map +1 -0
- package/dist/src/connection-monitor.js +1 -1
- package/dist/src/connection-monitor.js.map +1 -1
- package/dist/src/content-routing.js +6 -6
- package/dist/src/content-routing.js.map +1 -1
- package/dist/src/errors.d.ts +41 -61
- package/dist/src/errors.d.ts.map +1 -1
- package/dist/src/errors.js +84 -63
- package/dist/src/errors.js.map +1 -1
- package/dist/src/get-peer.d.ts.map +1 -1
- package/dist/src/get-peer.js +4 -5
- package/dist/src/get-peer.js.map +1 -1
- package/dist/src/index.d.ts +25 -7
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/index.js +9 -2
- package/dist/src/index.js.map +1 -1
- package/dist/src/libp2p.d.ts +11 -10
- package/dist/src/libp2p.d.ts.map +1 -1
- package/dist/src/libp2p.js +11 -29
- package/dist/src/libp2p.js.map +1 -1
- package/dist/src/peer-routing.js +8 -8
- package/dist/src/peer-routing.js.map +1 -1
- package/dist/src/registrar.js +7 -7
- package/dist/src/registrar.js.map +1 -1
- package/dist/src/transport-manager.d.ts.map +1 -1
- package/dist/src/transport-manager.js +15 -23
- package/dist/src/transport-manager.js.map +1 -1
- package/dist/src/upgrader.d.ts +4 -4
- package/dist/src/upgrader.d.ts.map +1 -1
- package/dist/src/upgrader.js +35 -35
- package/dist/src/upgrader.js.map +1 -1
- package/dist/src/version.d.ts +1 -1
- package/dist/src/version.d.ts.map +1 -1
- package/dist/src/version.js +1 -1
- package/dist/src/version.js.map +1 -1
- package/package.json +20 -20
- package/src/components.ts +4 -3
- package/src/config.ts +4 -10
- package/src/connection/index.ts +9 -9
- package/src/connection-manager/connection-pruner.ts +1 -1
- package/src/connection-manager/constants.browser.ts +0 -10
- package/src/connection-manager/constants.defaults.ts +14 -27
- package/src/connection-manager/constants.ts +0 -10
- package/src/connection-manager/dial-queue.ts +30 -15
- package/src/connection-manager/index.ts +80 -118
- package/src/connection-manager/reconnect-queue.ts +134 -0
- package/src/connection-monitor.ts +1 -1
- package/src/content-routing.ts +6 -6
- package/src/errors.ts +96 -61
- package/src/get-peer.ts +4 -5
- package/src/index.ts +40 -10
- package/src/libp2p.ts +20 -34
- package/src/peer-routing.ts +8 -8
- package/src/registrar.ts +7 -7
- package/src/transport-manager.ts +15 -23
- package/src/upgrader.ts +37 -38
- package/src/version.ts +1 -1
- package/dist/src/connection-manager/auto-dial.d.ts +0 -47
- package/dist/src/connection-manager/auto-dial.d.ts.map +0 -1
- package/dist/src/connection-manager/auto-dial.js +0 -223
- package/dist/src/connection-manager/auto-dial.js.map +0 -1
- package/dist/typedoc-urls.json +0 -14
- package/src/connection-manager/auto-dial.ts +0 -285
package/dist/index.min.js
CHANGED
|
@@ -1,23 +1,22 @@
|
|
|
1
1
|
(function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Libp2P = factory()}(typeof self !== 'undefined' ? self : this, function () {
|
|
2
|
-
"use strict";var Libp2P=(()=>{var mp=Object.create;var To=Object.defineProperty;var gp=Object.getOwnPropertyDescriptor;var yp=Object.getOwnPropertyNames;var wp=Object.getPrototypeOf,bp=Object.prototype.hasOwnProperty;var _t=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),ve=(r,e)=>{for(var t in e)To(r,t,{get:e[t],enumerable:!0})},cu=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of yp(e))!bp.call(r,o)&&o!==t&&To(r,o,{get:()=>e[o],enumerable:!(n=gp(e,o))||n.enumerable});return r};var pr=(r,e,t)=>(t=r!=null?mp(wp(r)):{},cu(e||!r||!r.__esModule?To(t,"default",{value:r,enumerable:!0}):t,r)),Ep=r=>cu(To({},"__esModule",{value:!0}),r);var df=_t(on=>{"use strict";var Zg="[object ArrayBuffer]",Nt=class r{static isArrayBuffer(e){return Object.prototype.toString.call(e)===Zg}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,t){if(e.constructor===t)return e;if(this.isArrayBuffer(e))return new t(e);if(this.isArrayBufferView(e))return new t(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(e,t){let n=r.toUint8Array(e),o=r.toUint8Array(t);if(n.length!==o.byteLength)return!1;for(let s=0;s<n.length;s++)if(n[s]!==o[s])return!1;return!0}static concat(...e){let t;Array.isArray(e[0])&&!(e[1]instanceof Function)||Array.isArray(e[0])&&e[1]instanceof Function?t=e[0]:e[e.length-1]instanceof Function?t=e.slice(0,e.length-1):t=e;let n=0;for(let i of t)n+=i.byteLength;let o=new Uint8Array(n),s=0;for(let i of t){let a=this.toUint8Array(i);o.set(a,s),s+=a.length}return e[e.length-1]instanceof Function?this.toView(o,e[e.length-1]):o.buffer}},gc="string",Qg=/^[0-9a-f]+$/i,Jg=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,e0=/^[a-zA-Z0-9-_]+$/,Zo=class{static fromString(e){let t=unescape(encodeURIComponent(e)),n=new Uint8Array(t.length);for(let o=0;o<t.length;o++)n[o]=t.charCodeAt(o);return n.buffer}static toString(e){let t=Nt.toUint8Array(e),n="";for(let s=0;s<t.length;s++)n+=String.fromCharCode(t[s]);return decodeURIComponent(escape(n))}},tt=class{static toString(e,t=!1){let n=Nt.toArrayBuffer(e),o=new DataView(n),s="";for(let i=0;i<n.byteLength;i+=2){let a=o.getUint16(i,t);s+=String.fromCharCode(a)}return s}static fromString(e,t=!1){let n=new ArrayBuffer(e.length*2),o=new DataView(n);for(let s=0;s<e.length;s++)o.setUint16(s*2,e.charCodeAt(s),t);return n}},Qo=class r{static isHex(e){return typeof e===gc&&Qg.test(e)}static isBase64(e){return typeof e===gc&&Jg.test(e)}static isBase64Url(e){return typeof e===gc&&e0.test(e)}static ToString(e,t="utf8"){let n=Nt.toUint8Array(e);switch(t.toLowerCase()){case"utf8":return this.ToUtf8String(n);case"binary":return this.ToBinary(n);case"hex":return this.ToHex(n);case"base64":return this.ToBase64(n);case"base64url":return this.ToBase64Url(n);case"utf16le":return tt.toString(n,!0);case"utf16":case"utf16be":return tt.toString(n);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromString(e,t="utf8"){if(!e)return new ArrayBuffer(0);switch(t.toLowerCase()){case"utf8":return this.FromUtf8String(e);case"binary":return this.FromBinary(e);case"hex":return this.FromHex(e);case"base64":return this.FromBase64(e);case"base64url":return this.FromBase64Url(e);case"utf16le":return tt.fromString(e,!0);case"utf16":case"utf16be":return tt.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){let t=Nt.toUint8Array(e);if(typeof btoa<"u"){let n=this.ToString(t,"binary");return btoa(n)}else return Buffer.from(t).toString("base64")}static FromBase64(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isBase64(t))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return typeof atob<"u"?this.FromBinary(atob(t)):new Uint8Array(Buffer.from(t,"base64")).buffer}static FromBase64Url(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isBase64Url(t))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(t.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(e){return this.ToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(e,t=r.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.FromBinary(e);case"utf8":return Zo.fromString(e);case"utf16":case"utf16be":return tt.fromString(e);case"utf16le":case"usc2":return tt.fromString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToUtf8String(e,t=r.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.ToBinary(e);case"utf8":return Zo.toString(e);case"utf16":case"utf16be":return tt.toString(e);case"utf16le":case"usc2":return tt.toString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromBinary(e){let t=e.length,n=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=e.charCodeAt(o);return n.buffer}static ToBinary(e){let t=Nt.toUint8Array(e),n="";for(let o=0;o<t.length;o++)n+=String.fromCharCode(t[o]);return n}static ToHex(e){let t=Nt.toUint8Array(e),n="",o=t.length;for(let s=0;s<o;s++){let i=t[s];i<16&&(n+="0"),n+=i.toString(16)}return n}static FromHex(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isHex(t))throw new TypeError("Argument 'hexString' is not HEX encoded");t.length%2&&(t=`0${t}`);let n=new Uint8Array(t.length/2);for(let o=0;o<t.length;o=o+2){let s=t.slice(o,o+2);n[o/2]=parseInt(s,16)}return n.buffer}static ToUtf16String(e,t=!1){return tt.toString(e,t)}static FromUtf16String(e,t=!1){return tt.fromString(e,t)}static Base64Padding(e){let t=4-e.length%4;if(t<4)for(let n=0;n<t;n++)e+="=";return e}static formatString(e){return e?.replace(/[\n\r\t ]/g,"")||""}};Qo.DEFAULT_UTF8_ENCODING="utf8";function t0(r,...e){let t=arguments[0];for(let n=1;n<arguments.length;n++){let o=arguments[n];for(let s in o)t[s]=o[s]}return t}function r0(...r){let e=r.map(o=>o.byteLength).reduce((o,s)=>o+s),t=new Uint8Array(e),n=0;return r.map(o=>new Uint8Array(o)).forEach(o=>{for(let s of o)t[n++]=s}),t.buffer}function n0(r,e){if(!(r&&e)||r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let o=0;o<r.byteLength;o++)if(t[o]!==n[o])return!1;return!0}on.BufferSourceConverter=Nt;on.Convert=Qo;on.assign=t0;on.combine=r0;on.isEqual=n0});var Ih=_t((io,qs)=>{(function(r,e){"use strict";var t={version:"3.0.0",x86:{},x64:{},inputValidation:!0};function n(h){if(!Array.isArray(h)&&!ArrayBuffer.isView(h))return!1;for(var d=0;d<h.length;d++)if(!Number.isInteger(h[d])||h[d]<0||h[d]>255)return!1;return!0}function o(h,d){return(h&65535)*d+(((h>>>16)*d&65535)<<16)}function s(h,d){return h<<d|h>>>32-d}function i(h){return h^=h>>>16,h=o(h,2246822507),h^=h>>>13,h=o(h,3266489909),h^=h>>>16,h}function a(h,d){h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535],d=[d[0]>>>16,d[0]&65535,d[1]>>>16,d[1]&65535];var m=[0,0,0,0];return m[3]+=h[3]+d[3],m[2]+=m[3]>>>16,m[3]&=65535,m[2]+=h[2]+d[2],m[1]+=m[2]>>>16,m[2]&=65535,m[1]+=h[1]+d[1],m[0]+=m[1]>>>16,m[1]&=65535,m[0]+=h[0]+d[0],m[0]&=65535,[m[0]<<16|m[1],m[2]<<16|m[3]]}function c(h,d){h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535],d=[d[0]>>>16,d[0]&65535,d[1]>>>16,d[1]&65535];var m=[0,0,0,0];return m[3]+=h[3]*d[3],m[2]+=m[3]>>>16,m[3]&=65535,m[2]+=h[2]*d[3],m[1]+=m[2]>>>16,m[2]&=65535,m[2]+=h[3]*d[2],m[1]+=m[2]>>>16,m[2]&=65535,m[1]+=h[1]*d[3],m[0]+=m[1]>>>16,m[1]&=65535,m[1]+=h[2]*d[2],m[0]+=m[1]>>>16,m[1]&=65535,m[1]+=h[3]*d[1],m[0]+=m[1]>>>16,m[1]&=65535,m[0]+=h[0]*d[3]+h[1]*d[2]+h[2]*d[1]+h[3]*d[0],m[0]&=65535,[m[0]<<16|m[1],m[2]<<16|m[3]]}function u(h,d){return d%=64,d===32?[h[1],h[0]]:d<32?[h[0]<<d|h[1]>>>32-d,h[1]<<d|h[0]>>>32-d]:(d-=32,[h[1]<<d|h[0]>>>32-d,h[0]<<d|h[1]>>>32-d])}function f(h,d){return d%=64,d===0?h:d<32?[h[0]<<d|h[1]>>>32-d,h[1]<<d]:[h[1]<<d-32,0]}function l(h,d){return[h[0]^d[0],h[1]^d[1]]}function p(h){return h=l(h,[0,h[0]>>>1]),h=c(h,[4283543511,3981806797]),h=l(h,[0,h[0]>>>1]),h=c(h,[3301882366,444984403]),h=l(h,[0,h[0]>>>1]),h}t.x86.hash32=function(h,d){if(t.inputValidation&&!n(h))return e;d=d||0;for(var m=h.length%4,w=h.length-m,g=d,y=0,b=3432918353,x=461845907,A=0;A<w;A=A+4)y=h[A]|h[A+1]<<8|h[A+2]<<16|h[A+3]<<24,y=o(y,b),y=s(y,15),y=o(y,x),g^=y,g=s(g,13),g=o(g,5)+3864292196;switch(y=0,m){case 3:y^=h[A+2]<<16;case 2:y^=h[A+1]<<8;case 1:y^=h[A],y=o(y,b),y=s(y,15),y=o(y,x),g^=y}return g^=h.length,g=i(g),g>>>0},t.x86.hash128=function(h,d){if(t.inputValidation&&!n(h))return e;d=d||0;for(var m=h.length%16,w=h.length-m,g=d,y=d,b=d,x=d,A=0,R=0,_=0,I=0,$=597399067,V=2869860233,K=951274213,Q=2716044179,D=0;D<w;D=D+16)A=h[D]|h[D+1]<<8|h[D+2]<<16|h[D+3]<<24,R=h[D+4]|h[D+5]<<8|h[D+6]<<16|h[D+7]<<24,_=h[D+8]|h[D+9]<<8|h[D+10]<<16|h[D+11]<<24,I=h[D+12]|h[D+13]<<8|h[D+14]<<16|h[D+15]<<24,A=o(A,$),A=s(A,15),A=o(A,V),g^=A,g=s(g,19),g+=y,g=o(g,5)+1444728091,R=o(R,V),R=s(R,16),R=o(R,K),y^=R,y=s(y,17),y+=b,y=o(y,5)+197830471,_=o(_,K),_=s(_,17),_=o(_,Q),b^=_,b=s(b,15),b+=x,b=o(b,5)+2530024501,I=o(I,Q),I=s(I,18),I=o(I,$),x^=I,x=s(x,13),x+=g,x=o(x,5)+850148119;switch(A=0,R=0,_=0,I=0,m){case 15:I^=h[D+14]<<16;case 14:I^=h[D+13]<<8;case 13:I^=h[D+12],I=o(I,Q),I=s(I,18),I=o(I,$),x^=I;case 12:_^=h[D+11]<<24;case 11:_^=h[D+10]<<16;case 10:_^=h[D+9]<<8;case 9:_^=h[D+8],_=o(_,K),_=s(_,17),_=o(_,Q),b^=_;case 8:R^=h[D+7]<<24;case 7:R^=h[D+6]<<16;case 6:R^=h[D+5]<<8;case 5:R^=h[D+4],R=o(R,V),R=s(R,16),R=o(R,K),y^=R;case 4:A^=h[D+3]<<24;case 3:A^=h[D+2]<<16;case 2:A^=h[D+1]<<8;case 1:A^=h[D],A=o(A,$),A=s(A,15),A=o(A,V),g^=A}return g^=h.length,y^=h.length,b^=h.length,x^=h.length,g+=y,g+=b,g+=x,y+=g,b+=g,x+=g,g=i(g),y=i(y),b=i(b),x=i(x),g+=y,g+=b,g+=x,y+=g,b+=g,x+=g,("00000000"+(g>>>0).toString(16)).slice(-8)+("00000000"+(y>>>0).toString(16)).slice(-8)+("00000000"+(b>>>0).toString(16)).slice(-8)+("00000000"+(x>>>0).toString(16)).slice(-8)},t.x64.hash128=function(h,d){if(t.inputValidation&&!n(h))return e;d=d||0;for(var m=h.length%16,w=h.length-m,g=[0,d],y=[0,d],b=[0,0],x=[0,0],A=[2277735313,289559509],R=[1291169091,658871167],_=0;_<w;_=_+16)b=[h[_+4]|h[_+5]<<8|h[_+6]<<16|h[_+7]<<24,h[_]|h[_+1]<<8|h[_+2]<<16|h[_+3]<<24],x=[h[_+12]|h[_+13]<<8|h[_+14]<<16|h[_+15]<<24,h[_+8]|h[_+9]<<8|h[_+10]<<16|h[_+11]<<24],b=c(b,A),b=u(b,31),b=c(b,R),g=l(g,b),g=u(g,27),g=a(g,y),g=a(c(g,[0,5]),[0,1390208809]),x=c(x,R),x=u(x,33),x=c(x,A),y=l(y,x),y=u(y,31),y=a(y,g),y=a(c(y,[0,5]),[0,944331445]);switch(b=[0,0],x=[0,0],m){case 15:x=l(x,f([0,h[_+14]],48));case 14:x=l(x,f([0,h[_+13]],40));case 13:x=l(x,f([0,h[_+12]],32));case 12:x=l(x,f([0,h[_+11]],24));case 11:x=l(x,f([0,h[_+10]],16));case 10:x=l(x,f([0,h[_+9]],8));case 9:x=l(x,[0,h[_+8]]),x=c(x,R),x=u(x,33),x=c(x,A),y=l(y,x);case 8:b=l(b,f([0,h[_+7]],56));case 7:b=l(b,f([0,h[_+6]],48));case 6:b=l(b,f([0,h[_+5]],40));case 5:b=l(b,f([0,h[_+4]],32));case 4:b=l(b,f([0,h[_+3]],24));case 3:b=l(b,f([0,h[_+2]],16));case 2:b=l(b,f([0,h[_+1]],8));case 1:b=l(b,[0,h[_]]),b=c(b,A),b=u(b,31),b=c(b,R),g=l(g,b)}return g=l(g,[0,h.length]),y=l(y,[0,h.length]),g=a(g,y),y=a(y,g),g=p(g),y=p(y),g=a(g,y),y=a(y,g),("00000000"+(g[0]>>>0).toString(16)).slice(-8)+("00000000"+(g[1]>>>0).toString(16)).slice(-8)+("00000000"+(y[0]>>>0).toString(16)).slice(-8)+("00000000"+(y[1]>>>0).toString(16)).slice(-8)},typeof io<"u"?(typeof qs<"u"&&qs.exports&&(io=qs.exports=t),io.murmurHash3=t):typeof define=="function"&&define.amd?define([],function(){return t}):(t._murmurHash3=r.murmurHash3,t.noConflict=function(){return r.murmurHash3=t._murmurHash3,t._murmurHash3=e,t.noConflict=e,t},r.murmurHash3=t)})(io)});var Bh=_t((Jv,Th)=>{Th.exports=Ih()});var Jh=_t((B2,tl)=>{"use strict";var Ty=Object.prototype.hasOwnProperty,He="~";function ho(){}Object.create&&(ho.prototype=Object.create(null),new ho().__proto__||(He=!1));function By(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function Qh(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var s=new By(t,n||r,o),i=He?He+e:e;return r._events[i]?r._events[i].fn?r._events[i]=[r._events[i],s]:r._events[i].push(s):(r._events[i]=s,r._eventsCount++),r}function Zs(r,e){--r._eventsCount===0?r._events=new ho:delete r._events[e]}function Oe(){this._events=new ho,this._eventsCount=0}Oe.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)Ty.call(t,n)&&e.push(He?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Oe.prototype.listeners=function(e){var t=He?He+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var o=0,s=n.length,i=new Array(s);o<s;o++)i[o]=n[o].fn;return i};Oe.prototype.listenerCount=function(e){var t=He?He+e:e,n=this._events[t];return n?n.fn?1:n.length:0};Oe.prototype.emit=function(e,t,n,o,s,i){var a=He?He+e:e;if(!this._events[a])return!1;var c=this._events[a],u=arguments.length,f,l;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),u){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,o),!0;case 5:return c.fn.call(c.context,t,n,o,s),!0;case 6:return c.fn.call(c.context,t,n,o,s,i),!0}for(l=1,f=new Array(u-1);l<u;l++)f[l-1]=arguments[l];c.fn.apply(c.context,f)}else{var p=c.length,h;for(l=0;l<p;l++)switch(c[l].once&&this.removeListener(e,c[l].fn,void 0,!0),u){case 1:c[l].fn.call(c[l].context);break;case 2:c[l].fn.call(c[l].context,t);break;case 3:c[l].fn.call(c[l].context,t,n);break;case 4:c[l].fn.call(c[l].context,t,n,o);break;default:if(!f)for(h=1,f=new Array(u-1);h<u;h++)f[h-1]=arguments[h];c[l].fn.apply(c[l].context,f)}}return!0};Oe.prototype.on=function(e,t,n){return Qh(this,e,t,n,!1)};Oe.prototype.once=function(e,t,n){return Qh(this,e,t,n,!0)};Oe.prototype.removeListener=function(e,t,n,o){var s=He?He+e:e;if(!this._events[s])return this;if(!t)return Zs(this,s),this;var i=this._events[s];if(i.fn)i.fn===t&&(!o||i.once)&&(!n||i.context===n)&&Zs(this,s);else{for(var a=0,c=[],u=i.length;a<u;a++)(i[a].fn!==t||o&&!i[a].once||n&&i[a].context!==n)&&c.push(i[a]);c.length?this._events[s]=c.length===1?c[0]:c:Zs(this,s)}return this};Oe.prototype.removeAllListeners=function(e){var t;return e?(t=He?He+e:e,this._events[t]&&Zs(this,t)):(this._events=new ho,this._eventsCount=0),this};Oe.prototype.off=Oe.prototype.removeListener;Oe.prototype.addListener=Oe.prototype.on;Oe.prefixed=He;Oe.EventEmitter=Oe;typeof tl<"u"&&(tl.exports=Oe)});var pd=_t((WS,dd)=>{"use strict";function hd(r,e){for(let t in e)Object.defineProperty(r,t,{value:e[t],enumerable:!0,configurable:!0});return r}function Gy(r,e,t){if(!r||typeof r=="string")throw new TypeError("Please pass an Error to err-code");t||(t={}),typeof e=="object"&&(t=e,e=""),e&&(t.code=e);try{return hd(r,t)}catch{t.message=r.message,t.stack=r.stack;let o=function(){};return o.prototype=Object.create(Object.getPrototypeOf(r)),hd(new o,t)}}dd.exports=Gy});var Ed=_t(yo=>{(function(){var r,e,t,n,o,s,i,a;a=function(c){var u,f,l,p;return u=(c&255<<24)>>>24,f=(c&255<<16)>>>16,l=(c&65280)>>>8,p=c&255,[u,f,l,p].join(".")},i=function(c){var u,f,l,p,h,d;for(u=[],l=p=0;p<=3&&c.length!==0;l=++p){if(l>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}d=e(c),h=d[0],f=d[1],c=c.substring(f),u.push(h)}if(c.length!==0)throw new Error("Invalid IP");switch(u.length){case 1:if(u[0]>4294967295)throw new Error("Invalid IP");return u[0]>>>0;case 2:if(u[0]>255||u[1]>16777215)throw new Error("Invalid IP");return(u[0]<<24|u[1])>>>0;case 3:if(u[0]>255||u[1]>255||u[2]>65535)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2])>>>0;case 4:if(u[0]>255||u[1]>255||u[2]>255||u[3]>255)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2]<<8|u[3])>>>0;default:throw new Error("Invalid IP")}},t=function(c){return c.charCodeAt(0)},n=t("0"),s=t("a"),o=t("A"),e=function(c){var u,f,l,p,h;for(p=0,u=10,f="9",l=0,c.length>1&&c[l]==="0"&&(c[l+1]==="x"||c[l+1]==="X"?(l+=2,u=16):"0"<=c[l+1]&&c[l+1]<="9"&&(l++,u=8,f="7")),h=l;l<c.length;){if("0"<=c[l]&&c[l]<=f)p=p*u+(t(c[l])-n)>>>0;else if(u===16)if("a"<=c[l]&&c[l]<="f")p=p*u+(10+t(c[l])-s)>>>0;else if("A"<=c[l]&&c[l]<="F")p=p*u+(10+t(c[l])-o)>>>0;else break;else break;if(p>4294967295)throw new Error("too large");l++}if(l===h)throw new Error("empty octet");return[p,l]},r=function(){function c(u,f){var l,p,h,d;if(typeof u!="string")throw new Error("Missing `net' parameter");if(f||(d=u.split("/",2),u=d[0],f=d[1]),f||(f=32),typeof f=="string"&&f.indexOf(".")>-1){try{this.maskLong=i(f)}catch(m){throw l=m,new Error("Invalid mask: "+f)}for(p=h=32;h>=0;p=--h)if(this.maskLong===4294967295<<32-p>>>0){this.bitmask=p;break}}else if(f||f===0)this.bitmask=parseInt(f,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(i(u)&this.maskLong)>>>0}catch(m){throw l=m,new Error("Invalid net address: "+u)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+f);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(u){return typeof u=="string"&&(u.indexOf("/")>0||u.split(".").length!==4)&&(u=new c(u)),u instanceof c?this.contains(u.base)&&this.contains(u.broadcast||u.last):(i(u)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(u){return u==null&&(u=1),new c(a(this.netLong+this.size*u),this.mask)},c.prototype.forEach=function(u){var f,l,p;for(p=i(this.first),l=i(this.last),f=0;p<=l;)u(a(p),p,f),f++,p++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),yo.ip2long=i,yo.long2ip=a,yo.Netmask=r}).call(yo)});var Ld=_t((rI,Nd)=>{Nd.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function o(s,i){t[s]=i,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(s){return t[s]!==void 0||n[s]!==void 0},remove:function(s){t[s]!==void 0&&(t[s]=void 0),n[s]!==void 0&&(n[s]=void 0)},get:function(s){var i=t[s];if(i!==void 0)return i;if((i=n[s])!==void 0)return o(s,i),i},set:function(s,i){t[s]!==void 0?t[s]=i:o(s,i)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var Md=_t((EI,Ud)=>{"use strict";Ud.exports=r=>{if(Object.prototype.toString.call(r)!=="[object Object]")return!1;let e=Object.getPrototypeOf(r);return e===null||e===Object.prototype}});var qd=_t((Hd,$d)=>{"use strict";var wi=Md(),{hasOwnProperty:Vd}=Object.prototype,{propertyIsEnumerable:Ew}=Object,An=(r,e,t)=>Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0}),xw=Hd,Fd={concatArrays:!1,ignoreUndefined:!1},bi=r=>{let e=[];for(let t in r)Vd.call(r,t)&&e.push(t);if(Object.getOwnPropertySymbols){let t=Object.getOwnPropertySymbols(r);for(let n of t)Ew.call(r,n)&&e.push(n)}return e};function Sn(r){return Array.isArray(r)?vw(r):wi(r)?_w(r):r}function vw(r){let e=r.slice(0,0);return bi(r).forEach(t=>{An(e,t,Sn(r[t]))}),e}function _w(r){let e=Object.getPrototypeOf(r)===null?Object.create(null):{};return bi(r).forEach(t=>{An(e,t,Sn(r[t]))}),e}var Kd=(r,e,t,n)=>(t.forEach(o=>{typeof e[o]>"u"&&n.ignoreUndefined||(o in r&&r[o]!==Object.getPrototypeOf(r)?An(r,o,kl(r[o],e[o],n)):An(r,o,Sn(e[o])))}),r),Aw=(r,e,t)=>{let n=r.slice(0,0),o=0;return[r,e].forEach(s=>{let i=[];for(let a=0;a<s.length;a++)Vd.call(s,a)&&(i.push(String(a)),s===r?An(n,o++,s[a]):An(n,o++,Sn(s[a])));n=Kd(n,s,bi(s).filter(a=>!i.includes(a)),t)}),n};function kl(r,e,t){return t.concatArrays&&Array.isArray(r)&&Array.isArray(e)?Aw(r,e,t):!wi(e)||!wi(r)?Sn(e):Kd(r,e,bi(e),t)}$d.exports=function(...r){let e=kl(Sn(Fd),this!==xw&&this||{},Fd),t={_:{}};for(let n of r)if(n!==void 0){if(!wi(n))throw new TypeError("`"+n+"` is not an Option Object");t=kl(t,{_:n},e)}return t._}});var rb={};ve(rb,{createLibp2p:()=>tb});var lu=Symbol.for("@libp2p/connection");var ia=Symbol.for("@libp2p/content-routing");var aa=Symbol.for("@libp2p/peer-discovery");var Bo=Symbol.for("@libp2p/peer-id");function Co(r){return r!=null&&!!r[Bo]}var ca=Symbol.for("@libp2p/peer-routing");var uu="keep-alive";var ub=Symbol.for("@libp2p/transport");var Ht;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Ht||(Ht={}));var $t=class r extends Error{code;type;constructor(e="The operation was aborted"){super(e),this.name="AbortError",this.code=r.code,this.type=r.type}static code="ABORT_ERR";static type="aborted"},E=class extends Error{code;props;constructor(e,t,n){super(e),this.code=t,this.name=n?.name??"CodeError",this.props=n??{}}},ko=class extends AggregateError{code;props;constructor(e,t,n,o){super(e,t),this.code=n,this.name=o?.name??"AggregateCodeError",this.props=o??{}}};var No="ERR_TIMEOUT";var ie=(r,...e)=>{try{[...e]}catch{}};var At=class extends EventTarget{#e=new Map;constructor(){super(),ie(1/0,this)}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){super.addEventListener(e,t,n);let o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}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))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:o})=>!o),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new la(e,t))}},la=globalThis.CustomEvent;function fu(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}var kn=Symbol.for("@libp2p/service-capabilities"),ua=Symbol.for("@libp2p/service-dependencies");var pc={};ve(pc,{Ed25519PrivateKey:()=>Ar,Ed25519PublicKey:()=>Hn,generateKeyPair:()=>Wg,generateKeyPairFromSeed:()=>hf,unmarshalEd25519PrivateKey:()=>Gg,unmarshalEd25519PublicKey:()=>Yg});var ma={};ve(ma,{base58btc:()=>ae,base58flickr:()=>Rp});var Vb=new Uint8Array(0);function hu(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 St(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 du(r){return new TextEncoder().encode(r)}function pu(r){return new TextDecoder().decode(r)}function xp(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),u=Math.log(a)/Math.log(256),f=Math.log(256)/Math.log(a);function l(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 m=0,w=0,g=0,y=d.length;g!==y&&d[g]===0;)g++,m++;for(var b=(y-g)*f+1>>>0,x=new Uint8Array(b);g!==y;){for(var A=d[g],R=0,_=b-1;(A!==0||R<w)&&_!==-1;_--,R++)A+=256*x[_]>>>0,x[_]=A%a>>>0,A=A/a>>>0;if(A!==0)throw new Error("Non-zero carry");w=R,g++}for(var I=b-w;I!==b&&x[I]===0;)I++;for(var $=c.repeat(m);I<b;++I)$+=r.charAt(x[I]);return $}function p(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var m=0;if(d[m]!==" "){for(var w=0,g=0;d[m]===c;)w++,m++;for(var y=(d.length-m)*u+1>>>0,b=new Uint8Array(y);d[m];){var x=t[d.charCodeAt(m)];if(x===255)return;for(var A=0,R=y-1;(x!==0||A<g)&&R!==-1;R--,A++)x+=a*b[R]>>>0,b[R]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");g=A,m++}if(d[m]!==" "){for(var _=y-g;_!==y&&b[_]===0;)_++;for(var I=new Uint8Array(w+(y-_)),$=w;_!==y;)I[$++]=b[_++];return I}}}function h(d){var m=p(d);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:l,decodeUnsafe:p,decode:h}}var vp=xp,_p=vp,gu=_p;var fa=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")}},ha=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),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 yu(this,e)}},da=class{decoders;constructor(e){this.decoders=e}or(e){return yu(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 yu(r,e){return new da({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var pa=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 fa(e,t,n),this.decoder=new ha(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Kr({name:r,prefix:e,encode:t,decode:n}){return new pa(r,e,t,n)}function qt({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=gu(t,r);return Kr({prefix:e,name:r,encode:n,decode:s=>St(o(s))})}function Ap(r,e,t,n){let o={};for(let f=0;f<e.length;++f)o[e[f]]=f;let s=r.length;for(;r[s-1]==="=";)--s;let i=new Uint8Array(s*t/8|0),a=0,c=0,u=0;for(let f=0;f<s;++f){let l=o[r[f]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<t|l,a+=t,a>=8&&(a-=8,i[u++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return i}function Sp(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;)s+="=";return s}function ce({name:r,prefix:e,bitsPerChar:t,alphabet:n}){return Kr({prefix:e,name:r,encode(o){return Sp(o,n,t)},decode(o){return Ap(o,n,t,r)}})}var ae=qt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Rp=qt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ya={};ve(ya,{identity:()=>Rt});var Ip=Eu,wu=128,Tp=127,Bp=~Tp,Cp=Math.pow(2,31);function Eu(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Cp;)e[t++]=r&255|wu,r/=128;for(;r&Bp;)e[t++]=r&255|wu,r>>>=7;return e[t]=r|0,Eu.bytes=t-n+1,e}var kp=ga,Np=128,bu=127;function ga(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw ga.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&bu)<<o:(i&bu)*Math.pow(2,o),o+=7}while(i>=Np);return ga.bytes=s-n,t}var Lp=Math.pow(2,7),Dp=Math.pow(2,14),Pp=Math.pow(2,21),Op=Math.pow(2,28),Up=Math.pow(2,35),Mp=Math.pow(2,42),Fp=Math.pow(2,49),Vp=Math.pow(2,56),Kp=Math.pow(2,63),Hp=function(r){return r<Lp?1:r<Dp?2:r<Pp?3:r<Op?4:r<Up?5:r<Mp?6:r<Fp?7:r<Vp?8:r<Kp?9:10},$p={encode:Ip,decode:kp,encodingLength:Hp},qp=$p,Nn=qp;function Ln(r,e=0){return[Nn.decode(r,e),Nn.decode.bytes]}function Hr(r,e,t=0){return Nn.encode(r,e,t),e}function $r(r){return Nn.encodingLength(r)}function mt(r,e){let t=e.byteLength,n=$r(r),o=n+$r(t),s=new Uint8Array(o+t);return Hr(r,s,0),Hr(t,s,n),s.set(e,o),new qr(r,t,e,s)}function mr(r){let e=St(r),[t,n]=Ln(e),[o,s]=Ln(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new qr(t,o,i,e)}function xu(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&hu(r.bytes,t.bytes)}}var qr=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var vu=0,zp="identity",_u=St;function Gp(r){return mt(vu,_u(r))}var Rt={code:vu,name:zp,encode:_u,digest:Gp};var Ea={};ve(Ea,{sha256:()=>Se,sha512:()=>Yp});function ba({name:r,code:e,encode:t}){return new wa(r,e,t)}var wa=class{name;code;encode;constructor(e,t,n){this.name=e,this.code=t,this.encode=n}digest(e){if(e instanceof Uint8Array){let t=this.encode(e);return t instanceof Uint8Array?mt(this.code,t):t.then(n=>mt(this.code,n))}else throw Error("Unknown type, must be binary type")}};function Su(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Se=ba({name:"sha2-256",code:18,encode:Su("SHA-256")}),Yp=ba({name:"sha2-512",code:19,encode:Su("SHA-512")});function J(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 st(r=0){return new Uint8Array(r)}function ke(r=0){return new Uint8Array(r)}function Re(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=ke(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}var xa={};ve(xa,{base10:()=>Wp});var Wp=qt({prefix:"9",name:"base10",alphabet:"0123456789"});var va={};ve(va,{base16:()=>jp,base16upper:()=>Xp});var jp=ce({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Xp=ce({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var _a={};ve(_a,{base2:()=>Zp});var Zp=ce({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Aa={};ve(Aa,{base256emoji:()=>rm});var Ru=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}"),Qp=Ru.reduce((r,e,t)=>(r[t]=e,r),[]),Jp=Ru.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function em(r){return r.reduce((e,t)=>(e+=Qp[t],e),"")}function tm(r){let e=[];for(let t of r){let n=Jp[t.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var rm=Kr({prefix:"\u{1F680}",name:"base256emoji",encode:em,decode:tm});var Sa={};ve(Sa,{base32:()=>Ye,base32hex:()=>im,base32hexpad:()=>cm,base32hexpadupper:()=>lm,base32hexupper:()=>am,base32pad:()=>om,base32padupper:()=>sm,base32upper:()=>nm,base32z:()=>um});var Ye=ce({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),nm=ce({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),om=ce({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),sm=ce({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),im=ce({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),am=ce({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),cm=ce({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),lm=ce({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),um=ce({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Ra={};ve(Ra,{base36:()=>fm,base36upper:()=>hm});var fm=qt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),hm=qt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Ta={};ve(Ta,{base64:()=>Dn,base64pad:()=>dm,base64url:()=>Ia,base64urlpad:()=>pm});var Dn=ce({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),dm=ce({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ia=ce({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),pm=ce({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Ba={};ve(Ba,{base8:()=>mm});var mm=ce({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Ca={};ve(Ca,{identity:()=>gm});var gm=Kr({prefix:"\0",name:"identity",encode:r=>pu(r),decode:r=>du(r)});var pE=new TextEncoder,mE=new TextDecoder;function Iu(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return Em(t,ka(r),e??ae.encoder);default:return xm(t,ka(r),e??Ye.encoder)}}var Tu=new WeakMap;function ka(r){let e=Tu.get(r);if(e==null){let t=new Map;return Tu.set(r,t),t}return e}var Qe=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!==Pn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==vm)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=mt(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&&xu(e.multihash,n.multihash)}toString(e){return Iu(this,e)}toJSON(){return{"/":Iu(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??Bu(n,o,s.bytes))}else if(t[_m]===!0){let{version:n,multihash:o,code:s}=t,i=mr(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!==Pn)throw new Error(`Version 0 CID must use dag-pb (code: ${Pn}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=Bu(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Pn,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=St(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 qr(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[l,p]=Ln(e.subarray(t));return t+=p,l},o=n(),s=Pn;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),u=t+c,f=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:f,size:u}}static parse(e,t){let[n,o]=bm(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 ka(s).set(n,e),s}};function bm(r,e){switch(r[0]){case"Q":{let t=e??ae;return[ae.prefix,t.decode(`${ae.prefix}${r}`)]}case ae.prefix:{let t=e??ae;return[ae.prefix,t.decode(r)]}case Ye.prefix:{let t=e??Ye;return[Ye.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function Em(r,e,t){let{prefix:n}=t;if(n!==ae.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 xm(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 Pn=112,vm=18;function Bu(r,e,t){let n=$r(r),o=n+$r(e),s=new Uint8Array(o+t.byteLength);return Hr(r,s,0),Hr(e,s,n),s.set(t,o),s}var _m=Symbol.for("@ipld/js-cid/CID");var zt={...Ca,..._a,...Ba,...xa,...va,...Sa,...Ra,...ma,...Ta,...Aa},kE={...Ea,...ya};function ku(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Cu=ku("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Na=ku("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=ke(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),Am={utf8:Cu,"utf-8":Cu,hex:zt.base16,latin1:Na,ascii:Na,binary:Na,...zt},Do=Am;function L(r,e="utf8"){let t=Do[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function Je(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function zr(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`positive integer expected, not ${r}`)}function Sm(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Gr(r,...e){if(!Sm(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error(`Uint8Array expected of length ${e}, not of length=${r.length}`)}function Po(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");zr(r.outputLen),zr(r.blockLen)}function Yr(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 Nu(r,e){Gr(r);let t=e.outputLen;if(r.length<t)throw new Error(`digestInto() expects output buffer of length at least ${t}`)}var Oo=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var jr=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),it=(r,e)=>r<<32-e|r>>>e;var zE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;var Rm=async()=>{};async function Lu(r,e,t){let n=Date.now();for(let o=0;o<r;o++){t(o);let s=Date.now()-n;s>=0&&s<e||(await Rm(),n+=s)}}function Du(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function Gt(r){return typeof r=="string"&&(r=Du(r)),Gr(r),r}function La(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];Gr(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}var Wr=class{clone(){return this._cloneInto()}},Im={}.toString;function Pu(r,e){if(e!==void 0&&Im.call(e)!=="[object Object]")throw new Error("Options should be object or undefined");return Object.assign(r,e)}function Uo(r){let e=n=>r().update(Gt(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function Xr(r=32){if(Oo&&typeof Oo.getRandomValues=="function")return Oo.getRandomValues(new Uint8Array(r));throw new Error("crypto.getRandomValues must be defined")}function Tm(r,e,t,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(t>>o&s),a=Number(t&s),c=n?4:0,u=n?0:4;r.setUint32(e+c,i,n),r.setUint32(e+u,a,n)}var Ou=(r,e,t)=>r&e^~r&t,Uu=(r,e,t)=>r&e^r&t^e&t,Zr=class extends Wr{constructor(e,t,n,o){super(),this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=jr(this.buffer)}update(e){Yr(this);let{view:t,buffer:n,blockLen:o}=this;e=Gt(e);let s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=jr(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){Yr(this),Nu(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,this.buffer.subarray(i).fill(0),this.padOffset>o-i&&(this.process(n,0),i=0);for(let l=i;l<o;l++)t[l]=0;Tm(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=jr(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,f=this.get();if(u>f.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<u;l++)a.setUint32(4*l,f[l],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.length=o,e.pos=a,e.finished=s,e.destroyed=i,o%t&&e.buffer.set(n),e}};var Mo=BigInt(4294967295),Da=BigInt(32);function Mu(r,e=!1){return e?{h:Number(r&Mo),l:Number(r>>Da&Mo)}:{h:Number(r>>Da&Mo)|0,l:Number(r&Mo)|0}}function Bm(r,e=!1){let t=new Uint32Array(r.length),n=new Uint32Array(r.length);for(let o=0;o<r.length;o++){let{h:s,l:i}=Mu(r[o],e);[t[o],n[o]]=[s,i]}return[t,n]}var Cm=(r,e)=>BigInt(r>>>0)<<Da|BigInt(e>>>0),km=(r,e,t)=>r>>>t,Nm=(r,e,t)=>r<<32-t|e>>>t,Lm=(r,e,t)=>r>>>t|e<<32-t,Dm=(r,e,t)=>r<<32-t|e>>>t,Pm=(r,e,t)=>r<<64-t|e>>>t-32,Om=(r,e,t)=>r>>>t-32|e<<64-t,Um=(r,e)=>e,Mm=(r,e)=>r,Fm=(r,e,t)=>r<<t|e>>>32-t,Vm=(r,e,t)=>e<<t|r>>>32-t,Km=(r,e,t)=>e<<t-32|r>>>64-t,Hm=(r,e,t)=>r<<t-32|e>>>64-t;function $m(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var qm=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),zm=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,Gm=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),Ym=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,Wm=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),jm=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var Xm={fromBig:Mu,split:Bm,toBig:Cm,shrSH:km,shrSL:Nm,rotrSH:Lm,rotrSL:Dm,rotrBH:Pm,rotrBL:Om,rotr32H:Um,rotr32L:Mm,rotlSH:Fm,rotlSL:Vm,rotlBH:Km,rotlBL:Hm,add:$m,add3L:qm,add3H:zm,add4L:Gm,add4H:Ym,add5H:jm,add5L:Wm},M=Xm;var[Zm,Qm]=M.split(["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))),Yt=new Uint32Array(80),Wt=new Uint32Array(80),Pa=class extends Zr{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:u,El:f,Fh:l,Fl:p,Gh:h,Gl:d,Hh:m,Hl:w}=this;return[e,t,n,o,s,i,a,c,u,f,l,p,h,d,m,w]}set(e,t,n,o,s,i,a,c,u,f,l,p,h,d,m,w){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=f|0,this.Fh=l|0,this.Fl=p|0,this.Gh=h|0,this.Gl=d|0,this.Hh=m|0,this.Hl=w|0}process(e,t){for(let b=0;b<16;b++,t+=4)Yt[b]=e.getUint32(t),Wt[b]=e.getUint32(t+=4);for(let b=16;b<80;b++){let x=Yt[b-15]|0,A=Wt[b-15]|0,R=M.rotrSH(x,A,1)^M.rotrSH(x,A,8)^M.shrSH(x,A,7),_=M.rotrSL(x,A,1)^M.rotrSL(x,A,8)^M.shrSL(x,A,7),I=Yt[b-2]|0,$=Wt[b-2]|0,V=M.rotrSH(I,$,19)^M.rotrBH(I,$,61)^M.shrSH(I,$,6),K=M.rotrSL(I,$,19)^M.rotrBL(I,$,61)^M.shrSL(I,$,6),Q=M.add4L(_,K,Wt[b-7],Wt[b-16]),D=M.add4H(Q,R,V,Yt[b-7],Yt[b-16]);Yt[b]=D|0,Wt[b]=Q|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:f,Eh:l,El:p,Fh:h,Fl:d,Gh:m,Gl:w,Hh:g,Hl:y}=this;for(let b=0;b<80;b++){let x=M.rotrSH(l,p,14)^M.rotrSH(l,p,18)^M.rotrBH(l,p,41),A=M.rotrSL(l,p,14)^M.rotrSL(l,p,18)^M.rotrBL(l,p,41),R=l&h^~l&m,_=p&d^~p&w,I=M.add5L(y,A,_,Qm[b],Wt[b]),$=M.add5H(I,g,x,R,Zm[b],Yt[b]),V=I|0,K=M.rotrSH(n,o,28)^M.rotrBH(n,o,34)^M.rotrBH(n,o,39),Q=M.rotrSL(n,o,28)^M.rotrBL(n,o,34)^M.rotrBL(n,o,39),D=n&s^n&a^s&a,N=o&i^o&c^i&c;g=m|0,y=w|0,m=h|0,w=d|0,h=l|0,d=p|0,{h:l,l:p}=M.add(u|0,f|0,$|0,V|0),u=a|0,f=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let S=M.add3L(V,Q,N);n=M.add3H(S,$,K,D),o=S|0}({h:n,l:o}=M.add(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=M.add(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=M.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:f}=M.add(this.Dh|0,this.Dl|0,u|0,f|0),{h:l,l:p}=M.add(this.Eh|0,this.El|0,l|0,p|0),{h,l:d}=M.add(this.Fh|0,this.Fl|0,h|0,d|0),{h:m,l:w}=M.add(this.Gh|0,this.Gl|0,m|0,w|0),{h:g,l:y}=M.add(this.Hh|0,this.Hl|0,g|0,y|0),this.set(n,o,s,i,a,c,u,f,l,p,h,d,m,w,g,y)}roundClean(){Yt.fill(0),Wt.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var On=Uo(()=>new Pa);var Vo={};ve(Vo,{aInRange:()=>qe,abool:()=>at,abytes:()=>Qr,bitGet:()=>sg,bitLen:()=>og,bitMask:()=>Mn,bitSet:()=>ig,bytesToHex:()=>Tt,bytesToNumberBE:()=>Bt,bytesToNumberLE:()=>Xt,concatBytes:()=>Ct,createHmacDrbg:()=>Va,ensureBytes:()=>le,equalBytes:()=>rg,hexToBytes:()=>yr,hexToNumber:()=>Fa,inRange:()=>Un,isBytes:()=>jt,memoized:()=>br,notImplemented:()=>cg,numberToBytesBE:()=>Zt,numberToBytesLE:()=>wr,numberToHexUnpadded:()=>Ku,numberToVarBytesBE:()=>tg,utf8ToBytes:()=>ng,validateObject:()=>gt});var Ma=BigInt(0),Fo=BigInt(1),Jm=BigInt(2);function jt(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Qr(r){if(!jt(r))throw new Error("Uint8Array expected")}function at(r,e){if(typeof e!="boolean")throw new Error(`${r} must be valid boolean, got "${e}".`)}var eg=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Tt(r){Qr(r);let e="";for(let t=0;t<r.length;t++)e+=eg[r[t]];return e}function Ku(r){let e=r.toString(16);return e.length&1?`0${e}`:e}function Fa(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return BigInt(r===""?"0":`0x${r}`)}var It={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function Fu(r){if(r>=It._0&&r<=It._9)return r-It._0;if(r>=It._A&&r<=It._F)return r-(It._A-10);if(r>=It._a&&r<=It._f)return r-(It._a-10)}function yr(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);let e=r.length,t=e/2;if(e%2)throw new Error("padded 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=Fu(r.charCodeAt(s)),a=Fu(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function Bt(r){return Fa(Tt(r))}function Xt(r){return Qr(r),Fa(Tt(Uint8Array.from(r).reverse()))}function Zt(r,e){return yr(r.toString(16).padStart(e*2,"0"))}function wr(r,e){return Zt(r,e).reverse()}function tg(r){return yr(Ku(r))}function le(r,e,t){let n;if(typeof e=="string")try{n=yr(e)}catch(s){throw new Error(`${r} must be valid hex string, got "${e}". Cause: ${s}`)}else if(jt(e))n=Uint8Array.from(e);else throw new Error(`${r} must be hex string or Uint8Array`);let o=n.length;if(typeof t=="number"&&o!==t)throw new Error(`${r} expected ${t} bytes, got ${o}`);return n}function Ct(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];Qr(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 rg(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 ng(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}var Oa=r=>typeof r=="bigint"&&Ma<=r;function Un(r,e,t){return Oa(r)&&Oa(e)&&Oa(t)&&e<=r&&r<t}function qe(r,e,t,n){if(!Un(e,t,n))throw new Error(`expected valid ${r}: ${t} <= n < ${n}, got ${typeof e} ${e}`)}function og(r){let e;for(e=0;r>Ma;r>>=Fo,e+=1);return e}function sg(r,e){return r>>BigInt(e)&Fo}function ig(r,e,t){return r|(t?Fo:Ma)<<BigInt(e)}var Mn=r=>(Jm<<BigInt(r-1))-Fo,Ua=r=>new Uint8Array(r),Vu=r=>Uint8Array.from(r);function Va(r,e,t){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let n=Ua(r),o=Ua(r),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...l)=>t(o,n,...l),c=(l=Ua())=>{o=a(Vu([0]),l),n=a(),l.length!==0&&(o=a(Vu([1]),l),n=a())},u=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let l=0,p=[];for(;l<e;){n=a();let h=n.slice();p.push(h),l+=n.length}return Ct(...p)};return(l,p)=>{i(),c(l);let h;for(;!(h=p(u()));)c();return i(),h}}var ag={bigint:r=>typeof r=="bigint",function:r=>typeof r=="function",boolean:r=>typeof r=="boolean",string:r=>typeof r=="string",stringOrUint8Array:r=>typeof r=="string"||jt(r),isSafeInteger:r=>Number.isSafeInteger(r),array:r=>Array.isArray(r),field:(r,e)=>e.Fp.isValid(r),hash:r=>typeof r=="function"&&Number.isSafeInteger(r.outputLen)};function gt(r,e,t={}){let n=(o,s,i)=>{let a=ag[s];if(typeof a!="function")throw new Error(`Invalid validator "${s}", expected function`);let c=r[o];if(!(i&&c===void 0)&&!a(c,r))throw new Error(`Invalid param ${String(o)}=${c} (${typeof c}), expected ${s}`)};for(let[o,s]of Object.entries(e))n(o,s,!1);for(let[o,s]of Object.entries(t))n(o,s,!0);return r}var cg=()=>{throw new Error("not implemented")};function br(r){let e=new WeakMap;return(t,...n)=>{let o=e.get(t);if(o!==void 0)return o;let s=r(t,...n);return e.set(t,s),s}}var ge=BigInt(0),ee=BigInt(1),Er=BigInt(2),lg=BigInt(3),Ka=BigInt(4),Hu=BigInt(5),$u=BigInt(8),ug=BigInt(9),fg=BigInt(16);function X(r,e){let t=r%e;return t>=ge?t:e+t}function hg(r,e,t){if(t<=ge||e<ge)throw new Error("Expected power/modulo > 0");if(t===ee)return ge;let n=ee;for(;e>ge;)e&ee&&(n=n*r%t),r=r*r%t,e>>=ee;return n}function te(r,e,t){let n=r;for(;e-- >ge;)n*=n,n%=t;return n}function Ko(r,e){if(r===ge||e<=ge)throw new Error(`invert: expected positive integers, got n=${r} mod=${e}`);let t=X(r,e),n=e,o=ge,s=ee,i=ee,a=ge;for(;t!==ge;){let u=n/t,f=n%t,l=o-i*u,p=s-a*u;n=t,t=f,o=i,s=a,i=l,a=p}if(n!==ee)throw new Error("invert: does not exist");return X(o,e)}function dg(r){let e=(r-ee)/Er,t,n,o;for(t=r-ee,n=0;t%Er===ge;t/=Er,n++);for(o=Er;o<r&&hg(o,e,r)!==r-ee;o++);if(n===1){let i=(r+ee)/Ka;return function(c,u){let f=c.pow(u,i);if(!c.eql(c.sqr(f),u))throw new Error("Cannot find square root");return f}}let s=(t+ee)/Er;return function(a,c){if(a.pow(c,e)===a.neg(a.ONE))throw new Error("Cannot find square root");let u=n,f=a.pow(a.mul(a.ONE,o),t),l=a.pow(c,s),p=a.pow(c,t);for(;!a.eql(p,a.ONE);){if(a.eql(p,a.ZERO))return a.ZERO;let h=1;for(let m=a.sqr(p);h<u&&!a.eql(m,a.ONE);h++)m=a.sqr(m);let d=a.pow(f,ee<<BigInt(u-h-1));f=a.sqr(d),l=a.mul(l,d),p=a.mul(p,f),u=h}return l}}function pg(r){if(r%Ka===lg){let e=(r+ee)/Ka;return function(n,o){let s=n.pow(o,e);if(!n.eql(n.sqr(s),o))throw new Error("Cannot find square root");return s}}if(r%$u===Hu){let e=(r-Hu)/$u;return function(n,o){let s=n.mul(o,Er),i=n.pow(s,e),a=n.mul(o,i),c=n.mul(n.mul(a,Er),i),u=n.mul(a,n.sub(c,n.ONE));if(!n.eql(n.sqr(u),o))throw new Error("Cannot find square root");return u}}return r%fg,dg(r)}var qu=(r,e)=>(X(r,e)&ee)===ee,mg=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ha(r){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=mg.reduce((n,o)=>(n[o]="function",n),e);return gt(r,t)}function gg(r,e,t){if(t<ge)throw new Error("Expected power > 0");if(t===ge)return r.ONE;if(t===ee)return e;let n=r.ONE,o=e;for(;t>ge;)t&ee&&(n=r.mul(n,o)),o=r.sqr(o),t>>=ee;return n}function yg(r,e){let t=new Array(e.length),n=e.reduce((s,i,a)=>r.is0(i)?s:(t[a]=s,r.mul(s,i)),r.ONE),o=r.inv(n);return e.reduceRight((s,i,a)=>r.is0(i)?s:(t[a]=r.mul(s,t[a]),r.mul(s,i)),o),t}function $a(r,e){let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function Ho(r,e,t=!1,n={}){if(r<=ge)throw new Error(`Expected Field ORDER > 0, got ${r}`);let{nBitLength:o,nByteLength:s}=$a(r,e);if(s>2048)throw new Error("Field lengths over 2048 bytes are not supported");let i=pg(r),a=Object.freeze({ORDER:r,BITS:o,BYTES:s,MASK:Mn(o),ZERO:ge,ONE:ee,create:c=>X(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return ge<=c&&c<r},is0:c=>c===ge,isOdd:c=>(c&ee)===ee,neg:c=>X(-c,r),eql:(c,u)=>c===u,sqr:c=>X(c*c,r),add:(c,u)=>X(c+u,r),sub:(c,u)=>X(c-u,r),mul:(c,u)=>X(c*u,r),pow:(c,u)=>gg(a,c,u),div:(c,u)=>X(c*Ko(u,r),r),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>Ko(c,r),sqrt:n.sqrt||(c=>i(a,c)),invertBatch:c=>yg(a,c),cmov:(c,u,f)=>f?u:c,toBytes:c=>t?wr(c,s):Zt(c,s),fromBytes:c=>{if(c.length!==s)throw new Error(`Fp.fromBytes: expected ${s}, got ${c.length}`);return t?Xt(c):Bt(c)}});return Object.freeze(a)}function zu(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let e=r.toString(2).length;return Math.ceil(e/8)}function qa(r){let e=zu(r);return e+Math.ceil(e/2)}function Gu(r,e,t=!1){let n=r.length,o=zu(e),s=qa(e);if(n<16||n<s||n>1024)throw new Error(`expected ${s}-1024 bytes of input, got ${n}`);let i=t?Bt(r):Xt(r),a=X(i,e-ee)+ee;return t?wr(a,o):Zt(a,o)}var bg=BigInt(0),za=BigInt(1),Ga=new WeakMap,Yu=new WeakMap;function $o(r,e){let t=(s,i)=>{let a=i.negate();return s?a:i},n=s=>{if(!Number.isSafeInteger(s)||s<=0||s>e)throw new Error(`Wrong window size=${s}, should be [1..${e}]`)},o=s=>{n(s);let i=Math.ceil(e/s)+1,a=2**(s-1);return{windows:i,windowSize:a}};return{constTimeNegate:t,unsafeLadder(s,i){let a=r.ZERO,c=s;for(;i>bg;)i&za&&(a=a.add(c)),c=c.double(),i>>=za;return a},precomputeWindow(s,i){let{windows:a,windowSize:c}=o(i),u=[],f=s,l=f;for(let p=0;p<a;p++){l=f,u.push(l);for(let h=1;h<c;h++)l=l.add(f),u.push(l);f=l.double()}return u},wNAF(s,i,a){let{windows:c,windowSize:u}=o(s),f=r.ZERO,l=r.BASE,p=BigInt(2**s-1),h=2**s,d=BigInt(s);for(let m=0;m<c;m++){let w=m*u,g=Number(a&p);a>>=d,g>u&&(g-=h,a+=za);let y=w,b=w+Math.abs(g)-1,x=m%2!==0,A=g<0;g===0?l=l.add(t(x,i[y])):f=f.add(t(A,i[b]))}return{p:f,f:l}},wNAFCached(s,i,a){let c=Yu.get(s)||1,u=Ga.get(s);return u||(u=this.precomputeWindow(s,c),c!==1&&Ga.set(s,a(u))),this.wNAF(c,u,i)},setWindowSize(s,i){n(i),Yu.set(s,i),Ga.delete(s)}}}function Fn(r){return Ha(r.Fp),gt(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...$a(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var ct=BigInt(0),ze=BigInt(1),qo=BigInt(2),Eg=BigInt(8),xg={zip215:!0};function vg(r){let e=Fn(r);return gt(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function Wu(r){let e=vg(r),{Fp:t,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=e,u=qo<<BigInt(a*8)-ze,f=t.create,l=e.uvRatio||((S,v)=>{try{return{isValid:!0,value:t.sqrt(S*t.inv(v))}}catch{return{isValid:!1,value:ct}}}),p=e.adjustScalarBytes||(S=>S),h=e.domain||((S,v,T)=>{if(at("phflag",T),v.length||T)throw new Error("Contexts/pre-hash are not supported");return S});function d(S,v){qe("coordinate "+S,v,ct,u)}function m(S){if(!(S instanceof y))throw new Error("ExtendedPoint expected")}let w=br((S,v)=>{let{ex:T,ey:B,ez:P}=S,O=S.is0();v==null&&(v=O?Eg:t.inv(P));let U=f(T*v),z=f(B*v),H=f(P*v);if(O)return{x:ct,y:ze};if(H!==ze)throw new Error("invZ was invalid");return{x:U,y:z}}),g=br(S=>{let{a:v,d:T}=e;if(S.is0())throw new Error("bad point: ZERO");let{ex:B,ey:P,ez:O,et:U}=S,z=f(B*B),H=f(P*P),G=f(O*O),oe=f(G*G),se=f(z*v),$e=f(G*f(se+H)),Ee=f(oe+f(T*f(z*H)));if($e!==Ee)throw new Error("bad point: equation left != right (1)");let me=f(B*P),nt=f(O*U);if(me!==nt)throw new Error("bad point: equation left != right (2)");return!0});class y{constructor(v,T,B,P){this.ex=v,this.ey=T,this.ez=B,this.et=P,d("x",v),d("y",T),d("z",B),d("t",P),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(v){if(v instanceof y)throw new Error("extended point not allowed");let{x:T,y:B}=v||{};return d("x",T),d("y",B),new y(T,B,ze,f(T*B))}static normalizeZ(v){let T=t.invertBatch(v.map(B=>B.ez));return v.map((B,P)=>B.toAffine(T[P])).map(y.fromAffine)}_setWindowSize(v){A.setWindowSize(this,v)}assertValidity(){g(this)}equals(v){m(v);let{ex:T,ey:B,ez:P}=this,{ex:O,ey:U,ez:z}=v,H=f(T*z),G=f(O*P),oe=f(B*z),se=f(U*P);return H===G&&oe===se}is0(){return this.equals(y.ZERO)}negate(){return new y(f(-this.ex),this.ey,this.ez,f(-this.et))}double(){let{a:v}=e,{ex:T,ey:B,ez:P}=this,O=f(T*T),U=f(B*B),z=f(qo*f(P*P)),H=f(v*O),G=T+B,oe=f(f(G*G)-O-U),se=H+U,$e=se-z,Ee=H-U,me=f(oe*$e),nt=f(se*Ee),xe=f(oe*Ee),ot=f($e*se);return new y(me,nt,ot,xe)}add(v){m(v);let{a:T,d:B}=e,{ex:P,ey:O,ez:U,et:z}=this,{ex:H,ey:G,ez:oe,et:se}=v;if(T===BigInt(-1)){let tu=f((O-P)*(G+H)),ru=f((O+P)*(G-H)),sa=f(ru-tu);if(sa===ct)return this.double();let nu=f(U*qo*se),ou=f(z*qo*oe),su=ou+nu,iu=ru+tu,au=ou-nu,fp=f(su*sa),hp=f(iu*au),dp=f(su*au),pp=f(sa*iu);return new y(fp,hp,pp,dp)}let $e=f(P*H),Ee=f(O*G),me=f(z*B*se),nt=f(U*oe),xe=f((P+O)*(H+G)-$e-Ee),ot=nt-me,dr=nt+me,Cn=f(Ee-T*$e),Io=f(xe*ot),cp=f(dr*Cn),lp=f(xe*Cn),up=f(ot*dr);return new y(Io,cp,up,lp)}subtract(v){return this.add(v.negate())}wNAF(v){return A.wNAFCached(this,v,y.normalizeZ)}multiply(v){let T=v;qe("scalar",T,ze,n);let{p:B,f:P}=this.wNAF(T);return y.normalizeZ([B,P])[0]}multiplyUnsafe(v){let T=v;return qe("scalar",T,ct,n),T===ct?x:this.equals(x)||T===ze?this:this.equals(b)?this.wNAF(T).p:A.unsafeLadder(this,T)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return A.unsafeLadder(this,n).is0()}toAffine(v){return w(this,v)}clearCofactor(){let{h:v}=e;return v===ze?this:this.multiplyUnsafe(v)}static fromHex(v,T=!1){let{d:B,a:P}=e,O=t.BYTES;v=le("pointHex",v,O),at("zip215",T);let U=v.slice(),z=v[O-1];U[O-1]=z&-129;let H=Xt(U),G=T?u:t.ORDER;qe("pointHex.y",H,ct,G);let oe=f(H*H),se=f(oe-ze),$e=f(B*oe-P),{isValid:Ee,value:me}=l(se,$e);if(!Ee)throw new Error("Point.fromHex: invalid y coordinate");let nt=(me&ze)===ze,xe=(z&128)!==0;if(!T&&me===ct&&xe)throw new Error("Point.fromHex: x=0 and x_0=1");return xe!==nt&&(me=f(-me)),y.fromAffine({x:me,y:H})}static fromPrivateKey(v){return I(v).point}toRawBytes(){let{x:v,y:T}=this.toAffine(),B=wr(T,t.BYTES);return B[B.length-1]|=v&ze?128:0,B}toHex(){return Tt(this.toRawBytes())}}y.BASE=new y(e.Gx,e.Gy,ze,f(e.Gx*e.Gy)),y.ZERO=new y(ct,ze,ze,ct);let{BASE:b,ZERO:x}=y,A=$o(y,a*8);function R(S){return X(S,n)}function _(S){return R(Xt(S))}function I(S){let v=a;S=le("private key",S,v);let T=le("hashed private key",s(S),2*v),B=p(T.slice(0,v)),P=T.slice(v,2*v),O=_(B),U=b.multiply(O),z=U.toRawBytes();return{head:B,prefix:P,scalar:O,point:U,pointBytes:z}}function $(S){return I(S).pointBytes}function V(S=new Uint8Array,...v){let T=Ct(...v);return _(s(h(T,le("context",S),!!o)))}function K(S,v,T={}){S=le("message",S),o&&(S=o(S));let{prefix:B,scalar:P,pointBytes:O}=I(v),U=V(T.context,B,S),z=b.multiply(U).toRawBytes(),H=V(T.context,z,O,S),G=R(U+H*P);qe("signature.s",G,ct,n);let oe=Ct(z,wr(G,t.BYTES));return le("result",oe,a*2)}let Q=xg;function D(S,v,T,B=Q){let{context:P,zip215:O}=B,U=t.BYTES;S=le("signature",S,2*U),v=le("message",v),O!==void 0&&at("zip215",O),o&&(v=o(v));let z=Xt(S.slice(U,2*U)),H,G,oe;try{H=y.fromHex(T,O),G=y.fromHex(S.slice(0,U),O),oe=b.multiplyUnsafe(z)}catch{return!1}if(!O&&H.isSmallOrder())return!1;let se=V(P,G.toRawBytes(),H.toRawBytes(),v);return G.add(H.multiplyUnsafe(se)).subtract(oe).clearCofactor().equals(y.ZERO)}return b._setWindowSize(8),{CURVE:e,getPublicKey:$,sign:K,verify:D,ExtendedPoint:y,utils:{getExtendedPublicKey:I,randomPrivateKey:()=>i(t.BYTES),precompute(S=8,v=y.BASE){return v._setWindowSize(S),v.multiply(BigInt(3)),v}}}}var Ya=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),ju=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),px=BigInt(0),_g=BigInt(1),Xu=BigInt(2),mx=BigInt(3),Ag=BigInt(5),Sg=BigInt(8);function Rg(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=Ya,a=r*r%s*r%s,c=te(a,Xu,s)*a%s,u=te(c,_g,s)*r%s,f=te(u,Ag,s)*u%s,l=te(f,e,s)*f%s,p=te(l,t,s)*l%s,h=te(p,n,s)*p%s,d=te(h,o,s)*h%s,m=te(d,o,s)*h%s,w=te(m,e,s)*f%s;return{pow_p_5_8:te(w,Xu,s)*r%s,b2:a}}function Ig(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function Tg(r,e){let t=Ya,n=X(e*e*e,t),o=X(n*n*e,t),s=Rg(r*o).pow_p_5_8,i=X(r*n*s,t),a=X(e*i*i,t),c=i,u=X(i*ju,t),f=a===r,l=a===X(-r,t),p=a===X(-r*ju,t);return f&&(i=c),(l||p)&&(i=u),qu(i,t)&&(i=X(-i,t)),{isValid:f||l,value:i}}var Bg=Ho(Ya,void 0,!0),Cg={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Bg,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:Sg,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:On,randomBytes:Xr,adjustScalarBytes:Ig,uvRatio:Tg},Jr=Wu(Cg);var en=32,kt=64,zo=32;function Zu(){let r=Jr.utils.randomPrivateKey(),e=Jr.getPublicKey(r);return{privateKey:tf(r,e),publicKey:e}}function Qu(r){if(r.length!==zo)throw new TypeError('"seed" must be 32 bytes in length.');if(!(r instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');let e=r,t=Jr.getPublicKey(e);return{privateKey:tf(e,t),publicKey:t}}function Ju(r,e){let t=r.subarray(0,zo);return Jr.sign(e instanceof Uint8Array?e:e.subarray(),t)}function ef(r,e,t){return Jr.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}function tf(r,e){let t=new Uint8Array(kt);for(let n=0;n<zo;n++)t[n]=r[n],t[zo+n]=e[n];return t}var Ue={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw Object.assign(new Error("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"),{code:"ERR_MISSING_WEB_CRYPTO"});return e}};var Wa={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function rf(r){let e=r?.algorithm??"AES-GCM",t=r?.keyLength??16,n=r?.nonceLength??12,o=r?.digest??"SHA-256",s=r?.saltLength??16,i=r?.iterations??32767,a=Ue.get();t*=8;async function c(l,p){let h=a.getRandomValues(new Uint8Array(s)),d=a.getRandomValues(new Uint8Array(n)),m={name:e,iv:d};typeof p=="string"&&(p=L(p));let w;if(p.length===0){w=await a.subtle.importKey("jwk",Wa,{name:"AES-GCM"},!0,["encrypt"]);try{let y={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},b=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);w=await a.subtle.deriveKey(y,b,{name:e,length:t},!0,["encrypt"])}catch{w=await a.subtle.importKey("jwk",Wa,{name:"AES-GCM"},!0,["encrypt"])}}else{let y={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},b=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);w=await a.subtle.deriveKey(y,b,{name:e,length:t},!0,["encrypt"])}let g=await a.subtle.encrypt(m,w,l);return Re([h,m.iv,new Uint8Array(g)])}async function u(l,p){let h=l.subarray(0,s),d=l.subarray(s,s+n),m=l.subarray(s+n),w={name:e,iv:d};typeof p=="string"&&(p=L(p));let g;if(p.length===0)try{let b={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},x=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(b,x,{name:e,length:t},!0,["decrypt"])}catch{g=await a.subtle.importKey("jwk",Wa,{name:"AES-GCM"},!0,["decrypt"])}else{let b={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},x=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(b,x,{name:e,length:t},!0,["decrypt"])}let y=await a.subtle.decrypt(w,g,m);return new Uint8Array(y)}return{encrypt:c,decrypt:u}}async function tn(r,e){let n=await rf().encrypt(r,e);return Dn.encode(n)}var Lg=Math.pow(2,7),Dg=Math.pow(2,14),Pg=Math.pow(2,21),ja=Math.pow(2,28),Xa=Math.pow(2,35),Za=Math.pow(2,42),Qa=Math.pow(2,49),W=128,Ne=127;function de(r){if(r<Lg)return 1;if(r<Dg)return 2;if(r<Pg)return 3;if(r<ja)return 4;if(r<Xa)return 5;if(r<Za)return 6;if(r<Qa)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Ja(r,e,t=0){switch(de(r)){case 8:e[t++]=r&255|W,r/=128;case 7:e[t++]=r&255|W,r/=128;case 6:e[t++]=r&255|W,r/=128;case 5:e[t++]=r&255|W,r/=128;case 4:e[t++]=r&255|W,r>>>=7;case 3:e[t++]=r&255|W,r>>>=7;case 2:e[t++]=r&255|W,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function Og(r,e,t=0){switch(de(r)){case 8:e.set(t++,r&255|W),r/=128;case 7:e.set(t++,r&255|W),r/=128;case 6:e.set(t++,r&255|W),r/=128;case 5:e.set(t++,r&255|W),r/=128;case 4:e.set(t++,r&255|W),r>>>=7;case 3:e.set(t++,r&255|W),r>>>=7;case 2:e.set(t++,r&255|W),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function ec(r,e){let t=r[e],n=0;if(n+=t&Ne,t<W||(t=r[e+1],n+=(t&Ne)<<7,t<W)||(t=r[e+2],n+=(t&Ne)<<14,t<W)||(t=r[e+3],n+=(t&Ne)<<21,t<W)||(t=r[e+4],n+=(t&Ne)*ja,t<W)||(t=r[e+5],n+=(t&Ne)*Xa,t<W)||(t=r[e+6],n+=(t&Ne)*Za,t<W)||(t=r[e+7],n+=(t&Ne)*Qa,t<W))return n;throw new RangeError("Could not decode varint")}function Ug(r,e){let t=r.get(e),n=0;if(n+=t&Ne,t<W||(t=r.get(e+1),n+=(t&Ne)<<7,t<W)||(t=r.get(e+2),n+=(t&Ne)<<14,t<W)||(t=r.get(e+3),n+=(t&Ne)<<21,t<W)||(t=r.get(e+4),n+=(t&Ne)*ja,t<W)||(t=r.get(e+5),n+=(t&Ne)*Xa,t<W)||(t=r.get(e+6),n+=(t&Ne)*Za,t<W)||(t=r.get(e+7),n+=(t&Ne)*Qa,t<W))return n;throw new RangeError("Could not decode varint")}function Le(r,e,t=0){return e==null&&(e=ke(de(r))),e instanceof Uint8Array?Ja(r,e,t):Og(r,e,t)}function lt(r,e=0){return r instanceof Uint8Array?ec(r,e):Ug(r,e)}var tc=new Float32Array([-0]),Qt=new Uint8Array(tc.buffer);function nf(r,e,t){tc[0]=r,e[t]=Qt[0],e[t+1]=Qt[1],e[t+2]=Qt[2],e[t+3]=Qt[3]}function of(r,e){return Qt[0]=r[e],Qt[1]=r[e+1],Qt[2]=r[e+2],Qt[3]=r[e+3],tc[0]}var rc=new Float64Array([-0]),De=new Uint8Array(rc.buffer);function sf(r,e,t){rc[0]=r,e[t]=De[0],e[t+1]=De[1],e[t+2]=De[2],e[t+3]=De[3],e[t+4]=De[4],e[t+5]=De[5],e[t+6]=De[6],e[t+7]=De[7]}function af(r,e){return De[0]=r[e],De[1]=r[e+1],De[2]=r[e+2],De[3]=r[e+3],De[4]=r[e+4],De[5]=r[e+5],De[6]=r[e+6],De[7]=r[e+7],rc[0]}var Mg=BigInt(Number.MAX_SAFE_INTEGER),Fg=BigInt(Number.MIN_SAFE_INTEGER),We=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 vr;if(e<Mg&&e>Fg)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>cf&&(o=0n,++n>cf&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return vr;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):vr}},vr=new We(0,0);vr.toBigInt=function(){return 0n};vr.zzEncode=vr.zzDecode=function(){return this};vr.length=function(){return 1};var cf=4294967296n;function lf(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 uf(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 nc(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 ut(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Go(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var oc=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,ut(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 ut(this,4);return Go(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw ut(this,4);return Go(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw ut(this,4);let e=of(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw ut(this,4);let e=af(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 ut(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return uf(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw ut(this,e);this.pos+=e}else do if(this.pos>=this.len)throw ut(this);while(this.buf[this.pos++]&128);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 We(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 ut(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 ut(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 ut(this,8);let e=Go(this.buf,this.pos+=4),t=Go(this.buf,this.pos+=4);return new We(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=ec(this.buf,this.pos);return this.pos+=de(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function sc(r){return new oc(r instanceof Uint8Array?r:r.subarray())}function Me(r,e,t){let n=sc(r);return e.decode(n,void 0,t)}function ic(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return ke(i);o+i>e&&(n=ke(e),o=0);let a=n.subarray(o,o+=i);return o&7&&(o=(o|7)+1),a}}var _r=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function ac(){}var lc=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},Vg=ic();function Kg(r){return globalThis.Buffer!=null?ke(r):Vg(r)}var Kn=class{len;head;tail;states;constructor(){this.len=0,this.head=new _r(ac,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new _r(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new uc((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(Yo,10,We.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=We.fromBigInt(e);return this._push(Yo,t.length(),t)}uint64Number(e){return this._push(Ja,de(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=We.fromBigInt(e).zzEncode();return this._push(Yo,t.length(),t)}sint64Number(e){let t=We.fromNumber(e).zzEncode();return this._push(Yo,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(cc,1,e?1:0)}fixed32(e){return this._push(Vn,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=We.fromBigInt(e);return this._push(Vn,4,t.lo)._push(Vn,4,t.hi)}fixed64Number(e){let t=We.fromNumber(e);return this._push(Vn,4,t.lo)._push(Vn,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(nf,4,e)}double(e){return this._push(sf,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(cc,1,0):this.uint32(t)._push($g,t,e)}string(e){let t=lf(e);return t!==0?this.uint32(t)._push(nc,t,e):this._push(cc,1,0)}fork(){return this.states=new lc(this),this.head=this.tail=new _r(ac,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 _r(ac,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=Kg(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function cc(r,e,t){e[t]=r&255}function Hg(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var uc=class extends _r{next;constructor(e,t){super(Hg,e,t),this.next=void 0}};function Yo(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 Vn(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 $g(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(Kn.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(qg,e,r),this},Kn.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(zg,e,r),this});function qg(r,e,t){e.set(r,t)}function zg(r,e,t){r.length<40?nc(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(L(r),t)}function fc(){return new Kn}function Fe(r,e){let t=fc();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var rn;(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"})(rn||(rn={}));function Wo(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function hc(r){function e(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let t=function(s,i){let a=e(s);i.int32(a)},n=function(s){let i=s.int32();return e(i)};return Wo("enum",rn.VARINT,t,n)}function Ve(r,e){return Wo("message",rn.LENGTH_DELIMITED,r,e)}var re;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.Secp256k1="Secp256k1"})(re||(re={}));var dc;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.Secp256k1=2]="Secp256k1"})(dc||(dc={}));(function(r){r.codec=()=>hc(dc)})(re||(re={}));var yt;(function(r){let e;r.codec=()=>(e==null&&(e=Ve((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),re.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.Type=re.codec().decode(t);break;case 2:o.Data=t.bytes();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Fe(t,r.codec()),r.decode=t=>Me(t,r.codec())})(yt||(yt={}));var wt;(function(r){let e;r.codec=()=>(e==null&&(e=Ve((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),re.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.Type=re.codec().decode(t);break;case 2:o.Data=t.bytes();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Fe(t,r.codec()),r.decode=t=>Me(t,r.codec())})(wt||(wt={}));var Hn=class{_key;constructor(e){this._key=nn(e,en)}verify(e,t){return ef(this._key,t,e)}marshal(){return this._key}get bytes(){return yt.encode({Type:re.Ed25519,Data:this.marshal()}).subarray()}equals(e){return J(this.bytes,e.bytes)}hash(){let e=Se.digest(this.bytes);return Je(e)?e.then(({bytes:t})=>t):e.bytes}},Ar=class{_key;_publicKey;constructor(e,t){this._key=nn(e,kt),this._publicKey=nn(t,en)}sign(e){return Ju(this._key,e)}get public(){return new Hn(this._publicKey)}marshal(){return this._key}get bytes(){return wt.encode({Type:re.Ed25519,Data:this.marshal()}).subarray()}equals(e){return J(this.bytes,e.bytes)}async hash(){let e=Se.digest(this.bytes),t;return Je(e)?{bytes:t}=await e:t=e.bytes,t}async id(){let e=Rt.digest(this.public.bytes);return ae.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if(t==="libp2p-key")return tn(this.bytes,e);throw new E(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function Gg(r){if(r.length>kt){r=nn(r,kt+en);let n=r.subarray(0,kt),o=r.subarray(kt,r.length);return new Ar(n,o)}r=nn(r,kt);let e=r.subarray(0,kt),t=r.subarray(en);return new Ar(e,t)}function Yg(r){return r=nn(r,en),new Hn(r)}async function Wg(){let{privateKey:r,publicKey:e}=Zu();return new Ar(r,e)}async function hf(r){let{privateKey:e,publicKey:t}=Qu(r);return new Ar(e,t)}function nn(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new E(`Key must be a Uint8Array of length ${e}, got ${r.length}`,"ERR_INVALID_KEY_TYPE");return r}function F(r,e="utf8"){let t=Do[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var Ac={};ve(Ac,{MAX_RSA_KEY_SIZE:()=>eo,RsaPrivateKey:()=>ln,RsaPublicKey:()=>Jn,fromJwk:()=>x0,generateKeyPair:()=>v0,unmarshalRsaPrivateKey:()=>vc,unmarshalRsaPublicKey:()=>E0});function et(r){if(isNaN(r)||r<=0)throw new E("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return Xr(r)}var rr={};ve(rr,{exportToPem:()=>m0,importFromPem:()=>g0,jwkToPkcs1:()=>f0,jwkToPkix:()=>d0,pkcs1ToJwk:()=>u0,pkixToJwk:()=>h0});var Xo=class extends Wr{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Po(e);let n=Gt(t);if(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 o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?e.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=e.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),s.fill(0)}update(e){return Yr(this),this.iHash.update(e),this}digestInto(e){Yr(this),Gr(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){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}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},$n=(r,e,t)=>new Xo(r,e).update(t).digest();$n.create=(r,e)=>new Xo(r,e);function jg(r,e,t,n){Po(r);let o=Pu({dkLen:32,asyncTick:10},n),{c:s,dkLen:i,asyncTick:a}=o;if(zr(s),zr(i),zr(a),s<1)throw new Error("PBKDF2: iterations (c) should be >= 1");let c=Gt(e),u=Gt(t),f=new Uint8Array(i),l=$n.create(r,c),p=l._cloneInto().update(u);return{c:s,dkLen:i,asyncTick:a,DK:f,PRF:l,PRFSalt:p}}function Xg(r,e,t,n,o){return r.destroy(),e.destroy(),n&&n.destroy(),o.fill(0),t}async function mc(r,e,t,n){let{c:o,dkLen:s,asyncTick:i,DK:a,PRF:c,PRFSalt:u}=jg(r,e,t,n),f,l=new Uint8Array(4),p=jr(l),h=new Uint8Array(c.outputLen);for(let d=1,m=0;m<s;d++,m+=c.outputLen){let w=a.subarray(m,m+c.outputLen);p.setInt32(0,d,!1),(f=u._cloneInto(f)).update(l).digestInto(h),w.set(h.subarray(0,w.length)),await Lu(o-1,i,()=>{c._cloneInto(f).update(h).digestInto(h);for(let g=0;g<w.length;g++)w[g]^=h[g]})}return Xg(c,u,a,f,h)}var q=pr(df());function Sr(r,e){let t=0;if(r.length===1)return r[0];for(let n=r.length-1;n>=0;n--)t+=r[r.length-1-n]*Math.pow(2,e*n);return t}function Jt(r,e,t=-1){let n=t,o=r,s=0,i=Math.pow(2,e);for(let a=1;a<8;a++){if(r<i){let c;if(n<0)c=new ArrayBuffer(a),s=a;else{if(n<a)return new ArrayBuffer(0);c=new ArrayBuffer(n),s=n}let u=new Uint8Array(c);for(let f=a-1;f>=0;f--){let l=Math.pow(2,f*e);u[s-f-1]=Math.floor(o/l),o-=u[s-f-1]*l}return c}i*=Math.pow(2,e)}return new ArrayBuffer(0)}function Jo(...r){let e=0,t=0;for(let s of r)e+=s.length;let n=new ArrayBuffer(e),o=new Uint8Array(n);for(let s of r)o.set(s,t),t+=s.length;return o}function yc(){let r=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){let a=r[0]===255&&r[1]&128,c=r[0]===0&&(r[1]&128)===0;(a||c)&&this.warnings.push("Needlessly long format")}let e=new ArrayBuffer(this.valueHex.byteLength),t=new Uint8Array(e);for(let a=0;a<this.valueHex.byteLength;a++)t[a]=0;t[0]=r[0]&128;let n=Sr(t,8),o=new ArrayBuffer(this.valueHex.byteLength),s=new Uint8Array(o);for(let a=0;a<this.valueHex.byteLength;a++)s[a]=r[a];return s[0]&=127,Sr(s,8)-n}function pf(r){let e=r<0?r*-1:r,t=128;for(let n=1;n<8;n++){if(e<=t){if(r<0){let i=t-e,a=Jt(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=Jt(e,8,n),s=new Uint8Array(o);if(s[0]&128){let i=o.slice(0),a=new Uint8Array(i);o=new ArrayBuffer(o.byteLength+1),s=new Uint8Array(o);for(let c=0;c<i.byteLength;c++)s[c+1]=a[c];s[0]=0}return o}t*=Math.pow(2,8)}return new ArrayBuffer(0)}function mf(r,e){if(r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let o=0;o<t.length;o++)if(t[o]!==n[o])return!1;return!0}function Ge(r,e){let t=r.toString(10);if(e<t.length)return"";let n=e-t.length,o=new Array(n);for(let i=0;i<n;i++)o[i]="0";return o.join("").concat(t)}var _1=Math.log(2);function es(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function wc(r){let e=0,t=0;for(let o=0;o<r.length;o++){let s=r[o];e+=s.byteLength}let n=new Uint8Array(e);for(let o=0;o<r.length;o++){let s=r[o];n.set(new Uint8Array(s),t),t+=s.byteLength}return n.buffer}function Ot(r,e,t,n){return e instanceof Uint8Array?e.byteLength?t<0?(r.error="Wrong parameter: inputOffset less than zero",!1):n<0?(r.error="Wrong parameter: inputLength less than zero",!1):e.byteLength-t-n<0?(r.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):!0:(r.error="Wrong parameter: inputBuffer has zero length",!1):(r.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}var zn=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return wc(this.items)}},qn=[new Uint8Array([1])],gf="0123456789";var an="",ht=new ArrayBuffer(0),bc=new Uint8Array(0),Gn="EndOfContent",wf="OCTET STRING",bf="BIT STRING";function Ut(r){var e;return e=class extends r{constructor(...n){var o;super(...n);let s=n[0]||{};this.isHexOnly=(o=s.isHexOnly)!==null&&o!==void 0?o:!1,this.valueHexView=s.valueHex?q.BufferSourceConverter.toUint8Array(s.valueHex):bc}get valueHex(){return this.valueHexView.slice().buffer}set valueHex(n){this.valueHexView=new Uint8Array(n)}fromBER(n,o,s){let i=n instanceof ArrayBuffer?new Uint8Array(n):n;if(!Ot(this,i,o,s))return-1;let a=o+s;return this.valueHexView=i.subarray(o,a),this.valueHexView.length?(this.blockLength=s,a):(this.warnings.push("Zero buffer length"),o)}toBER(n=!1){return this.isHexOnly?n?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",ht)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:q.Convert.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}var Lt=class{constructor({blockLength:e=0,error:t=an,warnings:n=[],valueBeforeDecode:o=bc}={}){this.blockLength=e,this.error=t,this.warnings=n,this.valueBeforeDecodeView=q.BufferSourceConverter.toUint8Array(o)}static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:q.Convert.ToHex(this.valueBeforeDecodeView)}}};Lt.NAME="baseBlock";var Pe=class extends Lt{fromBER(e,t,n){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,t){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}};Pe.NAME="valueBlock";var ts=class extends Ut(Lt){constructor({idBlock:e={}}={}){var t,n,o,s;super(),e?(this.isHexOnly=(t=e.isHexOnly)!==null&&t!==void 0?t:!1,this.valueHexView=e.valueHex?q.BufferSourceConverter.toUint8Array(e.valueHex):bc,this.tagClass=(n=e.tagClass)!==null&&n!==void 0?n:-1,this.tagNumber=(o=e.tagNumber)!==null&&o!==void 0?o:-1,this.isConstructed=(s=e.isConstructed)!==null&&s!==void 0?s:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(e=!1){let t=0;switch(this.tagClass){case 1:t|=0;break;case 2:t|=64;break;case 3:t|=128;break;case 4:t|=192;break;default:return this.error="Unknown tag class",ht}if(this.isConstructed&&(t|=32),this.tagNumber<31&&!this.isHexOnly){let o=new Uint8Array(1);if(!e){let s=this.tagNumber;s&=31,t|=s,o[0]=t}return o.buffer}if(!this.isHexOnly){let o=Jt(this.tagNumber,7),s=new Uint8Array(o),i=o.byteLength,a=new Uint8Array(i+1);if(a[0]=t|31,!e){for(let c=0;c<i-1;c++)a[c+1]=s[c]|128;a[i]=s[i-1]}return a.buffer}let n=new Uint8Array(this.valueHexView.byteLength+1);if(n[0]=t|31,!e){let o=this.valueHexView;for(let s=0;s<o.length-1;s++)n[s+1]=o[s]|128;n[this.valueHexView.byteLength]=o[o.length-1]}return n.buffer}fromBER(e,t,n){let o=q.BufferSourceConverter.toUint8Array(e);if(!Ot(this,o,t,n))return-1;let s=o.subarray(t,t+n);if(s.length===0)return this.error="Zero buffer length",-1;switch(s[0]&192){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=(s[0]&32)===32,this.isHexOnly=!1;let a=s[0]&31;if(a!==31)this.tagNumber=a,this.blockLength=1;else{let c=1,u=this.valueHexView=new Uint8Array(255),f=255;for(;s[c]&128;){if(u[c-1]=s[c]&127,c++,c>=s.length)return this.error="End of input reached before message was fully decoded",-1;if(c===f){f+=255;let p=new Uint8Array(f);for(let h=0;h<u.length;h++)p[h]=u[h];u=this.valueHexView=new Uint8Array(f)}}this.blockLength=c+1,u[c-1]=s[c]&127;let l=new Uint8Array(c);for(let p=0;p<c;p++)l[p]=u[p];u=this.valueHexView=new Uint8Array(c),u.set(l),this.blockLength<=9?this.tagNumber=Sr(u,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(this.tagClass===1&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return t+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}};ts.NAME="identificationBlock";var rs=class extends Lt{constructor({lenBlock:e={}}={}){var t,n,o;super(),this.isIndefiniteForm=(t=e.isIndefiniteForm)!==null&&t!==void 0?t:!1,this.longFormUsed=(n=e.longFormUsed)!==null&&n!==void 0?n:!1,this.length=(o=e.length)!==null&&o!==void 0?o:0}fromBER(e,t,n){let o=q.BufferSourceConverter.toUint8Array(e);if(!Ot(this,o,t,n))return-1;let s=o.subarray(t,t+n);if(s.length===0)return this.error="Zero buffer length",-1;if(s[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=s[0]===128,this.isIndefiniteForm)return this.blockLength=1,t+this.blockLength;if(this.longFormUsed=!!(s[0]&128),this.longFormUsed===!1)return this.length=s[0],this.blockLength=1,t+this.blockLength;let i=s[0]&127;if(i>8)return this.error="Too big integer",-1;if(i+1>s.length)return this.error="End of input reached before message was fully decoded",-1;let a=t+1,c=o.subarray(a,a+i);return c[i-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=Sr(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=i+1,t+this.blockLength}toBER(e=!1){let t,n;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=128),t;if(this.longFormUsed){let o=Jt(this.length,8);if(o.byteLength>127)return this.error="Too big length",ht;if(t=new ArrayBuffer(o.byteLength+1),e)return t;let s=new Uint8Array(o);n=new Uint8Array(t),n[0]=o.byteLength|128;for(let i=0;i<o.byteLength;i++)n[i+1]=s[i];return t}return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=this.length),t}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}};rs.NAME="lengthBlock";var C={},Ie=class extends Lt{constructor({name:e=an,optional:t=!1,primitiveSchema:n,...o}={},s){super(o),this.name=e,this.optional=t,n&&(this.primitiveSchema=n),this.idBlock=new ts(o),this.lenBlock=new rs(o),this.valueBlock=s?new s(o):new Pe(o)}fromBER(e,t,n){let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}toBER(e,t){let n=t||new zn;t||Ef(this);let o=this.idBlock.toBER(e);if(n.write(o),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,n),n.write(new ArrayBuffer(2));else{let s=this.valueBlock.toBER(e);this.lenBlock.length=s.byteLength;let i=this.lenBlock.toBER(e);n.write(i),n.write(s)}return t?ht:n.final()}toJSON(){let e={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(e.primitiveSchema=this.primitiveSchema.toJSON()),e}toString(e="ascii"){return e==="ascii"?this.onAsciiEncoding():q.Convert.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${q.Convert.ToHex(this.valueBlock.valueBeforeDecodeView)}`}isEqual(e){if(this===e)return!0;if(!(e instanceof this.constructor))return!1;let t=this.toBER(),n=e.toBER();return mf(t,n)}};Ie.NAME="BaseBlock";function Ef(r){if(r instanceof C.Constructed)for(let e of r.valueBlock.value)Ef(e)&&(r.lenBlock.isIndefiniteForm=!0);return!!r.lenBlock.isIndefiniteForm}var ns=class extends Ie{constructor({value:e=an,...t}={},n){super(t,n),e&&this.fromString(e)}getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}fromBER(e,t,n){let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}};ns.NAME="BaseStringBlock";var os=class extends Ut(Pe){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};os.NAME="PrimitiveValueBlock";var xf,ss=class extends Ie{constructor(e={}){super(e,os),this.idBlock.isConstructed=!1}};xf=ss;C.Primitive=xf;ss.NAME="PRIMITIVE";function s0(r,e){if(r instanceof e)return r;let t=new e;return t.idBlock=r.idBlock,t.lenBlock=r.lenBlock,t.warnings=r.warnings,t.valueBeforeDecodeView=r.valueBeforeDecodeView,t}function Ms(r,e=0,t=r.length){let n=e,o=new Ie({},Pe),s=new Lt;if(!Ot(s,r,e,t))return o.error=s.error,{offset:-1,result:o};if(!r.subarray(e,e+t).length)return o.error="Zero buffer length",{offset:-1,result:o};let a=o.idBlock.fromBER(r,e,t);if(o.idBlock.warnings.length&&o.warnings.concat(o.idBlock.warnings),a===-1)return o.error=o.idBlock.error,{offset:-1,result:o};if(e=a,t-=o.idBlock.blockLength,a=o.lenBlock.fromBER(r,e,t),o.lenBlock.warnings.length&&o.warnings.concat(o.lenBlock.warnings),a===-1)return o.error=o.lenBlock.error,{offset:-1,result:o};if(e=a,t-=o.lenBlock.blockLength,!o.idBlock.isConstructed&&o.lenBlock.isIndefiniteForm)return o.error="Indefinite length form used for primitive encoding form",{offset:-1,result:o};let c=Ie;switch(o.idBlock.tagClass){case 1:if(o.idBlock.tagNumber>=37&&o.idBlock.isHexOnly===!1)return o.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:o};switch(o.idBlock.tagNumber){case 0:if(o.idBlock.isConstructed&&o.lenBlock.length>0)return o.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:o};c=C.EndOfContent;break;case 1:c=C.Boolean;break;case 2:c=C.Integer;break;case 3:c=C.BitString;break;case 4:c=C.OctetString;break;case 5:c=C.Null;break;case 6:c=C.ObjectIdentifier;break;case 10:c=C.Enumerated;break;case 12:c=C.Utf8String;break;case 13:c=C.RelativeObjectIdentifier;break;case 14:c=C.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:c=C.Sequence;break;case 17:c=C.Set;break;case 18:c=C.NumericString;break;case 19:c=C.PrintableString;break;case 20:c=C.TeletexString;break;case 21:c=C.VideotexString;break;case 22:c=C.IA5String;break;case 23:c=C.UTCTime;break;case 24:c=C.GeneralizedTime;break;case 25:c=C.GraphicString;break;case 26:c=C.VisibleString;break;case 27:c=C.GeneralString;break;case 28:c=C.UniversalString;break;case 29:c=C.CharacterString;break;case 30:c=C.BmpString;break;case 31:c=C.DATE;break;case 32:c=C.TimeOfDay;break;case 33:c=C.DateTime;break;case 34:c=C.Duration;break;default:{let u=o.idBlock.isConstructed?new C.Constructed:new C.Primitive;u.idBlock=o.idBlock,u.lenBlock=o.lenBlock,u.warnings=o.warnings,o=u}}break;case 2:case 3:case 4:default:c=o.idBlock.isConstructed?C.Constructed:C.Primitive}return o=s0(o,c),a=o.fromBER(r,e,o.lenBlock.isIndefiniteForm?t:o.lenBlock.length),o.valueBeforeDecodeView=r.subarray(n,n+o.blockLength),{offset:a,result:o}}function cn(r){if(!r.byteLength){let e=new Ie({},Pe);return e.error="Input buffer has zero length",{offset:-1,result:e}}return Ms(q.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function i0(r,e){return r?1:e}var bt=class extends Pe{constructor({value:e=[],isIndefiniteForm:t=!1,...n}={}){super(n),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,n){let o=q.BufferSourceConverter.toUint8Array(e);if(!Ot(this,o,t,n))return-1;if(this.valueBeforeDecodeView=o.subarray(t,t+n),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),t;let s=t;for(;i0(this.isIndefiniteForm,n)>0;){let i=Ms(o,s,n);if(i.offset===-1)return this.error=i.result.error,this.warnings.concat(i.result.warnings),-1;if(s=i.offset,this.blockLength+=i.result.blockLength,n-=i.result.blockLength,this.value.push(i.result),this.isIndefiniteForm&&i.result.constructor.NAME===Gn)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===Gn?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(e,t){let n=t||new zn;for(let o=0;o<this.value.length;o++)this.value[o].toBER(e,n);return t?ht:n.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}};bt.NAME="ConstructedValueBlock";var vf,er=class extends Ie{constructor(e={}){super(e,bt),this.idBlock.isConstructed=!0}fromBER(e,t,n){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){let e=[];for(let n of this.valueBlock.value)e.push(n.toString("ascii").split(`
|
|
2
|
+
"use strict";var Libp2P=(()=>{var Kp=Object.create;var No=Object.defineProperty;var qp=Object.getOwnPropertyDescriptor;var zp=Object.getOwnPropertyNames;var Gp=Object.getPrototypeOf,Wp=Object.prototype.hasOwnProperty;var Qe=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Re=(r,e)=>{for(var t in e)No(r,t,{get:e[t],enumerable:!0})},Nu=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of zp(e))!Wp.call(r,o)&&o!==t&&No(r,o,{get:()=>e[o],enumerable:!(n=qp(e,o))||n.enumerable});return r};var sr=(r,e,t)=>(t=r!=null?Kp(Gp(r)):{},Nu(e||!r||!r.__esModule?No(t,"default",{value:r,enumerable:!0}):t,r)),jp=r=>Nu(No({},"__esModule",{value:!0}),r);var Mf=Qe(Yr=>{"use strict";var y0="[object ArrayBuffer]",Ct=class r{static isArrayBuffer(e){return Object.prototype.toString.call(e)===y0}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,t){if(e.constructor===t)return e;if(this.isArrayBuffer(e))return new t(e);if(this.isArrayBufferView(e))return new t(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(e,t){let n=r.toUint8Array(e),o=r.toUint8Array(t);if(n.length!==o.byteLength)return!1;for(let s=0;s<n.length;s++)if(n[s]!==o[s])return!1;return!0}static concat(...e){let t;Array.isArray(e[0])&&!(e[1]instanceof Function)||Array.isArray(e[0])&&e[1]instanceof Function?t=e[0]:e[e.length-1]instanceof Function?t=e.slice(0,e.length-1):t=e;let n=0;for(let i of t)n+=i.byteLength;let o=new Uint8Array(n),s=0;for(let i of t){let a=this.toUint8Array(i);o.set(a,s),s+=a.length}return e[e.length-1]instanceof Function?this.toView(o,e[e.length-1]):o.buffer}},zc="string",w0=/^[0-9a-f]+$/i,b0=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,x0=/^[a-zA-Z0-9-_]+$/,ls=class{static fromString(e){let t=unescape(encodeURIComponent(e)),n=new Uint8Array(t.length);for(let o=0;o<t.length;o++)n[o]=t.charCodeAt(o);return n.buffer}static toString(e){let t=Ct.toUint8Array(e),n="";for(let s=0;s<t.length;s++)n+=String.fromCharCode(t[s]);return decodeURIComponent(escape(n))}},Ze=class{static toString(e,t=!1){let n=Ct.toArrayBuffer(e),o=new DataView(n),s="";for(let i=0;i<n.byteLength;i+=2){let a=o.getUint16(i,t);s+=String.fromCharCode(a)}return s}static fromString(e,t=!1){let n=new ArrayBuffer(e.length*2),o=new DataView(n);for(let s=0;s<e.length;s++)o.setUint16(s*2,e.charCodeAt(s),t);return n}},us=class r{static isHex(e){return typeof e===zc&&w0.test(e)}static isBase64(e){return typeof e===zc&&b0.test(e)}static isBase64Url(e){return typeof e===zc&&x0.test(e)}static ToString(e,t="utf8"){let n=Ct.toUint8Array(e);switch(t.toLowerCase()){case"utf8":return this.ToUtf8String(n);case"binary":return this.ToBinary(n);case"hex":return this.ToHex(n);case"base64":return this.ToBase64(n);case"base64url":return this.ToBase64Url(n);case"utf16le":return Ze.toString(n,!0);case"utf16":case"utf16be":return Ze.toString(n);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromString(e,t="utf8"){if(!e)return new ArrayBuffer(0);switch(t.toLowerCase()){case"utf8":return this.FromUtf8String(e);case"binary":return this.FromBinary(e);case"hex":return this.FromHex(e);case"base64":return this.FromBase64(e);case"base64url":return this.FromBase64Url(e);case"utf16le":return Ze.fromString(e,!0);case"utf16":case"utf16be":return Ze.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){let t=Ct.toUint8Array(e);if(typeof btoa<"u"){let n=this.ToString(t,"binary");return btoa(n)}else return Buffer.from(t).toString("base64")}static FromBase64(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isBase64(t))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return typeof atob<"u"?this.FromBinary(atob(t)):new Uint8Array(Buffer.from(t,"base64")).buffer}static FromBase64Url(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isBase64Url(t))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(t.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(e){return this.ToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(e,t=r.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.FromBinary(e);case"utf8":return ls.fromString(e);case"utf16":case"utf16be":return Ze.fromString(e);case"utf16le":case"usc2":return Ze.fromString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToUtf8String(e,t=r.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.ToBinary(e);case"utf8":return ls.toString(e);case"utf16":case"utf16be":return Ze.toString(e);case"utf16le":case"usc2":return Ze.toString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromBinary(e){let t=e.length,n=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=e.charCodeAt(o);return n.buffer}static ToBinary(e){let t=Ct.toUint8Array(e),n="";for(let o=0;o<t.length;o++)n+=String.fromCharCode(t[o]);return n}static ToHex(e){let t=Ct.toUint8Array(e),n="",o=t.length;for(let s=0;s<o;s++){let i=t[s];i<16&&(n+="0"),n+=i.toString(16)}return n}static FromHex(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isHex(t))throw new TypeError("Argument 'hexString' is not HEX encoded");t.length%2&&(t=`0${t}`);let n=new Uint8Array(t.length/2);for(let o=0;o<t.length;o=o+2){let s=t.slice(o,o+2);n[o/2]=parseInt(s,16)}return n.buffer}static ToUtf16String(e,t=!1){return Ze.toString(e,t)}static FromUtf16String(e,t=!1){return Ze.fromString(e,t)}static Base64Padding(e){let t=4-e.length%4;if(t<4)for(let n=0;n<t;n++)e+="=";return e}static formatString(e){return e?.replace(/[\n\r\t ]/g,"")||""}};us.DEFAULT_UTF8_ENCODING="utf8";function v0(r,...e){let t=arguments[0];for(let n=1;n<arguments.length;n++){let o=arguments[n];for(let s in o)t[s]=o[s]}return t}function E0(...r){let e=r.map(o=>o.byteLength).reduce((o,s)=>o+s),t=new Uint8Array(e),n=0;return r.map(o=>new Uint8Array(o)).forEach(o=>{for(let s of o)t[n++]=s}),t.buffer}function A0(r,e){if(!(r&&e)||r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let o=0;o<r.byteLength;o++)if(t[o]!==n[o])return!1;return!0}Yr.BufferSourceConverter=Ct;Yr.Convert=us;Yr.assign=v0;Yr.combine=E0;Yr.isEqual=A0});var gd=Qe(lo=>{(function(){var r,e,t,n,o,s,i,a;a=function(c){var u,f,l,d;return u=(c&255<<24)>>>24,f=(c&255<<16)>>>16,l=(c&65280)>>>8,d=c&255,[u,f,l,d].join(".")},i=function(c){var u,f,l,d,h,p;for(u=[],l=d=0;d<=3&&c.length!==0;l=++d){if(l>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}p=e(c),h=p[0],f=p[1],c=c.substring(f),u.push(h)}if(c.length!==0)throw new Error("Invalid IP");switch(u.length){case 1:if(u[0]>4294967295)throw new Error("Invalid IP");return u[0]>>>0;case 2:if(u[0]>255||u[1]>16777215)throw new Error("Invalid IP");return(u[0]<<24|u[1])>>>0;case 3:if(u[0]>255||u[1]>255||u[2]>65535)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2])>>>0;case 4:if(u[0]>255||u[1]>255||u[2]>255||u[3]>255)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2]<<8|u[3])>>>0;default:throw new Error("Invalid IP")}},t=function(c){return c.charCodeAt(0)},n=t("0"),s=t("a"),o=t("A"),e=function(c){var u,f,l,d,h;for(d=0,u=10,f="9",l=0,c.length>1&&c[l]==="0"&&(c[l+1]==="x"||c[l+1]==="X"?(l+=2,u=16):"0"<=c[l+1]&&c[l+1]<="9"&&(l++,u=8,f="7")),h=l;l<c.length;){if("0"<=c[l]&&c[l]<=f)d=d*u+(t(c[l])-n)>>>0;else if(u===16)if("a"<=c[l]&&c[l]<="f")d=d*u+(10+t(c[l])-s)>>>0;else if("A"<=c[l]&&c[l]<="F")d=d*u+(10+t(c[l])-o)>>>0;else break;else break;if(d>4294967295)throw new Error("too large");l++}if(l===h)throw new Error("empty octet");return[d,l]},r=function(){function c(u,f){var l,d,h,p;if(typeof u!="string")throw new Error("Missing `net' parameter");if(f||(p=u.split("/",2),u=p[0],f=p[1]),f||(f=32),typeof f=="string"&&f.indexOf(".")>-1){try{this.maskLong=i(f)}catch(m){throw l=m,new Error("Invalid mask: "+f)}for(d=h=32;h>=0;d=--h)if(this.maskLong===4294967295<<32-d>>>0){this.bitmask=d;break}}else if(f||f===0)this.bitmask=parseInt(f,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(i(u)&this.maskLong)>>>0}catch(m){throw l=m,new Error("Invalid net address: "+u)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+f);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(u){return typeof u=="string"&&(u.indexOf("/")>0||u.split(".").length!==4)&&(u=new c(u)),u instanceof c?this.contains(u.base)&&this.contains(u.broadcast||u.last):(i(u)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(u){return u==null&&(u=1),new c(a(this.netLong+this.size*u),this.mask)},c.prototype.forEach=function(u){var f,l,d;for(d=i(this.first),l=i(this.last),f=0;d<=l;)u(a(d),d,f),f++,d++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),lo.ip2long=i,lo.long2ip=a,lo.Netmask=r}).call(lo)});var bd=Qe((iS,Cl)=>{"use strict";var Iy=Object.prototype.hasOwnProperty,Ve="~";function uo(){}Object.create&&(uo.prototype=Object.create(null),new uo().__proto__||(Ve=!1));function Cy(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function wd(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var s=new Cy(t,n||r,o),i=Ve?Ve+e:e;return r._events[i]?r._events[i].fn?r._events[i]=[r._events[i],s]:r._events[i].push(s):(r._events[i]=s,r._eventsCount++),r}function di(r,e){--r._eventsCount===0?r._events=new uo:delete r._events[e]}function Ne(){this._events=new uo,this._eventsCount=0}Ne.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)Iy.call(t,n)&&e.push(Ve?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Ne.prototype.listeners=function(e){var t=Ve?Ve+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var o=0,s=n.length,i=new Array(s);o<s;o++)i[o]=n[o].fn;return i};Ne.prototype.listenerCount=function(e){var t=Ve?Ve+e:e,n=this._events[t];return n?n.fn?1:n.length:0};Ne.prototype.emit=function(e,t,n,o,s,i){var a=Ve?Ve+e:e;if(!this._events[a])return!1;var c=this._events[a],u=arguments.length,f,l;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),u){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,o),!0;case 5:return c.fn.call(c.context,t,n,o,s),!0;case 6:return c.fn.call(c.context,t,n,o,s,i),!0}for(l=1,f=new Array(u-1);l<u;l++)f[l-1]=arguments[l];c.fn.apply(c.context,f)}else{var d=c.length,h;for(l=0;l<d;l++)switch(c[l].once&&this.removeListener(e,c[l].fn,void 0,!0),u){case 1:c[l].fn.call(c[l].context);break;case 2:c[l].fn.call(c[l].context,t);break;case 3:c[l].fn.call(c[l].context,t,n);break;case 4:c[l].fn.call(c[l].context,t,n,o);break;default:if(!f)for(h=1,f=new Array(u-1);h<u;h++)f[h-1]=arguments[h];c[l].fn.apply(c[l].context,f)}}return!0};Ne.prototype.on=function(e,t,n){return wd(this,e,t,n,!1)};Ne.prototype.once=function(e,t,n){return wd(this,e,t,n,!0)};Ne.prototype.removeListener=function(e,t,n,o){var s=Ve?Ve+e:e;if(!this._events[s])return this;if(!t)return di(this,s),this;var i=this._events[s];if(i.fn)i.fn===t&&(!o||i.once)&&(!n||i.context===n)&&di(this,s);else{for(var a=0,c=[],u=i.length;a<u;a++)(i[a].fn!==t||o&&!i[a].once||n&&i[a].context!==n)&&c.push(i[a]);c.length?this._events[s]=c.length===1?c[0]:c:di(this,s)}return this};Ne.prototype.removeAllListeners=function(e){var t;return e?(t=Ve?Ve+e:e,this._events[t]&&di(this,t)):(this._events=new uo,this._eventsCount=0),this};Ne.prototype.off=Ne.prototype.removeListener;Ne.prototype.addListener=Ne.prototype.on;Ne.prefixed=Ve;Ne.EventEmitter=Ne;typeof Cl<"u"&&(Cl.exports=Ne)});var Sd=Qe((CS,Ad)=>{Ad.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function o(s,i){t[s]=i,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(s){return t[s]!==void 0||n[s]!==void 0},remove:function(s){t[s]!==void 0&&(t[s]=void 0),n[s]!==void 0&&(n[s]=void 0)},get:function(s){var i=t[s];if(i!==void 0)return i;if((i=n[s])!==void 0)return o(s,i),i},set:function(s,i){t[s]!==void 0?t[s]=i:o(s,i)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var Cd=Qe((WS,Id)=>{"use strict";Id.exports=r=>{if(Object.prototype.toString.call(r)!=="[object Object]")return!1;let e=Object.getPrototypeOf(r);return e===null||e===Object.prototype}});var Dd=Qe((Pd,Rd)=>{"use strict";var yi=Cd(),{hasOwnProperty:Ld}=Object.prototype,{propertyIsEnumerable:Ry}=Object,dn=(r,e,t)=>Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0}),Dy=Pd,Td={concatArrays:!1,ignoreUndefined:!1},wi=r=>{let e=[];for(let t in r)Ld.call(r,t)&&e.push(t);if(Object.getOwnPropertySymbols){let t=Object.getOwnPropertySymbols(r);for(let n of t)Ry.call(r,n)&&e.push(n)}return e};function pn(r){return Array.isArray(r)?My(r):yi(r)?Uy(r):r}function My(r){let e=r.slice(0,0);return wi(r).forEach(t=>{dn(e,t,pn(r[t]))}),e}function Uy(r){let e=Object.getPrototypeOf(r)===null?Object.create(null):{};return wi(r).forEach(t=>{dn(e,t,pn(r[t]))}),e}var Nd=(r,e,t,n)=>(t.forEach(o=>{typeof e[o]>"u"&&n.ignoreUndefined||(o in r&&r[o]!==Object.getPrototypeOf(r)?dn(r,o,Ml(r[o],e[o],n)):dn(r,o,pn(e[o])))}),r),Oy=(r,e,t)=>{let n=r.slice(0,0),o=0;return[r,e].forEach(s=>{let i=[];for(let a=0;a<s.length;a++)Ld.call(s,a)&&(i.push(String(a)),s===r?dn(n,o++,s[a]):dn(n,o++,pn(s[a])));n=Nd(n,s,wi(s).filter(a=>!i.includes(a)),t)}),n};function Ml(r,e,t){return t.concatArrays&&Array.isArray(r)&&Array.isArray(e)?Oy(r,e,t):!yi(e)||!yi(r)?pn(e):Nd(r,e,wi(e),t)}Rd.exports=function(...r){let e=Ml(pn(Td),this!==Dy&&this||{},Td),t={_:{}};for(let n of r)if(n!==void 0){if(!yi(n))throw new TypeError("`"+n+"` is not an Option Object");t=Ml(t,{_:n},e)}return t._}});var Fd=Qe((mo,_i)=>{(function(r,e){"use strict";var t={version:"3.0.0",x86:{},x64:{},inputValidation:!0};function n(h){if(!Array.isArray(h)&&!ArrayBuffer.isView(h))return!1;for(var p=0;p<h.length;p++)if(!Number.isInteger(h[p])||h[p]<0||h[p]>255)return!1;return!0}function o(h,p){return(h&65535)*p+(((h>>>16)*p&65535)<<16)}function s(h,p){return h<<p|h>>>32-p}function i(h){return h^=h>>>16,h=o(h,2246822507),h^=h>>>13,h=o(h,3266489909),h^=h>>>16,h}function a(h,p){h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535],p=[p[0]>>>16,p[0]&65535,p[1]>>>16,p[1]&65535];var m=[0,0,0,0];return m[3]+=h[3]+p[3],m[2]+=m[3]>>>16,m[3]&=65535,m[2]+=h[2]+p[2],m[1]+=m[2]>>>16,m[2]&=65535,m[1]+=h[1]+p[1],m[0]+=m[1]>>>16,m[1]&=65535,m[0]+=h[0]+p[0],m[0]&=65535,[m[0]<<16|m[1],m[2]<<16|m[3]]}function c(h,p){h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535],p=[p[0]>>>16,p[0]&65535,p[1]>>>16,p[1]&65535];var m=[0,0,0,0];return m[3]+=h[3]*p[3],m[2]+=m[3]>>>16,m[3]&=65535,m[2]+=h[2]*p[3],m[1]+=m[2]>>>16,m[2]&=65535,m[2]+=h[3]*p[2],m[1]+=m[2]>>>16,m[2]&=65535,m[1]+=h[1]*p[3],m[0]+=m[1]>>>16,m[1]&=65535,m[1]+=h[2]*p[2],m[0]+=m[1]>>>16,m[1]&=65535,m[1]+=h[3]*p[1],m[0]+=m[1]>>>16,m[1]&=65535,m[0]+=h[0]*p[3]+h[1]*p[2]+h[2]*p[1]+h[3]*p[0],m[0]&=65535,[m[0]<<16|m[1],m[2]<<16|m[3]]}function u(h,p){return p%=64,p===32?[h[1],h[0]]:p<32?[h[0]<<p|h[1]>>>32-p,h[1]<<p|h[0]>>>32-p]:(p-=32,[h[1]<<p|h[0]>>>32-p,h[0]<<p|h[1]>>>32-p])}function f(h,p){return p%=64,p===0?h:p<32?[h[0]<<p|h[1]>>>32-p,h[1]<<p]:[h[1]<<p-32,0]}function l(h,p){return[h[0]^p[0],h[1]^p[1]]}function d(h){return h=l(h,[0,h[0]>>>1]),h=c(h,[4283543511,3981806797]),h=l(h,[0,h[0]>>>1]),h=c(h,[3301882366,444984403]),h=l(h,[0,h[0]>>>1]),h}t.x86.hash32=function(h,p){if(t.inputValidation&&!n(h))return e;p=p||0;for(var m=h.length%4,g=h.length-m,y=p,b=0,w=3432918353,x=461845907,A=0;A<g;A=A+4)b=h[A]|h[A+1]<<8|h[A+2]<<16|h[A+3]<<24,b=o(b,w),b=s(b,15),b=o(b,x),y^=b,y=s(y,13),y=o(y,5)+3864292196;switch(b=0,m){case 3:b^=h[A+2]<<16;case 2:b^=h[A+1]<<8;case 1:b^=h[A],b=o(b,w),b=s(b,15),b=o(b,x),y^=b}return y^=h.length,y=i(y),y>>>0},t.x86.hash128=function(h,p){if(t.inputValidation&&!n(h))return e;p=p||0;for(var m=h.length%16,g=h.length-m,y=p,b=p,w=p,x=p,A=0,_=0,v=0,B=0,T=597399067,ee=2869860233,V=951274213,F=2716044179,R=0;R<g;R=R+16)A=h[R]|h[R+1]<<8|h[R+2]<<16|h[R+3]<<24,_=h[R+4]|h[R+5]<<8|h[R+6]<<16|h[R+7]<<24,v=h[R+8]|h[R+9]<<8|h[R+10]<<16|h[R+11]<<24,B=h[R+12]|h[R+13]<<8|h[R+14]<<16|h[R+15]<<24,A=o(A,T),A=s(A,15),A=o(A,ee),y^=A,y=s(y,19),y+=b,y=o(y,5)+1444728091,_=o(_,ee),_=s(_,16),_=o(_,V),b^=_,b=s(b,17),b+=w,b=o(b,5)+197830471,v=o(v,V),v=s(v,17),v=o(v,F),w^=v,w=s(w,15),w+=x,w=o(w,5)+2530024501,B=o(B,F),B=s(B,18),B=o(B,T),x^=B,x=s(x,13),x+=y,x=o(x,5)+850148119;switch(A=0,_=0,v=0,B=0,m){case 15:B^=h[R+14]<<16;case 14:B^=h[R+13]<<8;case 13:B^=h[R+12],B=o(B,F),B=s(B,18),B=o(B,T),x^=B;case 12:v^=h[R+11]<<24;case 11:v^=h[R+10]<<16;case 10:v^=h[R+9]<<8;case 9:v^=h[R+8],v=o(v,V),v=s(v,17),v=o(v,F),w^=v;case 8:_^=h[R+7]<<24;case 7:_^=h[R+6]<<16;case 6:_^=h[R+5]<<8;case 5:_^=h[R+4],_=o(_,ee),_=s(_,16),_=o(_,V),b^=_;case 4:A^=h[R+3]<<24;case 3:A^=h[R+2]<<16;case 2:A^=h[R+1]<<8;case 1:A^=h[R],A=o(A,T),A=s(A,15),A=o(A,ee),y^=A}return y^=h.length,b^=h.length,w^=h.length,x^=h.length,y+=b,y+=w,y+=x,b+=y,w+=y,x+=y,y=i(y),b=i(b),w=i(w),x=i(x),y+=b,y+=w,y+=x,b+=y,w+=y,x+=y,("00000000"+(y>>>0).toString(16)).slice(-8)+("00000000"+(b>>>0).toString(16)).slice(-8)+("00000000"+(w>>>0).toString(16)).slice(-8)+("00000000"+(x>>>0).toString(16)).slice(-8)},t.x64.hash128=function(h,p){if(t.inputValidation&&!n(h))return e;p=p||0;for(var m=h.length%16,g=h.length-m,y=[0,p],b=[0,p],w=[0,0],x=[0,0],A=[2277735313,289559509],_=[1291169091,658871167],v=0;v<g;v=v+16)w=[h[v+4]|h[v+5]<<8|h[v+6]<<16|h[v+7]<<24,h[v]|h[v+1]<<8|h[v+2]<<16|h[v+3]<<24],x=[h[v+12]|h[v+13]<<8|h[v+14]<<16|h[v+15]<<24,h[v+8]|h[v+9]<<8|h[v+10]<<16|h[v+11]<<24],w=c(w,A),w=u(w,31),w=c(w,_),y=l(y,w),y=u(y,27),y=a(y,b),y=a(c(y,[0,5]),[0,1390208809]),x=c(x,_),x=u(x,33),x=c(x,A),b=l(b,x),b=u(b,31),b=a(b,y),b=a(c(b,[0,5]),[0,944331445]);switch(w=[0,0],x=[0,0],m){case 15:x=l(x,f([0,h[v+14]],48));case 14:x=l(x,f([0,h[v+13]],40));case 13:x=l(x,f([0,h[v+12]],32));case 12:x=l(x,f([0,h[v+11]],24));case 11:x=l(x,f([0,h[v+10]],16));case 10:x=l(x,f([0,h[v+9]],8));case 9:x=l(x,[0,h[v+8]]),x=c(x,_),x=u(x,33),x=c(x,A),b=l(b,x);case 8:w=l(w,f([0,h[v+7]],56));case 7:w=l(w,f([0,h[v+6]],48));case 6:w=l(w,f([0,h[v+5]],40));case 5:w=l(w,f([0,h[v+4]],32));case 4:w=l(w,f([0,h[v+3]],24));case 3:w=l(w,f([0,h[v+2]],16));case 2:w=l(w,f([0,h[v+1]],8));case 1:w=l(w,[0,h[v]]),w=c(w,A),w=u(w,31),w=c(w,_),y=l(y,w)}return y=l(y,[0,h.length]),b=l(b,[0,h.length]),y=a(y,b),b=a(b,y),y=d(y),b=d(b),y=a(y,b),b=a(b,y),("00000000"+(y[0]>>>0).toString(16)).slice(-8)+("00000000"+(y[1]>>>0).toString(16)).slice(-8)+("00000000"+(b[0]>>>0).toString(16)).slice(-8)+("00000000"+(b[1]>>>0).toString(16)).slice(-8)},typeof mo<"u"?(typeof _i<"u"&&_i.exports&&(mo=_i.exports=t),mo.murmurHash3=t):typeof define=="function"&&define.amd?define([],function(){return t}):(t._murmurHash3=r.murmurHash3,t.noConflict=function(){return r.murmurHash3=t._murmurHash3,t._murmurHash3=e,t.noConflict=e,t},r.murmurHash3=t)})(mo)});var Hd=Qe((E8,Vd)=>{Vd.exports=Fd()});var xp=Qe((iB,bp)=>{function Je(r,e){typeof e=="boolean"&&(e={forever:e}),this._originalTimeouts=JSON.parse(JSON.stringify(r)),this._timeouts=r,this._options=e||{},this._maxRetryTime=e&&e.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}bp.exports=Je;Je.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};Je.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};Je.prototype.retry=function(r){if(this._timeout&&clearTimeout(this._timeout),!r)return!1;var e=new Date().getTime();if(r&&e-this._operationStart>=this._maxRetryTime)return this._errors.push(r),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(r);var t=this._timeouts.shift();if(t===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),t=this._cachedTimeouts.slice(-1);else return!1;var n=this;return this._timer=setTimeout(function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout(function(){n._operationTimeoutCb(n._attempts)},n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)},t),this._options.unref&&this._timer.unref(),!0};Je.prototype.attempt=function(r,e){this._fn=r,e&&(e.timeout&&(this._operationTimeout=e.timeout),e.cb&&(this._operationTimeoutCb=e.cb));var t=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){t._operationTimeoutCb()},t._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};Je.prototype.try=function(r){console.log("Using RetryOperation.try() is deprecated"),this.attempt(r)};Je.prototype.start=function(r){console.log("Using RetryOperation.start() is deprecated"),this.attempt(r)};Je.prototype.start=Je.prototype.try;Je.prototype.errors=function(){return this._errors};Je.prototype.attempts=function(){return this._attempts};Je.prototype.mainError=function(){if(this._errors.length===0)return null;for(var r={},e=null,t=0,n=0;n<this._errors.length;n++){var o=this._errors[n],s=o.message,i=(r[s]||0)+1;r[s]=i,i>=t&&(e=o,t=i)}return e}});var vp=Qe(Cr=>{var Fw=xp();Cr.operation=function(r){var e=Cr.timeouts(r);return new Fw(e,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})};Cr.timeouts=function(r){if(r instanceof Array)return[].concat(r);var e={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var t in r)e[t]=r[t];if(e.minTimeout>e.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],o=0;o<e.retries;o++)n.push(this.createTimeout(o,e));return r&&r.forever&&!n.length&&n.push(this.createTimeout(o,e)),n.sort(function(s,i){return s-i}),n};Cr.createTimeout=function(r,e){var t=e.randomize?Math.random()+1:1,n=Math.round(t*Math.max(e.minTimeout,1)*Math.pow(e.factor,r));return n=Math.min(n,e.maxTimeout),n};Cr.wrap=function(r,e,t){if(e instanceof Array&&(t=e,e=null),!t){t=[];for(var n in r)typeof r[n]=="function"&&t.push(n)}for(var o=0;o<t.length;o++){var s=t[o],i=r[s];r[s]=function(c){var u=Cr.operation(e),f=Array.prototype.slice.call(arguments,1),l=f.pop();f.push(function(d){u.retry(d)||(d&&(arguments[0]=u.mainError()),l.apply(this,arguments))}),u.attempt(function(){c.apply(r,f)})}.bind(r,i),r[s].options=e}}});var Ap=Qe((cB,Ep)=>{Ep.exports=vp()});var hb={};Re(hb,{createLibp2p:()=>fb});var Pu=Symbol.for("@libp2p/connection");var Na=Symbol.for("@libp2p/content-routing");var Pa=Symbol.for("@libp2p/peer-discovery");var Po=Symbol.for("@libp2p/peer-id");function Ro(r){return!!r?.[Po]}var Ra=Symbol.for("@libp2p/peer-routing");var Da="keep-alive";var xb=Symbol.for("@libp2p/transport");var Ot;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Ot||(Ot={}));var bt=class extends Error{constructor(e="The operation was aborted"){super(e),this.name="AbortError"}},Nr=class extends Error{code;props;constructor(e,t,n){super(e),this.code=t,this.name=n?.name??"CodeError",this.props=n??{}}};var D=class extends Error{constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Pr=class extends Error{constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}},Bn=class extends Error{constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}};var Do=class extends Error{constructor(e="The connection is closing"){super(e),this.name="ConnectionClosingError"}},Mo=class extends Error{constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}};var Uo=class extends Error{constructor(e="Not found"){super(e),this.name="NotFoundError"}},Oo=class extends Error{constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}},Rr=class extends Error{constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},Fo=class extends Error{constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Vo=class extends Error{constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}},kn=class extends Error{constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}},Ho=class extends Error{constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var Dr=class extends Error{constructor(e="Timed out"){super(e),this.name="TimeoutError"}},xt=class extends Error{constructor(e="Not started"){super(e),this.name="NotStartedError"}};var Mr=class extends Error{constructor(e="Dial error"){super(e),this.name="DialError"}};var Ur=class extends Error{constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}},$o=class extends Error{constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}},Ko=class extends Error{constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}},Ft=class extends Error{constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var oe=(r,...e)=>{try{[...e]}catch{}};var vt=class extends EventTarget{#e=new Map;constructor(){super(),oe(1/0,this)}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){super.addEventListener(e,t,n);let o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}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))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:o})=>!o),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};function qo(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function Ru(...r){let e=[];for(let t of r)qo(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStart!=null&&await t.beforeStart()})),await Promise.all(e.map(async t=>{await t.start()})),await Promise.all(e.map(async t=>{t.afterStart!=null&&await t.afterStart()}))}async function Du(...r){let e=[];for(let t of r)qo(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStop!=null&&await t.beforeStop()})),await Promise.all(e.map(async t=>{await t.stop()})),await Promise.all(e.map(async t=>{t.afterStop!=null&&await t.afterStop()}))}var In=Symbol.for("@libp2p/service-capabilities"),Ma=Symbol.for("@libp2p/service-dependencies");var Ha={};Re(Ha,{base58btc:()=>W,base58flickr:()=>em});var Xb=new Uint8Array(0);function Mu(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 Et(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 Uu(r){return new TextEncoder().encode(r)}function Ou(r){return new TextDecoder().decode(r)}function Zp(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),u=Math.log(a)/Math.log(256),f=Math.log(256)/Math.log(a);function l(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var m=0,g=0,y=0,b=p.length;y!==b&&p[y]===0;)y++,m++;for(var w=(b-y)*f+1>>>0,x=new Uint8Array(w);y!==b;){for(var A=p[y],_=0,v=w-1;(A!==0||_<g)&&v!==-1;v--,_++)A+=256*x[v]>>>0,x[v]=A%a>>>0,A=A/a>>>0;if(A!==0)throw new Error("Non-zero carry");g=_,y++}for(var B=w-g;B!==w&&x[B]===0;)B++;for(var T=c.repeat(m);B<w;++B)T+=r.charAt(x[B]);return T}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var m=0;if(p[m]!==" "){for(var g=0,y=0;p[m]===c;)g++,m++;for(var b=(p.length-m)*u+1>>>0,w=new Uint8Array(b);p[m];){var x=t[p.charCodeAt(m)];if(x===255)return;for(var A=0,_=b-1;(x!==0||A<y)&&_!==-1;_--,A++)x+=a*w[_]>>>0,w[_]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");y=A,m++}if(p[m]!==" "){for(var v=b-y;v!==b&&w[v]===0;)v++;for(var B=new Uint8Array(g+(b-v)),T=g;v!==b;)B[T++]=w[v++];return B}}}function h(p){var m=d(p);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:l,decodeUnsafe:d,decode:h}}var Xp=Zp,Yp=Xp,Vu=Yp;var Ua=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")}},Oa=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),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 Hu(this,e)}},Fa=class{decoders;constructor(e){this.decoders=e}or(e){return Hu(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 Hu(r,e){return new Fa({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Va=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 Ua(e,t,n),this.decoder=new Oa(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Or({name:r,prefix:e,encode:t,decode:n}){return new Va(r,e,t,n)}function Vt({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=Vu(t,r);return Or({prefix:e,name:r,encode:n,decode:s=>Et(o(s))})}function Jp(r,e,t,n){let o={};for(let f=0;f<e.length;++f)o[e[f]]=f;let s=r.length;for(;r[s-1]==="=";)--s;let i=new Uint8Array(s*t/8|0),a=0,c=0,u=0;for(let f=0;f<s;++f){let l=o[r[f]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<t|l,a+=t,a>=8&&(a-=8,i[u++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return i}function Qp(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;)s+="=";return s}function se({name:r,prefix:e,bitsPerChar:t,alphabet:n}){return Or({prefix:e,name:r,encode(o){return Qp(o,n,t)},decode(o){return Jp(o,n,t,r)}})}var W=Vt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),em=Vt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var $a={};Re($a,{base32:()=>ze,base32hex:()=>om,base32hexpad:()=>im,base32hexpadupper:()=>am,base32hexupper:()=>sm,base32pad:()=>rm,base32padupper:()=>nm,base32upper:()=>tm,base32z:()=>cm});var ze=se({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),tm=se({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),rm=se({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),nm=se({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),om=se({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),sm=se({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),im=se({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),am=se({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),cm=se({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var lm=qu,$u=128,um=127,fm=~um,hm=Math.pow(2,31);function qu(r,e,t){e=e||[],t=t||0;for(var n=t;r>=hm;)e[t++]=r&255|$u,r/=128;for(;r&fm;)e[t++]=r&255|$u,r>>>=7;return e[t]=r|0,qu.bytes=t-n+1,e}var dm=Ka,pm=128,Ku=127;function Ka(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw Ka.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&Ku)<<o:(i&Ku)*Math.pow(2,o),o+=7}while(i>=pm);return Ka.bytes=s-n,t}var mm=Math.pow(2,7),gm=Math.pow(2,14),ym=Math.pow(2,21),wm=Math.pow(2,28),bm=Math.pow(2,35),xm=Math.pow(2,42),vm=Math.pow(2,49),Em=Math.pow(2,56),Am=Math.pow(2,63),Sm=function(r){return r<mm?1:r<gm?2:r<ym?3:r<wm?4:r<bm?5:r<xm?6:r<vm?7:r<Em?8:r<Am?9:10},_m={encode:lm,decode:dm,encodingLength:Sm},Bm=_m,Cn=Bm;function Tn(r,e=0){return[Cn.decode(r,e),Cn.decode.bytes]}function Fr(r,e,t=0){return Cn.encode(r,e,t),e}function Vr(r){return Cn.encodingLength(r)}function et(r,e){let t=e.byteLength,n=Vr(r),o=n+Vr(t),s=new Uint8Array(o+t);return Fr(r,s,0),Fr(t,s,n),s.set(e,o),new Hr(r,t,e,s)}function tt(r){let e=Et(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 Hr(t,o,i,e)}function zu(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Mu(r.bytes,t.bytes)}}var Hr=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};function Gu(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return Im(t,qa(r),e??W.encoder);default:return Cm(t,qa(r),e??ze.encoder)}}var Wu=new WeakMap;function qa(r){let e=Wu.get(r);if(e==null){let t=new Map;return Wu.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=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!==Ln)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Tm)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=et(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&&zu(e.multihash,n.multihash)}toString(e){return Gu(this,e)}toJSON(){return{"/":Gu(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??ju(n,o,s.bytes))}else if(t[Lm]===!0){let{version:n,multihash:o,code:s}=t,i=tt(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!==Ln)throw new Error(`Version 0 CID must use dag-pb (code: ${Ln}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=ju(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Ln,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=Et(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 Hr(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[l,d]=Tn(e.subarray(t));return t+=d,l},o=n(),s=Ln;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),u=t+c,f=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:f,size:u}}static parse(e,t){let[n,o]=km(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 qa(s).set(n,e),s}};function km(r,e){switch(r[0]){case"Q":{let t=e??W;return[W.prefix,t.decode(`${W.prefix}${r}`)]}case W.prefix:{let t=e??W;return[W.prefix,t.decode(r)]}case ze.prefix:{let t=e??ze;return[ze.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function Im(r,e,t){let{prefix:n}=t;if(n!==W.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 Cm(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 Ln=112,Tm=18;function ju(r,e,t){let n=Vr(r),o=n+Vr(e),s=new Uint8Array(o+t.byteLength);return Fr(r,s,0),Fr(e,s,n),s.set(t,o),s}var Lm=Symbol.for("@ipld/js-cid/CID");var za={};Re(za,{identity:()=>St});var Zu=0,Nm="identity",Xu=Et;function Pm(r){return et(Zu,Xu(r))}var St={code:Zu,name:Nm,encode:Xu,digest:Pm};function ie(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 Yu(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`positive integer expected, not ${r}`)}function Rm(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function $r(r,...e){if(!Rm(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error(`Uint8Array expected of length ${e}, not of length=${r.length}`)}function Ju(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Yu(r.outputLen),Yu(r.blockLen)}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 Qu(r,e){$r(r);let t=e.outputLen;if(r.length<t)throw new Error(`digestInto() expects output buffer of length at least ${t}`)}var ir=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var Go=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),rt=(r,e)=>r<<32-e|r>>>e;var yx=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function ef(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function Nn(r){return typeof r=="string"&&(r=ef(r)),$r(r),r}function Ga(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];$r(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}var qr=class{clone(){return this._cloneInto()}},wx={}.toString;function Wo(r){let e=n=>r().update(Nn(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function zr(r=32){if(ir&&typeof ir.getRandomValues=="function")return ir.getRandomValues(new Uint8Array(r));if(ir&&typeof ir.randomBytes=="function")return ir.randomBytes(r);throw new Error("crypto.getRandomValues must be defined")}function Dm(r,e,t,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(t>>o&s),a=Number(t&s),c=n?4:0,u=n?0:4;r.setUint32(e+c,i,n),r.setUint32(e+u,a,n)}var tf=(r,e,t)=>r&e^~r&t,rf=(r,e,t)=>r&e^r&t^e&t,Gr=class extends qr{constructor(e,t,n,o){super(),this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Go(this.buffer)}update(e){Kr(this);let{view:t,buffer:n,blockLen:o}=this;e=Nn(e);let s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=Go(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),Qu(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,this.buffer.subarray(i).fill(0),this.padOffset>o-i&&(this.process(n,0),i=0);for(let l=i;l<o;l++)t[l]=0;Dm(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=Go(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,f=this.get();if(u>f.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<u;l++)a.setUint32(4*l,f[l],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.length=o,e.pos=a,e.finished=s,e.destroyed=i,o%t&&e.buffer.set(n),e}};var jo=BigInt(4294967295),Wa=BigInt(32);function nf(r,e=!1){return e?{h:Number(r&jo),l:Number(r>>Wa&jo)}:{h:Number(r>>Wa&jo)|0,l:Number(r&jo)|0}}function Mm(r,e=!1){let t=new Uint32Array(r.length),n=new Uint32Array(r.length);for(let o=0;o<r.length;o++){let{h:s,l:i}=nf(r[o],e);[t[o],n[o]]=[s,i]}return[t,n]}var Um=(r,e)=>BigInt(r>>>0)<<Wa|BigInt(e>>>0),Om=(r,e,t)=>r>>>t,Fm=(r,e,t)=>r<<32-t|e>>>t,Vm=(r,e,t)=>r>>>t|e<<32-t,Hm=(r,e,t)=>r<<32-t|e>>>t,$m=(r,e,t)=>r<<64-t|e>>>t-32,Km=(r,e,t)=>r>>>t-32|e<<64-t,qm=(r,e)=>e,zm=(r,e)=>r,Gm=(r,e,t)=>r<<t|e>>>32-t,Wm=(r,e,t)=>e<<t|r>>>32-t,jm=(r,e,t)=>e<<t-32|r>>>64-t,Zm=(r,e,t)=>r<<t-32|e>>>64-t;function Xm(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var Ym=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),Jm=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,Qm=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),eg=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,tg=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),rg=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var ng={fromBig:nf,split:Mm,toBig:Um,shrSH:Om,shrSL:Fm,rotrSH:Vm,rotrSL:Hm,rotrBH:$m,rotrBL:Km,rotr32H:qm,rotr32L:zm,rotlSH:Gm,rotlSL:Wm,rotlBH:jm,rotlBL:Zm,add:Xm,add3L:Ym,add3H:Jm,add4L:Qm,add4H:eg,add5H:rg,add5L:tg},O=ng;var[og,sg]=O.split(["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))),Ht=new Uint32Array(80),$t=new Uint32Array(80),ja=class extends Gr{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:u,El:f,Fh:l,Fl:d,Gh:h,Gl:p,Hh:m,Hl:g}=this;return[e,t,n,o,s,i,a,c,u,f,l,d,h,p,m,g]}set(e,t,n,o,s,i,a,c,u,f,l,d,h,p,m,g){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=f|0,this.Fh=l|0,this.Fl=d|0,this.Gh=h|0,this.Gl=p|0,this.Hh=m|0,this.Hl=g|0}process(e,t){for(let w=0;w<16;w++,t+=4)Ht[w]=e.getUint32(t),$t[w]=e.getUint32(t+=4);for(let w=16;w<80;w++){let x=Ht[w-15]|0,A=$t[w-15]|0,_=O.rotrSH(x,A,1)^O.rotrSH(x,A,8)^O.shrSH(x,A,7),v=O.rotrSL(x,A,1)^O.rotrSL(x,A,8)^O.shrSL(x,A,7),B=Ht[w-2]|0,T=$t[w-2]|0,ee=O.rotrSH(B,T,19)^O.rotrBH(B,T,61)^O.shrSH(B,T,6),V=O.rotrSL(B,T,19)^O.rotrBL(B,T,61)^O.shrSL(B,T,6),F=O.add4L(v,V,$t[w-7],$t[w-16]),R=O.add4H(F,_,ee,Ht[w-7],Ht[w-16]);Ht[w]=R|0,$t[w]=F|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:f,Eh:l,El:d,Fh:h,Fl:p,Gh:m,Gl:g,Hh:y,Hl:b}=this;for(let w=0;w<80;w++){let x=O.rotrSH(l,d,14)^O.rotrSH(l,d,18)^O.rotrBH(l,d,41),A=O.rotrSL(l,d,14)^O.rotrSL(l,d,18)^O.rotrBL(l,d,41),_=l&h^~l&m,v=d&p^~d&g,B=O.add5L(b,A,v,sg[w],$t[w]),T=O.add5H(B,y,x,_,og[w],Ht[w]),ee=B|0,V=O.rotrSH(n,o,28)^O.rotrBH(n,o,34)^O.rotrBH(n,o,39),F=O.rotrSL(n,o,28)^O.rotrBL(n,o,34)^O.rotrBL(n,o,39),R=n&s^n&a^s&a,I=o&i^o&c^i&c;y=m|0,b=g|0,m=h|0,g=p|0,h=l|0,p=d|0,{h:l,l:d}=O.add(u|0,f|0,T|0,ee|0),u=a|0,f=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let L=O.add3L(ee,F,I);n=O.add3H(L,T,V,R),o=L|0}({h:n,l:o}=O.add(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=O.add(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=O.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:f}=O.add(this.Dh|0,this.Dl|0,u|0,f|0),{h:l,l:d}=O.add(this.Eh|0,this.El|0,l|0,d|0),{h,l:p}=O.add(this.Fh|0,this.Fl|0,h|0,p|0),{h:m,l:g}=O.add(this.Gh|0,this.Gl|0,m|0,g|0),{h:y,l:b}=O.add(this.Hh|0,this.Hl|0,y|0,b|0),this.set(n,o,s,i,a,c,u,f,l,d,h,p,m,g,y,b)}roundClean(){Ht.fill(0),$t.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var of=Wo(()=>new ja);var Xo={};Re(Xo,{aInRange:()=>$e,abool:()=>nt,abytes:()=>Wr,bitGet:()=>fg,bitLen:()=>Qa,bitMask:()=>Rn,bitSet:()=>hg,bytesToHex:()=>Bt,bytesToNumberBE:()=>kt,bytesToNumberLE:()=>qt,concatBytes:()=>It,createHmacDrbg:()=>ec,ensureBytes:()=>ae,equalBytes:()=>lg,hexToBytes:()=>cr,hexToNumber:()=>Ja,inRange:()=>Pn,isBytes:()=>Kt,memoized:()=>ur,notImplemented:()=>pg,numberToBytesBE:()=>zt,numberToBytesLE:()=>lr,numberToHexUnpadded:()=>ar,numberToVarBytesBE:()=>cg,utf8ToBytes:()=>ug,validateObject:()=>ut});var Ya=BigInt(0),Zo=BigInt(1),ig=BigInt(2);function Kt(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Wr(r){if(!Kt(r))throw new Error("Uint8Array expected")}function nt(r,e){if(typeof e!="boolean")throw new Error(`${r} must be valid boolean, got "${e}".`)}var ag=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Bt(r){Wr(r);let e="";for(let t=0;t<r.length;t++)e+=ag[r[t]];return e}function ar(r){let e=r.toString(16);return e.length&1?`0${e}`:e}function Ja(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return BigInt(r===""?"0":`0x${r}`)}var _t={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function sf(r){if(r>=_t._0&&r<=_t._9)return r-_t._0;if(r>=_t._A&&r<=_t._F)return r-(_t._A-10);if(r>=_t._a&&r<=_t._f)return r-(_t._a-10)}function cr(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);let e=r.length,t=e/2;if(e%2)throw new Error("padded 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=sf(r.charCodeAt(s)),a=sf(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function kt(r){return Ja(Bt(r))}function qt(r){return Wr(r),Ja(Bt(Uint8Array.from(r).reverse()))}function zt(r,e){return cr(r.toString(16).padStart(e*2,"0"))}function lr(r,e){return zt(r,e).reverse()}function cg(r){return cr(ar(r))}function ae(r,e,t){let n;if(typeof e=="string")try{n=cr(e)}catch(s){throw new Error(`${r} must be valid hex string, got "${e}". Cause: ${s}`)}else if(Kt(e))n=Uint8Array.from(e);else throw new Error(`${r} must be hex string or Uint8Array`);let o=n.length;if(typeof t=="number"&&o!==t)throw new Error(`${r} expected ${t} bytes, got ${o}`);return n}function It(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];Wr(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 lg(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 ug(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}var Za=r=>typeof r=="bigint"&&Ya<=r;function Pn(r,e,t){return Za(r)&&Za(e)&&Za(t)&&e<=r&&r<t}function $e(r,e,t,n){if(!Pn(e,t,n))throw new Error(`expected valid ${r}: ${t} <= n < ${n}, got ${typeof e} ${e}`)}function Qa(r){let e;for(e=0;r>Ya;r>>=Zo,e+=1);return e}function fg(r,e){return r>>BigInt(e)&Zo}function hg(r,e,t){return r|(t?Zo:Ya)<<BigInt(e)}var Rn=r=>(ig<<BigInt(r-1))-Zo,Xa=r=>new Uint8Array(r),af=r=>Uint8Array.from(r);function ec(r,e,t){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let n=Xa(r),o=Xa(r),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...l)=>t(o,n,...l),c=(l=Xa())=>{o=a(af([0]),l),n=a(),l.length!==0&&(o=a(af([1]),l),n=a())},u=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let l=0,d=[];for(;l<e;){n=a();let h=n.slice();d.push(h),l+=n.length}return It(...d)};return(l,d)=>{i(),c(l);let h;for(;!(h=d(u()));)c();return i(),h}}var dg={bigint:r=>typeof r=="bigint",function:r=>typeof r=="function",boolean:r=>typeof r=="boolean",string:r=>typeof r=="string",stringOrUint8Array:r=>typeof r=="string"||Kt(r),isSafeInteger:r=>Number.isSafeInteger(r),array:r=>Array.isArray(r),field:(r,e)=>e.Fp.isValid(r),hash:r=>typeof r=="function"&&Number.isSafeInteger(r.outputLen)};function ut(r,e,t={}){let n=(o,s,i)=>{let a=dg[s];if(typeof a!="function")throw new Error(`Invalid validator "${s}", expected function`);let c=r[o];if(!(i&&c===void 0)&&!a(c,r))throw new Error(`Invalid param ${String(o)}=${c} (${typeof c}), expected ${s}`)};for(let[o,s]of Object.entries(e))n(o,s,!1);for(let[o,s]of Object.entries(t))n(o,s,!0);return r}var pg=()=>{throw new Error("not implemented")};function ur(r){let e=new WeakMap;return(t,...n)=>{let o=e.get(t);if(o!==void 0)return o;let s=r(t,...n);return e.set(t,s),s}}var me=BigInt(0),te=BigInt(1),fr=BigInt(2),mg=BigInt(3),tc=BigInt(4),cf=BigInt(5),lf=BigInt(8),gg=BigInt(9),yg=BigInt(16);function Y(r,e){let t=r%e;return t>=me?t:e+t}function wg(r,e,t){if(t<=me||e<me)throw new Error("Expected power/modulo > 0");if(t===te)return me;let n=te;for(;e>me;)e&te&&(n=n*r%t),r=r*r%t,e>>=te;return n}function re(r,e,t){let n=r;for(;e-- >me;)n*=n,n%=t;return n}function Yo(r,e){if(r===me||e<=me)throw new Error(`invert: expected positive integers, got n=${r} mod=${e}`);let t=Y(r,e),n=e,o=me,s=te,i=te,a=me;for(;t!==me;){let u=n/t,f=n%t,l=o-i*u,d=s-a*u;n=t,t=f,o=i,s=a,i=l,a=d}if(n!==te)throw new Error("invert: does not exist");return Y(o,e)}function bg(r){let e=(r-te)/fr,t,n,o;for(t=r-te,n=0;t%fr===me;t/=fr,n++);for(o=fr;o<r&&wg(o,e,r)!==r-te;o++);if(n===1){let i=(r+te)/tc;return function(c,u){let f=c.pow(u,i);if(!c.eql(c.sqr(f),u))throw new Error("Cannot find square root");return f}}let s=(t+te)/fr;return function(a,c){if(a.pow(c,e)===a.neg(a.ONE))throw new Error("Cannot find square root");let u=n,f=a.pow(a.mul(a.ONE,o),t),l=a.pow(c,s),d=a.pow(c,t);for(;!a.eql(d,a.ONE);){if(a.eql(d,a.ZERO))return a.ZERO;let h=1;for(let m=a.sqr(d);h<u&&!a.eql(m,a.ONE);h++)m=a.sqr(m);let p=a.pow(f,te<<BigInt(u-h-1));f=a.sqr(p),l=a.mul(l,p),d=a.mul(d,f),u=h}return l}}function xg(r){if(r%tc===mg){let e=(r+te)/tc;return function(n,o){let s=n.pow(o,e);if(!n.eql(n.sqr(s),o))throw new Error("Cannot find square root");return s}}if(r%lf===cf){let e=(r-cf)/lf;return function(n,o){let s=n.mul(o,fr),i=n.pow(s,e),a=n.mul(o,i),c=n.mul(n.mul(a,fr),i),u=n.mul(a,n.sub(c,n.ONE));if(!n.eql(n.sqr(u),o))throw new Error("Cannot find square root");return u}}return r%yg,bg(r)}var uf=(r,e)=>(Y(r,e)&te)===te,vg=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function rc(r){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=vg.reduce((n,o)=>(n[o]="function",n),e);return ut(r,t)}function Eg(r,e,t){if(t<me)throw new Error("Expected power > 0");if(t===me)return r.ONE;if(t===te)return e;let n=r.ONE,o=e;for(;t>me;)t&te&&(n=r.mul(n,o)),o=r.sqr(o),t>>=te;return n}function Ag(r,e){let t=new Array(e.length),n=e.reduce((s,i,a)=>r.is0(i)?s:(t[a]=s,r.mul(s,i)),r.ONE),o=r.inv(n);return e.reduceRight((s,i,a)=>r.is0(i)?s:(t[a]=r.mul(s,t[a]),r.mul(s,i)),o),t}function nc(r,e){let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function Gt(r,e,t=!1,n={}){if(r<=me)throw new Error(`Expected Field ORDER > 0, got ${r}`);let{nBitLength:o,nByteLength:s}=nc(r,e);if(s>2048)throw new Error("Field lengths over 2048 bytes are not supported");let i=xg(r),a=Object.freeze({ORDER:r,BITS:o,BYTES:s,MASK:Rn(o),ZERO:me,ONE:te,create:c=>Y(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return me<=c&&c<r},is0:c=>c===me,isOdd:c=>(c&te)===te,neg:c=>Y(-c,r),eql:(c,u)=>c===u,sqr:c=>Y(c*c,r),add:(c,u)=>Y(c+u,r),sub:(c,u)=>Y(c-u,r),mul:(c,u)=>Y(c*u,r),pow:(c,u)=>Eg(a,c,u),div:(c,u)=>Y(c*Yo(u,r),r),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>Yo(c,r),sqrt:n.sqrt||(c=>i(a,c)),invertBatch:c=>Ag(a,c),cmov:(c,u,f)=>f?u:c,toBytes:c=>t?lr(c,s):zt(c,s),fromBytes:c=>{if(c.length!==s)throw new Error(`Fp.fromBytes: expected ${s}, got ${c.length}`);return t?qt(c):kt(c)}});return Object.freeze(a)}function ff(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let e=r.toString(2).length;return Math.ceil(e/8)}function oc(r){let e=ff(r);return e+Math.ceil(e/2)}function hf(r,e,t=!1){let n=r.length,o=ff(e),s=oc(e);if(n<16||n<s||n>1024)throw new Error(`expected ${s}-1024 bytes of input, got ${n}`);let i=t?kt(r):qt(r),a=Y(i,e-te)+te;return t?lr(a,o):zt(a,o)}var _g=BigInt(0),sc=BigInt(1),ic=new WeakMap,df=new WeakMap;function Jo(r,e){let t=(s,i)=>{let a=i.negate();return s?a:i},n=s=>{if(!Number.isSafeInteger(s)||s<=0||s>e)throw new Error(`Wrong window size=${s}, should be [1..${e}]`)},o=s=>{n(s);let i=Math.ceil(e/s)+1,a=2**(s-1);return{windows:i,windowSize:a}};return{constTimeNegate:t,unsafeLadder(s,i){let a=r.ZERO,c=s;for(;i>_g;)i&sc&&(a=a.add(c)),c=c.double(),i>>=sc;return a},precomputeWindow(s,i){let{windows:a,windowSize:c}=o(i),u=[],f=s,l=f;for(let d=0;d<a;d++){l=f,u.push(l);for(let h=1;h<c;h++)l=l.add(f),u.push(l);f=l.double()}return u},wNAF(s,i,a){let{windows:c,windowSize:u}=o(s),f=r.ZERO,l=r.BASE,d=BigInt(2**s-1),h=2**s,p=BigInt(s);for(let m=0;m<c;m++){let g=m*u,y=Number(a&d);a>>=p,y>u&&(y-=h,a+=sc);let b=g,w=g+Math.abs(y)-1,x=m%2!==0,A=y<0;y===0?l=l.add(t(x,i[b])):f=f.add(t(A,i[w]))}return{p:f,f:l}},wNAFCached(s,i,a){let c=df.get(s)||1,u=ic.get(s);return u||(u=this.precomputeWindow(s,c),c!==1&&ic.set(s,a(u))),this.wNAF(c,u,i)},setWindowSize(s,i){n(i),df.set(s,i),ic.delete(s)}}}function Qo(r,e,t,n){if(!Array.isArray(t)||!Array.isArray(n)||n.length!==t.length)throw new Error("arrays of points and scalars must have equal length");n.forEach((f,l)=>{if(!e.isValid(f))throw new Error(`wrong scalar at index ${l}`)}),t.forEach((f,l)=>{if(!(f instanceof r))throw new Error(`wrong point at index ${l}`)});let o=Qa(BigInt(t.length)),s=o>12?o-3:o>4?o-2:o?2:1,i=(1<<s)-1,a=new Array(i+1).fill(r.ZERO),c=Math.floor((e.BITS-1)/s)*s,u=r.ZERO;for(let f=c;f>=0;f-=s){a.fill(r.ZERO);for(let d=0;d<n.length;d++){let h=n[d],p=Number(h>>BigInt(f)&BigInt(i));a[p]=a[p].add(t[d])}let l=r.ZERO;for(let d=a.length-1,h=r.ZERO;d>0;d--)h=h.add(a[d]),l=l.add(h);if(u=u.add(l),f!==0)for(let d=0;d<s;d++)u=u.double()}return u}function Dn(r){return rc(r.Fp),ut(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...nc(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var ot=BigInt(0),Ke=BigInt(1),es=BigInt(2),Bg=BigInt(8),kg={zip215:!0};function Ig(r){let e=Dn(r);return ut(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function pf(r){let e=Ig(r),{Fp:t,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=e,u=es<<BigInt(a*8)-Ke,f=t.create,l=Gt(e.n,e.nBitLength),d=e.uvRatio||((S,E)=>{try{return{isValid:!0,value:t.sqrt(S*t.inv(E))}}catch{return{isValid:!1,value:ot}}}),h=e.adjustScalarBytes||(S=>S),p=e.domain||((S,E,k)=>{if(nt("phflag",k),E.length||k)throw new Error("Contexts/pre-hash are not supported");return S});function m(S,E){$e("coordinate "+S,E,ot,u)}function g(S){if(!(S instanceof w))throw new Error("ExtendedPoint expected")}let y=ur((S,E)=>{let{ex:k,ey:N,ez:M}=S,U=S.is0();E==null&&(E=U?Bg:t.inv(M));let $=f(k*E),z=f(N*E),K=f(M*E);if(U)return{x:ot,y:Ke};if(K!==Ke)throw new Error("invZ was invalid");return{x:$,y:z}}),b=ur(S=>{let{a:E,d:k}=e;if(S.is0())throw new Error("bad point: ZERO");let{ex:N,ey:M,ez:U,et:$}=S,z=f(N*N),K=f(M*M),X=f(U*U),Q=f(X*X),be=f(z*E),xe=f(X*f(be+K)),Ee=f(Q+f(k*f(z*K)));if(xe!==Ee)throw new Error("bad point: equation left != right (1)");let Pe=f(N*M),de=f(U*$);if(Pe!==de)throw new Error("bad point: equation left != right (2)");return!0});class w{constructor(E,k,N,M){this.ex=E,this.ey=k,this.ez=N,this.et=M,m("x",E),m("y",k),m("z",N),m("t",M),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(E){if(E instanceof w)throw new Error("extended point not allowed");let{x:k,y:N}=E||{};return m("x",k),m("y",N),new w(k,N,Ke,f(k*N))}static normalizeZ(E){let k=t.invertBatch(E.map(N=>N.ez));return E.map((N,M)=>N.toAffine(k[M])).map(w.fromAffine)}static msm(E,k){return Qo(w,l,E,k)}_setWindowSize(E){_.setWindowSize(this,E)}assertValidity(){b(this)}equals(E){g(E);let{ex:k,ey:N,ez:M}=this,{ex:U,ey:$,ez:z}=E,K=f(k*z),X=f(U*M),Q=f(N*z),be=f($*M);return K===X&&Q===be}is0(){return this.equals(w.ZERO)}negate(){return new w(f(-this.ex),this.ey,this.ez,f(-this.et))}double(){let{a:E}=e,{ex:k,ey:N,ez:M}=this,U=f(k*k),$=f(N*N),z=f(es*f(M*M)),K=f(E*U),X=k+N,Q=f(f(X*X)-U-$),be=K+$,xe=be-z,Ee=K-$,Pe=f(Q*xe),de=f(be*Ee),He=f(Q*Ee),wt=f(xe*be);return new w(Pe,de,wt,He)}add(E){g(E);let{a:k,d:N}=e,{ex:M,ey:U,ez:$,et:z}=this,{ex:K,ey:X,ez:Q,et:be}=E;if(k===BigInt(-1)){let _u=f((U-M)*(X+K)),Bu=f((U+M)*(X-K)),La=f(Bu-_u);if(La===ot)return this.double();let ku=f($*es*be),Iu=f(z*es*Q),Cu=Iu+ku,Tu=Bu+_u,Lu=Iu-ku,Fp=f(Cu*La),Vp=f(Tu*Lu),Hp=f(Cu*Lu),$p=f(La*Tu);return new w(Fp,Vp,$p,Hp)}let xe=f(M*K),Ee=f(U*X),Pe=f(z*N*be),de=f($*Q),He=f((M+U)*(K+X)-xe-Ee),wt=de-Pe,Sn=de+Pe,_n=f(Ee-k*xe),Dp=f(He*wt),Mp=f(Sn*_n),Up=f(He*_n),Op=f(wt*Sn);return new w(Dp,Mp,Op,Up)}subtract(E){return this.add(E.negate())}wNAF(E){return _.wNAFCached(this,E,w.normalizeZ)}multiply(E){let k=E;$e("scalar",k,Ke,n);let{p:N,f:M}=this.wNAF(k);return w.normalizeZ([N,M])[0]}multiplyUnsafe(E){let k=E;return $e("scalar",k,ot,n),k===ot?A:this.equals(A)||k===Ke?this:this.equals(x)?this.wNAF(k).p:_.unsafeLadder(this,k)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return _.unsafeLadder(this,n).is0()}toAffine(E){return y(this,E)}clearCofactor(){let{h:E}=e;return E===Ke?this:this.multiplyUnsafe(E)}static fromHex(E,k=!1){let{d:N,a:M}=e,U=t.BYTES;E=ae("pointHex",E,U),nt("zip215",k);let $=E.slice(),z=E[U-1];$[U-1]=z&-129;let K=qt($),X=k?u:t.ORDER;$e("pointHex.y",K,ot,X);let Q=f(K*K),be=f(Q-Ke),xe=f(N*Q-M),{isValid:Ee,value:Pe}=d(be,xe);if(!Ee)throw new Error("Point.fromHex: invalid y coordinate");let de=(Pe&Ke)===Ke,He=(z&128)!==0;if(!k&&Pe===ot&&He)throw new Error("Point.fromHex: x=0 and x_0=1");return He!==de&&(Pe=f(-Pe)),w.fromAffine({x:Pe,y:K})}static fromPrivateKey(E){return T(E).point}toRawBytes(){let{x:E,y:k}=this.toAffine(),N=lr(k,t.BYTES);return N[N.length-1]|=E&Ke?128:0,N}toHex(){return Bt(this.toRawBytes())}}w.BASE=new w(e.Gx,e.Gy,Ke,f(e.Gx*e.Gy)),w.ZERO=new w(ot,Ke,Ke,ot);let{BASE:x,ZERO:A}=w,_=Jo(w,a*8);function v(S){return Y(S,n)}function B(S){return v(qt(S))}function T(S){let E=a;S=ae("private key",S,E);let k=ae("hashed private key",s(S),2*E),N=h(k.slice(0,E)),M=k.slice(E,2*E),U=B(N),$=x.multiply(U),z=$.toRawBytes();return{head:N,prefix:M,scalar:U,point:$,pointBytes:z}}function ee(S){return T(S).pointBytes}function V(S=new Uint8Array,...E){let k=It(...E);return B(s(p(k,ae("context",S),!!o)))}function F(S,E,k={}){S=ae("message",S),o&&(S=o(S));let{prefix:N,scalar:M,pointBytes:U}=T(E),$=V(k.context,N,S),z=x.multiply($).toRawBytes(),K=V(k.context,z,U,S),X=v($+K*M);$e("signature.s",X,ot,n);let Q=It(z,lr(X,t.BYTES));return ae("result",Q,a*2)}let R=kg;function I(S,E,k,N=R){let{context:M,zip215:U}=N,$=t.BYTES;S=ae("signature",S,2*$),E=ae("message",E),U!==void 0&&nt("zip215",U),o&&(E=o(E));let z=qt(S.slice($,2*$)),K,X,Q;try{K=w.fromHex(k,U),X=w.fromHex(S.slice(0,$),U),Q=x.multiplyUnsafe(z)}catch{return!1}if(!U&&K.isSmallOrder())return!1;let be=V(M,X.toRawBytes(),K.toRawBytes(),E);return X.add(K.multiplyUnsafe(be)).subtract(Q).clearCofactor().equals(w.ZERO)}return x._setWindowSize(8),{CURVE:e,getPublicKey:ee,sign:F,verify:I,ExtendedPoint:w,utils:{getExtendedPublicKey:T,randomPrivateKey:()=>i(t.BYTES),precompute(S=8,E=w.BASE){return E._setWindowSize(S),E.multiply(BigInt(3)),E}}}}var ac=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),mf=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),Hx=BigInt(0),Cg=BigInt(1),gf=BigInt(2),$x=BigInt(3),Tg=BigInt(5),Lg=BigInt(8);function Ng(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=ac,a=r*r%s*r%s,c=re(a,gf,s)*a%s,u=re(c,Cg,s)*r%s,f=re(u,Tg,s)*u%s,l=re(f,e,s)*f%s,d=re(l,t,s)*l%s,h=re(d,n,s)*d%s,p=re(h,o,s)*h%s,m=re(p,o,s)*h%s,g=re(m,e,s)*f%s;return{pow_p_5_8:re(g,gf,s)*r%s,b2:a}}function Pg(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function Rg(r,e){let t=ac,n=Y(e*e*e,t),o=Y(n*n*e,t),s=Ng(r*o).pow_p_5_8,i=Y(r*n*s,t),a=Y(e*i*i,t),c=i,u=Y(i*mf,t),f=a===r,l=a===Y(-r,t),d=a===Y(-r*mf,t);return f&&(i=c),(l||d)&&(i=u),uf(i,t)&&(i=Y(-i,t)),{isValid:f||l,value:i}}var Dg=Gt(ac,void 0,!0),Mg={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Dg,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:Lg,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:of,randomBytes:zr,adjustScalarBytes:Pg,uvRatio:Rg},Mn=pf(Mg);var ts=32,rs=64,cc=32;function yf(){let r=Mn.utils.randomPrivateKey(),e=Mn.getPublicKey(r);return{privateKey:Ug(r,e),publicKey:e}}function wf(r,e){let t=r.subarray(0,cc);return Mn.sign(e instanceof Uint8Array?e:e.subarray(),t)}function bf(r,e,t){return Mn.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}function Ug(r,e){let t=new Uint8Array(rs);for(let n=0;n<cc;n++)t[n]=r[n],t[cc+n]=e[n];return t}var Un=class{type="Ed25519";raw;constructor(e){this.raw=os(e,ts)}toMultihash(){return St.digest(ft(this))}toCID(){return pe.createV1(114,this.toMultihash())}toString(){return W.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ie(this.raw,e.raw)}verify(e,t){return bf(this.raw,t,e)}},ns=class{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=os(e,rs),this.publicKey=new Un(t)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ie(this.raw,e.raw)}sign(e){return wf(this.raw,e)}};function lc(r){return r=os(r,ts),new Un(r)}async function vf(){let{privateKey:r,publicKey:e}=yf();return new ns(r,e)}function os(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new D(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}function ce(r=0){return new Uint8Array(r)}function ke(r=0){return new Uint8Array(r)}var Og=Math.pow(2,7),Fg=Math.pow(2,14),Vg=Math.pow(2,21),uc=Math.pow(2,28),fc=Math.pow(2,35),hc=Math.pow(2,42),dc=Math.pow(2,49),j=128,Ie=127;function he(r){if(r<Og)return 1;if(r<Fg)return 2;if(r<Vg)return 3;if(r<uc)return 4;if(r<fc)return 5;if(r<hc)return 6;if(r<dc)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function pc(r,e,t=0){switch(he(r)){case 8:e[t++]=r&255|j,r/=128;case 7:e[t++]=r&255|j,r/=128;case 6:e[t++]=r&255|j,r/=128;case 5:e[t++]=r&255|j,r/=128;case 4:e[t++]=r&255|j,r>>>=7;case 3:e[t++]=r&255|j,r>>>=7;case 2:e[t++]=r&255|j,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function Hg(r,e,t=0){switch(he(r)){case 8:e.set(t++,r&255|j),r/=128;case 7:e.set(t++,r&255|j),r/=128;case 6:e.set(t++,r&255|j),r/=128;case 5:e.set(t++,r&255|j),r/=128;case 4:e.set(t++,r&255|j),r>>>=7;case 3:e.set(t++,r&255|j),r>>>=7;case 2:e.set(t++,r&255|j),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function mc(r,e){let t=r[e],n=0;if(n+=t&Ie,t<j||(t=r[e+1],n+=(t&Ie)<<7,t<j)||(t=r[e+2],n+=(t&Ie)<<14,t<j)||(t=r[e+3],n+=(t&Ie)<<21,t<j)||(t=r[e+4],n+=(t&Ie)*uc,t<j)||(t=r[e+5],n+=(t&Ie)*fc,t<j)||(t=r[e+6],n+=(t&Ie)*hc,t<j)||(t=r[e+7],n+=(t&Ie)*dc,t<j))return n;throw new RangeError("Could not decode varint")}function $g(r,e){let t=r.get(e),n=0;if(n+=t&Ie,t<j||(t=r.get(e+1),n+=(t&Ie)<<7,t<j)||(t=r.get(e+2),n+=(t&Ie)<<14,t<j)||(t=r.get(e+3),n+=(t&Ie)<<21,t<j)||(t=r.get(e+4),n+=(t&Ie)*uc,t<j)||(t=r.get(e+5),n+=(t&Ie)*fc,t<j)||(t=r.get(e+6),n+=(t&Ie)*hc,t<j)||(t=r.get(e+7),n+=(t&Ie)*dc,t<j))return n;throw new RangeError("Could not decode varint")}function Ce(r,e,t=0){return e==null&&(e=ke(he(r))),e instanceof Uint8Array?pc(r,e,t):Hg(r,e,t)}function st(r,e=0){return r instanceof Uint8Array?mc(r,e):$g(r,e)}var gc=new Float32Array([-0]),Wt=new Uint8Array(gc.buffer);function Ef(r,e,t){gc[0]=r,e[t]=Wt[0],e[t+1]=Wt[1],e[t+2]=Wt[2],e[t+3]=Wt[3]}function Af(r,e){return Wt[0]=r[e],Wt[1]=r[e+1],Wt[2]=r[e+2],Wt[3]=r[e+3],gc[0]}var yc=new Float64Array([-0]),Te=new Uint8Array(yc.buffer);function Sf(r,e,t){yc[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 _f(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],yc[0]}var Kg=BigInt(Number.MAX_SAFE_INTEGER),qg=BigInt(Number.MIN_SAFE_INTEGER),Ge=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 dr;if(e<Kg&&e>qg)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>Bf&&(o=0n,++n>Bf&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return dr;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):dr}},dr=new Ge(0,0);dr.toBigInt=function(){return 0n};dr.zzEncode=dr.zzDecode=function(){return this};dr.length=function(){return 1};var Bf=4294967296n;function kf(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 If(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 wc(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 it(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function ss(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var bc=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,it(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 it(this,4);return ss(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw it(this,4);return ss(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw it(this,4);let e=Af(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw it(this,4);let e=_f(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 it(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return If(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw it(this,e);this.pos+=e}else do if(this.pos>=this.len)throw it(this);while(this.buf[this.pos++]&128);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 Ge(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 it(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 it(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 it(this,8);let e=ss(this.buf,this.pos+=4),t=ss(this.buf,this.pos+=4);return new Ge(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=mc(this.buf,this.pos);return this.pos+=he(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 xc(r){return new bc(r instanceof Uint8Array?r:r.subarray())}function De(r,e,t){let n=xc(r);return e.decode(n,void 0,t)}var vc={};Re(vc,{base10:()=>zg});var zg=Vt({prefix:"9",name:"base10",alphabet:"0123456789"});var Ec={};Re(Ec,{base16:()=>Gg,base16upper:()=>Wg});var Gg=se({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Wg=se({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Ac={};Re(Ac,{base2:()=>jg});var jg=se({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Sc={};Re(Sc,{base256emoji:()=>Qg});var Tf=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}"),Zg=Tf.reduce((r,e,t)=>(r[t]=e,r),[]),Xg=Tf.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function Yg(r){return r.reduce((e,t)=>(e+=Zg[t],e),"")}function Jg(r){let e=[];for(let t of r){let n=Xg[t.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var Qg=Or({prefix:"\u{1F680}",name:"base256emoji",encode:Yg,decode:Jg});var _c={};Re(_c,{base36:()=>e0,base36upper:()=>t0});var e0=Vt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),t0=Vt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Ic={};Re(Ic,{base64:()=>Bc,base64pad:()=>r0,base64url:()=>kc,base64urlpad:()=>n0});var Bc=se({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),r0=se({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),kc=se({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),n0=se({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Cc={};Re(Cc,{base8:()=>o0});var o0=se({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Tc={};Re(Tc,{identity:()=>s0});var s0=Or({prefix:"\0",name:"identity",encode:r=>Ou(r),decode:r=>Uu(r)});var E1=new TextEncoder,A1=new TextDecoder;var Pc={};Re(Pc,{sha256:()=>jr,sha512:()=>c0});function Nc({name:r,code:e,encode:t}){return new Lc(r,e,t)}var Lc=class{name;code;encode;constructor(e,t,n){this.name=e,this.code=t,this.encode=n}digest(e){if(e instanceof Uint8Array){let t=this.encode(e);return t instanceof Uint8Array?et(this.code,t):t.then(n=>et(this.code,n))}else throw Error("Unknown type, must be binary type")}};function Nf(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var jr=Nc({name:"sha2-256",code:18,encode:Nf("SHA-256")}),c0=Nc({name:"sha2-512",code:19,encode:Nf("SHA-512")});var On={...Tc,...Ac,...Cc,...vc,...Ec,...$a,..._c,...Ha,...Ic,...Sc},D1={...Pc,...za};function Rf(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Pf=Rf("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Rc=Rf("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=ke(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),l0={utf8:Pf,"utf-8":Pf,hex:On.base16,latin1:Rc,ascii:Rc,binary:Rc,...On},is=l0;function P(r,e="utf8"){let t=is[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function Dc(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return ke(i);o+i>e&&(n=ke(e),o=0);let a=n.subarray(o,o+=i);return o&7&&(o=(o|7)+1),a}}var pr=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function Mc(){}var Oc=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},u0=Dc();function f0(r){return globalThis.Buffer!=null?ke(r):u0(r)}var Vn=class{len;head;tail;states;constructor(){this.len=0,this.head=new pr(Mc,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new pr(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Fc((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(as,10,Ge.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Ge.fromBigInt(e);return this._push(as,t.length(),t)}uint64Number(e){return this._push(pc,he(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=Ge.fromBigInt(e).zzEncode();return this._push(as,t.length(),t)}sint64Number(e){let t=Ge.fromNumber(e).zzEncode();return this._push(as,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Uc,1,e?1:0)}fixed32(e){return this._push(Fn,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Ge.fromBigInt(e);return this._push(Fn,4,t.lo)._push(Fn,4,t.hi)}fixed64Number(e){let t=Ge.fromNumber(e);return this._push(Fn,4,t.lo)._push(Fn,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(Ef,4,e)}double(e){return this._push(Sf,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(Uc,1,0):this.uint32(t)._push(d0,t,e)}string(e){let t=kf(e);return t!==0?this.uint32(t)._push(wc,t,e):this._push(Uc,1,0)}fork(){return this.states=new Oc(this),this.head=this.tail=new pr(Mc,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 pr(Mc,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=f0(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function Uc(r,e,t){e[t]=r&255}function h0(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var Fc=class extends pr{next;constructor(e,t){super(h0,e,t),this.next=void 0}};function as(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 Fn(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 d0(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(Vn.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(p0,e,r),this},Vn.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(m0,e,r),this});function p0(r,e,t){e.set(r,t)}function m0(r,e,t){r.length<40?wc(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(P(r),t)}function Vc(){return new Vn}function Me(r,e){let t=Vc();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var Zr;(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"})(Zr||(Zr={}));function cs(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function Hc(r){function e(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let t=function(s,i){let a=e(s);i.int32(a)},n=function(s){let i=s.int32();return e(i)};return cs("enum",Zr.VARINT,t,n)}function Ue(r,e){return cs("message",Zr.LENGTH_DELIMITED,r,e)}var mr=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},Hn=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var ge;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1"})(ge||(ge={}));var $c;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1"})($c||($c={}));(function(r){r.codec=()=>Hc($c)})(ge||(ge={}));var ht;(function(r){let e;r.codec=()=>(e==null&&(e=Ue((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),ge.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.Type=ge.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Me(t,r.codec()),r.decode=(t,n)=>De(t,r.codec(),n)})(ht||(ht={}));var Kc;(function(r){let e;r.codec=()=>(e==null&&(e=Ue((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),ge.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.Type=ge.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Me(t,r.codec()),r.decode=(t,n)=>De(t,r.codec(),n)})(Kc||(Kc={}));var Jn={};Re(Jn,{MAX_RSA_KEY_SIZE:()=>Qs,generateRSAKeyPair:()=>el,jwkToJWKKeyPair:()=>Lh,jwkToPkcs1:()=>L0,jwkToPkix:()=>Jc,jwkToRSAPrivateKey:()=>Th,pkcs1ToJwk:()=>kh,pkcs1ToRSAPrivateKey:()=>Ch,pkixToJwk:()=>Ih,pkixToRSAPublicKey:()=>Qc});var g0=new Uint32Array([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]),jt=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Zt=new Uint32Array(64),qc=class extends Gr{constructor(){super(64,32,8,!1),this.A=jt[0]|0,this.B=jt[1]|0,this.C=jt[2]|0,this.D=jt[3]|0,this.E=jt[4]|0,this.F=jt[5]|0,this.G=jt[6]|0,this.H=jt[7]|0}get(){let{A:e,B:t,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,t,n,o,s,i,a,c]}set(e,t,n,o,s,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let l=0;l<16;l++,t+=4)Zt[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){let d=Zt[l-15],h=Zt[l-2],p=rt(d,7)^rt(d,18)^d>>>3,m=rt(h,17)^rt(h,19)^h>>>10;Zt[l]=m+Zt[l-7]+p+Zt[l-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:f}=this;for(let l=0;l<64;l++){let d=rt(a,6)^rt(a,11)^rt(a,25),h=f+d+tf(a,c,u)+g0[l]+Zt[l]|0,m=(rt(n,2)^rt(n,13)^rt(n,22))+rf(n,o,s)|0;f=u,u=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+m|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,f=f+this.H|0,this.set(n,o,s,i,a,c,u,f)}roundClean(){Zt.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var Xr=Wo(()=>new qc);var q=sr(Mf());function gr(r,e){let t=0;if(r.length===1)return r[0];for(let n=r.length-1;n>=0;n--)t+=r[r.length-1-n]*Math.pow(2,e*n);return t}function Xt(r,e,t=-1){let n=t,o=r,s=0,i=Math.pow(2,e);for(let a=1;a<8;a++){if(r<i){let c;if(n<0)c=new ArrayBuffer(a),s=a;else{if(n<a)return new ArrayBuffer(0);c=new ArrayBuffer(n),s=n}let u=new Uint8Array(c);for(let f=a-1;f>=0;f--){let l=Math.pow(2,f*e);u[s-f-1]=Math.floor(o/l),o-=u[s-f-1]*l}return c}i*=Math.pow(2,e)}return new ArrayBuffer(0)}function fs(...r){let e=0,t=0;for(let s of r)e+=s.length;let n=new ArrayBuffer(e),o=new Uint8Array(n);for(let s of r)o.set(s,t),t+=s.length;return o}function Gc(){let r=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){let a=r[0]===255&&r[1]&128,c=r[0]===0&&(r[1]&128)===0;(a||c)&&this.warnings.push("Needlessly long format")}let e=new ArrayBuffer(this.valueHex.byteLength),t=new Uint8Array(e);for(let a=0;a<this.valueHex.byteLength;a++)t[a]=0;t[0]=r[0]&128;let n=gr(t,8),o=new ArrayBuffer(this.valueHex.byteLength),s=new Uint8Array(o);for(let a=0;a<this.valueHex.byteLength;a++)s[a]=r[a];return s[0]&=127,gr(s,8)-n}function Uf(r){let e=r<0?r*-1:r,t=128;for(let n=1;n<8;n++){if(e<=t){if(r<0){let i=t-e,a=Xt(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=Xt(e,8,n),s=new Uint8Array(o);if(s[0]&128){let i=o.slice(0),a=new Uint8Array(i);o=new ArrayBuffer(o.byteLength+1),s=new Uint8Array(o);for(let c=0;c<i.byteLength;c++)s[c+1]=a[c];s[0]=0}return o}t*=Math.pow(2,8)}return new ArrayBuffer(0)}function Of(r,e){if(r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let o=0;o<t.length;o++)if(t[o]!==n[o])return!1;return!0}function qe(r,e){let t=r.toString(10);if(e<t.length)return"";let n=e-t.length,o=new Array(n);for(let i=0;i<n;i++)o[i]="0";return o.join("").concat(t)}var gv=Math.log(2);function hs(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function Wc(r){let e=0,t=0;for(let o=0;o<r.length;o++){let s=r[o];e+=s.byteLength}let n=new Uint8Array(e);for(let o=0;o<r.length;o++){let s=r[o];n.set(new Uint8Array(s),t),t+=s.byteLength}return n.buffer}function Pt(r,e,t,n){return e instanceof Uint8Array?e.byteLength?t<0?(r.error="Wrong parameter: inputOffset less than zero",!1):n<0?(r.error="Wrong parameter: inputLength less than zero",!1):e.byteLength-t-n<0?(r.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):!0:(r.error="Wrong parameter: inputBuffer has zero length",!1):(r.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}var Kn=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return Wc(this.items)}},$n=[new Uint8Array([1])],Ff="0123456789";var tn="",at=new ArrayBuffer(0),jc=new Uint8Array(0),qn="EndOfContent",Hf="OCTET STRING",$f="BIT STRING";function Rt(r){var e;return e=class extends r{constructor(...n){var o;super(...n);let s=n[0]||{};this.isHexOnly=(o=s.isHexOnly)!==null&&o!==void 0?o:!1,this.valueHexView=s.valueHex?q.BufferSourceConverter.toUint8Array(s.valueHex):jc}get valueHex(){return this.valueHexView.slice().buffer}set valueHex(n){this.valueHexView=new Uint8Array(n)}fromBER(n,o,s){let i=n instanceof ArrayBuffer?new Uint8Array(n):n;if(!Pt(this,i,o,s))return-1;let a=o+s;return this.valueHexView=i.subarray(o,a),this.valueHexView.length?(this.blockLength=s,a):(this.warnings.push("Zero buffer length"),o)}toBER(n=!1){return this.isHexOnly?n?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",at)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:q.Convert.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}var Tt=class{constructor({blockLength:e=0,error:t=tn,warnings:n=[],valueBeforeDecode:o=jc}={}){this.blockLength=e,this.error=t,this.warnings=n,this.valueBeforeDecodeView=q.BufferSourceConverter.toUint8Array(o)}static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:q.Convert.ToHex(this.valueBeforeDecodeView)}}};Tt.NAME="baseBlock";var Le=class extends Tt{fromBER(e,t,n){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,t){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}};Le.NAME="valueBlock";var ds=class extends Rt(Tt){constructor({idBlock:e={}}={}){var t,n,o,s;super(),e?(this.isHexOnly=(t=e.isHexOnly)!==null&&t!==void 0?t:!1,this.valueHexView=e.valueHex?q.BufferSourceConverter.toUint8Array(e.valueHex):jc,this.tagClass=(n=e.tagClass)!==null&&n!==void 0?n:-1,this.tagNumber=(o=e.tagNumber)!==null&&o!==void 0?o:-1,this.isConstructed=(s=e.isConstructed)!==null&&s!==void 0?s:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(e=!1){let t=0;switch(this.tagClass){case 1:t|=0;break;case 2:t|=64;break;case 3:t|=128;break;case 4:t|=192;break;default:return this.error="Unknown tag class",at}if(this.isConstructed&&(t|=32),this.tagNumber<31&&!this.isHexOnly){let o=new Uint8Array(1);if(!e){let s=this.tagNumber;s&=31,t|=s,o[0]=t}return o.buffer}if(!this.isHexOnly){let o=Xt(this.tagNumber,7),s=new Uint8Array(o),i=o.byteLength,a=new Uint8Array(i+1);if(a[0]=t|31,!e){for(let c=0;c<i-1;c++)a[c+1]=s[c]|128;a[i]=s[i-1]}return a.buffer}let n=new Uint8Array(this.valueHexView.byteLength+1);if(n[0]=t|31,!e){let o=this.valueHexView;for(let s=0;s<o.length-1;s++)n[s+1]=o[s]|128;n[this.valueHexView.byteLength]=o[o.length-1]}return n.buffer}fromBER(e,t,n){let o=q.BufferSourceConverter.toUint8Array(e);if(!Pt(this,o,t,n))return-1;let s=o.subarray(t,t+n);if(s.length===0)return this.error="Zero buffer length",-1;switch(s[0]&192){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=(s[0]&32)===32,this.isHexOnly=!1;let a=s[0]&31;if(a!==31)this.tagNumber=a,this.blockLength=1;else{let c=1,u=this.valueHexView=new Uint8Array(255),f=255;for(;s[c]&128;){if(u[c-1]=s[c]&127,c++,c>=s.length)return this.error="End of input reached before message was fully decoded",-1;if(c===f){f+=255;let d=new Uint8Array(f);for(let h=0;h<u.length;h++)d[h]=u[h];u=this.valueHexView=new Uint8Array(f)}}this.blockLength=c+1,u[c-1]=s[c]&127;let l=new Uint8Array(c);for(let d=0;d<c;d++)l[d]=u[d];u=this.valueHexView=new Uint8Array(c),u.set(l),this.blockLength<=9?this.tagNumber=gr(u,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(this.tagClass===1&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return t+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}};ds.NAME="identificationBlock";var ps=class extends Tt{constructor({lenBlock:e={}}={}){var t,n,o;super(),this.isIndefiniteForm=(t=e.isIndefiniteForm)!==null&&t!==void 0?t:!1,this.longFormUsed=(n=e.longFormUsed)!==null&&n!==void 0?n:!1,this.length=(o=e.length)!==null&&o!==void 0?o:0}fromBER(e,t,n){let o=q.BufferSourceConverter.toUint8Array(e);if(!Pt(this,o,t,n))return-1;let s=o.subarray(t,t+n);if(s.length===0)return this.error="Zero buffer length",-1;if(s[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=s[0]===128,this.isIndefiniteForm)return this.blockLength=1,t+this.blockLength;if(this.longFormUsed=!!(s[0]&128),this.longFormUsed===!1)return this.length=s[0],this.blockLength=1,t+this.blockLength;let i=s[0]&127;if(i>8)return this.error="Too big integer",-1;if(i+1>s.length)return this.error="End of input reached before message was fully decoded",-1;let a=t+1,c=o.subarray(a,a+i);return c[i-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=gr(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=i+1,t+this.blockLength}toBER(e=!1){let t,n;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=128),t;if(this.longFormUsed){let o=Xt(this.length,8);if(o.byteLength>127)return this.error="Too big length",at;if(t=new ArrayBuffer(o.byteLength+1),e)return t;let s=new Uint8Array(o);n=new Uint8Array(t),n[0]=o.byteLength|128;for(let i=0;i<o.byteLength;i++)n[i+1]=s[i];return t}return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=this.length),t}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}};ps.NAME="lengthBlock";var C={},Ae=class extends Tt{constructor({name:e=tn,optional:t=!1,primitiveSchema:n,...o}={},s){super(o),this.name=e,this.optional=t,n&&(this.primitiveSchema=n),this.idBlock=new ds(o),this.lenBlock=new ps(o),this.valueBlock=s?new s(o):new Le(o)}fromBER(e,t,n){let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}toBER(e,t){let n=t||new Kn;t||Kf(this);let o=this.idBlock.toBER(e);if(n.write(o),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,n),n.write(new ArrayBuffer(2));else{let s=this.valueBlock.toBER(e);this.lenBlock.length=s.byteLength;let i=this.lenBlock.toBER(e);n.write(i),n.write(s)}return t?at:n.final()}toJSON(){let e={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(e.primitiveSchema=this.primitiveSchema.toJSON()),e}toString(e="ascii"){return e==="ascii"?this.onAsciiEncoding():q.Convert.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${q.Convert.ToHex(this.valueBlock.valueBeforeDecodeView)}`}isEqual(e){if(this===e)return!0;if(!(e instanceof this.constructor))return!1;let t=this.toBER(),n=e.toBER();return Of(t,n)}};Ae.NAME="BaseBlock";function Kf(r){if(r instanceof C.Constructed)for(let e of r.valueBlock.value)Kf(e)&&(r.lenBlock.isIndefiniteForm=!0);return!!r.lenBlock.isIndefiniteForm}var ms=class extends Ae{constructor({value:e=tn,...t}={},n){super(t,n),e&&this.fromString(e)}getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}fromBER(e,t,n){let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}};ms.NAME="BaseStringBlock";var gs=class extends Rt(Le){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};gs.NAME="PrimitiveValueBlock";var qf,ys=class extends Ae{constructor(e={}){super(e,gs),this.idBlock.isConstructed=!1}};qf=ys;C.Primitive=qf;ys.NAME="PRIMITIVE";function _0(r,e){if(r instanceof e)return r;let t=new e;return t.idBlock=r.idBlock,t.lenBlock=r.lenBlock,t.warnings=r.warnings,t.valueBeforeDecodeView=r.valueBeforeDecodeView,t}function Ys(r,e=0,t=r.length){let n=e,o=new Ae({},Le),s=new Tt;if(!Pt(s,r,e,t))return o.error=s.error,{offset:-1,result:o};if(!r.subarray(e,e+t).length)return o.error="Zero buffer length",{offset:-1,result:o};let a=o.idBlock.fromBER(r,e,t);if(o.idBlock.warnings.length&&o.warnings.concat(o.idBlock.warnings),a===-1)return o.error=o.idBlock.error,{offset:-1,result:o};if(e=a,t-=o.idBlock.blockLength,a=o.lenBlock.fromBER(r,e,t),o.lenBlock.warnings.length&&o.warnings.concat(o.lenBlock.warnings),a===-1)return o.error=o.lenBlock.error,{offset:-1,result:o};if(e=a,t-=o.lenBlock.blockLength,!o.idBlock.isConstructed&&o.lenBlock.isIndefiniteForm)return o.error="Indefinite length form used for primitive encoding form",{offset:-1,result:o};let c=Ae;switch(o.idBlock.tagClass){case 1:if(o.idBlock.tagNumber>=37&&o.idBlock.isHexOnly===!1)return o.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:o};switch(o.idBlock.tagNumber){case 0:if(o.idBlock.isConstructed&&o.lenBlock.length>0)return o.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:o};c=C.EndOfContent;break;case 1:c=C.Boolean;break;case 2:c=C.Integer;break;case 3:c=C.BitString;break;case 4:c=C.OctetString;break;case 5:c=C.Null;break;case 6:c=C.ObjectIdentifier;break;case 10:c=C.Enumerated;break;case 12:c=C.Utf8String;break;case 13:c=C.RelativeObjectIdentifier;break;case 14:c=C.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:c=C.Sequence;break;case 17:c=C.Set;break;case 18:c=C.NumericString;break;case 19:c=C.PrintableString;break;case 20:c=C.TeletexString;break;case 21:c=C.VideotexString;break;case 22:c=C.IA5String;break;case 23:c=C.UTCTime;break;case 24:c=C.GeneralizedTime;break;case 25:c=C.GraphicString;break;case 26:c=C.VisibleString;break;case 27:c=C.GeneralString;break;case 28:c=C.UniversalString;break;case 29:c=C.CharacterString;break;case 30:c=C.BmpString;break;case 31:c=C.DATE;break;case 32:c=C.TimeOfDay;break;case 33:c=C.DateTime;break;case 34:c=C.Duration;break;default:{let u=o.idBlock.isConstructed?new C.Constructed:new C.Primitive;u.idBlock=o.idBlock,u.lenBlock=o.lenBlock,u.warnings=o.warnings,o=u}}break;case 2:case 3:case 4:default:c=o.idBlock.isConstructed?C.Constructed:C.Primitive}return o=_0(o,c),a=o.fromBER(r,e,o.lenBlock.isIndefiniteForm?t:o.lenBlock.length),o.valueBeforeDecodeView=r.subarray(n,n+o.blockLength),{offset:a,result:o}}function Zc(r){if(!r.byteLength){let e=new Ae({},Le);return e.error="Input buffer has zero length",{offset:-1,result:e}}return Ys(q.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function B0(r,e){return r?1:e}var dt=class extends Le{constructor({value:e=[],isIndefiniteForm:t=!1,...n}={}){super(n),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,n){let o=q.BufferSourceConverter.toUint8Array(e);if(!Pt(this,o,t,n))return-1;if(this.valueBeforeDecodeView=o.subarray(t,t+n),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),t;let s=t;for(;B0(this.isIndefiniteForm,n)>0;){let i=Ys(o,s,n);if(i.offset===-1)return this.error=i.result.error,this.warnings.concat(i.result.warnings),-1;if(s=i.offset,this.blockLength+=i.result.blockLength,n-=i.result.blockLength,this.value.push(i.result),this.isIndefiniteForm&&i.result.constructor.NAME===qn)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===qn?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(e,t){let n=t||new Kn;for(let o=0;o<this.value.length;o++)this.value[o].toBER(e,n);return t?at:n.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}};dt.NAME="ConstructedValueBlock";var zf,Yt=class extends Ae{constructor(e={}){super(e,dt),this.idBlock.isConstructed=!0}fromBER(e,t,n){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){let e=[];for(let n of this.valueBlock.value)e.push(n.toString("ascii").split(`
|
|
3
3
|
`).map(o=>` ${o}`).join(`
|
|
4
4
|
`));let t=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${t} :
|
|
5
5
|
${e.join(`
|
|
6
|
-
`)}`:`${t} :`}};vf=er;C.Constructed=vf;er.NAME="CONSTRUCTED";var is=class extends Pe{fromBER(e,t,n){return t}toBER(e){return ht}};is.override="EndOfContentValueBlock";var _f,as=class extends Ie{constructor(e={}){super(e,is),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};_f=as;C.EndOfContent=_f;as.NAME=Gn;var Af,tr=class extends Ie{constructor(e={}){super(e,Pe),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,t,n){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=n,t+n>e.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):t+n}toBER(e,t){let n=new ArrayBuffer(2);if(!e){let o=new Uint8Array(n);o[0]=5,o[1]=0}return t&&t.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};Af=tr;C.Null=Af;tr.NAME="NULL";var cs=class extends Ut(Pe){constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=q.BufferSourceConverter.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}get value(){for(let e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}fromBER(e,t,n){let o=q.BufferSourceConverter.toUint8Array(e);return Ot(this,o,t,n)?(this.valueHexView=o.subarray(t,t+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,yc.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};cs.NAME="BooleanValueBlock";var Sf,ls=class extends Ie{constructor(e={}){super(e,cs),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};Sf=ls;C.Boolean=Sf;ls.NAME="BOOLEAN";var us=class extends Ut(bt){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,n){let o=0;if(this.isConstructed){if(this.isHexOnly=!1,o=bt.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let s=0;s<this.value.length;s++){let i=this.value[s].constructor.NAME;if(i===Gn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(i!==wf)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,o=super.fromBER(e,t,n),this.blockLength=n;return o}toBER(e,t){return this.isConstructed?bt.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};us.NAME="OctetStringValueBlock";var Rf,Dt=class r extends Ie{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},us),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,t,n){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,n===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),t;if(!this.valueBlock.isConstructed){let s=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+n);try{if(s.byteLength){let i=Ms(s,0,s.byteLength);i.offset!==-1&&i.offset===n&&(this.valueBlock.value=[i.result])}}catch{}}return super.fromBER(e,t,n)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?er.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${q.Convert.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let e=[];for(let t of this.valueBlock.value)t instanceof r&&e.push(t.valueBlock.valueHexView);return q.BufferSourceConverter.concat(e)}};Rf=Dt;C.OctetString=Rf;Dt.NAME=wf;var fs=class extends Ut(bt){constructor({unusedBits:e=0,isConstructed:t=!1,...n}={}){super(n),this.unusedBits=e,this.isConstructed=t,this.blockLength=this.valueHexView.byteLength}fromBER(e,t,n){if(!n)return t;let o=-1;if(this.isConstructed){if(o=bt.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let a of this.value){let c=a.constructor.NAME;if(c===Gn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==bf)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let u=a.valueBlock;if(this.unusedBits>0&&u.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=u.unusedBits}return o}let s=q.BufferSourceConverter.toUint8Array(e);if(!Ot(this,s,t,n))return-1;let i=s.subarray(t,t+n);if(this.unusedBits=i[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let a=i.subarray(1);try{if(a.byteLength){let c=Ms(a,0,a.byteLength);c.offset!==-1&&c.offset===n-1&&(this.value=[c.result])}}catch{}}return this.valueHexView=i.subarray(1),this.blockLength=i.length,t+n}toBER(e,t){if(this.isConstructed)return bt.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return ht;let n=new Uint8Array(this.valueHexView.length+1);return n[0]=this.unusedBits,n.set(this.valueHexView,1),n.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}};fs.NAME="BitStringValueBlock";var If,sn=class extends Ie{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},fs),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,n){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return er.prototype.onAsciiEncoding.call(this);{let e=[],t=this.valueBlock.valueHexView;for(let o of t)e.push(o.toString(2).padStart(8,"0"));let n=e.join("");return`${this.constructor.NAME} : ${n.substring(0,n.length-this.valueBlock.unusedBits)}`}}};If=sn;C.BitString=If;sn.NAME=bf;var Tf;function a0(r,e){let t=new Uint8Array([0]),n=new Uint8Array(r),o=new Uint8Array(e),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,u=0,f=c<i?i:c,l=0;for(let p=f;p>=0;p--,l++){switch(!0){case l<a.length:u=s[i-l]+a[c-l]+t[0];break;default:u=s[i-l]+t[0]}switch(t[0]=u/10,!0){case l>=s.length:s=Jo(new Uint8Array([u%10]),s);break;default:s[i-l]=u%10}}return t[0]>0&&(s=Jo(t,s)),s}function yf(r){if(r>=qn.length)for(let e=qn.length;e<=r;e++){let t=new Uint8Array([0]),n=qn[e-1].slice(0);for(let o=n.length-1;o>=0;o--){let s=new Uint8Array([(n[o]<<1)+t[0]]);t[0]=s[0]/10,n[o]=s[0]%10}t[0]>0&&(n=Jo(t,n)),qn.push(n)}return qn[r]}function c0(r,e){let t=0,n=new Uint8Array(r),o=new Uint8Array(e),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,u,f=0;for(let l=c;l>=0;l--,f++)switch(u=s[i-f]-a[c-f]-t,!0){case u<0:t=1,s[i-f]=u+10;break;default:t=0,s[i-f]=u}if(t>0)for(let l=i-c+1;l>=0;l--,f++)if(u=s[i-f]-t,u<0)t=1,s[i-f]=u+10;else{t=0,s[i-f]=u;break}return s.slice()}var Yn=class extends Ut(Pe){constructor({value:e,...t}={}){super(t),this._valueDec=0,t.valueHex&&this.setValueHex(),e!==void 0&&(this.valueDec=e)}setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=yc.call(this)))}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(pf(e))}get valueDec(){return this._valueDec}fromDER(e,t,n,o=0){let s=this.fromBER(e,t,n);if(s===-1)return s;let i=this.valueHexView;return i[0]===0&&i[1]&128?this.valueHexView=i.subarray(1):o!==0&&i.length<o&&(o-i.length>1&&(o=i.length+1),this.valueHexView=i.subarray(o-i.length)),s}toDER(e=!1){let t=this.valueHexView;switch(!0){case(t[0]&128)!==0:{let n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(t,1),this.valueHexView=n}break;case(t[0]===0&&(t[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(e)}fromBER(e,t,n){let o=super.fromBER(e,t,n);return o===-1||this.setValueHex(),o}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let e=this.valueHexView.length*8-1,t=new Uint8Array(this.valueHexView.length*8/3),n=0,o,s=this.valueHexView,i="",a=!1;for(let c=s.byteLength-1;c>=0;c--){o=s[c];for(let u=0;u<8;u++){if((o&1)===1)switch(n){case e:t=c0(yf(n),t),i="-";break;default:t=a0(t,yf(n))}n++,o>>=1}}for(let c=0;c<t.length;c++)t[c]&&(a=!0),a&&(i+=gf.charAt(t[c]));return a===!1&&(i+=gf.charAt(0)),i}};Tf=Yn;Yn.NAME="IntegerValueBlock";Object.defineProperty(Tf.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var Bf,pe=class r extends Ie{constructor(e={}){super(e,Yn),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return es(),BigInt(this.valueBlock.toString())}static fromBigInt(e){es();let t=BigInt(e),n=new zn,o=t.toString(16).replace(/^-/,""),s=new Uint8Array(q.Convert.FromHex(o));if(t<0){let a=new Uint8Array(s.length+(s[0]&128?1:0));a[0]|=128;let u=BigInt(`0x${q.Convert.ToHex(a)}`)+t,f=q.BufferSourceConverter.toUint8Array(q.Convert.FromHex(u.toString(16)));f[0]|=128,n.write(f)}else s[0]&128&&n.write(new Uint8Array([0])),n.write(s);return new r({valueHex:n.final()})}convertToDER(){let e=new r({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new r({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};Bf=pe;C.Integer=Bf;pe.NAME="INTEGER";var Cf,hs=class extends pe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};Cf=hs;C.Enumerated=Cf;hs.NAME="ENUMERATED";var Wn=class extends Ut(Pe){constructor({valueDec:e=-1,isFirstSid:t=!1,...n}={}){super(n),this.valueDec=e,this.isFirstSid=t}fromBER(e,t,n){if(!n)return t;let o=q.BufferSourceConverter.toUint8Array(e);if(!Ot(this,o,t,n))return-1;let s=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,!!(s[a]&128));a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,s[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Sr(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){es();let t=BigInt(e).toString(2);for(;t.length%7;)t="0"+t;let n=new Uint8Array(t.length/7);for(let o=0;o<n.length;o++)n[o]=parseInt(t.slice(o*7,o*7+7),2)+(o+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let t=Jt(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",ht;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),s=t.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n}toString(){let e="";if(this.isHexOnly)e=q.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){let t=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",t-=40):(e="2.",t-=80),e+=t.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};Wn.NAME="sidBlock";var ds=class extends Pe{constructor({value:e=an,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new Wn;if(o=s.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.value.length===0&&(s.isFirstSid=!0),this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(e){let t=[];for(let n=0;n<this.value.length;n++){let o=this.value[n].toBER(e);if(o.byteLength===0)return this.error=this.value[n].error,ht;t.push(o)}return wc(t)}fromString(e){this.value=[];let t=0,n=0,o="",s=!1;do if(n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1,s){let i=this.value[0],a=0;switch(i.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:this.value=[];return}let c=parseInt(o,10);if(isNaN(c))return;i.valueDec=c+a,s=!1}else{let i=new Wn;if(o>Number.MAX_SAFE_INTEGER){es();let a=BigInt(o);i.valueBigInt=a}else if(i.valueDec=parseInt(o,10),isNaN(i.valueDec))return;this.value.length||(i.isFirstSid=!0,s=!0),this.value.push(i)}while(n!==-1)}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),t?(o=`{${o}}`,this.value[n].isFirstSid?e=`2.{${o} - 80}`:e+=o):e+=o}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};ds.NAME="ObjectIdentifierValueBlock";var kf,ft=class extends Ie{constructor(e={}){super(e,ds),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};kf=ft;C.ObjectIdentifier=kf;ft.NAME="OBJECT IDENTIFIER";var jn=class extends Ut(Lt){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,n){if(n===0)return t;let o=q.BufferSourceConverter.toUint8Array(e);if(!Ot(this,o,t,n))return-1;let s=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,!!(s[a]&128));a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,s[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Sr(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let t=Jt(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",ht;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),s=t.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n.buffer}toString(){let e="";return this.isHexOnly?e=q.Convert.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};jn.NAME="relativeSidBlock";var ps=class extends Pe{constructor({value:e=an,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new jn;if(o=s.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(e,t){let n=[];for(let o=0;o<this.value.length;o++){let s=this.value[o].toBER(e);if(s.byteLength===0)return this.error=this.value[o].error,ht;n.push(s)}return wc(n)}fromString(e){this.value=[];let t=0,n=0,o="";do{n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1;let s=new jn;if(s.valueDec=parseInt(o,10),isNaN(s.valueDec))return!0;this.value.push(s)}while(n!==-1);return!0}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),t&&(o=`{${o}}`),e+=o}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};ps.NAME="RelativeObjectIdentifierValueBlock";var Nf,ms=class extends Ie{constructor(e={}){super(e,ps),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};Nf=ms;C.RelativeObjectIdentifier=Nf;ms.NAME="RelativeObjectIdentifier";var Lf,_e=class extends er{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};Lf=_e;C.Sequence=Lf;_e.NAME="SEQUENCE";var Df,gs=class extends er{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};Df=gs;C.Set=Df;gs.NAME="SET";var ys=class extends Ut(Pe){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=an}toJSON(){return{...super.toJSON(),value:this.value}}};ys.NAME="StringValueBlock";var ws=class extends ys{};ws.NAME="SimpleStringValueBlock";var Ke=class extends ns{constructor({...e}={}){super(e,ws)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,q.BufferSourceConverter.toUint8Array(e))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=e.charCodeAt(o);this.valueBlock.value=e}};Ke.NAME="SIMPLE STRING";var bs=class extends Ke{fromBuffer(e){this.valueBlock.valueHexView=q.BufferSourceConverter.toUint8Array(e);try{this.valueBlock.value=q.Convert.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=q.Convert.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(q.Convert.FromUtf8String(e)),this.valueBlock.value=e}};bs.NAME="Utf8StringValueBlock";var Pf,Pt=class extends bs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};Pf=Pt;C.Utf8String=Pf;Pt.NAME="UTF8String";var Es=class extends Ke{fromBuffer(e){this.valueBlock.value=q.Convert.ToUtf16String(e),this.valueBlock.valueHexView=q.BufferSourceConverter.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(q.Convert.FromUtf16String(e))}};Es.NAME="BmpStringValueBlock";var Of,xs=class extends Es{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};Of=xs;C.BmpString=Of;xs.NAME="BMPString";var vs=class extends Ke{fromBuffer(e){let t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),n=new Uint8Array(t);for(let o=0;o<n.length;o+=4)n[o]=n[o+3],n[o+1]=n[o+2],n[o+2]=0,n[o+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(t))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t*4);for(let o=0;o<t;o++){let s=Jt(e.charCodeAt(o),8),i=new Uint8Array(s);if(i.length>4)continue;let a=4-i.length;for(let c=i.length-1;c>=0;c--)n[o*4+c+a]=i[c]}this.valueBlock.value=e}};vs.NAME="UniversalStringValueBlock";var Uf,_s=class extends vs{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};Uf=_s;C.UniversalString=Uf;_s.NAME="UniversalString";var Mf,As=class extends Ke{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};Mf=As;C.NumericString=Mf;As.NAME="NumericString";var Ff,Ss=class extends Ke{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};Ff=Ss;C.PrintableString=Ff;Ss.NAME="PrintableString";var Vf,Rs=class extends Ke{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};Vf=Rs;C.TeletexString=Vf;Rs.NAME="TeletexString";var Kf,Is=class extends Ke{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};Kf=Is;C.VideotexString=Kf;Is.NAME="VideotexString";var Hf,Ts=class extends Ke{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};Hf=Ts;C.IA5String=Hf;Ts.NAME="IA5String";var $f,Bs=class extends Ke{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};$f=Bs;C.GraphicString=$f;Bs.NAME="GraphicString";var qf,Xn=class extends Ke{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};qf=Xn;C.VisibleString=qf;Xn.NAME="VisibleString";var zf,Cs=class extends Ke{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};zf=Cs;C.GeneralString=zf;Cs.NAME="GeneralString";var Gf,ks=class extends Ke{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};Gf=ks;C.CharacterString=Gf;ks.NAME="CharacterString";var Yf,Zn=class extends Xn{constructor({value:e,valueDate:t,...n}={}){if(super(n),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,e){this.fromString(e),this.valueBlock.valueHexView=new Uint8Array(e.length);for(let o=0;o<e.length;o++)this.valueBlock.valueHexView[o]=e.charCodeAt(o)}t&&(this.fromDate(t),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,q.BufferSourceConverter.toUint8Array(e)))}toBuffer(){let e=this.toString(),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);return t}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){let n=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(e);if(n===null){this.error="Wrong input string for conversion";return}let o=parseInt(n[1],10);o>=50?this.year=1900+o:this.year=2e3+o,this.month=parseInt(n[2],10),this.day=parseInt(n[3],10),this.hour=parseInt(n[4],10),this.minute=parseInt(n[5],10),this.second=parseInt(n[6],10)}toString(e="iso"){if(e==="iso"){let t=new Array(7);return t[0]=Ge(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=Ge(this.month,2),t[2]=Ge(this.day,2),t[3]=Ge(this.hour,2),t[4]=Ge(this.minute,2),t[5]=Ge(this.second,2),t[6]="Z",t.join("")}return super.toString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}};Yf=Zn;C.UTCTime=Yf;Zn.NAME="UTCTime";var Wf,Ns=class extends Zn{constructor(e={}){var t;super(e),(t=this.millisecond)!==null&&t!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond))}fromString(e){let t=!1,n="",o="",s=0,i,a=0,c=0;if(e[e.length-1]==="Z")n=e.substring(0,e.length-1),t=!0;else{let l=new Number(e[e.length-1]);if(isNaN(l.valueOf()))throw new Error("Wrong input string for conversion");n=e}if(t){if(n.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(n.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let l=1,p=n.indexOf("+"),h="";if(p===-1&&(p=n.indexOf("-"),l=-1),p!==-1){if(h=n.substring(p+1),n=n.substring(0,p),h.length!==2&&h.length!==4)throw new Error("Wrong input string for conversion");let d=parseInt(h.substring(0,2),10);if(isNaN(d.valueOf()))throw new Error("Wrong input string for conversion");if(a=l*d,h.length===4){if(d=parseInt(h.substring(2,4),10),isNaN(d.valueOf()))throw new Error("Wrong input string for conversion");c=l*d}}}let u=n.indexOf(".");if(u===-1&&(u=n.indexOf(",")),u!==-1){let l=new Number(`0${n.substring(u)}`);if(isNaN(l.valueOf()))throw new Error("Wrong input string for conversion");s=l.valueOf(),o=n.substring(0,u)}else o=n;switch(!0){case o.length===8:if(i=/(\d{4})(\d{2})(\d{2})/ig,u!==-1)throw new Error("Wrong input string for conversion");break;case o.length===10:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=60*s;this.minute=Math.floor(l),l=60*(l-this.minute),this.second=Math.floor(l),l=1e3*(l-this.second),this.millisecond=Math.floor(l)}break;case o.length===12:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=60*s;this.second=Math.floor(l),l=1e3*(l-this.second),this.millisecond=Math.floor(l)}break;case o.length===14:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=1e3*s;this.millisecond=Math.floor(l)}break;default:throw new Error("Wrong input string for conversion")}let f=i.exec(o);if(f===null)throw new Error("Wrong input string for conversion");for(let l=1;l<f.length;l++)switch(l){case 1:this.year=parseInt(f[l],10);break;case 2:this.month=parseInt(f[l],10);break;case 3:this.day=parseInt(f[l],10);break;case 4:this.hour=parseInt(f[l],10)+a;break;case 5:this.minute=parseInt(f[l],10)+c;break;case 6:this.second=parseInt(f[l],10);break;default:throw new Error("Wrong input string for conversion")}if(t===!1){let l=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=l.getUTCFullYear(),this.month=l.getUTCMonth(),this.day=l.getUTCDay(),this.hour=l.getUTCHours(),this.minute=l.getUTCMinutes(),this.second=l.getUTCSeconds(),this.millisecond=l.getUTCMilliseconds()}}toString(e="iso"){if(e==="iso"){let t=[];return t.push(Ge(this.year,4)),t.push(Ge(this.month,2)),t.push(Ge(this.day,2)),t.push(Ge(this.hour,2)),t.push(Ge(this.minute,2)),t.push(Ge(this.second,2)),this.millisecond!==0&&(t.push("."),t.push(Ge(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};Wf=Ns;C.GeneralizedTime=Wf;Ns.NAME="GeneralizedTime";var jf,Ls=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};jf=Ls;C.DATE=jf;Ls.NAME="DATE";var Xf,Ds=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};Xf=Ds;C.TimeOfDay=Xf;Ds.NAME="TimeOfDay";var Zf,Ps=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};Zf=Ps;C.DateTime=Zf;Ps.NAME="DateTime";var Qf,Os=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};Qf=Os;C.Duration=Qf;Os.NAME="Duration";var Jf,Us=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};Jf=Us;C.TIME=Jf;Us.NAME="TIME";function u0(r){let{result:e}=cn(r),t=e.valueBlock.value;return{n:F(Et(t[1].toBigInt()),"base64url"),e:F(Et(t[2].toBigInt()),"base64url"),d:F(Et(t[3].toBigInt()),"base64url"),p:F(Et(t[4].toBigInt()),"base64url"),q:F(Et(t[5].toBigInt()),"base64url"),dp:F(Et(t[6].toBigInt()),"base64url"),dq:F(Et(t[7].toBigInt()),"base64url"),qi:F(Et(t[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}function f0(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 E("JWK was missing components","ERR_INVALID_PARAMETERS");let t=new _e({value:[new pe({value:0}),pe.fromBigInt(xt(L(r.n,"base64url"))),pe.fromBigInt(xt(L(r.e,"base64url"))),pe.fromBigInt(xt(L(r.d,"base64url"))),pe.fromBigInt(xt(L(r.p,"base64url"))),pe.fromBigInt(xt(L(r.q,"base64url"))),pe.fromBigInt(xt(L(r.dp,"base64url"))),pe.fromBigInt(xt(L(r.dq,"base64url"))),pe.fromBigInt(xt(L(r.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}function h0(r){let{result:e}=cn(r),t=e.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:F(Et(t[0].toBigInt()),"base64url"),e:F(Et(t[1].toBigInt()),"base64url")}}function d0(r){if(r.n==null||r.e==null)throw new E("JWK was missing components","ERR_INVALID_PARAMETERS");let t=new _e({value:[new _e({value:[new ft({value:"1.2.840.113549.1.1.1"}),new tr]}),new sn({valueHex:new _e({value:[pe.fromBigInt(xt(L(r.n,"base64url"))),pe.fromBigInt(xt(L(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}function Et(r){let e=r.toString(16);e.length%2>0&&(e=`0${e}`);let t=e.length/2,n=new Uint8Array(t),o=0,s=0;for(;o<t;)n[o]=parseInt(e.slice(s,s+2),16),o+=1,s+=2;return n}function xt(r){let e=[];return r.forEach(function(t){let n=t.toString(16);n.length%2>0&&(n=`0${n}`),e.push(n)}),BigInt("0x"+e.join(""))}var p0=16,Ec=32,xc=1e4;async function m0(r,e){let t=Ue.get(),o=new _e({value:[new pe({value:0}),new _e({value:[new ft({value:"1.2.840.113549.1.1.1"}),new tr]}),new Dt({valueHex:r.marshal()})]}).toBER(),s=new Uint8Array(o,0,o.byteLength),i=et(p0),a=await mc(On,e,i,{c:xc,dkLen:Ec}),c=et(16),u=await t.subtle.importKey("raw",a,"AES-CBC",!1,["encrypt"]),f=await t.subtle.encrypt({name:"AES-CBC",iv:c},u,s),l=new _e({value:[new Dt({valueHex:i}),new pe({value:xc}),new pe({value:Ec}),new _e({value:[new ft({value:"1.2.840.113549.2.11"}),new tr]})]}),p=new _e({value:[new ft({value:"1.2.840.113549.1.5.13"}),new _e({value:[new _e({value:[new ft({value:"1.2.840.113549.1.5.12"}),l]}),new _e({value:[new ft({value:"2.16.840.1.101.3.4.1.42"}),new Dt({valueHex:c})]})]})]}),d=new _e({value:[p,new Dt({valueHex:f})]}).toBER(),m=new Uint8Array(d,0,d.byteLength);return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...F(m,"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join(`
|
|
7
|
-
`)}async function g0(r,e){let t=Ue.get(),n;if(r.includes("-----BEGIN ENCRYPTED PRIVATE KEY-----")){let o=L(r.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----","").replace("-----END ENCRYPTED PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:s}=cn(o),{iv:i,salt:a,iterations:c,keySize:u,cipherText:f}=y0(s),l=await mc(On,e,a,{c,dkLen:u}),p=await t.subtle.importKey("raw",l,"AES-CBC",!1,["decrypt"]),h=Qn(await t.subtle.decrypt({name:"AES-CBC",iv:i},p,f)),{result:d}=cn(h);n=eh(d)}else if(r.includes("-----BEGIN PRIVATE KEY-----")){let o=L(r.replace("-----BEGIN PRIVATE KEY-----","").replace("-----END PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:s}=cn(o);n=eh(s)}else throw new E("Could not parse private key from PEM data","ERR_INVALID_PARAMETERS");return vc(n)}function y0(r){let e=r.valueBlock.value[0];if(e.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.13")throw new E("Only pkcs5PBES2 encrypted private keys are supported","ERR_INVALID_PARAMS");let n=e.valueBlock.value[1].valueBlock.value[0];if(n.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.12")throw new E("Only pkcs5PBKDF2 key derivation functions are supported","ERR_INVALID_PARAMS");let s=n.valueBlock.value[1],i=Qn(s.valueBlock.value[0].getValue()),a=xc,c=Ec;if(s.valueBlock.value.length===3)a=Number(s.valueBlock.value[1].toBigInt()),c=Number(s.valueBlock.value[2].toBigInt());else if(s.valueBlock.value.length===2)throw new E("Could not derive key size and iterations from PEM file - please use @libp2p/rsa to re-import your key","ERR_INVALID_PARAMS");let u=e.valueBlock.value[1].valueBlock.value[1],f=u.valueBlock.value[0].toString();if(f!=="OBJECT IDENTIFIER : 1.2.840.113549.3.7"){if(f!=="OBJECT IDENTIFIER : 1.3.14.3.2.7"){if(f!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.2"){if(f!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.22"){if(f!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.42")throw new E("Only AES-CBC encryption schemes are supported","ERR_INVALID_PARAMS")}}}}let l=Qn(u.valueBlock.value[1].getValue());return{cipherText:Qn(r.valueBlock.value[1].getValue()),salt:i,iterations:a,keySize:c,iv:l}}function eh(r){return Qn(r.valueBlock.value[2].getValue())}function Qn(r){return new Uint8Array(r,0,r.byteLength)}async function th(r){let e=await Ue.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),t=await oh(e);return{privateKey:t[0],publicKey:t[1]}}async function _c(r){let t=[await Ue.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await w0(r)],n=await oh({privateKey:t[0],publicKey:t[1]});return{privateKey:n[0],publicKey:n[1]}}async function rh(r,e){let t=await Ue.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Ue.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},t,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(n,0,n.byteLength)}async function nh(r,e,t){let n=await Ue.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Ue.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t instanceof Uint8Array?t:t.subarray())}async function oh(r){if(r.privateKey==null||r.publicKey==null)throw new E("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([Ue.get().subtle.exportKey("jwk",r.privateKey),Ue.get().subtle.exportKey("jwk",r.publicKey)])}async function w0(r){return Ue.get().subtle.importKey("jwk",{kty:r.kty,n:r.n,e:r.e},{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])}function Fs(r){if(r.kty!=="RSA")throw new E("invalid key type","ERR_INVALID_KEY_TYPE");if(r.n==null)throw new E("invalid key modulus","ERR_INVALID_KEY_MODULUS");return L(r.n,"base64url").length*8}var eo=8192,Jn=class{_key;constructor(e){this._key=e}verify(e,t){return nh(this._key,t,e)}marshal(){return rr.jwkToPkix(this._key)}get bytes(){return yt.encode({Type:re.RSA,Data:this.marshal()}).subarray()}equals(e){return J(this.bytes,e.bytes)}hash(){let e=Se.digest(this.bytes);return Je(e)?e.then(({bytes:t})=>t):e.bytes}},ln=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return et(16)}sign(e){return rh(this._key,e)}get public(){if(this._publicKey==null)throw new E("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new Jn(this._publicKey)}marshal(){return rr.jwkToPkcs1(this._key)}get bytes(){return wt.encode({Type:re.RSA,Data:this.marshal()}).subarray()}equals(e){return J(this.bytes,e.bytes)}hash(){let e=Se.digest(this.bytes);return Je(e)?e.then(({bytes:t})=>t):e.bytes}async id(){let e=await this.public.hash();return F(e,"base58btc")}async export(e,t="pkcs-8"){if(t==="pkcs-8")return rr.exportToPem(this,e);if(t==="libp2p-key")return tn(this.bytes,e);throw new E(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};async function vc(r){let e=rr.pkcs1ToJwk(r);if(Fs(e)>eo)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await _c(e);return new ln(t.privateKey,t.publicKey)}function E0(r){let e=rr.pkixToJwk(r);if(Fs(e)>eo)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new Jn(e)}async function x0(r){if(Fs(r)>eo)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await _c(r);return new ln(e.privateKey,e.publicKey)}async function v0(r){if(r>eo)throw new E("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await th(r);return new ln(e.privateKey,e.publicKey)}var Bc={};ve(Bc,{Secp256k1PrivateKey:()=>ro,Secp256k1PublicKey:()=>to,generateKeyPair:()=>P0,unmarshalSecp256k1PrivateKey:()=>L0,unmarshalSecp256k1PublicKey:()=>D0});var _0=new Uint32Array([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]),nr=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),or=new Uint32Array(64),Sc=class extends Zr{constructor(){super(64,32,8,!1),this.A=nr[0]|0,this.B=nr[1]|0,this.C=nr[2]|0,this.D=nr[3]|0,this.E=nr[4]|0,this.F=nr[5]|0,this.G=nr[6]|0,this.H=nr[7]|0}get(){let{A:e,B:t,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,t,n,o,s,i,a,c]}set(e,t,n,o,s,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let l=0;l<16;l++,t+=4)or[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){let p=or[l-15],h=or[l-2],d=it(p,7)^it(p,18)^p>>>3,m=it(h,17)^it(h,19)^h>>>10;or[l]=m+or[l-7]+d+or[l-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:f}=this;for(let l=0;l<64;l++){let p=it(a,6)^it(a,11)^it(a,25),h=f+p+Ou(a,c,u)+_0[l]+or[l]|0,m=(it(n,2)^it(n,13)^it(n,22))+Uu(n,o,s)|0;f=u,u=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+m|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,f=f+this.H|0,this.set(n,o,s,i,a,c,u,f)}roundClean(){or.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var sh=Uo(()=>new Sc);function ih(r){r.lowS!==void 0&&at("lowS",r.lowS),r.prehash!==void 0&&at("prehash",r.prehash)}function A0(r){let e=Fn(r);gt(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:t,Fp:n,a:o}=e;if(t){if(!n.eql(o,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...e})}var{bytesToNumberBE:S0,hexToBytes:R0}=Vo,Rr={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(r){let{Err:e}=Rr;if(r.length<2||r[0]!==2)throw new e("Invalid signature integer tag");let t=r[1],n=r.subarray(2,t+2);if(!t||n.length!==t)throw new e("Invalid signature integer: wrong length");if(n[0]&128)throw new e("Invalid signature integer: negative");if(n[0]===0&&!(n[1]&128))throw new e("Invalid signature integer: unnecessary leading zero");return{d:S0(n),l:r.subarray(t+2)}},toSig(r){let{Err:e}=Rr,t=typeof r=="string"?R0(r):r;Qr(t);let n=t.length;if(n<2||t[0]!=48)throw new e("Invalid signature tag");if(t[1]!==n-2)throw new e("Invalid signature: incorrect length");let{d:o,l:s}=Rr._parseInt(t.subarray(2)),{d:i,l:a}=Rr._parseInt(s);if(a.length)throw new e("Invalid signature: left bytes after parsing");return{r:o,s:i}},hexFromSig(r){let e=u=>Number.parseInt(u[0],16)&8?"00"+u:u,t=u=>{let f=u.toString(16);return f.length&1?`0${f}`:f},n=e(t(r.s)),o=e(t(r.r)),s=n.length/2,i=o.length/2,a=t(s),c=t(i);return`30${t(i+s+4)}02${c}${o}02${a}${n}`}},sr=BigInt(0),Ae=BigInt(1),j1=BigInt(2),ah=BigInt(3),X1=BigInt(4);function I0(r){let e=A0(r),{Fp:t}=e,n=e.toBytes||((d,m,w)=>{let g=m.toAffine();return Ct(Uint8Array.from([4]),t.toBytes(g.x),t.toBytes(g.y))}),o=e.fromBytes||(d=>{let m=d.subarray(1),w=t.fromBytes(m.subarray(0,t.BYTES)),g=t.fromBytes(m.subarray(t.BYTES,2*t.BYTES));return{x:w,y:g}});function s(d){let{a:m,b:w}=e,g=t.sqr(d),y=t.mul(g,d);return t.add(t.add(y,t.mul(d,m)),w)}if(!t.eql(t.sqr(e.Gy),s(e.Gx)))throw new Error("bad generator point: equation left != right");function i(d){return Un(d,Ae,e.n)}function a(d){let{allowedPrivateKeyLengths:m,nByteLength:w,wrapPrivateKey:g,n:y}=e;if(m&&typeof d!="bigint"){if(jt(d)&&(d=Tt(d)),typeof d!="string"||!m.includes(d.length))throw new Error("Invalid key");d=d.padStart(w*2,"0")}let b;try{b=typeof d=="bigint"?d:Bt(le("private key",d,w))}catch{throw new Error(`private key must be ${w} bytes, hex or bigint, not ${typeof d}`)}return g&&(b=X(b,y)),qe("private key",b,Ae,y),b}function c(d){if(!(d instanceof l))throw new Error("ProjectivePoint expected")}let u=br((d,m)=>{let{px:w,py:g,pz:y}=d;if(t.eql(y,t.ONE))return{x:w,y:g};let b=d.is0();m==null&&(m=b?t.ONE:t.inv(y));let x=t.mul(w,m),A=t.mul(g,m),R=t.mul(y,m);if(b)return{x:t.ZERO,y:t.ZERO};if(!t.eql(R,t.ONE))throw new Error("invZ was invalid");return{x,y:A}}),f=br(d=>{if(d.is0()){if(e.allowInfinityPoint&&!t.is0(d.py))return;throw new Error("bad point: ZERO")}let{x:m,y:w}=d.toAffine();if(!t.isValid(m)||!t.isValid(w))throw new Error("bad point: x or y not FE");let g=t.sqr(w),y=s(m);if(!t.eql(g,y))throw new Error("bad point: equation left != right");if(!d.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class l{constructor(m,w,g){if(this.px=m,this.py=w,this.pz=g,m==null||!t.isValid(m))throw new Error("x required");if(w==null||!t.isValid(w))throw new Error("y required");if(g==null||!t.isValid(g))throw new Error("z required");Object.freeze(this)}static fromAffine(m){let{x:w,y:g}=m||{};if(!m||!t.isValid(w)||!t.isValid(g))throw new Error("invalid affine point");if(m instanceof l)throw new Error("projective point not allowed");let y=b=>t.eql(b,t.ZERO);return y(w)&&y(g)?l.ZERO:new l(w,g,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(m){let w=t.invertBatch(m.map(g=>g.pz));return m.map((g,y)=>g.toAffine(w[y])).map(l.fromAffine)}static fromHex(m){let w=l.fromAffine(o(le("pointHex",m)));return w.assertValidity(),w}static fromPrivateKey(m){return l.BASE.multiply(a(m))}_setWindowSize(m){h.setWindowSize(this,m)}assertValidity(){f(this)}hasEvenY(){let{y:m}=this.toAffine();if(t.isOdd)return!t.isOdd(m);throw new Error("Field doesn't support isOdd")}equals(m){c(m);let{px:w,py:g,pz:y}=this,{px:b,py:x,pz:A}=m,R=t.eql(t.mul(w,A),t.mul(b,y)),_=t.eql(t.mul(g,A),t.mul(x,y));return R&&_}negate(){return new l(this.px,t.neg(this.py),this.pz)}double(){let{a:m,b:w}=e,g=t.mul(w,ah),{px:y,py:b,pz:x}=this,A=t.ZERO,R=t.ZERO,_=t.ZERO,I=t.mul(y,y),$=t.mul(b,b),V=t.mul(x,x),K=t.mul(y,b);return K=t.add(K,K),_=t.mul(y,x),_=t.add(_,_),A=t.mul(m,_),R=t.mul(g,V),R=t.add(A,R),A=t.sub($,R),R=t.add($,R),R=t.mul(A,R),A=t.mul(K,A),_=t.mul(g,_),V=t.mul(m,V),K=t.sub(I,V),K=t.mul(m,K),K=t.add(K,_),_=t.add(I,I),I=t.add(_,I),I=t.add(I,V),I=t.mul(I,K),R=t.add(R,I),V=t.mul(b,x),V=t.add(V,V),I=t.mul(V,K),A=t.sub(A,I),_=t.mul(V,$),_=t.add(_,_),_=t.add(_,_),new l(A,R,_)}add(m){c(m);let{px:w,py:g,pz:y}=this,{px:b,py:x,pz:A}=m,R=t.ZERO,_=t.ZERO,I=t.ZERO,$=e.a,V=t.mul(e.b,ah),K=t.mul(w,b),Q=t.mul(g,x),D=t.mul(y,A),N=t.add(w,g),S=t.add(b,x);N=t.mul(N,S),S=t.add(K,Q),N=t.sub(N,S),S=t.add(w,y);let v=t.add(b,A);return S=t.mul(S,v),v=t.add(K,D),S=t.sub(S,v),v=t.add(g,y),R=t.add(x,A),v=t.mul(v,R),R=t.add(Q,D),v=t.sub(v,R),I=t.mul($,S),R=t.mul(V,D),I=t.add(R,I),R=t.sub(Q,I),I=t.add(Q,I),_=t.mul(R,I),Q=t.add(K,K),Q=t.add(Q,K),D=t.mul($,D),S=t.mul(V,S),Q=t.add(Q,D),D=t.sub(K,D),D=t.mul($,D),S=t.add(S,D),K=t.mul(Q,S),_=t.add(_,K),K=t.mul(v,S),R=t.mul(N,R),R=t.sub(R,K),K=t.mul(N,Q),I=t.mul(v,I),I=t.add(I,K),new l(R,_,I)}subtract(m){return this.add(m.negate())}is0(){return this.equals(l.ZERO)}wNAF(m){return h.wNAFCached(this,m,l.normalizeZ)}multiplyUnsafe(m){qe("scalar",m,sr,e.n);let w=l.ZERO;if(m===sr)return w;if(m===Ae)return this;let{endo:g}=e;if(!g)return h.unsafeLadder(this,m);let{k1neg:y,k1:b,k2neg:x,k2:A}=g.splitScalar(m),R=w,_=w,I=this;for(;b>sr||A>sr;)b&Ae&&(R=R.add(I)),A&Ae&&(_=_.add(I)),I=I.double(),b>>=Ae,A>>=Ae;return y&&(R=R.negate()),x&&(_=_.negate()),_=new l(t.mul(_.px,g.beta),_.py,_.pz),R.add(_)}multiply(m){let{endo:w,n:g}=e;qe("scalar",m,Ae,g);let y,b;if(w){let{k1neg:x,k1:A,k2neg:R,k2:_}=w.splitScalar(m),{p:I,f:$}=this.wNAF(A),{p:V,f:K}=this.wNAF(_);I=h.constTimeNegate(x,I),V=h.constTimeNegate(R,V),V=new l(t.mul(V.px,w.beta),V.py,V.pz),y=I.add(V),b=$.add(K)}else{let{p:x,f:A}=this.wNAF(m);y=x,b=A}return l.normalizeZ([y,b])[0]}multiplyAndAddUnsafe(m,w,g){let y=l.BASE,b=(A,R)=>R===sr||R===Ae||!A.equals(y)?A.multiplyUnsafe(R):A.multiply(R),x=b(this,w).add(b(m,g));return x.is0()?void 0:x}toAffine(m){return u(this,m)}isTorsionFree(){let{h:m,isTorsionFree:w}=e;if(m===Ae)return!0;if(w)return w(l,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:m,clearCofactor:w}=e;return m===Ae?this:w?w(l,this):this.multiplyUnsafe(e.h)}toRawBytes(m=!0){return at("isCompressed",m),this.assertValidity(),n(l,this,m)}toHex(m=!0){return at("isCompressed",m),Tt(this.toRawBytes(m))}}l.BASE=new l(e.Gx,e.Gy,t.ONE),l.ZERO=new l(t.ZERO,t.ONE,t.ZERO);let p=e.nBitLength,h=$o(l,e.endo?Math.ceil(p/2):p);return{CURVE:e,ProjectivePoint:l,normPrivateKeyToScalar:a,weierstrassEquation:s,isWithinCurveOrder:i}}function T0(r){let e=Fn(r);return gt(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function ch(r){let e=T0(r),{Fp:t,n}=e,o=t.BYTES+1,s=2*t.BYTES+1;function i(N){return X(N,n)}function a(N){return Ko(N,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:u,weierstrassEquation:f,isWithinCurveOrder:l}=I0({...e,toBytes(N,S,v){let T=S.toAffine(),B=t.toBytes(T.x),P=Ct;return at("isCompressed",v),v?P(Uint8Array.from([S.hasEvenY()?2:3]),B):P(Uint8Array.from([4]),B,t.toBytes(T.y))},fromBytes(N){let S=N.length,v=N[0],T=N.subarray(1);if(S===o&&(v===2||v===3)){let B=Bt(T);if(!Un(B,Ae,t.ORDER))throw new Error("Point is not on curve");let P=f(B),O;try{O=t.sqrt(P)}catch(H){let G=H instanceof Error?": "+H.message:"";throw new Error("Point is not on curve"+G)}let U=(O&Ae)===Ae;return(v&1)===1!==U&&(O=t.neg(O)),{x:B,y:O}}else if(S===s&&v===4){let B=t.fromBytes(T.subarray(0,t.BYTES)),P=t.fromBytes(T.subarray(t.BYTES,2*t.BYTES));return{x:B,y:P}}else throw new Error(`Point of length ${S} was invalid. Expected ${o} compressed bytes or ${s} uncompressed bytes`)}}),p=N=>Tt(Zt(N,e.nByteLength));function h(N){let S=n>>Ae;return N>S}function d(N){return h(N)?i(-N):N}let m=(N,S,v)=>Bt(N.slice(S,v));class w{constructor(S,v,T){this.r=S,this.s=v,this.recovery=T,this.assertValidity()}static fromCompact(S){let v=e.nByteLength;return S=le("compactSignature",S,v*2),new w(m(S,0,v),m(S,v,2*v))}static fromDER(S){let{r:v,s:T}=Rr.toSig(le("DER",S));return new w(v,T)}assertValidity(){qe("r",this.r,Ae,n),qe("s",this.s,Ae,n)}addRecoveryBit(S){return new w(this.r,this.s,S)}recoverPublicKey(S){let{r:v,s:T,recovery:B}=this,P=R(le("msgHash",S));if(B==null||![0,1,2,3].includes(B))throw new Error("recovery id invalid");let O=B===2||B===3?v+e.n:v;if(O>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let U=B&1?"03":"02",z=c.fromHex(U+p(O)),H=a(O),G=i(-P*H),oe=i(T*H),se=c.BASE.multiplyAndAddUnsafe(z,G,oe);if(!se)throw new Error("point at infinify");return se.assertValidity(),se}hasHighS(){return h(this.s)}normalizeS(){return this.hasHighS()?new w(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return yr(this.toDERHex())}toDERHex(){return Rr.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return yr(this.toCompactHex())}toCompactHex(){return p(this.r)+p(this.s)}}let g={isValidPrivateKey(N){try{return u(N),!0}catch{return!1}},normPrivateKeyToScalar:u,randomPrivateKey:()=>{let N=qa(e.n);return Gu(e.randomBytes(N),e.n)},precompute(N=8,S=c.BASE){return S._setWindowSize(N),S.multiply(BigInt(3)),S}};function y(N,S=!0){return c.fromPrivateKey(N).toRawBytes(S)}function b(N){let S=jt(N),v=typeof N=="string",T=(S||v)&&N.length;return S?T===o||T===s:v?T===2*o||T===2*s:N instanceof c}function x(N,S,v=!0){if(b(N))throw new Error("first arg must be private key");if(!b(S))throw new Error("second arg must be public key");return c.fromHex(S).multiply(u(N)).toRawBytes(v)}let A=e.bits2int||function(N){let S=Bt(N),v=N.length*8-e.nBitLength;return v>0?S>>BigInt(v):S},R=e.bits2int_modN||function(N){return i(A(N))},_=Mn(e.nBitLength);function I(N){return qe(`num < 2^${e.nBitLength}`,N,sr,_),Zt(N,e.nByteLength)}function $(N,S,v=V){if(["recovered","canonical"].some(Ee=>Ee in v))throw new Error("sign() legacy options not supported");let{hash:T,randomBytes:B}=e,{lowS:P,prehash:O,extraEntropy:U}=v;P==null&&(P=!0),N=le("msgHash",N),ih(v),O&&(N=le("prehashed msgHash",T(N)));let z=R(N),H=u(S),G=[I(H),I(z)];if(U!=null&&U!==!1){let Ee=U===!0?B(t.BYTES):U;G.push(le("extraEntropy",Ee))}let oe=Ct(...G),se=z;function $e(Ee){let me=A(Ee);if(!l(me))return;let nt=a(me),xe=c.BASE.multiply(me).toAffine(),ot=i(xe.x);if(ot===sr)return;let dr=i(nt*i(se+ot*H));if(dr===sr)return;let Cn=(xe.x===ot?0:2)|Number(xe.y&Ae),Io=dr;return P&&h(dr)&&(Io=d(dr),Cn^=1),new w(ot,Io,Cn)}return{seed:oe,k2sig:$e}}let V={lowS:e.lowS,prehash:!1},K={lowS:e.lowS,prehash:!1};function Q(N,S,v=V){let{seed:T,k2sig:B}=$(N,S,v),P=e;return Va(P.hash.outputLen,P.nByteLength,P.hmac)(T,B)}c.BASE._setWindowSize(8);function D(N,S,v,T=K){let B=N;if(S=le("msgHash",S),v=le("publicKey",v),"strict"in T)throw new Error("options.strict was renamed to lowS");ih(T);let{lowS:P,prehash:O}=T,U,z;try{if(typeof B=="string"||jt(B))try{U=w.fromDER(B)}catch(xe){if(!(xe instanceof Rr.Err))throw xe;U=w.fromCompact(B)}else if(typeof B=="object"&&typeof B.r=="bigint"&&typeof B.s=="bigint"){let{r:xe,s:ot}=B;U=new w(xe,ot)}else throw new Error("PARSE");z=c.fromHex(v)}catch(xe){if(xe.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(P&&U.hasHighS())return!1;O&&(S=e.hash(S));let{r:H,s:G}=U,oe=R(S),se=a(G),$e=i(oe*se),Ee=i(H*se),me=c.BASE.multiplyAndAddUnsafe(z,$e,Ee)?.toAffine();return me?i(me.x)===H:!1}return{CURVE:e,getPublicKey:y,getSharedSecret:x,sign:Q,verify:D,ProjectivePoint:c,Signature:w,utils:g}}function B0(r){return{hash:r,hmac:(e,...t)=>$n(r,e,La(...t)),randomBytes:Xr}}function lh(r,e){let t=n=>ch({...r,...B0(n)});return Object.freeze({...t(e),create:t})}var hh=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),uh=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),C0=BigInt(1),Rc=BigInt(2),fh=(r,e)=>(r+e/Rc)/e;function k0(r){let e=hh,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=r*r*r%e,f=u*u*r%e,l=te(f,t,e)*f%e,p=te(l,t,e)*f%e,h=te(p,Rc,e)*u%e,d=te(h,o,e)*h%e,m=te(d,s,e)*d%e,w=te(m,a,e)*m%e,g=te(w,c,e)*w%e,y=te(g,a,e)*m%e,b=te(y,t,e)*f%e,x=te(b,i,e)*d%e,A=te(x,n,e)*u%e,R=te(A,Rc,e);if(!Ic.eql(Ic.sqr(R),r))throw new Error("Cannot find square root");return R}var Ic=Ho(hh,void 0,void 0,{sqrt:k0}),dt=lh({a:BigInt(0),b:BigInt(7),Fp:Ic,n:uh,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=uh,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-C0*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=t,i=BigInt("0x100000000000000000000000000000000"),a=fh(s*r,e),c=fh(-n*r,e),u=X(r-a*t-c*o,e),f=X(-a*n-c*s,e),l=u>i,p=f>i;if(l&&(u=e-u),p&&(f=e-f),u>i||f>i)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:l,k1:u,k2neg:p,k2:f}}}},sh),sv=BigInt(0);var iv=dt.ProjectivePoint;function dh(){return dt.utils.randomPrivateKey()}function ph(r,e){let t=Se.digest(e instanceof Uint8Array?e:e.subarray());if(Je(t))return t.then(({digest:n})=>dt.sign(n,r).toDERRawBytes()).catch(n=>{throw new E(String(n),"ERR_INVALID_INPUT")});try{return dt.sign(t.digest,r).toDERRawBytes()}catch(n){throw new E(String(n),"ERR_INVALID_INPUT")}}function mh(r,e,t){let n=Se.digest(t instanceof Uint8Array?t:t.subarray());if(Je(n))return n.then(({digest:o})=>dt.verify(e,o,r)).catch(o=>{throw new E(String(o),"ERR_INVALID_INPUT")});try{return dt.verify(e,n.digest,r)}catch(o){throw new E(String(o),"ERR_INVALID_INPUT")}}function gh(r){return dt.ProjectivePoint.fromHex(r).toRawBytes(!0)}function yh(r){try{dt.getPublicKey(r,!0)}catch(e){throw new E(String(e),"ERR_INVALID_PRIVATE_KEY")}}function Tc(r){try{dt.ProjectivePoint.fromHex(r)}catch(e){throw new E(String(e),"ERR_INVALID_PUBLIC_KEY")}}function wh(r){try{return dt.getPublicKey(r,!0)}catch(e){throw new E(String(e),"ERR_INVALID_PRIVATE_KEY")}}var to=class{_key;constructor(e){Tc(e),this._key=e}verify(e,t){return mh(this._key,t,e)}marshal(){return gh(this._key)}get bytes(){return yt.encode({Type:re.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return J(this.bytes,e.bytes)}async hash(){let e=Se.digest(this.bytes),t;return Je(e)?{bytes:t}=await e:t=e.bytes,t}},ro=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??wh(e),yh(this._key),Tc(this._publicKey)}sign(e){return ph(this._key,e)}get public(){return new to(this._publicKey)}marshal(){return this._key}get bytes(){return wt.encode({Type:re.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return J(this.bytes,e.bytes)}hash(){let e=Se.digest(this.bytes);return Je(e)?e.then(({bytes:t})=>t):e.bytes}async id(){let e=await this.public.hash();return F(e,"base58btc")}async export(e,t="libp2p-key"){if(t==="libp2p-key")return tn(this.bytes,e);throw new E(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function L0(r){return new ro(r)}function D0(r){return new to(r)}async function P0(){let r=dh();return new ro(r)}var ir={rsa:Ac,ed25519:pc,secp256k1:Bc};function Cc(r){let e=Object.keys(ir).join(" / ");return new E(`invalid or unsupported key type ${r}. Must be ${e}`,"ERR_UNSUPPORTED_KEY_TYPE")}function kc(r){if(r=r.toLowerCase(),r==="rsa"||r==="ed25519"||r==="secp256k1")return ir[r];throw Cc(r)}async function bh(r,e){return kc(r).generateKeyPair(e??2048)}function no(r){let e=yt.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case re.RSA:return ir.rsa.unmarshalRsaPublicKey(t);case re.Ed25519:return ir.ed25519.unmarshalEd25519PublicKey(t);case re.Secp256k1:return ir.secp256k1.unmarshalSecp256k1PublicKey(t);default:throw Cc(e.Type??"unknown")}}function Eh(r,e){return e=(e??"rsa").toLowerCase(),kc(e),r.bytes}async function oo(r){let e=wt.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case re.RSA:return ir.rsa.unmarshalRsaPrivateKey(t);case re.Ed25519:return ir.ed25519.unmarshalEd25519PrivateKey(t);case re.Secp256k1:return ir.secp256k1.unmarshalSecp256k1PrivateKey(t);default:throw Cc(e.Type??"RSA")}}function xh(r,e){return e=(e??"rsa").toLowerCase(),kc(e),r.bytes}function O0(r,e){try{if(typeof r=="string"&&r.length>0)return U0(r);if(typeof r=="number"&&isFinite(r))return e?.long?F0(r):M0(r);throw new Error("Value is not a string or number.")}catch(t){let n=V0(t)?`${t.message}. value=${JSON.stringify(r)}`:"An unknown error has occured.";throw new Error(n)}}function U0(r){if(r=String(r),r.length>100)throw new Error("Value exceeds the maximum length of 100 characters.");let e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(!e)return NaN;let t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*315576e5;case"weeks":case"week":case"w":return t*6048e5;case"days":case"day":case"d":return t*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return t*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return t*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return t*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:throw new Error(`The unit ${n} was matched, but no matching case exists.`)}}var Ks=O0;function M0(r){let e=Math.abs(r);return e>=864e5?`${Math.round(r/864e5)}d`:e>=36e5?`${Math.round(r/36e5)}h`:e>=6e4?`${Math.round(r/6e4)}m`:e>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function F0(r){let e=Math.abs(r);return e>=864e5?Vs(r,e,864e5,"day"):e>=36e5?Vs(r,e,36e5,"hour"):e>=6e4?Vs(r,e,6e4,"minute"):e>=1e3?Vs(r,e,1e3,"second"):`${r} ms`}function Vs(r,e,t,n){let o=e>=t*1.5;return`${Math.round(r/t)} ${n}${o?"s":""}`}function V0(r){return typeof r=="object"&&r!==null&&"message"in r}function Nc(r){t.debug=t,t.default=t,t.coerce=c,t.disable=s,t.enable=o,t.enabled=i,t.humanize=Ks,t.destroy=u,Object.keys(r).forEach(f=>{t[f]=r[f]}),t.names=[],t.skips=[],t.formatters={};function e(f){let l=0;for(let p=0;p<f.length;p++)l=(l<<5)-l+f.charCodeAt(p),l|=0;return t.colors[Math.abs(l)%t.colors.length]}t.selectColor=e;function t(f){let l,p=null,h,d;function m(...w){if(!m.enabled)return;let g=m,y=Number(new Date),b=y-(l||y);g.diff=b,g.prev=l,g.curr=y,l=y,w[0]=t.coerce(w[0]),typeof w[0]!="string"&&w.unshift("%O");let x=0;w[0]=w[0].replace(/%([a-zA-Z%])/g,(R,_)=>{if(R==="%%")return"%";x++;let I=t.formatters[_];if(typeof I=="function"){let $=w[x];R=I.call(g,$),w.splice(x,1),x--}return R}),t.formatArgs.call(g,w),(g.log||t.log).apply(g,w)}return m.namespace=f,m.useColors=t.useColors(),m.color=t.selectColor(f),m.extend=n,m.destroy=t.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>p!==null?p:(h!==t.namespaces&&(h=t.namespaces,d=t.enabled(f)),d),set:w=>{p=w}}),typeof t.init=="function"&&t.init(m),m}function n(f,l){let p=t(this.namespace+(typeof l>"u"?":":l)+f);return p.log=this.log,p}function o(f){t.save(f),t.namespaces=f,t.names=[],t.skips=[];let l,p=(typeof f=="string"?f:"").split(/[\s,]+/),h=p.length;for(l=0;l<h;l++)p[l]&&(f=p[l].replace(/\*/g,".*?"),f[0]==="-"?t.skips.push(new RegExp("^"+f.substr(1)+"$")):t.names.push(new RegExp("^"+f+"$")))}function s(){let f=[...t.names.map(a),...t.skips.map(a).map(l=>"-"+l)].join(",");return t.enable(""),f}function i(f){if(f[f.length-1]==="*")return!0;let l,p;for(l=0,p=t.skips.length;l<p;l++)if(t.skips[l].test(f))return!1;for(l=0,p=t.names.length;l<p;l++)if(t.names[l].test(f))return!0;return!1}function a(f){return f.toString().substring(2,f.toString().length-2).replace(/\.\*\?$/,"*")}function c(f){return f instanceof Error?f.stack??f.message:f}function u(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.setupFormatters(t.formatters),t.enable(t.load()),t}var Hs=Y0(),K0=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function H0(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/(edge|trident)\/(\d+)/)!=null?!1:typeof document<"u"&&document.documentElement?.style?.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/firefox\/(\d+)/)!=null&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/applewebkit\/(\d+)/)}function $0(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Ks(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(t++,o==="%c"&&(n=t))}),r.splice(n,0,e)}var q0=console.debug??console.log??(()=>{});function z0(r){try{r?Hs?.setItem("debug",r):Hs?.removeItem("debug")}catch{}}function G0(){let r;try{r=Hs?.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function Y0(){try{return localStorage}catch{}}function W0(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var vh=Nc({formatArgs:$0,save:z0,load:G0,useColors:H0,setupFormatters:W0,colors:K0,storage:Hs,log:q0});var je=vh;je.formatters.b=r=>r==null?"undefined":ae.baseEncode(r);je.formatters.t=r=>r==null?"undefined":Ye.baseEncode(r);je.formatters.m=r=>r==null?"undefined":Dn.baseEncode(r);je.formatters.p=r=>r==null?"undefined":r.toString();je.formatters.c=r=>r==null?"undefined":r.toString();je.formatters.k=r=>r==null?"undefined":r.toString();je.formatters.a=r=>r==null?"undefined":r.toString();function j0(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function $s(){return{forComponent(r){return X0(r)}}}function X0(r){let e=j0(`${r}:trace`);return je.enabled(`${r}:trace`)&&je.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=je(`${r}:trace`)),Object.assign(je(r),{error:je(`${r}:error`),trace:e})}var Ah=Symbol.for("nodejs.util.inspect.custom"),_h=Object.values(zt).map(r=>r.decoder).reduce((r,e)=>r.or(e),zt.identity.decoder),Sh=114,Pc=36,Oc=37,so=class{type;multihash;privateKey;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,this.privateKey=e.privateKey,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Bo]=!0;toString(){return this.string==null&&(this.string=ae.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return Qe.createV1(Sh,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return J(this.multihash.bytes,e);if(typeof e=="string")return ye(e).equals(this);if(e?.multihash?.bytes!=null)return J(this.multihash.bytes,e.multihash.bytes);throw new Error("not valid Id")}[Ah](){return`PeerId(${this.toString()})`}},Ir=class extends so{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Tr=class extends so{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.multihash.digest}},Br=class extends so{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.multihash.digest}},Lc=2336,Dc=class{type="url";multihash;privateKey;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Rt.digest(L(this.url))}[Ah](){return`PeerId(${this.url})`}[Bo]=!0;toString(){return this.toCID().toString()}toCID(){return Qe.createV1(Lc,this.multihash)}toBytes(){return this.toCID().bytes}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=F(e)),e.toString()===this.toString())}};function Rh(r){if(r.type==="RSA")return new Ir(r);if(r.type==="Ed25519")return new Tr(r);if(r.type==="secp256k1")return new Br(r);throw new E("Not a PeerId","ERR_INVALID_PARAMETERS")}function ye(r,e){if(e=e??_h,r.charAt(0)==="1"||r.charAt(0)==="Q"){let t=mr(ae.decode(`z${r}`));return r.startsWith("12D")?new Tr({multihash:t}):r.startsWith("16U")?new Br({multihash:t}):new Ir({multihash:t})}return un(_h.decode(r))}function un(r){try{let e=mr(r);if(e.code===Rt.code){if(e.digest.length===Pc)return new Tr({multihash:e});if(e.digest.length===Oc)return new Br({multihash:e})}if(e.code===Se.code)return new Ir({multihash:e})}catch{return Z0(Qe.decode(r))}throw new Error("Supplied PeerID CID is invalid")}function Z0(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==Sh&&r.code!==Lc)throw new Error("Supplied PeerID CID is invalid");if(r.code===Lc){let t=F(r.multihash.digest);return new Dc(new URL(t))}let e=r.multihash;if(e.code===Se.code)return new Ir({multihash:r.multihash});if(e.code===Rt.code){if(e.digest.length===Pc)return new Tr({multihash:r.multihash});if(e.digest.length===Oc)return new Br({multihash:r.multihash})}throw new Error("Supplied PeerID CID is invalid")}async function fn(r,e){return r.length===Pc?new Tr({multihash:mt(Rt.code,r),privateKey:e}):r.length===Oc?new Br({multihash:mt(Rt.code,r),privateKey:e}):new Ir({multihash:await Se.digest(r),publicKey:r,privateKey:e})}function hn(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}var Xe=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),n)}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return hn(this.map.entries(),e=>[ye(e[0]),e[1]])}forEach(e){this.map.forEach((t,n)=>{e(t,ye(n),this)})}get(e){return this.map.get(e.toString())}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),t)}keys(){return hn(this.map.keys(),e=>ye(e))}values(){return this.map.values()}get size(){return this.map.size}};var Mt=class r{set;constructor(e){if(this.set=new Set,e!=null)for(let t of e)this.set.add(t.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return hn(this.set.entries(),e=>{let t=ye(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=ye(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return hn(this.set.values(),e=>ye(e))}intersection(e){let t=new r;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new r;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new r;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};var kh=Symbol.for("@achingbrain/uint8arraylist");function Ch(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 zs(r){return!!r?.[kh]}var we=class r{bufs;length;[kh]=!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(zs(n))t+=n.byteLength,this.bufs.push(...n.bufs);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(zs(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=Ch(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Ch(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(zs(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 Re(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:Re(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=[...n],s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let u=e>=a&&e<c,f=t>a&&t<=c;if(u&&f){if(e===a&&t===c){n.push(i);break}let l=e-a;n.push(i.subarray(l,l+(t-e)));break}if(u){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(f){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!zs(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let l=0;l<s;l++)i[l]=-1;for(let l=0;l<o;l++)i[n[l]]=l;let a=i,c=this.byteLength-n.byteLength,u=n.byteLength-1,f;for(let l=t;l<=c;l+=f){f=0;for(let p=u;p>=0;p--){let h=this.get(l+p);if(n[p]!==h){f=Math.max(1,p-a[h]);break}}if(f===0)return l}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=ke(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=ke(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(!J(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 Uc=64,pt=class{fp;h;seed;constructor(e,t,n,o=2){if(o>Uc)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),i=st(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?J(this.fp,e.fp):!1}};function Cr(r,e){return Math.floor(Math.random()*(e-r))+r}var kr=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof pt))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof pt))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(this.contents[t]==null)return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof pt))throw new TypeError("Invalid Fingerprint");let t=Cr(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof pt))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var Mc={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Nh={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Lh=new globalThis.TextEncoder;function Q0(r,e){let t=Mc[e],n=Nh[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function J0(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Mc[e],o=Nh[e],s=r;for(;s.length>0;){let i=Lh.encodeInto(s,t);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(t[a]),o=BigInt.asUintN(e,o*n)}return o}function Fc(r,{size:e=32,utf8Buffer:t}={}){if(!Mc[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(t)return J0(r,e,t);r=Lh.encode(r)}return Q0(r,e)}var ey=pr(Bh(),1);var ao={hash:r=>Number(Fc(r,{size:32})),hashV:(r,e)=>ty(ao.hash(r,e))};function ty(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),L(e,"base16")}var ry=500,co=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??ao,this.seed=e.seed??Cr(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=L(e));let t=new pt(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new kr(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new kr(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let s=[n,o],i=s[Cr(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new kr(this.bucketSize));for(let a=0;a<ry;a++){let c=this.buckets[i].swap(t);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new kr(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=L(e));let t=new pt(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let s=(n^t.hash())%this.filterSize;return this.buckets[s]?.has(t)??!1}remove(e){typeof e=="string"&&(e=L(e));let t=new pt(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let s=(n^t.hash())%this.filterSize,i=this.buckets[s]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},ny={1:.5,2:.84,4:.95,8:.98};function oy(r=.001){return r>.002?2:r>1e-5?4:8}function Dh(r,e=.001){let t=oy(e),n=ny[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),Uc);return{filterSize:o,bucketSize:t,fingerprintSize:s}}var Gs=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??ao,this.seed=e.seed??Cr(0,Math.pow(2,10)),this.filterSeries=[new co({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=L(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new co({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=L(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=L(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function Vc(r,e=.001,t){return new Gs({...Dh(r,e),...t??{}})}var Ph=async()=>{let r=await bh("Ed25519"),e=await sy(r);if(e.type==="Ed25519")return e;throw new Error(`Generated unexpected PeerId type "${e.type}"`)};async function sy(r){return fn(Eh(r.public),xh(r))}var Oh={ERR_SIGNATURE_NOT_VALID:"ERR_SIGNATURE_NOT_VALID"};var lo;(function(r){let e;r.codec=()=>(e==null&&(e=Ve((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.publicKey!=null&&t.publicKey.byteLength>0&&(n.uint32(10),n.bytes(t.publicKey)),t.payloadType!=null&&t.payloadType.byteLength>0&&(n.uint32(18),n.bytes(t.payloadType)),t.payload!=null&&t.payload.byteLength>0&&(n.uint32(26),n.bytes(t.payload)),t.signature!=null&&t.signature.byteLength>0&&(n.uint32(42),n.bytes(t.signature)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={publicKey:new Uint8Array(0),payloadType:new Uint8Array(0),payload:new Uint8Array(0),signature:new Uint8Array(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.publicKey=t.bytes();break;case 2:o.payloadType=t.bytes();break;case 3:o.payload=t.bytes();break;case 5:o.signature=t.bytes();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Fe(t,r.codec()),r.decode=t=>Me(t,r.codec())})(lo||(lo={}));var dn=class r{static createFromProtobuf=async e=>{let t=lo.decode(e),n=await fn(t.publicKey);return new r({peerId:n,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t)=>{if(t.privateKey==null)throw new Error("Missing private key");let n=e.domain,o=e.codec,s=e.marshal(),i=Uh(n,o,s),c=await(await oo(t.privateKey)).sign(i.subarray());return new r({peerId:t,payloadType:o,payload:s,signature:c})};static openAndCertify=async(e,t)=>{let n=await r.createFromProtobuf(e);if(!await n.validate(t))throw new E("envelope signature is not valid for the given domain",Oh.ERR_SIGNATURE_NOT_VALID);return n};peerId;payloadType;payload;signature;marshaled;constructor(e){let{peerId:t,payloadType:n,payload:o,signature:s}=e;this.peerId=t,this.payloadType=n,this.payload=o,this.signature=s}marshal(){if(this.peerId.publicKey==null)throw new Error("Missing public key");return this.marshaled==null&&(this.marshaled=lo.encode({publicKey:this.peerId.publicKey,payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return J(this.marshal(),e.marshal())}async validate(e){let t=Uh(e,this.payloadType,this.payload);if(this.peerId.publicKey==null)throw new Error("Missing public key");return no(this.peerId.publicKey).verify(t.subarray(),this.signature)}},Uh=(r,e,t)=>{let n=L(r),o=Le(n.byteLength),s=Le(e.length),i=Le(t.length);return new we(o,n,s,e,i,t)};function Mh(r,e){let t=(n,o)=>n.toString().localeCompare(o.toString());return r.length!==e.length?!1:(e.sort(t),r.sort(t).every((n,o)=>e[o].equals(n)))}var Ys=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*o)-1;for(;;){let f=this.readAtomically(()=>{let l=this.readChar();if(l===void 0)return;let p=Number.parseInt(l,e);if(!Number.isNaN(p))return p});if(f===void 0)break;if(s*=e,s+=f,s>u||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Fh=45,iy=15,pn=new Ys;function Kc(r){if(!(r.length>iy))return pn.new(r).parseWith(()=>pn.readIPv4Addr())}function Hc(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Fh))return pn.new(r).parseWith(()=>pn.readIPv6Addr())}function Ws(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Fh))return pn.new(r).parseWith(()=>pn.readIPAddr())}var sA=parseInt("0xFFFF",16),iA=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function mn(r){return!!Kc(r)}function gn(r){return!!Hc(r)}function js(r){return!!Ws(r)}var Hh=mn,fy=gn,$c=function(r){let e=0;if(r=r.toString().trim(),Hh(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(fy(r)){let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=Hh(t[n]),i;s&&(i=$c(t[n]),t[n]=F(i.slice(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,F(i.slice(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++){let s=parseInt(t[n],16);o[e++]=s>>8&255,o[e++]=s&255}return o}throw new Error("invalid ip address")},$h=function(r,e=0,t){e=~~e,t=t??r.length-e;let n=new DataView(r.buffer);if(t===4){let o=[];for(let s=0;s<t;s++)o.push(r[e+s]);return o.join(".")}if(t===16){let o=[];for(let s=0;s<t;s+=2)o.push(n.getUint16(e+s).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var yn={},qc={},dy=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,-1,"ip6zone"],[43,8,"ipcidr"],[53,-1,"dns",!0],[54,-1,"dns4",!0],[55,-1,"dns6",!0],[56,-1,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,-1,"unix",!1,!0],[421,-1,"ipfs"],[421,-1,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,-1,"garlic64"],[448,0,"tls"],[449,-1,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,-1,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,-1,"http-path"],[777,-1,"memory"]];dy.forEach(r=>{let e=py(...r);qc[e.code]=e,yn[e.name]=e});function py(r,e,t,n,o){return{code:r,size:e,name:t,resolvable:!!n,path:!!o}}function j(r){if(typeof r=="number"){if(qc[r]!=null)return qc[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(yn[r]!=null)return yn[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var $A=j("ip4"),qA=j("ip6"),zA=j("ipcidr");function Wc(r,e){switch(j(r).code){case 4:case 41:return gy(e);case 42:return Yc(e);case 6:case 273:case 33:case 132:return Gh(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Yc(e);case 421:return Ey(e);case 444:return zh(e);case 445:return zh(e);case 466:return by(e);case 481:return globalThis.encodeURIComponent(Yc(e));default:return F(e,"base16")}}function jc(r,e){switch(j(r).code){case 4:return qh(e);case 41:return qh(e);case 42:return Gc(e);case 6:case 273:case 33:case 132:return Xc(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Gc(e);case 421:return yy(e);case 444:return xy(e);case 445:return vy(e);case 466:return wy(e);case 481:return Gc(globalThis.decodeURIComponent(e));default:return L(e,"base16")}}var zc=Object.values(zt).map(r=>r.decoder),my=function(){let r=zc[0].or(zc[1]);return zc.slice(2).forEach(e=>r=r.or(e)),r}();function qh(r){if(!js(r))throw new Error("invalid ip address");return $c(r)}function gy(r){let e=$h(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!js(e))throw new Error("invalid ip address");return e}function Xc(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function Gh(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function Gc(r){let e=L(r),t=Uint8Array.from(Le(e.length));return Re([t,e],t.length+e.length)}function Yc(r){let e=lt(r);if(r=r.slice(de(e)),r.length!==e)throw new Error("inconsistent lengths");return F(r)}function yy(r){let e;r[0]==="Q"||r[0]==="1"?e=mr(ae.decode(`z${r}`)).bytes:e=Qe.parse(r).multihash.bytes;let t=Uint8Array.from(Le(e.length));return Re([t,e],t.length+e.length)}function wy(r){let e=my.decode(r),t=Uint8Array.from(Le(e.length));return Re([t,e],t.length+e.length)}function by(r){let e=lt(r),t=r.slice(de(e));if(t.length!==e)throw new Error("inconsistent lengths");return"u"+F(t,"base64url")}function Ey(r){let e=lt(r),t=r.slice(de(e));if(t.length!==e)throw new Error("inconsistent lengths");return F(t,"base58btc")}function xy(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=Ye.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=Xc(n);return Re([t,o],t.length+o.length)}function vy(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=Ye.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=Xc(n);return Re([t,o],t.length+o.length)}function zh(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=F(e,"base32"),o=Gh(t);return`${n}:${o}`}function Yh(r){r=Zc(r);let e=[],t=[],n=null,o=r.split("/").slice(1);if(o.length===1&&o[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let s=0;s<o.length;s++){let i=o[s],a=j(i);if(a.size===0){e.push([a.code]),t.push([a.code]);continue}if(s++,s>=o.length)throw jh("invalid address: "+r);if(a.path===!0){n=Zc(o.slice(s).join("/")),e.push([a.code,jc(a.code,n)]),t.push([a.code,n]);break}let c=jc(a.code,o[s]);e.push([a.code,c]),t.push([a.code,Wc(a.code,c)])}return{string:Wh(t),bytes:Jc(e),tuples:e,stringTuples:t,path:n}}function Qc(r){let e=[],t=[],n=null,o=0;for(;o<r.length;){let s=lt(r,o),i=de(s),a=j(s),c=_y(a,r.slice(o+i));if(c===0){e.push([s]),t.push([s]),o+=i;continue}let u=r.slice(o+i,o+i+c);if(o+=c+i,o>r.length)throw jh("Invalid address Uint8Array: "+F(r,"base16"));e.push([s,u]);let f=Wc(s,u);if(t.push([s,f]),a.path===!0){n=f;break}}return{bytes:Uint8Array.from(r),string:Wh(t),tuples:e,stringTuples:t,path:n}}function Wh(r){let e=[];return r.map(t=>{let n=j(t[0]);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),Zc(e.join("/"))}function Jc(r){return Re(r.map(e=>{let t=j(e[0]),n=Uint8Array.from(Le(t.code));return e.length>1&&e[1]!=null&&(n=Re([n,e[1]])),n}))}function _y(r,e){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let t=lt(e instanceof Uint8Array?e:Uint8Array.from(e));return t+de(t)}}function Zc(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}function jh(r){return new Error("Error parsing address: "+r)}var Ay=Symbol.for("nodejs.util.inspect.custom"),el=Symbol.for("@multiformats/js-multiaddr/multiaddr"),Sy=[j("dns").code,j("dns4").code,j("dns6").code,j("dnsaddr").code],Xs=class r{bytes;#e;#t;#s;#a;[el]=!0;constructor(e){e==null&&(e="");let t;if(e instanceof Uint8Array)t=Qc(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);t=Yh(e)}else if(ar(e))t=Qc(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=t.bytes,this.#e=t.string,this.#t=t.tuples,this.#s=t.stringTuples,this.#a=t.path}toString(){return this.#e}toJSON(){return this.toString()}toOptions(){let e,t,n,o,s="",i=j("tcp"),a=j("udp"),c=j("ip4"),u=j("ip6"),f=j("dns6"),l=j("ip6zone");for(let[h,d]of this.stringTuples())h===l.code&&(s=`%${d??""}`),Sy.includes(h)&&(t=i.name,o=443,n=`${d??""}${s}`,e=h===f.code?6:4),(h===i.code||h===a.code)&&(t=j(h).name,o=parseInt(d??"")),(h===c.code||h===u.code)&&(t=j(h).name,n=`${d??""}${s}`,e=h===u.code?6:4);if(e==null||t==null||n==null||o==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:n,transport:t,port:o}}protos(){return this.#t.map(([e])=>Object.assign({},j(e)))}protoCodes(){return this.#t.map(([e])=>e)}protoNames(){return this.#t.map(([e])=>j(e).name)}tuples(){return this.#t}stringTuples(){return this.#s}encapsulate(e){return e=new r(e),new r(this.toString()+e.toString())}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new r(n.slice(0,o))}decapsulateCode(e){let t=this.tuples();for(let n=t.length-1;n>=0;n--)if(t[n][0]===e)return new r(Jc(t.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,o])=>{n===yn.p2p.code&&e.push([n,o]),n===yn["p2p-circuit"].code&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?F(ae.decode(`z${n}`),"base58btc"):F(Qe.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#a}equals(e){return J(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(s=>s.resolvable);if(t==null)return[this];let n=wn.get(t.name);if(n==null)throw new E(`no available resolver for ${t.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,e)).map(s=>ne(s))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(e){let t=(e??this).protos();return!(t.length!==2||t[0].code!==4&&t[0].code!==41||t[1].code!==6&&t[1].code!==273)}[Ay](){return`Multiaddr(${this.#e})`}};var wn=new Map;function ar(r){return!!r?.[el]}function ne(r){return new Xs(r)}var Xh="libp2p-peer-record",Zh=Uint8Array.from([3,1]);var uo;(function(r){let e;(function(n){let o;n.codec=()=>(o==null&&(o=Ve((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.multiaddr!=null&&s.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(s.multiaddr)),a.lengthDelimited!==!1&&i.ldelim()},(s,i)=>{let a={multiaddr:new Uint8Array(0)},c=i==null?s.len:s.pos+i;for(;s.pos<c;){let u=s.uint32();switch(u>>>3){case 1:a.multiaddr=s.bytes();break;default:s.skipType(u&7);break}}return a})),o),n.encode=s=>Fe(s,n.codec()),n.decode=s=>Me(s,n.codec())})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=Ve((n,o,s={})=>{if(s.lengthDelimited!==!1&&o.fork(),n.peerId!=null&&n.peerId.byteLength>0&&(o.uint32(10),o.bytes(n.peerId)),n.seq!=null&&n.seq!==0n&&(o.uint32(16),o.uint64(n.seq)),n.addresses!=null)for(let i of n.addresses)o.uint32(26),r.AddressInfo.codec().encode(i,o);s.lengthDelimited!==!1&&o.ldelim()},(n,o)=>{let s={peerId:new Uint8Array(0),seq:0n,addresses:[]},i=o==null?n.len:n.pos+o;for(;n.pos<i;){let a=n.uint32();switch(a>>>3){case 1:s.peerId=n.bytes();break;case 2:s.seq=n.uint64();break;case 3:s.addresses.push(r.AddressInfo.codec().decode(n,n.uint32()));break;default:n.skipType(a&7);break}}return s})),t),r.encode=n=>Fe(n,r.codec()),r.decode=n=>Me(n,r.codec())})(uo||(uo={}));var Nr=class r{static createFromProtobuf=e=>{let t=uo.decode(e),n=un(t.peerId),o=(t.addresses??[]).map(i=>ne(i.multiaddr)),s=t.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=Xh;static CODEC=Zh;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(e){let{peerId:t,multiaddrs:n,seqNumber:o}=e;this.peerId=t,this.multiaddrs=n??[],this.seqNumber=o??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=uo.encode({peerId:this.peerId.toBytes(),seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))})),this.marshaled}equals(e){return!(!(e instanceof r)||!this.peerId.equals(e.peerId)||this.seqNumber!==e.seqNumber||!Mh(this.multiaddrs,e.multiaddrs))}};function Ry(r){return r[Symbol.asyncIterator]!=null}function Iy(r){if(Ry(r))return(async()=>{let t=[];for await(let n of r)t.push(n);return t})();let e=[];for(let t of r)e.push(t);return e}var fo=Iy;var rl=pr(Jh(),1);var po=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},nl=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},ed=r=>globalThis.DOMException===void 0?new nl(r):new DOMException(r),td=r=>{let e=r.reason===void 0?ed("This operation was aborted."):r.reason;return e instanceof Error?e:ed(e)};function mo(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=e,i,c=new Promise((u,f)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:p}=e;p.aborted&&f(td(p)),p.addEventListener("abort",()=>{f(td(p))})}if(t===Number.POSITIVE_INFINITY){r.then(u,f);return}let l=new po;i=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(p){f(p)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?u():o instanceof Error?f(o):(l.message=o??`Promise timed out after ${t} milliseconds`,f(l))},t),(async()=>{try{u(await r)}catch(p){f(p)}})()}).finally(()=>{c.clear()});return c.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},c}function ol(r,e,t){let n=0,o=r.length;for(;o>0;){let s=Math.trunc(o/2),i=n+s;t(r[i],e)<=0?(n=++i,o-=s+1):o=s}return n}var go=class{#e=[];enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,run:e};if(this.size&&this.#e[this.size-1].priority>=t.priority){this.#e.push(n);return}let o=ol(this.#e,n,(s,i)=>i.priority-s.priority);this.#e.splice(o,0,n)}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this.#e.length}};var cr=class extends rl.default{#e;#t;#s=0;#a;#c;#p=0;#n;#l;#r;#m;#o=0;#u;#i;#g;timeout;constructor(e){if(super(),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:go,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#e=e.carryoverConcurrencyCount,this.#t=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#a=e.intervalCap,this.#c=e.interval,this.#r=new e.queueClass,this.#m=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#g=e.throwOnTimeout===!0,this.#i=e.autoStart===!1}get#b(){return this.#t||this.#s<this.#a}get#E(){return this.#o<this.#u}#x(){this.#o--,this.#f(),this.emit("next")}#v(){this.#w(),this.#y(),this.#l=void 0}get#_(){let e=Date.now();if(this.#n===void 0){let t=this.#p-e;if(t<0)this.#s=this.#e?this.#o:0;else return this.#l===void 0&&(this.#l=setTimeout(()=>{this.#v()},t)),!0}return!1}#f(){if(this.#r.size===0)return this.#n&&clearInterval(this.#n),this.#n=void 0,this.emit("empty"),this.#o===0&&this.emit("idle"),!1;if(!this.#i){let e=!this.#_;if(this.#b&&this.#E){let t=this.#r.dequeue();return t?(this.emit("active"),t(),e&&this.#y(),!0):!1}}return!1}#y(){this.#t||this.#n!==void 0||(this.#n=setInterval(()=>{this.#w()},this.#c),this.#p=Date.now()+this.#c)}#w(){this.#s===0&&this.#o===0&&this.#n&&(clearInterval(this.#n),this.#n=void 0),this.#s=this.#e?this.#o:0,this.#h()}#h(){for(;this.#f(););}get concurrency(){return this.#u}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#u=e,this.#h()}async#A(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(e.reason)},{once:!0})})}async add(e,t={}){return t={timeout:this.timeout,throwOnTimeout:this.#g,...t},new Promise((n,o)=>{this.#r.enqueue(async()=>{this.#o++,this.#s++;try{t.signal?.throwIfAborted();let s=e({signal:t.signal});t.timeout&&(s=mo(Promise.resolve(s),{milliseconds:t.timeout})),t.signal&&(s=Promise.race([s,this.#A(t.signal)]));let i=await s;n(i),this.emit("completed",i)}catch(s){if(s instanceof po&&!t.throwOnTimeout){n();return}o(s),this.emit("error",s)}finally{this.#x()}},t),this.emit("add"),this.#f()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#i?(this.#i=!1,this.#h(),this):this}pause(){this.#i=!0}clear(){this.#r=new this.#m}async onEmpty(){this.#r.size!==0&&await this.#d("empty")}async onSizeLessThan(e){this.#r.size<e||await this.#d("next",()=>this.#r.size<e)}async onIdle(){this.#o===0&&this.#r.size===0||await this.#d("idle")}async#d(e,t){return new Promise(n=>{let o=()=>{t&&!t()||(this.off(e,o),n())};this.on(e,o)})}get size(){return this.#r.size}sizeBy(e){return this.#r.filter(e).length}get pending(){return this.#o}get isPaused(){return this.#i}};var lr={},bn=r=>{r.addEventListener("message",e=>{bn.dispatchEvent("message",r,e)}),r.port!=null&&r.port.addEventListener("message",e=>{bn.dispatchEvent("message",r,e)})};bn.addEventListener=(r,e)=>{lr[r]==null&&(lr[r]=[]),lr[r].push(e)};bn.removeEventListener=(r,e)=>{lr[r]!=null&&(lr[r]=lr[r].filter(t=>t===e))};bn.dispatchEvent=function(r,e,t){lr[r]!=null&&lr[r].forEach(n=>n(e,t))};var sl=bn;var il="lock:worker:request-read",al="lock:worker:release-read",cl="lock:master:grant-read",ll="lock:worker:request-write",ul="lock:worker:release-write",fl="lock:master:grant-write";var rd=(r=21)=>Math.random().toString().substring(2);var nd=(r,e,t,n,o)=>(s,i)=>{if(i.data.type!==t)return;let a={type:i.data.type,name:i.data.name,identifier:i.data.identifier};r.dispatchEvent(new MessageEvent(e,{data:{name:a.name,handler:async()=>{s.postMessage({type:o,name:a.name,identifier:a.identifier}),await new Promise(c=>{let u=f=>{if(f==null||f.data==null)return;let l={type:f.data.type,name:f.data.name,identifier:f.data.identifier};l.type===n&&l.identifier===a.identifier&&(s.removeEventListener("message",u),c())};s.addEventListener("message",u)})}}}))},od=(r,e,t,n)=>async()=>{let o=rd();return globalThis.postMessage({type:e,identifier:o,name:r}),new Promise(s=>{let i=a=>{if(a==null||a.data==null)return;let c={type:a.data.type,identifier:a.data.identifier};c.type===t&&c.identifier===o&&(globalThis.removeEventListener("message",i),s(()=>{globalThis.postMessage({type:n,identifier:o,name:r})}))};globalThis.addEventListener("message",i)})},Cy={singleProcess:!1},sd=r=>{if(r=Object.assign({},Cy,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return sl.addEventListener("message",nd(t,"requestReadLock",il,al,cl)),sl.addEventListener("message",nd(t,"requestWriteLock",ll,ul,fl)),t}return{isWorker:!0,readLock:t=>od(t,il,cl,al),writeLock:t=>od(t,ll,fl,ul)}};var Lr={},ur;async function hl(r,e){let t,n=new Promise(o=>{t=o});return r.add(async()=>mo((async()=>{await new Promise(o=>{t(()=>{o()})})})(),{milliseconds:e.timeout})),n}var ky=(r,e)=>{if(ur.isWorker===!0)return{readLock:ur.readLock(r,e),writeLock:ur.writeLock(r,e)};let t=new cr({concurrency:1}),n;return{async readLock(){if(n!=null)return hl(n,e);n=new cr({concurrency:e.concurrency,autoStart:!1});let o=n,s=hl(n,e);return t.add(async()=>{o.start(),await o.onIdle().then(()=>{n===o&&(n=null)})}),s},async writeLock(){return n=null,hl(t,e)}}},Ny={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function dl(r){let e=Object.assign({},Ny,r);return ur==null&&(ur=sd(e),ur.isWorker!==!0&&(ur.addEventListener("requestReadLock",t=>{Lr[t.data.name]!=null&&Lr[t.data.name].readLock().then(async n=>t.data.handler().finally(()=>{n()}))}),ur.addEventListener("requestWriteLock",async t=>{Lr[t.data.name]!=null&&Lr[t.data.name].writeLock().then(async n=>t.data.handler().finally(()=>{n()}))}))),Lr[e.name]==null&&(Lr[e.name]=ky(e.name,e)),Lr[e.name]}var Te={ERR_INVALID_PARAMETERS:"ERR_INVALID_PARAMETERS"};var En;(function(r){let e;(function(o){let s;o.codec=()=>(s==null&&(s=Ve((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&i.value.byteLength>0&&(a.uint32(18),a.bytes(i.value)),c.lengthDelimited!==!1&&a.ldelim()},(i,a)=>{let c={key:"",value:new Uint8Array(0)},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let f=i.uint32();switch(f>>>3){case 1:c.key=i.string();break;case 2:c.value=i.bytes();break;default:i.skipType(f&7);break}}return c})),s),o.encode=i=>Fe(i,o.codec()),o.decode=i=>Me(i,o.codec())})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(o){let s;o.codec=()=>(s==null&&(s=Ve((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&(a.uint32(18),Js.codec().encode(i.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(i,a)=>{let c={key:""},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let f=i.uint32();switch(f>>>3){case 1:c.key=i.string();break;case 2:c.value=Js.codec().decode(i,i.uint32());break;default:i.skipType(f&7);break}}return c})),s),o.encode=i=>Fe(i,o.codec()),o.decode=i=>Me(i,o.codec())})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Ve((o,s,i={})=>{if(i.lengthDelimited!==!1&&s.fork(),o.addresses!=null)for(let a of o.addresses)s.uint32(10),Qs.codec().encode(a,s);if(o.protocols!=null)for(let a of o.protocols)s.uint32(18),s.string(a);if(o.publicKey!=null&&(s.uint32(34),s.bytes(o.publicKey)),o.peerRecordEnvelope!=null&&(s.uint32(42),s.bytes(o.peerRecordEnvelope)),o.metadata!=null&&o.metadata.size!==0)for(let[a,c]of o.metadata.entries())s.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},s);if(o.tags!=null&&o.tags.size!==0)for(let[a,c]of o.tags.entries())s.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},s);i.lengthDelimited!==!1&&s.ldelim()},(o,s)=>{let i={addresses:[],protocols:[],metadata:new Map,tags:new Map},a=s==null?o.len:o.pos+s;for(;o.pos<a;){let c=o.uint32();switch(c>>>3){case 1:i.addresses.push(Qs.codec().decode(o,o.uint32()));break;case 2:i.protocols.push(o.string());break;case 4:i.publicKey=o.bytes();break;case 5:i.peerRecordEnvelope=o.bytes();break;case 6:{let u=r.Peer$metadataEntry.codec().decode(o,o.uint32());i.metadata.set(u.key,u.value);break}case 7:{let u=r.Peer$tagsEntry.codec().decode(o,o.uint32());i.tags.set(u.key,u.value);break}default:o.skipType(c&7);break}}return i})),n),r.encode=o=>Fe(o,r.codec()),r.decode=o=>Me(o,r.codec())})(En||(En={}));var Qs;(function(r){let e;r.codec=()=>(e==null&&(e=Ve((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.multiaddr!=null&&t.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(t.multiaddr)),t.isCertified!=null&&(n.uint32(16),n.bool(t.isCertified)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={multiaddr:new Uint8Array(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.multiaddr=t.bytes();break;case 2:o.isCertified=t.bool();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Fe(t,r.codec()),r.decode=t=>Me(t,r.codec())})(Qs||(Qs={}));var Js;(function(r){let e;r.codec=()=>(e==null&&(e=Ve((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.value!=null&&t.value!==0&&(n.uint32(8),n.uint32(t.value)),t.expiry!=null&&(n.uint32(16),n.uint64(t.expiry)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={value:0},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.value=t.uint32();break;case 2:o.expiry=t.uint64();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Fe(t,r.codec()),r.decode=t=>Me(t,r.codec())})(Js||(Js={}));function xn(r,e){let t=En.decode(e);t.publicKey!=null&&r.publicKey==null&&(r=Rh({...r,publicKey:r.publicKey}));let n=new Map,o=BigInt(Date.now());for(let[s,i]of t.tags.entries())i.expiry!=null&&i.expiry<o||n.set(s,i);return{...t,id:r,addresses:t.addresses.map(({multiaddr:s,isCertified:i})=>({multiaddr:ne(s),isCertified:i??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}var Ft="/",id=new TextEncoder().encode(Ft),ei=id[0],Dr=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=L(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==ei)throw new Error("Invalid key")}toString(e="utf8"){return F(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Ft))}static random(){return new r(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new r(e):typeof e.uint8Array=="function"?new r(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=id),this._buf[0]!==ei){let e=new Uint8Array(this._buf.byteLength+1);e.fill(ei,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===ei;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let o=0;o<t.length;o++){if(n.length<o+1)return!1;let s=t[o],i=n[o];if(s<i)return!0;if(s>i)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Ft).slice(1)}type(){return Ly(this.baseNamespace())}name(){return Dy(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Ft)||(e+=Ft),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Ft):new r(e.slice(0,-1).join(Ft))}child(e){return this.toString()===Ft?e:e.toString()===Ft?this:new r(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()===this.toString()?!1:e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()===this.toString()?!1:this.toString().startsWith(e.toString())}isTopLevel(){return this.list().length===1}concat(...e){return r.withNamespaces([...this.namespaces(),...Py(e.map(t=>t.namespaces()))])}};function Ly(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function Dy(r){let e=r.split(":");return e[e.length-1]}function Py(r){return[].concat(...r)}var pl="/peers/";function vn(r){if(!Co(r)||r.type==null)throw new E("Invalid PeerId",Te.ERR_INVALID_PARAMETERS);let e=r.toCID().toString();return new Dr(`${pl}${e}`)}async function ad(r,e,t){let n=new Map;for(let o of t){if(o==null)continue;if(o.multiaddr instanceof Uint8Array&&(o.multiaddr=ne(o.multiaddr)),!ar(o.multiaddr))throw new E("Multiaddr was invalid",Te.ERR_INVALID_PARAMETERS);if(!await e(r,o.multiaddr))continue;let s=o.isCertified??!1,i=o.multiaddr.toString(),a=n.get(i);a!=null?o.isCertified=a.isCertified||s:n.set(i,{multiaddr:o.multiaddr,isCertified:s})}return[...n.values()].sort((o,s)=>o.multiaddr.toString().localeCompare(s.multiaddr.toString())).map(({isCertified:o,multiaddr:s})=>({isCertified:o,multiaddr:s.bytes}))}async function ri(r,e,t,n){if(e==null)throw new E("Invalid PeerData",Te.ERR_INVALID_PARAMETERS);if(e.publicKey!=null&&r.publicKey!=null&&!J(e.publicKey,r.publicKey))throw new E("publicKey bytes do not match peer id publicKey bytes",Te.ERR_INVALID_PARAMETERS);let o=n.existingPeer;if(o!=null&&!r.equals(o.id))throw new E("peer id did not match existing peer id",Te.ERR_INVALID_PARAMETERS);let s=o?.addresses??[],i=new Set(o?.protocols??[]),a=o?.metadata??new Map,c=o?.tags??new Map,u=o?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(s=[],e.multiaddrs!=null&&s.push(...e.multiaddrs.map(l=>({isCertified:!1,multiaddr:l}))),e.addresses!=null&&s.push(...e.addresses)),e.protocols!=null&&(i=new Set(e.protocols)),e.metadata!=null){let l=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=ti(l,{validate:cd})}if(e.tags!=null){let l=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=ti(l,{validate:ld,map:ud})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&s.push(...e.multiaddrs.map(l=>({isCertified:!1,multiaddr:l}))),e.addresses!=null&&s.push(...e.addresses),e.protocols!=null&&(i=new Set([...i,...e.protocols])),e.metadata!=null){let l=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[p,h]of l)h==null?a.delete(p):a.set(p,h);a=ti([...a.entries()],{validate:cd})}if(e.tags!=null){let l=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),p=new Map(c);for(let[h,d]of l)d==null?p.delete(h):p.set(h,d);c=ti([...p.entries()],{validate:ld,map:ud})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}let f={addresses:await ad(r,n.addressFilter??(async()=>!0),s),protocols:[...i.values()].sort((l,p)=>l.localeCompare(p)),metadata:a,tags:c,publicKey:o?.id.publicKey??e.publicKey??r.publicKey,peerRecordEnvelope:u};return r.type!=="RSA"&&delete f.publicKey,f}function ti(r,e){let t=new Map;for(let[n,o]of r)o!=null&&e.validate(n,o);for(let[n,o]of r.sort(([s],[i])=>s.localeCompare(i)))o!=null&&t.set(n,e.map?.(n,o)??o);return t}function cd(r,e){if(typeof r!="string")throw new E("Metadata key must be a string",Te.ERR_INVALID_PARAMETERS);if(!(e instanceof Uint8Array))throw new E("Metadata value must be a Uint8Array",Te.ERR_INVALID_PARAMETERS)}function ld(r,e){if(typeof r!="string")throw new E("Tag name must be a string",Te.ERR_INVALID_PARAMETERS);if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new E("Tag value must be an integer",Te.ERR_INVALID_PARAMETERS);if(e.value<0||e.value>100)throw new E("Tag value must be between 0-100",Te.ERR_INVALID_PARAMETERS)}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new E("Tag ttl must be an integer",Te.ERR_INVALID_PARAMETERS);if(e.ttl<0)throw new E("Tag ttl must be between greater than 0",Te.ERR_INVALID_PARAMETERS)}}function ud(r,e){let t;return e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl))),{value:e.value??0,expiry:t}}function ni(r,e,t){let n=r.toString().split("/")[2],o=Ye.decode(n),s=un(o),i=t.get(s);if(i!=null)return i;let a=xn(s,e);return t.set(s,a),a}function Oy(r,e){return r==null?{}:{prefix:pl,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(ni(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(ni(n.key,n.value,e),ni(o.key,o.value,e)))}}var oi=class{peerId;datastore;lock;addressFilter;constructor(e,t={}){this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=dl({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(vn(e))}async delete(e){if(this.peerId.equals(e))throw new E("Cannot delete self peer",Te.ERR_INVALID_PARAMETERS);await this.datastore.delete(vn(e))}async load(e){let t=await this.datastore.get(vn(e));return xn(e,t)}async save(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await ri(e,t,"patch",{addressFilter:this.addressFilter});return this.#t(e,s,n,o)}async patch(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await ri(e,t,"patch",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,n,o)}async merge(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await ri(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,n,o)}async*all(e){let t=new Xe;for await(let{key:n,value:o}of this.datastore.query(Oy(e??{},t))){let s=ni(n,o,t);s.id.equals(this.peerId)||(yield s)}}async#e(e){try{let t=await this.datastore.get(vn(e)),n=xn(e,t);return{existingBuf:t,existingPeer:n}}catch(t){if(t.code!=="ERR_NOT_FOUND")throw t}return{}}async#t(e,t,n,o){let s=En.encode(t);return n!=null&&J(s,n)?{peer:xn(e,s),previous:o,updated:!1}:(await this.datastore.put(vn(e),s),{peer:xn(e,s),previous:o,updated:!0})}};var si=class{store;events;peerId;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.events=e.events,this.peerId=e.peerId,this.store=new oi(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){this.log.trace("forEach await read lock");let n=await this.store.lock.readLock();this.log.trace("forEach got read lock");try{for await(let o of this.store.all(t))e(o)}finally{this.log.trace("forEach release read lock"),n()}}async all(e){this.log.trace("all await read lock");let t=await this.store.lock.readLock();this.log.trace("all got read lock");try{return await fo(this.store.all(e))}finally{this.log.trace("all release read lock"),t()}}async delete(e){this.log.trace("delete await write lock");let t=await this.store.lock.writeLock();this.log.trace("delete got write lock");try{await this.store.delete(e)}finally{this.log.trace("delete release write lock"),t()}}async has(e){this.log.trace("has await read lock");let t=await this.store.lock.readLock();this.log.trace("has got read lock");try{return await this.store.has(e)}finally{this.log.trace("has release read lock"),t()}}async get(e){this.log.trace("get await read lock");let t=await this.store.lock.readLock();this.log.trace("get got read lock");try{return await this.store.load(e)}finally{this.log.trace("get release read lock"),t()}}async save(e,t){this.log.trace("save await write lock");let n=await this.store.lock.writeLock();this.log.trace("save got write lock");try{let o=await this.store.save(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("save release write lock"),n()}}async patch(e,t){this.log.trace("patch await write lock");let n=await this.store.lock.writeLock();this.log.trace("patch got write lock");try{let o=await this.store.patch(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("patch release write lock"),n()}}async merge(e,t){this.log.trace("merge await write lock");let n=await this.store.lock.writeLock();this.log.trace("merge got write lock");try{let o=await this.store.merge(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("merge release write lock"),n()}}async consumePeerRecord(e,t){let n=await dn.openAndCertify(e,Nr.DOMAIN);if(t?.equals(n.peerId)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",t,n.peerId),!1;let o=Nr.createFromProtobuf(n.payload),s;try{s=await this.get(n.peerId)}catch(i){if(i.code!=="ERR_NOT_FOUND")throw i}if(s?.peerRecordEnvelope!=null){let i=await dn.createFromProtobuf(s.peerRecordEnvelope),a=Nr.createFromProtobuf(i.payload);if(a.seqNumber>=o.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",a.seqNumber,o.seqNumber),!1}return await this.patch(o.peerId,{peerRecordEnvelope:e,addresses:o.multiaddrs.map(i=>({isCertified:!0,multiaddr:i}))}),!0}#e(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}};function Uy(r){return r[Symbol.asyncIterator]!=null}function My(r){if(Uy(r))return(async()=>{for await(let e of r);})();for(let e of r);}var ml=My;function Fy(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var fd=Fy;function Vy(r){return r[Symbol.asyncIterator]!=null}function Ky(r,e){let t=0;if(Vy(r))return async function*(){for await(let c of r)await e(c,t++)&&(yield c)}();let n=fd(r),{value:o,done:s}=n.next();if(s===!0)return function*(){}();let i=e(o,t++);if(typeof i.then=="function")return async function*(){await i&&(yield o);for await(let c of n)await e(c,t++)&&(yield c)}();let a=e;return function*(){i===!0&&(yield o);for(let c of n)a(c,t++)&&(yield c)}()}var Pr=Ky;function Hy(r){return r[Symbol.asyncIterator]!=null}function $y(r,e){return Hy(r)?async function*(){yield*(await fo(r)).sort(e)}():function*(){yield*fo(r).sort(e)}()}var gl=$y;function qy(r){return r[Symbol.asyncIterator]!=null}function zy(r,e){return qy(r)?async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}}():function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}}()}var yl=zy;var ii=class{put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(let{key:n,value:o}of e)await this.put(n,o,t),yield n}async*getMany(e,t={}){for await(let n of e)yield{key:n,value:await this.get(n,t)}}async*deleteMany(e,t={}){for await(let n of e)await this.delete(n,t),yield n}batch(){let e=[],t=[];return{put(n,o){e.push({key:n,value:o})},delete(n){t.push(n)},commit:async n=>{await ml(this.putMany(e,n)),e=[],await ml(this.deleteMany(t,n)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let n=this._all(e,t);if(e.prefix!=null){let o=e.prefix;n=Pr(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Pr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>gl(o,s),n)),e.offset!=null){let o=0,s=e.offset;n=Pr(n,()=>o++>=s)}return e.limit!=null&&(n=yl(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let o=e.prefix;n=Pr(n,s=>s.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Pr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>gl(o,s),n)),e.offset!=null){let o=e.offset,s=0;n=Pr(n,()=>s++>=o)}return e.limit!=null&&(n=yl(n,e.limit)),n}};var md=pr(pd(),1);function gd(r){return r=r??new Error("Not Found"),(0,md.default)(r,"ERR_NOT_FOUND")}var ai=class extends ii{data;constructor(){super(),this.data=new Map}put(e,t){return this.data.set(e.toString(),t),e}get(e){let t=this.data.get(e.toString());if(t==null)throw gd();return t}has(e){return this.data.has(e.toString())}delete(e){this.data.delete(e.toString())}*_all(){for(let[e,t]of this.data.entries())yield{key:new Dr(e),value:t}}*_allKeys(){for(let e of this.data.keys())yield new Dr(e)}};function yd(r,e){let t;return function(){let n=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(n,e)}}var Wy=r=>r;function wl(r,e){let t=r.getPeerId();return t!=null&&ye(t).equals(e)&&(r=r.decapsulate(ne(`/p2p/${e.toString()}`))),r}var ci=class{log;components;listen;announce;observed;announceFilter;constructor(e,t={}){let{listen:n=[],announce:o=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(s=>s.toString()),this.announce=new Set(o.map(s=>s.toString())),this.observed=new Map,this.announceFilter=t.announceFilter??Wy,this._updatePeerStoreAddresses=yd(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){let e=this.getAnnounceAddrs().concat(this.components.transportManager.getAddrs()).concat([...this.observed.entries()].filter(([t,n])=>n.confident).map(([t])=>ne(t))).map(t=>t.getPeerId()===this.components.peerId.toString()?t.decapsulate(`/p2p/${this.components.peerId.toString()}`):t);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(t=>{this.log.error("error updating addresses",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>ne(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>ne(e))}getObservedAddrs(){return Array.from(this.observed).map(([e])=>ne(e))}addObservedAddr(e){e=wl(e,this.components.peerId);let t=e.toString();this.observed.has(t)||this.observed.set(t,{confident:!1})}confirmObservedAddr(e){e=wl(e,this.components.peerId);let t=e.toString(),o=(this.observed.get(t)??{confident:!1}).confident;this.observed.set(t,{confident:!0}),o||this._updatePeerStoreAddresses()}removeObservedAddr(e){e=wl(e,this.components.peerId);let t=e.toString();this.observed.delete(t)}getAddresses(){let e=this.getAnnounceAddrs().map(n=>n.toString());e.length===0&&(e=this.components.transportManager.getAddrs().map(n=>n.toString())),e=e.concat(Array.from(this.observed).filter(([n,o])=>o.confident).map(([n])=>n));let t=new Set(e);return this.announceFilter(Array.from(t).map(n=>ne(n))).map(n=>n.protos().pop()?.path===!0||n.getPeerId()===this.components.peerId.toString()?n:n.encapsulate(`/p2p/${this.components.peerId.toString()}`))}};var bl=class{components={};_started=!1;constructor(e={}){this.components={};for(let[t,n]of Object.entries(e))this.components[t]=n;this.components.logger==null&&(this.components.logger=$s())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>fu(t)).map(async t=>{await t[e]?.()}))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}},jy=["metrics","connectionProtector","dns"],Xy=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function wd(r={}){let e=new bl(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!Xy.includes(o)){let i=e.components[o];if(i==null&&!jy.includes(o))throw new E(`${o} not set`,"ERR_SERVICE_MISSING");return i}return Reflect.get(n,o,s)},set(n,o,s){return typeof o=="string"?e.components[o]=s:Reflect.set(n,o,s),!0}})}function bd(r){let e={};for(let t of Object.values(r.components))for(let n of Zy(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of Qy(t))if(e[n]!==!0)throw new E(`Service "${Jy(t)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`,"ERR_UNMET_SERVICE_DEPENDENCIES")}function Zy(r){return Array.isArray(r?.[kn])?r[kn]:[]}function Qy(r){return Array.isArray(r?.[ua])?r[ua]:[]}function Jy(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}var xd=pr(Ed(),1),ew=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"],tw=ew.map(r=>new xd.Netmask(r));function El(r){for(let e of tw)if(e.contains(r))return!0;return!1}function rw(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function nw(r){let e=r.split(":");if(e.length<2)return!1;let t=e[e.length-1].padStart(4,"0"),n=e[e.length-2].padStart(4,"0"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return El(o)}function ow(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function sw(r){let e=r.split(":"),t=e[e.length-1];return El(t)}function iw(r){return/^::$/.test(r)||/^::1$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}function li(r){return mn(r)?El(r):rw(r)?nw(r):ow(r)?sw(r):gn(r)?iw(r):void 0}function vd(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let t=e.stringTuples();return t[0][0]===4||t[0][0]===41?!!li(`${t[0][1]}`):!1},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...r}}var aw=r=>r.toString().split("/").slice(1),wo=r=>({match:e=>e.length<1?!1:r(e[0])?e.slice(1):!1,pattern:"fn"}),Y=r=>({match:e=>wo(t=>t===r).match(e),pattern:r}),hi=()=>({match:r=>wo(e=>typeof e=="string").match(r),pattern:"{string}"}),di=()=>({match:r=>wo(e=>!isNaN(parseInt(e))).match(r),pattern:"{number}"}),Be=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{ae.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),ui=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{Ia.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),be=r=>({match:e=>{let t=r.match(e);return t===!1?e:t},pattern:`optional(${r.pattern})`}),rt=(...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},pattern:`or(${r.map(e=>e.pattern).join(", ")})`}),Z=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e},pattern:`and(${r.map(e=>e.pattern).join(", ")})`});function fe(...r){function e(o){let s=aw(o);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{matches:t,exactMatch:n}}var vl=Z(Y("dns4"),hi()),_l=Z(Y("dns6"),hi()),Al=Z(Y("dnsaddr"),hi()),_d=Z(Y("dns"),hi()),gR=fe(vl),yR=fe(_l),wR=fe(Al),bR=fe(rt(_d,Al,vl,_l)),Ad=Z(Y("ip4"),wo(mn)),Sd=Z(Y("ip6"),wo(gn)),Rd=rt(Ad,Sd),vt=rt(Rd,_d,vl,_l,Al),ER=fe(vt),xR=fe(Ad),vR=fe(Sd),_R=fe(Rd),Sl=Z(vt,Y("tcp"),di()),bo=Z(vt,Y("udp"),di()),AR=fe(Sl),SR=fe(bo),Rl=Z(bo,Y("quic")),pi=Z(bo,Y("quic-v1")),cw=rt(Rl,pi),RR=fe(Rl),IR=fe(pi),xl=rt(vt,Sl,bo,Rl,pi),Id=rt(Z(xl,Y("ws"),be(Be()))),TR=fe(Id),Td=rt(Z(xl,Y("wss"),be(Be())),Z(xl,Y("tls"),Y("ws"),be(Be()))),BR=fe(Td),Bd=Z(bo,Y("webrtc-direct"),be(ui()),be(ui()),be(Be())),CR=fe(Bd),Cd=Z(pi,Y("webtransport"),be(ui()),be(ui()),be(Be())),kR=fe(Cd),fi=rt(Id,Td,Z(Sl,be(Be())),Z(cw,be(Be())),Z(vt,be(Be())),Bd,Cd,Be()),NR=fe(fi),lw=Z(fi,Y("p2p-circuit"),Be()),Eo=fe(lw),uw=rt(Z(fi,Y("p2p-circuit"),Y("webrtc"),be(Be())),Z(fi,Y("webrtc"),be(Be())),Y("webrtc")),LR=fe(uw),fw=rt(Z(vt,Y("tcp"),di(),Y("http"),be(Be())),Z(vt,Y("http"),be(Be()))),DR=fe(fw),hw=rt(Z(vt,Y("tcp"),rt(Z(Y("443"),Y("http")),Z(di(),Y("https"))),be(Be())),Z(vt,Y("tls"),Y("http"),be(Be())),Z(vt,Y("https"),be(Be()))),PR=fe(hw);function Il(r){try{let{address:e}=r.nodeAddress();return!!li(e)}catch{return!0}}function dw(r,e){let t=Il(r.multiaddr),n=Il(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function pw(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function mw(r,e){let t=Eo.exactMatch(r.multiaddr),n=Eo.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function _n(r,e){let t=dw(r,e);if(t!==0)return t;let n=mw(r,e);return n!==0?n:pw(r,e)}var he=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};function mi(r){let e=[Ze.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var Tl=60;function gi(r){return{Status:r.Status??0,TC:r.TC??r.flag_tc??!1,RD:r.RD??r.flag_rd??!1,RA:r.RA??r.flag_ra??!1,AD:r.AD??r.flag_ad??!1,CD:r.CD??r.flag_cd??!1,Question:(r.Question??r.questions??[]).map(e=>({name:e.name,type:Ze[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:Ze[e.type],TTL:e.TTL??e.ttl??Tl,data:e.data instanceof Uint8Array?F(e.data):e.data}))}}var gw=4;function Bl(r,e={}){let t=new cr({concurrency:e.queryConcurrency??gw});return async(n,o={})=>{let s=new URLSearchParams;s.set("name",n),mi(o.types).forEach(a=>{s.append("type",Ze[a])}),o.onProgress?.(new he("dns:query",{detail:n}));let i=await t.add(async()=>{let a=await fetch(`${r}?${s}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let c=gi(await a.json());return o.onProgress?.(new he("dns:response",{detail:c})),c},{signal:o.signal});if(i==null)throw new Error("No DNS response received");return i}}function kd(){return[Bl("https://cloudflare-dns.com/dns-query"),Bl("https://dns.google/resolve")]}var Dd=pr(Ld(),1);var Cl=class{lru;constructor(e){this.lru=(0,Dd.default)(e)}get(e,t){let n=!0,o=[];for(let s of t){let i=this.getAnswers(e,s);if(i.length===0){n=!1;break}o.push(...i)}if(n)return gi({answers:o})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,o=this.lru.get(n);if(o!=null){let s=o.filter(i=>i.expires>Date.now()).map(({expires:i,value:a})=>({...a,TTL:Math.round((i-Date.now())/1e3),type:Ze[a.type]}));return s.length===0&&this.lru.remove(n),s}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(t.TTL??Tl)*1e3,value:t}),this.lru.set(n,o)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function Pd(r){return new Cl(r)}var yw=1e3,yi=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=Pd(e.cacheSize??yw),Object.entries(e.resolvers??{}).forEach(([t,n])=>{Array.isArray(n)||(n=[n]),t.endsWith(".")||(t=`${t}.`),this.resolvers[t]=n}),this.resolvers["."]==null&&(this.resolvers["."]=kd())}async query(e,t={}){let n=mi(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new he("dns:cache",{detail:o})),o;let s=`${e.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of i){if(t.signal?.aborted===!0)break;try{let u=await c(e,{...t,types:n});for(let f of u.Answer)this.cache.add(e,f);return u}catch(u){a.push(u),t.onProgress?.(new he("dns:error",{detail:u}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${e} ${n} failed`)}};var Ze;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Ze||(Ze={}));function Od(r={}){return new yi(r)}var ww=32,{code:bw}=j("dnsaddr"),Or=async function(e,t={}){let n=t.maxRecursiveDepth??ww;if(n===0)throw new E("Max recursive depth reached","ERR_MAX_RECURSIVE_DEPTH_REACHED");let[,o]=e.stringTuples().find(([u])=>u===bw)??[],i=await(t?.dns??Od()).query(`_dnsaddr.${o}`,{signal:t?.signal,types:[Ze.TXT]}),a=e.getPeerId(),c=[];for(let u of i.Answer){let f=u.data.replace(/["']/g,"").trim().split("=")[1];if(f==null||a!=null&&!f.includes(a))continue;let l=ne(f);if(f.startsWith("/dnsaddr")){let p=await l.resolve({...t,maxRecursiveDepth:n-1});c.push(...p.map(h=>h.toString()))}else c.push(l.toString())}return c};var zd=pr(qd(),1),Ei=zd.default;var Vt;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.ERR_PROTECTOR_REQUIRED="Private network is enforced, but no protector was provided",r.NOT_FOUND="Not found"})(Vt||(Vt={}));var k;(function(r){r.ERR_PROTECTOR_REQUIRED="ERR_PROTECTOR_REQUIRED",r.ERR_PEER_DIAL_INTERCEPTED="ERR_PEER_DIAL_INTERCEPTED",r.ERR_CONNECTION_INTERCEPTED="ERR_CONNECTION_INTERCEPTED",r.ERR_INVALID_PROTOCOLS_FOR_STREAM="ERR_INVALID_PROTOCOLS_FOR_STREAM",r.ERR_CONNECTION_ENDED="ERR_CONNECTION_ENDED",r.ERR_CONNECTION_FAILED="ERR_CONNECTION_FAILED",r.ERR_NODE_NOT_STARTED="ERR_NODE_NOT_STARTED",r.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",r.ERR_TOO_MANY_ADDRESSES="ERR_TOO_MANY_ADDRESSES",r.ERR_NO_VALID_ADDRESSES="ERR_NO_VALID_ADDRESSES",r.ERR_RELAYED_DIAL="ERR_RELAYED_DIAL",r.ERR_DIALED_SELF="ERR_DIALED_SELF",r.ERR_DISCOVERED_SELF="ERR_DISCOVERED_SELF",r.ERR_DUPLICATE_TRANSPORT="ERR_DUPLICATE_TRANSPORT",r.ERR_ENCRYPTION_FAILED="ERR_ENCRYPTION_FAILED",r.ERR_HOP_REQUEST_FAILED="ERR_HOP_REQUEST_FAILED",r.ERR_INVALID_KEY="ERR_INVALID_KEY",r.ERR_INVALID_MESSAGE="ERR_INVALID_MESSAGE",r.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",r.ERR_INVALID_PEER="ERR_INVALID_PEER",r.ERR_MUXER_UNAVAILABLE="ERR_MUXER_UNAVAILABLE",r.ERR_NOT_FOUND="ERR_NOT_FOUND",r.ERR_TRANSPORT_UNAVAILABLE="ERR_TRANSPORT_UNAVAILABLE",r.ERR_TRANSPORT_DIAL_FAILED="ERR_TRANSPORT_DIAL_FAILED",r.ERR_UNSUPPORTED_PROTOCOL="ERR_UNSUPPORTED_PROTOCOL",r.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED="ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED",r.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",r.ERR_SIGNATURE_NOT_VALID="ERR_SIGNATURE_NOT_VALID",r.ERR_FIND_SELF="ERR_FIND_SELF",r.ERR_NO_ROUTERS_AVAILABLE="ERR_NO_ROUTERS_AVAILABLE",r.ERR_CONNECTION_NOT_MULTIPLEXED="ERR_CONNECTION_NOT_MULTIPLEXED",r.ERR_NO_DIAL_TOKENS="ERR_NO_DIAL_TOKENS",r.ERR_INVALID_CMS="ERR_INVALID_CMS",r.ERR_MISSING_KEYS="ERR_MISSING_KEYS",r.ERR_NO_KEY="ERR_NO_KEY",r.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",r.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",r.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",r.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",r.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",r.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",r.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",r.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",r.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",r.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",r.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",r.ERR_MISSING_PUBLIC_KEY="ERR_MISSING_PUBLIC_KEY",r.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",r.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",r.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH",r.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",r.ERR_WRONG_PING_ACK="ERR_WRONG_PING_ACK",r.ERR_INVALID_RECORD="ERR_INVALID_RECORD",r.ERR_ALREADY_SUCCEEDED="ERR_ALREADY_SUCCEEDED",r.ERR_NO_HANDLER_FOR_PROTOCOL="ERR_NO_HANDLER_FOR_PROTOCOL",r.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS",r.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",r.ERR_CONNECTION_DENIED="ERR_CONNECTION_DENIED",r.ERR_TRANSFER_LIMIT_EXCEEDED="ERR_TRANSFER_LIMIT_EXCEEDED"})(k||(k={}));var Sw={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:Or},addressSorter:_n},transportManager:{faultTolerance:Ht.FATAL_ALL}};async function Gd(r){let e=Ei(Sw,r);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new E(Vt.ERR_PROTECTOR_REQUIRED,k.ERR_PROTECTOR_REQUIRED);if(e.privateKey!=null&&!(await fn(e.privateKey.public.bytes,e.privateKey.bytes)).equals(e.peerId))throw new E("Private key doesn't match peer id",k.ERR_INVALID_KEY);return e}var Yd=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},Rw=new WeakMap;function Iw({clearTimeout:r,setTimeout:e}={}){return(t,{value:n,signal:o}={})=>{if(o?.aborted)return Promise.reject(Yd());let s,i,a,c=r??clearTimeout,u=()=>{c(s),a(Yd())},f=()=>{o&&o.removeEventListener("abort",u)},l=new Promise((p,h)=>{i=()=>{f(),p(n)},a=h,s=(e??setTimeout)(i,t)});return o&&o.addEventListener("abort",u,{once:!0}),Rw.set(l,()=>{c(s),s=null,i()}),l}}var Tw=Iw(),Wd=Tw;var xi=class{memoryStorage;points;duration;blockDuration;execEvenly;execEvenlyMinDelayMs;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.execEvenly=e.execEvenly??!1,this.execEvenlyMinDelayMs=e.execEvenlyMinDelayMs??this.duration*1e3/this.points,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new Nl}async consume(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+t&&(i=this.memoryStorage.set(o,i.consumedPoints,this.blockDuration)),new E("Rate limit exceeded","ERR_RATE_LIMIT_EXCEEDED",i);if(this.execEvenly&&i.msBeforeNext>0&&!i.isFirstInDuration){let a=Math.ceil(i.msBeforeNext/(i.remainingPoints+2));a<this.execEvenlyMinDelayMs&&(a=i.consumedPoints*this.execEvenlyMinDelayMs),await Wd(a)}return i}penalty(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,-t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(e,t){let n=t*1e3,o=this.points+1;return this.memoryStorage.set(this.getKey(e),o,t),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:o,isFirstInDuration:!1}}set(e,t,n=0){let o=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,n),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:t,isFirstInDuration:!1}}get(e){let t=this.memoryStorage.get(this.getKey(e));return t!=null&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return e?.customDuration!=null&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.substring(this.keyPrefix.length)}},Nl=class{storage;constructor(){this.storage=new Map}incrby(e,t,n){let o=this.storage.get(e);if(o!=null){let s=o.expiresAt!=null?o.expiresAt.getTime()-new Date().getTime():-1;return o.expiresAt==null||s>0?(o.value+=t,{remainingPoints:0,msBeforeNext:s,consumedPoints:o.value,isFirstInDuration:!1}):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let o=n*1e3,s=this.storage.get(e);s!=null&&clearTimeout(s.timeoutId);let i={value:t,expiresAt:o>0?new Date(Date.now()+o):void 0};return this.storage.set(e,i),o>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(e)},o),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:i.value,isFirstInDuration:!0}}get(e){let t=this.storage.get(e);if(t!=null)return{remainingPoints:0,msBeforeNext:t.expiresAt!=null?t.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){let t=this.storage.get(e);return t!=null?(t.timeoutId!=null&&clearTimeout(t.timeoutId),this.storage.delete(e),!0):!1}};function vi(r){if(Co(r))return{peerId:r,multiaddrs:[]};Array.isArray(r)||(r=[r]);let e;if(r.length>0){let t=r[0].getPeerId();e=t==null?void 0:ye(t),r.forEach(n=>{if(!ar(n))throw new E("Invalid Multiaddr",k.ERR_INVALID_MULTIADDR);let o=n.getPeerId();if(o==null){if(e!=null)throw new E("Multiaddrs must all have the same peer id or have no peer id",k.ERR_INVALID_PARAMETERS)}else{let s=ye(o);if(e?.equals(s)!==!0)throw new E("Multiaddrs must all have the same peer id or have no peer id",k.ERR_INVALID_PARAMETERS)}})}return{peerId:e,multiaddrs:r}}function ue(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var _i=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)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}},Rn=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new _i(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 _i(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 Ll=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Ai(r={}){return Bw(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 Bw(r,e){e=e??{};let t=e.onEnd,n=new Rn,o,s,i,a=ue(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((w,g)=>{s=y=>{s=null,n.push(y);try{w(r(n))}catch(b){g(b)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=ue()})}},u=w=>s!=null?s(w):(n.push(w),o),f=w=>(n=new Rn,s!=null?s({error:w}):(n.push({error:w}),o)),l=w=>{if(i)return o;if(e?.objectMode!==!0&&w?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:w})},p=w=>i?o:(i=!0,w!=null?f(w):u({done:!0})),h=()=>(n=new Rn,p(),{done:!0}),d=w=>(p(w),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:d,push:l,end:p,get readableLength(){return n.size},onEmpty:async w=>{let g=w?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let y,b;g!=null&&(y=new Promise((x,A)=>{b=()=>{A(new Ll)},g.addEventListener("abort",b)}));try{await Promise.race([a.promise,y])}finally{b!=null&&g!=null&&g?.removeEventListener("abort",b)}}},t==null)return o;let m=o;return o={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(w){return m.throw(w),t!=null&&(t(w),t=void 0),{done:!0}},return(){return m.return(),t!=null&&(t(),t=void 0),{done:!0}},push:l,end(w){return m.end(w),t!=null&&(t(w),t=void 0),o},get readableLength(){return m.readableLength},onEmpty:w=>m.onEmpty(w)},o}var Dl=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=t??"ABORT_ERR"}};async function In(r,e,t,n){let o=new Dl(n?.errorMessage,n?.errorCode);return t?.aborted===!0?Promise.reject(o):new Promise((s,i)=>{function a(){t?.removeEventListener("abort",f),r.removeEventListener(e,c),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,u)}let c=l=>{try{if(n?.filter?.(l)===!1)return}catch(p){a(),i(p);return}a(),s(l)},u=l=>{a(),i(l.detail)},f=()=>{a(),i(o)};t?.addEventListener("abort",f),r.addEventListener(e,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,u)})}var Si=class extends Error{type;code;constructor(e,t,n){super(e??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=t??"ABORT_ERR"}};async function fr(r,e,t){if(e==null)return r;if(e.aborted)return Promise.reject(new Si(t?.errorMessage,t?.errorCode,t?.errorName));let n,o=new Si(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var Ri=class{deferred;signal;constructor(e){this.signal=e,this.deferred=ue(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new $t)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Cw(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Ii=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=Cw(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,ie(1/0,this.controller.signal),this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new $t),this.cleanup())}async join(e={}){let t=new Ri(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await fr(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var Tn=class extends At{concurrency;queue;pending;sort;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.pending=0,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[]}tryToStartAnother(){if(this.size===0)return queueMicrotask(()=>{this.safeDispatchEvent("empty")}),this.running===0&&queueMicrotask(()=>{this.safeDispatchEvent("idle")}),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,t){t?.signal?.throwIfAborted();let n=new Ii(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(t).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("error",{detail:o}),this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new $t)}),this.clear()}async onEmpty(e){this.size!==0&&await In(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await In(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await In(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=Ai({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},s=c=>{n(c.detail)},i=()=>{n()},a=()=>{n(new E("Queue aborted","ERR_QUEUE_ABORTED"))};this.addEventListener("completed",o),this.addEventListener("error",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("error",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var Ti=class extends Tn{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var Bi="last-dial-failure";var Ci=5,ki=100,Ni=50,Li=1e3*60*7;var Ur={minConnections:Ci,maxQueueLength:100,autoDialConcurrency:25,autoDialPriority:0,autoDialInterval:5e3,autoDialPeerRetryThreshold:Li,autoDialDiscoveredPeersDebounce:10},Di=class{connectionManager;peerStore;queue;minConnections;autoDialPriority;autoDialIntervalMs;autoDialMaxQueueLength;autoDialPeerRetryThresholdMs;autoDialDiscoveredPeersDebounce;autoDialInterval;started;running;log;constructor(e,t){this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.minConnections=t.minConnections??Ur.minConnections,this.autoDialPriority=t.autoDialPriority??Ur.autoDialPriority,this.autoDialIntervalMs=t.autoDialInterval??Ur.autoDialInterval,this.autoDialMaxQueueLength=t.maxQueueLength??Ur.maxQueueLength,this.autoDialPeerRetryThresholdMs=t.autoDialPeerRetryThreshold??Ur.autoDialPeerRetryThreshold,this.autoDialDiscoveredPeersDebounce=t.autoDialDiscoveredPeersDebounce??Ur.autoDialDiscoveredPeersDebounce,this.log=e.logger.forComponent("libp2p:connection-manager:auto-dial"),this.started=!1,this.running=!1,this.queue=new Ti({concurrency:t.autoDialConcurrency??Ur.autoDialConcurrency,metricName:"libp2p_autodial_queue",metrics:e.metrics}),this.queue.addEventListener("error",o=>{this.log.error("error during auto-dial",o.detail)}),e.events.addEventListener("connection:close",()=>{this.autoDial().catch(o=>{this.log.error(o)})});let n;e.events.addEventListener("peer:discovery",()=>{clearTimeout(n),n=setTimeout(()=>{this.autoDial().catch(o=>{this.log.error(o)})},this.autoDialDiscoveredPeersDebounce)})}isStarted(){return this.started}start(){this.started=!0}afterStart(){this.autoDial().catch(e=>{this.log.error("error while autodialing",e)})}stop(){this.queue.clear(),clearTimeout(this.autoDialInterval),this.started=!1,this.running=!1}async autoDial(){if(!this.started||this.running)return;let e=this.connectionManager.getConnectionsMap(),t=e.size;if(t>=this.minConnections){this.minConnections>0&&this.log.trace("have enough connections %d/%d",t,this.minConnections);return}if(this.queue.size>this.autoDialMaxQueueLength){this.log("not enough connections %d/%d but auto dial queue is full",t,this.minConnections),this.sheduleNextAutodial();return}this.running=!0,this.log("not enough connections %d/%d - will dial peers to increase the number of connections",t,this.minConnections);let n=new Mt(this.connectionManager.getDialQueue().map(u=>u.peerId).filter(Boolean)),o=await this.peerStore.all({filters:[u=>u.addresses.length===0?(this.log.trace("not autodialing %p because they have no addresses",u.id),!1):e.has(u.id)?(this.log.trace("not autodialing %p because they are already connected",u.id),!1):n.has(u.id)?(this.log.trace("not autodialing %p because they are already being dialed",u.id),!1):this.queue.has(u.id)?(this.log.trace("not autodialing %p because they are already being autodialed",u.id),!1):!0]}),s=o.sort(()=>Math.random()>.5?1:-1),i=new Xe;for(let u of s)i.has(u.id)||i.set(u.id,[...u.tags.values()].reduce((f,l)=>f+l.value,0));let c=s.sort((u,f)=>{let l=i.get(u.id)??0,p=i.get(f.id)??0;return l>p?-1:l<p?1:0}).filter(u=>{let f=u.metadata.get(Bi);if(f==null)return!0;let l=parseInt(F(f));return isNaN(l)?!0:Date.now()-l>this.autoDialPeerRetryThresholdMs});this.log("selected %d/%d peers to dial",c.length,o.length);for(let u of c)this.queue.add(async()=>{let f=this.connectionManager.getConnectionsMap().size;if(f>=this.minConnections){this.log("got enough connections now %d/%d",f,this.minConnections),this.queue.clear();return}this.log("connecting to a peerStore stored peer %p",u.id),await this.connectionManager.openConnection(u.id,{priority:this.autoDialPriority})},{peerId:u.id}).catch(f=>{this.log.error("could not connect to peerStore stored peer",f)});this.running=!1,this.sheduleNextAutodial()}sheduleNextAutodial(){this.started&&(this.autoDialInterval=setTimeout(()=>{this.autoDial().catch(e=>{this.log.error("error while autodialing",e)})},this.autoDialIntervalMs))}};var Nw=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function jd(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??Nw;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}var Xd={maxConnections:ki,allow:[]},Pi=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??Xd.maxConnections,this.allow=t.allow??Xd.allow,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),e.events.addEventListener("connection:open",()=>{this.maybePruneConnections().catch(n=>{this.log.error(n)})})}async maybePruneConnections(){let e=this.connectionManager.getConnections(),t=e.length;if(this.log("checking max connections limit %d/%d",t,this.maxConnections),t<=this.maxConnections)return;let n=new Xe;for(let a of e){let c=a.remotePeer;if(!n.has(c)){n.set(c,0);try{let u=await this.peerStore.get(c);n.set(c,[...u.tags.values()].reduce((f,l)=>f+l.value,0))}catch(u){u.code!=="ERR_NOT_FOUND"&&this.log.error("error loading peer tags",u)}}}let o=this.sortConnections(e,n),s=Math.max(t-this.maxConnections,0),i=[];for(let a of o)if(this.log("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(u=>a.remoteAddr.toString().startsWith(u.toString()))||i.push(a),i.length===s)break;await Promise.all(i.map(async a=>{await jd(a,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:i})}sortConnections(e,t){return e.sort((n,o)=>{let s=n.timeline.open,i=o.timeline.open;return s<i?1:s>i?-1:0}).sort((n,o)=>n.direction==="outbound"&&o.direction==="inbound"?1:n.direction==="inbound"&&o.direction==="outbound"?-1:0).sort((n,o)=>n.streams.length>o.streams.length?1:n.streams.length<o.streams.length?-1:0).sort((n,o)=>{let s=t.get(n.remotePeer)??0,i=t.get(o.remotePeer)??0;return s>i?1:s<i?-1:0})}};var Oi=class extends Tn{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};function Mr(r){let e=new globalThis.AbortController;function t(){e.abort();for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}for(let s of r){if(s?.aborted===!0){t();break}s?.addEventListener!=null&&s.addEventListener("abort",t)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}async function Zd(r,e){let t=!1;for(let o of wn.keys())if(t=r.protoNames().includes(o),t)break;if(!t)return[r];let n=await r.resolve(e);return e.log("resolved %s to",r,n.map(o=>o.toString())),n}var xo={addressSorter:_n,maxParallelDials:Ni,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:5e3,resolvers:{dnsaddr:Or}},Ui=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(e,t={}){this.addressSorter=t.addressSorter??xo.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??xo.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??xo.maxDialQueueLength,this.dialTimeout=t.dialTimeout??xo.dialTimeout,this.connections=t.connections??new Xe,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.shutDownController=new AbortController,ie(1/0,this.shutDownController.signal);for(let[n,o]of Object.entries(t.resolvers??{}))wn.set(n,o);this.queue=new Oi({concurrency:t.maxParallelDials??xo.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("error",n=>{this.log.error("error in dial queue",n.detail)})}start(){this.shutDownController=new AbortController,ie(1/0,this.shutDownController.signal)}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:o}=vi(e),s=Array.from(this.connections.values()).flat().find(a=>t.force===!0?!1:a.remotePeer.equals(n)?!0:o.find(c=>c.equals(a.remoteAddr)));if(s!=null)return this.log("already connected to %a",s.remoteAddr),t.onProgress?.(new he("dial-queue:already-connected")),s;let i=this.queue.queue.find(a=>{if(n?.equals(a.options.peerId)===!0)return!0;let c=a.options.multiaddrs;if(c==null)return!1;for(let u of o)if(c.has(u.toString()))return!0;return!1});if(i!=null){this.log("joining existing dial target for %p",n);for(let a of o)i.options.multiaddrs.add(a.toString());return t.onProgress?.(new he("dial-queue:already-in-dial-queue")),i.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new E("Dial queue is full","ERR_DIAL_QUEUE_FULL");return this.log("creating dial target for %p",n,o.map(a=>a.toString())),t.onProgress?.(new he("dial-queue:add-to-dial-queue")),this.queue.add(async a=>{a?.onProgress?.(new he("dial-queue:start-dial"));let c=this.createDialAbortController(a?.signal),u;try{u=await this.calculateMultiaddrs(n,a?.multiaddrs,{...a,signal:c}),a?.onProgress?.(new he("dial-queue:calculated-addresses",u)),u.map(({multiaddr:f})=>f.toString()).forEach(f=>{a?.multiaddrs.add(f)})}catch(f){throw c.clear(),f}try{let f=0,l=[];for(let p of u){if(f===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",f,n),new E("Peer had more than maxPeerAddrsToDial",k.ERR_TOO_MANY_ADDRESSES);f++;try{let h=await this.components.transportManager.dial(p.multiaddr,{...a,signal:c});return this.log("dial to %a succeeded",p.multiaddr),h}catch(h){if(this.log.error("dial failed to %a",p.multiaddr,h),n!=null)try{await this.components.peerStore.patch(n,{metadata:{[Bi]:L(Date.now().toString())}})}catch(d){this.log.error("could not update last dial failure key for %p",n,d)}if(c.aborted)throw new E(h.message,No);l.push(h)}}throw l.length===1?l[0]:new ko(l,"All multiaddr dials failed",k.ERR_TRANSPORT_DIAL_FAILED)}finally{c.clear()}},{peerId:n,priority:t.priority??Hl,multiaddrs:new Set(o.map(a=>a.toString())),signal:t.signal,onProgress:t.onProgress})}createDialAbortController(e){let t=Mr([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e]);return ie(1/0,t),t}async calculateMultiaddrs(e,t=new Set,n={}){let o=[...t].map(l=>({multiaddr:ne(l),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new E("Tried to dial self",k.ERR_DIALED_SELF);if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new E("The dial request is blocked by gater.allowDialPeer",k.ERR_PEER_DIAL_INTERCEPTED);if(o.length===0){this.log("loading multiaddrs for %p",e);try{let l=await this.components.peerStore.get(e);o.push(...l.addresses),this.log("loaded multiaddrs for %p",e,o.map(({multiaddr:p})=>p.toString()))}catch(l){if(l.code!==k.ERR_NOT_FOUND)throw l}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let l=await this.components.peerRouting.findPeer(e);this.log("found multiaddrs for %p in the peer routing",e,o.map(({multiaddr:p})=>p.toString())),o.push(...l.multiaddrs.map(p=>({multiaddr:p,isCertified:!1})))}catch(l){l.code!==k.ERR_NO_ROUTERS_AVAILABLE&&this.log.error("looking up multiaddrs for %p in the peer routing failed",e,l)}}}let s=(await Promise.all(o.map(async l=>{let p=await Zd(l.multiaddr,{dns:this.components.dns,...n,log:this.log});return p.length===1&&p[0].equals(l.multiaddr)?l:p.map(h=>({multiaddr:h,isCertified:!1}))}))).flat();if(e!=null){let l=`/p2p/${e.toString()}`;s=s.map(p=>p.multiaddr.protos().pop()?.path===!0?p:p.multiaddr.getPeerId()==null?{multiaddr:p.multiaddr.encapsulate(l),isCertified:p.isCertified}:p)}let i=s.filter(l=>{if(this.components.transportManager.dialTransportForMultiaddr(l.multiaddr)==null)return!1;let p=l.multiaddr.getPeerId();return e!=null&&p!=null?e.equals(p):!0}),a=new Map;for(let l of i){let p=l.multiaddr.toString(),h=a.get(p);if(h!=null){h.isCertified=h.isCertified||l.isCertified||!1;continue}a.set(p,l)}let c=[...a.values()];if(c.length===0)throw new E("The dial request has no valid addresses",k.ERR_NO_VALID_ADDRESSES);let u=[];for(let l of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(l.multiaddr)||u.push(l);let f=u.sort(this.addressSorter);if(f.length===0)throw new E("The connection gater denied all addresses in the dial request",k.ERR_NO_VALID_ADDRESSES);return this.log.trace("addresses for %p before filtering",e??"unknown peer",s.map(({multiaddr:l})=>l.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",f.map(({multiaddr:l})=>l.toString())),f}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let n=await this.calculateMultiaddrs(void 0,new Set(e.map(o=>o.toString())),t);return t.runOnTransientConnection===!1?n.find(o=>!Eo.matches(o.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var Hl=50,Kt={minConnections:Ci,maxConnections:ki,inboundConnectionThreshold:5,maxIncomingPendingConnections:10,autoDialConcurrency:25,autoDialPriority:0,autoDialMaxQueueLength:100,autoDialPeerRetryThreshold:Li,autoDialDiscoveredPeersDebounce:10},Mi=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;autoDial;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??Kt.maxConnections;let n=t.minConnections??Kt.minConnections;if(this.maxConnections<n)throw new E("Connection Manager maxConnections must be greater than minConnections",k.ERR_INVALID_PARAMETERS);this.connections=new Xe,this.started=!1,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),this.allow=(t.allow??[]).map(o=>ne(o)),this.deny=(t.deny??[]).map(o=>ne(o)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??Kt.maxIncomingPendingConnections,this.inboundConnectionRateLimiter=new xi({points:t.inboundConnectionThreshold??Kt.inboundConnectionThreshold,duration:1}),this.autoDial=new Di({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{minConnections:n,autoDialConcurrency:t.autoDialConcurrency??Kt.autoDialConcurrency,autoDialPriority:t.autoDialPriority??Kt.autoDialPriority,autoDialPeerRetryThreshold:t.autoDialPeerRetryThreshold??Kt.autoDialPeerRetryThreshold,autoDialDiscoveredPeersDebounce:t.autoDialDiscoveredPeersDebounce??Kt.autoDialDiscoveredPeersDebounce,maxQueueLength:t.autoDialMaxQueueLength??Kt.autoDialMaxQueueLength}),this.connectionPruner=new Pi({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new Ui(e,{addressSorter:t.addressSorter??_n,maxParallelDials:t.maxParallelDials??Ni,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??5e3,resolvers:t.resolvers??{dnsaddr:Or},connections:this.connections})}[Symbol.toStringTag]="@libp2p/connection-manager";isStarted(){return this.started}async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,outbound:0};for(let t of this.connections.values())for(let n of t)n.direction==="inbound"?e.inbound++:e.outbound++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let t of this.connections.values())for(let n of t)for(let o of n.streams){let s=`${o.direction} ${o.protocol??"unnegotiated"}`;e[s]=(e[s]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let e={};for(let n of this.connections.values())for(let o of n){let s={};for(let i of o.streams){let a=`${i.direction} ${i.protocol??"unnegotiated"}`;s[a]=(s[a]??0)+1}for(let[i,a]of Object.entries(s))e[i]=e[i]??[],e[i].push(a)}let t={};for(let[n,o]of Object.entries(e)){o=o.sort((i,a)=>i-a);let s=Math.floor(o.length*.9);t[n]=o[s]}return t}}),this.dialQueue.start(),this.autoDial.start(),this.started=!0,this.log("started")}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>t.tags.has(uu)]});await Promise.all(e.map(async t=>{await this.openConnection(t.id).catch(n=>{this.log.error(n)})}))}).catch(e=>{this.log.error(e)}),this.autoDial.afterStart()}async stop(){this.dialQueue.stop(),this.autoDial.stop();let e=[];for(let t of this.connections.values())for(let n of t)e.push((async()=>{try{await n.close()}catch(o){this.log.error(o)}})());this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}onConnect(e){this._onConnect(e).catch(t=>{this.log.error(t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}let n=t.remotePeer,o=this.connections.get(n),s=!1;o!=null?o.push(t):(s=!0,this.connections.set(n,[t])),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),s&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e;if(!this.started)return;let n=t.remotePeer,o=this.connections.get(n);o!=null&&o.length>1?(o=o.filter(s=>s.id!==t.id),this.connections.set(n,o)):o!=null&&(this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:t.remotePeer}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let t=[];for(let n of this.connections.values())t=t.concat(n);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.isStarted())throw new E("Not started",k.ERR_NODE_NOT_STARTED);t.signal?.throwIfAborted();let{peerId:n}=vi(e);if(n!=null&&t.force!==!0){this.log("dial %p",n);let a=this.getConnections(n).find(c=>!c.transient);if(a!=null)return this.log("had an existing non-transient connection to %p",n),t.onProgress?.(new he("dial-queue:already-connected")),a}let o=await this.dialQueue.dial(e,{...t,priority:t.priority??Hl}),s=this.connections.get(o.remotePeer);s==null&&(s=[],this.connections.set(o.remotePeer,s));let i=!1;for(let a of s)a.id===o.id&&(i=!0);return i||s.push(o),o}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async o=>{try{await o.close(t)}catch(s){o.abort(s)}}))}async acceptIncomingConnection(e){if(this.deny.some(o=>e.remoteAddr.toString().startsWith(o.toString())))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(o=>e.remoteAddr.toString().startsWith(o.toString())))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){let o=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(o,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,o),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){let e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map(n=>ne(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};var Bn=class{movingAverage;variance;deviation;forecast;timespan;previousTime;constructor(e){this.timespan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timespan)}push(e,t=Date.now()){if(this.previousTime!=null){let n=this.alpha(t,this.previousTime),o=e-this.movingAverage,s=n*o;this.movingAverage=n*e+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+o*s),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*o}else this.movingAverage=e;this.previousTime=t}};var Pw=1.2,Ow=2,Uw=2e3,Fi=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;constructor(e={}){this.success=new Bn(e.interval??5e3),this.failure=new Bn(e.interval??5e3),this.next=new Bn(e.interval??5e3),this.failureMultiplier=e.failureMultiplier??Ow,this.timeoutMultiplier=e.timeoutMultiplier??Pw,this.minTimeout=e.minTimeout??Uw,e.metricName!=null&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){let t=Math.max(Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier)),this.minTimeout),n=AbortSignal.timeout(t),o=Mr([e.signal,n]);return ie(1/0,o,n),o.start=Date.now(),o.timeout=t,o}cleanUp(e){let t=Date.now()-e.start;e.aborted?(this.failure.push(t),this.next.push(t*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:t})):(this.success.push(t),this.next.push(t),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:t}))}};var $l=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=ue(),this.haveNext=ue()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=ue(),e}async throw(e){return this.ended=!0,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return await this._push(void 0),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=ue(),await fr(this.readNext.promise,t?.signal,t)}};function Qd(){return new $l}var Vi=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var ql=class extends Error{code;constructor(e,t){super(e),this.code=t}},zl=class extends ql{type;constructor(e){super(e,"ABORT_ERR"),this.type="aborted",this.name="AbortError"}};function Ki(r,e){let t=Qd();r.sink(t).catch(async i=>{await t.end(i)}),r.sink=async i=>{for await(let a of i)await t.push(a);await t.end()};let n=r.source;r.source[Symbol.iterator]!=null?n=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(n=r.source[Symbol.asyncIterator]());let o=new we;return{read:async(i,a)=>{a?.signal?.throwIfAborted();let c,u=new Promise((f,l)=>{c=()=>{l(new zl("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(i==null){let{done:l,value:p}=await Promise.race([n.next(),u]);return l===!0?new we:p}for(;o.byteLength<i;){let{value:l,done:p}=await Promise.race([n.next(),u]);if(p===!0)throw new Vi("unexpected end of input");o.append(l)}let f=o.sublist(0,i);return o.consume(i),f}finally{c!=null&&a?.signal?.removeEventListener("abort",c)}},write:async(i,a)=>{a?.signal?.throwIfAborted(),i instanceof Uint8Array?await t.push(i,a):await t.push(i.subarray(),a)},unwrap:()=>{if(o.byteLength>0){let i=r.source;r.source=async function*(){e?.yieldBytes===!1?yield o:yield*o,yield*i}()}return r}}}var Mw=1e4,Fw="1.0.0",Vw="ping",Kw="ipfs",Jd=32,Hi=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??Kw}/${Vw}/${Fw}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??Mw,this.timeout=new Fi({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[kn]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(e=>{Promise.resolve().then(async()=>{let t=Date.now();try{let n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),o=await e.newStream(this.protocol,{signal:n,runOnTransientConnection:!0}),s=Ki(o);t=Date.now(),await Promise.all([s.write(et(Jd),{signal:n}),s.read(Jd,{signal:n})]),e.rtt=Date.now()-t,await s.unwrap().close({signal:n})}catch(n){if(n.code!=="ERR_UNSUPPORTED_PROTOCOL")throw n;e.rtt=(Date.now()-t)/2}}).catch(t=>{this.log.error("error during heartbeat, aborting connection",t),e.abort(t)})})},this.pingIntervalMs)}stop(){this.abortController?.abort(),this.heartbeatInterval!=null&&clearInterval(this.heartbeatInterval)}};function Hw(r){return r[Symbol.asyncIterator]!=null}function $w(...r){let e=[];for(let t of r)Hw(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=Ai({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let o of n)t.push(o)})),t.end()}catch(n){t.end(n)}}),yield*t}()}var vo=$w;var $i=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(this.routers.length===0)throw new E("No content routers available",k.ERR_NO_ROUTERS_AVAILABLE);let n=this,o=new Mt;for await(let s of vo(...n.routers.map(i=>i.findProviders(e,t))))s!=null&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id)&&(o.add(s.id),yield s))}async provide(e,t={}){if(this.routers.length===0)throw new E("No content routers available",k.ERR_NO_ROUTERS_AVAILABLE);await Promise.all(this.routers.map(async n=>{await n.provide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new E(Vt.NOT_STARTED_YET,k.ERR_NODE_NOT_STARTED);await Promise.all(this.routers.map(async o=>{await o.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new E(Vt.NOT_STARTED_YET,k.ERR_NODE_NOT_STARTED);return Promise.any(this.routers.map(async n=>n.get(e,t)))}};var qi=globalThis.CustomEvent??Event;async function*Gl(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered==null?!1:e.ordered,o=new EventTarget,s=[],i=ue(),a=ue(),c=!1,u,f=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let d of r){if(s.length===t&&(i=ue(),await i.promise),f)break;let m={done:!1};s.push(m),d().then(w=>{m.done=!0,m.ok=!0,m.value=w,o.dispatchEvent(new qi("task-complete"))},w=>{m.done=!0,m.err=w,o.dispatchEvent(new qi("task-complete"))})}c=!0,o.dispatchEvent(new qi("task-complete"))}catch(d){u=d,o.dispatchEvent(new qi("task-complete"))}});function l(){return n?s[0]?.done:!!s.find(d=>d.done)}function*p(){for(;s.length>0&&s[0].done;){let d=s[0];if(s.shift(),d.ok)yield d.value;else throw f=!0,i.resolve(),d.err;i.resolve()}}function*h(){for(;l();)for(let d=0;d<s.length;d++)if(s[d].done){let m=s[d];if(s.splice(d,1),d--,m.ok)yield m.value;else throw f=!0,i.resolve(),m.err;i.resolve()}}for(;;){if(l()||(a=ue(),await a.promise),u!=null)throw u;if(n?yield*p():yield*h(),c&&s.length===0)break}}var zi=class{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[]}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(this.routers.length===0)throw new E("No peer routers available",k.ERR_NO_ROUTERS_AVAILABLE);if(e.toString()===this.peerId.toString())throw new E("Should not try to find self",k.ERR_FIND_SELF);let n=this,o=vo(...this.routers.map(s=>async function*(){try{yield await s.findPeer(e,t)}catch(i){n.log.error(i)}}()));for await(let s of o)if(s!=null)return s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),s;throw new E(Vt.NOT_FOUND,k.ERR_NOT_FOUND)}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new E("No peer routers available",k.ERR_NO_ROUTERS_AVAILABLE);let n=this,o=Vc(1024);for await(let s of Gl(async function*(){let i=vo(...n.routers.map(a=>a.getClosestPeers(e,t)));for await(let a of i)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.findPeer(a.id,{...t,useCache:!1})}catch(c){n.log.error("could not find peer multiaddrs",c);return}return a}}()))s!=null&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id.toBytes())&&(o.add(s.id.toBytes()),yield s))}};var Gi=class extends At{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,ie(1/0,this.shutdownController.signal)}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,ie(1/0,this.shutdownController.signal)}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=Mr([this.shutdownController.signal,e?.signal]);ie(1/0,t);try{for(;;)this.needNext?.resolve(),this.needNext=ue(),yield(await In(this,"walk:peer",t,{errorEvent:"walk:error"})).detail}finally{t.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,ie(1/0,this.walkController.signal);let e=Mr([this.walkController.signal,this.shutdownController.signal]);ie(1/0,e);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let o=et(32),s=Date.now();for await(let i of this.peerRouting.getClosestPeers(o,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",i.id,Date.now()-s,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:i}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await fr(this.needNext.promise,e)),s=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",o,this.walkers,n)}catch(o){this.log.error("randomwalk errored",o),this.safeDispatchEvent("walk:error",{detail:o})}this.log("no walkers left, ended walk")}).catch(o=>{this.log.error("randomwalk errored",o)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}};var Yl=32,Wl=64,Yi=class{log;topologies;handlers;components;constructor(e){this.log=e.logger.forComponent("libp2p:registrar"),this.topologies=new Map,this.handlers=new Map,this.components=e,this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new E(`No handler registered for protocol ${e}`,k.ERR_NO_HANDLER_FOR_PROTOCOL);return t}getTopologies(e){let t=this.topologies.get(e);return t==null?[]:[...t.values()]}async handle(e,t,n){if(this.handlers.has(e))throw new E(`Handler already registered for protocol ${e}`,k.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);let o=Ei.bind({ignoreUndefined:!0})({maxInboundStreams:Yl,maxOutboundStreams:Wl},n);this.handlers.set(e,{handler:t,options:o}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]})}async unhandle(e){(Array.isArray(e)?e:[e]).forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()})}async register(e,t){if(t==null)throw new E("invalid topology",k.ERR_INVALID_PARAMETERS);let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,o=this.topologies.get(e);return o==null&&(o=new Map,this.topologies.set(e,o)),o.set(n,t),n}unregister(e){for(let[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(t))}_onDisconnect(e){let t=e.detail;this.components.peerStore.get(t).then(n=>{for(let o of n.protocols){let s=this.topologies.get(o);if(s!=null)for(let i of s.values())i.filter?.has(t)!==!1&&(i.filter?.remove(t),i.onDisconnect?.(t))}}).catch(n=>{n.code!==k.ERR_NOT_FOUND&&this.log.error("could not inform topologies of disconnecting peer %p",t,n)})}_onPeerUpdate(e){let{peer:t,previous:n}=e.detail,o=(n?.protocols??[]).filter(s=>!t.protocols.includes(s));for(let s of o){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())a.filter?.has(t.id)!==!1&&(a.filter?.remove(t.id),a.onDisconnect?.(t.id))}}_onPeerIdentify(e){let t=e.detail.protocols,n=e.detail.connection,o=e.detail.peerId;for(let s of t){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())n.transient&&a.notifyOnTransient!==!0||a.filter?.has(o)!==!0&&(a.filter?.add(o),a.onConnect?.(o,n))}}};var jl=class extends Map{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function ep(r){let{name:e,metrics:t}=r,n;return t!=null?n=new jl({name:e,metrics:t}):n=new Map,n}var Wi=class{log;components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=new Map,this.listeners=ep({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??Ht.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new E("Transport must have a valid tag",k.ERR_INVALID_KEY);if(this.transports.has(t))throw new E(`There is already a transport with the tag ${t}`,k.ERR_DUPLICATE_TRANSPORT);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){let e=[];for(let[t,n]of this.listeners)for(this.log("closing listeners for %s",t);n.length>0;){let o=n.pop();o!=null&&e.push(o.close())}await Promise.all(e),this.log("all listeners closed");for(let t of this.listeners.keys())this.listeners.set(t,[]);this.started=!1}async dial(e,t){let n=this.dialTransportForMultiaddr(e);if(n==null)throw new E(`No transport available for address ${String(e)}`,k.ERR_TRANSPORT_UNAVAILABLE);t?.onProgress?.(new he("transport-manager:selected-transport",n[Symbol.toStringTag]));try{return await n.dial(e,{...t,upgrader:this.components.upgrader})}catch(o){throw o.code==null&&(o.code=k.ERR_TRANSPORT_DIAL_FAILED),o}}getAddrs(){let e=[];for(let t of this.listeners.values())for(let n of t)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(let t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(let t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new E("Not started",k.ERR_NODE_NOT_STARTED);if(e==null||e.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let t=[];for(let[n,o]of this.transports.entries()){let s=o.listenFilter(e),i=[];for(let u of s){this.log("creating listener for %s on %a",n,u);let f=o.createListener({upgrader:this.components.upgrader}),l=this.listeners.get(n)??[];l==null&&(l=[],this.listeners.set(n,l)),l.push(f),f.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:f})}),f.addEventListener("close",()=>{let p=l.findIndex(h=>h===f);l.splice(p,1),this.components.events.safeDispatchEvent("transport:close",{detail:f})}),i.push(f.listen(u))}if(i.length===0){t.push(n);continue}if((await Promise.allSettled(i)).find(u=>u.status==="fulfilled")==null&&this.faultTolerance!==Ht.NO_FATAL)throw new E(`Transport (${n}) could not listen on any available address`,k.ERR_NO_VALID_ADDRESSES)}if(t.length===this.transports.size){let n=`no valid addresses were provided for transports [${t.join(", ")}]`;if(this.faultTolerance===Ht.FATAL_ALL)throw new E(n,k.ERR_NO_VALID_ADDRESSES);this.log(`libp2p in dial mode only: ${n}`)}}async remove(e){let t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);let n=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){let o=t.pop();o!=null&&n.push(o.close())}await Promise.all(n),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}};var Ce="/multistream/1.0.0";var ji=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Xi=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Zi=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function _o(r,e={}){let t=Ki(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=de(e.maxDataLength));let n=e?.lengthDecoder??lt,o=e?.lengthEncoder??Le;return{read:async i=>{let a=-1,c=new we;for(;;){c.append(await t.read(1,i));try{a=n(c)}catch(u){if(u instanceof RangeError)continue;throw u}if(a<0)throw new ji("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new Zi("message length length too long");if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new Xi("message length too long");return t.read(a,i)},write:async(i,a)=>{await t.write(new we(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new we(...i.flatMap(u=>[o(u.byteLength),u]));await t.write(c,a)},unwrap:()=>t.unwrap()}}var qw=L(`
|
|
8
|
-
`)
|
|
9
|
-
`),i=
|
|
10
|
-
`)
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
`),
|
|
14
|
-
`),
|
|
15
|
-
`)
|
|
16
|
-
`),t),t.log.trace('handle: responded with "%s" for "%s"',
|
|
17
|
-
`)
|
|
18
|
-
`))),
|
|
19
|
-
`));t.log.trace('handle: respond with "%s" for %s',e,o),await Fr(n,s,t),t.log.trace('handle: responded with "%s" for %s',e,o);continue}t.log('handle: respond with "na" for "%s"',o),await Fr(n,L(`na
|
|
20
|
-
`),t),t.log('handle: responded with "na" for "%s"',o)}}var Xw=500,Jl=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;transient;log;tags;_newStream;_close;_abort;_getStreams;constructor(e){let{remoteAddr:t,remotePeer:n,newStream:o,close:s,abort:i,getStreams:a}=e;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=t,this.remotePeer=n,this.direction=e.direction,this.status="open",this.timeline=e.timeline,this.multiplexer=e.multiplexer,this.encryption=e.encryption,this.transient=e.transient??!1,this.log=e.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`),this.remoteAddr.getPeerId()==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this._newStream=o,this._close=s,this._abort=i,this._getStreams=a,this.tags=[]}[Symbol.toStringTag]="Connection";[lu]=!0;get streams(){return this._getStreams()}async newStream(e,t){if(this.status==="closing")throw new E("the connection is being closed","ERR_CONNECTION_BEING_CLOSED");if(this.status==="closed")throw new E("the connection is closed","ERR_CONNECTION_CLOSED");if(Array.isArray(e)||(e=[e]),this.transient&&t?.runOnTransientConnection!==!0)throw new E("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");let n=await this._newStream(e,t);return n.direction="outbound",n}async close(e={}){if(!(this.status==="closed"||this.status==="closing")){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",e.signal==null){let t=AbortSignal.timeout(Xw);ie(1/0,t),e={...e,signal:t}}try{this.log.trace("closing all streams"),await Promise.all(this.streams.map(async t=>t.close(e))),this.log.trace("closing underlying transport"),await this._close(e),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(t){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,t),this.abort(t)}}}abort(e){this.log.error("aborting connection to %a due to error",this.remoteAddr,e),this.status="closing",this.streams.forEach(t=>{t.abort(e)}),this.log.error("all streams aborted",this.streams.length),this._abort(e),this.timeline.close=Date.now(),this.status="closed"}};function np(r){return new Jl(r)}var Zw=3e4;function Qw(r,e){try{let{options:t}=e.getHandler(r);return t.maxInboundStreams}catch(t){if(t.code!==k.ERR_NO_HANDLER_FOR_PROTOCOL)throw t}return Yl}function Jw(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.code!==k.ERR_NO_HANDLER_FOR_PROTOCOL)throw n}return t.maxOutboundStreams??Wl}function op(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var oa=class{components;connectionEncryption;muxers;inboundUpgradeTimeout;events;constructor(e,t){this.components=e,this.connectionEncryption=new Map,t.connectionEncryption.forEach(n=>{this.connectionEncryption.set(n.protocol,n)}),this.muxers=new Map,t.muxers.forEach(n=>{this.muxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??2e3,this.events=e.events}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,t,n){let o=this.components.connectionGater[n];if(o!==void 0&&await o(e,t))throw new E(`The multiaddr connection is blocked by gater.${n}`,k.ERR_CONNECTION_INTERCEPTED)}async upgradeInbound(e,t){if(!await this.components.connectionManager.acceptIncomingConnection(e))throw new E("connection denied",k.ERR_CONNECTION_DENIED);let o,s,i,a,c,u=AbortSignal.timeout(this.inboundUpgradeTimeout),f=()=>{e.abort(new E("inbound upgrade timeout",No))};u.addEventListener("abort",f,{once:!0}),ie(1/0,u);try{if(await this.components.connectionGater.denyInboundConnection?.(e)===!0)throw new E("The multiaddr connection is blocked by gater.acceptConnection",k.ERR_CONNECTION_INTERCEPTED);this.components.metrics?.trackMultiaddrConnection(e),e.log("starting the inbound connection upgrade");let l=e;if(t?.skipProtection!==!0){let p=this.components.connectionProtector;p!=null&&(e.log("protecting the inbound connection"),l=await p.protect(e))}try{if(o=l,t?.skipEncryption!==!0){t?.onProgress?.(new he("upgrader:encrypt-inbound-connection")),{conn:o,remotePeer:s,protocol:c}=await this._encryptInbound(l);let p={...l,...o};await this.shouldBlockConnection(s,p,"denyInboundEncryptedConnection")}else{let p=e.remoteAddr.getPeerId();if(p==null)throw new E("inbound connection that skipped encryption must have a peer id",k.ERR_INVALID_MULTIADDR);let h=ye(p);c="native",s=h}if(i=o,t?.muxerFactory!=null)a=t.muxerFactory;else if(this.muxers.size>0){t?.onProgress?.(new he("upgrader:multiplex-inbound-connection"));let p=await this._multiplexInbound({...l,...o},this.muxers);a=p.muxerFactory,i=p.stream}}catch(p){throw e.log.error("failed to upgrade inbound connection",p),p}return await this.shouldBlockConnection(s,e,"denyInboundUpgradedConnection"),e.log("successfully upgraded inbound connection"),this._createConnection({cryptoProtocol:c,direction:"inbound",maConn:e,upgradedConn:i,muxerFactory:a,remotePeer:s,transient:t?.transient})}finally{u.removeEventListener("abort",f),this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){let n=e.remoteAddr.getPeerId(),o;n!=null&&(o=ye(n),await this.shouldBlockConnection(o,e,"denyOutboundConnection"));let s,i,a,c,u;this.components.metrics?.trackMultiaddrConnection(e),e.log("starting the outbound connection upgrade");let f=e;if(t?.skipProtection!==!0){let l=this.components.connectionProtector;l!=null&&(f=await l.protect(e))}try{if(s=f,t?.skipEncryption!==!0){({conn:s,remotePeer:i,protocol:c}=await this._encryptOutbound(f,o));let l={...f,...s};await this.shouldBlockConnection(i,l,"denyOutboundEncryptedConnection")}else{if(o==null)throw new E("Encryption was skipped but no peer id was passed",k.ERR_INVALID_PEER);c="native",i=o}if(a=s,t?.muxerFactory!=null)u=t.muxerFactory;else if(this.muxers.size>0){let l=await this._multiplexOutbound({...f,...s},this.muxers);u=l.muxerFactory,a=l.stream}}catch(l){throw e.log.error("failed to upgrade outbound connection",l),await e.close(l),l}return await this.shouldBlockConnection(i,e,"denyOutboundUpgradedConnection"),e.log("successfully upgraded outbound connection"),this._createConnection({cryptoProtocol:c,direction:"outbound",maConn:e,upgradedConn:a,muxerFactory:u,remotePeer:i,transient:t?.transient})}_createConnection(e){let{cryptoProtocol:t,direction:n,maConn:o,upgradedConn:s,remotePeer:i,muxerFactory:a,transient:c}=e,u,f,l;a!=null&&(u=a.createStreamMuxer({direction:n,onIncomingStream:d=>{l!=null&&Promise.resolve().then(async()=>{let m=this.components.registrar.getProtocols(),{stream:w,protocol:g}=await Ro(d,m,{log:d.log,yieldBytes:!1});if(l==null)return;l.log("incoming stream opened on %s",g);let y=Qw(g,this.components.registrar);if(op(g,"inbound",l)===y){let x=new E(`Too many inbound protocol streams for protocol "${g}" - limit ${y}`,k.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS);throw d.abort(x),x}d.source=w.source,d.sink=w.sink,d.protocol=g,w.closeWrite!=null&&(d.closeWrite=w.closeWrite),w.closeRead!=null&&(d.closeRead=w.closeRead),w.close!=null&&(d.close=w.close),await this.components.peerStore.merge(i,{protocols:[g]}),this.components.metrics?.trackProtocolStream(d,l),this._onStream({connection:l,stream:d,protocol:g})}).catch(async m=>{l.log.error("error handling incoming stream id %s",d.id,m.message,m.code,m.stack),d.timeline.close==null&&await d.close()})}}),f=async(d,m={})=>{if(u==null)throw new E("Stream is not multiplexed",k.ERR_MUXER_UNAVAILABLE);l.log("starting new stream for protocols %s",d);let w=await u.newStream();l.log.trace("started new stream %s for protocols %s",w.id,d);try{if(m.signal==null){w.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",d);let A=AbortSignal.timeout(Zw);ie(1/0,A),m={...m,signal:A}}w.log.trace("selecting protocol from protocols %s",d);let{stream:g,protocol:y}=await Ao(w,d,{...m,log:w.log,yieldBytes:!0});w.log("selected protocol %s",y);let b=Jw(y,this.components.registrar,m),x=op(y,"outbound",l);if(x>=b){let A=new E(`Too many outbound protocol streams for protocol "${y}" - ${x}/${b}`,k.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);throw w.abort(A),A}return await this.components.peerStore.merge(i,{protocols:[y]}),w.source=g.source,w.sink=g.sink,w.protocol=y,g.closeWrite!=null&&(w.closeWrite=g.closeWrite),g.closeRead!=null&&(w.closeRead=g.closeRead),g.close!=null&&(w.close=g.close),this.components.metrics?.trackProtocolStream(w,l),w}catch(g){throw l.log.error("could not create new stream for protocols %s",d,g),w.timeline.close==null&&w.abort(g),g.code!=null?g:new E(String(g),k.ERR_UNSUPPORTED_PROTOCOL)}},Promise.all([u.sink(s.source),s.sink(u.source)]).catch(d=>{l.log.error("error piping data through muxer",d)}));let p=o.timeline;o.timeline=new Proxy(p,{set:(...d)=>(l!=null&&d[1]==="close"&&d[2]!=null&&p.close==null&&(async()=>{try{l.status==="open"&&await l.close()}catch(m){l.log.error("error closing connection after timeline close",m)}finally{this.events.safeDispatchEvent("connection:close",{detail:l})}})().catch(m=>{l.log.error("error thrown while dispatching connection:close event",m)}),Reflect.set(...d))}),o.timeline.upgraded=Date.now();let h=()=>{throw new E("connection is not multiplexed",k.ERR_CONNECTION_NOT_MULTIPLEXED)};return l=np({remoteAddr:o.remoteAddr,remotePeer:i,status:"open",direction:n,timeline:o.timeline,multiplexer:u?.protocol,encryption:t,transient:c,logger:this.components.logger,newStream:f??h,getStreams:()=>u!=null?u.streams:[],close:async d=>{u!=null&&(l.log.trace("close muxer"),await u.close(d)),l.log.trace("close maconn"),await o.close(d),l.log.trace("closed maconn")},abort:d=>{o.abort(d),u?.abort(d)}}),this.events.safeDispatchEvent("connection:open",{detail:l}),l}_onStream(e){let{connection:t,stream:n,protocol:o}=e,{handler:s,options:i}=this.components.registrar.getHandler(o);if(t.transient&&i.runOnTransientConnection!==!0)throw new E("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");s({connection:t,stream:n})}async _encryptInbound(e){let t=Array.from(this.connectionEncryption.keys());e.log("handling inbound crypto protocol selection",t);try{let{stream:n,protocol:o}=await Ro(e,t,{log:e.log}),s=this.connectionEncryption.get(o);if(s==null)throw new Error(`no crypto module found for ${o}`);return e.log("encrypting inbound connection using",o),{...await s.secureInbound(this.components.peerId,n),protocol:o}}catch(n){throw e.log.error("encrypting inbound connection failed",n),new E(n.message,k.ERR_ENCRYPTION_FAILED)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncryption.keys());e.log("selecting outbound crypto protocol",n);try{e.log.trace("selecting encrypter from %s",n);let{stream:o,protocol:s}=await Ao(e,n,{log:e.log,yieldBytes:!0}),i=this.connectionEncryption.get(s);if(i==null)throw new Error(`no crypto module found for ${s}`);return e.log("encrypting outbound connection to %p using %s",t,i),{...await i.secureOutbound(this.components.peerId,o,t),protocol:s}}catch(o){throw e.log.error("encrypting outbound connection to %p failed",t,o),new E(o.message,k.ERR_ENCRYPTION_FAILED)}}async _multiplexOutbound(e,t){let n=Array.from(t.keys());e.log("outbound selecting muxer %s",n);try{e.log.trace("selecting stream muxer from %s",n);let{stream:o,protocol:s}=await Ao(e,n,{log:e.log,yieldBytes:!0});e.log("selected %s as muxer protocol",s);let i=t.get(s);return{stream:o,muxerFactory:i}}catch(o){throw e.log.error("error multiplexing outbound connection",o),new E(String(o),k.ERR_MUXER_UNAVAILABLE)}}async _multiplexInbound(e,t){let n=Array.from(t.keys());e.log("inbound handling muxers %s",n);try{let{stream:o,protocol:s}=await Ro(e,n,{log:e.log}),i=t.get(s);return{stream:o,muxerFactory:i}}catch(o){throw e.log.error("error multiplexing inbound connection",o),new E(String(o),k.ERR_MUXER_UNAVAILABLE)}}};var sp="1.9.3",ip="libp2p";var eu=class extends At{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new At,n=t.dispatchEvent.bind(t);t.dispatchEvent=a=>{let c=n(a),u=this.dispatchEvent(new la(a.type,{detail:a.detail}));return c||u},ie(1/0,t),this.peerId=e.peerId,this.logger=e.logger??$s(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=this.components=wd({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:e.nodeInfo??{name:ip,version:sp},logger:this.logger,events:t,datastore:e.datastore??new ai,connectionGater:vd(e.connectionGater),dns:e.dns});this.peerStore=this.configureComponent("peerStore",new si(o,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),o.events.addEventListener("peer:update",a=>{if(a.detail.previous==null){let c={id:a.detail.peer.id,multiaddrs:a.detail.peer.addresses.map(u=>u.multiaddr)};o.events.safeDispatchEvent("peer:discovery",{detail:c})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(o)),this.components.upgrader=new oa(this.components,{connectionEncryption:(e.connectionEncryption??[]).map((a,c)=>this.configureComponent(`connection-encryption-${c}`,a(this.components))),muxers:(e.streamMuxers??[]).map((a,c)=>this.configureComponent(`stream-muxers-${c}`,a(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout}),this.configureComponent("transportManager",new Wi(this.components,e.transportManager)),this.configureComponent("connectionManager",new Mi(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new Hi(this.components,e.connectionMonitor)),this.configureComponent("registrar",new Yi(this.components)),this.configureComponent("addressManager",new ci(this.components,e.addresses));let s=(e.peerRouters??[]).map((a,c)=>this.configureComponent(`peer-router-${c}`,a(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new zi(this.components,{routers:s}));let i=(e.contentRouters??[]).map((a,c)=>this.configureComponent(`content-router-${c}`,a(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new $i(this.components,{routers:i})),this.configureComponent("randomWalk",new Gi(this.components)),(e.peerDiscovery??[]).forEach((a,c)=>{this.configureComponent(`peer-discovery-${c}`,a(this.components)).addEventListener("peer",f=>{this.#e(f)})}),e.transports?.forEach((a,c)=>{this.components.transportManager.add(this.configureComponent(`transport-${c}`,a(this.components)))}),e.services!=null)for(let a of Object.keys(e.services)){let c=e.services[a],u=c(this.components);if(u==null){this.log.error("service factory %s returned null or undefined instance",a);continue}this.services[a]=u,this.configureComponent(a,u),u[ia]!=null&&(this.log("registering service %s for content routing",a),i.push(u[ia])),u[ca]!=null&&(this.log("registering service %s for peer routing",a),s.push(u[ca])),u[aa]!=null&&(this.log("registering service %s for peer discovery",a),u[aa].addEventListener?.("peer",f=>{this.#e(f)}))}bd(o)}configureComponent(e,t){return t==null&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started")}catch(e){throw this.log.error("An error occurred starting libp2p",e),this.status="started",await this.stop(),e}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new Mt;for(let t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,n={}){if(t==null)throw new E("no protocols were provided to open a stream",k.ERR_INVALID_PROTOCOLS_FOR_STREAM);if(t=Array.isArray(t)?t:[t],t.length===0)throw new E("no protocols were provided to open a stream",k.ERR_INVALID_PROTOCOLS_FOR_STREAM);return(await this.dial(e,n)).newStream(t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){ar(e)&&(e=ye(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;try{let s=await this.peerStore.get(e);if(s.id.publicKey!=null)return s.id.publicKey}catch(s){if(s.code!==k.ERR_NOT_FOUND)throw s}let n=Re([L("/pk/"),e.multihash.digest]),o=await this.contentRouting.get(n,t);return no(o),await this.peerStore.patch(e,{publicKey:o}),o}async handle(e,t,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async o=>{await this.components.registrar.handle(o,t,n)}))}async unhandle(e){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async t=>{await this.components.registrar.unhandle(t)}))}async register(e,t){return this.components.registrar.register(e,t)}unregister(e){this.components.registrar.unregister(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#e(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){this.log.error(new Error(k.ERR_DISCOVERED_SELF));return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error(n)})}};async function ap(r={}){let e=r.peerId??=await Ph();if(e.privateKey==null)throw new E("peer id was missing private key","ERR_MISSING_PRIVATE_KEY");return r.privateKey??=await oo(e.privateKey),new eu(await Gd(r))}async function tb(r={}){let e=await ap(r);return r.start!==!1&&await e.start(),e}return Ep(rb);})();
|
|
6
|
+
`)}`:`${t} :`}};zf=Yt;C.Constructed=zf;Yt.NAME="CONSTRUCTED";var ws=class extends Le{fromBER(e,t,n){return t}toBER(e){return at}};ws.override="EndOfContentValueBlock";var Gf,bs=class extends Ae{constructor(e={}){super(e,ws),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};Gf=bs;C.EndOfContent=Gf;bs.NAME=qn;var Wf,Jr=class extends Ae{constructor(e={}){super(e,Le),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,t,n){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=n,t+n>e.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):t+n}toBER(e,t){let n=new ArrayBuffer(2);if(!e){let o=new Uint8Array(n);o[0]=5,o[1]=0}return t&&t.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};Wf=Jr;C.Null=Wf;Jr.NAME="NULL";var xs=class extends Rt(Le){constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=q.BufferSourceConverter.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}get value(){for(let e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}fromBER(e,t,n){let o=q.BufferSourceConverter.toUint8Array(e);return Pt(this,o,t,n)?(this.valueHexView=o.subarray(t,t+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,Gc.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};xs.NAME="BooleanValueBlock";var jf,vs=class extends Ae{constructor(e={}){super(e,xs),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};jf=vs;C.Boolean=jf;vs.NAME="BOOLEAN";var Es=class extends Rt(dt){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,n){let o=0;if(this.isConstructed){if(this.isHexOnly=!1,o=dt.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let s=0;s<this.value.length;s++){let i=this.value[s].constructor.NAME;if(i===qn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(i!==Hf)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,o=super.fromBER(e,t,n),this.blockLength=n;return o}toBER(e,t){return this.isConstructed?dt.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};Es.NAME="OctetStringValueBlock";var Zf,As=class r extends Ae{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},Es),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,t,n){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,n===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),t;if(!this.valueBlock.isConstructed){let s=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+n);try{if(s.byteLength){let i=Ys(s,0,s.byteLength);i.offset!==-1&&i.offset===n&&(this.valueBlock.value=[i.result])}}catch{}}return super.fromBER(e,t,n)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?Yt.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${q.Convert.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let e=[];for(let t of this.valueBlock.value)t instanceof r&&e.push(t.valueBlock.valueHexView);return q.BufferSourceConverter.concat(e)}};Zf=As;C.OctetString=Zf;As.NAME=Hf;var Ss=class extends Rt(dt){constructor({unusedBits:e=0,isConstructed:t=!1,...n}={}){super(n),this.unusedBits=e,this.isConstructed=t,this.blockLength=this.valueHexView.byteLength}fromBER(e,t,n){if(!n)return t;let o=-1;if(this.isConstructed){if(o=dt.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let a of this.value){let c=a.constructor.NAME;if(c===qn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==$f)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let u=a.valueBlock;if(this.unusedBits>0&&u.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=u.unusedBits}return o}let s=q.BufferSourceConverter.toUint8Array(e);if(!Pt(this,s,t,n))return-1;let i=s.subarray(t,t+n);if(this.unusedBits=i[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let a=i.subarray(1);try{if(a.byteLength){let c=Ys(a,0,a.byteLength);c.offset!==-1&&c.offset===n-1&&(this.value=[c.result])}}catch{}}return this.valueHexView=i.subarray(1),this.blockLength=i.length,t+n}toBER(e,t){if(this.isConstructed)return dt.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return at;let n=new Uint8Array(this.valueHexView.length+1);return n[0]=this.unusedBits,n.set(this.valueHexView,1),n.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}};Ss.NAME="BitStringValueBlock";var Xf,Qr=class extends Ae{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},Ss),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,n){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return Yt.prototype.onAsciiEncoding.call(this);{let e=[],t=this.valueBlock.valueHexView;for(let o of t)e.push(o.toString(2).padStart(8,"0"));let n=e.join("");return`${this.constructor.NAME} : ${n.substring(0,n.length-this.valueBlock.unusedBits)}`}}};Xf=Qr;C.BitString=Xf;Qr.NAME=$f;var Yf;function k0(r,e){let t=new Uint8Array([0]),n=new Uint8Array(r),o=new Uint8Array(e),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,u=0,f=c<i?i:c,l=0;for(let d=f;d>=0;d--,l++){switch(!0){case l<a.length:u=s[i-l]+a[c-l]+t[0];break;default:u=s[i-l]+t[0]}switch(t[0]=u/10,!0){case l>=s.length:s=fs(new Uint8Array([u%10]),s);break;default:s[i-l]=u%10}}return t[0]>0&&(s=fs(t,s)),s}function Vf(r){if(r>=$n.length)for(let e=$n.length;e<=r;e++){let t=new Uint8Array([0]),n=$n[e-1].slice(0);for(let o=n.length-1;o>=0;o--){let s=new Uint8Array([(n[o]<<1)+t[0]]);t[0]=s[0]/10,n[o]=s[0]%10}t[0]>0&&(n=fs(t,n)),$n.push(n)}return $n[r]}function I0(r,e){let t=0,n=new Uint8Array(r),o=new Uint8Array(e),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,u,f=0;for(let l=c;l>=0;l--,f++)switch(u=s[i-f]-a[c-f]-t,!0){case u<0:t=1,s[i-f]=u+10;break;default:t=0,s[i-f]=u}if(t>0)for(let l=i-c+1;l>=0;l--,f++)if(u=s[i-f]-t,u<0)t=1,s[i-f]=u+10;else{t=0,s[i-f]=u;break}return s.slice()}var zn=class extends Rt(Le){constructor({value:e,...t}={}){super(t),this._valueDec=0,t.valueHex&&this.setValueHex(),e!==void 0&&(this.valueDec=e)}setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=Gc.call(this)))}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(Uf(e))}get valueDec(){return this._valueDec}fromDER(e,t,n,o=0){let s=this.fromBER(e,t,n);if(s===-1)return s;let i=this.valueHexView;return i[0]===0&&i[1]&128?this.valueHexView=i.subarray(1):o!==0&&i.length<o&&(o-i.length>1&&(o=i.length+1),this.valueHexView=i.subarray(o-i.length)),s}toDER(e=!1){let t=this.valueHexView;switch(!0){case(t[0]&128)!==0:{let n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(t,1),this.valueHexView=n}break;case(t[0]===0&&(t[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(e)}fromBER(e,t,n){let o=super.fromBER(e,t,n);return o===-1||this.setValueHex(),o}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let e=this.valueHexView.length*8-1,t=new Uint8Array(this.valueHexView.length*8/3),n=0,o,s=this.valueHexView,i="",a=!1;for(let c=s.byteLength-1;c>=0;c--){o=s[c];for(let u=0;u<8;u++){if((o&1)===1)switch(n){case e:t=I0(Vf(n),t),i="-";break;default:t=k0(t,Vf(n))}n++,o>>=1}}for(let c=0;c<t.length;c++)t[c]&&(a=!0),a&&(i+=Ff.charAt(t[c]));return a===!1&&(i+=Ff.charAt(0)),i}};Yf=zn;zn.NAME="IntegerValueBlock";Object.defineProperty(Yf.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var Jf,Se=class r extends Ae{constructor(e={}){super(e,zn),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return hs(),BigInt(this.valueBlock.toString())}static fromBigInt(e){hs();let t=BigInt(e),n=new Kn,o=t.toString(16).replace(/^-/,""),s=new Uint8Array(q.Convert.FromHex(o));if(t<0){let a=new Uint8Array(s.length+(s[0]&128?1:0));a[0]|=128;let u=BigInt(`0x${q.Convert.ToHex(a)}`)+t,f=q.BufferSourceConverter.toUint8Array(q.Convert.FromHex(u.toString(16)));f[0]|=128,n.write(f)}else s[0]&128&&n.write(new Uint8Array([0])),n.write(s);return new r({valueHex:n.final()})}convertToDER(){let e=new r({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new r({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};Jf=Se;C.Integer=Jf;Se.NAME="INTEGER";var Qf,_s=class extends Se{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};Qf=_s;C.Enumerated=Qf;_s.NAME="ENUMERATED";var Gn=class extends Rt(Le){constructor({valueDec:e=-1,isFirstSid:t=!1,...n}={}){super(n),this.valueDec=e,this.isFirstSid=t}fromBER(e,t,n){if(!n)return t;let o=q.BufferSourceConverter.toUint8Array(e);if(!Pt(this,o,t,n))return-1;let s=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,!!(s[a]&128));a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,s[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=gr(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){hs();let t=BigInt(e).toString(2);for(;t.length%7;)t="0"+t;let n=new Uint8Array(t.length/7);for(let o=0;o<n.length;o++)n[o]=parseInt(t.slice(o*7,o*7+7),2)+(o+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let t=Xt(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",at;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),s=t.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n}toString(){let e="";if(this.isHexOnly)e=q.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){let t=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",t-=40):(e="2.",t-=80),e+=t.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};Gn.NAME="sidBlock";var Bs=class extends Le{constructor({value:e=tn,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new Gn;if(o=s.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.value.length===0&&(s.isFirstSid=!0),this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(e){let t=[];for(let n=0;n<this.value.length;n++){let o=this.value[n].toBER(e);if(o.byteLength===0)return this.error=this.value[n].error,at;t.push(o)}return Wc(t)}fromString(e){this.value=[];let t=0,n=0,o="",s=!1;do if(n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1,s){let i=this.value[0],a=0;switch(i.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:this.value=[];return}let c=parseInt(o,10);if(isNaN(c))return;i.valueDec=c+a,s=!1}else{let i=new Gn;if(o>Number.MAX_SAFE_INTEGER){hs();let a=BigInt(o);i.valueBigInt=a}else if(i.valueDec=parseInt(o,10),isNaN(i.valueDec))return;this.value.length||(i.isFirstSid=!0,s=!0),this.value.push(i)}while(n!==-1)}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),t?(o=`{${o}}`,this.value[n].isFirstSid?e=`2.{${o} - 80}`:e+=o):e+=o}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};Bs.NAME="ObjectIdentifierValueBlock";var eh,en=class extends Ae{constructor(e={}){super(e,Bs),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};eh=en;C.ObjectIdentifier=eh;en.NAME="OBJECT IDENTIFIER";var Wn=class extends Rt(Tt){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,n){if(n===0)return t;let o=q.BufferSourceConverter.toUint8Array(e);if(!Pt(this,o,t,n))return-1;let s=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,!!(s[a]&128));a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,s[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=gr(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let t=Xt(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",at;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),s=t.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n.buffer}toString(){let e="";return this.isHexOnly?e=q.Convert.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};Wn.NAME="relativeSidBlock";var ks=class extends Le{constructor({value:e=tn,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new Wn;if(o=s.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(e,t){let n=[];for(let o=0;o<this.value.length;o++){let s=this.value[o].toBER(e);if(s.byteLength===0)return this.error=this.value[o].error,at;n.push(s)}return Wc(n)}fromString(e){this.value=[];let t=0,n=0,o="";do{n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1;let s=new Wn;if(s.valueDec=parseInt(o,10),isNaN(s.valueDec))return!0;this.value.push(s)}while(n!==-1);return!0}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),t&&(o=`{${o}}`),e+=o}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};ks.NAME="RelativeObjectIdentifierValueBlock";var th,Is=class extends Ae{constructor(e={}){super(e,ks),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};th=Is;C.RelativeObjectIdentifier=th;Is.NAME="RelativeObjectIdentifier";var rh,Lt=class extends Yt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};rh=Lt;C.Sequence=rh;Lt.NAME="SEQUENCE";var nh,Cs=class extends Yt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};nh=Cs;C.Set=nh;Cs.NAME="SET";var Ts=class extends Rt(Le){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=tn}toJSON(){return{...super.toJSON(),value:this.value}}};Ts.NAME="StringValueBlock";var Ls=class extends Ts{};Ls.NAME="SimpleStringValueBlock";var Oe=class extends ms{constructor({...e}={}){super(e,Ls)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,q.BufferSourceConverter.toUint8Array(e))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=e.charCodeAt(o);this.valueBlock.value=e}};Oe.NAME="SIMPLE STRING";var Ns=class extends Oe{fromBuffer(e){this.valueBlock.valueHexView=q.BufferSourceConverter.toUint8Array(e);try{this.valueBlock.value=q.Convert.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=q.Convert.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(q.Convert.FromUtf8String(e)),this.valueBlock.value=e}};Ns.NAME="Utf8StringValueBlock";var oh,Nt=class extends Ns{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};oh=Nt;C.Utf8String=oh;Nt.NAME="UTF8String";var Ps=class extends Oe{fromBuffer(e){this.valueBlock.value=q.Convert.ToUtf16String(e),this.valueBlock.valueHexView=q.BufferSourceConverter.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(q.Convert.FromUtf16String(e))}};Ps.NAME="BmpStringValueBlock";var sh,Rs=class extends Ps{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};sh=Rs;C.BmpString=sh;Rs.NAME="BMPString";var Ds=class extends Oe{fromBuffer(e){let t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),n=new Uint8Array(t);for(let o=0;o<n.length;o+=4)n[o]=n[o+3],n[o+1]=n[o+2],n[o+2]=0,n[o+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(t))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t*4);for(let o=0;o<t;o++){let s=Xt(e.charCodeAt(o),8),i=new Uint8Array(s);if(i.length>4)continue;let a=4-i.length;for(let c=i.length-1;c>=0;c--)n[o*4+c+a]=i[c]}this.valueBlock.value=e}};Ds.NAME="UniversalStringValueBlock";var ih,Ms=class extends Ds{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};ih=Ms;C.UniversalString=ih;Ms.NAME="UniversalString";var ah,Us=class extends Oe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};ah=Us;C.NumericString=ah;Us.NAME="NumericString";var ch,Os=class extends Oe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};ch=Os;C.PrintableString=ch;Os.NAME="PrintableString";var lh,Fs=class extends Oe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};lh=Fs;C.TeletexString=lh;Fs.NAME="TeletexString";var uh,Vs=class extends Oe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};uh=Vs;C.VideotexString=uh;Vs.NAME="VideotexString";var fh,Hs=class extends Oe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};fh=Hs;C.IA5String=fh;Hs.NAME="IA5String";var hh,$s=class extends Oe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};hh=$s;C.GraphicString=hh;$s.NAME="GraphicString";var dh,jn=class extends Oe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};dh=jn;C.VisibleString=dh;jn.NAME="VisibleString";var ph,Ks=class extends Oe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};ph=Ks;C.GeneralString=ph;Ks.NAME="GeneralString";var mh,qs=class extends Oe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};mh=qs;C.CharacterString=mh;qs.NAME="CharacterString";var gh,Zn=class extends jn{constructor({value:e,valueDate:t,...n}={}){if(super(n),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,e){this.fromString(e),this.valueBlock.valueHexView=new Uint8Array(e.length);for(let o=0;o<e.length;o++)this.valueBlock.valueHexView[o]=e.charCodeAt(o)}t&&(this.fromDate(t),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,q.BufferSourceConverter.toUint8Array(e)))}toBuffer(){let e=this.toString(),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);return t}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){let n=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(e);if(n===null){this.error="Wrong input string for conversion";return}let o=parseInt(n[1],10);o>=50?this.year=1900+o:this.year=2e3+o,this.month=parseInt(n[2],10),this.day=parseInt(n[3],10),this.hour=parseInt(n[4],10),this.minute=parseInt(n[5],10),this.second=parseInt(n[6],10)}toString(e="iso"){if(e==="iso"){let t=new Array(7);return t[0]=qe(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=qe(this.month,2),t[2]=qe(this.day,2),t[3]=qe(this.hour,2),t[4]=qe(this.minute,2),t[5]=qe(this.second,2),t[6]="Z",t.join("")}return super.toString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}};gh=Zn;C.UTCTime=gh;Zn.NAME="UTCTime";var yh,zs=class extends Zn{constructor(e={}){var t;super(e),(t=this.millisecond)!==null&&t!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond))}fromString(e){let t=!1,n="",o="",s=0,i,a=0,c=0;if(e[e.length-1]==="Z")n=e.substring(0,e.length-1),t=!0;else{let l=new Number(e[e.length-1]);if(isNaN(l.valueOf()))throw new Error("Wrong input string for conversion");n=e}if(t){if(n.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(n.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let l=1,d=n.indexOf("+"),h="";if(d===-1&&(d=n.indexOf("-"),l=-1),d!==-1){if(h=n.substring(d+1),n=n.substring(0,d),h.length!==2&&h.length!==4)throw new Error("Wrong input string for conversion");let p=parseInt(h.substring(0,2),10);if(isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");if(a=l*p,h.length===4){if(p=parseInt(h.substring(2,4),10),isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");c=l*p}}}let u=n.indexOf(".");if(u===-1&&(u=n.indexOf(",")),u!==-1){let l=new Number(`0${n.substring(u)}`);if(isNaN(l.valueOf()))throw new Error("Wrong input string for conversion");s=l.valueOf(),o=n.substring(0,u)}else o=n;switch(!0){case o.length===8:if(i=/(\d{4})(\d{2})(\d{2})/ig,u!==-1)throw new Error("Wrong input string for conversion");break;case o.length===10:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=60*s;this.minute=Math.floor(l),l=60*(l-this.minute),this.second=Math.floor(l),l=1e3*(l-this.second),this.millisecond=Math.floor(l)}break;case o.length===12:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=60*s;this.second=Math.floor(l),l=1e3*(l-this.second),this.millisecond=Math.floor(l)}break;case o.length===14:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=1e3*s;this.millisecond=Math.floor(l)}break;default:throw new Error("Wrong input string for conversion")}let f=i.exec(o);if(f===null)throw new Error("Wrong input string for conversion");for(let l=1;l<f.length;l++)switch(l){case 1:this.year=parseInt(f[l],10);break;case 2:this.month=parseInt(f[l],10);break;case 3:this.day=parseInt(f[l],10);break;case 4:this.hour=parseInt(f[l],10)+a;break;case 5:this.minute=parseInt(f[l],10)+c;break;case 6:this.second=parseInt(f[l],10);break;default:throw new Error("Wrong input string for conversion")}if(t===!1){let l=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=l.getUTCFullYear(),this.month=l.getUTCMonth(),this.day=l.getUTCDay(),this.hour=l.getUTCHours(),this.minute=l.getUTCMinutes(),this.second=l.getUTCSeconds(),this.millisecond=l.getUTCMilliseconds()}}toString(e="iso"){if(e==="iso"){let t=[];return t.push(qe(this.year,4)),t.push(qe(this.month,2)),t.push(qe(this.day,2)),t.push(qe(this.hour,2)),t.push(qe(this.minute,2)),t.push(qe(this.second,2)),this.millisecond!==0&&(t.push("."),t.push(qe(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};yh=zs;C.GeneralizedTime=yh;zs.NAME="GeneralizedTime";var wh,Gs=class extends Nt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};wh=Gs;C.DATE=wh;Gs.NAME="DATE";var bh,Ws=class extends Nt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};bh=Ws;C.TimeOfDay=bh;Ws.NAME="TimeOfDay";var xh,js=class extends Nt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};xh=js;C.DateTime=xh;js.NAME="DateTime";var vh,Zs=class extends Nt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};vh=Zs;C.Duration=vh;Zs.NAME="Duration";var Eh,Xs=class extends Nt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};Eh=Xs;C.TIME=Eh;Xs.NAME="TIME";function H(r,e="utf8"){let t=is[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}function rn(r){if(isNaN(r)||r<=0)throw new D("random bytes length must be a Number bigger than 0");return zr(r)}var Xn=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},Yn=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},Js=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var Ah={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new Js("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 Jt=Ah;async function Sh(r){let e=await Jt.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),t=await T0(e);return{privateKey:t[0],publicKey:t[1]}}async function _h(r,e){let t=await Jt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Jt.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},t,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(n,0,n.byteLength)}async function Bh(r,e,t){let n=await Jt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Jt.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t instanceof Uint8Array?t:t.subarray())}async function T0(r){if(r.privateKey==null||r.publicKey==null)throw new D("Private and public key are required");return Promise.all([Jt.get().subtle.exportKey("jwk",r.privateKey),Jt.get().subtle.exportKey("jwk",r.publicKey)])}function Xc(r){if(r.kty!=="RSA")throw new D("invalid key type");if(r.n==null)throw new D("invalid key modulus");return P(r.n,"base64url").length*8}var nn=class{type="RSA";_key;_raw;_multihash;constructor(e,t){this._key=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=Jn.jwkToPkix(this._key)),this._raw}toMultihash(){return this._multihash}toCID(){return pe.createV1(114,this._multihash)}toString(){return W.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ie(this.raw,e.raw)}verify(e,t){return Bh(this._key,t,e)}},Qn=class{type="RSA";_key;_raw;publicKey;constructor(e,t){this._key=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=Jn.jwkToPkcs1(this._key)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ie(this.raw,e.raw)}sign(e){return _h(this._key,e)}};var Qs=8192,Yc=18;function kh(r){let{result:e}=Zc(r),t=e.valueBlock.value;return{n:H(pt(t[1].toBigInt()),"base64url"),e:H(pt(t[2].toBigInt()),"base64url"),d:H(pt(t[3].toBigInt()),"base64url"),p:H(pt(t[4].toBigInt()),"base64url"),q:H(pt(t[5].toBigInt()),"base64url"),dp:H(pt(t[6].toBigInt()),"base64url"),dq:H(pt(t[7].toBigInt()),"base64url"),qi:H(pt(t[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}function L0(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 D("JWK was missing components");let t=new Lt({value:[new Se({value:0}),Se.fromBigInt(mt(P(r.n,"base64url"))),Se.fromBigInt(mt(P(r.e,"base64url"))),Se.fromBigInt(mt(P(r.d,"base64url"))),Se.fromBigInt(mt(P(r.p,"base64url"))),Se.fromBigInt(mt(P(r.q,"base64url"))),Se.fromBigInt(mt(P(r.dp,"base64url"))),Se.fromBigInt(mt(P(r.dq,"base64url"))),Se.fromBigInt(mt(P(r.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}function Ih(r){let{result:e}=Zc(r),t=e.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:H(pt(t[0].toBigInt()),"base64url"),e:H(pt(t[1].toBigInt()),"base64url")}}function Jc(r){if(r.n==null||r.e==null)throw new D("JWK was missing components");let t=new Lt({value:[new Lt({value:[new en({value:"1.2.840.113549.1.1.1"}),new Jr]}),new Qr({valueHex:new Lt({value:[Se.fromBigInt(mt(P(r.n,"base64url"))),Se.fromBigInt(mt(P(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}function pt(r){let e=r.toString(16);e.length%2>0&&(e=`0${e}`);let t=e.length/2,n=new Uint8Array(t),o=0,s=0;for(;o<t;)n[o]=parseInt(e.slice(s,s+2),16),o+=1,s+=2;return n}function mt(r){let e=[];return r.forEach(function(t){let n=t.toString(16);n.length%2>0&&(n=`0${n}`),e.push(n)}),BigInt("0x"+e.join(""))}function Ch(r){let e=kh(r);return Th(e)}function Qc(r){let e=Ih(r);if(Xc(e)>Qs)throw new Pr("Key size is too large");let t=Xr(ht.encode({Type:ge.RSA,Data:r})),n=et(Yc,t);return new nn(e,n)}function Th(r){if(Xc(r)>Qs)throw new D("Key size is too large");let e=Lh(r),t=Xr(ht.encode({Type:ge.RSA,Data:Jc(e.publicKey)})),n=et(Yc,t);return new Qn(e.privateKey,new nn(e.publicKey,n))}async function el(r){if(r>Qs)throw new D("Key size is too large");let e=await Sh(r),t=Xr(ht.encode({Type:ge.RSA,Data:Jc(e.publicKey)})),n=et(Yc,t);return new Qn(e.privateKey,new nn(e.publicKey,n))}function Lh(r){if(r==null)throw new D("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}var ei=class extends qr{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Ju(e);let n=Nn(t);if(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 o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?e.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=e.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),s.fill(0)}update(e){return Kr(this),this.iHash.update(e),this}digestInto(e){Kr(this),$r(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){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}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},tl=(r,e,t)=>new ei(r,e).update(t).digest();tl.create=(r,e)=>new ei(r,e);function Nh(r){r.lowS!==void 0&&nt("lowS",r.lowS),r.prehash!==void 0&&nt("prehash",r.prehash)}function N0(r){let e=Dn(r);ut(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:t,Fp:n,a:o}=e;if(t){if(!n.eql(o,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...e})}var{bytesToNumberBE:P0,hexToBytes:R0}=Xo,Dt={Err:class extends Error{constructor(e=""){super(e)}},_tlv:{encode:(r,e)=>{let{Err:t}=Dt;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,o=ar(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let s=n>127?ar(o.length/2|128):"";return`${ar(r)}${s}${o}${e}`},decode(r,e){let{Err:t}=Dt,n=0;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let o=e[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let u=e.subarray(n,n+c);if(u.length!==c)throw new t("tlv.decode: length bytes not complete");if(u[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let f of u)i=i<<8|f;if(n+=c,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(r){let{Err:e}=Dt;if(r<Mt)throw new e("integer: negative integers are not allowed");let t=ar(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected assertion");return t},decode(r){let{Err:e}=Dt;if(r[0]&128)throw new e("Invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("Invalid signature integer: unnecessary leading zero");return P0(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=Dt,o=typeof r=="string"?R0(r):r;Wr(o);let{v:s,l:i}=n.decode(48,o);if(i.length)throw new e("Invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:u,l:f}=n.decode(2,c);if(f.length)throw new e("Invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(u)}},hexFromSig(r){let{_tlv:e,_int:t}=Dt,n=`${e.encode(2,t.encode(r.r))}${e.encode(2,t.encode(r.s))}`;return e.encode(48,n)}},Mt=BigInt(0),ve=BigInt(1),Yv=BigInt(2),Ph=BigInt(3),Jv=BigInt(4);function D0(r){let e=N0(r),{Fp:t}=e,n=Gt(e.n,e.nBitLength),o=e.toBytes||((m,g,y)=>{let b=g.toAffine();return It(Uint8Array.from([4]),t.toBytes(b.x),t.toBytes(b.y))}),s=e.fromBytes||(m=>{let g=m.subarray(1),y=t.fromBytes(g.subarray(0,t.BYTES)),b=t.fromBytes(g.subarray(t.BYTES,2*t.BYTES));return{x:y,y:b}});function i(m){let{a:g,b:y}=e,b=t.sqr(m),w=t.mul(b,m);return t.add(t.add(w,t.mul(m,g)),y)}if(!t.eql(t.sqr(e.Gy),i(e.Gx)))throw new Error("bad generator point: equation left != right");function a(m){return Pn(m,ve,e.n)}function c(m){let{allowedPrivateKeyLengths:g,nByteLength:y,wrapPrivateKey:b,n:w}=e;if(g&&typeof m!="bigint"){if(Kt(m)&&(m=Bt(m)),typeof m!="string"||!g.includes(m.length))throw new Error("Invalid key");m=m.padStart(y*2,"0")}let x;try{x=typeof m=="bigint"?m:kt(ae("private key",m,y))}catch{throw new Error(`private key must be ${y} bytes, hex or bigint, not ${typeof m}`)}return b&&(x=Y(x,w)),$e("private key",x,ve,w),x}function u(m){if(!(m instanceof d))throw new Error("ProjectivePoint expected")}let f=ur((m,g)=>{let{px:y,py:b,pz:w}=m;if(t.eql(w,t.ONE))return{x:y,y:b};let x=m.is0();g==null&&(g=x?t.ONE:t.inv(w));let A=t.mul(y,g),_=t.mul(b,g),v=t.mul(w,g);if(x)return{x:t.ZERO,y:t.ZERO};if(!t.eql(v,t.ONE))throw new Error("invZ was invalid");return{x:A,y:_}}),l=ur(m=>{if(m.is0()){if(e.allowInfinityPoint&&!t.is0(m.py))return;throw new Error("bad point: ZERO")}let{x:g,y}=m.toAffine();if(!t.isValid(g)||!t.isValid(y))throw new Error("bad point: x or y not FE");let b=t.sqr(y),w=i(g);if(!t.eql(b,w))throw new Error("bad point: equation left != right");if(!m.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class d{constructor(g,y,b){if(this.px=g,this.py=y,this.pz=b,g==null||!t.isValid(g))throw new Error("x required");if(y==null||!t.isValid(y))throw new Error("y required");if(b==null||!t.isValid(b))throw new Error("z required");Object.freeze(this)}static fromAffine(g){let{x:y,y:b}=g||{};if(!g||!t.isValid(y)||!t.isValid(b))throw new Error("invalid affine point");if(g instanceof d)throw new Error("projective point not allowed");let w=x=>t.eql(x,t.ZERO);return w(y)&&w(b)?d.ZERO:new d(y,b,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(g){let y=t.invertBatch(g.map(b=>b.pz));return g.map((b,w)=>b.toAffine(y[w])).map(d.fromAffine)}static fromHex(g){let y=d.fromAffine(s(ae("pointHex",g)));return y.assertValidity(),y}static fromPrivateKey(g){return d.BASE.multiply(c(g))}static msm(g,y){return Qo(d,n,g,y)}_setWindowSize(g){p.setWindowSize(this,g)}assertValidity(){l(this)}hasEvenY(){let{y:g}=this.toAffine();if(t.isOdd)return!t.isOdd(g);throw new Error("Field doesn't support isOdd")}equals(g){u(g);let{px:y,py:b,pz:w}=this,{px:x,py:A,pz:_}=g,v=t.eql(t.mul(y,_),t.mul(x,w)),B=t.eql(t.mul(b,_),t.mul(A,w));return v&&B}negate(){return new d(this.px,t.neg(this.py),this.pz)}double(){let{a:g,b:y}=e,b=t.mul(y,Ph),{px:w,py:x,pz:A}=this,_=t.ZERO,v=t.ZERO,B=t.ZERO,T=t.mul(w,w),ee=t.mul(x,x),V=t.mul(A,A),F=t.mul(w,x);return F=t.add(F,F),B=t.mul(w,A),B=t.add(B,B),_=t.mul(g,B),v=t.mul(b,V),v=t.add(_,v),_=t.sub(ee,v),v=t.add(ee,v),v=t.mul(_,v),_=t.mul(F,_),B=t.mul(b,B),V=t.mul(g,V),F=t.sub(T,V),F=t.mul(g,F),F=t.add(F,B),B=t.add(T,T),T=t.add(B,T),T=t.add(T,V),T=t.mul(T,F),v=t.add(v,T),V=t.mul(x,A),V=t.add(V,V),T=t.mul(V,F),_=t.sub(_,T),B=t.mul(V,ee),B=t.add(B,B),B=t.add(B,B),new d(_,v,B)}add(g){u(g);let{px:y,py:b,pz:w}=this,{px:x,py:A,pz:_}=g,v=t.ZERO,B=t.ZERO,T=t.ZERO,ee=e.a,V=t.mul(e.b,Ph),F=t.mul(y,x),R=t.mul(b,A),I=t.mul(w,_),L=t.add(y,b),S=t.add(x,A);L=t.mul(L,S),S=t.add(F,R),L=t.sub(L,S),S=t.add(y,w);let E=t.add(x,_);return S=t.mul(S,E),E=t.add(F,I),S=t.sub(S,E),E=t.add(b,w),v=t.add(A,_),E=t.mul(E,v),v=t.add(R,I),E=t.sub(E,v),T=t.mul(ee,S),v=t.mul(V,I),T=t.add(v,T),v=t.sub(R,T),T=t.add(R,T),B=t.mul(v,T),R=t.add(F,F),R=t.add(R,F),I=t.mul(ee,I),S=t.mul(V,S),R=t.add(R,I),I=t.sub(F,I),I=t.mul(ee,I),S=t.add(S,I),F=t.mul(R,S),B=t.add(B,F),F=t.mul(E,S),v=t.mul(L,v),v=t.sub(v,F),F=t.mul(L,R),T=t.mul(E,T),T=t.add(T,F),new d(v,B,T)}subtract(g){return this.add(g.negate())}is0(){return this.equals(d.ZERO)}wNAF(g){return p.wNAFCached(this,g,d.normalizeZ)}multiplyUnsafe(g){$e("scalar",g,Mt,e.n);let y=d.ZERO;if(g===Mt)return y;if(g===ve)return this;let{endo:b}=e;if(!b)return p.unsafeLadder(this,g);let{k1neg:w,k1:x,k2neg:A,k2:_}=b.splitScalar(g),v=y,B=y,T=this;for(;x>Mt||_>Mt;)x&ve&&(v=v.add(T)),_&ve&&(B=B.add(T)),T=T.double(),x>>=ve,_>>=ve;return w&&(v=v.negate()),A&&(B=B.negate()),B=new d(t.mul(B.px,b.beta),B.py,B.pz),v.add(B)}multiply(g){let{endo:y,n:b}=e;$e("scalar",g,ve,b);let w,x;if(y){let{k1neg:A,k1:_,k2neg:v,k2:B}=y.splitScalar(g),{p:T,f:ee}=this.wNAF(_),{p:V,f:F}=this.wNAF(B);T=p.constTimeNegate(A,T),V=p.constTimeNegate(v,V),V=new d(t.mul(V.px,y.beta),V.py,V.pz),w=T.add(V),x=ee.add(F)}else{let{p:A,f:_}=this.wNAF(g);w=A,x=_}return d.normalizeZ([w,x])[0]}multiplyAndAddUnsafe(g,y,b){let w=d.BASE,x=(_,v)=>v===Mt||v===ve||!_.equals(w)?_.multiplyUnsafe(v):_.multiply(v),A=x(this,y).add(x(g,b));return A.is0()?void 0:A}toAffine(g){return f(this,g)}isTorsionFree(){let{h:g,isTorsionFree:y}=e;if(g===ve)return!0;if(y)return y(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:g,clearCofactor:y}=e;return g===ve?this:y?y(d,this):this.multiplyUnsafe(e.h)}toRawBytes(g=!0){return nt("isCompressed",g),this.assertValidity(),o(d,this,g)}toHex(g=!0){return nt("isCompressed",g),Bt(this.toRawBytes(g))}}d.BASE=new d(e.Gx,e.Gy,t.ONE),d.ZERO=new d(t.ZERO,t.ONE,t.ZERO);let h=e.nBitLength,p=Jo(d,e.endo?Math.ceil(h/2):h);return{CURVE:e,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:i,isWithinCurveOrder:a}}function M0(r){let e=Dn(r);return ut(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function Rh(r){let e=M0(r),{Fp:t,n}=e,o=t.BYTES+1,s=2*t.BYTES+1;function i(I){return Y(I,n)}function a(I){return Yo(I,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:u,weierstrassEquation:f,isWithinCurveOrder:l}=D0({...e,toBytes(I,L,S){let E=L.toAffine(),k=t.toBytes(E.x),N=It;return nt("isCompressed",S),S?N(Uint8Array.from([L.hasEvenY()?2:3]),k):N(Uint8Array.from([4]),k,t.toBytes(E.y))},fromBytes(I){let L=I.length,S=I[0],E=I.subarray(1);if(L===o&&(S===2||S===3)){let k=kt(E);if(!Pn(k,ve,t.ORDER))throw new Error("Point is not on curve");let N=f(k),M;try{M=t.sqrt(N)}catch(z){let K=z instanceof Error?": "+z.message:"";throw new Error("Point is not on curve"+K)}let U=(M&ve)===ve;return(S&1)===1!==U&&(M=t.neg(M)),{x:k,y:M}}else if(L===s&&S===4){let k=t.fromBytes(E.subarray(0,t.BYTES)),N=t.fromBytes(E.subarray(t.BYTES,2*t.BYTES));return{x:k,y:N}}else throw new Error(`Point of length ${L} was invalid. Expected ${o} compressed bytes or ${s} uncompressed bytes`)}}),d=I=>Bt(zt(I,e.nByteLength));function h(I){let L=n>>ve;return I>L}function p(I){return h(I)?i(-I):I}let m=(I,L,S)=>kt(I.slice(L,S));class g{constructor(L,S,E){this.r=L,this.s=S,this.recovery=E,this.assertValidity()}static fromCompact(L){let S=e.nByteLength;return L=ae("compactSignature",L,S*2),new g(m(L,0,S),m(L,S,2*S))}static fromDER(L){let{r:S,s:E}=Dt.toSig(ae("DER",L));return new g(S,E)}assertValidity(){$e("r",this.r,ve,n),$e("s",this.s,ve,n)}addRecoveryBit(L){return new g(this.r,this.s,L)}recoverPublicKey(L){let{r:S,s:E,recovery:k}=this,N=_(ae("msgHash",L));if(k==null||![0,1,2,3].includes(k))throw new Error("recovery id invalid");let M=k===2||k===3?S+e.n:S;if(M>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let U=k&1?"03":"02",$=c.fromHex(U+d(M)),z=a(M),K=i(-N*z),X=i(E*z),Q=c.BASE.multiplyAndAddUnsafe($,K,X);if(!Q)throw new Error("point at infinify");return Q.assertValidity(),Q}hasHighS(){return h(this.s)}normalizeS(){return this.hasHighS()?new g(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return cr(this.toDERHex())}toDERHex(){return Dt.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return cr(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}let y={isValidPrivateKey(I){try{return u(I),!0}catch{return!1}},normPrivateKeyToScalar:u,randomPrivateKey:()=>{let I=oc(e.n);return hf(e.randomBytes(I),e.n)},precompute(I=8,L=c.BASE){return L._setWindowSize(I),L.multiply(BigInt(3)),L}};function b(I,L=!0){return c.fromPrivateKey(I).toRawBytes(L)}function w(I){let L=Kt(I),S=typeof I=="string",E=(L||S)&&I.length;return L?E===o||E===s:S?E===2*o||E===2*s:I instanceof c}function x(I,L,S=!0){if(w(I))throw new Error("first arg must be private key");if(!w(L))throw new Error("second arg must be public key");return c.fromHex(L).multiply(u(I)).toRawBytes(S)}let A=e.bits2int||function(I){let L=kt(I),S=I.length*8-e.nBitLength;return S>0?L>>BigInt(S):L},_=e.bits2int_modN||function(I){return i(A(I))},v=Rn(e.nBitLength);function B(I){return $e(`num < 2^${e.nBitLength}`,I,Mt,v),zt(I,e.nByteLength)}function T(I,L,S=ee){if(["recovered","canonical"].some(xe=>xe in S))throw new Error("sign() legacy options not supported");let{hash:E,randomBytes:k}=e,{lowS:N,prehash:M,extraEntropy:U}=S;N==null&&(N=!0),I=ae("msgHash",I),Nh(S),M&&(I=ae("prehashed msgHash",E(I)));let $=_(I),z=u(L),K=[B(z),B($)];if(U!=null&&U!==!1){let xe=U===!0?k(t.BYTES):U;K.push(ae("extraEntropy",xe))}let X=It(...K),Q=$;function be(xe){let Ee=A(xe);if(!l(Ee))return;let Pe=a(Ee),de=c.BASE.multiply(Ee).toAffine(),He=i(de.x);if(He===Mt)return;let wt=i(Pe*i(Q+He*z));if(wt===Mt)return;let Sn=(de.x===He?0:2)|Number(de.y&ve),_n=wt;return N&&h(wt)&&(_n=p(wt),Sn^=1),new g(He,_n,Sn)}return{seed:X,k2sig:be}}let ee={lowS:e.lowS,prehash:!1},V={lowS:e.lowS,prehash:!1};function F(I,L,S=ee){let{seed:E,k2sig:k}=T(I,L,S),N=e;return ec(N.hash.outputLen,N.nByteLength,N.hmac)(E,k)}c.BASE._setWindowSize(8);function R(I,L,S,E=V){let k=I;if(L=ae("msgHash",L),S=ae("publicKey",S),"strict"in E)throw new Error("options.strict was renamed to lowS");Nh(E);let{lowS:N,prehash:M}=E,U,$;try{if(typeof k=="string"||Kt(k))try{U=g.fromDER(k)}catch(de){if(!(de instanceof Dt.Err))throw de;U=g.fromCompact(k)}else if(typeof k=="object"&&typeof k.r=="bigint"&&typeof k.s=="bigint"){let{r:de,s:He}=k;U=new g(de,He)}else throw new Error("PARSE");$=c.fromHex(S)}catch(de){if(de.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(N&&U.hasHighS())return!1;M&&(L=e.hash(L));let{r:z,s:K}=U,X=_(L),Q=a(K),be=i(X*Q),xe=i(z*Q),Ee=c.BASE.multiplyAndAddUnsafe($,be,xe)?.toAffine();return Ee?i(Ee.x)===z:!1}return{CURVE:e,getPublicKey:b,getSharedSecret:x,sign:F,verify:R,ProjectivePoint:c,Signature:g,utils:y}}function U0(r){return{hash:r,hmac:(e,...t)=>tl(r,e,Ga(...t)),randomBytes:zr}}function Dh(r,e){let t=n=>Rh({...r,...U0(n)});return Object.freeze({...t(e),create:t})}var Oh=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Mh=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),O0=BigInt(1),rl=BigInt(2),Uh=(r,e)=>(r+e/rl)/e;function F0(r){let e=Oh,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=r*r*r%e,f=u*u*r%e,l=re(f,t,e)*f%e,d=re(l,t,e)*f%e,h=re(d,rl,e)*u%e,p=re(h,o,e)*h%e,m=re(p,s,e)*p%e,g=re(m,a,e)*m%e,y=re(g,c,e)*g%e,b=re(y,a,e)*m%e,w=re(b,t,e)*f%e,x=re(w,i,e)*p%e,A=re(x,n,e)*u%e,_=re(A,rl,e);if(!nl.eql(nl.sqr(_),r))throw new Error("Cannot find square root");return _}var nl=Gt(Oh,void 0,void 0,{sqrt:F0}),Xe=Dh({a:BigInt(0),b:BigInt(7),Fp:nl,n:Mh,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=Mh,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-O0*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=t,i=BigInt("0x100000000000000000000000000000000"),a=Uh(s*r,e),c=Uh(-n*r,e),u=Y(r-a*t-c*o,e),f=Y(-a*n-c*s,e),l=u>i,d=f>i;if(l&&(u=e-u),d&&(f=e-f),u>i||f>i)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:l,k1:u,k2neg:d,k2:f}}}},Xr),a2=BigInt(0);var c2=Xe.ProjectivePoint;function Fe(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=ke(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}function ol(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function Fh(r,e){let t=jr.digest(e instanceof Uint8Array?e:e.subarray());if(ol(t))return t.then(({digest:n})=>Xe.sign(n,r).toDERRawBytes()).catch(n=>{throw new Xn(String(n))});try{return Xe.sign(t.digest,r).toDERRawBytes()}catch(n){throw new Xn(String(n))}}function Vh(r,e,t){let n=jr.digest(t instanceof Uint8Array?t:t.subarray());if(ol(n))return n.then(({digest:o})=>Xe.verify(e,o,r)).catch(o=>{throw new Yn(String(o))});try{return Xe.verify(e,n.digest,r)}catch(o){throw new Yn(String(o))}}var eo=class{type="secp256k1";raw;_key;constructor(e){this._key=Kh(e),this.raw=Hh(this._key)}toMultihash(){return St.digest(ft(this))}toCID(){return pe.createV1(114,this.toMultihash())}toString(){return W.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ie(this.raw,e.raw)}verify(e,t){return Vh(this._key,t,e)}},ti=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=$h(e),this.publicKey=new eo(t??qh(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ie(this.raw,e.raw)}sign(e){return Fh(this.raw,e)}};function sl(r){return new eo(r)}async function zh(){let r=V0();return new ti(r)}function Hh(r){return Xe.ProjectivePoint.fromHex(r).toRawBytes(!0)}function $h(r){try{return Xe.getPublicKey(r,!0),r}catch(e){throw new Bn(String(e))}}function Kh(r){try{return Xe.ProjectivePoint.fromHex(r),r}catch(e){throw new Pr(String(e))}}function qh(r){try{return Xe.getPublicKey(r,!0)}catch(e){throw new Bn(String(e))}}function V0(){return Xe.utils.randomPrivateKey()}async function Gh(r,e){if(r==="Ed25519")return vf();if(r==="secp256k1")return zh();if(r==="RSA")return el(e??2048);throw new Ft}function on(r){let{Type:e,Data:t}=ht.decode(r),n=t??new Uint8Array;switch(e){case ge.RSA:return Qc(n);case ge.Ed25519:return lc(n);case ge.secp256k1:return sl(n);default:throw new Ft}}function Wh(r){let{Type:e,Data:t}=ht.decode(r.digest),n=t??new Uint8Array;switch(e){case ge.Ed25519:return lc(n);case ge.secp256k1:return sl(n);default:throw new Ft}}function ft(r){return ht.encode({Type:ge[r.type],Data:r.raw})}var jh=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()})`}[Po]=!0;toString(){return this.string==null&&(this.string=W.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 ie(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return ie(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[jh](){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}},$0=2336,so=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=St.digest(P(this.url))}[jh](){return`PeerId(${this.url})`}[Po]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return pe.createV1($0,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=H(e)),e.toString()===this.toString())}};var K0=114,Zh=2336;function gt(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=tt(W.decode(`z${r}`));else{if(e==null)throw new D('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=tt(e.decode(r))}return sn(t)}function il(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 Ft}function Xh(r){return il(r.publicKey)}function sn(r){if(z0(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=H(r.digest);return new so(new URL(t))}throw new Vo("Supplied PeerID Multihash is invalid")}function ri(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==K0&&r.code!==Zh)throw new Fo("Supplied PeerID CID is invalid");if(r.code===Zh){let e=H(r.multihash.digest);return new so(new URL(e))}return sn(r.multihash)}function q0(r){return r.code===St.code}function z0(r){return r.code===jr.code}var ni=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*o)-1;for(;;){let f=this.readAtomically(()=>{let l=this.readChar();if(l===void 0)return;let d=Number.parseInt(l,e);if(!Number.isNaN(d))return d});if(f===void 0)break;if(s*=e,s+=f,s>u||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Yh=45,G0=15,an=new ni;function al(r){if(!(r.length>G0))return an.new(r).parseWith(()=>an.readIPv4Addr())}function cl(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Yh))return an.new(r).parseWith(()=>an.readIPv6Addr())}function oi(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Yh))return an.new(r).parseWith(()=>an.readIPAddr())}function cn(r){return!!al(r)}function ln(r){return!!cl(r)}function si(r){return!!oi(r)}var yE=parseInt("0xFFFF",16),wE=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);var ed=cn,Y0=ln,ll=function(r){let e=0;if(r=r.toString().trim(),ed(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(Y0(r)){let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=ed(t[n]),i;s&&(i=ll(t[n]),t[n]=H(i.slice(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,H(i.slice(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++){let s=parseInt(t[n],16);o[e++]=s>>8&255,o[e++]=s&255}return o}throw new Error("invalid ip address")},td=function(r,e=0,t){e=~~e,t=t??r.length-e;let n=new DataView(r.buffer);if(t===4){let o=[];for(let s=0;s<t;s++)o.push(r[e+s]);return o.join(".")}if(t===16){let o=[];for(let s=0;s<t;s+=2)o.push(n.getUint16(e+s).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var un={},ul={},Q0=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,-1,"ip6zone"],[43,8,"ipcidr"],[53,-1,"dns",!0],[54,-1,"dns4",!0],[55,-1,"dns6",!0],[56,-1,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,-1,"unix",!1,!0],[421,-1,"ipfs"],[421,-1,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,-1,"garlic64"],[448,0,"tls"],[449,-1,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,-1,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,-1,"http-path"],[777,-1,"memory"]];Q0.forEach(r=>{let e=ey(...r);ul[e.code]=e,un[e.name]=e});function ey(r,e,t,n,o){return{code:r,size:e,name:t,resolvable:!!n,path:!!o}}function Z(r){if(typeof r=="number"){if(ul[r]!=null)return ul[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(un[r]!=null)return un[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var QE=Z("ip4"),eA=Z("ip6"),tA=Z("ipcidr");function pl(r,e){switch(Z(r).code){case 4:case 41:return ry(e);case 42:return dl(e);case 6:case 273:case 33:case 132:return od(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return dl(e);case 421:return iy(e);case 444:return nd(e);case 445:return nd(e);case 466:return sy(e);case 481:return globalThis.encodeURIComponent(dl(e));default:return H(e,"base16")}}function ml(r,e){switch(Z(r).code){case 4:return rd(e);case 41:return rd(e);case 42:return hl(e);case 6:case 273:case 33:case 132:return gl(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return hl(e);case 421:return ny(e);case 444:return ay(e);case 445:return cy(e);case 466:return oy(e);case 481:return hl(globalThis.decodeURIComponent(e));default:return P(e,"base16")}}var fl=Object.values(On).map(r=>r.decoder),ty=function(){let r=fl[0].or(fl[1]);return fl.slice(2).forEach(e=>r=r.or(e)),r}();function rd(r){if(!si(r))throw new Error("invalid ip address");return ll(r)}function ry(r){let e=td(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!si(e))throw new Error("invalid ip address");return e}function gl(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function od(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function hl(r){let e=P(r),t=Uint8Array.from(Ce(e.length));return Fe([t,e],t.length+e.length)}function dl(r){let e=st(r);if(r=r.slice(he(e)),r.length!==e)throw new Error("inconsistent lengths");return H(r)}function ny(r){let e;r[0]==="Q"||r[0]==="1"?e=tt(W.decode(`z${r}`)).bytes:e=pe.parse(r).multihash.bytes;let t=Uint8Array.from(Ce(e.length));return Fe([t,e],t.length+e.length)}function oy(r){let e=ty.decode(r),t=Uint8Array.from(Ce(e.length));return Fe([t,e],t.length+e.length)}function sy(r){let e=st(r),t=r.slice(he(e));if(t.length!==e)throw new Error("inconsistent lengths");return"u"+H(t,"base64url")}function iy(r){let e=st(r),t=r.slice(he(e));if(t.length!==e)throw new Error("inconsistent lengths");return H(t,"base58btc")}function ay(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=ze.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=gl(n);return Fe([t,o],t.length+o.length)}function cy(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=ze.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=gl(n);return Fe([t,o],t.length+o.length)}function nd(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=H(e,"base32"),o=od(t);return`${n}:${o}`}function sd(r){r=yl(r);let e=[],t=[],n=null,o=r.split("/").slice(1);if(o.length===1&&o[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let s=0;s<o.length;s++){let i=o[s],a=Z(i);if(a.size===0){e.push([a.code]),t.push([a.code]);continue}if(s++,s>=o.length)throw ad("invalid address: "+r);if(a.path===!0){n=yl(o.slice(s).join("/")),e.push([a.code,ml(a.code,n)]),t.push([a.code,n]);break}let c=ml(a.code,o[s]);e.push([a.code,c]),t.push([a.code,pl(a.code,c)])}return{string:id(t),bytes:bl(e),tuples:e,stringTuples:t,path:n}}function wl(r){let e=[],t=[],n=null,o=0;for(;o<r.length;){let s=st(r,o),i=he(s),a=Z(s),c=ly(a,r.slice(o+i));if(c===0){e.push([s]),t.push([s]),o+=i;continue}let u=r.slice(o+i,o+i+c);if(o+=c+i,o>r.length)throw ad("Invalid address Uint8Array: "+H(r,"base16"));e.push([s,u]);let f=pl(s,u);if(t.push([s,f]),a.path===!0){n=f;break}}return{bytes:Uint8Array.from(r),string:id(t),tuples:e,stringTuples:t,path:n}}function id(r){let e=[];return r.map(t=>{let n=Z(t[0]);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),yl(e.join("/"))}function bl(r){return Fe(r.map(e=>{let t=Z(e[0]),n=Uint8Array.from(Ce(t.code));return e.length>1&&e[1]!=null&&(n=Fe([n,e[1]])),n}))}function ly(r,e){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let t=st(e instanceof Uint8Array?e:Uint8Array.from(e));return t+he(t)}}function yl(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}function ad(r){return new Error("Error parsing address: "+r)}var uy=Symbol.for("nodejs.util.inspect.custom"),xl=Symbol.for("@multiformats/js-multiaddr/multiaddr"),fy=[Z("dns").code,Z("dns4").code,Z("dns6").code,Z("dnsaddr").code],ii=class r{bytes;#e;#t;#s;#a;[xl]=!0;constructor(e){e==null&&(e="");let t;if(e instanceof Uint8Array)t=wl(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);t=sd(e)}else if(Qt(e))t=wl(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=t.bytes,this.#e=t.string,this.#t=t.tuples,this.#s=t.stringTuples,this.#a=t.path}toString(){return this.#e}toJSON(){return this.toString()}toOptions(){let e,t,n,o,s="",i=Z("tcp"),a=Z("udp"),c=Z("ip4"),u=Z("ip6"),f=Z("dns6"),l=Z("ip6zone");for(let[h,p]of this.stringTuples())h===l.code&&(s=`%${p??""}`),fy.includes(h)&&(t=i.name,o=443,n=`${p??""}${s}`,e=h===f.code?6:4),(h===i.code||h===a.code)&&(t=Z(h).name,o=parseInt(p??"")),(h===c.code||h===u.code)&&(t=Z(h).name,n=`${p??""}${s}`,e=h===u.code?6:4);if(e==null||t==null||n==null||o==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:n,transport:t,port:o}}protos(){return this.#t.map(([e])=>Object.assign({},Z(e)))}protoCodes(){return this.#t.map(([e])=>e)}protoNames(){return this.#t.map(([e])=>Z(e).name)}tuples(){return this.#t}stringTuples(){return this.#s}encapsulate(e){return e=new r(e),new r(this.toString()+e.toString())}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new r(n.slice(0,o))}decapsulateCode(e){let t=this.tuples();for(let n=t.length-1;n>=0;n--)if(t[n][0]===e)return new r(bl(t.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,o])=>{n===un.p2p.code&&e.push([n,o]),n===un["p2p-circuit"].code&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?H(W.decode(`z${n}`),"base58btc"):H(pe.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#a}equals(e){return ie(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(s=>s.resolvable);if(t==null)return[this];let n=fn.get(t.name);if(n==null)throw new Nr(`no available resolver for ${t.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,e)).map(s=>ne(s))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(e){let t=(e??this).protos();return!(t.length!==2||t[0].code!==4&&t[0].code!==41||t[1].code!==6&&t[1].code!==273)}[uy](){return`Multiaddr(${this.#e})`}};var fn=new Map;function Qt(r){return!!r?.[xl]}function ne(r){return new ii(r)}var hy=r=>r.toString().split("/").slice(1),io=r=>({match:e=>e.length<1?!1:r(e[0])?e.slice(1):!1,pattern:"fn"}),G=r=>({match:e=>io(t=>t===r).match(e),pattern:r}),li=()=>({match:r=>io(e=>typeof e=="string").match(r),pattern:"{string}"}),ui=()=>({match:r=>io(e=>!isNaN(parseInt(e))).match(r),pattern:"{number}"}),_e=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{W.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),ai=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{kc.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),ye=r=>({match:e=>{let t=r.match(e);return t===!1?e:t},pattern:`optional(${r.pattern})`}),Ye=(...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},pattern:`or(${r.map(e=>e.pattern).join(", ")})`}),J=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e},pattern:`and(${r.map(e=>e.pattern).join(", ")})`});function ue(...r){function e(o){let s=hy(o);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{matches:t,exactMatch:n}}var El=J(G("dns4"),li()),Al=J(G("dns6"),li()),Sl=J(G("dnsaddr"),li()),cd=J(G("dns"),li()),TA=ue(El),LA=ue(Al),NA=ue(Sl),PA=ue(Ye(cd,Sl,El,Al)),ld=J(G("ip4"),io(cn)),ud=J(G("ip6"),io(ln)),fd=Ye(ld,ud),yt=Ye(fd,cd,El,Al,Sl),RA=ue(yt),DA=ue(ld),MA=ue(ud),UA=ue(fd),_l=J(yt,G("tcp"),ui()),ao=J(yt,G("udp"),ui()),OA=ue(_l),FA=ue(ao),Bl=J(ao,G("quic")),fi=J(ao,G("quic-v1")),dy=Ye(Bl,fi),VA=ue(Bl),HA=ue(fi),vl=Ye(yt,_l,ao,Bl,fi),hd=Ye(J(vl,G("ws"),ye(_e()))),$A=ue(hd),dd=Ye(J(vl,G("wss"),ye(_e())),J(vl,G("tls"),G("ws"),ye(_e()))),KA=ue(dd),pd=J(ao,G("webrtc-direct"),ye(ai()),ye(ai()),ye(_e())),qA=ue(pd),md=J(fi,G("webtransport"),ye(ai()),ye(ai()),ye(_e())),zA=ue(md),ci=Ye(hd,dd,J(_l,ye(_e())),J(dy,ye(_e())),J(yt,ye(_e())),pd,md,_e()),GA=ue(ci),py=J(ci,G("p2p-circuit"),_e()),co=ue(py),my=Ye(J(ci,G("p2p-circuit"),G("webrtc"),ye(_e())),J(ci,G("webrtc"),ye(_e())),G("webrtc")),WA=ue(my),gy=Ye(J(yt,G("tcp"),ui(),G("http"),ye(_e())),J(yt,G("http"),ye(_e()))),jA=ue(gy),yy=Ye(J(yt,G("tcp"),Ye(J(G("443"),G("http")),J(ui(),G("https"))),ye(_e())),J(yt,G("tls"),G("http"),ye(_e())),J(yt,G("https"),ye(_e()))),ZA=ue(yy);var yd=sr(gd(),1),wy=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"],by=wy.map(r=>new yd.Netmask(r));function kl(r){for(let e of by)if(e.contains(r))return!0;return!1}function xy(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function vy(r){let e=r.split(":");if(e.length<2)return!1;let t=e[e.length-1].padStart(4,"0"),n=e[e.length-2].padStart(4,"0"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return kl(o)}function Ey(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function Ay(r){let e=r.split(":"),t=e[e.length-1];return kl(t)}function Sy(r){return/^::$/.test(r)||/^::1$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}function hi(r){return cn(r)?kl(r):xy(r)?vy(r):Ey(r)?Ay(r):ln(r)?Sy(r):void 0}function Il(r){try{let{address:e}=r.nodeAddress();return!!hi(e)}catch{return!0}}function _y(r,e){let t=Il(r.multiaddr),n=Il(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function By(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function ky(r,e){let t=co.exactMatch(r.multiaddr),n=co.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function hn(r,e){let t=_y(r,e);if(t!==0)return t;let n=ky(r,e);return n!==0?n:By(r,e)}var fe=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var Tl=sr(bd(),1);var fo=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Ll=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},xd=r=>globalThis.DOMException===void 0?new Ll(r):new DOMException(r),vd=r=>{let e=r.reason===void 0?xd("This operation was aborted."):r.reason;return e instanceof Error?e:xd(e)};function ho(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=e,i,c=new Promise((u,f)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:d}=e;d.aborted&&f(vd(d)),d.addEventListener("abort",()=>{f(vd(d))})}if(t===Number.POSITIVE_INFINITY){r.then(u,f);return}let l=new fo;i=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(d){f(d)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?u():o instanceof Error?f(o):(l.message=o??`Promise timed out after ${t} milliseconds`,f(l))},t),(async()=>{try{u(await r)}catch(d){f(d)}})()}).finally(()=>{c.clear()});return c.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},c}function Nl(r,e,t){let n=0,o=r.length;for(;o>0;){let s=Math.trunc(o/2),i=n+s;t(r[i],e)<=0?(n=++i,o-=s+1):o=s}return n}var po=class{#e=[];enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,run:e};if(this.size&&this.#e[this.size-1].priority>=t.priority){this.#e.push(n);return}let o=Nl(this.#e,n,(s,i)=>i.priority-s.priority);this.#e.splice(o,0,n)}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this.#e.length}};var er=class extends Tl.default{#e;#t;#s=0;#a;#c;#p=0;#n;#l;#r;#m;#o=0;#u;#i;#g;timeout;constructor(e){if(super(),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:po,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#e=e.carryoverConcurrencyCount,this.#t=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#a=e.intervalCap,this.#c=e.interval,this.#r=new e.queueClass,this.#m=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#g=e.throwOnTimeout===!0,this.#i=e.autoStart===!1}get#b(){return this.#t||this.#s<this.#a}get#x(){return this.#o<this.#u}#v(){this.#o--,this.#f(),this.emit("next")}#E(){this.#w(),this.#y(),this.#l=void 0}get#A(){let e=Date.now();if(this.#n===void 0){let t=this.#p-e;if(t<0)this.#s=this.#e?this.#o:0;else return this.#l===void 0&&(this.#l=setTimeout(()=>{this.#E()},t)),!0}return!1}#f(){if(this.#r.size===0)return this.#n&&clearInterval(this.#n),this.#n=void 0,this.emit("empty"),this.#o===0&&this.emit("idle"),!1;if(!this.#i){let e=!this.#A;if(this.#b&&this.#x){let t=this.#r.dequeue();return t?(this.emit("active"),t(),e&&this.#y(),!0):!1}}return!1}#y(){this.#t||this.#n!==void 0||(this.#n=setInterval(()=>{this.#w()},this.#c),this.#p=Date.now()+this.#c)}#w(){this.#s===0&&this.#o===0&&this.#n&&(clearInterval(this.#n),this.#n=void 0),this.#s=this.#e?this.#o:0,this.#h()}#h(){for(;this.#f(););}get concurrency(){return this.#u}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#u=e,this.#h()}async#S(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(e.reason)},{once:!0})})}async add(e,t={}){return t={timeout:this.timeout,throwOnTimeout:this.#g,...t},new Promise((n,o)=>{this.#r.enqueue(async()=>{this.#o++,this.#s++;try{t.signal?.throwIfAborted();let s=e({signal:t.signal});t.timeout&&(s=ho(Promise.resolve(s),{milliseconds:t.timeout})),t.signal&&(s=Promise.race([s,this.#S(t.signal)]));let i=await s;n(i),this.emit("completed",i)}catch(s){if(s instanceof fo&&!t.throwOnTimeout){n();return}o(s),this.emit("error",s)}finally{this.#v()}},t),this.emit("add"),this.#f()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#i?(this.#i=!1,this.#h(),this):this}pause(){this.#i=!0}clear(){this.#r=new this.#m}async onEmpty(){this.#r.size!==0&&await this.#d("empty")}async onSizeLessThan(e){this.#r.size<e||await this.#d("next",()=>this.#r.size<e)}async onIdle(){this.#o===0&&this.#r.size===0||await this.#d("idle")}async#d(e,t){return new Promise(n=>{let o=()=>{t&&!t()||(this.off(e,o),n())};this.on(e,o)})}get size(){return this.#r.size}sizeBy(e){return this.#r.filter(e).length}get pending(){return this.#o}get isPaused(){return this.#i}};function pi(r){let e=[We.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var Pl=60;function mi(r){return{Status:r.Status??0,TC:r.TC??r.flag_tc??!1,RD:r.RD??r.flag_rd??!1,RA:r.RA??r.flag_ra??!1,AD:r.AD??r.flag_ad??!1,CD:r.CD??r.flag_cd??!1,Question:(r.Question??r.questions??[]).map(e=>({name:e.name,type:We[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:We[e.type],TTL:e.TTL??e.ttl??Pl,data:e.data instanceof Uint8Array?H(e.data):e.data}))}}var Ty=4;function Rl(r,e={}){let t=new er({concurrency:e.queryConcurrency??Ty});return async(n,o={})=>{let s=new URLSearchParams;s.set("name",n),pi(o.types).forEach(a=>{s.append("type",We[a])}),o.onProgress?.(new fe("dns:query",{detail:n}));let i=await t.add(async()=>{let a=await fetch(`${r}?${s}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let c=mi(await a.json());return o.onProgress?.(new fe("dns:response",{detail:c})),c},{signal:o.signal});if(i==null)throw new Error("No DNS response received");return i}}function Ed(){return[Rl("https://cloudflare-dns.com/dns-query"),Rl("https://dns.google/resolve")]}var _d=sr(Sd(),1);var Dl=class{lru;constructor(e){this.lru=(0,_d.default)(e)}get(e,t){let n=!0,o=[];for(let s of t){let i=this.getAnswers(e,s);if(i.length===0){n=!1;break}o.push(...i)}if(n)return mi({answers:o})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,o=this.lru.get(n);if(o!=null){let s=o.filter(i=>i.expires>Date.now()).map(({expires:i,value:a})=>({...a,TTL:Math.round((i-Date.now())/1e3),type:We[a.type]}));return s.length===0&&this.lru.remove(n),s}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(t.TTL??Pl)*1e3,value:t}),this.lru.set(n,o)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function Bd(r){return new Dl(r)}var Ly=1e3,gi=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=Bd(e.cacheSize??Ly),Object.entries(e.resolvers??{}).forEach(([t,n])=>{Array.isArray(n)||(n=[n]),t.endsWith(".")||(t=`${t}.`),this.resolvers[t]=n}),this.resolvers["."]==null&&(this.resolvers["."]=Ed())}async query(e,t={}){let n=pi(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new fe("dns:cache",{detail:o})),o;let s=`${e.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of i){if(t.signal?.aborted===!0)break;try{let u=await c(e,{...t,types:n});for(let f of u.Answer)this.cache.add(e,f);return u}catch(u){a.push(u),t.onProgress?.(new fe("dns:error",{detail:u}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${e} ${n} failed`)}};var We;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(We||(We={}));function kd(r={}){return new gi(r)}var Ny=32,{code:Py}=Z("dnsaddr"),yr=async function(e,t={}){let n=t.maxRecursiveDepth??Ny;if(n===0)throw new Nr("Max recursive depth reached","ERR_MAX_RECURSIVE_DEPTH_REACHED");let[,o]=e.stringTuples().find(([u])=>u===Py)??[],i=await(t?.dns??kd()).query(`_dnsaddr.${o}`,{signal:t?.signal,types:[We.TXT]}),a=e.getPeerId(),c=[];for(let u of i.Answer){let f=u.data.replace(/["']/g,"").trim().split("=")[1];if(f==null||a!=null&&!f.includes(a))continue;let l=ne(f);if(f.startsWith("/dnsaddr")){let d=await l.resolve({...t,maxRecursiveDepth:n-1});c.push(...d.map(h=>h.toString()))}else c.push(l.toString())}return c};var Md=sr(Dd(),1),bi=Md.default;var Fy={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:yr},addressSorter:hn},transportManager:{faultTolerance:Ot.FATAL_ALL}};async function Ud(r){let e=bi(Fy,r);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new D("Private network is enforced, but no protector was provided");return e}function Vy(r,e){try{if(typeof r=="string"&&r.length>0)return Hy(r);if(typeof r=="number"&&isFinite(r))return e?.long?Ky(r):$y(r);throw new Error("Value is not a string or number.")}catch(t){let n=qy(t)?`${t.message}. value=${JSON.stringify(r)}`:"An unknown error has occured.";throw new Error(n)}}function Hy(r){if(r=String(r),r.length>100)throw new Error("Value exceeds the maximum length of 100 characters.");let e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(!e)return NaN;let t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*315576e5;case"weeks":case"week":case"w":return t*6048e5;case"days":case"day":case"d":return t*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return t*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return t*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return t*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:throw new Error(`The unit ${n} was matched, but no matching case exists.`)}}var vi=Vy;function $y(r){let e=Math.abs(r);return e>=864e5?`${Math.round(r/864e5)}d`:e>=36e5?`${Math.round(r/36e5)}h`:e>=6e4?`${Math.round(r/6e4)}m`:e>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function Ky(r){let e=Math.abs(r);return e>=864e5?xi(r,e,864e5,"day"):e>=36e5?xi(r,e,36e5,"hour"):e>=6e4?xi(r,e,6e4,"minute"):e>=1e3?xi(r,e,1e3,"second"):`${r} ms`}function xi(r,e,t,n){let o=e>=t*1.5;return`${Math.round(r/t)} ${n}${o?"s":""}`}function qy(r){return typeof r=="object"&&r!==null&&"message"in r}function Ul(r){t.debug=t,t.default=t,t.coerce=c,t.disable=s,t.enable=o,t.enabled=i,t.humanize=vi,t.destroy=u,Object.keys(r).forEach(f=>{t[f]=r[f]}),t.names=[],t.skips=[],t.formatters={};function e(f){let l=0;for(let d=0;d<f.length;d++)l=(l<<5)-l+f.charCodeAt(d),l|=0;return t.colors[Math.abs(l)%t.colors.length]}t.selectColor=e;function t(f){let l,d=null,h,p;function m(...g){if(!m.enabled)return;let y=m,b=Number(new Date),w=b-(l||b);y.diff=w,y.prev=l,y.curr=b,l=b,g[0]=t.coerce(g[0]),typeof g[0]!="string"&&g.unshift("%O");let x=0;g[0]=g[0].replace(/%([a-zA-Z%])/g,(_,v)=>{if(_==="%%")return"%";x++;let B=t.formatters[v];if(typeof B=="function"){let T=g[x];_=B.call(y,T),g.splice(x,1),x--}return _}),t.formatArgs.call(y,g),(y.log||t.log).apply(y,g)}return m.namespace=f,m.useColors=t.useColors(),m.color=t.selectColor(f),m.extend=n,m.destroy=t.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(h!==t.namespaces&&(h=t.namespaces,p=t.enabled(f)),p),set:g=>{d=g}}),typeof t.init=="function"&&t.init(m),m}function n(f,l){let d=t(this.namespace+(typeof l>"u"?":":l)+f);return d.log=this.log,d}function o(f){t.save(f),t.namespaces=f,t.names=[],t.skips=[];let l,d=(typeof f=="string"?f:"").split(/[\s,]+/),h=d.length;for(l=0;l<h;l++)d[l]&&(f=d[l].replace(/\*/g,".*?"),f[0]==="-"?t.skips.push(new RegExp("^"+f.substr(1)+"$")):t.names.push(new RegExp("^"+f+"$")))}function s(){let f=[...t.names.map(a),...t.skips.map(a).map(l=>"-"+l)].join(",");return t.enable(""),f}function i(f){if(f[f.length-1]==="*")return!0;let l,d;for(l=0,d=t.skips.length;l<d;l++)if(t.skips[l].test(f))return!1;for(l=0,d=t.names.length;l<d;l++)if(t.names[l].test(f))return!0;return!1}function a(f){return f.toString().substring(2,f.toString().length-2).replace(/\.\*\?$/,"*")}function c(f){return f instanceof Error?f.stack??f.message:f}function u(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.setupFormatters(t.formatters),t.enable(t.load()),t}var Ei=Yy(),zy=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function Gy(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/(edge|trident)\/(\d+)/)!=null?!1:typeof document<"u"&&document.documentElement?.style?.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/firefox\/(\d+)/)!=null&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/applewebkit\/(\d+)/)}function Wy(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+vi(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(t++,o==="%c"&&(n=t))}),r.splice(n,0,e)}var jy=console.debug??console.log??(()=>{});function Zy(r){try{r?Ei?.setItem("debug",r):Ei?.removeItem("debug")}catch{}}function Xy(){let r;try{r=Ei?.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function Yy(){try{return localStorage}catch{}}function Jy(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var Od=Ul({formatArgs:Wy,save:Zy,load:Xy,useColors:Gy,setupFormatters:Jy,colors:zy,storage:Ei,log:jy});var je=Od;je.formatters.b=r=>r==null?"undefined":W.baseEncode(r);je.formatters.t=r=>r==null?"undefined":ze.baseEncode(r);je.formatters.m=r=>r==null?"undefined":Bc.baseEncode(r);je.formatters.p=r=>r==null?"undefined":r.toString();je.formatters.c=r=>r==null?"undefined":r.toString();je.formatters.k=r=>r==null?"undefined":r.toString();je.formatters.a=r=>r==null?"undefined":r.toString();function Qy(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function Ai(){return{forComponent(r){return ew(r)}}}function ew(r){let e=Qy(`${r}:trace`);return je.enabled(`${r}:trace`)&&je.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=je(`${r}:trace`)),Object.assign(je(r),{error:je(`${r}:error`),trace:e})}function wr(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}function Si(r){let e=tt(W.decode(`z${r}`));return sn(e)}var ct=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),{key:t,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return wr(this.map.entries(),e=>[e[1].key,e[1].value])}forEach(e){this.map.forEach((t,n)=>{e(t.value,t.key,this)})}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),{key:e,value:t})}keys(){return wr(this.map.values(),e=>e.key)}values(){return wr(this.map.values(),e=>e.value)}get size(){return this.map.size}};var br=class r{set;constructor(e){if(this.set=new Set,e!=null)for(let t of e)this.set.add(t.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return wr(this.set.entries(),e=>{let t=Si(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=Si(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return wr(this.set.values(),e=>Si(e))}intersection(e){let t=new r;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new r;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new r;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};var Kd=Symbol.for("@achingbrain/uint8arraylist");function $d(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 Bi(r){return!!r?.[Kd]}var we=class r{bufs;length;[Kd]=!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(Bi(n))t+=n.byteLength,this.bufs.push(...n.bufs);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(Bi(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=$d(this.bufs,e);return t.buf[t.index]}set(e,t){let n=$d(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(Bi(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 Fe(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:Fe(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=[...n],s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let u=e>=a&&e<c,f=t>a&&t<=c;if(u&&f){if(e===a&&t===c){n.push(i);break}let l=e-a;n.push(i.subarray(l,l+(t-e)));break}if(u){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(f){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!Bi(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let l=0;l<s;l++)i[l]=-1;for(let l=0;l<o;l++)i[n[l]]=l;let a=i,c=this.byteLength-n.byteLength,u=n.byteLength-1,f;for(let l=t;l<=c;l+=f){f=0;for(let d=u;d>=0;d--){let h=this.get(l+d);if(n[d]!==h){f=Math.max(1,d-a[h]);break}}if(f===0)return l}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=ke(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=ce(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=ce(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=ce(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=ke(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=ce(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=ce(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=ce(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=ce(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=ce(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(!ie(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 Ol=64,lt=class{fp;h;seed;constructor(e,t,n,o=2){if(o>Ol)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),i=ce(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?ie(this.fp,e.fp):!1}};function xr(r,e){return Math.floor(Math.random()*(e-r))+r}var vr=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof lt))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof lt))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(this.contents[t]==null)return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof lt))throw new TypeError("Invalid Fingerprint");let t=xr(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof lt))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var Fl={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},qd={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},zd=new globalThis.TextEncoder;function tw(r,e){let t=Fl[e],n=qd[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function rw(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Fl[e],o=qd[e],s=r;for(;s.length>0;){let i=zd.encodeInto(s,t);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(t[a]),o=BigInt.asUintN(e,o*n)}return o}function Vl(r,{size:e=32,utf8Buffer:t}={}){if(!Fl[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(t)return rw(r,e,t);r=zd.encode(r)}return tw(r,e)}var nw=sr(Hd(),1);var go={hash:r=>Number(Vl(r,{size:32})),hashV:(r,e)=>ow(go.hash(r,e))};function ow(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),P(e,"base16")}var sw=500,yo=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??go,this.seed=e.seed??xr(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=P(e));let t=new lt(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new vr(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new vr(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let s=[n,o],i=s[xr(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new vr(this.bucketSize));for(let a=0;a<sw;a++){let c=this.buckets[i].swap(t);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new vr(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=P(e));let t=new lt(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let s=(n^t.hash())%this.filterSize;return this.buckets[s]?.has(t)??!1}remove(e){typeof e=="string"&&(e=P(e));let t=new lt(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let s=(n^t.hash())%this.filterSize,i=this.buckets[s]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},iw={1:.5,2:.84,4:.95,8:.98};function aw(r=.001){return r>.002?2:r>1e-5?4:8}function Gd(r,e=.001){let t=aw(e),n=iw[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),Ol);return{filterSize:o,bucketSize:t,fingerprintSize:s}}var ki=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??go,this.seed=e.seed??xr(0,Math.pow(2,10)),this.filterSeries=[new yo({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=P(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new yo({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=P(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=P(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function Hl(r,e=.001,t){return new ki({...Gd(r,e),...t??{}})}var wo;(function(r){let e;r.codec=()=>(e==null&&(e=Ue((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.publicKey!=null&&t.publicKey.byteLength>0&&(n.uint32(10),n.bytes(t.publicKey)),t.payloadType!=null&&t.payloadType.byteLength>0&&(n.uint32(18),n.bytes(t.payloadType)),t.payload!=null&&t.payload.byteLength>0&&(n.uint32(26),n.bytes(t.payload)),t.signature!=null&&t.signature.byteLength>0&&(n.uint32(42),n.bytes(t.signature)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={publicKey:ce(0),payloadType:ce(0),payload:ce(0),signature:ce(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.publicKey=t.bytes();break}case 2:{s.payloadType=t.bytes();break}case 3:{s.payload=t.bytes();break}case 5:{s.signature=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Me(t,r.codec()),r.decode=(t,n)=>De(t,r.codec(),n)})(wo||(wo={}));var Ii=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var mn=class r{static createFromProtobuf=async e=>{let t=wo.decode(e),n=on(t.publicKey);return new r({publicKey:n,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t)=>{if(t==null)throw new Error("Missing private key");let n=e.domain,o=e.codec,s=e.marshal(),i=Wd(n,o,s),a=await t.sign(i.subarray());return new r({publicKey:t.publicKey,payloadType:o,payload:s,signature:a})};static openAndCertify=async(e,t)=>{let n=await r.createFromProtobuf(e);if(!await n.validate(t))throw new Ii("Envelope signature is not valid for the given domain");return n};publicKey;payloadType;payload;signature;marshaled;constructor(e){let{publicKey:t,payloadType:n,payload:o,signature:s}=e;this.publicKey=t,this.payloadType=n,this.payload=o,this.signature=s}marshal(){return this.marshaled==null&&(this.marshaled=wo.encode({publicKey:ft(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return ie(this.marshal(),e.marshal())}async validate(e){let t=Wd(e,this.payloadType,this.payload);return this.publicKey.verify(t.subarray(),this.signature)}},Wd=(r,e,t)=>{let n=P(r),o=Ce(n.byteLength),s=Ce(e.length),i=Ce(t.length);return new we(o,n,s,e,i,t)};function jd(r,e){let t=(n,o)=>n.toString().localeCompare(o.toString());return r.length!==e.length?!1:(e.sort(t),r.sort(t).every((n,o)=>e[o].equals(n)))}var Zd="libp2p-peer-record",Xd=Uint8Array.from([3,1]);var bo;(function(r){let e;(function(n){let o;n.codec=()=>(o==null&&(o=Ue((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.multiaddr!=null&&s.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(s.multiaddr)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={multiaddr:ce(0)},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{c.multiaddr=s.bytes();break}default:{s.skipType(f&7);break}}}return c})),o),n.encode=s=>Me(s,n.codec()),n.decode=(s,i)=>De(s,n.codec(),i)})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=Ue((n,o,s={})=>{if(s.lengthDelimited!==!1&&o.fork(),n.peerId!=null&&n.peerId.byteLength>0&&(o.uint32(10),o.bytes(n.peerId)),n.seq!=null&&n.seq!==0n&&(o.uint32(16),o.uint64(n.seq)),n.addresses!=null)for(let i of n.addresses)o.uint32(26),r.AddressInfo.codec().encode(i,o);s.lengthDelimited!==!1&&o.ldelim()},(n,o,s={})=>{let i={peerId:ce(0),seq:0n,addresses:[]},a=o==null?n.len:n.pos+o;for(;n.pos<a;){let c=n.uint32();switch(c>>>3){case 1:{i.peerId=n.bytes();break}case 2:{i.seq=n.uint64();break}case 3:{if(s.limits?.addresses!=null&&i.addresses.length===s.limits.addresses)throw new mr('Decode error - map field "addresses" had too many elements');i.addresses.push(r.AddressInfo.codec().decode(n,n.uint32(),{limits:s.limits?.addresses$}));break}default:{n.skipType(c&7);break}}}return i})),t),r.encode=n=>Me(n,r.codec()),r.decode=(n,o)=>De(n,r.codec(),o)})(bo||(bo={}));var Er=class r{static createFromProtobuf=e=>{let t=bo.decode(e),n=sn(tt(t.peerId)),o=(t.addresses??[]).map(i=>ne(i.multiaddr)),s=t.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=Zd;static CODEC=Xd;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(e){let{peerId:t,multiaddrs:n,seqNumber:o}=e;this.peerId=t,this.multiaddrs=n??[],this.seqNumber=o??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=bo.encode({peerId:this.peerId.toMultihash().bytes,seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))})),this.marshaled}equals(e){return!(!(e instanceof r)||!this.peerId.equals(e.peerId)||this.seqNumber!==e.seqNumber||!jd(this.multiaddrs,e.multiaddrs))}};function cw(r){return r[Symbol.asyncIterator]!=null}function lw(r){if(cw(r))return(async()=>{let t=[];for await(let n of r)t.push(n);return t})();let e=[];for(let t of r)e.push(t);return e}var xo=lw;var tr={},gn=r=>{r.addEventListener("message",e=>{gn.dispatchEvent("message",r,e)}),r.port!=null&&r.port.addEventListener("message",e=>{gn.dispatchEvent("message",r,e)})};gn.addEventListener=(r,e)=>{tr[r]==null&&(tr[r]=[]),tr[r].push(e)};gn.removeEventListener=(r,e)=>{tr[r]!=null&&(tr[r]=tr[r].filter(t=>t===e))};gn.dispatchEvent=function(r,e,t){tr[r]!=null&&tr[r].forEach(n=>n(e,t))};var $l=gn;var Kl="lock:worker:request-read",ql="lock:worker:release-read",zl="lock:master:grant-read",Gl="lock:worker:request-write",Wl="lock:worker:release-write",jl="lock:master:grant-write";var Yd=(r=21)=>Math.random().toString().substring(2);var Jd=(r,e,t,n,o)=>(s,i)=>{if(i.data.type!==t)return;let a={type:i.data.type,name:i.data.name,identifier:i.data.identifier};r.dispatchEvent(new MessageEvent(e,{data:{name:a.name,handler:async()=>{s.postMessage({type:o,name:a.name,identifier:a.identifier}),await new Promise(c=>{let u=f=>{if(f==null||f.data==null)return;let l={type:f.data.type,name:f.data.name,identifier:f.data.identifier};l.type===n&&l.identifier===a.identifier&&(s.removeEventListener("message",u),c())};s.addEventListener("message",u)})}}}))},Qd=(r,e,t,n)=>async()=>{let o=Yd();return globalThis.postMessage({type:e,identifier:o,name:r}),new Promise(s=>{let i=a=>{if(a==null||a.data==null)return;let c={type:a.data.type,identifier:a.data.identifier};c.type===t&&c.identifier===o&&(globalThis.removeEventListener("message",i),s(()=>{globalThis.postMessage({type:n,identifier:o,name:r})}))};globalThis.addEventListener("message",i)})},uw={singleProcess:!1},ep=r=>{if(r=Object.assign({},uw,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return $l.addEventListener("message",Jd(t,"requestReadLock",Kl,ql,zl)),$l.addEventListener("message",Jd(t,"requestWriteLock",Gl,Wl,jl)),t}return{isWorker:!0,readLock:t=>Qd(t,Kl,zl,ql),writeLock:t=>Qd(t,Gl,jl,Wl)}};var Ar={},rr;async function Zl(r,e){let t,n=new Promise(o=>{t=o});return r.add(async()=>ho((async()=>{await new Promise(o=>{t(()=>{o()})})})(),{milliseconds:e.timeout})),n}var fw=(r,e)=>{if(rr.isWorker===!0)return{readLock:rr.readLock(r,e),writeLock:rr.writeLock(r,e)};let t=new er({concurrency:1}),n;return{async readLock(){if(n!=null)return Zl(n,e);n=new er({concurrency:e.concurrency,autoStart:!1});let o=n,s=Zl(n,e);return t.add(async()=>{o.start(),await o.onIdle().then(()=>{n===o&&(n=null)})}),s},async writeLock(){return n=null,Zl(t,e)}}},hw={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function Xl(r){let e=Object.assign({},hw,r);return rr==null&&(rr=ep(e),rr.isWorker!==!0&&(rr.addEventListener("requestReadLock",t=>{Ar[t.data.name]!=null&&Ar[t.data.name].readLock().then(async n=>t.data.handler().finally(()=>{n()}))}),rr.addEventListener("requestWriteLock",async t=>{Ar[t.data.name]!=null&&Ar[t.data.name].writeLock().then(async n=>t.data.handler().finally(()=>{n()}))}))),Ar[e.name]==null&&(Ar[e.name]=fw(e.name,e)),Ar[e.name]}var yn;(function(r){let e;(function(o){let s;o.codec=()=>(s==null&&(s=Ue((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&i.value.byteLength>0&&(a.uint32(18),a.bytes(i.value)),c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let u={key:"",value:ce(0)},f=a==null?i.len:i.pos+a;for(;i.pos<f;){let l=i.uint32();switch(l>>>3){case 1:{u.key=i.string();break}case 2:{u.value=i.bytes();break}default:{i.skipType(l&7);break}}}return u})),s),o.encode=i=>Me(i,o.codec()),o.decode=(i,a)=>De(i,o.codec(),a)})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(o){let s;o.codec=()=>(s==null&&(s=Ue((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&(a.uint32(18),Ti.codec().encode(i.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let u={key:""},f=a==null?i.len:i.pos+a;for(;i.pos<f;){let l=i.uint32();switch(l>>>3){case 1:{u.key=i.string();break}case 2:{u.value=Ti.codec().decode(i,i.uint32(),{limits:c.limits?.value});break}default:{i.skipType(l&7);break}}}return u})),s),o.encode=i=>Me(i,o.codec()),o.decode=(i,a)=>De(i,o.codec(),a)})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Ue((o,s,i={})=>{if(i.lengthDelimited!==!1&&s.fork(),o.addresses!=null)for(let a of o.addresses)s.uint32(10),Ci.codec().encode(a,s);if(o.protocols!=null)for(let a of o.protocols)s.uint32(18),s.string(a);if(o.publicKey!=null&&(s.uint32(34),s.bytes(o.publicKey)),o.peerRecordEnvelope!=null&&(s.uint32(42),s.bytes(o.peerRecordEnvelope)),o.metadata!=null&&o.metadata.size!==0)for(let[a,c]of o.metadata.entries())s.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},s);if(o.tags!=null&&o.tags.size!==0)for(let[a,c]of o.tags.entries())s.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},s);i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={addresses:[],protocols:[],metadata:new Map,tags:new Map},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let u=o.uint32();switch(u>>>3){case 1:{if(i.limits?.addresses!=null&&a.addresses.length===i.limits.addresses)throw new mr('Decode error - map field "addresses" had too many elements');a.addresses.push(Ci.codec().decode(o,o.uint32(),{limits:i.limits?.addresses$}));break}case 2:{if(i.limits?.protocols!=null&&a.protocols.length===i.limits.protocols)throw new mr('Decode error - map field "protocols" had too many elements');a.protocols.push(o.string());break}case 4:{a.publicKey=o.bytes();break}case 5:{a.peerRecordEnvelope=o.bytes();break}case 6:{if(i.limits?.metadata!=null&&a.metadata.size===i.limits.metadata)throw new Hn('Decode error - map field "metadata" had too many elements');let f=r.Peer$metadataEntry.codec().decode(o,o.uint32());a.metadata.set(f.key,f.value);break}case 7:{if(i.limits?.tags!=null&&a.tags.size===i.limits.tags)throw new Hn('Decode error - map field "tags" had too many elements');let f=r.Peer$tagsEntry.codec().decode(o,o.uint32(),{limits:{value:i.limits?.tags$value}});a.tags.set(f.key,f.value);break}default:{o.skipType(u&7);break}}}return a})),n),r.encode=o=>Me(o,r.codec()),r.decode=(o,s)=>De(o,r.codec(),s)})(yn||(yn={}));var Ci;(function(r){let e;r.codec=()=>(e==null&&(e=Ue((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.multiaddr!=null&&t.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(t.multiaddr)),t.isCertified!=null&&(n.uint32(16),n.bool(t.isCertified)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={multiaddr:ce(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.multiaddr=t.bytes();break}case 2:{s.isCertified=t.bool();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Me(t,r.codec()),r.decode=(t,n)=>De(t,r.codec(),n)})(Ci||(Ci={}));var Ti;(function(r){let e;r.codec=()=>(e==null&&(e=Ue((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.value!=null&&t.value!==0&&(n.uint32(8),n.uint32(t.value)),t.expiry!=null&&(n.uint32(16),n.uint64(t.expiry)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={value:0},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.value=t.uint32();break}case 2:{s.expiry=t.uint64();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Me(t,r.codec()),r.decode=(t,n)=>De(t,r.codec(),n)})(Ti||(Ti={}));function wn(r,e){let t=yn.decode(e);if(t.publicKey!=null&&r.publicKey==null){let s=on(t.publicKey);r=il(s)}let n=new Map,o=BigInt(Date.now());for(let[s,i]of t.tags.entries())i.expiry!=null&&i.expiry<o||n.set(s,i);return{...t,id:r,addresses:t.addresses.map(({multiaddr:s,isCertified:i})=>({multiaddr:ne(s),isCertified:i??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}var Ut="/",tp=new TextEncoder().encode(Ut),Li=tp[0],Sr=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=P(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==Li)throw new Error("Invalid key")}toString(e="utf8"){return H(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Ut))}static random(){return new r(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new r(e):typeof e.uint8Array=="function"?new r(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=tp),this._buf[0]!==Li){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Li,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Li;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let o=0;o<t.length;o++){if(n.length<o+1)return!1;let s=t[o],i=n[o];if(s<i)return!0;if(s>i)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Ut).slice(1)}type(){return dw(this.baseNamespace())}name(){return pw(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Ut)||(e+=Ut),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Ut):new r(e.slice(0,-1).join(Ut))}child(e){return this.toString()===Ut?e:e.toString()===Ut?this:new r(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()===this.toString()?!1:e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()===this.toString()?!1:this.toString().startsWith(e.toString())}isTopLevel(){return this.list().length===1}concat(...e){return r.withNamespaces([...this.namespaces(),...mw(e.map(t=>t.namespaces()))])}};function dw(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function pw(r){let e=r.split(":");return e[e.length-1]}function mw(r){return[].concat(...r)}var Yl="/peers/";function bn(r){if(!Ro(r)||r.type==null)throw new D("Invalid PeerId");let e=r.toCID().toString();return new Sr(`${Yl}${e}`)}async function rp(r,e,t){let n=new Map;for(let o of t){if(o==null)continue;if(o.multiaddr instanceof Uint8Array&&(o.multiaddr=ne(o.multiaddr)),!Qt(o.multiaddr))throw new D("Multiaddr was invalid");if(!await e(r,o.multiaddr))continue;let s=o.isCertified??!1,i=o.multiaddr.toString(),a=n.get(i);a!=null?o.isCertified=a.isCertified||s:n.set(i,{multiaddr:o.multiaddr,isCertified:s})}return[...n.values()].sort((o,s)=>o.multiaddr.toString().localeCompare(s.multiaddr.toString())).map(({isCertified:o,multiaddr:s})=>({isCertified:o,multiaddr:s.bytes}))}async function Pi(r,e,t,n){if(e==null)throw new D("Invalid PeerData");if(e.publicKey!=null&&r.publicKey!=null&&!e.publicKey.equals(r.publicKey))throw new D("publicKey bytes do not match peer id publicKey bytes");let o=n.existingPeer;if(o!=null&&!r.equals(o.id))throw new D("peer id did not match existing peer id");let s=o?.addresses??[],i=new Set(o?.protocols??[]),a=o?.metadata??new Map,c=o?.tags??new Map,u=o?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(s=[],e.multiaddrs!=null&&s.push(...e.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&s.push(...e.addresses)),e.protocols!=null&&(i=new Set(e.protocols)),e.metadata!=null){let d=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=Ni(d,{validate:np})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=Ni(d,{validate:op,map:sp})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&s.push(...e.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&s.push(...e.addresses),e.protocols!=null&&(i=new Set([...i,...e.protocols])),e.metadata!=null){let d=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[h,p]of d)p==null?a.delete(h):a.set(h,p);a=Ni([...a.entries()],{validate:np})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),h=new Map(c);for(let[p,m]of d)m==null?h.delete(p):h.set(p,m);c=Ni([...h.entries()],{validate:op,map:sp})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}let f;o?.id.publicKey!=null?f=ft(o.id.publicKey):e.publicKey!=null?f=ft(e.publicKey):r.publicKey!=null&&(f=ft(r.publicKey));let l={addresses:await rp(r,n.addressFilter??(async()=>!0),s),protocols:[...i.values()].sort((d,h)=>d.localeCompare(h)),metadata:a,tags:c,publicKey:f,peerRecordEnvelope:u};return r.type!=="RSA"&&delete l.publicKey,l}function Ni(r,e){let t=new Map;for(let[n,o]of r)o!=null&&e.validate(n,o);for(let[n,o]of r.sort(([s],[i])=>s.localeCompare(i)))o!=null&&t.set(n,e.map?.(n,o)??o);return t}function np(r,e){if(typeof r!="string")throw new D("Metadata key must be a string");if(!(e instanceof Uint8Array))throw new D("Metadata value must be a Uint8Array")}function op(r,e){if(typeof r!="string")throw new D("Tag name must be a string");if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new D("Tag value must be an integer");if(e.value<0||e.value>100)throw new D("Tag value must be between 0-100")}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new D("Tag ttl must be an integer");if(e.ttl<0)throw new D("Tag ttl must be between greater than 0")}}function sp(r,e){let t;return e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl))),{value:e.value??0,expiry:t}}function Ri(r,e,t){let n=r.toString().split("/")[2],o=pe.parse(n,ze),s=ri(o),i=t.get(s);if(i!=null)return i;let a=wn(s,e);return t.set(s,a),a}function gw(r,e){return r==null?{}:{prefix:Yl,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(Ri(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(Ri(n.key,n.value,e),Ri(o.key,o.value,e)))}}var Di=class{peerId;datastore;lock;addressFilter;constructor(e,t={}){this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=Xl({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(bn(e))}async delete(e){if(this.peerId.equals(e))throw new D("Cannot delete self peer");await this.datastore.delete(bn(e))}async load(e){let t=await this.datastore.get(bn(e));return wn(e,t)}async save(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await Pi(e,t,"patch",{addressFilter:this.addressFilter});return this.#t(e,s,n,o)}async patch(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await Pi(e,t,"patch",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,n,o)}async merge(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await Pi(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,n,o)}async*all(e){let t=new ct;for await(let{key:n,value:o}of this.datastore.query(gw(e??{},t))){let s=Ri(n,o,t);s.id.equals(this.peerId)||(yield s)}}async#e(e){try{let t=await this.datastore.get(bn(e)),n=wn(e,t);return{existingBuf:t,existingPeer:n}}catch(t){if(t.name!=="NotFoundError")throw t}return{}}async#t(e,t,n,o){let s=yn.encode(t);return n!=null&&ie(s,n)?{peer:wn(e,s),previous:o,updated:!1}:(await this.datastore.put(bn(e),s),{peer:wn(e,s),previous:o,updated:!0})}};var Mi=class{store;events;peerId;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.events=e.events,this.peerId=e.peerId,this.store=new Di(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){this.log.trace("forEach await read lock");let n=await this.store.lock.readLock();this.log.trace("forEach got read lock");try{for await(let o of this.store.all(t))e(o)}finally{this.log.trace("forEach release read lock"),n()}}async all(e){this.log.trace("all await read lock");let t=await this.store.lock.readLock();this.log.trace("all got read lock");try{return await xo(this.store.all(e))}finally{this.log.trace("all release read lock"),t()}}async delete(e){this.log.trace("delete await write lock");let t=await this.store.lock.writeLock();this.log.trace("delete got write lock");try{await this.store.delete(e)}finally{this.log.trace("delete release write lock"),t()}}async has(e){this.log.trace("has await read lock");let t=await this.store.lock.readLock();this.log.trace("has got read lock");try{return await this.store.has(e)}finally{this.log.trace("has release read lock"),t()}}async get(e){this.log.trace("get await read lock");let t=await this.store.lock.readLock();this.log.trace("get got read lock");try{return await this.store.load(e)}finally{this.log.trace("get release read lock"),t()}}async save(e,t){this.log.trace("save await write lock");let n=await this.store.lock.writeLock();this.log.trace("save got write lock");try{let o=await this.store.save(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("save release write lock"),n()}}async patch(e,t){this.log.trace("patch await write lock");let n=await this.store.lock.writeLock();this.log.trace("patch got write lock");try{let o=await this.store.patch(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("patch release write lock"),n()}}async merge(e,t){this.log.trace("merge await write lock");let n=await this.store.lock.writeLock();this.log.trace("merge got write lock");try{let o=await this.store.merge(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("merge release write lock"),n()}}async consumePeerRecord(e,t){let n=await mn.openAndCertify(e,Er.DOMAIN),o=ri(n.publicKey.toCID());if(t?.equals(o)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",t,o),!1;let s=Er.createFromProtobuf(n.payload),i;try{i=await this.get(o)}catch(a){if(a.name!=="NotFoundError")throw a}if(i?.peerRecordEnvelope!=null){let a=await mn.createFromProtobuf(i.peerRecordEnvelope),c=Er.createFromProtobuf(a.payload);if(c.seqNumber>=s.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",c.seqNumber,s.seqNumber),!1}return await this.patch(s.peerId,{peerRecordEnvelope:e,addresses:s.multiaddrs.map(a=>({isCertified:!0,multiaddr:a}))}),!0}#e(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}};var Ui=class extends Error{constructor(e="Not Found"){super(e),this.name="NotFoundError"}};function yw(r){return r[Symbol.asyncIterator]!=null}function ww(r){if(yw(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Jl=ww;function bw(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var ip=bw;function xw(r){return r[Symbol.asyncIterator]!=null}function vw(r,e){let t=0;if(xw(r))return async function*(){for await(let c of r)await e(c,t++)&&(yield c)}();let n=ip(r),{value:o,done:s}=n.next();if(s===!0)return function*(){}();let i=e(o,t++);if(typeof i.then=="function")return async function*(){await i&&(yield o);for await(let c of n)await e(c,t++)&&(yield c)}();let a=e;return function*(){i===!0&&(yield o);for(let c of n)a(c,t++)&&(yield c)}()}var _r=vw;function Ew(r){return r[Symbol.asyncIterator]!=null}function Aw(r,e){return Ew(r)?async function*(){yield*(await xo(r)).sort(e)}():function*(){yield*xo(r).sort(e)}()}var Ql=Aw;function Sw(r){return r[Symbol.asyncIterator]!=null}function _w(r,e){return Sw(r)?async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}}():function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}}()}var eu=_w;var Oi=class{put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(let{key:n,value:o}of e)await this.put(n,o,t),yield n}async*getMany(e,t={}){for await(let n of e)yield{key:n,value:await this.get(n,t)}}async*deleteMany(e,t={}){for await(let n of e)await this.delete(n,t),yield n}batch(){let e=[],t=[];return{put(n,o){e.push({key:n,value:o})},delete(n){t.push(n)},commit:async n=>{await Jl(this.putMany(e,n)),e=[],await Jl(this.deleteMany(t,n)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let n=this._all(e,t);if(e.prefix!=null){let o=e.prefix;n=_r(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>_r(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>Ql(o,s),n)),e.offset!=null){let o=0,s=e.offset;n=_r(n,()=>o++>=s)}return e.limit!=null&&(n=eu(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let o=e.prefix;n=_r(n,s=>s.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>_r(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>Ql(o,s),n)),e.offset!=null){let o=e.offset,s=0;n=_r(n,()=>s++>=o)}return e.limit!=null&&(n=eu(n,e.limit)),n}};var Fi=class extends Oi{data;constructor(){super(),this.data=new Map}put(e,t){return this.data.set(e.toString(),t),e}get(e){let t=this.data.get(e.toString());if(t==null)throw new Ui;return t}has(e){return this.data.has(e.toString())}delete(e){this.data.delete(e.toString())}*_all(){for(let[e,t]of this.data.entries())yield{key:new Sr(e),value:t}}*_allKeys(){for(let e of this.data.keys())yield new Sr(e)}};function ap(r,e){let t;return function(){let n=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(n,e)}}var Bw=r=>r;function tu(r,e){let t=r.getPeerId();return t!=null&>(t).equals(e)&&(r=r.decapsulate(ne(`/p2p/${e.toString()}`))),r}var Vi=class{log;components;listen;announce;observed;announceFilter;constructor(e,t={}){let{listen:n=[],announce:o=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(s=>s.toString()),this.announce=new Set(o.map(s=>s.toString())),this.observed=new Map,this.announceFilter=t.announceFilter??Bw,this._updatePeerStoreAddresses=ap(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){let e=this.getAnnounceAddrs().concat(this.components.transportManager.getAddrs()).concat([...this.observed.entries()].filter(([t,n])=>n.confident).map(([t])=>ne(t))).map(t=>t.getPeerId()===this.components.peerId.toString()?t.decapsulate(`/p2p/${this.components.peerId.toString()}`):t);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(t=>{this.log.error("error updating addresses",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>ne(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>ne(e))}getObservedAddrs(){return Array.from(this.observed).map(([e])=>ne(e))}addObservedAddr(e){e=tu(e,this.components.peerId);let t=e.toString();this.observed.has(t)||this.observed.set(t,{confident:!1})}confirmObservedAddr(e){e=tu(e,this.components.peerId);let t=e.toString(),o=(this.observed.get(t)??{confident:!1}).confident;this.observed.set(t,{confident:!0}),o||this._updatePeerStoreAddresses()}removeObservedAddr(e){e=tu(e,this.components.peerId);let t=e.toString();this.observed.delete(t)}getAddresses(){let e=this.getAnnounceAddrs().map(n=>n.toString());e.length===0&&(e=this.components.transportManager.getAddrs().map(n=>n.toString())),e=e.concat(Array.from(this.observed).filter(([n,o])=>o.confident).map(([n])=>n));let t=new Set(e);return this.announceFilter(Array.from(t).map(n=>ne(n))).map(n=>n.protos().pop()?.path===!0||n.getPeerId()===this.components.peerId.toString()?n:n.encapsulate(`/p2p/${this.components.peerId.toString()}`))}};var cp;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(cp||(cp={}));var Hi=class extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}},$i=class extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}},vo=class extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}},Eo=class extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}},Ki=class extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}},qi=class extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}},zi=class extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}},Ao=class extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}},Br=class extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}},So=class extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}},Gi=class extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}},kr=class extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}},_o=class extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}},Wi=class extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}};var ru=class{components={};_started=!1;constructor(e={}){this.components={};for(let[t,n]of Object.entries(e))this.components[t]=n;this.components.logger==null&&(this.components.logger=Ai())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>qo(t)).map(async t=>{await t[e]?.()}))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}},Iw=["metrics","connectionProtector","dns"],Cw=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function lp(r={}){let e=new ru(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!Cw.includes(o)){let i=e.components[o];if(i==null&&!Iw.includes(o))throw new Hi(`${o} not set`);return i}return Reflect.get(n,o,s)},set(n,o,s){return typeof o=="string"?e.components[o]=s:Reflect.set(n,o,s),!0}})}function up(r){let e={};for(let t of Object.values(r.components))for(let n of Tw(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of Lw(t))if(e[n]!==!0)throw new $i(`Service "${Nw(t)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function Tw(r){return Array.isArray(r?.[In])?r[In]:[]}function Lw(r){return Array.isArray(r?.[Ma])?r[Ma]:[]}function Nw(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}function fp(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let t=e.stringTuples();return t[0][0]===4||t[0][0]===41?!!hi(`${t[0][1]}`):!1},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...r}}var hp=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},Pw=new WeakMap;function Rw({clearTimeout:r,setTimeout:e}={}){return(t,{value:n,signal:o}={})=>{if(o?.aborted)return Promise.reject(hp());let s,i,a,c=r??clearTimeout,u=()=>{c(s),a(hp())},f=()=>{o&&o.removeEventListener("abort",u)},l=new Promise((d,h)=>{i=()=>{f(),d(n)},a=h,s=(e??setTimeout)(i,t)});return o&&o.addEventListener("abort",u,{once:!0}),Pw.set(l,()=>{c(s),s=null,i()}),l}}var Dw=Rw(),dp=Dw;var ji=class extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(e="Rate limit exceeded",t){super(e),this.name="RateLimitError",this.remainingPoints=t.remainingPoints,this.msBeforeNext=t.msBeforeNext,this.consumedPoints=t.consumedPoints,this.isFirstInDuration=t.isFirstInDuration}};var Zi=class{memoryStorage;points;duration;blockDuration;execEvenly;execEvenlyMinDelayMs;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.execEvenly=e.execEvenly??!1,this.execEvenlyMinDelayMs=e.execEvenlyMinDelayMs??this.duration*1e3/this.points,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new nu}async consume(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+t&&(i=this.memoryStorage.set(o,i.consumedPoints,this.blockDuration)),new ji("Rate limit exceeded",i);if(this.execEvenly&&i.msBeforeNext>0&&!i.isFirstInDuration){let a=Math.ceil(i.msBeforeNext/(i.remainingPoints+2));a<this.execEvenlyMinDelayMs&&(a=i.consumedPoints*this.execEvenlyMinDelayMs),await dp(a)}return i}penalty(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,-t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(e,t){let n=t*1e3,o=this.points+1;return this.memoryStorage.set(this.getKey(e),o,t),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:o,isFirstInDuration:!1}}set(e,t,n=0){let o=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,n),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:t,isFirstInDuration:!1}}get(e){let t=this.memoryStorage.get(this.getKey(e));return t!=null&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return e?.customDuration!=null&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.substring(this.keyPrefix.length)}},nu=class{storage;constructor(){this.storage=new Map}incrby(e,t,n){let o=this.storage.get(e);if(o!=null){let s=o.expiresAt!=null?o.expiresAt.getTime()-new Date().getTime():-1;return o.expiresAt==null||s>0?(o.value+=t,{remainingPoints:0,msBeforeNext:s,consumedPoints:o.value,isFirstInDuration:!1}):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let o=n*1e3,s=this.storage.get(e);s!=null&&clearTimeout(s.timeoutId);let i={value:t,expiresAt:o>0?new Date(Date.now()+o):void 0};return this.storage.set(e,i),o>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(e)},o),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:i.value,isFirstInDuration:!0}}get(e){let t=this.storage.get(e);if(t!=null)return{remainingPoints:0,msBeforeNext:t.expiresAt!=null?t.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){let t=this.storage.get(e);return t!=null?(t.timeoutId!=null&&clearTimeout(t.timeoutId),this.storage.delete(e),!0):!1}};function Xi(r){if(Ro(r))return{peerId:r,multiaddrs:[]};Array.isArray(r)||(r=[r]);let e;if(r.length>0){let t=r[0].getPeerId();e=t==null?void 0:gt(t),r.forEach(n=>{if(!Qt(n))throw new Rr("Invalid multiaddr");let o=n.getPeerId();if(o==null){if(e!=null)throw new D("Multiaddrs must all have the same peer id or have no peer id")}else{let s=gt(o);if(e?.equals(s)!==!0)throw new D("Multiaddrs must all have the same peer id or have no peer id")}})}return{peerId:e,multiaddrs:r}}var Mw=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function pp(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??Mw;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}var mp="last-dial-failure",gp="last-dial-success";var Yi=100,Ji=50;var yp={maxConnections:Yi,allow:[]},Qi=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??yp.maxConnections,this.allow=t.allow??yp.allow,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),e.events.addEventListener("connection:open",()=>{this.maybePruneConnections().catch(n=>{this.log.error(n)})})}async maybePruneConnections(){let e=this.connectionManager.getConnections(),t=e.length;if(this.log("checking max connections limit %d/%d",t,this.maxConnections),t<=this.maxConnections)return;let n=new ct;for(let a of e){let c=a.remotePeer;if(!n.has(c)){n.set(c,0);try{let u=await this.peerStore.get(c);n.set(c,[...u.tags.values()].reduce((f,l)=>f+l.value,0))}catch(u){u.name!=="NotFoundError"&&this.log.error("error loading peer tags",u)}}}let o=this.sortConnections(e,n),s=Math.max(t-this.maxConnections,0),i=[];for(let a of o)if(this.log("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(u=>a.remoteAddr.toString().startsWith(u.toString()))||i.push(a),i.length===s)break;await Promise.all(i.map(async a=>{await pp(a,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:i})}sortConnections(e,t){return e.sort((n,o)=>{let s=n.timeline.open,i=o.timeline.open;return s<i?1:s>i?-1:0}).sort((n,o)=>n.direction==="outbound"&&o.direction==="inbound"?1:n.direction==="inbound"&&o.direction==="outbound"?-1:0).sort((n,o)=>n.streams.length>o.streams.length?1:n.streams.length<o.streams.length?-1:0).sort((n,o)=>{let s=t.get(n.remotePeer)??0,i=t.get(o.remotePeer)??0;return s>i?1:s<i?-1:0})}};function le(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var ea=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)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}},xn=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new ea(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 ea(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 ou=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function ta(r={}){return Uw(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 Uw(r,e){e=e??{};let t=e.onEnd,n=new xn,o,s,i,a=le(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((g,y)=>{s=b=>{s=null,n.push(b);try{g(r(n))}catch(w){y(w)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=le()})}},u=g=>s!=null?s(g):(n.push(g),o),f=g=>(n=new xn,s!=null?s({error:g}):(n.push({error:g}),o)),l=g=>{if(i)return o;if(e?.objectMode!==!0&&g?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:g})},d=g=>i?o:(i=!0,g!=null?f(g):u({done:!0})),h=()=>(n=new xn,d(),{done:!0}),p=g=>(d(g),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:p,push:l,end:d,get readableLength(){return n.size},onEmpty:async g=>{let y=g?.signal;if(y?.throwIfAborted(),n.isEmpty())return;let b,w;y!=null&&(b=new Promise((x,A)=>{w=()=>{A(new ou)},y.addEventListener("abort",w)}));try{await Promise.race([a.promise,b])}finally{w!=null&&y!=null&&y?.removeEventListener("abort",w)}}},t==null)return o;let m=o;return o={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(g){return m.throw(g),t!=null&&(t(g),t=void 0),{done:!0}},return(){return m.return(),t!=null&&(t(),t=void 0),{done:!0}},push:l,end(g){return m.end(g),t!=null&&(t(g),t=void 0),o},get readableLength(){return m.readableLength},onEmpty:g=>m.onEmpty(g)},o}var su=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=t??"ABORT_ERR"}};async function vn(r,e,t,n){let o=new su(n?.errorMessage,n?.errorCode);return t?.aborted===!0?Promise.reject(o):new Promise((s,i)=>{function a(){t?.removeEventListener("abort",f),r.removeEventListener(e,c),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,u)}let c=l=>{try{if(n?.filter?.(l)===!1)return}catch(d){a(),i(d);return}a(),s(l)},u=l=>{a(),i(l.detail)},f=()=>{a(),i(o)};t?.addEventListener("abort",f),r.addEventListener(e,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,u)})}var ra=class extends Error{type;code;constructor(e,t,n){super(e??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=t??"ABORT_ERR"}};async function nr(r,e,t){if(e==null)return r;if(e.aborted)return Promise.reject(new ra(t?.errorMessage,t?.errorCode,t?.errorName));let n,o=new ra(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var na=class{deferred;signal;constructor(e){this.signal=e,this.deferred=le(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new bt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Ow(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var oa=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=Ow(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,oe(1/0,this.controller.signal),this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new bt),this.cleanup())}async join(e={}){let t=new na(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await nr(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var En=class extends vt{concurrency;queue;pending;sort;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.pending=0,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[]}tryToStartAnother(){if(this.size===0)return queueMicrotask(()=>{this.safeDispatchEvent("empty")}),this.running===0&&queueMicrotask(()=>{this.safeDispatchEvent("idle")}),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,t){t?.signal?.throwIfAborted();let n=new oa(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(t).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("error",{detail:o}),this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new bt)}),this.clear()}async onEmpty(e){this.size!==0&&await vn(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await vn(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await vn(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=ta({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},s=c=>{n(c.detail)},i=()=>{n()},a=()=>{n(new bt("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("error",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("error",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var sa=class extends En{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};function Ir(r){let e=new globalThis.AbortController;function t(){e.abort();for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}for(let s of r){if(s?.aborted===!0){t();break}s?.addEventListener!=null&&s.addEventListener("abort",t)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}async function wp(r,e){let t=!1;for(let o of fn.keys())if(t=r.protoNames().includes(o),t)break;if(!t)return[r];let n=await r.resolve(e);return e.log("resolved %s to",r,n.map(o=>o.toString())),n}var Bo={addressSorter:hn,maxParallelDials:Ji,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:5e3,resolvers:{dnsaddr:yr}},ia=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(e,t={}){this.addressSorter=t.addressSorter??Bo.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??Bo.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??Bo.maxDialQueueLength,this.dialTimeout=t.dialTimeout??Bo.dialTimeout,this.connections=t.connections??new ct,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.shutDownController=new AbortController,oe(1/0,this.shutDownController.signal);for(let[n,o]of Object.entries(t.resolvers??{}))fn.set(n,o);this.queue=new sa({concurrency:t.maxParallelDials??Bo.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("error",n=>{this.log.error("error in dial queue",n.detail)})}start(){this.shutDownController=new AbortController,oe(1/0,this.shutDownController.signal)}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:o}=Xi(e),s=Array.from(this.connections.values()).flat().find(a=>t.force===!0?!1:a.remotePeer.equals(n)?!0:o.find(c=>c.equals(a.remoteAddr)));if(s!=null)return this.log("already connected to %a",s.remoteAddr),t.onProgress?.(new fe("dial-queue:already-connected")),s;let i=this.queue.queue.find(a=>{if(n?.equals(a.options.peerId)===!0)return!0;let c=a.options.multiaddrs;if(c==null)return!1;for(let u of o)if(c.has(u.toString()))return!0;return!1});if(i!=null){this.log("joining existing dial target for %p",n);for(let a of o)i.options.multiaddrs.add(a.toString());return t.onProgress?.(new fe("dial-queue:already-in-dial-queue")),i.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new Mr("Dial queue is full");return this.log("creating dial target for %p",n,o.map(a=>a.toString())),t.onProgress?.(new fe("dial-queue:add-to-dial-queue")),this.queue.add(async a=>{a?.onProgress?.(new fe("dial-queue:start-dial"));let c=this.createDialAbortController(a?.signal),u;try{u=await this.calculateMultiaddrs(n,a?.multiaddrs,{...a,signal:c}),a?.onProgress?.(new fe("dial-queue:calculated-addresses",u)),u.map(({multiaddr:f})=>f.toString()).forEach(f=>{a?.multiaddrs.add(f)})}catch(f){throw c.clear(),f}try{let f=0,l=[];for(let d of u){if(f===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",f,n),new Mr("Peer had more than maxPeerAddrsToDial");f++;try{let h=await this.components.transportManager.dial(d.multiaddr,{...a,signal:c});this.log("dial to %a succeeded",d.multiaddr);try{await this.components.peerStore.merge(h.remotePeer,{multiaddrs:[h.remoteAddr],metadata:{[gp]:P(Date.now().toString())}})}catch(p){this.log.error("could not update last dial failure key for %p",n,p)}return h}catch(h){if(this.log.error("dial failed to %a",d.multiaddr,h),n!=null)try{await this.components.peerStore.merge(n,{metadata:{[mp]:P(Date.now().toString())}})}catch(p){this.log.error("could not update last dial failure key for %p",n,p)}if(c.aborted)throw new Dr(h.message);l.push(h)}}throw l.length===1?l[0]:new AggregateError(l,"All multiaddr dials failed")}finally{c.clear()}},{peerId:n,priority:t.priority??lu,multiaddrs:new Set(o.map(a=>a.toString())),signal:t.signal,onProgress:t.onProgress})}createDialAbortController(e){let t=Ir([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e]);return oe(1/0,t),t}async calculateMultiaddrs(e,t=new Set,n={}){let o=[...t].map(l=>({multiaddr:ne(l),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new Mr("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new Ao("The dial request is blocked by gater.allowDialPeer");if(o.length===0){this.log("loading multiaddrs for %p",e);try{let l=await this.components.peerStore.get(e);o.push(...l.addresses),this.log("loaded multiaddrs for %p",e,o.map(({multiaddr:d})=>d.toString()))}catch(l){if(l.name!=="NotFoundError")throw l}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let l=await this.components.peerRouting.findPeer(e);this.log("found multiaddrs for %p in the peer routing",e,o.map(({multiaddr:d})=>d.toString())),o.push(...l.multiaddrs.map(d=>({multiaddr:d,isCertified:!1})))}catch(l){l.name!=="NoPeerRoutersError"&&this.log.error("looking up multiaddrs for %p in the peer routing failed",e,l)}}}let s=(await Promise.all(o.map(async l=>{let d=await wp(l.multiaddr,{dns:this.components.dns,...n,log:this.log});return d.length===1&&d[0].equals(l.multiaddr)?l:d.map(h=>({multiaddr:h,isCertified:!1}))}))).flat();if(e!=null){let l=`/p2p/${e.toString()}`;s=s.map(d=>d.multiaddr.protos().pop()?.path===!0?d:d.multiaddr.getPeerId()==null?{multiaddr:d.multiaddr.encapsulate(l),isCertified:d.isCertified}:d)}let i=s.filter(l=>{if(this.components.transportManager.dialTransportForMultiaddr(l.multiaddr)==null)return!1;let d=l.multiaddr.getPeerId();return e!=null&&d!=null?e.equals(d):!0}),a=new Map;for(let l of i){let d=l.multiaddr.toString(),h=a.get(d);if(h!=null){h.isCertified=h.isCertified||l.isCertified||!1;continue}a.set(d,l)}let c=[...a.values()];if(c.length===0)throw new Br("The dial request has no valid addresses");let u=[];for(let l of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(l.multiaddr)||u.push(l);let f=u.sort(this.addressSorter);if(f.length===0)throw new Ao("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",e??"unknown peer",s.map(({multiaddr:l})=>l.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",f.map(({multiaddr:l})=>l.toString())),f}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let n=await this.calculateMultiaddrs(void 0,new Set(e.map(o=>o.toString())),t);return t.runOnLimitedConnection===!1?n.find(o=>!co.matches(o.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var aa=class extends En{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var _p=sr(Ap(),1);var Vw=Object.prototype.toString,Hw=r=>Vw.call(r)==="[object Error]",$w=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Load failed","Network request failed","fetch failed","terminated"]);function uu(r){return r&&Hw(r)&&r.name==="TypeError"&&typeof r.message=="string"?r.message==="Load failed"?r.stack===void 0:$w.has(r.message):!1}var fu=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}},Sp=(r,e,t)=>{let n=t.retries-(e-1);return r.attemptNumber=e,r.retriesLeft=n,r};async function hu(r,e){return new Promise((t,n)=>{e={onFailedAttempt(){},retries:10,shouldRetry:()=>!0,...e};let o=_p.default.operation(e),s=()=>{o.stop(),n(e.signal?.reason)};e.signal&&!e.signal.aborted&&e.signal.addEventListener("abort",s,{once:!0});let i=()=>{e.signal?.removeEventListener("abort",s),o.stop()};o.attempt(async a=>{try{let c=await r(a);i(),t(c)}catch(c){try{if(!(c instanceof Error))throw new TypeError(`Non-error was thrown: "${c}". You should only throw errors.`);if(c instanceof fu)throw c.originalError;if(c instanceof TypeError&&!uu(c))throw c;if(Sp(c,a,e),await e.shouldRetry(c)||(o.stop(),n(c)),await e.onFailedAttempt(c),!o.retry(c))throw o.mainError()}catch(u){Sp(u,a,e),i(),n(u)}}})})}var ca=class{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.queue=new aa({concurrency:t.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:e.metrics}),this.started=!1,this.retries=t.retries??5,this.backoffFactor=t.backoffFactor,this.retryInterval=t.retryInterval,e.events.addEventListener("peer:disconnect",n=>{this.maybeReconnect(n.detail).catch(o=>{this.log.error("failed to maybe reconnect to %p",n.detail,o)})})}async maybeReconnect(e){!this.started||!(await this.peerStore.get(e)).tags.has(Da)||this.queue.has(e)||this.queue.add(async n=>{await hu(async o=>{if(this.started)try{await this.connectionManager.openConnection(e,{signal:n?.signal})}catch(s){throw this.log("reconnecting to %p attempt %d of %d failed",e,o,this.retries,s),s}},{signal:n?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:e}).catch(n=>{this.log.error("failed to reconnect to %p",e,n)})}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>t.tags.has(Da)]});await Promise.all(e.map(async t=>{await this.connectionManager.openConnection(t.id).catch(n=>{this.log.error(n)})}))}).catch(e=>{this.log.error(e)})}stop(){this.started=!1,this.queue.abort()}};var lu=50,du={maxConnections:Yi,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},la=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;reconnectQueue;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;constructor(e,t={}){if(this.maxConnections=t.maxConnections??du.maxConnections,this.maxConnections<1)throw new D("Connection Manager maxConnections must be greater than 0");this.connections=new ct,this.started=!1,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),this.allow=(t.allow??[]).map(n=>ne(n)),this.deny=(t.deny??[]).map(n=>ne(n)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??du.maxIncomingPendingConnections,this.inboundConnectionRateLimiter=new Zi({points:t.inboundConnectionThreshold??du.inboundConnectionThreshold,duration:1}),this.connectionPruner=new Qi({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new ia(e,{addressSorter:t.addressSorter??hn,maxParallelDials:t.maxParallelDials??Ji,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??5e3,resolvers:t.resolvers??{dnsaddr:yr},connections:this.connections}),this.reconnectQueue=new ca({events:e.events,peerStore:e.peerStore,logger:e.logger,connectionManager:this},{retries:t.reconnectRetries,retryInterval:t.reconnectRetryInterval,backoffFactor:t.reconnectBackoffFactor,maxParallelReconnects:t.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";isStarted(){return this.started}async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,outbound:0};for(let t of this.connections.values())for(let n of t)n.direction==="inbound"?e.inbound++:e.outbound++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let t of this.connections.values())for(let n of t)for(let o of n.streams){let s=`${o.direction} ${o.protocol??"unnegotiated"}`;e[s]=(e[s]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let e={};for(let n of this.connections.values())for(let o of n){let s={};for(let i of o.streams){let a=`${i.direction} ${i.protocol??"unnegotiated"}`;s[a]=(s[a]??0)+1}for(let[i,a]of Object.entries(s))e[i]=e[i]??[],e[i].push(a)}let t={};for(let[n,o]of Object.entries(e)){o=o.sort((i,a)=>i-a);let s=Math.floor(o.length*.9);t[n]=o[s]}return t}}),await Ru(this.dialQueue,this.reconnectQueue),this.started=!0,this.log("started")}async stop(){await Du(this.reconnectQueue,this.dialQueue);let e=[];for(let t of this.connections.values())for(let n of t)e.push((async()=>{try{await n.close()}catch(o){this.log.error(o)}})());this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}onConnect(e){this._onConnect(e).catch(t=>{this.log.error(t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}let n=t.remotePeer,o=this.connections.get(n),s=!1;o!=null?o.push(t):(s=!0,this.connections.set(n,[t])),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),s&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e;if(!this.started)return;let n=t.remotePeer,o=this.connections.get(n);o!=null&&o.length>1?(o=o.filter(s=>s.id!==t.id),this.connections.set(n,o)):o!=null&&(this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:t.remotePeer}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let t=[];for(let n of this.connections.values())t=t.concat(n);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.isStarted())throw new xt("Not started");t.signal?.throwIfAborted();let{peerId:n}=Xi(e);if(n!=null&&t.force!==!0){this.log("dial %p",n);let a=this.getConnections(n).find(c=>c.limits==null);if(a!=null)return this.log("had an existing non-limited connection to %p",n),t.onProgress?.(new fe("dial-queue:already-connected")),a}let o=await this.dialQueue.dial(e,{...t,priority:t.priority??lu}),s=this.connections.get(o.remotePeer);s==null&&(s=[],this.connections.set(o.remotePeer,s));let i=!1;for(let a of s)a.id===o.id&&(i=!0);return i||s.push(o),o}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async o=>{try{await o.close(t)}catch(s){o.abort(s)}}))}async acceptIncomingConnection(e){if(this.deny.some(o=>e.remoteAddr.toString().startsWith(o.toString())))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(o=>e.remoteAddr.toString().startsWith(o.toString())))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){let o=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(o,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,o),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){let e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map(n=>ne(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};var An=class{movingAverage;variance;deviation;forecast;timespan;previousTime;constructor(e){this.timespan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timespan)}push(e,t=Date.now()){if(this.previousTime!=null){let n=this.alpha(t,this.previousTime),o=e-this.movingAverage,s=n*o;this.movingAverage=n*e+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+o*s),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*o}else this.movingAverage=e;this.previousTime=t}};var zw=1.2,Gw=2,Ww=2e3,ua=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;constructor(e={}){this.success=new An(e.interval??5e3),this.failure=new An(e.interval??5e3),this.next=new An(e.interval??5e3),this.failureMultiplier=e.failureMultiplier??Gw,this.timeoutMultiplier=e.timeoutMultiplier??zw,this.minTimeout=e.minTimeout??Ww,e.metricName!=null&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){let t=Math.max(Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier)),this.minTimeout),n=AbortSignal.timeout(t),o=Ir([e.signal,n]);return oe(1/0,o,n),o.start=Date.now(),o.timeout=t,o}cleanUp(e){let t=Date.now()-e.start;e.aborted?(this.failure.push(t),this.next.push(t*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:t})):(this.success.push(t),this.next.push(t),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:t}))}};var pu=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=le(),this.haveNext=le()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=le(),e}async throw(e){return this.ended=!0,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return await this._push(void 0),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=le(),await nr(this.readNext.promise,t?.signal,t)}};function Bp(){return new pu}var fa=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var mu=class extends Error{code;constructor(e,t){super(e),this.code=t}},gu=class extends mu{type;constructor(e){super(e,"ABORT_ERR"),this.type="aborted",this.name="AbortError"}};function ha(r,e){let t=Bp();r.sink(t).catch(async i=>{await t.end(i)}),r.sink=async i=>{for await(let a of i)await t.push(a);await t.end()};let n=r.source;r.source[Symbol.iterator]!=null?n=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(n=r.source[Symbol.asyncIterator]());let o=new we;return{read:async(i,a)=>{a?.signal?.throwIfAborted();let c,u=new Promise((f,l)=>{c=()=>{l(new gu("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(i==null){let{done:l,value:d}=await Promise.race([n.next(),u]);return l===!0?new we:d}for(;o.byteLength<i;){let{value:l,done:d}=await Promise.race([n.next(),u]);if(d===!0)throw new fa("unexpected end of input");o.append(l)}let f=o.sublist(0,i);return o.consume(i),f}finally{c!=null&&a?.signal?.removeEventListener("abort",c)}},write:async(i,a)=>{a?.signal?.throwIfAborted(),i instanceof Uint8Array?await t.push(i,a):await t.push(i.subarray(),a)},unwrap:()=>{if(o.byteLength>0){let i=r.source;r.source=async function*(){e?.yieldBytes===!1?yield o:yield*o,yield*i}()}return r}}}var jw=1e4,Zw="1.0.0",Xw="ping",Yw="ipfs",kp=32,da=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??Yw}/${Xw}/${Zw}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??jw,this.timeout=new ua({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[In]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(e=>{Promise.resolve().then(async()=>{let t=Date.now();try{let n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),o=await e.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0}),s=ha(o);t=Date.now(),await Promise.all([s.write(rn(kp),{signal:n}),s.read(kp,{signal:n})]),e.rtt=Date.now()-t,await s.unwrap().close({signal:n})}catch(n){if(n.code!=="ERR_UNSUPPORTED_PROTOCOL")throw n;e.rtt=(Date.now()-t)/2}}).catch(t=>{this.log.error("error during heartbeat, aborting connection",t),e.abort(t)})})},this.pingIntervalMs)}stop(){this.abortController?.abort(),this.heartbeatInterval!=null&&clearInterval(this.heartbeatInterval)}};function Jw(r){return r[Symbol.asyncIterator]!=null}function Qw(...r){let e=[];for(let t of r)Jw(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=ta({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let o of n)t.push(o)})),t.end()}catch(n){t.end(n)}}),yield*t}()}var ko=Qw;var pa=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(this.routers.length===0)throw new vo("No content routers available");let n=this,o=new br;for await(let s of ko(...n.routers.map(i=>i.findProviders(e,t))))s!=null&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id)&&(o.add(s.id),yield s))}async provide(e,t={}){if(this.routers.length===0)throw new vo("No content routers available");await Promise.all(this.routers.map(async n=>{await n.provide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new xt;await Promise.all(this.routers.map(async o=>{await o.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new xt;return Promise.any(this.routers.map(async n=>n.get(e,t)))}};var ma=globalThis.CustomEvent??Event;async function*yu(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered==null?!1:e.ordered,o=new EventTarget,s=[],i=le(),a=le(),c=!1,u,f=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of r){if(s.length===t&&(i=le(),await i.promise),f)break;let m={done:!1};s.push(m),p().then(g=>{m.done=!0,m.ok=!0,m.value=g,o.dispatchEvent(new ma("task-complete"))},g=>{m.done=!0,m.err=g,o.dispatchEvent(new ma("task-complete"))})}c=!0,o.dispatchEvent(new ma("task-complete"))}catch(p){u=p,o.dispatchEvent(new ma("task-complete"))}});function l(){return n?s[0]?.done:!!s.find(p=>p.done)}function*d(){for(;s.length>0&&s[0].done;){let p=s[0];if(s.shift(),p.ok)yield p.value;else throw f=!0,i.resolve(),p.err;i.resolve()}}function*h(){for(;l();)for(let p=0;p<s.length;p++)if(s[p].done){let m=s[p];if(s.splice(p,1),p--,m.ok)yield m.value;else throw f=!0,i.resolve(),m.err;i.resolve()}}for(;;){if(l()||(a=le(),await a.promise),u!=null)throw u;if(n?yield*d():yield*h(),c&&s.length===0)break}}var ga=class{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[]}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(this.routers.length===0)throw new Eo("No peer routers available");if(e.toString()===this.peerId.toString())throw new Ki("Should not try to find self");let n=this,o=ko(...this.routers.map(s=>async function*(){try{yield await s.findPeer(e,t)}catch(i){n.log.error(i)}}()));for await(let s of o)if(s!=null)return s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),s;throw new Uo}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new Eo("No peer routers available");let n=this,o=Hl(1024);for await(let s of yu(async function*(){let i=ko(...n.routers.map(a=>a.getClosestPeers(e,t)));for await(let a of i)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.findPeer(a.id,{...t,useCache:!1})}catch(c){n.log.error("could not find peer multiaddrs",c);return}return a}}()))s!=null&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id.toMultihash().bytes)&&(o.add(s.id.toMultihash().bytes),yield s))}};var ya=class extends vt{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,oe(1/0,this.shutdownController.signal)}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,oe(1/0,this.shutdownController.signal)}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=Ir([this.shutdownController.signal,e?.signal]);oe(1/0,t);try{for(;;)this.needNext?.resolve(),this.needNext=le(),yield(await vn(this,"walk:peer",t,{errorEvent:"walk:error"})).detail}finally{t.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,oe(1/0,this.walkController.signal);let e=Ir([this.walkController.signal,this.shutdownController.signal]);oe(1/0,e);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let o=rn(32),s=Date.now();for await(let i of this.peerRouting.getClosestPeers(o,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",i.id,Date.now()-s,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:i}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await nr(this.needNext.promise,e)),s=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",o,this.walkers,n)}catch(o){this.log.error("randomwalk errored",o),this.safeDispatchEvent("walk:error",{detail:o})}this.log("no walkers left, ended walk")}).catch(o=>{this.log.error("randomwalk errored",o)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}};var wu=32,bu=64,wa=class{log;topologies;handlers;components;constructor(e){this.log=e.logger.forComponent("libp2p:registrar"),this.topologies=new Map,this.handlers=new Map,this.components=e,this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new qi(`No handler registered for protocol ${e}`);return t}getTopologies(e){let t=this.topologies.get(e);return t==null?[]:[...t.values()]}async handle(e,t,n){if(this.handlers.has(e))throw new zi(`Handler already registered for protocol ${e}`);let o=bi.bind({ignoreUndefined:!0})({maxInboundStreams:wu,maxOutboundStreams:bu},n);this.handlers.set(e,{handler:t,options:o}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]})}async unhandle(e){(Array.isArray(e)?e:[e]).forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()})}async register(e,t){if(t==null)throw new D("invalid topology");let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,o=this.topologies.get(e);return o==null&&(o=new Map,this.topologies.set(e,o)),o.set(n,t),n}unregister(e){for(let[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(t))}_onDisconnect(e){let t=e.detail;this.components.peerStore.get(t).then(n=>{for(let o of n.protocols){let s=this.topologies.get(o);if(s!=null)for(let i of s.values())i.filter?.has(t)!==!1&&(i.filter?.remove(t),i.onDisconnect?.(t))}}).catch(n=>{n.name!=="NotFoundError"&&this.log.error("could not inform topologies of disconnecting peer %p",t,n)})}_onPeerUpdate(e){let{peer:t,previous:n}=e.detail,o=(n?.protocols??[]).filter(s=>!t.protocols.includes(s));for(let s of o){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())a.filter?.has(t.id)!==!1&&(a.filter?.remove(t.id),a.onDisconnect?.(t.id))}}_onPeerIdentify(e){let t=e.detail.protocols,n=e.detail.connection,o=e.detail.peerId;for(let s of t){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())n.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(o)!==!0&&(a.filter?.add(o),a.onConnect?.(o,n))}}};var xu=class extends Map{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Ip(r){let{name:e,metrics:t}=r,n;return t!=null?n=new xu({name:e,metrics:t}):n=new Map,n}var ba=class{log;components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=new Map,this.listeners=Ip({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??Ot.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new D("Transport must have a valid tag");if(this.transports.has(t))throw new D(`There is already a transport with the tag ${t}`);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){let e=[];for(let[t,n]of this.listeners)for(this.log("closing listeners for %s",t);n.length>0;){let o=n.pop();o!=null&&e.push(o.close())}await Promise.all(e),this.log("all listeners closed");for(let t of this.listeners.keys())this.listeners.set(t,[]);this.started=!1}async dial(e,t){let n=this.dialTransportForMultiaddr(e);if(n==null)throw new Wi(`No transport available for address ${String(e)}`);return t?.onProgress?.(new fe("transport-manager:selected-transport",n[Symbol.toStringTag])),n.dial(e,{...t,upgrader:this.components.upgrader})}getAddrs(){let e=[];for(let t of this.listeners.values())for(let n of t)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(let t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(let t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new xt("Not started");if(e==null||e.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let t=[];for(let[n,o]of this.transports.entries()){let s=o.listenFilter(e),i=[];for(let u of s){this.log("creating listener for %s on %a",n,u);let f=o.createListener({upgrader:this.components.upgrader}),l=this.listeners.get(n)??[];l==null&&(l=[],this.listeners.set(n,l)),l.push(f),f.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:f})}),f.addEventListener("close",()=>{let d=l.findIndex(h=>h===f);l.splice(d,1),this.components.events.safeDispatchEvent("transport:close",{detail:f})}),i.push(f.listen(u))}if(i.length===0){t.push(n);continue}if((await Promise.allSettled(i)).find(u=>u.status==="fulfilled")==null&&this.faultTolerance!==Ot.NO_FATAL)throw new Br(`Transport (${n}) could not listen on any available address`)}if(t.length===this.transports.size){let n=`no valid addresses were provided for transports [${t.join(", ")}]`;if(this.faultTolerance===Ot.FATAL_ALL)throw new Br(n);this.log(`libp2p in dial mode only: ${n}`)}}async remove(e){let t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);let n=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){let o=t.pop();o!=null&&n.push(o.close())}await Promise.all(n),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}};var Be="/multistream/1.0.0";var xa=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},va=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ea=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Io(r,e={}){let t=ha(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=he(e.maxDataLength));let n=e?.lengthDecoder??st,o=e?.lengthEncoder??Ce;return{read:async i=>{let a=-1,c=new we;for(;;){c.append(await t.read(1,i));try{a=n(c)}catch(u){if(u instanceof RangeError)continue;throw u}if(a<0)throw new xa("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new Ea("message length length too long");if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new va("message length too long");return t.read(a,i)},write:async(i,a)=>{await t.write(new we(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new we(...i.flatMap(u=>[o(u.byteLength),u]));await t.write(c,a)},unwrap:()=>t.unwrap()}}var eb=P(`
|
|
7
|
+
`);async function Tr(r,e,t){await r.write(e,t)}async function Cp(r,e,t){await r.writeV(e,t)}async function tb(r,e){let t=await r.read(e);if(t.byteLength===0||t.get(t.byteLength-1)!==eb[0])throw e.log.error("Invalid mss message - missing newline",t),new Ho("Missing newline");return t.sublist(0,-1)}async function or(r,e){let t=await tb(r,e);return H(t.subarray())}async function Co(r,e,t){if(e=Array.isArray(e)?[...e]:[e],e.length===1&&t.negotiateFully===!1)return rb(r,e[0],t);let n=Io(r,{...t,maxDataLength:1024}),o=e.shift();if(o==null)throw new Error("At least one protocol must be specified");t.log.trace('select: write ["%s", "%s"]',Be,o);let s=P(`${Be}
|
|
8
|
+
`),i=P(`${o}
|
|
9
|
+
`);await Cp(n,[s,i],t),t.log.trace("select: reading multistream-select header");let a=await or(n,t);if(t.log.trace('select: read "%s"',a),a===Be&&(t.log.trace("select: reading protocol response"),a=await or(n,t),t.log.trace('select: read "%s"',a)),a===o)return{stream:n.unwrap(),protocol:o};for(let c of e){t.log.trace('select: write "%s"',c),await Tr(n,P(`${c}
|
|
10
|
+
`),t),t.log.trace("select: reading protocol response");let u=await or(n,t);if(t.log.trace('select: read "%s" for "%s"',u,c),u===c)return{stream:n.unwrap(),protocol:c}}throw new kn("protocol selection failed")}function rb(r,e,t){let n=r.sink.bind(r),o=r.source,s=!1,i=!1,a=le(),c=!1,u=!1,f=le(),l=!1,d=!1,h=le(),p=Io({sink:n,source:o},{...t,maxDataLength:1024});r.sink=async b=>{let{sink:w}=p.unwrap();await w(async function*(){let x=!1;for await(let A of b){if(u&&await f.promise,c)yield A;else{u=!0,t.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink',Be,e,A.byteLength);let _=`${e}
|
|
11
|
+
`;yield new we(Uint8Array.from([19]),P(`${Be}
|
|
12
|
+
`),Ce(_.length),P(_),A).subarray(),t.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',Be,e,A.byteLength),c=!0,u=!1,f.resolve(),m().catch(v=>{t.log.error("could not finish optimistic protocol negotiation of %s",e,v)})}x=!0}x||await m()}())};async function m(){if(i){t.log.trace("optimistic: already negotiating %s stream",e),await a.promise;return}i=!0;try{c||(t.log.trace("optimistic: doing send protocol for %s stream",e),await g()),l||(t.log.trace("optimistic: doing read protocol for %s stream",e),await y())}finally{i=!1,s=!0,a.resolve()}}async function g(){if(u){await f.promise;return}u=!0;try{t.log.trace('optimistic: write ["%s", "%s", data] in source',Be,e),await p.writeV([P(`${Be}
|
|
13
|
+
`),P(`${e}
|
|
14
|
+
`)]),t.log.trace('optimistic: wrote ["%s", "%s", data] in source',Be,e)}finally{c=!0,u=!1,f.resolve()}}async function y(){if(d){await h.promise;return}d=!0;try{t.log.trace("optimistic: reading multistream select header");let b=await or(p,t);if(t.log.trace('optimistic: read multistream select header "%s"',b),b===Be&&(b=await or(p,t)),t.log.trace('optimistic: read protocol "%s", expecting "%s"',b,e),b!==e)throw new kn("protocol selection failed")}finally{l=!0,d=!1,h.resolve()}}if(r.source=async function*(){await m(),t.log.trace('optimistic: reading data from "%s" stream',e),yield*p.unwrap().source}(),r.closeRead!=null){let b=r.closeRead.bind(r);r.closeRead=async w=>{s||await m().catch(x=>{t.log.error("could not negotiate protocol before close read",x)}),await b(w)}}if(r.closeWrite!=null){let b=r.closeWrite.bind(r);r.closeWrite=async w=>{s||await m().catch(x=>{t.log.error("could not negotiate protocol before close write",x)}),await b(w)}}if(r.close!=null){let b=r.close.bind(r);r.close=async w=>{let x=[];u&&x.push(f.promise),d&&x.push(h.promise),x.length>0?await nr(Promise.all(x),w?.signal):(s=!0,i=!1,a.resolve()),await b(w)}}return{stream:r,protocol:e}}function Aa(r){return r[Symbol.asyncIterator]!=null}var Sa=r=>{let e=he(r),t=ke(e);return Ce(r,t),Sa.bytes=e,t};Sa.bytes=0;function _a(r,e){e=e??{};let t=e.lengthEncoder??Sa;function*n(o){let s=t(o.byteLength);s instanceof Uint8Array?yield s:yield*s,o instanceof Uint8Array?yield o:yield*o}return Aa(r)?async function*(){for await(let o of r)yield*n(o)}():function*(){for(let o of r)yield*n(o)}()}_a.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Sa;return new we(t(r.byteLength),r)};var Ba=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},ka=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ia=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},To=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var nb=8,ob=1024*1024*4,Lr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Lr||(Lr={}));var Au=r=>{let e=st(r);return Au.bytes=he(e),e};Au.bytes=0;function Eu(r,e){let t=new we,n=Lr.LENGTH,o=-1,s=e?.lengthDecoder??Au,i=e?.maxLengthLength??nb,a=e?.maxDataLength??ob;function*c(){for(;t.byteLength>0;){if(n===Lr.LENGTH)try{if(o=s(t),o<0)throw new Ba("Invalid message length");if(o>a)throw new ka("Message length too long");let u=s.bytes;t.consume(u),e?.onLength!=null&&e.onLength(o),n=Lr.DATA}catch(u){if(u instanceof RangeError){if(t.byteLength>i)throw new Ia("Message length length too long");break}throw u}if(n===Lr.DATA){if(t.byteLength<o)break;let u=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(u),yield u,n=Lr.LENGTH}}}return Aa(r)?async function*(){for await(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw new To("Unexpected end of input")}():function*(){for(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw new To("Unexpected end of input")}()}Eu.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 Eu(n,{...e??{},onLength:s=>{t=s}})};async function Lo(r,e,t){e=Array.isArray(e)?e:[e],t.log.trace("handle: available protocols %s",e);let n=Io(r,{...t,maxDataLength:1024,maxLengthLength:2});for(;;){t.log.trace("handle: reading incoming string");let o=await or(n,t);if(t.log.trace('handle: read "%s"',o),o===Be){t.log.trace('handle: respond with "%s" for "%s"',Be,o),await Tr(n,P(`${Be}
|
|
15
|
+
`),t),t.log.trace('handle: responded with "%s" for "%s"',Be,o);continue}if(e.includes(o))return t.log.trace('handle: respond with "%s" for "%s"',o,o),await Tr(n,P(`${o}
|
|
16
|
+
`),t),t.log.trace('handle: responded with "%s" for "%s"',o,o),{stream:n.unwrap(),protocol:o};if(o==="ls"){let s=new we(...e.map(i=>_a.single(P(`${i}
|
|
17
|
+
`))),P(`
|
|
18
|
+
`));t.log.trace('handle: respond with "%s" for %s',e,o),await Tr(n,s,t),t.log.trace('handle: responded with "%s" for %s',e,o);continue}t.log('handle: respond with "na" for "%s"',o),await Tr(n,P(`na
|
|
19
|
+
`),t),t.log('handle: responded with "na" for "%s"',o)}}var ib=500,Su=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;limits;log;tags;_newStream;_close;_abort;_getStreams;constructor(e){let{remoteAddr:t,remotePeer:n,newStream:o,close:s,abort:i,getStreams:a}=e;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=t,this.remotePeer=n,this.direction=e.direction,this.status="open",this.timeline=e.timeline,this.multiplexer=e.multiplexer,this.encryption=e.encryption,this.limits=e.limits,this.log=e.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`),this.remoteAddr.getPeerId()==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this._newStream=o,this._close=s,this._abort=i,this._getStreams=a,this.tags=[]}[Symbol.toStringTag]="Connection";[Pu]=!0;get streams(){return this._getStreams()}async newStream(e,t){if(this.status==="closing")throw new Do("the connection is being closed");if(this.status==="closed")throw new Mo("the connection is closed");if(Array.isArray(e)||(e=[e]),this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new Ur("Cannot open protocol stream on limited connection");let n=await this._newStream(e,t);return n.direction="outbound",n}async close(e={}){if(!(this.status==="closed"||this.status==="closing")){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",e.signal==null){let t=AbortSignal.timeout(ib);oe(1/0,t),e={...e,signal:t}}try{this.log.trace("closing all streams"),await Promise.all(this.streams.map(async t=>t.close(e))),this.log.trace("closing underlying transport"),await this._close(e),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(t){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,t),this.abort(t)}}}abort(e){this.log.error("aborting connection to %a due to error",this.remoteAddr,e),this.status="closing",this.streams.forEach(t=>{t.abort(e)}),this.log.error("all streams aborted",this.streams.length),this._abort(e),this.timeline.close=Date.now(),this.status="closed"}};function Lp(r){return new Su(r)}var ab=3e4;function cb(r,e){try{let{options:t}=e.getHandler(r);return t.maxInboundStreams}catch(t){if(t.name!=="UnhandledProtocolError")throw t}return wu}function lb(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.name!=="UnhandledProtocolError")throw n}return t.maxOutboundStreams??bu}function Np(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var Ca=class{components;connectionEncryption;muxers;inboundUpgradeTimeout;events;constructor(e,t){this.components=e,this.connectionEncryption=new Map,t.connectionEncryption.forEach(n=>{this.connectionEncryption.set(n.protocol,n)}),this.muxers=new Map,t.muxers.forEach(n=>{this.muxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??2e3,this.events=e.events}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,t,n){let o=this.components.connectionGater[n];if(o!==void 0&&await o(e,t))throw new So(`The multiaddr connection is blocked by gater.${n}`)}async upgradeInbound(e,t){if(!await this.components.connectionManager.acceptIncomingConnection(e))throw new Gi("connection denied");let o,s,i,a,c,u=AbortSignal.timeout(this.inboundUpgradeTimeout),f=()=>{e.abort(new Dr("inbound upgrade timeout"))};u.addEventListener("abort",f,{once:!0}),oe(1/0,u);try{if(await this.components.connectionGater.denyInboundConnection?.(e)===!0)throw new So("The multiaddr connection is blocked by gater.acceptConnection");this.components.metrics?.trackMultiaddrConnection(e),e.log("starting the inbound connection upgrade");let l=e;if(t?.skipProtection!==!0){let d=this.components.connectionProtector;d!=null&&(e.log("protecting the inbound connection"),l=await d.protect(e))}try{if(o=l,t?.skipEncryption!==!0){t?.onProgress?.(new fe("upgrader:encrypt-inbound-connection")),{conn:o,remotePeer:s,protocol:c}=await this._encryptInbound(l);let d={...l,...o};await this.shouldBlockConnection(s,d,"denyInboundEncryptedConnection")}else{let d=e.remoteAddr.getPeerId();if(d==null)throw new Rr("inbound connection that skipped encryption must have a peer id");let h=gt(d);c="native",s=h}if(i=o,t?.muxerFactory!=null)a=t.muxerFactory;else if(this.muxers.size>0){t?.onProgress?.(new fe("upgrader:multiplex-inbound-connection"));let d=await this._multiplexInbound({...l,...o},this.muxers);a=d.muxerFactory,i=d.stream}}catch(d){throw e.log.error("failed to upgrade inbound connection",d),d}return await this.shouldBlockConnection(s,e,"denyInboundUpgradedConnection"),e.log("successfully upgraded inbound connection"),this._createConnection({cryptoProtocol:c,direction:"inbound",maConn:e,upgradedConn:i,muxerFactory:a,remotePeer:s,limits:t?.limits})}finally{u.removeEventListener("abort",f),this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){let n=e.remoteAddr.getPeerId(),o;n!=null&&(o=gt(n),await this.shouldBlockConnection(o,e,"denyOutboundConnection"));let s,i,a,c,u;this.components.metrics?.trackMultiaddrConnection(e),e.log("starting the outbound connection upgrade");let f=e;if(t?.skipProtection!==!0){let l=this.components.connectionProtector;l!=null&&(f=await l.protect(e))}try{if(s=f,t?.skipEncryption!==!0){({conn:s,remotePeer:i,protocol:c}=await this._encryptOutbound(f,{...t,remotePeer:o}));let l={...f,...s};await this.shouldBlockConnection(i,l,"denyOutboundEncryptedConnection")}else{if(o==null)throw new Oo("Encryption was skipped but no peer id was passed");c="native",i=o}if(a=s,t?.muxerFactory!=null)u=t.muxerFactory;else if(this.muxers.size>0){let l=await this._multiplexOutbound({...f,...s},this.muxers);u=l.muxerFactory,a=l.stream}}catch(l){throw e.log.error("failed to upgrade outbound connection",l),await e.close(l),l}return await this.shouldBlockConnection(i,e,"denyOutboundUpgradedConnection"),e.log("successfully upgraded outbound connection"),this._createConnection({cryptoProtocol:c,direction:"outbound",maConn:e,upgradedConn:a,muxerFactory:u,remotePeer:i,limits:t?.limits})}_createConnection(e){let{cryptoProtocol:t,direction:n,maConn:o,upgradedConn:s,remotePeer:i,muxerFactory:a,limits:c}=e,u,f,l;a!=null&&(u=a.createStreamMuxer({direction:n,onIncomingStream:p=>{l!=null&&Promise.resolve().then(async()=>{let m=this.components.registrar.getProtocols(),{stream:g,protocol:y}=await Lo(p,m,{log:p.log,yieldBytes:!1});if(l==null)return;l.log("incoming stream opened on %s",y);let b=cb(y,this.components.registrar);if(Np(y,"inbound",l)===b){let x=new $o(`Too many inbound protocol streams for protocol "${y}" - limit ${b}`);throw p.abort(x),x}p.source=g.source,p.sink=g.sink,p.protocol=y,g.closeWrite!=null&&(p.closeWrite=g.closeWrite),g.closeRead!=null&&(p.closeRead=g.closeRead),g.close!=null&&(p.close=g.close),await this.components.peerStore.merge(i,{protocols:[y]}),this.components.metrics?.trackProtocolStream(p,l),this._onStream({connection:l,stream:p,protocol:y})}).catch(async m=>{l.log.error("error handling incoming stream id %s",p.id,m.message,m.code,m.stack),p.timeline.close==null&&await p.close()})}}),f=async(p,m={})=>{if(u==null)throw new kr("Connection is not multiplexed");l.log("starting new stream for protocols %s",p);let g=await u.newStream();l.log.trace("started new stream %s for protocols %s",g.id,p);try{if(m.signal==null){g.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",p);let A=AbortSignal.timeout(ab);oe(1/0,A),m={...m,signal:A}}g.log.trace("selecting protocol from protocols %s",p);let{stream:y,protocol:b}=await Co(g,p,{...m,log:g.log,yieldBytes:!0});g.log("selected protocol %s",b);let w=lb(b,this.components.registrar,m),x=Np(b,"outbound",l);if(x>=w){let A=new Ko(`Too many outbound protocol streams for protocol "${b}" - ${x}/${w}`);throw g.abort(A),A}return await this.components.peerStore.merge(i,{protocols:[b]}),g.source=y.source,g.sink=y.sink,g.protocol=b,y.closeWrite!=null&&(g.closeWrite=y.closeWrite),y.closeRead!=null&&(g.closeRead=y.closeRead),y.close!=null&&(g.close=y.close),this.components.metrics?.trackProtocolStream(g,l),g}catch(y){throw l.log.error("could not create new stream for protocols %s",p,y),g.timeline.close==null&&g.abort(y),y}},Promise.all([u.sink(s.source),s.sink(u.source)]).catch(p=>{l.log.error("error piping data through muxer",p)}));let d=o.timeline;o.timeline=new Proxy(d,{set:(...p)=>(l!=null&&p[1]==="close"&&p[2]!=null&&d.close==null&&(async()=>{try{l.status==="open"&&await l.close()}catch(m){l.log.error("error closing connection after timeline close",m)}finally{this.events.safeDispatchEvent("connection:close",{detail:l})}})().catch(m=>{l.log.error("error thrown while dispatching connection:close event",m)}),Reflect.set(...p))}),o.timeline.upgraded=Date.now();let h=()=>{throw new kr("Connection is not multiplexed")};return l=Lp({remoteAddr:o.remoteAddr,remotePeer:i,status:"open",direction:n,timeline:o.timeline,multiplexer:u?.protocol,encryption:t,limits:c,logger:this.components.logger,newStream:f??h,getStreams:()=>u!=null?u.streams:[],close:async p=>{u!=null&&(l.log.trace("close muxer"),await u.close(p)),l.log.trace("close maconn"),await o.close(p),l.log.trace("closed maconn")},abort:p=>{o.abort(p),u?.abort(p)}}),this.events.safeDispatchEvent("connection:open",{detail:l}),l}_onStream(e){let{connection:t,stream:n,protocol:o}=e,{handler:s,options:i}=this.components.registrar.getHandler(o);if(t.limits!=null&&i.runOnLimitedConnection!==!0)throw new Ur("Cannot open protocol stream on limited connection");s({connection:t,stream:n})}async _encryptInbound(e,t){let n=Array.from(this.connectionEncryption.keys());e.log("handling inbound crypto protocol selection",n);try{let{stream:o,protocol:s}=await Lo(e,n,{log:e.log}),i=this.connectionEncryption.get(s);if(i==null)throw new Error(`no crypto module found for ${s}`);return e.log("encrypting inbound connection using",s),{...await i.secureInbound(o,t),protocol:s}}catch(o){throw e.log.error("encrypting inbound connection failed",o),new _o(o.message)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncryption.keys());e.log("selecting outbound crypto protocol",n);try{e.log.trace("selecting encrypter from %s",n);let{stream:o,protocol:s}=await Co(e,n,{log:e.log,yieldBytes:!0}),i=this.connectionEncryption.get(s);if(i==null)throw new Error(`no crypto module found for ${s}`);return e.log("encrypting outbound connection to %p using %s",t?.remotePeer,i),{...await i.secureOutbound(o,t),protocol:s}}catch(o){throw e.log.error("encrypting outbound connection to %p failed",t?.remotePeer,o),new _o(o.message)}}async _multiplexOutbound(e,t){let n=Array.from(t.keys());e.log("outbound selecting muxer %s",n);try{e.log.trace("selecting stream muxer from %s",n);let{stream:o,protocol:s}=await Co(e,n,{log:e.log,yieldBytes:!0});e.log("selected %s as muxer protocol",s);let i=t.get(s);return{stream:o,muxerFactory:i}}catch(o){throw e.log.error("error multiplexing outbound connection",o),new kr(String(o))}}async _multiplexInbound(e,t){let n=Array.from(t.keys());e.log("inbound handling muxers %s",n);try{let{stream:o,protocol:s}=await Lo(e,n,{log:e.log}),i=t.get(s);return{stream:o,muxerFactory:i}}catch(o){throw e.log.error("error multiplexing inbound connection",o),new kr(String(o))}}};var Pp="1.9.4-df330695a",Rp="libp2p";var Ta=class extends vt{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new vt,n=t.dispatchEvent.bind(t);t.dispatchEvent=a=>{let c=n(a),u=this.dispatchEvent(new CustomEvent(a.type,{detail:a.detail}));return c||u},oe(1/0,t),this.peerId=e.peerId,this.logger=e.logger??Ai(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=this.components=lp({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:e.nodeInfo??{name:Rp,version:Pp},logger:this.logger,events:t,datastore:e.datastore??new Fi,connectionGater:fp(e.connectionGater),dns:e.dns});this.peerStore=this.configureComponent("peerStore",new Mi(o,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),o.events.addEventListener("peer:update",a=>{if(a.detail.previous==null){let c={id:a.detail.peer.id,multiaddrs:a.detail.peer.addresses.map(u=>u.multiaddr)};o.events.safeDispatchEvent("peer:discovery",{detail:c})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(o)),this.components.upgrader=new Ca(this.components,{connectionEncryption:(e.connectionEncryption??[]).map((a,c)=>this.configureComponent(`connection-encryption-${c}`,a(this.components))),muxers:(e.streamMuxers??[]).map((a,c)=>this.configureComponent(`stream-muxers-${c}`,a(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout}),this.configureComponent("transportManager",new ba(this.components,e.transportManager)),this.configureComponent("connectionManager",new la(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new da(this.components,e.connectionMonitor)),this.configureComponent("registrar",new wa(this.components)),this.configureComponent("addressManager",new Vi(this.components,e.addresses));let s=(e.peerRouters??[]).map((a,c)=>this.configureComponent(`peer-router-${c}`,a(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new ga(this.components,{routers:s}));let i=(e.contentRouters??[]).map((a,c)=>this.configureComponent(`content-router-${c}`,a(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new pa(this.components,{routers:i})),this.configureComponent("randomWalk",new ya(this.components)),(e.peerDiscovery??[]).forEach((a,c)=>{this.configureComponent(`peer-discovery-${c}`,a(this.components)).addEventListener("peer",f=>{this.#e(f)})}),e.transports?.forEach((a,c)=>{this.components.transportManager.add(this.configureComponent(`transport-${c}`,a(this.components)))}),e.services!=null)for(let a of Object.keys(e.services)){let c=e.services[a],u=c(this.components);if(u==null){this.log.error("service factory %s returned null or undefined instance",a);continue}this.services[a]=u,this.configureComponent(a,u),u[Na]!=null&&(this.log("registering service %s for content routing",a),i.push(u[Na])),u[Ra]!=null&&(this.log("registering service %s for peer routing",a),s.push(u[Ra])),u[Pa]!=null&&(this.log("registering service %s for peer discovery",a),u[Pa].addEventListener?.("peer",f=>{this.#e(f)}))}up(o)}configureComponent(e,t){return t==null&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started")}catch(e){throw this.log.error("An error occurred starting libp2p",e),this.status="started",await this.stop(),e}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new br;for(let t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,n={}){if(t==null)throw new D("no protocols were provided to open a stream");if(t=Array.isArray(t)?t:[t],t.length===0)throw new D("no protocols were provided to open a stream");return(await this.dial(e,n)).newStream(t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){Qt(e)&&(e=gt(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;try{let i=await this.peerStore.get(e);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let n=Fe([P("/pk/"),e.toMultihash().bytes]),o=await this.contentRouting.get(n,t),s=on(o);return await this.peerStore.patch(e,{publicKey:s}),s}async handle(e,t,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async o=>{await this.components.registrar.handle(o,t,n)}))}async unhandle(e){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async t=>{await this.components.registrar.unhandle(t)}))}async register(e,t){return this.components.registrar.register(e,t)}unregister(e){this.components.registrar.unregister(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#e(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error(n)})}};async function fb(r={}){r.privateKey??=await Gh("Ed25519");let e=new Ta({...await Ud(r),peerId:Xh(r.privateKey)});return r.start!==!1&&await e.start(),e}return jp(hb);})();
|
|
21
20
|
/*! Bundled license information:
|
|
22
21
|
|
|
23
22
|
pvtsutils/build/index.js:
|